repo_name
stringlengths
4
116
path
stringlengths
3
942
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
brettryan/spring-app-base
src/test/java/com/drunkendev/menu/MenuBuilderTest.java
3004
/* * Copyright 2016 Drunken Dev. * * 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.drunkendev.menu; import java.io.OutputStream; import java.nio.file.Files; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Brett Ryan */ public class MenuBuilderTest { /** * Test of builder method, of class MenuBuilder. */ @Test public void testBuilder() { System.out.println("builder"); MenuItem menu = MenuBuilder.builder() .child("Product") .child("Knowledge Base", "/kb") .withChild("Support") .child("Help Me", "/") .child("Tickets") .end() .child("Blog", "/blog") .build(); assertEquals("Root menu length.", 4, menu.getChildren().size()); assertEquals("Menu item", "Product", menu.getChildren().get(0).getText()); assertEquals("Menu item", "Knowledge Base", menu.getChildren().get(1).getText()); assertEquals("Menu item", "Support", menu.getChildren().get(2).getText()); assertEquals("Menu item", "Help Me", menu.getChildren().get(2).getChildren().get(0).getText()); } /** * Test of write method, of class MenuBuilder. */ @Test public void testWrite() throws Exception { MenuItem build = MenuBuilder.builder() .child("Product") .child("Knowledge Base", "/kb") .withChild("Support") .child("Help Me", "/") .child("Tickets") .end() .child("Blog", "/blog") .build(); try (OutputStream os = Files.newOutputStream(Files.createTempFile("menu-test", ".xml"))) { MenuBuilder.write(build, os); } } /** * Test of load method, of class MenuBuilder. */ @Test public void testLoad() throws Exception { MenuItem menu = MenuBuilder.load(MenuBuilderTest.class.getResourceAsStream("menu1.xml")); assertEquals("Root menu length.", 4, menu.getChildren().size()); assertEquals("Menu item", "Product", menu.getChildren().get(0).getText()); assertEquals("Menu item", "Knowledge Base", menu.getChildren().get(1).getText()); assertEquals("Menu item", "Support", menu.getChildren().get(2).getText()); assertEquals("Menu item", "Help Me", menu.getChildren().get(2).getChildren().get(0).getText()); } }
apache-2.0
hmrc/amls-frontend
test/views/businessmatching/updateservice/add/cannot_add_servicesSpec.scala
1990
/* * Copyright 2021 HM Revenue & Customs * * 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 views.businessmatching.updateservice.add import forms.EmptyForm import play.api.i18n.Messages import utils.AmlsViewSpec import views.Fixture import views.html.businessmatching.updateservice.add._ class cannot_add_servicesSpec extends AmlsViewSpec { trait ViewFixture extends Fixture { lazy val cannot_add_services = app.injector.instanceOf[cannot_add_services] implicit val requestWithToken = addTokenForView() def view = cannot_add_services(EmptyForm) } "The cannot_add_services view" must { "have the correct title" in new ViewFixture { doc.title must startWith(Messages("businessmatching.updateservice.nopsr.cannotcontinuewiththeapplication.title") + " - " + Messages("summary.updateservice")) } "have correct heading" in new ViewFixture { heading.html must be(Messages("businessmatching.updateservice.nopsr.cannotcontinuewiththeapplication.heading")) } "have correct subHeading" in new ViewFixture { subHeading.html must include(Messages("summary.updateservice")) } "have the back link button" in new ViewFixture { doc.getElementsByAttributeValue("class", "link-back") must not be empty } "show the correct content" in new ViewFixture { doc.body().text() must include(Messages("businessmatching.updateservice.nopsr.cannotcontinuewiththeapplication.requiredinfo.2")) } } }
apache-2.0
savantly-net/sprout-platform
frontend/libs/sprout-ui/src/components/Typeahead/TypeaheadInfo.tsx
1884
import React, { useContext } from 'react'; import { css, cx } from 'emotion'; import { CompletionItem, selectThemeVariant, ThemeContext } from '../..'; import { GrafanaTheme, renderMarkdown, textUtil } from '@savantly/sprout-api'; const getStyles = (theme: GrafanaTheme, height: number, visible: boolean) => { return { typeaheadItem: css` label: type-ahead-item; z-index: 11; padding: ${theme.spacing.sm} ${theme.spacing.sm} ${theme.spacing.sm} ${theme.spacing.md}; border-radius: ${theme.border.radius.md}; border: ${selectThemeVariant( { light: `solid 1px ${theme.palette.gray5}`, dark: `solid 1px ${theme.palette.dark1}` }, theme.type )}; overflow-y: scroll; overflow-x: hidden; outline: none; background: ${selectThemeVariant({ light: theme.palette.white, dark: theme.palette.dark4 }, theme.type)}; color: ${theme.colors.text}; box-shadow: ${selectThemeVariant( { light: `0 5px 10px 0 ${theme.palette.gray5}`, dark: `0 5px 10px 0 ${theme.palette.black}` }, theme.type )}; visibility: ${visible === true ? 'visible' : 'hidden'}; width: 250px; height: ${height + parseInt(theme.spacing.xxs, 10)}px; position: relative; word-break: break-word; `, }; }; interface Props { item: CompletionItem; height: number; } export const TypeaheadInfo: React.FC<Props> = ({ item, height }) => { const visible = item && !!item.documentation; const label = item ? item.label : ''; const documentation = textUtil.sanitize(renderMarkdown(item?.documentation)); const theme = useContext(ThemeContext); const styles = getStyles(theme, height, visible); return ( <div className={cx([styles.typeaheadItem])}> <b>{label}</b> <hr /> <div dangerouslySetInnerHTML={{ __html: documentation }} /> </div> ); };
apache-2.0
xjodoin/torpedoquery
src/main/java/org/torpedoquery/jpa/TorpedoFunction.java
14719
/** * Copyright (C) 2011 Xavier Jodoin ([email protected]) * * 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. * * @author xjodoin * @version $Id: $Id */ package org.torpedoquery.jpa; import static org.torpedoquery.jpa.internal.TorpedoMagic.getTorpedoMethodHandler; import static org.torpedoquery.jpa.internal.TorpedoMagic.setQuery; import org.torpedoquery.core.QueryBuilder; import org.torpedoquery.jpa.internal.Selector; import org.torpedoquery.jpa.internal.TorpedoProxy; import org.torpedoquery.jpa.internal.functions.CoalesceFunction; import org.torpedoquery.jpa.internal.functions.DynamicInstantiationFunction; import org.torpedoquery.jpa.internal.handlers.ArrayCallHandler; import org.torpedoquery.jpa.internal.handlers.AscFunctionHandler; import org.torpedoquery.jpa.internal.handlers.AvgFunctionHandler; import org.torpedoquery.jpa.internal.handlers.ComparableConstantFunctionHandler; import org.torpedoquery.jpa.internal.handlers.ConstantFunctionHandler; import org.torpedoquery.jpa.internal.handlers.CustomFunctionHandler; import org.torpedoquery.jpa.internal.handlers.DescFunctionHandler; import org.torpedoquery.jpa.internal.handlers.DistinctFunctionHandler; import org.torpedoquery.jpa.internal.handlers.IndexFunctionHandler; import org.torpedoquery.jpa.internal.handlers.MathOperationHandler; import org.torpedoquery.jpa.internal.handlers.MaxFunctionHandler; import org.torpedoquery.jpa.internal.handlers.MinFunctionHandler; import org.torpedoquery.jpa.internal.handlers.SubstringFunctionHandler; import org.torpedoquery.jpa.internal.handlers.SumFunctionHandler; import org.torpedoquery.jpa.internal.handlers.ValueHandler; import org.torpedoquery.jpa.internal.utils.TorpedoMethodHandler; public class TorpedoFunction { // JPA Functions /** * <p>count.</p> * * @param object a {@link java.lang.Object} object. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static Function<Long> count(Object object) { return function("count", Long.class, object); } /** * <p>sum.</p> * * @param number a T object. * @param <V> a V object. * @return a {@link org.torpedoquery.jpa.ComparableFunction} object. * @param <T> a T object. */ public static <V, T extends Comparable<V>> ComparableFunction<V> sum( T number) { return getTorpedoMethodHandler().handle( new SumFunctionHandler<V>(number)); } /** * <p>sum.</p> * * @param number a {@link org.torpedoquery.jpa.Function} object. * @param <V> a V object. * @return a {@link org.torpedoquery.jpa.ComparableFunction} object. * @param <T> a T object. */ public static <V, T extends Comparable<V>> ComparableFunction<V> sum( Function<T> number) { return getTorpedoMethodHandler().handle( new SumFunctionHandler<V>(number)); } /** * <p>min.</p> * * @param number a T object. * @param <V> a V object. * @return a {@link org.torpedoquery.jpa.ComparableFunction} object. * @param <T> a T object. */ public static <V, T extends Comparable<V>> ComparableFunction<V> min( T number) { return getTorpedoMethodHandler().handle( new MinFunctionHandler<V>(number)); } /** * <p>min.</p> * * @param number a {@link org.torpedoquery.jpa.Function} object. * @param <V> a V object. * @return a {@link org.torpedoquery.jpa.ComparableFunction} object. * @param <T> a T object. */ public static <V, T extends Comparable<V>> ComparableFunction<V> min( Function<T> number) { return getTorpedoMethodHandler().handle( new MinFunctionHandler<V>(number)); } /** * <p>max.</p> * * @param number a T object. * @param <V> a V object. * @return a {@link org.torpedoquery.jpa.ComparableFunction} object. * @param <T> a T object. */ public static <V, T extends Comparable<V>> ComparableFunction<V> max( T number) { return getTorpedoMethodHandler().handle( new MaxFunctionHandler<V>(number)); } /** * <p>max.</p> * * @param number a {@link org.torpedoquery.jpa.Function} object. * @param <V> a V object. * @return a {@link org.torpedoquery.jpa.ComparableFunction} object. * @param <T> a T object. */ public static <V, T extends Comparable<V>> ComparableFunction<V> max( Function<T> number) { return getTorpedoMethodHandler().handle( new MaxFunctionHandler<V>(number)); } /** * <p>avg.</p> * * @param number a T object. * @param <V> a V object. * @return a {@link org.torpedoquery.jpa.ComparableFunction} object. * @param <T> a T object. */ public static <V, T extends Comparable<V>> ComparableFunction<V> avg( T number) { return getTorpedoMethodHandler().handle( new AvgFunctionHandler<V>(number)); } /** * <p>avg.</p> * * @param number a {@link org.torpedoquery.jpa.Function} object. * @param <V> a V object. * @return a {@link org.torpedoquery.jpa.ComparableFunction} object. * @param <T> a T object. */ public static <V, T extends Comparable<V>> ComparableFunction<V> avg( Function<T> number) { return getTorpedoMethodHandler().handle( new AvgFunctionHandler<V>(number)); } /** * <p>coalesce.</p> * * @param values a E object. * @param <T> a T object. * @return a E object. * @param <E> a E object. */ public static <T, E extends Function<T>> E coalesce(E... values) { CoalesceFunction<E> coalesceFunction = getCoalesceFunction(values); return (E) coalesceFunction; } /** * <p>coalesce.</p> * * @param values a T object. * @param <T> a T object. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static <T> Function<T> coalesce(T... values) { return getCoalesceFunction(values); } private static <T> CoalesceFunction<T> getCoalesceFunction(T... values) { final CoalesceFunction coalesceFunction = new CoalesceFunction(); getTorpedoMethodHandler().handle( new ArrayCallHandler(new ValueHandler<Void>() { @Override public Void handle(TorpedoProxy proxy, QueryBuilder queryBuilder, Selector selector) { coalesceFunction.setQuery(proxy); coalesceFunction.addSelector(selector); return null; } }, values)); return coalesceFunction; } private static <T> DynamicInstantiationFunction<T> getDynamicInstantiationFunction(T val) { final DynamicInstantiationFunction<T> dynFunction = new DynamicInstantiationFunction<>(val); TorpedoMethodHandler torpedoMethodHandler = getTorpedoMethodHandler(); Object[] params = torpedoMethodHandler.params(); torpedoMethodHandler.handle( new ArrayCallHandler(new ValueHandler<Void>() { @Override public Void handle(TorpedoProxy proxy, QueryBuilder queryBuilder, Selector selector) { dynFunction.setQuery(proxy); dynFunction.addSelector(selector); return null; } }, params)); return dynFunction; } /** * * Hibernate calls this "dynamic instantiation". JPQL supports some of this feature and calls it a "constructor expression". * * dyn(new ProjectionEntity( * param(entity.getCode()), param(entity.getIntegerField()) * * Important: you need to wrap each constructor parameter with a param() call * * @param object a T object. * @param <T> a T object. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static <T> Function<T> dyn(T object) { return getDynamicInstantiationFunction(object); } /** * <p>distinct.</p> * * @param object a T object. * @param <T> a T object. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static <T> Function<T> distinct(T object) { if (object instanceof TorpedoProxy) { setQuery((TorpedoProxy) object); } return getTorpedoMethodHandler().handle( new DistinctFunctionHandler<T>(object)); } /** * <p>constant.</p> * * @param constant a T object. * @param <T> a T object. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static <T> Function<T> constant(T constant) { return getTorpedoMethodHandler().handle( new ConstantFunctionHandler<T>(constant)); } /** * <p>constant.</p> * * @param constant a T object. * @param <V> a V object. * @return a {@link org.torpedoquery.jpa.ComparableFunction} object. * @param <T> a T object. */ public static <V, T extends Comparable<V>> ComparableFunction<T> constant( T constant) { return getTorpedoMethodHandler().handle( new ComparableConstantFunctionHandler<T>(constant)); } /** * <p>index.</p> * * @param object a T object. * @param <T> a T object. * @return a {@link org.torpedoquery.jpa.ComparableFunction} object. */ public static <T> ComparableFunction<Integer> index(T object) { if (object instanceof TorpedoProxy) { setQuery((TorpedoProxy) object); } return getTorpedoMethodHandler().handle( new IndexFunctionHandler(object)); } /** * Use this method to call functions witch are not supported natively by * Torpedo * * @return your custom function * @param name a {@link java.lang.String} object. * @param returnType a {@link java.lang.Class} object. * @param value a {@link java.lang.Object} object. * @param <T> a T object. */ public static <T> Function<T> function(String name, Class<T> returnType, Object value) { return getTorpedoMethodHandler().handle( new CustomFunctionHandler<T>(name, value)); } /** * <p>comparableFunction.</p> * * @param name a {@link java.lang.String} object. * @param returnType a {@link java.lang.Class} object. * @param value a {@link java.lang.Object} object. * @param <V> a V object. * @return a {@link org.torpedoquery.jpa.ComparableFunction} object. * @param <T> a T object. */ public static <V, T extends Comparable<V>> ComparableFunction<V> comparableFunction( String name, Class<V> returnType, Object value) { return getTorpedoMethodHandler().handle( new CustomFunctionHandler<V>(name, value)); } // orderBy function /** * <p>asc.</p> * * @param object a T object. * @param <T> a T object. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static <T> Function<T> asc(T object) { return getTorpedoMethodHandler().handle(new AscFunctionHandler<T>()); } /** * <p>desc.</p> * * @param object a T object. * @param <T> a T object. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static <T> Function<T> desc(T object) { return getTorpedoMethodHandler().handle(new DescFunctionHandler<T>()); } // math operation /** * <p>operation.</p> * * @param left a T object. * @param <T> a T object. * @return a {@link org.torpedoquery.jpa.OnGoingMathOperation} object. */ public static <T> OnGoingMathOperation<T> operation(T left) { return getTorpedoMethodHandler().handle( new MathOperationHandler<T>(null)); } /** * <p>operation.</p> * * @param left a {@link org.torpedoquery.jpa.Function} object. * @param <T> a T object. * @return a {@link org.torpedoquery.jpa.OnGoingMathOperation} object. */ public static <T> OnGoingMathOperation<T> operation(Function<T> left) { return getTorpedoMethodHandler().handle( new MathOperationHandler<T>(left)); } // string functions // substring(), trim(), lower(), upper(), length() /** * <p>trim.</p> * * @param field a {@link java.lang.String} object. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static Function<String> trim(String field) { return function("trim", String.class, field); } /** * <p>trim.</p> * * @param function a {@link org.torpedoquery.jpa.Function} object. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static Function<String> trim(Function<String> function) { return function("trim", String.class, function); } /** * <p>lower.</p> * * @param field a {@link java.lang.String} object. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static Function<String> lower(String field) { return function("lower", String.class, field); } /** * <p>lower.</p> * * @param function a {@link org.torpedoquery.jpa.Function} object. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static Function<String> lower(Function<String> function) { return function("lower", String.class, function); } /** * <p>upper.</p> * * @param field a {@link java.lang.String} object. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static Function<String> upper(String field) { return function("upper", String.class, field); } /** * <p>upper.</p> * * @param function a {@link org.torpedoquery.jpa.Function} object. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static Function<String> upper(Function<String> function) { return function("upper", String.class, function); } /** * <p>length.</p> * * @param field a {@link java.lang.String} object. * @return a {@link org.torpedoquery.jpa.ComparableFunction} object. */ public static ComparableFunction<Integer> length(String field) { return comparableFunction("length", Integer.class, field); } /** * <p>length.</p> * * @param function a {@link org.torpedoquery.jpa.Function} object. * @return a {@link org.torpedoquery.jpa.ComparableFunction} object. */ public static ComparableFunction<Integer> length(Function<String> function) { return comparableFunction("length", Integer.class, function); } /** * <p>substring.</p> * * @param param a {@link java.lang.String} object. * @param beginIndex a int. * @param endIndex a int. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static Function<String> substring(String param, int beginIndex, int endIndex) { return getTorpedoMethodHandler().handle( new SubstringFunctionHandler(param, beginIndex, endIndex)); } /** * <p>substring.</p> * * @param param a {@link org.torpedoquery.jpa.Function} object. * @param beginIndex a int. * @param endIndex a int. * @return a {@link org.torpedoquery.jpa.Function} object. */ public static Function<String> substring(Function<String> param, int beginIndex, int endIndex) { return getTorpedoMethodHandler().handle( new SubstringFunctionHandler(param, beginIndex, endIndex)); } }
apache-2.0
akubicharm/openshift-ansible
roles/lib_openshift/src/lib/base.py
21165
# pylint: skip-file # flake8: noqa # pylint: disable=too-many-lines # noqa: E301,E302,E303,T001 class OpenShiftCLIError(Exception): '''Exception class for openshiftcli''' pass ADDITIONAL_PATH_LOOKUPS = ['/usr/local/bin', os.path.expanduser('~/bin')] def locate_oc_binary(): ''' Find and return oc binary file ''' # https://github.com/openshift/openshift-ansible/issues/3410 # oc can be in /usr/local/bin in some cases, but that may not # be in $PATH due to ansible/sudo paths = os.environ.get("PATH", os.defpath).split(os.pathsep) + ADDITIONAL_PATH_LOOKUPS oc_binary = 'oc' # Use shutil.which if it is available, otherwise fallback to a naive path search try: which_result = shutil.which(oc_binary, path=os.pathsep.join(paths)) if which_result is not None: oc_binary = which_result except AttributeError: for path in paths: if os.path.exists(os.path.join(path, oc_binary)): oc_binary = os.path.join(path, oc_binary) break return oc_binary # pylint: disable=too-few-public-methods class OpenShiftCLI(object): ''' Class to wrap the command line tools ''' def __init__(self, namespace, kubeconfig='/etc/origin/master/admin.kubeconfig', verbose=False, all_namespaces=False): ''' Constructor for OpenshiftCLI ''' self.namespace = namespace self.verbose = verbose self.kubeconfig = Utils.create_tmpfile_copy(kubeconfig) self.all_namespaces = all_namespaces self.oc_binary = locate_oc_binary() # Pylint allows only 5 arguments to be passed. # pylint: disable=too-many-arguments def _replace_content(self, resource, rname, content, force=False, sep='.'): ''' replace the current object with the content ''' res = self._get(resource, rname) if not res['results']: return res fname = Utils.create_tmpfile(rname + '-') yed = Yedit(fname, res['results'][0], separator=sep) changes = [] for key, value in content.items(): changes.append(yed.put(key, value)) if any([change[0] for change in changes]): yed.write() atexit.register(Utils.cleanup, [fname]) return self._replace(fname, force) return {'returncode': 0, 'updated': False} def _replace(self, fname, force=False): '''replace the current object with oc replace''' # We are removing the 'resourceVersion' to handle # a race condition when modifying oc objects yed = Yedit(fname) results = yed.delete('metadata.resourceVersion') if results[0]: yed.write() cmd = ['replace', '-f', fname] if force: cmd.append('--force') return self.openshift_cmd(cmd) def _create_from_content(self, rname, content): '''create a temporary file and then call oc create on it''' fname = Utils.create_tmpfile(rname + '-') yed = Yedit(fname, content=content) yed.write() atexit.register(Utils.cleanup, [fname]) return self._create(fname) def _create(self, fname): '''call oc create on a filename''' return self.openshift_cmd(['create', '-f', fname]) def _delete(self, resource, name=None, selector=None): '''call oc delete on a resource''' cmd = ['delete', resource] if selector is not None: cmd.append('--selector={}'.format(selector)) elif name is not None: cmd.append(name) else: raise OpenShiftCLIError('Either name or selector is required when calling delete.') return self.openshift_cmd(cmd) def _process(self, template_name, create=False, params=None, template_data=None): # noqa: E501 '''process a template template_name: the name of the template to process create: whether to send to oc create after processing params: the parameters for the template template_data: the incoming template's data; instead of a file ''' cmd = ['process'] if template_data: cmd.extend(['-f', '-']) else: cmd.append(template_name) if params: param_str = ["{}={}".format(key, str(value).replace("'", r'"')) for key, value in params.items()] cmd.append('-v') cmd.extend(param_str) results = self.openshift_cmd(cmd, output=True, input_data=template_data) if results['returncode'] != 0 or not create: return results fname = Utils.create_tmpfile(template_name + '-') yed = Yedit(fname, results['results']) yed.write() atexit.register(Utils.cleanup, [fname]) return self.openshift_cmd(['create', '-f', fname]) def _get(self, resource, name=None, selector=None): '''return a resource by name ''' cmd = ['get', resource] if selector is not None: cmd.append('--selector={}'.format(selector)) elif name is not None: cmd.append(name) cmd.extend(['-o', 'json']) rval = self.openshift_cmd(cmd, output=True) # Ensure results are retuned in an array if 'items' in rval: rval['results'] = rval['items'] elif not isinstance(rval['results'], list): rval['results'] = [rval['results']] return rval def _schedulable(self, node=None, selector=None, schedulable=True): ''' perform oadm manage-node scheduable ''' cmd = ['manage-node'] if node: cmd.extend(node) else: cmd.append('--selector={}'.format(selector)) cmd.append('--schedulable={}'.format(schedulable)) return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # noqa: E501 def _list_pods(self, node=None, selector=None, pod_selector=None): ''' perform oadm list pods node: the node in which to list pods selector: the label selector filter if provided pod_selector: the pod selector filter if provided ''' cmd = ['manage-node'] if node: cmd.extend(node) else: cmd.append('--selector={}'.format(selector)) if pod_selector: cmd.append('--pod-selector={}'.format(pod_selector)) cmd.extend(['--list-pods', '-o', 'json']) return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') # pylint: disable=too-many-arguments def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False): ''' perform oadm manage-node evacuate ''' cmd = ['manage-node'] if node: cmd.extend(node) else: cmd.append('--selector={}'.format(selector)) if dry_run: cmd.append('--dry-run') if pod_selector: cmd.append('--pod-selector={}'.format(pod_selector)) if grace_period: cmd.append('--grace-period={}'.format(int(grace_period))) if force: cmd.append('--force') cmd.append('--evacuate') return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') def _version(self): ''' return the openshift version''' return self.openshift_cmd(['version'], output=True, output_type='raw') def _import_image(self, url=None, name=None, tag=None): ''' perform image import ''' cmd = ['import-image'] image = '{0}'.format(name) if tag: image += ':{0}'.format(tag) cmd.append(image) if url: cmd.append('--from={0}/{1}'.format(url, image)) cmd.append('-n{0}'.format(self.namespace)) cmd.append('--confirm') return self.openshift_cmd(cmd) def _run(self, cmds, input_data): ''' Actually executes the command. This makes mocking easier. ''' curr_env = os.environ.copy() curr_env.update({'KUBECONFIG': self.kubeconfig}) proc = subprocess.Popen(cmds, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=curr_env) stdout, stderr = proc.communicate(input_data) return proc.returncode, stdout.decode('utf-8'), stderr.decode('utf-8') # pylint: disable=too-many-arguments,too-many-branches def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None): '''Base command for oc ''' cmds = [self.oc_binary] if oadm: cmds.append('adm') cmds.extend(cmd) if self.all_namespaces: cmds.extend(['--all-namespaces']) elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501 cmds.extend(['-n', self.namespace]) if self.verbose: print(' '.join(cmds)) try: returncode, stdout, stderr = self._run(cmds, input_data) except OSError as ex: returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex) rval = {"returncode": returncode, "cmd": ' '.join(cmds)} if output_type == 'json': rval['results'] = {} if output and stdout: try: rval['results'] = json.loads(stdout) except ValueError as verr: if "No JSON object could be decoded" in verr.args: rval['err'] = verr.args elif output_type == 'raw': rval['results'] = stdout if output else '' if self.verbose: print("STDOUT: {0}".format(stdout)) print("STDERR: {0}".format(stderr)) if 'err' in rval or returncode != 0: rval.update({"stderr": stderr, "stdout": stdout}) return rval class Utils(object): ''' utilities for openshiftcli modules ''' @staticmethod def _write(filename, contents): ''' Actually write the file contents to disk. This helps with mocking. ''' with open(filename, 'w') as sfd: sfd.write(str(contents)) @staticmethod def create_tmp_file_from_contents(rname, data, ftype='yaml'): ''' create a file in tmp with name and contents''' tmp = Utils.create_tmpfile(prefix=rname) if ftype == 'yaml': # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage # pylint: disable=no-member if hasattr(yaml, 'RoundTripDumper'): Utils._write(tmp, yaml.dump(data, Dumper=yaml.RoundTripDumper)) else: Utils._write(tmp, yaml.safe_dump(data, default_flow_style=False)) elif ftype == 'json': Utils._write(tmp, json.dumps(data)) else: Utils._write(tmp, data) # Register cleanup when module is done atexit.register(Utils.cleanup, [tmp]) return tmp @staticmethod def create_tmpfile_copy(inc_file): '''create a temporary copy of a file''' tmpfile = Utils.create_tmpfile('lib_openshift-') Utils._write(tmpfile, open(inc_file).read()) # Cleanup the tmpfile atexit.register(Utils.cleanup, [tmpfile]) return tmpfile @staticmethod def create_tmpfile(prefix='tmp'): ''' Generates and returns a temporary file name ''' with tempfile.NamedTemporaryFile(prefix=prefix, delete=False) as tmp: return tmp.name @staticmethod def create_tmp_files_from_contents(content, content_type=None): '''Turn an array of dict: filename, content into a files array''' if not isinstance(content, list): content = [content] files = [] for item in content: path = Utils.create_tmp_file_from_contents(item['path'] + '-', item['data'], ftype=content_type) files.append({'name': os.path.basename(item['path']), 'path': path}) return files @staticmethod def cleanup(files): '''Clean up on exit ''' for sfile in files: if os.path.exists(sfile): if os.path.isdir(sfile): shutil.rmtree(sfile) elif os.path.isfile(sfile): os.remove(sfile) @staticmethod def exists(results, _name): ''' Check to see if the results include the name ''' if not results: return False if Utils.find_result(results, _name): return True return False @staticmethod def find_result(results, _name): ''' Find the specified result by name''' rval = None for result in results: if 'metadata' in result and result['metadata']['name'] == _name: rval = result break return rval @staticmethod def get_resource_file(sfile, sfile_type='yaml'): ''' return the service file ''' contents = None with open(sfile) as sfd: contents = sfd.read() if sfile_type == 'yaml': # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage # pylint: disable=no-member if hasattr(yaml, 'RoundTripLoader'): contents = yaml.load(contents, yaml.RoundTripLoader) else: contents = yaml.safe_load(contents) elif sfile_type == 'json': contents = json.loads(contents) return contents @staticmethod def filter_versions(stdout): ''' filter the oc version output ''' version_dict = {} version_search = ['oc', 'openshift', 'kubernetes'] for line in stdout.strip().split('\n'): for term in version_search: if not line: continue if line.startswith(term): version_dict[term] = line.split()[-1] # horrible hack to get openshift version in Openshift 3.2 # By default "oc version in 3.2 does not return an "openshift" version if "openshift" not in version_dict: version_dict["openshift"] = version_dict["oc"] return version_dict @staticmethod def add_custom_versions(versions): ''' create custom versions strings ''' versions_dict = {} for tech, version in versions.items(): # clean up "-" from version if "-" in version: version = version.split("-")[0] if version.startswith('v'): versions_dict[tech + '_numeric'] = version[1:].split('+')[0] # "v3.3.0.33" is what we have, we want "3.3" versions_dict[tech + '_short'] = version[1:4] return versions_dict @staticmethod def openshift_installed(): ''' check if openshift is installed ''' import rpm transaction_set = rpm.TransactionSet() rpmquery = transaction_set.dbMatch("name", "atomic-openshift") return rpmquery.count() > 0 # Disabling too-many-branches. This is a yaml dictionary comparison function # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements @staticmethod def check_def_equal(user_def, result_def, skip_keys=None, debug=False): ''' Given a user defined definition, compare it with the results given back by our query. ''' # Currently these values are autogenerated and we do not need to check them skip = ['metadata', 'status'] if skip_keys: skip.extend(skip_keys) for key, value in result_def.items(): if key in skip: continue # Both are lists if isinstance(value, list): if key not in user_def: if debug: print('User data does not have key [%s]' % key) print('User data: %s' % user_def) return False if not isinstance(user_def[key], list): if debug: print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key])) return False if len(user_def[key]) != len(value): if debug: print("List lengths are not equal.") print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value))) print("user_def: %s" % user_def[key]) print("value: %s" % value) return False for values in zip(user_def[key], value): if isinstance(values[0], dict) and isinstance(values[1], dict): if debug: print('sending list - list') print(type(values[0])) print(type(values[1])) result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug) if not result: print('list compare returned false') return False elif value != user_def[key]: if debug: print('value should be identical') print(user_def[key]) print(value) return False # recurse on a dictionary elif isinstance(value, dict): if key not in user_def: if debug: print("user_def does not have key [%s]" % key) return False if not isinstance(user_def[key], dict): if debug: print("dict returned false: not instance of dict") return False # before passing ensure keys match api_values = set(value.keys()) - set(skip) user_values = set(user_def[key].keys()) - set(skip) if api_values != user_values: if debug: print("keys are not equal in dict") print(user_values) print(api_values) return False result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug) if not result: if debug: print("dict returned false") print(result) return False # Verify each key, value pair is the same else: if key not in user_def or value != user_def[key]: if debug: print("value not equal; user_def does not have key") print(key) print(value) if key in user_def: print(user_def[key]) return False if debug: print('returning true') return True class OpenShiftCLIConfig(object): '''Generic Config''' def __init__(self, rname, namespace, kubeconfig, options): self.kubeconfig = kubeconfig self.name = rname self.namespace = namespace self._options = options @property def config_options(self): ''' return config options ''' return self._options def to_option_list(self, ascommalist=''): '''return all options as a string if ascommalist is set to the name of a key, and the value of that key is a dict, format the dict as a list of comma delimited key=value pairs''' return self.stringify(ascommalist) def stringify(self, ascommalist=''): ''' return the options hash as cli params in a string if ascommalist is set to the name of a key, and the value of that key is a dict, format the dict as a list of comma delimited key=value pairs ''' rval = [] for key in sorted(self.config_options.keys()): data = self.config_options[key] if data['include'] \ and (data['value'] is not None or isinstance(data['value'], int)): if key == ascommalist: val = ','.join(['{}={}'.format(kk, vv) for kk, vv in sorted(data['value'].items())]) else: val = data['value'] rval.append('--{}={}'.format(key.replace('_', '-'), val)) return rval
apache-2.0
TatyanaAlex/tfukova
chapter_003/src/main/java/ru/job4j/testtask/Account.java
919
package ru.job4j.testtask; /** * Class Account. */ public class Account { public double value; public String requisites; /** * Constructor. * @param value amount of the money. * @param requisites user's account. */ public Account(double value, String requisites) { this.value = value; this.requisites = requisites; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Account account = (Account) o; if (value != account.value) { return false; } return requisites.equals(account.requisites); } @Override public int hashCode() { int result = (int) value; result = 31 * result + requisites.hashCode(); return result; } }
apache-2.0
bhecquet/seleniumRobot
core/src/main/java/com/seleniumtests/uipage/PageObject.java
75240
/** * Orignal work: Copyright 2015 www.seleniumtests.com * Modified work: Copyright 2016 www.infotel.com * Copyright 2017-2019 B.Hecquet * * 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.seleniumtests.uipage; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.time.Clock; import java.time.Instant; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.regex.Pattern; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.Dimension; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.NoAlertPresentException; import org.openqa.selenium.NoSuchWindowException; import org.openqa.selenium.PageLoadStrategy; import org.openqa.selenium.Point; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.UnhandledAlertException; import org.openqa.selenium.UnsupportedCommandException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.remote.UnreachableBrowserException; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import com.seleniumtests.core.SeleniumTestsContext; import com.seleniumtests.core.SeleniumTestsContextManager; import com.seleniumtests.core.TestTasks; import com.seleniumtests.customexception.ConfigurationException; import com.seleniumtests.customexception.CustomSeleniumTestsException; import com.seleniumtests.customexception.NotCurrentPageException; import com.seleniumtests.customexception.ScenarioException; import com.seleniumtests.driver.BrowserType; import com.seleniumtests.driver.CustomEventFiringWebDriver; import com.seleniumtests.driver.TestType; import com.seleniumtests.driver.WebUIDriver; import com.seleniumtests.driver.screenshots.ScreenShot; import com.seleniumtests.driver.screenshots.ScreenshotUtil; import com.seleniumtests.driver.screenshots.SnapshotCheckType; import com.seleniumtests.driver.screenshots.SnapshotCheckType.Control; import com.seleniumtests.driver.screenshots.SnapshotTarget; import com.seleniumtests.uipage.htmlelements.CheckBoxElement; import com.seleniumtests.uipage.htmlelements.Element; import com.seleniumtests.uipage.htmlelements.GenericPictureElement; import com.seleniumtests.uipage.htmlelements.HtmlElement; import com.seleniumtests.uipage.htmlelements.LinkElement; import com.seleniumtests.uipage.htmlelements.RadioButtonElement; import com.seleniumtests.uipage.htmlelements.SelectList; import com.seleniumtests.uipage.htmlelements.Table; import com.seleniumtests.uipage.htmlelements.UiLibraryRegistry; import com.seleniumtests.util.helper.WaitHelper; public class PageObject extends BasePage implements IPage { private static final String ERROR_ELEMENT_S_IS_NOT_AN_TABLE_ELEMENT = "Element %s is not an Table element"; private static final String ELEMENT_S_IS_NOT_AN_HTML_ELEMENT_SUBCLASS = "Element %s is not an HtmlElement subclass"; private static final String ERROR_ELEMENT_IS_PRESENT = "Element %s is present"; private boolean frameFlag = false; private String windowHandle = null; // store the window / tab on which this page is loaded private String url = null; private String suiteName = null; private String outputDirectory = null; private String htmlFilePath = null; private String imageFilePath = null; private boolean captureSnapshot = true; private static Map<String, List<String>> uiLibraries = Collections.synchronizedMap(new HashMap<>()); // the UI libraries used for searching elements. Allows to speed up search when several UI libs are declared (e.g for SelectList) private ScreenshotUtil screenshotUtil; private Clock systemClock; private PageLoadStrategy pageLoadStrategy; public static final String HTML_UI_LIBRARY = "html"; private static final String ERROR_ELEMENT_NOT_PRESENT = "Element %s is not present"; /** * Constructor for non-entry point page. The control is supposed to have reached the page from other API call. * * @throws Exception */ public PageObject() { this(null, (String)null); } public PageObject(List<String> uiLibs) { this(null, null, uiLibs); } /** * Constructor for non-entry point page. The control is supposed to have reached the page from other API call. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @throws IOException * * @throws Exception */ public PageObject(final HtmlElement pageIdentifierElement) { this(pageIdentifierElement, (String)null); } /** * Base Constructor. * Represents a page on our web site or mobile application. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @param uiLibs List of UI libraries that may be used in this page (normally one). e.g: 'Angular'. These libs must have been registred by HtmlElements. Failing to give the right one will display the list of available * @throws IOException * * @throws Exception */ public PageObject(final HtmlElement pageIdentifierElement, List<String> uiLibs) { this(pageIdentifierElement, null, uiLibs); } /** * Base Constructor. * Represents a page on our web site or mobile application. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @param url the URL to which we should connect. May be null if we do not want to go to a specific URL * @throws IOException * * @throws Exception */ public PageObject(final HtmlElement pageIdentifierElement, final String url) { this(pageIdentifierElement, url, new ArrayList<>()); } /** * Base Constructor. * Represents a page on our web site or mobile application. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @param url the URL to which we should connect. May be null if we do not want to go to a specific URL * @param uiLibs List of UI libraries that may be used in this page (normally one). e.g: 'Angular'. These libs must have been registred by HtmlElements. Failing to give the right one will display the list of available * @throws IOException * * @throws Exception */ public PageObject(final HtmlElement pageIdentifierElement, final String url, List<String> uiLibs) { this(pageIdentifierElement, url, SeleniumTestsContextManager.getThreadContext().getBrowser(), WebUIDriver.getCurrentWebUiDriverName(), null, uiLibs); } /** * Base Constructor. * Represents a page on our web site or mobile application. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @param url the URL to which we should connect. May be null if we do not want to go to a specific URL * @param pageLoadStrategy whether to wait for the page to load or not (this is complementary to Selenium driver strategy. If not null, it will override selenium * @throws IOException * * @throws Exception */ public PageObject(final HtmlElement pageIdentifierElement, final String url, PageLoadStrategy pageLoadStrategy) { this(pageIdentifierElement, url, SeleniumTestsContextManager.getThreadContext().getBrowser(), WebUIDriver.getCurrentWebUiDriverName(), null, pageLoadStrategy, true); } /** * Base Constructor. * Represents a page on our web site or mobile application. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @param url the URL to which we should connect. May be null if we do not want to go to a specific URL * @param pageLoadStrategy whether to wait for the page to load or not (this is complementary to Selenium driver strategy. If not null, it will override selenium * @param uiLibs List of UI libraries that may be used in this page (normally one). e.g: 'Angular'. These libs must have been registred by HtmlElements. Failing to give the right one will display the list of available * @throws IOException * * @throws Exception */ public PageObject(final HtmlElement pageIdentifierElement, final String url, PageLoadStrategy pageLoadStrategy, List<String> uiLibs) { this(pageIdentifierElement, url, SeleniumTestsContextManager.getThreadContext().getBrowser(), WebUIDriver.getCurrentWebUiDriverName(), null, pageLoadStrategy, true, uiLibs); } /** * Base Constructor. * Represents a page on our web site or mobile application. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @param url the URL to which we should connect. May be null if we do not want to go to a specific URL * @param pageLoadStrategy whether to wait for the page to load or not (this is complementary to Selenium driver strategy. If not null, it will override selenium * @param captureSnapshot if true, snapshot will be captured after page loading. 'false' should only be used when capturing snapshot interfere with a popup alert * @throws IOException * * @throws Exception */ public PageObject(final HtmlElement pageIdentifierElement, final String url, PageLoadStrategy pageLoadStrategy, boolean captureSnapshot) { this(pageIdentifierElement, url, SeleniumTestsContextManager.getThreadContext().getBrowser(), WebUIDriver.getCurrentWebUiDriverName(), null, pageLoadStrategy, captureSnapshot); } /** * Base Constructor. * Represents a page on our web site or mobile application. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @param url the URL to which we should connect. May be null if we do not want to go to a specific URL * @param pageLoadStrategy whether to wait for the page to load or not (this is complementary to Selenium driver strategy. If not null, it will override selenium * @param captureSnapshot if true, snapshot will be captured after page loading. 'false' should only be used when capturing snapshot interfere with a popup alert * @param uiLibs List of UI libraries that may be used in this page (normally one). e.g: 'Angular'. These libs must have been registred by HtmlElements. Failing to give the right one will display the list of available * @throws IOException * * @throws Exception */ public PageObject(final HtmlElement pageIdentifierElement, final String url, PageLoadStrategy pageLoadStrategy, boolean captureSnapshot, List<String> uiLibs) { this(pageIdentifierElement, url, SeleniumTestsContextManager.getThreadContext().getBrowser(), WebUIDriver.getCurrentWebUiDriverName(), null, pageLoadStrategy, captureSnapshot, uiLibs); } /** * Base Constructor. * Represents a page on our web site or mobile application. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @param url the URL to which we should connect. May be null if we do not want to go to a specific URL * @param browserType the new browser type to create * @param driverName a logical name to give to the created driver * @param attachExistingDriverPort if we need to attach to an existing browser instead of creating one, then specify the port here * @throws IOException * * @throws Exception */ public PageObject(HtmlElement pageIdentifierElement, String url, BrowserType browserType, String driverName, Integer attachExistingDriverPort) { this(pageIdentifierElement, url, browserType, driverName, attachExistingDriverPort, null, true); } /** * Base Constructor. * Represents a page on our web site or mobile application. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @param url the URL to which we should connect. May be null if we do not want to go to a specific URL * @param browserType the new browser type to create * @param driverName a logical name to give to the created driver * @param attachExistingDriverPort if we need to attach to an existing browser instead of creating one, then specify the port here * @param uiLibs List of UI libraries that may be used in this page (normally one). e.g: 'Angular'. These libs must have been registred by HtmlElements. Failing to give the right one will display the list of available * @throws IOException * * @throws Exception */ public PageObject(HtmlElement pageIdentifierElement, String url, BrowserType browserType, String driverName, Integer attachExistingDriverPort, List<String> uiLibs) { this(pageIdentifierElement, url, browserType, driverName, attachExistingDriverPort, null, true, uiLibs); } /** * Base Constructor. * Represents a page on our web site or mobile application. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @param url the URL to which we should connect. May be null if we do not want to go to a specific URL * @param browserType the new browser type to create * @param driverName a logical name to give to the created driver * @param attachExistingDriverPort if we need to attach to an existing browser instead of creating one, then specify the port here * @param captureSnapshot if true, snapshot will be captured after page loading. 'false' should only be used when capturing snapshot interfere with a popup alert * @throws IOException * * @throws Exception */ public PageObject(HtmlElement pageIdentifierElement, String url, BrowserType browserType, String driverName, Integer attachExistingDriverPort, boolean captureSnapshot) { this(pageIdentifierElement, url, browserType, driverName, attachExistingDriverPort, null, captureSnapshot); } /** * Base Constructor. * Represents a page on our web site or mobile application. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @param url the URL to which we should connect. May be null if we do not want to go to a specific URL * @param browserType the new browser type to create * @param driverName a logical name to give to the created driver * @param attachExistingDriverPort if we need to attach to an existing browser instead of creating one, then specify the port here * @param captureSnapshot if true, snapshot will be captured after page loading. 'false' should only be used when capturing snapshot interfere with a popup alert * @param uiLibs List of UI libraries that may be used in this page (normally one). e.g: 'Angular'. These libs must have been registred by HtmlElements. Failing to give the right one will display the list of available * @throws IOException * * @throws Exception */ public PageObject(HtmlElement pageIdentifierElement, String url, BrowserType browserType, String driverName, Integer attachExistingDriverPort, boolean captureSnapshot, List<String> uiLibs) { this(pageIdentifierElement, url, browserType, driverName, attachExistingDriverPort, null, captureSnapshot, uiLibs); } /** * Base Constructor. * Represents a page on our web site or mobile application. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @param url the URL to which we should connect. May be null if we do not want to go to a specific URL * @param browserType the new browser type to create * @param driverName a logical name to give to the created driver * @param attachExistingDriverPort if we need to attach to an existing browser instead of creating one, then specify the port here * @param pageLoadStrategy whether to wait for the page to load or not (this is complementary to Selenium driver strategy. If not null, it will override selenium * @param captureSnapshot if true, snapshot will be captured after page loading. 'false' should only be used when capturing snapshot interfere with a popup alert * @throws IOException * * @throws Exception */ public PageObject(HtmlElement pageIdentifierElement, String url, BrowserType browserType, String driverName, Integer attachExistingDriverPort, PageLoadStrategy pageLoadStrategy, boolean captureSnapshot) { this(pageIdentifierElement, url, browserType, driverName, attachExistingDriverPort, pageLoadStrategy, captureSnapshot, new ArrayList<>()); } /** * Base Constructor. * Represents a page on our web site or mobile application. * * @param pageIdentifierElement The element to search for so that we check we are on the right page. * May be null if we do not want to check we are on the page * @param url the URL to which we should connect. May be null if we do not want to go to a specific URL * @param browserType the new browser type to create * @param driverName a logical name to give to the created driver * @param attachExistingDriverPort if we need to attach to an existing browser instead of creating one, then specify the port here * @param pageLoadStrategy whether to wait for the page to load or not (this is complementary to Selenium driver strategy. If not null, it will override selenium * @param captureSnapshot if true, snapshot will be captured after page loading. 'false' should only be used when capturing snapshot interfere with a popup alert * @param uiLibs List of UI libraries that may be used in this page (normally one). e.g: 'Angular'. These libs must have been registred by HtmlElements. Failing to give the right one will display the list of available * @throws IOException * * @throws Exception */ public PageObject(HtmlElement pageIdentifierElement, String url, BrowserType browserType, String driverName, Integer attachExistingDriverPort, PageLoadStrategy pageLoadStrategy, boolean captureSnapshot, List<String> uiLibs) { for (String uiLib: uiLibs) { addUiLibrary(uiLib); } systemClock = Clock.systemUTC(); this.captureSnapshot = captureSnapshot; if (pageLoadStrategy == null) { this.pageLoadStrategy = robotConfig().getPageLoadStrategy(); } else { this.pageLoadStrategy = pageLoadStrategy; } Calendar start = Calendar.getInstance(); start.setTime(new Date()); if (SeleniumTestsContextManager.getGlobalContext() != null && SeleniumTestsContextManager.getGlobalContext().getTestNGContext() != null) { suiteName = SeleniumTestsContextManager.getGlobalContext().getTestNGContext().getSuite().getName(); outputDirectory = SeleniumTestsContextManager.getGlobalContext().getTestNGContext().getOutputDirectory(); } // set the URL to context if it has been provided. This will then be used on Edge(IE-mode) creation to avoid cross zone boundaries if (SeleniumTestsContextManager.getThreadContext() != null && url != null) { SeleniumTestsContextManager.getThreadContext().setInitialUrl(url); } // creates the driver and switch to it. It may be done twice as when the driver is created, we automatically switch to it, but in case driver // is already created, driver = WebUIDriver.getWebDriver(true, browserType, driverName, attachExistingDriverPort); if (driver == null && url != null) { throw new ConfigurationException("driver is null, 'browser' configuration may be empty"); } screenshotUtil = new ScreenshotUtil(driver); // open page openPage(url); // in case browser has been created outside of selenium and we attach to it, get initial window handles if (driver != null && attachExistingDriverPort != null && url == null) { ((CustomEventFiringWebDriver)driver).updateWindowsHandles(); } assertCurrentPage(false, pageIdentifierElement); Calendar end = Calendar.getInstance(); start.setTime(new Date()); long startTime = start.getTimeInMillis(); long endTime = end.getTimeInMillis(); if ((endTime - startTime) / 1000 > 0) { logger.log("Open web page in :" + (endTime - startTime) / 1000 + "seconds"); } } /** * Set the uiLibrary to use as a preferred library. * For example, by default, for SelectList, all UILibraries are tested before searching the element. With this setting, it's possible to make one of them preferred for this page * @param uiLibrary */ private synchronized void addUiLibrary(String uiLibrary) { String className = getClass().getCanonicalName(); uiLibraries.computeIfAbsent(className, k -> new ArrayList<>()); if (UiLibraryRegistry.getUiLibraries().contains(uiLibrary) && !uiLibraries.get(className).contains(uiLibrary)) { uiLibraries.get(className).add(uiLibrary); } else { throw new ScenarioException(String.format("uiLibrary '%s' has not been registered for any element. Available uiLibraries are: %s", uiLibrary, StringUtils.join(UiLibraryRegistry.getUiLibraries()))); } } protected void setUrl(final String openUrl) { this.url = openUrl; } public String getHtmlFilePath() { return htmlFilePath; } @Override public String getHtmlSource() { return driver.getPageSource(); } public String getImageFilePath() { return imageFilePath; } @Override public String getLocation() { return driver.getCurrentUrl(); } /** * Open page * Wait for page loading * @param url * @throws IOException */ private void openPage(String url) { if (url != null) { open(url); ((CustomEventFiringWebDriver)driver).updateWindowsHandles(); } // Wait for page load is applicable only for web test // When running tests on an iframe embedded site then test will fail if this command is not used // in case of mobile application, only capture screenshot if (SeleniumTestsContextManager.isWebTest()) { waitForPageToLoad(); } else if (SeleniumTestsContextManager.isAppTest() && captureSnapshot) { capturePageSnapshot(); } } @Override protected void assertCurrentPage(boolean log) { // not used } @Override protected void assertCurrentPage(boolean log, HtmlElement pageIdentifierElement) { if (pageIdentifierElement != null && !pageIdentifierElement.isElementPresent()) { throw new NotCurrentPageException(getClass().getCanonicalName() + " is not the current page.\nPageIdentifierElement " + pageIdentifierElement.toString() + " is not found."); } } /** * Get parameter from configuration * * @param key * * @return String */ public static String param(String key) { return TestTasks.param(key); } /** * Get parameter from configuration using pattern * If multiple variables match the pattern, only one is returned * @param keyPattern Pattern for searching key. If null, no filtering will be done on key * @return */ public static String param(Pattern keyPattern) { return TestTasks.param(keyPattern); } /** * Get parameter from configuration using pattern * If multiple variables match the pattern, only one is returned * @param keyPattern Pattern for searching key. If null, no filtering will be done on key * @param valuePattern Pattern for searching value. If null, no filtering will be done on value * @return */ public static String param(Pattern keyPattern, Pattern valuePattern) { return TestTasks.param(keyPattern, valuePattern); } /** * returns the robot configuration * @return */ public SeleniumTestsContext robotConfig() { return SeleniumTestsContextManager.getThreadContext(); } /** * Add step inside a page * @param stepName * @param passwordsToMask array of strings that must be replaced by '*****' in reports */ public void addStep(String stepName) { TestTasks.addStep(stepName); } public void addStep(String stepName, String ... passwordToMask) { TestTasks.addStep(stepName, passwordToMask); } /** * Method for creating or updating a variable on the seleniumRobot server (or locally if server is not used) * Moreover, created custom variable is specific to tuple (application, version, test environment) * Variable will be stored as a variable of the current tested application * @param key name of the param * @param value value of the parameter (or new value if we update it) */ public void createOrUpdateParam(String key, String value) { TestTasks.createOrUpdateParam(key, value); } /** * Method for creating or updating a variable locally. If selenium server is not used, there is no difference with 'createOrUpdateParam'. * If seleniumRobot server is used, then, this method will only change variable value locally, not updating the remote one * @param key * @param newValue */ public void createOrUpdateLocalParam(String key, String newValue) { TestTasks.createOrUpdateLocalParam(key, newValue); } /** * Method for creating or updating a variable on the seleniumRobot server ONLY. This will raise a ScenarioException if variables are get from * env.ini file * Moreover, created custom variable is specific to tuple (application, version, test environment) * @param key name of the param * @param newValue value of the parameter (or new value if we update it) * @param specificToVersion if true, this param will be stored on server with a reference to the application version. This will have no effect if changing a * current variable. */ public void createOrUpdateParam(String key, String value, boolean specificToVersion) { TestTasks.createOrUpdateParam(key, value, specificToVersion); } /** * Method for creating or updating a variable. If variables are get from seleniumRobot server, this method will update the value on the server * Moreover, created custom variable is specific to tuple (application, version, test environment) * @param key name of the param * @param newValue value of the parameter (or new value if we update it) * @param specificToVersion if true, this param will be stored on server with a reference to the application version. This will have no effect if changing a * current variable. * @param timeToLive if > 0, this variable will be destroyed after some days (defined by variable). A positive value is mandatory if reservable is set to true * because multiple variable can be created * @param reservable if true, this variable will be set as reservable in variable server. This means it can be used by only one test at the same time * True value also means that multiple variables of the same name can be created and a timeToLive > 0 MUST be provided so that server database is regularly purged */ public void createOrUpdateParam(String key, String value, boolean specificToVersion, int timeToLive, boolean reservable) { TestTasks.createOrUpdateParam(key, value, specificToVersion, timeToLive, reservable); } /** * In case the scenario uses several drivers, switch to one or another using this method, so that any new calls will go through this driver * @param driverName */ public WebDriver switchToDriver(String driverName) { driver = TestTasks.switchToDriver(driverName); return driver; } /** * Capture the whole page, scrolling if necessary * @param <T> * @return */ public <T extends PageObject> T capturePageSnapshot() { capturePageSnapshot(null); return (T)this; } /** * Capture only the visible part of the page, no scrolling will be done * @param <T> * @return */ public <T extends PageObject> T captureViewportSnapshot() { captureViewportSnapshot(null); return (T)this; } /** * Capture the desktop * @param <T> * @return */ public <T extends PageObject> T captureDesktopSnapshot() { captureDesktopSnapshot(null); return (T)this; } /** * Capture a page snapshot for storing in test step * @param snapshotName the snapshot name */ public void capturePageSnapshot(String snapshotName) { capturePageSnapshot(snapshotName, SnapshotCheckType.FALSE); } /** * Capture a viewport snapshot for storing in test step * @param snapshotName the snapshot name */ public void captureViewportSnapshot(String snapshotName) { captureViewportSnapshot(snapshotName, SnapshotCheckType.FALSE); } /** * Capture a viewport snapshot for storing in test step * @param snapshotName the snapshot name */ public void captureDesktopSnapshot(String snapshotName) { captureDesktopSnapshot(snapshotName, SnapshotCheckType.FALSE); } /** * Capture a page snapshot for storing in test step * @param snapshotName the snapshot name * @param checkSnapshot if true, will send snapshot to server (when seleniumRobot is configured for this) for comparison */ public void capturePageSnapshot(String snapshotName, SnapshotCheckType checkSnapshot) { ScreenShot screenShot = screenshotUtil.capture(SnapshotTarget.PAGE, ScreenShot.class, computeScrollDelay(checkSnapshot)); // check SnapshotCheckType configuration is compatible with the snapshot checkSnapshot.check(SnapshotTarget.PAGE); storeSnapshot(snapshotName, screenShot, checkSnapshot); } /** * Capture a page snapshot for storing in test step * @param snapshotName the snapshot name * @param checkSnapshot if true, will send snapshot to server (when seleniumRobot is configured for this) for comparison */ public void captureViewportSnapshot(String snapshotName, SnapshotCheckType checkSnapshot) { ScreenShot screenShot = screenshotUtil.capture(SnapshotTarget.VIEWPORT, ScreenShot.class); // check SnapshotCheckType configuration is compatible with the snapshot checkSnapshot.check(SnapshotTarget.VIEWPORT); storeSnapshot(snapshotName, screenShot, checkSnapshot); } /** * Capture a desktop snapshot (only the main screen in multiple screen environment) for storing in test step * @param snapshotName the snapshot name * @param checkSnapshot if true, will send snapshot to server (when seleniumRobot is configured for this) for comparison */ public void captureDesktopSnapshot(String snapshotName, SnapshotCheckType checkSnapshot) { ScreenShot screenShot = screenshotUtil.capture(SnapshotTarget.MAIN_SCREEN, ScreenShot.class); storeSnapshot(snapshotName, screenShot, checkSnapshot); } /** * Returns 0 if snapshot is only taken for test report. Else, returns the defined scrollDelay from params * @param checkSnapshot */ private int computeScrollDelay(SnapshotCheckType checkSnapshot) { if (checkSnapshot.getControl() != Control.NONE) { return robotConfig().getSnapshotScrollDelay().intValue(); } else { return 0; } } /** * Capture a portion of the page by giving the element to capture * @param element the element to capture */ public void captureElementSnapshot(WebElement element) { captureElementSnapshot(null, element); } /** * Capture a portion of the page by giving the element to capture * @param snapshotName the snapshot name * @param element the element to capture */ public void captureElementSnapshot(String snapshotName, WebElement element) { captureElementSnapshot(snapshotName, element, SnapshotCheckType.FALSE); } /** * Capture a portion of the page by giving the element to capture * @param snapshotName the snapshot name * @param element the element to capture * @param checkSnapshot if true, will send snapshot to server (when seleniumRobot is configured for this) for comparison */ public void captureElementSnapshot(String snapshotName, WebElement element, SnapshotCheckType checkSnapshot) { SnapshotTarget snapshotTarget = new SnapshotTarget(element); ScreenShot screenShot = screenshotUtil.capture(snapshotTarget, ScreenShot.class, computeScrollDelay(checkSnapshot)); // check SnapshotCheckType configuration is compatible with the snapshot checkSnapshot.check(snapshotTarget); storeSnapshot(snapshotName, screenShot, checkSnapshot); } /** * Store the snapshot to test step * Check if name is provided, in case we need to compare it to a baseline on server * @param snapshotName * @param screenShot * @param checkSnapshot */ private void storeSnapshot(String snapshotName, ScreenShot screenShot, SnapshotCheckType checkSnapshot) { if ((snapshotName == null || snapshotName.isEmpty()) && !checkSnapshot.equals(SnapshotCheckType.FALSE)) { throw new ScenarioException("Cannot check snapshot if no name is provided"); } if (screenShot != null) { // may be null if user request not to take snapshots if (screenShot.getHtmlSourcePath() != null) { htmlFilePath = screenShot.getHtmlSourcePath().replace(suiteName, outputDirectory); } if (screenShot.getImagePath() != null) { imageFilePath = screenShot.getImagePath().replace(suiteName, outputDirectory); } if (snapshotName != null) { screenShot.setTitle(snapshotName); } logger.logScreenshot(screenShot, snapshotName, checkSnapshot); } // store the window / tab on which this page is loaded windowHandle = driver.getWindowHandle(); } /** * Get focus on this page, using the handle we stored when creating it * When called, you should write {@code myPage.<MyPageClassName>getFocus().someMethodOfMyPage();} * @return */ @SuppressWarnings("unchecked") public <T extends PageObject> T getFocus() { selectWindow(windowHandle); return (T)this; } /** * Close a PageObject. This method can be called when a web session opens several pages and one of them has to be closed * In case there are multiple windows opened, switch back to the previous window in the list * * @throws NotCurrentPageException */ public final void close() { if (WebUIDriver.getWebDriver(false) == null) { return; } boolean isMultipleWindow = false; List<String> handles = new ArrayList<>(driver.getWindowHandles()); if (handles.size() > 1) { isMultipleWindow = true; } internalLogger.debug("Current handles: " + handles); try { logger.info("close web page: " + getTitle()); driver.close(); } catch (WebDriverException ignore) { internalLogger.info("Error closing driver: " + ignore.getMessage()); } // wait a bit before going back to main window WaitHelper.waitForSeconds(2); try { if (isMultipleWindow) { selectPreviousOrMainWindow(handles); } else { WebUIDriver.setWebDriver(null); } } catch (UnreachableBrowserException ex) { WebUIDriver.setWebDriver(null); } } private void selectPreviousOrMainWindow(List<String> handles) { try { selectWindow(handles.get(handles.indexOf(windowHandle) - 1)); } catch (IndexOutOfBoundsException | NoSuchWindowException e) { selectMainWindow(); } } /** * Close the current tab / window which leads to the previous window / tab in the list. * This uses the default constructor which MUST be available * @param previousPage the page we go back to, so that we can check we are on the right page * @return */ public <T extends PageObject> T close(Class<T> previousPage) { close(); try { return previousPage.getConstructor().newInstance(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new ScenarioException("Cannot check for previous page: " + e.getMessage(), e); } } /** * Drags an element a certain distance and then drops it. * * @param element to dragAndDrop * @param offsetX in pixels from the current location to which the element should be moved, e.g., 70 * @param offsetY in pixels from the current location to which the element should be moved, e.g., -300 */ public void dragAndDrop(final HtmlElement element, final int offsetX, final int offsetY) { new Actions(driver).dragAndDropBy( element.getElement(), offsetX, offsetY).perform(); } /** * Get the number of elements in page * @param element * @return */ public final int getElementCount(final HtmlElement element) { return element.findElements().size(); } public int getTimeout() { return SeleniumTestsContextManager.getThreadContext().getWebSessionTimeout(); } @Override public String getTitle() { return driver.getTitle(); } public String getUrl() { return url; } public String getCanonicalURL() { return new LinkElement("Canonical URL", By.cssSelector("link[rel=canonical]")).getAttribute("href"); } /** * Returns the value of the named cookie * @param name name of the cookie * @return */ public final String getCookieByName(final String name) { if (driver.manage().getCookieNamed(name) == null) { return null; } return driver.manage().getCookieNamed(name).getValue(); } /** * Check if named cookie is present * @param name name of the cookie * @return */ public boolean isCookiePresent(final String name) { return getCookieByName(name) != null; } private void open(final String url) { setUrl(url); try { // Navigate to app URL for browser test if (SeleniumTestsContextManager.isWebTest()) { setWindowToRequestedSize(); driver.navigate().to(url); } } catch (UnreachableBrowserException e) { // recreate the driver without recreating the enclosing WebUiDriver driver = WebUIDriver.getWebUIDriver(false).createWebDriver(); if (SeleniumTestsContextManager.isWebTest()) { setWindowToRequestedSize(); driver.navigate().to(url); } } catch (UnsupportedCommandException e) { logger.error("get UnsupportedCommandException, retry"); // recreate the driver without recreating the enclosing WebUiDriver driver = WebUIDriver.getWebUIDriver(false).createWebDriver(); if (SeleniumTestsContextManager.isWebTest()) { setWindowToRequestedSize(); driver.navigate().to(url); } } catch (org.openqa.selenium.TimeoutException ex) { logger.error("got time out when loading " + url + ", ignored"); } catch (org.openqa.selenium.UnhandledAlertException ex) { logger.error("got UnhandledAlertException, retry"); driver.navigate().to(url); } catch (WebDriverException e) { internalLogger.error(e); throw new CustomSeleniumTestsException(e); } } public final void maximizeWindow() { try { // app test are not compatible with window if (SeleniumTestsContextManager.getThreadContext().getTestType().family() == TestType.APP || SeleniumTestsContextManager.getThreadContext().getBrowser() == BrowserType.BROWSER) { return; } driver.manage().window().maximize(); } catch (Exception ex) { try { ((JavascriptExecutor) driver).executeScript( "if (window.screen){window.moveTo(0, 0);window.resizeTo(window.screen.availWidth,window.screen.availHeight);}"); } catch (Exception ignore) { logger.log("Unable to maximize browser window. Exception occured: " + ignore.getMessage()); } } } /** * On init set window to size requested by user. Window is maximized if no size is set */ public final void setWindowToRequestedSize() { if (!SeleniumTestsContextManager.isWebTest()) { return; } Integer width = SeleniumTestsContextManager.getThreadContext().getViewPortWidth(); Integer height = SeleniumTestsContextManager.getThreadContext().getViewPortHeight(); if (width == null || height == null) { maximizeWindow(); } else { resizeTo(width, height); } } /** * Resize window to given dimensions. * * @param width * @param height */ public final void resizeTo(final int width, final int height) { // app test are not compatible with window if (SeleniumTestsContextManager.isAppTest()) { return; } try { Dimension setSize = new Dimension(width, height); driver.manage().window().setPosition(new Point(0, 0)); int retries = 5; for (int i=0; i < retries; i++) { driver.manage().window().setSize(setSize); Dimension viewPortSize = ((CustomEventFiringWebDriver)driver).getViewPortDimensionWithoutScrollbar(); if (viewPortSize.height == height && viewPortSize.width == width) { break; } else { setSize = new Dimension(2 * width - viewPortSize.width, 2 * height - viewPortSize.height); } } } catch (Exception ex) { internalLogger.error(ex); } } /** * @deprecated useless * @return */ @Deprecated public boolean isFrame() { return frameFlag; } /** * @deprecated useless * @return */ @Deprecated public final void selectFrame(final Integer index) { driver.switchTo().frame(index); frameFlag = true; } /** * @deprecated useless * @return */ @Deprecated public final void selectFrame(final By by) { WebElement element = driver.findElement(by); driver.switchTo().frame(element); frameFlag = true; } /** * @deprecated useless * @return */ @Deprecated public final void selectFrame(final String locator) { driver.switchTo().frame(locator); frameFlag = true; } /** * @deprecated useless * @return */ @Deprecated public final void exitFrame() { driver.switchTo().defaultContent(); frameFlag = false; } /** * Switch to first window in the list */ public final void selectMainWindow() { selectWindow(0); } /** * Switch to nth window in the list * It may not reflect the order of tabs in browser if some windows have been closed before * @param index index of the window */ public final void selectWindow(final int index) { // app test are not compatible with window if (SeleniumTestsContextManager.isAppTest()) { throw new ScenarioException("Application are not compatible with Windows"); } driver.switchTo().window((String) driver.getWindowHandles().toArray()[index]); WaitHelper.waitForSeconds(1); } /** * Selects the first unknown window. To use we an action creates a new window or tab * @return */ public final String selectNewWindow() { return selectNewWindow(SeleniumTestsContextManager.getThreadContext().getExplicitWaitTimeout() * 1000); } /** * Selects the first unknown window. To use immediately after an action creates a new window or tab * Each time we do a click, but just before it (selenium click, JS click or action click), we record the list of windows. * I a new window or tab is displayed, we select it. * @param waitMs wait for N milliseconds before raising error * @return */ public final String selectNewWindow(int waitMs) { // app test are not compatible with window if (SeleniumTestsContextManager.getThreadContext().getTestType().family() == TestType.APP) { throw new ScenarioException("Application are not compatible with Windows"); } // Keep the name of the current window handle before switching // sometimes, our action made window disappear String mainWindowHandle; try { mainWindowHandle = driver.getWindowHandle(); } catch (Exception e) { mainWindowHandle = ""; } internalLogger.debug("Current handle: " + mainWindowHandle); // wait for window to be displayed Instant end = systemClock.instant().plusMillis(waitMs + 250L); Set<String> handles = new TreeSet<>(); boolean found = false; while (end.isAfter(systemClock.instant()) && !found) { handles = driver.getWindowHandles(); internalLogger.debug("All handles: " + handles.toString()); for (String handle: handles) { // we already know this handle if (getCurrentHandles().contains(handle)) { continue; } selectWindow(handle); // wait for a valid address String address = ""; Instant endLoad = systemClock.instant().plusMillis(5000); while (address.isEmpty() && endLoad.isAfter(systemClock.instant())) { address = driver.getCurrentUrl(); } // make window display in foreground // TODO: reactivate feature try { // Point windowPosition = driver.manage().window().getPosition(); // org.openqa.selenium.interactions.Mouse mouse = ((HasInputDevices) driver).getMouse(); // mouse.click(); // Mouse mouse = new DesktopMouse(); // mouse.click(new DesktopScreenRegion(Math.max(0, windowPosition.x) + driver.manage().window().getSize().width / 2, Math.max(0, windowPosition.y) + 5, 2, 2).getCenter()); } catch (Exception e) { internalLogger.warn("error while giving focus to window"); } found = true; break; } WaitHelper.waitForMilliSeconds(300); } // check window has changed if (waitMs > 0 && mainWindowHandle.equals(driver.getWindowHandle())) { throw new CustomSeleniumTestsException("new window has not been found. Handles: " + handles); } return mainWindowHandle; } /** * Switch to the default content */ public void switchToDefaultContent() { try { driver.switchTo().defaultContent(); } catch (UnhandledAlertException e) { logger.warn("Alert found, you should handle it"); } } private void waitForPageToLoad() { try { if (pageLoadStrategy == PageLoadStrategy.NORMAL) { new WebDriverWait(driver, 5).until(ExpectedConditions.jsReturnsValue("if (document.readyState === \"complete\") { return \"ok\"; }")); } else if (pageLoadStrategy == PageLoadStrategy.EAGER) { new WebDriverWait(driver, 5).until(ExpectedConditions.jsReturnsValue("if (document.readyState === \"interactive\") { return \"ok\"; }")); } } catch (TimeoutException e) { // nothing } // populate page info if (captureSnapshot) { try { capturePageSnapshot(); } catch (Exception ex) { internalLogger.error(ex); throw ex; } } } public Alert waitForAlert(int waitInSeconds) { Instant end = systemClock.instant().plusSeconds(waitInSeconds); while (end.isAfter(systemClock.instant())) { try { return driver.switchTo().alert(); } catch (NoAlertPresentException e) { WaitHelper.waitForSeconds(1); } catch (NoSuchWindowException e) { return null; } } return null; } /** * get the name of the PageObject that made the call * * @param stack : the stacktrace of the caller */ public static String getCallingPage(StackTraceElement[] stack) { String page = null; Class<?> stackClass = null; //find the PageObject Loader for(int i=0; i<stack.length;i++){ try{ stackClass = Class.forName(stack[i].getClassName()); } catch (ClassNotFoundException e){ continue; } if (PageObject.class.isAssignableFrom(stackClass)){ page = stack[i].getClassName(); } } return page; } public String cancelConfirmation() { Alert alert = getAlert(); String seenText = alert.getText(); alert.dismiss(); driver.switchTo().defaultContent(); return seenText; } /** * Returns an Element object based on field name * @return */ private Element getElement(String fieldName) { try { Field field = getClass().getDeclaredField(fieldName); field.setAccessible(true); return (Element)field.get(this); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { throw new ScenarioException(String.format("Field %s does not exist in class %s", fieldName, getClass().getSimpleName())); } } // --------------------- Actions -------------------------- @GenericStep public <T extends PageObject> T goBack() { driver.navigate().back(); return (T)this; } @GenericStep public <T extends PageObject> T goForward() { driver.navigate().forward(); return (T)this; } @GenericStep public <T extends PageObject> T sendKeysToField(String fieldName, String value) { Element element = getElement(fieldName); element.sendKeys(value); return (T)this; } @GenericStep public <T extends PageObject> T sendRandomKeysToField(Integer charNumber, String fieldName) { Element element = getElement(fieldName); element.sendKeys(RandomStringUtils.random(charNumber, true, false)); return (T)this; } @SuppressWarnings("unchecked") @GenericStep public <T extends PageObject> T clear(String fieldName) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { ((HtmlElement) element).clear(); } else { throw new ScenarioException(String.format(ELEMENT_S_IS_NOT_AN_HTML_ELEMENT_SUBCLASS, fieldName)); } return (T)this; } @SuppressWarnings("unchecked") @GenericStep public <T extends PageObject> T selectOption(String fieldName, String value) { Element element = getElement(fieldName); if (element instanceof SelectList) { ((SelectList)element).selectByText(value); } else { throw new ScenarioException(String.format("Element %s is not an SelectList", fieldName)); } return (T)this; } @SuppressWarnings("unchecked") @GenericStep public <T extends PageObject> T click(String fieldName) { Element element = getElement(fieldName); element.click(); return (T)this; } /** * Click on element and creates a new PageObject of the type of following page * @param fieldName * @param nextPage Class of the next page * @return * @throws SecurityException * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InstantiationException */ @GenericStep public <T extends PageObject> T clickAndChangeToPage(String fieldName, Class<T> nextPage) { Element element = getElement(fieldName); element.click(); try { return nextPage.getConstructor().newInstance(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new ScenarioException(String.format("Cannot switch to next page %s, maybe default constructor does not exist", nextPage.getSimpleName()), e); } } /** * Return the next page * @param <T> * @param nextPage * @return */ @GenericStep public <T extends PageObject> T changeToPage(Class<T> nextPage) { try { return nextPage.getConstructor().newInstance(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new ScenarioException(String.format("Cannot switch to next page %s, maybe default constructor does not exist", nextPage.getSimpleName()), e); } } @GenericStep public <T extends PageObject> T doubleClick(String fieldName) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { ((HtmlElement) element).doubleClickAction(); } else { ((GenericPictureElement)element).doubleClick(); } return (T)this; } @GenericStep public <T extends PageObject> T wait(Integer waitMs) { WaitHelper.waitForMilliSeconds(waitMs); return (T)this; } @GenericStep public <T extends PageObject> T clickTableCell(Integer row, Integer column, String fieldName) { Element element = getElement(fieldName); if (element instanceof Table) { ((Table)element).getCell(row, column).click(); } else { throw new ScenarioException(String.format(ERROR_ELEMENT_S_IS_NOT_AN_TABLE_ELEMENT, fieldName)); } return (T)this; } /** * Switch to the newly created window * @return */ @GenericStep public <T extends PageObject> T switchToNewWindow() { selectNewWindow(); return (T)this; } /** * Switch to the newly created window with wait * @return */ @GenericStep public <T extends PageObject> T switchToNewWindow(int waitMs) { selectNewWindow(waitMs); return (T)this; } /** * Select first window in the list * @return */ @GenericStep public <T extends PageObject> T switchToMainWindow() { selectMainWindow(); return (T)this; } /** * Selects the nth window in list * @param index * @return */ @GenericStep public <T extends PageObject> T switchToWindow(int index) { selectWindow(index); return (T)this; } /** * Refresh browser window * @return */ @GenericStep public <T extends PageObject> T refresh() { if (SeleniumTestsContextManager.isWebTest()) { try { driver.navigate().refresh(); } catch (org.openqa.selenium.TimeoutException ex) { logger.error("got time out customexception, ignore"); } } return (T)this; } @GenericStep public <T extends PageObject> T acceptAlert() { Alert alert = getAlert(); if (alert != null) { alert.accept(); } driver.switchTo().defaultContent(); return (T)this; } @GenericStep public <T extends PageObject> T cancelAlert() { cancelConfirmation(); return (T)this; } /** * Method to handle file upload through robot class * /!\ This should only be used as the last option when uploading file cannot be done an other way as explained below * https://saucelabs.com/resources/articles/best-practices-tips-selenium-file-upload * <code> * driver.setFileDetector(new LocalFileDetector()); * driver.get("http://sso.dev.saucelabs.com/test/guinea-file-upload"); * WebElement upload = driver.findElement(By.id("myfile")); * upload.sendKeys("/Users/sso/the/local/path/to/darkbulb.jpg"); * </code> * * * To use this method, first click on the upload file button / link, then call this method. * * /!\ on firefox, clicking MUST be done through 'clickAction'. 'click()' is not supported by browser. * /!\ on firefox, using the uploadFile method several times without other actions between usage may lead to error. Firefox will never click to the button the second time, probably due to focus problems * * @param filePath */ @GenericStep public <T extends PageObject> T uploadFile(String filePath) { try { byte[] encoded = Base64.encodeBase64(FileUtils.readFileToByteArray(new File(filePath))); CustomEventFiringWebDriver.uploadFile(new File(filePath).getName(), new String(encoded), SeleniumTestsContextManager.getThreadContext().getRunMode(), SeleniumTestsContextManager.getThreadContext().getSeleniumGridConnector()); Alert alert = waitForAlert(5); if (alert != null) { alert.accept(); } } catch (IOException e) { throw new ScenarioException(String.format("could not read file to upload %s: %s", filePath, e.getMessage())); } return (T)this; } // --------------------- Waits -------------------------- @GenericStep public <T extends PageObject> T waitForPresent(String fieldName) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { ((HtmlElement) element).waitForPresent(); } else { boolean present = ((GenericPictureElement)element).isElementPresent(SeleniumTestsContextManager.getThreadContext().getExplicitWaitTimeout() * 1000); if (!present) { throw new TimeoutException(String.format(ERROR_ELEMENT_NOT_PRESENT, fieldName)); } } return (T)this; } @GenericStep public <T extends PageObject> T waitForVisible(String fieldName) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { ((HtmlElement) element).waitForVisibility(); } else { boolean present = ((GenericPictureElement)element).isElementPresent(SeleniumTestsContextManager.getThreadContext().getExplicitWaitTimeout() * 1000); if (!present) { throw new TimeoutException(String.format(ERROR_ELEMENT_NOT_PRESENT, fieldName)); } } return (T)this; } @GenericStep public <T extends PageObject> T waitForNotPresent(String fieldName) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { ((HtmlElement) element).waitForNotPresent(); } else { boolean present = ((GenericPictureElement)element).isElementPresent(SeleniumTestsContextManager.getThreadContext().getExplicitWaitTimeout() * 1000); if (present) { throw new TimeoutException(String.format(ERROR_ELEMENT_IS_PRESENT, fieldName)); } } return (T)this; } @GenericStep public <T extends PageObject> T waitForInvisible(String fieldName) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { ((HtmlElement) element).waitForInvisibility(); } else { boolean present = ((GenericPictureElement)element).isElementPresent(SeleniumTestsContextManager.getThreadContext().getExplicitWaitTimeout() * 1000); if (present) { throw new TimeoutException(String.format(ERROR_ELEMENT_IS_PRESENT, fieldName)); } } return (T)this; } @GenericStep public <T extends PageObject> T waitForValue(String fieldName, String value) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { ((HtmlElement) element).waitFor(SeleniumTestsContextManager.getThreadContext().getExplicitWaitTimeout(), ExpectedConditions.or( ExpectedConditions.attributeToBe((HtmlElement)element, "value", value), ExpectedConditions.textToBePresentInElement((HtmlElement)element, value) )); } else { throw new ScenarioException(String.format(ELEMENT_S_IS_NOT_AN_HTML_ELEMENT_SUBCLASS, fieldName)); } return (T)this; } @GenericStep public <T extends PageObject> T waitTableCellValue(Integer row, Integer column, String fieldName, String value) { Element element = getElement(fieldName); if (element instanceof Table) { ((HtmlElement) element).waitFor(SeleniumTestsContextManager.getThreadContext().getExplicitWaitTimeout(), ExpectedConditions.textToBePresentInElement(((Table)element).getCell(row, column), value)); } else { throw new ScenarioException(String.format(ERROR_ELEMENT_S_IS_NOT_AN_TABLE_ELEMENT, fieldName)); } return (T)this; } // --------------------- Assertions -------------------------- @GenericStep public <T extends PageObject> T assertForInvisible(String fieldName) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { Assert.assertFalse(((HtmlElement) element).isElementPresent(0) && ((HtmlElement) element).isDisplayed(), String.format("Element %s is visible", fieldName)); } else { Assert.assertFalse(((GenericPictureElement)element).isElementPresent(), String.format("Element %s is visible", fieldName)); } return (T)this; } @GenericStep public <T extends PageObject> T assertForVisible(String fieldName) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { Assert.assertTrue(((HtmlElement) element).isElementPresent(0), String.format(ERROR_ELEMENT_NOT_PRESENT, fieldName)); Assert.assertTrue(((HtmlElement) element).isDisplayed(), String.format("Element %s is not visible", fieldName)); } else { Assert.assertTrue(((GenericPictureElement)element).isElementPresent(), String.format("Element %s is not visible", fieldName)); } return (T)this; } @GenericStep public <T extends PageObject> T assertForDisabled(String fieldName) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { Assert.assertTrue(((HtmlElement) element).isElementPresent(0), String.format(ERROR_ELEMENT_NOT_PRESENT, fieldName)); Assert.assertFalse(((HtmlElement) element).isEnabled(), String.format("Element %s is enabled", fieldName)); } else { throw new ScenarioException(String.format(ELEMENT_S_IS_NOT_AN_HTML_ELEMENT_SUBCLASS, fieldName)); } return (T)this; } @GenericStep public <T extends PageObject> T assertForEnabled(String fieldName) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { Assert.assertTrue(((HtmlElement) element).isElementPresent(0), String.format(ERROR_ELEMENT_NOT_PRESENT, fieldName)); Assert.assertTrue(((HtmlElement) element).isEnabled(), String.format("Element %s is disabled", fieldName)); } else { throw new ScenarioException(String.format(ELEMENT_S_IS_NOT_AN_HTML_ELEMENT_SUBCLASS, fieldName)); } return (T)this; } @GenericStep public <T extends PageObject> T assertForValue(String fieldName, String value) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { Assert.assertTrue(((HtmlElement) element).isElementPresent(0), String.format(ERROR_ELEMENT_NOT_PRESENT, fieldName)); Assert.assertTrue(((HtmlElement) element).getText().equals(value) || ((HtmlElement) element).getValue().equals(value), String.format("Value of element %s is not %s", fieldName, value)); } else { throw new ScenarioException(String.format(ELEMENT_S_IS_NOT_AN_HTML_ELEMENT_SUBCLASS, fieldName)); } return (T)this; } @GenericStep public <T extends PageObject> T assertForEmptyValue(String fieldName) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { Assert.assertTrue(((HtmlElement) element).isElementPresent(0), String.format(ERROR_ELEMENT_NOT_PRESENT, fieldName)); Assert.assertTrue(((HtmlElement) element).getValue().isEmpty(), String.format("Value or Element %s is not empty", fieldName)); } else { throw new ScenarioException(String.format(ELEMENT_S_IS_NOT_AN_HTML_ELEMENT_SUBCLASS, fieldName)); } return (T)this; } @GenericStep public <T extends PageObject> T assertForNonEmptyValue(String fieldName) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { Assert.assertTrue(((HtmlElement) element).isElementPresent(0), String.format(ERROR_ELEMENT_NOT_PRESENT, fieldName)); Assert.assertFalse(((HtmlElement) element).getValue().isEmpty(), String.format("Element %s is empty", fieldName)); } else { throw new ScenarioException(String.format(ELEMENT_S_IS_NOT_AN_HTML_ELEMENT_SUBCLASS, fieldName)); } return (T)this; } @GenericStep public <T extends PageObject> T assertForMatchingValue(String fieldName, String regex) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { Assert.assertTrue(((HtmlElement) element).isElementPresent(0), String.format(ERROR_ELEMENT_NOT_PRESENT, fieldName)); Assert.assertTrue(Pattern.compile(regex).matcher(((HtmlElement) element).getText()).find() || Pattern.compile(regex).matcher(((HtmlElement) element).getValue()).find(), String.format("Value of Element %s does not match %s ", fieldName, regex)); } else { throw new ScenarioException(String.format(ELEMENT_S_IS_NOT_AN_HTML_ELEMENT_SUBCLASS, fieldName)); } return (T)this; } @GenericStep public <T extends PageObject> T assertSelectedOption(String fieldName, String value) { Element element = getElement(fieldName); if (element instanceof SelectList) { try { WebElement selectedOption = ((SelectList)element).getFirstSelectedOption(); Assert.assertNotNull(selectedOption, "No selected option found"); Assert.assertEquals(selectedOption.getText(), value, "Selected option is not the expected one"); } catch (WebDriverException e) { Assert.assertTrue(false, String.format(ERROR_ELEMENT_NOT_PRESENT, fieldName)); } } else { throw new ScenarioException(String.format("Element %s is not an SelectList subclass", fieldName)); } return (T)this; } @GenericStep public <T extends PageObject> T assertChecked(String fieldName) { Element element = getElement(fieldName); if (element instanceof CheckBoxElement || element instanceof RadioButtonElement) { Assert.assertTrue(((HtmlElement) element).isElementPresent(0), String.format(ERROR_ELEMENT_NOT_PRESENT, fieldName)); Assert.assertTrue(((HtmlElement)element).isSelected(), String.format("Element %s is unchecked", fieldName)); } else { throw new ScenarioException(String.format("Element %s is not an CheckBoxElement/RadioButtonElement", fieldName)); } return (T)this; } @GenericStep public <T extends PageObject> T assertNotChecked(String fieldName) { Element element = getElement(fieldName); if (element instanceof CheckBoxElement || element instanceof RadioButtonElement) { Assert.assertTrue(((HtmlElement) element).isElementPresent(0), String.format(ERROR_ELEMENT_NOT_PRESENT, fieldName)); Assert.assertFalse(((HtmlElement)element).isSelected(), String.format("Element %s is checked", fieldName)); } else { throw new ScenarioException(String.format("Element %s is not an CheckBoxElement/RadioButtonElement", fieldName)); } return (T)this; } @GenericStep public <T extends PageObject> T assertTableCellValue(Integer row, Integer column, String fieldName, String value) { Element element = getElement(fieldName); if (element instanceof Table) { try { Assert.assertEquals(((Table)element).getCell(row, column).getText(), value, String.format("Value of cell [%d,%d] in table %s is not %s", row, column, fieldName, value)); } catch (WebDriverException e) { Assert.assertTrue(false, "Table or cell not found"); } } else { throw new ScenarioException(String.format(ERROR_ELEMENT_S_IS_NOT_AN_TABLE_ELEMENT, fieldName)); } return (T)this; } @GenericStep public <T extends PageObject> T assertTextPresentInPage(String text) { Assert.assertTrue(isTextPresent(text)); return (T)this; } @GenericStep public <T extends PageObject> T assertTextNotPresentInPage(String text) { Assert.assertFalse(isTextPresent(text)); return (T)this; } @GenericStep public <T extends PageObject> T assertCookiePresent(String name) { Assert.assertTrue(isCookiePresent(name), "Cookie: {" + name + "} not found."); return (T)this; } @GenericStep public <T extends PageObject> T assertElementCount(String fieldName, int elementCount) { Element element = getElement(fieldName); if (element instanceof HtmlElement) { Assert.assertEquals(((HtmlElement)element).findElements().size(), elementCount); } else { throw new ScenarioException(String.format("Element %s is not an HtmlElement", fieldName)); } return (T)this; } /** * Check page title matches parameter * @param regexTitle * @return */ @GenericStep public <T extends PageObject> T assertPageTitleMatches(String regexTitle) { Assert.assertTrue(getTitle().matches(regexTitle)); return (T)this; } @GenericStep public void assertHtmlSource(String text) { Assert.assertTrue(getHtmlSource().contains(text), String.format("Text: {%s} not found on page source.", text)); } /** * @deprecated useless * @param text */ @Deprecated public void assertKeywordNotPresent(String text) { Assert.assertFalse(getHtmlSource().contains(text), String.format("Text: {%s} not found on page source.", text)); } @GenericStep public void assertLocation(String urlPattern) { Assert.assertTrue(getLocation().contains(urlPattern), "Pattern: {" + urlPattern + "} not found on page location."); } /** * @deprecated useless * @param text */ @Deprecated public void assertTitle(final String text) { Assert.assertTrue(getTitle().contains(text), String.format("Text: {%s} not found on page title.", text)); } public ScreenshotUtil getScreenshotUtil() { return screenshotUtil; } public void setScreenshotUtil(ScreenshotUtil screenshotUtil) { this.screenshotUtil = screenshotUtil; } /** * Returns the list of uiLibraries associated to this page or an empty list if none found * @param cannonicalClassName * @return */ public static List<String> getUiLibraries(String cannonicalClassName) { return uiLibraries.getOrDefault(cannonicalClassName, new ArrayList<>()); } }
apache-2.0
spindance/serviced-precomp
cli/api/template_test.go
1096
// Copyright 2014 The Serviced 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. // +build unit package api import ( "testing" ) func TestListTemplates(t *testing.T) { } func BenchmarkListTemplates(b *testing.B) { } func TestAddTemplate(t *testing.T) { } func BenchmarkAddTemplate(b *testing.B) { } func TestRemoveTemplate(t *testing.T) { } func BenchmarkRemoveTemplate(b *testing.B) { } func TestCompileTemplate(t *testing.T) { } func BenchmarkCompileTemplate(b *testing.B) { } func TestDeployTemplate(t *testing.T) { } func BenchmarkDeployTemplate(b *testing.B) { }
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Alismatales/Araceae/Amorphophallus/Amorphophallus paeoniifolius/ Syn. Amorphophallus paeoniifolius paeoniifolius/README.md
189
# Amorphophallus paeoniifolius var. paeoniifolius VARIETY #### Status SYNONYM #### According to GRIN Taxonomy for Plants #### Published in null #### Original name null ### Remarks null
apache-2.0
dmitryilyin/mistral
mistral/tests/unit/engine/default/test_executor.py
4084
# Copyright (c) 2013 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. import eventlet eventlet.monkey_patch() import uuid import mock from oslo.config import cfg from mistral.tests import base from mistral.openstack.common import log as logging from mistral.openstack.common import importutils from mistral.engine import states from mistral.db import api as db_api from mistral.actions import std_actions from mistral import engine from mistral.engine import executor # We need to make sure that all configuration properties are registered. importutils.import_module("mistral.config") LOG = logging.getLogger(__name__) # Use the set_default method to set value otherwise in certain test cases # the change in value is not permanent. cfg.CONF.set_default('auth_enable', False, group='pecan') WORKBOOK_NAME = 'my_workbook' TASK_NAME = 'create-vms' SAMPLE_WORKBOOK = { 'id': str(uuid.uuid4()), 'name': WORKBOOK_NAME, 'description': 'my description', 'definition': base.get_resource("test_rest.yaml"), 'tags': [], 'scope': 'public', 'updated_at': None, 'project_id': '123', 'trust_id': '1234' } SAMPLE_EXECUTION = { 'id': str(uuid.uuid4()), 'workbook_name': WORKBOOK_NAME, 'task': TASK_NAME, 'state': states.RUNNING, 'updated_at': None, 'context': None } SAMPLE_TASK = { 'name': TASK_NAME, 'workbook_name': WORKBOOK_NAME, 'action_spec': { 'name': 'my-action', 'class': 'std.http', 'base-parameters': { 'url': 'http://localhost:8989/v1/workbooks', 'method': 'GET' }, 'namespace': 'MyRest' }, 'task_spec': { 'action': 'MyRest.my-action', 'name': TASK_NAME}, 'requires': {}, 'state': states.IDLE} SAMPLE_CONTEXT = { 'user': 'admin', 'tenant': 'mistral' } class TestExecutor(base.DbTestCase): def __init__(self, *args, **kwargs): super(TestExecutor, self).__init__(*args, **kwargs) self.transport = base.get_fake_transport() @mock.patch.object( executor.ExecutorClient, 'handle_task', mock.MagicMock(side_effect=base.EngineTestCase.mock_handle_task)) @mock.patch.object( std_actions.HTTPAction, 'run', mock.MagicMock(return_value={})) @mock.patch.object( engine.EngineClient, 'convey_task_result', mock.MagicMock(side_effect=base.EngineTestCase.mock_task_result)) def test_handle_task(self): # Create a new workbook. workbook = db_api.workbook_create(SAMPLE_WORKBOOK) self.assertIsInstance(workbook, dict) # Create a new execution. execution = db_api.execution_create(SAMPLE_EXECUTION['workbook_name'], SAMPLE_EXECUTION) self.assertIsInstance(execution, dict) # Create a new task. SAMPLE_TASK['execution_id'] = execution['id'] task = db_api.task_create(SAMPLE_TASK['workbook_name'], SAMPLE_TASK['execution_id'], SAMPLE_TASK) self.assertIsInstance(task, dict) self.assertIn('id', task) # Send the task request to the Executor. ex_client = executor.ExecutorClient(self.transport) ex_client.handle_task(SAMPLE_CONTEXT, task=task) # Check task execution state. db_task = db_api.task_get(task['workbook_name'], task['execution_id'], task['id']) self.assertEqual(db_task['state'], states.SUCCESS)
apache-2.0
hpe-cct/cct-nn
src/test/scala/toolkit/neuralnetwork/function/CrossEntropySpec.scala
2021
/* * (c) Copyright 2016 Hewlett Packard Enterprise Development LP * * 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 toolkit.neuralnetwork.function import libcog._ import toolkit.neuralnetwork.{ComputeTests, DifferentiableField, UnitSpec} /** Tests the self-consistency of the forward/jacobian/jacobianAdjoint functions of the CrossEntropy operator. * * @author Dick Carter */ class CrossEntropySpec extends UnitSpec with ComputeTests { val batchSizes = Seq(7, 7) val node = { a: Seq[DifferentiableField] => CrossEntropy(a.head, a(1)) } "The CrossEntropy operator" should "support the MNIST class size of 10" in { val inputLens = Seq(10, 10) val inputShapes = Seq(Shape(), Shape()) jacobian(node, inputShapes, inputLens, batchSizes, positiveXOnly = true) jacobianAdjoint(node, inputShapes, inputLens, batchSizes, positiveXOnly = true) } "The CrossEntropy operator" should "support a class size of 100" in { val inputLens = Seq(100, 100) val inputShapes = Seq(Shape(), Shape()) jacobian(node, inputShapes, inputLens, batchSizes, positiveXOnly = true) jacobianAdjoint(node, inputShapes, inputLens, batchSizes, positiveXOnly = true) } it should "support the ImageNet class size of 1000" in { val inputLens = Seq(1000, 1000) val inputShapes = Seq(Shape(), Shape()) jacobian(node, inputShapes, inputLens, batchSizes, positiveXOnly = true) jacobianAdjoint(node, inputShapes, inputLens, batchSizes, positiveXOnly = true) } }
apache-2.0
bfritscher/campuscard-visualization
dc.css
5289
@import url(http://fonts.googleapis.com/css?family=Droid+Sans:400,700); *{ font-family: 'Droid Sans', sans-serif; font-size: 13px; } body{ margin:0; padding: 20px; } a{ color: #3182bd; } a.reset { } #data-table{ clear: both; } #data-table-content{ float: none; height: 300px; overflow: auto; width: 400px; } #data-table .header > span{ display: table-cell; font-weight: bold; } .dc-table-column._0{ width: 100px; } .dc-table-column._1{ width: 180px; } .dc-table-column._2{ width: 100px; text-align: right; } .dc-table-group{ background-color: #d9edf7; } .dc-table-row{ } #list-widget{ width: 960px; } #list{ height: 540px; background-color: rgba(105,105,105,0.2); margin: 0; } #list-widget .progress{ height: 4px; margin-top: 0; } #list .item{ width: 320px; height: 180px; float: left; position: relative; } #list .item span{ display:block; padding: 2px; background-color: black; color: white; opacity: 0.8; font-size: 14px; } #list .item a{ position: absolute; bottom: 2px; left:2px; font-size: 10px; color: white; opacity: 0.6; text-decoration: none; padding: 0 1px; } #detail-background{ width: 100%; height: 100%; position: fixed; background-color: black; opacity: 0.4; top:0; left:0; } #detail{ position: absolute; width: 900px; background-color: white; top: 100px; left: 50%; margin-left: -460px; padding: 10px; } #day.dc-chart g.row text { fill:white; } #logo{ position: fixed; bottom: 10px; right: 20px; font-size: 16px; } #logo .accent{ color: #3182bd; font-size: 16px; } .dc-chart > div{ margin-top: 8px; } .main{ float: left; } .main .dc-chart { float: none; } #days-overview .axis.y{ display: none; } .detail-footer{ margin-top: 10px; font-weight: bold; font-size: 80%; } .detail-footer span{ font-weight: normal; } .detail-footer a{ font-weight: normal; text-decoration: none; float: right; } .dc-chart { float: left; } .dc-chart rect.bar { stroke: none; cursor: pointer; } .dc-chart rect.bar:hover { fill-opacity: .5; } .dc-chart rect.stack1 { stroke: none; fill: red; } .dc-chart rect.stack2 { stroke: none; fill: green; } .dc-chart rect.deselected { stroke: none; fill: #ccc; } .dc-chart .pie-slice { fill: white; font-size: 12px; cursor: pointer; } .dc-chart .pie-slice :hover { fill-opacity: .8; } .dc-chart .selected path { stroke-width: 3; stroke: #ccc; fill-opacity: 1; } .dc-chart .deselected path { strok: none; fill-opacity: .5; fill: #ccc; } .dc-chart .axis path, .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } .dc-chart .axis text { font: 10px sans-serif; } .dc-chart .grid-line { fill: none; stroke: #ccc; opacity: .5; shape-rendering: crispEdges; } .dc-chart .grid-line line { fill: none; stroke: #ccc; opacity: .5; shape-rendering: crispEdges; } .dc-chart .brush rect.background { z-index: -999; } .dc-chart .brush rect.extent { fill-opacity: .125; } .dc-chart .brush .resize path { fill: #eee; stroke: #666; } .dc-chart path.line { fill: none; stroke-width: 1.5px; } .dc-chart circle.dot { stroke: none; } .dc-chart g.dc-tooltip path { fill: none; stroke: grey; stroke-opacity: .8; } .dc-chart path.area { fill-opacity: .3; stroke: none; } .dc-chart .node { font-size: 0.7em; cursor: pointer; } .dc-chart .node :hover { fill-opacity: .8; } .dc-chart .selected circle { stroke-width: 3; stroke: #ccc; fill-opacity: 1; } .dc-chart .deselected circle { strok: none; fill-opacity: .5; fill: #ccc; } .dc-chart .bubble { stroke: none; fill-opacity: 0.6; } .dc-data-count { float: right; margin-top: 15px; margin-right: 15px; } .dc-data-count .filter-count { color: #3182bd; font-weight: bold; } .dc-data-count .total-count { color: #3182bd; font-weight: bold; } .dc-data-table { } .dc-chart g.state { cursor: pointer; } .dc-chart g.state :hover { fill-opacity: .8; } .dc-chart g.state path { stroke: white; } .dc-chart g.selected path { } .dc-chart g.deselected path { fill: grey; } .dc-chart g.selected text { } .dc-chart g.deselected text { display: none; } .dc-chart g.county path { stroke: white; fill: none; } .dc-chart g.debug rect { fill: blue; fill-opacity: .2; } .dc-chart g.row rect { cursor: pointer; } .dc-chart g.row rect:hover { fill-opacity: 0.6; } .dc-chart g.row text { fill: black; font-size: 12px; cursor: pointer; } .dc-legend { font-size: 11px; } .dc-legend-item { cursor: pointer; } .dc-chart g.axis text { /* Makes it so the user can't accidentally click and select text that is meant as a label only */ -webkit-user-select: none; /* Chrome/Safari */ -moz-user-select: none; /* Firefox */ -ms-user-select: none; /* IE10 */ -o-user-select: none; user-select: none; pointer-events: none; } .dc-chart path.highlight { stroke-width: 3; fill-opacity: 1; stroke-opacity: 1; } .dc-chart .highlight { fill-opacity: 1; stroke-opacity: 1; } .dc-chart .fadeout { fill-opacity: 0.2; stroke-opacity: 0.2; }
apache-2.0
CristianUrbainski/osiris-faces
osiris-faces/src/main/java/com/osiris/component/bootstrap/menu/render/MenuItemRender.java
2535
package com.osiris.component.bootstrap.menu.render; import java.io.IOException; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import javax.faces.render.FacesRenderer; import org.primefaces.renderkit.CoreRenderer; import com.osiris.component.bootstrap.menu.UIMenuItem; import com.osiris.component.util.HTML; import com.osiris.component.util.HtmlConstants; /** * * Classe que renderiza um item do menu. * * @author Cristian Urbainski<[email protected]> * @since 13/07/2013 * @version 1.0 * */ @FacesRenderer(componentFamily = UIMenuItem.COMPONENT_FAMILY, rendererType = MenuItemRender.RENDERER_TYPE) public class MenuItemRender extends CoreRenderer { /** * Tipo do renderizador do componente. */ public static final String RENDERER_TYPE = "com.osiris.component.bootstrap.MenuItemRenderer"; @Override public void encodeEnd(FacesContext context, UIComponent component) throws IOException { UIMenuItem menuItem = (UIMenuItem) component; encodeMarkup(context, menuItem); } /** * Método responsável por fazer a construção do html para o componente. * * @param context do jsf * @param menuItem componente a ser transcrito para html * @throws IOException excecao que pode ocorrer */ protected void encodeMarkup(FacesContext context, UIMenuItem menuItem) throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = menuItem.getClientId(context); String style = menuItem.getStyle(); String styleClass = ""; if (menuItem.isActive()) { styleClass = "active"; } if (menuItem.getStyleClass() != null) { styleClass += " " + menuItem.getStyleClass(); } writer.startElement(HTML.LI_ELEM, null); writer.writeAttribute(HtmlConstants.ID_ATTRIBUTE, clientId, null); if (styleClass.length() > 0) { writer.writeAttribute(HtmlConstants.CLASS_ATTR, styleClass, null); } if (style != null) { writer.writeAttribute(HtmlConstants.STYLE_ATTRIBUTE, style, null); } writer.startElement(HTML.A_ELEM, null); writer.writeAttribute(HtmlConstants.HREF_ATTR, menuItem.getLocation(), null); writer.writeText(menuItem.getLabel(), null); writer.endElement(HTML.A_ELEM); writer.endElement(HTML.LI_ELEM); } }
apache-2.0
mpelevina/context-eval
semeval_2013_13/dataset2key.py
2427
import codecs from pandas import read_csv import argparse import numpy as np import codecs import os FIELD_NAMES = ["context_id","target","target_pos","target_position","gold_sense_ids","predict_sense_ids", "golden_related","predict_related","context"] FIELD_TYPES = {"context_id":np.dtype(str),"target":np.dtype(str),"target_pos":np.dtype(str),"target_position":np.dtype(str),"gold_sense_ids":np.dtype(str),"predict_sense_ids":np.dtype(str), "golden_related":np.dtype(str),"predict_related":np.dtype(str),"context":np.dtype(str)} def cut_9_first(dataset_fpath, dataset_9_fpath): """ Cuts first 9 columns of the dataset file to make it openable with read_csv. """ with codecs.open(dataset_fpath, "r", "utf-8") as in_dataset, codecs.open(dataset_9_fpath, "w", "utf-8") as out_dataset: for line in in_dataset: print >> out_dataset, "\t".join(line.split("\t")[:9]) def convert_dataset2semevalkey(dataset_fpath, output_fpath, no_header=False): with codecs.open(output_fpath, "w", encoding="utf-8") as output: if no_header: df = read_csv(dataset_fpath, sep='\t', encoding='utf8', header=None, names=FIELD_NAMES, dtype=FIELD_TYPES, doublequote=False, quotechar='\0') df.target = df.target.astype(str) else: df = read_csv(dataset_fpath, encoding='utf-8', delimiter="\t", error_bad_lines=False, doublequote=False, quotechar='\0') for i, row in df.iterrows(): predicted_senses = " ".join(unicode(row.predict_sense_ids).split(",")) print >> output, "%s %s %s" % (row.target + "." + row.target_pos, row.context_id, predicted_senses) print "Key file:", output_fpath def main(): parser = argparse.ArgumentParser(description='Convert lexical sample dataset to SemEval 2013 key format.') parser.add_argument('input', help='Path to a file with input file.') parser.add_argument('output', help='Output file.') parser.add_argument('--no_header', action='store_true', help='No headers. Default -- false.') args = parser.parse_args() print "Input: ", args.input print "Output: ", args.output print "No header:", args.no_header tmp_fpath = args.input + "-9-columns.csv" cut_9_first(args.input, tmp_fpath) convert_dataset2semevalkey(tmp_fpath, args.output, args.no_header) #os.remove(tmp_fpath) if __name__ == '__main__': main()
apache-2.0
codelibs/cl-struts
src/share/org/apache/struts/taglib/html/HtmlTag.java
6309
/* * $Id: HtmlTag.java 54929 2004-10-16 16:38:42Z germuska $ * * Copyright 1999-2004 The Apache Software Foundation. * * 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.apache.struts.taglib.html; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.TagSupport; import org.apache.struts.Globals; import org.apache.struts.taglib.TagUtils; import org.apache.struts.util.MessageResources; /** * Renders an HTML <html> element with appropriate language attributes if * there is a current Locale available in the user's session. * * @version $Rev: 54929 $ $Date: 2004-10-17 01:38:42 +0900 (日, 17 10月 2004) $ */ public class HtmlTag extends TagSupport { // ------------------------------------------------------------- Properties /** * The message resources for this package. */ protected static MessageResources messages = MessageResources.getMessageResources(Constants.Package + ".LocalStrings"); /** * Should we set the current Locale for this user if needed? * @deprecated This will be removed after Struts 1.2. */ protected boolean locale = false; /** * @deprecated This will be removed after Struts 1.2. */ public boolean getLocale() { return (locale); } /** * @deprecated This will be removed after Struts 1.2. */ public void setLocale(boolean locale) { this.locale = locale; } /** * Are we rendering an xhtml page? */ protected boolean xhtml = false; /** * Are we rendering a lang attribute? * @since Struts 1.2 */ protected boolean lang = false; public boolean getXhtml() { return this.xhtml; } public void setXhtml(boolean xhtml) { this.xhtml = xhtml; } /** * Returns true if the tag should render a lang attribute. * @since Struts 1.2 */ public boolean getLang() { return this.lang; } /** * Sets whether the tag should render a lang attribute. * @since Struts 1.2 */ public void setLang(boolean lang) { this.lang = lang; } /** * Process the start of this tag. * * @exception JspException if a JSP exception has occurred */ public int doStartTag() throws JspException { TagUtils.getInstance().write(this.pageContext, this.renderHtmlStartElement()); return EVAL_BODY_INCLUDE; } /** * Renders an &lt;html&gt; element with appropriate language attributes. * @since Struts 1.2 */ protected String renderHtmlStartElement() { StringBuffer sb = new StringBuffer("<html"); String language = null; String country = ""; if (this.locale) { // provided for 1.1 backward compatibility, remove after 1.2 language = this.getCurrentLocale().getLanguage(); } else { Locale currentLocale = TagUtils.getInstance().getUserLocale(pageContext, Globals.LOCALE_KEY); language = currentLocale.getLanguage(); country = currentLocale.getCountry(); } boolean validLanguage = ((language != null) && (language.length() > 0)); boolean validCountry = country.length() > 0; if (this.xhtml) { this.pageContext.setAttribute( Globals.XHTML_KEY, "true", PageContext.PAGE_SCOPE); sb.append(" xmlns=\"http://www.w3.org/1999/xhtml\""); } if ((this.lang || this.locale || this.xhtml) && validLanguage) { sb.append(" lang=\""); sb.append(language); if (validCountry) { sb.append("-"); sb.append(country); } sb.append("\""); } if (this.xhtml && validLanguage) { sb.append(" xml:lang=\""); sb.append(language); if (validCountry) { sb.append("-"); sb.append(country); } sb.append("\""); } sb.append(">"); return sb.toString(); } /** * Process the end of this tag. * * @exception JspException if a JSP exception has occurred */ public int doEndTag() throws JspException { TagUtils.getInstance().write(pageContext, "</html>"); // Evaluate the remainder of this page return (EVAL_PAGE); } /** * Release any acquired resources. */ public void release() { this.locale = false; this.xhtml = false; this.lang=false; } // ------------------------------------------------------ Protected Methods /** * Return the current Locale for this request. If there is no locale in the session and * the locale attribute is set to "true", this method will create a Locale based on the * client's Accept-Language header or the server's default locale and store it in the * session. This will always return a Locale and never null. * @since Struts 1.1 * @deprecated This will be removed after Struts 1.2. */ protected Locale getCurrentLocale() { Locale userLocale = TagUtils.getInstance().getUserLocale(pageContext, Globals.LOCALE_KEY); // Store a new current Locale, if requested if (this.locale) { HttpSession session = ((HttpServletRequest) this.pageContext.getRequest()).getSession(); session.setAttribute(Globals.LOCALE_KEY, userLocale); } return userLocale; } }
apache-2.0
friendranjith/vizzly
jetty-runtime/javadoc/org/eclipse/jetty/servlet/class-use/ServletContextHandler.JspPropertyGroup.html
4762
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_03) on Mon Sep 10 14:25:59 CDT 2012 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class org.eclipse.jetty.servlet.ServletContextHandler.JspPropertyGroup (Jetty :: Aggregate :: All core Jetty 8.1.7.v20120910 API)</title> <meta name="date" content="2012-09-10"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.eclipse.jetty.servlet.ServletContextHandler.JspPropertyGroup (Jetty :: Aggregate :: All core Jetty 8.1.7.v20120910 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/eclipse/jetty/servlet/ServletContextHandler.JspPropertyGroup.html" title="class in org.eclipse.jetty.servlet">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/eclipse/jetty/servlet//class-useServletContextHandler.JspPropertyGroup.html" target="_top">Frames</a></li> <li><a href="ServletContextHandler.JspPropertyGroup.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.eclipse.jetty.servlet.ServletContextHandler.JspPropertyGroup" class="title">Uses of Class<br>org.eclipse.jetty.servlet.ServletContextHandler.JspPropertyGroup</h2> </div> <div class="classUseContainer">No usage of org.eclipse.jetty.servlet.ServletContextHandler.JspPropertyGroup</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/eclipse/jetty/servlet/ServletContextHandler.JspPropertyGroup.html" title="class in org.eclipse.jetty.servlet">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/eclipse/jetty/servlet//class-useServletContextHandler.JspPropertyGroup.html" target="_top">Frames</a></li> <li><a href="ServletContextHandler.JspPropertyGroup.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 1995-2012 <a href="http://www.mortbay.com">Mort Bay Consulting</a>. All Rights Reserved.</small></p> </body> </html>
apache-2.0
liquibase/liquibase
liquibase-core/src/main/java/liquibase/snapshot/jvm/UniqueConstraintSnapshotGenerator.java
30661
package liquibase.snapshot.jvm; import java.util.stream.Collectors; import liquibase.Scope; import liquibase.database.Database; import liquibase.database.core.*; import liquibase.exception.DatabaseException; import liquibase.exception.UnexpectedLiquibaseException; import liquibase.executor.ExecutorService; import liquibase.snapshot.CachedRow; import liquibase.snapshot.DatabaseSnapshot; import liquibase.snapshot.JdbcDatabaseSnapshot; import liquibase.statement.core.RawSqlStatement; import liquibase.structure.DatabaseObject; import liquibase.structure.core.Catalog; import liquibase.structure.core.Column; import liquibase.structure.core.Index; import liquibase.structure.core.Relation; import liquibase.structure.core.Schema; import liquibase.structure.core.Table; import liquibase.structure.core.UniqueConstraint; import liquibase.util.StringUtil; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class UniqueConstraintSnapshotGenerator extends JdbcSnapshotGenerator { public UniqueConstraintSnapshotGenerator() { super(UniqueConstraint.class, new Class[]{Table.class}); } @Override public int getPriority(Class<? extends DatabaseObject> objectType, Database database) { if (database instanceof SQLiteDatabase) { return PRIORITY_NONE; } return super.getPriority(objectType, database); } @Override protected DatabaseObject snapshotObject(DatabaseObject example, DatabaseSnapshot snapshot) throws DatabaseException { Database database = snapshot.getDatabase(); UniqueConstraint exampleConstraint = (UniqueConstraint) example; Relation table = exampleConstraint.getRelation(); List<Map<String, ?>> metadata = listColumns(exampleConstraint, database, snapshot); if (metadata.isEmpty()) { return null; } UniqueConstraint constraint = new UniqueConstraint(); constraint.setRelation(table); constraint.setName(example.getName()); constraint.setBackingIndex(exampleConstraint.getBackingIndex()); constraint.setInitiallyDeferred(((UniqueConstraint) example).isInitiallyDeferred()); constraint.setDeferrable(((UniqueConstraint) example).isDeferrable()); constraint.setClustered(((UniqueConstraint) example).isClustered()); for (Map<String, ?> col : metadata) { String ascOrDesc = (String) col.get("ASC_OR_DESC"); Boolean descending = "D".equals(ascOrDesc) ? Boolean.TRUE : ("A".equals(ascOrDesc) ? Boolean.FALSE : null); if (database instanceof H2Database) { for (String columnName : StringUtil.splitAndTrim((String) col.get("COLUMN_NAME"), ",")) { constraint.getColumns().add(new Column(columnName).setDescending(descending).setRelation(table)); } } else { constraint.getColumns().add(new Column((String) col.get("COLUMN_NAME")).setDescending(descending).setRelation(table)); } setValidateOptionIfAvailable(database, constraint, col); } return constraint; } /** * Method to map 'validate' option for UC. This thing works only for ORACLE * * @param database - DB where UC will be created * @param uniqueConstraint - UC object to persist validate option * @param columnsMetadata - it's a cache-map to get metadata about UC */ private void setValidateOptionIfAvailable(Database database, UniqueConstraint uniqueConstraint, Map<String, ?> columnsMetadata) { if (!(database instanceof OracleDatabase)) { return; } final Object constraintValidate = columnsMetadata.get("CONSTRAINT_VALIDATE"); final String VALIDATE = "VALIDATED"; if (constraintValidate != null && !constraintValidate.toString().trim().isEmpty()) { uniqueConstraint.setShouldValidate(VALIDATE.equals(cleanNameFromDatabase(constraintValidate.toString().trim(), database))); } } @Override protected void addTo(DatabaseObject foundObject, DatabaseSnapshot snapshot) throws DatabaseException { if (!snapshot.getSnapshotControl().shouldInclude(UniqueConstraint.class)) { return; } if (foundObject instanceof Table) { Table table = (Table) foundObject; Database database = snapshot.getDatabase(); Schema schema; schema = table.getSchema(); List<CachedRow> metadata; try { metadata = listConstraints(table, snapshot, schema); } catch (SQLException e) { throw new DatabaseException(e); } Set<String> seenConstraints = new HashSet<>(); for (CachedRow constraint : metadata) { UniqueConstraint uq = new UniqueConstraint() .setName(cleanNameFromDatabase((String) constraint.get("CONSTRAINT_NAME"), database)).setRelation(table); if (constraint.containsColumn("INDEX_NAME")) { uq.setBackingIndex(new Index((String) constraint.get("INDEX_NAME"), (String) constraint.get("INDEX_CATALOG"), (String) constraint.get("INDEX_SCHEMA"), table.getName())); } if ("CLUSTERED".equals(constraint.get("TYPE_DESC"))) { uq.setClustered(true); } if (seenConstraints.add(uq.getName())) { table.getUniqueConstraints().add(uq); } } } } protected List<CachedRow> listConstraints(Table table, DatabaseSnapshot snapshot, Schema schema) throws DatabaseException, SQLException { return ((JdbcDatabaseSnapshot) snapshot).getMetaDataFromCache().getUniqueConstraints(schema.getCatalogName(), schema.getName(), table.getName()); } protected List<Map<String, ?>> listColumns(UniqueConstraint example, Database database, DatabaseSnapshot snapshot) throws DatabaseException { Relation table = example.getRelation(); Schema schema = example.getSchema(); String name = example.getName(); boolean bulkQuery; String sql; String cacheKey = "uniqueConstraints-" + example.getClass().getSimpleName() + "-" + example.getSchema().toCatalogAndSchema().customize(database).toString(); String queryCountKey = "uniqueConstraints-" + example.getClass().getSimpleName() + "-queryCount"; Map<String, List<Map<String, ?>>> columnCache = (Map<String, List<Map<String, ?>>>) snapshot.getScratchData(cacheKey); Integer columnQueryCount = (Integer) snapshot.getScratchData(queryCountKey); if (columnQueryCount == null) { columnQueryCount = 0; } if (columnCache == null) { bulkQuery = false; if (columnQueryCount > 3) { bulkQuery = supportsBulkQuery(database); } snapshot.setScratchData(queryCountKey, columnQueryCount + 1); if ((database instanceof MySQLDatabase) || (database instanceof HsqlDatabase)) { sql = "select const.CONSTRAINT_NAME, const.TABLE_NAME, COLUMN_NAME, const.constraint_schema as CONSTRAINT_CONTAINER " + "from " + database.getSystemSchema() + ".table_constraints const " + "join " + database.getSystemSchema() + ".key_column_usage col " + "on const.constraint_schema=col.constraint_schema " + "and const.table_name=col.table_name " + "and const.constraint_name=col.constraint_name " + "where const.constraint_schema='" + database.correctObjectName(schema.getCatalogName(), Catalog.class) + "' "; if (!bulkQuery) { sql += "and const.table_name='" + database.correctObjectName(example.getRelation().getName(), Table.class) + "' " + "and const.constraint_name='" + database.correctObjectName(name, UniqueConstraint.class) + "'"; } sql += "order by ordinal_position"; } else if (database instanceof PostgresDatabase) { List<String> conditions = new ArrayList<>(); sql = "select const.CONSTRAINT_NAME, COLUMN_NAME, const.constraint_schema as CONSTRAINT_CONTAINER " + "from " + database.getSystemSchema() + ".table_constraints const " + "join " + database.getSystemSchema() + ".key_column_usage col " + "on const.constraint_schema=col.constraint_schema " + "and const.table_name=col.table_name " + "and const.constraint_name=col.constraint_name "; if (schema.getCatalogName() != null) { conditions.add("const.constraint_catalog='" + database.correctObjectName(schema.getCatalogName(), Catalog.class) + "'"); } if (database instanceof CockroachDatabase) { conditions.add("(select count(*) from (select indexdef from pg_indexes where schemaname='\" + database.correctObjectName(schema.getSchema().getName(), Schema.class) + \"' AND indexname='\" + database.correctObjectName(name, UniqueConstraint.class) + \"' AND (position('DESC,' in indexdef) > 0 OR position('DESC)' in indexdef) > 0))) = 0"); conditions.add("const.constraint_name != 'primary'"); } if (schema.getSchema().getName() != null) { conditions.add("const.constraint_schema='" + database.correctObjectName(schema.getSchema().getName(), Schema.class) + "'"); } if (!bulkQuery) { conditions.add("const.table_name='" + database.correctObjectName(example.getRelation().getName(), Table.class) + "'"); if (name != null) { conditions.add("const.constraint_name='" + database.correctObjectName(name, UniqueConstraint.class) + "' "); } } if (!conditions.isEmpty()) { sql += " WHERE "; sql += conditions.stream().collect(Collectors.joining(" AND ")); } sql += " order by ordinal_position"; } else if (database.getClass().getName().contains("MaxDB")) { //have to check classname as this is currently an extension sql = "select CONSTRAINTNAME as constraint_name, COLUMNNAME as column_name from CONSTRAINTCOLUMNS WHERE CONSTRAINTTYPE = 'UNIQUE_CONST' AND tablename = '" + database.correctObjectName(example.getRelation().getName(), Table.class) + "' AND constraintname = '" + database.correctObjectName(name, UniqueConstraint.class) + "'"; } else if (database instanceof MSSQLDatabase) { sql = "SELECT " + "[kc].[name] AS [CONSTRAINT_NAME], " + "s.name AS constraint_container, " + "[c].[name] AS [COLUMN_NAME], " + "CASE [ic].[is_descending_key] WHEN 0 THEN N'A' WHEN 1 THEN N'D' END AS [ASC_OR_DESC] " + "FROM [sys].[schemas] AS [s] " + "INNER JOIN [sys].[tables] AS [t] " + "ON [t].[schema_id] = [s].[schema_id] " + "INNER JOIN [sys].[key_constraints] AS [kc] " + "ON [kc].[parent_object_id] = [t].[object_id] " + "INNER JOIN [sys].[indexes] AS [i] " + "ON [i].[object_id] = [kc].[parent_object_id] " + "AND [i].[index_id] = [kc].[unique_index_id] " + "INNER JOIN [sys].[index_columns] AS [ic] " + "ON [ic].[object_id] = [i].[object_id] " + "AND [ic].[index_id] = [i].[index_id] " + "INNER JOIN [sys].[columns] AS [c] " + "ON [c].[object_id] = [ic].[object_id] " + "AND [c].[column_id] = [ic].[column_id] " + "WHERE [s].[name] = N'" + database.escapeStringForDatabase(database.correctObjectName(schema.getName(), Schema.class)) + "' "; if (!bulkQuery) { sql += "AND [t].[name] = N'" + database.escapeStringForDatabase(database.correctObjectName(example.getRelation().getName(), Table.class)) + "' " + "AND [kc].[name] = N'" + database.escapeStringForDatabase(database.correctObjectName(name, UniqueConstraint.class)) + "' "; } sql += "ORDER BY " + "[ic].[key_ordinal]"; } else if (database instanceof OracleDatabase) { sql = "select ucc.owner as constraint_container, ucc.constraint_name as constraint_name, ucc.column_name, f.validated as constraint_validate, ucc.table_name " + "from all_cons_columns ucc " + "INNER JOIN all_constraints f " + "ON ucc.owner = f.owner " + "AND ucc.constraint_name = f.constraint_name " + "where " + (bulkQuery ? "" : "ucc.constraint_name='" + database.correctObjectName(name, UniqueConstraint.class) + "' and ") + "ucc.owner='" + database.correctObjectName(schema.getCatalogName(), Catalog.class) + "' " + "and ucc.table_name not like 'BIN$%' " + "order by ucc.position"; } else if (database instanceof DB2Database) { if (database.getDatabaseProductName().startsWith("DB2 UDB for AS/400")) { sql = "select T1.constraint_name as CONSTRAINT_NAME, T2.COLUMN_NAME as COLUMN_NAME, T1.CONSTRAINT_SCHEMA as CONSTRAINT_CONTAINER from QSYS2.TABLE_CONSTRAINTS T1, QSYS2.SYSCSTCOL T2\n" + "where T1.CONSTRAINT_TYPE='UNIQUE' and T1.CONSTRAINT_NAME=T2.CONSTRAINT_NAME\n" + "and T1.CONSTRAINT_SCHEMA='" + database.correctObjectName(schema.getName(), Schema.class) + "'\n" + "and T2.CONSTRAINT_SCHEMA='" + database.correctObjectName(schema.getName(), Schema.class) + "'\n" //+ "T2.TABLE_NAME='"+ database.correctObjectName(example.getTable().getName(), Table.class) + "'\n" //+ "\n" + "order by T2.COLUMN_NAME\n"; } else { sql = "select k.constname as constraint_name, k.colname as column_name from syscat.keycoluse k, syscat.tabconst t " + "where k.constname = t.constname " + "and k.tabschema = t.tabschema " + "and t.type='U' " + (bulkQuery? "" : "and k.constname='" + database.correctObjectName(name, UniqueConstraint.class) + "' ") + "and t.tabschema = '" + database.correctObjectName(schema.getName(), Schema.class) + "' " + "order by colseq"; } } else if (database instanceof Db2zDatabase) { sql = "select k.colname as column_name from SYSIBM.SYSKEYCOLUSE k, SYSIBM.SYSTABCONST t " + "where k.constname = t.constname " + "and k.TBCREATOR = t.TBCREATOR " + "and t.type = 'U'" + "and k.constname='" + database.correctObjectName(name, UniqueConstraint.class) + "' " + "and t.TBCREATOR = '" + database.correctObjectName(schema.getName(), Schema.class) + "' " + "order by colseq"; } else if (database instanceof DerbyDatabase) { //does not support bulkQuery, supportsBulkQuery should return false() sql = "SELECT cg.descriptor as descriptor, t.tablename " + "FROM sys.sysconglomerates cg " + "JOIN sys.syskeys k ON cg.conglomerateid = k.conglomerateid " + "JOIN sys.sysconstraints c ON c.constraintid = k.constraintid " + "JOIN sys.systables t ON c.tableid = t.tableid " + "WHERE c.constraintname='" + database.correctObjectName(name, UniqueConstraint.class) + "'"; List<Map<String, ?>> rows = Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", database).queryForList(new RawSqlStatement(sql)); List<Map<String, ?>> returnList = new ArrayList<>(); if (rows.isEmpty()) { return returnList; } else if (rows.size() > 1) { throw new UnexpectedLiquibaseException("Got multiple rows back querying unique constraints"); } else { Map rowData = rows.get(0); String descriptor = rowData.get("DESCRIPTOR").toString(); descriptor = descriptor.replaceFirst(".*\\(", "").replaceFirst("\\).*", ""); for (String columnNumber : StringUtil.splitAndTrim(descriptor, ",")) { String columnName = Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", database).queryForObject(new RawSqlStatement( "select c.columnname from sys.syscolumns c " + "join sys.systables t on t.tableid=c.referenceid " + "where t.tablename='" + rowData.get("TABLENAME") + "' and c.columnnumber=" + columnNumber), String.class); Map<String, String> row = new HashMap<>(); row.put("COLUMN_NAME", columnName); returnList.add(row); } return returnList; } } else if (database instanceof FirebirdDatabase) { //does not support bulkQuery, supportsBulkQuery should return false() // Careful! FIELD_NAME and INDEX_NAME in RDB$INDEX_SEGMENTS are CHAR, not VARCHAR columns. sql = "SELECT TRIM(RDB$INDEX_SEGMENTS.RDB$FIELD_NAME) AS column_name " + "FROM RDB$INDEX_SEGMENTS " + "LEFT JOIN RDB$INDICES ON RDB$INDICES.RDB$INDEX_NAME = RDB$INDEX_SEGMENTS.RDB$INDEX_NAME " + "WHERE UPPER(TRIM(RDB$INDICES.RDB$INDEX_NAME))='" + database.correctObjectName(name, UniqueConstraint.class) + "' " + "ORDER BY RDB$INDEX_SEGMENTS.RDB$FIELD_POSITION"; } else if (database instanceof SybaseASADatabase) { //does not support bulkQuery, supportsBulkQuery should return false() sql = "select sysconstraint.constraint_name, syscolumn.column_name " + "from sysconstraint, syscolumn, systable " + "where sysconstraint.ref_object_id = syscolumn.object_id " + "and sysconstraint.table_object_id = systable.object_id " + "and sysconstraint.constraint_name = '" + database.correctObjectName(name, UniqueConstraint.class) + "' " + "and systable.table_name = '" + database.correctObjectName(example.getRelation().getName(), Table.class) + "'"; } else if(database instanceof Ingres9Database) { //does not support bulkQuery, supportsBulkQuery should return false() sql = "select constraint_name, column_name " + "from iikeys " + "where constraint_name = '" + database.correctObjectName(name, UniqueConstraint.class) + "' " + "and table_name = '" + database.correctObjectName(example.getTable().getName(), Table.class) + "'"; } else if (database instanceof InformixDatabase) { //does not support bulkQuery, supportsBulkQuery should return false() sql = getUniqueConstraintsSqlInformix((InformixDatabase) database, schema, name); } else if (database instanceof Db2zDatabase) { sql = "select KC.TBCREATOR as CONSTRAINT_CONTAINER, KC.CONSTNAME as CONSTRAINT_NAME, KC.COLNAME as COLUMN_NAME from SYSIBM.SYSKEYCOLUSE KC, SYSIBM.SYSTABCONST TC " + "where KC.CONSTNAME = TC.CONSTNAME " + "and KC.TBCREATOR = TC.TBCREATOR " + "and TC.TYPE='U' " + (bulkQuery ? "" : "and KC.CONSTNAME='" + database.correctObjectName(name, UniqueConstraint.class) + "' ") + "and TC.TBCREATOR = '" + database.correctObjectName(schema.getName(), Schema.class) + "' " + "order by KC.COLSEQ"; } else if (database instanceof H2Database && database.getDatabaseMajorVersion() >= 2) { String catalogName = database.correctObjectName(schema.getCatalogName(), Catalog.class); String schemaName = database.correctObjectName(schema.getName(), Schema.class); String constraintName = database.correctObjectName(name, UniqueConstraint.class); String tableName = database.correctObjectName(table.getName(), Table.class); sql = "select table_constraints.CONSTRAINT_NAME, index_columns.COLUMN_NAME, table_constraints.constraint_schema as CONSTRAINT_CONTAINER " + "from information_schema.table_constraints " + "join information_schema.index_columns on index_columns.index_name=table_constraints.index_name " + "where constraint_type='UNIQUE' "; if (catalogName != null) { sql += "and constraint_catalog='" + catalogName + "' "; } if (schemaName != null) { sql += "and constraint_schema='" + schemaName + "' "; } if (!bulkQuery) { if (tableName != null) { sql += "and table_constraints.table_name='" + tableName + "' "; } if (constraintName != null) { sql += "and constraint_name='" + constraintName + "'"; } } } else { // If we do not have a specific handler for the RDBMS, we assume that the database has an // INFORMATION_SCHEMA we can use. This is a last-resort measure and might fail. String catalogName = database.correctObjectName(schema.getCatalogName(), Catalog.class); String schemaName = database.correctObjectName(schema.getName(), Schema.class); String constraintName = database.correctObjectName(name, UniqueConstraint.class); String tableName = database.correctObjectName(table.getName(), Table.class); sql = "select CONSTRAINT_NAME, COLUMN_LIST as COLUMN_NAME, constraint_schema as CONSTRAINT_CONTAINER " + "from " + database.getSystemSchema() + ".constraints " + "where constraint_type='UNIQUE' "; if (catalogName != null) { sql += "and constraint_catalog='" + catalogName + "' "; } if (schemaName != null) { sql += "and constraint_schema='" + schemaName + "' "; } if (!bulkQuery) { if (tableName != null) { sql += "and table_name='" + tableName + "' "; } if (constraintName != null) { sql += "and constraint_name='" + constraintName + "'"; } } } List<Map<String, ?>> rows = Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", database).queryForList(new RawSqlStatement(sql)); if (bulkQuery) { columnCache = new HashMap<>(); snapshot.setScratchData(cacheKey, columnCache); for (Map<String, ?> row : rows) { String key = getCacheKey(row, database); List<Map<String, ?>> constraintRows = columnCache.get(key); if (constraintRows == null) { constraintRows = new ArrayList<>(); columnCache.put(key, constraintRows); } constraintRows.add(row); } return listColumns(example, database, snapshot); } else { return rows; } } else { String lookupKey = getCacheKey(example, database); List<Map<String, ?>> rows = columnCache.get(lookupKey); if (rows == null) { rows = new ArrayList<>(); } return rows; } } /** * Should the given database include the table name in the key? * Databases that need to include the table names are ones where unique constraint names do not have to be unique * within the schema. * * Currently only mysql is known to have non-unique constraint names. * * If this returns true, the database-specific query in {@link #listColumns(UniqueConstraint, Database, DatabaseSnapshot)} must include * a TABLE_NAME column in the results for {@link #getCacheKey(Map, Database)} to use. */ protected boolean includeTableNameInCacheKey(Database database) { return database instanceof MySQLDatabase; } /** * Return the cache key for the given UniqueConstraint. Must return the same result as {@link #getCacheKey(Map, Database)}. * Default implementation uses {@link #includeTableNameInCacheKey(Database)} to determine if the table name should be included in the key or not. */ protected String getCacheKey(UniqueConstraint example, Database database) { if (includeTableNameInCacheKey(database)) { return example.getSchema().getName() + "_" + example.getRelation() + "_" + example.getName(); } else { return example.getSchema().getName() + "_" + example.getName(); } } /** * Return the cache key for the given query row. Must return the same result as {@link #getCacheKey(UniqueConstraint, Database)} * Default implementation uses {@link #includeTableNameInCacheKey(Database)} to determine if the table name should be included in the key or not. */ protected String getCacheKey(Map<String, ?> row, Database database) { if (includeTableNameInCacheKey(database)) { return row.get("CONSTRAINT_CONTAINER") + "_" + row.get("TABLE_NAME") + "_" + row.get("CONSTRAINT_NAME"); } else { return row.get("CONSTRAINT_CONTAINER") + "_" + row.get("CONSTRAINT_NAME"); } } /** * To support bulk query, the resultSet must include a CONSTRAINT_CONTAINER column for caching purposes */ protected boolean supportsBulkQuery(Database database) { return !(database instanceof DerbyDatabase) && !(database instanceof FirebirdDatabase) && !(database instanceof SybaseASADatabase) && !(database instanceof Ingres9Database) && !(database instanceof InformixDatabase); } /** * Gets an SQL query that returns the constraint names and columns for all UNIQUE constraints. * * @param database A database object of the InformixDatabase type * @param schema Name of the schema to examine (or null for all) * @param name Name of the constraint to examine (or null for all) * @return A lengthy SQL statement that fetches the constraint names and columns */ private String getUniqueConstraintsSqlInformix(InformixDatabase database, Schema schema, String name) { StringBuilder sqlBuf = new StringBuilder(); sqlBuf.append("SELECT * FROM (\n"); // Yes, I am serious about this. It appears there are neither CTE/WITH clauses nor PIVOT/UNPIVOT operators // in Informix SQL. for (int i = 1; i <= 16; i++) { if (i > 1) sqlBuf.append("UNION ALL\n"); sqlBuf.append( String.format(" SELECT\n" + " CONS.owner,\n" + " CONS.constrname AS constraint_name,\n" + " COL.colname AS column_name,\n" + " CONS.constrtype,\n" + " %d AS column_index\n" + " FROM informix.sysconstraints CONS\n" + " JOIN informix.sysindexes IDX ON CONS.idxname = IDX.idxname\n" + " JOIN informix.syscolumns COL ON COL.tabid = CONS.tabid AND COL.colno = IDX.part%d\n", i, i ) ); } // Finish the subquery and filter on the U(NIQUE) constraint type sqlBuf.append( " ) SUBQ\n" + "WHERE constrtype='U' \n"); String catalogName = database.correctObjectName(schema.getCatalogName(), Catalog.class); String constraintName = database.correctObjectName(name, UniqueConstraint.class); // If possible, filter for catalog name and/or constraint name if (catalogName != null) { sqlBuf.append("AND owner='").append(catalogName).append("'\n"); } if (constraintName != null) { sqlBuf.append("AND constraint_name='").append(constraintName).append("'"); } // For correct processing, it is important that we get all columns in order. sqlBuf.append("ORDER BY owner, constraint_name, column_index"); // Return the query return sqlBuf.toString(); } }
apache-2.0
shareactorIO/pipeline
gpu.ml/Dockerfile
6640
FROM fluxcapacitor/package-tensorflow-2a48110-4d0a571-gpu:master WORKDIR /root # Based on the following: https://github.com/jupyterhub/jupyterhub/blob/master/Dockerfile # install nodejs, utf8 locale ENV DEBIAN_FRONTEND noninteractive RUN apt-get -y update && \ apt-get -y upgrade && \ apt-get -y install npm nodejs nodejs-legacy wget locales git # libav-tools for matplotlib anim RUN apt-get update && \ apt-get install -y --no-install-recommends libav-tools && \ apt-get clean # rm -rf /var/lib/apt/lists/* # Install JupyterHub dependencies RUN npm install -g configurable-http-proxy && rm -rf ~/.npm RUN \ conda install --yes -c conda-forge jupyterhub==0.7.2 \ && conda install --yes ipykernel==4.6.0 \ && conda install --yes notebook==5.0.0 \ && conda install --yes -c conda-forge jupyter_contrib_nbextensions==0.2.7 \ && conda install --yes ipywidgets==6.0.0 \ && conda install --yes -c anaconda-nb-extensions anaconda-nb-extensions==1.0.0 \ && conda install --yes -c conda-forge findspark==1.0.0 RUN \ pip install jupyterlab==0.19.0 \ && pip install jupyterlab_widgets==0.6.15 \ && pip install widgetslabextension==0.1.0 RUN \ jupyter labextension install --sys-prefix --py jupyterlab_widgets \ && jupyter labextension enable --sys-prefix --py jupyterlab_widgets \ && jupyter serverextension enable --py jupyterlab --sys-prefix # Install non-secure dummyauthenticator for jupyterhub (dev purposes only) RUN \ pip install jupyterhub-dummyauthenticator==0.1 RUN \ pip install jupyterhub-simplespawner==0.1 RUN \ conda install --yes nbconvert==5.1.1 \ && conda install --yes graphviz==2.38.0 \ && conda install --yes seaborn==0.7.1 RUN \ pip install grpcio \ && pip install git+https://github.com/wiliamsouza/hystrix-py.git # Spark ENV \ SPARK_VERSION=2.1.0 \ PYSPARK_VERSION=0.10.4 RUN \ # This is not a custom version of Spark. It's merely a version with all the desired -P profiles enabled. wget https://s3.amazonaws.com/fluxcapacitor.com/packages/spark-${SPARK_VERSION}-bin-fluxcapacitor.tgz \ && tar xvzf spark-${SPARK_VERSION}-bin-fluxcapacitor.tgz \ && rm spark-${SPARK_VERSION}-bin-fluxcapacitor.tgz ENV \ SPARK_HOME=/root/spark-${SPARK_VERSION}-bin-fluxcapacitor # This must be separate from the ${SPARK_HOME} ENV definition or else Docker doesn't recognize it ENV \ PATH=${SPARK_HOME}/bin:$PATH RUN \ git clone https://github.com/fluxcapacitor/pipeline.git RUN \ ln -s pipeline/gpu.ml/src \ && ln -s pipeline/gpu.ml/notebooks \ && mkdir -p /root/.ipython \ && cd /root/.ipython \ && ln -s pipeline/gpu.ml/profiles \ && cd ~ \ && ln -s pipeline/gpu.ml/config \ && ln -s pipeline/gpu.ml/html \ && ln -s pipeline/gpu.ml/run \ && ln -s pipeline/gpu.ml/lib \ && ln -s pipeline/gpu.ml/apache-jmeter-3.1 \ && ln -s pipeline/gpu.ml/tests \ && ln -s pipeline/gpu.ml/datasets \ && ln -s pipeline/gpu.ml/scripts # Hadoop/HDFS ENV \ HADOOP_VERSION=2.7.2 RUN \ wget http://www.apache.org/dist/hadoop/common/hadoop-${HADOOP_VERSION}/hadoop-${HADOOP_VERSION}.tar.gz \ && tar xvzf hadoop-${HADOOP_VERSION}.tar.gz \ && rm hadoop-${HADOOP_VERSION}.tar.gz ENV \ HADOOP_HOME=/root/hadoop-${HADOOP_VERSION} \ HADOOP_OPTS=-Djava.net.preferIPv4Stack=true # This must be separate from the ${HADOOP_HOME} ENV definition or else Docker doesn't recognize it ENV \ HADOOP_CONF=${HADOOP_HOME}/etc/hadoop/ \ PATH=${HADOOP_HOME}/bin:${HADOOP_HOME}/sbin:${PATH} # Required by Tensorflow ENV \ HADOOP_HDFS_HOME=${HADOOP_HOME} # Required by Tensorflow for HDFS RUN \ echo 'export CLASSPATH=$(${HADOOP_HDFS_HOME}/bin/hadoop classpath --glob)' >> /root/.bashrc RUN \ echo 'CLASSPATH=$(${HADOOP_HDFS_HOME}/bin/hadoop classpath --glob)' >> /etc/environment ENV \ LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${JAVA_HOME}/jre/lib/amd64/server # Required by Spark ENV \ HADOOP_CONF_DIR=${HADOOP_CONF} RUN \ cd ${SPARK_HOME}/conf \ && ln -s /root/config/spark/core-site.xml \ && ln -s /root/config/spark/fairscheduler.xml \ && ln -s /root/config/spark/hdfs-site.xml \ && ln -s /root/config/spark/hive-site.xml \ && ln -s /root/config/spark/spark-defaults.conf RUN \ mv ${HADOOP_CONF}/core-site.xml ${HADOOP_CONF}/core-site.xml.orig \ && cd ${HADOOP_CONF} \ && ln -s /root/config/hadoop/core-site.xml RUN \ mv ${HADOOP_CONF}/hdfs-site.xml ${HADOOP_CONF}/hdfs-site.xml.orig \ && cd ${HADOOP_CONF} \ && ln -s /root/config/hadoop/hdfs-site.xml RUN \ apt-get update \ && apt-get install -y ssh RUN \ sed -i s/#PermitRootLogin.*/PermitRootLogin\ yes/ /etc/ssh/sshd_config \ && sed -i s/#.*StrictHostKeyChecking.*/StrictHostKeyChecking\ no/ /etc/ssh/ssh_config \ && ssh-keygen -A \ && ssh-keygen -t rsa -f /root/.ssh/id_rsa -q -N "" \ && cat /root/.ssh/id_rsa.pub > /root/.ssh/authorized_keys RUN \ sed -i "s%<HADOOP_HOME>%${HADOOP_HOME}%" ${HADOOP_CONF}/*.xml \ && sed -i "s%\${JAVA_HOME}%${JAVA_HOME}%" ${HADOOP_CONF}/hadoop-env.sh RUN \ hadoop namenode -format # Hue (port 8000) #RUN \ # wget https://dl.dropboxusercontent.com/u/730827/hue/releases/3.12.0/hue-3.12.0.tgz \ # && tar xvzf hue-3.12.0.tgz \ # && rm hue-3.12.0.tgz # Required by sshd RUN \ mkdir /var/run/sshd RUN \ cd ~/lib/jni \ && ln -s ~/lib/jni/libtensorflow_jni-gpu.so libtensorflow_jni.so ENV \ TF_CPP_MIN_LOG_LEVEL=0 \ TF_XLA_FLAGS=--xla_generate_hlo_graph=.* ENV \ PATH=$TENSORFLOW_HOME/bazel-bin/tensorflow/tools/graph_transforms:$TENSORFLOW_HOME/bazel-bin/tensorflow/python/tools:$TENSORFLOW_HOME/bazel-bin/tensorflow/tools/benchmark/:$TENSORFLOW_HOME/bazel-bin/tensorflow/compiler/aot:$TENSORFLOW_HOME/bazel-bin/tensorflow/compiler/tests:$TENSORFLOW_HOME/bazel-bin/tensorflow/examples/tutorials/word2vec:$TENSORFLOW_HOME/bazel-bin/tensorflow/examples/tutorials/mnist:/root/apache-jmeter-3.1/bin/:/root/scripts:$PATH RUN \ conda install --yes graphviz RUN \ mkdir -p /root/tensorboard RUN \ mkdir -p /root/models RUN \ mkdir -p /root/logs # Apache2 RUN \ apt-get install -y apache2 RUN \ a2enmod proxy \ && a2enmod proxy_http \ && a2dissite 000-default RUN \ mv /var/www/html /var/www/html.orig RUN \ mv /etc/apache2/apache2.conf /etc/apache2/apache2.conf.orig # All paths (dirs, not files) up to and including /root must have +x permissions. # It's just the way linux works. Don't fight it. # http://askubuntu.com/questions/537032/how-to-configure-apache2-with-symbolic-links-in-var-www RUN \ chmod a+x /root EXPOSE 80 50070 39000 9000 9001 9002 9003 9004 6006 8754 7077 6066 6060 6061 4040 4041 4042 4043 4044 2222 # 8000 CMD ["supervise", "."]
apache-2.0
google/blockly
tests/mocha/connection_checker_test.js
12098
/** * @license * Copyright 2020 Google LLC * SPDX-License-Identifier: Apache-2.0 */ goog.module('Blockly.test.connectionChecker'); const {ConnectionType} = goog.require('Blockly.ConnectionType'); const {sharedTestSetup, sharedTestTeardown} = goog.require('Blockly.test.helpers'); suite('Connection checker', function() { setup(function() { sharedTestSetup.call(this); }); teardown(function() { sharedTestTeardown.call(this); }); suiteSetup(function() { this.checker = new Blockly.ConnectionChecker(); }); suite('Safety checks', function() { function assertReasonHelper(checker, one, two, reason) { chai.assert.equal(checker.canConnectWithReason(one, two), reason); // Order should not matter. chai.assert.equal(checker.canConnectWithReason(two, one), reason); } test('Target Null', function() { const connection = new Blockly.Connection({}, ConnectionType.INPUT_VALUE); assertReasonHelper( this.checker, connection, null, Blockly.Connection.REASON_TARGET_NULL); }); test('Target Self', function() { const block = {workspace: 1}; const connection1 = new Blockly.Connection(block, ConnectionType.INPUT_VALUE); const connection2 = new Blockly.Connection(block, ConnectionType.OUTPUT_VALUE); assertReasonHelper( this.checker, connection1, connection2, Blockly.Connection.REASON_SELF_CONNECTION); }); test('Different Workspaces', function() { const connection1 = new Blockly.Connection( {workspace: 1}, ConnectionType.INPUT_VALUE); const connection2 = new Blockly.Connection( {workspace: 2}, ConnectionType.OUTPUT_VALUE); assertReasonHelper( this.checker, connection1, connection2, Blockly.Connection.REASON_DIFFERENT_WORKSPACES); }); suite('Types', function() { setup(function() { // We have to declare each separately so that the connections belong // on different blocks. const prevBlock = {isShadow: function() {}}; const nextBlock = {isShadow: function() {}}; const outBlock = {isShadow: function() {}}; const inBlock = {isShadow: function() {}}; this.previous = new Blockly.Connection( prevBlock, ConnectionType.PREVIOUS_STATEMENT); this.next = new Blockly.Connection( nextBlock, ConnectionType.NEXT_STATEMENT); this.output = new Blockly.Connection( outBlock, ConnectionType.OUTPUT_VALUE); this.input = new Blockly.Connection( inBlock, ConnectionType.INPUT_VALUE); }); test('Previous, Next', function() { assertReasonHelper( this.checker, this.previous, this.next, Blockly.Connection.CAN_CONNECT); }); test('Previous, Output', function() { assertReasonHelper( this.checker, this.previous, this.output, Blockly.Connection.REASON_WRONG_TYPE); }); test('Previous, Input', function() { assertReasonHelper( this.checker, this.previous, this.input, Blockly.Connection.REASON_WRONG_TYPE); }); test('Next, Previous', function() { assertReasonHelper( this.checker, this.next, this.previous, Blockly.Connection.CAN_CONNECT); }); test('Next, Output', function() { assertReasonHelper( this.checker, this.next, this.output, Blockly.Connection.REASON_WRONG_TYPE); }); test('Next, Input', function() { assertReasonHelper( this.checker, this.next, this.input, Blockly.Connection.REASON_WRONG_TYPE); }); test('Output, Previous', function() { assertReasonHelper( this.checker, this.previous, this.output, Blockly.Connection.REASON_WRONG_TYPE); }); test('Output, Next', function() { assertReasonHelper( this.checker, this.output, this.next, Blockly.Connection.REASON_WRONG_TYPE); }); test('Output, Input', function() { assertReasonHelper( this.checker, this.output, this.input, Blockly.Connection.CAN_CONNECT); }); test('Input, Previous', function() { assertReasonHelper( this.checker, this.previous, this.input, Blockly.Connection.REASON_WRONG_TYPE); }); test('Input, Next', function() { assertReasonHelper( this.checker, this.input, this.next, Blockly.Connection.REASON_WRONG_TYPE); }); test('Input, Output', function() { assertReasonHelper( this.checker, this.input, this.output, Blockly.Connection.CAN_CONNECT); }); }); suite('Shadows', function() { test('Previous Shadow', function() { const prevBlock = {isShadow: function() {return true;}}; const nextBlock = {isShadow: function() {return false;}}; const prev = new Blockly.Connection(prevBlock, ConnectionType.PREVIOUS_STATEMENT); const next = new Blockly.Connection(nextBlock, ConnectionType.NEXT_STATEMENT); assertReasonHelper( this.checker, prev, next, Blockly.Connection.CAN_CONNECT); }); test('Next Shadow', function() { const prevBlock = {isShadow: function() {return false;}}; const nextBlock = {isShadow: function() {return true;}}; const prev = new Blockly.Connection(prevBlock, ConnectionType.PREVIOUS_STATEMENT); const next = new Blockly.Connection(nextBlock, ConnectionType.NEXT_STATEMENT); assertReasonHelper( this.checker, prev, next, Blockly.Connection.REASON_SHADOW_PARENT); }); test('Prev and Next Shadow', function() { const prevBlock = {isShadow: function() {return true;}}; const nextBlock = {isShadow: function() {return true;}}; const prev = new Blockly.Connection(prevBlock, ConnectionType.PREVIOUS_STATEMENT); const next = new Blockly.Connection(nextBlock, ConnectionType.NEXT_STATEMENT); assertReasonHelper( this.checker, prev, next, Blockly.Connection.CAN_CONNECT); }); test('Output Shadow', function() { const outBlock = {isShadow: function() {return true;}}; const inBlock = {isShadow: function() {return false;}}; const outCon = new Blockly.Connection(outBlock, ConnectionType.OUTPUT_VALUE); const inCon = new Blockly.Connection(inBlock, ConnectionType.INPUT_VALUE); assertReasonHelper( this.checker, outCon, inCon, Blockly.Connection.CAN_CONNECT); }); test('Input Shadow', function() { const outBlock = {isShadow: function() {return false;}}; const inBlock = {isShadow: function() {return true;}}; const outCon = new Blockly.Connection(outBlock, ConnectionType.OUTPUT_VALUE); const inCon = new Blockly.Connection(inBlock, ConnectionType.INPUT_VALUE); assertReasonHelper( this.checker, outCon, inCon, Blockly.Connection.REASON_SHADOW_PARENT); }); test('Output and Input Shadow', function() { const outBlock = {isShadow: function() {return true;}}; const inBlock = {isShadow: function() {return true;}}; const outCon = new Blockly.Connection(outBlock, ConnectionType.OUTPUT_VALUE); const inCon = new Blockly.Connection(inBlock, ConnectionType.INPUT_VALUE); assertReasonHelper( this.checker, outCon, inCon, Blockly.Connection.CAN_CONNECT); }); }); suite('Output and Previous', function() { /** * Update two connections to target each other. * @param {Connection} first The first connection to update. * @param {Connection} second The second connection to update. */ const connectReciprocally = function(first, second) { if (!first || !second) { throw Error('Cannot connect null connections.'); } first.targetConnection = second; second.targetConnection = first; }; test('Output connected, adding previous', function() { const outBlock = { isShadow: function() { }, }; const inBlock = { isShadow: function() { }, }; const outCon = new Blockly.Connection(outBlock, ConnectionType.OUTPUT_VALUE); const inCon = new Blockly.Connection(inBlock, ConnectionType.INPUT_VALUE); outBlock.outputConnection = outCon; inBlock.inputConnection = inCon; connectReciprocally(inCon, outCon); const prevCon = new Blockly.Connection(outBlock, ConnectionType.PREVIOUS_STATEMENT); const nextBlock = { isShadow: function() { }, }; const nextCon = new Blockly.Connection(nextBlock, ConnectionType.NEXT_STATEMENT); assertReasonHelper( this.checker, prevCon, nextCon, Blockly.Connection.REASON_PREVIOUS_AND_OUTPUT); }); test('Previous connected, adding output', function() { const prevBlock = { isShadow: function() { }, }; const nextBlock = { isShadow: function() { }, }; const prevCon = new Blockly.Connection(prevBlock, ConnectionType.PREVIOUS_STATEMENT); const nextCon = new Blockly.Connection(nextBlock, ConnectionType.NEXT_STATEMENT); prevBlock.previousConnection = prevCon; nextBlock.nextConnection = nextCon; connectReciprocally(prevCon, nextCon); const outCon = new Blockly.Connection(prevBlock, ConnectionType.OUTPUT_VALUE); const inBlock = { isShadow: function() { }, }; const inCon = new Blockly.Connection(inBlock, ConnectionType.INPUT_VALUE); assertReasonHelper( this.checker, outCon, inCon, Blockly.Connection.REASON_PREVIOUS_AND_OUTPUT); }); }); }); suite('Check Types', function() { setup(function() { this.con1 = new Blockly.Connection({}, ConnectionType.PREVIOUS_STATEMENT); this.con2 = new Blockly.Connection({}, ConnectionType.NEXT_STATEMENT); }); function assertCheckTypes(checker, one, two) { chai.assert.isTrue(checker.doTypeChecks(one, two)); // Order should not matter. chai.assert.isTrue(checker.doTypeChecks(one, two)); } test('No Types', function() { assertCheckTypes(this.checker, this.con1, this.con2); }); test('Same Type', function() { this.con1.setCheck('type1'); this.con2.setCheck('type1'); assertCheckTypes(this.checker, this.con1, this.con2); }); test('Same Types', function() { this.con1.setCheck(['type1', 'type2']); this.con2.setCheck(['type1', 'type2']); assertCheckTypes(this.checker, this.con1, this.con2); }); test('Single Same Type', function() { this.con1.setCheck(['type1', 'type2']); this.con2.setCheck(['type1', 'type3']); assertCheckTypes(this.checker, this.con1, this.con2); }); test('One Typed, One Promiscuous', function() { this.con1.setCheck('type1'); assertCheckTypes(this.checker, this.con1, this.con2); }); test('No Compatible Types', function() { this.con1.setCheck('type1'); this.con2.setCheck('type2'); chai.assert.isFalse(this.checker.doTypeChecks(this.con1, this.con2)); }); }); });
apache-2.0
google/googleapps-password-generator
templates/report.html
7491
{% extends "base.html" %} {% set active_page = "report" %} {% block title %}Reporting{% endblock title %} {% block head %} {{ super() }} {% endblock head %} {% block teleport_links %} {{ super() }} <a class="maia-teleport" href="#report_start_date">Skip to define the report start date</a> <a class="maia-teleport" href="#report_end_date">Skip to define report end date</a> <a class="maia-teleport" href="#report_user_email">Skip to define user email address</a> <a class="maia-teleport" href="#generate">Skip to generate report</a> {% endblock teleport_links %} {% block body %} {{ super() }} <div id="maia-main" role="main"> <div id="content" class="maia-teleport"></div> <div class="maia-cols"> <div class="maia-col-12"> <div class="maia-promo"> <form id=reporting action="/reporting" method="post"> <fieldset> <h1>Password Generator Reports</h1> <p> Search for password generations, by date only, by user only, or by date and user. </p><br> <ul> <li {% if reporting_form.start_date.errors %} class="maia-form-error" role="alert" {% endif %}> <div id="report_start_date" class="maia-teleport"></div> <label for="{{ reporting_form.start_date.id }}"> Report Start Date </label> <p class="maia-note"> Start date range of the report in the format of YYYY-MM-DD. </p> <input type="date" tabindex="1" name="{{ reporting_form.start_date.id }}"> {% if reporting_form.start_date.errors %} <div class="maia-form-error" role="alert"> {% for error in reporting_form.start_date.errors %} <p class="maia-form-error-msg">{{ error }}</p> {% endfor %} </div> {% endif %} </li> <li {% if reporting_form.end_date.errors %} class="maia-form-error" role="alert" {% endif %}> <div id="report_end_date" class="maia-teleport"></div> <label for="{{ reporting_form.end_date.id }}"> Report End Date </label> <p class="maia-note"> End date range of the report in the format of YYYY-MM-DD. </p> <input type="date" tabindex="2" name="{{ reporting_form.end_date.id }}"> {% if reporting_form.end_date.errors %} <div class="maia-form-error" role="alert"> {% for error in reporting_form.end_date.errors %} <p class="maia-form-error-msg">{{ error }}</p> {% endfor %} </div> {% endif %} </li> <li {% if reporting_form.user_email.errors %} class="maia-form-error" role="alert" {% endif %}> <div id="report_user_email" class="maia-teleport"></div> <label for="{{ reporting_form.user_email.id }}"> Filter by Email address </label> <p class="maia-note"> Enter an e-mail address to filter the report on a single user email address. </p> <input type="text" tabindex="3" name="{{ reporting_form.user_email.id }}"> {% if reporting_form.user_email.errors %} <div class="maia-form-error" role="alert"> {% for error in reporting_form.user_email.errors %} <p class="maia-form-error-msg">{{ error }}</p> {% endfor %} </div> {% endif %} </li> </ul> </fieldset> <input type="hidden" name="xsrf_token" value="{{ xsrf_token }}"> <div id="generate" class="maia-teleport"></div> <div> <input type="submit" class="maia-button" value="Generate" tabindex="4"> </div> </form> </div> {% if password_generations %} <h2>Password generation history</h2> <div class="maia-note"> <p> <a href="{{ download_report_url }}"> Download detailed report </a> </p> </div> <table> <tr> <th scope="col">Date</th> <th scope="col">Email</th> <th scope="col">Reason</th> <th scope="col">User-Agent</th> <th scope="col">IP Address</th> <th scope="col">Password Length</th> </tr> {% for password_generation in password_generations %} <tr> <td> {% if password_generation.date %} {{ password_generation.date.strftime('%m/%d/%Y %H:%M') }} {% else %} Unrecorded {% endif %} </td> <td> {% if password_generation.user.email() %} {{ password_generation.user.email() }} {% else %} Unrecorded {% endif %} </td> <td> {% if password_generation.reason %} {{ password_generation.reason|truncate(30, True) }} {% else %} Unrecorded {% endif %} </td> <td> {% if password_generation.user_agent %} {{ password_generation.user_agent|truncate(30, True) }} {% else %} Unrecorded {% endif %} </td> <td> {% if password_generation.user_ip_address %} {{ password_generation.user_ip_address }} {% else %} Unrecorded {% endif %} </td> <td> {% if password_generation.password_length %} {{ password_generation.password_length }} {% else %} Unrecorded {% endif %} </td> </tr> {% endfor %} </table> {% elif display_result_message %} <p>No results found. Please try again.</p> {% endif %} </div> </div> </div> <script type="text/javascript" src="//www.google.com/js/maia.js"></script> {% endblock body %}
apache-2.0
Complexible/basecrm
main/src/com/complexible/basecrm/Deal.java
2438
/* * Copyright (c) 2015 Complexible Inc. <http://complexible.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.complexible.basecrm; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; /** * <p></p> * * @author Michael Grove * @since 0.1 * @version 0.1 */ public class Deal extends BaseObject { private String mName; private String mStageName; private boolean mHot; private boolean mIsNew; private Contact mMainContact; private Contact mCompany; public Contact getCompany() { return mCompany; } public void setCompany(final Contact theCompany) { mCompany = theCompany; } public boolean isHot() { return mHot; } public void setHot(final boolean theHot) { mHot = theHot; } public boolean isNew() { return mIsNew; } public void setNew(final boolean theIsNew) { mIsNew = theIsNew; } public Contact getMainContact() { return mMainContact; } public void setMainContact(final Contact theMainContact) { mMainContact = theMainContact; } public String getName() { return mName; } public void setName(final String theName) { mName = theName; } public String getStageName() { return mStageName; } public void setStageName(final String theStageName) { mStageName = theStageName; } /** * @{inheritDoc} */ @Override public int hashCode() { return Objects.hashCode(mId, mName); } /** * @{inheritDoc} */ @Override public boolean equals(final Object theObj) { if (theObj == this) { return true; } else if (theObj instanceof Deal) { Deal aDeal = (Deal) theObj; return Objects.equal(mName, aDeal.mName) && Objects.equal(mId, aDeal.mId); } else { return false; } } /** * @{inheritDoc} */ @Override public String toString() { return MoreObjects.toStringHelper("Deal") .add("name", mName) .add("stage", mStageName) .add("company", mCompany) .toString(); } }
apache-2.0
Early-Modern-OCR/Cobre
libros/templates/registration/login.html
744
{% extends "main.html" %} {% block breadcrumb %}Login{% endblock %} {% block main_heading %}<h1>Login</h1>{% endblock %} {% block main_content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} <p>You can authenticate with this application using your Library Active Directory credentials.</p> <form method="post" action="{% url django.contrib.auth.views.login %}"> {% csrf_token %} <table> <tr> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password.label_tag }}</td> <td>{{ form.password }}</td> </tr> </table> <input type="submit" value="login" /> <input type="hidden" name="next" value="{{ next }}" /> </form> {% endblock %}
apache-2.0
FasterXML/jackson-databind
docs/javadoc/2.4/com/fasterxml/jackson/databind/ext/class-use/CoreXMLDeserializers.Std.html
4676
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_25) on Mon Jun 02 17:48:59 PDT 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class com.fasterxml.jackson.databind.ext.CoreXMLDeserializers.Std (jackson-databind 2.4.0 API)</title> <meta name="date" content="2014-06-02"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.fasterxml.jackson.databind.ext.CoreXMLDeserializers.Std (jackson-databind 2.4.0 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../com/fasterxml/jackson/databind/ext/CoreXMLDeserializers.Std.html" title="class in com.fasterxml.jackson.databind.ext">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?com/fasterxml/jackson/databind/ext/class-use/CoreXMLDeserializers.Std.html" target="_top">Frames</a></li> <li><a href="CoreXMLDeserializers.Std.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class com.fasterxml.jackson.databind.ext.CoreXMLDeserializers.Std" class="title">Uses of Class<br>com.fasterxml.jackson.databind.ext.CoreXMLDeserializers.Std</h2> </div> <div class="classUseContainer">No usage of com.fasterxml.jackson.databind.ext.CoreXMLDeserializers.Std</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../com/fasterxml/jackson/databind/ext/CoreXMLDeserializers.Std.html" title="class in com.fasterxml.jackson.databind.ext">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?com/fasterxml/jackson/databind/ext/class-use/CoreXMLDeserializers.Std.html" target="_top">Frames</a></li> <li><a href="CoreXMLDeserializers.Std.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2014 <a href="http://fasterxml.com/">FasterXML</a>. All Rights Reserved.</small></p> </body> </html>
apache-2.0
DuoSoftware/DVP-Apps
DVP-RuleConfigurationApplication/partials/newrule.html
5068
<div layout="column" flex-lt-md="80%"> <md-content layout-padding style="background-color: lightgrey" > <form name="newRuleForm" > <md-subheader class="md-no-sticky" style="background-color: #cccccc"><h2>{{frmTopic}}</h2></md-subheader> <div layout-gt-sm="row"> <md-input-container class="md-block" flex-gt-sm> <label style="color: blue" >Direction</label> <input type="text" name = "Direction" ng-model="newObj.Direction" required readonly/> <span style="color:red" ng-show="newRuleForm.Direction.$dirty && newRuleForm.Direction.$invalid"></span> </md-input-container> </div> <div layout-gt-sm="row"> <md-input-container class="md-block" flex-gt-sm> <label style="color: blue" >Description</label> <input type="text" name = "Description" ng-model="newObj.CallRuleDescription" required /> <span style="color:red" ng-show="newRuleForm.Description.$dirty && newRuleForm.Description.$invalid"></span> </md-input-container> </div> <div layout-gt-sm="row"> <md-input-container class="md-block" flex-gt-sm> <md-select name = "DregEx" ng-model="newObj.RegExPattern" ng-model-options="{trackBy: '$value'}" required ng-change="onDINISChange()"> <md-option value=STARTWITH selected>STARTWITH</md-option> <md-option value=EXACTMATCH>EXACTMATCH</md-option> <md-option value=ANY>ANY</md-option> <md-option value=CUSTOM>CUSTOM</md-option> </md-select> </md-input-container> <md-input-container class="md-block" flex-gt-sm> <label style="color: blue" >DNIS</label> <input type="text" name = "DNIS" ng-model="newObj.DNIS" ng-disabled="!isDNISRequired" ng-required="isDNISRequired" /> <span style="color:red" ng-show="newRuleForm.DNIS.$dirty && newRuleForm.DNIS.$invalid"></span> </md-input-container> </div> <div layout-gt-sm="row"> <md-input-container class="md-block" flex-gt-sm> <md-select name = "AregEx" ng-model="newObj.ANIRegExPattern" ng-model-options="{trackBy: '$value'}" required ng-change="onANISChange()"> <md-option value=STARTWITH selected>STARTWITH</md-option> <md-option value=EXACTMATCH>EXACTMATCH</md-option> <md-option value=ANY>ANY</md-option> <md-option value=CUSTOM>CUSTOM</md-option> </md-select> </md-input-container> <md-input-container class="md-block" flex-gt-sm> <label style="color: blue" >ANI</label> <input type="text" name = "ANI" ng-model="newObj.ANI" ng-disabled="!isANIRequired" ng-required="isANIRequired" /> <span style="color:red" ng-show="newRuleForm.ANI.$dirty && newRuleForm.ANI.$invalid"></span> </md-input-container> </div> <div layout-gt-sm="row"> <md-input-container name= "Context" class="md-block" flex-gt-sm> <label>Context</label> <md-select ng-model="newObj.Context" name = "Context" > <md-option ng-repeat="context in contextData" value="{{context.Context}}" ng-model-options="{trackBy: '$value'}"> {{context.Context}} </md-option> </md-select> </md-input-container> <div flex="5" hide-xs hide-sm> <!-- Spacer //--> </div> <md-input-container name= "Priority" class="md-block" flex-gt-sm> <label>Priority</label> <input type="number" name = "PriorityTxt" ng-model="newObj.Priority" required /> </md-input-container> </div> <div layout-gt-sm="row" class="animate-if" ng-hide="isInRule"> <md-input-container name= "TrunkIDCnt" class="md-block" flex-gt-sm> <label>Trunk Number</label> <md-select ng-model="newObj.TrunkNumber" name = "TrunkId" > <md-option ng-repeat="trunk in trunkObj" value="{{trunk.PhoneNumber}}" ng-model-options="{trackBy: '$value'}" ng-selected="$first" required> {{trunk.PhoneNumber}} </md-option> </md-select> </md-input-container> </div> <div layout-gt-sm="row"> <md-input-container name= "Status" class="md-block" flex-gt-sm> Active Status <md-switch ng-model="newObj.Enable" > </md-switch> </md-input-container> </div> <div layout-gt-sm="row"> <md-input-container style="background-color: lightgrey ;padding: 0% 0% 0% 80%"> <md-button class="md-icon-button" class="md-raised md-primary" ng-click="SaveRule()" ng-disabled="isDisabled || newRuleForm.$invalid "><md-icon md-svg-src="../img/ic_save_24px.svg"></md-icon></md-button><md-button class="md-icon-button" class="md-raised md-primary" ng-click="hideView()" ng-disabled="isDisabled"><md-icon md-svg-src="../img/ic_arrow_back_24px.svg"></md-button></td> </md-input-container> </div> </form> </md-content> </div>
apache-2.0
wanglilong007/rest_assured_framework
src/main/java/com/resource/RscValidator.java
504
package com.resource; public abstract class RscValidator { public ValidatorConfiguration config; public RscValidator(){} public RscValidator(ValidatorConfiguration config){ this.config = config; } public void set_config(ValidatorConfiguration config){ this.config = config; } public abstract void init(); public abstract void head(); public abstract void options(); public abstract void get(); public abstract void post(); public abstract void put(); public abstract void delete(); }
apache-2.0
spring-cloud/spring-cloud-gcp
spring-cloud-gcp-samples/spring-cloud-gcp-vision-ocr-demo/src/main/resources/templates/viewDocument.html
467
<!DOCTYPE HTML> <html xmlns:th="https://www.thymeleaf.org"> <head> <title>View Document Text</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link type="text/css" href="css/style.css" rel="stylesheet"/> </head> <body> <h1>Text from [[${gcsDocumentUrl}]]</h1> <p> <a href="/status">Back to Status Page</a> </p> <p> First 50 words of on page [[${pageNumber}]]: </p> <p id="extracted_text"> [[${text}]] </p> </body> </html>
apache-2.0
mashibing/rocketmq-client4cpp
src/consumer/ConsumeMessageService.h
1166
/** * Copyright (C) 2013 kangliqiang ,[email protected] * * 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. */ #if!defined __CONSUMEMESSAGESERVICE_H__ #define __CONSUMEMESSAGESERVICE_H__ #include <list> class MessageExt; class ProcessQueue; class MessageQueue; /** * Ïû·ÑÏûÏ¢·þÎñ£¬¹«¹²½Ó¿Ú * */ class ConsumeMessageService { public: virtual ~ConsumeMessageService() {} virtual void start()=0; virtual void shutdown()=0; virtual void updateCorePoolSize(int corePoolSize)=0; virtual void submitConsumeRequest(std::list<MessageExt*>* pMsgs, ProcessQueue* pProcessQueue, MessageQueue* pMessageQueue, bool dispathToConsume)=0; }; #endif
apache-2.0
zhongyiares/stockPolicy
src/main/webapp/stock/stu/h5CSS3/day4/day4_8.html
837
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> input:enabled{ border: 1px solid red; } input:disabled{ border: 1px solid green; } input:read-only{ border: 1px solid burlywood; } input:read-write{ border: 1px solid #0000aa; } input[type="radio"]:checked{ opacity:0.5; } </style> </head> <body> <form> <input type="radio" name="sex" checked>男 <input type="radio" name="sex">女 <input type="radio" name="sex">保密 <br/> <input type="text" value="123"><br/> <input type="text" disabled value="123"><br/> <input type="text" value="123" readonly><br/> <input type="text"><br/> </form> </body> </html>
apache-2.0
ezbake/ezbake-quarantine
quarantine-rest/README.md
332
## Quarantine Rest Service ### Running #### Locally via Maven: ``` mvn clean compile ``` ``` mvn jetty:run ``` #### EzCentos via [Jetty Runner]: ``` mvn clean package ``` ``` java -jar bin/jetty-runner.jar --port 8181 target/Quarantine.war ``` [Jetty Runner]: http://repo2.maven.org/maven2/org/mortbay/jetty/jetty-runner/
apache-2.0
eoasoft/evolve
application/modules/product/models/Series.php
1314
<?php /** * 2013-11-25 上午12:08:30 * @author x.li * @abstract */ class Product_Model_Series extends Application_Model_Db { /** * 表名、主键 */ protected $_name = 'product_catalog_series'; protected $_primary = 'id'; public function getData() { $sql = $this->select() ->setIntegrityCheck(false) ->from(array('t1' => $this->_name)) ->joinLeft(array('t2' => $this->_dbprefix.'user'), "t2.id = t1.create_user", array()) ->joinLeft(array('t3' => $this->_dbprefix.'employee'), "t3.id = t2.employee_id", array('creater' => 'cname')) ->joinLeft(array('t4' => $this->_dbprefix.'user'), "t4.id = t1.update_user", array()) ->joinLeft(array('t5' => $this->_dbprefix.'employee'), "t5.id = t4.employee_id", array('updater' => 'cname')) ->order(array('t1.name')); $data = $this->fetchAll($sql)->toArray(); for($i = 0; $i < count($data); $i++){ $data[$i]['create_time'] = strtotime($data[$i]['create_time']); $data[$i]['update_time'] = strtotime($data[$i]['update_time']); $data[$i]['active'] = $data[$i]['active'] == 1 ? true : false; } return $data; } }
apache-2.0
Orange-OpenSource/fiware-ngsi-api
ngsi-client/src/main/java/com/orange/ngsi/model/UpdateAction.java
1228
/* * Copyright (C) 2015 Orange * * 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.orange.ngsi.model; /** * Created by pborscia on 05/06/2015. */ public enum UpdateAction { UPDATE("UPDATE"),APPEND("APPEND"),DELETE("DELETE"); private String label; UpdateAction(String label) { this.label=label; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public Boolean isDelete() { return label.equals("DELETE"); } public Boolean isUpdate() { return label.equals("UPDATE"); } public Boolean isAppend() { return label.equals("APPEND"); } }
apache-2.0
alebarreiro/TSI2-AngularFront
app/scripts/directives/sidebar/sidebar.html
2267
<div class="navbar-default sidebar" role="navigation"> <div class="sidebar-nav navbar-collapse"> <ul class="nav in" id="side-menu"> <sidebar-search></sidebar-search> <li ui-sref-active="active"> <a ui-sref="dashboard.home"><i class="fa fa-dashboard fa-fw"></i> Dashboard</a> </li> <li ui-sref-active="active"> <a ui-sref="dashboard.chart"><i class="fa fa-bar-chart-o fa-fw"></i> Reportes<span></span></a> </li> <li ng-class="{active: collapseVar==2}"> <a href="" ng-click="check(2)"><i class="fa fa-sitemap fa-fw"></i> Almacenes <span class="fa arrow"></span></a> <ul class="nav nav-second-level" collapse="collapseVar!=2"> <li> <a ui-sref="dashboard.crearAlmacen.datos"> Crear almacén </a> </li> <li> <a ui-sref="dashboard.almacenes"> Mis almacenes </a> </li> <li> <a ui-sref="dashboard.almacenescolabora"> Almacenes que colaboro </a> </li> <li ng-init="third=!third" ng-class="{active: multiCollapseVar==3}"> <a href="" ng-click="multiCheck(3)"> Colaboradores <span class="fa arrow"></span></a> <ul class="nav nav-third-level" collapse="multiCollapseVar!=3"> <li> <a ui-sref="dashboard.agregarColaborador"> Agregar colaborador </a> </li> <li> <a ui-sref="dashboard.listarColaboradores"> Mis colaboradores </a> </li> </ul> <!-- /.nav-third-level --> </li> </ul> <!-- /.nav-second-level --> </li> <li ui-sref-active="active"> <a ui-sref="dashboard.notificaciones"><i class="fa fa-bell fa-fw"></i> Notificaciones <span></span></a> </li> </ul> </div> <!-- /.sidebar-collapse --> </div>
apache-2.0
mdoering/backbone
life/Plantae/Bacillariophyta/Bacillariophyceae/Cymbellales/Cymbellaceae/Cymbella/Cymbella falaisensis/README.md
212
# Cymbella falaisensis (Grunow) Krammer & Lange-Bertalot SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
saimandeper/ionic-site
_site/docs/1.0.1/api/directive/ionSpinner/index.html
33349
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Ionic makes it incredibly easy to build beautiful and interactive mobile apps using HTML5 and AngularJS."> <meta name="keywords" content="html5,javascript,mobile,drifty,ionic,hybrid,phonegap,cordova,native,ios,android,angularjs"> <meta name="author" content="Drifty"> <meta property="og:image" content="http://ionicframework.com/img/ionic-logo-blog.png"/> <title>ion-spinner - Directive in module ionic - Ionic Framework</title> <link href="/css/site.css?16" rel="stylesheet"> <!--<script src="//cdn.optimizely.com/js/595530035.js"></script>--> <script type="text/javascript">var _sf_startpt=(new Date()).getTime()</script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-44023830-1', 'ionicframework.com'); ga('send', 'pageview'); </script> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> </head> <body class="docs docs-page docs-api"> <nav class="navbar navbar-default horizontal-gradient" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle button ionic" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <i class="icon ion-navicon"></i> </button> <a class="navbar-brand" href="/"> <img src="/img/ionic-logo-white.svg" width="123" height="43" alt="Ionic Framework"> </a> <a href="http://blog.ionic.io/announcing-ionic-1-0/" target="_blank"> <img src="/img/ionic1-tag.png" alt="Ionic 1.0 is out!" width="28" height="32" style="margin-left: 140px; margin-top:22px; display:block"> </a> </div> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav navbar-right"> <li><a class="getting-started-nav nav-link" href="/getting-started/">Getting Started</a></li> <li><a class="docs-nav nav-link" href="/docs/">Docs</a></li> <li><a class="nav-link" href="http://ionic.io/support">Support</a></li> <li><a class="blog-nav nav-link" href="http://blog.ionic.io/">Blog <span id="blog-badge">1</span></a></li> <li><a class="nav-link" href="http://forum.ionicframework.com/">Forum</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle nav-link " data-toggle="dropdown" role="button" aria-expanded="false">More <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <div class="arrow-up"></div> <li><a class="products-nav nav-link" href="http://ionic.io/">Ionic Platform</a></li> <li><a class="examples-nav nav-link" href="http://showcase.ionicframework.com/">Showcase</a></li> <li><a class="nav-link" href="http://jobs.ionic.io/">Job Board</a></li> <li><a class="nav-link" href="http://market.ionic.io/">Market</a></li> <li><a class="nav-link" href="http://ionicworldwide.herokuapp.com/">Ionic Worldwide</a></li> <li><a class="nav-link" href="http://play.ionic.io/">Playground</a></li> <li><a class="nav-link" href="http://creator.ionic.io/">Creator</a></li> <li><a class="nav-link" href="http://shop.ionic.io/">Shop</a></li> <!--<li><a class="nav-link" href="http://ngcordova.com/">ngCordova</a></li>--> </ul> </li> </ul> </div> </div> </nav> <div class="header horizontal-gradient"> <div class="container"> <h3>ion-spinner</h3> <h4>Directive in module ionic</h4> </div> <div class="news"> <div class="container"> <div class="row"> <div class="col-sm-8 news-col"> <div class="picker"> <select onchange="window.location.href=this.options[this.selectedIndex].value"> <option value="/docs/nightly/api/directive/ionSpinner/" > nightly </option> <option value="/docs/api/directive/ionSpinner/" > 1.1.0 (latest) </option> <option value="/docs/1.0.1/api/directive/ionSpinner/" selected> 1.0.1 </option> <option value="/docs/1.0.0/api/directive/ionSpinner/" > 1.0.0 </option> <option value="/docs/1.0.0-rc.5/api/directive/ionSpinner/" > 1.0.0-rc.5 </option> <option value="/docs/1.0.0-rc.4/api/directive/ionSpinner/" > 1.0.0-rc.4 </option> <option value="/docs/1.0.0-rc.3/api/directive/ionSpinner/" > 1.0.0-rc.3 </option> <option value="/docs/1.0.0-rc.2/api/directive/ionSpinner/" > 1.0.0-rc.2 </option> <option value="/docs/1.0.0-rc.1/api/directive/ionSpinner/" > 1.0.0-rc.1 </option> <option value="/docs/1.0.0-rc.0/api/directive/ionSpinner/" > 1.0.0-rc.0 </option> <option value="/docs/1.0.0-beta.14/api/directive/ionSpinner/" > 1.0.0-beta.14 </option> <option value="/docs/1.0.0-beta.13/api/directive/ionSpinner/" > 1.0.0-beta.13 </option> <option value="/docs/1.0.0-beta.12/api/directive/ionSpinner/" > 1.0.0-beta.12 </option> <option value="/docs/1.0.0-beta.11/api/directive/ionSpinner/" > 1.0.0-beta.11 </option> <option value="/docs/1.0.0-beta.10/api/directive/ionSpinner/" > 1.0.0-beta.10 </option> </select> </div> </div> <div class="col-sm-4 search-col"> <div class="search-bar"> <span class="search-icon ionic"><i class="ion-ios7-search-strong"></i></span> <input type="search" id="search-input" value="Search"> </div> </div> </div> </div> </div> </div> <div id="search-results" class="search-results" style="display:none"> <div class="container"> <div class="search-section search-api"> <h4>JavaScript</h4> <ul id="results-api"></ul> </div> <div class="search-section search-css"> <h4>CSS</h4> <ul id="results-css"></ul> </div> <div class="search-section search-content"> <h4>Resources</h4> <ul id="results-content"></ul> </div> </div> </div> <div class="container content-container"> <div class="row"> <div class="col-md-2 col-sm-3 aside-menu"> <div> <ul class="nav left-menu"> <li class="menu-title"> <a href="/docs/overview/">Overview</a> </li> </ul> <ul class="nav left-menu"> <li class="menu-title"> <a href="/docs/components/">CSS</a> </li> </ul> <ul class="nav left-menu"> <li class="menu-title"> <a href="/docs/platform-customization/">Platform Customization</a> </li> </ul> <!-- Docs: JavaScript --> <ul class="nav left-menu active-menu"> <li class="menu-title"> <a href="/docs/api/"> JavaScript </a> </li> <!-- Action Sheet --> <li class="menu-section"> <a href="/docs/api/service/$ionicActionSheet/" class="api-section"> Action Sheet </a> <ul> <li> <a href="/docs/api/service/$ionicActionSheet/"> $ionicActionSheet </a> </li> </ul> </li> <!-- Backdrop --> <li class="menu-section"> <a href="/docs/api/service/$ionicBackdrop/" class="api-section"> Backdrop </a> <ul> <li> <a href="/docs/api/service/$ionicBackdrop/"> $ionicBackdrop </a> </li> </ul> </li> <!-- Content --> <li class="menu-section"> <a href="/docs/api/directive/ionContent/" class="api-section"> Content </a> <ul> <li> <a href="/docs/api/directive/ionContent/"> ion-content </a> </li> <li> <a href="/docs/api/directive/ionRefresher/"> ion-refresher </a> </li> <li> <a href="/docs/api/directive/ionPane/"> ion-pane </a> </li> </ul> </li> <!-- Form Inputs --> <li class="menu-section"> <a href="/docs/api/directive/ionCheckbox/" class="api-section"> Form Inputs </a> <ul> <li> <a href="/docs/api/directive/ionCheckbox/"> ion-checkbox </a> </li> <li> <a href="/docs/api/directive/ionRadio/"> ion-radio </a> </li> <li> <a href="/docs/api/directive/ionToggle/"> ion-toggle </a> </li> </ul> </li> <!-- Gesture and Events --> <li class="menu-section"> <a href="/docs/api/directive/onHold/" class="api-section"> Gestures and Events </a> <ul> <li> <a href="/docs/api/directive/onHold/"> on-hold </a> </li> <li> <a href="/docs/api/directive/onTap/"> on-tap </a> </li> <li> <a href="/docs/api/directive/onDoubleTap/"> on-double-tap </a> </li> <li> <a href="/docs/api/directive/onTouch/"> on-touch </a> </li> <li> <a href="/docs/api/directive/onRelease/"> on-release </a> </li> <li> <a href="/docs/api/directive/onDrag/"> on-drag </a> </li> <li> <a href="/docs/api/directive/onDragUp/"> on-drag-up </a> </li> <li> <a href="/docs/api/directive/onDragRight/"> on-drag-right </a> </li> <li> <a href="/docs/api/directive/onDragDown/"> on-drag-down </a> </li> <li> <a href="/docs/api/directive/onDragLeft/"> on-drag-left </a> </li> <li> <a href="/docs/api/directive/onSwipe/"> on-swipe </a> </li> <li> <a href="/docs/api/directive/onSwipeUp/"> on-swipe-up </a> </li> <li> <a href="/docs/api/directive/onSwipeRight/"> on-swipe-right </a> </li> <li> <a href="/docs/api/directive/onSwipeDown/"> on-swipe-down </a> </li> <li> <a href="/docs/api/directive/onSwipeLeft/"> on-swipe-left </a> </li> <li> <a href="/docs/api/service/$ionicGesture/"> $ionicGesture </a> </li> </ul> </li> <!-- Headers/Footers --> <li class="menu-section"> <a href="/docs/api/directive/ionHeaderBar/" class="api-section"> Headers/Footers </a> <ul> <li> <a href="/docs/api/directive/ionHeaderBar/"> ion-header-bar </a> </li> <li> <a href="/docs/api/directive/ionFooterBar/"> ion-footer-bar </a> </li> </ul> </li> <!-- Keyboard --> <li class="menu-section"> <a href="/docs/api/page/keyboard/" class="api-section"> Keyboard </a> <ul> <li> <a href="/docs/api/page/keyboard/"> Keyboard </a> </li> <li> <a href="/docs/api/directive/keyboardAttach/"> keyboard-attach </a> </li> </ul> </li> <!-- Lists --> <li class="menu-section"> <a href="/docs/api/directive/ionList/" class="api-section"> Lists </a> <ul> <li> <a href="/docs/api/directive/ionList/"> ion-list </a> </li> <li> <a href="/docs/api/directive/ionItem/"> ion-item </a> </li> <li> <a href="/docs/api/directive/ionDeleteButton/"> ion-delete-button </a> </li> <li> <a href="/docs/api/directive/ionReorderButton/"> ion-reorder-button </a> </li> <li> <a href="/docs/api/directive/ionOptionButton/"> ion-option-button </a> </li> <li> <a href="/docs/api/directive/collectionRepeat/"> collection-repeat </a> </li> <li> <a href="/docs/api/service/$ionicListDelegate/"> $ionicListDelegate </a> </li> </ul> </li> <!-- Loading --> <li class="menu-section"> <a href="/docs/api/service/$ionicLoading/" class="api-section"> Loading </a> <ul> <li> <a href="/docs/api/service/$ionicLoading/"> $ionicLoading </a> </li> </ul> <ul> <li> <a href="/docs/api/object/$ionicLoadingConfig/"> $ionicLoadingConfig </a> </li> </ul> </li> <!-- Modal --> <li class="menu-section"> <a href="/docs/api/service/$ionicModal/" class="api-section"> Modal </a> <ul> <li> <a href="/docs/api/service/$ionicModal/"> $ionicModal </a> </li> <li> <a href="/docs/api/controller/ionicModal/"> ionicModal </a> </li> </ul> </li> <!-- Navigation --> <li class="menu-section"> <a href="/docs/api/directive/ionNavView/" class="api-section"> Navigation </a> <ul> <li> <a href="/docs/api/directive/ionNavView/"> ion-nav-view </a> </li> <li> <a href="/docs/api/directive/ionView/"> ion-view </a> </li> <li> <a href="/docs/api/directive/ionNavBar/"> ion-nav-bar </a> </li> <li> <a href="/docs/api/directive/ionNavBackButton/"> ion-nav-back-button </a> </li> <li> <a href="/docs/api/directive/ionNavButtons/"> ion-nav-buttons </a> </li> <li> <a href="/docs/api/directive/ionNavTitle/"> ion-nav-title </a> </li> <li> <a href="/docs/api/directive/navTransition/"> nav-transition </a> </li> <li> <a href="/docs/api/directive/navDirection/"> nav-direction </a> </li> <li> <a href="/docs/api/service/$ionicNavBarDelegate/"> $ionicNavBarDelegate </a> </li> <li> <a href="/docs/api/service/$ionicHistory/"> $ionicHistory </a> </li> </ul> </li> <!-- Platform --> <li class="menu-section"> <a href="/docs/api/service/$ionicPlatform/" class="api-section"> Platform </a> <ul> <li> <a href="/docs/api/service/$ionicPlatform/"> $ionicPlatform </a> </li> </ul> </li> <!-- Popover --> <li class="menu-section"> <a href="/docs/api/service/$ionicPopover/" class="api-section"> Popover </a> <ul> <li> <a href="/docs/api/service/$ionicPopover/"> $ionicPopover </a> </li> <li> <a href="/docs/api/controller/ionicPopover/"> ionicPopover </a> </li> </ul> </li> <!-- Popup --> <li class="menu-section"> <a href="/docs/api/service/$ionicPopup/" class="api-section"> Popup </a> <ul> <li> <a href="/docs/api/service/$ionicPopup/"> $ionicPopup </a> </li> </ul> </li> <!-- Scroll --> <li class="menu-section"> <a href="/docs/api/directive/ionScroll/" class="api-section"> Scroll </a> <ul> <li> <a href="/docs/api/directive/ionScroll/"> ion-scroll </a> </li> <li> <a href="/docs/api/directive/ionInfiniteScroll/"> ion-infinite-scroll </a> </li> <li> <a href="/docs/api/service/$ionicScrollDelegate/"> $ionicScrollDelegate </a> </li> </ul> </li> <!-- Side Menus --> <li class="menu-section"> <a href="/docs/api/directive/ionSideMenus/" class="api-section"> Side Menus </a> <ul> <li> <a href="/docs/api/directive/ionSideMenus/"> ion-side-menus </a> </li> <li> <a href="/docs/api/directive/ionSideMenuContent/"> ion-side-menu-content </a> </li> <li> <a href="/docs/api/directive/ionSideMenu/"> ion-side-menu </a> </li> <li> <a href="/docs/api/directive/exposeAsideWhen/"> expose-aside-when </a> </li> <li> <a href="/docs/api/directive/menuToggle/"> menu-toggle </a> </li> <li> <a href="/docs/api/directive/menuClose/"> menu-close </a> </li> <li> <a href="/docs/api/service/$ionicSideMenuDelegate/"> $ionicSideMenuDelegate </a> </li> </ul> </li> <!-- Slide Box --> <li class="menu-section"> <a href="/docs/api/directive/ionSlideBox/" class="api-section"> Slide Box </a> <ul> <li> <a href="/docs/api/directive/ionSlideBox/"> ion-slide-box </a> </li> <li> <a href="/docs/api/directive/ionSlidePager/"> ion-slide-pager </a> </li> <li> <a href="/docs/api/directive/ionSlide/"> ion-slide </a> </li> <li> <a href="/docs/api/service/$ionicSlideBoxDelegate/"> $ionicSlideBoxDelegate </a> </li> </ul> </li> <!-- Spinner --> <li class="menu-section"> <a href="/docs/api/directive/ionSpinner/" class="api-section"> Spinner </a> <ul> <li> <a href="/docs/api/directive/ionSpinner/"> ion-spinner </a> </li> </ul> </li> <!-- Tabs --> <li class="menu-section"> <a href="/docs/api/directive/ionTabs/" class="api-section"> Tabs </a> <ul> <li> <a href="/docs/api/directive/ionTabs/"> ion-tabs </a> </li> <li> <a href="/docs/api/directive/ionTab/"> ion-tab </a> </li> <li> <a href="/docs/api/service/$ionicTabsDelegate/"> $ionicTabsDelegate </a> </li> </ul> </li> <!-- Tap --> <li class="menu-section"> <a href="/docs/api/page/tap/" class="api-section"> Tap &amp; Click </a> </li> <!-- Utility --> <li class="menu-section"> <a href="#" class="api-section"> Utility </a> <ul> <li> <a href="/docs/api/provider/$ionicConfigProvider/"> $ionicConfigProvider </a> </li> <li> <a href="/docs/api/utility/ionic.Platform/"> ionic.Platform </a> </li> <li> <a href="/docs/api/utility/ionic.DomUtil/"> ionic.DomUtil </a> </li> <li> <a href="/docs/api/utility/ionic.EventController/"> ionic.EventController </a> </li> <li> <a href="/docs/api/service/$ionicPosition/"> $ionicPosition </a> </li> </ul> </li> </ul> <ul class="nav left-menu"> <li class="menu-title"> <a href="/docs/cli/">CLI</a> </li> </ul> <ul class="nav left-menu"> <li class="menu-title"> <a href="http://learn.ionicframework.com/">Learn Ionic</a> </li> </ul> <ul class="nav left-menu"> <li class="menu-title"> <a href="/docs/guide/">Guide</a> </li> </ul> <ul class="nav left-menu"> <li class="menu-title"> <a href="/docs/ionic-cli-faq/">FAQ</a> </li> </ul> <ul class="nav left-menu"> <li class="menu-title"> <a href="/docs/getting-help/">Getting Help</a> </li> </ul> <ul class="nav left-menu"> <li class="menu-title"> <a href="/docs/concepts/">Ionic Concepts</a> </li> </ul> </div> </div> <div class="col-md-10 col-sm-9 main-content"> <div class="improve-docs"> <a href='http://github.com/driftyco/ionic/tree/master/js/angular/directive/spinner.js#L1'> View Source </a> &nbsp; <a href='http://github.com/driftyco/ionic/edit/master/js/angular/directive/spinner.js#L1'> Improve this doc </a> </div> <h1 class="api-title"> ion-spinner </h1> <p>The <code>ionSpinner</code> directive provides a variety of animated spinners. Spinners enables you to give your users feedback that the app is processing/thinking/waiting/chillin&#39; out, or whatever you&#39;d like it to indicate. By default, the <a href="/docs/api/directive/ionRefresher/"><code>ionRefresher</code></a> feature uses this spinner, rather than rotating font icons (previously included in <a href="http://ionicons.com/">ionicons</a>). While font icons are great for simple or stationary graphics, they&#39;re not suited to provide great animations, which is why Ionic uses SVG instead.</p> <p>Ionic offers ten spinners out of the box, and by default, it will use the appropriate spinner for the platform on which it&#39;s running. Under the hood, the <code>ionSpinner</code> directive dynamically builds the required SVG element, which allows Ionic to provide all ten of the animated SVGs within 3KB.</p> <style> .spinner-table { max-width: 280px; } .spinner-table tbody > tr > th, .spinner-table tbody > tr > td { vertical-align: middle; width: 42px; height: 42px; } .spinner { stroke: #444; fill: #444; } .spinner svg { width: 28px; height: 28px; } .spinner.spinner-inverse { stroke: #fff; fill: #fff; } .spinner-android { stroke: #4b8bf4; } .spinner-ios, .spinner-ios-small { stroke: #69717d; } .spinner-spiral .stop1 { stop-color: #fff; stop-opacity: 0; } .spinner-spiral.spinner-inverse .stop1 { stop-color: #000; } .spinner-spiral.spinner-inverse .stop2 { stop-color: #fff; } </style> <script src="http://code.ionicframework.com/nightly/js/ionic.bundle.min.js"></script> <table class="table spinner-table" ng-app="ionic"> <tr> <th> <code>android</code> </th> <td> <ion-spinner icon="android"></ion-spinner> </td> </tr> <tr> <th> <code>ios</code> </th> <td> <ion-spinner icon="ios"></ion-spinner> </td> </tr> <tr> <th> <code>ios-small</code> </th> <td> <ion-spinner icon="ios-small"></ion-spinner> </td> </tr> <tr> <th> <code>bubbles</code> </th> <td> <ion-spinner icon="bubbles"></ion-spinner> </td> </tr> <tr> <th> <code>circles</code> </th> <td> <ion-spinner icon="circles"></ion-spinner> </td> </tr> <tr> <th> <code>crescent</code> </th> <td> <ion-spinner icon="crescent"></ion-spinner> </td> </tr> <tr> <th> <code>dots</code> </th> <td> <ion-spinner icon="dots"></ion-spinner> </td> </tr> <tr> <th> <code>lines</code> </th> <td> <ion-spinner icon="lines"></ion-spinner> </td> </tr> <tr> <th> <code>ripple</code> </th> <td> <ion-spinner icon="ripple"></ion-spinner> </td> </tr> <tr> <th> <code>spiral</code> </th> <td> <ion-spinner icon="spiral"></ion-spinner> </td> </tr> </table> <p>Each spinner uses SVG with SMIL animations, however, the Android spinner also uses JavaScript so it also works on Android 4.0-4.3. Additionally, each spinner can be styled with CSS, and scaled to any size.</p> <h2 id="usage">Usage</h2> <p>The following code would use the default spinner for the platform it&#39;s running from. If it&#39;s neither iOS or Android, it&#39;ll default to use <code>ios</code>.</p> <div class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;ion-spinner&gt;&lt;/ion-spinner&gt;</span> </code></pre></div> <p>By setting the <code>icon</code> attribute, you can specify which spinner to use, no matter what the platform is.</p> <div class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;ion-spinner</span> <span class="na">icon=</span><span class="s">&quot;spiral&quot;</span><span class="nt">&gt;&lt;/ion-spinner&gt;</span> </code></pre></div> <h2>Spinner Colors</h2> <p>Like with most of Ionic&#39;s other components, spinners can also be styled using Ionic&#39;s standard color naming convention. For example:</p> <div class="highlight"><pre><code class="language-html" data-lang="html"><span class="nt">&lt;ion-spinner</span> <span class="na">class=</span><span class="s">&quot;spinner-energized&quot;</span><span class="nt">&gt;&lt;/ion-spinner&gt;</span> </code></pre></div> <h2>Styling SVG with CSS</h2> <p>One cool thing about SVG is its ability to be styled with CSS! Some of the properties have different names, for example, SVG uses the term <code>stroke</code> instead of <code>border</code>, and <code>fill</code> instead of <code>background-color</code>.</p> <div class="highlight"><pre><code class="language-css" data-lang="css"><span class="nc">.spinner</span> <span class="nt">svg</span> <span class="p">{</span> <span class="k">width</span><span class="o">:</span> <span class="m">28px</span><span class="p">;</span> <span class="k">height</span><span class="o">:</span> <span class="m">28px</span><span class="p">;</span> <span class="n">stroke</span><span class="o">:</span> <span class="m">#444</span><span class="p">;</span> <span class="n">fill</span><span class="o">:</span> <span class="m">#444</span><span class="p">;</span> <span class="p">}</span> </code></pre></div> </div> </div> </div> <div class="pre-footer"> <div class="row ionic"> <div class="col-sm-6 col-a"> <h4> <a href="/getting-started/">Getting started <span class="icon ion-arrow-right-c"></span></a> </h4> <p> Learn more about how Ionic was built, why you should use it, and what's included. We'll cover the basics and help you get started from the ground up. </p> </div> <div class="col-sm-6 col-b"> <h4> <a href="/docs/">Documentation <span class="icon ion-arrow-right-c"></span></a> </h4> <p> What are you waiting for? Take a look and get coding! Our documentation covers all you need to know to get an app up and running in minutes. </p> </div> </div> </div> <footer class="footer"> <nav class="base-links"> <dl> <dt>Docs</dt> <dd><a href="http://ionicframework.com/docs/">Documentation</a></dd> <dd><a href="http://ionicframework.com/getting-started/">Getting Started</a></dd> <dd><a href="http://ionicframework.com/docs/overview/">Overview</a></dd> <dd><a href="http://ionicframework.com/docs/components/">Components</a></dd> <dd><a href="http://ionicframework.com/docs/api/">JavaScript</a></dd> <dd><a href="http://ionicframework.com/submit-issue/">Submit Issue</a></dd> </dl> <dl> <dt>Resources</dt> <dd><a href="http://learn.ionicframework.com/">Learn Ionic</a></dd> <dd><a href="http://ngcordova.com/">ngCordova</a></dd> <dd><a href="http://ionicons.com/">Ionicons</a></dd> <dd><a href="http://creator.ionic.io/">Creator</a></dd> <dd><a href="http://showcase.ionicframework.com/">Showcase</a></dd> <dd><a href="http://manning.com/wilken/?a_aid=ionicinactionben&a_bid=1f0a0e1d">The Ionic Book</a></dd> </dl> <dl> <dt>Contribute</dt> <dd><a href="http://forum.ionicframework.com/">Community Forum</a></dd> <dd><a href="http://webchat.freenode.net/?randomnick=1&amp;channels=%23ionic&amp;uio=d4">Ionic IRC</a></dd> <dd><a href="http://ionicframework.com/present-ionic/">Present Ionic</a></dd> <dd><a href="http://ionicframework.com/contribute/">Contribute</a></dd> <dd><a href="https://github.com/driftyco/ionic-learn/issues/new">Write for us</a></dd> <dd><a href="http://shop.ionic.io/">Ionic Shop</a></dd> </dl> <dl class="small-break"> <dt>About</dt> <dd><a href="http://blog.ionic.io/">Blog</a></dd> <dd><a href="http://ionic.io">Services</a></dd> <dd><a href="http://drifty.com">Company</a></dd> <dd><a href="https://s3.amazonaws.com/ionicframework.com/logo-pack.zip">Logo Pack</a></dd> <dd><a href="mailto:[email protected]">Contact</a></dd> <dd><a href="http://ionicframework.com/jobs/">Jobs</a></dd> </dl> <dl> <dt>Connect</dt> <dd><a href="https://twitter.com/IonicFramework">Twitter</a></dd> <dd><a href="https://github.com/driftyco/ionic">GitHub</a></dd> <dd><a href="https://www.facebook.com/ionicframework">Facebook</a></dd> <dd><a href="https://plus.google.com/b/112280728135675018538/+Ionicframework/posts">Google+</a></dd> <dd><a href="https://www.youtube.com/channel/UChYheBnVeCfhCmqZfCUdJQw">YouTube</a></dd> <dd><a href="https://twitter.com/ionitron">Ionitron</a></dd> </dl> </nav> <div class="newsletter row"> <div class="newsletter-container"> <div class="col-sm-7"> <div class="newsletter-text">Stay in the loop</div> <div class="sign-up">Sign up to receive emails for the latest updates, features, and news on the framework.</div> </div> <form action="http://codiqa.createsend.com/t/t/s/jytylh/" method="post" class="input-group col-sm-5"> <input id="fieldEmail" name="cm-jytylh-jytylh" class="form-control" type="email" placeholder="Email" required /> <span class="input-group-btn"> <button class="btn btn-default" type="submit">Subscribe</button> </span> </form> </div> </div> <div class="copy"> <div class="copy-container"> <p class="authors"> Code licensed under <a href="/docs/#license">MIT</a>. Docs under <a href="https://tldrlegal.com/license/apache-license-2.0-(apache-2.0)">Apache 2</a> <span>|</span> &copy; 2013-2015 <a href="http://drifty.com/">Drifty Co</a> </p> </div> </div> </footer> <script type="text/javascript"> var _sf_async_config = { uid: 54141, domain: 'ionicframework.com', useCanonical: true }; (function() { function loadChartbeat() { window._sf_endpt = (new Date()).getTime(); var e = document.createElement('script'); e.setAttribute('language', 'javascript'); e.setAttribute('type', 'text/javascript'); e.setAttribute('src','//static.chartbeat.com/js/chartbeat.js'); document.body.appendChild(e); }; var oldonload = window.onload; window.onload = (typeof window.onload != 'function') ? loadChartbeat : function() { oldonload(); loadChartbeat(); }; })(); </script> <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.2/js/bootstrap.min.js"></script> <script src="/js/site.js?1"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/Cookies.js/0.4.0/cookies.min.js"></script> <script> $('.navbar .dropdown').on('show.bs.dropdown', function(e){ //$(this).find('.dropdown-menu').addClass('animated fadeInDown'); }); // ADD SLIDEUP ANIMATION TO DROPDOWN // $('.navbar .dropdown').on('hide.bs.dropdown', function(e){ //$(this).find('.dropdown-menu').first().stop(true, true).slideUp(200); //$(this).find('.dropdown-menu').removeClass('animated fadeInDown'); }); try { var d = new Date('2015-03-20 05:00:00 -0500'); var ts = d.getTime(); var cd = Cookies.get('_iondj'); if(cd) { cd = JSON.parse(atob(cd)); if(parseInt(cd.lp) < ts) { var bt = document.getElementById('blog-badge'); bt.style.display = 'block'; } cd.lp = ts; } else { var bt = document.getElementById('blog-badge'); bt.style.display = 'block'; cd = { lp: ts } } Cookies.set('_iondj', btoa(JSON.stringify(cd))); } catch(e) { } </script> <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> </body> </html>
apache-2.0
hazendaz/assertj-core
src/test/java/org/assertj/core/error/ShouldBeSame_create_Test.java
1541
/* * 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. * * Copyright 2012-2021 the original author or authors. */ package org.assertj.core.error; import static java.lang.String.format; import static org.assertj.core.api.BDDAssertions.then; import static org.assertj.core.error.ShouldBeSame.shouldBeSame; import org.assertj.core.description.TextDescription; import org.assertj.core.presentation.StandardRepresentation; import org.junit.jupiter.api.Test; /** * Tests for <code>{@link ShouldBeSame#create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation)}</code>. * * @author Alex Ruiz */ class ShouldBeSame_create_Test { @Test void should_create_error_message() { // GIVEN ErrorMessageFactory factory = shouldBeSame("Yoda", "Luke"); // WHEN String message = factory.create(new TextDescription("Test"), new StandardRepresentation()); // THEN then(message).isEqualTo(format("[Test] %nExpecting actual:%n \"Luke\"%nand actual:%n \"Yoda\"%nto refer to the same object")); } }
apache-2.0
mkrtchyanmnatsakan/DemoAppHelloWord
camerafragment/src/main/java/com/github/florent37/camerafragment/internal/timer/TimerTask.java
1308
package com.github.florent37.camerafragment.internal.timer; import com.github.florent37.camerafragment.internal.utils.DateTimeUtils; /* * Created by florentchampigny on 13/01/2017. */ public class TimerTask extends TimerTaskBase implements Runnable { public TimerTask(TimerTaskBase.Callback callback) { super(callback); } @Override public void run() { recordingTimeSeconds++; if (recordingTimeSeconds == 60) { recordingTimeSeconds = 0; recordingTimeMinutes++; } if(callback != null) { callback.setText( String.format("%02d:%02d", recordingTimeMinutes, recordingTimeSeconds)); } if (alive) handler.postDelayed(this, DateTimeUtils.SECOND); } public void start() { alive = true; recordingTimeMinutes = 0; recordingTimeSeconds = 0; if(callback != null) { callback.setText( String.format("%02d:%02d", recordingTimeMinutes, recordingTimeSeconds)); callback.setTextVisible(true); } handler.postDelayed(this, DateTimeUtils.SECOND); } public void stop() { if(callback != null){ callback.setTextVisible(false); } alive = false; } }
apache-2.0
openwide-java/owsi-core-parent
owsi-core/owsi-core-components/owsi-core-component-commons/src/main/java/fr/openwide/core/commons/util/registry/TFileRegistry.java
4967
package fr.openwide.core.commons.util.registry; import java.io.Closeable; import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.util.Objects; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Sets; import de.schlichtherle.truezip.file.TFile; import de.schlichtherle.truezip.file.TVFS; import de.schlichtherle.truezip.fs.FsSyncException; import de.schlichtherle.truezip.fs.FsSyncOptions; /** * A registry responsible for keeping track of open {@link TFile TFiles} and for cleaning them up upon closing it. * <p>This should generally be used as a factory for creating TFiles (see the <code>create</code> methods), and the * calling of {@link #open()} and {@link #close()} should be done in some generic code (such as a servlet filter). * <p>Please note that this registry is using a {@link ThreadLocal}. Opening and closing the registry must therefore * be done in the same thread, and each TFile-creating thread should use its own registry. */ public final class TFileRegistry { private static final Logger LOGGER = LoggerFactory.getLogger(TFileRegistry.class); private static final ThreadLocal<TFileRegistryImpl> THREAD_LOCAL = new ThreadLocal<TFileRegistryImpl>(); private TFileRegistry() { } /** * Enables the (thread-local) TFileRegistry, so that every call to the createXX() or register() static methods * will result in the relevant TFile to be stored for further cleaning of TrueZip internal resources. * <p>The actual cleaning must be performed by calling the {@link #close()} static method on TFileRegistry. */ public static void open() { TFileRegistryImpl registry = THREAD_LOCAL.get(); if (registry == null) { THREAD_LOCAL.set(new TFileRegistryImpl()); } else { throw new IllegalStateException("TFileRegistry.open() should not be called twice without calling close() in-between."); } } /** * {@link TVFS#sync(de.schlichtherle.truezip.fs.FsMountPoint, de.schlichtherle.truezip.util.BitField) Synchronize} * the TrueZip virtual filesystem for every registered file, and clears the registry. * <p><strong>WARNING :</strong> If some {@link InputStream InputStreams} or {@link OutputStream OutputStreams} * managed by the current thread have not been closed yet, they will be ignored. */ public static void close() { try { TFileRegistryImpl registry = THREAD_LOCAL.get(); if (registry != null) { registry.close(); } else { throw new IllegalStateException("TFileRegistry.close() should not be called if TFileRegistry.open() has not been called before."); } } finally { THREAD_LOCAL.remove(); } } public static TFile create(String path) { TFile tFile = new TFile(path); register(tFile); return tFile; } public static TFile create(File file) { TFile tFile = new TFile(file); register(tFile); return tFile; } public static TFile create(String parent, String member) { TFile tFile = new TFile(parent, member); register(tFile); return tFile; } public static TFile create(File parent, String member) { TFile tFile = new TFile(parent, member); register(tFile); return tFile; } public static TFile create(URI uri) { TFile tFile = new TFile(uri); register(tFile); return tFile; } public static void register(File file) { Objects.requireNonNull(file, "file must not be null"); TFileRegistryImpl registry = THREAD_LOCAL.get(); if (registry != null) { registry.register(file); } else { LOGGER.info("Trying to register file '{}', but the TFileRegistry has not been open (see TFileRegistry.open()). Ignoring registration.", file); THREAD_LOCAL.remove(); } } public static void register(Iterable<? extends File> files) { Objects.requireNonNull(files, "files must not be null"); TFileRegistryImpl registry = THREAD_LOCAL.get(); if (registry != null) { registry.register(files); } else { LOGGER.info("Trying to register files '{}', but the TFileRegistry has not been open (see TFileRegistry.open()). Ignoring registration.", files); THREAD_LOCAL.remove(); } } private static final class TFileRegistryImpl implements Closeable { private final Set<TFile> registeredFiles = Sets.newHashSet(); private TFileRegistryImpl() { } public void register(File file) { if (file instanceof TFile) { TFile topLevelArchive = ((TFile)file).getTopLevelArchive(); if (topLevelArchive != null) { registeredFiles.add(topLevelArchive); } } } public void register(Iterable<? extends File> files) { for (File file : files) { register(file); } } @Override public void close() { for (TFile tFile : registeredFiles) { try { TVFS.sync(tFile, FsSyncOptions.SYNC); } catch (RuntimeException | FsSyncException e) { LOGGER.error("Error while trying to sync the truezip filesystem on '" + tFile + "'", e); } } } } }
apache-2.0
base2Services/kagura
shared/reporting-core/src/main/java/com/base2/kagura/core/report/configmodel/JDBCReportConfig.java
2350
/* Copyright 2014 base2Services 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.base2.kagura.core.report.configmodel; import com.base2.kagura.core.report.connectors.JDBCDataReportConnector; import com.base2.kagura.core.report.connectors.ReportConnector; /** * JDBC backend for @see #FreeMarkerSQLReport * User: aubels * Date: 24/07/13 * Time: 4:46 PM * */ public class JDBCReportConfig extends FreeMarkerSQLReportConfig { String jdbc; String username; String password; private String classLoaderPath; /** * {@inheritDoc} * @return */ @Override public ReportConnector getReportConnector() { return new JDBCDataReportConnector(this); } /** * JDBC connection string * @return */ public String getJdbc() { return jdbc; } /** * @see #getJdbc() */ public void setJdbc(String jdbc) { this.jdbc = jdbc; } /** * JDBC Password if necessary * @return */ public String getPassword() { return password; } /** * @see #getPassword() */ public void setPassword(String password) { this.password = password; } /** * JDBC username * @return */ public String getUsername() { return username; } /** * @see #getUsername() * @param username */ public void setUsername(String username) { this.username = username; } /** * Class path loader for the Database driver, for instance: com.mysql.jdbc.Driver * @return */ public String getClassLoaderPath() { return classLoaderPath; } /** * @see #getClassLoaderPath() */ public void setClassLoaderPath(String classLoaderPath) { this.classLoaderPath = classLoaderPath; } }
apache-2.0
LogtalkDotOrg/logtalk3
manuals/libraries/html.html
25102
<!DOCTYPE html> <html class="writer-html5" lang="en" > <head> <meta charset="utf-8" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>html &mdash; The Logtalk Handbook v3.54.0-b02 documentation</title> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" href="../_static/css/theme.css" type="text/css" /> <link rel="stylesheet" href="../_static/css/custom.css" type="text/css" /> <!--[if lt IE 9]> <script src="../_static/js/html5shiv.min.js"></script> <![endif]--> <script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/doctools.js"></script> <script src="../_static/js/theme.js"></script> <!-- begin favicon --> <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" /> <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" /> <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" /> <link rel="manifest" href="/site.webmanifest" /> <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5" /> <meta name="msapplication-TileColor" content="#355b95" /> <meta name="theme-color" content="#ffffff" /> <!-- end favicon --> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="intervals" href="intervals.html" /> <link rel="prev" title="hook_objects" href="hook_objects.html" /> </head> <body class="wy-body-for-nav"> <div class="wy-grid-for-nav"> <nav data-toggle="wy-nav-shift" class="wy-nav-side"> <div class="wy-side-scroll"> <div class="wy-side-nav-search" > <a href="../index.html" class="icon icon-home"> The Logtalk Handbook <img src="../_static/logtalk.gif" class="logo" alt="Logo"/> </a> <div class="version"> 3.54.0 </div> <div role="search"> <form id="rtd-search-form" class="wy-form" action="../search.html" method="get"> <input type="text" name="q" placeholder="Search docs" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div><div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="Navigation menu"> <p class="caption" role="heading"><span class="caption-text">Contents</span></p> <ul class="current"> <li class="toctree-l1"><a class="reference internal" href="../userman/index.html">User Manual</a></li> <li class="toctree-l1"><a class="reference internal" href="../refman/index.html">Reference Manual</a></li> <li class="toctree-l1"><a class="reference internal" href="../tutorial/index.html">Tutorial</a></li> <li class="toctree-l1"><a class="reference internal" href="../faq/index.html">FAQ</a></li> <li class="toctree-l1"><a class="reference internal" href="../devtools/index.html">Developer Tools</a></li> <li class="toctree-l1 current"><a class="reference internal" href="index.html">Libraries</a><ul class="current"> <li class="toctree-l2"><a class="reference internal" href="overview.html">Overview</a></li> <li class="toctree-l2"><a class="reference internal" href="arbitrary.html"><code class="docutils literal notranslate"><span class="pre">arbitrary</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="assignvars.html"><code class="docutils literal notranslate"><span class="pre">assignvars</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="base64.html"><code class="docutils literal notranslate"><span class="pre">base64</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="basic_types.html"><code class="docutils literal notranslate"><span class="pre">basic_types</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="coroutining.html"><code class="docutils literal notranslate"><span class="pre">coroutining</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="cbor.html"><code class="docutils literal notranslate"><span class="pre">cbor</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="csv.html"><code class="docutils literal notranslate"><span class="pre">csv</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="dates.html"><code class="docutils literal notranslate"><span class="pre">dates</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="dependents.html"><code class="docutils literal notranslate"><span class="pre">dependents</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="dictionaries.html"><code class="docutils literal notranslate"><span class="pre">dictionaries</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="dif.html"><code class="docutils literal notranslate"><span class="pre">dif</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="edcg.html"><code class="docutils literal notranslate"><span class="pre">edcg</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="events.html"><code class="docutils literal notranslate"><span class="pre">events</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="expand_library_alias_paths.html"><code class="docutils literal notranslate"><span class="pre">expand_library_alias_paths</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="expecteds.html"><code class="docutils literal notranslate"><span class="pre">expecteds</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="format.html"><code class="docutils literal notranslate"><span class="pre">format</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="gensym.html"><code class="docutils literal notranslate"><span class="pre">gensym</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="git.html"><code class="docutils literal notranslate"><span class="pre">git</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="grammars.html"><code class="docutils literal notranslate"><span class="pre">grammars</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="heaps.html"><code class="docutils literal notranslate"><span class="pre">heaps</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="hierarchies.html"><code class="docutils literal notranslate"><span class="pre">hierarchies</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="hook_flows.html"><code class="docutils literal notranslate"><span class="pre">hook_flows</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="hook_objects.html"><code class="docutils literal notranslate"><span class="pre">hook_objects</span></code></a></li> <li class="toctree-l2 current"><a class="current reference internal" href="#"><code class="docutils literal notranslate"><span class="pre">html</span></code></a><ul> <li class="toctree-l3"><a class="reference internal" href="#api-documentation">API documentation</a></li> <li class="toctree-l3"><a class="reference internal" href="#loading">Loading</a></li> <li class="toctree-l3"><a class="reference internal" href="#testing">Testing</a></li> <li class="toctree-l3"><a class="reference internal" href="#generating-a-html-document">Generating a HTML document</a></li> <li class="toctree-l3"><a class="reference internal" href="#generating-a-html-fragment">Generating a HTML fragment</a></li> <li class="toctree-l3"><a class="reference internal" href="#working-with-callbacks-to-generate-content">Working with callbacks to generate content</a></li> <li class="toctree-l3"><a class="reference internal" href="#working-with-custom-elements">Working with custom elements</a></li> </ul> </li> <li class="toctree-l2"><a class="reference internal" href="intervals.html"><code class="docutils literal notranslate"><span class="pre">intervals</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="java.html"><code class="docutils literal notranslate"><span class="pre">java</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="json.html"><code class="docutils literal notranslate"><span class="pre">json</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="logging.html"><code class="docutils literal notranslate"><span class="pre">logging</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="loops.html"><code class="docutils literal notranslate"><span class="pre">loops</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="meta.html"><code class="docutils literal notranslate"><span class="pre">meta</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="meta_compiler.html"><code class="docutils literal notranslate"><span class="pre">meta_compiler</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="nested_dictionaries.html"><code class="docutils literal notranslate"><span class="pre">nested_dictionaries</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="optionals.html"><code class="docutils literal notranslate"><span class="pre">optionals</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="options.html"><code class="docutils literal notranslate"><span class="pre">options</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="os.html"><code class="docutils literal notranslate"><span class="pre">os</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="queues.html"><code class="docutils literal notranslate"><span class="pre">queues</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="random.html"><code class="docutils literal notranslate"><span class="pre">random</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="reader.html"><code class="docutils literal notranslate"><span class="pre">reader</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="redis.html"><code class="docutils literal notranslate"><span class="pre">redis</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="sets.html"><code class="docutils literal notranslate"><span class="pre">sets</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="statistics.html"><code class="docutils literal notranslate"><span class="pre">statistics</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="term_io.html"><code class="docutils literal notranslate"><span class="pre">term_io</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="timeout.html"><code class="docutils literal notranslate"><span class="pre">timeout</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="types.html"><code class="docutils literal notranslate"><span class="pre">types</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="unicode_data.html"><code class="docutils literal notranslate"><span class="pre">unicode_data</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="union_find.html"><code class="docutils literal notranslate"><span class="pre">union_find</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="uuid.html"><code class="docutils literal notranslate"><span class="pre">uuid</span></code></a></li> <li class="toctree-l2"><a class="reference internal" href="zippers.html"><code class="docutils literal notranslate"><span class="pre">zippers</span></code></a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="../glossary.html">Glossary</a></li> <li class="toctree-l1"><a class="reference internal" href="../bibliography.html">Bibliography</a></li> <li class="toctree-l1"><a class="reference internal" href="../genindex.html">Index</a></li> </ul> <p class="caption"><span class="caption-text">External Contents</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="../../docs/index.html">APIs</a></li> <li class="toctree-l1"><a class="reference internal" href="https://logtalk.org">Logtalk website</a></li> <li class="toctree-l1"><a class="reference internal" href="https://github.com/LogtalkDotOrg/logtalk3">GitHub repo</a></li> </ul> </div> </div> </nav> <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap"><nav class="wy-nav-top" aria-label="Mobile navigation menu" > <i data-toggle="wy-nav-top" class="fa fa-bars"></i> <a href="../index.html">The Logtalk Handbook</a> </nav> <div class="wy-nav-content"> <div class="rst-content"> <div role="navigation" aria-label="Page navigation"> <ul class="wy-breadcrumbs"> <li><a href="../index.html" class="icon icon-home"></a> &raquo;</li> <li><a href="index.html">Libraries</a> &raquo;</li> <li><code class="docutils literal notranslate"><span class="pre">html</span></code></li> <li class="wy-breadcrumbs-aside"> <a href="https://github.com/LogtalkDotOrg/logtalk3/blob/master/manuals/sources/libraries/html.rst" class="fa fa-github"> Edit on GitHub</a> </li> </ul> <hr/> </div> <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article"> <div itemprop="articleBody"> <section id="html"> <h1><code class="docutils literal notranslate"><span class="pre">html</span></code><a class="headerlink" href="#html" title="Permalink to this headline"></a></h1> <p>This library provides predicates for generating HTML content using either HTML 5 or XHTML 1.1 formats from a term representation. The library performs minimal validation, checking only that all elements are valid. No attempt is made to generate nicely indented output.</p> <p>Normal elements are represented using a compound term with one argument (the element content) or two arguments (the element attributes represented by a list of <code class="docutils literal notranslate"><span class="pre">Key=Value</span></code> or <code class="docutils literal notranslate"><span class="pre">Key-Value</span></code> pairs and the element content). The element content can be another element or a list of elements. For example:</p> <div class="highlight-logtalk notranslate"><div class="highlight"><pre><span></span>ol([type<span class="o">-</span>a], [li(foo), li(bar), li(baz)]) </pre></div> </div> <p>The two exceptions are the <code class="docutils literal notranslate"><span class="pre">pre</span></code> or <code class="docutils literal notranslate"><span class="pre">code</span></code> elements whose content is never interpreted as an element or a list of elements. For example, the fragment:</p> <div class="highlight-logtalk notranslate"><div class="highlight"><pre><span></span>pre([foo,bar,baz]) </pre></div> </div> <p>is translated to:</p> <div class="highlight-logtalk notranslate"><div class="highlight"><pre><span></span><span class="o">&lt;</span>pre<span class="o">&gt;</span> [foo,bar,baz] <span class="o">&lt;/</span>pre<span class="o">&gt;</span> </pre></div> </div> <p>Void elements are represented using a compound term with one argument, the (possibly empty) list of attributes represented by a list of <code class="docutils literal notranslate"><span class="pre">Key=Value</span></code> or <code class="docutils literal notranslate"><span class="pre">Key-Value</span></code> pairs. For example:</p> <div class="highlight-logtalk notranslate"><div class="highlight"><pre><span></span>hr([class<span class="o">-</span>separator]) </pre></div> </div> <p>Atomic arguments of the compound terms are interpreted as element content. Non atomic element content can be represented as a quoted atom or by using the <code class="docutils literal notranslate"><span class="pre">pre</span></code> or <code class="docutils literal notranslate"><span class="pre">code</span></code> elements as explained above.</p> <p>This library is a work in progress.</p> <section id="api-documentation"> <h2>API documentation<a class="headerlink" href="#api-documentation" title="Permalink to this headline"></a></h2> <p>Open the <a class="reference external" href="../../docs/library_index.html#html">../../docs/library_index.html#html</a> link in a web browser.</p> </section> <section id="loading"> <h2>Loading<a class="headerlink" href="#loading" title="Permalink to this headline"></a></h2> <p>To load all entities in this library, load the <code class="docutils literal notranslate"><span class="pre">loader.lgt</span></code> file:</p> <div class="highlight-logtalk notranslate"><div class="highlight"><pre><span></span>| <span class="o">?-</span> <span class="k">logtalk_load</span>(html(loader)). </pre></div> </div> </section> <section id="testing"> <h2>Testing<a class="headerlink" href="#testing" title="Permalink to this headline"></a></h2> <p>To test this library predicates, load the <code class="docutils literal notranslate"><span class="pre">tester.lgt</span></code> file:</p> <div class="highlight-logtalk notranslate"><div class="highlight"><pre><span></span>| <span class="o">?-</span> <span class="k">logtalk_load</span>(html(tester)). </pre></div> </div> </section> <section id="generating-a-html-document"> <h2>Generating a HTML document<a class="headerlink" href="#generating-a-html-document" title="Permalink to this headline"></a></h2> <p>HTML documents can be generated from a compound term representation and written to a file or a stream. For example, assuming we want to generate a HTML 5 file:</p> <div class="highlight-logtalk notranslate"><div class="highlight"><pre><span></span>| <span class="o">?-</span> html5<span class="o">::</span>generate( file(<span class="s">&#39;hello.html&#39;</span>), html([lang<span class="o">=</span>en], [head(title(<span class="s">&#39;Hello world!&#39;</span>)), body(p(<span class="s">&#39;Bye!&#39;</span>))]) ). </pre></div> </div> <p>When the second argument is a <code class="docutils literal notranslate"><span class="pre">html/1</span></code> or <code class="docutils literal notranslate"><span class="pre">html/2</span></code> compound term, a <em>doctype</em> is automatically written. If we prefer instead e.g. a XHTML 1.1 document, we use the <code class="docutils literal notranslate"><span class="pre">xhtml11</span></code> object:</p> <div class="highlight-logtalk notranslate"><div class="highlight"><pre><span></span>| <span class="o">?-</span> xhtml11<span class="o">::</span>generate( file(<span class="s">&#39;hello.html&#39;</span>), html([lang<span class="o">=</span>en], [head(title(<span class="s">&#39;Hello world!&#39;</span>)), body(p(<span class="s">&#39;Bye!&#39;</span>))]) ). </pre></div> </div> </section> <section id="generating-a-html-fragment"> <h2>Generating a HTML fragment<a class="headerlink" href="#generating-a-html-fragment" title="Permalink to this headline"></a></h2> <p>It’s also possible to generate just a fragment of a (X)HTML document by using a list of compound terms or a compound term for an element other then <code class="docutils literal notranslate"><span class="pre">html</span></code>. For example:</p> <div class="highlight-logtalk notranslate"><div class="highlight"><pre><span></span>| <span class="o">?-</span> <span class="k">current_output</span>(<span class="nv">Stream</span>), html5<span class="o">::</span>generate(stream(<span class="nv">Stream</span>), ul([li(foo), li(bar), li(baz)])). <span class="o">&lt;</span>ul<span class="o">&gt;</span> <span class="o">&lt;</span>li<span class="o">&gt;</span> foo<span class="o">&lt;/</span>li<span class="o">&gt;</span> <span class="o">&lt;</span>li<span class="o">&gt;</span> bar<span class="o">&lt;/</span>li<span class="o">&gt;</span> <span class="o">&lt;</span>li<span class="o">&gt;</span> baz<span class="o">&lt;/</span>li<span class="o">&gt;</span> <span class="o">&lt;/</span>ul<span class="o">&gt;</span> <span class="nv">Stream</span> <span class="o">=</span> ... </pre></div> </div> </section> <section id="working-with-callbacks-to-generate-content"> <h2>Working with callbacks to generate content<a class="headerlink" href="#working-with-callbacks-to-generate-content" title="Permalink to this headline"></a></h2> <p>Often we need to programmatically generate HTML content from queries. In other cases, we may have fixed content that we don’t want to keep repeating (e.g. a navigation bar). The library supports a <code class="docutils literal notranslate"><span class="pre">::/2</span></code> pseudo-element that sends a message to an object to retrieve content. As an example, assume the following predicate definition in <code class="docutils literal notranslate"><span class="pre">user</span></code>:</p> <div class="highlight-logtalk notranslate"><div class="highlight"><pre><span></span>content(strong(<span class="s">&#39;Hello world!&#39;</span>)). </pre></div> </div> <p>This predicate can then be called from the HTML term representation. For example:</p> <div class="highlight-logtalk notranslate"><div class="highlight"><pre><span></span>| <span class="o">?-</span> <span class="k">current_output</span>(<span class="nv">Stream</span>), html5<span class="o">::</span>generate(stream(<span class="nv">Stream</span>), span(user<span class="o">::</span>content)). <span class="o">&lt;</span>span<span class="o">&gt;&lt;</span>strong<span class="o">&gt;</span><span class="nv">Hello</span> world<span class="o">!&lt;/</span>strong<span class="o">&gt;&lt;/</span>span<span class="o">&gt;</span> <span class="nv">Stream</span> <span class="o">=</span> ... </pre></div> </div> <p>Note that the callback always takes the form <code class="docutils literal notranslate"><span class="pre">Object::Closure</span></code> where <code class="docutils literal notranslate"><span class="pre">Closure</span></code> is extended with a single argument (to be bound to the generated content). More complex callbacks are possible by using lambda expressions.</p> </section> <section id="working-with-custom-elements"> <h2>Working with custom elements<a class="headerlink" href="#working-with-custom-elements" title="Permalink to this headline"></a></h2> <p>The <code class="docutils literal notranslate"><span class="pre">html5</span></code> and <code class="docutils literal notranslate"><span class="pre">xhtml11</span></code> objects recognize the same set of standard HTML 5 normal and void elements and generate an error for non-standard elements. If you need to generate HTML content containing custom elements, define a new object that extends one of the library objects. For example:</p> <div class="highlight-logtalk notranslate"><div class="highlight"><pre><span></span><span class="p">:- </span><span class="k">object</span>(html5custom, <span class="k">extends</span>(html5)). normal_element(foo, inline). normal_element(bar, block). normal_element(<span class="nv">Name</span>, <span class="nv">Display</span>) <span class="o">:-</span> <span class="o">^^</span>normal_element(<span class="nv">Name</span>, <span class="nv">Display</span>). <span class="p">:- </span><span class="k">end_object</span>. </pre></div> </div> </section> </section> </div> </div> <footer><div class="rst-footer-buttons" role="navigation" aria-label="Footer"> <a href="hook_objects.html" class="btn btn-neutral float-left" title="hook_objects" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left" aria-hidden="true"></span> Previous</a> <a href="intervals.html" class="btn btn-neutral float-right" title="intervals" accesskey="n" rel="next">Next <span class="fa fa-arrow-circle-right" aria-hidden="true"></span></a> </div> <hr/> <div role="contentinfo"> <p>&#169; Copyright 1998-2022, Paulo Moura.</p> </div> Built with <a href="https://www.sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/readthedocs/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>. </footer> </div> </div> </section> </div> <script> jQuery(function () { SphinxRtdTheme.Navigation.enable(true); }); </script> </body> </html>
apache-2.0
pingcap/tikv
components/concurrency_manager/src/lib.rs
7031
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. //! The concurrency manager is responsible for concurrency control of //! transactions. //! //! The concurrency manager contains a lock table in memory. Lock information //! can be stored in it and reading requests can check if these locks block //! the read. //! //! In order to mutate the lock of a key stored in the lock table, it needs //! to be locked first using `lock_key` or `lock_keys`. mod key_handle; mod lock_table; pub use self::key_handle::{KeyHandle, KeyHandleGuard}; pub use self::lock_table::LockTable; use std::{ mem::{self, MaybeUninit}, sync::{ atomic::{AtomicU64, Ordering}, Arc, }, }; use txn_types::{Key, Lock, TimeStamp}; // TODO: Currently we are using a Mutex<BTreeMap> to implement the handle table. // In the future we should replace it with a concurrent ordered map. // Pay attention that the async functions of ConcurrencyManager should not hold // the mutex. #[derive(Clone)] pub struct ConcurrencyManager { max_ts: Arc<AtomicU64>, lock_table: LockTable, } impl ConcurrencyManager { pub fn new(latest_ts: TimeStamp) -> Self { ConcurrencyManager { max_ts: Arc::new(AtomicU64::new(latest_ts.into_inner())), lock_table: LockTable::default(), } } pub fn max_ts(&self) -> TimeStamp { TimeStamp::new(self.max_ts.load(Ordering::SeqCst)) } /// Updates max_ts with the given new_ts. It has no effect if /// max_ts >= new_ts or new_ts is TimeStamp::max(). pub fn update_max_ts(&self, new_ts: TimeStamp) { if new_ts != TimeStamp::max() { self.max_ts.fetch_max(new_ts.into_inner(), Ordering::SeqCst); } } /// Acquires a mutex of the key and returns an RAII guard. When the guard goes /// out of scope, the mutex will be unlocked. /// /// The guard can be used to store Lock in the table. The stored lock /// is visible to `read_key_check` and `read_range_check`. pub async fn lock_key(&self, key: &Key) -> KeyHandleGuard { self.lock_table.lock_key(key).await } /// Acquires mutexes of the keys and returns the RAII guards. The order of the /// guards is the same with the given keys. /// /// The guards can be used to store Lock in the table. The stored lock /// is visible to `read_key_check` and `read_range_check`. pub async fn lock_keys(&self, keys: impl Iterator<Item = &Key>) -> Vec<KeyHandleGuard> { let mut keys_with_index: Vec<_> = keys.enumerate().collect(); // To prevent deadlock, we sort the keys and lock them one by one. keys_with_index.sort_by_key(|(_, key)| *key); let mut result: Vec<MaybeUninit<KeyHandleGuard>> = Vec::new(); result.resize_with(keys_with_index.len(), MaybeUninit::uninit); for (index, key) in keys_with_index { result[index] = MaybeUninit::new(self.lock_table.lock_key(key).await); } #[allow(clippy::unsound_collection_transmute)] unsafe { mem::transmute(result) } } /// Checks if there is a memory lock of the key which blocks the read. /// The given `check_fn` should return false iff the lock passed in /// blocks the read. pub fn read_key_check<E>( &self, key: &Key, check_fn: impl FnOnce(&Lock) -> Result<(), E>, ) -> Result<(), E> { self.lock_table.check_key(key, check_fn) } /// Checks if there is a memory lock in the range which blocks the read. /// The given `check_fn` should return false iff the lock passed in /// blocks the read. pub fn read_range_check<E>( &self, start_key: Option<&Key>, end_key: Option<&Key>, check_fn: impl FnMut(&Key, &Lock) -> Result<(), E>, ) -> Result<(), E> { self.lock_table.check_range(start_key, end_key, check_fn) } /// Find the minimum start_ts among all locks in memory. pub fn global_min_lock_ts(&self) -> Option<TimeStamp> { let mut min_lock_ts = None; // TODO: The iteration looks not so efficient. It's better to be optimized. self.lock_table.for_each(|handle| { if let Some(curr_ts) = handle.with_lock(|lock| lock.as_ref().map(|l| l.ts)) { if min_lock_ts.map(|ts| ts > curr_ts).unwrap_or(true) { min_lock_ts = Some(curr_ts); } } }); min_lock_ts } } #[cfg(test)] mod tests { use super::*; use txn_types::LockType; #[tokio::test] async fn test_lock_keys_order() { let concurrency_manager = ConcurrencyManager::new(1.into()); let keys: Vec<_> = [b"c", b"a", b"b"] .iter() .map(|k| Key::from_raw(*k)) .collect(); let guards = concurrency_manager.lock_keys(keys.iter()).await; for (key, guard) in keys.iter().zip(&guards) { assert_eq!(key, guard.key()); } } #[tokio::test] async fn test_update_max_ts() { let concurrency_manager = ConcurrencyManager::new(10.into()); concurrency_manager.update_max_ts(20.into()); assert_eq!(concurrency_manager.max_ts(), 20.into()); concurrency_manager.update_max_ts(5.into()); assert_eq!(concurrency_manager.max_ts(), 20.into()); concurrency_manager.update_max_ts(TimeStamp::max()); assert_eq!(concurrency_manager.max_ts(), 20.into()); } fn new_lock(ts: impl Into<TimeStamp>, primary: &[u8], lock_type: LockType) -> Lock { let ts = ts.into(); Lock::new(lock_type, primary.to_vec(), ts, 0, None, 0.into(), 1, ts) } #[tokio::test] async fn test_global_min_lock_ts() { let concurrency_manager = ConcurrencyManager::new(1.into()); assert_eq!(concurrency_manager.global_min_lock_ts(), None); let guard = concurrency_manager.lock_key(&Key::from_raw(b"a")).await; assert_eq!(concurrency_manager.global_min_lock_ts(), None); guard.with_lock(|l| *l = Some(new_lock(10, b"a", LockType::Put))); assert_eq!(concurrency_manager.global_min_lock_ts(), Some(10.into())); drop(guard); assert_eq!(concurrency_manager.global_min_lock_ts(), None); let ts_seqs = vec![ vec![20, 30, 40], vec![40, 30, 20], vec![20, 40, 30], vec![30, 20, 40], ]; let keys: Vec<_> = vec![b"a", b"b", b"c"] .into_iter() .map(|k| Key::from_raw(k)) .collect(); for ts_seq in ts_seqs { let guards = concurrency_manager.lock_keys(keys.iter()).await; assert_eq!(concurrency_manager.global_min_lock_ts(), None); for (ts, guard) in ts_seq.into_iter().zip(guards.iter()) { guard.with_lock(|l| *l = Some(new_lock(ts, b"pk", LockType::Put))); } assert_eq!(concurrency_manager.global_min_lock_ts(), Some(20.into())); } } }
apache-2.0
akkakks/phabricator
src/applications/maniphest/view/ManiphestTaskResultListView.php
7755
<?php final class ManiphestTaskResultListView extends ManiphestView { private $tasks; private $savedQuery; private $canEditPriority; private $canBatchEdit; private $showBatchControls; public function setSavedQuery(PhabricatorSavedQuery $query) { $this->savedQuery = $query; return $this; } public function setTasks(array $tasks) { $this->tasks = $tasks; return $this; } public function setCanEditPriority($can_edit_priority) { $this->canEditPriority = $can_edit_priority; return $this; } public function setCanBatchEdit($can_batch_edit) { $this->canBatchEdit = $can_batch_edit; return $this; } public function setShowBatchControls($show_batch_controls) { $this->showBatchControls = $show_batch_controls; return $this; } public function render() { $viewer = $this->getUser(); $tasks = $this->tasks; $query = $this->savedQuery; // If we didn't match anything, just pick up the default empty state. if (!$tasks) { return id(new PHUIObjectItemListView()) ->setUser($viewer); } $group_parameter = nonempty($query->getParameter('group'), 'priority'); $order_parameter = nonempty($query->getParameter('order'), 'priority'); $handles = ManiphestTaskListView::loadTaskHandles($viewer, $tasks); $groups = $this->groupTasks( $tasks, $group_parameter, $handles); $can_edit_priority = $this->canEditPriority; $can_drag = ($order_parameter == 'priority') && ($can_edit_priority) && ($group_parameter == 'none' || $group_parameter == 'priority'); if (!$viewer->isLoggedIn()) { // TODO: (T603) Eventually, we conceivably need to make each task // draggable individually, since the user may be able to edit some but // not others. $can_drag = false; } $result = array(); $lists = array(); foreach ($groups as $group => $list) { $task_list = new ManiphestTaskListView(); $task_list->setShowBatchControls($this->showBatchControls); if ($can_drag) { $task_list->setShowSubpriorityControls(true); } $task_list->setUser($viewer); $task_list->setTasks($list); $task_list->setHandles($handles); $header = javelin_tag( 'h1', array( 'class' => 'maniphest-task-group-header', 'sigil' => 'task-group', 'meta' => array( 'priority' => head($list)->getPriority(), ), ), pht('%s (%s)', $group, new PhutilNumber(count($list)))); $lists[] = phutil_tag( 'div', array( 'class' => 'maniphest-task-group' ), array( $header, $task_list, )); } if ($can_drag) { Javelin::initBehavior( 'maniphest-subpriority-editor', array( 'uri' => '/maniphest/subpriority/', )); } return phutil_tag( 'div', array( 'class' => 'maniphest-list-container', ), array( $lists, $this->showBatchControls ? $this->renderBatchEditor($query) : null, )); } private function groupTasks(array $tasks, $group, array $handles) { assert_instances_of($tasks, 'ManiphestTask'); assert_instances_of($handles, 'PhabricatorObjectHandle'); $groups = $this->getTaskGrouping($tasks, $group); $results = array(); foreach ($groups as $label_key => $tasks) { $label = $this->getTaskLabelName($group, $label_key, $handles); $results[$label][] = $tasks; } foreach ($results as $label => $task_groups) { $results[$label] = array_mergev($task_groups); } return $results; } private function getTaskGrouping(array $tasks, $group) { switch ($group) { case 'priority': return mgroup($tasks, 'getPriority'); case 'status': return mgroup($tasks, 'getStatus'); case 'assigned': return mgroup($tasks, 'getOwnerPHID'); case 'project': return mgroup($tasks, 'getGroupByProjectPHID'); default: return array(pht('Tasks') => $tasks); } } private function getTaskLabelName($group, $label_key, array $handles) { switch ($group) { case 'priority': return ManiphestTaskPriority::getTaskPriorityName($label_key); case 'status': return ManiphestTaskStatus::getTaskStatusFullName($label_key); case 'assigned': if ($label_key) { return $handles[$label_key]->getFullName(); } else { return pht('(Not Assigned)'); } case 'project': if ($label_key) { return $handles[$label_key]->getFullName(); } else { // This may mean "No Projects", or it may mean the query has project // constraints but the task is only in constrained projects (in this // case, we don't show the group because it would always have all // of the tasks). Since distinguishing between these two cases is // messy and the UI is reasonably clear, label generically. return pht('(Ungrouped)'); } default: return pht('Tasks'); } } private function renderBatchEditor(PhabricatorSavedQuery $saved_query) { $user = $this->getUser(); if (!$this->canBatchEdit) { return null; } if (!$user->isLoggedIn()) { // Don't show the batch editor or excel export for logged-out users. // Technically we //could// let them export, but ehh. return null; } Javelin::initBehavior( 'maniphest-batch-selector', array( 'selectAll' => 'batch-select-all', 'selectNone' => 'batch-select-none', 'submit' => 'batch-select-submit', 'status' => 'batch-select-status-cell', 'idContainer' => 'batch-select-id-container', 'formID' => 'batch-select-form', )); $select_all = javelin_tag( 'a', array( 'href' => '#', 'mustcapture' => true, 'class' => 'grey button', 'id' => 'batch-select-all', ), pht('Select All')); $select_none = javelin_tag( 'a', array( 'href' => '#', 'mustcapture' => true, 'class' => 'grey button', 'id' => 'batch-select-none', ), pht('Clear Selection')); $submit = phutil_tag( 'button', array( 'id' => 'batch-select-submit', 'disabled' => 'disabled', 'class' => 'disabled', ), pht("Batch Edit Selected \xC2\xBB")); $export = javelin_tag( 'a', array( 'href' => '/maniphest/export/'.$saved_query->getQueryKey().'/', 'class' => 'grey button', ), pht('Export to Excel')); $hidden = phutil_tag( 'div', array( 'id' => 'batch-select-id-container', ), ''); $editor = hsprintf( '<div class="maniphest-batch-editor">'. '<div class="batch-editor-header">%s</div>'. '<table class="maniphest-batch-editor-layout">'. '<tr>'. '<td>%s%s</td>'. '<td>%s</td>'. '<td id="batch-select-status-cell">%s</td>'. '<td class="batch-select-submit-cell">%s%s</td>'. '</tr>'. '</table>'. '</div>', pht('Batch Task Editor'), $select_all, $select_none, $export, '', $submit, $hidden); $editor = phabricator_form( $user, array( 'method' => 'POST', 'action' => '/maniphest/batch/', 'id' => 'batch-select-form', ), $editor); return $editor; } }
apache-2.0
JetBrains/resharper-angularjs
src/resharper-angularjs/Psi/AngularJs/References/AngularJsIncludeFileReferenceProvider.cs
4390
#region license // Copyright 2014 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. #endregion using JetBrains.ReSharper.Plugins.AngularJS.Psi.Html; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.JavaScript.Tree; using JetBrains.ReSharper.Psi.Resolve; using JetBrains.ReSharper.Psi.Tree; using JetBrains.ReSharper.Psi.Util; using JetBrains.Util; namespace JetBrains.ReSharper.Plugins.AngularJS.Psi.AngularJs.References { [ReferenceProviderFactory] public class AngularJsIncludeFileReferenceProvider : AngularJsReferenceFactoryBase { private readonly IAngularJsHtmlDeclaredElementTypes elementTypes; public AngularJsIncludeFileReferenceProvider(IAngularJsHtmlDeclaredElementTypes elementTypes) { this.elementTypes = elementTypes; } protected override IReference[] GetReferences(ITreeNode element, IReference[] oldReferences) { if (!HasReference(element, null)) return EmptyArray<IReference>.Instance; var stringLiteral = (IJavaScriptLiteralExpression)element; var references = PathReferenceUtil.CreatePathReferences(stringLiteral, stringLiteral, null, GetFolderPathReference, GetFileReference, node => node.GetStringValue(), node => node.GetUnquotedTreeTextRange('"', '\'').StartOffset.Offset); return references; } private static IPathReference GetFileReference(IJavaScriptLiteralExpression literal, IQualifier qualifier, IJavaScriptLiteralExpression token, TreeTextRange range) { return new AngularJsFileLateBoundReference<IJavaScriptLiteralExpression, IJavaScriptLiteralExpression>(literal, qualifier, token, range); } private static IPathReference GetFolderPathReference(IJavaScriptLiteralExpression literal, IQualifier qualifier, IJavaScriptLiteralExpression token, TreeTextRange range) { return new AngularJsFolderLateBoundReference<IJavaScriptLiteralExpression, IJavaScriptLiteralExpression>(literal, qualifier, token, range); } protected override bool HasReference(ITreeNode element, IReferenceNameContainer names) { var stringLiteral = element as IJavaScriptLiteralExpression; if (stringLiteral == null) return false; var file = element.GetContainingFile(); if (file == null) return false; // TODO: We can't use this, due to losing data when we reparse for code completion // When we start code completion, the tree node is reparsed with new text inserted, // so that references have something to attach to. Reparsing works with IChameleon // blocks that allow for resync-ing in-place. Our AngularJs nodes don't have any // chameleon blocks (for JS, it's the Block class - anything with braces) so we end // up re-parsing the file. This creates a new IFile, (in a sandbox that allows access // to the original file's reference provider) but it doesn't copy the user data. We // could theoretically look for a containing sandbox, get the context node and try // and get the user data there, but that just makes it feel like this is the wrong // solution. I think maybe this should be a reference provider for HTML, not AngularJs. // It would have the context of the attribute name, but should really work with the // injected AngularJs language, if only to see that it's a string literal //var originalAttributeType = file.UserData.GetData(AngularJsFileData.OriginalAttributeType); //if (originalAttributeType != elementTypes.AngularJsUrlType.Name) // return false; return true; } } }
apache-2.0
aso4/aso4.github.io
_posts/2016-09-01-project-6.markdown
701
--- title: FireChat subtitle: Angular-based Real-time Chat layout: default modal-id: 6 date: 2016-09-01 img: firechat.png thumbnail: chat_thumbnail.png alt: image-alt project-date: September 2016 git: https://github.com/aso4/firechat demo: https://aso4-firechat.herokuapp.com/ description: This chat app is so-named due to the use of Google Firebase to persist chatroom data. It also marks one of the earliest attempts at utilizing the Bootstrap framework. Users enter a handle and can select an existing room or create a new room to begin chatting in real-time with other users. Deployed to Heroku using Grunt and Node. tools: Angular, jQuery, Bootstrap, CSS, Firebase, AngularFire, Grunt, Node ---
apache-2.0
windchopper/common
common-fx/src/main/java/com/github/windchopper/common/fx/behavior/WindowMoveResizeBehavior.java
12341
package com.github.windchopper.common.fx.behavior; import javafx.geometry.*; import javafx.scene.Cursor; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Region; import javafx.stage.Stage; import javafx.stage.Window; import java.util.stream.Stream; import static java.util.Arrays.stream; public class WindowMoveResizeBehavior implements Behavior<Region> { private static class AngleRange { private final double minAngle; private final double maxAngle; public AngleRange(double minAngle, double maxAngle) { this.minAngle = minAngle; this.maxAngle = maxAngle; } public boolean matches(double angle) { return angle >= minAngle && angle <= maxAngle; } } private abstract class DragMode { protected double savedSceneX; protected double savedSceneY; protected double savedScreenX; protected double savedScreenY; protected double savedWidth; protected double savedHeight; public abstract void apply(MouseEvent event); public void store(MouseEvent event) { savedSceneX = event.getSceneX(); savedSceneY = event.getSceneY(); savedScreenX = event.getScreenX(); savedScreenY = event.getScreenY(); Window window = region.getScene().getWindow(); savedWidth = window.getWidth(); savedHeight = window.getHeight(); } } private class MoveMode extends DragMode { private final Cursor normalCursor; private final Cursor dragCursor; public MoveMode(Cursor normalCursor, Cursor dragCursor) { this.normalCursor = normalCursor; this.dragCursor = dragCursor; } @Override public void apply(MouseEvent event) { if (event.getEventType() != MouseEvent.MOUSE_DRAGGED) { region.setCursor(normalCursor); } else { region.setCursor(dragCursor); Window window = region.getScene().getWindow(); window.setX(event.getScreenX() - savedSceneX); window.setY(event.getScreenY() - savedSceneY); } } } private abstract class ResizeMode extends DragMode { private final Cursor cursor; private final AngleRange []angleRanges; public abstract Bounds calculateBounds(MouseEvent dragEvent, Window window); public ResizeMode(Cursor cursor, AngleRange... angleRanges) { this.cursor = cursor; this.angleRanges = angleRanges; } public boolean matches(double angle) { return stream(angleRanges).anyMatch(range -> range.matches(angle)); } @Override public void apply(MouseEvent event) { region.setCursor(cursor); if (event.getEventType() == MouseEvent.MOUSE_DRAGGED) { var window = region.getScene().getWindow(); var bounds = calculateBounds(event, window); var width = bounds.getWidth(); var height = bounds.getHeight(); if (window instanceof Stage) { var stage = (Stage) window; if (stage.isResizable()) { width = Math.min(Math.max(width, stage.getMinWidth()), stage.getMaxWidth()); height = Math.min(Math.max(height, stage.getMinHeight()), stage.getMaxHeight()); } else { width = window.getWidth(); height = window.getHeight(); } } window.setX(bounds.getMinX()); window.setY(bounds.getMinY()); window.setWidth(width); window.setHeight(height); } } } private class ResizeEastMode extends ResizeMode { public ResizeEastMode(AngleRange... angleRanges) { super(Cursor.E_RESIZE, angleRanges); } @Override public Bounds calculateBounds(MouseEvent dragEvent, Window window) { return new BoundingBox( window.getX(), window.getY(), savedWidth + dragEvent.getScreenX() - savedScreenX, window.getHeight()); } } private class ResizeNorthEastMode extends ResizeMode { public ResizeNorthEastMode(AngleRange... angleRanges) { super(Cursor.NE_RESIZE, angleRanges); } @Override public Bounds calculateBounds(MouseEvent dragEvent, Window window) { return new BoundingBox( window.getX(), dragEvent.getScreenY() - savedSceneY, savedWidth + dragEvent.getScreenX() - savedScreenX, savedHeight - dragEvent.getScreenY() + savedScreenY); } } private class ResizeNorthMode extends ResizeMode { public ResizeNorthMode(AngleRange... angleRanges) { super(Cursor.N_RESIZE, angleRanges); } @Override public Bounds calculateBounds(MouseEvent dragEvent, Window window) { return new BoundingBox( window.getX(), dragEvent.getScreenY() - savedSceneY, window.getWidth(), savedHeight - dragEvent.getScreenY() + savedScreenY); } } private class ResizeNorthWestMode extends ResizeMode { public ResizeNorthWestMode(AngleRange... angleRanges) { super(Cursor.NW_RESIZE, angleRanges); } @Override public Bounds calculateBounds(MouseEvent dragEvent, Window window) { return new BoundingBox( dragEvent.getScreenX() - savedSceneX, dragEvent.getScreenY() - savedSceneY, savedWidth - dragEvent.getScreenX() + savedScreenX, savedHeight - dragEvent.getScreenY() + savedScreenY); } } private class ResizeWestMode extends ResizeMode { public ResizeWestMode(AngleRange... angleRanges) { super(Cursor.W_RESIZE, angleRanges); } @Override public Bounds calculateBounds(MouseEvent dragEvent, Window window) { return new BoundingBox( dragEvent.getScreenX() - savedSceneX, window.getY(), savedWidth - dragEvent.getScreenX() + savedScreenX, window.getHeight()); } } private class ResizeSouthWestMode extends ResizeMode { public ResizeSouthWestMode(AngleRange... angleRanges) { super(Cursor.SW_RESIZE, angleRanges); } @Override public Bounds calculateBounds(MouseEvent dragEvent, Window window) { return new BoundingBox( dragEvent.getScreenX() - savedSceneX, window.getY(), savedWidth - dragEvent.getScreenX() + savedScreenX, savedHeight + dragEvent.getScreenY() - savedScreenY); } } private class ResizeSouthMode extends ResizeMode { public ResizeSouthMode(AngleRange... angleRanges) { super(Cursor.S_RESIZE, angleRanges); } @Override public Bounds calculateBounds(MouseEvent dragEvent, Window window) { return new BoundingBox( window.getX(), window.getY(), window.getWidth(), savedHeight + dragEvent.getScreenY() - savedScreenY); } } private class ResizeSouthEastMode extends ResizeMode { public ResizeSouthEastMode(AngleRange... angleRanges) { super(Cursor.SE_RESIZE, angleRanges); } @Override public Bounds calculateBounds(MouseEvent dragEvent, Window window) { return new BoundingBox( window.getX(), window.getY(), savedWidth + dragEvent.getScreenX() - savedScreenX, savedHeight + dragEvent.getScreenY() - savedScreenY); } } private final Region region; private final double resizeBorderSize; private final MoveMode move; private final ResizeMode resizeEast; private final ResizeMode resizeNorthEast; private final ResizeMode resizeNorth; private final ResizeMode resizeNorthWest; private final ResizeMode resizeWest; private final ResizeMode resizeSouthWest; private final ResizeMode resizeSouth; private final ResizeMode resizeSouthEast; private DragMode dragMode; public WindowMoveResizeBehavior(Region region) { this(region, 2, 2); } public WindowMoveResizeBehavior(Region region, double resizeBorderSize, double diagonalResizeSpotAngularSize) { this.region = region; this.resizeBorderSize = resizeBorderSize; dragMode = move = new MoveMode(Cursor.DEFAULT, Cursor.MOVE); resizeEast = new ResizeEastMode(new AngleRange(0, 45 - diagonalResizeSpotAngularSize), new AngleRange(315 + diagonalResizeSpotAngularSize, 360)); resizeNorthEast = new ResizeNorthEastMode(new AngleRange(45 - diagonalResizeSpotAngularSize, 45 + diagonalResizeSpotAngularSize)); resizeNorth = new ResizeNorthMode(new AngleRange(45 + diagonalResizeSpotAngularSize, 135 - diagonalResizeSpotAngularSize)); resizeNorthWest = new ResizeNorthWestMode(new AngleRange(135 - diagonalResizeSpotAngularSize, 135 + diagonalResizeSpotAngularSize)); resizeWest = new ResizeWestMode(new AngleRange(135 + diagonalResizeSpotAngularSize, 225 - diagonalResizeSpotAngularSize)); resizeSouthWest = new ResizeSouthWestMode(new AngleRange(225 - diagonalResizeSpotAngularSize, 225 + diagonalResizeSpotAngularSize)); resizeSouth = new ResizeSouthMode(new AngleRange(225 + diagonalResizeSpotAngularSize, 315 - diagonalResizeSpotAngularSize)); resizeSouthEast = new ResizeSouthEastMode(new AngleRange(315 - diagonalResizeSpotAngularSize, 315 + diagonalResizeSpotAngularSize)); } private double calculateAngle(double x, double y) { double angle = Math.toDegrees( Math.atan2(y, x)); if (angle < 0) { angle = 360 + angle; } if (angle > 360) { angle = 360; } return angle; } private DragMode detect(MouseEvent event) { Bounds bounds = region.getLayoutBounds(); Bounds outerBounds = new BoundingBox(bounds.getMinX() - resizeBorderSize, bounds.getMinY() - resizeBorderSize, bounds.getWidth() + resizeBorderSize * 2, bounds.getHeight() + resizeBorderSize * 2); Bounds innerBounds = new BoundingBox(bounds.getMinX() + resizeBorderSize, bounds.getMinY() + resizeBorderSize, bounds.getWidth() - resizeBorderSize * 2, bounds.getHeight() - resizeBorderSize * 2); Point2D center = new Point2D(innerBounds.getWidth() / 2, innerBounds.getHeight() / 2); Point2D ptr = new Point2D( event.getX(), event.getY()); if (outerBounds.contains(ptr) && !innerBounds.contains(ptr)) { double angle = calculateAngle(ptr.getX() - center.getX(), (ptr.getY() - center.getY()) * (outerBounds.getWidth() / outerBounds.getHeight()) * -1); return Stream.of(resizeEast, resizeNorthEast, resizeNorth, resizeNorthWest, resizeWest, resizeSouthWest, resizeSouth, resizeSouthEast) .filter(mode -> mode.matches(angle)) .findFirst().orElseThrow(AssertionError::new); } return move; } private void mouseAny(MouseEvent event) { dragMode.apply(event); } private void mousePress(MouseEvent event) { dragMode.store(event); mouseAny(event); } private void mouseRelease(MouseEvent event) { mouseAny(event); } private void mouseMove(MouseEvent event) { dragMode = detect(event); mouseAny(event); } private void mouseDrag(MouseEvent event) { mouseAny(event); } /* * */ @Override public void apply(Region region) { region.setOnMousePressed(this::mousePress); region.setOnMouseReleased(this::mouseRelease); region.setOnMouseMoved(this::mouseMove); region.setOnMouseDragged(this::mouseDrag); } }
apache-2.0
jreyes/mirror
app/src/main/java/com/vaporwarecorp/mirror/feature/artik/ArtikManagerImpl.java
7495
/* * Copyright 2016 Johann Reyes * * 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.vaporwarecorp.mirror.feature.artik; import android.content.Intent; import com.fasterxml.jackson.databind.JsonNode; import com.robopupu.api.dependency.Provides; import com.robopupu.api.dependency.Scope; import com.robopupu.api.plugin.Plug; import com.robopupu.api.plugin.Plugin; import com.robopupu.api.plugin.PluginBus; import com.vaporwarecorp.mirror.app.MirrorAppScope; import com.vaporwarecorp.mirror.component.AppManager; import com.vaporwarecorp.mirror.component.ConfigurationManager; import com.vaporwarecorp.mirror.component.EventManager; import com.vaporwarecorp.mirror.component.PluginFeatureManager; import com.vaporwarecorp.mirror.event.ApplicationEvent; import com.vaporwarecorp.mirror.feature.common.AbstractMirrorManager; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import timber.log.Timber; import java.util.Map; import static com.vaporwarecorp.mirror.event.ApplicationEvent.TRY_TO_START; import static com.vaporwarecorp.mirror.util.JsonUtil.createTextNode; import static org.apache.commons.lang3.StringUtils.isNotEmpty; @Plugin @Scope(MirrorAppScope.class) @Provides(ArtikManager.class) public class ArtikManagerImpl extends AbstractMirrorManager implements ArtikManager { // ------------------------------ FIELDS ------------------------------ private static final String PREF = ArtikManager.class.getName(); private static final String PREF_APPLICATION_ID = PREF + ".PREF_APPLICATION_ID"; private static final String PREF_CONTROL_DEVICE_ID = PREF + ".PREF_CONTROL_DEVICE_ID"; private static final String PREF_SIDEKICK_DEVICE_ID = PREF + ".PREF_SIDEKICK_DEVICE_ID"; @Plug AppManager mAppManager; @Plug ConfigurationManager mConfigurationManager; @Plug EventManager mEventManager; @Plug PluginFeatureManager mFeatureManager; private String mAccessToken; private String mApplicationId; private ArtikCloudManager mArtikCloudManager; private ArtikOAuthManager mArtikOAuthManager; private String mControlDeviceId; private boolean mEnabled; private String mSidekickDeviceId; // ------------------------ INTERFACE METHODS ------------------------ // --------------------- Interface ArtikManager --------------------- @Override public void share(Map<String, Object> content) { if (mArtikCloudManager == null) { return; } subscribe(mArtikCloudManager.sendAction(content) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<String>() { @Override public void onCompleted() { Timber.d("onCompleted"); } @Override public void onError(Throwable e) { Timber.e(e, "Error trying to send action"); } @Override public void onNext(String s) { } })); } // --------------------- Interface Configuration --------------------- @Override public String getJsonConfiguration() { return "configuration/json/artik.json"; } @Override public String getJsonValues() { return createTextNode("applicationId", mApplicationId) .put("controlDeviceId", mControlDeviceId) .put("sidekickDeviceId", mSidekickDeviceId) .toString(); } @Override public void updateConfiguration(JsonNode jsonNode) { mConfigurationManager.updateString(PREF_APPLICATION_ID, jsonNode, "applicationId"); mConfigurationManager.updateString(PREF_CONTROL_DEVICE_ID, jsonNode, "controlDeviceId"); mConfigurationManager.updateString(PREF_SIDEKICK_DEVICE_ID, jsonNode, "sidekickDeviceId"); loadConfiguration(); onFeatureResume(); } // --------------------- Interface MirrorManager --------------------- @Override public void onFeaturePause() { if (mArtikCloudManager != null) { mArtikCloudManager.stopMessaging(); mArtikCloudManager = null; } } @Override public void onFeatureResume() { if (mEnabled) { mArtikCloudManager = new ArtikCloudManager(mEventManager, mApplicationId, mSidekickDeviceId, mControlDeviceId, mAccessToken); mArtikCloudManager.startMessaging(); } } // --------------------- Interface PluginComponent --------------------- @Override public void onPlugged(PluginBus bus) { super.onPlugged(bus); loadConfiguration(); } @Override public void onUnplugged(PluginBus bus) { mArtikCloudManager = null; mArtikOAuthManager = null; super.onUnplugged(bus); } // --------------------- Interface WebAuthentication --------------------- @Override public void doAuthentication() { if(!mEnabled) { mEventManager.post(new ApplicationEvent(TRY_TO_START)); return; } // get authorization subscribe(mArtikOAuthManager.authorizeImplicitly() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<String>() { @Override public void onCompleted() { Timber.d("onCompleted"); mEventManager.post(new ApplicationEvent(TRY_TO_START)); } @Override public void onError(Throwable e) { Timber.e(e, "Error trying to authenticate"); } @Override public void onNext(String s) { mAccessToken = s; } })); } @Override public void isAuthenticated(IsAuthenticatedCallback callback) { callback.onResult(false); } @Override public void onAuthenticationResult(int requestCode, int resultCode, Intent data) { } private void loadConfiguration() { mApplicationId = mConfigurationManager.getString(PREF_APPLICATION_ID, ""); mControlDeviceId = mConfigurationManager.getString(PREF_CONTROL_DEVICE_ID, ""); mSidekickDeviceId = mConfigurationManager.getString(PREF_SIDEKICK_DEVICE_ID, ""); mEnabled = isNotEmpty(mApplicationId) && (isNotEmpty(mControlDeviceId) || isNotEmpty(mSidekickDeviceId)); startArtikManagers(); } private void startArtikManagers() { if (!mEnabled) { return; } mArtikOAuthManager = ArtikOAuthManager.newInstance(mFeatureManager.getForegroundActivity(), mApplicationId); } }
apache-2.0
BillHan/book-examples-v6
src/main/java/com/vaadin/book/applications/UriFragmentApplication.java
2141
package com.vaadin.book.applications; import com.vaadin.Application; import com.vaadin.data.Property; import com.vaadin.data.Property.ValueChangeEvent; import com.vaadin.ui.*; import com.vaadin.ui.UriFragmentUtility.FragmentChangedEvent; import com.vaadin.ui.UriFragmentUtility.FragmentChangedListener; // BEGIN-EXAMPLE: advanced.urifragmentutility.uriexample public class UriFragmentApplication extends Application { private static final long serialVersionUID = -128617724108192945L; @Override public void init() { Window main = new Window("URI Fragment Example"); setMainWindow(main); setTheme("book-examples"); // Create the URI fragment utility final UriFragmentUtility urifu = new UriFragmentUtility(); main.addComponent(urifu); // Application state menu final ListSelect menu = new ListSelect("Select a URI Fragment"); menu.addItem("mercury"); menu.addItem("venus"); menu.addItem("earth"); menu.addItem("mars"); menu.setRows(4); menu.setNullSelectionAllowed(false); menu.setImmediate(true); main.addComponent(menu); // Set the URI Fragment when menu selection changes menu.addListener(new Property.ValueChangeListener() { private static final long serialVersionUID = 6380648224897936536L; public void valueChange(ValueChangeEvent event) { String itemid = (String) event.getProperty().getValue(); urifu.setFragment(itemid); } }); // When the URI fragment is given, use it to set menu selection urifu.addListener(new FragmentChangedListener() { private static final long serialVersionUID = -6588416218607827834L; public void fragmentChanged(FragmentChangedEvent source) { String fragment = source.getUriFragmentUtility().getFragment(); if (fragment != null) menu.setValue(fragment); } }); } } // END-EXAMPLE: advanced.urifragmentutility.uriexample
apache-2.0
elmgone/coligui
vendor/github.com/rs/rest-layer/resource/index.go
3120
package resource import ( "fmt" "net/url" "strings" "github.com/rs/rest-layer/schema" ) // Index is an interface defining a type able to bind and retrieve resources // from a resource graph. type Index interface { // Bind a new resource at the "name" endpoint Bind(name string, s schema.Schema, h Storer, c Conf) *Resource // GetResource retrives a given resource by it's path. // For instance if a resource user has a sub-resource posts, // a users.posts path can be use to retrieve the posts resource. // // If a parent is given and the path starts with a dot, the lookup is started at the // parent's location instead of root's. GetResource(path string, parent *Resource) (*Resource, bool) // GetResources returns first level resources GetResources() []*Resource } // index is the root of the resource graph type index struct { resources subResources } // NewIndex creates a new resource index func NewIndex() Index { return &index{ resources: subResources{}, } } // Bind a resource at the specified endpoint name func (r *index) Bind(name string, s schema.Schema, h Storer, c Conf) *Resource { assertNotBound(name, r.resources, nil) sr := new(name, s, h, c) r.resources.add(sr) return sr } // Compile the resource graph and report any error func (r *index) Compile() error { return compileResourceGraph(r.resources) } // GetResource retrives a given resource by it's path. // For instance if a resource user has a sub-resource posts, // a users.posts path can be use to retrieve the posts resource. // // If a parent is given and the path starts with a dot, the lookup is started at the // parent's location instead of root's. func (r *index) GetResource(path string, parent *Resource) (*Resource, bool) { resources := r.resources if len(path) > 0 && path[0] == '.' { if parent == nil { // If field starts with a dot and no parent is given, fail the lookup return nil, false } path = path[1:] resources = parent.resources } var sr *Resource if strings.IndexByte(path, '.') == -1 { if sr = resources.get(path); sr != nil { resources = sr.resources } else { return nil, false } } else { for _, comp := range strings.Split(path, ".") { if sr = resources.get(comp); sr != nil { resources = sr.resources } else { return nil, false } } } return sr, true } // GetResources returns first level resources func (r *index) GetResources() []*Resource { return r.resources } func compileResourceGraph(resources subResources) error { for _, r := range resources { if err := r.Compile(); err != nil { sep := "." if err.Error()[0] == ':' { sep = "" } return fmt.Errorf("%s%s%s", r.name, sep, err) } } return nil } // assertNotBound asserts a given resource name is not already bound func assertNotBound(name string, resources subResources, aliases map[string]url.Values) { for _, r := range resources { if r.name == name { logPanicf(nil, "Cannot bind `%s': already bound as resource'", name) } } if _, found := aliases[name]; found { logPanicf(nil, "Cannot bind `%s': already bound as alias'", name) } }
apache-2.0
brata-hsdc/brata.masterserver
workspace/ms/scoreboard/tests/test_dock.py
49951
from django.test import TestCase from django.utils.timezone import utc from datetime import datetime import json import logging import mock from dbkeeper.models import Organization, Team, Setting from piservice.models import PiStation, PiEvent import scoreboard.views as target def _mocked_utcNow(): return datetime(2001, 1, 1, 0, 0, 0).replace(tzinfo=utc) class ScoreboardStatusDockTestCase(TestCase): def _setUpStations(self): self.launchStation = PiStation.objects.create( station_type = PiStation.LAUNCH_STATION_TYPE, serial_num = self._serialNum ) self._serialNum += 1 self.dockStation = PiStation.objects.create( station_type = PiStation.DOCK_STATION_TYPE, serial_num = self._serialNum ) self._serialNum += 1 self.secureStation = PiStation.objects.create( station_type = PiStation.SECURE_STATION_TYPE, serial_num = self._serialNum ) self._serialNum += 1 self.returnStation = PiStation.objects.create( station_type = PiStation.RETURN_STATION_TYPE, serial_num = self._serialNum ) self._serialNum += 1 self.station = self.dockStation def _setUpTeams(self): org = Organization.objects.create( name = "School 1", type = Organization.SCHOOL_TYPE ) self.team1Name = "Team 1" self.team1 = Team.objects.create( name = self.team1Name, organization = org ) def _setUpEvents(self): # Some tests don't need these events. If not needed for a particular # test, use PiEvent.objects.all().delete() e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 0, 0).replace(tzinfo=utc), type = PiEvent.EVENT_STARTED_MSG_TYPE ) def _verify(self, expectedScore, expectedDuration_s): actual = target._recomputeTeamScore(self.team1Name) actualScore = actual['dock_score'] actualDuration_s = actual['dock_duration_s'] self.assertEqual(expectedScore, actualScore) self.assertEqual(expectedDuration_s, actualDuration_s) def setUp(self): PiEvent._meta.get_field("time").auto_now_add = False self._serialNum = 1 self._setUpStations() self._setUpTeams() self._setUpEvents() self._watchingTime_s = 45.0 Setting.objects.create(name = 'DNF_TIME_PENALTY_FACTOR', value = str(2.0)) Setting.objects.create(name = 'DOCK_SIM_PLAYBACK_TIME_S', value = str(self._watchingTime_s)) def test_recomputeDockScore_noEvents(self): PiEvent.objects.all().delete() expectedScore = 0 expectedDuration_s = 0 self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_noEventStartedEvent(self, side_effect=_mocked_utcNow): PiEvent.objects.all().delete() e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.SUCCESS_STATUS, data = json.dumps({"candidate_answer": 0, "fail_message": "OUTCOME_SUCCESS"}, separators=(',',':')) ) expectedScore = 0 expectedDuration_s = 0 self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_eventsBeforeEventStartedEvent(self, side_effect=_mocked_utcNow): PiEvent.objects.all().delete() e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, pi = self.station, team = self.team1, status = PiEvent.SUCCESS_STATUS, data = json.dumps({"candidate_answer": 0, "fail_message": "OUTCOME_SUCCESS"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 59).replace(tzinfo=utc), type = PiEvent.EVENT_STARTED_MSG_TYPE ) expectedScore = 0 expectedDuration_s = 0 self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_noStartChallengeEvents(self, side_effect=_mocked_utcNow): e = PiEvent.objects.create( time = datetime(2001, 1, 1, 0, 0, 0).replace(tzinfo=utc), type = PiEvent.REGISTER_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.SUCCESS_STATUS ) expectedScore = 0 expectedDuration_s = 0 self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_onlyOneStartChallengeEventSameTimestampNoSuccessFail(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2001, 1, 1, 0, 0, 0).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) expectedScore = 1 expectedDuration_s = 0 self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_onlyOneStartChallengeEventEarlierTimestampNoSuccessFail(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) expectedScore = 1 expectedDuration_s = 10 self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_onlyOneStartChallengeEventEarlierTimestampSuccessNoConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime_s = 100 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.SUCCESS_STATUS, data = json.dumps({"candidate_answer": actualTime_s, "fail_message": "OUTCOME_SUCCESS"}, separators=(',',':')) ) expectedScore = 9 expectedDuration_s = 6 - self._watchingTime_s + actualTime_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_onlyOneStartChallengeEventEarlierTimestampSuccessWithConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime_s = 68 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.SUCCESS_STATUS, data = json.dumps({"candidate_answer": actualTime_s, "fail_message": "OUTCOME_SUCCESS"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 58).replace(tzinfo=utc), type = PiEvent.EVENT_CONCLUDED_MSG_TYPE, team = self.team1, pi = self.station ) expectedScore = 9 expectedDuration_s = 6 - self._watchingTime_s + actualTime_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_onlyOneStartChallengeEventEarlierTimestampFailOutcomeDnf2xPenaltyNoConclude(self, mock_utcNow): dnfPenalty = 2.0 Setting.objects.all().delete() Setting.objects.create(name = 'DNF_TIME_PENALTY_FACTOR', value = str(dnfPenalty)) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime_s = 213 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime_s, "fail_message": "OUTCOME_DNF"}, separators=(',',':')) ) expectedScore = 1 expectedDuration_s = 10 - self._watchingTime_s + (actualTime_s * dnfPenalty) self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_onlyOneStartChallengeEventEarlierTimestampFailOutcomeDnf3xPenaltyNoConclude(self, mock_utcNow): dnfPenalty = 3.0 Setting.objects.all().delete() Setting.objects.create(name = 'DNF_TIME_PENALTY_FACTOR', value = str(dnfPenalty)) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime_s = 47 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime_s, "fail_message": "OUTCOME_DNF"}, separators=(',',':')) ) expectedScore = 1 expectedDuration_s = 10 - self._watchingTime_s + (actualTime_s * dnfPenalty) self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_onlyOneStartChallengeEventEarlierTimestampFailOutcomeDnf8xPenaltyNoConclude(self, mock_utcNow): dnfPenalty = 8.0 Setting.objects.all().delete() Setting.objects.create(name = 'DNF_TIME_PENALTY_FACTOR', value = str(dnfPenalty)) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime_s = 33 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime_s, "fail_message": "OUTCOME_DNF"}, separators=(',',':')) ) expectedScore = 1 expectedDuration_s = 10 - self._watchingTime_s + (actualTime_s * dnfPenalty) self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_onlyOneStartChallengeEventEarlierTimestampFailNoConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime_s = 1684 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) expectedScore = 1 expectedDuration_s = 10 - self._watchingTime_s + actualTime_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_onlyOneStartChallengeEventEarlierTimestampFailWithConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime_s = 2000 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 58).replace(tzinfo=utc), type = PiEvent.EVENT_CONCLUDED_MSG_TYPE, team = self.team1, pi = self.station ) expectedScore = 1 expectedDuration_s = 8 - self._watchingTime_s + actualTime_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_twoStartChallengeEventsEarlierTimestampSuccessNoSuccessFail(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime_s = 3000 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.SUCCESS_STATUS, data = json.dumps({"candidate_answer": actualTime_s, "fail_message": "OUTCOME_SUCCESS"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 57).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) expectedScore = 9 expectedDuration_s = 6 - self._watchingTime_s + actualTime_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_twoStartChallengeEventsEarlierTimestampSuccessFail(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 319 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.SUCCESS_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_SUCCESS"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 57).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 4897 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 58).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) expectedScore = 9 expectedDuration_s = 6 - self._watchingTime_s + actualTime1_s # ignore actualTime2_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_twoStartChallengeEventsEarlierTimestampSuccessSuccess(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 3213 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.SUCCESS_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_SUCCESS"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 57).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 228 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 58).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.SUCCESS_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_SUCCESS"}, separators=(',',':')) ) expectedScore = 9 expectedDuration_s = 6 - self._watchingTime_s + actualTime1_s # ignore acutalTime2_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_twoStartChallengeEventsEarlierTimestampFailNoSuccessFail(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 46).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime_s = 283 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 48).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) expectedScore = 1 expectedDuration_s = 14 - self._watchingTime_s + actualTime_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_twoStartChallengeEventsEarlierTimestampFailSuccessNoConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 46).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 9385 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 48).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 332 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 52).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.SUCCESS_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_SUCCESS"}, separators=(',',':')) ) expectedScore = 9 expectedDuration_s = 6 - self._watchingTime_s + actualTime1_s - self._watchingTime_s + actualTime2_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_twoStartChallengeEventsEarlierTimestampFailSuccessWithConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 46).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 123 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 48).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 456 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 52).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.SUCCESS_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_SUCCESS"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 58).replace(tzinfo=utc), type = PiEvent.EVENT_CONCLUDED_MSG_TYPE, team = self.team1, pi = self.station ) expectedScore = 9 expectedDuration_s = 6 - self._watchingTime_s + actualTime1_s - self._watchingTime_s + actualTime2_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_twoStartChallengeEventsEarlierTimestampFailFailNoConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 46).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 345 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 48).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 678 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 52).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 54).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) expectedScore = 1 expectedDuration_s = 14 - self._watchingTime_s + actualTime1_s - self._watchingTime_s + actualTime2_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_twoStartChallengeEventsEarlierTimestampFailFailWithConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 46).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 4567 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 48).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 678 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 52).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 54).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 58).replace(tzinfo=utc), type = PiEvent.EVENT_CONCLUDED_MSG_TYPE, team = self.team1, pi = self.station ) expectedScore = 1 expectedDuration_s = 12 - self._watchingTime_s + actualTime1_s - self._watchingTime_s + actualTime2_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_threeStartChallengeEventsEarlierTimestampFailFailNoSuccessFail(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 46).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 567 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 48).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 890 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 52).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 54).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) expectedScore = 1 expectedDuration_s = 14 - self._watchingTime_s + actualTime1_s - self._watchingTime_s + actualTime2_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_threeStartChallengeEventsEarlierTimestampFailFailSuccessNoConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 46).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 678 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 48).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 789 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 52).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 54).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime3_s = 7654 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.SUCCESS_STATUS, data = json.dumps({"candidate_answer": actualTime3_s, "fail_message": "OUTCOME_SUCCESS"}, separators=(',',':')) ) expectedScore = 9 expectedDuration_s = 10 - self._watchingTime_s + actualTime1_s - self._watchingTime_s + actualTime2_s - self._watchingTime_s + actualTime3_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_threeStartChallengeEventsEarlierTimestampFailFailSuccessWithConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 46).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 321 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 48).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 654 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 52).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 54).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime3_s = 987 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.SUCCESS_STATUS, data = json.dumps({"candidate_answer": actualTime3_s, "fail_message": "OUTCOME_SUCCESS"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 58).replace(tzinfo=utc), type = PiEvent.EVENT_CONCLUDED_MSG_TYPE, team = self.team1, pi = self.station ) expectedScore = 9 expectedDuration_s = 10 - self._watchingTime_s + actualTime1_s - self._watchingTime_s + actualTime2_s - self._watchingTime_s + actualTime3_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_threeStartChallengeEventsEarlierTimestampFailFailFailNoConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 46).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 37 # this is less than 45 sec, so watchingTime will be used instead e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 48).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 54 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 52).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 54).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime3_s = 76 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime3_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) expectedScore = 5 expectedDuration_s = 10 - self._watchingTime_s + self._watchingTime_s - self._watchingTime_s + actualTime2_s - self._watchingTime_s + actualTime3_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_threeStartChallengeEventsEarlierTimestampFailFailFailWithConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 46).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 23 # use watchTime_s instead since this is less than 45 sec e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 48).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 45 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 52).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 54).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime3_s = 67 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime3_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 58).replace(tzinfo=utc), type = PiEvent.EVENT_CONCLUDED_MSG_TYPE, team = self.team1, pi = self.station ) expectedScore = 5 expectedDuration_s = 10 - self._watchingTime_s + self._watchingTime_s - self._watchingTime_s + actualTime2_s - self._watchingTime_s + actualTime3_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_fourStartChallengeEventsEarlierTimestampFailFailFailNoSuccessFail(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 46).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 123 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 48).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 45 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 52).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 54).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime3_s = 6789 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime3_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 57).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) expectedScore = 5 expectedDuration_s = 10 - self._watchingTime_s + actualTime1_s - self._watchingTime_s + actualTime2_s - self._watchingTime_s + actualTime3_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_fourStartChallengeEventsEarlierTimestampFailFailFailFailNoConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 46).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 122 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 48).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 233 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 52).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 54).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime3_s = 344 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime3_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 57).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime4_s = 455 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 58).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime4_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) expectedScore = 5 expectedDuration_s = 10 - self._watchingTime_s + actualTime1_s - self._watchingTime_s + actualTime2_s - self._watchingTime_s + actualTime3_s # ignore actualTime4_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_fourStartChallengeEventsEarlierTimestampFailFailFailSuccessNoConclude(self, mock_utcNow): e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 46).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime1_s = 1223 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 48).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime1_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 50).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime2_s = 2334 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 52).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime2_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 54).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime3_s = 3445 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 56).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.FAIL_STATUS, data = json.dumps({"candidate_answer": actualTime3_s, "fail_message": "OUTCOME_TOO_SLOW"}, separators=(',',':')) ) e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 57).replace(tzinfo=utc), type = PiEvent.START_CHALLENGE_MSG_TYPE, team = self.team1, pi = self.station ) actualTime4_s = 4556 e = PiEvent.objects.create( time = datetime(2000, 12, 31, 23, 59, 58).replace(tzinfo=utc), type = PiEvent.SUBMIT_MSG_TYPE, team = self.team1, pi = self.station, status = PiEvent.SUCCESS_STATUS, data = json.dumps({"candidate_answer": actualTime4_s, "fail_message": "OUTCOME_SUCCESS"}, separators=(',',':')) ) expectedScore = 5 expectedDuration_s = 10 - self._watchingTime_s + actualTime1_s - self._watchingTime_s + actualTime2_s - self._watchingTime_s + actualTime3_s # ignore actualTime4_s self._verify(expectedScore, expectedDuration_s) @mock.patch('scoreboard.views._utcNow', side_effect=_mocked_utcNow) def test_recomputeDockScore_onlyOneStartChallengeEventLaterTimestamp(self, mock_utcNow): pass # Don't worry about later timestamps #TODO - Remaining items... # # Scoreboard # [x] 1. absent/present Registered indicator # [x] 2. make title larger and change to "Leaderboard" # [x] 3. fill width 100% # [x] 4. make 30 teams fit on the same page with roughly 20-30 chars # [x] 5. header row multiple lines--all text doesn't show up # [x] 6. don't need to show page footer; find another place for the attribution # [ ] 7. put "Harris Design Challenge 2016" along the left-hand side # [x] 8. ranking # [x] 11. remove team logo if not implementing this time # [ ] 12. Page has two jquery <script> tags--one looks WRONG_ARGUMENTS # # # Enhancements # [ ] 9. Change color (darker) for the ones that are zero (not started) # [ ] 10. Set color brighter to stand out for the ones that are done
apache-2.0
Hamcker/PersonalExit
app.js
4622
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var stylus = require('stylus'); var nib = require('nib'); var passport = require('passport'); var HttpStrategy = require('passport-http'); var LocalStrategy = require('passport-local').Strategy; var expressSession = require('express-session'); var md5 = require('md5'); var sql = require('mssql') var flash = require('connect-flash'); var routes = require('./routes/index'); var templates = require('./routes/templates'); var publicApisRoutes = require('./routes/publicApis'); var authedApisRoutes = require('./routes/authedApis'); var app = express(); var db = require('mongoskin').db('mongodb://192.168.0.56/TestDB', { native_parser: true }) // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); //-------------------------------------------------------------------------------------------------------------- app.use(expressSession({ secret: 'mySecretKey' })); app.use(passport.initialize()); app.use(passport.session()); app.use(flash()); function compile(str, path) { return stylus(str) .set('filename', path) .use(nib()); } app.use(stylus.middleware({ src: __dirname + '/public/', compile: compile })); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use(express.static(path.join(__dirname, 'bower_components'))); var sqlconfig = { user: 'Nodejs', password: 'Nodejs', server: 'frosh', database: 'UM', } app.use(function (req, res, next) { req.db = db req.sqlconfig = sqlconfig; next(); }); passport.serializeUser(function (user, done) { done(null, user.UserId); }); passport.deserializeUser(function (id, done) { var sqlconnection = new sql.Connection(sqlconfig, function (err) { var request = new sql.Request(sqlconnection); request.query('SELECT TOP 1 * FROM dbo.Users WHERE UserId = ' + id, function (err, recordset) { if (recordset) return done(err, recordset[0]); }); }); }); passport.use('local', new LocalStrategy({ passReqToCallback: true }, function (req, username, password, done) { var sqlconnection = new sql.Connection(sqlconfig, function (err) { var request = new sql.Request(sqlconnection); request.query('SELECT TOP 1 * FROM dbo.Users WHERE UserId = ' + username, function (err, recordset) { if (recordset.length == 1) { var userRec = recordset[0]; var hashPass = md5(password); if (userRec.PasswordText.toLowerCase() == hashPass.toLowerCase()) { //success var request2 = new sql.Request(sqlconnection); request2.input('ID', sql.NVarChar(50), username) request2.execute('dbo.spTest', function (err, records) { req.session.user = recordset[0]; req.session.employee = records[0][0]; return done(null, recordset[0]); }) } else return done(null, false, req.flash('loginMessage', 'کلمه عبور صحیح نیست.')); } else return done(err, false, req.flash('loginMessage', 'کد پرسنلی صحیح نیست یا در مرکز سعیدآباد مشغول نیست.')); }); }); })); //-------------------------------------------------------------------------------------------------------------- app.use('/tmpl', templates); app.use('/papi', publicApisRoutes); app.use('/api', authedApisRoutes(passport)); app.all('/*', routes(passport)); passport.authenticate('local', function (req, res, next) { }) // catch 404 and forward to error handler app.use(function (req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function (err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
apache-2.0
shashwat7/spark-cassandra-connector
spark-cassandra-connector/src/main/scala/org/apache/spark/sql/cassandra/BasicCassandraPredicatePushDown.scala
8703
package org.apache.spark.sql.cassandra import com.datastax.driver.core.ProtocolVersion import com.datastax.driver.core.ProtocolVersion._ import com.datastax.spark.connector.cql.TableDef import com.datastax.spark.connector.types.TimeUUIDType /** * Determines which filter predicates can be pushed down to Cassandra. * * 1. Only push down no-partition key column predicates with =, >, <, >=, <= predicate * 2. Only push down primary key column predicates with = or IN predicate. * 3. If there are regular columns in the pushdown predicates, they should have * at least one EQ expression on an indexed column and no IN predicates. * 4. All partition column predicates must be included in the predicates to be pushed down, * only the last part of the partition key can be an IN predicate. For each partition column, * only one predicate is allowed. * 5. For cluster column predicates, only last predicate can be non-EQ predicate * including IN predicate, and preceding column predicates must be EQ predicates. * If there is only one cluster column predicate, the predicates could be any non-IN predicate. * 6. There is no pushdown predicates if there is any OR condition or NOT IN condition. * 7. We're not allowed to push down multiple predicates for the same column if any of them * is equality or IN predicate. * * The list of predicates to be pushed down is available in `predicatesToPushDown` property. * The list of predicates that cannot be pushed down is available in `predicatesToPreserve` property. * * @param predicates list of filter predicates available in the user query * @param table Cassandra table definition */ class BasicCassandraPredicatePushDown[Predicate : PredicateOps]( predicates: Set[Predicate], table: TableDef, pv: ProtocolVersion = ProtocolVersion.NEWEST_SUPPORTED) { val pvOrdering = implicitly[Ordering[ProtocolVersion]] import pvOrdering._ private val Predicates = implicitly[PredicateOps[Predicate]] private val partitionKeyColumns = table.partitionKey.map(_.columnName) private val clusteringColumns = table.clusteringColumns.map(_.columnName) private val regularColumns = table.regularColumns.map(_.columnName) private val allColumns = partitionKeyColumns ++ clusteringColumns ++ regularColumns private val indexedColumns = table.indexedColumns.map(_.columnName) private val singleColumnPredicates = predicates.filter(Predicates.isSingleColumnPredicate) private val eqPredicates = singleColumnPredicates.filter(Predicates.isEqualToPredicate) private val eqPredicatesByName = eqPredicates .groupBy(Predicates.columnName) .mapValues(_.take(1)) // don't push down more than one EQ predicate for the same column .withDefaultValue(Set.empty) private val inPredicates = singleColumnPredicates.filter(Predicates.isInPredicate) private val inPredicatesByName = inPredicates .groupBy(Predicates.columnName) .mapValues(_.take(1)) // don't push down more than one IN predicate for the same column .withDefaultValue(Set.empty) private val rangePredicates = singleColumnPredicates.filter(Predicates.isRangePredicate) private val rangePredicatesByName = rangePredicates .groupBy(Predicates.columnName) .withDefaultValue(Set.empty) /** Returns a first non-empty set. If not found, returns an empty set. */ private def firstNonEmptySet[T](sets: Set[T]*): Set[T] = sets.find(_.nonEmpty).getOrElse(Set.empty[T]) /** All non-equal predicates on a TimeUUID column are going to fail and fail * in silent way. The basic issue here is that when you use a comparison on * a time UUID column in C* it compares based on the Time portion of the UUID. When * Spark executes this filter (unhandled behavior) it will compare lexically, this * will lead to results being incorrectly filtered out of the set. As long as the * range predicate is handled completely by the connector the correct result * will be obtained. */ val timeUUIDNonEqual = { val timeUUIDCols = table.columns.filter(x => x.columnType == TimeUUIDType) timeUUIDCols.flatMap(col => rangePredicatesByName.get(col.columnName)).flatten } /** * Selects partition key predicates for pushdown: * 1. Partition key predicates must be equality or IN predicates. * 2. Only the last partition key column predicate can be an IN. * 3. All partition key predicates must be used or none. */ private val partitionKeyPredicatesToPushDown: Set[Predicate] = { val (eqColumns, otherColumns) = partitionKeyColumns.span(eqPredicatesByName.contains) val inColumns = otherColumns.headOption.toSeq.filter(inPredicatesByName.contains) if (eqColumns.size + inColumns.size == partitionKeyColumns.size) (eqColumns.flatMap(eqPredicatesByName) ++ inColumns.flatMap(inPredicatesByName)).toSet else Set.empty } /** * Selects clustering key predicates for pushdown: * 1. Clustering column predicates must be equality predicates, except the last one. * 2. The last predicate is allowed to be an equality or a range predicate. * 3. The last predicate is allowed to be an IN predicate only if it was preceded by * an equality predicate. * 4. Consecutive clustering columns must be used, but, contrary to partition key, * the tail can be skipped. */ private val clusteringColumnPredicatesToPushDown: Set[Predicate] = { val (eqColumns, otherColumns) = clusteringColumns.span(eqPredicatesByName.contains) val eqPredicates = eqColumns.flatMap(eqPredicatesByName).toSet val optionalNonEqPredicate = for { c <- otherColumns.headOption.toSeq p <- firstNonEmptySet( rangePredicatesByName(c), inPredicatesByName(c).filter(_ => c == clusteringColumns.last)) } yield p eqPredicates ++ optionalNonEqPredicate } /** * Selects indexed and regular column predicates for pushdown: * 1. At least one indexed column must be present in an equality predicate to be pushed down. * 2. Regular column predicates can be either equality or range predicates. * 3. If multiple predicates use the same column, equality predicates are preferred over range * predicates. */ private val indexedColumnPredicatesToPushDown: Set[Predicate] = { val inPredicateInPrimaryKey = partitionKeyPredicatesToPushDown.exists(Predicates.isInPredicate) val eqIndexedColumns = indexedColumns.filter(eqPredicatesByName.contains) //No Partition Key Equals Predicates In PV < 4 val eqIndexedPredicates = eqIndexedColumns .filter{ c => pv >= V4 || !partitionKeyColumns.contains(c)} .flatMap(eqPredicatesByName) // Don't include partition predicates in nonIndexedPredicates if partition predicates can't // be pushed down because we use token range query which already has partition columns in the // where clause and it can't have other partial partition columns in where clause any more. val nonIndexedPredicates = for { c <- allColumns if partitionKeyPredicatesToPushDown.nonEmpty && !eqIndexedColumns.contains(c) || partitionKeyPredicatesToPushDown.isEmpty && !eqIndexedColumns.contains(c) && !partitionKeyColumns.contains(c) p <- firstNonEmptySet(eqPredicatesByName(c), rangePredicatesByName(c)) } yield p if (!inPredicateInPrimaryKey && eqIndexedColumns.nonEmpty) (eqIndexedPredicates ++ nonIndexedPredicates).toSet else Set.empty } /** Returns the set of predicates that can be safely pushed down to Cassandra */ val predicatesToPushDown: Set[Predicate] = partitionKeyPredicatesToPushDown ++ clusteringColumnPredicatesToPushDown ++ indexedColumnPredicatesToPushDown /** Returns the set of predicates that cannot be pushed down to Cassandra, * so they must be applied by Spark */ val predicatesToPreserve: Set[Predicate] = predicates -- predicatesToPushDown val unhandledTimeUUIDNonEqual = { timeUUIDNonEqual.toSet -- predicatesToPushDown } require(unhandledTimeUUIDNonEqual.isEmpty, s""" | You are attempting to do a non-equality comparison on a TimeUUID column in Spark. | Spark can only compare TimeUUIDs Lexically which means that the comparison will be | different than the comparison done in C* which is done based on the Time Portion of | TimeUUID. This will in almost all cases lead to incorrect results. If possible restrict | doing a TimeUUID comparison only to columns which can be pushed down to Cassandra. | https://datastax-oss.atlassian.net/browse/SPARKC-405. | | $unhandledTimeUUIDNonEqual """.stripMargin) }
apache-2.0
kuri65536/sl4a
android/Utils/src/com/googlecode/android_scripting/future/FutureResult.java
1701
/* * Copyright (C) 2016 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.googlecode.android_scripting.future; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** * FutureResult represents an eventual execution result for asynchronous operations. * * @author Damon Kohler ([email protected]) */ public class FutureResult<T> implements Future<T> { private final CountDownLatch mLatch = new CountDownLatch(1); private volatile T mResult = null; public void set(T result) { mResult = result; mLatch.countDown(); } @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public T get() throws InterruptedException { mLatch.await(); return mResult; } @Override public T get(long timeout, TimeUnit unit) throws InterruptedException { mLatch.await(timeout, unit); return mResult; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return mResult != null; } }
apache-2.0
eikek/sitebag
README.md
18025
# Sitebag Sitebag is a "read-it-later" REST server; a self-hostable web application to store web pages. It saves the complete page (including images) and the extracted main content. You can then read the saved pages with a browser or rss reader for example. Sitebag is compatible to [wallabag](https://github.com/wallabag/wallabag), meaning that it responds to its url endpoints. This way you can use their nice android and iOS clients as well as their browser extension with sitebag. There is a basic web ui provided, too. There is a demo installation at [heroku](http://heroku.com) so you can try it out easily. Goto <http://sitebag.herokuapp.com/ui> and login with either `demo`, `demo1` or `demo2` (use the username as password). ## Dependencies Sitebag is an [akka](http://akka.io) application. Other dependencies are: * [jsoup](https://github.com/jhy/jsoup/) is used for html content extraction * [spray](http://spray.io) provides the http stack * [reactivemongo](http://reactivemongo.org/) connects the app to a mongo database and * [porter](https://github.com/eikek/porter) provides authentication and user management * full text search is done via [lucene](http://lucene.apache.org/) The ui templates are processed by [twirl](https://github.com/spray/twirl) and [bootstrap](http://getbootstrap.com) is used to provide a responsive site. You can choose from free [bootswatch](http://bootswatch.com/) themes. Additionally, [mustache](https://github.com/janl/mustache.js) and [spinjs](http://fgnass.github.io/spin.js/) are at work. ## Building The build tool [sbt](http://scala-sbt.org) can compile the sources and create deployable artifacts: sbt dist will create a zip file, ready to start. ## Installation #### 1. Install MongoDB and JRE SiteBag needs a running MongoDB and Java 1.7. #### 2. [Download](https://eknet.org/main/projects/sitebag/download.html) sitebag zip file Unpack the zip file somewhere. You can have a look at the configuration file `etc/sitebag.conf`. If you have mongodb running on some other port, you'll need to update this file. #### 3. Starting up For linux, simply execute the script `bin/start.sh`. There is no windows `.bat` version yet. You can pass the option `-Dsitebag.create-admin-account=true` to have sitebag create an admin account (you must change the `bin/start.sh` script). This is useful when starting with an empty database. Sitebag creates an account with username "admin" and password "admin". This allows you to skip the next step "Add user account". #### 4. Add user account This is not needed, if you enable the option `-Dsitebag.create-admin-account=true` in `bin/start.sh`. You'll need to setup an account with sitebag. The very first account cannot be setup via the web interface. Please use the following steps to add a admin user, with all permissions. In a terminal type: $ telnet localhost 9996 Connected to localhost. Escape character is '^]'. Welcome to porter 0.2.0 Type 'help' for a list of available commands. porter> update realm Enter the realm properties. realm id: default realm name: Realm updated: Realm(Ident(default),) porter> use realm default Using realm default: (default) porter> update group Enter group details. name: admin rules: sitebag:* props: Group updated. (default) porter> update account Enter the account details. name: admin groups: admin password: admin props: Account updated: true (default) porter> Good bye. Connection closed by foreign host. Now you can login with username "admin" and password "admin" at <http://localhost:9995/ui/conf>. Of course, you can choose different name and password. The rule `sitebag:*` means that this user has all sitebag related permissions. You can then create new -- non-admin -- accounts via the web interface. Non-admin accounts have only permissions to access their own data. If the admin account should also be a standard sitebag account (not only for creating new users), then you need to create a token for it which can be done on the web interface mentioned above. ## Usage The web interface can be found at `http://localhost:9995/ui`. The REST api is `http://localhost:9995/api/...` and can be queried with a `www-form-urlencoded` parameter list or a corresponding json object. Sitebag authenticates requests either with form- or json values `account` and `password` or a cookie. There is another password involved: the special `token` can be used to query entries (using special urls), everything else is protected with the main password. For `PUT` and `DELETE` requests, there is an fallback to `POST` requests with some action parameter (for example `POST /entry?id=abc123&delete`). All JSON responses will always return an object like: { sucess: true|false, message: "error or success message", value: ... } If the request was for side-effects only, `value` is omitted. The very first account must be created using porter's api or console. Once an account exists, create a token to enable the feed urls. In short, here are the relevant url endpoints: /api/<account>/login /api/<account>/logout /api/<account> (PUT ?newaccount=&newpassword=) /api/<account>/newtoken /api/<account>/changepassword?newpassword= /api/<account>/reextract /api/<account>/entry /api/<account>/entry/<id> (GET|DELETE|POST?delete=true) /api/<account>/entry/<id>/togglearchived /api/<account>/entry/<id>/setarchived ?flag=true|false /api/<account>/entry/<id>/tag ?tag=&tag=|tags=a,b,c /api/<account>/entry/<id>/untag ?tag=&tag=|tags=a,b,c /api/<account>/entry/<id>/tags ?tag=&tag=|tags=a,b,c /api/<account>/tags ?filter=pro.*ing /api/<account>/entries/rss ?tag=&tag=&tags=a,b,c&archived&q="" (lucene) /api/<account>/entries/json -"- /bin/<id> (GET) binary files /bin?url= get binary files More details to each one can be found below. #### login and logout The `login` endpoint is provided to retrieve a cookie that can be used for subsequent requests. The `logout` endpoint returns a `Set-Cookie` header that instructs clients to delete the cookie. #### create a new user account Creates a new user account. PUT /<account> { newpassword: "" } -> JSON { success: true, message: "" } You must have the permission `sitebag:createuser` to be able to create new accounts. Sitebag users must have a set of permissions that are checked on each access. For example, to retrieve a page entry the permission `sitebag:<user>:get:entry:<id>` is checked. You can easily grant a user "john" all permissions for his own things, by adding `sitebag:john:*` to his permission set. This is done automatically when creating new accounts via this api. #### create a new token Creates a secondary password that must be supplied with all non-admin urls. POST /<account>/newtoken -> JSON { token: "random" } #### change main password POST /<account>/changepassword?newpassword= POST /<account>/chanegpassword { newpassword: "" } -> JSON { success: true, message: "password changed" } #### delete user account This will remove the account and all its data. DELETE /<account> POST /<account>?delete=true -> JSON { success: true, message: "" } If porter is embedded, the account is removed from the database. If authentication is done on a remote instance, all sitebag permissions are removed from the group. If you remove an account using porter's console, the data related to this account is still there. You can manually drop the collection with mongodb client. #### add new site PUT|POST /<account>/entry { url: "", title: "", tags: [] } -> JSON{ id: "", title: "", url: "", content: "", read: false, tags:[] } This will add the contents of the site at the given url to sitebag. The `title` parameter is optional and will override the automatic detection. The optional `tags` list can carry tags that are associated with the new entry. #### re-extract content from entries Sitebag tries to extract the "main content". The algorithm how to extract this may change in the future and already stored entries could then be extracted anew to benefit from this. Since Sitebag stores the original document, they can be simply "re-extracted". POST /<account>/reextract { entryId: ... } The `entryId` parameter is optional. If specified, only content from this entry is extracted. If not specified a job starts that goes through all entries of the given account and extracts the content from each anew. This might take a while and the progress can be queried with: GET /<account>/reextract?status This returns a json object like this { account: <account>, running: true|false, ... } If `running` is `true`, then the object has more properties that describe the current progress: | property | description | |-----------+--------------------------------------------| | done | number of entries that have been extracted | | total | total number of entries to extract | | progress | done / total * 100 | | startedAt | the timestamp when extraction started | | since | startedAd as ISO date-time string | #### delete site Deletes the page entry with the given id. DELETE /<account>/entry/<id> POST /<account>/entry/<id> {delete:true} -> { success: true, message: "Deleted successfully." } #### toggle archived Toggles the archived flag on a page entry. POST /<account>/entry/<id>/[toggle|set]archived[?flag=true|false] POST /<account>/entry/<id>[toggle|set]archived { id: "", flag: } -> { value: true|false } Instead of `toggle` you can use `set` and specify the flag. The response contains the new archived value. #### retrieve a site entry Fetch a page entry from sitebag by its id. GET /<account>/entry/<id> > JSON{ hash, title, url, content, shortText, archived, created, tags: [] } You can also get the cached original content with GET /<account>/entry/<id>/cache This returns the complete original document that was fetched at the time this entry was created. If you just like to get the meta data (everything but `content`), then use: GET /<account>/entry/<id>?complete=false #### tag / untag a site entry Adds or removes a tag from a page entry. POST /<account>/entry/<id>/[un]tag/?tag=a&tag=b&tag=c&tags=x,y,z&account=&password= POST /<account>/entry/<id>/[un]tag/ { tags: "..." } -> JSON { success: true, message: "tags added/removed" } You can specify multiple `tag` parameters or one `tags` parameter with a comma separated list of tag names. Tag names must consist of alphanumeric characters and `-` and `_`. The actions will either add or remove the specified tags. If you want to do a update of a complete list use the `tags` endpoint: POST /<account>/entry/<id>/tags?tag=a&tag=b&tags=c,d,e This will remove all existing tags for entry `id` and then add the given list. #### get entries Get a list of page entries as RSS feed or as JSON. GET /<account>/entries/rss|json?<params> -> xml rss or json. a list of entries Parameters: | Parameter | Meaning | |-----------+-----------------------------------------------------| | q | a query string for fulltext search. default is the | | | empty string (see below for more details). | | | | | tags, tag | provide a set of tags. only entries that are tagged | | | with all of them are returned. you can specify a | | | combination of a comma-separataed list of tag names | | | with `tags=a,b,c` and multiple`tag=` values. if not | | | specified, tags are not checked. | | | | | archived | a boolean value. if `true` return archived entries | | | only. If `false` return only entries that are not | | | archived. if not specified, all (archived and not | | | archived) entries are returned. | | | | | size | the page size. A number that controls how many | | | entries to return for eacht request. | | | default is 24, but this may change. it is | | | recommended to always specify it. | | | | | num | the page number. A positive number specifying the | | | page index to return. Defaults to 1. | | | | | complete | a boolean value to control whether to return full | | | entries or only meta data. meta data is everything | | | but not the full page content. default is `false`. | By default each entry is returned without its content. Only title, short-text and other properties are transferred, because this is usually enough for a listing. If the entries should be complete, specify this with the parameter `complete=true`. There is one known tag called "favourite" that returns all "starred" entries. The query value for the `q` parameter is a [lucene query](http://www.lucenetutorial.com/lucene-query-syntax.html). By default, the title and content of a page entry is searched, but the query can be customized to search other fields, too. The index has the following fields: * `_id` the entry id * `title` the title of an entry * `content` the full main content of the page and the title, this is used if not specified otherwise * `archived` the archived flag * `tag` a tag name associated to the entry (possible many of them) * `created` the created timestamp in milliseconds * `date` the create date of form `yyyymmdd`, like `20140523` * `url` the complete url of the original site * `host` the host part of the url If the query string contains fields (like `archived` or `tag` fields) that are also provided by the search form, the query has precedence. So to find all sites with _icecream_ that are archived and were downloaded from _myrecipes.org_, the query string could be archived:true host:*.myrecipes.org icecream If you want to search for multiple tags, you need to specify it multiple times, like `tag:favourite tag:clojure archived:true`. The index is created if it does not exist. Thus, to re-create it, simply remove the directory which is at `var/luceneVV`. #### list all tags Returns a list of used tags. list tag names: GET /<account>/tags?filter= -> JSON { tags: [], cloud: { "tagname": usage-count } } The `filter` parameter is a regex string like `fav.*rite`. The returned `value` is a json object that contains a `tags` array with all tag names and a `cloud` object that is a mapping from a tagname to its usage count (how many entries have this tag). To get the tags of one entry, retrieve the meta data it (see "retrieve a site entry"). #### Binary files Binary files are also stored in sitebag. Currently only images are supported. You can get them using this url /bin/<id> (GET) binary files /bin?url=http://original-image-url Note that access to these are *not* protected. The `<id>` is the binary id, which is the md5 checksum of the content. ## Configuration and more Detail ### Mongo DB All data is pushed to a mongo database. Mongodb must be installed and running. The data is organized as follows: <account>_entries _id (= md5 hash of url), title, url, content, read, created, content-id, binary-ids <account>_tags _id (= tag name), entries: [ hash1, hash2, ... ] binaries _id (= hash of content), urls, data, md5, contentType, created Here `<account>` is replaced by the actual account name. The `created` field is a timestamp denoting the creation of this record. The collection `<account>_entries` stores all pages that the user adds. The `content` field is the extracted main content. The original page is stored in the `binaries` collection, that can be refered to using the `content-id` field. The `binary-ids` array contains all ids into the binary collection that this entry uses. The collection `<account>_tags` contains all tags of an account. A page is "tagged" by adding the entry `_id` to the `entries` array of the corresponding tag. Thus, to look up all tags of an entry this collection must be iterated through, checking the `entries` array for containment of a given page id. Images (and other binary content) is stored in a collection global to all accounts. The id of a binary is the md5 checksum of its content. The url is also stored for further reference. Binary resources are available without authentication. The `binaries` collection as written above is only for documenting the meta fields. Mongo provides [GridFS](http://docs.mongodb.org/manual/faq/developers/#faq-developers-when-to-use-gridfs) for this already. ### sitebag.conf The file `etc/sitebag.conf` contains all configuration settings. It first includes all default values which can be overriden. ### Authentication Authentication is provided by porter. There are two options: You already have a porter instance running and want sitebag to connect to it; or you can use an embedded porter instance that is running within sitebag. With the latter option, sitebag manages its own set of user accounts. ## Issues and Feedback Please use the issue tracker for all sorts of things concerning sitebag. Feedback is always most welcome. ## License SiteBag is licensed under [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0.html).
apache-2.0
datalint/open
Open/src/main/java/com/datalint/open/server/io/LineReader.java
669
package com.datalint.open.server.io; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import com.datalint.open.shared.general.ILineReader; public class LineReader implements ILineReader { private final BufferedReader reader; public LineReader(Reader reader) { this.reader = new BufferedReader(reader); } public LineReader(InputStream inputStream) { this(new InputStreamReader(inputStream)); } @Override public String readLine() throws IOException { return reader.readLine(); } @Override public void close() throws IOException { reader.close(); } }
apache-2.0
slimkit/thinksns-plus
app/Http/Controllers/APIs/V2/PingPlusPlusChargeWebHooks.php
3568
<?php declare(strict_types=1); /* * +----------------------------------------------------------------------+ * | ThinkSNS Plus | * +----------------------------------------------------------------------+ * | Copyright (c) 2016-Present ZhiYiChuangXiang Technology Co., Ltd. | * +----------------------------------------------------------------------+ * | This source file is subject to enterprise private license, that is | * | bundled with this package in the file LICENSE, and is available | * | through the world-wide-web at the following url: | * | https://github.com/slimkit/plus/blob/master/LICENSE | * +----------------------------------------------------------------------+ * | Author: Slim Kit Group <[email protected]> | * | Homepage: www.thinksns.com | * +----------------------------------------------------------------------+ */ namespace Zhiyi\Plus\Http\Controllers\APIs\V2; use Illuminate\Http\Request; use Illuminate\Support\Arr; use Zhiyi\Plus\Models\WalletCharge as WalletChargeModel; use Zhiyi\Plus\Services\Wallet\Charge as ChargeService; use function Zhiyi\Plus\setting; class PingPlusPlusChargeWebHooks { public function webhook(Request $request, ChargeService $chargeService) { if ($request->json('type') !== 'charge.succeeded') { return response('不是支持的事件', 422); } $settings = setting('wallet', 'ping++', []); $signature = $request->headers->get('x-pingplusplus-signature'); $pingPlusPlusPublicCertificate = $settings['public_key'] ?? null; $signed = openssl_verify($request->getContent(), base64_decode($signature), $pingPlusPlusPublicCertificate, OPENSSL_ALGO_SHA256); if (! $signed) { return response('加密验证失败', 422); } $pingPlusPlusCharge = $request->json('data.object'); $charge = WalletChargeModel::find($chargeService->unformatChargeId($pingPlusPlusCharge['order_no'])); if (! $charge) { return response('凭据不存在', 404); } elseif ($charge->status === 1) { return response('订单已提前完成'); } $user = $charge->user; $charge->status = 1; $charge->transaction_no = $pingPlusPlusCharge['transaction_no']; $charge->account = $this->resolveChargeAccount($pingPlusPlusCharge, $charge->account); $user->getConnection()->transaction(function () use ($user, $charge) { $user->wallet()->increment('balance', $charge->amount); $charge->save(); }); return response('通知成功'); } /** * 解决付款订单来源. * * @param array $charge * @param string|null $default * @return string|null * @author Seven Du <[email protected]> */ protected function resolveChargeAccount($charge, $default = null) { $channel = Arr::get($charge, 'channel'); // 支付宝渠道 if (in_array($channel, ['alipay', 'alipay_wap', 'alipay_pc_direct', 'alipay_qr'])) { return Arr::get($charge, 'extra.buyer_account', $default); // 支付宝付款账号 // 微信渠道 } elseif (in_array($channel, ['wx', 'wx_pub', 'wx_pub_qr', 'wx_wap', 'wx_lite'])) { return Arr::get($charge, 'extra.open_id', $default); // 用户唯一 open_id } return $default; } }
apache-2.0
vicamo/docker_yocto
trusty/Dockerfile
588
FROM buildpack-deps:trusty MAINTAINER [email protected] RUN apt-get update -qq \ && apt-get install --no-install-recommends -y \ ccache \ chrpath \ cpio \ diffstat \ gawk \ iptables \ locales \ python3 \ $(which realpath >/dev/null 2>&1 || echo realpath) \ sudo \ texinfo \ && apt-get clean \ && rm -f /var/lib/apt/lists/*_dists_* RUN (echo "en_US.UTF-8 UTF-8"; \ echo "en_US ISO-8859-1"; \ echo "en_US.ISO-8859-15 ISO-8859-15") >/var/lib/locales/supported.d/bitbake.conf \ && locale-gen \ && update-locale LANG=en_US.UTF-8 LANGUAGE ENV LANG=en_US.UTF-8
apache-2.0
IsaacR2/FerramentaX
login.php
957
<!DOCTYPE html> <html> <head> <title>Ferramenta X</title> </head> <body> <?php require("template.php"); ?> <div class="container" align="center"> <h2>Login</h2> <p>Realize o login para acessar a plataforma NERD POWER</p><br> <form name="form1" action="proc/proc_login.php" method="POST" id="IdForm1"> <div class="col-md-4 col-md-offset-4"> <label for="usr">E-mail:</label> <input type="text" class="form-control" id="IdEmail" name="NEmail" required placeholder="Digite seu email..." /> </div> <br><br><br><br> <div class="col-md-4 col-md-offset-4"> <label for="pwd">Senha:</label> <input type="password" class="form-control" id="IdSenha" name="NSenha" required placeholder="Sua senha..." /> </div> <br><br><br><br> <div class="col-md-4 col-md-offset-4"> <button type="submit" class="btn btn-primary" name="Enviar">Login</button> </div> </form> </div> <br /> </body> </html>
apache-2.0
mdoering/backbone
life/Fungi/Ascomycota/Dothideomycetes/Microthyriales/Microthyriaceae/Trichothyriomyces/README.md
290
# Trichothyriomyces Bat. & H. Maia GENUS #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in in Batista, Maia, Silva & Vital, Anais Soc. Biol. Pernambuco 13(2): 104 (1955) #### Original name Trichothyriomyces Bat. & H. Maia ### Remarks null
apache-2.0
mdoering/backbone
life/incertae sedis/Trochiliascia/README.md
211
# Trochiliascia Deák, 1964 GENUS #### Status ACCEPTED #### According to Interim Register of Marine and Nonmarine Genera #### Published in Földt. Kozl. 94 (1): 104. #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Cucurbitales/Begoniaceae/Begonia/Begonia maurandiae/README.md
213
# Begonia maurandiae A.DC. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in Ann. Sci. Nat. , Bot. sér. 4, 11:119. 1859 #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Fagales/Fagaceae/Quercus/Quercus byarsii/README.md
188
# Quercus byarsii Sudw. ex Trel. SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Serapias/Serapias vomeracea/ Syn. Serapias vomeracea platyglottis/README.md
188
# Serapias vomeracea f. platyglottis FORM #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Plumbaginaceae/Limonium/Limonium ramosissimum/Limonium ramosissimum confusum/README.md
216
# Limonium ramosissimum subsp. confusum (Gren. & Godron) Pignatti SUBSPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Fungi/Basidiomycota/Agaricomycetes/Hymenochaetales/Hymenochaetaceae/Coltricia/Polystictus bresadolanus/README.md
236
# Polystictus bresadolanus Speg. SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in Boln Acad. nac. Cienc. Córdoba 23(3/4): 420 (1919) #### Original name Polystictus bresadolanus Speg. ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Dioscoreales/Burmanniaceae/Dictyostega/Dictyostega orobanchoides/Dictyostega orobanchoides orobanchoides/README.md
207
# Dictyostega orobanchoides subsp. orobanchoides SUBSPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Ebenaceae/Royena/Royena opaca/README.md
169
# Royena opaca E.Mey. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Hieracium/Hieracium transiens/ Syn. Hieracium erythrocarpum ceahlavicum/README.md
207
# Hieracium erythrocarpum subsp. ceahlavicum Zahn SUBSPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Santalales/Loranthaceae/Loranthus/Loranthus korthalsii/README.md
179
# Loranthus korthalsii Molkenb. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
apache-2.0
dfensgmbh/biz.dfch.PS.Appclusive.Scriplets
README.md
144
# biz.dfch.PS.Appclusive.Scriplets A collection of script pieces to perform various tasks on the Appclusive Application and Middleware platform
apache-2.0
google/exposure-notifications-verification-server
pkg/controller/issueapi/send_sms.go
5453
// Copyright 2020 the Exposure Notifications Verification Server authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package issueapi import ( "context" "crypto" "fmt" "net/http" "strings" "time" "github.com/google/exposure-notifications-server/pkg/logging" enobs "github.com/google/exposure-notifications-server/pkg/observability" "github.com/google/exposure-notifications-verification-server/pkg/api" "github.com/google/exposure-notifications-verification-server/pkg/database" "github.com/google/exposure-notifications-verification-server/pkg/signatures" "github.com/google/exposure-notifications-verification-server/pkg/sms" ) // scrubbers is a list of known Twilio error messages that contain the send to phone number. var scrubbers = []struct { prefix string suffix string }{ { prefix: "phone number: ", suffix: ", ", }, { prefix: "'To' number ", suffix: " is not", }, } // ScrubPhoneNumbers checks for phone numbers in known Twilio error strings that contains // user phone numbers. func ScrubPhoneNumbers(s string) string { noScrubs := s for _, scrub := range scrubbers { pi := strings.Index(noScrubs, scrub.prefix) si := strings.Index(noScrubs, scrub.suffix) // if prefix is in the string and suffix is in the sting after the prefix if pi >= 0 && si > pi+len(scrub.prefix) { noScrubs = strings.Join([]string{ noScrubs[0 : pi+len(scrub.prefix)], noScrubs[si:], }, "REDACTED") } } return noScrubs } // SendSMS sends the sms mesage with the given provider and wraps any seen errors into the IssueResult func (c *Controller) SendSMS(ctx context.Context, realm *database.Realm, smsProvider sms.Provider, signer crypto.Signer, keyID string, request *api.IssueCodeRequest, result *IssueResult) { if request.Phone == "" { return } if err := c.doSend(ctx, realm, smsProvider, signer, keyID, request, result); err != nil { result.HTTPCode = http.StatusBadRequest if sms.IsSMSQueueFull(err) { result.ErrorReturn = api.Errorf("failed to send sms: queue is full: %s", err).WithCode(api.ErrSMSQueueFull) } else { result.ErrorReturn = api.Errorf("failed to send sms: %s", err).WithCode(api.ErrSMSFailure) } } } // BuildSMS builds and signs (if configured) the SMS message. It returns the // complete and compiled message. func (c *Controller) BuildSMS(ctx context.Context, realm *database.Realm, signer crypto.Signer, keyID string, request *api.IssueCodeRequest, vercode *database.VerificationCode) (string, error) { now := time.Now() logger := logging.FromContext(ctx).Named("issueapi.BuildSMS") redirectDomain := c.config.IssueConfig().ENExpressRedirectDomain message, err := realm.BuildSMSText(vercode.Code, vercode.LongCode, redirectDomain, request.SMSTemplateLabel) if err != nil { logger.Errorw("failed to build sms text for realm", "template", request.SMSTemplateLabel, "error", err) return "", fmt.Errorf("failed to build sms message: %w", err) } // A signer will only be provided if the realm has configured and enabled // SMS signing. if signer == nil { return message, nil } purpose := signatures.SMSPurposeENReport if request.TestType == api.TestTypeUserReport { purpose = signatures.SMSPurposeUserReport } message, err = signatures.SignSMS(signer, keyID, now, purpose, request.Phone, message) if err != nil { logger.Errorw("failed to sign sms", "error", err) if c.config.GetAuthenticatedSMSFailClosed() { return "", fmt.Errorf("failed to sign sms: %w", err) } } return message, nil } func (c *Controller) doSend(ctx context.Context, realm *database.Realm, smsProvider sms.Provider, signer crypto.Signer, keyID string, request *api.IssueCodeRequest, result *IssueResult) error { defer enobs.RecordLatency(ctx, time.Now(), mSMSLatencyMs, &result.obsResult) logger := logging.FromContext(ctx).Named("issueapi.sendSMS") // Build the message message, err := c.BuildSMS(ctx, realm, signer, keyID, request, result.VerCode) if err != nil { logger.Errorw("failed to build sms", "error", err) result.obsResult = enobs.ResultError("FAILED_TO_BUILD_SMS") return err } // Send the message if err := smsProvider.SendSMS(ctx, request.Phone, message); err != nil { // Delete the user report record. if result.VerCode.UserReportID != nil { // No audit record since this is a recall of an action that can't happen inside the transaction. if err := c.db.DeleteUserReport(request.Phone, database.NullActor); err != nil { logger.Errorw("failed to delete the user report record", "error", err) } } // Delete the verification code. if err := realm.DeleteVerificationCode(c.db, result.VerCode.ID); err != nil { logger.Errorw("failed to delete verification code", "error", err) // fallthrough to the error } logger.Infow("failed to send sms", "error", ScrubPhoneNumbers(err.Error())) result.obsResult = enobs.ResultError("FAILED_TO_SEND_SMS") return err } return nil }
apache-2.0
ir2pid/MarvelCharacterLibrary
doc/index-files/index-19.html
6159
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_79) on Sat Mar 19 15:13:07 IST 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>U-Index</title> <meta name="date" content="2016-03-19"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="U-Index"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-18.html">Prev Letter</a></li> <li><a href="index-20.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-filesindex-19.html" target="_top">Frames</a></li> <li><a href="index-19.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="contentContainer"><a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">K</a>&nbsp;<a href="index-11.html">L</a>&nbsp;<a href="index-12.html">M</a>&nbsp;<a href="index-13.html">N</a>&nbsp;<a href="index-14.html">O</a>&nbsp;<a href="index-15.html">P</a>&nbsp;<a href="index-16.html">R</a>&nbsp;<a href="index-17.html">S</a>&nbsp;<a href="index-18.html">T</a>&nbsp;<a href="index-19.html">U</a>&nbsp;<a href="index-20.html">V</a>&nbsp;<a href="index-21.html">W</a>&nbsp;<a href="index-22.html">Y</a>&nbsp;<a href="index-23.html">Z</a>&nbsp;<a name="_U_"> <!-- --> </a> <h2 class="title">U</h2> <dl> <dt><a href="../noisyninja/com/marvelcharacterlibrary/models/Url.html" title="class in noisyninja.com.marvelcharacterlibrary.models"><span class="strong">Url</span></a> - Class in <a href="../noisyninja/com/marvelcharacterlibrary/models/package-summary.html">noisyninja.com.marvelcharacterlibrary.models</a></dt> <dd> <div class="block">Created by ir2pid on 12/03/16.</div> </dd> <dt><span class="strong"><a href="../noisyninja/com/marvelcharacterlibrary/models/Url.html#Url()">Url()</a></span> - Constructor for class noisyninja.com.marvelcharacterlibrary.models.<a href="../noisyninja/com/marvelcharacterlibrary/models/Url.html" title="class in noisyninja.com.marvelcharacterlibrary.models">Url</a></dt> <dd>&nbsp;</dd> <dt><span class="strong"><a href="../noisyninja/com/marvelcharacterlibrary/NoisyConstants.html#URL_KEY">URL_KEY</a></span> - Static variable in class noisyninja.com.marvelcharacterlibrary.<a href="../noisyninja/com/marvelcharacterlibrary/NoisyConstants.html" title="class in noisyninja.com.marvelcharacterlibrary">NoisyConstants</a></dt> <dd>&nbsp;</dd> </dl> <a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">H</a>&nbsp;<a href="index-9.html">I</a>&nbsp;<a href="index-10.html">K</a>&nbsp;<a href="index-11.html">L</a>&nbsp;<a href="index-12.html">M</a>&nbsp;<a href="index-13.html">N</a>&nbsp;<a href="index-14.html">O</a>&nbsp;<a href="index-15.html">P</a>&nbsp;<a href="index-16.html">R</a>&nbsp;<a href="index-17.html">S</a>&nbsp;<a href="index-18.html">T</a>&nbsp;<a href="index-19.html">U</a>&nbsp;<a href="index-20.html">V</a>&nbsp;<a href="index-21.html">W</a>&nbsp;<a href="index-22.html">Y</a>&nbsp;<a href="index-23.html">Z</a>&nbsp;</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li><a href="../overview-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-18.html">Prev Letter</a></li> <li><a href="index-20.html">Next Letter</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-filesindex-19.html" target="_top">Frames</a></li> <li><a href="index-19.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
apache-2.0
swapnil96/Website
temp.html
1111
<!Doctype html> <html class="no-js" lang="en" style="min-height: 100%;"> <head> <title>Swapnil Das-temp</title> <link rel="stylesheet" href="Bootstrap/css/bootstrap.css" /> </head> <body> <script src="Bootstrap/js/bootstrap.js"></script> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="http://www.bootply.com" target="ext">About</a></li> <li><a href="#contact">Contact</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li class="divider"></li> <li><a href="#">Separated link</a></li> <li><a href="#">One more separated link</a></li> </ul> </li> </ul> </div> </body> </html>
apache-2.0
SuicidePreventionSquad/SeniorProject
resources/sap/m/InputListItem-dbg.js
1780
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides control sap.m.InputListItem. sap.ui.define(['jquery.sap.global', './ListItemBase', './library'], function(jQuery, ListItemBase, library) { "use strict"; /** * Constructor for a new InputListItem. * * @param {string} [sId] id for the new control, generated automatically if no id is given * @param {object} [mSettings] initial settings for the new control * * @class * List item should be used for a label and an input field. * @extends sap.m.ListItemBase * * @author SAP SE * @version 1.38.7 * * @constructor * @public * @alias sap.m.InputListItem * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var InputListItem = ListItemBase.extend("sap.m.InputListItem", /** @lends sap.m.InputListItem.prototype */ { metadata : { library : "sap.m", properties : { /** * Label of the list item */ label : {type : "string", group : "Misc", defaultValue : null}, /** * This property specifies the label text directionality with enumerated options. By default, the label inherits text direction from the DOM. * @since 1.30.0 */ labelTextDirection : {type : "sap.ui.core.TextDirection", group : "Appearance", defaultValue : sap.ui.core.TextDirection.Inherit} }, defaultAggregation : "content", aggregations : { /** * Content controls can be added */ content : {type : "sap.ui.core.Control", multiple : true, singularName : "content", bindable : "bindable"} }, designtime : true }}); return InputListItem; }, /* bExport= */ true);
apache-2.0
yangyining/JFinal-plus
src/main/java/com/janeluo/jfinalplus/package-info.java
80
/** * Created by Janeluo on 2016/8/13 0013. */ package com.janeluo.jfinalplus;
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Alismatales/Tofieldiaceae/Tofieldia/Tofieldia cernua/ Syn. Asphodeliris cernua/README.md
189
# Asphodeliris cernua (Sm.) Kuntze SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
likyateknoloji/TlosSWGroup
TlosSW_V1.0/src/com/likya/tlossw/utils/CpcUtils.java
12211
package com.likya.tlossw.utils; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import org.apache.commons.collections.iterators.ArrayIterator; import org.apache.log4j.Logger; import com.likya.tlos.model.xmlbeans.data.JobListDocument.JobList; import com.likya.tlos.model.xmlbeans.data.JobPropertiesDocument.JobProperties; import com.likya.tlos.model.xmlbeans.data.ScenarioDocument.Scenario; import com.likya.tlos.model.xmlbeans.data.TlosProcessDataDocument.TlosProcessData; import com.likya.tlos.model.xmlbeans.state.LiveStateInfoDocument.LiveStateInfo; import com.likya.tlos.model.xmlbeans.state.StateNameDocument.StateName; import com.likya.tlos.model.xmlbeans.state.StatusNameDocument.StatusName; import com.likya.tlos.model.xmlbeans.state.SubstateNameDocument.SubstateName; import com.likya.tlossw.TlosSpaceWide; import com.likya.tlossw.core.cpc.CpcBase; import com.likya.tlossw.core.cpc.model.SpcInfoType; import com.likya.tlossw.core.spc.Spc; import com.likya.tlossw.core.spc.helpers.JobQueueOperations; import com.likya.tlossw.core.spc.model.JobRuntimeProperties; import com.likya.tlossw.exceptions.TlosFatalException; import com.likya.tlossw.model.SpcLookupTable; import com.likya.tlossw.model.engine.EngineeConstants; import com.likya.tlossw.model.path.BasePathType; import com.likya.tlossw.model.path.TlosSWPathType; import com.likya.tlossw.utils.validation.XMLValidations; public class CpcUtils { public static Scenario getScenario(TlosProcessData tlosProcessData) { Scenario scenario = Scenario.Factory.newInstance(); scenario.setJobList(tlosProcessData.getJobList()); scenario.setScenarioArray(tlosProcessData.getScenarioArray()); scenario.setBaseScenarioInfos(tlosProcessData.getBaseScenarioInfos()); scenario.setDependencyList(tlosProcessData.getDependencyList()); scenario.setScenarioStatusList(tlosProcessData.getScenarioStatusList()); scenario.setAlarmPreference(tlosProcessData.getAlarmPreference()); scenario.setManagement(tlosProcessData.getManagement()); scenario.setAdvancedScenarioInfos(tlosProcessData.getAdvancedScenarioInfos()); scenario.setLocalParameters(tlosProcessData.getLocalParameters()); return scenario; } public static Scenario getScenario(TlosProcessData tlosProcessData, String runId) { Scenario scenario = CpcUtils.getScenario(tlosProcessData); scenario.getManagement().getConcurrencyManagement().setRunningId(runId); return scenario; } // public static Scenario getScenarioOrj(TlosProcessData tlosProcessData, String planId) { // // Scenario scenario = Scenario.Factory.newInstance(); // scenario.setJobList(tlosProcessData.getJobList()); // // scenario.setScenarioArray(tlosProcessData.getScenarioArray()); // // tlosProcessData.getConcurrencyManagement().setPlanId(planId); // // scenario.setBaseScenarioInfos(tlosProcessData.getBaseScenarioInfos()); // scenario.setDependencyList(tlosProcessData.getDependencyList()); // scenario.setScenarioStatusList(tlosProcessData.getScenarioStatusList()); // scenario.setAlarmPreference(tlosProcessData.getAlarmPreference()); // scenario.setTimeManagement(tlosProcessData.getTimeManagement()); // scenario.setAdvancedScenarioInfos(tlosProcessData.getAdvancedScenarioInfos()); // scenario.setConcurrencyManagement(tlosProcessData.getConcurrencyManagement()); // scenario.setLocalParameters(tlosProcessData.getLocalParameters()); // // return scenario; // } public static Scenario getScenario(Spc spc) { Scenario scenario = Scenario.Factory.newInstance(); scenario.setBaseScenarioInfos(spc.getBaseScenarioInfos()); scenario.setDependencyList(spc.getDependencyList()); scenario.setScenarioStatusList(spc.getScenarioStatusList()); scenario.setAlarmPreference(spc.getAlarmPreference()); scenario.setManagement(spc.getManagement()); scenario.setAdvancedScenarioInfos(spc.getAdvancedScenarioInfos()); scenario.setLocalParameters(spc.getLocalParameters()); return scenario; } public static Scenario getScenario(Scenario tmpScenario) { Scenario scenario = Scenario.Factory.newInstance(); scenario.setBaseScenarioInfos(tmpScenario.getBaseScenarioInfos()); scenario.setDependencyList(tmpScenario.getDependencyList()); scenario.setScenarioStatusList(tmpScenario.getScenarioStatusList()); scenario.setAlarmPreference(tmpScenario.getAlarmPreference()); scenario.setManagement(tmpScenario.getManagement()); scenario.setAdvancedScenarioInfos(tmpScenario.getAdvancedScenarioInfos()); scenario.setLocalParameters(tmpScenario.getLocalParameters()); return scenario; } public static SpcInfoType getSpcInfo(Spc spc, String userId, String runId, Scenario tmpScenario) { LiveStateInfo myLiveStateInfo = LiveStateInfo.Factory.newInstance(); myLiveStateInfo.setStateName(StateName.PENDING); myLiveStateInfo.setSubstateName(SubstateName.IDLED); myLiveStateInfo.setStatusName(StatusName.BYTIME); spc.setLiveStateInfo(myLiveStateInfo); Thread thread = new Thread(spc); spc.setExecuterThread(thread); spc.setJsName(tmpScenario.getBaseScenarioInfos().getJsName()); spc.setConcurrent(tmpScenario.getManagement().getConcurrencyManagement().getConcurrent()); spc.setComment(tmpScenario.getBaseScenarioInfos().getComment()); spc.setUserId(userId); tmpScenario.getManagement().getConcurrencyManagement().setRunningId(runId); spc.setBaseScenarioInfos(tmpScenario.getBaseScenarioInfos()); spc.setDependencyList(tmpScenario.getDependencyList()); spc.setScenarioStatusList(tmpScenario.getScenarioStatusList()); spc.setAlarmPreference(tmpScenario.getAlarmPreference()); spc.setManagement(tmpScenario.getManagement()); spc.setAdvancedScenarioInfos(tmpScenario.getAdvancedScenarioInfos()); spc.setLocalParameters(tmpScenario.getLocalParameters()); SpcInfoType spcInfoType = new SpcInfoType(); spcInfoType.setJsName(spc.getBaseScenarioInfos().getJsName()); spcInfoType.setConcurrent(spc.getManagement().getConcurrencyManagement().getConcurrent()); spcInfoType.setComment(spc.getBaseScenarioInfos().getComment()); spcInfoType.setUserId(userId); Scenario scenario = CpcUtils.getScenario(spc); spcInfoType.setScenario(scenario); spcInfoType.setSpcReferance(spc); return spcInfoType; } public static SpcInfoType getSpcInfo(String userId, String runId, Scenario tmpScenario) { SpcInfoType spcInfoType = new SpcInfoType(); spcInfoType.setJsName(tmpScenario.getBaseScenarioInfos().getJsName()); spcInfoType.setConcurrent(tmpScenario.getManagement().getConcurrencyManagement().getConcurrent()); spcInfoType.setComment(tmpScenario.getBaseScenarioInfos().getComment()); spcInfoType.setUserId(userId); Scenario scenario = CpcUtils.getScenario(tmpScenario); spcInfoType.setScenario(scenario); spcInfoType.setSpcReferance(null); return spcInfoType; } public static ArrayList<JobRuntimeProperties> transformJobList(JobList jobList, Logger myLogger) { myLogger.debug("start:transformJobList"); ArrayList<JobRuntimeProperties> transformTable = new ArrayList<JobRuntimeProperties>(); ArrayIterator jobListIterator = new ArrayIterator(jobList.getJobPropertiesArray()); while (jobListIterator.hasNext()) { JobProperties jobProperties = (JobProperties) (jobListIterator.next()); JobRuntimeProperties jobRuntimeProperties = new JobRuntimeProperties(); /* IDLED state i ekle */ LiveStateInfoUtils.insertNewLiveStateInfo(jobProperties, StateName.INT_PENDING, SubstateName.INT_IDLED, StatusName.INT_BYTIME); jobRuntimeProperties.setJobProperties(jobProperties); // TODO infoBusInfo Manager i bilgilendir. transformTable.add(jobRuntimeProperties); } myLogger.debug("end:transformJobList"); return transformTable; } public static boolean validateJobList(JobList jobList, Logger myLogger) { XMLValidations.validateWithCode(jobList, myLogger); return true; } public static SpcInfoType prepareScenario(String runId, TlosSWPathType tlosSWPathType, Scenario myScenario, Logger myLogger) throws TlosFatalException { myLogger.info(""); myLogger.info(" > Senaryo ismi : " + tlosSWPathType.getFullPath()); JobList jobList = myScenario.getJobList(); if (!validateJobList(jobList, myLogger)) { // TODO WAITING e nasil alacagiz? myLogger.info(" > is listesi validasyonunda problem oldugundan WAITING e alinarak problemin giderilmesi beklenmektedir."); myLogger.error("Cpc Scenario jobs validation failed, process state changed to WAITING !"); return null; // 08.07.2013 Serkan // throw new TlosException("Cpc Job List validation failed, process state changed to WAITING !"); } if (jobList.getJobPropertiesArray().length == 0 && myScenario.getScenarioArray().length == 0) { myLogger.error(tlosSWPathType.getFullPath() + " isimli senaryo bilgileri yüklenemedi ya da iş listesi bos geldi !"); myLogger.error(tlosSWPathType.getFullPath() + " isimli senaryo için spc başlatılmıyor !"); return null; } SpcInfoType spcInfoType = null; // TODO Henüz ayarlanmadı ! String userId = null; if (jobList.getJobPropertiesArray().length == 0) { spcInfoType = CpcUtils.getSpcInfo(userId, runId, myScenario); spcInfoType.setSpcId(tlosSWPathType); } else { Spc spc = new Spc(tlosSWPathType.getRunId(), tlosSWPathType.getAbsolutePath(), TlosSpaceWide.getSpaceWideRegistry(), transformJobList(jobList, myLogger)); spcInfoType = CpcUtils.getSpcInfo(spc, userId, runId, myScenario); spcInfoType.setSpcId(tlosSWPathType); if (!TlosSpaceWide.getSpaceWideRegistry().getServerConfig().getServerParams().getIsPersistent().getUse() || !JobQueueOperations.recoverJobQueue(spcInfoType.getSpcReferance().getSpcAbsolutePath(), spc.getJobQueue(), spc.getJobQueueIndex())) { if (!spc.initScenarioInfo()) { myLogger.warn(tlosSWPathType.getFullPath() + " isimli senaryo bilgileri yüklenemedi ya da iş listesi boş geldi !"); Logger.getLogger(CpcBase.class).warn(" WARNING : " + tlosSWPathType.getFullPath() + " isimli senaryo bilgileri yüklenemedi ya da iş listesi boş geldi !"); System.exit(-1); } } } return spcInfoType; } public static String getRunId(TlosProcessData tlosProcessData, boolean isTest, Logger myLogger) { String runId = null; if (isTest) { String userId = "" + tlosProcessData.getBaseScenarioInfos().getUserId(); if (userId == null || userId.equals("")) { userId = "" + Calendar.getInstance().getTimeInMillis(); } myLogger.info(" > InstanceID = " + userId + " olarak belirlenmistir."); runId = userId; } else { runId = tlosProcessData.getRunId(); if (runId == null) { runId = "" + Calendar.getInstance().getTimeInMillis(); } myLogger.info(" > InstanceID = " + runId + " olarak belirlenmiştir."); } return runId; } public static void startSpc(TlosSWPathType tlosSWPathType, Logger myLogger) { SpcLookupTable spcLookupTable = TlosSpaceWide.getSpaceWideRegistry().getRunLookupTable().get(tlosSWPathType.getRunId()).getSpcLookupTable(); HashMap<String, SpcInfoType> table = spcLookupTable.getTable(); SpcInfoType spcInfoType = table.get(tlosSWPathType.getFullPath()); startSpc(spcInfoType, myLogger); } public static void startSpc(SpcInfoType spcInfoType, Logger myLogger) { /** * Bu thread daha once calistirildi mi? Degilse thread i * baslatabiliriz !! **/ Spc mySpc = spcInfoType.getSpcReferance(); if (spcInfoType.isVirgin() && !mySpc.getExecuterThread().isAlive()) { spcInfoType.setVirgin(false); /* Artik baslattik */ /** Statuleri set edelim **/ mySpc.getLiveStateInfo().setStateName(StateName.RUNNING); mySpc.getLiveStateInfo().setSubstateName(SubstateName.STAGE_IN); myLogger.info(" > Senaryo " + mySpc.getSpcFullPath() + " aktive edildi !"); mySpc.getExecuterThread().setName(mySpc.getCommonName()); /** Senaryonun thread lerle calistirildigi yer !! **/ mySpc.getExecuterThread().start(); myLogger.info(" > OK"); } } public static String getRootScenarioPath(String runId) { return getInstancePath(runId) + "." + EngineeConstants.LONELY_JOBS; } public static String getInstancePath(String runId) { return BasePathType.getRootPath() + "." + runId; } }
apache-2.0
raksha-rao/gluster-ovirt
backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/businessentities/Quota.java
12992
package org.ovirt.engine.core.common.businessentities; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.Size; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.INotifyPropertyChanged; /** * Quota business entity which reflects the <code>Quota</code> limitations for storage pool. <BR/> * The limitation are separated to two different types * <ul> * <li>General Limitation - Indicates the general limitation of the quota cross all the storage pool</li> * <li>Specific Limitation - Indicates specific limitation of the quota for specific storage or vds group</li> * </ul> * <BR/> * Quota entity encapsulate the specific limitations of the storage pool with lists, general limitations are configured * in the field members.<BR/> * <BR/> * Take in notice there can not be general limitation and specific limitation on the same resource type. */ public class Quota extends IVdcQueryable implements INotifyPropertyChanged, Serializable, QuotaVdsGroupProperties, QuotaStorageProperties { /** * Automatic generated serial version ID. */ private static final long serialVersionUID = 6637198348072059199L; /** * The quota id. */ private Guid id = new Guid(); /** * The storage pool id the quota is enforced on. */ private Guid storagePoolId; /** * The storage pool name the quota is enforced on, for GUI use. */ private transient String storagePoolName; /** * The quota name. */ @Size(min = 1, max = BusinessEntitiesDefinitions.QUOTA_NAME_SIZE) private String quotaName; /** * The quota description. */ @Size(min = 1, max = BusinessEntitiesDefinitions.QUOTA_DESCRIPTION_SIZE) private String description; /** * The threshold of vds group in percentages. */ @Min(0) @Max(100) private int thresholdVdsGroupPercentage; /** * The threshold of storage in percentages. */ @Min(0) @Max(100) private int thresholdStoragePercentage; /** * The grace of vds group in percentages. */ @Min(0) @Max(100) private int graceVdsGroupPercentage; /** * The grace of storage in percentages. */ @Min(0) @Max(100) private int graceStoragePercentage; /** * The global storage limit in Giga bytes. */ @Min(-1) private Long storageSizeGB; /** * The global storage usage in Giga bytes for Quota. */ private transient Double storageSizeGBUsage; /** * The global virtual CPU limitations. */ @Min(-1) private Integer virtualCpu; /** * The global virtual CPU usage for Quota. */ private transient Integer virtualCpuUsage; /** * The global virtual memory limitations for Quota. */ @Min(-1) private Long memSizeMB; /** * The global virtual memory usage for Quota. */ private transient Long memSizeMBUsage; /** * List of all the specific VdsGroups limitations. */ private List<QuotaVdsGroup> quotaVdsGroupList; /** * List of all the specific storage limitations. */ private List<QuotaStorage> quotaStorageList; /** * Default constructor of Quota, which initialize empty lists for specific limitations, and no user assigned. */ public Quota() { setQuotaStorages(new ArrayList<QuotaStorage>()); setQuotaVdsGroups(new ArrayList<QuotaVdsGroup>()); } /** * @return the quota id. */ public Guid getId() { return id; } /** * @param id * the quota Id to set. */ public void setId(Guid id) { this.id = id; } /** * @return the thresholdVdsGroupPercentage */ public int getThresholdVdsGroupPercentage() { return thresholdVdsGroupPercentage; } /** * @param thresholdVdsGroupPercentage * the thresholdVdsGroupPercentage to set */ public void setThresholdVdsGroupPercentage(int thresholdVdsGroupPercentage) { this.thresholdVdsGroupPercentage = thresholdVdsGroupPercentage; } /** * @return the thresholdStoragePercentage */ public int getThresholdStoragePercentage() { return thresholdStoragePercentage; } /** * @param thresholdStoragePercentage * the thresholdStoragePercentage to set */ public void setThresholdStoragePercentage(int thresholdStoragePercentage) { this.thresholdStoragePercentage = thresholdStoragePercentage; } /** * @return the graceVdsGroupPercentage */ public int getGraceVdsGroupPercentage() { return graceVdsGroupPercentage; } /** * @param graceVdsGroupPercentage * the graceVdsGroupPercentage to set */ public void setGraceVdsGroupPercentage(int graceVdsGroupPercentage) { this.graceVdsGroupPercentage = graceVdsGroupPercentage; } /** * @return the graceStoragePercentage */ public int getGraceStoragePercentage() { return graceStoragePercentage; } /** * @param graceStoragePercentage * the graceStoragePercentage to set */ public void setGraceStoragePercentage(int graceStoragePercentage) { this.graceStoragePercentage = graceStoragePercentage; } /** * @return the description */ public String getDescription() { return description; } /** * @param description * the description to set */ public void setDescription(String description) { this.description = description; } /** * @return the quotaName */ public String getQuotaName() { return quotaName; } /** * @param quotaName * the quotaName to set */ public void setQuotaName(String quotaName) { this.quotaName = quotaName; } /** * @return the storagePoolId */ public Guid getStoragePoolId() { return storagePoolId; } /** * @param storagePoolId * the storagePoolId to set */ public void setStoragePoolId(Guid storagePoolId) { this.storagePoolId = storagePoolId; } /** * @return the storagePoolName */ public String getStoragePoolName() { return storagePoolName; } /** * @param storagePoolName * the storagePoolName to set */ public void setStoragePoolName(String storagePoolName) { this.storagePoolName = storagePoolName; } /** * @return the quotaStorageList */ public List<QuotaStorage> getQuotaStorages() { return quotaStorageList; } /** * @param quotaStorages * the quotaStorages to set */ public void setQuotaStorages(List<QuotaStorage> quotaStorages) { this.quotaStorageList = quotaStorages; } /** * @return the quotaVdsGroups */ public List<QuotaVdsGroup> getQuotaVdsGroups() { return quotaVdsGroupList; } /** * @param quotaVdsGroups * the quotaVdsGroups to set */ public void setQuotaVdsGroups(List<QuotaVdsGroup> quotaVdsGroups) { this.quotaVdsGroupList = quotaVdsGroups; } /** * @return the memSizeMBUsage */ public Long getMemSizeMBUsage() { return memSizeMBUsage; } /** * @param memSizeMBUsage * the memSizeMBUsage to set */ public void setMemSizeMBUsage(Long memSizeMBUsage) { this.memSizeMBUsage = memSizeMBUsage; } /** * @return the memSizeMB */ public Long getMemSizeMB() { return memSizeMB; } /** * @param memSizeMB * the memSizeMB to set */ public void setMemSizeMB(Long memSizeMB) { this.memSizeMB = memSizeMB; } /** * @return the virtualCpuUsage */ public Integer getVirtualCpuUsage() { return virtualCpuUsage; } /** * @param virtualCpuUsage * the virtualCpuUsage to set */ public void setVirtualCpuUsage(Integer virtualCpuUsage) { this.virtualCpuUsage = virtualCpuUsage; } /** * @return the virtualCpu */ public Integer getVirtualCpu() { return virtualCpu; } /** * @param virtualCpu * the virtualCpu to set */ public void setVirtualCpu(Integer virtualCpu) { this.virtualCpu = virtualCpu; } /** * @return the storageSizeGBUsage */ public Double getStorageSizeGBUsage() { return storageSizeGBUsage; } /** * @param storageSizeGBUsage * the storageSizeGBUsage to set */ public void setStorageSizeGBUsage(Double storageSizeGBUsage) { this.storageSizeGBUsage = storageSizeGBUsage; } /** * @return the storageSizeGB */ public Long getStorageSizeGB() { return storageSizeGB; } /** * @param storageSizeGB * the storageSizeGB to set */ public void setStorageSizeGB(Long storageSizeGB) { this.storageSizeGB = storageSizeGB; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + graceStoragePercentage; result = prime * result + graceVdsGroupPercentage; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((quotaName == null) ? 0 : quotaName.hashCode()); result = prime * result + ((quotaStorageList == null) ? 0 : quotaStorageList.hashCode()); result = prime * result + ((quotaVdsGroupList == null) ? 0 : quotaVdsGroupList.hashCode()); result = prime * result + ((storageSizeGB == null) ? 0 : storageSizeGB.hashCode()); result = prime * result + ((storagePoolId == null) ? 0 : storagePoolId.hashCode()); result = prime * result + thresholdStoragePercentage; result = prime * result + thresholdVdsGroupPercentage; result = prime * result + ((virtualCpu == null) ? 0 : virtualCpu.hashCode()); result = prime * result + ((memSizeMB == null) ? 0 : memSizeMB.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Quota other = (Quota) obj; if (description == null) { if (other.description != null) return false; } else if (!description.equals(other.description)) return false; if (graceStoragePercentage != other.graceStoragePercentage) return false; if (graceVdsGroupPercentage != other.graceVdsGroupPercentage) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (quotaName == null) { if (other.quotaName != null) return false; } else if (!quotaName.equals(other.quotaName)) return false; if (quotaStorageList == null) { if (other.quotaStorageList != null) return false; } else if (!quotaStorageList.equals(other.quotaStorageList)) return false; if (quotaVdsGroupList == null) { if (other.quotaVdsGroupList != null) return false; } else if (!quotaVdsGroupList.equals(other.quotaVdsGroupList)) return false; if (storageSizeGB == null) { if (other.storageSizeGB != null) return false; } else if (!storageSizeGB.equals(other.storageSizeGB)) return false; if (storagePoolId == null) { if (other.storagePoolId != null) return false; } else if (!storagePoolId.equals(other.storagePoolId)) return false; if (thresholdStoragePercentage != other.thresholdStoragePercentage) return false; if (thresholdVdsGroupPercentage != other.thresholdVdsGroupPercentage) return false; if (virtualCpu == null) { if (other.virtualCpu != null) return false; } else if (!virtualCpu.equals(other.virtualCpu)) return false; if (memSizeMB == null) { if (other.memSizeMB != null) return false; } else if (!memSizeMB.equals(other.memSizeMB)) return false; return true; } }
apache-2.0
yahoo/pulsar
pulsar-broker-common/src/main/java/org/apache/pulsar/broker/resources/NamespaceResources.java
3049
/** * 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.pulsar.broker.resources; import com.fasterxml.jackson.core.type.TypeReference; import java.util.Map; import java.util.Optional; import lombok.Getter; import org.apache.pulsar.common.partition.PartitionedTopicMetadata; import org.apache.pulsar.common.policies.data.NamespaceIsolationData; import org.apache.pulsar.common.policies.data.Policies; import org.apache.pulsar.common.policies.impl.NamespaceIsolationPolicies; import org.apache.pulsar.metadata.api.MetadataStoreException; import org.apache.pulsar.metadata.api.extended.MetadataStoreExtended; @Getter public class NamespaceResources extends BaseResources<Policies> { private IsolationPolicyResources isolationPolicies; private PartitionedTopicResources partitionedTopicResources; private MetadataStoreExtended configurationStore; public NamespaceResources(MetadataStoreExtended configurationStore, int operationTimeoutSec) { super(configurationStore, Policies.class, operationTimeoutSec); this.configurationStore = configurationStore; isolationPolicies = new IsolationPolicyResources(configurationStore, operationTimeoutSec); partitionedTopicResources = new PartitionedTopicResources(configurationStore, operationTimeoutSec); } public static class IsolationPolicyResources extends BaseResources<Map<String, NamespaceIsolationData>> { public IsolationPolicyResources(MetadataStoreExtended store, int operationTimeoutSec) { super(store, new TypeReference<Map<String, NamespaceIsolationData>>() { }, operationTimeoutSec); } public Optional<NamespaceIsolationPolicies> getPolicies(String path) throws MetadataStoreException { Optional<Map<String, NamespaceIsolationData>> data = super.get(path); return data.isPresent() ? Optional.of(new NamespaceIsolationPolicies(data.get())) : Optional.empty(); } } public static class PartitionedTopicResources extends BaseResources<PartitionedTopicMetadata> { public PartitionedTopicResources(MetadataStoreExtended configurationStore, int operationTimeoutSec) { super(configurationStore, PartitionedTopicMetadata.class, operationTimeoutSec); } } }
apache-2.0
StTu/sjcom
deploy.sh
355
jekyll build --destination /vol/websites/sjcom cpwd=pwd cd /vol/websites/sjcom cd publications/ mogrify -resize 200x -format png */*.png mogrify -resize 200x -format jpg */*.jpg cd .. cd images/ mogrify -resize '1000x>' -format png */*.png mogrify -resize '1000x>' -format jpg */*.jpg cd .. git add * val=date git commit -m "$val" git push --force cd pwd
apache-2.0
DonBranson/DonsProxy
src/main/com/moneybender/proxy/channels/decorators/ThrottleDecorator.java
1299
/* * Created on Nov 29, 2007 * * Copyright (c), 2007 Don Branson. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.moneybender.proxy.channels.decorators; import com.moneybender.proxy.channels.IReadBytes; public class ThrottleDecorator extends ReadDelayDecorator { private final int microsecondsPerByte; public ThrottleDecorator(IReadBytes decoratedWriter, int bandwidthLimit) { super(decoratedWriter); double bytesPerSecond = bandwidthLimit * 1000; this.microsecondsPerByte = (int)((1 / bytesPerSecond) * 1000 * 1000); saveEarliestNextIO(0); } @Override protected void saveEarliestNextIO(int bytesRead) { setEarliestNextIO(System.currentTimeMillis() + ((bytesRead * microsecondsPerByte) / 1000)); } }
apache-2.0
stackanetes/stackanetes
demo_openstack.sh
3223
#!/bin/bash set +x # Load environment. . env_openstack.sh # Install command-line tools. pip install python-neutronclient python-openstackclient -U # Import CoreOS / CirrOS images. cd /tmp wget http://download.cirros-cloud.net/0.3.3/cirros-0.3.3-x86_64-disk.img wget https://stable.release.core-os.net/amd64-usr/current/coreos_production_openstack_image.img.bz2 bunzip2 coreos_production_openstack_image.img.bz2 openstack image create CoreOS --container-format bare --disk-format qcow2 --file /tmp/coreos_production_openstack_image.img --public openstack image create CirrOS --container-format bare --disk-format qcow2 --file /tmp/cirros-0.3.3-x86_64-disk.img --public rm coreos_production_openstack_image.img rm cirros-0.3.3-x86_64-disk.img # Create external network. openstack network create ext-net --external --provider-physical-network physnet1 --provider-network-type flat openstack subnet create ext-subnet --no-dhcp --allocation-pool start=172.16.0.2,end=172.16.0.249 --network=ext-net --subnet-range 172.16.0.0/24 --gateway 172.16.0.1 # Create default flavors. openstack flavor create --public m1.tiny --ram 512 --disk 1 --vcpus 1 openstack flavor create --public m1.small --ram 2048 --disk 20 --vcpus 1 openstack flavor create --public m1.medium --ram 4096 --disk 40 --vcpus 2 openstack flavor create --public m1.large --ram 8192 --disk 80 --vcpus 4 openstack flavor create --public m1.xlarge --ram 16384 --disk 160 --vcpus 8 # Create a demo tenant network, router and security group. openstack network create demo-net openstack subnet create demo-subnet --allocation-pool start=192.168.0.2,end=192.168.0.254 --network demo-net --subnet-range 192.168.0.0/24 --gateway 192.168.0.1 --dns-nameserver 8.8.8.8 --dns-nameserver 8.8.4.4 openstack router create demo-router neutron router-interface-add demo-router $(openstack subnet show demo-subnet -c id -f value) neutron router-gateway-set demo-router ext-net #openstack security group rule create default --protocol icmp #openstack security group rule create default --protocol tcp --dst-port 22 # Create keypair. openstack keypair create demo-key > ./stackanetes.id_rsa # Create a CoreOS instance. openstack server create demo-coreos \ --image $(openstack image show CoreOS -c id -f value) \ --flavor $(openstack flavor show m1.small -c id -f value) \ --nic net-id=$(openstack network show demo-net -c id -f value) \ --key-name demo-key # Allocate and attach a floating IP to the instance. openstack ip floating add $(openstack ip floating create ext-net -c floating_ip_address -f value) demo-coreos # Create a volume and attach it to the instance. openstack volume create demo-volume --size 10 sleep 10 openstack server add volume demo-coreos demo-volume # Live migrate the instance. # openstack server migrate --live b1-3 demo-coreos # Boot instance from volume. openstack volume create demo-boot-volume --image $(openstack image show CoreOS -c id -f value) --size 10 openstack server create demo-coreos-boot-volume \ --volume $(openstack volume show demo-boot-volume -c id -f value) \ --flavor $(openstack flavor show m1.small -c id -f value) \ --nic net-id=$(openstack network show demo-net -c id -f value) \ --key-name demo-key
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Elymus/Elymus trachycaulus/ Syn. Agropyron caninum hornemannii/README.md
191
# Agropyron caninum var. hornemannii VARIETY #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
apache-2.0
Jackygq1982/hbase_src
hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/wal/TestCustomWALCellCodec.java
2335
/** * 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.hbase.regionserver.wal; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.SmallTests; import org.junit.Test; import org.junit.experimental.categories.Category; /** * Test that we can create, load, setup our own custom codec */ @Category(SmallTests.class) public class TestCustomWALCellCodec { public static class CustomWALCellCodec extends WALCellCodec { public Configuration conf; public CompressionContext context; public CustomWALCellCodec(Configuration conf, CompressionContext compression) { super(conf, compression); this.conf = conf; this.context = compression; } } /** * Test that a custom {@link WALCellCodec} will be completely setup when it is instantiated via * {@link WALCellCodec} * @throws Exception on failure */ @Test public void testCreatePreparesCodec() throws Exception { Configuration conf = new Configuration(false); conf.setClass(WALCellCodec.WAL_CELL_CODEC_CLASS_KEY, CustomWALCellCodec.class, WALCellCodec.class); CustomWALCellCodec codec = (CustomWALCellCodec) WALCellCodec.create(conf, null, null); assertEquals("Custom codec didn't get initialized with the right configuration!", conf, codec.conf); assertEquals("Custom codec didn't get initialized with the right compression context!", null, codec.context); } }
apache-2.0
bio-org-au/nsl-editor
test/models/reference/update/if_changed/for_an_unchanged_volume_test.rb
968
# frozen_string_literal: true # Copyright 2015 Australian National Botanic Gardens # # This file is part of the NSL Editor. # # 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. # require "test_helper" require "models/reference/update/if_changed/test_helper" # Single Reference model test. class ForAnUnchangedRefVolumeTest < ActiveSupport::TestCase test "unchanged volume" do test_reference_text_field_lack_of_change_is_detected("volume") end end
apache-2.0
UniversalDependencies/docs
treebanks/kpv_lattice/kpv_lattice-dep-flat.md
3580
--- layout: base title: 'Statistics of flat in UD_Komi_Zyrian-Lattice' udver: '2' --- ## Treebank Statistics: UD_Komi_Zyrian-Lattice: Relations: `flat` This relation is universal. There are 2 language-specific subtypes of `flat`: <tt><a href="kpv_lattice-dep-flat-name.html">flat:name</a></tt>, <tt><a href="kpv_lattice-dep-flat-num.html">flat:num</a></tt>. 3 nodes (0%) are attached to their parents as `flat`. 3 instances of `flat` (100%) are left-to-right (parent precedes child). Average distance between parent and child is 1. The following 2 pairs of parts of speech are connected with `flat`: <tt><a href="kpv_lattice-pos-NOUN.html">NOUN</a></tt>-<tt><a href="kpv_lattice-pos-NOUN.html">NOUN</a></tt> (2; 67% instances), <tt><a href="kpv_lattice-pos-NUM.html">NUM</a></tt>-<tt><a href="kpv_lattice-pos-NUM.html">NUM</a></tt> (1; 33% instances). ~~~ conllu # visual-style 5 bgColor:blue # visual-style 5 fgColor:white # visual-style 4 bgColor:blue # visual-style 4 fgColor:white # visual-style 4 5 flat color:blue 1 Пыстин Пыстин NOUN N Animacy=Hum|Case=Nom|Number=Sing 11 nsubj _ GTtags=Prop,Sem/Sur-Mal,Sg,Nom 2 Максим Максим NOUN N Animacy=Hum|Case=Nom|Number=Sing 1 flat _ GTtags=Prop,Sem/Mal,Sg,Nom|SpaceAfter=No 3 , , PUNCT PUNCT _ 6 punct _ _ 4 Куршайт Куршайт NOUN N Animacy=Hum|Case=Nom|Number=Sing 6 nmod:poss _ GTtags=Prop,Sem/Ant,Sg,Nom 5 Гришлӧн Гриш NOUN N Animacy=Hum|Case=Gen|Number=Sing 4 flat _ GTtags=Prop,Sem/Mal,Sg,Gen 6 батьыс бать NOUN N Case=Nom|Number=Sing|Number[psor]=Sing|Person[psor]=3 1 appos _ GTtags=Sg,Nom,PxSg3|SpaceAfter=No 7 , , PUNCT PUNCT _ 6 punct _ _ 8 дас дас·кык NUM Num Case=Nom|Number=Sing|NumType=Card 10 nummod _ GTtags=Card,Sg,Nom 9 кык _ NUM Num _ 8 flat _ _ 10 арӧсӧн арӧс NOUN N Case=Ins|Number=Sing 11 obl _ GTtags=Sg,Ins 11 заводитіс заводитны VERB V Mood=Ind|Number=Sing|Person=3|Tense=Past|Valency=1 0 root _ GTtags=IV,Ind,Prt1,Sg3 12 вӧрын вӧр NOUN N Case=Ine|Number=Sing 13 obl:lmod _ GTtags=Sg,Ine 13 келавны келавны VERB V Valency=1|VerbForm=Inf 11 xcomp _ GTtags=IV,Inf|SpaceAfter=No 14 . . PUNCT PUNCT _ 11 punct _ _ ~~~ ~~~ conllu # visual-style 9 bgColor:blue # visual-style 9 fgColor:white # visual-style 8 bgColor:blue # visual-style 8 fgColor:white # visual-style 8 9 flat color:blue 1 Пыстин Пыстин NOUN N Animacy=Hum|Case=Nom|Number=Sing 11 nsubj _ GTtags=Prop,Sem/Sur-Mal,Sg,Nom 2 Максим Максим NOUN N Animacy=Hum|Case=Nom|Number=Sing 1 flat _ GTtags=Prop,Sem/Mal,Sg,Nom|SpaceAfter=No 3 , , PUNCT PUNCT _ 6 punct _ _ 4 Куршайт Куршайт NOUN N Animacy=Hum|Case=Nom|Number=Sing 6 nmod:poss _ GTtags=Prop,Sem/Ant,Sg,Nom 5 Гришлӧн Гриш NOUN N Animacy=Hum|Case=Gen|Number=Sing 4 flat _ GTtags=Prop,Sem/Mal,Sg,Gen 6 батьыс бать NOUN N Case=Nom|Number=Sing|Number[psor]=Sing|Person[psor]=3 1 appos _ GTtags=Sg,Nom,PxSg3|SpaceAfter=No 7 , , PUNCT PUNCT _ 6 punct _ _ 8 дас дас·кык NUM Num Case=Nom|Number=Sing|NumType=Card 10 nummod _ GTtags=Card,Sg,Nom 9 кык _ NUM Num _ 8 flat _ _ 10 арӧсӧн арӧс NOUN N Case=Ins|Number=Sing 11 obl _ GTtags=Sg,Ins 11 заводитіс заводитны VERB V Mood=Ind|Number=Sing|Person=3|Tense=Past|Valency=1 0 root _ GTtags=IV,Ind,Prt1,Sg3 12 вӧрын вӧр NOUN N Case=Ine|Number=Sing 13 obl:lmod _ GTtags=Sg,Ine 13 келавны келавны VERB V Valency=1|VerbForm=Inf 11 xcomp _ GTtags=IV,Inf|SpaceAfter=No 14 . . PUNCT PUNCT _ 11 punct _ _ ~~~
apache-2.0
wilfriedcomte/centreon-plugins
centreon/common/dell/powerconnect3000/mode/globalstatus.pm
3990
# # Copyright 2018 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # 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 centreon::common::dell::powerconnect3000::mode::globalstatus; use base qw(centreon::plugins::mode); use strict; use warnings; my %states = ( 3 => ['ok', 'OK'], 4 => ['non critical', 'WARNING'], 5 => ['critical', 'CRITICAL'], ); sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $self->{version} = '1.0'; $options{options}->add_options(arguments => { }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); } sub run { my ($self, %options) = @_; $self->{snmp} = $options{snmp}; my $oid_productStatusGlobalStatus = '.1.3.6.1.4.1.674.10895.3000.1.2.110.1'; my $oid_productIdentificationDisplayName = '.1.3.6.1.4.1.674.10895.3000.1.2.100.1'; my $oid_productIdentificationBuildNumber = '.1.3.6.1.4.1.674.10895.3000.1.2.100.5'; my $oid_productIdentificationServiceTag = '.1.3.6.1.4.1.674.10895.3000.1.2.100.8.1.4'; my $result = $self->{snmp}->get_multiple_table(oids => [ { oid => $oid_productStatusGlobalStatus, start => $oid_productStatusGlobalStatus }, { oid => $oid_productIdentificationDisplayName, start => $oid_productIdentificationDisplayName }, { oid => $oid_productIdentificationBuildNumber, start => $oid_productIdentificationBuildNumber }, { oid => $oid_productIdentificationServiceTag, start => $oid_productIdentificationServiceTag }, ], nothing_quit => 1 ); my $globalStatus = $result->{$oid_productStatusGlobalStatus}->{$oid_productStatusGlobalStatus . '.0'}; my $displayName = $result->{$oid_productIdentificationDisplayName}->{$oid_productIdentificationDisplayName . '.0'}; my $buildNumber = $result->{$oid_productIdentificationBuildNumber}->{$oid_productIdentificationBuildNumber . '.0'}; my $serviceTag; foreach my $key ($self->{snmp}->oid_lex_sort(keys %{$result->{$oid_productIdentificationServiceTag}})) { next if ($key !~ /^$oid_productIdentificationServiceTag\.(\d+)$/); if (!defined($serviceTag)) { $serviceTag = $result->{$oid_productIdentificationServiceTag}->{$oid_productIdentificationServiceTag . '.' . $1}; } else { $serviceTag .= ',' . $result->{$oid_productIdentificationServiceTag}->{$oid_productIdentificationServiceTag . '.' . $1}; } } $self->{output}->output_add(severity => ${$states{$globalStatus}}[1], short_msg => sprintf("Overall global status is '%s' [Product: %s] [Version: %s] [Service Tag: %s]", ${$states{$globalStatus}}[0], $displayName, $buildNumber, $serviceTag)); $self->{output}->display(); $self->{output}->exit(); } 1; __END__ =head1 MODE Check the overall status of Dell Powerconnect 3000. =over 8 =back =cut
apache-2.0
System3D/gestor-de-lotes
storage/framework/views/96fd683b3799ea6bb61223346be7d37255bde268.php
3354
<?php echo e(Form::open(['url' => route('lotes.store'), 'class'=>'form-horizontal', 'role'=>"form"])); ?> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title">Criar Lote</h4> </div> <div class="modal-body"> <div class="form-group"> <label for="inputDescricao" class="col-sm-2 control-label">Nome:</label> <div class="col-sm-10"> <input type="text" name="descricao" id="inputDescricao" class="form-control" value="" required="required" tabindex="1" autofocus> </div> </div> <div class="form-group"> <label for="inputDataPCP" class="col-sm-2 control-label">PCP:</label> <div class="col-sm-4"> <input type="date" name="dataprev_pcp" id="inputDataPCP" class="form-control" value="<?php echo e(date('Y-m-d')); ?>" tabindex="2" required="required"> </div> <label for="inputDataPintura" class="col-sm-2 control-label">Pintura:</label> <div class="col-sm-4"> <input type="date" name="dataprev_pintura" id="inputDataPintura" class="form-control" value="" tabindex="6"> </div> </div> <div class="form-group"> <label for="inputDataPreparacao" class="col-sm-2 control-label">Preparacao:</label> <div class="col-sm-4"> <input type="date" name="dataprev_preparacao" id="inputDataPreparacao" class="form-control" value="" tabindex="3"> </div> <label for="inputDataExpedicao" class="col-sm-2 control-label">Expedição:</label> <div class="col-sm-4"> <input type="date" name="dataprev_expedicao" id="inputDataExpedicao" class="form-control" value="" tabindex="7"> </div> </div> <div class="form-group"> <label for="inputDataGabarito" class="col-sm-2 control-label">Gabarito:</label> <div class="col-sm-4"> <input type="date" name="dataprev_gabarito" id="inputDataGabarito" class="form-control" value="" tabindex="4"> </div> <label for="inputDataMontagem" class="col-sm-2 control-label">Montagem:</label> <div class="col-sm-4"> <input type="date" name="dataprev_montagem" id="inputDataMontagem" class="form-control" value="" tabindex="8"> </div> </div> <div class="form-group"> <label for="inputDataSolda" class="col-sm-2 control-label">Solda:</label> <div class="col-sm-4"> <input type="date" name="dataprev_solda" id="inputDataSolda" class="form-control" value="" tabindex="5"> </div> <label for="inputDataEntregaFinal" class="col-sm-2 control-label">Entrega Final:</label> <div class="col-sm-4"> <input type="date" name="dataprev_entrega" id="inputDataEntregaFinal" class="form-control" value="null" tabindex="9"> </div> </div> <!-- HIDDEN IDs --> <input type="hidden" name="obra_id" value="<?php echo e($obra_id); ?>"> <input type="hidden" name="etapa_id" value="<?php echo e($etapa_id); ?>"> <input type="hidden" name="grouped" value="<?php echo e($grouped); ?>"> <?php foreach($handles_ids as $handle_id): ?> <input type="hidden" name="handles_ids[]" id="inputHandleIds" class="form-control" value="<?php echo e($handle_id); ?>"> <?php endforeach; ?> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button> <button type="submit" class="btn btn-primary">Salvar</button> </div> <?php echo e(Form::close()); ?>
apache-2.0
kishikawakatsumi/Mozc-for-iOS
src/android/tests/src/com/google/android/inputmethod/japanese/testing/MozcLayoutUtil.java
3609
// Copyright 2010-2014, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package org.mozc.android.inputmethod.japanese.testing; import org.mozc.android.inputmethod.japanese.protobuf.ProtoCandidates.CandidateWord; import org.mozc.android.inputmethod.japanese.ui.CandidateLayout; import org.mozc.android.inputmethod.japanese.ui.CandidateLayout.Row; import org.mozc.android.inputmethod.japanese.ui.CandidateLayout.Span; import com.google.common.base.Optional; import org.easymock.EasyMockSupport; import org.easymock.IMockBuilder; import java.util.Collections; import java.util.List; /** * Methods commonly used for MechaMozc's testing. * */ public class MozcLayoutUtil { // Disallow instantiation. private MozcLayoutUtil() { } public static Row createRow(int top, int height, int width, Span... spans) { Row result = new Row(); result.setTop(top); result.setHeight(height); result.setWidth(width); for (Span span : spans) { result.addSpan(span); } return result; } public static Span createSpan(int id, int left, int right) { Span span = new Span( Optional.of(CandidateWord.newBuilder().setId(id).build()), 0, 0, Collections.<String>emptyList()); span.setLeft(left); span.setRight(right); return span; } public static Span createEmptySpan() { return new Span( Optional.of(CandidateWord.getDefaultInstance()), 0, 0, Collections.<String>emptyList()); } public static CandidateLayout createCandidateLayoutMock(EasyMockSupport easyMockSupport) { return createCandidateLayoutMockBuilder(easyMockSupport).createMock(); } public static CandidateLayout createNiceCandidateLayoutMock(EasyMockSupport easyMockSupport) { return createCandidateLayoutMockBuilder(easyMockSupport).createNiceMock(); } public static IMockBuilder<CandidateLayout> createCandidateLayoutMockBuilder( EasyMockSupport easyMockSupport) { return easyMockSupport.createMockBuilder(CandidateLayout.class) .withConstructor(List.class, float.class, float.class) .withArgs(Collections.emptyList(), 0f, 0f); } }
apache-2.0
lanesawyer/island
static/homepage/scripts/animated-menu.js
275
$(function(){$("li.animated").mouseover(function(){$(this).stop().animate({height:'50px'},{queue:false,duration:600,easing:'easeOutBounce'})});$("li.animated").mouseout(function(){$(this).stop().animate({height:'40px'},{queue:false,duration:600,easing:'easeOutBounce'})});});
apache-2.0
marques-work/gocd
spark/spark-base/src/main/java/com/thoughtworks/go/spark/HtmlErrorPage.java
1606
/* * Copyright 2021 ThoughtWorks, 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.thoughtworks.go.spark; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import static java.lang.String.valueOf; public abstract class HtmlErrorPage { public static String errorPage(int code, String message) { return Holder.INSTANCE.replaceAll(buildRegex("status_code"), valueOf(code)) .replaceAll(buildRegex("error_message"), message); } private static String buildRegex(final String value) { return "\\{\\{" + value + "\\}\\}"; } private static class Holder { private static final String INSTANCE = fileContents(); private static String fileContents() { try (InputStream in = Holder.class.getResourceAsStream("/error.html")) { return IOUtils.toString(in, StandardCharsets.UTF_8); } catch (IOException e) { throw new RuntimeException(e); } } } }
apache-2.0
emullaraj/ebay-sdk-php
src/DTS/eBaySDK/Trading/Types/CategoryType.php
5200
<?php /** * THE CODE IN THIS FILE WAS GENERATED FROM THE EBAY WSDL USING THE PROJECT: * * https://github.com/davidtsadler/ebay-api-sdk-php * * Copyright 2014 David T. Sadler * * 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 DTS\eBaySDK\Trading\Types; /** * * @property boolean $BestOfferEnabled * @property boolean $AutoPayEnabled * @property boolean $B2BVATEnabled * @property boolean $CatalogEnabled * @property string $CategoryID * @property integer $CategoryLevel * @property string $CategoryName * @property string[] $CategoryParentID * @property string[] $CategoryParentName * @property boolean $Expired * @property boolean $IntlAutosFixedCat * @property boolean $LeafCategory * @property boolean $Virtual * @property boolean $ORPA * @property boolean $ORRA * @property boolean $LSD */ class CategoryType extends \DTS\eBaySDK\Types\BaseType { /** * @var array Properties belonging to objects of this class. */ private static $propertyTypes = array( 'BestOfferEnabled' => array( 'type' => 'boolean', 'unbound' => false, 'attribute' => false, 'elementName' => 'BestOfferEnabled' ), 'AutoPayEnabled' => array( 'type' => 'boolean', 'unbound' => false, 'attribute' => false, 'elementName' => 'AutoPayEnabled' ), 'B2BVATEnabled' => array( 'type' => 'boolean', 'unbound' => false, 'attribute' => false, 'elementName' => 'B2BVATEnabled' ), 'CatalogEnabled' => array( 'type' => 'boolean', 'unbound' => false, 'attribute' => false, 'elementName' => 'CatalogEnabled' ), 'CategoryID' => array( 'type' => 'string', 'unbound' => false, 'attribute' => false, 'elementName' => 'CategoryID' ), 'CategoryLevel' => array( 'type' => 'integer', 'unbound' => false, 'attribute' => false, 'elementName' => 'CategoryLevel' ), 'CategoryName' => array( 'type' => 'string', 'unbound' => false, 'attribute' => false, 'elementName' => 'CategoryName' ), 'CategoryParentID' => array( 'type' => 'string', 'unbound' => true, 'attribute' => false, 'elementName' => 'CategoryParentID' ), 'CategoryParentName' => array( 'type' => 'string', 'unbound' => true, 'attribute' => false, 'elementName' => 'CategoryParentName' ), 'Expired' => array( 'type' => 'boolean', 'unbound' => false, 'attribute' => false, 'elementName' => 'Expired' ), 'IntlAutosFixedCat' => array( 'type' => 'boolean', 'unbound' => false, 'attribute' => false, 'elementName' => 'IntlAutosFixedCat' ), 'LeafCategory' => array( 'type' => 'boolean', 'unbound' => false, 'attribute' => false, 'elementName' => 'LeafCategory' ), 'Virtual' => array( 'type' => 'boolean', 'unbound' => false, 'attribute' => false, 'elementName' => 'Virtual' ), 'ORPA' => array( 'type' => 'boolean', 'unbound' => false, 'attribute' => false, 'elementName' => 'ORPA' ), 'ORRA' => array( 'type' => 'boolean', 'unbound' => false, 'attribute' => false, 'elementName' => 'ORRA' ), 'LSD' => array( 'type' => 'boolean', 'unbound' => false, 'attribute' => false, 'elementName' => 'LSD' ) ); /** * @param array $values Optional properties and values to assign to the object. */ public function __construct(array $values = array()) { list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values); parent::__construct($parentValues); if (!array_key_exists(__CLASS__, self::$properties)) { self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes); } if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) { self::$xmlNamespaces[__CLASS__] = 'urn:ebay:apis:eBLBaseComponents'; } $this->setValues(__CLASS__, $childValues); } }
apache-2.0
YorkUIRLab/irlab
lib/lucene-6.0.1/docs/benchmark/org/apache/lucene/benchmark/byTask/feeds/class-use/ReutersContentSource.html
5350
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_77) on Mon May 23 19:37:04 EDT 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Uses of Class org.apache.lucene.benchmark.byTask.feeds.ReutersContentSource (Lucene 6.0.1 API)</title> <meta name="date" content="2016-05-23"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.lucene.benchmark.byTask.feeds.ReutersContentSource (Lucene 6.0.1 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/apache/lucene/benchmark/byTask/feeds/ReutersContentSource.html" title="class in org.apache.lucene.benchmark.byTask.feeds">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/lucene/benchmark/byTask/feeds/class-use/ReutersContentSource.html" target="_top">Frames</a></li> <li><a href="ReutersContentSource.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.lucene.benchmark.byTask.feeds.ReutersContentSource" class="title">Uses of Class<br>org.apache.lucene.benchmark.byTask.feeds.ReutersContentSource</h2> </div> <div class="classUseContainer">No usage of org.apache.lucene.benchmark.byTask.feeds.ReutersContentSource</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/apache/lucene/benchmark/byTask/feeds/ReutersContentSource.html" title="class in org.apache.lucene.benchmark.byTask.feeds">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/lucene/benchmark/byTask/feeds/class-use/ReutersContentSource.html" target="_top">Frames</a></li> <li><a href="ReutersContentSource.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <i>Copyright &copy; 2000-2016 Apache Software Foundation. All Rights Reserved.</i> <script src='../../../../../../../prettify.js' type='text/javascript'></script> <script type='text/javascript'> (function(){ var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = prettyPrint; } else { window.onload = function() { oldonload(); prettyPrint(); } } })(); </script> </small></p> </body> </html>
apache-2.0
chimerast/niconico-speenya
messages/index.ts
389
export interface CommentJson { body: string; color?: string; size?: number; duration?: number; easing?: string; } export interface StampJson { path?: string; url?: string; duration?: number; easing?: string; } export interface Setting { key: string; value: string; } export interface Stamp { id: number; label: string; path: string; contentType: string; }
apache-2.0
mlaggner/tinyMediaManager
src/org/tinymediamanager/core/movie/MovieSettings.java
32049
/* * Copyright 2012 - 2015 Manuel Laggner * * 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.tinymediamanager.core.movie; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import org.jdesktop.observablecollections.ObservableCollections; import org.tinymediamanager.core.AbstractModelObject; import org.tinymediamanager.core.movie.connector.MovieConnectors; import org.tinymediamanager.scraper.CountryCode; import org.tinymediamanager.scraper.MediaArtwork.FanartSizes; import org.tinymediamanager.scraper.MediaArtwork.PosterSizes; import org.tinymediamanager.scraper.MediaLanguages; /** * The Class MovieSettings. */ @XmlRootElement(name = "MovieSettings") public class MovieSettings extends AbstractModelObject { private final static String PATH = "path"; private final static String FILENAME = "filename"; private final static String MOVIE_DATA_SOURCE = "movieDataSource"; private final static String IMAGE_POSTER_SIZE = "imagePosterSize"; private final static String IMAGE_FANART_SIZE = "imageFanartSize"; private final static String IMAGE_EXTRATHUMBS = "imageExtraThumbs"; private final static String IMAGE_EXTRATHUMBS_RESIZE = "imageExtraThumbsResize"; private final static String IMAGE_EXTRATHUMBS_SIZE = "imageExtraThumbsSize"; private final static String IMAGE_EXTRATHUMBS_COUNT = "imageExtraThumbsCount"; private final static String IMAGE_EXTRAFANART = "imageExtraFanart"; private final static String IMAGE_EXTRAFANART_COUNT = "imageExtraFanartCount"; private final static String ENABLE_MOVIESET_ARTWORK_MOVIE_FOLDER = "enableMovieSetArtworkMovieFolder"; private final static String ENABLE_MOVIESET_ARTWORK_FOLDER = "enableMovieSetArtworkFolder"; private final static String MOVIESET_ARTWORK_FOLDER = "movieSetArtworkFolder"; private final static String MOVIE_CONNECTOR = "movieConnector"; private final static String MOVIE_NFO_FILENAME = "movieNfoFilename"; private final static String MOVIE_POSTER_FILENAME = "moviePosterFilename"; private final static String MOVIE_FANART_FILENAME = "movieFanartFilename"; private final static String MOVIE_RENAMER_PATHNAME = "movieRenamerPathname"; private final static String MOVIE_RENAMER_FILENAME = "movieRenamerFilename"; private final static String MOVIE_RENAMER_SPACE_SUBSTITUTION = "movieRenamerSpaceSubstitution"; private final static String MOVIE_RENAMER_SPACE_REPLACEMENT = "movieRenamerSpaceReplacement"; private final static String MOVIE_RENAMER_NFO_CLEANUP = "movieRenamerNfoCleanup"; private final static String MOVIE_RENAMER_MOVIESET_SINGLE_MOVIE = "movieRenamerMoviesetSingleMovie"; private final static String MOVIE_SCRAPER = "movieScraper"; private final static String SCRAPE_BEST_IMAGE = "scrapeBestImage"; private final static String IMAGE_SCRAPER_TMDB = "imageScraperTmdb"; private final static String IMAGE_SCRAPER_FANART_TV = "imageScraperFanartTv"; private final static String TRAILER_SCRAPER_TMDB = "trailerScraperTmdb"; private final static String TRAILER_SCRAPER_HD_TRAILERS = "trailerScraperHdTrailers"; private final static String TRAILER_SCRAPER_OFDB = "trailerScraperOfdb"; private final static String WRITE_ACTOR_IMAGES = "writeActorImages"; private final static String IMDB_SCRAPE_FOREIGN_LANGU = "imdbScrapeForeignLanguage"; private final static String SCRAPER_LANGU = "scraperLanguage"; private final static String CERTIFICATION_COUNTRY = "certificationCountry"; private final static String SCRAPER_THRESHOLD = "scraperThreshold"; private final static String DETECT_MOVIE_MULTI_DIR = "detectMovieMultiDir"; private final static String BUILD_IMAGE_CACHE_ON_IMPORT = "buildImageCacheOnImport"; private final static String BAD_WORDS = "badWords"; private final static String ENTRY = "entry"; private final static String RUNTIME_FROM_MI = "runtimeFromMediaInfo"; private final static String ASCII_REPLACEMENT = "asciiReplacement"; private final static String YEAR_COLUMN_VISIBLE = "yearColumnVisible"; private final static String NFO_COLUMN_VISIBLE = "nfoColumnVisible"; private final static String IMAGE_COLUMN_VISIBLE = "imageColumnVisible"; private final static String TRAILER_COLUMN_VISIBLE = "trailerColumnVisible"; private final static String SUBTITLE_COLUMN_VISIBLE = "subtitleColumnVisible"; private final static String WATCHED_COLUMN_VISIBLE = "watchedColumnVisible"; private final static String SCRAPER_FALLBACK = "scraperFallback"; @XmlElementWrapper(name = MOVIE_DATA_SOURCE) @XmlElement(name = PATH) private final List<String> movieDataSources = ObservableCollections.observableList(new ArrayList<String>()); @XmlElementWrapper(name = MOVIE_NFO_FILENAME) @XmlElement(name = FILENAME) private final List<MovieNfoNaming> movieNfoFilenames = new ArrayList<MovieNfoNaming>(); @XmlElementWrapper(name = MOVIE_POSTER_FILENAME) @XmlElement(name = FILENAME) private final List<MoviePosterNaming> moviePosterFilenames = new ArrayList<MoviePosterNaming>(); @XmlElementWrapper(name = MOVIE_FANART_FILENAME) @XmlElement(name = FILENAME) private final List<MovieFanartNaming> movieFanartFilenames = new ArrayList<MovieFanartNaming>(); @XmlElementWrapper(name = BAD_WORDS) @XmlElement(name = ENTRY) private final List<String> badWords = ObservableCollections.observableList(new ArrayList<String>()); private MovieConnectors movieConnector = MovieConnectors.XBMC; private String movieRenamerPathname = "$T ($Y)"; private String movieRenamerFilename = "$T ($Y) $V $A"; private boolean movieRenamerSpaceSubstitution = false; private String movieRenamerSpaceReplacement = "_"; private boolean movieRenamerNfoCleanup = false; private boolean imdbScrapeForeignLanguage = false; private MovieScrapers movieScraper = MovieScrapers.TMDB; private PosterSizes imagePosterSize = PosterSizes.BIG; private boolean imageScraperTmdb = true; private boolean imageScraperFanartTv = true; private FanartSizes imageFanartSize = FanartSizes.LARGE; private boolean imageExtraThumbs = false; private boolean imageExtraThumbsResize = true; private int imageExtraThumbsSize = 300; private int imageExtraThumbsCount = 5; private boolean imageExtraFanart = false; private int imageExtraFanartCount = 5; private boolean enableMovieSetArtworkMovieFolder = true; private boolean enableMovieSetArtworkFolder = false; private String movieSetArtworkFolder = "MoviesetArtwork"; private boolean scrapeBestImage = true; private boolean imageLanguagePriority = true; private boolean imageLogo = false; private boolean imageBanner = false; private boolean imageClearart = false; private boolean imageDiscart = false; private boolean imageThumb = false; private boolean trailerScraperTmdb = true; private boolean trailerScraperHdTrailers = true; private boolean trailerScraperOfdb = true; private boolean writeActorImages = false; private MediaLanguages scraperLanguage = MediaLanguages.en; private CountryCode certificationCountry = CountryCode.US; private double scraperThreshold = 0.75; private boolean detectMovieMultiDir = false; private boolean buildImageCacheOnImport = false; private boolean movieRenamerCreateMoviesetForSingleMovie = false; private boolean runtimeFromMediaInfo = false; private boolean asciiReplacement = false; private boolean yearColumnVisible = true; private boolean ratingColumnVisible = true; private boolean nfoColumnVisible = true; private boolean imageColumnVisible = true; private boolean trailerColumnVisible = true; private boolean subtitleColumnVisible = true; private boolean watchedColumnVisible = true; private boolean scraperFallback = false; private boolean useTrailerPreference = false; private MovieTrailerQuality trailerQuality = MovieTrailerQuality.HD_720; private MovieTrailerSources trailerSource = MovieTrailerSources.YOUTUBE; private boolean syncTrakt = false; public MovieSettings() { } public void addMovieDataSources(String path) { if (!movieDataSources.contains(path)) { movieDataSources.add(path); firePropertyChange(MOVIE_DATA_SOURCE, null, movieDataSources); } } public void removeMovieDataSources(String path) { MovieList movieList = MovieList.getInstance(); movieList.removeDatasource(path); movieDataSources.remove(path); firePropertyChange(MOVIE_DATA_SOURCE, null, movieDataSources); } public List<String> getMovieDataSource() { return movieDataSources; } public void addMovieNfoFilename(MovieNfoNaming filename) { if (!movieNfoFilenames.contains(filename)) { movieNfoFilenames.add(filename); firePropertyChange(MOVIE_NFO_FILENAME, null, movieNfoFilenames); } } public void removeMovieNfoFilename(MovieNfoNaming filename) { if (movieNfoFilenames.contains(filename)) { movieNfoFilenames.remove(filename); firePropertyChange(MOVIE_NFO_FILENAME, null, movieNfoFilenames); } } public void clearMovieNfoFilenames() { movieNfoFilenames.clear(); firePropertyChange(MOVIE_NFO_FILENAME, null, movieNfoFilenames); } public List<MovieNfoNaming> getMovieNfoFilenames() { return new ArrayList<MovieNfoNaming>(this.movieNfoFilenames); } public void addMoviePosterFilename(MoviePosterNaming filename) { if (!moviePosterFilenames.contains(filename)) { moviePosterFilenames.add(filename); firePropertyChange(MOVIE_POSTER_FILENAME, null, moviePosterFilenames); } } public void removeMoviePosterFilename(MoviePosterNaming filename) { if (moviePosterFilenames.contains(filename)) { moviePosterFilenames.remove(filename); firePropertyChange(MOVIE_POSTER_FILENAME, null, moviePosterFilenames); } } public void clearMoviePosterFilenames() { moviePosterFilenames.clear(); firePropertyChange(MOVIE_POSTER_FILENAME, null, moviePosterFilenames); } public List<MoviePosterNaming> getMoviePosterFilenames() { return new ArrayList<MoviePosterNaming>(this.moviePosterFilenames); } public void addMovieFanartFilename(MovieFanartNaming filename) { if (!movieFanartFilenames.contains(filename)) { movieFanartFilenames.add(filename); firePropertyChange(MOVIE_FANART_FILENAME, null, movieFanartFilenames); } } public void removeMovieFanartFilename(MovieFanartNaming filename) { if (movieFanartFilenames.contains(filename)) { movieFanartFilenames.remove(filename); firePropertyChange(MOVIE_FANART_FILENAME, null, movieFanartFilenames); } } public void clearMovieFanartFilenames() { movieFanartFilenames.clear(); firePropertyChange(MOVIE_FANART_FILENAME, null, movieFanartFilenames); } public List<MovieFanartNaming> getMovieFanartFilenames() { return new ArrayList<MovieFanartNaming>(this.movieFanartFilenames); } @XmlElement(name = IMAGE_POSTER_SIZE) public PosterSizes getImagePosterSize() { return imagePosterSize; } public void setImagePosterSize(PosterSizes newValue) { PosterSizes oldValue = this.imagePosterSize; this.imagePosterSize = newValue; firePropertyChange(IMAGE_POSTER_SIZE, oldValue, newValue); } @XmlElement(name = IMAGE_FANART_SIZE) public FanartSizes getImageFanartSize() { return imageFanartSize; } public void setImageFanartSize(FanartSizes newValue) { FanartSizes oldValue = this.imageFanartSize; this.imageFanartSize = newValue; firePropertyChange(IMAGE_FANART_SIZE, oldValue, newValue); } public boolean isImageExtraThumbs() { return imageExtraThumbs; } public boolean isImageExtraThumbsResize() { return imageExtraThumbsResize; } public int getImageExtraThumbsSize() { return imageExtraThumbsSize; } public void setImageExtraThumbsResize(boolean newValue) { boolean oldValue = this.imageExtraThumbsResize; this.imageExtraThumbsResize = newValue; firePropertyChange(IMAGE_EXTRATHUMBS_RESIZE, oldValue, newValue); } public void setImageExtraThumbsSize(int newValue) { int oldValue = this.imageExtraThumbsSize; this.imageExtraThumbsSize = newValue; firePropertyChange(IMAGE_EXTRATHUMBS_SIZE, oldValue, newValue); } public int getImageExtraThumbsCount() { return imageExtraThumbsCount; } public void setImageExtraThumbsCount(int newValue) { int oldValue = this.imageExtraThumbsCount; this.imageExtraThumbsCount = newValue; firePropertyChange(IMAGE_EXTRATHUMBS_COUNT, oldValue, newValue); } public int getImageExtraFanartCount() { return imageExtraFanartCount; } public void setImageExtraFanartCount(int newValue) { int oldValue = this.imageExtraFanartCount; this.imageExtraFanartCount = newValue; firePropertyChange(IMAGE_EXTRAFANART_COUNT, oldValue, newValue); } public boolean isImageExtraFanart() { return imageExtraFanart; } public void setImageExtraThumbs(boolean newValue) { boolean oldValue = this.imageExtraThumbs; this.imageExtraThumbs = newValue; firePropertyChange(IMAGE_EXTRATHUMBS, oldValue, newValue); } public void setImageExtraFanart(boolean newValue) { boolean oldValue = this.imageExtraFanart; this.imageExtraFanart = newValue; firePropertyChange(IMAGE_EXTRAFANART, oldValue, newValue); } public boolean isEnableMovieSetArtworkMovieFolder() { return enableMovieSetArtworkMovieFolder; } public void setEnableMovieSetArtworkMovieFolder(boolean newValue) { boolean oldValue = this.enableMovieSetArtworkMovieFolder; this.enableMovieSetArtworkMovieFolder = newValue; firePropertyChange(ENABLE_MOVIESET_ARTWORK_MOVIE_FOLDER, oldValue, newValue); } public boolean isEnableMovieSetArtworkFolder() { return enableMovieSetArtworkFolder; } public void setEnableMovieSetArtworkFolder(boolean newValue) { boolean oldValue = this.enableMovieSetArtworkFolder; this.enableMovieSetArtworkFolder = newValue; firePropertyChange(ENABLE_MOVIESET_ARTWORK_FOLDER, oldValue, newValue); } public String getMovieSetArtworkFolder() { return movieSetArtworkFolder; } public void setMovieSetArtworkFolder(String newValue) { String oldValue = this.movieSetArtworkFolder; this.movieSetArtworkFolder = newValue; firePropertyChange(MOVIESET_ARTWORK_FOLDER, oldValue, newValue); } @XmlElement(name = MOVIE_CONNECTOR) public MovieConnectors getMovieConnector() { return movieConnector; } public void setMovieConnector(MovieConnectors newValue) { MovieConnectors oldValue = this.movieConnector; this.movieConnector = newValue; firePropertyChange(MOVIE_CONNECTOR, oldValue, newValue); } @XmlElement(name = MOVIE_RENAMER_PATHNAME) public String getMovieRenamerPathname() { return movieRenamerPathname; } public void setMovieRenamerPathname(String newValue) { String oldValue = this.movieRenamerPathname; this.movieRenamerPathname = newValue; firePropertyChange(MOVIE_RENAMER_PATHNAME, oldValue, newValue); } @XmlElement(name = MOVIE_RENAMER_FILENAME) public String getMovieRenamerFilename() { return movieRenamerFilename; } public void setMovieRenamerFilename(String newValue) { String oldValue = this.movieRenamerFilename; this.movieRenamerFilename = newValue; firePropertyChange(MOVIE_RENAMER_FILENAME, oldValue, newValue); } @XmlElement(name = MOVIE_RENAMER_SPACE_SUBSTITUTION) public boolean isMovieRenamerSpaceSubstitution() { return movieRenamerSpaceSubstitution; } public void setMovieRenamerSpaceSubstitution(boolean movieRenamerSpaceSubstitution) { this.movieRenamerSpaceSubstitution = movieRenamerSpaceSubstitution; } @XmlElement(name = MOVIE_RENAMER_SPACE_REPLACEMENT) public String getMovieRenamerSpaceReplacement() { return movieRenamerSpaceReplacement; } public void setMovieRenamerSpaceReplacement(String movieRenamerSpaceReplacement) { this.movieRenamerSpaceReplacement = movieRenamerSpaceReplacement; } public MovieScrapers getMovieScraper() { if (movieScraper == null) { return MovieScrapers.TMDB; } return movieScraper; } public void setMovieScraper(MovieScrapers newValue) { MovieScrapers oldValue = this.movieScraper; this.movieScraper = newValue; firePropertyChange(MOVIE_SCRAPER, oldValue, newValue); } public boolean isImdbScrapeForeignLanguage() { return imdbScrapeForeignLanguage; } public void setImdbScrapeForeignLanguage(boolean newValue) { boolean oldValue = this.imdbScrapeForeignLanguage; this.imdbScrapeForeignLanguage = newValue; firePropertyChange(IMDB_SCRAPE_FOREIGN_LANGU, oldValue, newValue); } public boolean isImageScraperTmdb() { return imageScraperTmdb; } public boolean isImageScraperFanartTv() { return imageScraperFanartTv; } public void setImageScraperTmdb(boolean newValue) { boolean oldValue = this.imageScraperTmdb; this.imageScraperTmdb = newValue; firePropertyChange(IMAGE_SCRAPER_TMDB, oldValue, newValue); } public void setImageScraperFanartTv(boolean newValue) { boolean oldValue = this.imageScraperFanartTv; this.imageScraperFanartTv = newValue; firePropertyChange(IMAGE_SCRAPER_FANART_TV, oldValue, newValue); } public boolean isScrapeBestImage() { return scrapeBestImage; } public void setScrapeBestImage(boolean newValue) { boolean oldValue = this.scrapeBestImage; this.scrapeBestImage = newValue; firePropertyChange(SCRAPE_BEST_IMAGE, oldValue, newValue); } public boolean isTrailerScraperTmdb() { return trailerScraperTmdb; } public boolean isTrailerScraperHdTrailers() { return trailerScraperHdTrailers; } public void setTrailerScraperTmdb(boolean newValue) { boolean oldValue = this.trailerScraperTmdb; this.trailerScraperTmdb = newValue; firePropertyChange(TRAILER_SCRAPER_TMDB, oldValue, newValue); } public void setTrailerScraperHdTrailers(boolean newValue) { boolean oldValue = this.trailerScraperHdTrailers; this.trailerScraperHdTrailers = newValue; firePropertyChange(TRAILER_SCRAPER_HD_TRAILERS, oldValue, newValue); } public boolean isTrailerScraperOfdb() { return trailerScraperOfdb; } public void setTrailerScraperOfdb(boolean newValue) { boolean oldValue = this.trailerScraperOfdb; this.trailerScraperOfdb = newValue; firePropertyChange(TRAILER_SCRAPER_OFDB, oldValue, newValue); } public boolean isWriteActorImages() { return writeActorImages; } public void setWriteActorImages(boolean newValue) { boolean oldValue = this.writeActorImages; this.writeActorImages = newValue; firePropertyChange(WRITE_ACTOR_IMAGES, oldValue, newValue); } @XmlElement(name = SCRAPER_LANGU) public MediaLanguages getScraperLanguage() { return scraperLanguage; } public void setScraperLanguage(MediaLanguages newValue) { MediaLanguages oldValue = this.scraperLanguage; this.scraperLanguage = newValue; firePropertyChange(SCRAPER_LANGU, oldValue, newValue); } @XmlElement(name = CERTIFICATION_COUNTRY) public CountryCode getCertificationCountry() { return certificationCountry; } public void setCertificationCountry(CountryCode newValue) { CountryCode oldValue = this.certificationCountry; certificationCountry = newValue; firePropertyChange(CERTIFICATION_COUNTRY, oldValue, newValue); } @XmlElement(name = SCRAPER_THRESHOLD) public double getScraperThreshold() { return scraperThreshold; } public void setScraperThreshold(double newValue) { double oldValue = this.scraperThreshold; scraperThreshold = newValue; firePropertyChange(SCRAPER_THRESHOLD, oldValue, newValue); } @XmlElement(name = MOVIE_RENAMER_NFO_CLEANUP) public boolean isMovieRenamerNfoCleanup() { return movieRenamerNfoCleanup; } public void setMovieRenamerNfoCleanup(boolean movieRenamerNfoCleanup) { this.movieRenamerNfoCleanup = movieRenamerNfoCleanup; } /** * Should we detect (and create) movies from directories containing more than one movie? * * @return true/false */ public boolean isDetectMovieMultiDir() { return detectMovieMultiDir; } /** * Should we detect (and create) movies from directories containing more than one movie? * * @param newValue * true/false */ public void setDetectMovieMultiDir(boolean newValue) { boolean oldValue = this.detectMovieMultiDir; this.detectMovieMultiDir = newValue; firePropertyChange(DETECT_MOVIE_MULTI_DIR, oldValue, newValue); } public boolean isBuildImageCacheOnImport() { return buildImageCacheOnImport; } public void setBuildImageCacheOnImport(boolean newValue) { boolean oldValue = this.buildImageCacheOnImport; this.buildImageCacheOnImport = newValue; firePropertyChange(BUILD_IMAGE_CACHE_ON_IMPORT, oldValue, newValue); } public boolean isMovieRenamerCreateMoviesetForSingleMovie() { return movieRenamerCreateMoviesetForSingleMovie; } public void setMovieRenamerCreateMoviesetForSingleMovie(boolean newValue) { boolean oldValue = this.movieRenamerCreateMoviesetForSingleMovie; this.movieRenamerCreateMoviesetForSingleMovie = newValue; firePropertyChange(MOVIE_RENAMER_MOVIESET_SINGLE_MOVIE, oldValue, newValue); } public boolean isRuntimeFromMediaInfo() { return runtimeFromMediaInfo; } public void setRuntimeFromMediaInfo(boolean newValue) { boolean oldValue = this.runtimeFromMediaInfo; this.runtimeFromMediaInfo = newValue; firePropertyChange(RUNTIME_FROM_MI, oldValue, newValue); } public boolean isAsciiReplacement() { return asciiReplacement; } public void setAsciiReplacement(boolean newValue) { boolean oldValue = this.asciiReplacement; this.asciiReplacement = newValue; firePropertyChange(ASCII_REPLACEMENT, oldValue, newValue); } public void addBadWord(String badWord) { if (!badWords.contains(badWord.toLowerCase())) { badWords.add(badWord.toLowerCase()); firePropertyChange(BAD_WORDS, null, badWords); } } public void removeBadWord(String badWord) { badWords.remove(badWord.toLowerCase()); firePropertyChange(BAD_WORDS, null, badWords); } public List<String> getBadWords() { // convert to lowercase for easy contains checking ListIterator<String> iterator = badWords.listIterator(); while (iterator.hasNext()) { iterator.set(iterator.next().toLowerCase()); } return badWords; } public boolean isYearColumnVisible() { return yearColumnVisible; } public void setYearColumnVisible(boolean newValue) { boolean oldValue = this.yearColumnVisible; this.yearColumnVisible = newValue; firePropertyChange(YEAR_COLUMN_VISIBLE, oldValue, newValue); } public boolean isRatingColumnVisible() { return ratingColumnVisible; } public void setRatingColumnVisible(boolean newValue) { boolean oldValue = this.ratingColumnVisible; this.ratingColumnVisible = newValue; firePropertyChange("ratingColumnVisible", oldValue, newValue); } public boolean isNfoColumnVisible() { return nfoColumnVisible; } public void setNfoColumnVisible(boolean newValue) { boolean oldValue = this.nfoColumnVisible; this.nfoColumnVisible = newValue; firePropertyChange(NFO_COLUMN_VISIBLE, oldValue, newValue); } public boolean isImageColumnVisible() { return imageColumnVisible; } public void setImageColumnVisible(boolean newValue) { boolean oldValue = this.imageColumnVisible; this.imageColumnVisible = newValue; firePropertyChange(IMAGE_COLUMN_VISIBLE, oldValue, newValue); } public boolean isTrailerColumnVisible() { return trailerColumnVisible; } public void setTrailerColumnVisible(boolean newValue) { boolean oldValue = this.trailerColumnVisible; this.trailerColumnVisible = newValue; firePropertyChange(TRAILER_COLUMN_VISIBLE, oldValue, newValue); } public boolean isSubtitleColumnVisible() { return subtitleColumnVisible; } public void setSubtitleColumnVisible(boolean newValue) { boolean oldValue = this.subtitleColumnVisible; this.subtitleColumnVisible = newValue; firePropertyChange(SUBTITLE_COLUMN_VISIBLE, oldValue, newValue); } public boolean isWatchedColumnVisible() { return watchedColumnVisible; } public void setWatchedColumnVisible(boolean newValue) { boolean oldValue = this.watchedColumnVisible; this.watchedColumnVisible = newValue; firePropertyChange(WATCHED_COLUMN_VISIBLE, oldValue, newValue); } public boolean isScraperFallback() { return scraperFallback; } public void setScraperFallback(boolean newValue) { boolean oldValue = this.scraperFallback; this.scraperFallback = newValue; firePropertyChange(SCRAPER_FALLBACK, oldValue, newValue); } public boolean isImageLogo() { return imageLogo; } public boolean isImageBanner() { return imageBanner; } public boolean isImageClearart() { return imageClearart; } public boolean isImageDiscart() { return imageDiscart; } public boolean isImageThumb() { return imageThumb; } public void setImageLogo(boolean newValue) { boolean oldValue = this.imageLogo; this.imageLogo = newValue; firePropertyChange("imageLogo", oldValue, newValue); } public void setImageBanner(boolean newValue) { boolean oldValue = this.imageBanner; this.imageBanner = newValue; firePropertyChange("imageBanner", oldValue, newValue); } public void setImageClearart(boolean newValue) { boolean oldValue = this.imageClearart; this.imageClearart = newValue; firePropertyChange("imageClearart", oldValue, newValue); } public void setImageDiscart(boolean newValue) { boolean oldValue = this.imageDiscart; this.imageDiscart = newValue; firePropertyChange("imageDiscart", oldValue, newValue); } public void setImageThumb(boolean newValue) { boolean oldValue = this.imageThumb; this.imageThumb = newValue; firePropertyChange("imageThumb", oldValue, newValue); } public boolean isUseTrailerPreference() { return useTrailerPreference; } public void setUseTrailerPreference(boolean newValue) { boolean oldValue = this.useTrailerPreference; this.useTrailerPreference = newValue; firePropertyChange("useTrailerPreference", oldValue, newValue); } public MovieTrailerQuality getTrailerQuality() { return trailerQuality; } public void setTrailerQuality(MovieTrailerQuality newValue) { MovieTrailerQuality oldValue = this.trailerQuality; this.trailerQuality = newValue; firePropertyChange("trailerQuality", oldValue, newValue); } public MovieTrailerSources getTrailerSource() { return trailerSource; } public void setTrailerSource(MovieTrailerSources newValue) { MovieTrailerSources oldValue = this.trailerSource; this.trailerSource = newValue; firePropertyChange("trailerSource", oldValue, newValue); } public void setSyncTrakt(boolean newValue) { boolean oldValue = this.syncTrakt; this.syncTrakt = newValue; firePropertyChange("syncTrakt", oldValue, newValue); } public boolean getSyncTrakt() { return syncTrakt; } public boolean isImageLanguagePriority() { return imageLanguagePriority; } public void setImageLanguagePriority(boolean newValue) { boolean oldValue = this.imageLanguagePriority; this.imageLanguagePriority = newValue; firePropertyChange("imageLanguagePriority", oldValue, newValue); } }
apache-2.0
stdlib-js/stdlib
lib/node_modules/@stdlib/utils/async/some-by/lib/some_by.js
3300
/** * @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'; // MODULES // var factory = require( './factory.js' ); // MAIN // /** * Tests whether a collection contains at least `n` elements which pass a test implemented by a predicate function. * * ## Notes * * - If a predicate function calls the provided callback with a truthy error argument, the function suspends execution and immediately calls the `done` callback for subsequent error handling. * - This function does **not** guarantee that execution is asynchronous. To do so, wrap the `done` callback in a function which either executes at the end of the current stack (e.g., `nextTick`) or during a subsequent turn of the event loop (e.g., `setImmediate`, `setTimeout`). * * * @param {Collection} collection - input collection * @param {PositiveInteger} n - number of elements * @param {Options} [options] - function options * @param {*} [options.thisArg] - execution context * @param {PositiveInteger} [options.limit] - maximum number of pending invocations at any one time * @param {boolean} [options.series=false] - boolean indicating whether to wait for a previous invocation to complete before invoking a provided function for the next element in a collection * @param {Function} predicate - predicate function to invoke for each element in a collection * @param {Callback} done - function to invoke upon completion * @throws {TypeError} first argument must be a collection * @throws {TypeError} second argument must be a positive integer * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @throws {TypeError} second-to-last argument must be a function * @throws {TypeError} last argument must be a function * @returns {void} * * @example * var readFile = require( '@stdlib/fs/read-file' ); * * function done( error, bool ) { * if ( error ) { * throw error; * } * if ( bool ) { * console.log( 'Successfully read some files.' ); * } else { * console.log( 'Unable to read some files.' ); * } * } * * function predicate( file, next ) { * var opts = { * 'encoding': 'utf8' * }; * readFile( file, opts, onFile ); * * function onFile( error ) { * if ( error ) { * return next( null, false ); * } * next( null, true ); * } * } * * var files = [ * './beep.js', * './boop.js' * ]; * * someByAsync( files, 2, predicate, done ); */ function someByAsync( collection, n, options, predicate, done ) { if ( arguments.length < 5 ) { return factory( options )( collection, n, predicate ); } factory( options, predicate )( collection, n, done ); } // EXPORTS // module.exports = someByAsync;
apache-2.0
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Lamiaceae/Clinopodium/Clinopodium densiflorum/README.md
180
# Clinopodium densiflorum Kuntze SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
apache-2.0
neuneu2k/SEL
JetbrainsPlugin/src/fr/assoba/open/sel/jetbrains/SelElementType.java
923
/* * Copyright 2014 Josselin Pujo * * 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 fr.assoba.open.sel.jetbrains; import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; public class SelElementType extends IElementType { public SelElementType(@NotNull @NonNls String debugName) { super(debugName, SelLanguage.INSTANCE); } }
apache-2.0
offerHere/offer
app/src/main/java/com/hxtech/offer/fragments/CanonFragment.java
877
package com.hxtech.offer.fragments; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.hxtech.offer.R; public class CanonFragment extends BaseFragment { public static CanonFragment newInstance() { CanonFragment fragment = new CanonFragment(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } public CanonFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_canon, container, false); } }
apache-2.0
sunhai1988/nutz-book-project
src/main/resources/doc/ngrok.md
1362
### Ngrok内网穿透神器 ### 使用原则 供Nutz社区的用户开发Nutz相关的项目时使用 ### 下载链接 ** 注意: 已单独部署为域名 wendal.cn ** [配置文件](/ngrok/config/download) [Ngrok客户端v1.x 不支持2.x客户端](https://ngrok.com/download/1) http://pan.baidu.com/s/1eQptxvk 客户端网盘地址 ### 使用方法 下载配置文件(ngrok.yml)及客户端后, 启动之, 以转发到8080端口为例 ``` ngrok -config ngrok.yml 8080 ``` 等待出现如下信息, 请注意,子域名与用户名是绑定的,不允许自定义 ``` ngrok Tunnel Status online Version 1.7/1.7 Forwarding http://wendal.ngrok.wendal.cn:9080 -> 127.0.0.1:8080 Forwarding https://wendal.ngrok.wendal.cn:9080 -> 127.0.0.1:8080 Web Interface 127.0.0.1:4040 # Conn 0 Avg Conn Time 1.59ms HTTP Requests ------------- GET /nutzbook/rs/logo.png 200 OK ``` 本地启动tomcat或其他web应用后, 访问对应的地址即可(替换成自己的地址哦) ``` http://wendal.ngrok.wendal.cn/nutzbook/ http://wendal.ngrok.wendal.cn:9080/nutzbook/ ``` ### 注意事项 1. 可以通过80端口访问,经由nginx转发,最长链接10分钟,最大POST body大小为1mb 2. 本服务的可用性保证是95%
apache-2.0
google/xls
xls/tools/io_strategy.h
3479
// Copyright 2020 The XLS 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. #ifndef XLS_TOOLS_IO_STRATEGY_H_ #define XLS_TOOLS_IO_STRATEGY_H_ #include "absl/status/status.h" #include "absl/status/statusor.h" #include "xls/codegen/vast.h" #include "xls/tools/verilog_include.h" namespace xls { namespace verilog { // Represents a pluggable strategy for wiring up I/O in the uncore. // // The I/O strategy gets to add top-level dependencies (e.g. sourcing top-level // pins from the outside world), then is asked to instantiate I/O blocks for // communicating the byte transport (via output.tx_byte and input.rx_byte). // // The ready/valid signaling presented here (in the Input / Output types) is the // way host I/O is exposed to the uncore. class IoStrategy { public: // Signals related to sending output (i.e. to the host). // // These connect to the top-level state machine that manages device RPCs. struct Output { // Byte to transfer to the host (driven externally, into the I/O block). LogicRef* tx_byte; // Whether tx_byte holds valid data (driven externally, into the I/O block). LogicRef* tx_byte_valid; // Signals that the transmitter is done processing the tx_byte value and is // ready to receive a new value (driven internally, from the I/O block). LogicRef* tx_byte_ready; }; // Signals related to accepting input (i.e. from the host). // // These connect to the top-level state machine that manages device RPCs. struct Input { // Byte that has been received from the host (driven from the I/O block). LogicRef* rx_byte; // Whether rx_byte contains valid data (driven from the I/O block). LogicRef* rx_byte_valid; // Signals that the device is done processing the rx_byte value (driven // externally). LogicRef* rx_byte_done; }; virtual ~IoStrategy() = default; // Adds any top-level signals as input/output ports of "m" that are required // for the I/O. // // For example, on ICE40 this ensures that the tx/rx signals are present on // the top level of the design for binding to those known top-level pins. virtual absl::Status AddTopLevelDependencies(LogicRef* clk, Reset reset, Module* m) = 0; // Instantiates transmitter/receiver blocks that operate in byte-wise fashion // and connects them to the "input" and "output" signals. virtual absl::Status InstantiateIoBlocks(Input input, Output output, Module* m) = 0; // Returns the set of inclusions tick-included by the Verilog generated by the // IO strategy. Each VerilogInclude specifies the relative path that the file // is included with (eg, "foo/bar.v" for "`include "foo/bar.v") and the // Verilog text of the included file. virtual absl::StatusOr<std::vector<VerilogInclude>> GetIncludes() = 0; }; } // namespace verilog } // namespace xls #endif // XLS_TOOLS_IO_STRATEGY_H_
apache-2.0
apple/swift-nio-ssl
Sources/CNIOBoringSSL/ssl/ssl_buffer.cc
8307
/* Copyright (c) 2015, Google Inc. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <CNIOBoringSSL_ssl.h> #include <assert.h> #include <limits.h> #include <stdlib.h> #include <string.h> #include <CNIOBoringSSL_bio.h> #include <CNIOBoringSSL_err.h> #include <CNIOBoringSSL_mem.h> #include "../crypto/internal.h" #include "internal.h" BSSL_NAMESPACE_BEGIN // BIO uses int instead of size_t. No lengths will exceed uint16_t, so this will // not overflow. static_assert(0xffff <= INT_MAX, "uint16_t does not fit in int"); static_assert((SSL3_ALIGN_PAYLOAD & (SSL3_ALIGN_PAYLOAD - 1)) == 0, "SSL3_ALIGN_PAYLOAD must be a power of 2"); void SSLBuffer::Clear() { if (buf_allocated_) { free(buf_); // Allocated with malloc(). } buf_ = nullptr; buf_allocated_ = false; offset_ = 0; size_ = 0; cap_ = 0; } bool SSLBuffer::EnsureCap(size_t header_len, size_t new_cap) { if (new_cap > 0xffff) { OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR); return false; } if (cap_ >= new_cap) { return true; } uint8_t *new_buf; bool new_buf_allocated; size_t new_offset; if (new_cap <= sizeof(inline_buf_)) { // This function is called twice per TLS record, first for the five-byte // header. To avoid allocating twice, use an inline buffer for short inputs. new_buf = inline_buf_; new_buf_allocated = false; new_offset = 0; } else { // Add up to |SSL3_ALIGN_PAYLOAD| - 1 bytes of slack for alignment. // // Since this buffer gets allocated quite frequently and doesn't contain any // sensitive data, we allocate with malloc rather than |OPENSSL_malloc| and // avoid zeroing on free. new_buf = (uint8_t *)malloc(new_cap + SSL3_ALIGN_PAYLOAD - 1); if (new_buf == NULL) { OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE); return false; } new_buf_allocated = true; // Offset the buffer such that the record body is aligned. new_offset = (0 - header_len - (uintptr_t)new_buf) & (SSL3_ALIGN_PAYLOAD - 1); } // Note if the both old and new buffer are inline, the source and destination // may alias. OPENSSL_memmove(new_buf + new_offset, buf_ + offset_, size_); if (buf_allocated_) { free(buf_); // Allocated with malloc(). } buf_ = new_buf; buf_allocated_ = new_buf_allocated; offset_ = new_offset; cap_ = new_cap; return true; } void SSLBuffer::DidWrite(size_t new_size) { if (new_size > cap() - size()) { abort(); } size_ += new_size; } void SSLBuffer::Consume(size_t len) { if (len > size_) { abort(); } offset_ += (uint16_t)len; size_ -= (uint16_t)len; cap_ -= (uint16_t)len; } void SSLBuffer::DiscardConsumed() { if (size_ == 0) { Clear(); } } static int dtls_read_buffer_next_packet(SSL *ssl) { SSLBuffer *buf = &ssl->s3->read_buffer; if (!buf->empty()) { // It is an error to call |dtls_read_buffer_extend| when the read buffer is // not empty. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR); return -1; } // Read a single packet from |ssl->rbio|. |buf->cap()| must fit in an int. int ret = BIO_read(ssl->rbio.get(), buf->data(), static_cast<int>(buf->cap())); if (ret <= 0) { ssl->s3->rwstate = SSL_ERROR_WANT_READ; return ret; } buf->DidWrite(static_cast<size_t>(ret)); return 1; } static int tls_read_buffer_extend_to(SSL *ssl, size_t len) { SSLBuffer *buf = &ssl->s3->read_buffer; if (len > buf->cap()) { OPENSSL_PUT_ERROR(SSL, SSL_R_BUFFER_TOO_SMALL); return -1; } // Read until the target length is reached. while (buf->size() < len) { // The amount of data to read is bounded by |buf->cap|, which must fit in an // int. int ret = BIO_read(ssl->rbio.get(), buf->data() + buf->size(), static_cast<int>(len - buf->size())); if (ret <= 0) { ssl->s3->rwstate = SSL_ERROR_WANT_READ; return ret; } buf->DidWrite(static_cast<size_t>(ret)); } return 1; } int ssl_read_buffer_extend_to(SSL *ssl, size_t len) { // |ssl_read_buffer_extend_to| implicitly discards any consumed data. ssl->s3->read_buffer.DiscardConsumed(); if (SSL_is_dtls(ssl)) { static_assert( DTLS1_RT_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH <= 0xffff, "DTLS read buffer is too large"); // The |len| parameter is ignored in DTLS. len = DTLS1_RT_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH; } if (!ssl->s3->read_buffer.EnsureCap(ssl_record_prefix_len(ssl), len)) { return -1; } if (ssl->rbio == nullptr) { OPENSSL_PUT_ERROR(SSL, SSL_R_BIO_NOT_SET); return -1; } int ret; if (SSL_is_dtls(ssl)) { // |len| is ignored for a datagram transport. ret = dtls_read_buffer_next_packet(ssl); } else { ret = tls_read_buffer_extend_to(ssl, len); } if (ret <= 0) { // If the buffer was empty originally and remained empty after attempting to // extend it, release the buffer until the next attempt. ssl->s3->read_buffer.DiscardConsumed(); } return ret; } int ssl_handle_open_record(SSL *ssl, bool *out_retry, ssl_open_record_t ret, size_t consumed, uint8_t alert) { *out_retry = false; if (ret != ssl_open_record_partial) { ssl->s3->read_buffer.Consume(consumed); } if (ret != ssl_open_record_success) { // Nothing was returned to the caller, so discard anything marked consumed. ssl->s3->read_buffer.DiscardConsumed(); } switch (ret) { case ssl_open_record_success: return 1; case ssl_open_record_partial: { int read_ret = ssl_read_buffer_extend_to(ssl, consumed); if (read_ret <= 0) { return read_ret; } *out_retry = true; return 1; } case ssl_open_record_discard: *out_retry = true; return 1; case ssl_open_record_close_notify: return 0; case ssl_open_record_error: if (alert != 0) { ssl_send_alert(ssl, SSL3_AL_FATAL, alert); } return -1; } assert(0); return -1; } static_assert(SSL3_RT_HEADER_LENGTH * 2 + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD * 2 + SSL3_RT_MAX_PLAIN_LENGTH <= 0xffff, "maximum TLS write buffer is too large"); static_assert(DTLS1_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD + SSL3_RT_MAX_PLAIN_LENGTH <= 0xffff, "maximum DTLS write buffer is too large"); static int tls_write_buffer_flush(SSL *ssl) { SSLBuffer *buf = &ssl->s3->write_buffer; while (!buf->empty()) { int ret = BIO_write(ssl->wbio.get(), buf->data(), buf->size()); if (ret <= 0) { ssl->s3->rwstate = SSL_ERROR_WANT_WRITE; return ret; } buf->Consume(static_cast<size_t>(ret)); } buf->Clear(); return 1; } static int dtls_write_buffer_flush(SSL *ssl) { SSLBuffer *buf = &ssl->s3->write_buffer; if (buf->empty()) { return 1; } int ret = BIO_write(ssl->wbio.get(), buf->data(), buf->size()); if (ret <= 0) { ssl->s3->rwstate = SSL_ERROR_WANT_WRITE; // If the write failed, drop the write buffer anyway. Datagram transports // can't write half a packet, so the caller is expected to retry from the // top. buf->Clear(); return ret; } buf->Clear(); return 1; } int ssl_write_buffer_flush(SSL *ssl) { if (ssl->wbio == nullptr) { OPENSSL_PUT_ERROR(SSL, SSL_R_BIO_NOT_SET); return -1; } if (SSL_is_dtls(ssl)) { return dtls_write_buffer_flush(ssl); } else { return tls_write_buffer_flush(ssl); } } BSSL_NAMESPACE_END
apache-2.0