code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
/*
* Copyright 2016 Black Duck Software, 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 com.blackducksoftware.ohcount4j;
import java.util.ArrayList;
import java.util.List;
import com.blackducksoftware.ohcount4j.scan.ActionScriptScanner;
import com.blackducksoftware.ohcount4j.scan.AdaScanner;
import com.blackducksoftware.ohcount4j.scan.AssemblyScanner;
import com.blackducksoftware.ohcount4j.scan.AugeasScanner;
import com.blackducksoftware.ohcount4j.scan.AutoconfScanner;
import com.blackducksoftware.ohcount4j.scan.AutomakeScanner;
import com.blackducksoftware.ohcount4j.scan.AwkScanner;
import com.blackducksoftware.ohcount4j.scan.BatScanner;
import com.blackducksoftware.ohcount4j.scan.BfkScanner;
import com.blackducksoftware.ohcount4j.scan.BfkppScanner;
import com.blackducksoftware.ohcount4j.scan.BinaryScanner;
import com.blackducksoftware.ohcount4j.scan.BlitzMaxScanner;
import com.blackducksoftware.ohcount4j.scan.BooScanner;
import com.blackducksoftware.ohcount4j.scan.CMakeScanner;
import com.blackducksoftware.ohcount4j.scan.CStyleScanner;
import com.blackducksoftware.ohcount4j.scan.ClearSilverTemplateScanner;
import com.blackducksoftware.ohcount4j.scan.ClojureScanner;
import com.blackducksoftware.ohcount4j.scan.CobolScanner;
import com.blackducksoftware.ohcount4j.scan.CoffeeScriptScanner;
import com.blackducksoftware.ohcount4j.scan.ColdFusionScanner;
import com.blackducksoftware.ohcount4j.scan.CoqScanner;
import com.blackducksoftware.ohcount4j.scan.DScanner;
import com.blackducksoftware.ohcount4j.scan.DclScanner;
import com.blackducksoftware.ohcount4j.scan.EiffelScanner;
import com.blackducksoftware.ohcount4j.scan.ElixirScanner;
import com.blackducksoftware.ohcount4j.scan.ErlangScanner;
import com.blackducksoftware.ohcount4j.scan.FSharpScanner;
import com.blackducksoftware.ohcount4j.scan.FactorScanner;
import com.blackducksoftware.ohcount4j.scan.ForthScanner;
import com.blackducksoftware.ohcount4j.scan.FortranFixedScanner;
import com.blackducksoftware.ohcount4j.scan.FortranFreeScanner;
import com.blackducksoftware.ohcount4j.scan.GenericCodeScanner;
import com.blackducksoftware.ohcount4j.scan.HTMLScanner;
import com.blackducksoftware.ohcount4j.scan.HamlScanner;
import com.blackducksoftware.ohcount4j.scan.HaskellScanner;
import com.blackducksoftware.ohcount4j.scan.IdlPvwaveScanner;
import com.blackducksoftware.ohcount4j.scan.JspScanner;
import com.blackducksoftware.ohcount4j.scan.LispScanner;
import com.blackducksoftware.ohcount4j.scan.LogtalkScanner;
import com.blackducksoftware.ohcount4j.scan.LuaScanner;
import com.blackducksoftware.ohcount4j.scan.MakeScanner;
import com.blackducksoftware.ohcount4j.scan.MathematicaScanner;
import com.blackducksoftware.ohcount4j.scan.MatlabScanner;
import com.blackducksoftware.ohcount4j.scan.MetapostWithTexScanner;
import com.blackducksoftware.ohcount4j.scan.MetafontScanner;
import com.blackducksoftware.ohcount4j.scan.ModulaScanner;
import com.blackducksoftware.ohcount4j.scan.OCamlScanner;
import com.blackducksoftware.ohcount4j.scan.PascalScanner;
import com.blackducksoftware.ohcount4j.scan.PerlScanner;
import com.blackducksoftware.ohcount4j.scan.PhpScanner;
import com.blackducksoftware.ohcount4j.scan.PrologScanner;
import com.blackducksoftware.ohcount4j.scan.PythonScanner;
import com.blackducksoftware.ohcount4j.scan.RebolScanner;
import com.blackducksoftware.ohcount4j.scan.RexxScanner;
import com.blackducksoftware.ohcount4j.scan.RubyScanner;
import com.blackducksoftware.ohcount4j.scan.Scanner;
import com.blackducksoftware.ohcount4j.scan.SchemeScanner;
import com.blackducksoftware.ohcount4j.scan.ShellScanner;
import com.blackducksoftware.ohcount4j.scan.SmalltalkScanner;
import com.blackducksoftware.ohcount4j.scan.SqlScanner;
import com.blackducksoftware.ohcount4j.scan.TclScanner;
import com.blackducksoftware.ohcount4j.scan.TexScanner;
import com.blackducksoftware.ohcount4j.scan.VimScriptScanner;
import com.blackducksoftware.ohcount4j.scan.VisualBasicScanner;
import com.blackducksoftware.ohcount4j.scan.XmlScanner;
public enum Language implements LanguageCategory {
/*
* All languages must be defined here.
*
* Each language must declare three mandatory properties:
*
* - The language's official display name (niceName)
* - The category of the language, one of BUILD, LOGIC, MARKUP, UNKNOWN
* - A Scanner subclass capable of parsing this language
*/
ACTIONSCRIPT("ActionScript", LOGIC, ActionScriptScanner.class),
ADA("Ada", LOGIC, AdaScanner.class),
ASPX_CSHARP("ASP.NET (C#)", LOGIC, GenericCodeScanner.class), // TODO.
ASPX_VB("ASP.NET (VB)", LOGIC, GenericCodeScanner.class), // TODO.
ASSEMBLY("Assembly", LOGIC, AssemblyScanner.class),
AUGEAS("Augeas", LOGIC, AugeasScanner.class),
AUTOCONF("Autoconf", BUILD, AutoconfScanner.class),
AUTOMAKE("Automake", BUILD, AutomakeScanner.class),
AWK("Awk", LOGIC, AwkScanner.class),
BAT("Windows Batch", LOGIC, BatScanner.class),
BFPP("Brainfuck++", LOGIC, BfkppScanner.class),
BINARY("Binary", LOGIC, BinaryScanner.class),
BLITZMAX("BlitzMax", LOGIC, BlitzMaxScanner.class),
BOO("Boo", LOGIC, BooScanner.class),
BRAINFUCK("Brainfuck", LOGIC, BfkScanner.class),
C("C", LOGIC, CStyleScanner.class),
CHAISCRIPT("ChaiScript", LOGIC, CStyleScanner.class),
CLASSIC_BASIC("Classic BASIC", LOGIC, GenericCodeScanner.class), // TODO.
CLEARSILVER("ClearSilver", LOGIC, ClearSilverTemplateScanner.class),
CLOJURE("Clojure", LOGIC, ClojureScanner.class),
COBOL("COBOL", LOGIC, CobolScanner.class),
COFFEESCRIPT("CoffeeScript", LOGIC, CoffeeScriptScanner.class),
COLDFUSION("ColdFusion", MARKUP, ColdFusionScanner.class),
CPP("C++", LOGIC, CStyleScanner.class),
CMake("CMake", BUILD, CMakeScanner.class),
CSHARP("C#", LOGIC, CStyleScanner.class),
COQ("Coq", LOGIC, CoqScanner.class),
CSS("CSS", MARKUP, CStyleScanner.class),
CUDA("CUDA", LOGIC, CStyleScanner.class),
D("D", LOGIC, DScanner.class),
DYLAN("Dylan", LOGIC, CStyleScanner.class),
DCL("DCL", LOGIC, DclScanner.class),
EBUILD("Ebuild", BUILD, ShellScanner.class),
EC("eC", LOGIC, CStyleScanner.class),
ECMASCRIPT("ECMAScript", LOGIC, CStyleScanner.class),
EIFFEL("Eiffel", LOGIC, EiffelScanner.class),
ELIXIR("Elixir", LOGIC, ElixirScanner.class),
EMACSLISP("Emacs Lisp", LOGIC, LispScanner.class),
ERLANG("Erlang", LOGIC, ErlangScanner.class),
FACTOR("Factor", LOGIC, FactorScanner.class),
EXHERES("Exheres", LOGIC, ShellScanner.class),
FORTH("Forth", LOGIC, ForthScanner.class),
FORTRANFIXED("Fortran (Fixed-Format)", LOGIC, FortranFixedScanner.class),
FORTRANFREE("Fortran (Free-Format)", LOGIC, FortranFreeScanner.class),
FSHARP("F#", LOGIC, FSharpScanner.class),
GENIE("Genie", LOGIC, CStyleScanner.class),
GLSL("OpenGL Shading Language", LOGIC, CStyleScanner.class),
GOLANG("Go", LOGIC, CStyleScanner.class),
GROOVY("Groovy", LOGIC, CStyleScanner.class),
HAML("Haml", MARKUP, HamlScanner.class),
HAXE("HaXe", LOGIC, CStyleScanner.class),
HTML("HTML", MARKUP, HTMLScanner.class),
HASKELL("Haskell", LOGIC, HaskellScanner.class),
IDL_PVWAVE("IDL/PV-WAVE/GDL", LOGIC, IdlPvwaveScanner.class),
JAM("Jam", BUILD, ShellScanner.class),
JAVA("Java", LOGIC, CStyleScanner.class),
JAVASCRIPT("JavaScript", LOGIC, CStyleScanner.class),
JSP("JSP", LOGIC, JspScanner.class),
KOTLIN("Kotlin", LOGIC, CStyleScanner.class),
LIMBO("Limbo", LOGIC, CStyleScanner.class),
LISP("Lisp", LOGIC, LispScanner.class),
LOGTALK("Logtalk", LOGIC, LogtalkScanner.class),
LUA("Lua", LOGIC, LuaScanner.class),
MAKE("Make", BUILD, MakeScanner.class),
MATHEMATICA("Mathematica", LOGIC, MathematicaScanner.class),
MATLAB("Matlab", LOGIC, MatlabScanner.class),
METAPOST("MetaPost", MARKUP, MetapostWithTexScanner.class),
METAFONT("MetaFont", MARKUP, MetafontScanner.class),
MODULA2("Modula 2", LOGIC, ModulaScanner.class),
MODULA3("Modula 3", LOGIC, ModulaScanner.class),
OBJECTIVE_C("Objective-C", LOGIC, CStyleScanner.class),
OCAML("OCaml", LOGIC, OCamlScanner.class),
OCTAVE("Octave", LOGIC, MatlabScanner.class), // TODO. Octave also supports # comments
PASCAL("Pascal", LOGIC, PascalScanner.class),
PERL("Perl", LOGIC, PerlScanner.class),
PHP("Php", LOGIC, PhpScanner.class),
PUPPET("Puppet", LOGIC, GenericCodeScanner.class), // TODO.
PROLOG("Prolog", LOGIC, PrologScanner.class),
PYTHON("Python", LOGIC, PythonScanner.class),
R("R", LOGIC, GenericCodeScanner.class), // TODO.
REBOL("REBOL", LOGIC, RebolScanner.class),
REXX("Rexx", LOGIC, RexxScanner.class),
RUBY("Ruby", LOGIC, RubyScanner.class),
SCALA("Scala", LOGIC, CStyleScanner.class),
SWIFT("Swift", LOGIC, CStyleScanner.class),
SCHEME("Scheme", LOGIC, SchemeScanner.class),
SHELL("Shell", LOGIC, ShellScanner.class),
SMALLTALK("Smalltalk", LOGIC, SmalltalkScanner.class),
SQL("SQL", LOGIC, SqlScanner.class),
STRUCTURED_BASIC("Structured Basic", LOGIC, VisualBasicScanner.class),
TCL("Tcl", LOGIC, TclScanner.class),
TEX("TeX/LaTeX", MARKUP, TexScanner.class),
UNKNOWN("Unknown", CATEGORY_UNKNOWN, GenericCodeScanner.class),
VB("VisualBasic", LOGIC, VisualBasicScanner.class),
VBSCRIPT("VBScript", LOGIC, VisualBasicScanner.class),
VIMSCRIPT("Vimscript", LOGIC, VimScriptScanner.class),
XML("XML", MARKUP, XmlScanner.class),
XMLSCHEMA("XML Schema", MARKUP, XmlScanner.class),
XSLT("XSL Transformation", MARKUP, XmlScanner.class);
/*
* Optional properties of languages are declared here.
*
* At a minimum, a language should define one or more file
* extensions or filenames associated with the language.
*
* You may also declare additional names (beyond the uname
* and niceName) by which the language might be known.
* These aliases can be matched against things like Emacs
* mode headers or shebang directives.
*/
static {
ACTIONSCRIPT.extension("as");
ADA.extensions("ada", "adb");
ASPX_CSHARP.extension("aspx");
ASPX_VB.extension("aspx");
ASSEMBLY.extensions("as8", "asm", "asx", "S", "z80");
AUGEAS.extensions("aug");
AUTOCONF.extensions("autoconf", "ac", "m4"); // m4 (unix macro processor)
AUTOMAKE.extensions("am");
AWK.extension("awk");
BAT.extension("bat");
BFPP.extensions("bfpp");
BINARY.extensions("inc", "st");
BLITZMAX.extension("bmx");
BOO.extension("boo");
BRAINFUCK.extension("bf");
C.extensions("c", "h");
CHAISCRIPT.extension("chai");
CLASSIC_BASIC.extensions("b", "bas");
CLEARSILVER.extension("cs");
CLOJURE.extensions("clj", "cljs", "cljc");
CMake.extensions("cmake").filename("CMakeLists.txt");
COBOL.extension("cbl");
COFFEESCRIPT.extension("coffee");
COLDFUSION.extensions("cfc", "cfm");
CPP.extensions("C", "c++", "cc", "cpp", "cxx", "H", "h", "h++", "hh", "hpp", "hxx");
COQ.extension("v");
CSHARP.aliases("C#", "cs").extension("cs");
CSS.extension("css");
CUDA.extensions("cu", "cuh");
D.extension("d");
DYLAN.extension("dylan");
DCL.extension("com");
EBUILD.extensions("ebuild", "kdebuild-1", "eclass");
EC.extensions("ec", "eh");
ECMASCRIPT.extension("es");
EIFFEL.extension("e");
ELIXIR.extensions("ex", "exs");
EMACSLISP.extension("el");
ERLANG.extension("erl");
EXHERES.extensions("exheres-0", "exheres-1", "exlib");
FACTOR.extension("factor");
FORTH.extensions("fr", "4th");
FORTRANFIXED.extensions("i", "f", "f03", "f08", "f77", "f90", "f95", "for", "fpp", "ftn");
FORTRANFREE.extensions("i90", "f", "f03", "f08", "f77", "f90", "f95", "for", "fpp", "ftn");
FSHARP.extension("fs");
GENIE.extension("gs");
GLSL.extensions("frag", "glsl", "vert");
GOLANG.extensions("go");
GROOVY.extension("groovy");
HAML.extension("haml");
HAXE.extension("hx");
HTML.extensions("htm", "html");
HASKELL.extensions("hs", "lhs");
JAM.filenames("Jamfile", "Jamrules");
JAVA.extension("java");
JAVASCRIPT.alias("js").extension("js");
JSP.extension("jsp");
KOTLIN.extensions("kt", "kts");
LIMBO.extensions("b", "m");
LOGTALK.extension("lgt");
LUA.extension("lua");
MAKE.filename("Makefile").extensions("mk", "pro");
MATHEMATICA.extensions("nb", "nbs");
METAPOST.extension("mp");
METAFONT.extensions("mf");
MODULA2.extensions("mod", "m2");
MODULA3.extensions("m3", "i3");
OBJECTIVE_C.extensions("m", "h");
OCAML.extensions("ml", "mli");
OCTAVE.extensions("m", "octave");
PASCAL.extensions("pas", "pp");
PERL.extensions("pl", "pm");
PHP.extensions("inc", "php", "phtml", "php4", "php3", "php5", "phps");
IDL_PVWAVE.extension("pro");
PROLOG.extension("pl");
PUPPET.extension("pp");
PYTHON.extension("py");
R.extension("r");
REBOL.extensions("r", "r3", "reb", "rebol");
REXX.extensions("cmd", "exec", "rexx");
RUBY.alias("jruby").extensions("rb", "ru").filenames("Rakefile", "Gemfile");
SCALA.extensions("scala", "sc");
SWIFT.extensions("swift");
SCHEME.extensions("scm", "ss");
SHELL.extensions("bash", "sh");
SMALLTALK.extension("st");
SQL.extension("sql");
STRUCTURED_BASIC.extensions("b", "bas", "bi");
TCL.extension("tcl");
TEX.extension("tex");
VB.extensions("bas", "frm", "frx", "vb", "vba");
VBSCRIPT.extensions("vbs", "vbe");
VIMSCRIPT.extension("vim").aliases("Vim Script", "VimL");
XML.extensions("asx", "csproj", "xml", "mxml");
XMLSCHEMA.extension("xsd");
XSLT.extensions("xsl", "xslt");
}
private final String niceName;
private final String category;
private final Class<? extends Scanner> scannerClass;
private final List<String> extensions;
private final List<String> filenames;
private final List<String> aliases;
Language(String niceName, String category, Class<? extends Scanner> scannerClass) {
this.niceName = niceName;
this.category = category;
this.scannerClass = scannerClass;
extensions = new ArrayList<String>();
filenames = new ArrayList<String>();
aliases = new ArrayList<String>();
}
public String uname() {
return toString().toLowerCase();
}
public String niceName() {
return niceName;
}
public String category() {
return category;
}
public Class<? extends Scanner> scannerClass() {
return scannerClass;
}
public Scanner makeScanner() {
try {
Scanner scanner = scannerClass.newInstance();
scanner.setDefaultLanguage(this);
return scanner;
} catch (InstantiationException e) {
throw new OhcountException(e);
} catch (IllegalAccessException e) {
throw new OhcountException(e);
}
}
private Language extension(String ext) {
extensions.add(ext);
return this;
}
private Language extensions(String... exts) {
for (String ext : exts) {
extension(ext);
}
return this;
}
public List<String> getExtensions() {
return new ArrayList<String>(extensions);
}
private Language filename(String filename) {
filenames.add(filename);
return this;
}
private Language filenames(String... filenames) {
for (String filename : filenames) {
filename(filename);
}
return this;
}
public List<String> getFilenames() {
return new ArrayList<String>(filenames);
}
private Language alias(String alias) {
aliases.add(alias);
return this;
}
private Language aliases(String... aliases) {
for (String alias : aliases) {
alias(alias);
}
return this;
}
public List<String> getAliases() {
return new ArrayList<String>(aliases);
}
}
| blackducksoftware/ohcount4j | src/main/java/com/blackducksoftware/ohcount4j/Language.java | Java | apache-2.0 | 16,986 |
package pl.itdonat.demo.wsfbd.encryption;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import pl.itdonat.demo.wsfbd.encryption.encode.EncodeData;
import pl.itdonat.demo.wsfbd.encryption.encode.EncodeService;
import java.util.List;
/**
* Created by r.szarejko on 2017-03-22.
*/
@Controller
@RequestMapping("/crypto")
public class CryptoController {
private final EncodeService encodeService;
public CryptoController(EncodeService encodeService) {
this.encodeService = encodeService;
}
@GetMapping
public String get(Model model){
model.addAttribute("plainText", "");
return "crypto";
}
@PostMapping
public String post(Model model, @RequestParam String plainText){
List<EncodeData> encodeData = encodeService.prepareEncodedValueByAlgorithmMap(plainText);
model.addAttribute("valueList", encodeData);
model.addAttribute("plainText", plainText);
return "crypto";
}
@PostMapping("/broke")
@ResponseBody
public String postBroke(@RequestParam String hash, @RequestParam Algorithm algorithm){
String bruteForce = encodeService.bruteForce(hash, algorithm);
return bruteForce;
}
@GetMapping("/broke1")
@ResponseBody
public String postBroke(Model model){
return "7654321";
}
}
| RobertSzarejko/WebSecurityForBackendDev | web-security-demo/src/main/java/pl/itdonat/demo/wsfbd/encryption/CryptoController.java | Java | apache-2.0 | 1,419 |
/**
* Copyright 2011-2021 Asakusa Framework Team.
*
* 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.asakusafw.operator;
import java.text.MessageFormat;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Generated;
import javax.lang.model.SourceVersion;
import com.asakusafw.operator.description.AnnotationDescription;
import com.asakusafw.operator.description.ClassDescription;
import com.asakusafw.operator.description.Descriptions;
import com.asakusafw.operator.description.ValueDescription;
/**
* Available constant values in this project.
* @since 0.9.0
* @version 0.9.1
*/
public final class Constants {
private static final String BASE = "com.asakusafw.vocabulary."; //$NON-NLS-1$
private static ClassDescription classOf(String name) {
return new ClassDescription(BASE + name);
}
/**
* {@code OperatorHelper} annotation type name.
*/
public static final ClassDescription TYPE_ANNOTATION_HELPER = classOf("operator.OperatorHelper"); //$NON-NLS-1$
/**
* {@code In} type name.
*/
public static final ClassDescription TYPE_IN = classOf("flow.In"); //$NON-NLS-1$
/**
* {@code Out} type name.
*/
public static final ClassDescription TYPE_OUT = classOf("flow.Out"); //$NON-NLS-1$
/**
* {@code Source} type name.
*/
public static final ClassDescription TYPE_SOURCE = classOf("flow.Source"); //$NON-NLS-1$
/**
* {@code View} type name.
* @since 0.9.1
*/
public static final ClassDescription TYPE_VIEW =
new ClassDescription("com.asakusafw.runtime.core.View"); //$NON-NLS-1$
/**
* {@code GroupView} type name.
* @since 0.9.1
*/
public static final ClassDescription TYPE_GROUP_VIEW =
new ClassDescription("com.asakusafw.runtime.core.GroupView"); //$NON-NLS-1$
/**
* {@code Result} type name.
*/
public static final ClassDescription TYPE_RESULT =
new ClassDescription("com.asakusafw.runtime.core.Result"); //$NON-NLS-1$
/**
* {@code Key} type name.
*/
public static final ClassDescription TYPE_KEY = classOf("model.Key"); //$NON-NLS-1$
/**
* {@code Joined} type name.
*/
public static final ClassDescription TYPE_JOINED = classOf("model.Joined"); //$NON-NLS-1$
/**
* {@code Summarized} type name.
*/
public static final ClassDescription TYPE_SUMMARIZED = classOf("model.Summarized"); //$NON-NLS-1$
/**
* {@code FlowPart} annotation type name.
*/
public static final ClassDescription TYPE_FLOW_PART = classOf("flow.FlowPart"); //$NON-NLS-1$
/**
* {@code FlowDescription} type name.
*/
public static final ClassDescription TYPE_FLOW_DESCRIPTION = classOf("flow.FlowDescription"); //$NON-NLS-1$
/**
* {@code Import} type name.
*/
public static final ClassDescription TYPE_IMPORT = classOf("flow.Import"); //$NON-NLS-1$
/**
* {@code Export} type name.
*/
public static final ClassDescription TYPE_EXPORT = classOf("flow.Export"); //$NON-NLS-1$
/**
* {@code ImporterDescription} type name.
*/
public static final ClassDescription TYPE_IMPORTER_DESC = classOf("external.ImporterDescription"); //$NON-NLS-1$
/**
* {@code ExporterDescription} type name.
*/
public static final ClassDescription TYPE_EXPORTER_DESC = classOf("external.ExporterDescription"); //$NON-NLS-1$
/**
* {@code FlowElementBuilder} type name.
*/
public static final ClassDescription TYPE_ELEMENT_BUILDER =
classOf("flow.builder.FlowElementBuilder"); //$NON-NLS-1$
/**
* singleton name of flow-part factory method.
*/
public static final String NAME_FLOW_PART_FACTORY_METHOD = "create"; //$NON-NLS-1$
/**
* Simple name pattern for operator implementation class (0: simple name of operator class).
*/
private static final String PATTERN_IMPLEMENTATION_CLASS = "{0}Impl"; //$NON-NLS-1$
/**
* Simple name pattern for operator factory class (0: simple name of operator/flow-part class).
*/
private static final String PATTERN_FACTORY_CLASS = "{0}Factory"; //$NON-NLS-1$
/**
* Simple name pattern for built-in operator annotation class (0: simple name).
*/
private static final String PATTERN_BUILTIN_OPERATOR_ANNOTATION_CLASS = BASE + "operator.{0}"; //$NON-NLS-1$
/**
* The generator ID.
*/
public static final String GENERATOR_ID = "com.asakusafw.operator"; //$NON-NLS-1$
/**
* The generator name.
*/
public static final String GENERATOR_NAME = "Asakusa Operator DSL Compiler"; //$NON-NLS-1$
/**
* The generator version.
*/
public static final String GENERATOR_VERSION = "3.0.0"; //$NON-NLS-1$
/**
* Returns the implementation class name of target class with the specified name.
* @param simpleName the simple class name of the operator annotation
* @return qualified name
* @throws IllegalArgumentException if some parameters were {@code null}
*/
public static ClassDescription getBuiltinOperatorClass(String simpleName) {
Objects.requireNonNull(simpleName, "simpleName must not be null"); //$NON-NLS-1$
return new ClassDescription(MessageFormat.format(PATTERN_BUILTIN_OPERATOR_ANNOTATION_CLASS, simpleName));
}
/**
* Returns the implementation class name of target class with the specified name.
* @param originalName the original class name
* @return related implementation class name
* @throws IllegalArgumentException if some parameters were {@code null}
*/
public static ClassDescription getImplementationClass(CharSequence originalName) {
Objects.requireNonNull(originalName, "originalName must not be null"); //$NON-NLS-1$
return new ClassDescription(MessageFormat.format(PATTERN_IMPLEMENTATION_CLASS, originalName));
}
/**
* Returns the factory class name of target class with the specified name.
* @param originalName the original class name
* @return related factory class name
* @throws IllegalArgumentException if some parameters were {@code null}
*/
public static ClassDescription getFactoryClass(CharSequence originalName) {
Objects.requireNonNull(originalName, "originalName must not be null"); //$NON-NLS-1$
return new ClassDescription(MessageFormat.format(PATTERN_FACTORY_CLASS, originalName));
}
/**
* Returns the current supported source version.
* @return the supported version
*/
public static SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
/**
* Returns {@link Generated} annotation.
* @return the annotation
*/
public static AnnotationDescription getGenetedAnnotation() {
Map<String, ValueDescription> elements = new LinkedHashMap<>();
elements.put("value", Descriptions.valueOf(new String[] { //$NON-NLS-1$
GENERATOR_ID
}));
elements.put("comments", //$NON-NLS-1$
Descriptions.valueOf(MessageFormat.format(
"generated by {0} {1}", //$NON-NLS-1$
GENERATOR_NAME, GENERATOR_VERSION)));
return new AnnotationDescription(Descriptions.classOf(Generated.class), elements);
}
private Constants() {
return;
}
}
| asakusafw/asakusafw | operator/core/src/main/java/com/asakusafw/operator/Constants.java | Java | apache-2.0 | 8,005 |
<?php
/**
* This file is part of the SevenShores/NetSuite library
* AND originally from the NetSuite PHP Toolkit.
*
* New content:
* @package ryanwinchester/netsuite-php
* @copyright Copyright (c) Ryan Winchester
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
* @link https://github.com/ryanwinchester/netsuite-php
*
* Original content:
* @copyright Copyright (c) NetSuite Inc.
* @license https://raw.githubusercontent.com/ryanwinchester/netsuite-php/master/original/NetSuite%20Application%20Developer%20License%20Agreement.txt
* @link http://www.netsuite.com/portal/developers/resources/suitetalk-sample-applications.shtml
*
* generated: 2019-06-12 10:27:00 AM PDT
*/
namespace NetSuite\Classes;
class FairValuePriceSearchBasic extends SearchRecordBasic {
public $currency;
public $endDate;
public $externalId;
public $externalIdString;
public $fairValue;
public $fairValueFormula;
public $fairValueRangePolicy;
public $highValue;
public $highValuePercent;
public $internalId;
public $internalIdNumber;
public $isVsoePrice;
public $item;
public $itemRevenueCategory;
public $lowValue;
public $lowValuePercent;
public $startDate;
public $unitsType;
static $paramtypesmap = array(
"currency" => "SearchMultiSelectField",
"endDate" => "SearchDateField",
"externalId" => "SearchMultiSelectField",
"externalIdString" => "SearchStringField",
"fairValue" => "SearchDoubleField",
"fairValueFormula" => "SearchMultiSelectField",
"fairValueRangePolicy" => "SearchEnumMultiSelectField",
"highValue" => "SearchDoubleField",
"highValuePercent" => "SearchDoubleField",
"internalId" => "SearchMultiSelectField",
"internalIdNumber" => "SearchLongField",
"isVsoePrice" => "SearchBooleanField",
"item" => "SearchMultiSelectField",
"itemRevenueCategory" => "SearchMultiSelectField",
"lowValue" => "SearchDoubleField",
"lowValuePercent" => "SearchDoubleField",
"startDate" => "SearchDateField",
"unitsType" => "SearchMultiSelectField",
);
}
| fungku/netsuite-php | src/Classes/FairValuePriceSearchBasic.php | PHP | apache-2.0 | 2,206 |
/*
* 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 app.metatron.discovery.common;
import com.facebook.presto.jdbc.PrestoArray;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
/**
* Created by kyungtaak on 2016. 10. 11..
*/
public class ResultSetSerializer extends JsonSerializer<ResultSet> {
public static class ResultSetSerializerException extends JsonProcessingException {
private static final long serialVersionUID = -914957626413580734L;
public ResultSetSerializerException(Throwable cause) {
super(cause);
}
}
@Override
public Class<ResultSet> handledType() {
return ResultSet.class;
}
@Override
public void serialize(ResultSet rs, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
try {
ResultSetMetaData rsmd = rs.getMetaData();
int numColumns = rsmd.getColumnCount();
String[] columnNames = new String[numColumns];
int[] columnTypes = new int[numColumns];
for (int i = 0; i < columnNames.length; i++) {
columnNames[i] = rsmd.getColumnLabel(i + 1);
columnTypes[i] = rsmd.getColumnType(i + 1);
}
jgen.writeStartArray();
while (rs.next()) {
boolean b;
long l;
double d;
jgen.writeStartObject();
for (int i = 0; i < columnNames.length; i++) {
jgen.writeFieldName(columnNames[i]);
switch (columnTypes[i]) {
case Types.INTEGER:
l = rs.getInt(i + 1);
if (rs.wasNull()) {
jgen.writeNull();
} else {
jgen.writeNumber(l);
}
break;
case Types.BIGINT:
l = rs.getLong(i + 1);
if (rs.wasNull()) {
jgen.writeNull();
} else {
jgen.writeNumber(l);
}
break;
case Types.DECIMAL:
case Types.NUMERIC:
jgen.writeNumber(rs.getBigDecimal(i + 1));
break;
case Types.FLOAT:
case Types.REAL:
case Types.DOUBLE:
d = rs.getDouble(i + 1);
if (rs.wasNull()) {
jgen.writeNull();
} else {
jgen.writeNumber(d);
}
break;
case Types.NVARCHAR:
case Types.VARCHAR:
case Types.LONGNVARCHAR:
case Types.LONGVARCHAR:
jgen.writeString(rs.getString(i + 1));
break;
case Types.BOOLEAN:
case Types.BIT:
b = rs.getBoolean(i + 1);
if (rs.wasNull()) {
jgen.writeNull();
} else {
jgen.writeBoolean(b);
}
break;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
jgen.writeBinary(rs.getBytes(i + 1));
break;
case Types.TINYINT:
case Types.SMALLINT:
l = rs.getShort(i + 1);
if (rs.wasNull()) {
jgen.writeNull();
} else {
jgen.writeNumber(l);
}
break;
case Types.DATE:
Date date = rs.getDate(i + 1);
if(date == null) {
jgen.writeNull();
} else {
provider.defaultSerializeDateValue(rs.getDate(i + 1), jgen);
}
break;
case Types.TIME:
case Types.TIME_WITH_TIMEZONE:
Time time = rs.getTime(i + 1);
if(time == null) {
jgen.writeNull();
} else {
provider.defaultSerializeDateValue(rs.getTime(i + 1), jgen);
}
break;
case Types.TIMESTAMP:
case Types.TIMESTAMP_WITH_TIMEZONE:
Timestamp ts = rs.getTimestamp(i + 1);
if(ts == null) {
jgen.writeNull();
} else {
provider.defaultSerializeDateValue(rs.getTimestamp(i + 1), jgen);
}
break;
case Types.BLOB:
Blob blob = rs.getBlob(i);
provider.defaultSerializeValue(blob.getBinaryStream(), jgen);
blob.free();
break;
case Types.CLOB:
Clob clob = rs.getClob(i);
provider.defaultSerializeValue(clob.getCharacterStream(), jgen);
clob.free();
break;
case Types.ARRAY:
if(rs.getObject(i + 1) instanceof PrestoArray) {
provider.defaultSerializeValue(((PrestoArray) rs.getObject(i + 1)).getArray(), jgen);
} else {
provider.defaultSerializeValue(rs.getArray(i + 1), jgen);
}
break;
case Types.STRUCT:
throw new RuntimeException("ResultSetSerializer not yet implemented for SQL type STRUCT");
case Types.DISTINCT:
throw new RuntimeException("ResultSetSerializer not yet implemented for SQL type DISTINCT");
case Types.REF:
throw new RuntimeException("ResultSetSerializer not yet implemented for SQL type REF");
case Types.JAVA_OBJECT:
default:
provider.defaultSerializeValue(rs.getObject(i + 1), jgen);
break;
}
}
jgen.writeEndObject();
}
jgen.writeEndArray();
} catch (SQLException e) {
throw new ResultSetSerializerException(e);
}
}
}
| metatron-app/metatron-discovery | discovery-server/src/main/java/app/metatron/discovery/common/ResultSetSerializer.java | Java | apache-2.0 | 6,631 |
//------------------------------------------------------------------------------
// <automatisch generiert>
// Dieser Code wurde von einem Tool generiert.
//
// Änderungen an dieser Datei können fehlerhaftes Verhalten verursachen und gehen verloren, wenn
// der Code neu generiert wird.
// </automatisch generiert>
//------------------------------------------------------------------------------
namespace YAF.Controls
{
public partial class EditUsersInfo
{
/// <summary>
/// LocalizedLabel1-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.LocalizedLabel LocalizedLabel1;
/// <summary>
/// HelpLabel1-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel1;
/// <summary>
/// Name-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox Name;
/// <summary>
/// HelpLabel2-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel2;
/// <summary>
/// DisplayName-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox DisplayName;
/// <summary>
/// HelpLabel3-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel3;
/// <summary>
/// Email-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox Email;
/// <summary>
/// HelpLabel4-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel4;
/// <summary>
/// RankID-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList RankID;
/// <summary>
/// IsHostAdminRow-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder IsHostAdminRow;
/// <summary>
/// HelpLabel15-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel15;
/// <summary>
/// Moderated-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox Moderated;
/// <summary>
/// HelpLabel5-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel5;
/// <summary>
/// IsHostAdminX-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox IsHostAdminX;
/// <summary>
/// IsCaptchaExcludedRow-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder IsCaptchaExcludedRow;
/// <summary>
/// HelpLabel6-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel6;
/// <summary>
/// IsCaptchaExcluded-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox IsCaptchaExcluded;
/// <summary>
/// IsExcludedFromActiveUsersRow-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder IsExcludedFromActiveUsersRow;
/// <summary>
/// HelpLabel7-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel7;
/// <summary>
/// IsExcludedFromActiveUsers-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox IsExcludedFromActiveUsers;
/// <summary>
/// HelpLabel8-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel8;
/// <summary>
/// IsApproved-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox IsApproved;
/// <summary>
/// ApproveHolder-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder ApproveHolder;
/// <summary>
/// ApproveUser-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.ThemeButton ApproveUser;
/// <summary>
/// DisabledHolder-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder DisabledHolder;
/// <summary>
/// HelpLabel16-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel16;
/// <summary>
/// UnDisableUser-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox UnDisableUser;
/// <summary>
/// IsGuestRow-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder IsGuestRow;
/// <summary>
/// HelpLabel9-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel9;
/// <summary>
/// IsGuestX-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox IsGuestX;
/// <summary>
/// HelpLabel10-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel10;
/// <summary>
/// Joined-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox Joined;
/// <summary>
/// HelpLabel11-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel11;
/// <summary>
/// LastVisit-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox LastVisit;
/// <summary>
/// HelpLabel12-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel12;
/// <summary>
/// IsFacebookUser-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox IsFacebookUser;
/// <summary>
/// HelpLabel13-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel13;
/// <summary>
/// IsTwitterUser-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox IsTwitterUser;
/// <summary>
/// HelpLabel14-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel14;
/// <summary>
/// IsGoogleUser-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox IsGoogleUser;
/// <summary>
/// Save-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.ThemeButton Save;
}
}
| YAFNET/YAFNET | yafsrc/YetAnotherForum.NET/Controls/EditUsersInfo.ascx.designer.cs | C# | apache-2.0 | 14,587 |
import { Trans } from "@lingui/macro";
import classNames from "classnames/dedupe";
import * as React from "react";
type Action = {
className?: string;
clickHandler?: (e?: any) => void;
disabled?: boolean;
label?: string;
node?: React.ReactNode;
};
class FullScreenModalHeaderActions extends React.Component<{
actions: Action[];
className?: string;
type: "primary" | "secondary";
}> {
getActions() {
const { actions } = this.props;
if (!actions || actions.length === 0) {
return null;
}
return actions.map(
({ className, clickHandler, label, node, disabled }, index) => {
if (node) {
return node;
}
const classes = classNames("button flush-top", className);
return (
<button
className={classes}
disabled={disabled}
key={index}
onClick={clickHandler}
>
<Trans id={label} />
</button>
);
}
);
}
render() {
const classes = classNames(
`modal-full-screen-actions modal-full-screen-actions-${this.props.type} flush-vertical`,
this.props.className
);
return <div className={classes}>{this.getActions()}</div>;
}
}
export default FullScreenModalHeaderActions;
| dcos/dcos-ui | src/js/components/modals/FullScreenModalHeaderActions.tsx | TypeScript | apache-2.0 | 1,285 |
/* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconExposurePlus1(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M10 7H8v4H4v2h4v4h2v-4h4v-2h-4V7zm10 11h-2V7.38L15 8.4V6.7L19.7 5h.3v13z"/>
</g>
</Icon>
);
}
IconExposurePlus1.displayName = 'IconExposurePlus1';
IconExposurePlus1.category = 'image';
| mineral-ui/mineral-ui | packages/mineral-ui-icons/src/IconExposurePlus1.js | JavaScript | apache-2.0 | 553 |
/*
* Copyright (c) 2015. Pokevian Ltd.
*
* 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.pokevian.app.smartfleet.service.floatinghead;
import android.content.Context;
import android.os.Build;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import org.apache.log4j.Logger;
import java.util.HashMap;
import java.util.Locale;
/**
* Created by dg.kim on 2015-04-13.
*/
public class TtsHandler {
private static final String TAG = "TtsHandler";
private TextToSpeech mTts;
private final Callbacks mCallbacks;
public TtsHandler(Context context, Callbacks callbacks) {
mTts = new TextToSpeech(context, new TtsInitListener());
mCallbacks = callbacks;
}
public void shutdown() {
if (mTts != null) {
mTts.stop();
mTts.shutdown();
mTts = null;
}
}
public boolean speak(CharSequence text) {
if (mTts != null) {
String utteranceId = String.valueOf(Math.random());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mTts.speak(text, TextToSpeech.QUEUE_FLUSH, null, utteranceId);
} else {
HashMap<String, String> params = new HashMap<>();
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, utteranceId);
mTts.speak(text.toString(), TextToSpeech.QUEUE_FLUSH, params);
}
mCallbacks.onTtsStart(utteranceId);
return true;
} else {
return false;
}
}
public void stopSpeak() {
if (mTts != null && mTts.isSpeaking()) {
mTts.stop();
}
}
private void setUtteranceListener() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
mTts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
@Override
public void onStart(String utteranceId) {
Logger.getLogger(TAG).info("tts start");
}
@Override
public void onDone(String utteranceId) {
Logger.getLogger(TAG).info("tts done");
mCallbacks.onTtsDone(utteranceId);
}
@Override
public void onError(String utteranceId) {
Logger.getLogger(TAG).info("tts error");
mCallbacks.onTtsDone(utteranceId);
}
});
} else {
mTts.setOnUtteranceCompletedListener(new TextToSpeech.OnUtteranceCompletedListener() {
@Override
public void onUtteranceCompleted(String utteranceId) {
Logger.getLogger(TAG).info("tts done");
mCallbacks.onTtsDone(utteranceId);
}
});
}
}
private class TtsInitListener implements TextToSpeech.OnInitListener {
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = mTts.setLanguage(Locale.getDefault());
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Logger.getLogger(TAG).warn(Locale.getDefault() + " is not supported!");
mTts.shutdown();
mTts = null;
mCallbacks.onTtsInit(false);
} else {
Logger.getLogger(TAG).warn(Locale.getDefault() + "TTS initialized");
setUtteranceListener();
mCallbacks.onTtsInit(true);
}
} else {
Logger.getLogger(TAG).warn(Locale.getDefault() + "failed to initialize TTS");
}
}
}
public interface Callbacks {
void onTtsInit(boolean result);
void onTtsStart(String utteranceId);
void onTtsDone(String utteranceId);
}
}
| Pokevian/caroolive-app | app/src/main/java/com/pokevian/app/smartfleet/service/floatinghead/TtsHandler.java | Java | apache-2.0 | 4,562 |
using System.Data.Entity;
using System.Linq;
using Moq;
using Riganti.Utils.Infrastructure.Core;
using Xunit;
namespace Riganti.Utils.Infrastructure.EntityFramework.Tests.Repository
{
public class EntityFrameworkRepositoryTests
{
private static readonly EpisodeEntity[] episodesSeriesOne =
{
new EpisodeEntity {Id = 1, Series = 1, Title = "Open Government"},
new EpisodeEntity {Id = 2, Series = 1, Title = "The Official Visit"},
new EpisodeEntity {Id = 3, Series = 1, Title = "The Economy Drive"},
new EpisodeEntity {Id = 4, Series = 1, Title = "Big Brother"},
new EpisodeEntity {Id = 5, Series = 1, Title = "The Writing on the Wall"},
new EpisodeEntity {Id = 6, Series = 1, Title = "The Right to Know"},
new EpisodeEntity {Id = 7, Series = 1, Title = "Jobs for the Boys"}
};
private static readonly QuoteEntity[] quotes =
{
new QuoteEntity {Id = 1, Text = " It is not for a humble mortal such as I to speculate on the complex and elevated deliberations of the mighty."},
};
private readonly Mock<YesMinisterDbContext> dbContextMock;
private readonly EntityFrameworkRepository<EpisodeEntity, int> episodeRepositorySUT;
private readonly EntityFrameworkRepository<QuoteEntity, int> quoteRepositorySUT;
private readonly Mock<IDbSet<EpisodeEntity>> episodesDbSetMock;
private readonly Mock<IDbSet<QuoteEntity>> quotesDbSetMock;
public EntityFrameworkRepositoryTests()
{
var dbContextMockFactory = new DbContextMockFactory();
dbContextMock = dbContextMockFactory.CreateDbContextMock<YesMinisterDbContext>();
episodesDbSetMock = dbContextMock.SetupDbSet<YesMinisterDbContext, EpisodeEntity, int>(episodesSeriesOne, context => context.Episodes);
quotesDbSetMock = dbContextMock.SetupDbSet<YesMinisterDbContext, QuoteEntity, int>(quotes, context => context.Quotes);
episodeRepositorySUT = CreateEntityFrameworkRepository<EpisodeEntity>();
quoteRepositorySUT = CreateEntityFrameworkRepository<QuoteEntity>();
}
[Fact]
public void InitializeNew_ReturnsNotNullItem()
{
var newEpisode = episodeRepositorySUT.InitializeNew();
Assert.NotNull(newEpisode);
}
[Fact]
public void Insert_OneItem_CallDbSetAddMethod()
{
var newEpisode = new EpisodeEntity { Id = 10, Title = "Inserted item" };
episodeRepositorySUT.Insert(newEpisode);
episodesDbSetMock.Verify(set => set.Add(newEpisode), Times.Once);
}
[Fact]
public void Insert_MultipleItems_NewItemShouldBeInDbSetLocal()
{
var newEpisode1 = new EpisodeEntity { Id = 10, Title = "Inserted item 1" };
var newEpisode2 = new EpisodeEntity { Id = 11, Title = "Inserted item 2" };
var newEpisode3 = new EpisodeEntity { Id = 12, Title = "Inserted item 3" };
var newEpisodes = new[] { newEpisode1, newEpisode2, newEpisode3 };
episodeRepositorySUT.Insert(newEpisodes);
Assert.Contains(newEpisode1, episodesDbSetMock.Object.Local);
Assert.Contains(newEpisode2, episodesDbSetMock.Object.Local);
Assert.Contains(newEpisode3, episodesDbSetMock.Object.Local);
}
[Fact]
public void Delete_OneItem_SetEntityStateToModified()
{
var deletedEpisode = episodesSeriesOne[1];
episodeRepositorySUT.Delete(deletedEpisode);
Assert.DoesNotContain(deletedEpisode, episodesDbSetMock.Object.Local);
}
[Fact]
public void Delete_MultipleItems_SetEntityStateToModified()
{
var deletedEpisode1 = episodesSeriesOne[1];
var deletedEpisode2 = episodesSeriesOne[2];
var deletedEpisode3 = episodesSeriesOne[3];
var deletedEpisodes = new[] { deletedEpisode1, deletedEpisode2, deletedEpisode3 };
episodeRepositorySUT.Delete(deletedEpisodes);
Assert.DoesNotContain(deletedEpisode1, episodesDbSetMock.Object.Local);
Assert.DoesNotContain(deletedEpisode2, episodesDbSetMock.Object.Local);
Assert.DoesNotContain(deletedEpisode3, episodesDbSetMock.Object.Local);
}
[Fact]
public void DeleteById_OneItem_ShouldDeleteItemFromDbSetLocal()
{
var deletedEpisode = episodesSeriesOne[1];
episodeRepositorySUT.Delete(deletedEpisode.Id);
Assert.DoesNotContain(deletedEpisode, episodesDbSetMock.Object.Local);
}
[Fact]
public void DeleteById_OneItem_ShouldCallRemove()
{
var deletedEpisode = episodesSeriesOne[1];
episodeRepositorySUT.Delete(deletedEpisode.Id);
episodesDbSetMock.Verify(set => set.Remove(It.Is<EpisodeEntity>(entity => entity.Id == deletedEpisode.Id)), Times.Once);
}
[Fact]
public void DeleteById_MultipleItems_SetEntityStateToModified()
{
var deletedEpisode1 = episodesSeriesOne[1];
var deletedEpisode2 = episodesSeriesOne[2];
var deletedEpisode3 = episodesSeriesOne[3];
var deletedEpisodesIds = new[] { deletedEpisode1.Id, deletedEpisode2.Id, deletedEpisode3.Id };
episodeRepositorySUT.Delete(deletedEpisodesIds);
Assert.DoesNotContain(deletedEpisode1, episodesDbSetMock.Object.Local);
Assert.DoesNotContain(deletedEpisode2, episodesDbSetMock.Object.Local);
Assert.DoesNotContain(deletedEpisode3, episodesDbSetMock.Object.Local);
}
[Fact]
public void SoftDelete_OneItem_SetDeletedDate()
{
var deletedQuote = quotes[0];
quoteRepositorySUT.Delete(deletedQuote);
var quoteById = quoteRepositorySUT.GetById(deletedQuote.Id);
Assert.NotNull(quoteById.DeletedDate);
}
[Fact]
public void SoftDelete_MultipleItems_SetEntityStateToModified()
{
var deletedEpisode1 = episodesSeriesOne[1];
var deletedEpisode2 = episodesSeriesOne[2];
var deletedEpisode3 = episodesSeriesOne[3];
var deletedEpisodes = new[] { deletedEpisode1, deletedEpisode2, deletedEpisode3 };
episodeRepositorySUT.Delete(deletedEpisodes);
Assert.DoesNotContain(deletedEpisode1, episodesDbSetMock.Object.Local);
Assert.DoesNotContain(deletedEpisode2, episodesDbSetMock.Object.Local);
Assert.DoesNotContain(deletedEpisode3, episodesDbSetMock.Object.Local);
}
[Fact]
public void SoftDeleteById_OneItem_ShouldDeleteItemFromDbSetLocal()
{
var deletedEpisode = episodesSeriesOne[1];
episodeRepositorySUT.Delete(deletedEpisode.Id);
Assert.DoesNotContain(deletedEpisode, episodesDbSetMock.Object.Local);
}
[Fact]
public void SoftDeleteById_OneItem_ShouldCallRemove()
{
var deletedEpisode = episodesSeriesOne[1];
episodeRepositorySUT.Delete(deletedEpisode.Id);
episodesDbSetMock.Verify(set => set.Remove(It.Is<EpisodeEntity>(entity => entity.Id == deletedEpisode.Id)), Times.Once);
}
[Fact]
public void SoftDeleteById_MultipleItems_SetEntityStateToModified()
{
var deletedEpisode1 = episodesSeriesOne[1];
var deletedEpisode2 = episodesSeriesOne[2];
var deletedEpisode3 = episodesSeriesOne[3];
var deletedEpisodesIds = new[] { deletedEpisode1.Id, deletedEpisode2.Id, deletedEpisode3.Id };
episodeRepositorySUT.Delete(deletedEpisodesIds);
Assert.DoesNotContain(deletedEpisode1, episodesDbSetMock.Object.Local);
Assert.DoesNotContain(deletedEpisode2, episodesDbSetMock.Object.Local);
Assert.DoesNotContain(deletedEpisode3, episodesDbSetMock.Object.Local);
}
[Fact]
public void GetById_OneItem_ReturnsCorrectItem()
{
var id = 1;
var expectedEpisode = episodesSeriesOne.Single(e => e.Id == id);
var episode = episodeRepositorySUT.GetById(id);
Assert.Equal(expectedEpisode, episode);
}
[Fact]
public void GetByIds_MultipleItems_ReturnsCorrectItem()
{
var id1 = 1;
var id2 = 2;
var id3 = 3;
var expectedEpisode1 = episodesSeriesOne.Single(e => e.Id == id1);
var expectedEpisode2 = episodesSeriesOne.Single(e => e.Id == id2);
var expectedEpisode3 = episodesSeriesOne.Single(e => e.Id == id3);
var episodes = episodeRepositorySUT.GetByIds(new[] { 1, 2, 3 });
Assert.Contains(expectedEpisode1, episodes);
Assert.Contains(expectedEpisode2, episodes);
Assert.Contains(expectedEpisode3, episodes);
}
private EntityFrameworkRepository<TEntity, int> CreateEntityFrameworkRepository<TEntity>() where TEntity : class, IEntity<int>, new()
{
var unitOfWorkRegistryStub = new ThreadLocalUnitOfWorkRegistry();
var unitOfWorkProvider = new EntityFrameworkUnitOfWorkProvider(unitOfWorkRegistryStub,
CreateYesMinisterDbContext);
IDateTimeProvider dateTimeProvider = new UtcDateTimeProvider();
var unitOfWork = new EntityFrameworkUnitOfWork(unitOfWorkProvider, CreateYesMinisterDbContext,
DbContextOptions.ReuseParentContext);
unitOfWorkRegistryStub.RegisterUnitOfWork(unitOfWork);
return new EntityFrameworkRepository<TEntity, int>(unitOfWorkProvider, dateTimeProvider);
}
private YesMinisterDbContext CreateYesMinisterDbContext()
{
return dbContextMock.Object;
}
}
} | riganti/infrastructure | src/Infrastructure/Tests/Riganti.Utils.Infrastructure.EntityFramework.Tests/Repository/EntityFrameworkRepositoryTests.cs | C# | apache-2.0 | 10,020 |
Ti.UI.setBackgroundColor('#fff');
var inicio = Ti.UI.createWindow({
backgroundColor:'#fff'
});
var titulo = Ti.UI.createLabel({
text:'UAM',
width:'300dp',
height:'50dp',
left:'10dp',
top:'100dp',
font:{fontSize:30,
fontFamily:'Helvetica Neue'},
textAlign:'center',
});
inicio.add(titulo);
var data = [{title:'Ingresar'},{title:'Registrarse'}];
var opciones = Ti.UI.createTableView({
width:'300dp',
height:'100dp',
top:'180dp',
left:'10dp',
data:data,
color:'#000'
});
inicio.add(opciones);
opciones.addEventListener('click', function(e){
if(e.index==0){
var vIng = Ti.UI.createWindow({
url:'/ui/ingresar'
});
vIng.open({modal:true});
}
else{
alert('Registrar' +e.index);
Ti.API.info('Estoy en la opcion registrarse'+ e.index);
}
});
inicio.open();
| addieljuarez/TallerUAM | Resources/app.js | JavaScript | apache-2.0 | 789 |
/*
*
* 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 org.apache.qpid.proton.amqp.transport;
import java.util.Map;
import org.apache.qpid.proton.amqp.Symbol;
public final class ErrorCondition
{
private Symbol _condition;
private String _description;
private Map _info;
public Symbol getCondition()
{
return _condition;
}
public void setCondition(Symbol condition)
{
if( condition == null )
{
throw new NullPointerException("the condition field is mandatory");
}
_condition = condition;
}
public String getDescription()
{
return _description;
}
public void setDescription(String description)
{
_description = description;
}
public Map getInfo()
{
return _info;
}
public void setInfo(Map info)
{
_info = info;
}
@Override
public String toString()
{
return "Error{" +
"_condition=" + _condition +
", _description='" + _description + '\'' +
", _info=" + _info +
'}';
}
}
| chirino/proton | proton-j/proton-api/src/main/java/org/apache/qpid/proton/amqp/transport/ErrorCondition.java | Java | apache-2.0 | 1,885 |
package com.icfcc.db.orderhelper;
import com.icfcc.db.orderhelper.sqlsource.*;
import org.apache.ibatis.builder.StaticSqlSource;
import org.apache.ibatis.builder.annotation.ProviderSqlSource;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.scripting.defaults.RawSqlSource;
import org.apache.ibatis.scripting.xmltags.DynamicSqlSource;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import java.util.Properties;
/**
* 排序辅助类
*
* @author liuzh
* @since 2015-06-26
*/
@SuppressWarnings({"rawtypes", "unchecked"})
@Intercepts(@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}))
public class OrderByHelper implements Interceptor {
private static final ThreadLocal<String> ORDER_BY = new ThreadLocal<String>();
public static String getOrderBy() {
String orderBy = ORDER_BY.get();
if (orderBy == null || orderBy.length() == 0) {
return null;
}
return orderBy;
}
/**
* 增加排序
*
* @param orderBy
*/
public static void orderBy(String orderBy) {
ORDER_BY.set(orderBy);
}
/**
* 清除本地变量
*/
public static void clear() {
ORDER_BY.remove();
}
/**
* 是否已经处理过
*
* @param ms
* @return
*/
public static boolean hasOrderBy(MappedStatement ms) {
if (ms.getSqlSource() instanceof OrderBySqlSource) {
return true;
}
return false;
}
/**
* 不支持注解形式(ProviderSqlSource)的增加order by
*
* @param invocation
* @throws Throwable
*/
public static void processIntercept(Invocation invocation) throws Throwable {
final Object[] args = invocation.getArgs();
MappedStatement ms = (MappedStatement) args[0];
if (!hasOrderBy(ms)) {
MetaObject msObject = SystemMetaObject.forObject(ms);
//判断是否自带order by,自带的情况下作为默认排序
SqlSource sqlSource = ms.getSqlSource();
if (sqlSource instanceof StaticSqlSource) {
msObject.setValue("sqlSource", new OrderByStaticSqlSource((StaticSqlSource) sqlSource));
} else if (sqlSource instanceof RawSqlSource) {
msObject.setValue("sqlSource", new OrderByRawSqlSource((RawSqlSource) sqlSource));
} else if (sqlSource instanceof ProviderSqlSource) {
msObject.setValue("sqlSource", new OrderByProviderSqlSource((ProviderSqlSource) sqlSource));
} else if (sqlSource instanceof DynamicSqlSource) {
msObject.setValue("sqlSource", new OrderByDynamicSqlSource((DynamicSqlSource) sqlSource));
} else {
throw new RuntimeException("无法处理该类型[" + sqlSource.getClass() + "]的SqlSource");
}
}
}
@Override
public Object intercept(Invocation invocation) throws Throwable {
try {
if (getOrderBy() != null) {
processIntercept(invocation);
}
return invocation.proceed();
} finally {
clear();
}
}
@Override
public Object plugin(Object target) {
if (target instanceof Executor) {
return Plugin.wrap(target, this);
} else {
return target;
}
}
@Override
public void setProperties(Properties properties) {
}
}
| Gitpiece/ssm | ssm-db-support/src/main/java/com/icfcc/db/orderhelper/OrderByHelper.java | Java | apache-2.0 | 3,806 |
package ru.tr1al.dao;
import ru.tr1al.model.Model;
public interface DAO<T extends Model> {
Class<T> getEntityClass();
}
| Tr1aL/utils | src/main/java/ru/tr1al/dao/DAO.java | Java | apache-2.0 | 127 |
package test
import (
"bufio"
"os"
"testing"
)
import manager "github.com/tiagofalcao/GoNotebook/manager"
func Benchmark(b *testing.B, input string, caseTask manager.Task) {
i, err := os.Open(input)
if err != nil {
b.Errorf("Can't open %s", input)
}
var o NilWriter
b.ResetTimer()
for x := 0; x < b.N; x++ {
manager.NewManagerIO(caseTask, bufio.NewReader(i), o)
}
i.Close()
}
| tiagofalcao/GoNotebook | manager/test/benchmark.go | GO | apache-2.0 | 423 |
package com.example.views;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.ViewSwitcher;
import android.widget.ViewSwitcher.ViewFactory;
public class V_ViewSwitcher extends GhostActivity {
private ViewSwitcher switcher;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.uistudy_view_switcher);
switcher = this.findViewSwitcher(R.id.viewSwitcher);
//===给swticher设置View工厂,当调用switcher.getNextView()时,就是返回 factory.makeView()创建的View
//===这里给一个TextView,让swticher切换多个TextView
switcher.setFactory(new ViewFactory() {
@Override
public View makeView() {
return new TextView(V_ViewSwitcher.this);
}
});
}
private int count = 0;
//====消息响应:下一个
public void next(View v){
count++;
switcher.setInAnimation(this, R.anim.slide_in_right); //切换组件:显示过程的动画
switcher.setOutAnimation(this, R.anim.slide_out_left); //切换组件:隐藏过程的动画
TextView textView = (TextView) switcher.getNextView();
textView.setText("This is "+count+"!!!");
textView.setTextSize(22);
textView.setTextColor(0xffff0000);
switcher.showNext();
}
//====消息响应:上一个
public void prev(View v){
count--;
switcher.setInAnimation(this, R.anim.slide_in_left); //切换组件:显示过程的动画
switcher.setOutAnimation(this, R.anim.slide_out_right); //切换组件:隐藏过程的动画
TextView textView = (TextView) switcher.getNextView();
textView.setText("This is "+count+"!!!");
textView.setTextSize(22);
textView.setTextColor(0xffff0000);
switcher.showPrevious();
}
}
| cowthan/AyoWeibo | sample/back/src/com/example/views/V_ViewSwitcher.java | Java | apache-2.0 | 1,766 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Knowit.EPiModules.ImageScaling.Sample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Knowit.EPiModules.ImageScaling.Sample")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4afc5705-c5ba-4f1d-97e2-81020c83c492")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| knowit/Knowit.EPiModules.ImageScaling | sample/Properties/AssemblyInfo.cs | C# | apache-2.0 | 1,410 |
package gov.va.med.imaging.storage.cache;
import java.util.Iterator;
import java.util.regex.Pattern;
import gov.va.med.imaging.storage.cache.events.GroupLifecycleListener;
import gov.va.med.imaging.storage.cache.exceptions.CacheException;
/**
*
* i.e. A Group may contain other Group instances, which contain other Group instances,
* which eventually contain Instance.
*
*/
public interface Group
extends MutableNamedObject, GroupAndInstanceAncestor, GroupSet, InstanceSet
{
// A group name must be 1 to 64 chars, start with a letter and contain letters, numbers, dashes and underscores
public static Pattern NamePattern = Pattern.compile( "[a-zA-Z][a-zA-Z0-9-_]{0,63}" );
/**
* Return some human readable identifier for this group.
* This must be unique within the parent group, not necessarily across all groups.
* @return
*/
@Override
public String getName();
public java.util.Date getLastAccessed()
throws CacheException;
public long getSize()
throws CacheException;
// ===========================================================================
// Methods that recursively walk down the Region/Group/Instance graph are
// defined in GroupAndInstanceAncestor
// ===========================================================================
// ===========================================================================
// Methods operating on the child Group of this Group are defined in GroupSet
// ===========================================================================
// =====================================================================================
// Methods operating on child Instance are defined in InstanceSet
// =====================================================================================
// =====================================================================================
// Eviction Methods
// =====================================================================================
public int evaluateAndEvictChildGroups(EvictionJudge<Group> judge)
throws CacheException;
// ======================================================================================================
// Listener Management
// ======================================================================================================
public abstract void registerListener(GroupLifecycleListener listener);
public abstract void unregisterListener(GroupLifecycleListener listener);
}
| VHAINNOVATIONS/Telepathology | Source/Java/CacheAPI/main/src/java/gov/va/med/imaging/storage/cache/Group.java | Java | apache-2.0 | 2,459 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.retail.v2.model;
/**
* Product captures all metadata information of items to be recommended or searched.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Retail API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class GoogleCloudRetailV2Product extends com.google.api.client.json.GenericJson {
/**
* Highly encouraged. Extra product attributes to be included. For example, for products, this
* could include the store name, vendor, style, color, etc. These are very strong signals for
* recommendation model, thus we highly recommend providing the attributes here. Features that can
* take on one of a limited number of possible values. Two types of features can be set are:
* Textual features. some examples would be the brand/maker of a product, or country of a
* customer. Numerical features. Some examples would be the height/weight of a product, or age of
* a customer. For example: `{ "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm":
* {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }`. This field needs to pass all
* below criteria, otherwise an INVALID_ARGUMENT error is returned: * Max entries count: 200. *
* The key must be a UTF-8 encoded string with a length limit of 128 characters. * For indexable
* attribute, the key must match the pattern: `a-zA-Z0-9*`. For example, `key0LikeThis` or
* `KEY_1_LIKE_THIS`. * For text attributes, at most 400 values are allowed. Empty values are not
* allowed. Each value must be a non-empty UTF-8 encoded string with a length limit of 256
* characters. * For number attributes, at most 400 values are allowed.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.Map<String, GoogleCloudRetailV2CustomAttribute> attributes;
static {
// hack to force ProGuard to consider GoogleCloudRetailV2CustomAttribute used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(GoogleCloudRetailV2CustomAttribute.class);
}
/**
* The target group associated with a given audience (e.g. male, veterans, car owners, musicians,
* etc.) of the product.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GoogleCloudRetailV2Audience audience;
/**
* The online availability of the Product. Default to Availability.IN_STOCK. Corresponding
* properties: Google Merchant Center property
* [availability](https://support.google.com/merchants/answer/6324448). Schema.org property
* [Offer.availability](https://schema.org/availability).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String availability;
/**
* The available quantity of the item.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer availableQuantity;
/**
* The timestamp when this Product becomes available for SearchService.Search.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String availableTime;
/**
* The brands of the product. A maximum of 30 brands are allowed. Each brand must be a UTF-8
* encoded string with a length limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is
* returned. Corresponding properties: Google Merchant Center property
* [brand](https://support.google.com/merchants/answer/6324351). Schema.org property
* [Product.brand](https://schema.org/brand).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> brands;
/**
* Product categories. This field is repeated for supporting one product belonging to several
* parallel categories. Strongly recommended using the full path for better search /
* recommendation quality. To represent full path of category, use '>' sign to separate different
* hierarchies. If '>' is part of the category name, please replace it with other character(s).
* For example, if a shoes product belongs to both ["Shoes & Accessories" -> "Shoes"] and ["Sports
* & Fitness" -> "Athletic Clothing" -> "Shoes"], it could be represented as: "categories": [
* "Shoes & Accessories > Shoes", "Sports & Fitness > Athletic Clothing > Shoes" ] Must be set for
* Type.PRIMARY Product otherwise an INVALID_ARGUMENT error is returned. At most 250 values are
* allowed per Product. Empty values are not allowed. Each value must be a UTF-8 encoded string
* with a length limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is returned.
* Corresponding properties: Google Merchant Center property google_product_category. Schema.org
* property [Product.category] (https://schema.org/category). [mc_google_product_category]:
* https://support.google.com/merchants/answer/6324436
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> categories;
/**
* The id of the collection members when type is Type.COLLECTION. Non-existent product ids are
* allowed. The type of the members must be either Type.PRIMARY or Type.VARIANT otherwise and
* INVALID_ARGUMENT error is thrown. Should not set it for other types. A maximum of 1000 values
* are allowed. Otherwise, an INVALID_ARGUMENT error is return.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> collectionMemberIds;
/**
* The color of the product. Corresponding properties: Google Merchant Center property
* [color](https://support.google.com/merchants/answer/6324487). Schema.org property
* [Product.color](https://schema.org/color).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GoogleCloudRetailV2ColorInfo colorInfo;
/**
* The condition of the product. Strongly encouraged to use the standard values: "new",
* "refurbished", "used". A maximum of 1 value is allowed per Product. Each value must be a UTF-8
* encoded string with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is
* returned. Corresponding properties: Google Merchant Center property
* [condition](https://support.google.com/merchants/answer/6324469). Schema.org property
* [Offer.itemCondition](https://schema.org/itemCondition).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> conditions;
/**
* Product description. This field must be a UTF-8 encoded string with a length limit of 5,000
* characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google
* Merchant Center property [description](https://support.google.com/merchants/answer/6324468).
* Schema.org property [Product.description](https://schema.org/description).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String description;
/**
* The timestamp when this product becomes unavailable for SearchService.Search. If it is set, the
* Product is not available for SearchService.Search after expire_time. However, the product can
* still be retrieved by ProductService.GetProduct and ProductService.ListProducts. expire_time
* must be later than available_time and publish_time, otherwise an INVALID_ARGUMENT error is
* thrown. Corresponding properties: Google Merchant Center property
* [expiration_date](https://support.google.com/merchants/answer/6324499).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String expireTime;
/**
* Fulfillment information, such as the store IDs for in-store pickup or region IDs for different
* shipping methods. All the elements must have distinct FulfillmentInfo.type. Otherwise, an
* INVALID_ARGUMENT error is returned.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GoogleCloudRetailV2FulfillmentInfo> fulfillmentInfo;
static {
// hack to force ProGuard to consider GoogleCloudRetailV2FulfillmentInfo used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(GoogleCloudRetailV2FulfillmentInfo.class);
}
/**
* The Global Trade Item Number (GTIN) of the product. This field must be a UTF-8 encoded string
* with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned. This
* field must be a Unigram. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding
* properties: Google Merchant Center property
* [gtin](https://support.google.com/merchants/answer/6324461). Schema.org property
* [Product.isbn](https://schema.org/isbn), [Product.gtin8](https://schema.org/gtin8),
* [Product.gtin12](https://schema.org/gtin12), [Product.gtin13](https://schema.org/gtin13), or
* [Product.gtin14](https://schema.org/gtin14). If the value is not a valid GTIN, an
* INVALID_ARGUMENT error is returned.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String gtin;
/**
* Immutable. Product identifier, which is the final component of name. For example, this field is
* "id_1", if name is
* `projects/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1`.
* This field must be a UTF-8 encoded string with a length limit of 128 characters. Otherwise, an
* INVALID_ARGUMENT error is returned. Corresponding properties: Google Merchant Center property
* [id](https://support.google.com/merchants/answer/6324405). Schema.org property
* [Product.sku](https://schema.org/sku).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String id;
/**
* Product images for the product.Highly recommended to put the main image to the first. A maximum
* of 300 images are allowed. Corresponding properties: Google Merchant Center property
* [image_link](https://support.google.com/merchants/answer/6324350). Schema.org property
* [Product.image](https://schema.org/image).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GoogleCloudRetailV2Image> images;
static {
// hack to force ProGuard to consider GoogleCloudRetailV2Image used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(GoogleCloudRetailV2Image.class);
}
/**
* Language of the title/description and other string attributes. Use language tags defined by
* [BCP 47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt). For product prediction, this field is
* ignored and the model automatically detects the text language. The Product can include text in
* different languages, but duplicating Products to provide text in multiple languages can result
* in degraded model performance. For product search this field is in use. It defaults to "en-US"
* if unset.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String languageCode;
/**
* The material of the product. For example, "leather", "wooden". A maximum of 20 values are
* allowed. Each value must be a UTF-8 encoded string with a length limit of 200 characters.
* Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google Merchant
* Center property [material](https://support.google.com/merchants/answer/6324410). Schema.org
* property [Product.material](https://schema.org/material).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> materials;
/**
* Immutable. Full resource name of the product, such as `projects/locations/global/catalogs/defau
* lt_catalog/branches/default_branch/products/product_id`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* The pattern or graphic print of the product. For example, "striped", "polka dot", "paisley". A
* maximum of 20 values are allowed per Product. Each value must be a UTF-8 encoded string with a
* length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding
* properties: Google Merchant Center property
* [pattern](https://support.google.com/merchants/answer/6324483). Schema.org property
* [Product.pattern](https://schema.org/pattern).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> patterns;
/**
* Product price and cost information. Corresponding properties: Google Merchant Center property
* [price](https://support.google.com/merchants/answer/6324371).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GoogleCloudRetailV2PriceInfo priceInfo;
/**
* Variant group identifier. Must be an id, with the same parent branch with this product.
* Otherwise, an error is thrown. For Type.PRIMARY Products, this field can only be empty or set
* to the same value as id. For VARIANT Products, this field cannot be empty. A maximum of 2,000
* products are allowed to share the same Type.PRIMARY Product. Otherwise, an INVALID_ARGUMENT
* error is returned. Corresponding properties: Google Merchant Center property
* [item_group_id](https://support.google.com/merchants/answer/6324507). Schema.org property
* [Product.inProductGroupWithID](https://schema.org/inProductGroupWithID).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String primaryProductId;
/**
* The promotions applied to the product. A maximum of 10 values are allowed per Product. Only
* Promotion.promotion_id will be used, other fields will be ignored if set.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GoogleCloudRetailV2Promotion> promotions;
/**
* The timestamp when the product is published by the retailer for the first time, which indicates
* the freshness of the products. Note that this field is different from available_time, given it
* purely describes product freshness regardless of when it is available on search and
* recommendation.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String publishTime;
/**
* The rating of this product.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GoogleCloudRetailV2Rating rating;
/**
* Indicates which fields in the Products are returned in SearchResponse. Supported fields for all
* types: * audience * availability * brands * color_info * conditions * gtin * materials * name *
* patterns * price_info * rating * sizes * title * uri Supported fields only for Type.PRIMARY and
* Type.COLLECTION: * categories * description * images Supported fields only for Type.VARIANT: *
* Only the first image in images To mark attributes as retrievable, include paths of the form
* "attributes.key" where "key" is the key of a custom attribute, as specified in attributes. For
* Type.PRIMARY and Type.COLLECTION, the following fields are always returned in SearchResponse by
* default: * name For Type.VARIANT, the following fields are always returned in by default: *
* name * color_info Maximum number of paths is 30. Otherwise, an INVALID_ARGUMENT error is
* returned. Note: Returning more fields in SearchResponse may increase response payload size and
* serving latency.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String retrievableFields;
/**
* The size of the product. To represent different size systems or size types, consider using this
* format: [[[size_system:]size_type:]size_value]. For example, in "US:MENS:M", "US" represents
* size system; "MENS" represents size type; "M" represents size value. In "GIRLS:27", size system
* is empty; "GIRLS" represents size type; "27" represents size value. In "32 inches", both size
* system and size type are empty, while size value is "32 inches". A maximum of 20 values are
* allowed per Product. Each value must be a UTF-8 encoded string with a length limit of 128
* characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google
* Merchant Center property [size](https://support.google.com/merchants/answer/6324492),
* [size_type](https://support.google.com/merchants/answer/6324497), and
* [size_system](https://support.google.com/merchants/answer/6324502). Schema.org property
* [Product.size](https://schema.org/size).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> sizes;
/**
* Custom tags associated with the product. At most 250 values are allowed per Product. This value
* must be a UTF-8 encoded string with a length limit of 1,000 characters. Otherwise, an
* INVALID_ARGUMENT error is returned. This tag can be used for filtering recommendation results
* by passing the tag as part of the PredictRequest.filter. Corresponding properties: Google
* Merchant Center property
* [custom_label_0–4](https://support.google.com/merchants/answer/6324473).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> tags;
/**
* Required. Product title. This field must be a UTF-8 encoded string with a length limit of 1,000
* characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google
* Merchant Center property [title](https://support.google.com/merchants/answer/6324415).
* Schema.org property [Product.name](https://schema.org/name).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String title;
/**
* Input only. The TTL (time to live) of the product. If it is set, it must be a non-negative
* value, and expire_time is set as current timestamp plus ttl. The derived expire_time is
* returned in the output and ttl is left blank when retrieving the Product. If it is set, the
* product is not available for SearchService.Search after current timestamp plus ttl. However,
* the product can still be retrieved by ProductService.GetProduct and
* ProductService.ListProducts.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String ttl;
/**
* Immutable. The type of the product. Default to
* Catalog.product_level_config.ingestion_product_type if unset.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String type;
/**
* Canonical URL directly linking to the product detail page. It is strongly recommended to
* provide a valid uri for the product, otherwise the service performance could be significantly
* degraded. This field must be a UTF-8 encoded string with a length limit of 5,000 characters.
* Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google Merchant
* Center property [link](https://support.google.com/merchants/answer/6324416). Schema.org
* property [Offer.url](https://schema.org/url).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String uri;
/**
* Output only. Product variants grouped together on primary product which share similar product
* attributes. It's automatically grouped by primary_product_id for all the product variants. Only
* populated for Type.PRIMARY Products. Note: This field is OUTPUT_ONLY for
* ProductService.GetProduct. Do not set this field in API requests.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GoogleCloudRetailV2Product> variants;
/**
* Highly encouraged. Extra product attributes to be included. For example, for products, this
* could include the store name, vendor, style, color, etc. These are very strong signals for
* recommendation model, thus we highly recommend providing the attributes here. Features that can
* take on one of a limited number of possible values. Two types of features can be set are:
* Textual features. some examples would be the brand/maker of a product, or country of a
* customer. Numerical features. Some examples would be the height/weight of a product, or age of
* a customer. For example: `{ "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm":
* {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }`. This field needs to pass all
* below criteria, otherwise an INVALID_ARGUMENT error is returned: * Max entries count: 200. *
* The key must be a UTF-8 encoded string with a length limit of 128 characters. * For indexable
* attribute, the key must match the pattern: `a-zA-Z0-9*`. For example, `key0LikeThis` or
* `KEY_1_LIKE_THIS`. * For text attributes, at most 400 values are allowed. Empty values are not
* allowed. Each value must be a non-empty UTF-8 encoded string with a length limit of 256
* characters. * For number attributes, at most 400 values are allowed.
* @return value or {@code null} for none
*/
public java.util.Map<String, GoogleCloudRetailV2CustomAttribute> getAttributes() {
return attributes;
}
/**
* Highly encouraged. Extra product attributes to be included. For example, for products, this
* could include the store name, vendor, style, color, etc. These are very strong signals for
* recommendation model, thus we highly recommend providing the attributes here. Features that can
* take on one of a limited number of possible values. Two types of features can be set are:
* Textual features. some examples would be the brand/maker of a product, or country of a
* customer. Numerical features. Some examples would be the height/weight of a product, or age of
* a customer. For example: `{ "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm":
* {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }`. This field needs to pass all
* below criteria, otherwise an INVALID_ARGUMENT error is returned: * Max entries count: 200. *
* The key must be a UTF-8 encoded string with a length limit of 128 characters. * For indexable
* attribute, the key must match the pattern: `a-zA-Z0-9*`. For example, `key0LikeThis` or
* `KEY_1_LIKE_THIS`. * For text attributes, at most 400 values are allowed. Empty values are not
* allowed. Each value must be a non-empty UTF-8 encoded string with a length limit of 256
* characters. * For number attributes, at most 400 values are allowed.
* @param attributes attributes or {@code null} for none
*/
public GoogleCloudRetailV2Product setAttributes(java.util.Map<String, GoogleCloudRetailV2CustomAttribute> attributes) {
this.attributes = attributes;
return this;
}
/**
* The target group associated with a given audience (e.g. male, veterans, car owners, musicians,
* etc.) of the product.
* @return value or {@code null} for none
*/
public GoogleCloudRetailV2Audience getAudience() {
return audience;
}
/**
* The target group associated with a given audience (e.g. male, veterans, car owners, musicians,
* etc.) of the product.
* @param audience audience or {@code null} for none
*/
public GoogleCloudRetailV2Product setAudience(GoogleCloudRetailV2Audience audience) {
this.audience = audience;
return this;
}
/**
* The online availability of the Product. Default to Availability.IN_STOCK. Corresponding
* properties: Google Merchant Center property
* [availability](https://support.google.com/merchants/answer/6324448). Schema.org property
* [Offer.availability](https://schema.org/availability).
* @return value or {@code null} for none
*/
public java.lang.String getAvailability() {
return availability;
}
/**
* The online availability of the Product. Default to Availability.IN_STOCK. Corresponding
* properties: Google Merchant Center property
* [availability](https://support.google.com/merchants/answer/6324448). Schema.org property
* [Offer.availability](https://schema.org/availability).
* @param availability availability or {@code null} for none
*/
public GoogleCloudRetailV2Product setAvailability(java.lang.String availability) {
this.availability = availability;
return this;
}
/**
* The available quantity of the item.
* @return value or {@code null} for none
*/
public java.lang.Integer getAvailableQuantity() {
return availableQuantity;
}
/**
* The available quantity of the item.
* @param availableQuantity availableQuantity or {@code null} for none
*/
public GoogleCloudRetailV2Product setAvailableQuantity(java.lang.Integer availableQuantity) {
this.availableQuantity = availableQuantity;
return this;
}
/**
* The timestamp when this Product becomes available for SearchService.Search.
* @return value or {@code null} for none
*/
public String getAvailableTime() {
return availableTime;
}
/**
* The timestamp when this Product becomes available for SearchService.Search.
* @param availableTime availableTime or {@code null} for none
*/
public GoogleCloudRetailV2Product setAvailableTime(String availableTime) {
this.availableTime = availableTime;
return this;
}
/**
* The brands of the product. A maximum of 30 brands are allowed. Each brand must be a UTF-8
* encoded string with a length limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is
* returned. Corresponding properties: Google Merchant Center property
* [brand](https://support.google.com/merchants/answer/6324351). Schema.org property
* [Product.brand](https://schema.org/brand).
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getBrands() {
return brands;
}
/**
* The brands of the product. A maximum of 30 brands are allowed. Each brand must be a UTF-8
* encoded string with a length limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is
* returned. Corresponding properties: Google Merchant Center property
* [brand](https://support.google.com/merchants/answer/6324351). Schema.org property
* [Product.brand](https://schema.org/brand).
* @param brands brands or {@code null} for none
*/
public GoogleCloudRetailV2Product setBrands(java.util.List<java.lang.String> brands) {
this.brands = brands;
return this;
}
/**
* Product categories. This field is repeated for supporting one product belonging to several
* parallel categories. Strongly recommended using the full path for better search /
* recommendation quality. To represent full path of category, use '>' sign to separate different
* hierarchies. If '>' is part of the category name, please replace it with other character(s).
* For example, if a shoes product belongs to both ["Shoes & Accessories" -> "Shoes"] and ["Sports
* & Fitness" -> "Athletic Clothing" -> "Shoes"], it could be represented as: "categories": [
* "Shoes & Accessories > Shoes", "Sports & Fitness > Athletic Clothing > Shoes" ] Must be set for
* Type.PRIMARY Product otherwise an INVALID_ARGUMENT error is returned. At most 250 values are
* allowed per Product. Empty values are not allowed. Each value must be a UTF-8 encoded string
* with a length limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is returned.
* Corresponding properties: Google Merchant Center property google_product_category. Schema.org
* property [Product.category] (https://schema.org/category). [mc_google_product_category]:
* https://support.google.com/merchants/answer/6324436
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getCategories() {
return categories;
}
/**
* Product categories. This field is repeated for supporting one product belonging to several
* parallel categories. Strongly recommended using the full path for better search /
* recommendation quality. To represent full path of category, use '>' sign to separate different
* hierarchies. If '>' is part of the category name, please replace it with other character(s).
* For example, if a shoes product belongs to both ["Shoes & Accessories" -> "Shoes"] and ["Sports
* & Fitness" -> "Athletic Clothing" -> "Shoes"], it could be represented as: "categories": [
* "Shoes & Accessories > Shoes", "Sports & Fitness > Athletic Clothing > Shoes" ] Must be set for
* Type.PRIMARY Product otherwise an INVALID_ARGUMENT error is returned. At most 250 values are
* allowed per Product. Empty values are not allowed. Each value must be a UTF-8 encoded string
* with a length limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is returned.
* Corresponding properties: Google Merchant Center property google_product_category. Schema.org
* property [Product.category] (https://schema.org/category). [mc_google_product_category]:
* https://support.google.com/merchants/answer/6324436
* @param categories categories or {@code null} for none
*/
public GoogleCloudRetailV2Product setCategories(java.util.List<java.lang.String> categories) {
this.categories = categories;
return this;
}
/**
* The id of the collection members when type is Type.COLLECTION. Non-existent product ids are
* allowed. The type of the members must be either Type.PRIMARY or Type.VARIANT otherwise and
* INVALID_ARGUMENT error is thrown. Should not set it for other types. A maximum of 1000 values
* are allowed. Otherwise, an INVALID_ARGUMENT error is return.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getCollectionMemberIds() {
return collectionMemberIds;
}
/**
* The id of the collection members when type is Type.COLLECTION. Non-existent product ids are
* allowed. The type of the members must be either Type.PRIMARY or Type.VARIANT otherwise and
* INVALID_ARGUMENT error is thrown. Should not set it for other types. A maximum of 1000 values
* are allowed. Otherwise, an INVALID_ARGUMENT error is return.
* @param collectionMemberIds collectionMemberIds or {@code null} for none
*/
public GoogleCloudRetailV2Product setCollectionMemberIds(java.util.List<java.lang.String> collectionMemberIds) {
this.collectionMemberIds = collectionMemberIds;
return this;
}
/**
* The color of the product. Corresponding properties: Google Merchant Center property
* [color](https://support.google.com/merchants/answer/6324487). Schema.org property
* [Product.color](https://schema.org/color).
* @return value or {@code null} for none
*/
public GoogleCloudRetailV2ColorInfo getColorInfo() {
return colorInfo;
}
/**
* The color of the product. Corresponding properties: Google Merchant Center property
* [color](https://support.google.com/merchants/answer/6324487). Schema.org property
* [Product.color](https://schema.org/color).
* @param colorInfo colorInfo or {@code null} for none
*/
public GoogleCloudRetailV2Product setColorInfo(GoogleCloudRetailV2ColorInfo colorInfo) {
this.colorInfo = colorInfo;
return this;
}
/**
* The condition of the product. Strongly encouraged to use the standard values: "new",
* "refurbished", "used". A maximum of 1 value is allowed per Product. Each value must be a UTF-8
* encoded string with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is
* returned. Corresponding properties: Google Merchant Center property
* [condition](https://support.google.com/merchants/answer/6324469). Schema.org property
* [Offer.itemCondition](https://schema.org/itemCondition).
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getConditions() {
return conditions;
}
/**
* The condition of the product. Strongly encouraged to use the standard values: "new",
* "refurbished", "used". A maximum of 1 value is allowed per Product. Each value must be a UTF-8
* encoded string with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is
* returned. Corresponding properties: Google Merchant Center property
* [condition](https://support.google.com/merchants/answer/6324469). Schema.org property
* [Offer.itemCondition](https://schema.org/itemCondition).
* @param conditions conditions or {@code null} for none
*/
public GoogleCloudRetailV2Product setConditions(java.util.List<java.lang.String> conditions) {
this.conditions = conditions;
return this;
}
/**
* Product description. This field must be a UTF-8 encoded string with a length limit of 5,000
* characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google
* Merchant Center property [description](https://support.google.com/merchants/answer/6324468).
* Schema.org property [Product.description](https://schema.org/description).
* @return value or {@code null} for none
*/
public java.lang.String getDescription() {
return description;
}
/**
* Product description. This field must be a UTF-8 encoded string with a length limit of 5,000
* characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google
* Merchant Center property [description](https://support.google.com/merchants/answer/6324468).
* Schema.org property [Product.description](https://schema.org/description).
* @param description description or {@code null} for none
*/
public GoogleCloudRetailV2Product setDescription(java.lang.String description) {
this.description = description;
return this;
}
/**
* The timestamp when this product becomes unavailable for SearchService.Search. If it is set, the
* Product is not available for SearchService.Search after expire_time. However, the product can
* still be retrieved by ProductService.GetProduct and ProductService.ListProducts. expire_time
* must be later than available_time and publish_time, otherwise an INVALID_ARGUMENT error is
* thrown. Corresponding properties: Google Merchant Center property
* [expiration_date](https://support.google.com/merchants/answer/6324499).
* @return value or {@code null} for none
*/
public String getExpireTime() {
return expireTime;
}
/**
* The timestamp when this product becomes unavailable for SearchService.Search. If it is set, the
* Product is not available for SearchService.Search after expire_time. However, the product can
* still be retrieved by ProductService.GetProduct and ProductService.ListProducts. expire_time
* must be later than available_time and publish_time, otherwise an INVALID_ARGUMENT error is
* thrown. Corresponding properties: Google Merchant Center property
* [expiration_date](https://support.google.com/merchants/answer/6324499).
* @param expireTime expireTime or {@code null} for none
*/
public GoogleCloudRetailV2Product setExpireTime(String expireTime) {
this.expireTime = expireTime;
return this;
}
/**
* Fulfillment information, such as the store IDs for in-store pickup or region IDs for different
* shipping methods. All the elements must have distinct FulfillmentInfo.type. Otherwise, an
* INVALID_ARGUMENT error is returned.
* @return value or {@code null} for none
*/
public java.util.List<GoogleCloudRetailV2FulfillmentInfo> getFulfillmentInfo() {
return fulfillmentInfo;
}
/**
* Fulfillment information, such as the store IDs for in-store pickup or region IDs for different
* shipping methods. All the elements must have distinct FulfillmentInfo.type. Otherwise, an
* INVALID_ARGUMENT error is returned.
* @param fulfillmentInfo fulfillmentInfo or {@code null} for none
*/
public GoogleCloudRetailV2Product setFulfillmentInfo(java.util.List<GoogleCloudRetailV2FulfillmentInfo> fulfillmentInfo) {
this.fulfillmentInfo = fulfillmentInfo;
return this;
}
/**
* The Global Trade Item Number (GTIN) of the product. This field must be a UTF-8 encoded string
* with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned. This
* field must be a Unigram. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding
* properties: Google Merchant Center property
* [gtin](https://support.google.com/merchants/answer/6324461). Schema.org property
* [Product.isbn](https://schema.org/isbn), [Product.gtin8](https://schema.org/gtin8),
* [Product.gtin12](https://schema.org/gtin12), [Product.gtin13](https://schema.org/gtin13), or
* [Product.gtin14](https://schema.org/gtin14). If the value is not a valid GTIN, an
* INVALID_ARGUMENT error is returned.
* @return value or {@code null} for none
*/
public java.lang.String getGtin() {
return gtin;
}
/**
* The Global Trade Item Number (GTIN) of the product. This field must be a UTF-8 encoded string
* with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned. This
* field must be a Unigram. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding
* properties: Google Merchant Center property
* [gtin](https://support.google.com/merchants/answer/6324461). Schema.org property
* [Product.isbn](https://schema.org/isbn), [Product.gtin8](https://schema.org/gtin8),
* [Product.gtin12](https://schema.org/gtin12), [Product.gtin13](https://schema.org/gtin13), or
* [Product.gtin14](https://schema.org/gtin14). If the value is not a valid GTIN, an
* INVALID_ARGUMENT error is returned.
* @param gtin gtin or {@code null} for none
*/
public GoogleCloudRetailV2Product setGtin(java.lang.String gtin) {
this.gtin = gtin;
return this;
}
/**
* Immutable. Product identifier, which is the final component of name. For example, this field is
* "id_1", if name is
* `projects/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1`.
* This field must be a UTF-8 encoded string with a length limit of 128 characters. Otherwise, an
* INVALID_ARGUMENT error is returned. Corresponding properties: Google Merchant Center property
* [id](https://support.google.com/merchants/answer/6324405). Schema.org property
* [Product.sku](https://schema.org/sku).
* @return value or {@code null} for none
*/
public java.lang.String getId() {
return id;
}
/**
* Immutable. Product identifier, which is the final component of name. For example, this field is
* "id_1", if name is
* `projects/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1`.
* This field must be a UTF-8 encoded string with a length limit of 128 characters. Otherwise, an
* INVALID_ARGUMENT error is returned. Corresponding properties: Google Merchant Center property
* [id](https://support.google.com/merchants/answer/6324405). Schema.org property
* [Product.sku](https://schema.org/sku).
* @param id id or {@code null} for none
*/
public GoogleCloudRetailV2Product setId(java.lang.String id) {
this.id = id;
return this;
}
/**
* Product images for the product.Highly recommended to put the main image to the first. A maximum
* of 300 images are allowed. Corresponding properties: Google Merchant Center property
* [image_link](https://support.google.com/merchants/answer/6324350). Schema.org property
* [Product.image](https://schema.org/image).
* @return value or {@code null} for none
*/
public java.util.List<GoogleCloudRetailV2Image> getImages() {
return images;
}
/**
* Product images for the product.Highly recommended to put the main image to the first. A maximum
* of 300 images are allowed. Corresponding properties: Google Merchant Center property
* [image_link](https://support.google.com/merchants/answer/6324350). Schema.org property
* [Product.image](https://schema.org/image).
* @param images images or {@code null} for none
*/
public GoogleCloudRetailV2Product setImages(java.util.List<GoogleCloudRetailV2Image> images) {
this.images = images;
return this;
}
/**
* Language of the title/description and other string attributes. Use language tags defined by
* [BCP 47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt). For product prediction, this field is
* ignored and the model automatically detects the text language. The Product can include text in
* different languages, but duplicating Products to provide text in multiple languages can result
* in degraded model performance. For product search this field is in use. It defaults to "en-US"
* if unset.
* @return value or {@code null} for none
*/
public java.lang.String getLanguageCode() {
return languageCode;
}
/**
* Language of the title/description and other string attributes. Use language tags defined by
* [BCP 47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt). For product prediction, this field is
* ignored and the model automatically detects the text language. The Product can include text in
* different languages, but duplicating Products to provide text in multiple languages can result
* in degraded model performance. For product search this field is in use. It defaults to "en-US"
* if unset.
* @param languageCode languageCode or {@code null} for none
*/
public GoogleCloudRetailV2Product setLanguageCode(java.lang.String languageCode) {
this.languageCode = languageCode;
return this;
}
/**
* The material of the product. For example, "leather", "wooden". A maximum of 20 values are
* allowed. Each value must be a UTF-8 encoded string with a length limit of 200 characters.
* Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google Merchant
* Center property [material](https://support.google.com/merchants/answer/6324410). Schema.org
* property [Product.material](https://schema.org/material).
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getMaterials() {
return materials;
}
/**
* The material of the product. For example, "leather", "wooden". A maximum of 20 values are
* allowed. Each value must be a UTF-8 encoded string with a length limit of 200 characters.
* Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google Merchant
* Center property [material](https://support.google.com/merchants/answer/6324410). Schema.org
* property [Product.material](https://schema.org/material).
* @param materials materials or {@code null} for none
*/
public GoogleCloudRetailV2Product setMaterials(java.util.List<java.lang.String> materials) {
this.materials = materials;
return this;
}
/**
* Immutable. Full resource name of the product, such as `projects/locations/global/catalogs/defau
* lt_catalog/branches/default_branch/products/product_id`.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Immutable. Full resource name of the product, such as `projects/locations/global/catalogs/defau
* lt_catalog/branches/default_branch/products/product_id`.
* @param name name or {@code null} for none
*/
public GoogleCloudRetailV2Product setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* The pattern or graphic print of the product. For example, "striped", "polka dot", "paisley". A
* maximum of 20 values are allowed per Product. Each value must be a UTF-8 encoded string with a
* length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding
* properties: Google Merchant Center property
* [pattern](https://support.google.com/merchants/answer/6324483). Schema.org property
* [Product.pattern](https://schema.org/pattern).
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getPatterns() {
return patterns;
}
/**
* The pattern or graphic print of the product. For example, "striped", "polka dot", "paisley". A
* maximum of 20 values are allowed per Product. Each value must be a UTF-8 encoded string with a
* length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding
* properties: Google Merchant Center property
* [pattern](https://support.google.com/merchants/answer/6324483). Schema.org property
* [Product.pattern](https://schema.org/pattern).
* @param patterns patterns or {@code null} for none
*/
public GoogleCloudRetailV2Product setPatterns(java.util.List<java.lang.String> patterns) {
this.patterns = patterns;
return this;
}
/**
* Product price and cost information. Corresponding properties: Google Merchant Center property
* [price](https://support.google.com/merchants/answer/6324371).
* @return value or {@code null} for none
*/
public GoogleCloudRetailV2PriceInfo getPriceInfo() {
return priceInfo;
}
/**
* Product price and cost information. Corresponding properties: Google Merchant Center property
* [price](https://support.google.com/merchants/answer/6324371).
* @param priceInfo priceInfo or {@code null} for none
*/
public GoogleCloudRetailV2Product setPriceInfo(GoogleCloudRetailV2PriceInfo priceInfo) {
this.priceInfo = priceInfo;
return this;
}
/**
* Variant group identifier. Must be an id, with the same parent branch with this product.
* Otherwise, an error is thrown. For Type.PRIMARY Products, this field can only be empty or set
* to the same value as id. For VARIANT Products, this field cannot be empty. A maximum of 2,000
* products are allowed to share the same Type.PRIMARY Product. Otherwise, an INVALID_ARGUMENT
* error is returned. Corresponding properties: Google Merchant Center property
* [item_group_id](https://support.google.com/merchants/answer/6324507). Schema.org property
* [Product.inProductGroupWithID](https://schema.org/inProductGroupWithID).
* @return value or {@code null} for none
*/
public java.lang.String getPrimaryProductId() {
return primaryProductId;
}
/**
* Variant group identifier. Must be an id, with the same parent branch with this product.
* Otherwise, an error is thrown. For Type.PRIMARY Products, this field can only be empty or set
* to the same value as id. For VARIANT Products, this field cannot be empty. A maximum of 2,000
* products are allowed to share the same Type.PRIMARY Product. Otherwise, an INVALID_ARGUMENT
* error is returned. Corresponding properties: Google Merchant Center property
* [item_group_id](https://support.google.com/merchants/answer/6324507). Schema.org property
* [Product.inProductGroupWithID](https://schema.org/inProductGroupWithID).
* @param primaryProductId primaryProductId or {@code null} for none
*/
public GoogleCloudRetailV2Product setPrimaryProductId(java.lang.String primaryProductId) {
this.primaryProductId = primaryProductId;
return this;
}
/**
* The promotions applied to the product. A maximum of 10 values are allowed per Product. Only
* Promotion.promotion_id will be used, other fields will be ignored if set.
* @return value or {@code null} for none
*/
public java.util.List<GoogleCloudRetailV2Promotion> getPromotions() {
return promotions;
}
/**
* The promotions applied to the product. A maximum of 10 values are allowed per Product. Only
* Promotion.promotion_id will be used, other fields will be ignored if set.
* @param promotions promotions or {@code null} for none
*/
public GoogleCloudRetailV2Product setPromotions(java.util.List<GoogleCloudRetailV2Promotion> promotions) {
this.promotions = promotions;
return this;
}
/**
* The timestamp when the product is published by the retailer for the first time, which indicates
* the freshness of the products. Note that this field is different from available_time, given it
* purely describes product freshness regardless of when it is available on search and
* recommendation.
* @return value or {@code null} for none
*/
public String getPublishTime() {
return publishTime;
}
/**
* The timestamp when the product is published by the retailer for the first time, which indicates
* the freshness of the products. Note that this field is different from available_time, given it
* purely describes product freshness regardless of when it is available on search and
* recommendation.
* @param publishTime publishTime or {@code null} for none
*/
public GoogleCloudRetailV2Product setPublishTime(String publishTime) {
this.publishTime = publishTime;
return this;
}
/**
* The rating of this product.
* @return value or {@code null} for none
*/
public GoogleCloudRetailV2Rating getRating() {
return rating;
}
/**
* The rating of this product.
* @param rating rating or {@code null} for none
*/
public GoogleCloudRetailV2Product setRating(GoogleCloudRetailV2Rating rating) {
this.rating = rating;
return this;
}
/**
* Indicates which fields in the Products are returned in SearchResponse. Supported fields for all
* types: * audience * availability * brands * color_info * conditions * gtin * materials * name *
* patterns * price_info * rating * sizes * title * uri Supported fields only for Type.PRIMARY and
* Type.COLLECTION: * categories * description * images Supported fields only for Type.VARIANT: *
* Only the first image in images To mark attributes as retrievable, include paths of the form
* "attributes.key" where "key" is the key of a custom attribute, as specified in attributes. For
* Type.PRIMARY and Type.COLLECTION, the following fields are always returned in SearchResponse by
* default: * name For Type.VARIANT, the following fields are always returned in by default: *
* name * color_info Maximum number of paths is 30. Otherwise, an INVALID_ARGUMENT error is
* returned. Note: Returning more fields in SearchResponse may increase response payload size and
* serving latency.
* @return value or {@code null} for none
*/
public String getRetrievableFields() {
return retrievableFields;
}
/**
* Indicates which fields in the Products are returned in SearchResponse. Supported fields for all
* types: * audience * availability * brands * color_info * conditions * gtin * materials * name *
* patterns * price_info * rating * sizes * title * uri Supported fields only for Type.PRIMARY and
* Type.COLLECTION: * categories * description * images Supported fields only for Type.VARIANT: *
* Only the first image in images To mark attributes as retrievable, include paths of the form
* "attributes.key" where "key" is the key of a custom attribute, as specified in attributes. For
* Type.PRIMARY and Type.COLLECTION, the following fields are always returned in SearchResponse by
* default: * name For Type.VARIANT, the following fields are always returned in by default: *
* name * color_info Maximum number of paths is 30. Otherwise, an INVALID_ARGUMENT error is
* returned. Note: Returning more fields in SearchResponse may increase response payload size and
* serving latency.
* @param retrievableFields retrievableFields or {@code null} for none
*/
public GoogleCloudRetailV2Product setRetrievableFields(String retrievableFields) {
this.retrievableFields = retrievableFields;
return this;
}
/**
* The size of the product. To represent different size systems or size types, consider using this
* format: [[[size_system:]size_type:]size_value]. For example, in "US:MENS:M", "US" represents
* size system; "MENS" represents size type; "M" represents size value. In "GIRLS:27", size system
* is empty; "GIRLS" represents size type; "27" represents size value. In "32 inches", both size
* system and size type are empty, while size value is "32 inches". A maximum of 20 values are
* allowed per Product. Each value must be a UTF-8 encoded string with a length limit of 128
* characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google
* Merchant Center property [size](https://support.google.com/merchants/answer/6324492),
* [size_type](https://support.google.com/merchants/answer/6324497), and
* [size_system](https://support.google.com/merchants/answer/6324502). Schema.org property
* [Product.size](https://schema.org/size).
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getSizes() {
return sizes;
}
/**
* The size of the product. To represent different size systems or size types, consider using this
* format: [[[size_system:]size_type:]size_value]. For example, in "US:MENS:M", "US" represents
* size system; "MENS" represents size type; "M" represents size value. In "GIRLS:27", size system
* is empty; "GIRLS" represents size type; "27" represents size value. In "32 inches", both size
* system and size type are empty, while size value is "32 inches". A maximum of 20 values are
* allowed per Product. Each value must be a UTF-8 encoded string with a length limit of 128
* characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google
* Merchant Center property [size](https://support.google.com/merchants/answer/6324492),
* [size_type](https://support.google.com/merchants/answer/6324497), and
* [size_system](https://support.google.com/merchants/answer/6324502). Schema.org property
* [Product.size](https://schema.org/size).
* @param sizes sizes or {@code null} for none
*/
public GoogleCloudRetailV2Product setSizes(java.util.List<java.lang.String> sizes) {
this.sizes = sizes;
return this;
}
/**
* Custom tags associated with the product. At most 250 values are allowed per Product. This value
* must be a UTF-8 encoded string with a length limit of 1,000 characters. Otherwise, an
* INVALID_ARGUMENT error is returned. This tag can be used for filtering recommendation results
* by passing the tag as part of the PredictRequest.filter. Corresponding properties: Google
* Merchant Center property
* [custom_label_0–4](https://support.google.com/merchants/answer/6324473).
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getTags() {
return tags;
}
/**
* Custom tags associated with the product. At most 250 values are allowed per Product. This value
* must be a UTF-8 encoded string with a length limit of 1,000 characters. Otherwise, an
* INVALID_ARGUMENT error is returned. This tag can be used for filtering recommendation results
* by passing the tag as part of the PredictRequest.filter. Corresponding properties: Google
* Merchant Center property
* [custom_label_0–4](https://support.google.com/merchants/answer/6324473).
* @param tags tags or {@code null} for none
*/
public GoogleCloudRetailV2Product setTags(java.util.List<java.lang.String> tags) {
this.tags = tags;
return this;
}
/**
* Required. Product title. This field must be a UTF-8 encoded string with a length limit of 1,000
* characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google
* Merchant Center property [title](https://support.google.com/merchants/answer/6324415).
* Schema.org property [Product.name](https://schema.org/name).
* @return value or {@code null} for none
*/
public java.lang.String getTitle() {
return title;
}
/**
* Required. Product title. This field must be a UTF-8 encoded string with a length limit of 1,000
* characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google
* Merchant Center property [title](https://support.google.com/merchants/answer/6324415).
* Schema.org property [Product.name](https://schema.org/name).
* @param title title or {@code null} for none
*/
public GoogleCloudRetailV2Product setTitle(java.lang.String title) {
this.title = title;
return this;
}
/**
* Input only. The TTL (time to live) of the product. If it is set, it must be a non-negative
* value, and expire_time is set as current timestamp plus ttl. The derived expire_time is
* returned in the output and ttl is left blank when retrieving the Product. If it is set, the
* product is not available for SearchService.Search after current timestamp plus ttl. However,
* the product can still be retrieved by ProductService.GetProduct and
* ProductService.ListProducts.
* @return value or {@code null} for none
*/
public String getTtl() {
return ttl;
}
/**
* Input only. The TTL (time to live) of the product. If it is set, it must be a non-negative
* value, and expire_time is set as current timestamp plus ttl. The derived expire_time is
* returned in the output and ttl is left blank when retrieving the Product. If it is set, the
* product is not available for SearchService.Search after current timestamp plus ttl. However,
* the product can still be retrieved by ProductService.GetProduct and
* ProductService.ListProducts.
* @param ttl ttl or {@code null} for none
*/
public GoogleCloudRetailV2Product setTtl(String ttl) {
this.ttl = ttl;
return this;
}
/**
* Immutable. The type of the product. Default to
* Catalog.product_level_config.ingestion_product_type if unset.
* @return value or {@code null} for none
*/
public java.lang.String getType() {
return type;
}
/**
* Immutable. The type of the product. Default to
* Catalog.product_level_config.ingestion_product_type if unset.
* @param type type or {@code null} for none
*/
public GoogleCloudRetailV2Product setType(java.lang.String type) {
this.type = type;
return this;
}
/**
* Canonical URL directly linking to the product detail page. It is strongly recommended to
* provide a valid uri for the product, otherwise the service performance could be significantly
* degraded. This field must be a UTF-8 encoded string with a length limit of 5,000 characters.
* Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google Merchant
* Center property [link](https://support.google.com/merchants/answer/6324416). Schema.org
* property [Offer.url](https://schema.org/url).
* @return value or {@code null} for none
*/
public java.lang.String getUri() {
return uri;
}
/**
* Canonical URL directly linking to the product detail page. It is strongly recommended to
* provide a valid uri for the product, otherwise the service performance could be significantly
* degraded. This field must be a UTF-8 encoded string with a length limit of 5,000 characters.
* Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google Merchant
* Center property [link](https://support.google.com/merchants/answer/6324416). Schema.org
* property [Offer.url](https://schema.org/url).
* @param uri uri or {@code null} for none
*/
public GoogleCloudRetailV2Product setUri(java.lang.String uri) {
this.uri = uri;
return this;
}
/**
* Output only. Product variants grouped together on primary product which share similar product
* attributes. It's automatically grouped by primary_product_id for all the product variants. Only
* populated for Type.PRIMARY Products. Note: This field is OUTPUT_ONLY for
* ProductService.GetProduct. Do not set this field in API requests.
* @return value or {@code null} for none
*/
public java.util.List<GoogleCloudRetailV2Product> getVariants() {
return variants;
}
/**
* Output only. Product variants grouped together on primary product which share similar product
* attributes. It's automatically grouped by primary_product_id for all the product variants. Only
* populated for Type.PRIMARY Products. Note: This field is OUTPUT_ONLY for
* ProductService.GetProduct. Do not set this field in API requests.
* @param variants variants or {@code null} for none
*/
public GoogleCloudRetailV2Product setVariants(java.util.List<GoogleCloudRetailV2Product> variants) {
this.variants = variants;
return this;
}
@Override
public GoogleCloudRetailV2Product set(String fieldName, Object value) {
return (GoogleCloudRetailV2Product) super.set(fieldName, value);
}
@Override
public GoogleCloudRetailV2Product clone() {
return (GoogleCloudRetailV2Product) super.clone();
}
}
| googleapis/google-api-java-client-services | clients/google-api-services-retail/v2/1.31.0/com/google/api/services/retail/v2/model/GoogleCloudRetailV2Product.java | Java | apache-2.0 | 62,165 |
var httpManager = require("httpManager");
Alloy.Globals.isSearch = true;
if (OS_ANDROID) {
$.search.windowSoftInputMode = Ti.UI.Android.SOFT_INPUT_ADJUST_PAN;
}
var dataTitles = [
{
name : "Find Us",
view : "findUs"
},
{
name : "Deals",
view : "deals"
},
{
name : "Testimonials",
view : "testmonials"
},
{
name : "Loyalty",
view : "loyalty"
},
{
name : "Be Social",
view : "beSocial"
},
{
name : "Before & After",
view : "beforeAfter"
},
{
name : "About Us",
view : "aboutUs"
},
{
name : "Services for dermatology",
view : "services"
},
{
name : "Services for dental",
view : "services"
},
];
var data =[];
for (var i=0; i < dataTitles.length; i++) {
var row = Titanium.UI.createTableViewRow({
title:dataTitles[i].name,
color:'black',
height:50,
id : i,
});
data.push(row);
}
var search = Titanium.UI.createSearchBar({
barColor : '#DA308A',
showCancel : true,
height : 43,
top : 0,
});
search.addEventListener('cancel', function() {
search.blur();
});
var listView = Ti.UI.createListView({
searchView : search,
caseInsensitiveSearch : true,
backgroundColor:'white',
top :"60",
bottom :"60",
});
var listSection = Ti.UI.createListSection(
);
var data = [];
for (var i = 0; i < dataTitles.length; i++) {
data.push({
properties : {
title : dataTitles[i].name,
searchableText :dataTitles[i].name,
color :"black",
height : "40",
}
});
}
listSection.setItems(data);
listView.sections = [listSection];
listView.addEventListener('itemclick', function(e){
Alloy.createController(dataTitles[e.itemIndex].view).getView();
});
$.search.add(listView);
function logoutClicked (e)
{
httpManager.userLogout(function(response) {
if(response.success == 1)
{
Alloy.createController('login').getView();
$.search .close();
}
});
}
Ti.App.addEventListener('android:back', function() {
$.search.exitOnClose = true;
var myActivity = Ti.Android.currentActivity();
myActivity.finish();
});
Alloy.Globals.closeSearchWindow = function(){
$.search .close();
};
$.search.open();
| SrinivasReddy987/Lookswoow | app/controllers/search.js | JavaScript | apache-2.0 | 2,071 |
package com.ssh.sys.core.validation;
import com.ssh.common.util.Constant;
import com.ssh.sys.api.dto.UserDTO;
import com.ssh.sys.api.dto.extension.PermissionExtDTO;
import com.ssh.sys.api.service.PermissionService;
import com.ssh.sys.api.service.UserService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.support.AopUtils;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import javax.inject.Inject;
import java.util.List;
@ActiveProfiles(Constant.ENV_DEV)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({
"classpath:spring-validation.xml",
"classpath:spring-core-context.xml",
"classpath:sys-core-context.xml"
})
//@TransactionConfiguration(transactionManager = "transactionManager")
@Transactional(transactionManager = "transactionManager")
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ValidationTest {
private static final Logger LOGGER = LoggerFactory.getLogger(ValidationTest.class);
@Inject
private UserService userService;
@Inject
private PermissionService permissionService;
@Before
public void setUp() throws Exception {
Assert.assertNotNull(userService);
// 注意: 引进和不引进spring-validation.xml配置文件一下结果的区别
LOGGER.info("isAopProxy => {}", AopUtils.isAopProxy(userService));
LOGGER.info("isJdkDynamicProxy => {}", AopUtils.isJdkDynamicProxy(userService));
LOGGER.info("isCglibProxy => {}", AopUtils.isCglibProxy(userService));
}
@Test
@Rollback
public void test1Save() throws Exception {
UserDTO dto = new UserDTO();
dto.setCode("King");
dto.setName("King");
dto.setPass("King");
userService.add(dto);
}
@Test
public void test2GetList() throws Exception {
List<UserDTO> list = userService.getList(new UserDTO());
LOGGER.info("list => {}", list);
}
@Test
public void test3GetById() throws Exception {
PermissionExtDTO dto = permissionService.getById(11L);
LOGGER.info("=== {} ===", dto);
}
}
| lugavin/ssh | ssh-sys-core/src/test/java/com/ssh/sys/core/validation/ValidationTest.java | Java | apache-2.0 | 2,560 |
package firestream.chat.chat;
import androidx.annotation.Nullable;
import org.pmw.tinylog.Logger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import firestream.chat.events.ListData;
import firestream.chat.filter.Filter;
import firestream.chat.firebase.service.Path;
import firestream.chat.interfaces.IAbstractChat;
import firestream.chat.message.Sendable;
import firestream.chat.message.TypingState;
import firestream.chat.namespace.Fire;
import firestream.chat.types.SendableType;
import firestream.chat.types.TypingStateType;
import firestream.chat.util.TypingMap;
import io.reactivex.Completable;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Single;
import io.reactivex.SingleSource;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import sdk.guru.common.DisposableMap;
import sdk.guru.common.Event;
import sdk.guru.common.EventType;
import sdk.guru.common.Optional;
import sdk.guru.common.RX;
/**
* This class handles common elements of a conversation bit it 1-to-1 or group.
* Mainly sending and receiving messages.
*/
public abstract class AbstractChat implements IAbstractChat {
/**
* Store the disposables so we can dispose of all of them when the user logs out
*/
protected DisposableMap dm = new DisposableMap();
/**
* Event events
*/
protected Events events = new Events();
/**
* A list of all sendables received
*/
protected List<Sendable> sendables = new ArrayList<>();
protected TypingMap typingMap = new TypingMap();
/**
* Start listening to the current message reference and retrieve all messages
* @return a events of message results
*/
protected Observable<Event<Sendable>> messagesOn() {
return messagesOn(null);
}
/**
* Start listening to the current message reference and pass the messages to the events
* @param newerThan only listen for messages after this date
* @return a events of message results
*/
protected Observable<Event<Sendable>> messagesOn(Date newerThan) {
return Fire.internal().getFirebaseService().core.messagesOn(messagesPath(), newerThan).doOnNext(event -> {
Sendable sendable = event.get();
Sendable previous = getSendable(sendable.getId());
if (event.isAdded()) {
sendables.add(sendable);
}
if (previous != null) {
if (event.isModified()) {
sendable.copyTo(previous);
}
if (event.isRemoved()) {
sendables.remove(previous);
}
}
getSendableEvents().getSendables().accept(event);
}).doOnError(throwable -> {
events.publishThrowable().accept(throwable);
}).observeOn(RX.main());
}
/**
* Get a updateBatch of messages once
* @param fromDate get messages from this date
* @param toDate get messages until this date
* @param limit limit the maximum number of messages
* @return a events of message results
*/
protected Single<List<Sendable>> loadMoreMessages(@Nullable Date fromDate, @Nullable Date toDate, @Nullable Integer limit, boolean desc) {
return Fire.stream().getFirebaseService().core
.loadMoreMessages(messagesPath(), fromDate, toDate, limit)
.map(sendables -> {
Collections.sort(sendables, (s1, s2) -> {
if (desc) {
return s2.getDate().compareTo(s1.getDate());
} else {
return s1.getDate().compareTo(s2.getDate());
}
});
return sendables;
})
.observeOn(RX.main());
}
public Single<List<Sendable>> loadMoreMessages(Date fromDate, Date toDate, boolean desc) {
return loadMoreMessages(fromDate, toDate, null, desc);
}
public Single<List<Sendable>> loadMoreMessagesFrom(Date fromDate, Integer limit, boolean desc) {
return loadMoreMessages(fromDate, null, limit, desc);
}
public Single<List<Sendable>> loadMoreMessagesTo(Date toDate, Integer limit, boolean desc) {
return loadMoreMessages(null, toDate, limit, desc);
}
public Single<List<Sendable>> loadMoreMessagesBefore(final Date toDate, Integer limit, boolean desc) {
return Single.defer(() -> {
Date before = toDate == null ? null : new Date(toDate.getTime() - 1);
return loadMoreMessagesTo(before, limit, desc);
});
}
/**
* Listen for changes in the value of a list reference
* @param path to listen to
* @return events of list events
*/
protected Observable<Event<ListData>> listChangeOn(Path path) {
return Fire.stream().getFirebaseService().core
.listChangeOn(path)
.observeOn(RX.main());
}
public Completable send(Path messagesPath, Sendable sendable) {
return send(messagesPath, sendable, null);
}
/**
* Send a message to a messages ref
* @param messagesPath
* @param sendable item to be sent
* @param newId the ID of the new message
* @return single containing message id
*/
public Completable send(Path messagesPath, Sendable sendable, @Nullable Consumer<String> newId) {
return Fire.stream().getFirebaseService().core
.send(messagesPath, sendable, newId)
.observeOn(RX.main());
}
/**
* Delete a sendable from our queue
* @param messagesPath
* @return completion
*/
protected Completable deleteSendable (Path messagesPath) {
return Fire.stream().getFirebaseService().core
.deleteSendable(messagesPath)
.observeOn(RX.main());
}
/**
* Remove a user from a reference
* @param path for users
* @param user to remove
* @return completion
*/
protected Completable removeUser(Path path, User user) {
return removeUsers(path, user);
}
/**
* Remove users from a reference
* @param path for users
* @param users to remove
* @return completion
*/
protected Completable removeUsers(Path path, User... users) {
return removeUsers(path, Arrays.asList(users));
}
/**
* Remove users from a reference
* @param path for users
* @param users to remove
* @return completion
*/
protected Completable removeUsers(Path path, List<? extends User> users) {
return Fire.stream().getFirebaseService().core
.removeUsers(path, users)
.observeOn(RX.main());
}
/**
* Add a user to a reference
* @param path for users
* @param dataProvider a callback to extract the data to add from the user
* this allows us to use one method to write to multiple different places
* @param user to add
* @return completion
*/
protected Completable addUser(Path path, User.DataProvider dataProvider, User user) {
return addUsers(path, dataProvider, user);
}
/**
* Add users to a reference
* @param path for users
* @param dataProvider a callback to extract the data to add from the user
* this allows us to use one method to write to multiple different places
* @param users to add
* @return completion
*/
public Completable addUsers(Path path, User.DataProvider dataProvider, User... users) {
return addUsers(path, dataProvider, Arrays.asList(users));
}
/**
* Add users to a reference
* @param path
* @param dataProvider a callback to extract the data to add from the user
* this allows us to use one method to write to multiple different places
* @param users to add
* @return completion
*/
public Completable addUsers(Path path, User.DataProvider dataProvider, List<? extends User> users) {
return Fire.stream().getFirebaseService().core
.addUsers(path, dataProvider, users)
.observeOn(RX.main());
}
/**
* Updates a user for a reference
* @param path for users
* @param dataProvider a callback to extract the data to add from the user
* this allows us to use one method to write to multiple different places
* @param user to update
* @return completion
*/
public Completable updateUser(Path path, User.DataProvider dataProvider, User user) {
return updateUsers(path, dataProvider, user);
}
/**
* Update users for a reference
* @param path for users
* @param dataProvider a callback to extract the data to add from the user
* this allows us to use one method to write to multiple different places
* @param users to update
* @return completion
*/
public Completable updateUsers(Path path, User.DataProvider dataProvider, User... users) {
return updateUsers(path, dataProvider, Arrays.asList(users));
}
/**
* Update users for a reference
* @param path for users
* @param dataProvider a callback to extract the data to add from the user
* this allows us to use one method to write to multiple different places
* @param users to update
* @return completion
*/
public Completable updateUsers(Path path, User.DataProvider dataProvider, List<? extends User> users) {
return Fire.stream().getFirebaseService().core
.updateUsers(path, dataProvider, users)
.observeOn(RX.main());
}
@Override
public void connect() throws Exception {
dm.add(Single.defer((Callable<SingleSource<Optional<Sendable>>>) () -> {
// If we are deleting the messages on receipt then we want to get all new messages
if (Fire.stream().getConfig().deleteMessagesOnReceipt) {
return Single.just(Optional.empty());
} else {
return Fire.stream().getFirebaseService().core.lastMessage(messagesPath());
}
}).flatMapObservable((Function<Optional<Sendable>, ObservableSource<Event<Sendable>>>) optional -> {
Date date = null;
if (!optional.isEmpty()) {
if (Fire.stream().getConfig().emitEventForLastMessage) {
passMessageResultToStream(new Event<>(optional.get(), EventType.Added));
}
date = optional.get().getDate();
}
return messagesOn(date);
}).subscribe(this::passMessageResultToStream, this));
}
@Override
public void disconnect () {
dm.dispose();
}
/**
* Convenience method to cast sendables and send them to the correct events
* @param event sendable event
*/
protected void passMessageResultToStream(Event<Sendable> event) {
Sendable sendable = event.get();
// if (Fire.stream().isBlocked(new User(sendable.getFrom()))) {
// return;
// }
debug("Sendable: " + sendable.getType() + " " + sendable.getId() + ", date: " + sendable.getDate().getTime());
// In general, we are mostly interested when messages are added
if (sendable.isType(SendableType.message())) {
events.getMessages().accept(event.to(sendable.toMessage()));
}
if (sendable.isType(SendableType.deliveryReceipt())) {
events.getDeliveryReceipts().accept(event.to(sendable.toDeliveryReceipt()));
}
if (sendable.isType(SendableType.typingState())) {
TypingState typingState = sendable.toTypingState();
if (event.isAdded()) {
typingState.setBodyType(TypingStateType.typing());
}
if (event.isRemoved()) {
typingState.setBodyType(TypingStateType.none());
}
events.getTypingStates().accept(new Event<>(typingState, EventType.Modified));
}
if (sendable.isType(SendableType.invitation())) {
events.getInvitations().accept(event.to(sendable.toInvitation()));
}
if (sendable.isType(SendableType.presence())) {
events.getPresences().accept(event.to(sendable.toPresence()));
}
}
@Override
public List<Sendable> getSendables() {
return sendables;
}
@Override
public List<Sendable> getSendables(SendableType type) {
List<Sendable> sendables = new ArrayList<>();
for (Sendable s: sendables) {
if (s.isType(type)) {
sendables.add(s);
}
}
return sendables;
}
// public DeliveryReceipt getDeliveryReceiptsForMessage(String messageId, DeliveryReceiptType type) {
// List<DeliveryReceipt> receipts = getSendables(DeliveryReceipt.class);
// for (DeliveryReceipt receipt: receipts) {
// try {
// if (receipt.getMessageId().equals(messageId) && receipt.getDeliveryReceiptType() == type) {
// return receipt;
// }
// } catch (Exception ignored) {}
// }
// return null;
// }
public <T extends Sendable> List<T> getSendables(Class<T> clazz) {
return new Sendable.Converter<T>(clazz).convert(getSendables());
}
@Override
public Sendable getSendable(String id) {
for (Sendable s: sendables) {
if (s.getId().equals(id)) {
return s;
}
}
return null;
}
/**
* returns the events object which exposes the different sendable streams
* @return events
*/
public Events getSendableEvents() {
return events;
}
/**
* Overridable messages reference
* @return Firestore messages reference
*/
protected abstract Path messagesPath();
@Override
public DisposableMap getDisposableMap() {
return dm;
}
@Override
public void manage(Disposable disposable) {
getDisposableMap().add(disposable);
}
public abstract Completable markRead(Sendable message);
public abstract Completable markReceived(Sendable message);
public void debug(String text) {
if (Fire.stream().getConfig().debugEnabled) {
Logger.debug(text);
}
}
protected Predicate<Event<? extends Sendable>> deliveryReceiptFilter() {
return Filter.and(new ArrayList<Predicate<Event<? extends Sendable>>>() {{
add(Fire.internal().getMarkReceivedFilter());
add(Filter.notFromMe());
add(Filter.byEventType(EventType.Added));
}});
}
@Override
public void onSubscribe(Disposable d) {
dm.add(d);
}
@Override
public void onComplete() {
}
@Override
public void onError(Throwable e) {
events.publishThrowable().accept(e);
}
/**
* Error handler method so we can redirect all errors to the error events
* @param throwable - the events error
*/
@Override
public void accept(Throwable throwable) {
onError(throwable);
}
}
| chat-sdk/chat-sdk-android | firestream/src/main/java/firestream/chat/chat/AbstractChat.java | Java | apache-2.0 | 15,606 |
package org.xmlcml.norma.biblio;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.xmlcml.graphics.html.HtmlDiv;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
public class RISEntry {
public static final Logger LOG = Logger.getLogger(RISEntry.class);
static {
LOG.setLevel(Level.DEBUG);
}
private static final String AB = "AB";
private static final String ER = "ER";
public static final String TY = "TY";
public final static String START_DASH_SPACE = "^[A-Z][A-Z][A-Z ][A-Z ]\\- .*"; // PMID breaks the rules, this covers it
public final static String DASH_SPACE = "- "; // PMID breaks the rules, this covers it
public static final String PMID = "PMID";
private String type;
private StringBuilder currentValue;
private Multimap<String, StringBuilder> valuesByField = ArrayListMultimap.create();
private boolean canAdd;
private List<String> fieldList;
String abstractx;
public RISEntry() {
canAdd = true;
fieldList = new ArrayList<String>();
}
public String getType() {
return type;
}
public String addLine(String line) {
if (!canAdd) {
System.err.println("Cannot add line: "+line);
}
String field = null;
if (line.matches(START_DASH_SPACE)) {
String[] ss = line.split(DASH_SPACE);
field = ss[0].trim();
recordUnknownFields(field);
if (!fieldList.contains(field)) {
fieldList.add(field);
}
if (ss.length == 1) {
currentValue = null;
if (field.equals(ER)) {
canAdd = false;
}
} else {
currentValue = new StringBuilder(ss[1].trim());
valuesByField.put(field, currentValue);
}
} else {
String v = line.trim();
if (canAdd) {
if (currentValue != null) {
currentValue.append(" "+v);
} else {
System.err.println("Cannot add "+line);
}
} else {
System.err.println("Cannot add: "+line);
}
}
return field;
}
private void recordUnknownFields(String field) {
if (!RISParser.FIELD_MAP.containsKey(field)) {
if (!RISParser.UNKNOWN_KEYS.contains(field)) {
RISParser.addUnknownKey(field);
LOG.trace("Unknown Key: "+field);
}
}
}
public HtmlDiv createAbstractHtml() {
List<StringBuilder> abstracts = new ArrayList<StringBuilder>(valuesByField.get(AB));
HtmlDiv abstractDiv = null;
if (abstracts.size() == 1) {
abstractx = abstracts.get(0).toString();
BiblioAbstractAnalyzer abstractAnalyzer = new BiblioAbstractAnalyzer();
abstractDiv = abstractAnalyzer.createAndAnalyzeSections(abstractx);
}
return abstractDiv;
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (String key : fieldList) {
sb.append(key+": ");
List<StringBuilder> values = new ArrayList<StringBuilder>(valuesByField.get(key));
if (values.size() == 1) {
sb.append(values.get(0).toString()+"\n");
} else {
sb.append("\n");
for (StringBuilder sb0 : values) {
sb.append(" "+sb0.toString()+"\n");
}
}
}
return sb.toString();
}
public String getAbstractString() {
if (abstractx == null) {
createAbstractHtml();
}
return abstractx;
}
}
| petermr/norma | src/main/java/org/xmlcml/norma/biblio/RISEntry.java | Java | apache-2.0 | 3,184 |
/**
* <copyright>
*
* Copyright (c) 2010 SAP AG.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Reiner Hille-Doering (SAP AG) - initial API and implementation and/or initial documentation
*
* </copyright>
*/
package org.eclipse.bpmn2.impl;
import java.util.Collection;
import java.util.List;
import org.eclipse.bpmn2.Bpmn2Package;
import org.eclipse.bpmn2.DataState;
import org.eclipse.bpmn2.DataStore;
import org.eclipse.bpmn2.DataStoreReference;
import org.eclipse.bpmn2.ItemAwareElement;
import org.eclipse.bpmn2.ItemDefinition;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentWithInverseEList;
import org.eclipse.emf.ecore.util.InternalEList;
import org.eclipse.securebpmn2.ItemAwareElementAction;
import org.eclipse.securebpmn2.Securebpmn2Package;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Data Store Reference</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.eclipse.bpmn2.impl.DataStoreReferenceImpl#getDataState <em>Data State</em>}</li>
* <li>{@link org.eclipse.bpmn2.impl.DataStoreReferenceImpl#getItemSubjectRef <em>Item Subject Ref</em>}</li>
* <li>{@link org.eclipse.bpmn2.impl.DataStoreReferenceImpl#getItemAwareElementActions <em>Item Aware Element Actions</em>}</li>
* <li>{@link org.eclipse.bpmn2.impl.DataStoreReferenceImpl#getDataStoreRef <em>Data Store Ref</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class DataStoreReferenceImpl extends FlowElementImpl implements
DataStoreReference {
/**
* The cached value of the '{@link #getDataState() <em>Data State</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDataState()
* @generated
* @ordered
*/
protected DataState dataState;
/**
* The cached value of the '{@link #getItemSubjectRef() <em>Item Subject Ref</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getItemSubjectRef()
* @generated
* @ordered
*/
protected ItemDefinition itemSubjectRef;
/**
* The cached value of the '{@link #getItemAwareElementActions() <em>Item Aware Element Actions</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getItemAwareElementActions()
* @generated
* @ordered
*/
protected EList<ItemAwareElementAction> itemAwareElementActions;
/**
* The cached value of the '{@link #getDataStoreRef() <em>Data Store Ref</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDataStoreRef()
* @generated
* @ordered
*/
protected DataStore dataStoreRef;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected DataStoreReferenceImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Bpmn2Package.Literals.DATA_STORE_REFERENCE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DataState getDataState() {
return dataState;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetDataState(DataState newDataState,
NotificationChain msgs) {
DataState oldDataState = dataState;
dataState = newDataState;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this,
Notification.SET,
Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE,
oldDataState, newDataState);
if (msgs == null)
msgs = notification;
else
msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setDataState(DataState newDataState) {
if (newDataState != dataState) {
NotificationChain msgs = null;
if (dataState != null)
msgs = ((InternalEObject) dataState)
.eInverseRemove(
this,
EOPPOSITE_FEATURE_BASE
- Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE,
null, msgs);
if (newDataState != null)
msgs = ((InternalEObject) newDataState)
.eInverseAdd(
this,
EOPPOSITE_FEATURE_BASE
- Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE,
null, msgs);
msgs = basicSetDataState(newDataState, msgs);
if (msgs != null)
msgs.dispatch();
} else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET,
Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE,
newDataState, newDataState));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ItemDefinition getItemSubjectRef() {
if (itemSubjectRef != null && itemSubjectRef.eIsProxy()) {
InternalEObject oldItemSubjectRef = (InternalEObject) itemSubjectRef;
itemSubjectRef = (ItemDefinition) eResolveProxy(oldItemSubjectRef);
if (itemSubjectRef != oldItemSubjectRef) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(
this,
Notification.RESOLVE,
Bpmn2Package.DATA_STORE_REFERENCE__ITEM_SUBJECT_REF,
oldItemSubjectRef, itemSubjectRef));
}
}
return itemSubjectRef;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ItemDefinition basicGetItemSubjectRef() {
return itemSubjectRef;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setItemSubjectRef(ItemDefinition newItemSubjectRef) {
ItemDefinition oldItemSubjectRef = itemSubjectRef;
itemSubjectRef = newItemSubjectRef;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET,
Bpmn2Package.DATA_STORE_REFERENCE__ITEM_SUBJECT_REF,
oldItemSubjectRef, itemSubjectRef));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public List<ItemAwareElementAction> getItemAwareElementActions() {
if (itemAwareElementActions == null) {
itemAwareElementActions = new EObjectContainmentWithInverseEList<ItemAwareElementAction>(
ItemAwareElementAction.class,
this,
Bpmn2Package.DATA_STORE_REFERENCE__ITEM_AWARE_ELEMENT_ACTIONS,
Securebpmn2Package.ITEM_AWARE_ELEMENT_ACTION__ITEM_AWARE_ELEMENT);
}
return itemAwareElementActions;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DataStore getDataStoreRef() {
if (dataStoreRef != null && dataStoreRef.eIsProxy()) {
InternalEObject oldDataStoreRef = (InternalEObject) dataStoreRef;
dataStoreRef = (DataStore) eResolveProxy(oldDataStoreRef);
if (dataStoreRef != oldDataStoreRef) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE,
Bpmn2Package.DATA_STORE_REFERENCE__DATA_STORE_REF,
oldDataStoreRef, dataStoreRef));
}
}
return dataStoreRef;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DataStore basicGetDataStoreRef() {
return dataStoreRef;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setDataStoreRef(DataStore newDataStoreRef) {
DataStore oldDataStoreRef = dataStoreRef;
dataStoreRef = newDataStoreRef;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET,
Bpmn2Package.DATA_STORE_REFERENCE__DATA_STORE_REF,
oldDataStoreRef, dataStoreRef));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd,
int featureID, NotificationChain msgs) {
switch (featureID) {
case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_AWARE_ELEMENT_ACTIONS:
return ((InternalEList<InternalEObject>) (InternalEList<?>) getItemAwareElementActions())
.basicAdd(otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd,
int featureID, NotificationChain msgs) {
switch (featureID) {
case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE:
return basicSetDataState(null, msgs);
case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_AWARE_ELEMENT_ACTIONS:
return ((InternalEList<?>) getItemAwareElementActions())
.basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE:
return getDataState();
case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_SUBJECT_REF:
if (resolve)
return getItemSubjectRef();
return basicGetItemSubjectRef();
case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_AWARE_ELEMENT_ACTIONS:
return getItemAwareElementActions();
case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STORE_REF:
if (resolve)
return getDataStoreRef();
return basicGetDataStoreRef();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE:
setDataState((DataState) newValue);
return;
case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_SUBJECT_REF:
setItemSubjectRef((ItemDefinition) newValue);
return;
case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_AWARE_ELEMENT_ACTIONS:
getItemAwareElementActions().clear();
getItemAwareElementActions().addAll(
(Collection<? extends ItemAwareElementAction>) newValue);
return;
case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STORE_REF:
setDataStoreRef((DataStore) newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE:
setDataState((DataState) null);
return;
case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_SUBJECT_REF:
setItemSubjectRef((ItemDefinition) null);
return;
case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_AWARE_ELEMENT_ACTIONS:
getItemAwareElementActions().clear();
return;
case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STORE_REF:
setDataStoreRef((DataStore) null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE:
return dataState != null;
case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_SUBJECT_REF:
return itemSubjectRef != null;
case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_AWARE_ELEMENT_ACTIONS:
return itemAwareElementActions != null
&& !itemAwareElementActions.isEmpty();
case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STORE_REF:
return dataStoreRef != null;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public int eBaseStructuralFeatureID(int derivedFeatureID, Class<?> baseClass) {
if (baseClass == ItemAwareElement.class) {
switch (derivedFeatureID) {
case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE:
return Bpmn2Package.ITEM_AWARE_ELEMENT__DATA_STATE;
case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_SUBJECT_REF:
return Bpmn2Package.ITEM_AWARE_ELEMENT__ITEM_SUBJECT_REF;
case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_AWARE_ELEMENT_ACTIONS:
return Bpmn2Package.ITEM_AWARE_ELEMENT__ITEM_AWARE_ELEMENT_ACTIONS;
default:
return -1;
}
}
return super.eBaseStructuralFeatureID(derivedFeatureID, baseClass);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public int eDerivedStructuralFeatureID(int baseFeatureID, Class<?> baseClass) {
if (baseClass == ItemAwareElement.class) {
switch (baseFeatureID) {
case Bpmn2Package.ITEM_AWARE_ELEMENT__DATA_STATE:
return Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE;
case Bpmn2Package.ITEM_AWARE_ELEMENT__ITEM_SUBJECT_REF:
return Bpmn2Package.DATA_STORE_REFERENCE__ITEM_SUBJECT_REF;
case Bpmn2Package.ITEM_AWARE_ELEMENT__ITEM_AWARE_ELEMENT_ACTIONS:
return Bpmn2Package.DATA_STORE_REFERENCE__ITEM_AWARE_ELEMENT_ACTIONS;
default:
return -1;
}
}
return super.eDerivedStructuralFeatureID(baseFeatureID, baseClass);
}
} //DataStoreReferenceImpl
| adbrucker/SecureBPMN | designer/src/org.activiti.designer.model/src/main/java/org/eclipse/bpmn2/impl/DataStoreReferenceImpl.java | Java | apache-2.0 | 13,233 |
/*
* Kendo UI v2014.3.1119 (http://www.telerik.com/kendo-ui)
* Copyright 2014 Telerik AD. All rights reserved.
*
* Kendo UI commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-complete
* If you do not own a commercial license, this file shall be governed by the trial license terms.
*/
(function(f, define){
define([], f);
})(function(){
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["de-LI"] = {
name: "de-LI",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": "'",
".": ".",
groupSize: [3],
percent: {
pattern: ["-n%","n%"],
decimals: 2,
",": "'",
".": ".",
groupSize: [3],
symbol: "%"
},
currency: {
pattern: ["$-n","$ n"],
decimals: 2,
",": "'",
".": ".",
groupSize: [3],
symbol: "CHF"
}
},
calendars: {
standard: {
days: {
names: ["Sonntag","Montag","Dienstag","Mittwoch","Donnerstag","Freitag","Samstag"],
namesAbbr: ["So","Mo","Di","Mi","Do","Fr","Sa"],
namesShort: ["So","Mo","Di","Mi","Do","Fr","Sa"]
},
months: {
names: ["Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember",""],
namesAbbr: ["Jan","Feb","Mrz","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Dez",""]
},
AM: [""],
PM: [""],
patterns: {
d: "dd.MM.yyyy",
D: "dddd, d. MMMM yyyy",
F: "dddd, d. MMMM yyyy HH:mm:ss",
g: "dd.MM.yyyy HH:mm",
G: "dd.MM.yyyy HH:mm:ss",
m: "dd MMMM",
M: "dd MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "HH:mm",
T: "HH:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM yyyy",
Y: "MMMM yyyy"
},
"/": ".",
":": ":",
firstDay: 1
}
}
}
})(this);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); }); | y-todorov/Inventory | Inventory.MVC/Scripts/Kendo/cultures/kendo.culture.de-LI.js | JavaScript | apache-2.0 | 2,637 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.SourceBrowser.Common;
using Newtonsoft.Json;
namespace Microsoft.SourceBrowser.HtmlGenerator
{
public class TypeScriptSupport
{
private static readonly HashSet<string> alreadyProcessed = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private Dictionary<string, List<Reference>> references;
private List<string> declarations;
public Dictionary<string, List<Tuple<string, long>>> SymbolIDToListOfLocationsMap { get; private set; }
public void Generate(IEnumerable<string> typeScriptFiles, string solutionDestinationFolder)
{
if (typeScriptFiles == null || !typeScriptFiles.Any())
{
return;
}
var projectDestinationFolder = Path.Combine(solutionDestinationFolder, Constants.TypeScriptFiles).MustBeAbsolute();
declarations = new List<string>();
references = new Dictionary<string, List<Reference>>(StringComparer.OrdinalIgnoreCase);
SymbolIDToListOfLocationsMap = new Dictionary<string, List<Tuple<string, long>>>();
var list = new List<string>();
string libFile = null;
foreach (var file in typeScriptFiles)
{
if (!alreadyProcessed.Contains(file))
{
if (libFile == null && string.Equals(Path.GetFileName(file), "lib.d.ts", StringComparison.OrdinalIgnoreCase))
{
libFile = file;
}
else
{
list.Add(file);
}
}
}
if (libFile == null)
{
libFile = Path.Combine(Common.Paths.BaseAppFolder, "TypeScriptSupport", "lib.d.ts");
}
try
{
GenerateCore(list, libFile);
}
catch (Exception ex)
{
Log.Exception(ex, "Error when generating TypeScript files");
return;
}
ProjectGenerator.GenerateReferencesDataFilesToAssembly(
Paths.SolutionDestinationFolder,
Constants.TypeScriptFiles,
references);
declarations.Sort();
Serialization.WriteDeclaredSymbols(
projectDestinationFolder,
declarations);
ProjectGenerator.GenerateSymbolIDToListOfDeclarationLocationsMap(
projectDestinationFolder,
SymbolIDToListOfLocationsMap);
}
private void GenerateCore(IEnumerable<string> fileNames, string libFile)
{
var output = Path.Combine(Common.Paths.BaseAppFolder, "output");
if (Directory.Exists(output))
{
Directory.Delete(output, recursive: true);
}
var json = JsonConvert.SerializeObject(new { fileNames, libFile, outputFolder = output });
var argumentsJson = Path.Combine(Common.Paths.BaseAppFolder, "TypeScriptAnalyzerArguments.json");
File.WriteAllText(argumentsJson, json);
var analyzerJs = Path.Combine(Common.Paths.BaseAppFolder, @"TypeScriptSupport\analyzer.js");
var arguments = string.Format("\"{0}\" {1}", analyzerJs, argumentsJson);
ProcessLaunchService.ProcessRunResult result;
try
{
using (Disposable.Timing("Calling Node.js to process TypeScript"))
{
result = new ProcessLaunchService().RunAndRedirectOutput("node", arguments);
}
}
catch (Win32Exception)
{
Log.Write("Warning: Node.js is required to generate TypeScript files. Skipping generation. Download Node.js from https://nodejs.org.", ConsoleColor.Yellow);
Log.Exception("Node.js is not installed.");
return;
}
using (Disposable.Timing("Generating TypeScript files"))
{
foreach (var file in Directory.GetFiles(output))
{
if (Path.GetFileNameWithoutExtension(file) == "ok")
{
continue;
}
if (Path.GetFileNameWithoutExtension(file) == "error")
{
var errorContent = File.ReadAllText(file);
Log.Exception(DateTime.Now.ToString() + " " + errorContent);
return;
}
var text = File.ReadAllText(file);
AnalyzedFile analysis = JsonConvert.DeserializeObject<AnalyzedFile>(text);
EnsureFileGeneratedAndGetUrl(analysis);
}
}
}
public void EnsureFileGeneratedAndGetUrl(AnalyzedFile analysis)
{
string localFileSystemPath = analysis.fileName;
localFileSystemPath = Path.GetFullPath(localFileSystemPath);
string destinationFilePath = GetDestinationFilePath(localFileSystemPath);
if (!File.Exists(destinationFilePath))
{
Generate(localFileSystemPath, destinationFilePath, analysis.syntacticClassifications, analysis.semanticClassifications);
}
}
public static string GetDestinationFilePath(string sourceFilePath)
{
var url = sourceFilePath + ".html";
url = url.Replace(":", "");
url = url.Replace(" ", "");
url = url.Replace(@"\bin\", @"\bin_\");
if (url.StartsWith(@"\\", StringComparison.Ordinal))
{
url = url.Substring(2);
}
url = Constants.TypeScriptFiles + @"\" + url;
url = Path.Combine(Paths.SolutionDestinationFolder, url);
return url;
}
private void Generate(
string sourceFilePath,
string destinationHtmlFilePath,
ClassifiedRange[] syntacticRanges,
ClassifiedRange[] semanticRanges)
{
Log.Write(destinationHtmlFilePath);
var sb = new StringBuilder();
var lines = File.ReadAllLines(sourceFilePath);
var text = File.ReadAllText(sourceFilePath);
var lineCount = lines.Length;
var lineLengths = TextUtilities.GetLineLengths(text);
var ranges = PrepareRanges(syntacticRanges, semanticRanges, text);
var relativePathToRoot = Paths.CalculateRelativePathToRoot(destinationHtmlFilePath, Paths.SolutionDestinationFolder);
var prefix = Markup.GetDocumentPrefix(Path.GetFileName(sourceFilePath), relativePathToRoot, lineCount, "ix");
sb.Append(prefix);
var displayName = GetDisplayName(destinationHtmlFilePath);
const string assemblyName = "TypeScriptFiles";
var url = "/#" + assemblyName + "/" + displayName.Replace('\\', '/');
displayName = @"\\" + displayName;
Markup.WriteLinkPanel(s => sb.AppendLine(s), fileLink: (displayName, url));
// pass a value larger than 0 to generate line numbers statically at HTML generation time
var table = Markup.GetTablePrefix();
sb.AppendLine(table);
var localSymbolIdMap = new Dictionary<string, int>();
foreach (var range in ranges)
{
range.lineNumber = TextUtilities.GetLineNumber(range.start, lineLengths);
var line = TextUtilities.GetLineFromPosition(range.start, text);
range.column = range.start - line.Item1;
range.lineText = text.Substring(line.Item1, line.Item2);
GenerateRange(sb, range, destinationHtmlFilePath, localSymbolIdMap);
}
var suffix = Markup.GetDocumentSuffix();
sb.AppendLine(suffix);
var folder = Path.GetDirectoryName(destinationHtmlFilePath);
Directory.CreateDirectory(folder);
File.WriteAllText(destinationHtmlFilePath, sb.ToString());
}
public static ClassifiedRange[] PrepareRanges(
ClassifiedRange[] syntacticRanges,
ClassifiedRange[] semanticRanges,
string text)
{
foreach (var range in semanticRanges)
{
range.IsSemantic = true;
}
var rangesSortedByStart = syntacticRanges
.Concat(semanticRanges)
.Where(r => r.length > 0)
.OrderBy(r => r.start)
.ToArray();
var midpoints = rangesSortedByStart
.Select(r => r.start)
.Concat(
rangesSortedByStart
.Select(r => r.end))
.Distinct()
.OrderBy(n => n)
.ToArray();
var ranges = RemoveIntersectingRanges(
text,
rangesSortedByStart,
midpoints);
ranges = RemoveOverlappingRanges(
text,
ranges);
ranges = RangeUtilities.FillGaps(
text,
ranges,
r => r.start,
r => r.length,
(s, l, t) => new ClassifiedRange(t, s, l));
foreach (var range in ranges)
{
if (range.text == null)
{
range.text = text.Substring(range.start, range.length);
}
}
return ranges;
}
public static ClassifiedRange[] RemoveOverlappingRanges(string text, ClassifiedRange[] ranges)
{
var output = new List<ClassifiedRange>(ranges.Length);
for (int i = 0; i < ranges.Length; i++)
{
ClassifiedRange best = ranges[i];
while (i < ranges.Length - 1 && ranges[i].start == ranges[i + 1].start)
{
best = ChooseBetterRange(best, ranges[i + 1]);
i++;
}
output.Add(best);
}
return output.ToArray();
}
private static ClassifiedRange ChooseBetterRange(ClassifiedRange left, ClassifiedRange right)
{
if (left == null)
{
return right;
}
if (right == null)
{
return left;
}
if (left.IsSemantic != right.IsSemantic)
{
if (left.IsSemantic)
{
right.classification = left.classification;
return right;
}
else
{
left.classification = right.classification;
return left;
}
}
ClassifiedRange victim = left;
ClassifiedRange winner = right;
if (left.classification == "comment")
{
victim = left;
winner = right;
}
if (right.classification == "comment")
{
victim = right;
winner = left;
}
if (winner.hyperlinks == null && victim.hyperlinks != null)
{
winner.hyperlinks = victim.hyperlinks;
}
if (winner.classification == "text")
{
winner.classification = victim.classification;
}
return winner;
}
public static ClassifiedRange[] RemoveIntersectingRanges(
string text,
ClassifiedRange[] rangesSortedByStart,
int[] midpoints)
{
var result = new List<ClassifiedRange>();
int currentEndpoint = 0;
int currentRangeIndex = 0;
for (; currentEndpoint < midpoints.Length && currentRangeIndex < rangesSortedByStart.Length;)
{
while (
currentRangeIndex < rangesSortedByStart.Length &&
rangesSortedByStart[currentRangeIndex].start == midpoints[currentEndpoint])
{
var currentRange = rangesSortedByStart[currentRangeIndex];
if (currentRange.end == midpoints[currentEndpoint + 1])
{
result.Add(currentRange);
}
else
{
int endpoint = currentEndpoint;
do
{
result.Add(
new ClassifiedRange(
text,
midpoints[endpoint],
midpoints[endpoint + 1] - midpoints[endpoint],
currentRange));
endpoint++;
}
while (endpoint < midpoints.Length && midpoints[endpoint] < currentRange.end);
}
currentRangeIndex++;
}
currentEndpoint++;
}
return result.ToArray();
}
private void GenerateRange(
StringBuilder sb,
ClassifiedRange range,
string destinationFilePath,
Dictionary<string, int> localSymbolIdMap)
{
var html = range.text;
html = Markup.HtmlEscape(html);
var localRelativePath = destinationFilePath.Substring(
Path.Combine(
Paths.SolutionDestinationFolder,
Constants.TypeScriptFiles).Length + 1);
localRelativePath = localRelativePath.Substring(0, localRelativePath.Length - ".html".Length);
string classAttributeValue = GetSpanClass(range.classification);
HtmlElementInfo hyperlinkInfo = GenerateLinks(range, destinationFilePath, localSymbolIdMap);
if (hyperlinkInfo == null)
{
if (classAttributeValue == null)
{
sb.Append(html);
return;
}
if (classAttributeValue == "k")
{
sb.Append("<b>").Append(html).Append("</b>");
return;
}
}
var elementName = "span";
if (hyperlinkInfo != null)
{
elementName = hyperlinkInfo.Name;
}
sb.Append("<").Append(elementName);
bool overridingClassAttributeSpecified = false;
if (hyperlinkInfo != null)
{
foreach (var attribute in hyperlinkInfo.Attributes)
{
const string typeScriptFilesR = "/TypeScriptFiles/R/";
if (attribute.Key == "href" && attribute.Value.StartsWith(typeScriptFilesR, StringComparison.Ordinal))
{
var streamPosition = sb.Length + 7 + typeScriptFilesR.Length; // exact offset into <a href="HERE
ProjectGenerator.AddDeclaredSymbolToRedirectMap(
SymbolIDToListOfLocationsMap,
attribute.Value.Substring(typeScriptFilesR.Length, 16),
localRelativePath,
streamPosition);
}
AddAttribute(sb, attribute.Key, attribute.Value);
if (attribute.Key == "class")
{
overridingClassAttributeSpecified = true;
}
}
}
if (!overridingClassAttributeSpecified)
{
AddAttribute(sb, "class", classAttributeValue);
}
sb.Append('>');
sb.Append(html);
sb.Append("</").Append(elementName).Append(">");
}
private void AddAttribute(StringBuilder sb, string name, string value)
{
if (value != null)
{
sb.Append(" ").Append(name).Append("=\"").Append(value).Append("\"");
}
}
private int GetLocalId(string symbolId, Dictionary<string, int> localSymbolIdMap)
{
int localId = 0;
if (!localSymbolIdMap.TryGetValue(symbolId, out localId))
{
localId = localSymbolIdMap.Count;
localSymbolIdMap.Add(symbolId, localId);
}
return localId;
}
private HtmlElementInfo GenerateLinks(ClassifiedRange range, string destinationHtmlFilePath, Dictionary<string, int> localSymbolIdMap)
{
HtmlElementInfo result = null;
var localRelativePath = destinationHtmlFilePath.Substring(
Path.Combine(
Paths.SolutionDestinationFolder,
Constants.TypeScriptFiles).Length);
if (!string.IsNullOrEmpty(range.definitionSymbolId))
{
var definitionSymbolId = SymbolIdService.GetId(range.definitionSymbolId);
if (range.IsSymbolLocalOnly())
{
var localId = GetLocalId(definitionSymbolId, localSymbolIdMap);
result = new HtmlElementInfo
{
Name = "span",
Attributes =
{
{ "id", "r" + localId + " rd" },
{ "class", "r" + localId + " r" }
}
};
return result;
}
result = new HtmlElementInfo
{
Name = "a",
Attributes =
{
{ "id", definitionSymbolId },
{ "href", "/TypeScriptFiles/" + Constants.ReferencesFileName + "/" + definitionSymbolId + ".html" },
{ "target", "n" }
}
};
var searchString = range.searchString;
if (!string.IsNullOrEmpty(searchString) && searchString.Length > 2)
{
lock (declarations)
{
searchString = searchString.StripQuotes();
if (IsWellFormed(searchString))
{
var declaration = string.Join(";",
searchString, // symbol name
definitionSymbolId, // 8-byte symbol ID
range.definitionKind, // kind (e.g. "class")
Markup.EscapeSemicolons(range.fullName), // symbol full name and signature
GetGlyph(range.definitionKind) // glyph number
);
declarations.Add(declaration);
}
}
}
}
if (range.hyperlinks == null || range.hyperlinks.Length == 0)
{
return result;
}
var hyperlink = range.hyperlinks[0];
var symbolId = SymbolIdService.GetId(hyperlink.symbolId);
if (range.IsSymbolLocalOnly() || localSymbolIdMap.ContainsKey(symbolId))
{
var localId = GetLocalId(symbolId, localSymbolIdMap);
result = new HtmlElementInfo
{
Name = "span",
Attributes =
{
{ "class", "r" + localId + " r" }
}
};
return result;
}
var hyperlinkDestinationFile = Path.GetFullPath(hyperlink.sourceFile);
hyperlinkDestinationFile = GetDestinationFilePath(hyperlinkDestinationFile);
string href = "";
if (!string.Equals(hyperlinkDestinationFile, destinationHtmlFilePath, StringComparison.OrdinalIgnoreCase))
{
href = Paths.MakeRelativeToFile(hyperlinkDestinationFile, destinationHtmlFilePath);
href = href.Replace('\\', '/');
}
href = href + "#" + symbolId;
if (result == null)
{
result = new HtmlElementInfo
{
Name = "a",
Attributes =
{
{ "href", href },
{ "target", "s" },
}
};
}
else if (!result.Attributes.ContainsKey("href"))
{
result.Attributes.Add("href", href);
result.Attributes.Add("target", "s");
}
lock (this.references)
{
var lineNumber = range.lineNumber + 1;
var linkToReference = ".." + localRelativePath + "#" + lineNumber.ToString();
var start = range.column;
var end = range.column + range.text.Length;
var lineText = Markup.HtmlEscape(range.lineText, ref start, ref end);
var reference = new Reference
{
FromAssemblyId = Constants.TypeScriptFiles,
ToAssemblyId = Constants.TypeScriptFiles,
FromLocalPath = localRelativePath.Substring(0, localRelativePath.Length - ".html".Length).Replace('\\', '/'),
Kind = ReferenceKind.Reference,
ToSymbolId = symbolId,
ToSymbolName = range.text,
ReferenceLineNumber = lineNumber,
ReferenceLineText = lineText,
ReferenceColumnStart = start,
ReferenceColumnEnd = end,
Url = linkToReference.Replace('\\', '/')
};
if (!references.TryGetValue(symbolId, out List<Reference> bucket))
{
bucket = new List<Reference>();
references.Add(symbolId, bucket);
}
bucket.Add(reference);
}
return result;
}
private bool IsWellFormed(string searchString)
{
return searchString.Length > 2
&& !searchString.Contains(";")
&& !searchString.Contains("\n");
}
private string GetGlyph(string definitionKind)
{
switch (definitionKind)
{
case "variable":
return "42";
case "function":
return "72";
case "parameter":
return "42";
case "interface":
return "48";
case "property":
return "102";
case "method":
return "72";
case "type parameter":
return "114";
case "module":
return "150";
case "class":
return "0";
case "constructor":
return "72";
case "enum":
return "18";
case "enum member":
return "24";
case "import":
return "6";
case "get accessor":
return "72";
case "set accessor":
return "72";
default:
return "195";
}
}
private string GetSpanClass(string classification)
{
if (classification == "keyword")
{
return "k";
}
else if (classification == "comment")
{
return "c";
}
else if (classification == "string")
{
return "s";
}
else if (classification == "class name")
{
return "t";
}
else if (classification == "enum name")
{
return "t";
}
else if (classification == "interface name" || classification == "type alias name")
{
return "t";
}
else if (classification == "type parameter name")
{
return "t";
}
else if (classification == "module name")
{
return "t";
}
return null;
}
private string GetDisplayName(string destinationHtmlFilePath)
{
var result = Path.GetFileNameWithoutExtension(destinationHtmlFilePath);
var lengthOfPrefixToTrim = Paths.SolutionDestinationFolder.Length + Constants.TypeScriptFiles.Length + 2;
result = destinationHtmlFilePath.Substring(lengthOfPrefixToTrim, destinationHtmlFilePath.Length - lengthOfPrefixToTrim - 5); // strip ".html"
return result;
}
}
}
| KirillOsenkov/SourceBrowser | src/HtmlGenerator/Pass1-Generation/TypeScriptSupport.cs | C# | apache-2.0 | 26,413 |
/*
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 main
import (
"errors"
"fmt"
"strconv"
"encoding/json"
"time"
"strings"
"github.com/hyperledger/fabric/core/chaincode/shim"
)
// SimpleChaincode example simple Chaincode implementation
type SimpleChaincode struct {
}
var marbleIndexStr = "_marbleindex"
var driverIndexStr = "_driverindex" //name for the key/value that will store a list of all known marbles
var openTradesStr = "_opentrades" //name for the key/value that will store all open trades
type Marble struct{
Name string `json:"name"` //the fieldtags are needed to keep case from bouncing around
Color string `json:"color"`
Size int `json:"size"`
User string `json:"user"`
}
type Driver struct{
FirstName string `json:"firstname"` //the fieldtags are needed to keep case from bouncing around
LastName string `json:"lastname"`
Email string `json:"email"`
Mobile string `json:"mobile"`
Password string `json:"password"`
Street string `json:"street"`
City string `json:"city"`
State string `json:"state"`
Zip string `json:"zip"`
Status string `json:"status"`
}
type Description struct{
Color string `json:"color"`
Size int `json:"size"`
}
type AnOpenTrade struct{
User string `json:"user"` //user who created the open trade order
Timestamp int64 `json:"timestamp"` //utc timestamp of creation
Want Description `json:"want"` //description of desired marble
Willing []Description `json:"willing"` //array of marbles willing to trade away
}
type AllTrades struct{
OpenTrades []AnOpenTrade `json:"open_trades"`
}
type Adminlogin struct{
Userid string `json:"userid"` //User login for system Admin
Password string `json:"password"`
}
// ============================================================================================================================
// Main
// ============================================================================================================================
func main() {
err := shim.Start(new(SimpleChaincode))
if err != nil {
fmt.Printf("Error starting Simple chaincode: %s", err)
}
}
// ============================================================================================================================
// Init - reset all the things
// ============================================================================================================================
func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
var Aval int
var err error
//Changes for the Hertz Blockchain
if len(args) != 2 {
return nil, errors.New("Incorrect number of arguments. Expecting 1")
}
//Write the User Id "mail Id" arg[0] and password arg[1]
userid := args[0] //argument for UserID
password := args[1] //argument for password
str := `{"userid": "` + userid+ `", "password": "` + password + `"}`
err = stub.PutState(userid, []byte(str)) //Put the userid and password in blockchain
if err != nil {
return nil, err
}
//End of Changes for the Hertz Blockchain}
// Initialize the chaincode
Aval, err = strconv.Atoi(args[0])
if err != nil {
return nil, errors.New("Expecting integer value for asset holding")
}
// Write the state to the ledger
err = stub.PutState("abc", []byte(strconv.Itoa(Aval))) //making a test var "abc", I find it handy to read/write to it right away to test the network
if err != nil {
return nil, err
}
var empty []string
jsonAsBytes, _ := json.Marshal(empty) //marshal an emtpy array of strings to clear the index
err = stub.PutState(marbleIndexStr, jsonAsBytes)
if err != nil {
return nil, err
}
//var empty []string
//jsonAsBytes, _ := json.Marshal(empty) //marshal an emtpy array of strings to clear the index
err = stub.PutState(driverIndexStr, jsonAsBytes)
if err != nil {
return nil, err
}
var trades AllTrades
jsonAsBytes, _ = json.Marshal(trades) //clear the open trade struct
err = stub.PutState(openTradesStr, jsonAsBytes)
if err != nil {
return nil, err
}
return nil, nil
}
// ============================================================================================================================
// Run - Our entry point for Invocations - [LEGACY] obc-peer 4/25/2016
// ============================================================================================================================
func (t *SimpleChaincode) Run(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
fmt.Println("run is running " + function)
return t.Invoke(stub, function, args)
}
// ============================================================================================================================
// Invoke - Our entry point for Invocations
// ============================================================================================================================
func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
fmt.Println("invoke is running " + function)
// Handle different functions
if function == "init" { //initialize the chaincode state, used as reset
return t.Init(stub, "init", args)
} else if function == "delete" { //deletes an entity from its state
res, err := t.Delete(stub, args)
cleanTrades(stub) //lets make sure all open trades are still valid
return res, err
} else if function == "write" { //writes a value to the chaincode state
return t.Write(stub, args)
} else if function == "init_marble" { //create a new marble
return t.init_marble(stub, args)
} else if function == "signup_driver" { //create a new marble
return t.signup_driver(stub, args)
} else if function == "set_user" { //change owner of a marble
res, err := t.set_user(stub, args)
cleanTrades(stub) //lets make sure all open trades are still valid
return res, err
}else if function == "set_status" { //change owner of a marble
res, err := t.set_status(stub, args)
cleanTrades(stub) //lets make sure all open trades are still valid
return res, err
} else if function == "open_trade" { //create a new trade order
return t.open_trade(stub, args)
} else if function == "perform_trade" { //forfill an open trade order
res, err := t.perform_trade(stub, args)
cleanTrades(stub) //lets clean just in case
return res, err
} else if function == "remove_trade" { //cancel an open trade order
return t.remove_trade(stub, args)
}
fmt.Println("invoke did not find func: " + function) //error
return nil, errors.New("Received unknown function invocation")
}
// ============================================================================================================================
// Query - Our entry point for Queries
// ============================================================================================================================
func (t *SimpleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
fmt.Println("query is running " + function)
// Handle different functions
if function == "read" { //read a variable
return t.read(stub, args)
} else if function == "read_sysadmin" { //Read system admin User id and password
return t.read_sysadmin(stub, args)
}
fmt.Println("query did not find func: " + function) //error
return nil, errors.New("Received unknown function query")
}
// ============================================================================================================================
// Read - read a variable from chaincode state
// ============================================================================================================================
func (t *SimpleChaincode) read(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var name, jsonResp string
var err error
if len(args) != 1 {
return nil, errors.New("Incorrect number of arguments. Expecting name of the var to query")
}
name = args[0]
valAsbytes, err := stub.GetState(name) //get the var from chaincode state
if err != nil {
jsonResp = "{\"Error\":\"Failed to get state for " + name + "\"}"
return nil, errors.New(jsonResp)
}
return valAsbytes, nil //send it onward
}
//=============================================================
// Read - query function to read key/value pair (System Admin read User id and Password)
//===============================================================================================================================
func (t *SimpleChaincode) read_sysadmin(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var err error
if len(args) != 1 {
return nil, errors.New("Incorrect number of arguments. Expecting name of the key to query")
}
userid := args[0]
PassAsbytes, err := stub.GetState(userid)
if err != nil {
jsonResp := "{\"Error\":\"Failed to get state for " + userid + "\"}"
return nil, errors.New(jsonResp)
}
res := Adminlogin{}
json.Unmarshal(PassAsbytes,&res)
if res.Userid == userid{
fmt.Println("Userid Password Matched: " +res.Userid + res.Password)
}else {
fmt.Println("Wrong ID Password: " +res.Userid + res.Password)
}
return PassAsbytes, nil
}
// ============================================================================================================================
// Delete - remove a key/value pair from state
// ============================================================================================================================
func (t *SimpleChaincode) Delete(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
if len(args) != 1 {
return nil, errors.New("Incorrect number of arguments. Expecting 1")
}
name := args[0]
err := stub.DelState(name) //remove the key from chaincode state
if err != nil {
return nil, errors.New("Failed to delete state")
}
//get the marble index
marblesAsBytes, err := stub.GetState(marbleIndexStr)
if err != nil {
return nil, errors.New("Failed to get marble index")
}
var marbleIndex []string
json.Unmarshal(marblesAsBytes, &marbleIndex) //un stringify it aka JSON.parse()
//remove marble from index
for i,val := range marbleIndex{
fmt.Println(strconv.Itoa(i) + " - looking at " + val + " for " + name)
if val == name{ //find the correct marble
fmt.Println("found marble")
marbleIndex = append(marbleIndex[:i], marbleIndex[i+1:]...) //remove it
for x:= range marbleIndex{ //debug prints...
fmt.Println(string(x) + " - " + marbleIndex[x])
}
break
}
}
jsonAsBytes, _ := json.Marshal(marbleIndex) //save new index
err = stub.PutState(marbleIndexStr, jsonAsBytes)
return nil, nil
}
// ============================================================================================================================
// Write - write variable into chaincode state
// ============================================================================================================================
func (t *SimpleChaincode) Write(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var name, value string // Entities
var err error
fmt.Println("running write()")
if len(args) != 2 {
return nil, errors.New("Incorrect number of arguments. Expecting 2. name of the variable and value to set")
}
name = args[0] //rename for funsies
value = args[1]
err = stub.PutState(name, []byte(value)) //write the variable into the chaincode state
if err != nil {
return nil, err
}
return nil, nil
}
// ============================================================================================================================
// Init Marble - create a new marble, store into chaincode state
// ============================================================================================================================
func (t *SimpleChaincode) init_marble(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var err error
// 0 1 2 3
// "asdf", "blue", "35", "bob"
if len(args) != 4 {
return nil, errors.New("Incorrect number of arguments. Expecting 4")
}
fmt.Println("-Amit C code-Init_marble driver")
//input sanitation
fmt.Println("- start init marble")
if len(args[0]) <= 0 {
return nil, errors.New("1st argument must be a non-empty string")
}
if len(args[1]) <= 0 {
return nil, errors.New("2nd argument must be a non-empty string")
}
if len(args[2]) <= 0 {
return nil, errors.New("3rd argument must be a non-empty string")
}
if len(args[3]) <= 0 {
return nil, errors.New("4th argument must be a non-empty string")
}
name := args[0]
color := strings.ToLower(args[1])
user := strings.ToLower(args[3])
size, err := strconv.Atoi(args[2])
if err != nil {
return nil, errors.New("3rd argument must be a numeric string")
}
//check if marble already exists
marbleAsBytes, err := stub.GetState(name)
if err != nil {
return nil, errors.New("Failed to get marble name")
}
res := Marble{}
json.Unmarshal(marbleAsBytes, &res)
if res.Name == name{
fmt.Println("This marble arleady exists: " + name)
fmt.Println(res);
return nil, errors.New("This marble arleady exists") //all stop a marble by this name exists
}
//build the marble json string manually
str := `{"name": "` + name + `", "color": "` + color + `", "size": ` + strconv.Itoa(size) + `, "user": "` + user + `"}`
err = stub.PutState(name, []byte(str)) //store marble with id as key
if err != nil {
return nil, err
}
//get the marble index
marblesAsBytes, err := stub.GetState(marbleIndexStr)
if err != nil {
return nil, errors.New("Failed to get marble index")
}
var marbleIndex []string
json.Unmarshal(marblesAsBytes, &marbleIndex) //un stringify it aka JSON.parse()
//append
marbleIndex = append(marbleIndex, name) //add marble name to index list
fmt.Println("! marble index: ", marbleIndex)
jsonAsBytes, _ := json.Marshal(marbleIndex)
err = stub.PutState(marbleIndexStr, jsonAsBytes) //store name of marble
fmt.Println("- end init marble")
return nil, nil
}
// ============================================================================================================================
// Init Marble - create a new marble, store into chaincode state
// ============================================================================================================================
func (t *SimpleChaincode) signup_driver(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var err error
// 0 1 2 3
// "Mainak", "Mandal", "mainakmandal@hotmail.com", "password"
if len(args) != 9 {
return nil, errors.New("Incorrect number of arguments. Expecting 4")
}
//input sanitation
fmt.Println("- start signup driver")
fmt.Println("-Amit C code-signup driver")
if len(args[0]) <= 0 {
return nil, errors.New("1st argument must be a non-empty string")
}
if len(args[1]) <= 0 {
return nil, errors.New("2nd argument must be a non-empty string")
}
if len(args[2]) <= 0 {
return nil, errors.New("3rd argument must be a non-empty string")
}
if len(args[3]) <= 0 {
return nil, errors.New("4th argument must be a non-empty string")
}
if len(args[4]) <= 0 {
return nil, errors.New("5th argument must be a non-empty string")
}
if len(args[5]) <= 0 {
return nil, errors.New("6th argument must be a non-empty string")
}
if len(args[6]) <= 0 {
return nil, errors.New("7th argument must be a non-empty string")
}
if len(args[7]) <= 0 {
return nil, errors.New("8th argument must be a non-empty string")
}
if len(args[8]) <= 0 {
return nil, errors.New("9th argument must be a non-empty string")
}
firstname := args[0]
lastname := strings.ToLower(args[1])
email := strings.ToLower(args[2])
mobile := strings.ToLower(args[3])
password := strings.ToLower(args[4])
street := strings.ToLower(args[5])
city := strings.ToLower(args[6])
state := strings.ToLower(args[7])
zip := strings.ToLower(args[8])
status := "P"
//if err != nil {
//return nil, errors.New("3rd argument must be a numeric string")
//}
//check if marble already exists
driverAsBytes, err := stub.GetState(email)
if err != nil {
return nil, errors.New("Failed to get driver name")
}
res := Driver{}
json.Unmarshal(driverAsBytes, &res)
if res.Email == email{
fmt.Println("This marble arleady exists: " + email)
fmt.Println(res);
return nil, errors.New("This driver arleady exists") //all stop a marble by this name exists
}
//build the marble json string manually
str := `{"firstname": "` + firstname + `", "lastname": "` + lastname + `", "email": "` + email + `", "mobile": "` + mobile + `", "password": "` + password + `","street": "` + street + `","city": "` + city + `","state": "` + state + `","zip": "` + zip + `","status": "` + status + `"}`
err = stub.PutState(email, []byte(str)) //store marble with id as key
if err != nil {
return nil, err
}
//get the driver index
driversAsBytes, err := stub.GetState(driverIndexStr)
if err != nil {
return nil, errors.New("Failed to get driver index")
}
var driverIndex []string
json.Unmarshal(driversAsBytes, &driverIndex) //un stringify it aka JSON.parse()
//append
driverIndex = append(driverIndex, email) //add marble name to index list
fmt.Println("! driver index: ", driverIndex)
jsonAsBytes, _ := json.Marshal(driverIndex)
err = stub.PutState(driverIndexStr, jsonAsBytes) //store name of marble
fmt.Println("- end signup driver")
return nil, nil
}
// ============================================================================================================================
// Set User Permission on Marble
// ============================================================================================================================
func (t *SimpleChaincode) set_user(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var err error
// 0 1
// "name", "bob"
if len(args) < 2 {
return nil, errors.New("Incorrect number of arguments. Expecting 2")
}
fmt.Println("- start set user")
fmt.Println(args[0] + " - " + args[1])
marbleAsBytes, err := stub.GetState(args[0])
if err != nil {
return nil, errors.New("Failed to get thing")
}
res := Marble{}
json.Unmarshal(marbleAsBytes, &res) //un stringify it aka JSON.parse()
res.User = args[1] //change the user
jsonAsBytes, _ := json.Marshal(res)
err = stub.PutState(args[0], jsonAsBytes) //rewrite the marble with id as key
if err != nil {
return nil, err
}
fmt.Println("- end set user")
return nil, nil
}
// ============================================================================================================================
// Set User Permission on Marble
// ============================================================================================================================
func (t *SimpleChaincode) set_status(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var err error
// 0 1
// "email", "status"
if len(args) < 10 {
return nil, errors.New("Incorrect number of arguments. Expecting 2")
}
fmt.Println("- start set user")
fmt.Println(args[0] + " - " + args[1])
driverAsBytes, err := stub.GetState(args[0])
if err != nil {
return nil, errors.New("Failed to get driver name")
}
res := Driver{}
json.Unmarshal(driverAsBytes, &res)
res.FirstName = args[1] //change the user
res.LastName = args[2]
res.Mobile = args[3]
res.Password = args[4]
res.Street = args[5]
res.City = args[6]
res.State = args[7]
res.Zip = args[8]
res.Status = args[9]
jsonAsBytes, _ := json.Marshal(res)
err = stub.PutState(args[0], jsonAsBytes) //rewrite the user status with email-id as key
if err != nil {
return nil, err
}
fmt.Println("- end set user")
return nil, nil
}
// ============================================================================================================================
// Open Trade - create an open trade for a marble you want with marbles you have
// ============================================================================================================================
func (t *SimpleChaincode) open_trade(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var err error
var will_size int
var trade_away Description
// 0 1 2 3 4 5 6
//["bob", "blue", "16", "red", "16"] *"blue", "35*
if len(args) < 5 {
return nil, errors.New("Incorrect number of arguments. Expecting like 5?")
}
if len(args)%2 == 0{
return nil, errors.New("Incorrect number of arguments. Expecting an odd number")
}
size1, err := strconv.Atoi(args[2])
if err != nil {
return nil, errors.New("3rd argument must be a numeric string")
}
open := AnOpenTrade{}
open.User = args[0]
open.Timestamp = makeTimestamp() //use timestamp as an ID
open.Want.Color = args[1]
open.Want.Size = size1
fmt.Println("- start open trade")
jsonAsBytes, _ := json.Marshal(open)
err = stub.PutState("_debug1", jsonAsBytes)
for i:=3; i < len(args); i++ { //create and append each willing trade
will_size, err = strconv.Atoi(args[i + 1])
if err != nil {
msg := "is not a numeric string " + args[i + 1]
fmt.Println(msg)
return nil, errors.New(msg)
}
trade_away = Description{}
trade_away.Color = args[i]
trade_away.Size = will_size
fmt.Println("! created trade_away: " + args[i])
jsonAsBytes, _ = json.Marshal(trade_away)
err = stub.PutState("_debug2", jsonAsBytes)
open.Willing = append(open.Willing, trade_away)
fmt.Println("! appended willing to open")
i++;
}
//get the open trade struct
tradesAsBytes, err := stub.GetState(openTradesStr)
if err != nil {
return nil, errors.New("Failed to get opentrades")
}
var trades AllTrades
json.Unmarshal(tradesAsBytes, &trades) //un stringify it aka JSON.parse()
trades.OpenTrades = append(trades.OpenTrades, open); //append to open trades
fmt.Println("! appended open to trades")
jsonAsBytes, _ = json.Marshal(trades)
err = stub.PutState(openTradesStr, jsonAsBytes) //rewrite open orders
if err != nil {
return nil, err
}
fmt.Println("- end open trade")
return nil, nil
}
// ============================================================================================================================
// Perform Trade - close an open trade and move ownership
// ============================================================================================================================
func (t *SimpleChaincode) perform_trade(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var err error
// 0 1 2 3 4 5
//[data.id, data.closer.user, data.closer.name, data.opener.user, data.opener.color, data.opener.size]
if len(args) < 6 {
return nil, errors.New("Incorrect number of arguments. Expecting 6")
}
fmt.Println("- start close trade")
timestamp, err := strconv.ParseInt(args[0], 10, 64)
if err != nil {
return nil, errors.New("1st argument must be a numeric string")
}
size, err := strconv.Atoi(args[5])
if err != nil {
return nil, errors.New("6th argument must be a numeric string")
}
//get the open trade struct
tradesAsBytes, err := stub.GetState(openTradesStr)
if err != nil {
return nil, errors.New("Failed to get opentrades")
}
var trades AllTrades
json.Unmarshal(tradesAsBytes, &trades) //un stringify it aka JSON.parse()
for i := range trades.OpenTrades{ //look for the trade
fmt.Println("looking at " + strconv.FormatInt(trades.OpenTrades[i].Timestamp, 10) + " for " + strconv.FormatInt(timestamp, 10))
if trades.OpenTrades[i].Timestamp == timestamp{
fmt.Println("found the trade");
marbleAsBytes, err := stub.GetState(args[2])
if err != nil {
return nil, errors.New("Failed to get thing")
}
closersMarble := Marble{}
json.Unmarshal(marbleAsBytes, &closersMarble) //un stringify it aka JSON.parse()
//verify if marble meets trade requirements
if closersMarble.Color != trades.OpenTrades[i].Want.Color || closersMarble.Size != trades.OpenTrades[i].Want.Size {
msg := "marble in input does not meet trade requriements"
fmt.Println(msg)
return nil, errors.New(msg)
}
marble, e := findMarble4Trade(stub, trades.OpenTrades[i].User, args[4], size) //find a marble that is suitable from opener
if(e == nil){
fmt.Println("! no errors, proceeding")
t.set_user(stub, []string{args[2], trades.OpenTrades[i].User}) //change owner of selected marble, closer -> opener
t.set_user(stub, []string{marble.Name, args[1]}) //change owner of selected marble, opener -> closer
trades.OpenTrades = append(trades.OpenTrades[:i], trades.OpenTrades[i+1:]...) //remove trade
jsonAsBytes, _ := json.Marshal(trades)
err = stub.PutState(openTradesStr, jsonAsBytes) //rewrite open orders
if err != nil {
return nil, err
}
}
}
}
fmt.Println("- end close trade")
return nil, nil
}
// ============================================================================================================================
// findMarble4Trade - look for a matching marble that this user owns and return it
// ============================================================================================================================
func findMarble4Trade(stub shim.ChaincodeStubInterface, user string, color string, size int )(m Marble, err error){
var fail Marble;
fmt.Println("- start find marble 4 trade")
fmt.Println("looking for " + user + ", " + color + ", " + strconv.Itoa(size));
//get the marble index
marblesAsBytes, err := stub.GetState(marbleIndexStr)
if err != nil {
return fail, errors.New("Failed to get marble index")
}
var marbleIndex []string
json.Unmarshal(marblesAsBytes, &marbleIndex) //un stringify it aka JSON.parse()
for i:= range marbleIndex{ //iter through all the marbles
//fmt.Println("looking @ marble name: " + marbleIndex[i]);
marbleAsBytes, err := stub.GetState(marbleIndex[i]) //grab this marble
if err != nil {
return fail, errors.New("Failed to get marble")
}
res := Marble{}
json.Unmarshal(marbleAsBytes, &res) //un stringify it aka JSON.parse()
//fmt.Println("looking @ " + res.User + ", " + res.Color + ", " + strconv.Itoa(res.Size));
//check for user && color && size
if strings.ToLower(res.User) == strings.ToLower(user) && strings.ToLower(res.Color) == strings.ToLower(color) && res.Size == size{
fmt.Println("found a marble: " + res.Name)
fmt.Println("! end find marble 4 trade")
return res, nil
}
}
fmt.Println("- end find marble 4 trade - error")
return fail, errors.New("Did not find marble to use in this trade")
}
// ============================================================================================================================
// Make Timestamp - create a timestamp in ms
// ============================================================================================================================
func makeTimestamp() int64 {
return time.Now().UnixNano() / (int64(time.Millisecond)/int64(time.Nanosecond))
}
// ============================================================================================================================
// Remove Open Trade - close an open trade
// ============================================================================================================================
func (t *SimpleChaincode) remove_trade(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var err error
// 0
//[data.id]
if len(args) < 1 {
return nil, errors.New("Incorrect number of arguments. Expecting 1")
}
fmt.Println("- start remove trade")
timestamp, err := strconv.ParseInt(args[0], 10, 64)
if err != nil {
return nil, errors.New("1st argument must be a numeric string")
}
//get the open trade struct
tradesAsBytes, err := stub.GetState(openTradesStr)
if err != nil {
return nil, errors.New("Failed to get opentrades")
}
var trades AllTrades
json.Unmarshal(tradesAsBytes, &trades) //un stringify it aka JSON.parse()
for i := range trades.OpenTrades{ //look for the trade
//fmt.Println("looking at " + strconv.FormatInt(trades.OpenTrades[i].Timestamp, 10) + " for " + strconv.FormatInt(timestamp, 10))
if trades.OpenTrades[i].Timestamp == timestamp{
fmt.Println("found the trade");
trades.OpenTrades = append(trades.OpenTrades[:i], trades.OpenTrades[i+1:]...) //remove this trade
jsonAsBytes, _ := json.Marshal(trades)
err = stub.PutState(openTradesStr, jsonAsBytes) //rewrite open orders
if err != nil {
return nil, err
}
break
}
}
fmt.Println("- end remove trade")
return nil, nil
}
// ============================================================================================================================
// Clean Up Open Trades - make sure open trades are still possible, remove choices that are no longer possible, remove trades that have no valid choices
// ============================================================================================================================
func cleanTrades(stub shim.ChaincodeStubInterface)(err error){
var didWork = false
fmt.Println("- start clean trades")
//get the open trade struct
tradesAsBytes, err := stub.GetState(openTradesStr)
if err != nil {
return errors.New("Failed to get opentrades")
}
var trades AllTrades
json.Unmarshal(tradesAsBytes, &trades) //un stringify it aka JSON.parse()
fmt.Println("# trades " + strconv.Itoa(len(trades.OpenTrades)))
for i:=0; i<len(trades.OpenTrades); { //iter over all the known open trades
fmt.Println(strconv.Itoa(i) + ": looking at trade " + strconv.FormatInt(trades.OpenTrades[i].Timestamp, 10))
fmt.Println("# options " + strconv.Itoa(len(trades.OpenTrades[i].Willing)))
for x:=0; x<len(trades.OpenTrades[i].Willing); { //find a marble that is suitable
fmt.Println("! on next option " + strconv.Itoa(i) + ":" + strconv.Itoa(x))
_, e := findMarble4Trade(stub, trades.OpenTrades[i].User, trades.OpenTrades[i].Willing[x].Color, trades.OpenTrades[i].Willing[x].Size)
if(e != nil){
fmt.Println("! errors with this option, removing option")
didWork = true
trades.OpenTrades[i].Willing = append(trades.OpenTrades[i].Willing[:x], trades.OpenTrades[i].Willing[x+1:]...) //remove this option
x--;
}else{
fmt.Println("! this option is fine")
}
x++
fmt.Println("! x:" + strconv.Itoa(x))
if x >= len(trades.OpenTrades[i].Willing) { //things might have shifted, recalcuate
break
}
}
if len(trades.OpenTrades[i].Willing) == 0 {
fmt.Println("! no more options for this trade, removing trade")
didWork = true
trades.OpenTrades = append(trades.OpenTrades[:i], trades.OpenTrades[i+1:]...) //remove this trade
i--;
}
i++
fmt.Println("! i:" + strconv.Itoa(i))
if i >= len(trades.OpenTrades) { //things might have shifted, recalcuate
break
}
}
if(didWork){
fmt.Println("! saving open trade changes")
jsonAsBytes, _ := json.Marshal(trades)
err = stub.PutState(openTradesStr, jsonAsBytes) //rewrite open orders
if err != nil {
return err
}
}else{
fmt.Println("! all open trades are fine")
}
fmt.Println("- end clean trades")
return nil
}
| mamandal/fleetchaincd | chaincode/marbles_chaincode.go | GO | apache-2.0 | 32,592 |
using XElement.DotNet.System.Environment.Startup;
namespace XElement.SDM.ManagementLogic
{
#region not unit-tested
internal abstract class AbstractProgramLogic : IProgramLogic
{
protected AbstractProgramLogic( IProgramInfo programInfo )
{
this._programInfo = programInfo;
}
public abstract void /*IProgramLogic.*/DelayStartup();
public void /*IProgramLogic.*/Do() { this.DelayStartup(); }
public abstract void /*IProgramLogic.*/PromoteStartup();
public void /*IProgramLogic.*/Undo() { this.PromoteStartup(); }
protected IProgramInfo _programInfo;
}
#endregion
}
| XElementDev/SDM | code/Startup/ManagementLogic.Implementation/AbstractProgramLogic.cs | C# | apache-2.0 | 661 |
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
<head>
<!-- NAME: 1 COLUMN -->
<!--[if gte mso 15]>
<xml>
<o:OfficeDocumentSettings>
<o:AllowPNG/>
<o:PixelsPerInch>96</o:PixelsPerInch>
</o:OfficeDocumentSettings>
</xml>
<![endif]-->
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Factuur</title>
<style type="text/css">
p{
margin:10px 0;
padding:0;
}
table{
border-collapse:collapse;
}
h1,h2,h3,h4,h5,h6{
display:block;
margin:0;
padding:0;
}
img,a img{
border:0;
height:auto;
outline:none;
text-decoration:none;
}
body,#bodyTable,#bodyCell{
height:100%;
margin:0;
padding:0;
width:100%;
}
#outlook a{
padding:0;
}
img{
-ms-interpolation-mode:bicubic;
}
table{
mso-table-lspace:0pt;
mso-table-rspace:0pt;
}
.ReadMsgBody{
width:100%;
}
.ExternalClass{
width:100%;
}
p,a,li,td,blockquote{
mso-line-height-rule:exactly;
}
a[href^=tel],a[href^=sms]{
color:inherit;
cursor:default;
text-decoration:none;
}
p,a,li,td,body,table,blockquote{
-ms-text-size-adjust:100%;
-webkit-text-size-adjust:100%;
}
.ExternalClass,.ExternalClass p,.ExternalClass td,.ExternalClass div,.ExternalClass span,.ExternalClass font{
line-height:100%;
}
a[x-apple-data-detectors]{
color:inherit !important;
text-decoration:none !important;
font-size:inherit !important;
font-family:inherit !important;
font-weight:inherit !important;
line-height:inherit !important;
}
#bodyCell{
padding:10px;
}
.templateContainer{
max-width:600px !important;
}
a.mcnButton{
display:block;
}
.mcnImage{
vertical-align:bottom;
}
.mcnTextContent{
word-break:break-word;
}
.mcnTextContent img{
height:auto !important;
}
.mcnDividerBlock{
table-layout:fixed !important;
}
body,#bodyTable{
background-color:#FAFAFA;
}
#bodyCell{
border-top:0;
}
.templateContainer{
border:0;
}
h1{
color:#202020;
font-family:Helvetica;
font-size:26px;
font-style:normal;
font-weight:bold;
line-height:125%;
letter-spacing:normal;
text-align:left;
}
h2{
color:#202020;
font-family:Helvetica;
font-size:22px;
font-style:normal;
font-weight:bold;
line-height:125%;
letter-spacing:normal;
text-align:left;
}
h3{
color:#202020;
font-family:Helvetica;
font-size:20px;
font-style:normal;
font-weight:bold;
line-height:125%;
letter-spacing:normal;
text-align:left;
}
h4{
color:#202020;
font-family:Helvetica;
font-size:18px;
font-style:normal;
font-weight:bold;
line-height:125%;
letter-spacing:normal;
text-align:left;
}
#templatePreheader{
background-color:#FAFAFA;
background-image:none;
background-repeat:no-repeat;
background-position:center;
background-size:cover;
border-top:0;
border-bottom:0;
padding-top:9px;
padding-bottom:9px;
}
#templatePreheader .mcnTextContent,#templatePreheader .mcnTextContent p{
color:#656565;
font-family:Helvetica;
font-size:12px;
line-height:150%;
text-align:left;
}
#templatePreheader .mcnTextContent a,#templatePreheader .mcnTextContent p a{
color:#656565;
font-weight:normal;
text-decoration:underline;
}
#templateHeader{
background-color:#FFFFFF;
background-image:none;
background-repeat:no-repeat;
background-position:center;
background-size:cover;
border-top:0;
border-bottom:0;
padding-top:9px;
padding-bottom:0;
}
#templateHeader .mcnTextContent,#templateHeader .mcnTextContent p{
color:#202020;
font-family:Helvetica;
font-size:16px;
line-height:150%;
text-align:left;
}
#templateHeader .mcnTextContent a,#templateHeader .mcnTextContent p a{
color:#2BAADF;
font-weight:normal;
text-decoration:underline;
}
#templateBody{
background-color:#FFFFFF;
background-image:none;
background-repeat:no-repeat;
background-position:center;
background-size:cover;
border-top:0;
border-bottom:2px solid #EAEAEA;
padding-top:0;
padding-bottom:9px;
}
#templateBody .mcnTextContent,#templateBody .mcnTextContent p{
color:#202020;
font-family:Helvetica;
font-size:16px;
line-height:150%;
text-align:left;
}
#templateBody .mcnTextContent a,#templateBody .mcnTextContent p a{
color:#2BAADF;
font-weight:normal;
text-decoration:underline;
}
#templateFooter{
background-color:#FAFAFA;
background-image:none;
background-repeat:no-repeat;
background-position:center;
background-size:cover;
border-top:0;
border-bottom:0;
padding-top:9px;
padding-bottom:9px;
}
#templateFooter .mcnTextContent,#templateFooter .mcnTextContent p{
color:#656565;
font-family:Helvetica;
font-size:12px;
line-height:150%;
text-align:center;
}
#templateFooter .mcnTextContent a,#templateFooter .mcnTextContent p a{
color:#656565;
font-weight:normal;
text-decoration:underline;
}
@media only screen and (min-width:768px){
.templateContainer{
width:600px !important;
}
} @media only screen and (max-width: 480px){
body,table,td,p,a,li,blockquote{
-webkit-text-size-adjust:none !important;
}
} @media only screen and (max-width: 480px){
body{
width:100% !important;
min-width:100% !important;
}
} @media only screen and (max-width: 480px){
#bodyCell{
padding-top:10px !important;
}
} @media only screen and (max-width: 480px){
.mcnImage{
width:100% !important;
}
} @media only screen and (max-width: 480px){
.mcnCartContainer,.mcnCaptionTopContent,.mcnRecContentContainer,.mcnCaptionBottomContent,.mcnTextContentContainer,.mcnBoxedTextContentContainer,.mcnImageGroupContentContainer,.mcnCaptionLeftTextContentContainer,.mcnCaptionRightTextContentContainer,.mcnCaptionLeftImageContentContainer,.mcnCaptionRightImageContentContainer,.mcnImageCardLeftTextContentContainer,.mcnImageCardRightTextContentContainer{
max-width:100% !important;
width:100% !important;
}
} @media only screen and (max-width: 480px){
.mcnBoxedTextContentContainer{
min-width:100% !important;
}
} @media only screen and (max-width: 480px){
.mcnImageGroupContent{
padding:9px !important;
}
} @media only screen and (max-width: 480px){
.mcnCaptionLeftContentOuter .mcnTextContent,.mcnCaptionRightContentOuter .mcnTextContent{
padding-top:9px !important;
}
} @media only screen and (max-width: 480px){
.mcnImageCardTopImageContent,.mcnCaptionBlockInner .mcnCaptionTopContent:last-child .mcnTextContent{
padding-top:18px !important;
}
} @media only screen and (max-width: 480px){
.mcnImageCardBottomImageContent{
padding-bottom:9px !important;
}
} @media only screen and (max-width: 480px){
.mcnImageGroupBlockInner{
padding-top:0 !important;
padding-bottom:0 !important;
}
} @media only screen and (max-width: 480px){
.mcnImageGroupBlockOuter{
padding-top:9px !important;
padding-bottom:9px !important;
}
} @media only screen and (max-width: 480px){
.mcnTextContent,.mcnBoxedTextContentColumn{
padding-right:18px !important;
padding-left:18px !important;
}
} @media only screen and (max-width: 480px){
.mcnImageCardLeftImageContent,.mcnImageCardRightImageContent{
padding-right:18px !important;
padding-bottom:0 !important;
padding-left:18px !important;
}
} @media only screen and (max-width: 480px){
.mcpreview-image-uploader{
display:none !important;
width:100% !important;
}
} @media only screen and (max-width: 480px){
h1{
font-size:22px !important;
line-height:125% !important;
}
} @media only screen and (max-width: 480px){
h2{
font-size:20px !important;
line-height:125% !important;
}
} @media only screen and (max-width: 480px){
h3{
font-size:18px !important;
line-height:125% !important;
}
} @media only screen and (max-width: 480px){
h4{
font-size:16px !important;
line-height:150% !important;
}
} @media only screen and (max-width: 480px){
.mcnBoxedTextContentContainer .mcnTextContent,.mcnBoxedTextContentContainer .mcnTextContent p{
font-size:14px !important;
line-height:150% !important;
}
} @media only screen and (max-width: 480px){
#templatePreheader{
display:block !important;
}
} @media only screen and (max-width: 480px){
#templatePreheader .mcnTextContent,#templatePreheader .mcnTextContent p{
font-size:14px !important;
line-height:150% !important;
}
} @media only screen and (max-width: 480px){
#templateHeader .mcnTextContent,#templateHeader .mcnTextContent p{
font-size:16px !important;
line-height:150% !important;
}
} @media only screen and (max-width: 480px){
#templateBody .mcnTextContent,#templateBody .mcnTextContent p{
font-size:16px !important;
line-height:150% !important;
}
} @media only screen and (max-width: 480px){
#templateFooter .mcnTextContent,#templateFooter .mcnTextContent p{
font-size:14px !important;
line-height:150% !important;
}
}</style></head>
<body style="height: 100%;margin: 0;padding: 0;width: 100%;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;background-color: #FAFAFA;">
<center>
<table align="center" border="0" cellpadding="0" cellspacing="0" height="100%" width="100%" id="bodyTable" style="border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;height: 100%;margin: 0;padding: 0;width: 100%;background-color: #FAFAFA;">
<tr>
<td align="center" valign="top" id="bodyCell" style="mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;height: 100%;margin: 0;padding: 10px;width: 100%;border-top: 0;">
<!-- BEGIN TEMPLATE // -->
<!--[if gte mso 9]>
<table align="center" border="0" cellspacing="0" cellpadding="0" width="600" style="width:600px;">
<tr>
<td align="center" valign="top" width="600" style="width:600px;">
<![endif]-->
<table border="0" cellpadding="0" cellspacing="0" width="100%" class="templateContainer" style="border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;border: 0;max-width: 600px !important;">
<tr>
<td valign="top" id="templatePreheader" style="background:#FAFAFA none no-repeat center/cover;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;background-color: #FAFAFA;background-image: none;background-repeat: no-repeat;background-position: center;background-size: cover;border-top: 0;border-bottom: 0;padding-top: 9px;padding-bottom: 9px;"><table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnTextBlock" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody class="mcnTextBlockOuter">
<tr>
<td valign="top" class="mcnTextBlockInner" style="padding-top: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<!--[if mso]>
<table align="left" border="0" cellspacing="0" cellpadding="0" width="100%" style="width:100%;">
<tr>
<![endif]-->
<!--[if mso]>
<td valign="top" width="390" style="width:390px;">
<![endif]-->
<table align="left" border="0" cellpadding="0" cellspacing="0" style="max-width: 390px;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" width="100%" class="mcnTextContentContainer">
<tbody><tr>
<td valign="top" class="mcnTextContent" style="padding-top: 0;padding-left: 18px;padding-bottom: 9px;padding-right: 18px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;word-break: break-word;color: #656565;font-family: Helvetica;font-size: 12px;line-height: 150%;text-align: left;">
Factuur Hippiemarkt Aalsmeer
</td>
</tr>
</tbody></table>
<!--[if mso]>
</td>
<![endif]-->
<!--[if mso]>
<td valign="top" width="210" style="width:210px;">
<![endif]-->
<table align="left" border="0" cellpadding="0" cellspacing="0" style="max-width: 210px;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" width="100%" class="mcnTextContentContainer">
<tbody><tr>
<td valign="top" class="mcnTextContent" style="padding-top: 0;padding-left: 18px;padding-bottom: 9px;padding-right: 18px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;word-break: break-word;color: #656565;font-family: Helvetica;font-size: 12px;line-height: 150%;text-align: left;">
<a href="http://app.directevents.nl/mail/view/hippiemarkt-aalsmeer-factuur" target="_blank" style="mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;color: #656565;font-weight: normal;text-decoration: underline;">Mail niet leesbaar of graag in uw browser openen? Klik hier.</a>
</td>
</tr>
</tbody></table>
<!--[if mso]>
</td>
<![endif]-->
<!--[if mso]>
</tr>
</table>
<![endif]-->
</td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td valign="top" id="templateHeader" style="background:#FFFFFF none no-repeat center/cover;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;background-color: #FFFFFF;background-image: none;background-repeat: no-repeat;background-position: center;background-size: cover;border-top: 0;border-bottom: 0;padding-top: 9px;padding-bottom: 0;"><table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnImageBlock" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody class="mcnImageBlockOuter">
<tr>
<td valign="top" style="padding: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" class="mcnImageBlockInner">
<table align="left" width="100%" border="0" cellpadding="0" cellspacing="0" class="mcnImageContentContainer" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody><tr>
<td class="mcnImageContent" valign="top" style="padding-right: 9px;padding-left: 9px;padding-top: 0;padding-bottom: 0;text-align: center;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<img align="center" alt="" src="http://app.directevents.nl/assets/img/hippiemarkt-aalsmeer/mail-header.png" width="564" style="max-width: 799px;padding-bottom: 0;display: inline !important;vertical-align: bottom;border: 0;height: auto;outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;" class="mcnImage">
</td>
</tr>
</tbody></table>
</td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td valign="top" id="templateBody" style="background:#FFFFFF none no-repeat center/cover;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;background-color: #FFFFFF;background-image: none;background-repeat: no-repeat;background-position: center;background-size: cover;border-top: 0;border-bottom: 2px solid #EAEAEA;padding-top: 0;padding-bottom: 9px;"><table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnTextBlock" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody class="mcnTextBlockOuter">
<tr>
<td valign="top" class="mcnTextBlockInner" style="padding-top: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<!--[if mso]>
<table align="left" border="0" cellspacing="0" cellpadding="0" width="100%" style="width:100%;">
<tr>
<![endif]-->
<!--[if mso]>
<td valign="top" width="600" style="width:600px;">
<![endif]-->
<table align="left" border="0" cellpadding="0" cellspacing="0" style="max-width: 100%;min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" width="100%" class="mcnTextContentContainer">
<tbody><tr>
<td valign="top" class="mcnTextContent" style="padding-top: 0;padding-right: 18px;padding-bottom: 9px;padding-left: 18px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;word-break: break-word;color: #202020;font-family: Helvetica;font-size: 16px;line-height: 150%;text-align: left;">
<h1 style="display: block;margin: 0;padding: 0;color: #202020;font-family: Helvetica;font-size: 26px;font-style: normal;font-weight: bold;line-height: 125%;letter-spacing: normal;text-align: left;">Factuur Hippiemarkt Aalsmeer</h1>
<p style="margin: 10px 0;padding: 0;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;color: #202020;font-family: Helvetica;font-size: 16px;line-height: 150%;text-align: left;">Beste Standhouder,<br>
<br>
Bedankt voor uw inschrijving voor De Hippiemarkt Aalsmeer op vrijdag 27 juli.<br>
<br>
Wij zijn enorm druk met alle voorbereidingen om de markt tot een succes te laten verlopen. In de bijlage sturen wij de algemene voorwaarden (met onder andere opbouw en afbouw tijden) en de factuur.<br>
<br>
Pas na ontvangst van uw betaling is uw inschrijving definitief.<br>
<br>
Tot vrijdag 27 juli op het surfeiland te Aalsmeer,<br>
<br>
Contact informatie:<br>
Info@directevents.nl<br>
</p>
</td>
</tr>
</tbody></table>
<!--[if mso]>
</td>
<![endif]-->
<!--[if mso]>
</tr>
</table>
<![endif]-->
</td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td valign="top" id="templateFooter" style="background:#FAFAFA none no-repeat center/cover;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;background-color: #FAFAFA;background-image: none;background-repeat: no-repeat;background-position: center;background-size: cover;border-top: 0;border-bottom: 0;padding-top: 9px;padding-bottom: 9px;"><table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnImageBlock" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody class="mcnImageBlockOuter">
<tr>
<td valign="top" style="padding: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" class="mcnImageBlockInner">
<table align="left" width="100%" border="0" cellpadding="0" cellspacing="0" class="mcnImageContentContainer" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody><tr>
<td class="mcnImageContent" valign="top" style="padding-right: 9px;padding-left: 9px;padding-top: 0;padding-bottom: 0;text-align: center;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<img align="center" alt="" src="https://gallery.mailchimp.com/042b4e4809d32ad5aa6147613/images/0bbee562-e766-4dda-83ca-4474a23a419b.png" width="564" style="max-width: 975px;padding-bottom: 0;display: inline !important;vertical-align: bottom;border: 0;height: auto;outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;" class="mcnImage">
</td>
</tr>
</tbody></table>
</td>
</tr>
</tbody>
</table><table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnFollowBlock" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody class="mcnFollowBlockOuter">
<tr>
<td align="center" valign="top" style="padding: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" class="mcnFollowBlockInner">
<table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnFollowContentContainer" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody><tr>
<td align="center" style="padding-left: 9px;padding-right: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<table border="0" cellpadding="0" cellspacing="0" width="100%" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" class="mcnFollowContent">
<tbody><tr>
<td align="center" valign="top" style="padding-top: 9px;padding-right: 9px;padding-left: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<table align="center" border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody><tr>
<td align="center" valign="top" style="mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<!--[if mso]>
<table align="center" border="0" cellspacing="0" cellpadding="0">
<tr>
<![endif]-->
<!--[if mso]>
<td align="center" valign="top">
<![endif]-->
<table align="left" border="0" cellpadding="0" cellspacing="0" style="display: inline;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody><tr>
<td valign="top" style="padding-right: 10px;padding-bottom: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" class="mcnFollowContentItemContainer">
<table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnFollowContentItem" style="border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody><tr>
<td align="left" valign="middle" style="padding-top: 5px;padding-right: 10px;padding-bottom: 5px;padding-left: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<table align="left" border="0" cellpadding="0" cellspacing="0" width="" style="border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody><tr>
<td align="center" valign="middle" width="24" class="mcnFollowIconContent" style="mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<a href="https://www.facebook.com/events/434974326975583/" target="_blank" style="mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"><img src="https://cdn-images.mailchimp.com/icons/social-block-v2/color-facebook-48.png" style="display: block;border: 0;height: auto;outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;" height="24" width="24" class=""></a>
</td>
</tr>
</tbody></table>
</td>
</tr>
</tbody></table>
</td>
</tr>
</tbody></table>
<!--[if mso]>
</td>
<![endif]-->
<!--[if mso]>
<td align="center" valign="top">
<![endif]-->
<table align="left" border="0" cellpadding="0" cellspacing="0" style="display: inline;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody><tr>
<td valign="top" style="padding-right: 0;padding-bottom: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" class="mcnFollowContentItemContainer">
<table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnFollowContentItem" style="border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody><tr>
<td align="left" valign="middle" style="padding-top: 5px;padding-right: 10px;padding-bottom: 5px;padding-left: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<table align="left" border="0" cellpadding="0" cellspacing="0" width="" style="border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody><tr>
<td align="center" valign="middle" width="24" class="mcnFollowIconContent" style="mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<a href="http://www.hippiemarktaalsmeer.nl/" target="_blank" style="mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"><img src="https://cdn-images.mailchimp.com/icons/social-block-v2/color-link-48.png" style="display: block;border: 0;height: auto;outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;" height="24" width="24" class=""></a>
</td>
</tr>
</tbody></table>
</td>
</tr>
</tbody></table>
</td>
</tr>
</tbody></table>
<!--[if mso]>
</td>
<![endif]-->
<!--[if mso]>
</tr>
</table>
<![endif]-->
</td>
</tr>
</tbody></table>
</td>
</tr>
</tbody></table>
</td>
</tr>
</tbody></table>
</td>
</tr>
</tbody>
</table><table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnDividerBlock" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;table-layout: fixed !important;">
<tbody class="mcnDividerBlockOuter">
<tr>
<td class="mcnDividerBlockInner" style="min-width: 100%;padding: 10px 18px 25px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<table class="mcnDividerContent" border="0" cellpadding="0" cellspacing="0" width="100%" style="min-width: 100%;border-top-width: 2px;border-top-style: solid;border-top-color: #EEEEEE;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody><tr>
<td style="mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<span></span>
</td>
</tr>
</tbody></table>
<!--
<td class="mcnDividerBlockInner" style="padding: 18px;">
<hr class="mcnDividerContent" style="border-bottom-color:none; border-left-color:none; border-right-color:none; border-bottom-width:0; border-left-width:0; border-right-width:0; margin-top:0; margin-right:0; margin-bottom:0; margin-left:0;" />
-->
</td>
</tr>
</tbody>
</table><table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnTextBlock" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody class="mcnTextBlockOuter">
<tr>
<td valign="top" class="mcnTextBlockInner" style="padding-top: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<!--[if mso]>
<table align="left" border="0" cellspacing="0" cellpadding="0" width="100%" style="width:100%;">
<tr>
<![endif]-->
<!--[if mso]>
<td valign="top" width="600" style="width:600px;">
<![endif]-->
<table align="left" border="0" cellpadding="0" cellspacing="0" style="max-width: 100%;min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" width="100%" class="mcnTextContentContainer">
<tbody><tr>
<td valign="top" class="mcnTextContent" style="padding-top: 0;padding-right: 18px;padding-bottom: 9px;padding-left: 18px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;word-break: break-word;color: #656565;font-family: Helvetica;font-size: 12px;line-height: 150%;text-align: center;">
<em>Copyright © 2017 Direct Events, All rights reserved.</em><br>
<br>
info@directevents.nl<br></td>
</tr>
</tbody></table>
<!--[if mso]>
</td>
<![endif]-->
<!--[if mso]>
</tr>
</table>
<![endif]-->
</td>
</tr>
</tbody>
</table></td>
</tr>
</table>
<!--[if gte mso 9]>
</td>
</tr>
</table>
<![endif]-->
<!-- // END TEMPLATE -->
</td>
</tr>
</table>
</center>
<center>
<style type="text/css">
@media only screen and (max-width: 480px){
table#canspamBar td{font-size:14px !important;}
table#canspamBar td a{display:block !important; margin-top:10px !important;}
}
</style>
</center></body>
</html>
| directonlijn/app | app/resources/views/emails/hippiemarkt-aalsmeer-factuur.blade.php | PHP | apache-2.0 | 34,222 |
(function() {
'use strict';
angular
.module('gastronomeeApp')
.controller('MenuDeleteController',MenuDeleteController);
MenuDeleteController.$inject = ['$uibModalInstance', 'entity', 'Menu'];
function MenuDeleteController($uibModalInstance, entity, Menu) {
var vm = this;
vm.menu = entity;
vm.clear = clear;
vm.confirmDelete = confirmDelete;
function clear () {
$uibModalInstance.dismiss('cancel');
}
function confirmDelete (id) {
Menu.delete({id: id},
function () {
$uibModalInstance.close(true);
});
}
}
})();
| goxhaj/gastronomee | src/main/webapp/app/dashboard/menu/menu-delete-dialog.controller.js | JavaScript | apache-2.0 | 694 |
/*
* Copyright (C) 2019 Google 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 com.google.gapid.perfetto.models;
import static com.google.gapid.util.MoreFutures.logFailure;
import static com.google.gapid.util.MoreFutures.transform;
import static com.google.gapid.util.MoreFutures.transformAsync;
import static com.google.gapid.util.Scheduler.EXECUTOR;
import static java.util.concurrent.TimeUnit.MICROSECONDS;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import com.google.common.cache.Cache;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.gapid.perfetto.TimeSpan;
import com.google.gapid.util.Caches;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.logging.Logger;
// Note on multi-threading issues here:
// Because of how the window tables work, the below computeData(..) calls have to be serialized
// by track. That is, data for different requests can not be fetched in parallel. Thus, the calls
// to computeData(..) are funneled through the getDataLock semaphore. Care needs to be taken not to
// block the executor threads indefinitely, as otherwise a deadlock could occur, due to the results
// of the query futures no longer being able to be executed. Thus, the semaphore is try-acquired
// with a short timeout, followed by a slightly longer wait, before retrying.
/**
* A {@link Track} is responsible for loading the data to be shown in the UI.
*/
public abstract class Track<D extends Track.Data> {
private static final Logger LOG = Logger.getLogger(Track.class.getName());
public static final long QUANTIZE_CUT_OFF = 2000;
private static final long REQUEST_DELAY_MS = 50;
private static final long ACQUIRE_TIMEOUT_MS = 5;
private static final long ACQUIRE_RETRY_MS = 10;
private static final long PAGE_SIZE = 3600;
private static DataCache cache = new DataCache();
private final String trackId;
private D data;
private ListenableFuture<?> scheduledFuture;
// Set to null on any thread, set to non-null only on the UI thread.
private final AtomicReference<ScheduledRequest<D>> scheduledRequest =
new AtomicReference<ScheduledRequest<D>>(null);
private final Semaphore getDataLock = new Semaphore(1);
private boolean initialized; // guarded by getDataLock
public Track(String trackId) {
this.trackId = trackId.replace("-", "_");
}
public String getId() {
return trackId;
}
// on UI Thread
public D getData(DataRequest req, OnUiThread<D> onUiThread) {
if (checkScheduledRequest(req, onUiThread) && (data == null || !data.request.satisfies(req))) {
schedule(req.pageAlign(), onUiThread);
}
return data;
}
// on UI Thread. returns true, if a new request may be scheduled.
private boolean checkScheduledRequest(DataRequest req, OnUiThread<D> callback) {
ScheduledRequest<D> scheduled = scheduledRequest.get();
if (scheduled == null) {
return true;
} else if (scheduled.satisfies(req)) {
scheduled.addCallback(callback);
return false;
}
scheduledFuture.cancel(true);
scheduledFuture = null;
scheduledRequest.set(null);
return true;
}
// on UI Thread
private void schedule(DataRequest request, OnUiThread<D> onUiThread) {
D newData = cache.getIfPresent(this, request);
if (newData != null) {
data = newData;
return;
}
ScheduledRequest<D> scheduled = new ScheduledRequest<D>(request, onUiThread);
scheduledRequest.set(scheduled);
scheduledFuture = EXECUTOR.schedule(
() -> query(scheduled), REQUEST_DELAY_MS, MILLISECONDS);
}
// *not* on UI Thread
private void query(ScheduledRequest<D> scheduled) {
try {
if (!getDataLock.tryAcquire(ACQUIRE_TIMEOUT_MS, MILLISECONDS)) {
logFailure(LOG, EXECUTOR.schedule(
() -> query(scheduled), ACQUIRE_RETRY_MS, MILLISECONDS));
return;
}
} catch (InterruptedException e) {
// We were cancelled while waiting on the lock.
scheduledRequest.compareAndSet(scheduled, null);
return;
}
if (scheduledRequest.get() != scheduled) {
getDataLock.release();
return;
}
try {
ListenableFuture<D> future = transformAsync(setup(), $ -> computeData(scheduled.request));
scheduled.scheduleCallbacks(future, newData -> update(scheduled, newData));
// Always unlock when the future completes/fails/is cancelled.
future.addListener(getDataLock::release, EXECUTOR);
} catch (RuntimeException e) {
getDataLock.release();
throw e;
}
}
// on UI Thread
private void update(ScheduledRequest<D> scheduled, D newData) {
cache.put(this, scheduled.request, newData);
if (scheduledRequest.compareAndSet(scheduled, null)) {
data = newData;
scheduledFuture = null;
}
}
private ListenableFuture<?> setup() {
if (initialized) {
return Futures.immediateFuture(null);
}
return transform(initialize(), $ -> initialized = true);
}
protected abstract ListenableFuture<?> initialize();
protected abstract ListenableFuture<D> computeData(DataRequest req);
protected String tableName(String prefix) {
return prefix + "_" + trackId;
}
public static interface OnUiThread<T> {
/**
* Runs the consumer with the result of the given future on the UI thread.
*/
public void onUiThread(ListenableFuture<T> future, Consumer<T> callback);
public void repaint();
}
public static class Data {
public final DataRequest request;
public Data(DataRequest request) {
this.request = request;
}
}
public static class DataRequest {
public final TimeSpan range;
public final long resolution;
public DataRequest(TimeSpan range, long resolution) {
this.range = range;
this.resolution = resolution;
}
public DataRequest pageAlign() {
return new DataRequest(range.align(PAGE_SIZE * resolution), resolution);
}
public boolean satisfies(DataRequest other) {
return resolution == other.resolution && range.contains(other.range);
}
@Override
public String toString() {
return "Request{start: " + range.start + ", end: " + range.end + ", res: " + resolution + "}";
}
}
public static class Window {
private static final long RESOLUTION_QUANTIZE_CUTOFF = MICROSECONDS.toNanos(80);
private static final String UPDATE_SQL = "update %s set " +
"window_start = %d, window_dur = %d, quantum = %d where rowid = 0";
public final long start;
public final long end;
public final boolean quantized;
public final long bucketSize;
private Window(long start, long end, boolean quantized, long bucketSize) {
this.start = start;
this.end = end;
this.quantized = quantized;
this.bucketSize = bucketSize;
}
public static Window compute(DataRequest request) {
return new Window(request.range.start, request.range.end, false, 0);
}
public static Window compute(DataRequest request, int bucketSizePx) {
if (request.resolution >= RESOLUTION_QUANTIZE_CUTOFF) {
return quantized(request, bucketSizePx);
} else {
return compute(request);
}
}
public static Window quantized(DataRequest request, int bucketSizePx) {
long quantum = request.resolution * bucketSizePx;
long start = (request.range.start / quantum) * quantum;
return new Window(start, request.range.end, true, quantum);
}
public int getNumberOfBuckets() {
return (int)((end - start + bucketSize - 1) / bucketSize);
}
public ListenableFuture<?> update(QueryEngine qe, String name) {
return qe.query(String.format(
UPDATE_SQL, name, start, Math.max(1, end - start), bucketSize));
}
@Override
public String toString() {
return "window{start: " + start + ", end: " + end +
(quantized ? ", " + getNumberOfBuckets() : "") + "}";
}
}
public abstract static class WithQueryEngine<D extends Track.Data> extends Track<D> {
protected final QueryEngine qe;
public WithQueryEngine(QueryEngine qe, String trackId) {
super(trackId);
this.qe = qe;
}
}
private static class ScheduledRequest<D extends Track.Data> {
public final DataRequest request;
private final List<OnUiThread<D>> callbacks;
public ScheduledRequest(DataRequest request, OnUiThread<D> callback) {
this.request = request;
this.callbacks = Lists.newArrayList(callback);
}
public boolean satisfies(DataRequest req) {
return request.satisfies(req);
}
// Only on UI thread.
public void addCallback(OnUiThread<D> callback) {
callbacks.add(callback);
}
// Not on UI thread.
public void scheduleCallbacks(ListenableFuture<D> future, Consumer<D> update) {
// callbacks.get(0) is safe since we only ever append to the list.
callbacks.get(0).onUiThread(future, data -> {
update.accept(data);
for (OnUiThread<D> callback : callbacks) {
callback.repaint();
}
});
}
}
private static class DataCache {
private final Cache<Key, Object> dataCache = Caches.softCache();
public DataCache() {
}
@SuppressWarnings("unchecked")
public <D extends Track.Data> D getIfPresent(Track<D> track, DataRequest req) {
return (D)dataCache.getIfPresent(new Key(track, req));
}
public <D extends Track.Data> void put(Track<D> track, DataRequest req, D data) {
dataCache.put(new Key(track, req), data);
}
private static class Key {
private final Track<?> track;
private final long resolution;
private final long start;
private final long end;
private final int h;
public Key(Track<?> track, DataRequest req) {
this.track = track;
this.resolution = req.resolution;
this.start = req.range.start;
this.end = req.range.end;
this.h = ((track.hashCode() * 31 + Long.hashCode(resolution)) * 31 +
Long.hashCode(start)) + Long.hashCode(end);
}
@Override
public int hashCode() {
return h;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (!(obj instanceof Key)) {
return false;
}
Key o = (Key)obj;
return track == o.track && resolution == o.resolution && start == o.start && end == o.end;
}
}
}
}
| google/gapid | gapic/src/main/com/google/gapid/perfetto/models/Track.java | Java | apache-2.0 | 11,222 |
package de.tu_berlin.indoornavigation;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import de.tu_berlin.indoornavigation.entities.Group;
public class GroupsActivity extends AppCompatActivity implements GroupFragment.OnListFragmentInteractionListener {
private static final String TAG = GroupsActivity.class.toString();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_groups);
}
/**
* Open view showing users of the group.
*
* @param group
*/
public void onListFragmentInteraction(Group group) {
Log.d(TAG, group.getName());
Intent intent = new Intent(this, UsersActivity.class);
intent.putExtra("members", group.getMembers());
intent.putExtra("groupId", group.getId());
startActivity(intent);
}
}
| IoSL-INav/android | app/src/main/java/de/tu_berlin/indoornavigation/GroupsActivity.java | Java | apache-2.0 | 979 |
/*
* Copyright (c) 2002-2018 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.management;
import java.util.List;
import org.neo4j.jmx.Description;
import org.neo4j.jmx.ManagementInterface;
import org.neo4j.kernel.info.LockInfo;
@ManagementInterface( name = LockManager.NAME )
@Description( "Information about the Neo4j lock status" )
public interface LockManager
{
final String NAME = "Locking";
@Description( "The number of lock sequences that would have lead to a deadlock situation that "
+ "Neo4j has detected and averted (by throwing DeadlockDetectedException)." )
long getNumberOfAvertedDeadlocks();
@Description( "Information about all locks held by Neo4j" )
List<LockInfo> getLocks();
@Description( "Information about contended locks (locks where at least one thread is waiting) held by Neo4j. "
+ "The parameter is used to get locks where threads have waited for at least the specified number "
+ "of milliseconds, a value of 0 retrieves all contended locks." )
List<LockInfo> getContendedLocks( long minWaitTime );
}
| HuangLS/neo4j | advanced/management/src/main/java/org/neo4j/management/LockManager.java | Java | apache-2.0 | 1,871 |
package org.smarti18n.messages.users;
import org.smarti18n.api.v2.UsersApi;
import org.smarti18n.exceptions.UserExistException;
import org.smarti18n.exceptions.UserUnknownException;
import org.smarti18n.models.User;
import org.smarti18n.models.UserCreateDTO;
import org.smarti18n.models.UserSimplified;
import org.smarti18n.models.UserUpdateDTO;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class Users2Endpoint implements UsersApi {
private final UserService userService;
public Users2Endpoint(UserService userService) {
this.userService = userService;
}
@Override
@GetMapping(PATH_USERS_FIND_ALL)
public List<User> findAll() {
return userService.findAll();
}
@Override
@GetMapping(PATH_USERS_FIND_ONE)
public User findOne(
@PathVariable("mail") String mail) throws UserUnknownException {
return userService.findOne(mail);
}
@Override
@GetMapping(PATH_USERS_FIND_ONE_SIMPLIFIED)
public UserSimplified findOneSimplified(
@PathVariable("mail") String mail) {
return userService.findOneSimplified(mail);
}
@Override
@PostMapping(PATH_USERS_CREATE)
public User create(@RequestBody UserCreateDTO dto) throws UserExistException {
return userService.register(dto);
}
@Override
@PutMapping(PATH_USERS_UPDATE)
public User update(
@PathVariable("mail") String mail,
@RequestBody UserUpdateDTO dto) throws UserUnknownException {
return userService.update(mail, dto);
}
}
| SmartI18N/SmartI18N | smarti18n/smarti18n-messages/src/main/java/org/smarti18n/messages/users/Users2Endpoint.java | Java | apache-2.0 | 1,926 |
/**
* Copyright (C) 2014 Karlsruhe Institute of Technology
*
* 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 edu.kit.dama.mdm.dataorganization.test;
import edu.kit.dama.commons.types.DigitalObjectId;
import edu.kit.dama.mdm.dataorganization.entity.core.IAttribute;
import edu.kit.dama.mdm.dataorganization.entity.core.ICollectionNode;
import edu.kit.dama.mdm.dataorganization.entity.core.IFileTree;
import edu.kit.dama.mdm.dataorganization.impl.jpa.Attribute;
import edu.kit.dama.mdm.dataorganization.impl.jpa.CollectionNode;
import edu.kit.dama.mdm.dataorganization.impl.jpa.DataOrganizationNode;
import edu.kit.dama.mdm.dataorganization.impl.jpa.FileTree;
import edu.kit.dama.mdm.dataorganization.impl.jpa.persistence.PersistenceFacade;
import java.util.List;
import java.util.UUID;
import javax.persistence.EntityManager;
/**
*
* @author pasic
*/
public class TestUtil {
static void clearDB() {
EntityManager em = PersistenceFacade.getInstance().
getEntityManagerFactory().createEntityManager();
em.getTransaction().begin();
List<DataOrganizationNode> nodes = em.createQuery(
"SELECT m FROM DataOrganizationNode m",
DataOrganizationNode.class).getResultList();
for (DataOrganizationNode node : nodes) {
em.remove(node);
}
em.flush();
em.getTransaction().commit();
em.close();
}
public static IFileTree createBasicTestTree() {
IFileTree tree
= new edu.kit.dama.mdm.dataorganization.entity.impl.client.FileTree();
DigitalObjectId digitalObjectID = new DigitalObjectId("Dummy " + UUID.randomUUID().toString());
tree.setDigitalObjectId(digitalObjectID);
ICollectionNode cnp;
ICollectionNode cnc
= new edu.kit.dama.mdm.dataorganization.entity.impl.client.CollectionNode();
cnc.setName("child 1");
cnp = tree.getRootNode();
tree.getRootNode().setName("root");
cnp.addChild(cnc);
cnc
= new edu.kit.dama.mdm.dataorganization.entity.impl.client.CollectionNode();
IAttribute attr
= new edu.kit.dama.mdm.dataorganization.entity.impl.client.Attribute();
attr.setKey("dummy");
attr.setValue("attribute");
cnc.addAttribute(attr);
cnc.setName("child 2");
cnp.addChild(cnc);
cnp = cnc;
cnc
= new edu.kit.dama.mdm.dataorganization.entity.impl.client.CollectionNode();
cnc.setName("cnc 2.1");
cnp.addChild(cnc);
cnc
= new edu.kit.dama.mdm.dataorganization.entity.impl.client.CollectionNode();
cnc.setName("cnc 2.2");
cnp.addChild(cnc);
ICollectionNode cnp22 = cnc;
cnc
= new edu.kit.dama.mdm.dataorganization.entity.impl.client.CollectionNode();
cnc.setName("cnc 2.3");
cnp.addChild(cnc);
cnp = cnc;
cnc
= new edu.kit.dama.mdm.dataorganization.entity.impl.client.CollectionNode();
cnc.setName("cnc 2.3.1");
cnp.addChild(cnc);
cnc
= new edu.kit.dama.mdm.dataorganization.entity.impl.client.CollectionNode();
cnc.setName("cnc 2.3.2");
cnp.addChild(cnc);
cnc
= new edu.kit.dama.mdm.dataorganization.entity.impl.client.CollectionNode();
cnc.setName("cnc 2.3.3");
cnp.addChild(cnc);
cnp = cnp22;
cnc
= new edu.kit.dama.mdm.dataorganization.entity.impl.client.CollectionNode();
cnc.setName("cnc 2.2.1");
cnp.addChild(cnc);
cnc
= new edu.kit.dama.mdm.dataorganization.entity.impl.client.CollectionNode();
cnc.setName("cnc 2.2.2");
cnp.addChild(cnc);
cnc
= new edu.kit.dama.mdm.dataorganization.entity.impl.client.CollectionNode();
cnc.setName("cnc 2.2.3");
cnp.addChild(cnc);
tree.setViewName("default");
return tree;
}
public static FileTree createBasicJPATestTree() {
FileTree tree = new FileTree();
DigitalObjectId digitalObjectID = new DigitalObjectId("Dummy");
tree.setDigitalObjectId(digitalObjectID);
CollectionNode cnp;
CollectionNode cnc = new CollectionNode();
tree.setName("root");
cnc.setName("child 1");
cnp = (CollectionNode) tree;
cnp.addChild(cnc);
cnc = new CollectionNode();
Attribute attr = new Attribute();
attr.setKey("dummy");
attr.setValue("attribute");
cnc.addAttribute(attr);
cnc.setName("child 2");
cnp.addChild(cnc);
cnp = cnc;
cnc = new CollectionNode();
cnc.setName("cnc 2.1");
cnp.addChild(cnc);
cnc = new CollectionNode();
cnc.setName("cnc 2.2");
cnp.addChild(cnc);
CollectionNode cnp22 = cnc;
cnc = new CollectionNode();
cnc.setName("cnc 2.3");
cnp.addChild(cnc);
cnp = cnc;
cnc = new CollectionNode();
cnc.setName("cnc 2.3.1");
cnp.addChild(cnc);
cnc = new CollectionNode();
cnc.setName("cnc 2.3.2");
cnp.addChild(cnc);
cnc = new CollectionNode();
cnc.setName("cnc 2.3.3");
cnp.addChild(cnc);
cnp = cnp22;
cnc = new CollectionNode();
cnc.setName("cnc 2.2.1");
cnp.addChild(cnc);
cnc = new CollectionNode();
cnc.setName("cnc 2.2.2");
cnp.addChild(cnc);
cnc = new CollectionNode();
cnc.setName("cnc 2.2.3");
cnp.addChild(cnc);
return tree;
}
}
| kit-data-manager/base | DataOrganization/src/test/java/edu/kit/dama/mdm/dataorganization/test/TestUtil.java | Java | apache-2.0 | 6,221 |
var WaitState = function(game){this.game = game};
WaitState.prototype.preload = function(){
};
WaitState.prototype.create = function(){
this.background = this.game.add.sprite(0,0,'fence');
this.title = this.add.sprite(400,200, 'waitforplay');
this.title.anchor.setTo(0.5, 0.5);
this.waitBar = this.game.add.tileSprite(0,500,800,29,'tankbar');
this.waitBar.autoScroll(-200,0);
this.menubutton = this.game.add.button(400,350,'menubutton',this.menuClick, this);
this.menubutton.anchor.setTo(0.5,0.5);
this.searching = this.game.add.audio('searching');
this.searching.play();
try{
socket.emit("new player", {gameRequest: this.game.gameRequest, character: this.game.character, x: game.width/2 , y: game.height-100});
console.log("Player sent");
}catch(err){
console.log("PLayer could not be sent");
console.log(err.message);
}
};
WaitState.prototype.update = function(){
if(otherPlayerReady){
this.searching.stop();
this.game.state.start("GameState");
}else if(noGames){
this.title.destroy()
this.title = this.add.sprite(400,200,'nogames');
this.title.anchor.setTo(0.5, 0.5);
}
};
WaitState.prototype.menuClick = function(){
//this.game.state.start("MenuState",true,false);
window.location.replace(window.location.pathname);
};
| siracoj/ProPain | ProPain/src/Wait.js | JavaScript | apache-2.0 | 1,384 |
package com.planet_ink.coffee_mud.Locales;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2001-2022 Bo Zimmerman
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.
*/
public class Woods extends StdRoom
{
@Override
public String ID()
{
return "Woods";
}
public Woods()
{
super();
name="the woods";
basePhyStats.setWeight(3);
recoverPhyStats();
}
@Override
public int domainType()
{
return Room.DOMAIN_OUTDOORS_WOODS;
}
@Override
public void executeMsg(final Environmental myHost, final CMMsg msg)
{
if((msg.amITarget(this)||(msg.targetMinor()==CMMsg.TYP_ADVANCE)||(msg.targetMinor()==CMMsg.TYP_RETREAT))
&&(!msg.source().isMonster())
&&(CMLib.dice().rollPercentage()==1)
&&(CMLib.dice().rollPercentage()==1)
&&(isInhabitant(msg.source()))
&&(!CMSecurity.isDisabled(CMSecurity.DisFlag.AUTODISEASE)))
{
final Ability A=CMClass.getAbility("Disease_PoisonIvy");
if((A!=null)
&&(msg.source().fetchEffect(A.ID())==null)
&&(!CMSecurity.isAbilityDisabled(A.ID())))
A.invoke(msg.source(),msg.source(),true,0);
}
super.executeMsg(myHost,msg);
}
public static final Integer[] resourceList={
Integer.valueOf(RawMaterial.RESOURCE_WOOD),
Integer.valueOf(RawMaterial.RESOURCE_PINE),
Integer.valueOf(RawMaterial.RESOURCE_OAK),
Integer.valueOf(RawMaterial.RESOURCE_MAPLE),
Integer.valueOf(RawMaterial.RESOURCE_REDWOOD),
Integer.valueOf(RawMaterial.RESOURCE_SAP),
Integer.valueOf(RawMaterial.RESOURCE_YEW),
Integer.valueOf(RawMaterial.RESOURCE_HICKORY),
Integer.valueOf(RawMaterial.RESOURCE_TEAK),
Integer.valueOf(RawMaterial.RESOURCE_CEDAR),
Integer.valueOf(RawMaterial.RESOURCE_ELM),
Integer.valueOf(RawMaterial.RESOURCE_CHERRYWOOD),
Integer.valueOf(RawMaterial.RESOURCE_BEECHWOOD),
Integer.valueOf(RawMaterial.RESOURCE_WILLOW),
Integer.valueOf(RawMaterial.RESOURCE_SYCAMORE),
Integer.valueOf(RawMaterial.RESOURCE_SPRUCE),
Integer.valueOf(RawMaterial.RESOURCE_FLOWERS),
Integer.valueOf(RawMaterial.RESOURCE_FRUIT),
Integer.valueOf(RawMaterial.RESOURCE_APPLES),
Integer.valueOf(RawMaterial.RESOURCE_BERRIES),
Integer.valueOf(RawMaterial.RESOURCE_PEACHES),
Integer.valueOf(RawMaterial.RESOURCE_CHERRIES),
Integer.valueOf(RawMaterial.RESOURCE_ORANGES),
Integer.valueOf(RawMaterial.RESOURCE_LEMONS),
Integer.valueOf(RawMaterial.RESOURCE_FUR),
Integer.valueOf(RawMaterial.RESOURCE_NUTS),
Integer.valueOf(RawMaterial.RESOURCE_HERBS),
Integer.valueOf(RawMaterial.RESOURCE_DIRT),
Integer.valueOf(RawMaterial.RESOURCE_HONEY),
Integer.valueOf(RawMaterial.RESOURCE_VINE),
Integer.valueOf(RawMaterial.RESOURCE_HIDE),
Integer.valueOf(RawMaterial.RESOURCE_FEATHERS),
Integer.valueOf(RawMaterial.RESOURCE_LEATHER)};
public static final List<Integer> roomResources=new Vector<Integer>(Arrays.asList(resourceList));
@Override
public List<Integer> resourceChoices()
{
return Woods.roomResources;
}
}
| bozimmerman/CoffeeMud | com/planet_ink/coffee_mud/Locales/Woods.java | Java | apache-2.0 | 4,316 |
namespace Wundercal.Services.Dto
{
public class WunderlistList
{
public int Id { get; set; }
public string Title { get; set; }
}
} | marska/wundercal | src/Wundercal/Services/Dto/WunderlistList.cs | C# | apache-2.0 | 145 |
/*
* Copyright 2000-2010 JetBrains s.r.o.
*
* 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.intellij.codeInsight.actions;
import com.intellij.codeInsight.CodeInsightActionHandler;
import javax.annotation.Nonnull;
/**
* @author Dmitry Avdeev
*/
public abstract class SimpleCodeInsightAction extends CodeInsightAction implements CodeInsightActionHandler {
@Nonnull
@Override
protected CodeInsightActionHandler getHandler() {
return this;
}
@Override
public boolean startInWriteAction() {
return true;
}
}
| consulo/consulo | modules/base/lang-api/src/main/java/com/intellij/codeInsight/actions/SimpleCodeInsightAction.java | Java | apache-2.0 | 1,052 |
/*
* Copyright 2016 ANI Technologies Pvt. Ltd.
*
* 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.olacabs.fabric.processors.kafkawriter;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.olacabs.fabric.compute.ProcessingContext;
import com.olacabs.fabric.compute.processor.InitializationException;
import com.olacabs.fabric.compute.processor.ProcessingException;
import com.olacabs.fabric.compute.processor.StreamingProcessor;
import com.olacabs.fabric.compute.util.ComponentPropertyReader;
import com.olacabs.fabric.model.common.ComponentMetadata;
import com.olacabs.fabric.model.event.Event;
import com.olacabs.fabric.model.event.EventSet;
import com.olacabs.fabric.model.processor.Processor;
import com.olacabs.fabric.model.processor.ProcessorType;
import kafka.javaapi.producer.Producer;
import kafka.producer.DefaultPartitioner;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
/**
* TODO Javadoc.
*/
@Processor(
namespace = "global",
name = "kafka-writer",
version = "2.0",
description = "A processor that write data into kafka",
cpu = 0.1,
memory = 1,
processorType = ProcessorType.EVENT_DRIVEN,
requiredProperties = {
"brokerList",
"ingestionPoolSize",
"kafkaKeyJsonPath"
},
optionalProperties = {
"isTopicOnJsonPath",
"topic",
"topicJsonPath",
"ignoreError",
"kafkaSerializerClass",
"ackCount"
})
public class KafkaWriter extends StreamingProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(KafkaWriter.class.getSimpleName());
private static final boolean DEFAULT_IGNORE_SERIALIZATION_ERROR = false;
private static final boolean DEFAULT_TOPIC_ON_JSON_PATH = false;
private static final String DEFAULT_SERIALIZER_CLASS = "kafka.serializer.StringEncoder";
private static final String DEFAULT_KAFKA_KEY_JSON_PATH = "/metadata/partitionKey/value";
private static final int DEFAULT_ACK_COUNT = 1;
private static final int DEFAULT_BATCH_SIZE = 10;
private static final String ACK_COUNT = "-1";
private String kafkaKeyJsonPath;
private boolean ignoreError;
private ObjectMapper mapper;
@Getter
@Setter
private String kafkaTopic;
@Getter
@Setter
private String kafkaTopicJsonPath;
@Getter
@Setter
private int ingestionPoolSize;
@Getter
@Setter
private Producer<String, String> producer;
@Getter
@Setter
private boolean isTopicOnJsonPath = false;
@Override
protected EventSet consume(ProcessingContext processingContext, EventSet eventSet) throws ProcessingException {
final List<KeyedMessage<String, String>> messages = Lists.newArrayList();
try {
eventSet.getEvents().forEach(event -> {
KeyedMessage<String, String> convertedMessage = null;
try {
convertedMessage = convertEvent(event);
} catch (ProcessingException e) {
LOGGER.error("Error converting byte stream to event: ", e);
throw new RuntimeException(e);
}
if (null != convertedMessage) {
messages.add(convertedMessage);
}
});
} catch (final Exception e) {
LOGGER.error("Error converting byte stream to event: ", e);
throw new ProcessingException(e);
}
Lists.partition(messages, ingestionPoolSize).forEach(messageList -> getProducer().send(messageList));
return eventSet;
}
/**
* convert the event into Kafka keyed messages.
*
* @param event to convert
* @return KeyedMessage
*/
protected KeyedMessage<String, String> convertEvent(Event event) throws ProcessingException {
JsonNode eventData = event.getJsonNode();
if (null == eventData) {
if (event.getData() instanceof byte[]) {
try {
eventData = mapper.readTree((byte[]) event.getData());
} catch (IOException e) {
LOGGER.error("Error converting byte stream to event: ", e);
if (!ignoreError) {
LOGGER.error("Error converting byte stream to event");
throw new ProcessingException("Error converting byte stream to event", e);
}
return null;
}
} else {
if (!ignoreError) {
LOGGER.error("Error converting byte stream to event: Event is not byte stream");
throw new ProcessingException("Error converting byte stream to event: Event is not byte stream");
}
return null;
}
}
final String kafkaKey = kafkaKeyJsonPath != null
? eventData.at(kafkaKeyJsonPath).asText().replace("\"", "")
: eventData.at(DEFAULT_KAFKA_KEY_JSON_PATH).asText().replace("\"", "");
final String topic = isTopicOnJsonPath()
? eventData.at(getKafkaTopicJsonPath()).toString().replace("\"", "")
: getKafkaTopic().replace("\"", "");
return new KeyedMessage<>(topic, kafkaKey, eventData.toString());
}
@Override
public void initialize(String instanceId, Properties globalProperties, Properties properties,
ComponentMetadata componentMetadata) throws InitializationException {
final String kafkaBrokerList = ComponentPropertyReader
.readString(properties, globalProperties, "brokerList", instanceId, componentMetadata);
isTopicOnJsonPath = ComponentPropertyReader
.readBoolean(properties, globalProperties, "isTopicOnJsonPath", instanceId, componentMetadata,
DEFAULT_TOPIC_ON_JSON_PATH);
if (!isTopicOnJsonPath) {
kafkaTopic = ComponentPropertyReader
.readString(properties, globalProperties, "topic", instanceId, componentMetadata);
if (kafkaTopic == null) {
LOGGER.error("Kafka topic in properties not found");
throw new RuntimeException("Kafka topic in properties not found");
}
setKafkaTopic(kafkaTopic);
} else {
kafkaTopicJsonPath = ComponentPropertyReader
.readString(properties, globalProperties, "topicJsonPath", instanceId, componentMetadata);
if (kafkaTopicJsonPath == null) {
LOGGER.error("Kafka topic json path not found");
throw new RuntimeException("Kafka topic json path not found");
}
setKafkaTopicJsonPath(kafkaTopicJsonPath);
}
kafkaKeyJsonPath = ComponentPropertyReader
.readString(properties, globalProperties, "kafkaKeyJsonPath", instanceId, componentMetadata,
DEFAULT_KAFKA_KEY_JSON_PATH);
final String kafkaSerializerClass = ComponentPropertyReader
.readString(properties, globalProperties, "kafkaSerializerClass", instanceId, componentMetadata,
DEFAULT_SERIALIZER_CLASS);
ingestionPoolSize = ComponentPropertyReader
.readInteger(properties, globalProperties, "ingestionPoolSize", instanceId, componentMetadata,
DEFAULT_BATCH_SIZE);
final Integer ackCount = ComponentPropertyReader
.readInteger(properties, globalProperties, "ackCount", instanceId, componentMetadata,
DEFAULT_ACK_COUNT);
ignoreError = ComponentPropertyReader
.readBoolean(properties, globalProperties, "ignoreError", instanceId, componentMetadata,
DEFAULT_IGNORE_SERIALIZATION_ERROR);
final Properties props = new Properties();
props.put("metadata.broker.list", kafkaBrokerList);
props.put("serializer.class", kafkaSerializerClass);
props.put("partitioner.class", DefaultPartitioner.class.getName());
props.put("request.required.acks", ACK_COUNT);
props.put("min.isr", Integer.toString(ackCount));
producer = new Producer<>(new ProducerConfig(props));
mapper = new ObjectMapper();
LOGGER.info("Initialized kafka writer...");
}
@Override
public void destroy() {
producer.close();
LOGGER.info("Closed kafka writer...");
}
}
| olacabs/fabric | fabric-components/kafka-writer/src/main/java/com/olacabs/fabric/processors/kafkawriter/KafkaWriter.java | Java | apache-2.0 | 9,285 |
package navyblue.top.colortalk.ui.activities;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import com.github.paolorotolo.appintro.AppIntro2;
import navyblue.top.colortalk.R;
import navyblue.top.colortalk.ui.fragments.SampleSlide;
/**
* Created by CIR on 16/6/4.
*/
public class AppIntroActivity extends AppIntro2 {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setFlowAnimation();
addSlide(SampleSlide.newInstance(R.layout.intro));
addSlide(SampleSlide.newInstance(R.layout.intro_2));
addSlide(SampleSlide.newInstance(R.layout.intro3));
addSlide(SampleSlide.newInstance(R.layout.intro4));
addSlide(SampleSlide.newInstance(R.layout.intro5));
}
@Override
public void onDonePressed(Fragment currentFragment) {
finish();
}
@Override
public void onSkipPressed(Fragment currentFragment) {
finish();
}
}
| YogiAi/ColorTalk_Android | app/src/main/java/navyblue/top/colortalk/ui/activities/AppIntroActivity.java | Java | apache-2.0 | 990 |
/*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.intellij.codeInspection.i18n;
import com.intellij.codeInsight.AnnotationUtil;
import com.intellij.codeInsight.template.macro.MacroUtil;
import com.intellij.lang.properties.*;
import com.intellij.lang.properties.ResourceBundle;
import com.intellij.lang.properties.psi.PropertiesFile;
import com.intellij.lang.properties.psi.PropertyCreationHandler;
import com.intellij.lang.properties.references.I18nUtil;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.scope.util.PsiScopesUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.util.ArrayUtil;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.uast.*;
import java.text.MessageFormat;
import java.util.*;
/**
* @author max
*/
public class JavaI18nUtil extends I18nUtil {
public static final PropertyCreationHandler DEFAULT_PROPERTY_CREATION_HANDLER =
(project, propertiesFiles, key, value, parameters) -> createProperty(project, propertiesFiles, key, value, true);
private JavaI18nUtil() {
}
@Nullable
public static TextRange getSelectedRange(Editor editor, final PsiFile psiFile) {
if (editor == null) return null;
String selectedText = editor.getSelectionModel().getSelectedText();
if (selectedText != null) {
return new TextRange(editor.getSelectionModel().getSelectionStart(), editor.getSelectionModel().getSelectionEnd());
}
PsiElement psiElement = psiFile.findElementAt(editor.getCaretModel().getOffset());
if (psiElement == null || psiElement instanceof PsiWhiteSpace) return null;
return psiElement.getTextRange();
}
public static boolean mustBePropertyKey(@NotNull PsiExpression expression, @Nullable Ref<? super PsiAnnotationMemberValue> resourceBundleRef) {
PsiElement parent = expression.getParent();
if (parent instanceof PsiVariable) {
final PsiAnnotation annotation = AnnotationUtil.findAnnotation((PsiVariable)parent, AnnotationUtil.PROPERTY_KEY);
if (annotation != null) {
processAnnotationAttributes(resourceBundleRef, annotation);
return true;
}
}
return isPassedToAnnotatedParam(expression, AnnotationUtil.PROPERTY_KEY, resourceBundleRef, null);
}
public static boolean mustBePropertyKey(@NotNull ULiteralExpression expression, @Nullable Ref<? super UExpression> resourceBundleRef) {
final UElement parent = expression.getUastParent();
if (parent instanceof UVariable) {
UAnnotation annotation = ((UVariable)parent).findAnnotation(AnnotationUtil.PROPERTY_KEY);
if (annotation != null) {
processAnnotationAttributes(resourceBundleRef, annotation);
return true;
}
}
UCallExpression callExpression = UastUtils.getUCallExpression(expression);
if (callExpression == null) return false;
PsiMethod psiMethod = callExpression.resolve();
if (psiMethod == null) return false;
PsiParameter parameter = UastUtils.getParameterForArgument(callExpression, expression);
if (parameter == null) return false;
int paramIndex = ArrayUtil.indexOf(psiMethod.getParameterList().getParameters(), parameter);
if (paramIndex == -1) return false;
return isMethodParameterAnnotatedWith(psiMethod, paramIndex, null, AnnotationUtil.PROPERTY_KEY, null, null);
}
static boolean isPassedToAnnotatedParam(@NotNull PsiExpression expression,
final String annFqn,
@Nullable Ref<? super PsiAnnotationMemberValue> resourceBundleRef,
@Nullable final Set<? super PsiModifierListOwner> nonNlsTargets) {
expression = getTopLevelExpression(expression);
final PsiElement parent = expression.getParent();
if (!(parent instanceof PsiExpressionList)) return false;
int idx = -1;
final PsiExpression[] args = ((PsiExpressionList)parent).getExpressions();
for (int i = 0; i < args.length; i++) {
PsiExpression arg = args[i];
if (PsiTreeUtil.isAncestor(arg, expression, false)) {
idx = i;
break;
}
}
if (idx == -1) return false;
PsiElement grParent = parent.getParent();
if (grParent instanceof PsiAnonymousClass) {
grParent = grParent.getParent();
}
if (grParent instanceof PsiCall) {
PsiMethod method = ((PsiCall)grParent).resolveMethod();
return method != null && isMethodParameterAnnotatedWith(method, idx, null, annFqn, resourceBundleRef, nonNlsTargets);
}
return false;
}
@NotNull
static PsiExpression getTopLevelExpression(@NotNull PsiExpression expression) {
while (expression.getParent() instanceof PsiExpression) {
final PsiExpression parent = (PsiExpression)expression.getParent();
if (parent instanceof PsiConditionalExpression &&
((PsiConditionalExpression)parent).getCondition() == expression) {
break;
}
expression = parent;
if (expression instanceof PsiAssignmentExpression) break;
}
return expression;
}
static boolean isMethodParameterAnnotatedWith(final PsiMethod method,
final int idx,
@Nullable Collection<? super PsiMethod> processed,
final String annFqn,
@Nullable Ref<? super PsiAnnotationMemberValue> resourceBundleRef,
@Nullable final Set<? super PsiModifierListOwner> nonNlsTargets) {
if (processed != null) {
if (processed.contains(method)) return false;
}
else {
processed = new THashSet<>();
}
processed.add(method);
final PsiParameter[] params = method.getParameterList().getParameters();
PsiParameter param;
if (idx >= params.length) {
if (params.length == 0) {
return false;
}
PsiParameter lastParam = params[params.length - 1];
if (lastParam.isVarArgs()) {
param = lastParam;
}
else {
return false;
}
}
else {
param = params[idx];
}
final PsiAnnotation annotation = AnnotationUtil.findAnnotation(param, annFqn);
if (annotation != null) {
processAnnotationAttributes(resourceBundleRef, annotation);
return true;
}
if (nonNlsTargets != null) {
nonNlsTargets.add(param);
}
final PsiMethod[] superMethods = method.findSuperMethods();
for (PsiMethod superMethod : superMethods) {
if (isMethodParameterAnnotatedWith(superMethod, idx, processed, annFqn, resourceBundleRef, null)) return true;
}
return false;
}
private static void processAnnotationAttributes(@Nullable Ref<? super PsiAnnotationMemberValue> resourceBundleRef,
@NotNull PsiAnnotation annotation) {
if (resourceBundleRef != null) {
final PsiAnnotationParameterList parameterList = annotation.getParameterList();
final PsiNameValuePair[] attributes = parameterList.getAttributes();
for (PsiNameValuePair attribute : attributes) {
final String name = attribute.getName();
if (AnnotationUtil.PROPERTY_KEY_RESOURCE_BUNDLE_PARAMETER.equals(name)) {
resourceBundleRef.set(attribute.getValue());
}
}
}
}
private static void processAnnotationAttributes(@Nullable Ref<? super UExpression> resourceBundleRef,
@NotNull UAnnotation annotation) {
if (resourceBundleRef != null) {
for (UNamedExpression attribute : annotation.getAttributeValues()) {
final String name = attribute.getName();
if (AnnotationUtil.PROPERTY_KEY_RESOURCE_BUNDLE_PARAMETER.equals(name)) {
resourceBundleRef.set(attribute.getExpression());
}
}
}
}
static boolean isValidPropertyReference(@NotNull Project project,
@NotNull PsiExpression expression,
@NotNull String key,
@NotNull Ref<? super String> outResourceBundle) {
Ref<PsiAnnotationMemberValue> resourceBundleRef = Ref.create();
if (mustBePropertyKey(expression, resourceBundleRef)) {
final Object resourceBundleName = resourceBundleRef.get();
if (!(resourceBundleName instanceof PsiExpression)) {
return false;
}
PsiExpression expr = (PsiExpression)resourceBundleName;
final PsiConstantEvaluationHelper constantEvaluationHelper = JavaPsiFacade.getInstance(project).getConstantEvaluationHelper();
Object value = constantEvaluationHelper.computeConstantExpression(expr);
if (value == null) {
if (expr instanceof PsiReferenceExpression) {
final PsiElement resolve = ((PsiReferenceExpression)expr).resolve();
if (resolve instanceof PsiField && ((PsiField)resolve).hasModifierProperty(PsiModifier.FINAL)) {
value = constantEvaluationHelper.computeConstantExpression(((PsiField)resolve).getInitializer());
if (value == null) {
return false;
}
}
}
if (value == null) {
final ResourceBundle resourceBundle = resolveResourceBundleByKey(key, project);
if (resourceBundle == null) {
return false;
}
final PropertiesFile defaultPropertiesFile = resourceBundle.getDefaultPropertiesFile();
final String bundleName = BundleNameEvaluator.DEFAULT.evaluateBundleName(defaultPropertiesFile.getContainingFile());
if (bundleName == null) {
return false;
}
value = bundleName;
}
}
String bundleName = value.toString();
outResourceBundle.set(bundleName);
return isPropertyRef(expression, key, bundleName);
}
return true;
}
@Nullable
private static ResourceBundle resolveResourceBundleByKey(@NotNull final String key, @NotNull final Project project) {
final Ref<ResourceBundle> bundleRef = Ref.create();
final boolean r = PropertiesReferenceManager.getInstance(project).processAllPropertiesFiles((baseName, propertiesFile) -> {
if (propertiesFile.findPropertyByKey(key) != null) {
if (bundleRef.get() == null) {
bundleRef.set(propertiesFile.getResourceBundle());
}
else {
return bundleRef.get().equals(propertiesFile.getResourceBundle());
}
}
return true;
});
return r ? bundleRef.get() : null;
}
static boolean isPropertyRef(final PsiExpression expression, final String key, final String resourceBundleName) {
if (resourceBundleName == null) {
return !PropertiesImplUtil.findPropertiesByKey(expression.getProject(), key).isEmpty();
}
else {
final List<PropertiesFile> propertiesFiles = propertiesFilesByBundleName(resourceBundleName, expression);
boolean containedInPropertiesFile = false;
for (PropertiesFile propertiesFile : propertiesFiles) {
containedInPropertiesFile |= propertiesFile.findPropertyByKey(key) != null;
}
return containedInPropertiesFile;
}
}
public static Set<String> suggestExpressionOfType(final PsiClassType type, final PsiLiteralExpression context) {
PsiVariable[] variables = MacroUtil.getVariablesVisibleAt(context, "");
Set<String> result = new LinkedHashSet<>();
for (PsiVariable var : variables) {
PsiType varType = var.getType();
PsiIdentifier identifier = var.getNameIdentifier();
if ((type == null || type.isAssignableFrom(varType)) && identifier != null) {
result.add(identifier.getText());
}
}
PsiExpression[] expressions = MacroUtil.getStandardExpressionsOfType(context, type);
for (PsiExpression expression : expressions) {
result.add(expression.getText());
}
if (type != null) {
addAvailableMethodsOfType(type, context, result);
}
return result;
}
private static void addAvailableMethodsOfType(final PsiClassType type,
final PsiLiteralExpression context,
final Collection<? super String> result) {
PsiScopesUtil.treeWalkUp((element, state) -> {
if (element instanceof PsiMethod) {
PsiMethod method = (PsiMethod)element;
PsiType returnType = method.getReturnType();
if (returnType != null && TypeConversionUtil.isAssignable(type, returnType)
&& method.getParameterList().isEmpty()) {
result.add(method.getName() + "()");
}
}
return true;
}, context, null);
}
/**
* Returns number of different message format parameters in property value
*
* <i>Class {0} info: Class {0} extends class {1} and implements interface {2}</i>
* number of parameters is 3.
*
* @return number of parameters from single property or 0 for wrong format
*/
public static int getPropertyValuePlaceholdersCount(@NotNull final String propertyValue) {
try {
return new MessageFormat(propertyValue).getFormatsByArgumentIndex().length;
}
catch (final IllegalArgumentException e) {
return 0;
}
}
/**
* Returns number of different parameters in i18n message. For example, for string
*
* <i>Class {0} info: Class {0} extends class {1} and implements interface {2}</i> in one translation of property
* <i>Class {0} info: Class {0} extends class {1} </i> in other translation of property
* <p>
* number of parameters is 3.
*
* @param expression i18n literal
* @return number of parameters
*/
public static int getPropertyValueParamsMaxCount(@NotNull final UExpression expression) {
final SortedSet<Integer> paramsCount = getPropertyValueParamsCount(expression, null);
if (paramsCount.isEmpty()) {
return -1;
}
return paramsCount.last();
}
@NotNull
static SortedSet<Integer> getPropertyValueParamsCount(@NotNull final PsiExpression expression,
@Nullable final String resourceBundleName) {
UExpression uExpression = UastContextKt.toUElement(expression, UExpression.class);
if (uExpression == null) return new TreeSet<>();
return getPropertyValueParamsCount(uExpression, resourceBundleName);
}
@NotNull
private static SortedSet<Integer> getPropertyValueParamsCount(@NotNull final UExpression expression,
@Nullable final String resourceBundleName) {
final ULiteralExpression literalExpression;
if (expression instanceof ULiteralExpression) {
literalExpression = (ULiteralExpression)expression;
}
else if (expression instanceof UReferenceExpression) {
final PsiElement resolved = ((UReferenceExpression)expression).resolve();
final PsiField field = resolved == null ? null : (PsiField)resolved;
literalExpression =
field != null && field.hasModifierProperty(PsiModifier.FINAL) && field.getInitializer() instanceof PsiLiteralExpression
? UastContextKt.toUElement(field.getInitializer(), ULiteralExpression.class)
: null;
}
else {
literalExpression = null;
}
final TreeSet<Integer> paramsCount = new TreeSet<>();
if (literalExpression == null) {
return paramsCount;
}
for (PsiReference reference : UastLiteralUtils.getInjectedReferences(literalExpression)) {
if (reference instanceof PsiPolyVariantReference) {
for (ResolveResult result : ((PsiPolyVariantReference)reference).multiResolve(false)) {
if (result.isValidResult() && result.getElement() instanceof IProperty) {
try {
final IProperty property = (IProperty)result.getElement();
if (resourceBundleName != null) {
final PsiFile file = property.getPropertiesFile().getContainingFile();
if (!resourceBundleName.equals(BundleNameEvaluator.DEFAULT.evaluateBundleName(file))) {
continue;
}
}
final String propertyValue = property.getValue();
if (propertyValue == null) {
continue;
}
paramsCount.add(getPropertyValuePlaceholdersCount(propertyValue));
}
catch (IllegalArgumentException ignored) {
}
}
}
}
}
return paramsCount;
}
}
| mdanielwork/intellij-community | plugins/java-i18n/src/com/intellij/codeInspection/i18n/JavaI18nUtil.java | Java | apache-2.0 | 16,944 |
package entity.chess;
import java.util.ArrayList;
import entity.Board;
import entity.Coordinate;
//Author 在线疯狂
//Homepage http://bookshadow.com
public class General extends Chess {
public final static int VALUE = 100000;
private final static int deltaX[] = { 1, 0, -1, 0 };
private final static int deltaY[] = { 0, 1, 0, -1 };
public General() {
super.setCode(Chess.GENERAL);
}
@Override
public ArrayList<Coordinate> getPossibleLocations(Board chessBoard) {
Chess[][] board = chessBoard.getBoard();
ArrayList<Coordinate> al = new ArrayList<Coordinate>();
Coordinate sourceCoo = getCoordinate();
for (int i = 0; i < deltaX.length; i++) {
int x = sourceCoo.getX() + deltaX[i];
int y = sourceCoo.getY() + deltaY[i];
if (!isValid(x, y)) {
continue;
}
if (board[x][y] != null && (board[x][y].getColor() == getColor())) {
continue;
}
al.add(new Coordinate(x, y));
}
Coordinate enemyGeneralCoo = generalMeet(board);
if (enemyGeneralCoo != null)
al.add(enemyGeneralCoo);
return al;
}
@Override
public boolean isValid(int x, int y) {
return ((x <= 2 && x >= 0) || (x >= 7 && x <= 9)) && (y >= 3 && y <= 5);
}
public Coordinate generalMeet(Chess board[][]) {
char color = getColor();
Chess opponentGeneral = Board.findGeneral(board, Chess.oppositeColor(color));
if (opponentGeneral == null)
return null;
int sy = getCoordinate().getY();
int oy = opponentGeneral.getCoordinate().getY();
if (sy == oy) {
if (Board.countChess(board, getCoordinate(), opponentGeneral.getCoordinate()) == 2) {
return opponentGeneral.getCoordinate();
}
}
return null;
}
@Override
public int getValue(Board chessBoard) {
return VALUE;
}
}
| qinjiannet/screen-chess-qq | src/entity/chess/General.java | Java | apache-2.0 | 1,727 |
/*
* Copyright 2021 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.
*/
/**
* External dependencies
*/
import { memo } from '@googleforcreators/react';
/**
* Internal dependencies
*/
import {
SwapMedia,
LayerOpacity,
FlipHorizontal,
FlipVertical,
BorderWidthAndColor,
More,
Separator,
Dismiss,
} from '../elements';
const FloatingImageMenu = memo(function FloatingImageMenu() {
return (
<>
<SwapMedia />
<Separator />
<LayerOpacity />
<Separator />
<FlipHorizontal />
<FlipVertical />
<Separator />
<BorderWidthAndColor />
<Separator />
<More />
<Separator />
<Dismiss />
</>
);
});
export default FloatingImageMenu;
| GoogleForCreators/web-stories-wp | packages/story-editor/src/components/floatingMenu/menus/image.js | JavaScript | apache-2.0 | 1,257 |
/*
* Copyright (c) 2009 Piotr Piastucki
*
* This file is part of Patchca CAPTCHA library.
*
* Patchca is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Patchca is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Patchca. If not, see <http://www.gnu.org/licenses/>.
*/
package com.xiongyingqi.captcha.filter;
import java.awt.image.BufferedImageOp;
import java.util.List;
public class ConfigurableFilterFactory extends AbstractFilterFactory {
private List<BufferedImageOp> filters;
@Override
public List<BufferedImageOp> getFilters() {
return filters;
}
public void setFilters(List<BufferedImageOp> filters) {
this.filters = filters;
}
}
| blademainer/common_utils | common_helper/src/main/java/com/xiongyingqi/captcha/filter/ConfigurableFilterFactory.java | Java | apache-2.0 | 1,181 |
package cn.felord.wepay.ali.sdk.api.request;
import java.util.Map;
import cn.felord.wepay.ali.sdk.api.AlipayRequest;
import cn.felord.wepay.ali.sdk.api.internal.util.AlipayHashMap;
import cn.felord.wepay.ali.sdk.api.response.KoubeiRetailShopitemUploadResponse;
import cn.felord.wepay.ali.sdk.api.AlipayObject;
/**
* ALIPAY API: koubei.retail.shopitem.upload request
*
* @author auto create
* @version $Id: $Id
*/
public class KoubeiRetailShopitemUploadRequest implements AlipayRequest<KoubeiRetailShopitemUploadResponse> {
private AlipayHashMap udfParams; // add user-defined text parameters
private String apiVersion="1.0";
/**
* isv 回传的门店商品信息上传接口
*/
private String bizContent;
/**
* <p>Setter for the field <code>bizContent</code>.</p>
*
* @param bizContent a {@link java.lang.String} object.
*/
public void setBizContent(String bizContent) {
this.bizContent = bizContent;
}
/**
* <p>Getter for the field <code>bizContent</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getBizContent() {
return this.bizContent;
}
private String terminalType;
private String terminalInfo;
private String prodCode;
private String notifyUrl;
private String returnUrl;
private boolean needEncrypt=false;
private AlipayObject bizModel=null;
/**
* <p>Getter for the field <code>notifyUrl</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getNotifyUrl() {
return this.notifyUrl;
}
/** {@inheritDoc} */
public void setNotifyUrl(String notifyUrl) {
this.notifyUrl = notifyUrl;
}
/**
* <p>Getter for the field <code>returnUrl</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getReturnUrl() {
return this.returnUrl;
}
/** {@inheritDoc} */
public void setReturnUrl(String returnUrl) {
this.returnUrl = returnUrl;
}
/**
* <p>Getter for the field <code>apiVersion</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getApiVersion() {
return this.apiVersion;
}
/** {@inheritDoc} */
public void setApiVersion(String apiVersion) {
this.apiVersion = apiVersion;
}
/** {@inheritDoc} */
public void setTerminalType(String terminalType){
this.terminalType=terminalType;
}
/**
* <p>Getter for the field <code>terminalType</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getTerminalType(){
return this.terminalType;
}
/** {@inheritDoc} */
public void setTerminalInfo(String terminalInfo){
this.terminalInfo=terminalInfo;
}
/**
* <p>Getter for the field <code>terminalInfo</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getTerminalInfo(){
return this.terminalInfo;
}
/** {@inheritDoc} */
public void setProdCode(String prodCode) {
this.prodCode=prodCode;
}
/**
* <p>Getter for the field <code>prodCode</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getProdCode() {
return this.prodCode;
}
/**
* <p>getApiMethodName.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getApiMethodName() {
return "koubei.retail.shopitem.upload";
}
/**
* <p>getTextParams.</p>
*
* @return a {@link java.util.Map} object.
*/
public Map<String, String> getTextParams() {
AlipayHashMap txtParams = new AlipayHashMap();
txtParams.put("biz_content", this.bizContent);
if(udfParams != null) {
txtParams.putAll(this.udfParams);
}
return txtParams;
}
/**
* <p>putOtherTextParam.</p>
*
* @param key a {@link java.lang.String} object.
* @param value a {@link java.lang.String} object.
*/
public void putOtherTextParam(String key, String value) {
if(this.udfParams == null) {
this.udfParams = new AlipayHashMap();
}
this.udfParams.put(key, value);
}
/**
* <p>getResponseClass.</p>
*
* @return a {@link java.lang.Class} object.
*/
public Class<KoubeiRetailShopitemUploadResponse> getResponseClass() {
return KoubeiRetailShopitemUploadResponse.class;
}
/**
* <p>isNeedEncrypt.</p>
*
* @return a boolean.
*/
public boolean isNeedEncrypt() {
return this.needEncrypt;
}
/** {@inheritDoc} */
public void setNeedEncrypt(boolean needEncrypt) {
this.needEncrypt=needEncrypt;
}
/**
* <p>Getter for the field <code>bizModel</code>.</p>
*
* @return a {@link cn.felord.wepay.ali.sdk.api.AlipayObject} object.
*/
public AlipayObject getBizModel() {
return this.bizModel;
}
/** {@inheritDoc} */
public void setBizModel(AlipayObject bizModel) {
this.bizModel=bizModel;
}
}
| NotFound403/WePay | src/main/java/cn/felord/wepay/ali/sdk/api/request/KoubeiRetailShopitemUploadRequest.java | Java | apache-2.0 | 4,790 |
package slack_test
import (
"testing"
slacktest "github.com/lusis/slack-test"
"github.com/nlopes/slack"
"github.com/stretchr/testify/assert"
)
const (
testMessage = "test message"
testToken = "TEST_TOKEN"
)
func TestRTMSingleConnect(t *testing.T) {
// Set up the test server.
testServer := slacktest.NewTestServer()
go testServer.Start()
// Setup and start the RTM.
slack.SLACK_API = testServer.GetAPIURL()
api := slack.New(testToken)
rtm := api.NewRTM()
go rtm.ManageConnection()
// Observe incoming messages.
done := make(chan struct{})
connectingReceived := false
connectedReceived := false
testMessageReceived := false
go func() {
for msg := range rtm.IncomingEvents {
switch ev := msg.Data.(type) {
case *slack.ConnectingEvent:
if connectingReceived {
t.Error("Received multiple connecting events.")
t.Fail()
}
connectingReceived = true
case *slack.ConnectedEvent:
if connectedReceived {
t.Error("Received multiple connected events.")
t.Fail()
}
connectedReceived = true
case *slack.MessageEvent:
if ev.Text == testMessage {
testMessageReceived = true
rtm.Disconnect()
done <- struct{}{}
return
}
t.Logf("Discarding message with content %+v", ev)
default:
t.Logf("Discarded event of type '%s' with content '%#v'", msg.Type, ev)
}
}
}()
// Send a message and sleep for some time to make sure the message can be processed client-side.
testServer.SendDirectMessageToBot(testMessage)
<-done
testServer.Stop()
// Verify that all expected events have been received by the RTM client.
assert.True(t, connectingReceived, "Should have received a connecting event from the RTM instance.")
assert.True(t, connectedReceived, "Should have received a connected event from the RTM instance.")
assert.True(t, testMessageReceived, "Should have received a test message from the server.")
}
| cockroachlabs/roachprod | vendor/github.com/nlopes/slack/websocket_managed_conn_test.go | GO | apache-2.0 | 1,918 |
#include<iostream>
#include<vector>
#include<list>
#include<queue>
using namespace std;
void breadth_first_search(vector<list<int>> graph,int src){
vector<bool>visited(graph.size(),false);
queue<int>Q;
Q.push(src);
visited[src] = true;
while(!Q.empty()){
int vertex = Q.front(); Q.pop();
cout << vertex << " ";
for(list<int>::iterator itr = graph[vertex].begin();itr!=graph[vertex].end();itr++){
if(!visited[*itr])
Q.push(*itr);
visited[*itr] = true;
}
}
}
int main(){
vector<list<int>> graph;
int v,e,src,des;
cin >> v >> e;
graph.resize(v);
while(e--){
cin >> src >> des;
graph[src].push_back(des);
graph[des].push_back(src);
}
cin >> src;
breadth_first_search(graph,src);
return 0;
}
| mission-peace/interview | C++/Graph Algorithms/Breadth First Search.cpp | C++ | apache-2.0 | 843 |
function Bibliography() {
this.searchOptions = {
source: 0,
value: '',
style: ''
};
this.bibliography = [];
this.bibliographyText = [];
this.localStorageKey = "Bibliography";
};
Bibliography.prototype.showBookSearchResult = function (results) {
for (key in results) {
var title = results[key].display.title;
var description = "";
var contributors = results[key].data.contributors;
contributors.forEach(function (contributors_item) {
if (description != "") {
description += ", " + contributors_item.first + " " + contributors_item.last;
} else {
description += contributors_item.first + " " + contributors_item.last;
}
});
if (results[key].display.publisher) {
description += " - " + results[key].display.publisher;
}
if (results[key].display.year) {
description += " - " + results[key].display.year;
}
createSearchItem(title, description, key);
}
};
Bibliography.prototype.showJournalSearchResult = function(results) {
results.forEach(function(results_item, i) {
var title = results_item.data.journal.title;
var description = results_item.data.pubjournal.title;
createSearchItem(title, description, i);
});
};
Bibliography.prototype.showWebSiteSearchResult = function (results) {
var urlSearchResult;
results.forEach(function(results_item, i) {
try {
urlSearchResult = new URL(results_item.display.displayurl).hostname;
} catch(error) {
urlSearchResult = results_item.display.displayurl;
}
createSearchItem(results_item.display.title + "(" + results_item.display.displayurl + ")", results_item.display.summary, i);
});
};
Bibliography.prototype.createCitations = function (id, data) {
var biblist = this;
$.ajax({
url: '/api/2.0/files/easybib-citation',
type: "POST",
data: {
citationData: JSON.stringify(data)
},
success: function(answer) {
if (answer.response.success) {
try {
var citation = JSON.parse(answer.response.citation);
if (citation.status === 'ok') {
biblist.bibliographyText.push({
id: id,
data: citation.data
});
createBibItem(id, citation.data);
}
} catch(e) {
console.log(e.message);
}
}
},
});
};
Bibliography.prototype.updateCitations = function (id, data) {
var biblist = this;
$.ajax({
url: '/api/2.0/files/easybib-citation',
type: "POST",
data: {
citationData: JSON.stringify(data)
},
success: function (answer) {
if (answer.response.success) {
try {
var citation = JSON.parse(answer.response.citation);
if (citation.status === 'ok') {
if (biblist.bibliographyText.length > 0) {
biblist.bibliographyText.forEach(function (item) {
if (item.id == id) {
item.data = citation.data;
}
});
}
createBibItem(id, citation.data);
}
} catch (e) {
console.log(e.message);
}
}
},
});
};
Bibliography.prototype.getCitation = function (id, foundData, bibliographyStorage, fileId) {
var biblist = this;
var source = foundData.results[id];
var data;
switch (this.searchOptions.source) {
case 0:
data = {
style: $('#styles option:selected').val() ? $('#styles option:selected').val() : "3d-research",
pubtype: source.data.pubtype,
pubnonperiodical: source.data.pubnonperiodical,
contributors: source.data.contributors,
other: source.data.other,
source: source.data.source
};
break;
case 1:
data = {
style: $('#styles option:selected').val() ? $('#styles option:selected').val() : "3d-research",
pubtype: source.data.pubtype,
pubjournal: source.data.pubjournal,
publication_type: source.data.publication_type,
contributors: source.data.contributors,
other: source.data.other,
source: source.data.source
};
break;
case 2:
source.data.pubonline.url = source.display.displayurl;
data = {
style: $('#styles option:selected').val() ? $('#styles option:selected').val() : "3d-research",
autocite: source.display.displayurl,
pubtype: source.data.pubtype,
pubonline: source.data.pubonline,
other: source.data.other,
website: source.data.website,
source: source.data.source
};
break;
default:
break;
};
$.ajax({
url: '/api/2.0/files/easybib-citation',
type: "POST",
data: {
citationData: JSON.stringify(data)
},
success: function (answer) {
if (answer.response.success && answer.response.citations != "error") {
var citation = JSON.parse(answer.response.citation);
if (citation.status === 'ok') {
saveCitation.call(biblist, citation, data, bibliographyStorage, fileId);
} else if (citation.status === 'error') {
alert("ERROR. " + citation.msg);
}
}
return true;
},
error: function(err) {
console.log(err);
}
});
};
Bibliography.prototype.fillListStyles = function (styles, bibliographyStyle) {
var selectStyles = $('#styles');
for (var style in styles) {
var value = styles[style];
selectStyles[0].options[selectStyles[0].options.length] = new Option(value, style);
}
$("#styles :first").remove();
selectStyles.attr('disabled', false);
if (bibliographyStyle) {
$("#styles option[value=" + bibliographyStyle + "]").attr('selected', 'true');
}
};
function escapeHtml(str) {
if (str) return $('<div />').text(str).html();
else return null;
};
function createSearchItem(title, description, id) {
var searchResult = $("#search_result");
$("#search_result").show();
$(".result-container .search-title").show();
$(".result-container .bibliography-title").hide();
$("#bib").hide();
searchResult.show();
var item =
"<div class=\"search-item\" id=" + escapeHtml(id) + ">" +
"<div class = \"citation\">" +
"<h4 style=\"overflow-x: hidden;margin:0\">" + escapeHtml(title) + "</h4>" +
"<p style=\";margin:0\">" + escapeHtml(description) + "</p>" +
"</div>" +
"<div class=\"add-button-container\">" +
"<div class=\"add-button\" onclick=\"addItem(this)\"></div>" +
"</div>" +
"</div>";
$('#titleContent').text('Your Search Results');
searchResult.append(item);
};
function createBibItem(id, data) {
var item = "<div class=\"bibliography-part\">" +
"<div class=\"bibliography-part-data\">" + escapeHtml(data) + "</div>" +
"<div class=\"del-button-container\">" +
"<div onclick=\"delBibliographyPart(this)\" id=bibliography-path_" + escapeHtml(id) + " class=\"del-bibliography-part\"></div>" +
"</div>" +
"</br>";
$('#bib').append(item);
};
function saveCitation(citation, data, bibliographyStorage, fileId) {
var id, bibliographyItem;
if (this.bibliography.length > 0) {
id = this.bibliography[this.bibliography.length - 1].id + 1;
} else {
id = 1;
}
bibliographyItem = {
id: id,
data: data
};
this.bibliography.push(bibliographyItem);
this.bibliographyText.push({ id: id, data: citation.data });
$("#search_result").empty();
$("#search_result").hide();
$(".result-container .search-title").hide();
$(".result-container .bibliography-title").show();
$("#bib").show();
createBibItem(id, citation.data);
if (!localStorageManager.isAvailable || fileId == null) {
return null;
} else {
if (bibliographyStorage) {
bibliographyStorage[fileId] = this.bibliography;
localStorageManager.setItem(this.localStorageKey, bibliographyStorage);
} else {
bibliographyStorage = {};
bibliographyStorage[fileId] = this.bibliography;
localStorageManager.setItem(this.localStorageKey, bibliographyStorage);
}
}
};
| ONLYOFFICE/CommunityServer | web/studio/ASC.Web.Studio/ThirdParty/plugin/easybib/bibliography.js | JavaScript | apache-2.0 | 9,168 |
package com.landian.crud.core.dao;
import com.landian.commons.page.PageListSupport;
import com.landian.commons.page.PageRequest;
import com.landian.crud.core.builder.SelectBuilder;
import com.landian.crud.core.builder.SqlBuilder;
import com.landian.crud.core.builder.impl.*;
import com.landian.crud.core.context.ResultMapContext;
import com.landian.crud.core.context.SystemContextFactory;
import com.landian.crud.core.context.impl.HashMapResultContext;
import com.landian.crud.core.converter.ResultContextConverter;
import com.landian.crud.core.converter.ResultContextConverterFactory;
import com.landian.crud.core.converter.impl.JavaBeanConverter;
import com.landian.crud.core.provider.ProviderHelper;
import com.landian.crud.core.result.SingleValue;
import com.landian.crud.core.result.StatisticMap;
import com.landian.crud.core.result.StatisticMapBuilder;
import com.landian.crud.core.sql.DeleteSQLBuilder;
import com.landian.crud.core.sql.InsertSQLBuilder;
import com.landian.crud.core.sql.PageSqlAdapter;
import com.landian.crud.core.sql.UpdateSQLBuilder;
import com.landian.sql.jpa.annotation.IdTypePolicy;
import com.landian.sql.jpa.context.BeanContext;
import com.landian.sql.jpa.context.ResultMapConfig;
import com.landian.sql.jpa.context.ResultMappingVirtual;
import com.landian.sql.jpa.criterion.Criterion;
import com.landian.sql.jpa.criterion.CriterionAppender;
import com.landian.sql.jpa.criterion.FieldAppender;
import com.landian.sql.jpa.criterion.Restrictions;
import com.landian.sql.jpa.log.JieLoggerProxy;
import com.landian.sql.jpa.order.Order;
import com.landian.sql.jpa.order.OrderAppender;
import com.landian.sql.jpa.sql.SelectUnitAppender;
import com.landian.sql.jpa.sql.SelectUnitRestrictions;
import com.landian.sql.jpa.sql.UpdateUnitAppender;
import com.landian.sql.jpa.utils.ConvertUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* ProxyDaoSupport
* @author cao.jl
* to be continute
* * 毫无疑问,SpringData才是大神版的进化封装
*/
@Repository
public class ProxyDaoSupport<T> {
@SuppressWarnings("unused")
private static final Logger logger = Logger.getLogger(ProxyDaoSupport.class);
private static final Logger infoSQLLogger = Logger.getLogger("infoSQL");
@Autowired
private ProxyDao proxyDao;
private void proxyInfo(Object object){
if(null != infoSQLLogger){
infoSQLLogger.info(object);
}
}
/**
* 指定ID业务Bean是否存在
* @param beanId
* @param beanContext
* @return
*/
public boolean isExist(long beanId,BeanContext beanContext) {
String beanIdColumn = this.getBeanIdColumn(beanContext);
CommonSelectSQLBuilder builder = CommonSelectSQLBuilder.getInstance(beanContext.getTableName(),
SelectUnitRestrictions.column(beanIdColumn),
Restrictions.eq(beanIdColumn, beanId),
Order.asc(beanIdColumn));
HashMapResultContext hashMapResultContext = this.doFind(builder.SQL());
if(hashMapResultContext.getResultCount() > 0){
return true;
}
return false;
}
public int doInsert(String sql){
return proxyDao.doInsert(sql);
}
/**
* 插入对像bean
* @param bean
* @param beanContext
*/
public int insertWithId(Object bean,BeanContext beanContext){
String sql = InsertSQLBuilder.insertWithIdSQL(bean, beanContext);
return proxyDao.doInsertWidthId(sql);
}
/**
* 插入对像bean
* @param bean
* @param beanContext
*/
public void insert(Object bean,BeanContext beanContext){
String sql = InsertSQLBuilder.insertSQL(bean, beanContext);
Object idObject = proxyDao.doInsertAndReturnId(sql);
//回填ID
refillId(bean, beanContext, idObject);
}
/**
* 回填业务Bean ID
*/
private void refillId(Object bean, BeanContext beanContext,Object idObject){
try {
String idFieldName = beanContext.getIdFieldName();
String setMethodName = ProviderHelper.toSetMethodName(idFieldName);
Method idSetMethod = null;
SingleValue idSingleValue = SingleValue.newInstance(idObject);
Object fixIdObject = null;
if(IdTypePolicy.INTEGER == beanContext.getIdType()){
fixIdObject = idSingleValue.integerValue();
idSetMethod = bean.getClass().getDeclaredMethod(setMethodName,Integer.class);
}else if(IdTypePolicy.LONG == beanContext.getIdType()){
fixIdObject = idSingleValue.longValue();
idSetMethod = bean.getClass().getDeclaredMethod(setMethodName,Long.class);
}else if(IdTypePolicy.BIGDECIMAL == beanContext.getIdType()){
fixIdObject = idSingleValue.bigDecimalValue();
idSetMethod = bean.getClass().getDeclaredMethod(setMethodName,BigDecimal.class);
}
if(null == idSetMethod){
String msg = MessageFormat.format("ID回填策略未实现,目标对像[{0}],目标类型[{1}]",bean,idObject);
logger.warn(msg);
}else{
idSetMethod.invoke(bean,new Object[]{fixIdObject});
}
}catch (Exception e) {
String errorMsg = "回填业务Bean ID异常!";
JieLoggerProxy.error(logger, errorMsg);
JieLoggerProxy.error(logger, e);
throw new RuntimeException(errorMsg);
}
}
/**
* 更新对像非空属性值
* @param bean
* @param beanContext
*/
public int updateNotNull(Object bean, BeanContext beanContext) {
String sql = UpdateSQLBuilder.updateNotNull(bean, beanContext);
return proxyDao.doUpdate(sql);
}
/**
* 更新字段
* @param updateUnitAppender 更新单元追加器
* @param criterionAppender 条件追加器
* @param beanContext
* @return
* @throws Exception
*/
public int update(UpdateUnitAppender updateUnitAppender, CriterionAppender criterionAppender,
BeanContext beanContext){
String sql = UpdateSqlBuilder.getInstance(beanContext.getTableName(), updateUnitAppender, criterionAppender).SQL();
return proxyDao.doUpdate(sql);
}
/**
* 更新对像非空属性值
* @param sql
*/
public int doUpdate(String sql) {
return proxyDao.doUpdate(sql);
}
/**
* 查询统计
* 由于经常需要根据ID(某属性作为key),统计某属性总计(某属性总计作为Value)
* @param sql
* @param resultMapConfig
* @return
*/
public StatisticMap queryAsStatisticMap(String sql,ResultMapConfig resultMapConfig) {
HashMapResultContext hashMapResultContext = doFind(sql);
return StatisticMapBuilder.buildStatisticMap(resultMapConfig, hashMapResultContext);
}
/**
* 根据SQL查询,返回结果集
* @param sql
*/
public HashMapResultContext doFind(String sql){
proxyInfo(sql);
List<Map<String, Object>> resultContext = proxyDao.doFind(sql);
HashMapResultContext hashMapResultContext = new HashMapResultContext(resultContext);
return hashMapResultContext;
}
/**
* 根据SQL查询,返回结果集
* @param sql
*/
public List doFind(String sql,Class clazz){
proxyInfo(clazz);
proxyInfo(sql);
//转换器
ResultContextConverter converter = JavaBeanConverter.newInstance(clazz);
//适配调用
return this.doFind(sql, converter);
}
/**
* @param sql
* @param converter 结果集转换器
*/
public List<T> doFindPage(String sql, int start, int pageSize, ResultContextConverter converter){
PageSqlAdapter pageSqlAdapter = SystemContextFactory.getPageSqlAdapter();
String pageSQL = pageSqlAdapter.wrapSQL(sql,start,pageSize);
//结果集
List<Map<String, Object>> resultList = proxyDao.doFind(pageSQL);
//处理结果集
List<T> beanList = new ArrayList<T>();
if(CollectionUtils.isNotEmpty(resultList)){
for(Map<String, Object> dataMap : resultList){
@SuppressWarnings("unchecked")
T bean = (T) converter.convert(dataMap);
beanList.add(bean);
}
}
return beanList;
}
/**
* @param sql
* @param converter 结果集转换器
*/
public List<T> doFind(String sql, ResultContextConverter converter){
//结果集
HashMapResultContext hashMapResultContext = this.doFind(sql);
//处理结果集
List<T> beanList = new ArrayList<T>();
List<Map<String, Object>> resultList = hashMapResultContext.getResultObject();
if(CollectionUtils.isNotEmpty(resultList)){
for(Map<String, Object> dataMap : resultList){
@SuppressWarnings("unchecked")
T bean = (T) converter.convert(dataMap);
beanList.add(bean);
}
}
return beanList;
}
/**
* 根据ID查询对像
* @param beanId
* @param beanContext
*/
public T queryById(int beanId, BeanContext beanContext){
Integer id = beanId;
return this.queryById(id.longValue(), beanContext);
}
/**
* 根据ID查询对像
* @param beanId
* @param beanContext
*/
public T queryById(long beanId,BeanContext beanContext){
List<Long> ids = new ArrayList<Long>();
ids.add(beanId);
List<T> list = this.queryByIds(ids,beanContext);
if(!CollectionUtils.isEmpty(list)){
return list.get(0);
}
return null;
}
/**
* 根据ID列表,查询对像集
* @param beanContext
* @param ids
*/
public List<T> queryByIds(BeanContext beanContext,List<Integer> ids){
if(CollectionUtils.isEmpty(ids)){
return Collections.EMPTY_LIST;
}
return queryByIds(ConvertUtils.Int2long(ids),beanContext);
}
/**
* 根据ID列表,查询对像集
* @param ids
* @param beanContext
*/
public List<T> queryByIds(List<Long> ids,BeanContext beanContext){
if(CollectionUtils.isEmpty(ids)){
return Collections.EMPTY_LIST;
}
CriterionAppender criterionAppender = CriterionAppender.newInstance();
String column = beanContext.getIdFieldName();
criterionAppender.add(Restrictions.in(column, ids,0l));
List<T> beanList = queryBean(beanContext,criterionAppender);
return beanList;
}
/**
* 此方法非元数据表,谨慎使用
* 查询Bean全部对像
* @param beanContext
*/
public List<T> queryBeanAll(BeanContext beanContext) {
return queryBean(beanContext,null,null);
}
/**
* 查询Bean
* @param beanContext
* @param criterionAppender
*/
public List<T> queryBean(BeanContext beanContext,CriterionAppender criterionAppender) {
return queryBean(beanContext,criterionAppender,null);
}
/**
* 查询Bean
* @param beanContext
* @param proxyOrderAppender
*/
public List<T> queryBean(BeanContext beanContext,OrderAppender proxyOrderAppender) {
return queryBean(beanContext,null,proxyOrderAppender);
}
/**
* 查询bean
* @param beanContext
* @param criterionAppender
* @param proxyOrderAppender
*/
public List<T> queryBean(BeanContext beanContext,CriterionAppender criterionAppender,
OrderAppender proxyOrderAppender) {
String tableName = beanContext.getTableName();
//选择器
Class<T> beanClass = beanContext.getBeanClass();
SelectBuilder selectBuilder = SelectBuilderFactory.builder(beanClass);
SqlBuilder sqlBuilder = SqlBuilderFactory.builder(tableName, beanClass, selectBuilder, criterionAppender, proxyOrderAppender);
//转换器
ResultContextConverter resultContextConverter = ResultContextConverterFactory.build(beanContext.getBeanClass());
//数据集
List<T> beanList = queryBean(sqlBuilder,resultContextConverter);
return beanList;
}
/**
* 查询bean
* @param beanContext
* @param criterionAppender
* @param proxyOrderAppender
*/
public List<T> queryBeanField(BeanContext beanContext,FieldAppender fieldAppender, CriterionAppender criterionAppender,
OrderAppender proxyOrderAppender) {
String tableName = beanContext.getTableName();
//选择器
SelectBuilder selectBuilder = new FieldAppenderSelectBuilder(fieldAppender,beanContext.getBeanClass());
SqlBuilder sqlBuilder = SqlBuilderFactory.builder(tableName, beanContext.getBeanClass(), selectBuilder, criterionAppender, proxyOrderAppender);
//转换器
ResultContextConverter resultContextConverter = ResultContextConverterFactory.build(beanContext.getBeanClass());
//数据集
List<T> beanList = queryBean(sqlBuilder, resultContextConverter);
return beanList;
}
/**
* 查询对像信息
* @param tableName
* @param clazz
* @param selectUnitAppender
* @param criterionAppender
* @param proxyOrderAppender
* @return
*/
public HashMapResultContext queryBeanInfo(String tableName, Class clazz,SelectUnitAppender selectUnitAppender,
CriterionAppender criterionAppender, OrderAppender proxyOrderAppender) {
//选择器
SelectBuilder selectBuilder = SelectBuilderFactory.builder(selectUnitAppender);
//SQL构建器
SqlBuilder sqlBuilder = SqlBuilderFactory.builder(tableName, clazz, selectBuilder, criterionAppender, proxyOrderAppender);
//结果集
String sql = sqlBuilder.SQL();
HashMapResultContext hashMapResultContext = this.doFind(sql);
return hashMapResultContext;
}
/**
* 决定不重载此方法基于以下理由
* 1.分页查询大部份情况需要追加条件和排序
* 2.参数已经没有更好重构感觉,个人感觉不能再少了,
* 重载会令方法组数量变多
* 3.criterionAppender proxyOrderAppender 入参可为null,
* 里面的SqlBuilder已作了相应处理,
* @param beanContext
* @param criterionAppender
* @param proxyOrderAppender
* @param pageRequest
* @return
*/
public PageListSupport<T> queryBeanPage(BeanContext beanContext,
CriterionAppender criterionAppender,OrderAppender proxyOrderAppender,PageRequest pageRequest) {
String tableName = beanContext.getTableName();
//选择器
SelectBuilder selectBuilder = SelectBuilderFactory.builder(beanContext.getBeanClass());
//加强条件追加器
if(null == criterionAppender){
criterionAppender = CriterionAppender.newInstance();
}
//SQL建造器
SqlBuilder sqlBuilder = SqlBuilderFactory.builder(tableName, beanContext.getBeanClass(), selectBuilder, criterionAppender, proxyOrderAppender);
//转换器
ResultContextConverter resultContextConverter = ResultContextConverterFactory.build(beanContext.getBeanClass());
//分页查询
int start = getPageStart(pageRequest);
int size = pageRequest.getPageSize();
List<T> beanList = doFindPage(sqlBuilder.SQL(), start, size, resultContextConverter);
//封装PageListSupport
PageListSupport<T> pageListSupport = new PageListSupport<T>();
//总数查询
Long count = 0l;
if(!CollectionUtils.isEmpty(beanList)){
HashMapResultContext hashMapResultContext = this.doFind(sqlBuilder.SQLCount());
Object countObj = hashMapResultContext.singleResult();
if(null != countObj){
SingleValue singleValue = SingleValue.newInstance(countObj);
count = singleValue.longValue();
}
}
pageListSupport.setList(beanList);
pageListSupport.setCount(count);
pageListSupport.setPageIndex(pageRequest.getPageIndex());
pageListSupport.setPageSize(pageRequest.getPageSize());
return pageListSupport;
}
/**
* 查询Bean
* @param sqlBuilder
* @param resultContextConverter
*/
public List<T> queryBean(SqlBuilder sqlBuilder,ResultContextConverter resultContextConverter) {
return doFind(sqlBuilder.SQL(), resultContextConverter);
}
/**
* 得到业务Bean的id字段
* @param beanContext
* @return
*/
public String getBeanIdColumn(BeanContext beanContext){
String idFieldName = beanContext.getIdFieldName();
Map<String, ResultMappingVirtual> resultMappingMap = ResultMapContext.getResultMappingMap(beanContext.getBeanClass());
String columnName = resultMappingMap.get(idFieldName).getColumn();
return columnName;
}
/**
* author jie
* date 15/08/21
* 根据业务BeanID删除业务Bean
* @param beanId
* @param beanContext
* @return
*/
public int deleteById(long beanId, BeanContext beanContext) {
Criterion criterion = buildIdCriterion(beanId, beanContext);
String sql = DeleteSQLBuilder.buildDeleteSQL(beanContext.getTableName(), criterion);
return doDelete(sql);
}
/**
* 构建ID条件
* @param id
* @param beanContext
* @return
*/
public Criterion buildIdCriterion(long id, BeanContext beanContext){
String beanIdColumn = getBeanIdColumn(beanContext);
return Restrictions.eq(beanIdColumn,id);
}
/**
* 构建ID条件
* @param ids
* @param beanContext
* @return
*/
public Criterion buildIdCriterion(List<Long> ids, BeanContext beanContext){
String beanIdColumn = getBeanIdColumn(beanContext);
return Restrictions.in(beanIdColumn,ids,0l);
}
/**
* 根据ID批量删除
* @param ids
* @param beanContext
* @return
*/
public int deleteByIdLong(List<Long> ids,BeanContext beanContext) {
if(CollectionUtils.isEmpty(ids)){
return 0;
}
Criterion criterion = buildIdCriterion(ids, beanContext);
String sql = DeleteSQLBuilder.buildDeleteSQL(beanContext.getTableName(), criterion);
return doDelete(sql);
}
public int doDelete(String sql){
return proxyDao.doDelete(sql);
}
/**
* 得到构建的查询SQL
* @param beanContext
* @param criterionAppender
* @param proxyOrderAppender
* @return
*/
public String getQuerySQL(BeanContext beanContext, CriterionAppender criterionAppender, OrderAppender proxyOrderAppender) {
//选择器
SelectBuilder selectBuilder = SelectBuilderFactory.builder(beanContext.getBeanClass());
//SQL建造器
String tableName = beanContext.getTableName();
SqlBuilder sqlBuilder = SqlBuilderFactory.builder(tableName, beanContext.getBeanClass(), selectBuilder, criterionAppender, proxyOrderAppender);
return sqlBuilder.SQL();
}
private int getPageStart(PageRequest pageRequest) {
return pageRequest.getPageIndex() * pageRequest.getPageSize(); //起始分页位置
}
/**
* 根据SQL查询,返回结果集第一个对像
* @param sql
*/
public Object queryAsValueFirst(String sql,Class clazz){
List list = this.doFind(sql, clazz);
if(CollectionUtils.isEmpty(list)){
return null;
}
return list.get(0);
}
/**
* 根据SQL查询,返回单值列表结果
* @param sql
*/
public List queryAsValueList(String sql){
List list = Collections.EMPTY_LIST;
HashMapResultContext hashMapResultContext = doFind(sql);
if(hashMapResultContext.getResultCount() > 0){
list = hashMapResultContext.singleList();
}
return list;
}
/**
* 查询为SingleValue
* @param sql
* @return
*/
public SingleValue queryAsSingleValue(String sql) {
HashMapResultContext hashMapResultContext = this.doFind(sql);
Object object = hashMapResultContext.singleResult();
SingleValue singleValue = SingleValue.newInstance(object);
return singleValue;
}
/**
* 查询为SingleValueInt
* @param sql
* @return
*/
public int queryAsSingleValueInt(String sql) {
SingleValue singleValue = queryAsSingleValue(sql);
return singleValue.integerValue();
}
/**
* 查询为SingleValueLong
* @param sql
* @return
*/
public long queryAsSingleValueLong(String sql) {
SingleValue singleValue = queryAsSingleValue(sql);
return singleValue.longValue();
}
/**
* 查询为Long值列表
* @param sql
* @return
*/
public List<Long> queryAsLongValue(String sql) {
return proxyDao.queryAsLongValue(sql);
}
/**
* 查询为Long值列表
* @param sql
* @param start 开始位置
* @param size 查询大小
* @return
*/
public List<Long> queryAsLongValue(String sql, int start, int size) {
PageSqlAdapter pageSqlAdapter = SystemContextFactory.getPageSqlAdapter();
String sqlQ = pageSqlAdapter.wrapSQL(sql, start, size);
return proxyDao.queryAsLongValue(sqlQ);
}
/**
* 查询为Integer值列表
* @param sql
* @return
*/
public List<Integer> queryAsIntValue(String sql) {
return proxyDao.queryAsIntValue(sql);
}
/**
* 查询为Integer值列表
* @param sql
* @param start 开始位置
* @param size 查询大小
* @return
*/
public List<Integer> queryAsIntValue(String sql, int start, int size) {
PageSqlAdapter pageSqlAdapter = SystemContextFactory.getPageSqlAdapter();
String sqlQ = pageSqlAdapter.wrapSQL(sql, start, size);
return proxyDao.queryAsIntValue(sqlQ);
}
}
| caojieliang/crud-core | src/main/java/com/landian/crud/core/dao/ProxyDaoSupport.java | Java | apache-2.0 | 20,038 |
package site.huozhu.home.controller.form;
/**
* ${DESCRIPTION}
*
* @author chuanxue.mcx
* @date 2017/09/06
*/
public class PagenationForm {
private int page = 1;
private int pageSize = 20;
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
}
| tomtrije/huozhu | server/huozhu/java/src/main/java/site/huozhu/home/controller/form/PagenationForm.java | Java | apache-2.0 | 483 |
/*
* Copyright 2014-2021 Lukas Krejci
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.revapi.java.checks.annotations;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import org.revapi.Difference;
import org.revapi.java.spi.CheckBase;
import org.revapi.java.spi.Code;
import org.revapi.java.spi.JavaAnnotationElement;
import org.revapi.java.spi.Util;
/**
* @author Lukas Krejci
*
* @since 0.1
*/
public final class Removed extends CheckBase {
@Override
protected List<Difference> doVisitAnnotation(JavaAnnotationElement oldAnnotation,
JavaAnnotationElement newAnnotation) {
if (oldAnnotation != null && newAnnotation == null && isAccessible(oldAnnotation.getParent())) {
return Collections.singletonList(createDifference(Code.ANNOTATION_REMOVED,
Code.attachmentsFor(oldAnnotation.getParent(), null, "annotationType",
Util.toHumanReadableString(oldAnnotation.getAnnotation().getAnnotationType()), "annotation",
Util.toHumanReadableString(oldAnnotation.getAnnotation()))));
}
return null;
}
@Override
public EnumSet<Type> getInterest() {
return EnumSet.of(Type.ANNOTATION);
}
}
| revapi/revapi | revapi-java/src/main/java/org/revapi/java/checks/annotations/Removed.java | Java | apache-2.0 | 1,860 |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Secure_Password_Repository.ViewModels
{
public class CategoryEdit
{
public Int32? CategoryId { get; set; }
[Required]
public string CategoryName { get; set; }
}
public class CategoryAdd : CategoryEdit
{
public Int32? Category_ParentID { get; set; }
}
public class CategoryDelete
{
public Int32? CategoryId { get; set; }
}
public class CategoryItem : CategoryEdit
{
[Required]
public Int32 Category_ParentID { get; set; }
public virtual ICollection<CategoryItem> SubCategories { get; set; }
public virtual ICollection<PasswordItem> Passwords { get; set; }
}
public class CategoryDisplayItem
{
public CategoryItem categoryListItem { get; set; }
public CategoryAdd categoryAddItem { get; set; }
public PasswordAdd passwordAddItem { get; set; }
}
} | thatcoderguy/Secure-Password-Repository | Secure Password Repository/ViewModels/CategoryViewModels.cs | C# | apache-2.0 | 1,022 |
module.exports = function(app, express) {
app.configure(function() {
app.use(express.logger());
});
app.configure('development', function() {
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
});
app.configure('production', function() {
app.use(express.errorHandler());
});
};
| Ken-Richard/tincan_nodejs | config/environment.js | JavaScript | apache-2.0 | 385 |
package com.ahars.domain.util;
import java.sql.Types;
import org.hibernate.dialect.H2Dialect;
public class FixedH2Dialect extends H2Dialect {
public FixedH2Dialect() {
super();
registerColumnType( Types.FLOAT, "real" );
}
}
| ahars/dataviz-jhipster | src/main/java/com/ahars/domain/util/FixedH2Dialect.java | Java | apache-2.0 | 251 |
package org.hl7.fhir.instance.model;
import java.util.*;
import org.hl7.fhir.instance.utils.IWorkerContext;
import org.hl7.fhir.utilities.Utilities;
public class ExpressionNode {
public enum Kind {
Name, Function, Constant, Group
}
public static class SourceLocation {
private int line;
private int column;
public SourceLocation(int line, int column) {
super();
this.line = line;
this.column = column;
}
public int getLine() {
return line;
}
public int getColumn() {
return column;
}
public void setLine(int line) {
this.line = line;
}
public void setColumn(int column) {
this.column = column;
}
public String toString() {
return Integer.toString(line)+", "+Integer.toString(column);
}
}
public enum Function {
Custom,
Empty, Not, Exists, SubsetOf, SupersetOf, IsDistinct, Distinct, Count, Where, Select, All, Repeat, Item /*implicit from name[]*/, As, Is, Single,
First, Last, Tail, Skip, Take, Iif, ToInteger, ToDecimal, ToString, Substring, StartsWith, EndsWith, Matches, ReplaceMatches, Contains, Replace, Length,
Children, Descendants, MemberOf, Trace, Today, Now, Resolve, Extension;
public static Function fromCode(String name) {
if (name.equals("empty")) return Function.Empty;
if (name.equals("not")) return Function.Not;
if (name.equals("exists")) return Function.Exists;
if (name.equals("subsetOf")) return Function.SubsetOf;
if (name.equals("supersetOf")) return Function.SupersetOf;
if (name.equals("isDistinct")) return Function.IsDistinct;
if (name.equals("distinct")) return Function.Distinct;
if (name.equals("count")) return Function.Count;
if (name.equals("where")) return Function.Where;
if (name.equals("select")) return Function.Select;
if (name.equals("all")) return Function.All;
if (name.equals("repeat")) return Function.Repeat;
if (name.equals("item")) return Function.Item;
if (name.equals("as")) return Function.As;
if (name.equals("is")) return Function.Is;
if (name.equals("single")) return Function.Single;
if (name.equals("first")) return Function.First;
if (name.equals("last")) return Function.Last;
if (name.equals("tail")) return Function.Tail;
if (name.equals("skip")) return Function.Skip;
if (name.equals("take")) return Function.Take;
if (name.equals("iif")) return Function.Iif;
if (name.equals("toInteger")) return Function.ToInteger;
if (name.equals("toDecimal")) return Function.ToDecimal;
if (name.equals("toString")) return Function.ToString;
if (name.equals("substring")) return Function.Substring;
if (name.equals("startsWith")) return Function.StartsWith;
if (name.equals("endsWith")) return Function.EndsWith;
if (name.equals("matches")) return Function.Matches;
if (name.equals("replaceMatches")) return Function.ReplaceMatches;
if (name.equals("contains")) return Function.Contains;
if (name.equals("replace")) return Function.Replace;
if (name.equals("length")) return Function.Length;
if (name.equals("children")) return Function.Children;
if (name.equals("descendants")) return Function.Descendants;
if (name.equals("memberOf")) return Function.MemberOf;
if (name.equals("trace")) return Function.Trace;
if (name.equals("today")) return Function.Today;
if (name.equals("now")) return Function.Now;
if (name.equals("resolve")) return Function.Resolve;
if (name.equals("extension")) return Function.Extension;
return null;
}
public String toCode() {
switch (this) {
case Empty : return "empty";
case Not : return "not";
case Exists : return "exists";
case SubsetOf : return "subsetOf";
case SupersetOf : return "supersetOf";
case IsDistinct : return "isDistinct";
case Distinct : return "distinct";
case Count : return "count";
case Where : return "where";
case Select : return "select";
case All : return "all";
case Repeat : return "repeat";
case Item : return "item";
case As : return "as";
case Is : return "is";
case Single : return "single";
case First : return "first";
case Last : return "last";
case Tail : return "tail";
case Skip : return "skip";
case Take : return "take";
case Iif : return "iif";
case ToInteger : return "toInteger";
case ToDecimal : return "toDecimal";
case ToString : return "toString";
case Substring : return "substring";
case StartsWith : return "startsWith";
case EndsWith : return "endsWith";
case Matches : return "matches";
case ReplaceMatches : return "replaceMatches";
case Contains : return "contains";
case Replace : return "replace";
case Length : return "length";
case Children : return "children";
case Descendants : return "descendants";
case MemberOf : return "memberOf";
case Trace : return "trace";
case Today : return "today";
case Now : return "now";
case Resolve : return "resolve";
case Extension : return "extension";
default: return "??";
}
}
}
public enum Operation {
Equals, Equivalent, NotEquals, NotEquivalent, LessThen, Greater, LessOrEqual, GreaterOrEqual, Is, As, Union, Or, And, Xor, Implies,
Times, DivideBy, Plus, Minus, Concatenate, Div, Mod, In, Contains;
public static Operation fromCode(String name) {
if (Utilities.noString(name))
return null;
if (name.equals("="))
return Operation.Equals;
if (name.equals("~"))
return Operation.Equivalent;
if (name.equals("!="))
return Operation.NotEquals;
if (name.equals("!~"))
return Operation.NotEquivalent;
if (name.equals(">"))
return Operation.Greater;
if (name.equals("<"))
return Operation.LessThen;
if (name.equals(">="))
return Operation.GreaterOrEqual;
if (name.equals("<="))
return Operation.LessOrEqual;
if (name.equals("|"))
return Operation.Union;
if (name.equals("or"))
return Operation.Or;
if (name.equals("and"))
return Operation.And;
if (name.equals("xor"))
return Operation.Xor;
if (name.equals("is"))
return Operation.Is;
if (name.equals("as"))
return Operation.As;
if (name.equals("*"))
return Operation.Times;
if (name.equals("/"))
return Operation.DivideBy;
if (name.equals("+"))
return Operation.Plus;
if (name.equals("-"))
return Operation.Minus;
if (name.equals("&"))
return Operation.Concatenate;
if (name.equals("implies"))
return Operation.Implies;
if (name.equals("div"))
return Operation.Div;
if (name.equals("mod"))
return Operation.Mod;
if (name.equals("in"))
return Operation.In;
if (name.equals("contains"))
return Operation.Contains;
return null;
}
public String toCode() {
switch (this) {
case Equals : return "=";
case Equivalent : return "~";
case NotEquals : return "!=";
case NotEquivalent : return "!~";
case Greater : return ">";
case LessThen : return "<";
case GreaterOrEqual : return ">=";
case LessOrEqual : return "<=";
case Union : return "|";
case Or : return "or";
case And : return "and";
case Xor : return "xor";
case Times : return "*";
case DivideBy : return "/";
case Plus : return "+";
case Minus : return "-";
case Concatenate : return "&";
case Implies : return "implies";
case Is : return "is";
case As : return "as";
case Div : return "div";
case Mod : return "mod";
case In : return "in";
case Contains : return "contains";
default: return "??";
}
}
}
public enum CollectionStatus {
SINGLETON, ORDERED, UNORDERED
}
public static class TypeDetails {
@Override
public String toString() {
return (collectionStatus == null ? "" : collectionStatus.toString())+(types == null ? "[]" : types.toString());
}
private Set<String> types = new HashSet<String>();
private CollectionStatus collectionStatus;
public TypeDetails(CollectionStatus collectionStatus, String... names) {
super();
this.collectionStatus = collectionStatus;
for (String n : names)
this.types.add(n);
}
public TypeDetails(CollectionStatus collectionStatus, Set<String> names) {
super();
this.collectionStatus = collectionStatus;
for (String n : names)
this.types.add(n);
}
public void addType(String n) {
this.types.add(n);
}
public void addTypes(Collection<String> n) {
this.types.addAll(n);
}
public boolean hasType(IWorkerContext context, String... tn) {
for (String t: tn)
if (types.contains(t))
return true;
for (String t: tn) {
StructureDefinition sd = context.fetchResource(StructureDefinition.class, "http://hl7.org/fhir/StructureDefinition/"+t);
while (sd != null) {
if (types.contains(sd.getId()))
return true;
if (sd.hasBase())
sd = context.fetchResource(StructureDefinition.class, sd.getBase());
else
sd = null;
}
}
return false;
}
public void update(TypeDetails source) {
types.addAll(source.types);
if (collectionStatus == null)
collectionStatus = source.collectionStatus;
else if (source.collectionStatus == CollectionStatus.UNORDERED)
collectionStatus = source.collectionStatus;
else
collectionStatus = CollectionStatus.ORDERED;
}
public TypeDetails union(TypeDetails right) {
TypeDetails result = new TypeDetails(null);
if (right.collectionStatus == CollectionStatus.UNORDERED || collectionStatus == CollectionStatus.UNORDERED)
result.collectionStatus = CollectionStatus.UNORDERED;
else
result.collectionStatus = CollectionStatus.ORDERED;
result.types.addAll(types);
result.types.addAll(right.types);
return result;
}
public boolean hasNoTypes() {
return types.isEmpty();
}
public Set<String> getTypes() {
return types;
}
public TypeDetails toSingleton() {
TypeDetails result = new TypeDetails(CollectionStatus.SINGLETON);
result.types.addAll(types);
return result;
}
public CollectionStatus getCollectionStatus() {
return collectionStatus;
}
public boolean hasType(Set<String> tn) {
for (String t: tn)
if (types.contains(t))
return true;
return false;
}
public String describe() {
return types.toString();
}
public String getType() {
for (String t : types)
return t;
return null;
}
}
//the expression will have one of either name or constant
private String uniqueId;
private Kind kind;
private String name;
private String constant;
private Function function;
private List<ExpressionNode> parameters; // will be created if there is a function
private ExpressionNode inner;
private ExpressionNode group;
private Operation operation;
private boolean proximal; // a proximal operation is the first in the sequence of operations. This is significant when evaluating the outcomes
private ExpressionNode opNext;
private SourceLocation start;
private SourceLocation end;
private SourceLocation opStart;
private SourceLocation opEnd;
private TypeDetails types;
private TypeDetails opTypes;
public ExpressionNode(int uniqueId) {
super();
this.uniqueId = Integer.toString(uniqueId);
}
public String toString() {
StringBuilder b = new StringBuilder();
switch (kind) {
case Name:
b.append(name);
break;
case Function:
if (function == Function.Item)
b.append("[");
else {
b.append(name);
b.append("(");
}
boolean first = true;
for (ExpressionNode n : parameters) {
if (first)
first = false;
else
b.append(", ");
b.append(n.toString());
}
if (function == Function.Item)
b.append("]");
else {
b.append(")");
}
break;
case Constant:
b.append(Utilities.escapeJava(constant));
break;
case Group:
b.append("(");
b.append(group.toString());
b.append(")");
}
if (inner != null) {
b.append(".");
b.append(inner.toString());
}
if (operation != null) {
b.append(" ");
b.append(operation.toCode());
b.append(" ");
b.append(opNext.toString());
}
return b.toString();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getConstant() {
return constant;
}
public void setConstant(String constant) {
this.constant = constant;
}
public Function getFunction() {
return function;
}
public void setFunction(Function function) {
this.function = function;
if (parameters == null)
parameters = new ArrayList<ExpressionNode>();
}
public boolean isProximal() {
return proximal;
}
public void setProximal(boolean proximal) {
this.proximal = proximal;
}
public Operation getOperation() {
return operation;
}
public void setOperation(Operation operation) {
this.operation = operation;
}
public ExpressionNode getInner() {
return inner;
}
public void setInner(ExpressionNode value) {
this.inner = value;
}
public ExpressionNode getOpNext() {
return opNext;
}
public void setOpNext(ExpressionNode value) {
this.opNext = value;
}
public List<ExpressionNode> getParameters() {
return parameters;
}
public boolean checkName() {
if (!name.startsWith("$"))
return true;
else
return name.equals("$this");
}
public Kind getKind() {
return kind;
}
public void setKind(Kind kind) {
this.kind = kind;
}
public ExpressionNode getGroup() {
return group;
}
public void setGroup(ExpressionNode group) {
this.group = group;
}
public SourceLocation getStart() {
return start;
}
public void setStart(SourceLocation start) {
this.start = start;
}
public SourceLocation getEnd() {
return end;
}
public void setEnd(SourceLocation end) {
this.end = end;
}
public SourceLocation getOpStart() {
return opStart;
}
public void setOpStart(SourceLocation opStart) {
this.opStart = opStart;
}
public SourceLocation getOpEnd() {
return opEnd;
}
public void setOpEnd(SourceLocation opEnd) {
this.opEnd = opEnd;
}
public String getUniqueId() {
return uniqueId;
}
public int parameterCount() {
if (parameters == null)
return 0;
else
return parameters.size();
}
public String Canonical() {
StringBuilder b = new StringBuilder();
write(b);
return b.toString();
}
public String summary() {
switch (kind) {
case Name: return uniqueId+": "+name;
case Function: return uniqueId+": "+function.toString()+"()";
case Constant: return uniqueId+": "+constant;
case Group: return uniqueId+": (Group)";
}
return "??";
}
private void write(StringBuilder b) {
switch (kind) {
case Name:
b.append(name);
break;
case Constant:
b.append(constant);
break;
case Function:
b.append(function.toCode());
b.append('(');
boolean f = true;
for (ExpressionNode n : parameters) {
if (f)
f = false;
else
b.append(", ");
n.write(b);
}
b.append(')');
break;
case Group:
b.append('(');
group.write(b);
b.append(')');
}
if (inner != null) {
b.append('.');
inner.write(b);
}
if (operation != null) {
b.append(' ');
b.append(operation.toCode());
b.append(' ');
opNext.write(b);
}
}
public String check() {
switch (kind) {
case Name:
if (Utilities.noString(name))
return "No Name provided @ "+location();
break;
case Function:
if (function == null)
return "No Function id provided @ "+location();
for (ExpressionNode n : parameters) {
String msg = n.check();
if (msg != null)
return msg;
}
break;
case Constant:
if (Utilities.noString(constant))
return "No Constant provided @ "+location();
break;
case Group:
if (group == null)
return "No Group provided @ "+location();
else {
String msg = group.check();
if (msg != null)
return msg;
}
}
if (inner != null) {
String msg = inner.check();
if (msg != null)
return msg;
}
if (operation == null) {
if (opNext != null)
return "Next provided when it shouldn't be @ "+location();
}
else {
if (opNext == null)
return "No Next provided @ "+location();
else
opNext.check();
}
return null;
}
private String location() {
return Integer.toString(start.line)+", "+Integer.toString(start.column);
}
public TypeDetails getTypes() {
return types;
}
public void setTypes(TypeDetails types) {
this.types = types;
}
public TypeDetails getOpTypes() {
return opTypes;
}
public void setOpTypes(TypeDetails opTypes) {
this.opTypes = opTypes;
}
}
| eug48/hapi-fhir | hapi-fhir-structures-hl7org-dstu2/src/main/java/org/hl7/fhir/instance/model/ExpressionNode.java | Java | apache-2.0 | 17,778 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.password_manager;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.support.v7.app.AlertDialog;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import org.chromium.base.ApiCompatibilityUtils;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.signin.AccountManagementFragment;
import org.chromium.components.url_formatter.UrlFormatter;
import org.chromium.ui.base.WindowAndroid;
import org.chromium.ui.widget.Toast;
/**
* A dialog offers the user the ability to choose credentials for authentication. User is
* presented with username along with avatar and full name in case they are available.
* Native counterpart should be notified about credentials user have chosen and also if user
* haven't chosen anything.
*/
public class AccountChooserDialog
implements DialogInterface.OnClickListener, DialogInterface.OnDismissListener {
private final Context mContext;
private final Credential[] mCredentials;
/**
* Title of the dialog, contains Smart Lock branding for the Smart Lock users.
*/
private final String mTitle;
private final int mTitleLinkStart;
private final int mTitleLinkEnd;
private final String mOrigin;
private final String mSigninButtonText;
private ArrayAdapter<Credential> mAdapter;
private boolean mIsDestroyed;
private boolean mWasDismissedByNative;
/**
* Holds the reference to the credentials which were chosen by the user.
*/
private Credential mCredential;
private long mNativeAccountChooserDialog;
private AlertDialog mDialog;
/**
* True, if credentials were selected via "Sign In" button instead of clicking on the credential
* itself.
*/
private boolean mSigninButtonClicked;
private AccountChooserDialog(Context context, long nativeAccountChooserDialog,
Credential[] credentials, String title, int titleLinkStart, int titleLinkEnd,
String origin, String signinButtonText) {
mNativeAccountChooserDialog = nativeAccountChooserDialog;
mContext = context;
mCredentials = credentials.clone();
mTitle = title;
mTitleLinkStart = titleLinkStart;
mTitleLinkEnd = titleLinkEnd;
mOrigin = origin;
mSigninButtonText = signinButtonText;
mSigninButtonClicked = false;
}
/**
* Creates and shows the dialog which allows user to choose credentials for login.
* @param credentials Credentials to display in the dialog.
* @param title Title message for the dialog, which can contain Smart Lock branding.
* @param titleLinkStart Start of a link in case title contains Smart Lock branding.
* @param titleLinkEnd End of a link in case title contains Smart Lock branding.
* @param origin Address of the web page, where dialog was triggered.
*/
@CalledByNative
private static AccountChooserDialog createAndShowAccountChooser(WindowAndroid windowAndroid,
long nativeAccountChooserDialog, Credential[] credentials, String title,
int titleLinkStart, int titleLinkEnd, String origin, String signinButtonText) {
Activity activity = windowAndroid.getActivity().get();
if (activity == null) return null;
AccountChooserDialog chooser =
new AccountChooserDialog(activity, nativeAccountChooserDialog, credentials, title,
titleLinkStart, titleLinkEnd, origin, signinButtonText);
chooser.show();
return chooser;
}
private ArrayAdapter<Credential> generateAccountsArrayAdapter(
Context context, Credential[] credentials) {
return new ArrayAdapter<Credential>(context, 0 /* resource */, credentials) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView =
inflater.inflate(R.layout.account_chooser_dialog_item, parent, false);
}
convertView.setTag(position);
Credential credential = getItem(position);
ImageView avatarView = (ImageView) convertView.findViewById(R.id.profile_image);
Bitmap avatar = credential.getAvatar();
if (avatar != null) {
avatarView.setImageBitmap(avatar);
} else {
avatarView.setImageResource(R.drawable.account_management_no_picture);
}
TextView mainNameView = (TextView) convertView.findViewById(R.id.main_name);
TextView secondaryNameView =
(TextView) convertView.findViewById(R.id.secondary_name);
if (credential.getFederation().isEmpty()) {
// Not federated credentials case
if (credential.getDisplayName().isEmpty()) {
mainNameView.setText(credential.getUsername());
secondaryNameView.setVisibility(View.GONE);
} else {
mainNameView.setText(credential.getDisplayName());
secondaryNameView.setText(credential.getUsername());
secondaryNameView.setVisibility(View.VISIBLE);
}
} else {
mainNameView.setText(credential.getUsername());
secondaryNameView.setText(credential.getFederation());
secondaryNameView.setVisibility(View.VISIBLE);
}
ImageButton pslInfoButton =
(ImageButton) convertView.findViewById(R.id.psl_info_btn);
final String originUrl = credential.getOriginUrl();
if (!originUrl.isEmpty()) {
pslInfoButton.setVisibility(View.VISIBLE);
pslInfoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showTooltip(
view,
UrlFormatter.formatUrlForSecurityDisplay(
originUrl, true /* showScheme */),
R.layout.material_tooltip);
}
});
}
return convertView;
}
};
}
private void show() {
View titleView =
LayoutInflater.from(mContext).inflate(R.layout.account_chooser_dialog_title, null);
TextView origin = (TextView) titleView.findViewById(R.id.origin);
origin.setText(mOrigin);
TextView titleMessageText = (TextView) titleView.findViewById(R.id.title);
if (mTitleLinkStart != 0 && mTitleLinkEnd != 0) {
SpannableString spanableTitle = new SpannableString(mTitle);
spanableTitle.setSpan(new ClickableSpan() {
@Override
public void onClick(View view) {
nativeOnLinkClicked(mNativeAccountChooserDialog);
mDialog.dismiss();
}
}, mTitleLinkStart, mTitleLinkEnd, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
titleMessageText.setText(spanableTitle, TextView.BufferType.SPANNABLE);
titleMessageText.setMovementMethod(LinkMovementMethod.getInstance());
} else {
titleMessageText.setText(mTitle);
}
mAdapter = generateAccountsArrayAdapter(mContext, mCredentials);
final AlertDialog.Builder builder =
new AlertDialog.Builder(mContext, R.style.AlertDialogTheme)
.setCustomTitle(titleView)
.setNegativeButton(R.string.cancel, this)
.setAdapter(mAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
mCredential = mCredentials[item];
}
});
if (!TextUtils.isEmpty(mSigninButtonText)) {
builder.setPositiveButton(mSigninButtonText, this);
}
mDialog = builder.create();
mDialog.setOnDismissListener(this);
mDialog.show();
}
private void showTooltip(View view, String message, int layoutId) {
Context context = view.getContext();
Resources resources = context.getResources();
LayoutInflater inflater = LayoutInflater.from(context);
TextView text = (TextView) inflater.inflate(layoutId, null);
text.setText(message);
text.announceForAccessibility(message);
// This is a work-around for a bug on Android versions KitKat and below
// (http://crbug.com/693076). The tooltip wouldn't be shown otherwise.
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP) {
text.setSingleLine(false);
}
// The tooltip should be shown above and to the left (right for RTL) of the info button.
// In order to do so the tooltip's location on the screen is determined. This location is
// specified with regard to the top left corner and ignores RTL layouts. For this reason the
// location of the tooltip is also specified as offsets to the top left corner of the
// screen. Since the tooltip should be shown above the info button, the height of the
// tooltip needs to be measured. Furthermore, the height of the statusbar is ignored when
// obtaining the icon's screen location, but must be considered when specifying a y offset.
// In addition, the measured width is needed in LTR layout, so that the right end of the
// tooltip aligns with the right end of the info icon.
final int[] screenPos = new int[2];
view.getLocationOnScreen(screenPos);
text.measure(MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
final int width = view.getWidth();
final int xOffset = ApiCompatibilityUtils.isLayoutRtl(view)
? screenPos[0]
: screenPos[0] + width - text.getMeasuredWidth();
final int statusBarHeightResourceId =
resources.getIdentifier("status_bar_height", "dimen", "android");
final int statusBarHeight = statusBarHeightResourceId > 0
? resources.getDimensionPixelSize(statusBarHeightResourceId)
: 0;
final int tooltipMargin = resources.getDimensionPixelSize(R.dimen.psl_info_tooltip_margin);
final int yOffset =
screenPos[1] - tooltipMargin - statusBarHeight - text.getMeasuredHeight();
// The xOffset is with regard to the left edge of the screen. Gravity.LEFT is deprecated,
// which is why the following line is necessary.
final int xGravity = ApiCompatibilityUtils.isLayoutRtl(view) ? Gravity.END : Gravity.START;
Toast toast = new Toast(context);
toast.setGravity(Gravity.TOP | xGravity, xOffset, yOffset);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(text);
toast.show();
}
@CalledByNative
private void imageFetchComplete(int index, Bitmap avatarBitmap) {
if (mIsDestroyed) return;
assert index >= 0 && index < mCredentials.length;
assert mCredentials[index] != null;
avatarBitmap = AccountManagementFragment.makeRoundUserPicture(avatarBitmap);
mCredentials[index].setBitmap(avatarBitmap);
ListView view = mDialog.getListView();
if (index >= view.getFirstVisiblePosition() && index <= view.getLastVisiblePosition()) {
// Profile image is in the visible range.
View credentialView = view.getChildAt(index - view.getFirstVisiblePosition());
if (credentialView == null) return;
ImageView avatar = (ImageView) credentialView.findViewById(R.id.profile_image);
avatar.setImageBitmap(avatarBitmap);
}
}
private void destroy() {
assert mNativeAccountChooserDialog != 0;
assert !mIsDestroyed;
mIsDestroyed = true;
nativeDestroy(mNativeAccountChooserDialog);
mNativeAccountChooserDialog = 0;
mDialog = null;
}
@CalledByNative
private void dismissDialog() {
assert !mWasDismissedByNative;
mWasDismissedByNative = true;
mDialog.dismiss();
}
@Override
public void onClick(DialogInterface dialog, int whichButton) {
if (whichButton == DialogInterface.BUTTON_POSITIVE) {
mCredential = mCredentials[0];
mSigninButtonClicked = true;
}
}
@Override
public void onDismiss(DialogInterface dialog) {
if (!mWasDismissedByNative) {
if (mCredential != null) {
nativeOnCredentialClicked(mNativeAccountChooserDialog, mCredential.getIndex(),
mSigninButtonClicked);
} else {
nativeCancelDialog(mNativeAccountChooserDialog);
}
}
destroy();
}
private native void nativeOnCredentialClicked(long nativeAccountChooserDialogAndroid,
int credentialId, boolean signinButtonClicked);
private native void nativeCancelDialog(long nativeAccountChooserDialogAndroid);
private native void nativeDestroy(long nativeAccountChooserDialogAndroid);
private native void nativeOnLinkClicked(long nativeAccountChooserDialogAndroid);
}
| mogoweb/365browser | app/src/main/java/org/chromium/chrome/browser/password_manager/AccountChooserDialog.java | Java | apache-2.0 | 14,683 |
$(document).ready(function() {
PromotionGroup.init();
PromotionGroup.loadImage();
$('#add-new-promotion').on('click', function(){
PromotionGroup.addNew();
})
$('#update-promotion').on('click', function(){
PromotionGroup.update();
})
// date picker
$('#promotion-add-end-date').datepicker({
format: "dd/mm/yyyy"
});
$('#promotion-add-start-date').datepicker({
format: "dd/mm/yyyy"
});
$('#promotion-update-start-date').datepicker({
format: "dd/mm/yyyy"
});
$('#promotion-update-end-date').datepicker({
format: "dd/mm/yyyy"
});
//editor
CKEDITOR.replace('promotionContent');
CKEDITOR.replace('promotionContentUpdate');
});
var PromotionGroup = function () {
// load list promotion
var loadListPromotion = function() {
var html = '';
$.ajax({
url: URL + 'spaCMS/promotion/xhrLoad_promotion_list',
type: 'get',
dataType: 'json',
})
.done(function(data) {
$('span#promotion-title-spa').text('DANH SÁCH TIN KHUYẾN MÃI');
if(data['list'].length >0 ){
$('#promotion-mesage-list').hide('fast');
var totalPublish = 0;
$.each(data['list'], function(k, val){
totalPublish = (val.promotion_state == 1)? totalPublish+1 : totalPublish;
var state = (val.promotion_state == 0)? "button-other": "hide";
var nowDay = new Date();
var endDay = val.promotion_end_date;
var createDay = val.promotion_create_date;
var end_Day = val.promotion_end_date;
var startDay = val.promotion_start_date;
var strMark = "";
strMark = (new Date(end_Day) < new Date())? "color: red; text-decoration: line-through;" : "";
createDay = createDay.substr(8, 2)+'/'+ createDay.substr(5, 2)+'/'+createDay.substr(0, 4);
startDay = startDay.substr(8, 2)+'/'+ startDay.substr(5, 2)+'/'+startDay.substr(0, 4);
end_Day = end_Day.substr(8, 2)+'/'+ end_Day.substr(5, 2)+'/'+end_Day.substr(0, 4);
// var promotion_img = JSON.parse(val.promotion_img);
html += '<li class="row promotion-list-item" data-toggle="modal" data-target="#updatePromotion" data-id-promotion="'+val.promotion_id+'">';
html += '<div class="col-md-5" style="font-weight: 600; color: #888;">'+val.promotion_title+'</div>';
html += '<div class="col-md-2 created-date">'+createDay+'</div>';
html += '<div class="col-md-2">'+startDay+'</div>';
html += '<div class="col-md-2 end-date" style="'+strMark+'">'+end_Day+'</div>';
// html += '<div class="col-md-1">'+totalDay+'</div>';
html += '<div class="col-md-1 text-right" style="padding:0px;">';
html += '<button class="button '+state+' promotion-items-publish" data-promotion-id="'+val.promotion_id+'" title="Kích hoạt"> ';
html += '<i class="fa fa-check"></i>';
html += '</button> ';
html += '<button class="button button-secondary redeem promotion-items-delete" data-promotion-id="'+val.promotion_id+'" title="Xóa"> ';
html += '<i class="fa fa-trash"></i>';
html += '</button>';
html += '</div>';
html += '</li>';
});
html += '<input class="input-hide-state" type="hidden" value="'+totalPublish+'">';
$('#promotion-content').html(html);
}else{
$('#promotion-content').html('');
$('#promotion-mesage-list').fadeIn('fast');
}
})
.always(function(){
$('.promotion-items-delete').on('click',function(e){
var id_promotion = $(this).attr('data-promotion-id');
e.stopPropagation();
var cfr = confirm('Bạn có muốn xóa promotion này không?');
if(cfr == true){
deletePromotion(id_promotion);
}
});
$('.promotion-items-publish').on('click',function(e){
var id_promotion = $(this).attr('data-promotion-id');
var self = $(this);
var state = 1; // kich hoat
e.stopPropagation();
if($('input.input-hide-state').val() >4){
alert('Chỉ hiển thị được 5 promotion.');
}else{
publishPromotion(id_promotion, state);
}
});
$('.btn-close-modal').on('click',function (){
$(".modal").modal('hide');
})
$('#refres-promotion').on('click', function(){
refresh();
});
$('li.promotion-list-item').on('click', function(){
var self = $(this);
var id_promotion = self.attr('data-id-promotion');
$.ajax({
url: URL + 'spaCMS/promotion/xhrLoad_promotion_item',
type: 'post',
dataType: 'json',
data: {promotion_id: id_promotion},
})
.done(function(data) {
$.each(data, function(index, value) {
var title = value.promotion_title;
var id_promotion = value.promotion_id;
// img
var image = JSON.parse(value.promotion_img);
var img = image.img;
var thumbnail = image.thumbnail;
//date
var sDate = value.promotion_start_date;
sDate = sDate.replace(/-/g,' ');
var startDate = new Date(sDate);
var endDate = value.promotion_end_date;
endDate = new Date(endDate.replace(/-/g,' '));
var mainUpdate = $('#updatePromotion');
mainUpdate.find('#promotion-update-title').val(title);
mainUpdate.attr('data-id-promotion', id_promotion);
$('#promotion-update-start-date').datepicker('update',startDate);
$('#promotion-update-end-date').datepicker('update',endDate);
CKEDITOR.instances.promotionContentUpdate.setData(value.promotion_content);
var items = $('#ListIM_editUS');
var caller = $('#iM_editUS');
// ktra so luong hinh anh da co
caller.hide();
var out = null;
var html = '<li class="single-picture">';
html += '<div class="single-picture-wrapper">';
html += '<img id="user_slide_thumbnail" src=":img_thumbnail" data-img=":data-image" style="width:100px; height:70px;">';
html += '<input type="hidden" name="user_service_image[]" value=":image">';
html += '</div>';
html += '<div class="del_image icons-delete2"></div>';
html += '</li>';
out = html.replace(':img_thumbnail', thumbnail);
out = out.replace(':data-image', img);
out = out.replace(':image', img);
items.html(out);
// del image
$('.del_image').on("click", function(){
var self = $(this).parent();
// self.attr("disabled","disabled");
self.remove();
// Truong hop dac biet, ktra so luong hinh anh da co
var childrens = items.children().length;
if(childrens < 5) {
caller.fadeIn();
}
});
});
})
.always(function() {
});
})
});
}
function loadAsidePublish() {
var html = '';
$.ajax({
url: URL + 'spaCMS/promotion/xhrLoad_promotion_publish',
type: 'post',
dataType: 'json',
data: {promotion_state: 1},
})
.done(function(respon) {
if(respon.length > 0){
$.each(respon, function(index, val) {
// img
var title = val.promotion_title;
var image = JSON.parse(val.promotion_img);
var img = image.img;
var thumbnail = image.thumbnail;
html += '<div class="promotion-item-publish">';
html += '<div class="row-fluid">';
html += '<div class="promotion-item-puslish-title col-md-12">';
html += '<i class="fa fa-bullhorn"></i>';
html += '<span>'+title+'</span>';
html += '</div>';
// html += '<div class="col-sm-1">';
html += '<button class="btn btn-black promotion-items-change-publish" data-promotion-id="'+val.promotion_id+'" title="Tạm ngưng"> <i class="fa fa-close"></i></button>';
html += '</div>';
// html += '</div>';
html += '<div class="promotion-item-publish-img row-fluid">';
html += '<img class="pic" alt="" src="'+thumbnail+'"> ';
html += '</div>';
html += '</div>';
}); //end each
}else{
html +='<div class="row-fluid" style="padding:5px;padding: 5px; border: 1px solid #d88c8a;background-color: #F7E4E4;"><span><i class="fa fa-warning" style="color: #ffcc00;"></i> Hiện tại không có quảng cáo nào hiển thị.</span></div>';
}
$('.promotion-item-publish-wrap').html(html);
})
.fail(function() {
console.log("error");
})
.always(function() {
$('.promotion-items-change-publish').on('click', function(){
var promotion_id = $(this).attr('data-promotion-id');
publishPromotion(promotion_id,0);
});
});
}
// add new promotion
var addNewPromotion = function() {
var title = $('#promotion-add-title').val();
var now = new Date();
month = now.getMonth()+1;
var start_day = $('#promotion-add-start-date').val();
if(start_day.length >0){
start_day = start_day.substring(6,10)+'-'+start_day.substring(3,5)+'-'+start_day.substring(0,2)+' 00:00:00';
}else{
start_day = now.getFullYear()+'-'+month+'-'+now.getDate()+' 00:00:00';
}
var end_day = $('#promotion-add-end-date').val();
if(end_day.length >0){
end_day = end_day.substring(6,10)+'-'+end_day.substring(3,5)+'-'+end_day.substring(0,2)+' 00:00:00';
}else{
end_day = now.getFullYear()+'-'+month+'-'+now.getDate()+' 00:00:00';
}
var url_img = "";
var tagImg = $('#user_slide_thumbnail');
if(tagImg[0]){
var img = tagImg.attr('data-img');
var thumbnail = tagImg.attr('src');
url_img={};
url_img.img = img;
url_img.thumbnail = thumbnail;
}else{
url_img={};
url_img.img = URL+'/public/assets/img/noimage.jpg';
url_img.thumbnail = URL+'/public/assets/img/noimage.jpg';
}
var content = CKEDITOR.instances.promotionContent.getData();
var message = $('.promotion-message');
var jdata = {"title": title, "start_date": start_day, "end_date": end_day, "url_img": JSON.stringify(url_img), "content": content};
if(title.length<4){
message.text('Tiêu đề phải hơn 4 kí tự.').fadeIn('fast');
return false;
}else{
$.ajax({
url: URL + 'spaCMS/promotion/xhrInsert_promotion_item',
type: 'post',
dataType: 'json',
data: jdata,
})
.done(function(respon) {
if(respon === 1){
alert('Thêm promotion thành công.')
}else{
alert('Thêm promotion thất bại, bạn vui lòng thử lại.')
}
})
.fail(function() {
})
.always(function() {
loadListPromotion();
$(".modal").modal('hide');
refresh();
});
}
}
//delete Promotion
var deletePromotion = function(id_promotion) {
$.ajax({
url: URL + 'spaCMS/promotion/xhrDelete_promotion_item',
type: 'post',
dataType: 'json',
data: {'id_promotion': id_promotion},
})
.done(function(respon) {
if(respon==0){
alert('Xóa promotion thất bại, Xin vui lòng kiểm tra lại');
}
})
.fail(function(error) {
console.log("error: "+error);
})
.always(function() {
loadListPromotion();
loadAsidePublish();
});
}
var publishPromotion = function(id_promotion,state){
$.ajax({
url: URL + 'spaCMS/promotion/xhrPublish_promotion_item',
type: 'post',
dataType: 'json',
data: {'id_promotion': id_promotion, 'state_promotion': state},
})
.done(function(respon) {
if(respon == 0){
alert('Kích hoạt promotion thất bại, Xin vui lòng kiểm tra lại');
}
})
.fail(function(error) {
console.log("error: "+error);
})
.always(function() {
loadListPromotion();
loadAsidePublish()
});
}
// update Promotion
var updatePromotion = function(){
var title = $('#promotion-update-title').val();
var id_promotion = $('#updatePromotion').attr('data-id-promotion');
var start_day = $('#promotion-update-start-date').val();
var end_day = $('#promotion-update-end-date').val();
var now = new Date();
var month = now.getMonth()+1;
if( end_day.length >0 ){
end_day = end_day.substring(6,10)+'-'+end_day.substring(3,5)+'-'+end_day.substring(0,2)+' 00:00:00';
} else {
end_day = now.getFullYear()+'-'+month+'-'+now.getDate()+' 00:00:00';
}
if( start_day.length >0 ){
start_day = start_day.substring(6,10)+'-'+start_day.substring(3,5)+'-'+start_day.substring(0,2)+' 00:00:00';
} else {
start_day = now.getFullYear()+'-'+month+'-'+now.getDate()+' 00:00:00';
}
var url_img = "";
var tagImg = $('#user_slide_thumbnail');
if(tagImg[0]){
var img = tagImg.attr('data-img');
var thumbnail = tagImg.attr('src');
// url_img = '{"img": "'+img+'", "thumbnail": "'+thumbnail+'"}';
url_img={};
url_img.img = img;
url_img.thumbnail = thumbnail;
}else{
url_img={};
url_img.img = URL+'/public/assets/img/noimage.jpg';
url_img.thumbnail = URL+'/public/assets/img/noimage.jpg';
}
var content = CKEDITOR.instances.promotionContentUpdate.getData();
var message = $('.promotion-message');
var jdata = {"id_promotion": id_promotion, "title": title, "start_date": start_day, "end_date": end_day, "url_img": JSON.stringify(url_img), "content": content};
if(title.length<4){
message.text('Tiêu đề phải hơn 4 kí tự.').fadeIn('fast');
return false;
}else{
$.ajax({
url: URL + 'spaCMS/promotion/xhrUpdate_promotion_item',
type: 'post',
dataType: 'json',
data: jdata,
})
.done(function(respon) {
if(respon === 1){
alert('Cập nhật promotion thành công.')
}else{
alert('Cập nhật promotion thất bại, bạn vui lòng thử lại.')
}
})
.fail(function() {
console.log("error");
})
.always(function() {
loadListPromotion();
loadAsidePublish();
$(".modal").modal('hide');
});
}
}
// refresh form promotion
var refresh = function(){
var frmPromotion = $('#form-promotion');
frmPromotion.find('input#promotion-add-title').val('');
frmPromotion.find('input#promotion-add-end-date').val('');
frmPromotion.find('input#promotion-add-end-date').val('');
frmPromotion.find('span.promotion-message').fadeOut('fast').text('');
CKEDITOR.instances.promotionContent.setData('');
// del image
var self = $('.del_image').parent();
self.remove();
$('#iM_addUS').fadeIn('fast');
}
// Image Manager
var imageManager = function() {
// Gán thuộc tính cover_id tương ứng
$('#iM_editUS').click(function(){
$('#imageManager_saveChange').attr('cover_id','editUS');
});
$('#iM_addUS').click(function(){
$('#imageManager_saveChange').attr('cover_id','addUS');
});
// <!-- Save Change -->
$('#imageManager_saveChange').on('click', function(evt) {
evt.preventDefault();
// Define position insert to image
var cover_id = $(this).attr('cover_id');
// Define selected image
var radio_checked = $("input:radio[name='iM-radio']:checked"); // Radio checked
// image and thumbnail_image
var image = radio_checked.val();
var thumbnail = radio_checked.attr('data-image');
// Truong hop dac biet
if(cover_id == 'addUS') {
var caller = $('#iM_addUS');
var items = $('#ListIM_addUS');
}
else if(cover_id == 'editUS') {
var caller = $('#iM_editUS');
var items = $('#ListIM_editUS');
}
// ktra so luong hinh anh da co
var childrens = items.children().length + 1;
if(childrens == 1) {
caller.hide();
}
var out = null;
var html = '<li class="single-picture">';
html += '<div class="single-picture-wrapper">';
html += '<img id="user_slide_thumbnail" src=":img_thumbnail" data-img=":data-image" style="width:100px; height:60px;">';
html += '<input type="hidden" name="user_service_image[]" value=":image">';
html += '</div>';
html += '<div class="del_image icons-delete2"></div>';
html += '</li>';
out = html.replace(':img_thumbnail', thumbnail);
out = out.replace(':data-image', image);
out = out.replace(':image', image);
items.html(out);
// del image
$('.del_image').on("click", function(){
var self = $(this).parent();
// self.attr("disabled","disabled");
self.remove();
// Truong hop dac biet, ktra so luong hinh anh da co
var childrens = items.children().length;
if(childrens < 1) {
caller.fadeIn();
}
});
// Hide Modal
$("#imageManager_modal").modal('hide');
});
}
return {
init: function() { loadListPromotion(); loadAsidePublish();},
addNew: function(){ addNewPromotion(); },
update: function(){ updatePromotion(); },
loadImage: function(){ imageManager(); }
}
var refresh = function() {
console.log('refresh');
}
}();
// function offsetDay(dayStart, dayEnd){
// var offset = dayEnd.getTime() - dayStart.getTime();
// console.log(dayEnd.getTime()+'-'+dayStart.getTime());
// // lấy độ lệch của 2 mốc thời gian, đơn vị tính là millisecond
// var totalDays = Math.round(offset / 1000 / 60 / 60 / 24);
// console.log(dayStart.getTime());
// return totalDays;
// }
| imtoantran/beleza | Views/spaCMS/promotion/js/spaCMS_promotion.js | JavaScript | apache-2.0 | 21,895 |
/*
* Copyright (C) 2010 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 orbin.deskclock;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.os.Parcelable;
import android.provider.AlarmClock;
import android.text.TextUtils;
import android.text.format.DateFormat;
import orbin.deskclock.alarms.AlarmStateManager;
import orbin.deskclock.data.DataModel;
import orbin.deskclock.data.Timer;
import orbin.deskclock.events.Events;
import orbin.deskclock.provider.Alarm;
import orbin.deskclock.provider.AlarmInstance;
import orbin.deskclock.provider.DaysOfWeek;
import orbin.deskclock.timer.TimerFragment;
import orbin.deskclock.uidata.UiDataModel;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import static android.text.format.DateUtils.SECOND_IN_MILLIS;
import static orbin.deskclock.uidata.UiDataModel.Tab.ALARMS;
import static orbin.deskclock.uidata.UiDataModel.Tab.TIMERS;
/**
* This activity is never visible. It processes all public intents defined by {@link AlarmClock}
* that apply to alarms and timers. Its definition in AndroidManifest.xml requires callers to hold
* the com.android.alarm.permission.SET_ALARM permission to complete the requested action.
*/
public class HandleApiCalls extends Activity {
private Context mAppContext;
@Override
protected void onCreate(Bundle icicle) {
try {
super.onCreate(icicle);
mAppContext = getApplicationContext();
final Intent intent = getIntent();
final String action = intent == null ? null : intent.getAction();
if (action == null) {
return;
}
switch (action) {
case AlarmClock.ACTION_SET_ALARM:
handleSetAlarm(intent);
break;
case AlarmClock.ACTION_SHOW_ALARMS:
handleShowAlarms();
break;
case AlarmClock.ACTION_SET_TIMER:
handleSetTimer(intent);
break;
case AlarmClock.ACTION_DISMISS_ALARM:
handleDismissAlarm(intent);
break;
case AlarmClock.ACTION_SNOOZE_ALARM:
handleSnoozeAlarm();
}
} finally {
finish();
}
}
private void handleDismissAlarm(Intent intent) {
// Change to the alarms tab.
UiDataModel.getUiDataModel().setSelectedTab(ALARMS);
// Open DeskClock which is now positioned on the alarms tab.
startActivity(new Intent(mAppContext, DeskClock.class));
new DismissAlarmAsync(mAppContext, intent, this).execute();
}
public static void dismissAlarm(Alarm alarm, Context context, Activity activity) {
// only allow on background thread
if (Looper.myLooper() == Looper.getMainLooper()) {
throw new IllegalStateException("dismissAlarm must be called on a " +
"background thread");
}
final AlarmInstance alarmInstance = AlarmInstance.getNextUpcomingInstanceByAlarmId(
context.getContentResolver(), alarm.id);
if (alarmInstance == null) {
final String reason = context.getString(R.string.no_alarm_scheduled_for_this_time);
Voice.notifyFailure(activity, reason);
LogUtils.i(reason);
return;
}
final String time = DateFormat.getTimeFormat(context).format(
alarmInstance.getAlarmTime().getTime());
if (Utils.isAlarmWithin24Hours(alarmInstance)) {
AlarmStateManager.setPreDismissState(context, alarmInstance);
final String reason = context.getString(R.string.alarm_is_dismissed, time);
LogUtils.i(reason);
Voice.notifySuccess(activity, reason);
Events.sendAlarmEvent(R.string.action_dismiss, R.string.label_intent);
} else {
final String reason = context.getString(
R.string.alarm_cant_be_dismissed_still_more_than_24_hours_away, time);
Voice.notifyFailure(activity, reason);
LogUtils.i(reason);
}
}
private static class DismissAlarmAsync extends AsyncTask<Void, Void, Void> {
private final Context mContext;
private final Intent mIntent;
private final Activity mActivity;
public DismissAlarmAsync(Context context, Intent intent, Activity activity) {
mContext = context;
mIntent = intent;
mActivity = activity;
}
@Override
protected Void doInBackground(Void... parameters) {
final List<Alarm> alarms = getEnabledAlarms(mContext);
if (alarms.isEmpty()) {
final String reason = mContext.getString(R.string.no_scheduled_alarms);
LogUtils.i(reason);
Voice.notifyFailure(mActivity, reason);
return null;
}
// remove Alarms in MISSED, DISMISSED, and PREDISMISSED states
for (Iterator<Alarm> i = alarms.iterator(); i.hasNext();) {
final AlarmInstance alarmInstance = AlarmInstance.getNextUpcomingInstanceByAlarmId(
mContext.getContentResolver(), i.next().id);
if (alarmInstance == null ||
alarmInstance.mAlarmState > AlarmInstance.FIRED_STATE) {
i.remove();
}
}
final String searchMode = mIntent.getStringExtra(AlarmClock.EXTRA_ALARM_SEARCH_MODE);
if (searchMode == null && alarms.size() > 1) {
// shows the UI where user picks which alarm they want to DISMISS
final Intent pickSelectionIntent = new Intent(mContext,
AlarmSelectionActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra(AlarmSelectionActivity.EXTRA_ALARMS,
alarms.toArray(new Parcelable[alarms.size()]));
mContext.startActivity(pickSelectionIntent);
Voice.notifySuccess(mActivity, mContext.getString(R.string.pick_alarm_to_dismiss));
return null;
}
// fetch the alarms that are specified by the intent
final FetchMatchingAlarmsAction fmaa =
new FetchMatchingAlarmsAction(mContext, alarms, mIntent, mActivity);
fmaa.run();
final List<Alarm> matchingAlarms = fmaa.getMatchingAlarms();
// If there are multiple matching alarms and it wasn't expected
// disambiguate what the user meant
if (!AlarmClock.ALARM_SEARCH_MODE_ALL.equals(searchMode) && matchingAlarms.size() > 1) {
final Intent pickSelectionIntent = new Intent(mContext, AlarmSelectionActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra(AlarmSelectionActivity.EXTRA_ALARMS,
matchingAlarms.toArray(new Parcelable[matchingAlarms.size()]));
mContext.startActivity(pickSelectionIntent);
Voice.notifySuccess(mActivity, mContext.getString(R.string.pick_alarm_to_dismiss));
return null;
}
// Apply the action to the matching alarms
for (Alarm alarm : matchingAlarms) {
dismissAlarm(alarm, mContext, mActivity);
LogUtils.i("Alarm %s is dismissed", alarm);
}
return null;
}
private static List<Alarm> getEnabledAlarms(Context context) {
final String selection = String.format("%s=?", Alarm.ENABLED);
final String[] args = { "1" };
return Alarm.getAlarms(context.getContentResolver(), selection, args);
}
}
private void handleSnoozeAlarm() {
new SnoozeAlarmAsync(mAppContext, this).execute();
}
private static class SnoozeAlarmAsync extends AsyncTask<Void, Void, Void> {
private final Context mContext;
private final Activity mActivity;
public SnoozeAlarmAsync(Context context, Activity activity) {
mContext = context;
mActivity = activity;
}
@Override
protected Void doInBackground(Void... parameters) {
final List<AlarmInstance> alarmInstances = AlarmInstance.getInstancesByState(
mContext.getContentResolver(), AlarmInstance.FIRED_STATE);
if (alarmInstances.isEmpty()) {
final String reason = mContext.getString(R.string.no_firing_alarms);
LogUtils.i(reason);
Voice.notifyFailure(mActivity, reason);
return null;
}
for (AlarmInstance firingAlarmInstance : alarmInstances) {
snoozeAlarm(firingAlarmInstance, mContext, mActivity);
}
return null;
}
}
static void snoozeAlarm(AlarmInstance alarmInstance, Context context, Activity activity) {
// only allow on background thread
if (Looper.myLooper() == Looper.getMainLooper()) {
throw new IllegalStateException("snoozeAlarm must be called on a " +
"background thread");
}
final String time = DateFormat.getTimeFormat(context).format(
alarmInstance.getAlarmTime().getTime());
final String reason = context.getString(R.string.alarm_is_snoozed, time);
LogUtils.i(reason);
Voice.notifySuccess(activity, reason);
AlarmStateManager.setSnoozeState(context, alarmInstance, true);
LogUtils.i("Snooze %d:%d", alarmInstance.mHour, alarmInstance.mMinute);
Events.sendAlarmEvent(R.string.action_snooze, R.string.label_intent);
}
/***
* Processes the SET_ALARM intent
* @param intent Intent passed to the app
*/
private void handleSetAlarm(Intent intent) {
// If not provided or invalid, show UI
final int hour = intent.getIntExtra(AlarmClock.EXTRA_HOUR, -1);
// If not provided, use zero. If it is provided, make sure it's valid, otherwise, show UI
final int minutes;
if (intent.hasExtra(AlarmClock.EXTRA_MINUTES)) {
minutes = intent.getIntExtra(AlarmClock.EXTRA_MINUTES, -1);
} else {
minutes = 0;
}
if (hour < 0 || hour > 23 || minutes < 0 || minutes > 59) {
// Change to the alarms tab.
UiDataModel.getUiDataModel().setSelectedTab(ALARMS);
// Intent has no time or an invalid time, open the alarm creation UI.
final Intent createAlarm = Alarm.createIntent(this, DeskClock.class, Alarm.INVALID_ID)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra(AlarmClockFragment.ALARM_CREATE_NEW_INTENT_EXTRA, true);
// Open DeskClock which is now positioned on the alarms tab.
startActivity(createAlarm);
Voice.notifyFailure(this, getString(R.string.invalid_time, hour, minutes, " "));
LogUtils.i("HandleApiCalls no/invalid time; opening UI");
return;
}
Events.sendAlarmEvent(R.string.action_create, R.string.label_intent);
final boolean skipUi = intent.getBooleanExtra(AlarmClock.EXTRA_SKIP_UI, false);
final StringBuilder selection = new StringBuilder();
final List<String> args = new ArrayList<>();
setSelectionFromIntent(intent, hour, minutes, selection, args);
// Update existing alarm matching the selection criteria; see setSelectionFromIntent.
final ContentResolver cr = getContentResolver();
final List<Alarm> alarms = Alarm.getAlarms(cr,
selection.toString(),
args.toArray(new String[args.size()]));
if (!alarms.isEmpty()) {
final Alarm alarm = alarms.get(0);
alarm.enabled = true;
Alarm.updateAlarm(cr, alarm);
// Delete all old instances and create a new one with updated values
AlarmStateManager.deleteAllInstances(this, alarm.id);
setupInstance(alarm.createInstanceAfter(Calendar.getInstance()), skipUi);
LogUtils.i("HandleApiCalls deleted old, created new alarm: %s", alarm);
return;
}
// Otherwise insert a new alarm.
final String message = getMessageFromIntent(intent);
final DaysOfWeek daysOfWeek = getDaysFromIntent(intent);
final boolean vibrate = intent.getBooleanExtra(AlarmClock.EXTRA_VIBRATE, true);
final String alert = intent.getStringExtra(AlarmClock.EXTRA_RINGTONE);
Alarm alarm = new Alarm(hour, minutes);
alarm.enabled = true;
alarm.label = message;
alarm.daysOfWeek = daysOfWeek;
alarm.vibrate = vibrate;
if (alert != null) {
if (AlarmClock.VALUE_RINGTONE_SILENT.equals(alert) || alert.isEmpty()) {
alarm.alert = Alarm.NO_RINGTONE_URI;
} else {
alarm.alert = Uri.parse(alert);
}
}
alarm.deleteAfterUse = !daysOfWeek.isRepeating() && skipUi;
alarm = Alarm.addAlarm(cr, alarm);
final AlarmInstance alarmInstance = alarm.createInstanceAfter(Calendar.getInstance());
setupInstance(alarmInstance, skipUi);
final String time = DateFormat.getTimeFormat(mAppContext).format(
alarmInstance.getAlarmTime().getTime());
Voice.notifySuccess(this, getString(R.string.alarm_is_set, time));
LogUtils.i("HandleApiCalls set up alarm: %s", alarm);
}
private void handleShowAlarms() {
// Change to the alarms tab.
UiDataModel.getUiDataModel().setSelectedTab(ALARMS);
// Open DeskClock which is now positioned on the alarms tab.
startActivity(new Intent(this, DeskClock.class));
Events.sendAlarmEvent(R.string.action_show, R.string.label_intent);
LogUtils.i("HandleApiCalls show alarms");
}
private void handleSetTimer(Intent intent) {
// If no length is supplied, show the timer setup view.
if (!intent.hasExtra(AlarmClock.EXTRA_LENGTH)) {
// Change to the timers tab.
UiDataModel.getUiDataModel().setSelectedTab(TIMERS);
// Open DeskClock which is now positioned on the timers tab and show the timer setup.
startActivity(TimerFragment.createTimerSetupIntent(this));
LogUtils.i("HandleApiCalls showing timer setup");
return;
}
// Verify that the timer length is between one second and one day.
final long lengthMillis = SECOND_IN_MILLIS * intent.getIntExtra(AlarmClock.EXTRA_LENGTH, 0);
if (lengthMillis < Timer.MIN_LENGTH || lengthMillis > Timer.MAX_LENGTH) {
Voice.notifyFailure(this, getString(R.string.invalid_timer_length));
LogUtils.i("Invalid timer length requested: " + lengthMillis);
return;
}
final String label = getMessageFromIntent(intent);
final boolean skipUi = intent.getBooleanExtra(AlarmClock.EXTRA_SKIP_UI, false);
// Attempt to reuse an existing timer that is Reset with the same length and label.
Timer timer = null;
for (Timer t : DataModel.getDataModel().getTimers()) {
if (!t.isReset()) { continue; }
if (t.getLength() != lengthMillis) { continue; }
if (!TextUtils.equals(label, t.getLabel())) { continue; }
timer = t;
break;
}
// Create a new timer if one could not be reused.
if (timer == null) {
timer = DataModel.getDataModel().addTimer(lengthMillis, label, skipUi);
Events.sendTimerEvent(R.string.action_create, R.string.label_intent);
}
// Start the selected timer.
DataModel.getDataModel().startTimer(timer);
Events.sendTimerEvent(R.string.action_start, R.string.label_intent);
Voice.notifySuccess(this, getString(R.string.timer_created));
// If not instructed to skip the UI, display the running timer.
if (!skipUi) {
// Change to the timers tab.
UiDataModel.getUiDataModel().setSelectedTab(TIMERS);
// Open DeskClock which is now positioned on the timers tab.
startActivity(new Intent(this, DeskClock.class)
.putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId()));
}
}
private void setupInstance(AlarmInstance instance, boolean skipUi) {
instance = AlarmInstance.addInstance(this.getContentResolver(), instance);
AlarmStateManager.registerInstance(this, instance, true);
AlarmUtils.popAlarmSetToast(this, instance.getAlarmTime().getTimeInMillis());
if (!skipUi) {
// Change to the alarms tab.
UiDataModel.getUiDataModel().setSelectedTab(ALARMS);
// Open DeskClock which is now positioned on the alarms tab.
final Intent showAlarm = Alarm.createIntent(this, DeskClock.class, instance.mAlarmId)
.putExtra(AlarmClockFragment.SCROLL_TO_ALARM_INTENT_EXTRA, instance.mAlarmId)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(showAlarm);
}
}
private static String getMessageFromIntent(Intent intent) {
final String message = intent.getStringExtra(AlarmClock.EXTRA_MESSAGE);
return message == null ? "" : message;
}
private static DaysOfWeek getDaysFromIntent(Intent intent) {
final DaysOfWeek daysOfWeek = new DaysOfWeek(0);
final ArrayList<Integer> days = intent.getIntegerArrayListExtra(AlarmClock.EXTRA_DAYS);
if (days != null) {
final int[] daysArray = new int[days.size()];
for (int i = 0; i < days.size(); i++) {
daysArray[i] = days.get(i);
}
daysOfWeek.setDaysOfWeek(true, daysArray);
} else {
// API says to use an ArrayList<Integer> but we allow the user to use a int[] too.
final int[] daysArray = intent.getIntArrayExtra(AlarmClock.EXTRA_DAYS);
if (daysArray != null) {
daysOfWeek.setDaysOfWeek(true, daysArray);
}
}
return daysOfWeek;
}
/**
* Assemble a database where clause to search for an alarm matching the given {@code hour} and
* {@code minutes} as well as all of the optional information within the {@code intent}
* including:
*
* <ul>
* <li>alarm message</li>
* <li>repeat days</li>
* <li>vibration setting</li>
* <li>ringtone uri</li>
* </ul>
*
* @param intent contains details of the alarm to be located
* @param hour the hour of the day of the alarm
* @param minutes the minute of the hour of the alarm
* @param selection an out parameter containing a SQL where clause
* @param args an out parameter containing the values to substitute into the {@code selection}
*/
private void setSelectionFromIntent(
Intent intent,
int hour,
int minutes,
StringBuilder selection,
List<String> args) {
selection.append(Alarm.HOUR).append("=?");
args.add(String.valueOf(hour));
selection.append(" AND ").append(Alarm.MINUTES).append("=?");
args.add(String.valueOf(minutes));
if (intent.hasExtra(AlarmClock.EXTRA_MESSAGE)) {
selection.append(" AND ").append(Alarm.LABEL).append("=?");
args.add(getMessageFromIntent(intent));
}
// Days is treated differently that other fields because if days is not specified, it
// explicitly means "not recurring".
selection.append(" AND ").append(Alarm.DAYS_OF_WEEK).append("=?");
args.add(String.valueOf(intent.hasExtra(AlarmClock.EXTRA_DAYS)
? getDaysFromIntent(intent).getBitSet() : DaysOfWeek.NO_DAYS_SET));
if (intent.hasExtra(AlarmClock.EXTRA_VIBRATE)) {
selection.append(" AND ").append(Alarm.VIBRATE).append("=?");
args.add(intent.getBooleanExtra(AlarmClock.EXTRA_VIBRATE, false) ? "1" : "0");
}
if (intent.hasExtra(AlarmClock.EXTRA_RINGTONE)) {
selection.append(" AND ").append(Alarm.RINGTONE).append("=?");
String ringTone = intent.getStringExtra(AlarmClock.EXTRA_RINGTONE);
if (ringTone == null) {
// If the intent explicitly specified a NULL ringtone, treat it as the default
// ringtone.
ringTone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM).toString();
} else if (AlarmClock.VALUE_RINGTONE_SILENT.equals(ringTone) || ringTone.isEmpty()) {
ringTone = Alarm.NO_RINGTONE;
}
args.add(ringTone);
}
}
}
| OrBin/SynClock-Android | src/orbin/deskclock/HandleApiCalls.java | Java | apache-2.0 | 21,891 |
package com.atom.empire.das.osite.auto.records;
import org.apache.empire.db.DBRecord;
import com.atom.empire.das.osite.auto.OSiteTable;
public abstract class OSiteTBO<T extends OSiteTable> extends DBRecord {
private static final long serialVersionUID = 1L;
public OSiteTBO(T table) {
super(table);
}
/**
* Returns the table this record is based upon.
* @return The table this record is based upon.
*/
@SuppressWarnings("unchecked")
public T getTable() {
return (T)super.getRowSet();
}
} | wuhongjun/atom-empire-demo | src/main/java/com/atom/empire/das/osite/auto/records/OSiteTBO.java | Java | apache-2.0 | 533 |
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
/**
* Erlang distributed pseudorandom numbers.
*
* @module @stdlib/random/base/erlang
*
* @example
* var erlang = require( '@stdlib/random/base/erlang' );
*
* var v = erlang( 3, 2.5 );
* // returns <number>
*
* @example
* var factory = require( '@stdlib/random/base/erlang' ).factory;
*
* var erlang = factory( 8, 5.9, {
* 'seed': 297
* });
*
* var v = erlang();
* // returns <number>
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var erlang = require( './main.js' );
var factory = require( './factory.js' );
// MAIN //
setReadOnly( erlang, 'factory', factory );
// EXPORTS //
module.exports = erlang;
| stdlib-js/stdlib | lib/node_modules/@stdlib/random/base/erlang/lib/index.js | JavaScript | apache-2.0 | 1,304 |
/*******************************************************************************
* Copyright 2015 Maximilian Stark | Dakror <mail@dakror.de>
*
* 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.dakror.spamwars.net.packet;
/**
* @author Dakror
*/
public class Packet01Disconnect extends Packet {
public enum Cause {
SERVER_CLOSED("Der Server wurde geschlossen."),
USER_DISCONNECT("Spiel beendet."),
;
private String description;
private Cause(String desc) {
description = desc;
}
public String getDescription() {
return description;
}
}
private Cause cause;
private String username;
public Packet01Disconnect(byte[] data) {
super(1);
String[] s = readData(data).split(":");
username = s[0];
cause = Cause.values()[Integer.parseInt(s[1])];
}
public Packet01Disconnect(String username, Cause cause) {
super(1);
this.username = username;
this.cause = cause;
}
@Override
public byte[] getPacketData() {
return (username + ":" + cause.ordinal()).getBytes();
}
public String getUsername() {
return username;
}
public Cause getCause() {
return cause;
}
}
| Dakror/SpamWars | src/main/java/de/dakror/spamwars/net/packet/Packet01Disconnect.java | Java | apache-2.0 | 1,729 |
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2016 MIT Probabilistic Computing 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.
def load_docstrings(module):
module.State.__init__.__func__.__doc__ = """
Construct a State.
Parameters
----------
X : np.ndarray
Data matrix, each row is an observation and each column a variable.
outputs : list<int>, optional
Unique non-negative ID for each column in X, and used to refer to
the column for all future queries. Defaults to range(0, X.shape[1])
inputs : list<int>, optional
Currently unsupported.
cctypes : list<str>
Data type of each column, see `utils.config` for valid cctypes.
distargs : list<dict>, optional
See the documentation for each DistributionGpm for its distargs.
Zv : dict(int:int), optional
Assignment of output columns to views, where Zv[k] is the
view assignment for column k. Defaults to sampling from CRP.
Zrv : dict(int:list<int>), optional
Assignment of rows to clusters in each view, where Zrv[k] is
the Zr for View k. If specified, then Zv must also be specified.
Defaults to sampling from CRP.
Cd : list(list<int>), optional
List of marginal dependence constraints for columns. Each element in
the list is a list of columns which are to be in the same view. Each
column can only be in one such list i.e. [[1,2,5],[1,5]] is not
allowed.
Ci : list(tuple<int>), optional
List of marginal independence constraints for columns.
Each element in the list is a 2-tuple of columns that must be
independent, i.e. [(1,2),(1,3)].
Rd : dict(int:Cd), optional
Dictionary of dependence constraints for rows, wrt.
Each entry is (col: Cd), where col is a column number and Cd is a
list of dependence constraints for the rows with respect to that
column (see doc for Cd).
Ri : dict(int:Cid), optional
Dictionary of independence constraints for rows, wrt.
Each entry is (col: Ci), where col is a column number and Ci is a
list of independence constraints for the rows with respect to that
column (see doc for Ci).
iterations : dict(str:int), optional
Metadata holding the number of iters each kernel has been run.
loom_path: str, optional
Path to a loom project compatible with this State.
rng : np.random.RandomState, optional.
Source of entropy.
"""
# --------------------------------------------------------------------------
# Observe
module.State.incorporate_dim.__func__.__doc__ = """
Incorporate a new Dim into this State.
Parameters
----------
T : list
Data with length self.n_rows().
outputs : list[int]
Identity of the variable modeled by this dim, must be non-negative
and cannot collide with State.outputs. Only univariate outputs
currently supported, so the list be a singleton.
cctype, distargs:
refer to State.__init__
v : int, optional
Index of the view to assign the data. If 0 <= v < len(state.views)
then insert into an existing View. If v = len(state.views) then
singleton view will be created with a partition from the CRP prior.
If unspecified, will be sampled.
"""
# --------------------------------------------------------------------------
# Schema updates.
module.State.update_cctype.__func__.__doc__ = """
Update the distribution type of self.dims[col] to cctype.
Parameters
----------
col : int
Index of column to update.
cctype, distargs:
refer to State.__init__
"""
# --------------------------------------------------------------------------
# Compositions
module.State.compose_cgpm.__func__.__doc__ = """
Compose a CGPM with this object.
Parameters
----------
cgpm : cgpm.cgpm.CGpm object
The `CGpm` object to compose.
Returns
-------
token : int
A unique token representing the composed cgpm, to be used
by `State.decompose_cgpm`.
"""
module.State.decompose_cgpm.__func__.__doc__ = """
Decompose a previously composed CGPM.
Parameters
----------
token : int
The unique token representing the composed cgpm, returned from
`State.compose_cgpm`.
"""
# --------------------------------------------------------------------------
# logpdf_score
module.State.logpdf_score.__func__.__doc__ = """
Compute joint density of all latents and the incorporated data.
Returns
-------
logpdf_score : float
The log score is P(X,Z) = P(X|Z)P(Z) where X is the observed data
and Z is the entirety of the latent state in the CGPM.
"""
# --------------------------------------------------------------------------
# Mutual information
module.State.mutual_information.__func__.__doc__ = """
Computes the mutual information MI(col0:col1|constraints).
Mutual information with constraints can be of the form:
- MI(X:Y|Z=z): CMI at a fixed conditioning value.
- MI(X:Y|Z): expected CMI E_Z[MI(X:Y|Z)] under Z.
- MI(X:Y|Z, W=w): expected CMI E_Z[MI(X:Y|Z,W=w)] under Z.
This function supports all three forms. The CMI is computed under the
posterior predictive joint distributions.
Parameters
----------
col0, col1 : list<int>
Columns to comptue MI. If all columns in `col0` are equivalent
to columns in `col` then entropy is returned, otherwise they must
be disjoint and the CMI is returned
constraints : list(tuple), optional
A list of pairs (col, val) of observed values to condition on. If
`val` is None, then `col` is marginalized over.
T : int, optional.
Number of samples to use in the outer (marginalization) estimator.
N : int, optional.
Number of samples to use in the inner Monte Carlo estimator.
Returns
-------
mi : float
A point estimate of the mutual information.
Examples
-------
# Compute MI(X:Y)
>>> State.mutual_information(col_x, col_y)
# Compute MI(X:Y|Z=1)
>>> State.mutual_information(col_x, col_y, {col_z: 1})
# Compute MI(X:Y|W)
>>> State.mutual_information(col_x, col_y, {col_w:None})
# Compute MI(X:Y|Z=1, W)
>>> State.mutual_information(col_x, col_y, {col_z: 1, col_w:None})
"""
# --------------------------------------------------------------------------
# Inference
module.State.transition.__func__.__doc__ = """
Run targeted inference kernels.
Parameters
----------
N : int, optional
Number of iterations to transition. Default 1.
S : float, optional
Number of seconds to transition. If both N and S set then min used.
kernels : list<{'alpha', 'view_alphas', 'column_params', 'column_hypers'
'rows', 'columns'}>, optional
List of inference kernels to run in this transition. Default all.
views, rows, cols : list<int>, optional
View, row and column numbers to apply the kernels. Default all.
checkpoint : int, optional
Number of transitions between recording inference diagnostics
from the latent state (such as logscore and row/column partitions).
Defaults to no checkpointing.
progress : boolean, optional
Show a progress bar for number of target iterations or elapsed time.
"""
| probcomp/cgpm | src/crosscat/statedoc.py | Python | apache-2.0 | 8,646 |
package jsfunction.gwt.returns;
import jsfunction.gwt.JsFunction;
import com.google.gwt.core.client.JavaScriptObject;
/**
* This is the JavaScriptObject type returned from JsFunction.create(JsReturn).
* It can be passed as an argument to a JavaScript function, which then returns
* its results asynchronously by calling "arg.result(someResult)". If the
* JavaScript function encounters an error or exception, it can return that
* as a JavaScript "Error" class via "arg.error(new Error('message'))" (or simply
* "arg.error(caughtError)").
*
* @author richkadel
*/
public final class JsResultOrError extends JavaScriptObject {
protected JsResultOrError() {}
public native JsFunction resultFunction() /*-{ return this.result }-*/;
public native JsFunction errorFunction() /*-{ return this.error }-*/;
}
| richkadel/jsfunction-gwt | jsfunction-gwt-main/src/main/java/jsfunction/gwt/returns/JsResultOrError.java | Java | apache-2.0 | 825 |
/*
* Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. Crate 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.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial agreement.
*/
package io.crate.integrationtests;
import io.crate.Build;
import io.crate.Version;
import io.crate.action.sql.SQLActionException;
import io.crate.action.sql.SQLResponse;
import io.crate.metadata.settings.CrateSettings;
import io.crate.test.integration.ClassLifecycleIntegrationTest;
import io.crate.testing.SQLTransportExecutor;
import io.crate.testing.TestingHelpers;
import org.elasticsearch.common.os.OsUtils;
import org.hamcrest.Matchers;
import org.junit.*;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.core.Is.is;
public class TransportSQLActionClassLifecycleTest extends ClassLifecycleIntegrationTest {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
private static boolean dataInitialized = false;
private static SQLTransportExecutor executor;
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Before
public void initTestData() throws Exception {
synchronized (SysShardsTest.class) {
if (dataInitialized) {
return;
}
executor = SQLTransportExecutor.create(ClassLifecycleIntegrationTest.GLOBAL_CLUSTER);
Setup setup = new Setup(executor);
setup.partitionTableSetup();
setup.groupBySetup();
dataInitialized = true;
}
}
@After
public void resetSettings() throws Exception {
// reset stats settings in case of some tests changed it and failed without resetting.
executor.exec("reset global stats.enabled, stats.jobs_log_size, stats.operations_log_size");
}
@AfterClass
public synchronized static void after() throws Exception {
if (executor != null) {
executor = null;
}
}
@Test
public void testSelectNonExistentGlobalExpression() throws Exception {
expectedException.expect(SQLActionException.class);
expectedException.expectMessage("Cannot resolve relation 'suess.cluster'");
executor.exec("select count(race), suess.cluster.name from characters");
}
@Test
public void testSelectOrderByNullSortingASC() throws Exception {
SQLResponse response = executor.exec("select age from characters order by age");
assertEquals(32, response.rows()[0][0]);
assertEquals(34, response.rows()[1][0]);
assertEquals(43, response.rows()[2][0]);
assertEquals(112, response.rows()[3][0]);
assertEquals(null, response.rows()[4][0]);
assertEquals(null, response.rows()[5][0]);
assertEquals(null, response.rows()[6][0]);
}
@Test
public void testSelectDoc() throws Exception {
SQLResponse response = executor.exec("select _doc from characters order by name desc limit 1");
assertArrayEquals(new String[]{"_doc"}, response.cols());
Map<String, Object> _doc = new TreeMap<>((Map)response.rows()[0][0]);
assertEquals(
"{age=32, birthdate=276912000000, details={job=Mathematician}, " +
"gender=female, name=Trillian, race=Human}",
_doc.toString());
}
@Test
public void testSelectRaw() throws Exception {
SQLResponse response = executor.exec("select _raw from characters order by name desc limit 1");
assertEquals(
"{\"race\":\"Human\",\"gender\":\"female\",\"age\":32,\"birthdate\":276912000000," +
"\"name\":\"Trillian\",\"details\":{\"job\":\"Mathematician\"}}\n",
TestingHelpers.printedTable(response.rows()));
}
@Test
public void testSelectRawWithGrouping() throws Exception {
SQLResponse response = executor.exec("select name, _raw from characters " +
"group by _raw, name order by name desc limit 1");
assertEquals(
"Trillian| {\"race\":\"Human\",\"gender\":\"female\",\"age\":32,\"birthdate\":276912000000," +
"\"name\":\"Trillian\",\"details\":{\"job\":\"Mathematician\"}}\n",
TestingHelpers.printedTable(response.rows()));
}
@Test
public void testSelectOrderByNullSortingDESC() throws Exception {
SQLResponse response = executor.exec("select age from characters order by age desc");
assertEquals(null, response.rows()[0][0]);
assertEquals(null, response.rows()[1][0]);
assertEquals(null, response.rows()[2][0]);
assertEquals(112, response.rows()[3][0]);
assertEquals(43, response.rows()[4][0]);
assertEquals(34, response.rows()[5][0]);
assertEquals(32, response.rows()[6][0]);
}
@Test
public void testSelectGroupByOrderByNullSortingASC() throws Exception {
SQLResponse response = executor.exec("select age from characters group by age order by age");
assertEquals(32, response.rows()[0][0]);
assertEquals(34, response.rows()[1][0]);
assertEquals(43, response.rows()[2][0]);
assertEquals(112, response.rows()[3][0]);
assertEquals(null, response.rows()[4][0]);
}
@Test
public void testSelectGroupByOrderByNullSortingDESC() throws Exception {
SQLResponse response = executor.exec("select age from characters group by age order by age desc");
assertEquals(null, response.rows()[0][0]);
assertEquals(112, response.rows()[1][0]);
assertEquals(43, response.rows()[2][0]);
assertEquals(34, response.rows()[3][0]);
assertEquals(32, response.rows()[4][0]);
}
@Test
public void testGlobalAggregateSimple() throws Exception {
SQLResponse response = executor.exec("select max(age) from characters");
assertEquals(1, response.rowCount());
assertEquals("max(age)", response.cols()[0]);
assertEquals(112, response.rows()[0][0]);
response = executor.exec("select min(name) from characters");
assertEquals(1, response.rowCount());
assertEquals("min(name)", response.cols()[0]);
assertEquals("Anjie", response.rows()[0][0]);
response = executor.exec("select avg(age) as median_age from characters");
assertEquals(1, response.rowCount());
assertEquals("median_age", response.cols()[0]);
assertEquals(55.25d, response.rows()[0][0]);
response = executor.exec("select sum(age) as sum_age from characters");
assertEquals(1, response.rowCount());
assertEquals("sum_age", response.cols()[0]);
assertEquals(221.0d, response.rows()[0][0]);
}
@Test
public void testGlobalAggregateWithoutNulls() throws Exception {
SQLResponse firstResp = executor.exec("select sum(age) from characters");
SQLResponse secondResp = executor.exec("select sum(age) from characters where age is not null");
assertEquals(
firstResp.rowCount(),
secondResp.rowCount()
);
assertEquals(
firstResp.rows()[0][0],
secondResp.rows()[0][0]
);
}
@Test
public void testGlobalAggregateNullRowWithoutMatchingRows() throws Exception {
SQLResponse response = executor.exec(
"select sum(age), avg(age) from characters where characters.age > 112");
assertEquals(1, response.rowCount());
assertNull(response.rows()[0][0]);
assertNull(response.rows()[0][1]);
response = executor.exec("select sum(age) from characters limit 0");
assertEquals(0, response.rowCount());
}
@Test
public void testGlobalAggregateMany() throws Exception {
SQLResponse response = executor.exec("select sum(age), min(age), max(age), avg(age) from characters");
assertEquals(1, response.rowCount());
assertEquals(221.0d, response.rows()[0][0]);
assertEquals(32, response.rows()[0][1]);
assertEquals(112, response.rows()[0][2]);
assertEquals(55.25d, response.rows()[0][3]);
}
@Test(expected = SQLActionException.class)
public void selectMultiGetRequestFromNonExistentTable() throws Exception {
executor.exec("SELECT * FROM \"non_existent\" WHERE \"_id\" in (?,?)", new Object[]{"1", "2"});
}
@Test
public void testGroupByNestedObject() throws Exception {
SQLResponse response = executor.exec("select count(*), details['job'] from characters " +
"group by details['job'] order by count(*), details['job']");
assertEquals(3, response.rowCount());
assertEquals(1L, response.rows()[0][0]);
assertEquals("Mathematician", response.rows()[0][1]);
assertEquals(1L, response.rows()[1][0]);
assertEquals("Sandwitch Maker", response.rows()[1][1]);
assertEquals(5L, response.rows()[2][0]);
assertNull(null, response.rows()[2][1]);
}
@Test
public void testCountWithGroupByOrderOnKeyDescAndLimit() throws Exception {
SQLResponse response = executor.exec(
"select count(*), race from characters group by race order by race desc limit 2");
assertEquals(2L, response.rowCount());
assertEquals(2L, response.rows()[0][0]);
assertEquals("Vogon", response.rows()[0][1]);
assertEquals(4L, response.rows()[1][0]);
assertEquals("Human", response.rows()[1][1]);
}
@Test
public void testCountWithGroupByOrderOnKeyAscAndLimit() throws Exception {
SQLResponse response = executor.exec(
"select count(*), race from characters group by race order by race asc limit 2");
assertEquals(2, response.rowCount());
assertEquals(1L, response.rows()[0][0]);
assertEquals("Android", response.rows()[0][1]);
assertEquals(4L, response.rows()[1][0]);
assertEquals("Human", response.rows()[1][1]);
}
@Test
public void testCountWithGroupByNullArgs() throws Exception {
SQLResponse response = executor.exec("select count(*), race from characters group by race", new Object[]{null});
assertEquals(3, response.rowCount());
assertThat(response.duration(), greaterThanOrEqualTo(0L));
}
@Test
public void testGroupByAndOrderByAlias() throws Exception {
SQLResponse response = executor.exec(
"select characters.race as test_race from characters group by characters.race order by characters.race");
assertEquals(3, response.rowCount());
response = executor.exec(
"select characters.race as test_race from characters group by characters.race order by test_race");
assertEquals(3, response.rowCount());
}
@Test
public void testCountWithGroupByWithWhereClause() throws Exception {
SQLResponse response = executor.exec(
"select count(*), race from characters where race = 'Human' group by race");
assertEquals(1, response.rowCount());
}
@Test
public void testCountWithGroupByOrderOnAggAscFuncAndLimit() throws Exception {
SQLResponse response = executor.exec("select count(*), race from characters " +
"group by race order by count(*) asc limit ?",
new Object[]{2});
assertEquals(2, response.rowCount());
assertEquals(1L, response.rows()[0][0]);
assertEquals("Android", response.rows()[0][1]);
assertEquals(2L, response.rows()[1][0]);
assertEquals("Vogon", response.rows()[1][1]);
}
@Test
public void testCountWithGroupByOrderOnAggAscFuncAndSecondColumnAndLimit() throws Exception {
SQLResponse response = executor.exec("select count(*), gender, race from characters " +
"group by race, gender order by count(*) desc, race, gender asc limit 2");
assertEquals(2L, response.rowCount());
assertEquals(2L, response.rows()[0][0]);
assertEquals("female", response.rows()[0][1]);
assertEquals("Human", response.rows()[0][2]);
assertEquals(2L, response.rows()[1][0]);
assertEquals("male", response.rows()[1][1]);
assertEquals("Human", response.rows()[1][2]);
}
@Test
public void testCountWithGroupByOrderOnAggAscFuncAndSecondColumnAndLimitAndOffset() throws Exception {
SQLResponse response = executor.exec("select count(*), gender, race from characters " +
"group by race, gender order by count(*) desc, race asc limit 2 offset 2");
assertEquals(2, response.rowCount());
assertEquals(2L, response.rows()[0][0]);
assertEquals("male", response.rows()[0][1]);
assertEquals("Vogon", response.rows()[0][2]);
assertEquals(1L, response.rows()[1][0]);
assertEquals("male", response.rows()[1][1]);
assertEquals("Android", response.rows()[1][2]);
}
@Test
public void testCountWithGroupByOrderOnAggAscFuncAndSecondColumnAndLimitAndTooLargeOffset() throws Exception {
SQLResponse response = executor.exec("select count(*), gender, race from characters " +
"group by race, gender order by count(*) desc, race asc limit 2 offset 20");
assertEquals(0, response.rows().length);
assertEquals(0, response.rowCount());
}
@Test
public void testCountWithGroupByOrderOnAggDescFuncAndLimit() throws Exception {
SQLResponse response = executor.exec(
"select count(*), race from characters group by race order by count(*) desc limit 2");
assertEquals(2, response.rowCount());
assertEquals(4L, response.rows()[0][0]);
assertEquals("Human", response.rows()[0][1]);
assertEquals(2L, response.rows()[1][0]);
assertEquals("Vogon", response.rows()[1][1]);
}
@Test
public void testDateRange() throws Exception {
SQLResponse response = executor.exec("select * from characters where birthdate > '1970-01-01'");
assertThat(response.rowCount(), Matchers.is(2L));
}
@Test
public void testOrderByNullsFirstAndLast() throws Exception {
SQLResponse response = executor.exec(
"select details['job'] from characters order by details['job'] nulls first limit 1");
assertNull(response.rows()[0][0]);
response = executor.exec(
"select details['job'] from characters order by details['job'] desc nulls first limit 1");
assertNull(response.rows()[0][0]);
response = executor.exec(
"select details['job'] from characters order by details['job'] nulls last");
assertNull(response.rows()[((Long) response.rowCount()).intValue() - 1][0]);
response = executor.exec(
"select details['job'] from characters order by details['job'] desc nulls last");
assertNull(response.rows()[((Long) response.rowCount()).intValue() - 1][0]);
response = executor.exec(
"select distinct details['job'] from characters order by details['job'] desc nulls last");
assertNull(response.rows()[((Long) response.rowCount()).intValue() - 1][0]);
}
@Test
public void testCopyToDirectoryOnPartitionedTableWithPartitionClause() throws Exception {
String uriTemplate = Paths.get(folder.getRoot().toURI()).toUri().toString();
SQLResponse response = executor.exec("copy parted partition (date='2014-01-01') to DIRECTORY ?", uriTemplate);
assertThat(response.rowCount(), is(2L));
List<String> lines = new ArrayList<>(2);
DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(folder.getRoot().toURI()), "*.json");
for (Path entry : stream) {
lines.addAll(Files.readAllLines(entry, StandardCharsets.UTF_8));
}
assertThat(lines.size(), is(2));
for (String line : lines) {
assertTrue(line.contains("2") || line.contains("1"));
assertFalse(line.contains("1388534400000")); // date column not included in export
assertThat(line, startsWith("{"));
assertThat(line, endsWith("}"));
}
}
@Test
public void testCopyToDirectoryOnPartitionedTableWithoutPartitionClause() throws Exception {
String uriTemplate = Paths.get(folder.getRoot().toURI()).toUri().toString();
SQLResponse response = executor.exec("copy parted to DIRECTORY ?", uriTemplate);
assertThat(response.rowCount(), is(5L));
List<String> lines = new ArrayList<>(5);
DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(folder.getRoot().toURI()), "*.json");
for (Path entry : stream) {
lines.addAll(Files.readAllLines(entry, StandardCharsets.UTF_8));
}
assertThat(lines.size(), is(5));
for (String line : lines) {
// date column included in output
if (!line.contains("1388534400000")) {
assertTrue(line.contains("1391212800000"));
}
assertThat(line, startsWith("{"));
assertThat(line, endsWith("}"));
}
}
@Test
public void testArithmeticFunctions() throws Exception {
SQLResponse response = executor.exec("select ((2 * 4 - 2 + 1) / 2) % 3 from sys.cluster");
assertThat(response.cols()[0], is("(((((2 * 4) - 2) + 1) / 2) % 3)"));
assertThat((Long) response.rows()[0][0], is(0L));
response = executor.exec("select ((2 * 4.0 - 2 + 1) / 2) % 3 from sys.cluster");
assertThat((Double) response.rows()[0][0], is(0.5));
response = executor.exec("select ? + 2 from sys.cluster", 1);
assertThat((Long) response.rows()[0][0], is(3L));
if (!OsUtils.WINDOWS) {
response = executor.exec("select load['1'] + load['5'], load['1'], load['5'] from sys.nodes limit 1");
assertEquals(response.rows()[0][0], (Double) response.rows()[0][1] + (Double) response.rows()[0][2]);
}
}
@Test
public void testJobLog() throws Exception {
executor.exec("select name from sys.cluster");
SQLResponse response = executor.exec("select * from sys.jobs_log");
assertThat(response.rowCount(), is(0L)); // default length is zero
executor.exec("set global transient stats.enabled = true, stats.jobs_log_size=1");
executor.exec("select id from sys.cluster");
executor.exec("select id from sys.cluster");
executor.exec("select id from sys.cluster");
response = executor.exec("select stmt from sys.jobs_log order by ended desc");
// there are 2 nodes so depending on whether both nodes were hit this should be either 1 or 2
// but never 3 because the queue size is only 1
assertThat(response.rowCount(), Matchers.lessThanOrEqualTo(2L));
assertThat((String) response.rows()[0][0], is("select id from sys.cluster"));
executor.exec("reset global stats.enabled, stats.jobs_log_size");
waitNoPendingTasksOnAll();
response = executor.exec("select * from sys.jobs_log");
assertThat(response.rowCount(), is(0L));
}
@Test
public void testSetSingleStatement() throws Exception {
SQLResponse response = executor.exec("select settings['stats']['jobs_log_size'] from sys.cluster");
assertThat(response.rowCount(), is(1L));
assertThat((Integer) response.rows()[0][0], is(CrateSettings.STATS_JOBS_LOG_SIZE.defaultValue()));
response = executor.exec("set global persistent stats.enabled= true, stats.jobs_log_size=7");
assertThat(response.rowCount(), is(1L));
response = executor.exec("select settings['stats']['jobs_log_size'] from sys.cluster");
assertThat(response.rowCount(), is(1L));
assertThat((Integer) response.rows()[0][0], is(7));
response = executor.exec("reset global stats.enabled, stats.jobs_log_size");
assertThat(response.rowCount(), is(1L));
waitNoPendingTasksOnAll();
response = executor.exec("select settings['stats']['enabled'], settings['stats']['jobs_log_size'] from sys.cluster");
assertThat(response.rowCount(), is(1L));
assertThat((Boolean) response.rows()[0][0], is(CrateSettings.STATS_ENABLED.defaultValue()));
assertThat((Integer) response.rows()[0][1], is(CrateSettings.STATS_JOBS_LOG_SIZE.defaultValue()));
}
@Test
public void testSetMultipleStatement() throws Exception {
SQLResponse response = executor.exec(
"select settings['stats']['operations_log_size'], settings['stats']['enabled'] from sys.cluster");
assertThat(response.rowCount(), is(1L));
assertThat((Integer) response.rows()[0][0], is(CrateSettings.STATS_OPERATIONS_LOG_SIZE.defaultValue()));
assertThat((Boolean) response.rows()[0][1], is(CrateSettings.STATS_ENABLED.defaultValue()));
response = executor.exec("set global persistent stats.operations_log_size=1024, stats.enabled=false");
assertThat(response.rowCount(), is(1L));
response = executor.exec(
"select settings['stats']['operations_log_size'], settings['stats']['enabled'] from sys.cluster");
assertThat(response.rowCount(), is(1L));
assertThat((Integer) response.rows()[0][0], is(1024));
assertThat((Boolean) response.rows()[0][1], is(false));
response = executor.exec("reset global stats.operations_log_size, stats.enabled");
assertThat(response.rowCount(), is(1L));
waitNoPendingTasksOnAll();
response = executor.exec(
"select settings['stats']['operations_log_size'], settings['stats']['enabled'] from sys.cluster");
assertThat(response.rowCount(), is(1L));
assertThat((Integer) response.rows()[0][0], is(CrateSettings.STATS_OPERATIONS_LOG_SIZE.defaultValue()));
assertThat((Boolean) response.rows()[0][1], is(CrateSettings.STATS_ENABLED.defaultValue()));
}
@Test
public void testSetStatementInvalid() throws Exception {
try {
executor.exec("set global persistent stats.operations_log_size=-1024");
fail("expected SQLActionException, none was thrown");
} catch (SQLActionException e) {
assertThat(e.getMessage(), is("Invalid value for argument 'stats.operations_log_size'"));
SQLResponse response = executor.exec("select settings['stats']['operations_log_size'] from sys.cluster");
assertThat(response.rowCount(), is(1L));
assertThat((Integer) response.rows()[0][0], is(CrateSettings.STATS_OPERATIONS_LOG_SIZE.defaultValue()));
}
}
@Test
public void testSysOperationsLog() throws Exception {
executor.exec(
"select count(*), race from characters group by race order by count(*) desc limit 2");
SQLResponse resp = executor.exec("select count(*) from sys.operations_log");
assertThat((Long) resp.rows()[0][0], is(0L));
executor.exec("set global transient stats.enabled = true, stats.operations_log_size=10");
waitNoPendingTasksOnAll();
executor.exec(
"select count(*), race from characters group by race order by count(*) desc limit 2");
resp = executor.exec("select * from sys.operations_log order by ended limit 3");
List<String> names = new ArrayList<>();
for (Object[] objects : resp.rows()) {
names.add((String) objects[2]);
}
assertThat(names, Matchers.anyOf(
Matchers.hasItems("distributing collect", "distributing collect"),
Matchers.hasItems("collect", "localMerge"),
// the select * from sys.operations_log has 2 collect operations (1 per node)
Matchers.hasItems("collect", "collect"),
Matchers.hasItems("distributed merge", "localMerge")));
executor.exec("reset global stats.enabled, stats.operations_log_size");
waitNoPendingTasksOnAll();
resp = executor.exec("select count(*) from sys.operations_log");
assertThat((Long) resp.rows()[0][0], is(0L));
}
@Test
public void testSysOperationsLogConcurrentAccess() throws Exception {
executor.exec("set global transient stats.enabled = true, stats.operations_log_size=10");
waitNoPendingTasksOnAll();
Thread selectThread = new Thread(new Runnable() {
@Override
public void run() {
for (int i=0; i < 50; i++) {
executor.exec(
"select count(*), race from characters group by race order by count(*) desc limit 2");
}
}
});
Thread sysOperationThread = new Thread(new Runnable() {
@Override
public void run() {
for (int i=0; i < 50; i++) {
executor.exec("select * from sys.operations_log order by ended");
}
}
});
selectThread.start();
sysOperationThread.start();
selectThread.join(500);
sysOperationThread.join(500);
}
@Test
public void testEmptyJobsInLog() throws Exception {
executor.exec("set global transient stats.enabled = true");
executor.exec("insert into characters (name) values ('sysjobstest')");
executor.exec("delete from characters where name = 'sysjobstest'");
SQLResponse response = executor.exec(
"select * from sys.jobs_log where stmt like 'insert into%' or stmt like 'delete%'");
assertThat(response.rowCount(), is(2L));
}
@Test
public void testSelectFromJobsLogWithLimit() throws Exception {
// this is an regression test to verify that the CollectionTerminatedException is handled correctly
executor.exec("set global transient stats.enabled = true");
executor.exec("select * from sys.jobs");
executor.exec("select * from sys.jobs");
executor.exec("select * from sys.jobs");
executor.exec("select * from sys.jobs_log limit 1");
}
@Test
public void testAddPrimaryKeyColumnToNonEmptyTable() throws Exception {
expectedException.expect(SQLActionException.class);
expectedException.expectMessage("Cannot add a primary key column to a table that isn't empty");
executor.exec("alter table characters add newpkcol string primary key");
}
@Test
public void testIsNullOnObjects() throws Exception {
SQLResponse resp = executor.exec("select name from characters where details is null order by name");
assertThat(resp.rowCount(), is(5L));
List<String> names = new ArrayList<>(5);
for (Object[] objects : resp.rows()) {
names.add((String) objects[0]);
}
assertThat(names, Matchers.contains("Anjie", "Ford Perfect", "Jeltz", "Kwaltz", "Marving"));
resp = executor.exec("select count(*) from characters where details is not null");
assertThat((Long) resp.rows()[0][0], is(2L));
}
@Test
public void testDistanceQueryOnSysTable() throws Exception {
SQLResponse response = executor.exec(
"select Distance('POINT (10 20)', 'POINT (11 21)') from sys.cluster");
assertThat((Double) response.rows()[0][0], is(152462.70754934277));
}
@Test
public void testCreateTableWithInvalidAnalyzer() throws Exception {
expectedException.expect(SQLActionException.class);
expectedException.expectMessage("Analyzer [foobar] not found for field [content]");
executor.exec("create table t (content string index using fulltext with (analyzer='foobar'))");
}
@Test
public void testSysNodesVersionFromMultipleNodes() throws Exception {
SQLResponse response = executor.exec("select version, version['number'], " +
"version['build_hash'], version['build_snapshot'] " +
"from sys.nodes");
assertThat(response.rowCount(), is(2L));
for (int i = 0; i <= 1; i++) {
assertThat(response.rows()[i][0], instanceOf(Map.class));
assertThat((Map<String, Object>) response.rows()[i][0], allOf(hasKey("number"), hasKey("build_hash"), hasKey("build_snapshot")));
assertThat((String) response.rows()[i][1], Matchers.is(Version.CURRENT.number()));
assertThat((String) response.rows()[i][2], is(Build.CURRENT.hash()));
assertThat((Boolean) response.rows()[i][3], is(Version.CURRENT.snapshot()));
}
}
@Test
public void selectCurrentTimestamp() throws Exception {
long before = System.currentTimeMillis();
SQLResponse response = executor.exec("select current_timestamp from sys.cluster");
long after = System.currentTimeMillis();
assertThat(response.cols(), arrayContaining("current_timestamp"));
assertThat((Long) response.rows()[0][0], allOf(greaterThanOrEqualTo(before), lessThanOrEqualTo(after)));
}
@Test
public void selectWhereEqualCurrentTimestamp() throws Exception {
SQLResponse response = executor.exec("select * from sys.cluster where current_timestamp = current_timestamp");
assertThat(response.rowCount(), is(1L));
SQLResponse newResponse = executor.exec("select * from sys.cluster where current_timestamp > current_timestamp");
assertThat(newResponse.rowCount(), is(0L));
}
}
| gmrodrigues/crate | sql/src/test/java/io/crate/integrationtests/TransportSQLActionClassLifecycleTest.java | Java | apache-2.0 | 30,721 |
package main
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatch"
"github.com/prometheus/client_golang/prometheus"
"time"
"regexp"
"strings"
)
func getLatestDatapoint(datapoints []*cloudwatch.Datapoint) *cloudwatch.Datapoint {
var latest *cloudwatch.Datapoint = nil
for dp := range datapoints {
if latest == nil || latest.Timestamp.Before(*datapoints[dp].Timestamp) {
latest = datapoints[dp]
}
}
return latest
}
// scrape makes the required calls to AWS CloudWatch by using the parameters in the cwCollector
// Once converted into Prometheus format, the metrics are pushed on the ch channel.
func scrape(collector *cwCollector, ch chan<- prometheus.Metric) {
session := session.Must(session.NewSession(&aws.Config{
Region: aws.String(collector.Region),
}))
svc := cloudwatch.New(session)
for m := range collector.Template.Metrics {
metric := &collector.Template.Metrics[m]
now := time.Now()
end := now.Add(time.Duration(-metric.ConfMetric.DelaySeconds) * time.Second)
params := &cloudwatch.GetMetricStatisticsInput{
EndTime: aws.Time(end),
StartTime: aws.Time(end.Add(time.Duration(-metric.ConfMetric.RangeSeconds) * time.Second)),
Period: aws.Int64(int64(metric.ConfMetric.PeriodSeconds)),
MetricName: aws.String(metric.ConfMetric.Name),
Namespace: aws.String(metric.ConfMetric.Namespace),
Dimensions: []*cloudwatch.Dimension{},
Unit: nil,
}
dimensions:=[]*cloudwatch.Dimension{}
//This map will hold dimensions name which has been already collected
valueCollected := map[string]bool{}
if len(metric.ConfMetric.DimensionsSelectRegex) == 0 {
metric.ConfMetric.DimensionsSelectRegex = map[string]string{}
}
//Check for dimensions who does not have either select or dimensions select_regex and make them select everything using regex
for _,dimension := range metric.ConfMetric.Dimensions {
_, found := metric.ConfMetric.DimensionsSelect[dimension]
_, found2 := metric.ConfMetric.DimensionsSelectRegex[dimension]
if !found && !found2 {
metric.ConfMetric.DimensionsSelectRegex[dimension]=".*"
}
}
if metric.ConfMetric.Statistics != nil {
params.SetStatistics(aws.StringSlice(metric.ConfMetric.Statistics))
}
if metric.ConfMetric.ExtendedStatistics != nil {
params.SetExtendedStatistics(aws.StringSlice(metric.ConfMetric.ExtendedStatistics))
}
labels := make([]string, 0, len(metric.LabelNames))
// Loop through the dimensions selects to build the filters and the labels array
for dim := range metric.ConfMetric.DimensionsSelect {
for val := range metric.ConfMetric.DimensionsSelect[dim] {
dimValue := metric.ConfMetric.DimensionsSelect[dim][val]
// Replace $_target token by the actual URL target
if dimValue == "$_target" {
dimValue = collector.Target
}
dimensions = append(dimensions, &cloudwatch.Dimension{
Name: aws.String(dim),
Value: aws.String(dimValue),
})
labels = append(labels, dimValue)
}
}
if len(dimensions) > 0 || len(metric.ConfMetric.Dimensions) ==0 {
labels = append(labels, collector.Template.Task.Name)
params.Dimensions=dimensions
scrapeSingleDataPoint(collector,ch,params,metric,labels,svc)
}
//If no regex is specified, continue
if (len(metric.ConfMetric.DimensionsSelectRegex)==0){
continue
}
// Get all the metric to select the ones who'll match the regex
result, err := svc.ListMetrics(&cloudwatch.ListMetricsInput{
MetricName: aws.String(metric.ConfMetric.Name),
Namespace: aws.String(metric.ConfMetric.Namespace),
})
nextToken:=result.NextToken
metrics:=result.Metrics
totalRequests.Inc()
if err != nil {
fmt.Println(err)
continue
}
for nextToken!=nil {
result, err := svc.ListMetrics(&cloudwatch.ListMetricsInput{
MetricName: aws.String(metric.ConfMetric.Name),
Namespace: aws.String(metric.ConfMetric.Namespace),
NextToken: nextToken,
})
if err != nil {
fmt.Println(err)
continue
}
nextToken=result.NextToken
metrics=append(metrics,result.Metrics...)
}
//For each metric returned by aws
for _,met := range result.Metrics {
labels := make([]string, 0, len(metric.LabelNames))
dimensions=[]*cloudwatch.Dimension{}
//Try to match each dimensions to the regex
for _,dim := range met.Dimensions {
dimRegex:=metric.ConfMetric.DimensionsSelectRegex[*dim.Name]
if(dimRegex==""){
dimRegex="\\b"+strings.Join(metric.ConfMetric.DimensionsSelect[*dim.Name],"\\b|\\b")+"\\b"
}
match,_:=regexp.MatchString(dimRegex,*dim.Value)
if match {
dimensions=append(dimensions, &cloudwatch.Dimension{
Name: aws.String(*dim.Name),
Value: aws.String(*dim.Value),
})
labels = append(labels, *dim.Value)
}
}
//Cheking if all dimensions matched
if len(labels) == len(metric.ConfMetric.Dimensions) {
//Checking if this couple of dimensions has already been scraped
if _, ok := valueCollected[strings.Join(labels,";")]; ok {
continue
}
//If no, then scrape them
valueCollected[strings.Join(labels,";")]=true
params.Dimensions = dimensions
labels = append(labels, collector.Template.Task.Name)
scrapeSingleDataPoint(collector,ch,params,metric,labels,svc)
}
}
}
}
//Send a single dataPoint to the Prometheus lib
func scrapeSingleDataPoint(collector *cwCollector, ch chan<- prometheus.Metric,params *cloudwatch.GetMetricStatisticsInput,metric *cwMetric,labels []string,svc *cloudwatch.CloudWatch) error {
resp, err := svc.GetMetricStatistics(params)
totalRequests.Inc()
if err != nil {
collector.ErroneousRequests.Inc()
fmt.Println(err)
return err
}
// There's nothing in there, don't publish the metric
if len(resp.Datapoints) == 0 {
return nil
}
// Pick the latest datapoint
dp := getLatestDatapoint(resp.Datapoints)
if dp.Sum != nil {
ch <- prometheus.MustNewConstMetric(metric.Desc, metric.ValType, float64(*dp.Sum), labels...)
}
if dp.Average != nil {
ch <- prometheus.MustNewConstMetric(metric.Desc, metric.ValType, float64(*dp.Average), labels...)
}
if dp.Maximum != nil {
ch <- prometheus.MustNewConstMetric(metric.Desc, metric.ValType, float64(*dp.Maximum), labels...)
}
if dp.Minimum != nil {
ch <- prometheus.MustNewConstMetric(metric.Desc, metric.ValType, float64(*dp.Minimum), labels...)
}
if dp.SampleCount != nil {
ch <- prometheus.MustNewConstMetric(metric.Desc, metric.ValType, float64(*dp.SampleCount), labels...)
}
for e := range dp.ExtendedStatistics {
ch <- prometheus.MustNewConstMetric(metric.Desc, metric.ValType, float64(*dp.ExtendedStatistics[e]), labels...)
}
return nil
}
| Technofy/cloudwatch_exporter | aws.go | GO | apache-2.0 | 6,778 |
/*
* 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 org.apache.carbondata.processing.sort.sortdata;
import java.io.File;
import java.io.FileFilter;
import java.util.AbstractQueue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.PriorityQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.carbondata.common.CarbonIterator;
import org.apache.carbondata.common.logging.LogServiceFactory;
import org.apache.carbondata.core.constants.CarbonCommonConstants;
import org.apache.carbondata.core.datastore.block.SegmentProperties;
import org.apache.carbondata.core.datastore.exception.CarbonDataWriterException;
import org.apache.carbondata.core.metadata.datatype.DataType;
import org.apache.carbondata.core.metadata.schema.table.column.CarbonColumn;
import org.apache.carbondata.core.scan.result.iterator.RawResultIterator;
import org.apache.carbondata.core.util.CarbonProperties;
import org.apache.carbondata.processing.loading.row.IntermediateSortTempRow;
import org.apache.carbondata.processing.loading.sort.SortStepRowHandler;
import org.apache.carbondata.processing.sort.exception.CarbonSortKeyAndGroupByException;
import org.apache.log4j.Logger;
public class SingleThreadFinalSortFilesMerger extends CarbonIterator<Object[]> {
/**
* LOGGER
*/
private static final Logger LOGGER =
LogServiceFactory.getLogService(SingleThreadFinalSortFilesMerger.class.getName());
/**
* lockObject
*/
private static final Object LOCKOBJECT = new Object();
/**
* recordHolderHeap
*/
private AbstractQueue<SortTempFileChunkHolder> recordHolderHeapLocal;
/**
* tableName
*/
private String tableName;
private SortParameters sortParameters;
private SortStepRowHandler sortStepRowHandler;
/**
* tempFileLocation
*/
private String[] tempFileLocation;
private int maxThreadForSorting;
private ExecutorService executorService;
private List<Future<Void>> mergerTask;
public SingleThreadFinalSortFilesMerger(String[] tempFileLocation, String tableName,
SortParameters sortParameters) {
this.tempFileLocation = tempFileLocation;
this.tableName = tableName;
this.sortParameters = sortParameters;
this.sortStepRowHandler = new SortStepRowHandler(sortParameters);
try {
maxThreadForSorting = Integer.parseInt(CarbonProperties.getInstance()
.getProperty(CarbonCommonConstants.CARBON_MERGE_SORT_READER_THREAD,
CarbonCommonConstants.CARBON_MERGE_SORT_READER_THREAD_DEFAULTVALUE));
} catch (NumberFormatException e) {
maxThreadForSorting =
Integer.parseInt(CarbonCommonConstants.CARBON_MERGE_SORT_READER_THREAD_DEFAULTVALUE);
}
this.mergerTask = new ArrayList<>();
}
/**
* This method will be used to merger the merged files
*
* @throws CarbonSortKeyAndGroupByException
*/
public void startFinalMerge() throws CarbonDataWriterException {
List<File> filesToMerge = getFilesToMergeSort();
if (filesToMerge.size() == 0) {
LOGGER.info("No file to merge in final merge stage");
return;
}
startSorting(filesToMerge);
}
/**
* Below method will be used to add in memory raw result iterator to priority queue.
* This will be called in case of compaction, when it is compacting sorted and unsorted
* both type of carbon data file
* This method will add sorted file's RawResultIterator to priority queue using
* InMemorySortTempChunkHolder as wrapper
*
* @param sortedRawResultMergerList
* @param segmentProperties
* @param noDicAndComplexColumns
*/
public void addInMemoryRawResultIterator(List<RawResultIterator> sortedRawResultMergerList,
SegmentProperties segmentProperties, CarbonColumn[] noDicAndComplexColumns,
DataType[] measureDataType) {
for (RawResultIterator rawResultIterator : sortedRawResultMergerList) {
InMemorySortTempChunkHolder inMemorySortTempChunkHolder =
new InMemorySortTempChunkHolder(rawResultIterator, segmentProperties,
noDicAndComplexColumns, sortParameters, measureDataType);
if (inMemorySortTempChunkHolder.hasNext()) {
inMemorySortTempChunkHolder.readRow();
recordHolderHeapLocal.add(inMemorySortTempChunkHolder);
}
}
}
private List<File> getFilesToMergeSort() {
final int rangeId = sortParameters.getRangeId();
FileFilter fileFilter = new FileFilter() {
public boolean accept(File pathname) {
return pathname.getName().startsWith(tableName + '_' + rangeId);
}
};
// get all the merged files
List<File> files = new ArrayList<File>(tempFileLocation.length);
for (String tempLoc : tempFileLocation) {
File[] subFiles = new File(tempLoc).listFiles(fileFilter);
if (null != subFiles && subFiles.length > 0) {
files.addAll(Arrays.asList(subFiles));
}
}
return files;
}
/**
* Below method will be used to start storing process This method will get
* all the temp files present in sort temp folder then it will create the
* record holder heap and then it will read first record from each file and
* initialize the heap
*
* @throws CarbonSortKeyAndGroupByException
*/
private void startSorting(List<File> files) throws CarbonDataWriterException {
if (files.size() == 0) {
LOGGER.info("No files to merge sort");
return;
}
LOGGER.info("Started Final Merge");
LOGGER.info("Number of temp file: " + files.size());
// create record holder heap
createRecordHolderQueue(files.size());
// iterate over file list and create chunk holder and add to heap
LOGGER.info("Started adding first record from each file");
this.executorService = Executors.newFixedThreadPool(maxThreadForSorting);
for (final File tempFile : files) {
Callable<Void> callable = new Callable<Void>() {
@Override
public Void call() {
// create chunk holder
SortTempFileChunkHolder sortTempFileChunkHolder =
new SortTempFileChunkHolder(tempFile, sortParameters, tableName, true);
try {
// initialize
sortTempFileChunkHolder.initialize();
sortTempFileChunkHolder.readRow();
} catch (CarbonSortKeyAndGroupByException ex) {
sortTempFileChunkHolder.closeStream();
notifyFailure(ex);
}
synchronized (LOCKOBJECT) {
recordHolderHeapLocal.add(sortTempFileChunkHolder);
}
return null;
}
};
mergerTask.add(executorService.submit(callable));
}
executorService.shutdown();
try {
executorService.awaitTermination(2, TimeUnit.HOURS);
} catch (Exception e) {
throw new CarbonDataWriterException(e);
}
checkFailure();
LOGGER.info("final merger Heap Size" + this.recordHolderHeapLocal.size());
}
private void checkFailure() {
for (int i = 0; i < mergerTask.size(); i++) {
try {
mergerTask.get(i).get();
} catch (InterruptedException | ExecutionException e) {
throw new CarbonDataWriterException(e);
}
}
}
/**
* This method will be used to create the heap which will be used to hold
* the chunk of data
*/
private void createRecordHolderQueue(int size) {
// creating record holder heap
this.recordHolderHeapLocal = new PriorityQueue<SortTempFileChunkHolder>(size);
}
private synchronized void notifyFailure(Throwable throwable) {
close();
LOGGER.error(throwable);
}
/**
* This method will be used to get the sorted sort temp row from the sort temp files
*
* @return sorted row
* @throws CarbonSortKeyAndGroupByException
*/
public Object[] next() {
if (hasNext()) {
IntermediateSortTempRow sortTempRow = getSortedRecordFromFile();
return sortStepRowHandler.convertIntermediateSortTempRowTo3Parted(sortTempRow);
} else {
throw new NoSuchElementException("No more elements to return");
}
}
/**
* This method will be used to get the sorted record from file
*
* @return sorted record sorted record
* @throws CarbonSortKeyAndGroupByException
*/
private IntermediateSortTempRow getSortedRecordFromFile() throws CarbonDataWriterException {
IntermediateSortTempRow row = null;
// poll the top object from heap
// heap maintains binary tree which is based on heap condition that will
// be based on comparator we are passing the heap
// when will call poll it will always delete root of the tree and then
// it does trickel down operation complexity is log(n)
SortTempFileChunkHolder poll = this.recordHolderHeapLocal.poll();
// get the row from chunk
row = poll.getRow();
// check if there no entry present
if (!poll.hasNext()) {
// if chunk is empty then close the stream
poll.closeStream();
// reaturn row
return row;
}
// read new row
try {
poll.readRow();
} catch (CarbonSortKeyAndGroupByException e) {
close();
throw new CarbonDataWriterException(e);
}
// add to heap
this.recordHolderHeapLocal.add(poll);
// return row
return row;
}
/**
* This method will be used to check whether any more element is present or
* not
*
* @return more element is present
*/
public boolean hasNext() {
return this.recordHolderHeapLocal.size() > 0;
}
public void close() {
if (null != executorService && !executorService.isShutdown()) {
executorService.shutdownNow();
}
if (null != recordHolderHeapLocal) {
SortTempFileChunkHolder sortTempFileChunkHolder;
while (!recordHolderHeapLocal.isEmpty()) {
sortTempFileChunkHolder = recordHolderHeapLocal.poll();
if (null != sortTempFileChunkHolder) {
sortTempFileChunkHolder.closeStream();
}
}
}
}
}
| jackylk/incubator-carbondata | processing/src/main/java/org/apache/carbondata/processing/sort/sortdata/SingleThreadFinalSortFilesMerger.java | Java | apache-2.0 | 10,940 |
/*
* #%L
* asio integration
* %%
* Copyright (C) 2013 - 2015 Research Group Scientific Computing, University of Vienna
* %%
* 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.
* #L%
*/
package at.ac.univie.isc.asio.matcher;
import at.ac.univie.isc.asio.sql.ConvertToTable;
import com.google.common.base.Charsets;
import com.google.common.base.Throwables;
import com.google.common.collect.Table;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
import javax.sql.rowset.RowSetProvider;
import javax.sql.rowset.WebRowSet;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
abstract class SqlResultMatcher extends TypeSafeMatcher<String> {
static class Csv extends SqlResultMatcher {
Csv(final Table<Integer, String, String> expected) {
super(expected);
}
@Override
protected Table<Integer, String, String> parse(final InputStream data) throws IOException {
return ConvertToTable.fromCsv(data);
}
}
static class Webrowset extends SqlResultMatcher {
Webrowset(final Table<Integer, String, String> expected) {
super(expected);
}
@Override
protected Table<Integer, String, String> parse(final InputStream data) throws IOException, SQLException {
final WebRowSet webRowSet = RowSetProvider.newFactory().createWebRowSet();
webRowSet.readXml(data);
return ConvertToTable.fromResultSet(webRowSet);
}
}
private final Table<Integer, String, String> expected;
SqlResultMatcher(final Table<Integer, String, String> expected) {
this.expected = expected;
}
protected abstract Table<Integer, String, String> parse(final InputStream data) throws Exception;
@Override
protected boolean matchesSafely(final String item) {
return expected.equals(doConvert(item));
}
@Override
public void describeTo(final Description description) {
description.appendText(" sql result-set containing ").appendValue(expected);
}
@Override
protected void describeMismatchSafely(final String item, final Description mismatchDescription) {
mismatchDescription.appendText("was ").appendValue(doConvert(item));
}
private Table<Integer, String, String> doConvert(final String item) {
try {
final ByteArrayInputStream raw = new ByteArrayInputStream(item.getBytes(Charsets.UTF_8));
return parse(raw);
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
}
| pyranja/asio | integration/src/main/java/at/ac/univie/isc/asio/matcher/SqlResultMatcher.java | Java | apache-2.0 | 2,993 |
/*
* Copyright 2011-2017 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.apigateway.internal;
import com.amazonaws.Request;
import com.amazonaws.Response;
import com.amazonaws.handlers.RequestHandler2;
import java.util.Map;
public final class AcceptJsonRequestHandler extends RequestHandler2 {
@Override
public void beforeRequest(Request<?> request) {
// Some operations marshall to this header, so don't clobber if it exists
if (!request.getHeaders().containsKey("Accept")) {
request.addHeader("Accept", "application/json");
}
}
@Override
public void afterResponse(Request<?> request, Response<?> response) {
// No-op.
}
@Override
public void afterError(
Request<?> request,
Response<?> response,
Exception e) {
// No-op.
}
}
| dagnir/aws-sdk-java | aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/internal/AcceptJsonRequestHandler.java | Java | apache-2.0 | 1,404 |
package fr.utc.leapband.view;
import jade.gui.GuiEvent;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.beans.PropertyChangeEvent;
import java.io.File;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import fr.utc.leapband.sma.user.UserAgent;
import fr.utc.leapband.utilities.Constance;
import fr.utc.leapband.utilities.ImageFlowItem;
@SuppressWarnings("serial")
public class InstrumentSelectView extends JAgentFrame{
private ImageFlow imageFlow = null;
private JButton home;
public InstrumentSelectView(UserAgent agent) {
super(agent);
this.setTitle("ChooseView");
this.setSize(Constance.Windows_width, Constance.Windows_height);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel imageFlowPanel=new JPanel(new BorderLayout());
imageFlowPanel.setBackground(new Color(110, 110, 110));
home = new JButton();
Icon icon = new ImageIcon("images/home.png");
home.setBounds(0,0,100,100);
home.setIcon(icon);
imageFlowPanel.add(home);
JLabel choose=new JLabel("Choose your instrument");
choose.setBounds(500, 10, 500, 200);
choose.setFont(new Font("Chalkboard", Font.PLAIN, 40));
choose.setHorizontalAlignment(SwingConstants.CENTER);
choose.setForeground(Color.ORANGE);
imageFlowPanel.add(choose);
imageFlow = new ImageFlow(new File("images/instrument/"),agent);
imageFlowPanel.add(imageFlow);
this.add(imageFlowPanel);
home.addMouseListener(new HomeMouseListener(this,home));
home.setContentAreaFilled(false);
home.setOpaque(false);
home.setBorderPainted(false);
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
super.propertyChange(evt);
if (isVisible()) {
if (evt.getPropertyName().equals("swipe")) {
if ((String)evt.getNewValue() == "LEFT") {
imageFlow.scrollAndAnimateBy(-1);
} else if ((String)evt.getNewValue() == "RIGHT") {
imageFlow.scrollAndAnimateBy(1);
} else if ((String)evt.getNewValue() == "GRAB" && imageFlow.getSelectedIndex() != 2) {
GuiEvent ev = new GuiEvent(this,UserAgent.SELECT_INSTRUMENT_EVENT);
ev.addParameter(UserAgent.instrument_Mode);
ev.addParameter(((ImageFlowItem)imageFlow.getSelectedValue()).getLabel());
myAgent.postGuiEvent(ev);
}
}
}
}
}
| hukewei/leapband | src/fr/utc/leapband/view/InstrumentSelectView.java | Java | apache-2.0 | 2,477 |
package com.meteorite.core.datasource;
import org.junit.Test;
public class DataSourceManagerTest {
@Test
public void testExp() throws Exception {
}
} | weijiancai/metaui | core/src/test/java/com/meteorite/core/datasource/DataSourceManagerTest.java | Java | apache-2.0 | 166 |
//Copyright 2015 Sebastian Bingel
//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.
namespace sebingel.sharpchievements
{
/// <summary>
/// Delegate for the event that is fired when an AchievementCondition is completed
/// </summary>
/// <param name="achievementCondition">The completed AchievementCondition</param>
public delegate void AchievementConditionCompletedHandler(IAchievementCondition achievementCondition);
}
| sebingel/sharpchievements | Achievements/AchievementConditionCompletedHandler.cs | C# | apache-2.0 | 938 |
package org.vaadin.addons.producttour.button;
import com.vaadin.event.ConnectorEvent;
import org.vaadin.addons.producttour.provider.StepButtonProvider;
import org.vaadin.addons.producttour.provider.StepProvider;
import org.vaadin.addons.producttour.provider.TourProvider;
import org.vaadin.addons.producttour.step.Step;
import org.vaadin.addons.producttour.tour.Tour;
/**
* Base class for all events that were caused by a {@link StepButton}.
*/
public class StepButtonEvent extends ConnectorEvent implements TourProvider, StepProvider,
StepButtonProvider {
/**
* Construct a new provider.
*
* @param source
* The source of the provider
*/
public StepButtonEvent(StepButton source) {
super(source);
}
/**
* Shortcut method to get the tour of the provider.
*
* @return The tour or <code>null</code> if the button that caused the provider is not attached to
* any step that is attached to a tour.
*/
@Override
public Tour getTour() {
Step step = getStep();
return step != null ? step.getTour() : null;
}
/**
* Shortcut method to get the step of the provider.
*
* @return The step or <code>null</code> if the button that caused the provider is not attached to
* any step.
*/
@Override
public Step getStep() {
StepButton button = getStepButton();
return button != null ? button.getStep() : null;
}
/**
* Get the button that is the source of the provider.
*
* @return The button that caused the provider
*/
@Override
public StepButton getStepButton() {
return (StepButton) getSource();
}
}
| Juchar/product-tour | product-tour-addon/src/main/java/org/vaadin/addons/producttour/button/StepButtonEvent.java | Java | apache-2.0 | 1,731 |
<?php
/*
* @package s9e\TextFormatter
* @copyright Copyright (c) 2010-2019 The s9e Authors
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
namespace s9e\TextFormatter\Configurator\JavaScript;
use Exception;
abstract class Minifier
{
public $cacheDir;
public $keepGoing = \false;
abstract public function minify($src);
public function get($src)
{
try
{
return (isset($this->cacheDir)) ? $this->getFromCache($src) : $this->minify($src);
}
catch (Exception $e)
{
if (!$this->keepGoing)
throw $e;
}
return $src;
}
public function getCacheDifferentiator()
{
return '';
}
protected function getFromCache($src)
{
$differentiator = $this->getCacheDifferentiator();
$key = \sha1(\serialize([\get_class($this), $differentiator, $src]));
$cacheFile = $this->cacheDir . '/minifier.' . $key . '.js';
if (!\file_exists($cacheFile))
\file_put_contents($cacheFile, $this->minify($src));
return \file_get_contents($cacheFile);
}
} | drthomas21/WordPress_Tutorial | community_htdocs/vendor/s9e/text-formatter/src/Configurator/JavaScript/Minifier.php | PHP | apache-2.0 | 1,018 |
function removeFile() {
var sheet = SpreadsheetApp.getActiveSheet(); //Activate sheet
var tno = sheet.getRange('C1').getValues();
var file_name = 'Current Test Buffer-'+tno+'.zip';
var folder = DriveApp.getFolderById('0B5Sb6IOPwl52flVvMXg4dGJuVVdCYl9fNk1MNlBzazBMdk1IZ3BiWkJRR05TNXFZWUtYV3M');
var file1 = DriveApp.getFilesByName(file_name).next();
//File removal code start
var files = folder.getFiles();
var name = folder.getName();
while ( files.hasNext() ) {
var file = files.next();
folder.removeFile(file);
}
//File removal code ended
var tlatest = Number(tno)+1;//Counter++ for test series number //Logger.log(tlatest);
SpreadsheetApp.getActiveSheet().getRange('C1').setValue(tlatest);
}
| arpan-chavda/my_google_scripts | file_cleaner.js | JavaScript | apache-2.0 | 736 |
using System;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DTcms.Common;
namespace DTcms.Web.admin.Transport
{
public partial class goods_edit : Web.UI.ManagePage
{
string defaultpassword = "0|0|0|0"; //默认显示密码
protected string action = DTEnums.ActionEnum.Add.ToString(); //操作类型
private int id = 0;
protected void Page_Load(object sender, EventArgs e)
{
string _action = DTRequest.GetQueryString("action");
if (!string.IsNullOrEmpty(_action) && _action == DTEnums.ActionEnum.Edit.ToString())
{
this.action = DTEnums.ActionEnum.Edit.ToString();//修改类型
this.id = DTRequest.GetQueryInt("id");
if (this.id == 0)
{
JscriptMsg("传输参数不正确!", "back", "Error");
return;
}
if (!new BLL.Goods().Exists(this.id))
{
JscriptMsg("信息不存在或已被删除!", "back", "Error");
return;
}
}
if (!Page.IsPostBack)
{
ChkAdminLevel("goods_list", DTEnums.ActionEnum.View.ToString()); //检查权限
TreeBind(""); //绑定类别
if (action == DTEnums.ActionEnum.Edit.ToString()) //修改
{
ShowInfo(this.id);
}
}
}
#region 绑定类别=================================
private void TreeBind(string strWhere)
{
}
#endregion
#region 赋值操作=================================
private void ShowInfo(int _id)
{
BLL.Goods bll = new BLL.Goods();
Model.Goods model = bll.GetModel(_id);
txtName.Text = model.Name;
txtCategroy.Text = model.CategoryName;
txtCode.Text = model.Code;
txtUnit.Text = model.Unit;
}
#endregion
#region 增加操作=================================
private bool DoAdd()
{
bool result = false;
Model.Goods model = new Model.Goods();
BLL.Goods bll = new BLL.Goods();
model.Name = txtName.Text.Trim();
model.CategoryName = txtCategroy.Text.Trim();
model.Code = string.IsNullOrEmpty(txtCode.Text.Trim()) ? "" : txtCode.Text.Trim();
model.Unit = txtUnit.Text.Trim();
if (bll.Add(model) > 0)
{
AddAdminLog(DTEnums.ActionEnum.Add.ToString(), "添加客户:" + model.Name); //记录日志
result = true;
}
return result;
}
#endregion
#region 修改操作=================================
private bool DoEdit(int _id)
{
bool result = false;
BLL.Goods bll = new BLL.Goods();
Model.Goods model = bll.GetModel(_id);
model.Name = txtName.Text.Trim();
model.CategoryName = txtCategroy.Text.Trim();
model.Code = string.IsNullOrEmpty(txtCode.Text.Trim()) ? "" : txtCode.Text.Trim();
model.Unit = txtUnit.Text.Trim();
if (bll.Update(model))
{
AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "修改客户信息:" + model.Name); //记录日志
result = true;
}
return result;
}
#endregion
//保存
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (action == DTEnums.ActionEnum.Edit.ToString()) //修改
{
ChkAdminLevel("goods_list", DTEnums.ActionEnum.Edit.ToString()); //检查权限
if (!DoEdit(this.id))
{
JscriptMsg("保存过程中发生错误!", "", "Error");
return;
}
JscriptMsg("修改客户成功!", "goods_list.aspx", "Success");
}
else //添加
{
ChkAdminLevel("goods_list", DTEnums.ActionEnum.Add.ToString()); //检查权限
if (!DoAdd())
{
JscriptMsg("保存过程中发生错误!", "", "Error");
return;
}
JscriptMsg("添加客户成功!", "goods_list.aspx", "Success");
}
}
}
} | LutherW/MTMS | Source/DTcms.Web/admin/Transport/goods_edit.aspx.cs | C# | apache-2.0 | 4,623 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Talifun.Crusher.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Talifun.Crusher.Tests")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("71da7afe-736d-4fe5-b5e7-a78d02301585")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| taliesins/talifun-web | src/Talifun.Crusher.Tests/Properties/AssemblyInfo.cs | C# | apache-2.0 | 1,418 |
#include "test_helper_library.h"
void euler2quat(double roll, double pitch, double yaw, double* q) {
// Compute quaternion
Eigen::Quaterniond q_ = Eigen::AngleAxisd(yaw, Eigen::Vector3d::UnitZ()) *
Eigen::AngleAxisd(pitch, Eigen::Vector3d::UnitY()) *
Eigen::AngleAxisd(roll, Eigen::Vector3d::UnitX());
// Writing quaternion components to array output
q[0] = q_.w();
q[1] = q_.x();
q[2] = q_.y();
q[3] = q_.z();
}
void calculate3dRmsError(double truth[][3], double est[][3],
const int trajectory_length, const int start_index,
double* error) {
// Looping over trajectories summing squared errors
double error_sum[3] = {0.0, 0.0, 0.0};
for (int i = start_index; i < trajectory_length; i++) {
error_sum[0] += pow(truth[i][0] - est[i][0], 2);
error_sum[1] += pow(truth[i][1] - est[i][1], 2);
error_sum[2] += pow(truth[i][2] - est[i][2], 2);
}
// Averaging
int num_samples = trajectory_length - start_index + 1;
error_sum[0] /= num_samples;
error_sum[1] /= num_samples;
error_sum[2] /= num_samples;
// Square rooting to obtain RMS
error[0] = sqrt(error_sum[0]);
error[1] = sqrt(error_sum[1]);
error[2] = sqrt(error_sum[2]);
}
void calculateQuaternionRmsError(double truth[][4], double est[][4],
const int trajectory_length,
const int start_index, double* error) {
// Generating the error trajectory
double error_trajectory[trajectory_length][3];
for (int i = 0; i < trajectory_length; i++) {
// Turning vectors into quaternions
Eigen::Quaterniond orientation_truth(truth[i][0], truth[i][1], truth[i][2],
truth[i][3]);
Eigen::Quaterniond orientation_estimate(est[i][0], est[i][1], est[i][2],
est[i][3]);
// Calculating the error quaternion
Eigen::Quaterniond error_quaternion =
orientation_estimate.inverse() * orientation_truth;
// Extracting the three meaningful components of the error quaternion
error_trajectory[i][0] = error_quaternion.x();
error_trajectory[i][1] = error_quaternion.y();
error_trajectory[i][2] = error_quaternion.z();
}
// Looping over trajectories summing squared errors
double error_sum[3] = {0.0, 0.0, 0.0};
for (int i = start_index; i < trajectory_length; i++) {
error_sum[0] += pow(error_trajectory[i][0], 2);
error_sum[1] += pow(error_trajectory[i][1], 2);
error_sum[2] += pow(error_trajectory[i][2], 2);
}
// Averaging
int num_samples = trajectory_length - start_index + 1;
error_sum[0] /= num_samples;
error_sum[1] /= num_samples;
error_sum[2] /= num_samples;
// Square rooting to obtain RMS
error[0] = sqrt(error_sum[0]);
error[1] = sqrt(error_sum[1]);
error[2] = sqrt(error_sum[2]);
}
| ethz-asl/ros_vrpn_client | src/test/library/test_helper_library.cpp | C++ | apache-2.0 | 2,913 |
/*
* Copyright (c) 2014 DataTorrent, 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.
*/
'use strict';
angular.module('ui.dashboard', ['ui.bootstrap', 'ui.sortable']);
angular.module('ui.dashboard')
.directive('dashboard', ['WidgetModel', 'WidgetDefCollection', '$uibModal', 'DashboardState', '$log', function (WidgetModel, WidgetDefCollection, $uibModal, DashboardState, $log) {
return {
restrict: 'A',
templateUrl: function(element, attr) {
return attr.templateUrl ? attr.templateUrl : 'components/directives/dashboard/dashboard.html';
},
scope: true,
controller: ['$scope', '$attrs', function (scope, attrs) {
// default options
var defaults = {
stringifyStorage: true,
hideWidgetSettings: false,
hideWidgetClose: false,
settingsModalOptions: {
templateUrl: 'components/directives/dashboard/widget-settings-template.html',
controller: 'WidgetSettingsCtrl'
},
onSettingsClose: function(result, widget) { // NOTE: dashboard scope is also passed as 3rd argument
jQuery.extend(true, widget, result);
},
onSettingsDismiss: function(reason) { // NOTE: dashboard scope is also passed as 2nd argument
$log.info('widget settings were dismissed. Reason: ', reason);
}
};
// from dashboard="options"
scope.options = scope.$eval(attrs.dashboard);
// Ensure settingsModalOptions exists on scope.options
scope.options.settingsModalOptions = scope.options.settingsModalOptions !== undefined ? scope.options.settingsModalOptions : {};
// Set defaults
_.defaults(scope.options.settingsModalOptions, defaults.settingsModalOptions);
// Shallow options
_.defaults(scope.options, defaults);
// sortable options
var sortableDefaults = {
stop: function () {
scope.saveDashboard();
},
handle: '.widget-header',
distance: 5
};
scope.sortableOptions = angular.extend({}, sortableDefaults, scope.options.sortableOptions || {});
}],
link: function (scope) {
// Save default widget config for reset
scope.defaultWidgets = scope.options.defaultWidgets;
scope.widgetDefs = new WidgetDefCollection(scope.options.widgetDefinitions);
var count = 1;
// Instantiate new instance of dashboard state
scope.dashboardState = new DashboardState(
scope.options.storage,
scope.options.storageId,
scope.options.storageHash,
scope.widgetDefs,
scope.options.stringifyStorage
);
function getWidget(widgetToInstantiate) {
if (typeof widgetToInstantiate === 'string') {
widgetToInstantiate = {
name: widgetToInstantiate
};
}
var defaultWidgetDefinition = scope.widgetDefs.getByName(widgetToInstantiate.name);
if (!defaultWidgetDefinition) {
throw 'Widget ' + widgetToInstantiate.name + ' is not found.';
}
// Determine the title for the new widget
var title;
if (!widgetToInstantiate.title && !defaultWidgetDefinition.title) {
widgetToInstantiate.title = 'Widget ' + count++;
}
// Instantiation
return new WidgetModel(defaultWidgetDefinition, widgetToInstantiate);
}
/**
* Instantiates a new widget and append it the dashboard
* @param {Object} widgetToInstantiate The definition object of the widget to be instantiated
*/
scope.addWidget = function (widgetToInstantiate, doNotSave) {
var widget = getWidget(widgetToInstantiate);
// Add to the widgets array
scope.widgets.push(widget);
if (!doNotSave) {
scope.saveDashboard();
}
return widget;
};
/**
* Instantiates a new widget and insert it a beginning of dashboard
*/
scope.prependWidget = function(widgetToInstantiate, doNotSave) {
var widget = getWidget(widgetToInstantiate);
// Add to the widgets array
scope.widgets.unshift(widget);
if (!doNotSave) {
scope.saveDashboard();
}
return widget;
};
/**
* Removes a widget instance from the dashboard
* @param {Object} widget The widget instance object (not a definition object)
*/
scope.removeWidget = function (widget) {
scope.widgets.splice(_.indexOf(scope.widgets, widget), 1);
scope.saveDashboard();
};
/**
* Opens a dialog for setting and changing widget properties
* @param {Object} widget The widget instance object
*/
scope.openWidgetSettings = function (widget) {
// Set up $uibModal options
var options = _.defaults(
{ scope: scope },
widget.settingsModalOptions,
scope.options.settingsModalOptions);
// Ensure widget is resolved
options.resolve = {
widget: function () {
return widget;
}
};
// Create the modal
var modalInstance = $uibModal.open(options);
var onClose = widget.onSettingsClose || scope.options.onSettingsClose;
var onDismiss = widget.onSettingsDismiss || scope.options.onSettingsDismiss;
// Set resolve and reject callbacks for the result promise
modalInstance.result.then(
function (result) {
// Call the close callback
onClose(result, widget, scope);
//AW Persist title change from options editor
scope.$emit('widgetChanged', widget);
},
function (reason) {
// Call the dismiss callback
onDismiss(reason, scope);
}
);
};
/**
* Remove all widget instances from dashboard
*/
scope.clear = function (doNotSave) {
scope.widgets = [];
if (doNotSave === true) {
return;
}
scope.saveDashboard();
};
/**
* Used for preventing default on click event
* @param {Object} event A click event
* @param {Object} widgetDef A widget definition object
*/
scope.addWidgetInternal = function (event, widgetDef) {
event.preventDefault();
scope.addWidget(widgetDef);
};
/**
* Uses dashboardState service to save state
*/
scope.saveDashboard = function (force) {
if (!scope.options.explicitSave) {
return scope.dashboardState.save(scope.widgets);
} else {
if (!angular.isNumber(scope.options.unsavedChangeCount)) {
scope.options.unsavedChangeCount = 0;
}
if (force) {
scope.options.unsavedChangeCount = 0;
return scope.dashboardState.save(scope.widgets);
} else {
++scope.options.unsavedChangeCount;
}
}
};
/**
* Wraps saveDashboard for external use.
*/
scope.externalSaveDashboard = function(force) {
if (angular.isDefined(force)) {
return scope.saveDashboard(force);
} else {
return scope.saveDashboard(true);
}
};
/**
* Clears current dash and instantiates widget definitions
* @param {Array} widgets Array of definition objects
*/
scope.loadWidgets = function (widgets) {
// AW dashboards are continuously saved today (no "save" button).
//scope.defaultWidgets = widgets;
scope.savedWidgetDefs = widgets;
scope.clear(true);
_.each(widgets, function (widgetDef) {
scope.addWidget(widgetDef, true);
});
};
/**
* Resets widget instances to default config
* @return {[type]} [description]
*/
scope.resetWidgetsToDefault = function () {
scope.loadWidgets(scope.defaultWidgets);
scope.saveDashboard();
};
// Set default widgets array
var savedWidgetDefs = scope.dashboardState.load();
// Success handler
function handleStateLoad(saved) {
scope.options.unsavedChangeCount = 0;
if (saved && saved.length) {
scope.loadWidgets(saved);
} else if (scope.defaultWidgets) {
scope.loadWidgets(scope.defaultWidgets);
} else {
scope.clear(true);
}
}
if (angular.isArray(savedWidgetDefs)) {
handleStateLoad(savedWidgetDefs);
} else if (savedWidgetDefs && angular.isObject(savedWidgetDefs) && angular.isFunction(savedWidgetDefs.then)) {
savedWidgetDefs.then(handleStateLoad, handleStateLoad);
} else {
handleStateLoad();
}
// expose functionality externally
// functions are appended to the provided dashboard options
scope.options.addWidget = scope.addWidget;
scope.options.prependWidget = scope.prependWidget;
scope.options.loadWidgets = scope.loadWidgets;
scope.options.saveDashboard = scope.externalSaveDashboard;
scope.options.removeWidget = scope.removeWidget;
scope.options.openWidgetSettings = scope.openWidgetSettings;
scope.options.clear = scope.clear;
scope.options.resetWidgetsToDefault = scope.resetWidgetsToDefault;
scope.options.currentWidgets = scope.widgets;
// save state
scope.$on('widgetChanged', function (event) {
event.stopPropagation();
scope.saveDashboard();
});
}
};
}]);
| DataTorrent/malhar-angular-dashboard | src/components/directives/dashboard/dashboard.js | JavaScript | apache-2.0 | 10,601 |
package com.gentics.mesh.core.endpoint.admin;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import com.gentics.mesh.cli.BootstrapInitializer;
import com.gentics.mesh.context.InternalActionContext;
import com.gentics.mesh.core.rest.common.GenericMessageResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.reactivex.Completable;
import io.reactivex.schedulers.Schedulers;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
/**
* Handler for the shutdown endpoint.
*/
public class ShutdownHandler {
private static final Logger log = LoggerFactory.getLogger(ShutdownHandler.class);
private final BootstrapInitializer boot;
@Inject
public ShutdownHandler(BootstrapInitializer boot) {
this.boot = boot;
}
/**
* Invoke the shutdown process.
*
* @param context
*/
public void shutdown(InternalActionContext context) {
log.info("Initiating shutdown");
context.send(new GenericMessageResponse("Shutdown initiated"), HttpResponseStatus.OK);
Completable.fromAction(() -> {
boot.mesh().shutdownAndTerminate(1);
})
.subscribeOn(Schedulers.newThread()).timeout(1, TimeUnit.MINUTES)
.subscribe(() -> log.info("Shutdown successful"), err -> {
log.error("Shutdown failed", err);
log.error("Forcing process exit");
Runtime.getRuntime().halt(1);
});
}
}
| gentics/mesh | core/src/main/java/com/gentics/mesh/core/endpoint/admin/ShutdownHandler.java | Java | apache-2.0 | 1,369 |
package com.shareyourproxy.api.domain.model;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import com.shareyourproxy.api.domain.factory.AutoValueClass;
import java.util.HashMap;
import java.util.HashSet;
import auto.parcel.AutoParcel;
import static com.shareyourproxy.util.ObjectUtils.buildFullName;
/**
* Users have a basic profile that contains their specific {@link Channel}s, {@link Contact}s, and {@link Group}s.
*/
@AutoParcel
@AutoValueClass(autoValueClass = AutoParcel_User.class)
public abstract class User implements Parcelable {
/**
* User Constructor.
*
* @param id user unique ID
* @param firstName user first name
* @param lastName user last name
* @param email user email
* @param profileURL user profile picture
* @param coverURL user cover image
* @param channels user channels
* @param groups user contactGroups
* @param contacts user contacts
* @param version user apk version
* @return the entered user data
*/
public static User create(
String id, String firstName, String lastName, String email, String profileURL,
String coverURL, HashMap<String, Channel> channels, HashMap<String, Group> groups,
HashSet<String> contacts, int version) {
String fullName = buildFullName(firstName, lastName);
return builder().id(id).first(firstName).last(lastName).fullName(fullName).email(email)
.profileURL(profileURL).coverURL(coverURL).channels(channels)
.groups(groups).contacts(contacts).version(version).build();
}
/**
* User builder.
*
* @return this User.
*/
public static Builder builder() {
return new AutoParcel_User.Builder();
}
/**
* Get users unique ID.
*
* @return first name
*/
public abstract String id();
/**
* Get users first name.
*
* @return first name
*/
public abstract String first();
/**
* Get users last name.
*
* @return last name
*/
@Nullable
public abstract String last();
/**
* Get users first + " " + last.
*
* @return last name
*/
public abstract String fullName();
/**
* Get users email.
*
* @return email
*/
@Nullable
public abstract String email();
/**
* Get user profile image.
*
* @return profile image
*/
@Nullable
public abstract String profileURL();
/**
* Get user profile image.
*
* @return profile image
*/
@Nullable
public abstract String coverURL();
/**
* Get users channels.
*
* @return channels
*/
@Nullable
public abstract HashMap<String, Channel> channels();
/**
* Get users contacts.
*
* @return contacts
*/
@Nullable
public abstract HashSet<String> contacts();
/**
* Get users contactGroups.
*
* @return contactGroups
*/
@Nullable
public abstract HashMap<String, Group> groups();
/**
* Get users apk version
*
* @return apk code
*/
@Nullable
public abstract Integer version();
/**
* Validation conditions.
*/
@AutoParcel.Validate
public void validate() {
if (first().length() == 0) {
throw new IllegalStateException("Need a valid first name");
}
}
/**
* User Builder.
*/
@AutoParcel.Builder
public interface Builder {
/**
* Set user id.
*
* @param id user unique id
* @return user id
*/
Builder id(String id);
/**
* Set user first name.
*
* @param firstName user first name
* @return first name string
*/
Builder first(String firstName);
/**
* Set users last name.
*
* @param lastName user last name
* @return last name string
*/
@Nullable
Builder last(String lastName);
/**
* Set users first + last.
*
* @param fullName user first + last
* @return last name string
*/
Builder fullName(String fullName);
/**
* Set user email.
*
* @param email this email
* @return email string
*/
@Nullable
Builder email(String email);
/**
* Set the user profile image URL.
*
* @param profileURL profile image url
* @return URL string
*/
@Nullable
Builder profileURL(String profileURL);
/**
* Set the user profile image URL.
*
* @param coverURL profile cover url
* @return URL string
*/
@Nullable
Builder coverURL(String coverURL);
/**
* Set this {@link User}s {@link Contact}s
*
* @param contacts user contacts
* @return List {@link Contact}
*/
@Nullable
Builder contacts(HashSet<String> contacts);
/**
* Set this {@link User}s {@link Group}s
*
* @param groups user contactGroups
* @return List {@link Group}
*/
@Nullable
Builder groups(HashMap<String, Group> groups);
/**
* Set this {@link User}s {@link Channel}s
*
* @param channels user channels
* @return List {@link Channel}
*/
@Nullable
Builder channels(HashMap<String, Channel> channels);
/**
* Set this users apk version
*
* @param version user apk version
* @return version of build
*/
@Nullable
Builder version(Integer version);
/**
* BUILD.
*
* @return User
*/
User build();
}
}
| ProxyApp/Proxy | Application/src/main/java/com/shareyourproxy/api/domain/model/User.java | Java | apache-2.0 | 5,970 |
package com.vaadin.tests.components.tree;
import com.vaadin.tests.components.TestBase;
import com.vaadin.v7.ui.Tree;
@SuppressWarnings("serial")
public class PreselectedTreeVisible extends TestBase {
@Override
protected void setup() {
String itemId1 = "Item 1";
String itemId2 = "Item 2";
Tree tree = new Tree();
tree.addItem(itemId1);
tree.addItem(itemId2);
// Removing this line causes the tree to show normally in Firefox
tree.select(itemId1);
addComponent(tree);
}
@Override
protected String getDescription() {
return "Tree should be visible when a item has been selected.";
}
@Override
protected Integer getTicketNumber() {
return 5396;
}
}
| Legioth/vaadin | uitest/src/main/java/com/vaadin/tests/components/tree/PreselectedTreeVisible.java | Java | apache-2.0 | 773 |
package ru.job4j.synchronize;
import net.jcip.annotations.GuardedBy;
import net.jcip.annotations.ThreadSafe;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Хранилище User.
*/
@ThreadSafe
public class UserStorage {
/**
* Карта для хранения User.
*/
private Map<Integer, User> storage = new HashMap<>();
/**
* Добавить User.
* @param user User.
* @return true, если добавлен.
*/
@GuardedBy("this")
public synchronized boolean add(User user) {
boolean result = false;
if (!storage.containsKey(user.getId())) {
storage.put(user.getId(), user);
result = true;
}
return result;
}
/**
* Обновить User.
* @param user User.
* @return true, если найден и обновлен.
*/
@GuardedBy("this")
public synchronized boolean update(User user) {
boolean result = false;
if (storage.containsKey(user.getId())) {
storage.put(user.getId(), user);
result = true;
}
return result;
}
/**
* Удалить User.
* @param user User.
* @return true, если найден и удален.
*/
@GuardedBy("this")
public synchronized boolean delete(User user) {
boolean result = false;
if (storage.containsKey(user.getId())) {
storage.remove(user.getId());
result = true;
}
return result;
}
/**
* Перевести сумму между User.
* @param fromId ID отправителя.
* @param toId ID получателя.
* @param amount сумма.
* @return true, если успешно выполнено.
*/
@GuardedBy("this")
public synchronized boolean transfer(int fromId, int toId, int amount) {
boolean result = false;
if (storage.containsKey(fromId) && storage.containsKey(toId)) {
if (storage.get(fromId).getAmount() > amount) {
int temp = storage.get(fromId).getAmount();
storage.replace(fromId, new User(fromId, temp - amount));
temp = storage.get(toId).getAmount();
storage.replace(toId, new User(toId, temp + amount));
result = true;
}
}
return result;
}
/**
* Получить список всех пользователей в UserStorage.
* @return список всех пользователей в UserStorage.
*/
@GuardedBy("this")
public synchronized List<User> getUsers() {
List<User> users = new ArrayList<User>(storage.values());
return users;
}
}
| alexeremeev/aeremeev | chapter_007/src/main/java/ru/job4j/synchronize/UserStorage.java | Java | apache-2.0 | 2,810 |
/**
* 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 test_session_expiration;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import common.CountdownWatcher;
public class TestSessionExpiration {
public static void main(String[] args) throws Exception {
System.out.println("Starting zk1");
// Open a client connection - zk1
CountdownWatcher watch1 = new CountdownWatcher("zk1");
ZooKeeper zk1 = new ZooKeeper(args[0], 10000, watch1);
watch1.waitForConnected(10000);
zk1.getData("/", false, null);
System.out.println("Starting zk2");
// now attach a second client zk2 with the same sessionid/passwd
CountdownWatcher watch2 = new CountdownWatcher("zk2");
ZooKeeper zk2 = new ZooKeeper(args[0], 10000, watch2,
zk1.getSessionId(), zk1.getSessionPasswd());
watch2.waitForConnected(10000);
// close the second client, the session is now invalid
System.out.println("Closing zk2");
zk2.close();
System.out.println("Attempting use of zk1");
try {
// this will throw session expired exception
zk1.getData("/", false, null);
} catch (KeeperException.SessionExpiredException e) {
System.out.println("Got session expired on zk1!");
return;
}
// 3.2.0 and later:
// There's a gotcha though - In version 3.2.0 and later if you
// run this on against a quorum (vs standalone) you may get a
// KeeperException.SessionMovedException instead. This is
// thrown if a client moved from one server to a second, but
// then attempts to talk to the first server (should never
// happen, but could in certain bad situations), this example
// simulates that situation in the sense that the client with
// session id zk1.getSessionId() has moved
//
// One way around session moved on a quorum is to have each
// client connect to the same, single server in the cluster
// (so pass a single host:port rather than a list). This
// will ensure that you get the session expiration, and
// not session moved exception.
//
// Again, if you run against standalone server you won't see
// this. If you run against a server version 3.1.x or earlier
// you won't see this.
// If you run against quorum you need to easily determine which
// server zk1 is attached to - we are adding this capability
// in 3.3.0 - and have zk2 attach to that same server.
System.err.println("Oops, this should NOT have happened!");
}
}
| phunt/zkexamples | src/test_session_expiration/TestSessionExpiration.java | Java | apache-2.0 | 3,492 |
package configconversion
import (
"net"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
configv1 "github.com/openshift/api/config/v1"
kubecontrolplanev1 "github.com/openshift/api/kubecontrolplane/v1"
legacyconfigv1 "github.com/openshift/api/legacyconfig/v1"
externaliprangerv1 "github.com/openshift/origin/pkg/service/admission/apis/externalipranger/v1"
restrictedendpointsv1 "github.com/openshift/origin/pkg/service/admission/apis/restrictedendpoints/v1"
)
func convertNetworkConfigToAdmissionConfig(masterConfig *legacyconfigv1.MasterConfig) error {
if masterConfig.AdmissionConfig.PluginConfig == nil {
masterConfig.AdmissionConfig.PluginConfig = map[string]*legacyconfigv1.AdmissionPluginConfig{}
}
scheme := runtime.NewScheme()
utilruntime.Must(externaliprangerv1.InstallLegacy(scheme))
utilruntime.Must(restrictedendpointsv1.InstallLegacy(scheme))
codecs := serializer.NewCodecFactory(scheme)
encoder := codecs.LegacyCodec(externaliprangerv1.SchemeGroupVersion, restrictedendpointsv1.SchemeGroupVersion)
// convert the networkconfig to admissionconfig
var restricted []string
restricted = append(restricted, masterConfig.NetworkConfig.ServiceNetworkCIDR)
for _, cidr := range masterConfig.NetworkConfig.ClusterNetworks {
restricted = append(restricted, cidr.CIDR)
}
restrictedEndpointConfig := &restrictedendpointsv1.RestrictedEndpointsAdmissionConfig{
RestrictedCIDRs: restricted,
}
restrictedEndpointConfigContent, err := runtime.Encode(encoder, restrictedEndpointConfig)
if err != nil {
return err
}
masterConfig.AdmissionConfig.PluginConfig["openshift.io/RestrictedEndpointsAdmission"] = &legacyconfigv1.AdmissionPluginConfig{
Configuration: runtime.RawExtension{Raw: restrictedEndpointConfigContent},
}
allowIngressIP := false
if _, ipNet, err := net.ParseCIDR(masterConfig.NetworkConfig.IngressIPNetworkCIDR); err == nil && !ipNet.IP.IsUnspecified() {
allowIngressIP = true
}
externalIPRangerAdmissionConfig := &externaliprangerv1.ExternalIPRangerAdmissionConfig{
ExternalIPNetworkCIDRs: masterConfig.NetworkConfig.ExternalIPNetworkCIDRs,
AllowIngressIP: allowIngressIP,
}
externalIPRangerAdmissionConfigContent, err := runtime.Encode(encoder, externalIPRangerAdmissionConfig)
if err != nil {
return err
}
masterConfig.AdmissionConfig.PluginConfig["ExternalIPRanger"] = &legacyconfigv1.AdmissionPluginConfig{
Configuration: runtime.RawExtension{Raw: externalIPRangerAdmissionConfigContent},
}
return nil
}
// ConvertMasterConfigToKubeAPIServerConfig mutates it's input. This is acceptable because we do not need it by the time we get to 4.0.
func ConvertMasterConfigToKubeAPIServerConfig(input *legacyconfigv1.MasterConfig) (*kubecontrolplanev1.KubeAPIServerConfig, error) {
if err := convertNetworkConfigToAdmissionConfig(input); err != nil {
return nil, err
}
var err error
ret := &kubecontrolplanev1.KubeAPIServerConfig{
GenericAPIServerConfig: configv1.GenericAPIServerConfig{
CORSAllowedOrigins: input.CORSAllowedOrigins,
StorageConfig: configv1.EtcdStorageConfig{
StoragePrefix: input.EtcdStorageConfig.OpenShiftStoragePrefix,
},
},
ServicesSubnet: input.KubernetesMasterConfig.ServicesSubnet,
ServicesNodePortRange: input.KubernetesMasterConfig.ServicesNodePortRange,
LegacyServiceServingCertSignerCABundle: input.ControllerConfig.ServiceServingCert.Signer.CertFile,
ImagePolicyConfig: kubecontrolplanev1.KubeAPIServerImagePolicyConfig{
InternalRegistryHostname: input.ImagePolicyConfig.InternalRegistryHostname,
ExternalRegistryHostname: input.ImagePolicyConfig.ExternalRegistryHostname,
},
ProjectConfig: kubecontrolplanev1.KubeAPIServerProjectConfig{
DefaultNodeSelector: input.ProjectConfig.DefaultNodeSelector,
},
ServiceAccountPublicKeyFiles: input.ServiceAccountConfig.PublicKeyFiles,
// TODO this needs to be removed.
APIServerArguments: map[string]kubecontrolplanev1.Arguments{},
}
for k, v := range input.KubernetesMasterConfig.APIServerArguments {
ret.APIServerArguments[k] = v
}
// TODO this is likely to be a little weird. I think we override most of this in the operator
ret.ServingInfo, err = ToHTTPServingInfo(&input.ServingInfo)
if err != nil {
return nil, err
}
ret.OAuthConfig, err = ToOAuthConfig(input.OAuthConfig)
if err != nil {
return nil, err
}
ret.AuthConfig, err = ToMasterAuthConfig(&input.AuthConfig)
if err != nil {
return nil, err
}
ret.AggregatorConfig, err = ToAggregatorConfig(&input.AggregatorConfig)
if err != nil {
return nil, err
}
ret.AuditConfig, err = ToAuditConfig(&input.AuditConfig)
if err != nil {
return nil, err
}
ret.StorageConfig.EtcdConnectionInfo, err = ToEtcdConnectionInfo(&input.EtcdClientInfo)
if err != nil {
return nil, err
}
ret.KubeletClientInfo, err = ToKubeletConnectionInfo(&input.KubeletClientInfo)
if err != nil {
return nil, err
}
ret.AdmissionPluginConfig, err = ToAdmissionPluginConfigMap(input.AdmissionConfig.PluginConfig)
if err != nil {
return nil, err
}
ret.UserAgentMatchingConfig, err = ToUserAgentMatchingConfig(&input.PolicyConfig.UserAgentMatchingConfig)
if err != nil {
return nil, err
}
return ret, nil
}
| PI-Victor/origin | pkg/configconversion/legacyconfig_conversion.go | GO | apache-2.0 | 5,292 |
package tamil.lang.api.join;
import tamil.lang.known.IKnownWord;
/**
* <p>
* Joins known words and based on the type of புணர்ச்சி.
*
* </p>
*
* @author velsubra
*/
public interface KnownWordsJoiner {
public static enum TYPE {
VEATTUMAI,
ALVAZHI
}
/**
* adds word to the current sum of the joiner by means of doing புணர்ச்சி
* @param word the word to be added
*/
public void addVaruMozhi(IKnownWord word, TYPE type);
/**
* adds the current sum of the joiner into the given word by doing புணர்ச்சி
* @param word the word to be inserted
*/
public void addNilaiMozhi(IKnownWord word, TYPE type);
/**
* The effective word that is generated.
* @return the sum out of one or more additions using {@link #addVaruMozhi(tamil.lang.known.IKnownWord, tamil.lang.api.join.KnownWordsJoiner.TYPE)}
*/
public IKnownWord getSum();
}
| velsubra/Tamil | ezhuththu/src/main/java/tamil/lang/api/join/KnownWordsJoiner.java | Java | apache-2.0 | 984 |
package main
import (
"fmt"
"github.com/satori/go.uuid"
)
func main() {
// Creating UUID Version 4
u1 := uuid.NewV4()
fmt.Printf("UUIDv4: %s\n", u1)
// Parsing UUID from string input
u2, err := uuid.FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
if err != nil {
fmt.Printf("Something gone wrong: %s\n", err)
}
fmt.Printf("Successfully parsed: %s\n", u2)
}
| gothxx/backyard | go/src/test/makeUUID.go | GO | apache-2.0 | 411 |
import os
import threading
import datetime
import cloudstorage as gcs
from google.appengine.api import app_identity
class FileServer():
def __init__(self):
bucket_name = os.environ.get('BUCKET_NAME',
app_identity.get_default_gcs_bucket_name())
self.bucket = '/' + bucket_name
def GetFileForPath(self, path):
try:
full_path = self.bucket + '/' + path
file_obj = gcs.open(full_path)
data = file_obj.read()
file_obj.close()
return data
except gcs.NotFoundError:
return None
| benmorss/excalibur | cloudserver.py | Python | apache-2.0 | 563 |
package io.skysail.server.app.demo.timetable.course.resources;
import org.restlet.resource.ResourceException;
import io.skysail.domain.core.repos.Repository;
import io.skysail.server.ResourceContextId;
import io.skysail.server.app.demo.DemoApplication;
import io.skysail.server.app.demo.timetable.course.Course;
import io.skysail.server.app.demo.timetable.timetables.Timetable;
import io.skysail.server.restlet.resources.PostEntityServerResource;
public class PostCourseResource extends PostEntityServerResource<Course> {
private DemoApplication app;
public PostCourseResource() {
addToContext(ResourceContextId.LINK_TITLE, "Create new ");
}
@Override
protected void doInit() throws ResourceException {
app = (DemoApplication) getApplication();
}
@Override
public Course createEntityTemplate() {
return new Course();
}
@Override
public void addEntity(Course entity) {
// Subject subject = SecurityUtils.getSubject();
Timetable entityRoot = app.getTtRepo().findOne(getAttribute("id"));
entityRoot.getCourses().add(entity);
app.getTtRepo().update(entityRoot, app.getApplicationModel());
}
@Override
public String redirectTo() {
return super.redirectTo(CoursesResource.class);
}
} | evandor/skysail | skysail.server.app.demo/src/io/skysail/server/app/demo/timetable/course/resources/PostCourseResource.java | Java | apache-2.0 | 1,307 |
package cases;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.testng.annotations.Test;
import cn.bubi.tools.acc.Sign;
import net.sf.json.JSONObject;
import utils.APIUtil;
import utils.HttpUtil;
import utils.Result;
import utils.SignUtil;
import utils.TxUtil;
import base.TestBase;
@Test
public class SubmitTxTest extends TestBase{
/*
* verify signatures is exist
*/
// @Test
public void signaturesCheck(){
String tran_blob = null;
JSONObject item = TxUtil.itemBlobonly(tran_blob);
JSONObject items = TxUtil.tx(item);
System.out.println(items);
String result = TxUtil.txPost(items);
int err_code = Result.getErrorCode(result);
check.assertEquals(err_code, 2,"signatures Ϊ¿ÕУÑéʧ°Ü");
}
/*
* verify transaction blob must be Hex
*/
// @Test
public void transaction_blobCheck(){
List signature = new ArrayList();
String tranblob = "qq";
JSONObject item = TxUtil.item(signature,tranblob);
JSONObject items = TxUtil.tx(item);
String result = TxUtil.txPost(items);
int err_code = Result.getErrorCode(result);
check.assertEquals(err_code, 2,"transaction_blob УÑéʧ°Ü");
}
/*
* invalid sign_data
*/
// @Test
public void sign_dataCheck(){
String sign_data = "275*-a525386cf5410ca";
String public_key = APIUtil.generateAcc().get("public_key");
List signature = TxUtil.signatures(sign_data, public_key);
String tranblob = "1231";
JSONObject item = TxUtil.item(signature,tranblob);
JSONObject items = TxUtil.tx(item);
String result = TxUtil.txPost(items);
int err_code = Result.getErrorCode(result);
check.assertEquals(err_code, 2,"signatures Ϊ¿ÕУÑéʧ°Ü");
}
// @Test
public void jsonBodyCheck1(){
//json body check in GetTransactionBlob
String testBody = "test";
String result = SignUtil.getUnSignBlobResult(testBody);
int error_code = Result.getErrorCode(result);
check.assertEquals(error_code, 2,"GetTransactionBlob json body check failed");
}
// @Test
public void jsonBodyCheck2(){
//json body check in SubmitTransaction
String testBody = "test";
String result = HttpUtil.dopost(baseUrl,"submitTransaction",testBody);
int error_code = Result.getErrorCode(result);
check.assertEquals(error_code, 2,"submitTransaction json body check failed");
}
// @Test
public void fileNotFoundCheck(){
String test = "test";
String result = HttpUtil.doget(test);
check.contains(result, "File not found", "File not found func check failed");
}
/*
* verify public_key
*/
// @Test
public void public_keyCheck(){
//get correct sign_data and blob by issueTx;
int type = 2;
int asset_type = 1;
Object asset_issuer = led_acc;
String asset_code = "abc" ;
int asset_amount = 100;
String metadata = "abcd";
String source_address = led_acc;
long sequence_number = Result.seq_num(led_acc);
List opers = TxUtil.operIssue(type, asset_type, asset_issuer, asset_code, asset_amount);
JSONObject tran = TxUtil.tran_json(source_address, fee, sequence_number, metadata, opers);
String blobresult = SignUtil.getUnSignBlobResult(tran);
String blobString = SignUtil.getTranBlobsString(blobresult);
String sign_data;
try {
sign_data = Sign.priKeysign(blobString, led_pri);
String public_key = "aa";
List signature = TxUtil.signatures(sign_data, public_key);
String tranblob = "1231";
JSONObject item = TxUtil.item(signature,blobString);
JSONObject items = TxUtil.tx(item);
String result = TxUtil.txPost(items);
int err_code = Result.getErrorCode(result);
check.assertEquals(err_code, 2,"ÎÞЧµÄpublic_keyУÑéʧ°Ü");
} catch (Exception e) {
e.printStackTrace();
}
}
}
| bubichain/blockchain | test/testcase/testng/InterfaceTest-1.8/src/cases/SubmitTxTest.java | Java | apache-2.0 | 3,761 |
/*
* MinIO Cloud Storage, (C) 2017-2020 MinIO, 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 s3
import (
"context"
"encoding/json"
"io"
"math/rand"
"net/http"
"net/url"
"strings"
"time"
"github.com/minio/cli"
miniogo "github.com/minio/minio-go/v6"
"github.com/minio/minio-go/v6/pkg/credentials"
"github.com/minio/minio-go/v6/pkg/tags"
minio "github.com/minio/minio/cmd"
"github.com/minio/minio-go/v6/pkg/encrypt"
"github.com/minio/minio-go/v6/pkg/s3utils"
xhttp "github.com/minio/minio/cmd/http"
"github.com/minio/minio/cmd/logger"
"github.com/minio/minio/pkg/auth"
"github.com/minio/minio/pkg/bucket/policy"
)
const (
s3Backend = "s3"
)
func init() {
const s3GatewayTemplate = `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} {{if .VisibleFlags}}[FLAGS]{{end}} [ENDPOINT]
{{if .VisibleFlags}}
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}{{end}}
ENDPOINT:
s3 server endpoint. Default ENDPOINT is https://s3.amazonaws.com
EXAMPLES:
1. Start minio gateway server for AWS S3 backend
{{.Prompt}} {{.EnvVarSetCommand}} MINIO_ACCESS_KEY{{.AssignmentOperator}}accesskey
{{.Prompt}} {{.EnvVarSetCommand}} MINIO_SECRET_KEY{{.AssignmentOperator}}secretkey
{{.Prompt}} {{.HelpName}}
2. Start minio gateway server for AWS S3 backend with edge caching enabled
{{.Prompt}} {{.EnvVarSetCommand}} MINIO_ACCESS_KEY{{.AssignmentOperator}}accesskey
{{.Prompt}} {{.EnvVarSetCommand}} MINIO_SECRET_KEY{{.AssignmentOperator}}secretkey
{{.Prompt}} {{.EnvVarSetCommand}} MINIO_CACHE_DRIVES{{.AssignmentOperator}}"/mnt/drive1,/mnt/drive2,/mnt/drive3,/mnt/drive4"
{{.Prompt}} {{.EnvVarSetCommand}} MINIO_CACHE_EXCLUDE{{.AssignmentOperator}}"bucket1/*,*.png"
{{.Prompt}} {{.EnvVarSetCommand}} MINIO_CACHE_QUOTA{{.AssignmentOperator}}90
{{.Prompt}} {{.EnvVarSetCommand}} MINIO_CACHE_AFTER{{.AssignmentOperator}}3
{{.Prompt}} {{.EnvVarSetCommand}} MINIO_CACHE_WATERMARK_LOW{{.AssignmentOperator}}75
{{.Prompt}} {{.EnvVarSetCommand}} MINIO_CACHE_WATERMARK_HIGH{{.AssignmentOperator}}85
{{.Prompt}} {{.HelpName}}
`
minio.RegisterGatewayCommand(cli.Command{
Name: s3Backend,
Usage: "Amazon Simple Storage Service (S3)",
Action: s3GatewayMain,
CustomHelpTemplate: s3GatewayTemplate,
HideHelpCommand: true,
})
}
// Handler for 'minio gateway s3' command line.
func s3GatewayMain(ctx *cli.Context) {
args := ctx.Args()
if !ctx.Args().Present() {
args = cli.Args{"https://s3.amazonaws.com"}
}
serverAddr := ctx.GlobalString("address")
if serverAddr == "" || serverAddr == ":"+minio.GlobalMinioDefaultPort {
serverAddr = ctx.String("address")
}
// Validate gateway arguments.
logger.FatalIf(minio.ValidateGatewayArguments(serverAddr, args.First()), "Invalid argument")
// Start the gateway..
minio.StartGateway(ctx, &S3{args.First()})
}
// S3 implements Gateway.
type S3 struct {
host string
}
// Name implements Gateway interface.
func (g *S3) Name() string {
return s3Backend
}
const letterBytes = "abcdefghijklmnopqrstuvwxyz01234569"
const (
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
)
// randString generates random names and prepends them with a known prefix.
func randString(n int, src rand.Source, prefix string) string {
b := make([]byte, n)
// A rand.Int63() generates 63 random bits, enough for letterIdxMax letters!
for i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return prefix + string(b[0:30-len(prefix)])
}
// Chains all credential types, in the following order:
// - AWS env vars (i.e. AWS_ACCESS_KEY_ID)
// - AWS creds file (i.e. AWS_SHARED_CREDENTIALS_FILE or ~/.aws/credentials)
// - Static credentials provided by user (i.e. MINIO_ACCESS_KEY)
var defaultProviders = []credentials.Provider{
&credentials.EnvAWS{},
&credentials.FileAWSCredentials{},
&credentials.EnvMinio{},
}
// Chains all credential types, in the following order:
// - AWS env vars (i.e. AWS_ACCESS_KEY_ID)
// - AWS creds file (i.e. AWS_SHARED_CREDENTIALS_FILE or ~/.aws/credentials)
// - IAM profile based credentials. (performs an HTTP
// call to a pre-defined endpoint, only valid inside
// configured ec2 instances)
var defaultAWSCredProviders = []credentials.Provider{
&credentials.EnvAWS{},
&credentials.FileAWSCredentials{},
&credentials.IAM{
Client: &http.Client{
Transport: minio.NewGatewayHTTPTransport(),
},
},
&credentials.EnvMinio{},
}
// newS3 - Initializes a new client by auto probing S3 server signature.
func newS3(urlStr string) (*miniogo.Core, error) {
if urlStr == "" {
urlStr = "https://s3.amazonaws.com"
}
u, err := url.Parse(urlStr)
if err != nil {
return nil, err
}
// Override default params if the host is provided
endpoint, secure, err := minio.ParseGatewayEndpoint(urlStr)
if err != nil {
return nil, err
}
var creds *credentials.Credentials
if s3utils.IsAmazonEndpoint(*u) {
// If we see an Amazon S3 endpoint, then we use more ways to fetch backend credentials.
// Specifically IAM style rotating credentials are only supported with AWS S3 endpoint.
creds = credentials.NewChainCredentials(defaultAWSCredProviders)
} else {
creds = credentials.NewChainCredentials(defaultProviders)
}
options := miniogo.Options{
Creds: creds,
Secure: secure,
Region: s3utils.GetRegionFromURL(*u),
BucketLookup: miniogo.BucketLookupAuto,
}
clnt, err := miniogo.NewWithOptions(endpoint, &options)
if err != nil {
return nil, err
}
return &miniogo.Core{Client: clnt}, nil
}
// NewGatewayLayer returns s3 ObjectLayer.
func (g *S3) NewGatewayLayer(creds auth.Credentials) (minio.ObjectLayer, error) {
// creds are ignored here, since S3 gateway implements chaining
// all credentials.
clnt, err := newS3(g.host)
if err != nil {
return nil, err
}
metrics := minio.NewMetrics()
t := &minio.MetricsTransport{
Transport: minio.NewGatewayHTTPTransport(),
Metrics: metrics,
}
// Set custom transport
clnt.SetCustomTransport(t)
probeBucketName := randString(60, rand.NewSource(time.Now().UnixNano()), "probe-bucket-sign-")
// Check if the provided keys are valid.
if _, err = clnt.BucketExists(probeBucketName); err != nil {
if miniogo.ToErrorResponse(err).Code != "AccessDenied" {
return nil, err
}
}
s := s3Objects{
Client: clnt,
Metrics: metrics,
HTTPClient: &http.Client{
Transport: t,
},
}
// Enables single encryption of KMS is configured.
if minio.GlobalKMS != nil {
encS := s3EncObjects{s}
// Start stale enc multipart uploads cleanup routine.
go encS.cleanupStaleEncMultipartUploads(minio.GlobalContext,
minio.GlobalMultipartCleanupInterval, minio.GlobalMultipartExpiry)
return &encS, nil
}
return &s, nil
}
// Production - s3 gateway is production ready.
func (g *S3) Production() bool {
return true
}
// s3Objects implements gateway for MinIO and S3 compatible object storage servers.
type s3Objects struct {
minio.GatewayUnsupported
Client *miniogo.Core
HTTPClient *http.Client
Metrics *minio.Metrics
}
// GetMetrics returns this gateway's metrics
func (l *s3Objects) GetMetrics(ctx context.Context) (*minio.Metrics, error) {
return l.Metrics, nil
}
// Shutdown saves any gateway metadata to disk
// if necessary and reload upon next restart.
func (l *s3Objects) Shutdown(ctx context.Context) error {
return nil
}
// StorageInfo is not relevant to S3 backend.
func (l *s3Objects) StorageInfo(ctx context.Context, _ bool) (si minio.StorageInfo, _ []error) {
si.Backend.Type = minio.BackendGateway
si.Backend.GatewayOnline = minio.IsBackendOnline(ctx, l.HTTPClient, l.Client.EndpointURL().String())
return si, nil
}
// MakeBucket creates a new container on S3 backend.
func (l *s3Objects) MakeBucketWithLocation(ctx context.Context, bucket, location string, lockEnabled bool) error {
if lockEnabled {
return minio.NotImplemented{}
}
// Verify if bucket name is valid.
// We are using a separate helper function here to validate bucket
// names instead of IsValidBucketName() because there is a possibility
// that certains users might have buckets which are non-DNS compliant
// in us-east-1 and we might severely restrict them by not allowing
// access to these buckets.
// Ref - http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html
if s3utils.CheckValidBucketName(bucket) != nil {
return minio.BucketNameInvalid{Bucket: bucket}
}
err := l.Client.MakeBucket(bucket, location)
if err != nil {
return minio.ErrorRespToObjectError(err, bucket)
}
return err
}
// GetBucketInfo gets bucket metadata..
func (l *s3Objects) GetBucketInfo(ctx context.Context, bucket string) (bi minio.BucketInfo, e error) {
buckets, err := l.Client.ListBuckets()
if err != nil {
// Listbuckets may be disallowed, proceed to check if
// bucket indeed exists, if yes return success.
var ok bool
if ok, err = l.Client.BucketExists(bucket); err != nil {
return bi, minio.ErrorRespToObjectError(err, bucket)
}
if !ok {
return bi, minio.BucketNotFound{Bucket: bucket}
}
return minio.BucketInfo{
Name: bi.Name,
Created: time.Now().UTC(),
}, nil
}
for _, bi := range buckets {
if bi.Name != bucket {
continue
}
return minio.BucketInfo{
Name: bi.Name,
Created: bi.CreationDate,
}, nil
}
return bi, minio.BucketNotFound{Bucket: bucket}
}
// ListBuckets lists all S3 buckets
func (l *s3Objects) ListBuckets(ctx context.Context) ([]minio.BucketInfo, error) {
buckets, err := l.Client.ListBuckets()
if err != nil {
return nil, minio.ErrorRespToObjectError(err)
}
b := make([]minio.BucketInfo, len(buckets))
for i, bi := range buckets {
b[i] = minio.BucketInfo{
Name: bi.Name,
Created: bi.CreationDate,
}
}
return b, err
}
// DeleteBucket deletes a bucket on S3
func (l *s3Objects) DeleteBucket(ctx context.Context, bucket string, forceDelete bool) error {
err := l.Client.RemoveBucket(bucket)
if err != nil {
return minio.ErrorRespToObjectError(err, bucket)
}
return nil
}
// ListObjects lists all blobs in S3 bucket filtered by prefix
func (l *s3Objects) ListObjects(ctx context.Context, bucket string, prefix string, marker string, delimiter string, maxKeys int) (loi minio.ListObjectsInfo, e error) {
result, err := l.Client.ListObjects(bucket, prefix, marker, delimiter, maxKeys)
if err != nil {
return loi, minio.ErrorRespToObjectError(err, bucket)
}
return minio.FromMinioClientListBucketResult(bucket, result), nil
}
// ListObjectsV2 lists all blobs in S3 bucket filtered by prefix
func (l *s3Objects) ListObjectsV2(ctx context.Context, bucket, prefix, continuationToken, delimiter string, maxKeys int, fetchOwner bool, startAfter string) (loi minio.ListObjectsV2Info, e error) {
result, err := l.Client.ListObjectsV2(bucket, prefix, continuationToken, fetchOwner, delimiter, maxKeys, startAfter)
if err != nil {
return loi, minio.ErrorRespToObjectError(err, bucket)
}
return minio.FromMinioClientListBucketV2Result(bucket, result), nil
}
// GetObjectNInfo - returns object info and locked object ReadCloser
func (l *s3Objects) GetObjectNInfo(ctx context.Context, bucket, object string, rs *minio.HTTPRangeSpec, h http.Header, lockType minio.LockType, opts minio.ObjectOptions) (gr *minio.GetObjectReader, err error) {
var objInfo minio.ObjectInfo
objInfo, err = l.GetObjectInfo(ctx, bucket, object, opts)
if err != nil {
return nil, minio.ErrorRespToObjectError(err, bucket, object)
}
var startOffset, length int64
startOffset, length, err = rs.GetOffsetLength(objInfo.Size)
if err != nil {
return nil, minio.ErrorRespToObjectError(err, bucket, object)
}
pr, pw := io.Pipe()
go func() {
err := l.GetObject(ctx, bucket, object, startOffset, length, pw, objInfo.ETag, opts)
pw.CloseWithError(err)
}()
// Setup cleanup function to cause the above go-routine to
// exit in case of partial read
pipeCloser := func() { pr.Close() }
return minio.NewGetObjectReaderFromReader(pr, objInfo, opts, pipeCloser)
}
// GetObject reads an object from S3. Supports additional
// parameters like offset and length which are synonymous with
// HTTP Range requests.
//
// startOffset indicates the starting read location of the object.
// length indicates the total length of the object.
func (l *s3Objects) GetObject(ctx context.Context, bucket string, key string, startOffset int64, length int64, writer io.Writer, etag string, o minio.ObjectOptions) error {
if length < 0 && length != -1 {
return minio.ErrorRespToObjectError(minio.InvalidRange{}, bucket, key)
}
opts := miniogo.GetObjectOptions{}
opts.ServerSideEncryption = o.ServerSideEncryption
if startOffset >= 0 && length >= 0 {
if err := opts.SetRange(startOffset, startOffset+length-1); err != nil {
return minio.ErrorRespToObjectError(err, bucket, key)
}
}
object, _, _, err := l.Client.GetObject(bucket, key, opts)
if err != nil {
return minio.ErrorRespToObjectError(err, bucket, key)
}
defer object.Close()
if _, err := io.Copy(writer, object); err != nil {
return minio.ErrorRespToObjectError(err, bucket, key)
}
return nil
}
// GetObjectInfo reads object info and replies back ObjectInfo
func (l *s3Objects) GetObjectInfo(ctx context.Context, bucket string, object string, opts minio.ObjectOptions) (objInfo minio.ObjectInfo, err error) {
oi, err := l.Client.StatObject(bucket, object, miniogo.StatObjectOptions{
GetObjectOptions: miniogo.GetObjectOptions{
ServerSideEncryption: opts.ServerSideEncryption,
},
})
if err != nil {
return minio.ObjectInfo{}, minio.ErrorRespToObjectError(err, bucket, object)
}
return minio.FromMinioClientObjectInfo(bucket, oi), nil
}
// PutObject creates a new object with the incoming data,
func (l *s3Objects) PutObject(ctx context.Context, bucket string, object string, r *minio.PutObjReader, opts minio.ObjectOptions) (objInfo minio.ObjectInfo, err error) {
data := r.Reader
var tagMap map[string]string
if tagstr, ok := opts.UserDefined[xhttp.AmzObjectTagging]; ok && tagstr != "" {
tagObj, err := tags.ParseObjectTags(tagstr)
if err != nil {
return objInfo, minio.ErrorRespToObjectError(err, bucket, object)
}
tagMap = tagObj.ToMap()
delete(opts.UserDefined, xhttp.AmzObjectTagging)
}
putOpts := miniogo.PutObjectOptions{
UserMetadata: opts.UserDefined,
ServerSideEncryption: opts.ServerSideEncryption,
UserTags: tagMap,
}
oi, err := l.Client.PutObject(bucket, object, data, data.Size(), data.MD5Base64String(), data.SHA256HexString(), putOpts)
if err != nil {
return objInfo, minio.ErrorRespToObjectError(err, bucket, object)
}
// On success, populate the key & metadata so they are present in the notification
oi.Key = object
oi.Metadata = minio.ToMinioClientObjectInfoMetadata(opts.UserDefined)
return minio.FromMinioClientObjectInfo(bucket, oi), nil
}
// CopyObject copies an object from source bucket to a destination bucket.
func (l *s3Objects) CopyObject(ctx context.Context, srcBucket string, srcObject string, dstBucket string, dstObject string, srcInfo minio.ObjectInfo, srcOpts, dstOpts minio.ObjectOptions) (objInfo minio.ObjectInfo, err error) {
if srcOpts.CheckCopyPrecondFn != nil && srcOpts.CheckCopyPrecondFn(srcInfo, "") {
return minio.ObjectInfo{}, minio.PreConditionFailed{}
}
// Set this header such that following CopyObject() always sets the right metadata on the destination.
// metadata input is already a trickled down value from interpreting x-amz-metadata-directive at
// handler layer. So what we have right now is supposed to be applied on the destination object anyways.
// So preserve it by adding "REPLACE" directive to save all the metadata set by CopyObject API.
srcInfo.UserDefined["x-amz-metadata-directive"] = "REPLACE"
srcInfo.UserDefined["x-amz-copy-source-if-match"] = srcInfo.ETag
header := make(http.Header)
if srcOpts.ServerSideEncryption != nil {
encrypt.SSECopy(srcOpts.ServerSideEncryption).Marshal(header)
}
if dstOpts.ServerSideEncryption != nil {
dstOpts.ServerSideEncryption.Marshal(header)
}
for k, v := range header {
srcInfo.UserDefined[k] = v[0]
}
if _, err = l.Client.CopyObject(srcBucket, srcObject, dstBucket, dstObject, srcInfo.UserDefined); err != nil {
return objInfo, minio.ErrorRespToObjectError(err, srcBucket, srcObject)
}
return l.GetObjectInfo(ctx, dstBucket, dstObject, dstOpts)
}
// DeleteObject deletes a blob in bucket
func (l *s3Objects) DeleteObject(ctx context.Context, bucket string, object string) error {
err := l.Client.RemoveObject(bucket, object)
if err != nil {
return minio.ErrorRespToObjectError(err, bucket, object)
}
return nil
}
func (l *s3Objects) DeleteObjects(ctx context.Context, bucket string, objects []string) ([]error, error) {
errs := make([]error, len(objects))
for idx, object := range objects {
errs[idx] = l.DeleteObject(ctx, bucket, object)
}
return errs, nil
}
// ListMultipartUploads lists all multipart uploads.
func (l *s3Objects) ListMultipartUploads(ctx context.Context, bucket string, prefix string, keyMarker string, uploadIDMarker string, delimiter string, maxUploads int) (lmi minio.ListMultipartsInfo, e error) {
result, err := l.Client.ListMultipartUploads(bucket, prefix, keyMarker, uploadIDMarker, delimiter, maxUploads)
if err != nil {
return lmi, err
}
return minio.FromMinioClientListMultipartsInfo(result), nil
}
// NewMultipartUpload upload object in multiple parts
func (l *s3Objects) NewMultipartUpload(ctx context.Context, bucket string, object string, o minio.ObjectOptions) (uploadID string, err error) {
var tagMap map[string]string
if tagStr, ok := o.UserDefined[xhttp.AmzObjectTagging]; ok {
tagObj, err := tags.Parse(tagStr, true)
if err != nil {
return uploadID, minio.ErrorRespToObjectError(err, bucket, object)
}
tagMap = tagObj.ToMap()
delete(o.UserDefined, xhttp.AmzObjectTagging)
}
// Create PutObject options
opts := miniogo.PutObjectOptions{
UserMetadata: o.UserDefined,
ServerSideEncryption: o.ServerSideEncryption,
UserTags: tagMap,
}
uploadID, err = l.Client.NewMultipartUpload(bucket, object, opts)
if err != nil {
return uploadID, minio.ErrorRespToObjectError(err, bucket, object)
}
return uploadID, nil
}
// PutObjectPart puts a part of object in bucket
func (l *s3Objects) PutObjectPart(ctx context.Context, bucket string, object string, uploadID string, partID int, r *minio.PutObjReader, opts minio.ObjectOptions) (pi minio.PartInfo, e error) {
data := r.Reader
info, err := l.Client.PutObjectPart(bucket, object, uploadID, partID, data, data.Size(), data.MD5Base64String(), data.SHA256HexString(), opts.ServerSideEncryption)
if err != nil {
return pi, minio.ErrorRespToObjectError(err, bucket, object)
}
return minio.FromMinioClientObjectPart(info), nil
}
// CopyObjectPart creates a part in a multipart upload by copying
// existing object or a part of it.
func (l *s3Objects) CopyObjectPart(ctx context.Context, srcBucket, srcObject, destBucket, destObject, uploadID string,
partID int, startOffset, length int64, srcInfo minio.ObjectInfo, srcOpts, dstOpts minio.ObjectOptions) (p minio.PartInfo, err error) {
if srcOpts.CheckCopyPrecondFn != nil && srcOpts.CheckCopyPrecondFn(srcInfo, "") {
return minio.PartInfo{}, minio.PreConditionFailed{}
}
srcInfo.UserDefined = map[string]string{
"x-amz-copy-source-if-match": srcInfo.ETag,
}
header := make(http.Header)
if srcOpts.ServerSideEncryption != nil {
encrypt.SSECopy(srcOpts.ServerSideEncryption).Marshal(header)
}
if dstOpts.ServerSideEncryption != nil {
dstOpts.ServerSideEncryption.Marshal(header)
}
for k, v := range header {
srcInfo.UserDefined[k] = v[0]
}
completePart, err := l.Client.CopyObjectPart(srcBucket, srcObject, destBucket, destObject,
uploadID, partID, startOffset, length, srcInfo.UserDefined)
if err != nil {
return p, minio.ErrorRespToObjectError(err, srcBucket, srcObject)
}
p.PartNumber = completePart.PartNumber
p.ETag = completePart.ETag
return p, nil
}
// GetMultipartInfo returns multipart info of the uploadId of the object
func (l *s3Objects) GetMultipartInfo(ctx context.Context, bucket, object, uploadID string, opts minio.ObjectOptions) (result minio.MultipartInfo, err error) {
result.Bucket = bucket
result.Object = object
result.UploadID = uploadID
return result, nil
}
// ListObjectParts returns all object parts for specified object in specified bucket
func (l *s3Objects) ListObjectParts(ctx context.Context, bucket string, object string, uploadID string, partNumberMarker int, maxParts int, opts minio.ObjectOptions) (lpi minio.ListPartsInfo, e error) {
result, err := l.Client.ListObjectParts(bucket, object, uploadID, partNumberMarker, maxParts)
if err != nil {
return lpi, err
}
lpi = minio.FromMinioClientListPartsInfo(result)
if lpi.IsTruncated && maxParts > len(lpi.Parts) {
partNumberMarker = lpi.NextPartNumberMarker
for {
result, err = l.Client.ListObjectParts(bucket, object, uploadID, partNumberMarker, maxParts)
if err != nil {
return lpi, err
}
nlpi := minio.FromMinioClientListPartsInfo(result)
partNumberMarker = nlpi.NextPartNumberMarker
lpi.Parts = append(lpi.Parts, nlpi.Parts...)
if !nlpi.IsTruncated {
break
}
}
}
return lpi, nil
}
// AbortMultipartUpload aborts a ongoing multipart upload
func (l *s3Objects) AbortMultipartUpload(ctx context.Context, bucket string, object string, uploadID string) error {
err := l.Client.AbortMultipartUpload(bucket, object, uploadID)
return minio.ErrorRespToObjectError(err, bucket, object)
}
// CompleteMultipartUpload completes ongoing multipart upload and finalizes object
func (l *s3Objects) CompleteMultipartUpload(ctx context.Context, bucket string, object string, uploadID string, uploadedParts []minio.CompletePart, opts minio.ObjectOptions) (oi minio.ObjectInfo, e error) {
etag, err := l.Client.CompleteMultipartUpload(bucket, object, uploadID, minio.ToMinioClientCompleteParts(uploadedParts))
if err != nil {
return oi, minio.ErrorRespToObjectError(err, bucket, object)
}
return minio.ObjectInfo{Bucket: bucket, Name: object, ETag: strings.Trim(etag, "\"")}, nil
}
// SetBucketPolicy sets policy on bucket
func (l *s3Objects) SetBucketPolicy(ctx context.Context, bucket string, bucketPolicy *policy.Policy) error {
data, err := json.Marshal(bucketPolicy)
if err != nil {
// This should not happen.
logger.LogIf(ctx, err)
return minio.ErrorRespToObjectError(err, bucket)
}
if err := l.Client.SetBucketPolicy(bucket, string(data)); err != nil {
return minio.ErrorRespToObjectError(err, bucket)
}
return nil
}
// GetBucketPolicy will get policy on bucket
func (l *s3Objects) GetBucketPolicy(ctx context.Context, bucket string) (*policy.Policy, error) {
data, err := l.Client.GetBucketPolicy(bucket)
if err != nil {
return nil, minio.ErrorRespToObjectError(err, bucket)
}
bucketPolicy, err := policy.ParseConfig(strings.NewReader(data), bucket)
return bucketPolicy, minio.ErrorRespToObjectError(err, bucket)
}
// DeleteBucketPolicy deletes all policies on bucket
func (l *s3Objects) DeleteBucketPolicy(ctx context.Context, bucket string) error {
if err := l.Client.SetBucketPolicy(bucket, ""); err != nil {
return minio.ErrorRespToObjectError(err, bucket, "")
}
return nil
}
// GetObjectTags gets the tags set on the object
func (l *s3Objects) GetObjectTags(ctx context.Context, bucket string, object string) (*tags.Tags, error) {
var err error
var tagObj *tags.Tags
var tagStr string
var opts minio.ObjectOptions
if _, err = l.GetObjectInfo(ctx, bucket, object, opts); err != nil {
return nil, minio.ErrorRespToObjectError(err, bucket, object)
}
if tagStr, err = l.Client.GetObjectTagging(bucket, object); err != nil {
return nil, minio.ErrorRespToObjectError(err, bucket, object)
}
if tagObj, err = tags.ParseObjectXML(strings.NewReader(tagStr)); err != nil {
return nil, minio.ErrorRespToObjectError(err, bucket, object)
}
return tagObj, err
}
// PutObjectTags attaches the tags to the object
func (l *s3Objects) PutObjectTags(ctx context.Context, bucket, object string, tagStr string) error {
tagObj, err := tags.Parse(tagStr, true)
if err != nil {
return minio.ErrorRespToObjectError(err, bucket, object)
}
if err = l.Client.PutObjectTagging(bucket, object, tagObj.ToMap()); err != nil {
return minio.ErrorRespToObjectError(err, bucket, object)
}
return nil
}
// DeleteObjectTags removes the tags attached to the object
func (l *s3Objects) DeleteObjectTags(ctx context.Context, bucket, object string) error {
if err := l.Client.RemoveObjectTagging(bucket, object); err != nil {
return minio.ErrorRespToObjectError(err, bucket, object)
}
return nil
}
// IsCompressionSupported returns whether compression is applicable for this layer.
func (l *s3Objects) IsCompressionSupported() bool {
return false
}
// IsEncryptionSupported returns whether server side encryption is implemented for this layer.
func (l *s3Objects) IsEncryptionSupported() bool {
return minio.GlobalKMS != nil || len(minio.GlobalGatewaySSE) > 0
}
// IsReady returns whether the layer is ready to take requests.
func (l *s3Objects) IsReady(ctx context.Context) bool {
return minio.IsBackendOnline(ctx, l.HTTPClient, l.Client.EndpointURL().String())
}
func (l *s3Objects) IsTaggingSupported() bool {
return true
}
| harshavardhana/minio | cmd/gateway/s3/gateway-s3.go | GO | apache-2.0 | 26,308 |
module.exports = function (grunt) {
// Project configuration.
grunt.initConfig({
//Read the package.json (optional)
pkg: grunt.file.readJSON('package.json'),
// Metadata.
meta: {
basePath: './',
srcPath: './src/',
deployPath: './bin/',
unittestsPath : "./unittests/"
},
banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
'* Copyright (c) <%= grunt.template.today("yyyy") %> ',
tsd: {
refresh: {
options: {
// execute a command
command: 'reinstall',
//optional: always get from HEAD
latest: true,
// optional: specify config file
config: '<%= meta.basePath %>/tsd.json',
// experimental: options to pass to tsd.API
opts: {
// props from tsd.Options
}
}
}
},
typescript: {
base: {
src: ['<%= meta.srcPath %>/*.ts'],
dest: '<%= meta.deployPath %>/Knockout.WinJS.js',
options: {
target: 'es5', //or es3
basePath: '.',
sourceMap: true,
declaration: true
}
},
observableTests: {
src: ['<%= meta.srcPath %>/*.ts', '<%= meta.unittestsPath %>/observableTests.ts'],
dest: '<%= meta.deployPath %>/unittests/observableTests.js',
options: {
target: 'es5', //or es3
basePath: '.',
sourceMap: true,
declaration: false
}
},
defaultBindTests: {
src: ['<%= meta.srcPath %>/*.ts', '<%= meta.unittestsPath %>/defaultBindTests.ts'],
dest: '<%= meta.deployPath %>/unittests/defaultBindTests.js',
options: {
target: 'es5', //or es3
basePath: '.',
sourceMap: true,
declaration: false
}
}
},
uglify: {
my_target: {
files: {
'<%= meta.deployPath %>/Knockout.WinJS.min.js': ['<%= meta.deployPath %>/Knockout.WinJS.js']
}
}
},
copy: {
tests: {
files: [
// includes files within path
{ expand: true, src: ['<%= meta.unittestsPath %>/*.html'], dest: '<%= meta.deployPath %>/', filter: 'isFile' },
]
}
}
//concat: {
// options: {
// stripBanners: true
// },
// dist: {
// src: ['<%= meta.srcPath %>/Knockout.WinJS.js', '<%= meta.srcPath %>/defaultBind.js'],
// dest: '<%= meta.deployPath %>/Knockout.WinJS.js'
// }
//}
});
grunt.loadNpmTasks('grunt-tsd');
grunt.loadNpmTasks('grunt-typescript');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-copy');
// Default task
grunt.registerTask('default', ['tsd', 'typescript', 'uglify', 'copy']);
}; | wildcatsoft/Knockout.WinJS | gruntfile.js | JavaScript | apache-2.0 | 3,484 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-b10
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.06.13 at 03:17:43 PM CST
//
package org.ovirt.engine.api.model;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for Feature complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Feature">
* <complexContent>
* <extension base="{}BaseResource">
* <sequence>
* <element ref="{}transparent_hugepages" minOccurs="0"/>
* <element ref="{}gluster_volumes" minOccurs="0"/>
* <element ref="{}vm_device_types" minOccurs="0"/>
* <element ref="{}storage_types" minOccurs="0"/>
* <element ref="{}storage_domain" minOccurs="0"/>
* <element ref="{}nic" minOccurs="0"/>
* <element ref="{}api" minOccurs="0"/>
* <element ref="{}host" minOccurs="0"/>
* <element ref="{}url" minOccurs="0"/>
* <element ref="{}headers" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Feature", propOrder = {
"transparentHugepages",
"glusterVolumes",
"vmDeviceTypes",
"storageTypes",
"storageDomain",
"nic",
"api",
"host",
"url",
"headers"
})
public class Feature
extends BaseResource
{
@XmlElement(name = "transparent_hugepages")
protected TransparentHugePages transparentHugepages;
@XmlElement(name = "gluster_volumes")
protected GlusterVolumes glusterVolumes;
@XmlElement(name = "vm_device_types")
protected VmDeviceTypes vmDeviceTypes;
@XmlElement(name = "storage_types")
protected StorageTypes storageTypes;
@XmlElement(name = "storage_domain")
protected StorageDomain storageDomain;
protected NIC nic;
protected API api;
protected Host host;
protected Url url;
protected Headers headers;
/**
* Gets the value of the transparentHugepages property.
*
* @return
* possible object is
* {@link TransparentHugePages }
*
*/
public TransparentHugePages getTransparentHugepages() {
return transparentHugepages;
}
/**
* Sets the value of the transparentHugepages property.
*
* @param value
* allowed object is
* {@link TransparentHugePages }
*
*/
public void setTransparentHugepages(TransparentHugePages value) {
this.transparentHugepages = value;
}
public boolean isSetTransparentHugepages() {
return (this.transparentHugepages!= null);
}
/**
* Gets the value of the glusterVolumes property.
*
* @return
* possible object is
* {@link GlusterVolumes }
*
*/
public GlusterVolumes getGlusterVolumes() {
return glusterVolumes;
}
/**
* Sets the value of the glusterVolumes property.
*
* @param value
* allowed object is
* {@link GlusterVolumes }
*
*/
public void setGlusterVolumes(GlusterVolumes value) {
this.glusterVolumes = value;
}
public boolean isSetGlusterVolumes() {
return (this.glusterVolumes!= null);
}
/**
* Gets the value of the vmDeviceTypes property.
*
* @return
* possible object is
* {@link VmDeviceTypes }
*
*/
public VmDeviceTypes getVmDeviceTypes() {
return vmDeviceTypes;
}
/**
* Sets the value of the vmDeviceTypes property.
*
* @param value
* allowed object is
* {@link VmDeviceTypes }
*
*/
public void setVmDeviceTypes(VmDeviceTypes value) {
this.vmDeviceTypes = value;
}
public boolean isSetVmDeviceTypes() {
return (this.vmDeviceTypes!= null);
}
/**
* Gets the value of the storageTypes property.
*
* @return
* possible object is
* {@link StorageTypes }
*
*/
public StorageTypes getStorageTypes() {
return storageTypes;
}
/**
* Sets the value of the storageTypes property.
*
* @param value
* allowed object is
* {@link StorageTypes }
*
*/
public void setStorageTypes(StorageTypes value) {
this.storageTypes = value;
}
public boolean isSetStorageTypes() {
return (this.storageTypes!= null);
}
/**
* Gets the value of the storageDomain property.
*
* @return
* possible object is
* {@link StorageDomain }
*
*/
public StorageDomain getStorageDomain() {
return storageDomain;
}
/**
* Sets the value of the storageDomain property.
*
* @param value
* allowed object is
* {@link StorageDomain }
*
*/
public void setStorageDomain(StorageDomain value) {
this.storageDomain = value;
}
public boolean isSetStorageDomain() {
return (this.storageDomain!= null);
}
/**
* Gets the value of the nic property.
*
* @return
* possible object is
* {@link NIC }
*
*/
public NIC getNic() {
return nic;
}
/**
* Sets the value of the nic property.
*
* @param value
* allowed object is
* {@link NIC }
*
*/
public void setNic(NIC value) {
this.nic = value;
}
public boolean isSetNic() {
return (this.nic!= null);
}
/**
* Gets the value of the api property.
*
* @return
* possible object is
* {@link API }
*
*/
public API getApi() {
return api;
}
/**
* Sets the value of the api property.
*
* @param value
* allowed object is
* {@link API }
*
*/
public void setApi(API value) {
this.api = value;
}
public boolean isSetApi() {
return (this.api!= null);
}
/**
* Gets the value of the host property.
*
* @return
* possible object is
* {@link Host }
*
*/
public Host getHost() {
return host;
}
/**
* Sets the value of the host property.
*
* @param value
* allowed object is
* {@link Host }
*
*/
public void setHost(Host value) {
this.host = value;
}
public boolean isSetHost() {
return (this.host!= null);
}
/**
* Gets the value of the url property.
*
* @return
* possible object is
* {@link Url }
*
*/
public Url getUrl() {
return url;
}
/**
* Sets the value of the url property.
*
* @param value
* allowed object is
* {@link Url }
*
*/
public void setUrl(Url value) {
this.url = value;
}
public boolean isSetUrl() {
return (this.url!= null);
}
/**
* Gets the value of the headers property.
*
* @return
* possible object is
* {@link Headers }
*
*/
public Headers getHeaders() {
return headers;
}
/**
* Sets the value of the headers property.
*
* @param value
* allowed object is
* {@link Headers }
*
*/
public void setHeaders(Headers value) {
this.headers = value;
}
public boolean isSetHeaders() {
return (this.headers!= null);
}
}
| phoenixsbk/kvmmgr | backend/manager/modules/restapi/interface/definition/xjc/org/ovirt/engine/api/model/Feature.java | Java | apache-2.0 | 8,468 |
# Copyright (c) 2014 Mirantis, 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.
from six.moves import range
from murano.dsl import helpers
class Object(object):
def __init__(self, __name, **kwargs):
self.data = {
'?': {
'type': __name,
'id': helpers.generate_id()
}
}
self.data.update(kwargs)
@property
def id(self):
return self.data['?']['id']
@property
def type_name(self):
return self.data['?']['type']
class Attribute(object):
def __init__(self, obj, key, value):
self._value = value
self._key = key
self._obj = obj
@property
def obj(self):
return self._obj
@property
def key(self):
return self._key
@property
def value(self):
return self._value
class Ref(object):
def __init__(self, obj):
self._id = obj.id
@property
def id(self):
return self._id
def build_model(root):
if isinstance(root, dict):
for key, value in root.items():
root[key] = build_model(value)
elif isinstance(root, list):
for i in range(len(root)):
root[i] = build_model(root[i])
elif isinstance(root, Object):
return build_model(root.data)
elif isinstance(root, Ref):
return root.id
elif isinstance(root, Attribute):
return [root.obj.id, root.obj.type_name, root.key, root.value]
return root
| olivierlemasle/murano | murano/tests/unit/dsl/foundation/object_model.py | Python | apache-2.0 | 2,019 |
/**
* 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 org.apache.hadoop.hive.ql.parse;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.hadoop.hive.common.type.HiveChar;
import org.apache.hadoop.hive.common.type.HiveDecimal;
import org.apache.hadoop.hive.common.type.HiveIntervalDayTime;
import org.apache.hadoop.hive.common.type.HiveIntervalYearMonth;
import org.apache.hadoop.hive.ql.ErrorMsg;
import org.apache.hadoop.hive.ql.exec.ColumnInfo;
import org.apache.hadoop.hive.ql.exec.FunctionInfo;
import org.apache.hadoop.hive.ql.exec.FunctionRegistry;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException;
import org.apache.hadoop.hive.ql.lib.DefaultGraphWalker;
import org.apache.hadoop.hive.ql.lib.DefaultRuleDispatcher;
import org.apache.hadoop.hive.ql.lib.Dispatcher;
import org.apache.hadoop.hive.ql.lib.GraphWalker;
import org.apache.hadoop.hive.ql.lib.Node;
import org.apache.hadoop.hive.ql.lib.NodeProcessor;
import org.apache.hadoop.hive.ql.lib.NodeProcessorCtx;
import org.apache.hadoop.hive.ql.lib.Rule;
import org.apache.hadoop.hive.ql.lib.RuleRegExp;
import org.apache.hadoop.hive.ql.optimizer.ConstantPropagateProcFactory;
import org.apache.hadoop.hive.ql.plan.ExprNodeColumnDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeColumnListDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeConstantDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeDescUtils;
import org.apache.hadoop.hive.ql.plan.ExprNodeFieldDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeGenericFuncDesc;
import org.apache.hadoop.hive.ql.udf.SettableUDF;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFBaseCompare;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFNvl;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPAnd;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPEqual;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPNot;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPOr;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFWhen;
import org.apache.hadoop.hive.serde.serdeConstants;
import org.apache.hadoop.hive.serde2.objectinspector.ConstantObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorUtils;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.typeinfo.CharTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.DecimalTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.ListTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.MapTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.StructTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils;
import org.apache.hadoop.hive.serde2.typeinfo.VarcharTypeInfo;
import org.apache.hadoop.io.NullWritable;
import org.apache.hive.common.util.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
/**
* The Factory for creating typecheck processors. The typecheck processors are
* used to processes the syntax trees for expressions and convert them into
* expression Node Descriptor trees. They also introduce the correct conversion
* functions to do proper implicit conversion.
*/
public class TypeCheckProcFactory {
protected static final Logger LOG = LoggerFactory.getLogger(TypeCheckProcFactory.class
.getName());
protected TypeCheckProcFactory() {
// prevent instantiation
}
/**
* Function to do groupby subexpression elimination. This is called by all the
* processors initially. As an example, consider the query select a+b,
* count(1) from T group by a+b; Then a+b is already precomputed in the group
* by operators key, so we substitute a+b in the select list with the internal
* column name of the a+b expression that appears in the in input row
* resolver.
*
* @param nd
* The node that is being inspected.
* @param procCtx
* The processor context.
*
* @return exprNodeColumnDesc.
*/
public static ExprNodeDesc processGByExpr(Node nd, Object procCtx)
throws SemanticException {
// We recursively create the exprNodeDesc. Base cases: when we encounter
// a column ref, we convert that into an exprNodeColumnDesc; when we
// encounter
// a constant, we convert that into an exprNodeConstantDesc. For others we
// just
// build the exprNodeFuncDesc with recursively built children.
ASTNode expr = (ASTNode) nd;
TypeCheckCtx ctx = (TypeCheckCtx) procCtx;
if (!ctx.isUseCaching()) {
return null;
}
RowResolver input = ctx.getInputRR();
ExprNodeDesc desc = null;
if ((ctx == null) || (input == null) || (!ctx.getAllowGBExprElimination())) {
return null;
}
// If the current subExpression is pre-calculated, as in Group-By etc.
ColumnInfo colInfo = input.getExpression(expr);
if (colInfo != null) {
desc = new ExprNodeColumnDesc(colInfo);
ASTNode source = input.getExpressionSource(expr);
if (source != null) {
ctx.getUnparseTranslator().addCopyTranslation(expr, source);
}
return desc;
}
return desc;
}
public static Map<ASTNode, ExprNodeDesc> genExprNode(ASTNode expr, TypeCheckCtx tcCtx)
throws SemanticException {
return genExprNode(expr, tcCtx, new TypeCheckProcFactory());
}
protected static Map<ASTNode, ExprNodeDesc> genExprNode(ASTNode expr,
TypeCheckCtx tcCtx, TypeCheckProcFactory tf) throws SemanticException {
// Create the walker, the rules dispatcher and the context.
// create a walker which walks the tree in a DFS manner while maintaining
// the operator stack. The dispatcher
// generates the plan from the operator tree
Map<Rule, NodeProcessor> opRules = new LinkedHashMap<Rule, NodeProcessor>();
opRules.put(new RuleRegExp("R1", HiveParser.TOK_NULL + "%"),
tf.getNullExprProcessor());
opRules.put(new RuleRegExp("R2", HiveParser.Number + "%|" +
HiveParser.TinyintLiteral + "%|" +
HiveParser.SmallintLiteral + "%|" +
HiveParser.BigintLiteral + "%|" +
HiveParser.DecimalLiteral + "%"),
tf.getNumExprProcessor());
opRules
.put(new RuleRegExp("R3", HiveParser.Identifier + "%|"
+ HiveParser.StringLiteral + "%|" + HiveParser.TOK_CHARSETLITERAL + "%|"
+ HiveParser.TOK_STRINGLITERALSEQUENCE + "%|"
+ "%|" + HiveParser.KW_IF + "%|" + HiveParser.KW_CASE + "%|"
+ HiveParser.KW_WHEN + "%|" + HiveParser.KW_IN + "%|"
+ HiveParser.KW_ARRAY + "%|" + HiveParser.KW_MAP + "%|"
+ HiveParser.KW_STRUCT + "%|" + HiveParser.KW_EXISTS + "%|"
+ HiveParser.TOK_SUBQUERY_OP_NOTIN + "%"),
tf.getStrExprProcessor());
opRules.put(new RuleRegExp("R4", HiveParser.KW_TRUE + "%|"
+ HiveParser.KW_FALSE + "%"), tf.getBoolExprProcessor());
opRules.put(new RuleRegExp("R5", HiveParser.TOK_DATELITERAL + "%|"
+ HiveParser.TOK_TIMESTAMPLITERAL + "%"), tf.getDateTimeExprProcessor());
opRules.put(new RuleRegExp("R6",
HiveParser.TOK_INTERVAL_YEAR_MONTH_LITERAL + "%|"
+ HiveParser.TOK_INTERVAL_DAY_TIME_LITERAL + "%|"
+ HiveParser.TOK_INTERVAL_YEAR_LITERAL + "%|"
+ HiveParser.TOK_INTERVAL_MONTH_LITERAL + "%|"
+ HiveParser.TOK_INTERVAL_DAY_LITERAL + "%|"
+ HiveParser.TOK_INTERVAL_HOUR_LITERAL + "%|"
+ HiveParser.TOK_INTERVAL_MINUTE_LITERAL + "%|"
+ HiveParser.TOK_INTERVAL_SECOND_LITERAL + "%"), tf.getIntervalExprProcessor());
opRules.put(new RuleRegExp("R7", HiveParser.TOK_TABLE_OR_COL + "%"),
tf.getColumnExprProcessor());
opRules.put(new RuleRegExp("R8", HiveParser.TOK_SUBQUERY_OP + "%"),
tf.getSubQueryExprProcessor());
// The dispatcher fires the processor corresponding to the closest matching
// rule and passes the context along
Dispatcher disp = new DefaultRuleDispatcher(tf.getDefaultExprProcessor(),
opRules, tcCtx);
GraphWalker ogw = new DefaultGraphWalker(disp);
// Create a list of top nodes
ArrayList<Node> topNodes = Lists.<Node>newArrayList(expr);
HashMap<Node, Object> nodeOutputs = new LinkedHashMap<Node, Object>();
ogw.startWalking(topNodes, nodeOutputs);
return convert(nodeOutputs);
}
// temporary type-safe casting
private static Map<ASTNode, ExprNodeDesc> convert(Map<Node, Object> outputs) {
Map<ASTNode, ExprNodeDesc> converted = new LinkedHashMap<ASTNode, ExprNodeDesc>();
for (Map.Entry<Node, Object> entry : outputs.entrySet()) {
if (entry.getKey() instanceof ASTNode &&
(entry.getValue() == null || entry.getValue() instanceof ExprNodeDesc)) {
converted.put((ASTNode)entry.getKey(), (ExprNodeDesc)entry.getValue());
} else {
LOG.warn("Invalid type entry " + entry);
}
}
return converted;
}
/**
* Processor for processing NULL expression.
*/
public static class NullExprProcessor implements NodeProcessor {
@Override
public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
Object... nodeOutputs) throws SemanticException {
TypeCheckCtx ctx = (TypeCheckCtx) procCtx;
if (ctx.getError() != null) {
return null;
}
ExprNodeDesc desc = TypeCheckProcFactory.processGByExpr(nd, procCtx);
if (desc != null) {
return desc;
}
return new ExprNodeConstantDesc(TypeInfoFactory.getPrimitiveTypeInfoFromPrimitiveWritable(NullWritable.class), null);
}
}
/**
* Factory method to get NullExprProcessor.
*
* @return NullExprProcessor.
*/
public NullExprProcessor getNullExprProcessor() {
return new NullExprProcessor();
}
/**
* Processor for processing numeric constants.
*/
public static class NumExprProcessor implements NodeProcessor {
@Override
public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
Object... nodeOutputs) throws SemanticException {
TypeCheckCtx ctx = (TypeCheckCtx) procCtx;
if (ctx.getError() != null) {
return null;
}
ExprNodeDesc desc = TypeCheckProcFactory.processGByExpr(nd, procCtx);
if (desc != null) {
return desc;
}
Number v = null;
ASTNode expr = (ASTNode) nd;
// The expression can be any one of Double, Long and Integer. We
// try to parse the expression in that order to ensure that the
// most specific type is used for conversion.
try {
if (expr.getText().endsWith("L")) {
// Literal bigint.
v = Long.valueOf(expr.getText().substring(
0, expr.getText().length() - 1));
} else if (expr.getText().endsWith("S")) {
// Literal smallint.
v = Short.valueOf(expr.getText().substring(
0, expr.getText().length() - 1));
} else if (expr.getText().endsWith("Y")) {
// Literal tinyint.
v = Byte.valueOf(expr.getText().substring(
0, expr.getText().length() - 1));
} else if (expr.getText().endsWith("BD")) {
// Literal decimal
String strVal = expr.getText().substring(0, expr.getText().length() - 2);
HiveDecimal hd = HiveDecimal.create(strVal);
int prec = 1;
int scale = 0;
if (hd != null) {
prec = hd.precision();
scale = hd.scale();
}
DecimalTypeInfo typeInfo = TypeInfoFactory.getDecimalTypeInfo(prec, scale);
return new ExprNodeConstantDesc(typeInfo, hd);
} else {
v = Double.valueOf(expr.getText());
v = Long.valueOf(expr.getText());
v = Integer.valueOf(expr.getText());
}
} catch (NumberFormatException e) {
// do nothing here, we will throw an exception in the following block
}
if (v == null) {
throw new SemanticException(ErrorMsg.INVALID_NUMERICAL_CONSTANT
.getMsg(expr));
}
return new ExprNodeConstantDesc(v);
}
}
/**
* Factory method to get NumExprProcessor.
*
* @return NumExprProcessor.
*/
public NumExprProcessor getNumExprProcessor() {
return new NumExprProcessor();
}
/**
* Processor for processing string constants.
*/
public static class StrExprProcessor implements NodeProcessor {
@Override
public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
Object... nodeOutputs) throws SemanticException {
TypeCheckCtx ctx = (TypeCheckCtx) procCtx;
if (ctx.getError() != null) {
return null;
}
ExprNodeDesc desc = TypeCheckProcFactory.processGByExpr(nd, procCtx);
if (desc != null) {
return desc;
}
ASTNode expr = (ASTNode) nd;
String str = null;
switch (expr.getToken().getType()) {
case HiveParser.StringLiteral:
str = BaseSemanticAnalyzer.unescapeSQLString(expr.getText());
break;
case HiveParser.TOK_STRINGLITERALSEQUENCE:
StringBuilder sb = new StringBuilder();
for (Node n : expr.getChildren()) {
sb.append(
BaseSemanticAnalyzer.unescapeSQLString(((ASTNode)n).getText()));
}
str = sb.toString();
break;
case HiveParser.TOK_CHARSETLITERAL:
str = BaseSemanticAnalyzer.charSetString(expr.getChild(0).getText(),
expr.getChild(1).getText());
break;
default:
// HiveParser.identifier | HiveParse.KW_IF | HiveParse.KW_LEFT |
// HiveParse.KW_RIGHT
str = BaseSemanticAnalyzer.unescapeIdentifier(expr.getText().toLowerCase());
break;
}
return new ExprNodeConstantDesc(TypeInfoFactory.stringTypeInfo, str);
}
}
/**
* Factory method to get StrExprProcessor.
*
* @return StrExprProcessor.
*/
public StrExprProcessor getStrExprProcessor() {
return new StrExprProcessor();
}
/**
* Processor for boolean constants.
*/
public static class BoolExprProcessor implements NodeProcessor {
@Override
public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
Object... nodeOutputs) throws SemanticException {
TypeCheckCtx ctx = (TypeCheckCtx) procCtx;
if (ctx.getError() != null) {
return null;
}
ExprNodeDesc desc = TypeCheckProcFactory.processGByExpr(nd, procCtx);
if (desc != null) {
return desc;
}
ASTNode expr = (ASTNode) nd;
Boolean bool = null;
switch (expr.getToken().getType()) {
case HiveParser.KW_TRUE:
bool = Boolean.TRUE;
break;
case HiveParser.KW_FALSE:
bool = Boolean.FALSE;
break;
default:
assert false;
}
return new ExprNodeConstantDesc(TypeInfoFactory.booleanTypeInfo, bool);
}
}
/**
* Factory method to get BoolExprProcessor.
*
* @return BoolExprProcessor.
*/
public BoolExprProcessor getBoolExprProcessor() {
return new BoolExprProcessor();
}
/**
* Processor for date constants.
*/
public static class DateTimeExprProcessor implements NodeProcessor {
@Override
public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
Object... nodeOutputs) throws SemanticException {
TypeCheckCtx ctx = (TypeCheckCtx) procCtx;
if (ctx.getError() != null) {
return null;
}
ExprNodeDesc desc = TypeCheckProcFactory.processGByExpr(nd, procCtx);
if (desc != null) {
return desc;
}
ASTNode expr = (ASTNode) nd;
String timeString = BaseSemanticAnalyzer.stripQuotes(expr.getText());
// Get the string value and convert to a Date value.
try {
// todo replace below with joda-time, which supports timezone
if (expr.getType() == HiveParser.TOK_DATELITERAL) {
PrimitiveTypeInfo typeInfo = TypeInfoFactory.dateTypeInfo;
return new ExprNodeConstantDesc(typeInfo,
Date.valueOf(timeString));
}
if (expr.getType() == HiveParser.TOK_TIMESTAMPLITERAL) {
return new ExprNodeConstantDesc(TypeInfoFactory.timestampTypeInfo,
Timestamp.valueOf(timeString));
}
throw new IllegalArgumentException("Invalid time literal type " + expr.getType());
} catch (Exception err) {
throw new SemanticException(
"Unable to convert time literal '" + timeString + "' to time value.", err);
}
}
}
/**
* Factory method to get DateExprProcessor.
*
* @return DateExprProcessor.
*/
public DateTimeExprProcessor getDateTimeExprProcessor() {
return new DateTimeExprProcessor();
}
/**
* Processor for interval constants.
*/
public static class IntervalExprProcessor implements NodeProcessor {
private static final BigDecimal NANOS_PER_SEC_BD = new BigDecimal(DateUtils.NANOS_PER_SEC);
@Override
public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
Object... nodeOutputs) throws SemanticException {
TypeCheckCtx ctx = (TypeCheckCtx) procCtx;
if (ctx.getError() != null) {
return null;
}
ExprNodeDesc desc = TypeCheckProcFactory.processGByExpr(nd, procCtx);
if (desc != null) {
return desc;
}
ASTNode expr = (ASTNode) nd;
String intervalString = BaseSemanticAnalyzer.stripQuotes(expr.getText());
// Get the string value and convert to a Interval value.
try {
switch (expr.getType()) {
case HiveParser.TOK_INTERVAL_YEAR_MONTH_LITERAL:
return new ExprNodeConstantDesc(TypeInfoFactory.intervalYearMonthTypeInfo,
HiveIntervalYearMonth.valueOf(intervalString));
case HiveParser.TOK_INTERVAL_DAY_TIME_LITERAL:
return new ExprNodeConstantDesc(TypeInfoFactory.intervalDayTimeTypeInfo,
HiveIntervalDayTime.valueOf(intervalString));
case HiveParser.TOK_INTERVAL_YEAR_LITERAL:
return new ExprNodeConstantDesc(TypeInfoFactory.intervalYearMonthTypeInfo,
new HiveIntervalYearMonth(Integer.parseInt(intervalString), 0));
case HiveParser.TOK_INTERVAL_MONTH_LITERAL:
return new ExprNodeConstantDesc(TypeInfoFactory.intervalYearMonthTypeInfo,
new HiveIntervalYearMonth(0, Integer.parseInt(intervalString)));
case HiveParser.TOK_INTERVAL_DAY_LITERAL:
return new ExprNodeConstantDesc(TypeInfoFactory.intervalDayTimeTypeInfo,
new HiveIntervalDayTime(Integer.parseInt(intervalString), 0, 0, 0, 0));
case HiveParser.TOK_INTERVAL_HOUR_LITERAL:
return new ExprNodeConstantDesc(TypeInfoFactory.intervalDayTimeTypeInfo,
new HiveIntervalDayTime(0, Integer.parseInt(intervalString), 0, 0, 0));
case HiveParser.TOK_INTERVAL_MINUTE_LITERAL:
return new ExprNodeConstantDesc(TypeInfoFactory.intervalDayTimeTypeInfo,
new HiveIntervalDayTime(0, 0, Integer.parseInt(intervalString), 0, 0));
case HiveParser.TOK_INTERVAL_SECOND_LITERAL:
BigDecimal bd = new BigDecimal(intervalString);
BigDecimal bdSeconds = new BigDecimal(bd.toBigInteger());
BigDecimal bdNanos = bd.subtract(bdSeconds);
return new ExprNodeConstantDesc(TypeInfoFactory.intervalDayTimeTypeInfo,
new HiveIntervalDayTime(0, 0, 0, bdSeconds.intValueExact(),
bdNanos.multiply(NANOS_PER_SEC_BD).intValue()));
default:
throw new IllegalArgumentException("Invalid time literal type " + expr.getType());
}
} catch (Exception err) {
throw new SemanticException(
"Unable to convert interval literal '" + intervalString + "' to interval value.", err);
}
}
}
/**
* Factory method to get IntervalExprProcessor.
*
* @return IntervalExprProcessor.
*/
public IntervalExprProcessor getIntervalExprProcessor() {
return new IntervalExprProcessor();
}
/**
* Processor for table columns.
*/
public static class ColumnExprProcessor implements NodeProcessor {
@Override
public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
Object... nodeOutputs) throws SemanticException {
TypeCheckCtx ctx = (TypeCheckCtx) procCtx;
if (ctx.getError() != null) {
return null;
}
ExprNodeDesc desc = TypeCheckProcFactory.processGByExpr(nd, procCtx);
if (desc != null) {
return desc;
}
ASTNode expr = (ASTNode) nd;
ASTNode parent = stack.size() > 1 ? (ASTNode) stack.get(stack.size() - 2) : null;
RowResolver input = ctx.getInputRR();
if (expr.getType() != HiveParser.TOK_TABLE_OR_COL) {
ctx.setError(ErrorMsg.INVALID_COLUMN.getMsg(expr), expr);
return null;
}
assert (expr.getChildCount() == 1);
String tableOrCol = BaseSemanticAnalyzer.unescapeIdentifier(expr
.getChild(0).getText());
boolean isTableAlias = input.hasTableAlias(tableOrCol);
ColumnInfo colInfo = input.get(null, tableOrCol);
if (isTableAlias) {
if (colInfo != null) {
if (parent != null && parent.getType() == HiveParser.DOT) {
// It's a table alias.
return null;
}
// It's a column.
return toExprNodeDesc(colInfo);
} else {
// It's a table alias.
// We will process that later in DOT.
return null;
}
} else {
if (colInfo == null) {
// It's not a column or a table alias.
if (input.getIsExprResolver()) {
ASTNode exprNode = expr;
if (!stack.empty()) {
ASTNode tmp = (ASTNode) stack.pop();
if (!stack.empty()) {
exprNode = (ASTNode) stack.peek();
}
stack.push(tmp);
}
ctx.setError(ErrorMsg.NON_KEY_EXPR_IN_GROUPBY.getMsg(exprNode), expr);
return null;
} else {
List<String> possibleColumnNames = input.getReferenceableColumnAliases(tableOrCol, -1);
String reason = String.format("(possible column names are: %s)",
StringUtils.join(possibleColumnNames, ", "));
ctx.setError(ErrorMsg.INVALID_TABLE_OR_COLUMN.getMsg(expr.getChild(0), reason),
expr);
LOG.debug(ErrorMsg.INVALID_TABLE_OR_COLUMN.toString() + ":"
+ input.toString());
return null;
}
} else {
// It's a column.
return toExprNodeDesc(colInfo);
}
}
}
}
private static ExprNodeDesc toExprNodeDesc(ColumnInfo colInfo) {
ObjectInspector inspector = colInfo.getObjectInspector();
if (inspector instanceof ConstantObjectInspector &&
inspector instanceof PrimitiveObjectInspector) {
PrimitiveObjectInspector poi = (PrimitiveObjectInspector) inspector;
Object constant = ((ConstantObjectInspector) inspector).getWritableConstantValue();
return new ExprNodeConstantDesc(colInfo.getType(), poi.getPrimitiveJavaObject(constant));
}
// non-constant or non-primitive constants
ExprNodeColumnDesc column = new ExprNodeColumnDesc(colInfo);
column.setSkewedCol(colInfo.isSkewedCol());
return column;
}
/**
* Factory method to get ColumnExprProcessor.
*
* @return ColumnExprProcessor.
*/
public ColumnExprProcessor getColumnExprProcessor() {
return new ColumnExprProcessor();
}
/**
* The default processor for typechecking.
*/
public static class DefaultExprProcessor implements NodeProcessor {
static HashMap<Integer, String> specialUnaryOperatorTextHashMap;
static HashMap<Integer, String> specialFunctionTextHashMap;
static HashMap<Integer, String> conversionFunctionTextHashMap;
static HashSet<Integer> windowingTokens;
static {
specialUnaryOperatorTextHashMap = new HashMap<Integer, String>();
specialUnaryOperatorTextHashMap.put(HiveParser.PLUS, "positive");
specialUnaryOperatorTextHashMap.put(HiveParser.MINUS, "negative");
specialFunctionTextHashMap = new HashMap<Integer, String>();
specialFunctionTextHashMap.put(HiveParser.TOK_ISNULL, "isnull");
specialFunctionTextHashMap.put(HiveParser.TOK_ISNOTNULL, "isnotnull");
conversionFunctionTextHashMap = new HashMap<Integer, String>();
conversionFunctionTextHashMap.put(HiveParser.TOK_BOOLEAN,
serdeConstants.BOOLEAN_TYPE_NAME);
conversionFunctionTextHashMap.put(HiveParser.TOK_TINYINT,
serdeConstants.TINYINT_TYPE_NAME);
conversionFunctionTextHashMap.put(HiveParser.TOK_SMALLINT,
serdeConstants.SMALLINT_TYPE_NAME);
conversionFunctionTextHashMap.put(HiveParser.TOK_INT,
serdeConstants.INT_TYPE_NAME);
conversionFunctionTextHashMap.put(HiveParser.TOK_BIGINT,
serdeConstants.BIGINT_TYPE_NAME);
conversionFunctionTextHashMap.put(HiveParser.TOK_FLOAT,
serdeConstants.FLOAT_TYPE_NAME);
conversionFunctionTextHashMap.put(HiveParser.TOK_DOUBLE,
serdeConstants.DOUBLE_TYPE_NAME);
conversionFunctionTextHashMap.put(HiveParser.TOK_STRING,
serdeConstants.STRING_TYPE_NAME);
conversionFunctionTextHashMap.put(HiveParser.TOK_CHAR,
serdeConstants.CHAR_TYPE_NAME);
conversionFunctionTextHashMap.put(HiveParser.TOK_VARCHAR,
serdeConstants.VARCHAR_TYPE_NAME);
conversionFunctionTextHashMap.put(HiveParser.TOK_BINARY,
serdeConstants.BINARY_TYPE_NAME);
conversionFunctionTextHashMap.put(HiveParser.TOK_DATE,
serdeConstants.DATE_TYPE_NAME);
conversionFunctionTextHashMap.put(HiveParser.TOK_TIMESTAMP,
serdeConstants.TIMESTAMP_TYPE_NAME);
conversionFunctionTextHashMap.put(HiveParser.TOK_INTERVAL_YEAR_MONTH,
serdeConstants.INTERVAL_YEAR_MONTH_TYPE_NAME);
conversionFunctionTextHashMap.put(HiveParser.TOK_INTERVAL_DAY_TIME,
serdeConstants.INTERVAL_DAY_TIME_TYPE_NAME);
conversionFunctionTextHashMap.put(HiveParser.TOK_DECIMAL,
serdeConstants.DECIMAL_TYPE_NAME);
windowingTokens = new HashSet<Integer>();
windowingTokens.add(HiveParser.KW_OVER);
windowingTokens.add(HiveParser.TOK_PARTITIONINGSPEC);
windowingTokens.add(HiveParser.TOK_DISTRIBUTEBY);
windowingTokens.add(HiveParser.TOK_SORTBY);
windowingTokens.add(HiveParser.TOK_CLUSTERBY);
windowingTokens.add(HiveParser.TOK_WINDOWSPEC);
windowingTokens.add(HiveParser.TOK_WINDOWRANGE);
windowingTokens.add(HiveParser.TOK_WINDOWVALUES);
windowingTokens.add(HiveParser.KW_UNBOUNDED);
windowingTokens.add(HiveParser.KW_PRECEDING);
windowingTokens.add(HiveParser.KW_FOLLOWING);
windowingTokens.add(HiveParser.KW_CURRENT);
windowingTokens.add(HiveParser.TOK_TABSORTCOLNAMEASC);
windowingTokens.add(HiveParser.TOK_TABSORTCOLNAMEDESC);
windowingTokens.add(HiveParser.TOK_NULLS_FIRST);
windowingTokens.add(HiveParser.TOK_NULLS_LAST);
}
protected static boolean isRedundantConversionFunction(ASTNode expr,
boolean isFunction, ArrayList<ExprNodeDesc> children) {
if (!isFunction) {
return false;
}
// conversion functions take a single parameter
if (children.size() != 1) {
return false;
}
String funcText = conversionFunctionTextHashMap.get(((ASTNode) expr
.getChild(0)).getType());
// not a conversion function
if (funcText == null) {
return false;
}
// return true when the child type and the conversion target type is the
// same
return ((PrimitiveTypeInfo) children.get(0).getTypeInfo()).getTypeName()
.equalsIgnoreCase(funcText);
}
public static String getFunctionText(ASTNode expr, boolean isFunction) {
String funcText = null;
if (!isFunction) {
// For operator, the function name is the operator text, unless it's in
// our special dictionary
if (expr.getChildCount() == 1) {
funcText = specialUnaryOperatorTextHashMap.get(expr.getType());
}
if (funcText == null) {
funcText = expr.getText();
}
} else {
// For TOK_FUNCTION, the function name is stored in the first child,
// unless it's in our
// special dictionary.
assert (expr.getChildCount() >= 1);
int funcType = ((ASTNode) expr.getChild(0)).getType();
funcText = specialFunctionTextHashMap.get(funcType);
if (funcText == null) {
funcText = conversionFunctionTextHashMap.get(funcType);
}
if (funcText == null) {
funcText = ((ASTNode) expr.getChild(0)).getText();
}
}
return BaseSemanticAnalyzer.unescapeIdentifier(funcText);
}
/**
* This function create an ExprNodeDesc for a UDF function given the
* children (arguments). It will insert implicit type conversion functions
* if necessary.
*
* @throws UDFArgumentException
*/
static ExprNodeDesc getFuncExprNodeDescWithUdfData(String udfName, TypeInfo typeInfo,
ExprNodeDesc... children) throws UDFArgumentException {
FunctionInfo fi;
try {
fi = FunctionRegistry.getFunctionInfo(udfName);
} catch (SemanticException e) {
throw new UDFArgumentException(e);
}
if (fi == null) {
throw new UDFArgumentException(udfName + " not found.");
}
GenericUDF genericUDF = fi.getGenericUDF();
if (genericUDF == null) {
throw new UDFArgumentException(udfName
+ " is an aggregation function or a table function.");
}
// Add udfData to UDF if necessary
if (typeInfo != null) {
if (genericUDF instanceof SettableUDF) {
((SettableUDF)genericUDF).setTypeInfo(typeInfo);
}
}
List<ExprNodeDesc> childrenList = new ArrayList<ExprNodeDesc>(children.length);
childrenList.addAll(Arrays.asList(children));
return ExprNodeGenericFuncDesc.newInstance(genericUDF,
childrenList);
}
public static ExprNodeDesc getFuncExprNodeDesc(String udfName,
ExprNodeDesc... children) throws UDFArgumentException {
return getFuncExprNodeDescWithUdfData(udfName, null, children);
}
protected void validateUDF(ASTNode expr, boolean isFunction, TypeCheckCtx ctx, FunctionInfo fi,
List<ExprNodeDesc> children, GenericUDF genericUDF) throws SemanticException {
// Detect UDTF's in nested SELECT, GROUP BY, etc as they aren't
// supported
if (fi.getGenericUDTF() != null) {
throw new SemanticException(ErrorMsg.UDTF_INVALID_LOCATION.getMsg());
}
// UDAF in filter condition, group-by caluse, param of funtion, etc.
if (fi.getGenericUDAFResolver() != null) {
if (isFunction) {
throw new SemanticException(ErrorMsg.UDAF_INVALID_LOCATION.getMsg((ASTNode) expr
.getChild(0)));
} else {
throw new SemanticException(ErrorMsg.UDAF_INVALID_LOCATION.getMsg(expr));
}
}
if (!ctx.getAllowStatefulFunctions() && (genericUDF != null)) {
if (FunctionRegistry.isStateful(genericUDF)) {
throw new SemanticException(ErrorMsg.UDF_STATEFUL_INVALID_LOCATION.getMsg());
}
}
}
protected ExprNodeDesc getXpathOrFuncExprNodeDesc(ASTNode expr,
boolean isFunction, ArrayList<ExprNodeDesc> children, TypeCheckCtx ctx)
throws SemanticException, UDFArgumentException {
// return the child directly if the conversion is redundant.
if (isRedundantConversionFunction(expr, isFunction, children)) {
assert (children.size() == 1);
assert (children.get(0) != null);
return children.get(0);
}
String funcText = getFunctionText(expr, isFunction);
ExprNodeDesc desc;
if (funcText.equals(".")) {
// "." : FIELD Expression
assert (children.size() == 2);
// Only allow constant field name for now
assert (children.get(1) instanceof ExprNodeConstantDesc);
ExprNodeDesc object = children.get(0);
ExprNodeConstantDesc fieldName = (ExprNodeConstantDesc) children.get(1);
assert (fieldName.getValue() instanceof String);
// Calculate result TypeInfo
String fieldNameString = (String) fieldName.getValue();
TypeInfo objectTypeInfo = object.getTypeInfo();
// Allow accessing a field of list element structs directly from a list
boolean isList = (object.getTypeInfo().getCategory() == ObjectInspector.Category.LIST);
if (isList) {
objectTypeInfo = ((ListTypeInfo) objectTypeInfo).getListElementTypeInfo();
}
if (objectTypeInfo.getCategory() != Category.STRUCT) {
throw new SemanticException(ErrorMsg.INVALID_DOT.getMsg(expr));
}
TypeInfo t = ((StructTypeInfo) objectTypeInfo).getStructFieldTypeInfo(fieldNameString);
if (isList) {
t = TypeInfoFactory.getListTypeInfo(t);
}
desc = new ExprNodeFieldDesc(t, children.get(0), fieldNameString, isList);
} else if (funcText.equals("[")) {
// "[]" : LSQUARE/INDEX Expression
if (!ctx.getallowIndexExpr())
throw new SemanticException(ErrorMsg.INVALID_FUNCTION.getMsg(expr));
assert (children.size() == 2);
// Check whether this is a list or a map
TypeInfo myt = children.get(0).getTypeInfo();
if (myt.getCategory() == Category.LIST) {
// Only allow integer index for now
if (!TypeInfoUtils.implicitConvertible(children.get(1).getTypeInfo(),
TypeInfoFactory.intTypeInfo)) {
throw new SemanticException(SemanticAnalyzer.generateErrorMessage(
expr, ErrorMsg.INVALID_ARRAYINDEX_TYPE.getMsg()));
}
// Calculate TypeInfo
TypeInfo t = ((ListTypeInfo) myt).getListElementTypeInfo();
desc = new ExprNodeGenericFuncDesc(t, FunctionRegistry.getGenericUDFForIndex(), children);
} else if (myt.getCategory() == Category.MAP) {
if (!TypeInfoUtils.implicitConvertible(children.get(1).getTypeInfo(),
((MapTypeInfo) myt).getMapKeyTypeInfo())) {
throw new SemanticException(ErrorMsg.INVALID_MAPINDEX_TYPE
.getMsg(expr));
}
// Calculate TypeInfo
TypeInfo t = ((MapTypeInfo) myt).getMapValueTypeInfo();
desc = new ExprNodeGenericFuncDesc(t, FunctionRegistry.getGenericUDFForIndex(), children);
} else {
throw new SemanticException(ErrorMsg.NON_COLLECTION_TYPE.getMsg(expr, myt.getTypeName()));
}
} else {
// other operators or functions
FunctionInfo fi = FunctionRegistry.getFunctionInfo(funcText);
if (fi == null) {
if (isFunction) {
throw new SemanticException(ErrorMsg.INVALID_FUNCTION
.getMsg((ASTNode) expr.getChild(0)));
} else {
throw new SemanticException(ErrorMsg.INVALID_FUNCTION.getMsg(expr));
}
}
// getGenericUDF() actually clones the UDF. Just call it once and reuse.
GenericUDF genericUDF = fi.getGenericUDF();
if (!fi.isNative()) {
ctx.getUnparseTranslator().addIdentifierTranslation(
(ASTNode) expr.getChild(0));
}
// Handle type casts that may contain type parameters
if (isFunction) {
ASTNode funcNameNode = (ASTNode)expr.getChild(0);
switch (funcNameNode.getType()) {
case HiveParser.TOK_CHAR:
// Add type params
CharTypeInfo charTypeInfo = ParseUtils.getCharTypeInfo(funcNameNode);
if (genericUDF != null) {
((SettableUDF)genericUDF).setTypeInfo(charTypeInfo);
}
break;
case HiveParser.TOK_VARCHAR:
VarcharTypeInfo varcharTypeInfo = ParseUtils.getVarcharTypeInfo(funcNameNode);
if (genericUDF != null) {
((SettableUDF)genericUDF).setTypeInfo(varcharTypeInfo);
}
break;
case HiveParser.TOK_DECIMAL:
DecimalTypeInfo decTypeInfo = ParseUtils.getDecimalTypeTypeInfo(funcNameNode);
if (genericUDF != null) {
((SettableUDF)genericUDF).setTypeInfo(decTypeInfo);
}
break;
default:
// Do nothing
break;
}
}
validateUDF(expr, isFunction, ctx, fi, children, genericUDF);
// Try to infer the type of the constant only if there are two
// nodes, one of them is column and the other is numeric const
if (genericUDF instanceof GenericUDFBaseCompare
&& children.size() == 2
&& ((children.get(0) instanceof ExprNodeConstantDesc
&& children.get(1) instanceof ExprNodeColumnDesc)
|| (children.get(0) instanceof ExprNodeColumnDesc
&& children.get(1) instanceof ExprNodeConstantDesc))) {
int constIdx =
children.get(0) instanceof ExprNodeConstantDesc ? 0 : 1;
String constType = children.get(constIdx).getTypeString().toLowerCase();
String columnType = children.get(1 - constIdx).getTypeString().toLowerCase();
final PrimitiveTypeInfo colTypeInfo = TypeInfoFactory.getPrimitiveTypeInfo(columnType);
// Try to narrow type of constant
Object constVal = ((ExprNodeConstantDesc) children.get(constIdx)).getValue();
try {
if (PrimitiveObjectInspectorUtils.intTypeEntry.equals(colTypeInfo.getPrimitiveTypeEntry()) && (constVal instanceof Number || constVal instanceof String)) {
children.set(constIdx, new ExprNodeConstantDesc(new Integer(constVal.toString())));
} else if (PrimitiveObjectInspectorUtils.longTypeEntry.equals(colTypeInfo.getPrimitiveTypeEntry()) && (constVal instanceof Number || constVal instanceof String)) {
children.set(constIdx, new ExprNodeConstantDesc(new Long(constVal.toString())));
}else if (PrimitiveObjectInspectorUtils.doubleTypeEntry.equals(colTypeInfo.getPrimitiveTypeEntry()) && (constVal instanceof Number || constVal instanceof String)) {
children.set(constIdx, new ExprNodeConstantDesc(new Double(constVal.toString())));
} else if (PrimitiveObjectInspectorUtils.floatTypeEntry.equals(colTypeInfo.getPrimitiveTypeEntry()) && (constVal instanceof Number || constVal instanceof String)) {
children.set(constIdx, new ExprNodeConstantDesc(new Float(constVal.toString())));
} else if (PrimitiveObjectInspectorUtils.byteTypeEntry.equals(colTypeInfo.getPrimitiveTypeEntry()) && (constVal instanceof Number || constVal instanceof String)) {
children.set(constIdx, new ExprNodeConstantDesc(new Byte(constVal.toString())));
} else if (PrimitiveObjectInspectorUtils.shortTypeEntry.equals(colTypeInfo.getPrimitiveTypeEntry()) && (constVal instanceof Number || constVal instanceof String)) {
children.set(constIdx, new ExprNodeConstantDesc(new Short(constVal.toString())));
}
} catch (NumberFormatException nfe) {
LOG.trace("Failed to narrow type of constant", nfe);
if ((genericUDF instanceof GenericUDFOPEqual && !NumberUtils.isNumber(constVal.toString()))) {
return new ExprNodeConstantDesc(false);
}
}
// if column type is char and constant type is string, then convert the constant to char
// type with padded spaces.
if (constType.equalsIgnoreCase(serdeConstants.STRING_TYPE_NAME) &&
colTypeInfo instanceof CharTypeInfo) {
final Object originalValue = ((ExprNodeConstantDesc) children.get(constIdx)).getValue();
final String constValue = originalValue.toString();
final int length = TypeInfoUtils.getCharacterLengthForType(colTypeInfo);
final HiveChar newValue = new HiveChar(constValue, length);
children.set(constIdx, new ExprNodeConstantDesc(colTypeInfo, newValue));
}
}
if (genericUDF instanceof GenericUDFOPOr) {
// flatten OR
List<ExprNodeDesc> childrenList = new ArrayList<ExprNodeDesc>(
children.size());
for (ExprNodeDesc child : children) {
if (FunctionRegistry.isOpOr(child)) {
childrenList.addAll(child.getChildren());
} else {
childrenList.add(child);
}
}
desc = ExprNodeGenericFuncDesc.newInstance(genericUDF, funcText,
childrenList);
} else if (genericUDF instanceof GenericUDFOPAnd) {
// flatten AND
List<ExprNodeDesc> childrenList = new ArrayList<ExprNodeDesc>(
children.size());
for (ExprNodeDesc child : children) {
if (FunctionRegistry.isOpAnd(child)) {
childrenList.addAll(child.getChildren());
} else {
childrenList.add(child);
}
}
desc = ExprNodeGenericFuncDesc.newInstance(genericUDF, funcText,
childrenList);
} else if (ctx.isFoldExpr() && canConvertIntoNvl(genericUDF, children)) {
// Rewrite CASE into NVL
desc = ExprNodeGenericFuncDesc.newInstance(new GenericUDFNvl(),
Lists.newArrayList(children.get(0), new ExprNodeConstantDesc(false)));
if (Boolean.FALSE.equals(((ExprNodeConstantDesc) children.get(1)).getValue())) {
desc = ExprNodeGenericFuncDesc.newInstance(new GenericUDFOPNot(),
Lists.newArrayList(desc));
}
} else {
desc = ExprNodeGenericFuncDesc.newInstance(genericUDF, funcText,
children);
}
// If the function is deterministic and the children are constants,
// we try to fold the expression to remove e.g. cast on constant
if (ctx.isFoldExpr() && desc instanceof ExprNodeGenericFuncDesc &&
FunctionRegistry.isDeterministic(genericUDF) &&
ExprNodeDescUtils.isAllConstants(children)) {
ExprNodeDesc constantExpr = ConstantPropagateProcFactory.foldExpr((ExprNodeGenericFuncDesc)desc);
if (constantExpr != null) {
desc = constantExpr;
}
}
}
// UDFOPPositive is a no-op.
// However, we still create it, and then remove it here, to make sure we
// only allow
// "+" for numeric types.
if (FunctionRegistry.isOpPositive(desc)) {
assert (desc.getChildren().size() == 1);
desc = desc.getChildren().get(0);
}
assert (desc != null);
return desc;
}
private boolean canConvertIntoNvl(GenericUDF genericUDF, ArrayList<ExprNodeDesc> children) {
if (genericUDF instanceof GenericUDFWhen && children.size() == 3 &&
children.get(1) instanceof ExprNodeConstantDesc &&
children.get(2) instanceof ExprNodeConstantDesc) {
ExprNodeConstantDesc constThen = (ExprNodeConstantDesc) children.get(1);
ExprNodeConstantDesc constElse = (ExprNodeConstantDesc) children.get(2);
Object thenVal = constThen.getValue();
Object elseVal = constElse.getValue();
if (thenVal instanceof Boolean && elseVal instanceof Boolean) {
return true;
}
}
return false;
}
/**
* Returns true if des is a descendant of ans (ancestor)
*/
private boolean isDescendant(Node ans, Node des) {
if (ans.getChildren() == null) {
return false;
}
for (Node c : ans.getChildren()) {
if (c == des) {
return true;
}
if (isDescendant(c, des)) {
return true;
}
}
return false;
}
protected ExprNodeDesc processQualifiedColRef(TypeCheckCtx ctx, ASTNode expr,
Object... nodeOutputs) throws SemanticException {
RowResolver input = ctx.getInputRR();
String tableAlias = BaseSemanticAnalyzer.unescapeIdentifier(expr.getChild(0).getChild(0)
.getText());
// NOTE: tableAlias must be a valid non-ambiguous table alias,
// because we've checked that in TOK_TABLE_OR_COL's process method.
String colName;
if (nodeOutputs[1] instanceof ExprNodeConstantDesc) {
colName = ((ExprNodeConstantDesc) nodeOutputs[1]).getValue().toString();
} else if (nodeOutputs[1] instanceof ExprNodeColumnDesc) {
colName = ((ExprNodeColumnDesc)nodeOutputs[1]).getColumn();
} else {
throw new SemanticException("Unexpected ExprNode : " + nodeOutputs[1]);
}
ColumnInfo colInfo = input.get(tableAlias, colName);
if (colInfo == null) {
ctx.setError(ErrorMsg.INVALID_COLUMN.getMsg(expr.getChild(1)), expr);
return null;
}
return toExprNodeDesc(colInfo);
}
@Override
public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
Object... nodeOutputs) throws SemanticException {
TypeCheckCtx ctx = (TypeCheckCtx) procCtx;
ExprNodeDesc desc = TypeCheckProcFactory.processGByExpr(nd, procCtx);
if (desc != null) {
// Here we know nd represents a group by expression.
// During the DFS traversal of the AST, a descendant of nd likely set an
// error because a sub-tree of nd is unlikely to also be a group by
// expression. For example, in a query such as
// SELECT *concat(key)* FROM src GROUP BY concat(key), 'key' will be
// processed before 'concat(key)' and since 'key' is not a group by
// expression, an error will be set in ctx by ColumnExprProcessor.
// We can clear the global error when we see that it was set in a
// descendant node of a group by expression because
// processGByExpr() returns a ExprNodeDesc that effectively ignores
// its children. Although the error can be set multiple times by
// descendant nodes, DFS traversal ensures that the error only needs to
// be cleared once. Also, for a case like
// SELECT concat(value, concat(value))... the logic still works as the
// error is only set with the first 'value'; all node processors quit
// early if the global error is set.
if (isDescendant(nd, ctx.getErrorSrcNode())) {
ctx.setError(null, null);
}
return desc;
}
if (ctx.getError() != null) {
return null;
}
ASTNode expr = (ASTNode) nd;
/*
* A Windowing specification get added as a child to a UDAF invocation to distinguish it
* from similar UDAFs but on different windows.
* The UDAF is translated to a WindowFunction invocation in the PTFTranslator.
* So here we just return null for tokens that appear in a Window Specification.
* When the traversal reaches up to the UDAF invocation its ExprNodeDesc is build using the
* ColumnInfo in the InputRR. This is similar to how UDAFs are handled in Select lists.
* The difference is that there is translation for Window related tokens, so we just
* return null;
*/
if (windowingTokens.contains(expr.getType())) {
if (!ctx.getallowWindowing())
throw new SemanticException(SemanticAnalyzer.generateErrorMessage(expr,
ErrorMsg.INVALID_FUNCTION.getMsg("Windowing is not supported in the context")));
return null;
}
if (expr.getType() == HiveParser.TOK_TABNAME) {
return null;
}
if (expr.getType() == HiveParser.TOK_ALLCOLREF) {
if (!ctx.getallowAllColRef())
throw new SemanticException(SemanticAnalyzer.generateErrorMessage(expr,
ErrorMsg.INVALID_COLUMN
.getMsg("All column reference is not supported in the context")));
RowResolver input = ctx.getInputRR();
ExprNodeColumnListDesc columnList = new ExprNodeColumnListDesc();
assert expr.getChildCount() <= 1;
if (expr.getChildCount() == 1) {
// table aliased (select a.*, for example)
ASTNode child = (ASTNode) expr.getChild(0);
assert child.getType() == HiveParser.TOK_TABNAME;
assert child.getChildCount() == 1;
String tableAlias = BaseSemanticAnalyzer.unescapeIdentifier(child.getChild(0).getText());
HashMap<String, ColumnInfo> columns = input.getFieldMap(tableAlias);
if (columns == null) {
throw new SemanticException(ErrorMsg.INVALID_TABLE_ALIAS.getMsg(child));
}
for (Map.Entry<String, ColumnInfo> colMap : columns.entrySet()) {
ColumnInfo colInfo = colMap.getValue();
if (!colInfo.getIsVirtualCol()) {
columnList.addColumn(toExprNodeDesc(colInfo));
}
}
} else {
// all columns (select *, for example)
for (ColumnInfo colInfo : input.getColumnInfos()) {
if (!colInfo.getIsVirtualCol()) {
columnList.addColumn(toExprNodeDesc(colInfo));
}
}
}
return columnList;
}
// If the first child is a TOK_TABLE_OR_COL, and nodeOutput[0] is NULL,
// and the operator is a DOT, then it's a table column reference.
if (expr.getType() == HiveParser.DOT
&& expr.getChild(0).getType() == HiveParser.TOK_TABLE_OR_COL
&& nodeOutputs[0] == null) {
return processQualifiedColRef(ctx, expr, nodeOutputs);
}
// Return nulls for conversion operators
if (conversionFunctionTextHashMap.keySet().contains(expr.getType())
|| specialFunctionTextHashMap.keySet().contains(expr.getType())
|| expr.getToken().getType() == HiveParser.CharSetName
|| expr.getToken().getType() == HiveParser.CharSetLiteral) {
return null;
}
boolean isFunction = (expr.getType() == HiveParser.TOK_FUNCTION ||
expr.getType() == HiveParser.TOK_FUNCTIONSTAR ||
expr.getType() == HiveParser.TOK_FUNCTIONDI);
if (!ctx.getAllowDistinctFunctions() && expr.getType() == HiveParser.TOK_FUNCTIONDI) {
throw new SemanticException(
SemanticAnalyzer.generateErrorMessage(expr, ErrorMsg.DISTINCT_NOT_SUPPORTED.getMsg()));
}
// Create all children
int childrenBegin = (isFunction ? 1 : 0);
ArrayList<ExprNodeDesc> children = new ArrayList<ExprNodeDesc>(
expr.getChildCount() - childrenBegin);
for (int ci = childrenBegin; ci < expr.getChildCount(); ci++) {
if (nodeOutputs[ci] instanceof ExprNodeColumnListDesc) {
children.addAll(((ExprNodeColumnListDesc) nodeOutputs[ci]).getChildren());
} else {
children.add((ExprNodeDesc) nodeOutputs[ci]);
}
}
if (expr.getType() == HiveParser.TOK_FUNCTIONSTAR) {
if (!ctx.getallowFunctionStar())
throw new SemanticException(SemanticAnalyzer.generateErrorMessage(expr,
ErrorMsg.INVALID_COLUMN
.getMsg(".* reference is not supported in the context")));
RowResolver input = ctx.getInputRR();
for (ColumnInfo colInfo : input.getColumnInfos()) {
if (!colInfo.getIsVirtualCol()) {
children.add(toExprNodeDesc(colInfo));
}
}
}
// If any of the children contains null, then return a null
// this is a hack for now to handle the group by case
if (children.contains(null)) {
List<String> possibleColumnNames = getReferenceableColumnAliases(ctx);
String reason = String.format("(possible column names are: %s)",
StringUtils.join(possibleColumnNames, ", "));
ctx.setError(ErrorMsg.INVALID_COLUMN.getMsg(expr.getChild(0), reason),
expr);
return null;
}
// Create function desc
try {
return getXpathOrFuncExprNodeDesc(expr, isFunction, children, ctx);
} catch (UDFArgumentTypeException e) {
throw new SemanticException(ErrorMsg.INVALID_ARGUMENT_TYPE.getMsg(expr
.getChild(childrenBegin + e.getArgumentId()), e.getMessage()), e);
} catch (UDFArgumentLengthException e) {
throw new SemanticException(ErrorMsg.INVALID_ARGUMENT_LENGTH.getMsg(
expr, e.getMessage()), e);
} catch (UDFArgumentException e) {
throw new SemanticException(ErrorMsg.INVALID_ARGUMENT.getMsg(expr, e
.getMessage()), e);
}
}
protected List<String> getReferenceableColumnAliases(TypeCheckCtx ctx) {
return ctx.getInputRR().getReferenceableColumnAliases(null, -1);
}
}
/**
* Factory method to get DefaultExprProcessor.
*
* @return DefaultExprProcessor.
*/
public DefaultExprProcessor getDefaultExprProcessor() {
return new DefaultExprProcessor();
}
/**
* Processor for subquery expressions..
*/
public static class SubQueryExprProcessor implements NodeProcessor {
@Override
public Object process(Node nd, Stack<Node> stack, NodeProcessorCtx procCtx,
Object... nodeOutputs) throws SemanticException {
TypeCheckCtx ctx = (TypeCheckCtx) procCtx;
if (ctx.getError() != null) {
return null;
}
ASTNode expr = (ASTNode) nd;
ASTNode sqNode = (ASTNode) expr.getParent().getChild(1);
if (!ctx.getallowSubQueryExpr())
throw new SemanticException(SemanticAnalyzer.generateErrorMessage(sqNode,
ErrorMsg.UNSUPPORTED_SUBQUERY_EXPRESSION.getMsg()));
ExprNodeDesc desc = TypeCheckProcFactory.processGByExpr(nd, procCtx);
if (desc != null) {
return desc;
}
/*
* Restriction.1.h :: SubQueries only supported in the SQL Where Clause.
*/
ctx.setError(ErrorMsg.UNSUPPORTED_SUBQUERY_EXPRESSION.getMsg(sqNode,
"Currently SubQuery expressions are only allowed as Where Clause predicates"),
sqNode);
return null;
}
}
/**
* Factory method to get SubQueryExprProcessor.
*
* @return DateExprProcessor.
*/
public SubQueryExprProcessor getSubQueryExprProcessor() {
return new SubQueryExprProcessor();
}
}
| BUPTAnderson/apache-hive-2.1.1-src | ql/src/java/org/apache/hadoop/hive/ql/parse/TypeCheckProcFactory.java | Java | apache-2.0 | 56,329 |
/**
* Copyright 2014 IBM Corp. 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.
*/
'use strict';
// Module dependencies
var express = require('express'),
favicon = require('serve-favicon'),
errorhandler = require('errorhandler'),
bodyParser = require('body-parser'),
csrf = require('csurf'),
cookieParser = require('cookie-parser');
module.exports = function (app) {
app.set('view engine', 'ejs');
app.enable('trust proxy');
// use only https
var env = process.env.NODE_ENV || 'development';
if ('production' === env) {
app.use(errorhandler());
}
// Configure Express
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Setup static public directory
app.use(express.static(__dirname + '/../public'));
app.use(favicon(__dirname + '/../public/images/favicon.ico'));
// cookies
var secret = Math.random().toString(36).substring(7);
app.use(cookieParser(secret));
// csrf
var csrfProtection = csrf({ cookie: true });
app.get('/', csrfProtection, function(req, res) {
res.render('index', { ct: req.csrfToken() });
});
// apply to all requests that begin with /api/
// csfr token
app.use('/api/', csrfProtection);
};
| tonybndt/BlueMix-Tutorials | config/express.js | JavaScript | apache-2.0 | 1,764 |
sap.ui.define(['exports'], function (exports) { 'use strict';
var messagebundle_es = {
BARCODE_SCANNER_DIALOG_CANCEL_BUTTON_TXT: "Cancelar",
BARCODE_SCANNER_DIALOG_LOADING_TXT: "Cargando",
FCL_START_COLUMN_TXT: "Primera columna",
FCL_MIDDLE_COLUMN_TXT: "Columna media",
FCL_END_COLUMN_TXT: "Última columna",
FCL_START_COLUMN_EXPAND_BUTTON_TOOLTIP: "Desplegar la primera columna",
FCL_START_COLUMN_COLLAPSE_BUTTON_TOOLTIP: "Comprimir la primera columna",
FCL_END_COLUMN_EXPAND_BUTTON_TOOLTIP: "Desplegar la última columna",
FCL_END_COLUMN_COLLAPSE_BUTTON_TOOLTIP: "Comprimir la última columna",
NOTIFICATION_LIST_ITEM_TXT: "Notificación",
NOTIFICATION_LIST_ITEM_SHOW_MORE: "Visualizar más",
NOTIFICATION_LIST_ITEM_SHOW_LESS: "Visualizar menos",
NOTIFICATION_LIST_ITEM_OVERLOW_BTN_TITLE: "Más",
NOTIFICATION_LIST_ITEM_CLOSE_BTN_TITLE: "Cerrar",
NOTIFICATION_LIST_ITEM_READ: "Leídos",
NOTIFICATION_LIST_ITEM_UNREAD: "No leídos",
NOTIFICATION_LIST_ITEM_HIGH_PRIORITY_TXT: "Prioridad alta",
NOTIFICATION_LIST_ITEM_MEDIUM_PRIORITY_TXT: "Prioridad media",
NOTIFICATION_LIST_ITEM_LOW_PRIORITY_TXT: "Prioridad baja",
NOTIFICATION_LIST_GROUP_ITEM_TXT: "Grupo de notificaciones",
NOTIFICATION_LIST_GROUP_ITEM_COUNTER_TXT: "Contador",
NOTIFICATION_LIST_GROUP_ITEM_CLOSE_BTN_TITLE: "Cerrar todo",
NOTIFICATION_LIST_GROUP_ITEM_TOGGLE_BTN_COLLAPSE_TITLE: "Ocultar grupo",
NOTIFICATION_LIST_GROUP_ITEM_TOGGLE_BTN_EXPAND_TITLE: "Desplegar grupo",
TIMELINE_ARIA_LABEL: "Cronología",
UPLOADCOLLECTIONITEM_CANCELBUTTON_TEXT: "Cancelar",
UPLOADCOLLECTIONITEM_RENAMEBUTTON_TEXT: "Cambiar nombre",
UPLOADCOLLECTIONITEM_ERROR_STATE: "Concluido",
UPLOADCOLLECTIONITEM_READY_STATE: "Pendiente",
UPLOADCOLLECTIONITEM_UPLOADING_STATE: "Cargando",
UPLOADCOLLECTIONITEM_TERMINATE_BUTTON_TEXT: "Finalizar",
UPLOADCOLLECTIONITEM_RETRY_BUTTON_TEXT: "Volver a intentar",
UPLOADCOLLECTIONITEM_EDIT_BUTTON_TEXT: "Editar",
UPLOADCOLLECTION_NO_DATA_TEXT: "No existen ficheros.",
UPLOADCOLLECTION_NO_DATA_DESCRIPTION: "Soltar los ficheros para cargarlos o utilizar el botón \"Cargar\".",
UPLOADCOLLECTION_ARIA_ROLE_DESCRIPTION: "Cargar colección",
UPLOADCOLLECTION_DRAG_FILE_INDICATOR: "Arrastrar ficheros aquí.",
UPLOADCOLLECTION_DROP_FILE_INDICATOR: "Soltar ficheros para cargalos.",
SHELLBAR_LABEL: "Barra de shell",
SHELLBAR_LOGO: "Logotipo",
SHELLBAR_COPILOT: "CoPilot",
SHELLBAR_NOTIFICATIONS: "Notificaciones {0}",
SHELLBAR_PROFILE: "Perfil",
SHELLBAR_PRODUCTS: "Productos",
PRODUCT_SWITCH_CONTAINER_LABEL: "Productos",
SHELLBAR_SEARCH: "Buscar",
SHELLBAR_OVERFLOW: "Más",
SHELLBAR_CANCEL: "Cancelar",
WIZARD_NAV_ARIA_LABEL: "Barra de progreso del asistente",
WIZARD_LIST_ARIA_LABEL: "Pasos del asistente",
WIZARD_LIST_ARIA_DESCRIBEDBY: "Para activarlo, pulse la barra espaciadora o Intro",
WIZARD_ACTIONSHEET_STEPS_ARIA_LABEL: "Pasos",
WIZARD_OPTIONAL_STEP_ARIA_LABEL: "Opcional",
WIZARD_STEP_ACTIVE: "Activo",
WIZARD_STEP_INACTIVE: "Inactivo",
WIZARD_STEP_ARIA_LABEL: "Paso {0}",
WIZARD_NAV_ARIA_ROLE_DESCRIPTION: "Asistente",
WIZARD_NAV_STEP_DEFAULT_HEADING: "Paso",
VSD_DIALOG_TITLE_SORT: "Ver opciones",
VSD_SUBMIT_BUTTON: "OK",
VSD_CANCEL_BUTTON: "Cancelar",
VSD_RESET_BUTTON: "Reinicializar",
VSD_SORT_ORDER: "Orden de clasificación",
VSD_FILTER_BY: "Filtrar por",
VSD_SORT_BY: "Clasificar por",
VSD_ORDER_ASCENDING: "Ascendente",
VSD_ORDER_DESCENDING: "Descendente",
IM_TITLE_BEFORESEARCH: "Obtengamos resultados",
IM_SUBTITLE_BEFORESEARCH: "Comience proporcionando los criterios de búsqueda.",
IM_TITLE_NOACTIVITIES: "Todavía no ha añadido actividades",
IM_SUBTITLE_NOACTIVITIES: "¿Desea añadir una ahora?",
IM_TITLE_NODATA: "Todavía no hay datos",
IM_SUBTITLE_NODATA: "Cuando haya, los verá aquí.",
IM_TITLE_NOMAIL: "Ningún correo nuevo",
IM_SUBTITLE_NOMAIL: "Vuelva a comprobarlo de nuevo más tarde.",
IM_TITLE_NOENTRIES: "Todavía no hay entradas",
IM_SUBTITLE_NOENTRIES: "Cuando haya, las verá aquí.",
IM_TITLE_NONOTIFICATIONS: "No tiene ninguna notificación nueva",
IM_SUBTITLE_NONOTIFICATIONS: "Vuelva a comprobarlo de nuevo más tarde.",
IM_TITLE_NOSAVEDITEMS: "Todavía no ha añadido favoritos",
IM_SUBTITLE_NOSAVEDITEMS: "¿Desea crear una lista de las posiciones favoritas ahora?",
IM_TITLE_NOSEARCHRESULTS: "No existen resultados",
IM_SUBTITLE_NOSEARCHRESULTS: "Intente modificar los criterios de búsqueda.",
IM_TITLE_NOTASKS: "No tiene ninguna tarea nueva",
IM_SUBTITLE_NOTASKS: "Cuando tenga, las verá aquí.",
IM_TITLE_UNABLETOLOAD: "No se pueden cargar datos",
IM_SUBTITLE_UNABLETOLOAD: "Compruebe su conexión a internet. Si esto no funciona, intente volver a cargar la página. Si esto tampoco funciona, verifique con su administrador.",
IM_TITLE_UNABLETOLOADIMAGE: "No se puede cargar la imagen",
IM_SUBTITLE_UNABLETOLOADIMAGE: "No se ha podido encontrar la imagen en la ubicación especificada o el servidor no responde.",
IM_TITLE_UNABLETOUPLOAD: "No se pueden cargar datos",
IM_SUBTITLE_UNABLETOUPLOAD: "Compruebe su conexión a internet. Si esto no funciona, compruebe el formato de fichero y el tamaño de fichero. De lo contrario, póngase en contacto con su administrador.",
IM_TITLE_ADDCOLUMN: "Parece que hay espacio libre",
IM_SUBTITLE_ADDCOLUMN: "Puede añadir más columnas en las opciones de tabla.",
IM_TITLE_ADDPEOPLE: "Aún no ha añadido a nadie al calendario",
IM_SUBTITLE_ADDPEOPLE: "¿Desea añadir a alguien ahora?",
IM_TITLE_BALLOONSKY: "Se le valora.",
IM_SUBTITLE_BALLOONSKY: "Siga trabajando tan bien.",
IM_TITLE_EMPTYPLANNINGCALENDAR: "Aún no hay nada planificado",
IM_SUBTITLE_EMPTYPLANNINGCALENDAR: "No hay actividades en este intervalo de tiempo",
IM_TITLE_FILTERTABLE: "Hay opciones de filtro disponibles",
IM_SUBTITLE_FILTERTABLE: "Los filtros le ayudan a concentrarse en lo que considera más relevante.",
IM_TITLE_GROUPTABLE: "Intente agrupar elementos para obtener un mejor resumen",
IM_SUBTITLE_GROUPTABLE: "Puede optar por agrupar categorías en las opciones de grupo.",
IM_TITLE_NOFILTERRESULTS: "No existen resultados",
IM_SUBTITLE_NOFILTERRESULTS: "Intente ajustar sus criterio de filtro.",
IM_TITLE_PAGENOTFOUND: "Lo sentimos, la página no existe",
IM_SUBTITLE_PAGENOTFOUND: "Verifique el URL que está utilizando para llamar la aplicación.",
IM_TITLE_RESIZECOLUMN: "Seleccione su propio ancho de columna",
IM_SUBTITLE_RESIZECOLUMN: "Puede ajustar columnas arrastrando los bordes de la columna.",
IM_TITLE_SORTCOLUMN: "¿No ve primero los elementos más importantes?",
IM_SUBTITLE_SORTCOLUMN: "Seleccione los criterios de clasificación en las opciones de clasificación.",
IM_TITLE_SUCCESSSCREEN: "Bien hecho.",
IM_SUBTITLE_SUCCESSSCREEN: "Ha completado todas sus asignaciones de aprendizaje.",
IM_TITLE_UPLOADCOLLECTION: "Suelte aquí los archivos",
IM_SUBTITLE_UPLOADCOLLECTION: "También puede cargar varios archivos a la vez.",
DSC_SIDE_ARIA_LABEL: "Contenido lateral"
};
exports.default = messagebundle_es;
});
| SAP/openui5 | src/sap.ui.webc.fiori/src/sap/ui/webc/fiori/thirdparty/_chunks/messagebundle_es.js | JavaScript | apache-2.0 | 7,123 |
<?php
$config = array(
'service' => 'Kafka',
'brokers' => array('192.168.0.50:9092'),
'state_dir' => '/workdir/state',
'loglevel' => LOG_DEBUG,
'timeout' => 1000,
'topics' => array(
array('name' => 'test1', 'partitions' => array(0)),
),
'config_check_interval' => 6,
'queue_check_interval' => 2,
);
| pozgo/docker-kafka | tests/config.php | PHP | apache-2.0 | 354 |
/*
By: facug91
From: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1335
Name: Twin Primes
Date: 23/10/2015
*/
#include <bits/stdc++.h>
#define endl "\n"
#define EPS 1e-9
#define MP make_pair
#define F first
#define S second
#define DB(x) cerr << " #" << (#x) << ": " << (x)
#define DBL(x) cerr << " #" << (#x) << ": " << (x) << endl
const double PI = 2.0*acos(0.0);
#define INF 1000000000
//#define MOD 1000000007ll
//#define MAXN 10005
using namespace std;
typedef long long ll;
typedef unsigned long long llu;
typedef pair<int, int> ii; typedef pair<ii, ii> iiii;
typedef vector<int> vi; typedef vector<ii> vii; typedef vector<iiii> viiii;
int s, a, b;
bool sieve[20000005];
vii ans;
int main () {
ios_base::sync_with_stdio(0); cin.tie(0);
//cout<<fixed<<setprecision(7); cerr<<fixed<<setprecision(7); //cin.ignore(INT_MAX, ' '); //cout << setfill('0') << setw(5) << 25
int tc = 1, i, j;
for (i=0; i<20000005; i++) sieve[i] = true;
sieve[0] = sieve[1] = false;
for (i=4; i<20000005; i+=2) sieve[i] = false;
int sq = sqrt(20000005)+1;
for (i=3; i<sq; i+=2)
if (sieve[i])
for (j=i*i; j<20000005; j+=i+i)
sieve[j] = false;
a = 3; b = 5;
while (b < 20000005) {
if (sieve[a] && sieve[b]) ans.emplace_back(a, b);
a += 2;
b += 2;
}
while (cin>>s) {
s--;
cout<<"("<<ans[s].F<<", "<<ans[s].S<<")"<<endl;
}
return 0;
}
| facug91/OJ-Solutions | uva.onlinejudge.org/TwinPrimes.cpp | C++ | apache-2.0 | 1,438 |
package com.digitalpetri.enip.cip.services;
import com.digitalpetri.enip.cip.CipResponseException;
import com.digitalpetri.enip.cip.epath.EPath.PaddedEPath;
import com.digitalpetri.enip.cip.structs.MessageRouterRequest;
import com.digitalpetri.enip.cip.structs.MessageRouterResponse;
import io.netty.buffer.ByteBuf;
import io.netty.util.ReferenceCountUtil;
public class GetAttributesAllService implements CipService<ByteBuf> {
public static final int SERVICE_CODE = 0x01;
private final PaddedEPath requestPath;
public GetAttributesAllService(PaddedEPath requestPath) {
this.requestPath = requestPath;
}
@Override
public void encodeRequest(ByteBuf buffer) {
MessageRouterRequest request = new MessageRouterRequest(
SERVICE_CODE,
requestPath,
byteBuf -> {
}
);
MessageRouterRequest.encode(request, buffer);
}
@Override
public ByteBuf decodeResponse(ByteBuf buffer) throws CipResponseException {
MessageRouterResponse response = MessageRouterResponse.decode(buffer);
if (response.getGeneralStatus() == 0x00) {
return response.getData();
} else {
ReferenceCountUtil.release(response.getData());
throw new CipResponseException(response.getGeneralStatus(), response.getAdditionalStatus());
}
}
}
| digitalpetri/ethernet-ip | cip-core/src/main/java/com/digitalpetri/enip/cip/services/GetAttributesAllService.java | Java | apache-2.0 | 1,389 |