repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
d/fruit
tests/late_binding_new.cpp
1291
// expect-success /* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <fruit/fruit.h> #include "test_macros.h" using fruit::Component; using fruit::Injector; struct X { INJECT(X()) = default; }; struct Y { INJECT(Y()) { Assert(!constructed); constructed = true; } static bool constructed; }; bool Y::constructed = false; struct Z { INJECT(Z()) = default; }; fruit::Component<Z, Y, X> getComponent() { return fruit::createComponent(); } int main() { fruit::NormalizedComponent<> normalizedComponent(fruit::createComponent()); Injector<Y> injector(normalizedComponent, getComponent()); Assert(!Y::constructed); injector.get<Y>(); Assert(Y::constructed); return 0; }
apache-2.0
thompsct/VPRKB
src/semsimKB/model/physical/DBCompositeEntity.java
3833
package semsimKB.model.physical; import java.net.URI; import org.apache.commons.lang3.tuple.Pair; import semsimKB.definitions.SemSimTypes; import semsimKB.definitions.StructuralRelation; public class DBCompositeEntity extends DBPhysicalComponent implements PhysicalEntity{ private Pair<PhysicalEntity, PhysicalEntity> componententities = null; protected StructuralRelation relation = StructuralRelation.PART_OF_RELATION; public DBCompositeEntity(Pair<PhysicalEntity,PhysicalEntity> entitiestoadd, StructuralRelation rel) { super(SemSimTypes.KB_COMPOSITE_ENTITY); componententities = entitiestoadd; relation = rel; createName(); } public DBCompositeEntity(URI uri, String label) { super(SemSimTypes.KB_COMPOSITE_ENTITY, uri, label); } private void createName() { Pair<String, String> names = getComponentNames(); String[] pe1name = names.getLeft().split(" "); String[] pe2name = names.getRight().split(" "); //Find where component entity names match, if they do int index = 0; for (int i= 0; i < pe2name.length; i++) { if (pe1name[pe1name.length-1].equalsIgnoreCase(pe2name[i])) { index = i+1; break; } } //If the index is less than the number of words in the name, it's a composite //Get the index of the first word following the relation if (index < pe2name.length) { if (pe2name[index].equalsIgnoreCase("part")) index = index+2; else if (pe2name[index].equalsIgnoreCase("in")) index = index+1; } else index = 0; String pe2 = ""; for (int i = index; i < pe2name.length; i++) { pe2 = pe2 + pe2name[i] + " "; } //Get rid of last space pe2 = pe2.trim(); String rel = " part of "; if (relation==StructuralRelation.CONTAINED_IN_RELATION) { rel = " in "; } setName(names.getLeft() + rel + pe2 ); } public Pair<URI, URI> getComponentURIs() { URI righturi = null; if (componententities.getRight()!=null) { righturi = componententities.getRight().getURI(); } return Pair.of(componententities.getLeft().getURI(), righturi); } public Pair<String, String> getComponentNames() { String rightname = "<none>"; if (componententities.getRight()!=null) { rightname = componententities.getRight().getName(); } return Pair.of(componententities.getLeft().getName(), rightname); } public Pair<String, String> getComponentFullNames() { String rightname = "<none>"; if (componententities.getRight()!=null) { rightname = componententities.getRight().getFullName(); } return Pair.of(componententities.getLeft().getFullName(), rightname); } public boolean equals(DBCompositeEntity dbc) { return componentEntityListsMatch(dbc.componententities); } public StructuralRelation getRelation() { return relation; } public void setRelation(StructuralRelation r) { relation = r; } public boolean componentEntityListsMatch(Pair<PhysicalEntity, PhysicalEntity> components) { if (components.getRight()==null) { return (components.getLeft().getURI().equals(componententities.getLeft().getURI()) && components.getRight()==null); } return (components.getLeft().getURI().equals(componententities.getLeft().getURI()) && components.getRight().getURI().equals(componententities.getRight().getURI())); } public void setComponents(Pair<PhysicalEntity, PhysicalEntity> cmptpair) { if (componententities == null) { componententities = cmptpair; } } public final Pair<PhysicalEntity, PhysicalEntity> getComponents() { return componententities; } public String getFullName() { return getName(); } }
apache-2.0
jacarrichan/eoffice
src/main/webapp/js/hrm/StandSalaryForm.js
6989
var StandSalaryForm = function(a) { this.standardId = a; return new Ext.Panel( { id : "StandSalaryForm", iconCls : "menu-development", tbar : this.initToolbar(), border : false, title : "薪酬标准详细信息", items : [ this.setup(a) ] }); }; StandSalaryForm.prototype.setup = function(c) { var b = new StandSalaryItemView(c); var a = new Ext.FormPanel( { id : "StandSalaryFormPanel", url : __ctxPath + "/hrm/saveStandSalary.do", layout : "form", bodyStyle : "padding:5px 10px 10px 10px;", formId : "StandSalaryFormId", defaultType : "textfield", border : false, reader : new Ext.data.JsonReader( { root : "data" }, [ { name : "standSalaryForm.standardId", mapping : "standardId" }, { name : "standSalaryForm.setdownTime", mapping : "setdownTime" }, { name : "standSalaryForm.framer", mapping : "framer" }, { name : "standSalaryForm.checkName", mapping : "checkName" }, { name : "standSalaryForm.checkTime", mapping : "checkTime" }, { name : "standSalaryForm.checkOpinion", mapping : "checkOpinion" }, { name : "standSalaryForm.standardNo", mapping : "standardNo" }, { name : "standSalaryForm.standardName", mapping : "standardName" }, { name : "standSalaryForm.totalMoney", mapping : "totalMoney" }, { name : "standSalaryForm.memo", mapping : "memo" } ]), items : [ { name : "standSalary.standardId", id : "standSalaryForm.standardId", xtype : "hidden", value : this.standardId == null ? "" : this.standardId }, { name : "standSalary.setdownTime", id : "standSalaryForm.setdownTime", xtype : "hidden" }, { name : "standSalary.framer", id : "standSalaryForm.framer", xtype : "hidden" }, { name : "standSalary.checkName", id : "standSalaryForm.checkName", xtype : "hidden" }, { name : "standSalary.checkTime", id : "standSalaryForm.checkTime", xtype : "hidden" }, { name : "standSalary.checkOpinion", id : "standSalaryForm.checkOpinion", xtype : "hidden" }, { name : "deleteItemIds", id : "deleteItemIds", xtype : "hidden" }, { xtype : "fieldset", title : "薪酬信息", anchor : "100%", layout : "form", items : [ { xtype : "container", layout : "column", style : "padding-left:0px;", items : [ { xtype : "container", defaultType : "textfield", style : "padding-left:0px;", columnWidth : 0.5, defaults : { anchor : "100%,100%" }, layout : "form", items : [ { fieldLabel : "标准编号", allowBlank : false, blankText : "标准编号不能为空!", name : "standSalary.standardNo", id : "standSalaryForm.standardNo" }, { fieldLabel : "标准名称", xtype : "textfield", name : "standSalary.standardName", allowBlank : false, blankText : "标准名称不能为空!", id : "standSalaryForm.standardName" } ] }, { xtype : "container", columnWidth : 0.5, style : "padding-left:0px;", defaults : { anchor : "100%,100%" }, layout : "form", items : [ { id : "getStandardNoButton", xtype : "button", autoWidth : true, text : "系统生成", iconCls : "btn-system-setting", handler : function() { Ext.Ajax .request( { url : __ctxPath + "/hrm/numberStandSalary.do", success : function( e) { var d = Ext.util.JSON .decode(e.responseText); Ext .getCmp( "standSalaryForm.standardNo") .setValue( d.standardNo); } }); } }, { fieldLabel : "薪资总额", name : "standSalary.totalMoney", id : "standSalaryForm.totalMoney", xtype : "textfield", readOnly : true, anchor : "100%" } ] } ] }, { fieldLabel : "备注", name : "standSalary.memo", id : "standSalaryForm.memo", xtype : "textarea", anchor : "99%" } ] }, b ] }); if (this.standardId != null && this.standardId != "undefined") { a.getForm() .load( { deferredRender : false, url : __ctxPath + "/hrm/getStandSalary.do?standardId=" + this.standardId, waitMsg : "正在载入数据...", success : function(d, e) { Ext.getCmp("getStandardNoButton").disable(); Ext.getCmp("standSalaryForm.standardNo") .getEl().dom.readOnly = true; }, failure : function(d, e) { } }); } return a; }; StandSalaryForm.prototype.initToolbar = function() { var a = new Ext.Toolbar( { width : "100%", height : 30, items : [ { text : "保存", iconCls : "btn-save", handler : function() { StandSalaryForm.saveStandSalary(); } }, { text : "取消", iconCls : "btn-cancel", handler : function() { var b = Ext.getCmp("centerTabPanel"); b.remove("StandSalaryForm"); } } ] }); return a; }; StandSalaryForm.saveStandSalary = function() { StandSalaryItemView.onCalcTotalMoney(); var c = Ext.getCmp("StandSalaryFormPanel"); var b = Ext.getCmp("StandSalaryItemGrid").getStore(); var d = []; for (i = 0, cnt = b.getCount(); i < cnt; i += 1) { var a = b.getAt(i); if (a.data.itemId == "" || a.data.itemId == null) { a.set("itemId", -1); } if (a.dirty) { d.push(a.data); } } if (c.getForm().isValid()) { c.getForm().submit( { method : "post", params : { data : Ext.encode(d) }, waitMsg : "正在提交数据...", success : function(e, f) { Ext.ux.Toast.msg("操作信息", "成功保存信息!"); }, failure : function(e, f) { Ext.MessageBox.show( { title : "操作信息", msg : f.result.msg, buttons : Ext.MessageBox.OK, icon : "ext-mb-error" }); Ext.getCmp("standSalaryForm.standardNo").setValue(""); } }); } };
apache-2.0
pioneers/topgear
python/forseti2/piemos_cmd.java
2759
/* LCM type definition class file * This file was automatically generated by lcm-gen * DO NOT MODIFY BY HAND!!!! */ package forseti2; import java.io.*; import java.util.*; import lcm.lcm.*; public final class piemos_cmd implements lcm.lcm.LCMEncodable { public forseti2.header header; public boolean auton; public boolean enabled; public boolean is_blue; public int game_time; public piemos_cmd() { } public static final long LCM_FINGERPRINT; public static final long LCM_FINGERPRINT_BASE = 0xa6ee79d563b22a14L; static { LCM_FINGERPRINT = _hashRecursive(new ArrayList<Class<?>>()); } public static long _hashRecursive(ArrayList<Class<?>> classes) { if (classes.contains(forseti2.piemos_cmd.class)) return 0L; classes.add(forseti2.piemos_cmd.class); long hash = LCM_FINGERPRINT_BASE + forseti2.header._hashRecursive(classes) ; classes.remove(classes.size() - 1); return (hash<<1) + ((hash>>63)&1); } public void encode(DataOutput outs) throws IOException { outs.writeLong(LCM_FINGERPRINT); _encodeRecursive(outs); } public void _encodeRecursive(DataOutput outs) throws IOException { this.header._encodeRecursive(outs); outs.writeByte( this.auton ? 1 : 0); outs.writeByte( this.enabled ? 1 : 0); outs.writeByte( this.is_blue ? 1 : 0); outs.writeInt(this.game_time); } public piemos_cmd(byte[] data) throws IOException { this(new LCMDataInputStream(data)); } public piemos_cmd(DataInput ins) throws IOException { if (ins.readLong() != LCM_FINGERPRINT) throw new IOException("LCM Decode error: bad fingerprint"); _decodeRecursive(ins); } public static forseti2.piemos_cmd _decodeRecursiveFactory(DataInput ins) throws IOException { forseti2.piemos_cmd o = new forseti2.piemos_cmd(); o._decodeRecursive(ins); return o; } public void _decodeRecursive(DataInput ins) throws IOException { this.header = forseti2.header._decodeRecursiveFactory(ins); this.auton = ins.readByte()!=0; this.enabled = ins.readByte()!=0; this.is_blue = ins.readByte()!=0; this.game_time = ins.readInt(); } public forseti2.piemos_cmd copy() { forseti2.piemos_cmd outobj = new forseti2.piemos_cmd(); outobj.header = this.header.copy(); outobj.auton = this.auton; outobj.enabled = this.enabled; outobj.is_blue = this.is_blue; outobj.game_time = this.game_time; return outobj; } }
apache-2.0
google-research/google-research
aqt/utils/hparams_utils.py
6561
# coding=utf-8 # Copyright 2022 The Google Research 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. """Functions to load/save the hparams to/from a config dict.""" import json import os import typing from typing import Any, Dict, Optional, Type, TypeVar import dacite import dataclasses import jax import ml_collections from aqt.jax import quant_config from aqt.jax import quantization from aqt.jax.flax import struct as flax_struct T = TypeVar('T') dataclass = flax_struct.dataclass if not typing.TYPE_CHECKING else dataclasses.dataclass @dataclass class HParamsMetadata: """Metadata associated with an experiment configuration.""" # Human-readable description of this hparams configuration. Mainly # useful for hand inspection of serialized JSON files. description: str # Creation time of the configuration in the format of seconds from epoch. # Used for versioning different hyperparameter settings for the same # model configuration. last_updated_time: Optional[float] # By default, it is used to name the model directory and label the # experiment in tensorboard. hyper_str: Optional[str] = None # TODO(abdolrashidi): Add unit tests for the functions below. def save_dataclass_to_disk(data, path): """Serializes the given dataclass to a JSON file on disk. Args: data: A dataclass instance. path: Path to save the dataclass to. """ data_dict = dataclasses.asdict(data) with open(path, 'w') as file: json.dump(data_dict, file, indent=2) def write_hparams_to_file_with_host_id_check(hparams, output_dir): """Writes hparams to file for master host. Args: hparams: Hparams. output_dir: Output directory to save hparams to, saves as output_dir / 'hparams_config.json. """ if jax.host_id() == 0 and output_dir is not None: # The directory is usually created automatically by the time we reach here, # but on some training runs it appears not to be. # MakeDirs will create the directory if it doesn't already exist and is a # no-op if it already exists. os.makedirs(output_dir, exist_ok=True) save_dataclass_to_disk(hparams, os.path.join(output_dir, 'hparams_config.json')) def load_dataclass_from_dict(dataclass_name, data_dict): """Converts parsed dictionary from JSON into a dataclass. Args: dataclass_name: Name of the dataclass. data_dict: Dictionary parsed from JSON. Returns: An instance of `dataclass` populated with the data from `data_dict`. """ # Some fields in TrainingHParams are formal Python enums, but they are stored # as plain text in the json. Dacite needs to be given a list of which classes # to convert from a string into an enum. The classes of all enum values which # are stored in a TrainingHParams instance (directly or indirectly) should be # listed here. See https://github.com/konradhalas/dacite#casting. enum_classes = [ quantization.QuantOps.ActHParams.InputDistribution, quantization.QuantType, quant_config.QuantGranularity ] data_dict = _convert_lists_to_tuples(data_dict) return dacite.from_dict( data_class=dataclass_name, data=data_dict, config=dacite.Config(cast=enum_classes)) T = TypeVar('T') def _convert_lists_to_tuples(node): """Recursively converts all lists to tuples in a nested structure. Recurses into all lists and dictionary values referenced by 'node', converting all lists to tuples. Args: node: A Python structure corresponding to JSON (a dictionary, a list, scalars, and compositions thereof) Returns: A Python structure identical to the input, but with lists replaced by tuples. """ if isinstance(node, dict): return {key: _convert_lists_to_tuples(value) for key, value in node.items()} elif isinstance(node, (list, tuple)): return tuple([_convert_lists_to_tuples(value) for value in node]) else: return node def load_dataclass_from_json(dataclass_name, json_data): """Creates a dataclass instance from JSON. Args: dataclass_name: Name of the dataclass to deserialize the JSON into. json_data: A Python string containing JSON. Returns: An instance of 'dataclass' populated with the JSON data. """ data_dict = json.loads(json_data) return load_dataclass_from_dict(dataclass_name, data_dict) # TODO(shivaniagrawal): functionality `load_hparams_from_file` is created for a # generic (model hparams independent) train_hparams class; either we should move # towards shared TrainHparams or remove the following functionalities. def load_hparams_from_config_dict(hparams_classname, model_classname, config_dict): """Loads hparams from a configdict, and populates its model object. Args: hparams_classname: Name of the hparams class. model_classname: Name of the model class within the hparams class config_dict: A config dict mirroring the structure of hparams. Returns: An instance of 'hparams_classname' populated with the data from 'config_dict'. """ hparams = load_dataclass_from_config_dict(hparams_classname, config_dict) hparams.model_hparams = load_dataclass_from_dict(model_classname, hparams.model_hparams) return hparams def load_dataclass_from_config_dict( dataclass_name, config_dict): """Creates a dataclass instance from a configdict. Args: dataclass_name: Name of the dataclass to deserialize the configdict into. config_dict: A config dict mirroring the structure of 'dataclass_name'. Returns: An instance of 'dataclass_name' populated with the data from 'config_dict'. """ # We convert the config dicts to JSON instead of a dictionary to force all # recursive field references to fully resolve in a way that Dacite can # consume. json_data = config_dict.to_json() return load_dataclass_from_json(dataclass_name, json_data)
apache-2.0
bradcfisher/izpack
izpack-panel/src/main/java/com/izforge/izpack/panels/target/TargetConsolePanel.java
5721
/* * IzPack - Copyright 2001-2012 Julien Ponge, All Rights Reserved. * * http://izpack.org/ * http://izpack.codehaus.org/ * * Copyright 2002 Jan Blok * * 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.izforge.izpack.panels.target; import com.izforge.izpack.api.adaptator.IXMLElement; import com.izforge.izpack.api.data.InstallData; import com.izforge.izpack.api.handler.Prompt; import com.izforge.izpack.installer.console.ConsolePanel; import com.izforge.izpack.installer.panel.PanelView; import com.izforge.izpack.panels.path.PathInputBase; import com.izforge.izpack.panels.path.PathInputConsolePanel; import com.izforge.izpack.util.Console; import java.io.File; import java.io.PrintWriter; import java.util.Properties; /** * Console implementation of the {@link TargetPanel}. * * @author Mounir El Hajj */ public class TargetConsolePanel extends PathInputConsolePanel implements ConsolePanel { private final InstallData installData; /** * Constructs a {@code TargetConsolePanel}. * * @param panel the parent panel/view. May be {@code null} */ public TargetConsolePanel(PanelView<ConsolePanel> panel, InstallData installData, Prompt prompt) { super(panel, installData, prompt); this.installData = installData; } @Override public boolean generateProperties(InstallData installData, PrintWriter printWriter) { printWriter.println(InstallData.INSTALL_PATH + "="); return true; } @Override public boolean run(InstallData installData, Properties properties) { boolean result = false; String path = properties.getProperty(InstallData.INSTALL_PATH); if (path == null || "".equals(path.trim())) { System.err.println("Missing mandatory target path!"); } else if (TargetPanelHelper.isIncompatibleInstallation(path)) { System.err.println(getIncompatibleInstallationMsg(installData)); } else { path = installData.getVariables().replace(path); installData.setInstallPath(path); result = true; } return result; } /** * Runs the panel using the specified console. * * @param installData the installation data * @param console the console * @return <tt>true</tt> if the panel ran successfully, otherwise <tt>false</tt> */ @Override public boolean run(InstallData installData, Console console) { printHeadLine(installData, console); File pathFile; String normalizedPath; String defaultPath = TargetPanelHelper.getPath(installData); PathInputBase.setInstallData(installData); if (defaultPath == null) { defaultPath = ""; } while (true) { String path = console.promptLocation(installData.getMessages().get("TargetPanel.info") + " [" + defaultPath + "] ", defaultPath); if (path != null) { path = installData.getVariables().replace(path); normalizedPath = PathInputBase.normalizePath(path); pathFile = new File(normalizedPath); if (TargetPanelHelper.isIncompatibleInstallation(normalizedPath)) { console.println(getIncompatibleInstallationMsg(installData)); continue; } else if (!PathInputBase.isWritable(normalizedPath)) { console.println(installData.getMessages().get("UserPathPanel.notwritable")); continue; } else if (!normalizedPath.isEmpty()) { if (pathFile.isFile()) { console.println(installData.getMessages().get("PathInputPanel.isfile")); continue; } else if (pathFile.exists()) { if (!checkOverwrite(pathFile, console)) { continue; } } else if (!checkCreateDirectory(pathFile, console)) { continue; } else if (!installData.getPlatform().isValidDirectoryPath(pathFile)) { console.println(installData.getMessages().get("TargetPanel.syntax.error")); continue; } installData.setInstallPath(normalizedPath); return promptEndPanel(installData, console); } return run(installData, console); } else { return false; } } } private String getIncompatibleInstallationMsg(InstallData installData) { return installData.getMessages().get("TargetPanel.incompatibleInstallation"); } @Override public void createInstallationRecord(IXMLElement panelRoot) { new TargetPanelAutomation().createInstallationRecord(installData, panelRoot); } }
apache-2.0
cloudera/cm_api
setup.py
1298
#! /usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. 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. # # This file is basically a symlink to "python/setup.py" expressed in # python code. If python executes "setup.py", it will be effectively # executing "python/setup.py". # This is required to allow PIP installation from a git repo, which assumes # that "setup.py" is at the root. import os.path import imp base_dir = os.path.split(os.path.abspath(__file__))[0] setup = os.path.join(base_dir, "python", "setup.py") fobj = open(setup) imp.load_module("__setup2__", fobj, setup, imp.get_suffixes()[3])
apache-2.0
fengcms/fengcms
system/common/function.php
17295
<?php /******************************************************************* * @authors FengCms * @web http://www.fengcms.com * @email web@fengcms.com * @date 2013-10-30 16:00:12 * @version FengCms Beta 1.0 * @copy Copyright © 2013-2018 Powered by DiFang Web Studio *******************************************************************/ // 公用函数 defined('TPL_INCLUDE') or die( 'Restricted access'); //-------------------------------------------------------- // 系统函数 //-------------------------------------------------------- /** * 文件载入 * * @access public * @param string $name 文件名称 * @param array $ext 文件后缀 * @return bool */ function import($name, $ext = '.php') { static $_loads = array(); $path = substr($name, 0, 4) == 'root' ? ROOT_PATH : SYSTEM_PATH; $name = str_replace('root.', '', $name); $name = str_replace('.', '/', $name); $file = $path . $name . $ext; if(isset($_loads[$file])) { //如果已经载入过直接返回 return true; } if(strpos($file, '*') > 1){ //如果有*号存在, 代表载入指定目录下的所有 $files = glob($file); $len = count($files); for($i = 0; $i < $len; $i++) { if(file_exists($files[$i])) { include_once($files[$i]); $_loads[$file] = true; } } return true; }elseif(file_exists($file)) { include_once($file); $_loads[$file] = true; return true; } return false; } /** * 模型方法 * * @param string $path 文件夹路径 * @param int $mode 权限 * @return bool */ function M($model_name){ $default_model='Model'; $definition_model=strtolower($model_name).$default_model; $model_file=MODEL_PATH.$definition_model.'.php'; if(file_exists($model_file)){ include_once $model_file; if(class_exists($definition_model)){ return new $definition_model($model_name); }else{ throwexce(sprintf('%s Model does not exist!', $definition_model)); } }else{ throwexce(sprintf('%s Model File does not exist!', $definition_model)); } } /** * 库方法 * * @param string $path 文件夹路径 * @param int $mode 权限 * @return bool */ function D($model_name,$prefix=""){ $model='model'; if(class_exists($model)){ return new $model($model_name,$prefix); }else{ throwexce(sprintf('Model does not exist!')); } } //-------------------------------------------------------- // 文件目录函数 //-------------------------------------------------------- /** * 批量创建目录 * * @access public * @param string $path 文件夹路径 * @param int $mode 权限 * @return bool */ function mkdirs($path, $mode = 0775){ if (!is_dir($path)) { mkdirs(dirname($path), $mode); $error_level = error_reporting(0); $result = mkdir($path, $mode); error_reporting($error_level); return $result; } return true; } /** * 删除文件夹 * * @access public * @param string $path 要删除的文件夹路径 * @return bool */ function rmdirs($path){ $error_level = error_reporting(0); if ($dh = opendir($path)) { while (false !== ($file=readdir($dh))) { if ($file != '.' && $file != '..') { $file_path = $path.'/'.$file; is_dir($file_path) ? rmdirs($file_path) : unlink($file_path); } } closedir($dh); } $result = rmdir($path); error_reporting($error_level); return $result; } /** * 读取目录列表 * * @access public * @return bool */ function getDir($dir) { $dirArray[]=NULL; if (false != ($handle = opendir ( $dir ))) { $i=0; while ( false !== ($file = readdir ( $handle )) ) { //去掉"“.”、“..”以及带“.xxx”后缀的文件 if ($file != "." && $file != ".."&&!strpos($file,".")) { $dirArray[$i]=$file; $i++; } } //关闭句柄 closedir ( $handle ); } return $dirArray; } /** * 读取文件列表 * * @access public * @return bool */ function getFile($dir) { $fileArray[]=NULL; if (false != ($handle = opendir ( $dir ))) { $i=0; while( false !== ($file = readdir ( $handle )) ) { //去掉"“.”、“..”以及带“.xxx”后缀的文件 if ($file != "." && $file != ".."&&strpos($file,".")) { $fileArray[$i]=$file; if($i==100){ break; } $i++; } } //关闭句柄 closedir ( $handle ); } return $fileArray; } /** * 写入文件 * * @access public * @param string $files 文件名 * @return bool */ function fileWrite($content,$files,$path){ mkdirs($path); $fp = fopen($path.'/'.$files, 'a+'); $re=fputs($fp, $content); fclose($fp); if($re){ return true; }else{ return false; } } /** * 读取或设置缓存 * * @access public * @param string $name 缓存名称 * @param mixed $value 缓存内容, null删除缓存 * @param string $path 缓存路径 * @return mixed */ function cache($name, $value ="" , $path ="" ){ // return false; //调试阶段, 不进行缓存 $path = empty($path) ? CACHE_PATH ."data/" : $path; $file = $path . $name . ".php"; if (empty($value)) { //缓存不存在 if (!is_file($file)) { return false; } // 删除缓存 if (is_null($value)) { unlink($file); return true; } $data = include $file; return $data; } $value = var_export($value, true); $value = "<?php defined('TPL_INCLUDE') or exit('Access Denied'); return {$value}; ?>"; return file_put_contents($file, $value); } //-------------------------------------------------------- // XML函数 //-------------------------------------------------------- /** * 数据转XML * * @access public * @param string $array 数组 * @param mixed $dom dom定义,编码 * @param string $item item定义 * @return mixed */ function arrtoxml($array,$dom=0,$item=0){ if (!$dom){ $dom = new DOMDocument("1.0","utf-8"); } if(!$item){ $item = $dom->createElement("root"); $dom->appendChild($item); } foreach ($array as $key=>$val){ $itemx = $dom->createElement(is_string($key)?$key:"item"); $item->appendChild($itemx); if (!is_array($val)){ $text = $dom->createTextNode($val); $itemx->appendChild($text); }else { arrtoxml($val,$dom,$itemx); } } return $dom->saveXML(); } //-------------------------------------------------------- // 数组函数 //-------------------------------------------------------- /** * 二维数组转一维数组 * * @access public * @param string $array 数组 * @return array */ function array_multi2single($array){ static $result_array=array(); foreach($array as $value){ if(is_array($value)){ array_multi2single($value); } else $result_array[]=$value; } return $result_array; } //-------------------------------------------------------- // URL函数 //-------------------------------------------------------- /** * 读取url数据 * * @access public * @param string $url 链接地址 * @param array $date 数据 */ function sock_post($url, $data='') { $url = parse_url($url); $url['scheme'] || $url['scheme'] = 'http'; $url['host'] || $url['host'] = $_SERVER['HTTP_HOST']; $url['path'][0] != '/' && $url['path'] = '/'.$url['path']; $query = $data; if(is_array($data)) $query = http_build_query($data); $fp = @fsockopen($url['host'], $url['port'] ? $url['port'] : 80); if (!$fp) return "Failed to open socket to $url[host]"; fputs($fp, sprintf("POST %s%s%s HTTP/1.0\n", $url['path'], $url['query'] ? "?" : "", $url['query'])); fputs($fp, "Host: $url[host]\n"); fputs($fp, "Content-type: application/x-www-form-urlencoded\n"); fputs($fp, "Content-length: " . strlen($query) . "\n"); fputs($fp, "Connection: close\n\n"); fputs($fp, "$query\n"); $line = fgets($fp,1024); if (!eregi("^HTTP/1\.. 200", $line)) return; $results = ""; $inheader = 1; while(!feof($fp)) { $line = fgets($fp,1024); if ($inheader && ($line == "\n" || $line == "\r\n")) { $inheader = 0; }elseif (!$inheader) { $results .= $line; } } fclose($fp); return $results; } function url($url){ if(URL_TYPE=='1'){ return $url; }elseif(URL_TYPE=='0'){ if(substr($url,0,4)=="http"){ return $url; }else{ $u=explode('.',$url); $url=explode('_',$u[0]); if(substr($url[0],1)=='content'){ return "?controller=content&project=".$url[1]."&id=".$url[2]; }else{ return "?controller=classify&project=".substr($url[0],1)."&classify=".$url[1]."&classid=".$url[2]; } } } } function curl($string,$func="",$id=""){ if(URL_TYPE=='1'){ if($func){ return $string.'_'.$func.'.html'; }elseif($id){ return $string.'_'.$func.'_'.$id.'.html'; }else{ return $string.'.html'; } }elseif(URL_TYPE=='0'){ if($func){ return '/?controller='.$string.'&operate='.$func; }elseif($id){ return '/?controller='.$string.'&operate='.$func.'&id='.$id; }else{ return '/?controller='.$string; } } } function search($string){ if(URL_TYPE=='1'){ return '/tags/'.urlencode($string).'.html'; }elseif(URL_TYPE=='0'){ return '/?controller=search&tags='.$string; } } /* 字体转换 $content 内容 $to_encoding 目标编码,默认为UTF-8 $from_encoding 源编码,默认为GBK */ function mbStrreplace($content,$to_encoding="UTF-8",$from_encoding="UTF-8") { $content=mb_convert_encoding($content,$to_encoding,$from_encoding); $str=mb_convert_encoding(" ",$to_encoding,$from_encoding); $content=mb_eregi_replace($str,"",$content); $content=mb_convert_encoding($content,$from_encoding,$to_encoding); $content=trim($content); return $content; } /** * 压缩html : 清除换行符,清除制表符,去掉注释标记 * @param $string * @return 压缩后的$string * from: www.jbxue.com * */ function compress_html($string) { $string = str_replace("\r\n", '', $string); //清除换行符 $string = str_replace("\n", '', $string); //清除换行符 $string = str_replace("\t", '', $string); //清除制表符 $pattern = array ( "/> *([^ ]*) *</", //去掉注释标记 "/[\s]+/", "/<!--[^!]*-->/", "/\" /", "/ \"/", "'/\*[^*]*\*/'" ); $replace = array ( ">\\1<", " ", "", "\"", "\"", "" ); return preg_replace($pattern, $replace, $string); } /** * 加密解密 * @param $string 字符串 * @param $operation 方式E/D * @param $key 密钥 * @return $string **/ function encrypt($string,$operation,$key='123456789'){ $key=md5($key); $key_length=strlen($key); $string=$operation=='D'?base64_decode($string):substr(md5($string.$key),0,8).$string; $string_length=strlen($string); $rndkey=$box=array(); $result=''; for($i=0;$i<=255;$i++){ $rndkey[$i]=ord($key[$i%$key_length]); $box[$i]=$i; } for($j=$i=0;$i<256;$i++){ $j=($j+$box[$i]+$rndkey[$i])%256; $tmp=$box[$i]; $box[$i]=$box[$j]; $box[$j]=$tmp; } for($a=$j=$i=0;$i<$string_length;$i++){ $a=($a+1)%256; $j=($j+$box[$a])%256; $tmp=$box[$a]; $box[$a]=$box[$j]; $box[$j]=$tmp; $result.=chr(ord($string[$i])^($box[($box[$a]+$box[$j])%256])); } if($operation=='D'){ if(substr($result,0,8)==substr(md5(substr($result,8).$key),0,8)){ return substr($result,8); }else{ return''; } }else{ return str_replace('=','',base64_encode($result)); } } //-------------------------------------------------------- // 其他函数 //-------------------------------------------------------- /** * 获取当前IP * * @access public * @return string */ function getIP() { if (@$_SERVER["HTTP_X_FORWARDED_FOR"]) $ip = $_SERVER["HTTP_X_FORWARDED_FOR"]; else if (@$_SERVER["HTTP_CLIENT_IP"]) $ip = $_SERVER["HTTP_CLIENT_IP"]; else if (@$_SERVER["REMOTE_ADDR"]) $ip = $_SERVER["REMOTE_ADDR"]; else if (@getenv("HTTP_X_FORWARDED_FOR")) $ip = getenv("HTTP_X_FORWARDED_FOR"); else if (@getenv("HTTP_CLIENT_IP")) $ip = getenv("HTTP_CLIENT_IP"); else if (@getenv("REMOTE_ADDR")) $ip = getenv("REMOTE_ADDR"); else $ip = "Unknown"; return $ip; } /** * 替换文件路径以网站根目录开始,防止暴露文件的真实地址 * * @param string $path * @return string 返回一个相对当前站点的文件路径 */ function replpath($path){ $root_path = str_replace(DIRECTORY_SEPARATOR, '/', ROOT_PATH); $src_path = str_replace(DIRECTORY_SEPARATOR, '/', $path); return str_replace($root_path, '', $src_path); } function down($filename){ echo '/?controller=down&file='.base64_encode($filename); } /* // 万能标签函数 */ function l($table,$func=""){ return M('module')->l($table,$func); } /* // 判断是否是手机 */ function is_mobile_request(){ $_SERVER['ALL_HTTP'] = isset($_SERVER['ALL_HTTP']) ? $_SERVER['ALL_HTTP'] : ''; $mobile_browser = '0'; if(preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom)/i', strtolower($_SERVER['HTTP_USER_AGENT']))) $mobile_browser++; if((isset($_SERVER['HTTP_ACCEPT'])) and (strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') !== false)) $mobile_browser++; if(isset($_SERVER['HTTP_X_WAP_PROFILE'])) $mobile_browser++; if(isset($_SERVER['HTTP_PROFILE'])) $mobile_browser++; $mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,4)); $mobile_agents = array( 'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac', 'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno', 'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-', 'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-', 'newt','noki','oper','palm','pana','pant','phil','play','port','prox', 'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar', 'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-', 'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp', 'wapr','webc','winw','winw','xda','xda-' ); if(in_array($mobile_ua, $mobile_agents)) $mobile_browser++; if(strpos(strtolower($_SERVER['ALL_HTTP']), 'operamini') !== false) $mobile_browser++; // Pre-final check to reset everything if the user is on Windows if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows') !== false) $mobile_browser=0; // But WP7 is also Windows, with a slightly different characteristic if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows phone') !== false) $mobile_browser++; if($mobile_browser>0) return true; else return false; } /** * 生成缩略图函数(支持图片格式:gif、jpeg、png和bmp) * 用法:{thumb($imgUrl,50,50)} * @author ruxing.li * @param string $src 源图片路径 * @param int $width 缩略图宽度(只指定高度时进行等比缩放) * @param int $width 缩略图高度(只指定宽度时进行等比缩放) * @param string $filename 保存路径(不指定时直接输出到浏览器) * @return bool */ function thumb($src, $width = null, $height = null, $filename = null) { if (!isset($width) && !isset($height)) return false; if (isset($width) && $width <= 0) return false; if (isset($height) && $height <= 0) return false; $size = getimagesize($src); if (!$size) return false; list($src_w, $src_h, $src_type) = $size; $src_mime = $size['mime']; switch($src_type) { case 1 : $img_type = 'gif'; break; case 2 : $img_type = 'jpeg'; break; case 3 : $img_type = 'png'; break; case 15 : $img_type = 'wbmp'; break; default : return false; } if (!isset($width)) $width = $src_w * ($height / $src_h); if (!isset($height)) $height = $src_h * ($width / $src_w); $imagecreatefunc = 'imagecreatefrom' . $img_type; $src_img = $imagecreatefunc($src); $dest_img = imagecreatetruecolor($width, $height); imagecopyresampled($dest_img, $src_img, 0, 0, 0, 0, $width, $height, $src_w, $src_h); $imagefunc = 'image' . $img_type; if ($filename) { $imagefunc($dest_img, $filename); } else { header('Content-Type: ' . $src_mime); $imagefunc($dest_img); } imagedestroy($src_img); imagedestroy($dest_img); return true; } ?>
apache-2.0
davidknipe/MenuPin
MenuPin/MenuProvider/AddFindPinToMenu.cs
663
using System.Collections.Generic; using EPiServer.Shell.Navigation; namespace MenuPin.MenuProvider { [MenuProvider] public class AddFindPinToMenu : IMenuProvider { public IEnumerable<MenuItem> GetMenuItems() { var pinMenuItemCommerce = new UrlMenuItem( "<span class=\"epi-iconPin menuPinButton\"></span>", "/global/find/Manage", "javascript: return;" ); pinMenuItemCommerce.Alignment = MenuItemAlignment.Right; return new List<MenuItem>() { pinMenuItemCommerce }; } } }
apache-2.0
b-slim/hive
ql/src/java/org/apache/hadoop/hive/ql/ddl/table/storage/AlterTableArchiveDesc.java
1869
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.ddl.table.storage; import java.util.Map; import org.apache.hadoop.hive.ql.ddl.DDLDesc; import org.apache.hadoop.hive.ql.plan.Explain; import org.apache.hadoop.hive.ql.plan.Explain.Level; /** * DDL task description for ALTER TABLE ... ARCHIVE [PARTITION ...] commands. */ @Explain(displayName = "Archive", explainLevels = { Level.USER, Level.DEFAULT, Level.EXTENDED }) public class AlterTableArchiveDesc implements DDLDesc { private final String tableName; private final Map<String, String> partitionSpec; public AlterTableArchiveDesc(String tableName, Map<String, String> partitionSpec) { this.tableName = tableName; this.partitionSpec = partitionSpec; } @Explain(displayName = "table name", explainLevels = { Level.USER, Level.DEFAULT, Level.EXTENDED }) public String getTableName() { return tableName; } @Explain(displayName = "partition spec", explainLevels = { Level.USER, Level.DEFAULT, Level.EXTENDED }) public Map<String, String> getPartitionSpec() { return partitionSpec; } }
apache-2.0
wapache/wason
core/src/test/java/org/wapache/json/mapper/example/package-info.java
1325
/******************************************************************************* * Copyright (c) 2016 EclipseSource. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ******************************************************************************/ /** * */ package org.wapache.json.mapper.example;
apache-2.0
wastl/cmarmotta
java/model/src/main/java/org/apache/marmotta/cmarmotta/model/ProtoNamespace.java
1719
package org.apache.marmotta.cmarmotta.model; import org.apache.marmotta.cmarmotta.model.proto.Model; import org.openrdf.model.Namespace; /** * An implementation of a Sesame Namespace backed by a protocol buffer. * * @author Sebastian Schaffert (sschaffert@apache.org) */ public class ProtoNamespace implements Namespace { private Model.Namespace message; public ProtoNamespace(Model.Namespace message) { this.message = message; } public ProtoNamespace(String prefix, String uri) { message = Model.Namespace.newBuilder() .setUri(uri) .setPrefix(prefix).build(); } public Model.Namespace getMessage() { return message; } /** * Gets the name of the current namespace (i.e. it's URI). * * @return name of namespace */ @Override public String getName() { return message.getUri(); } /** * Gets the prefix of the current namespace. The default namespace is * represented by an empty prefix string. * * @return prefix of namespace, or an empty string in case of the default * namespace. */ @Override public String getPrefix() { return message.getPrefix(); } @Override public int compareTo(Namespace namespace) { return getPrefix().compareTo(namespace.getPrefix()); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof Namespace)) return false; Namespace that = (Namespace) o; return getPrefix().equals(that.getPrefix()); } @Override public int hashCode() { return getPrefix().hashCode(); } }
apache-2.0
JasonKessler/scattertext
scattertext/termscoring/CredTFIDF.py
9983
import math import pandas as pd from scipy.stats import norm from scattertext.termscoring.CohensDCalculator import CohensDCalculator from scattertext.termscoring.CorpusBasedTermScorer import CorpusBasedTermScorer import numpy as np from scipy.sparse import csr_matrix import math import pandas as pd from scipy.stats import norm from scattertext.termscoring.CorpusBasedTermScorer import CorpusBasedTermScorer import numpy as np from scipy.sparse import csr_matrix class CredTFIDF(CorpusBasedTermScorer): ''' Yoon Kim and Owen Zhang. Implementation of Credibility Adjusted Term Frequency: A Supervised Term Weighting Scheme for Sentiment Analysis and Text Classification. WASSA 2014. http://www.people.fas.harvard.edu/~yoonkim/data/cred-tfidf.pdf ''' def get_score_df(self): ''' :return: pd.DataFrame ''' X = self._get_X().astype(np.float64) tf_i_d_pos, tf_i_d_neg = self._get_cat_and_ncat(X) return self._get_score_df_from_category_Xs(tf_i_d_neg, tf_i_d_pos) def _get_score_df_from_category_Xs(self, tf_i_d_neg, tf_i_d_pos): # Eq 2 C_i_pos = tf_i_d_pos.sum(axis=0) # number of times of a token occurs in pos class C_i_neg = tf_i_d_neg.sum(axis=0) # number of times of a token occurs in neg class C_i = C_i_pos + C_i_neg # total number of time a token occurs # s_i_pos = C_i_pos / C_i # where s_i^(j) == 1 # s_i_neg = C_i_neg / C_i # where s_i^(j) == -1 # Eq 4 # "s_hatˆi is the average likelihood of making the correct classification # given token i's occurrence in the document, if i was the only token in # the document." s_hat_i = (np.power(C_i_pos, 2) + np.power(C_i_neg, 2)) / (np.power(C_i, 2)) # Eq 5 # Suppose sˆi = ˆsj = 0.75 for two different tokens # i and j, but Ci = 5 and Cj = 100. Intuition suggests that sˆj is a more credible score than # sˆi, and that sˆi should be shrunk towards the population # mean. Let sˆ be the (weighted) population mean. # That is, C = C_i.sum() s_hat = ((s_hat_i.A1 * C_i.A1) / C).sum() # Eq 6 # We define credibility adjusted score for token i to # be, (Eqn 6) where γ is an additive smoothing parameter. If # Ci,k’s are small, then si ≈ sˆ (otherwise, si ≈ sˆi). # This is a form of Buhlmann credibility adjustment # from the actuarial literature (Buhlmann and Gisler, # 2005) s_bar_i = ((np.power(C_i_pos, 2) + np.power(C_i_neg, 2) + s_hat * self.eta) / (np.power(C_i, 2) + self.eta)) # Eq 7 if self.use_sublinear: if not type(tf_i_d_pos) in [np.matrix, np.array]: tf_i_d_pos = tf_i_d_pos.todense() tf_i_d_neg = tf_i_d_neg.todense() adjpos_tf_idf = np.asarray(np.log(tf_i_d_pos + 0.5)) adjneg_tf_idf = np.asarray(np.log(tf_i_d_neg + 0.5)) else: # tf_bar_i_pos = tf_i_d_pos.multiply(0.5 + s_bar_i).todense() # tf_bar_i_neg = tf_i_d_neg.multiply(0.5 + s_bar_i).todense() adjpos_tf_idf = np.asarray(tf_i_d_pos.todense()) adjneg_tf_idf = np.asarray(tf_i_d_neg.todense()) s_bar_i_coef = (0.5 + s_bar_i).A1 tf_bar_i_pos = adjpos_tf_idf tf_bar_i_neg = adjneg_tf_idf if self.use_cred: tf_bar_i_pos *= s_bar_i_coef tf_bar_i_neg *= s_bar_i_coef # Eq 8 N = 1. * tf_i_d_pos.shape[0] + tf_bar_i_neg.shape[0] df_i = ((tf_i_d_pos > 0).astype(float).sum(axis=0) + (tf_i_d_neg > 0).astype(float).sum(axis=0)) w_i_d_pos = tf_bar_i_pos * np.log(N / df_i).A1 w_i_d_neg = tf_bar_i_neg * np.log(N / df_i).A1 w_d_pos_l2 = 1. w_d_neg_l2 = 1. if self.use_l2_norm: w_d_pos_l2 = np.linalg.norm(w_i_d_pos, 2, axis=1) w_d_neg_l2 = np.linalg.norm(w_i_d_neg, 2, axis=1) pos_cred_tfidf = (w_i_d_pos.T / w_d_pos_l2 ).mean(axis=1) neg_cred_tfidf = (w_i_d_neg.T / w_d_neg_l2 ).mean(axis=1) score_df = pd.DataFrame({ 'pos_cred_tfidf': pos_cred_tfidf, 'neg_cred_tfidf': neg_cred_tfidf, 'delta_cred_tf_idf': pos_cred_tfidf - neg_cred_tfidf }, index=self._get_index()) return score_df def _set_scorer_args(self, **kwargs): self.eta = kwargs.get('eta', 1.) self.use_sublinear = kwargs.get('use_sublinear', True) self.use_cred = kwargs.get('use_cred', True) self.use_l2_norm = kwargs.get('use_l2_norm', True) def get_scores(self, *args): return self.get_score_df()['delta_cred_tf_idf'] def get_name(self): return "Delta mean %stf-idf" % ('cred-' if self.use_cred else '') """ class CredTFIDF(CorpusBasedTermScorer): ''' !!! Not working Yoon Kim and Owen Zhang. Implementation of Credibility Adjusted Term Frequency: A Supervised Term Weighting Scheme for Sentiment Analysis and Text Classification. WASSA 2014. http://www.people.fas.harvard.edu/~yoonkim/data/cred-tfidf.pdf ''' def get_score_df(self): ''' :return: pd.DataFrame ''' X = self._get_X().astype(np.float64) tf_i_d_pos, tf_i_d_neg = self._get_cat_and_ncat(X) return self._get_score_df_from_category_Xs(tf_i_d_neg, tf_i_d_pos) def _get_score_df_from_category_Xs(self, tf_i_d_neg, tf_i_d_pos): neg_cred_tfidf, pos_cred_tfidf = self.get_pos_neg_tfidf_matrices(tf_i_d_neg, tf_i_d_pos) print(pos_cred_tfidf.shape) print(neg_cred_tfidf.shape) score_df = CohensDCalculator().get_cohens_d_df(pos_cred_tfidf.T, neg_cred_tfidf.T) print('score_df', score_df.shape) print(score_df) print(pos_cred_tfidf.shape) print(neg_cred_tfidf.shape) score_df['pos_cred_tfidf'] = pos_cred_tfidf.mean(axis=1) score_df['neg_cred_tfidf'] = neg_cred_tfidf.mean(axis=1) score_df['delta_cred_tf_idf'] = score_df['pos_cred_tfidf'] - score_df['neg_cred_tfidf'] return score_df def get_pos_neg_tfidf_matrices(self, tf_i_d_neg, tf_i_d_pos): # Eq 2 C_i_pos = tf_i_d_pos.sum(axis=0) # number of times of a token occurs in pos class C_i_neg = tf_i_d_neg.sum(axis=0) # number of times of a token occurs in neg class C_i = C_i_pos + C_i_neg # total number of time a token occurs # s_i_pos = C_i_pos / C_i # where s_i^(j) == 1 # s_i_neg = C_i_neg / C_i # where s_i^(j) == -1 # Eq 4 # "s_hatˆi is the average likelihood of making the correct classification # given token i's occurrence in the document, if i was the only token in # the document." s_hat_i = (np.power(C_i_pos, 2) + np.power(C_i_neg, 2)) / (np.power(C_i, 2)) # Eq 5 # Suppose sˆi = ˆsj = 0.75 for two different tokens # i and j, but Ci = 5 and Cj = 100. Intuition suggests that sˆj is a more credible score than # sˆi, and that sˆi should be shrunk towards the population # mean. Let sˆ be the (weighted) population mean. # That is, C = C_i.sum() s_hat = ((s_hat_i.A1 * C_i.A1) / C).sum() # Eq 6 # We define credibility adjusted score for token i to # be, (Eqn 6) where γ is an additive smoothing parameter. If # Ci,k’s are small, then si ≈ sˆ (otherwise, si ≈ sˆi). # This is a form of Buhlmann credibility adjustment # from the actuarial literature (Buhlmann and Gisler, # 2005) s_bar_i = ((np.power(C_i_pos, 2) + np.power(C_i_neg, 2) + s_hat * self.eta) / (np.power(C_i, 2) + self.eta)) # Eq 7 if self.use_sublinear: if not type(tf_i_d_pos) in [np.matrix, np.array]: tf_i_d_pos = tf_i_d_pos.todense() tf_i_d_neg = tf_i_d_neg.todense() adjpos_tf_idf = np.asarray(np.log(tf_i_d_pos + 0.5)) adjneg_tf_idf = np.asarray(np.log(tf_i_d_neg + 0.5)) else: # tf_bar_i_pos = tf_i_d_pos.multiply(0.5 + s_bar_i).todense() # tf_bar_i_neg = tf_i_d_neg.multiply(0.5 + s_bar_i).todense() adjpos_tf_idf = np.asarray(tf_i_d_pos.todense()) adjneg_tf_idf = np.asarray(tf_i_d_neg.todense()) s_bar_i_coef = (0.5 + s_bar_i).A1 tf_bar_i_pos = adjpos_tf_idf tf_bar_i_neg = adjneg_tf_idf if self.use_cred: tf_bar_i_pos *= s_bar_i_coef tf_bar_i_neg *= s_bar_i_coef # Eq 8 N = 1. * tf_i_d_pos.shape[0] + tf_bar_i_neg.shape[0] df_i = ((tf_i_d_pos > 0).astype(float).sum(axis=0) + (tf_i_d_neg > 0).astype(float).sum(axis=0)) w_i_d_pos = tf_bar_i_pos * np.log(N / df_i).A1 w_i_d_neg = tf_bar_i_neg * np.log(N / df_i).A1 w_d_pos_l2 = 1. w_d_neg_l2 = 1. if self.use_l2_norm: w_d_pos_l2 = np.linalg.norm(w_i_d_pos, 2, axis=1) w_d_neg_l2 = np.linalg.norm(w_i_d_neg, 2, axis=1) pos_X_cred_tfidf = w_i_d_pos.T / w_d_pos_l2 neg_X_cred_tfidf = w_i_d_neg.T / w_d_neg_l2 #pos_cred_tfidf = pos_X_cred_tfidf.mean(axis=1) #neg_cred_tfidf = neg_X_cred_tfidf.mean(axis=1) return pos_X_cred_tfidf, neg_X_cred_tfidf def _set_scorer_args(self, **kwargs): self.eta = kwargs.get('eta', 1.) self.use_sublinear = kwargs.get('use_sublinear', True) self.use_cred = kwargs.get('use_cred', True) self.use_l2_norm = kwargs.get('use_l2_norm', True) def get_scores(self, *args): return self.get_score_df()['delta_cred_tf_idf'] def get_name(self): return "Delta mean %stf-idf" % ('cred-' if self.use_cred else '') """
apache-2.0
freeVM/freeVM
enhanced/archive/classlib/modules/security/src/main/java/java/security/BasicPermissionCollection.java
3759
/* Copyright 1998, 2004 The Apache Software Foundation or its licensors, as applicable * * 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 java.security; import java.util.Enumeration; import java.util.Hashtable; /** * A Hashtable based collection of BasicPermission objects. It make a number of * assumptions about what is stored in it, allowing it to be quite performant. * <p> * Limitation 1: It does <em>not</em> actually check that the contained * permission objects <em>grant</em> the permission being checked, only that a * permission with a matching name is present. Thus, this collection can not be * used where the Permission objects implement interesting semantics in their * implies methods. * <p> * Limitation 2: It assumes (and does not check) that all permissions which are * stored in the collection are instances of the same class. * <p> * Limitation 3: Because it uses a hashtable, it will not record the fact that * multiple occurances of .equal permissions have been added. * */ class BasicPermissionCollection extends PermissionCollection { private static final long serialVersionUID = 739301742472979399L; /** * A flag to indicate whether the "grant all wildcard" (i.e. "*") has been * added. */ boolean all_allowed = false; /** * A hashtable which maps from a permission name to the matching permission. * Multiple occurances of the same permission are ignored. */ Hashtable permissions = new Hashtable(8); /** * Constructs a new instance of this class. * */ public BasicPermissionCollection() { super(); } /** * Adds the argument to the collection. * * * @param perm * java.security.Permission the permission to add to the * collection */ public void add(Permission perm) { if (isReadOnly()) { throw new IllegalStateException(); } String name = perm.getName(); all_allowed = all_allowed || name.equals("*"); permissions.put(name, perm); } /** * Answers an enumeration of the permissions in the receiver. * * * @return Enumeration the permissions in the receiver. */ public Enumeration elements() { return permissions.elements(); } /** * Indicates whether the argument permission is implied by the permissions * contained in the receiver. Note that, the permissions are not consulted * during the operation of this method. * * * @return boolean <code>true</code> if the argument permission is implied * by the permissions in the receiver, and <code>false</code> if * it is not. * @param perm * java.security.Permission the permission to check */ public boolean implies(Permission perm) { if (all_allowed) return true; String name = perm.getName(); if (permissions.get(name) != null) return true; int i = name.lastIndexOf('.'); while (i >= 0) { // Fail for strings of the form "foo..bar" or "foo.". if (i + 1 == name.length()) return false; name = name.substring(0, i); if (permissions.get(name + ".*") != null) return true; i = name.lastIndexOf('.'); } return false; } }
apache-2.0
exKAZUu/ParserTests
fixture/IronRuby/expected_xml/block.rb
34867
<block startline="1"> <lasgn startline="1"> <Symbol>i</Symbol> <lit startline="1"> <Fixnum>0</Fixnum> </lit> </lasgn> <if startline="3"> <call startline="3"> <lvar startline="3"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="4"> <lit startline="3"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="3"> <Nil /> <Symbol>p</Symbol> <arglist startline="3"> <lvar startline="3"> <Symbol>i</Symbol> </lvar> </arglist> </call> </block> <block /> </if> <if startline="4"> <call startline="4"> <lvar startline="4"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="4"> <lit startline="4"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block startline="4"> <call startline="4"> <Nil /> <Symbol>p</Symbol> <arglist startline="4"> <str startline="4"> <String>c</String> </str> </arglist> </call> <call startline="4"> <Nil /> <Symbol>p</Symbol> <arglist startline="4"> <str startline="4"> <String>c</String> </str> </arglist> </call> </block> <block /> </if> <if startline="5"> <call startline="5"> <lvar startline="5"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="5"> <lit startline="5"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="5"> <Nil /> <Symbol>p</Symbol> <arglist startline="5"> <str startline="5"> <String>c</String> </str> </arglist> </call> </block> <block /> </if> <if startline="6"> <call startline="6"> <lvar startline="6"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="6"> <lit startline="6"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block /> </if> <if startline="7"> <call startline="7"> <lvar startline="7"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="7"> <lit startline="7"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block startline="7"> <call startline="7"> <Nil /> <Symbol>p</Symbol> <arglist startline="7"> <str startline="7"> <String>c</String> </str> </arglist> </call> <call startline="7"> <Nil /> <Symbol>p</Symbol> <arglist startline="7"> <str startline="7"> <String>c</String> </str> </arglist> </call> </block> <block /> </if> <if startline="8"> <call startline="8"> <lvar startline="8"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="8"> <lit startline="8"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="8"> <Nil /> <Symbol>p</Symbol> <arglist startline="8"> <str startline="8"> <String>c</String> </str> </arglist> </call> </block> <block /> </if> <if startline="9"> <call startline="9"> <lvar startline="9"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="9"> <lit startline="9"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block /> </if> <if startline="10"> <call startline="10"> <lvar startline="10"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="11"> <lit startline="10"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block /> </if> <if startline="12"> <call startline="12"> <lvar startline="12"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="13"> <lit startline="12"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block /> </if> <if startline="15"> <call startline="15"> <lvar startline="15"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="16"> <lit startline="15"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block> <if startline="17"> <call startline="16"> <lvar startline="16"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="17"> <lit startline="16"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block /> </if> </block> </if> <if startline="18"> <call startline="18"> <lvar startline="18"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="19"> <lit startline="18"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block> <if startline="21"> <call startline="19"> <lvar startline="19"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="20"> <lit startline="19"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block /> </if> </block> </if> <if startline="24"> <call startline="24"> <lvar startline="24"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="25"> <lit startline="24"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block> <call startline="24"> <Nil /> <Symbol>p</Symbol> <arglist startline="24"> <lvar startline="24"> <Symbol>i</Symbol> </lvar> </arglist> </call> </block> </if> <if startline="25"> <call startline="25"> <lvar startline="25"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="25"> <lit startline="25"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block startline="25"> <call startline="25"> <Nil /> <Symbol>p</Symbol> <arglist startline="25"> <str startline="25"> <String>c</String> </str> </arglist> </call> <call startline="25"> <Nil /> <Symbol>p</Symbol> <arglist startline="25"> <str startline="25"> <String>c</String> </str> </arglist> </call> </block> <block /> </if> <if startline="26"> <call startline="26"> <lvar startline="26"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="26"> <lit startline="26"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="26"> <Nil /> <Symbol>p</Symbol> <arglist startline="26"> <str startline="26"> <String>c</String> </str> </arglist> </call> </block> <block /> </if> <if startline="27"> <call startline="27"> <lvar startline="27"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="27"> <lit startline="27"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block /> </if> <if startline="28"> <call startline="28"> <lvar startline="28"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="28"> <lit startline="28"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block startline="28"> <call startline="28"> <Nil /> <Symbol>p</Symbol> <arglist startline="28"> <str startline="28"> <String>c</String> </str> </arglist> </call> <call startline="28"> <Nil /> <Symbol>p</Symbol> <arglist startline="28"> <str startline="28"> <String>c</String> </str> </arglist> </call> </block> <block /> </if> <if startline="29"> <call startline="29"> <lvar startline="29"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="29"> <lit startline="29"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="29"> <Nil /> <Symbol>p</Symbol> <arglist startline="29"> <str startline="29"> <String>c</String> </str> </arglist> </call> </block> <block /> </if> <if startline="30"> <call startline="30"> <lvar startline="30"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="30"> <lit startline="30"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block /> </if> <if startline="32"> <call startline="31"> <lvar startline="31"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="32"> <lit startline="31"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block /> </if> <if startline="34"> <call startline="33"> <lvar startline="33"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="34"> <lit startline="33"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <block /> </if> <case startline="38"> <lvar startline="38"> <Symbol>i</Symbol> </lvar> <when startline="38"> <array startline="39"> <lit startline="38"> <Fixnum>1</Fixnum> </lit> </array> <call startline="40"> <Nil /> <Symbol>p</Symbol> <arglist startline="40"> <str startline="39"> <String>1</String> </str> </arglist> </call> </when> <Nil /> </case> <case startline="43"> <lvar startline="43"> <Symbol>i</Symbol> </lvar> <when startline="43"> <array startline="44"> <lit startline="43"> <Fixnum>1</Fixnum> </lit> </array> <Nil /> </when> <Nil /> </case> <case startline="47"> <lvar startline="47"> <Symbol>i</Symbol> </lvar> <when startline="47"> <array startline="48"> <lit startline="47"> <Fixnum>1</Fixnum> </lit> </array> <call startline="49"> <Nil /> <Symbol>p</Symbol> <arglist startline="49"> <str startline="48"> <String>1</String> </str> </arglist> </call> </when> <when startline="49"> <array startline="50"> <lit startline="49"> <Fixnum>2</Fixnum> </lit> </array> <call startline="51"> <Nil /> <Symbol>p</Symbol> <arglist startline="51"> <str startline="50"> <String>1</String> </str> </arglist> </call> </when> <Nil /> </case> <case startline="54"> <lvar startline="54"> <Symbol>i</Symbol> </lvar> <when startline="54"> <array startline="55"> <lit startline="54"> <Fixnum>1</Fixnum> </lit> </array> <Nil /> </when> <when startline="55"> <array startline="56"> <lit startline="55"> <Fixnum>2</Fixnum> </lit> </array> <Nil /> </when> <Nil /> </case> <case startline="59"> <lvar startline="59"> <Symbol>i</Symbol> </lvar> <when startline="59"> <array startline="60"> <lit startline="59"> <Fixnum>1</Fixnum> </lit> </array> <call startline="61"> <Nil /> <Symbol>p</Symbol> <arglist startline="61"> <str startline="60"> <String>1</String> </str> </arglist> </call> </when> <when startline="61"> <array startline="62"> <lit startline="61"> <Fixnum>2</Fixnum> </lit> </array> <call startline="63"> <Nil /> <Symbol>p</Symbol> <arglist startline="63"> <str startline="62"> <String>2</String> </str> </arglist> </call> </when> <call startline="65"> <Nil /> <Symbol>p</Symbol> <arglist startline="65"> <str startline="64"> <String>else</String> </str> </arglist> </call> </case> <case startline="68"> <lvar startline="68"> <Symbol>i</Symbol> </lvar> <when startline="68"> <array startline="69"> <lit startline="68"> <Fixnum>1</Fixnum> </lit> </array> <Nil /> </when> <when startline="69"> <array startline="70"> <lit startline="69"> <Fixnum>2</Fixnum> </lit> </array> <Nil /> </when> <Nil /> </case> <case startline="74"> <Nil /> <when startline="74"> <array startline="75"> <call startline="74"> <lvar startline="74"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="75"> <lit startline="74"> <Fixnum>1</Fixnum> </lit> </arglist> </call> </array> <call startline="76"> <Nil /> <Symbol>p</Symbol> <arglist startline="76"> <str startline="75"> <String>1</String> </str> </arglist> </call> </when> <when startline="76"> <array startline="77"> <call startline="76"> <lvar startline="76"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="77"> <lit startline="76"> <Fixnum>2</Fixnum> </lit> </arglist> </call> </array> <call startline="78"> <Nil /> <Symbol>p</Symbol> <arglist startline="78"> <str startline="77"> <String>2</String> </str> </arglist> </call> </when> <call startline="80"> <Nil /> <Symbol>p</Symbol> <arglist startline="80"> <str startline="79"> <String>else</String> </str> </arglist> </call> </case> <case startline="83"> <Nil /> <when startline="83"> <array startline="83"> <call startline="83"> <lvar startline="83"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="83"> <lit startline="83"> <Fixnum>1</Fixnum> </lit> </arglist> </call> </array> <call startline="84"> <Nil /> <Symbol>p</Symbol> <arglist startline="84"> <str startline="83"> <String>1</String> </str> </arglist> </call> </when> <when startline="84"> <array startline="84"> <call startline="84"> <lvar startline="84"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="84"> <lit startline="84"> <Fixnum>2</Fixnum> </lit> </arglist> </call> </array> <call startline="85"> <Nil /> <Symbol>p</Symbol> <arglist startline="85"> <str startline="84"> <String>2</String> </str> </arglist> </call> </when> <call startline="86"> <Nil /> <Symbol>p</Symbol> <arglist startline="86"> <str startline="85"> <String>else</String> </str> </arglist> </call> </case> <call startline="89"> <Nil /> <Symbol>p</Symbol> <arglist startline="89"> <if startline="89"> <call startline="88"> <lvar startline="88"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="88"> <lit startline="88"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <str startline="88"> <String>0</String> </str> </block> <block> <str startline="88"> <String>1</String> </str> </block> </if> </arglist> </call> <until startline="91"> <call startline="91"> <lvar startline="91"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="91"> <lit startline="91"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block startline="91"> <call startline="91"> <Nil /> <Symbol>p</Symbol> <arglist startline="91"> <str startline="91"> <String>c</String> </str> </arglist> </call> <call startline="91"> <Nil /> <Symbol>p</Symbol> <arglist startline="91"> <str startline="91"> <String>c</String> </str> </arglist> </call> </block> <TrueClass>true</TrueClass> </until> <until startline="92"> <call startline="92"> <lvar startline="92"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="92"> <lit startline="92"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="92"> <Nil /> <Symbol>p</Symbol> <arglist startline="92"> <str startline="92"> <String>c</String> </str> </arglist> </call> </block> <TrueClass>true</TrueClass> </until> <until startline="93"> <call startline="93"> <lvar startline="93"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="93"> <lit startline="93"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <TrueClass>true</TrueClass> </until> <until startline="94"> <call startline="94"> <lvar startline="94"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="94"> <lit startline="94"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="94"> <Nil /> <Symbol>p</Symbol> <arglist startline="94"> <str startline="94"> <String>c</String> </str> </arglist> </call> </block> <TrueClass>true</TrueClass> </until> <until startline="95"> <call startline="95"> <lvar startline="95"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="95"> <lit startline="95"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <TrueClass>true</TrueClass> </until> <until startline="97"> <call startline="96"> <lvar startline="96"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="97"> <lit startline="96"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <TrueClass>true</TrueClass> </until> <until startline="100"> <call startline="100"> <lvar startline="100"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="100"> <lit startline="100"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block startline="100"> <call startline="100"> <Nil /> <Symbol>p</Symbol> <arglist startline="100"> <str startline="100"> <String>c</String> </str> </arglist> </call> <call startline="100"> <Nil /> <Symbol>p</Symbol> <arglist startline="100"> <str startline="100"> <String>c</String> </str> </arglist> </call> </block> <TrueClass>true</TrueClass> </until> <until startline="101"> <call startline="101"> <lvar startline="101"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="101"> <lit startline="101"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="101"> <Nil /> <Symbol>p</Symbol> <arglist startline="101"> <str startline="101"> <String>c</String> </str> </arglist> </call> </block> <TrueClass>true</TrueClass> </until> <until startline="102"> <call startline="102"> <lvar startline="102"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="102"> <lit startline="102"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <TrueClass>true</TrueClass> </until> <until startline="103"> <call startline="103"> <lvar startline="103"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="103"> <lit startline="103"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block> <call startline="103"> <Nil /> <Symbol>p</Symbol> <arglist startline="103"> <str startline="103"> <String>c</String> </str> </arglist> </call> </block> <TrueClass>true</TrueClass> </until> <until startline="104"> <call startline="104"> <lvar startline="104"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="104"> <lit startline="104"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <TrueClass>true</TrueClass> </until> <until startline="105"> <call startline="105"> <lvar startline="105"> <Symbol>i</Symbol> </lvar> <Symbol>==</Symbol> <arglist startline="106"> <lit startline="105"> <Fixnum>0</Fixnum> </lit> </arglist> </call> <block /> <TrueClass>true</TrueClass> </until> <for startline="109"> <array startline="109" /> <lasgn startline="109"> <Symbol>y</Symbol> </lasgn> <block startline="109"> <call startline="109"> <Nil /> <Symbol>p</Symbol> <arglist startline="109"> <str startline="109"> <String>c</String> </str> </arglist> </call> <call startline="109"> <Nil /> <Symbol>p</Symbol> <arglist startline="109"> <str startline="109"> <String>c</String> </str> </arglist> </call> </block> </for> <for startline="110"> <array startline="110" /> <lasgn startline="110"> <Symbol>y</Symbol> </lasgn> <block> <call startline="110"> <Nil /> <Symbol>p</Symbol> <arglist startline="110"> <str startline="110"> <String>c</String> </str> </arglist> </call> </block> </for> <for startline="111"> <array startline="111" /> <lasgn startline="111"> <Symbol>y</Symbol> </lasgn> <block /> </for> <for startline="112"> <array startline="112" /> <lasgn startline="112"> <Symbol>y</Symbol> </lasgn> <block> <call startline="112"> <Nil /> <Symbol>p</Symbol> <arglist startline="112"> <str startline="112"> <String>c</String> </str> </arglist> </call> </block> </for> <for startline="113"> <array startline="113" /> <lasgn startline="113"> <Symbol>y</Symbol> </lasgn> <block /> </for> <for startline="114"> <array startline="114" /> <lasgn startline="114"> <Symbol>y</Symbol> </lasgn> <block> <call startline="116"> <Nil /> <Symbol>p</Symbol> <arglist startline="116"> <str startline="115"> <String>c</String> </str> </arglist> </call> </block> </for> <for startline="117"> <array startline="117" /> <lasgn startline="117"> <Symbol>y</Symbol> </lasgn> <block /> </for> <iter startline="121"> <call startline="121"> <Nil /> <Symbol>loop</Symbol> <arglist startline="121" /> </call> <Nil /> <block startline="121"> <call startline="121"> <Nil /> <Symbol>p</Symbol> <arglist startline="121"> <str startline="121"> <String>c</String> </str> </arglist> </call> <call startline="121"> <Nil /> <Symbol>p</Symbol> <arglist startline="121"> <str startline="121"> <String>c</String> </str> </arglist> </call> </block> </iter> <iter startline="122"> <call startline="122"> <Nil /> <Symbol>loop</Symbol> <arglist startline="122" /> </call> <Nil /> <block> <call startline="122"> <Nil /> <Symbol>p</Symbol> <arglist startline="122"> <str startline="122"> <String>c</String> </str> </arglist> </call> </block> </iter> <iter startline="123"> <call startline="123"> <Nil /> <Symbol>loop</Symbol> <arglist startline="123" /> </call> <Nil /> <block /> </iter> <iter startline="124"> <call startline="124"> <Nil /> <Symbol>loop</Symbol> <arglist startline="124" /> </call> <Nil /> <block startline="124"> <call startline="124"> <Nil /> <Symbol>p</Symbol> <arglist startline="124"> <str startline="124"> <String>c</String> </str> </arglist> </call> <call startline="124"> <Nil /> <Symbol>p</Symbol> <arglist startline="124"> <str startline="124"> <String>c</String> </str> </arglist> </call> </block> </iter> <iter startline="125"> <call startline="125"> <Nil /> <Symbol>loop</Symbol> <arglist startline="125" /> </call> <Nil /> <block> <call startline="125"> <Nil /> <Symbol>p</Symbol> <arglist startline="125"> <str startline="125"> <String>c</String> </str> </arglist> </call> </block> </iter> <iter startline="126"> <call startline="126"> <Nil /> <Symbol>loop</Symbol> <arglist startline="126" /> </call> <Nil /> <block /> </iter> <defn startline="129"> <Symbol>a</Symbol> <args startline="129" /> <scope startline="129"> <block startline="129"> <call startline="129"> <Nil /> <Symbol>p</Symbol> <arglist startline="129"> <str startline="129"> <String>c</String> </str> </arglist> </call> <call startline="129"> <Nil /> <Symbol>p</Symbol> <arglist startline="129"> <str startline="129"> <String>c</String> </str> </arglist> </call> </block> </scope> </defn> <defn startline="130"> <Symbol>a</Symbol> <args startline="130" /> <scope startline="130"> <block startline="130"> <call startline="130"> <Nil /> <Symbol>p</Symbol> <arglist startline="130"> <str startline="130"> <String>c</String> </str> </arglist> </call> </block> </scope> </defn> <defn startline="131"> <Symbol>a</Symbol> <args startline="131" /> <scope startline="131"> <block startline="131"> <nil startline="131" /> </block> </scope> </defn> <iter startline="134"> <call startline="134"> <array startline="134" /> <Symbol>each</Symbol> <arglist startline="134" /> </call> <lasgn startline="134"> <Symbol>b</Symbol> </lasgn> <block startline="134"> <call startline="134"> <Nil /> <Symbol>p</Symbol> <arglist startline="134"> <lvar startline="134"> <Symbol>b</Symbol> </lvar> </arglist> </call> <call startline="134"> <Nil /> <Symbol>p</Symbol> <arglist startline="134"> <lvar startline="134"> <Symbol>b</Symbol> </lvar> </arglist> </call> </block> </iter> <iter startline="135"> <call startline="135"> <array startline="135" /> <Symbol>each</Symbol> <arglist startline="135" /> </call> <lasgn startline="135"> <Symbol>b</Symbol> </lasgn> <block> <call startline="135"> <Nil /> <Symbol>p</Symbol> <arglist startline="135"> <lvar startline="135"> <Symbol>b</Symbol> </lvar> </arglist> </call> </block> </iter> <iter startline="136"> <call startline="136"> <array startline="136" /> <Symbol>each</Symbol> <arglist startline="136" /> </call> <lasgn startline="136"> <Symbol>b</Symbol> </lasgn> <block /> </iter> <iter startline="137"> <call startline="137"> <array startline="137" /> <Symbol>each</Symbol> <arglist startline="137" /> </call> <Nil /> <block /> </iter> <iter startline="138"> <call startline="138"> <array startline="138" /> <Symbol>each</Symbol> <arglist startline="138" /> </call> <lasgn startline="138"> <Symbol>b</Symbol> </lasgn> <block> <call startline="138"> <Nil /> <Symbol>p</Symbol> <arglist startline="138"> <lvar startline="138"> <Symbol>b</Symbol> </lvar> </arglist> </call> </block> </iter> <iter startline="139"> <call startline="139"> <array startline="139" /> <Symbol>each</Symbol> <arglist startline="139" /> </call> <lasgn startline="139"> <Symbol>b</Symbol> </lasgn> <block /> </iter> <iter startline="140"> <call startline="140"> <array startline="140" /> <Symbol>each</Symbol> <arglist startline="140" /> </call> <Nil /> <block /> </iter> <iter startline="143"> <call startline="143"> <Nil /> <Symbol>lambda</Symbol> <arglist startline="143" /> </call> <masgn startline="143"> <array startline="143"> <lasgn startline="143"> <Symbol>x</Symbol> </lasgn> <lasgn startline="143"> <Symbol>y</Symbol> </lasgn> </array> </masgn> <block> <call startline="143"> <lvar startline="143"> <Symbol>x</Symbol> </lvar> <Symbol>+</Symbol> <arglist startline="143"> <lvar startline="143"> <Symbol>y</Symbol> </lvar> </arglist> </call> </block> </iter> <iter startline="144"> <call startline="144"> <Nil /> <Symbol>lambda</Symbol> <arglist startline="144" /> </call> <masgn startline="144"> <array startline="144"> <lasgn startline="144"> <Symbol>x</Symbol> </lasgn> <lasgn startline="144"> <Symbol>y</Symbol> </lasgn> </array> </masgn> <block /> </iter> <iter startline="145"> <call startline="145"> <Nil /> <Symbol>lambda</Symbol> <arglist startline="145" /> </call> <lasgn startline="145"> <Symbol>x</Symbol> </lasgn> <block> <call startline="145"> <lvar startline="145"> <Symbol>x</Symbol> </lvar> <Symbol>+</Symbol> <arglist startline="145"> <lit startline="145"> <Fixnum>1</Fixnum> </lit> </arglist> </call> </block> </iter> <iter startline="146"> <call startline="146"> <Nil /> <Symbol>lambda</Symbol> <arglist startline="146" /> </call> <lasgn startline="146"> <Symbol>x</Symbol> </lasgn> <block /> </iter> <iter startline="147"> <call startline="147"> <Nil /> <Symbol>lambda</Symbol> <arglist startline="147" /> </call> <Nil /> <block /> </iter> <iter startline="148"> <call startline="148"> <Nil /> <Symbol>lambda</Symbol> <arglist startline="148" /> </call> <lasgn startline="148"> <Symbol>x</Symbol> </lasgn> <block> <call startline="148"> <Nil /> <Symbol>p</Symbol> <arglist startline="148"> <call startline="148"> <lvar startline="148"> <Symbol>x</Symbol> </lvar> <Symbol>+</Symbol> <arglist startline="148"> <lit startline="148"> <Fixnum>1</Fixnum> </lit> </arglist> </call> </arglist> </call> </block> </iter> <iter startline="149"> <call startline="149"> <Nil /> <Symbol>lambda</Symbol> <arglist startline="149" /> </call> <lasgn startline="149"> <Symbol>x</Symbol> </lasgn> <block /> </iter> <iter startline="150"> <call startline="150"> <Nil /> <Symbol>lambda</Symbol> <arglist startline="150" /> </call> <Nil /> <block /> </iter> </block>
apache-2.0
SAP/go-hdb
driver/ioutildepr1.15.go
381
//go:build !go1.16 // +build !go1.16 // SPDX-FileCopyrightText: 2014-2022 SAP SE // // SPDX-License-Identifier: Apache-2.0 // Delete after go1.15 is out of maintenance. package driver import ( "io" "io/ioutil" ) func _readFile(filename string) ([]byte, error) { return ioutil.ReadFile(filename) } func _readAll(r io.Reader) ([]byte, error) { return ioutil.ReadAll(r) }
apache-2.0
OpenNetworking/gcoin-community
src/rpcblockchain.cpp
34649
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin Core developers // Copyright (c) 2014-2016 The Gcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "checkpoints.h" #include "consensus/validation.h" #include "main.h" #include "primitives/transaction.h" #include "rpcserver.h" #include "sync.h" #include "util.h" #include <stdint.h> #include <boost/thread.hpp> #include "json/json_spirit_value.h" using namespace json_spirit; using namespace std; extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry); void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out, bool fIncludeHex); double GetDifficulty(const CBlockIndex* blockindex) { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (blockindex == NULL) { if (chainActive.Tip() == NULL) return 1.0; else blockindex = chainActive.Tip(); } int nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails = false) { Object result; result.push_back(Pair("hash", block.GetHash().GetHex())); int confirmations = -1; // Only report confirmations if the block is on the main chain if (chainActive.Contains(blockindex)) confirmations = chainActive.Height() - blockindex->nHeight + 1; result.push_back(Pair("confirmations", confirmations)); result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION))); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); Array txs; BOOST_FOREACH(const CTransaction&tx, block.vtx) { if(txDetails) { Object objTx; TxToJSON(tx, uint256(), objTx); txs.push_back(objTx); } else txs.push_back(tx.GetHash().GetHex()); } result.push_back(Pair("tx", txs)); result.push_back(Pair("time", block.GetBlockTime())); result.push_back(Pair("starttime", block.GetBlockStartTime())); result.push_back(Pair("nonce", (uint64_t)block.nNonce)); result.push_back(Pair("bits", strprintf("%08x", block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex())); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); CBlockIndex *pnext = chainActive.Next(blockindex); if (pnext) result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex())); return result; } Value getblockcount(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw std::runtime_error( "getblockcount\n" "\nReturns the number of blocks in the longest block chain.\n" "\nResult:\n" "n (numeric) The current block count\n" "\nExamples:\n" + HelpExampleCli("getblockcount", "") + HelpExampleRpc("getblockcount", "") ); LOCK(cs_main); return chainActive.Height(); } Value getbestblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw std::runtime_error( "getbestblockhash\n" "\nReturns the hash of the best (tip) block in the longest block chain.\n" "\nResult\n" "\"hex\" (string) the block hash hex encoded\n" "\nExamples\n" + HelpExampleCli("getbestblockhash", "") + HelpExampleRpc("getbestblockhash", "") ); LOCK(cs_main); return chainActive.Tip()->GetBlockHash().GetHex(); } Value getdifficulty(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw std::runtime_error( "getdifficulty\n" "\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n" "\nResult:\n" "n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\n" "\nExamples:\n" + HelpExampleCli("getdifficulty", "") + HelpExampleRpc("getdifficulty", "") ); LOCK(cs_main); return GetDifficulty(); } Value getrawmempool(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw std::runtime_error( "getrawmempool ( verbose )\n" "\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n" "\nArguments:\n" "1. verbose (boolean, optional, default=false) true for a json object, false for array of transaction ids\n" "\nResult: (for verbose = false):\n" "[ (json array of string)\n" " \"transactionid\" (string) The transaction id\n" " ,...\n" "]\n" "\nResult: (for verbose = true):\n" "{ (json object)\n" " \"transactionid\" : { (json object)\n" " \"size\" : n, (numeric) transaction size in bytes\n" " \"fee\" : n, (numeric) transaction fee\n" " \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n" " \"height\" : n, (numeric) block height when transaction entered pool\n" " \"startingpriority\" : n, (numeric) priority when transaction entered pool\n" " \"currentpriority\" : n, (numeric) transaction priority now\n" " \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n" " \"transactionid\", (string) parent transaction id\n" " ... ]\n" " }, ...\n" "}\n" "\nExamples\n" + HelpExampleCli("getrawmempool", "true") + HelpExampleRpc("getrawmempool", "true") ); LOCK(cs_main); bool fVerbose = false; if (params.size() > 0) fVerbose = params[0].get_bool(); if (fVerbose) { LOCK(mempool.cs); Object o; BOOST_FOREACH(const PAIRTYPE(uint256, CTxMemPoolEntry)& entry, mempool.mapTx) { const uint256& hash = entry.first; const CTxMemPoolEntry& e = entry.second; Object info; info.push_back(Pair("size", (int)e.GetTxSize())); info.push_back(Pair("fee", ValueFromAmount(e.GetFee()))); info.push_back(Pair("time", e.GetTime())); info.push_back(Pair("height", (int)e.GetHeight())); info.push_back(Pair("startingpriority", e.GetPriority(e.GetHeight()))); info.push_back(Pair("currentpriority", e.GetPriority(chainActive.Height()))); const CTransaction& tx = e.GetTx(); std::set<std::string> setDepends; BOOST_FOREACH(const CTxIn& txin, tx.vin) { if (mempool.exists(txin.prevout.hash)) setDepends.insert(txin.prevout.hash.ToString()); } Array depends(setDepends.begin(), setDepends.end()); info.push_back(Pair("depends", depends)); o.push_back(Pair(hash.ToString(), info)); } return o; } else { std::vector<uint256> vtxid; mempool.queryHashes(vtxid); Array a; BOOST_FOREACH(const uint256& hash, vtxid) a.push_back(hash.ToString()); return a; } } Value getaddrmempool(const Array& params, bool fHelp) { if (fHelp || params.size() > 2 || params.size() < 1) throw std::runtime_error( "getaddrmempool ( verbose )\n" "\nReturns all transaction ids in memory pool as a json array of string transaction ids related to given address.\n" "\nArguments:\n" "1. address (string) Specific address\n" "2. verbose (boolean, optional, default=false) true for a json object, false for array of transaction ids\n" "\nResult: (for verbose = false):\n" "[ (json array of string)\n" " \"transactionid\" (string) The transaction id\n" " ,...\n" "]\n" "\nResult: (for verbose = true):\n" "{ (json object)\n" " \"transactionid\" : { (json object)\n" " \"size\" : n, (numeric) transaction size in bytes\n" " \"fee\" : n, (numeric) transaction fee\n" " \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n" " \"height\" : n, (numeric) block height when transaction entered pool\n" " \"startingpriority\" : n, (numeric) priority when transaction entered pool\n" " \"currentpriority\" : n, (numeric) transaction priority now\n" " \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n" " \"transactionid\", (string) parent transaction id\n" " ... ]\n" " }, ...\n" "]\n" "\nExamples\n" + HelpExampleCli("getaddrmempool", "true") + HelpExampleRpc("getaddrmempool", "true") ); bool fVerbose = false; std::string addr = params[0].get_str(); if (params.size() > 1) fVerbose = params[1].get_bool(); Object o; Array a; typedef std::pair<const uint256, const CTxMemPoolEntry> mapit_t; BOOST_FOREACH(const mapit_t &it, mempool.mapTx) { LOCK(mempool.cs); const uint256& hash = it.first; const CTxMemPoolEntry& e = it.second; const CTransaction& tx = e.GetTx(); bool fAddr = false; TxInfo txinfo(tx); for (unsigned int index = 0; !fAddr && index < txinfo.GetTxOutSize(); index++) { if (addr == txinfo.GetTxOutAddressOfIndex(index)) fAddr = true; } BOOST_FOREACH(const CTxIn txin, tx.vin) { if (fAddr) break; TxInfo txinfoIn; if (!txinfoIn.init(txin.prevout, NULL)) { continue; } else if (addr == txinfoIn.GetTxOutAddressOfIndex(txin.prevout.n)) fAddr = true; } if (!fAddr) continue; if (fVerbose) { Object info; info.push_back(Pair("size", (int)e.GetTxSize())); info.push_back(Pair("fee", ValueFromAmount(e.GetFee()))); info.push_back(Pair("time", e.GetTime())); info.push_back(Pair("height", (int)e.GetHeight())); info.push_back(Pair("startingpriority", e.GetPriority(e.GetHeight()))); info.push_back(Pair("currentpriority", e.GetPriority(chainActive.Height()))); std::set<std::string> setDepends; BOOST_FOREACH(const CTxIn& txin, tx.vin) { if (mempool.exists(txin.prevout.hash)) setDepends.insert(txin.prevout.hash.ToString()); } Array depends(setDepends.begin(), setDepends.end()); info.push_back(Pair("depends", depends)); o.push_back(Pair(hash.ToString(), info)); } else { a.push_back(hash.ToString()); } } if (fVerbose) return o; else return a; } Value getblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw std::runtime_error( "getblockhash index\n" "\nReturns hash of block in best-block-chain at index provided.\n" "\nArguments:\n" "1. index (numeric, required) The block index\n" "\nResult:\n" "\"hash\" (string) The block hash\n" "\nExamples:\n" + HelpExampleCli("getblockhash", "1000") + HelpExampleRpc("getblockhash", "1000") ); LOCK(cs_main); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > chainActive.Height()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range"); CBlockIndex* pblockindex = chainActive[nHeight]; return pblockindex->GetBlockHash().GetHex(); } Value getblock(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw std::runtime_error( "getblock \"hash\" ( verbose )\n" "\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash'.\n" "If verbose is true, returns an Object with information about block <hash>.\n" "\nArguments:\n" "1. \"hash\" (string, required) The block hash\n" "2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n" "\nResult (for verbose = true):\n" "{\n" " \"hash\" : \"hash\", (string) the block hash (same as provided)\n" " \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n" " \"size\" : n, (numeric) The block size\n" " \"height\" : n, (numeric) The block height or index\n" " \"version\" : n, (numeric) The block version\n" " \"merkleroot\" : \"xxxx\", (string) The merkle root\n" " \"tx\" : [ (array of string) The transaction ids\n" " \"transactionid\" (string) The transaction id\n" " ,...\n" " ],\n" " \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"nonce\" : n, (numeric) The nonce\n" " \"bits\" : \"1d00ffff\", (string) The bits\n" " \"difficulty\" : x.xxx, (numeric) The difficulty\n" " \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n" " \"nextblockhash\" : \"hash\" (string) The hash of the next block\n" "}\n" "\nResult (for verbose=false):\n" "\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n" "\nExamples:\n" + HelpExampleCli("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"") + HelpExampleRpc("getblock", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"") ); LOCK(cs_main); std::string strHash = params[0].get_str(); uint256 hash(uint256S(strHash)); bool fVerbose = true; if (params.size() > 1) fVerbose = params[1].get_bool(); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0) throw JSONRPCError(RPC_INTERNAL_ERROR, "Block not available (pruned data)"); if(!ReadBlockFromDisk(block, pblockindex)) throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk"); if (!fVerbose) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION); ssBlock << block; std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()); return strHex; } return blockToJSON(block, pblockindex); } Value gettxoutsetinfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw std::runtime_error( "gettxoutsetinfo\n" "\nReturns statistics about the unspent transaction output set.\n" "Note this call may take some time.\n" "\nResult:\n" "{\n" " \"height\":n, (numeric) The current block height (index)\n" " \"bestblock\": \"hex\", (string) the best block hash hex\n" " \"transactions\": n, (numeric) The number of transactions\n" " \"txouts\": n, (numeric) The number of output transactions\n" " \"bytes_serialized\": n, (numeric) The serialized size\n" " \"hash_serialized\": \"hash\", (string) The serialized hash\n" " \"total_amount\": x.xxx (numeric) The total amount\n" "}\n" "\nExamples:\n" + HelpExampleCli("gettxoutsetinfo", "") + HelpExampleRpc("gettxoutsetinfo", "") ); LOCK(cs_main); Object ret; CCoinsStats stats; FlushStateToDisk(); if (pcoinsTip->GetStats(stats)) { ret.push_back(Pair("height", (int64_t)stats.nHeight)); ret.push_back(Pair("bestblock", stats.hashBlock.GetHex())); ret.push_back(Pair("transactions", (int64_t)stats.nTransactions)); ret.push_back(Pair("txouts", (int64_t)stats.nTransactionOutputs)); ret.push_back(Pair("bytes_serialized", (int64_t)stats.nSerializedSize)); ret.push_back(Pair("hash_serialized", stats.hashSerialized.GetHex())); Array arrColorAmount; for (colorAmount_t::iterator it = stats.mapTotalAmount.begin(); it != stats.mapTotalAmount.end(); it++) { Object temp; temp.push_back(Pair(boost::to_string(it->first), ValueFromAmount(it->second))); arrColorAmount.push_back(temp); } ret.push_back(Pair("color_amount", arrColorAmount)); } return ret; } Value gettxout(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) throw std::runtime_error( "gettxout \"txid\" n ( includemempool )\n" "\nReturns details about an unspent transaction output.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id\n" "2. n (numeric, required) vout value\n" "3. includemempool (boolean, optional) Whether to included the mem pool\n" "\nResult:\n" "{\n" " \"bestblock\" : \"hash\", (string) the block hash\n" " \"confirmations\" : n, (numeric) The number of confirmations\n" " \"value\" : x.xxx, (numeric) The transaction value in btc\n" " \"scriptPubKey\" : { (json object)\n" " \"asm\" : \"code\", (string) \n" " \"hex\" : \"hex\", (string) \n" " \"reqSigs\" : n, (numeric) Number of required signatures\n" " \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n" " \"addresses\" : [ (array of string) array of gcoin addresses\n" " \"address\" (string) gcoin address\n" " ,...\n" " ]\n" " },\n" " \"version\" : n, (numeric) The version\n" " \"coinbase\" : true|false (boolean) Coinbase or not\n" "}\n" "\nExamples:\n" "\nGet unspent transactions\n" + HelpExampleCli("listunspent", "") + "\nView the details\n" + HelpExampleCli("gettxout", "\"txid\" 1") + "\nAs a json rpc call\n" + HelpExampleRpc("gettxout", "\"txid\", 1") ); LOCK(cs_main); Object ret; std::string strHash = params[0].get_str(); uint256 hash(uint256S(strHash)); int n = params[1].get_int(); bool fMempool = true; if (params.size() > 2) fMempool = params[2].get_bool(); CCoins coins; if (fMempool) { LOCK(mempool.cs); CCoinsViewMemPool view(pcoinsTip, mempool); if (!view.GetCoins(hash, coins)) return Value::null; mempool.pruneSpent(hash, coins); // TODO: this should be done by the CCoinsViewMemPool } else { if (!pcoinsTip->GetCoins(hash, coins)) return Value::null; } if (n<0 || (unsigned int)n>=coins.vout.size() || coins.vout[n].IsNull()) return Value::null; BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock()); CBlockIndex *pindex = it->second; ret.push_back(Pair("bestblock", pindex->GetBlockHash().GetHex())); if ((unsigned int)coins.nHeight == MEMPOOL_HEIGHT) ret.push_back(Pair("confirmations", 0)); else ret.push_back(Pair("confirmations", pindex->nHeight - coins.nHeight + 1)); ret.push_back(Pair("value", ValueFromAmount(coins.vout[n].nValue))); Object o; ScriptPubKeyToJSON(coins.vout[n].scriptPubKey, o, true); ret.push_back(Pair("scriptPubKey", o)); ret.push_back(Pair("version", coins.nVersion)); ret.push_back(Pair("coinbase", coins.fCoinBase)); return ret; } Value gettxoutaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw std::runtime_error( "gettxoutaddress \"address\" ( includemempool ) ( returnlicense )\n" "\nReturns transaction output for a determined address.\n" "\nArguments:\n" "1. \"address\" (string, required) The transaction id\n" "2. includemempool (boolean, optional) Whether to include the mempool\n" "3. returnlicense (numeric, optional, default=0) If 0, return coin, otherwise return license\n" "\nResult:\n" "{\n" " \"tx\" : \"hash\", (string) the transaction hash\n" " \"vout\" : n, (numeric) vout index\n" " \"color\" : n, (numeric) color\n" " \"value\" : n, (numeric) value\n" "}\n" "\nExamples:\n" "\nGet unspent transactions for determined address\n" + HelpExampleCli("gettxoutaddress", "\"address\"") + "\nAs a json rpc call\n" + HelpExampleRpc("gettxoutaddress", "\"address\"") ); LOCK(cs_main); std::string address = params[0].get_str(); bool fMempool = true; if (params.size() > 1) fMempool = params[1].get_bool(); bool fLicense = false; if (params.size() > 2) fLicense = (params[2].get_int() != 0); CTxOutMap mapTxOut; FlushStateToDisk(); if (fMempool) { LOCK(mempool.cs); CCoinsViewMemPool view(pcoinsTip, mempool); if (!view.GetAddrCoins(address, mapTxOut, fLicense)) return Value::null; } else { if (!pcoinsTip->GetAddrCoins(address, mapTxOut, fLicense)) return Value::null; } if (mapTxOut.size() == 0) return Value::null; Array ret; for (CTxOutMap::iterator it = mapTxOut.begin(); it != mapTxOut.end(); it++) { Object info; uint256 hash = it->first.hash; unsigned int index = it->first.n; CTxOut out = it->second; info.push_back(Pair("txid", hash.GetHex())); info.push_back(Pair("vout", (uint64_t)index)); info.push_back(Pair("color", (uint64_t)out.color)); info.push_back(Pair("value", ValueFromAmount(out.nValue))); info.push_back(Pair("scriptPubKey", HexStr(out.scriptPubKey.begin(), out.scriptPubKey.end()))); ret.push_back(info); } return ret; } Value verifychain(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw std::runtime_error( "verifychain ( checklevel numblocks )\n" "\nVerifies blockchain database.\n" "\nArguments:\n" "1. checklevel (numeric, optional, 0-4, default=3) How thorough the block verification is.\n" "2. numblocks (numeric, optional, default=288, 0=all) The number of blocks to check.\n" "\nResult:\n" "true|false (boolean) Verified or not\n" "\nExamples:\n" + HelpExampleCli("verifychain", "") + HelpExampleRpc("verifychain", "") ); LOCK(cs_main); int nCheckLevel = GetArg("-checklevel", 3); int nCheckDepth = GetArg("-checkblocks", 288); if (params.size() > 0) nCheckLevel = params[0].get_int(); if (params.size() > 1) nCheckDepth = params[1].get_int(); return CVerifyDB().VerifyDB(pcoinsTip, nCheckLevel, nCheckDepth); } Value getblockchaininfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw std::runtime_error( "getblockchaininfo\n" "Returns an object containing various state info regarding block chain processing.\n" "\nResult:\n" "{\n" " \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n" " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n" " \"headers\": xxxxxx, (numeric) the current number of headers we have validated\n" " \"bestblockhash\": \"...\", (string) the hash of the currently best block\n" " \"difficulty\": xxxxxx, (numeric) the current difficulty\n" " \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n" "}\n" "\nExamples:\n" + HelpExampleCli("getblockchaininfo", "") + HelpExampleRpc("getblockchaininfo", "") ); LOCK(cs_main); Object obj; obj.push_back(Pair("chain", Params().NetworkIDString())); obj.push_back(Pair("blocks", (int)chainActive.Height())); obj.push_back(Pair("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1)); obj.push_back(Pair("bestblockhash", chainActive.Tip()->GetBlockHash().GetHex())); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("chainwork", chainActive.Tip()->nChainWork.GetHex())); obj.push_back(Pair("pruned", fPruneMode)); if (fPruneMode) { CBlockIndex *block = chainActive.Tip(); while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA)) block = block->pprev; obj.push_back(Pair("pruneheight", block->nHeight)); } return obj; } /** Comparison function for sorting the getchaintips heads. */ struct CompareBlocksByHeight { bool operator()(const CBlockIndex* a, const CBlockIndex* b) const { /* Make sure that unequal blocks with the same height do not compare equal. Use the pointers themselves to make a distinction. */ if (a->nHeight != b->nHeight) return (a->nHeight > b->nHeight); return a < b; } }; Value getchaintips(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw std::runtime_error( "getchaintips\n" "Return information about all known tips in the block tree," " including the main chain as well as orphaned branches.\n" "\nResult:\n" "[\n" " {\n" " \"height\": xxxx, (numeric) height of the chain tip\n" " \"hash\": \"xxxx\", (string) block hash of the tip\n" " \"branchlen\": 0 (numeric) zero for main chain\n" " \"status\": \"active\" (string) \"active\" for the main chain\n" " },\n" " {\n" " \"height\": xxxx,\n" " \"hash\": \"xxxx\",\n" " \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n" " \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n" " }\n" "]\n" "Possible values for status:\n" "1. \"invalid\" This branch contains at least one invalid block\n" "2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n" "3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n" "4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n" "5. \"active\" This is the tip of the active main chain, which is certainly valid\n" "\nExamples:\n" + HelpExampleCli("getchaintips", "") + HelpExampleRpc("getchaintips", "") ); LOCK(cs_main); /* Build up a list of chain tips. We start with the list of all known blocks, and successively remove blocks that appear as pprev of another block. */ std::set<const CBlockIndex*, CompareBlocksByHeight> setTips; BOOST_FOREACH(const PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex) setTips.insert(item.second); BOOST_FOREACH(const PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex) { const CBlockIndex* pprev = item.second->pprev; if (pprev) setTips.erase(pprev); } // Always report the currently active tip. setTips.insert(chainActive.Tip()); /* Construct the output array. */ Array res; BOOST_FOREACH(const CBlockIndex* block, setTips) { Object obj; obj.push_back(Pair("height", block->nHeight)); obj.push_back(Pair("hash", block->phashBlock->GetHex())); const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight; obj.push_back(Pair("branchlen", branchLen)); string status; if (chainActive.Contains(block)) { // This block is part of the currently active chain. status = "active"; } else if (block->nStatus & BLOCK_FAILED_MASK) { // This block or one of its ancestors is invalid. status = "invalid"; } else if (block->nChainTx == 0) { // This block cannot be connected because full block data for it or one of its parents is missing. status = "headers-only"; } else if (block->IsValid(BLOCK_VALID_SCRIPTS)) { // This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized. status = "valid-fork"; } else if (block->IsValid(BLOCK_VALID_TREE)) { // The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain. status = "valid-headers"; } else { // No clue. status = "unknown"; } obj.push_back(Pair("status", status)); res.push_back(obj); } return res; } Value getmempoolinfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw std::runtime_error( "getmempoolinfo\n" "\nReturns details on the active state of the TX memory pool.\n" "\nResult:\n" "{\n" " \"size\": xxxxx (numeric) Current tx count\n" " \"bytes\": xxxxx (numeric) Sum of all tx sizes\n" "}\n" "\nExamples:\n" + HelpExampleCli("getmempoolinfo", "") + HelpExampleRpc("getmempoolinfo", "") ); Object ret; ret.push_back(Pair("size", (int64_t) mempool.size())); ret.push_back(Pair("bytes", (int64_t) mempool.GetTotalTxSize())); return ret; } Value invalidateblock(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "invalidateblock \"hash\"\n" "\nPermanently marks a block as invalid, as if it violated a consensus rule.\n" "\nArguments:\n" "1. hash (string, required) the hash of the block to mark as invalid\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("invalidateblock", "\"blockhash\"") + HelpExampleRpc("invalidateblock", "\"blockhash\"") ); std::string strHash = params[0].get_str(); uint256 hash(uint256S(strHash)); CValidationState state; { LOCK(cs_main); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlockIndex* pblockindex = mapBlockIndex[hash]; InvalidateBlock(state, pblockindex); } if (state.IsValid()) { ActivateBestChain(state); } if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason()); } return Value::null; } Value reconsiderblock(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "reconsiderblock \"hash\"\n" "\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\n" "This can be used to undo the effects of invalidateblock.\n" "\nArguments:\n" "1. hash (string, required) the hash of the block to reconsider\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("reconsiderblock", "\"blockhash\"") + HelpExampleRpc("reconsiderblock", "\"blockhash\"") ); std::string strHash = params[0].get_str(); uint256 hash(uint256S(strHash)); CValidationState state; { LOCK(cs_main); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlockIndex* pblockindex = mapBlockIndex[hash]; ReconsiderBlock(state, pblockindex); } if (state.IsValid()) { ActivateBestChain(state); } if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason()); } return Value::null; }
apache-2.0
arquillian/arquillian-extension-warp
impl/src/main/java/org/jboss/arquillian/warp/impl/client/proxy/URLMapping.java
1216
/* * JBoss, Home of Professional Open Source * Copyright 2012, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * 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.jboss.arquillian.warp.impl.client.proxy; import java.net.URL; /** * Singleton services for tracking * * @author Lukas Fryc */ public interface URLMapping { /** * <p> * Returns a proxy URL for given real URL. * </p> * <p> * <p> * If no proxy URL was registered for given real URL, new URL to be used by proxy is generated. * </p> */ URL getProxyURL(URL realUrl); }
apache-2.0
box/mojito
webapp/src/main/java/com/box/l10n/mojito/android/strings/AndroidStringDocumentReader.java
1683
package com.box.l10n.mojito.android.strings; import com.google.common.base.Strings; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.util.LinkedList; import java.util.Queue; import static com.box.l10n.mojito.android.strings.AndroidStringDocumentUtils.documentBuilder; public class AndroidStringDocumentReader { public static AndroidStringDocument fromFile(String fileName) throws ParserConfigurationException, IOException, SAXException { return buildFromDocument(documentBuilder().parse(new File(fileName))); } public static AndroidStringDocument fromText(String text) throws ParserConfigurationException, IOException, SAXException { return buildFromDocument(documentBuilder().parse(new InputSource(new StringReader(Strings.nullToEmpty(text))))); } private static AndroidStringDocument buildFromDocument(Document source) { Queue<Node> commentNodes = new LinkedList<>(); AndroidStringDocument document = new AndroidStringDocument(); Node node; for (int i = 0; i < source.getDocumentElement().getChildNodes().getLength(); i++) { node = source.getDocumentElement().getChildNodes().item(i); if (Node.COMMENT_NODE == node.getNodeType()) { commentNodes.offer(node); } else if (Node.ELEMENT_NODE == node.getNodeType()) { document.addElement(node, commentNodes.poll()); } } return document; } }
apache-2.0
chenbillcat/AuthDog
authdog/tests/test_functional.py
688
from unittest import TestCase from webtest import TestApp from authdog.tests import FunctionalTest class TestRootController(FunctionalTest): def test_get(self): response = self.app.get('/') assert response.status_int == 200 def test_search(self): response = self.app.post('/', params={'q': 'RestController'}) assert response.status_int == 302 assert response.headers['Location'] == ( 'https://pecan.readthedocs.io/en/latest/search.html' '?q=RestController' ) def test_get_not_found(self): response = self.app.get('/a/bogus/url', expect_errors=True) assert response.status_int == 404
apache-2.0
SheldonNunes/Twilight-Imperium-Companion-App
TwilightImperiumMasterCompanion.iOS/ViewControllers/Race/RaceSetupView.designer.cs
1813
// WARNING // // This file has been generated automatically by Visual Studio from the outlets and // actions declared in your storyboard file. // Manual changes to this file will not be maintained. // using Foundation; using System; using System.CodeDom.Compiler; using UIKit; namespace TwilightImperiumMasterCompanion.iOS { [Register ("RaceSetupView")] partial class RaceSetupView { [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UICollectionView startingPlanetsCollectionView { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UITextView startingTechnologiesTextView { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UICollectionView startingUnitsCollectionView { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.NSLayoutConstraint startingUnitViewHeightConstraint { get; set; } void ReleaseDesignerOutlets () { if (startingPlanetsCollectionView != null) { startingPlanetsCollectionView.Dispose (); startingPlanetsCollectionView = null; } if (startingTechnologiesTextView != null) { startingTechnologiesTextView.Dispose (); startingTechnologiesTextView = null; } if (startingUnitsCollectionView != null) { startingUnitsCollectionView.Dispose (); startingUnitsCollectionView = null; } if (startingUnitViewHeightConstraint != null) { startingUnitViewHeightConstraint.Dispose (); startingUnitViewHeightConstraint = null; } } } }
apache-2.0
bbxyard/bbxyard
yard/skills/66-java/mp-study/mp-comb-search/src/main/java/com/bbxyard/mp/comb/config/MPConfig.java
529
package com.bbxyard.mp.comb.config; import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableTransactionManagement public class MPConfig { /** * 分页插件 */ @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } }
apache-2.0
dobbymoodge/origin
test/extended/util/framework.go
46707
package util import ( "fmt" "io/ioutil" "net/http" "os" "os/exec" "path" "path/filepath" "regexp" "strings" "sync" "time" g "github.com/onsi/ginkgo" o "github.com/onsi/gomega" "k8s.io/kubernetes/pkg/api/legacyscheme" batchv1 "k8s.io/api/batch/v1" kapiv1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/selection" "k8s.io/apimachinery/pkg/util/uuid" "k8s.io/apimachinery/pkg/util/wait" kclientset "k8s.io/client-go/kubernetes" kbatchclient "k8s.io/client-go/kubernetes/typed/batch/v1" kcoreclient "k8s.io/client-go/kubernetes/typed/core/v1" "k8s.io/kubernetes/pkg/apis/authorization" kapi "k8s.io/kubernetes/pkg/apis/core" kinternalcoreclient "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion" "k8s.io/kubernetes/pkg/quota" e2e "k8s.io/kubernetes/test/e2e/framework" "github.com/openshift/origin/pkg/api/apihelpers" appsapi "github.com/openshift/origin/pkg/apps/apis/apps" appstypeclientset "github.com/openshift/origin/pkg/apps/generated/internalclientset/typed/apps/internalversion" appsutil "github.com/openshift/origin/pkg/apps/util" buildapi "github.com/openshift/origin/pkg/build/apis/build" buildtypedclientset "github.com/openshift/origin/pkg/build/generated/internalclientset/typed/build/internalversion" "github.com/openshift/origin/pkg/git" imageapi "github.com/openshift/origin/pkg/image/apis/image" imagetypeclientset "github.com/openshift/origin/pkg/image/generated/internalclientset/typed/image/internalversion" "github.com/openshift/origin/test/extended/testdata" "github.com/openshift/origin/test/util" ) const pvPrefix = "pv-" const nfsPrefix = "nfs-" // WaitForOpenShiftNamespaceImageStreams waits for the standard set of imagestreams to be imported func WaitForOpenShiftNamespaceImageStreams(oc *CLI) error { langs := []string{"ruby", "nodejs", "perl", "php", "python", "wildfly", "mysql", "postgresql", "mongodb", "jenkins"} scan := func() bool { for _, lang := range langs { e2e.Logf("Checking language %v \n", lang) is, err := oc.ImageClient().Image().ImageStreams("openshift").Get(lang, metav1.GetOptions{}) if err != nil { e2e.Logf("ImageStream Error: %#v \n", err) return false } for tag := range is.Spec.Tags { e2e.Logf("Checking tag %v \n", tag) if _, ok := is.Status.Tags[tag]; !ok { e2e.Logf("Tag Error: %#v \n", ok) return false } } } return true } success := false for i := 0; i < 10; i++ { e2e.Logf("Running scan #%v \n", i) success = scan() if success { break } e2e.Logf("Sleeping for 3 seconds \n") time.Sleep(3 * time.Second) } if success { e2e.Logf("Success! \n") return nil } DumpImageStreams(oc) return fmt.Errorf("Failed to import expected imagestreams") } // CheckOpenShiftNamespaceImageStreams is a temporary workaround for the intermittent // issue seen in extended tests where *something* is deleteing the pre-loaded, languange // imagestreams from the OpenShift namespace func CheckOpenShiftNamespaceImageStreams(oc *CLI) { missing := false langs := []string{"ruby", "nodejs", "perl", "php", "python", "wildfly", "mysql", "postgresql", "mongodb", "jenkins"} for _, lang := range langs { _, err := oc.ImageClient().Image().ImageStreams("openshift").Get(lang, metav1.GetOptions{}) if err != nil { missing = true break } } if missing { fmt.Fprint(g.GinkgoWriter, "\n\n openshift namespace image streams corrupted \n\n") DumpImageStreams(oc) out, err := oc.Run("get").Args("is", "-n", "openshift", "--config", KubeConfigPath()).Output() err = fmt.Errorf("something has tampered with the image streams in the openshift namespace; look at audits in master log; \n%s\n", out) o.Expect(err).NotTo(o.HaveOccurred()) } else { fmt.Fprint(g.GinkgoWriter, "\n\n openshift namespace image streams OK \n\n") } } //DumpImageStreams will dump both the openshift namespace and local namespace imagestreams // as part of debugging when the language imagestreams in the openshift namespace seem to disappear func DumpImageStreams(oc *CLI) { out, err := oc.AsAdmin().Run("get").Args("is", "-n", "openshift", "-o", "yaml", "--config", KubeConfigPath()).Output() if err == nil { e2e.Logf("\n imagestreams in openshift namespace: \n%s\n", out) } else { e2e.Logf("\n error on getting imagestreams in openshift namespace: %+v\n%#v\n", err, out) } out, err = oc.AsAdmin().Run("get").Args("is", "-o", "yaml").Output() if err == nil { e2e.Logf("\n imagestreams in dynamic test namespace: \n%s\n", out) } else { e2e.Logf("\n error on getting imagestreams in dynamic test namespace: %+v\n%#v\n", err, out) } ids, err := ListImages() if err != nil { e2e.Logf("\n got error on docker images %+v\n", err) } else { for _, id := range ids { e2e.Logf(" found local image %s\n", id) } } } // DumpBuildLogs will dump the latest build logs for a BuildConfig for debug purposes func DumpBuildLogs(bc string, oc *CLI) { buildOutput, err := oc.AsAdmin().Run("logs").Args("-f", "bc/"+bc, "--timestamps").Output() if err == nil { e2e.Logf("\n\n build logs : %s\n\n", buildOutput) } else { e2e.Logf("\n\n got error on build logs %+v\n\n", err) } // if we suspect that we are filling up the registry file system, call ExamineDiskUsage / ExaminePodDiskUsage // also see if manipulations of the quota around /mnt/openshift-xfs-vol-dir exist in the extended test set up scripts ExamineDiskUsage() ExaminePodDiskUsage(oc) } // DumpBuilds will dump the yaml for every build in the test namespace; remember, pipeline builds // don't have build pods so a generic framework dump won't cat our pipeline builds objs in openshift func DumpBuilds(oc *CLI) { buildOutput, err := oc.AsAdmin().Run("get").Args("builds", "-o", "yaml").Output() if err == nil { e2e.Logf("\n\n builds yaml:\n%s\n\n", buildOutput) } else { e2e.Logf("\n\n got error on build yaml dump: %#v\n\n", err) } } func GetDeploymentConfigPods(oc *CLI, dcName string, version int64) (*kapiv1.PodList, error) { return oc.AdminKubeClient().CoreV1().Pods(oc.Namespace()).List(metav1.ListOptions{LabelSelector: ParseLabelsOrDie(fmt.Sprintf("%s=%s-%d", appsapi.DeployerPodForDeploymentLabel, dcName, version)).String()}) } func GetApplicationPods(oc *CLI, dcName string) (*kapiv1.PodList, error) { return oc.AdminKubeClient().CoreV1().Pods(oc.Namespace()).List(metav1.ListOptions{LabelSelector: ParseLabelsOrDie(fmt.Sprintf("deploymentconfig=%s", dcName)).String()}) } func GetStatefulSetPods(oc *CLI, setName string) (*kapiv1.PodList, error) { return oc.AdminKubeClient().CoreV1().Pods(oc.Namespace()).List(metav1.ListOptions{LabelSelector: ParseLabelsOrDie(fmt.Sprintf("name=%s", setName)).String()}) } // DumpDeploymentLogs will dump the latest deployment logs for a DeploymentConfig for debug purposes func DumpDeploymentLogs(dcName string, version int64, oc *CLI) { e2e.Logf("Dumping deployment logs for deploymentconfig %q\n", dcName) pods, err := GetDeploymentConfigPods(oc, dcName, version) if err != nil { e2e.Logf("Unable to retrieve pods for deploymentconfig %q: %v\n", dcName, err) return } DumpPodLogs(pods.Items, oc) } // DumpApplicationPodLogs will dump the latest application logs for a DeploymentConfig for debug purposes func DumpApplicationPodLogs(dcName string, oc *CLI) { e2e.Logf("Dumping application logs for deploymentconfig %q\n", dcName) pods, err := GetApplicationPods(oc, dcName) if err != nil { e2e.Logf("Unable to retrieve pods for deploymentconfig %q: %v\n", dcName, err) return } DumpPodLogs(pods.Items, oc) } func DumpPodStates(oc *CLI) { e2e.Logf("Dumping pod state for namespace %s", oc.Namespace()) out, err := oc.AsAdmin().Run("get").Args("pods", "-o", "yaml").Output() if err != nil { e2e.Logf("Error dumping pod states: %v", err) return } e2e.Logf(out) } // DumpPodLogsStartingWith will dump any pod starting with the name prefix provided func DumpPodLogsStartingWith(prefix string, oc *CLI) { podsToDump := []kapiv1.Pod{} podList, err := oc.AdminKubeClient().CoreV1().Pods(oc.Namespace()).List(metav1.ListOptions{}) if err != nil { e2e.Logf("Error listing pods: %v", err) return } for _, pod := range podList.Items { if strings.HasPrefix(pod.Name, prefix) { podsToDump = append(podsToDump, pod) } } if len(podsToDump) > 0 { DumpPodLogs(podsToDump, oc) } } // DumpPodLogsStartingWith will dump any pod starting with the name prefix provided func DumpPodLogsStartingWithInNamespace(prefix, namespace string, oc *CLI) { podsToDump := []kapiv1.Pod{} podList, err := oc.AdminKubeClient().CoreV1().Pods(namespace).List(metav1.ListOptions{}) if err != nil { e2e.Logf("Error listing pods: %v", err) return } for _, pod := range podList.Items { if strings.HasPrefix(pod.Name, prefix) { podsToDump = append(podsToDump, pod) } } if len(podsToDump) > 0 { DumpPodLogs(podsToDump, oc) } } func DumpPodLogs(pods []kapiv1.Pod, oc *CLI) { for _, pod := range pods { descOutput, err := oc.AsAdmin().Run("describe").Args("pod/" + pod.Name).Output() if err == nil { e2e.Logf("Describing pod %q\n%s\n\n", pod.Name, descOutput) } else { e2e.Logf("Error retrieving description for pod %q: %v\n\n", pod.Name, err) } dumpContainer := func(container *kapiv1.Container) { depOutput, err := oc.AsAdmin().Run("logs").WithoutNamespace().Args("pod/"+pod.Name, "-c", container.Name, "-n", pod.Namespace).Output() if err == nil { e2e.Logf("Log for pod %q/%q\n---->\n%s\n<----end of log for %[1]q/%[2]q\n", pod.Name, container.Name, depOutput) } else { e2e.Logf("Error retrieving logs for pod %q/%q: %v\n\n", pod.Name, container.Name, err) } } for _, c := range pod.Spec.InitContainers { dumpContainer(&c) } for _, c := range pod.Spec.Containers { dumpContainer(&c) } } } // DumpPodsCommand runs the provided command in every pod identified by selector in the provided namespace. func DumpPodsCommand(c kclientset.Interface, ns string, selector labels.Selector, cmd string) { podList, err := c.CoreV1().Pods(ns).List(metav1.ListOptions{LabelSelector: selector.String()}) o.Expect(err).NotTo(o.HaveOccurred()) values := make(map[string]string) for _, pod := range podList.Items { stdout, err := e2e.RunHostCmdWithRetries(pod.Namespace, pod.Name, cmd, e2e.StatefulSetPoll, e2e.StatefulPodTimeout) o.Expect(err).NotTo(o.HaveOccurred()) values[pod.Name] = stdout } for name, stdout := range values { stdout = strings.TrimSuffix(stdout, "\n") e2e.Logf(name + ": " + strings.Join(strings.Split(stdout, "\n"), fmt.Sprintf("\n%s: ", name))) } } // GetMasterThreadDump will get a golang thread stack dump func GetMasterThreadDump(oc *CLI) { out, err := oc.AsAdmin().Run("get").Args("--raw", "/debug/pprof/goroutine?debug=2").Output() if err == nil { e2e.Logf("\n\n Master thread stack dump:\n\n%s\n\n", string(out)) return } e2e.Logf("\n\n got error on oc get --raw /debug/pprof/goroutine?godebug=2: %v\n\n", err) } // ExamineDiskUsage will dump df output on the testing system; leveraging this as part of diagnosing // the registry's disk filling up during external tests on jenkins func ExamineDiskUsage() { // disabling this for now, easier to do it here than everywhere that's calling it. return /* out, err := exec.Command("/bin/df", "-m").Output() if err == nil { e2e.Logf("\n\n df -m output: %s\n\n", string(out)) } else { e2e.Logf("\n\n got error on df %v\n\n", err) } DumpDockerInfo() */ } // DumpDockerInfo runs `docker info` and logs it to the job output func DumpDockerInfo() { out, err := exec.Command("/bin/docker", "info").Output() if err == nil { e2e.Logf("\n\n docker info output: \n%s\n\n", string(out)) } else { e2e.Logf("\n\n got error on docker inspect %v\n\n", err) } } // ExaminePodDiskUsage will dump df/du output on registry pod; leveraging this as part of diagnosing // the registry's disk filling up during external tests on jenkins func ExaminePodDiskUsage(oc *CLI) { // disabling this for now, easier to do it here than everywhere that's calling it. return /* out, err := oc.Run("get").Args("pods", "-o", "json", "-n", "default", "--config", KubeConfigPath()).Output() var podName string if err == nil { b := []byte(out) var list kapiv1.PodList err = json.Unmarshal(b, &list) if err == nil { for _, pod := range list.Items { e2e.Logf("\n\n looking at pod %s \n\n", pod.ObjectMeta.Name) if strings.Contains(pod.ObjectMeta.Name, "docker-registry-") && !strings.Contains(pod.ObjectMeta.Name, "deploy") { podName = pod.ObjectMeta.Name break } } } else { e2e.Logf("\n\n got json unmarshal err: %v\n\n", err) } } else { e2e.Logf("\n\n got error on get pods: %v\n\n", err) } if len(podName) == 0 { e2e.Logf("Unable to determine registry pod name, so we can't examine its disk usage.") return } out, err = oc.Run("exec").Args("-n", "default", podName, "df", "--config", KubeConfigPath()).Output() if err == nil { e2e.Logf("\n\n df from registry pod: \n%s\n\n", out) } else { e2e.Logf("\n\n got error on reg pod df: %v\n", err) } out, err = oc.Run("exec").Args("-n", "default", podName, "du", "/registry", "--config", KubeConfigPath()).Output() if err == nil { e2e.Logf("\n\n du from registry pod: \n%s\n\n", out) } else { e2e.Logf("\n\n got error on reg pod du: %v\n", err) } */ } // VarSubOnFile reads in srcFile, finds instances of ${key} from the map // and replaces them with their associated values. func VarSubOnFile(srcFile string, destFile string, vars map[string]string) error { srcData, err := ioutil.ReadFile(srcFile) if err == nil { srcString := string(srcData) for k, v := range vars { k = "${" + k + "}" srcString = strings.Replace(srcString, k, v, -1) // -1 means unlimited replacements } err = ioutil.WriteFile(destFile, []byte(srcString), 0644) } return err } // StartBuild executes OC start-build with the specified arguments. StdOut and StdErr from the process // are returned as separate strings. func StartBuild(oc *CLI, args ...string) (stdout, stderr string, err error) { stdout, stderr, err = oc.Run("start-build").Args(args...).Outputs() e2e.Logf("\n\nstart-build output with args %v:\nError>%v\nStdOut>\n%s\nStdErr>\n%s\n\n", args, err, stdout, stderr) return stdout, stderr, err } var buildPathPattern = regexp.MustCompile(`^build/([\w\-\._]+)$`) type LogDumperFunc func(oc *CLI, br *BuildResult) (string, error) func NewBuildResult(oc *CLI, build *buildapi.Build) *BuildResult { return &BuildResult{ Oc: oc, BuildName: build.Name, BuildPath: "builds/" + build.Name, } } type BuildResult struct { // BuildPath is a resource qualified name (e.g. "build/test-1"). BuildPath string // BuildName is the non-resource qualified name. BuildName string // StartBuildStdErr is the StdErr output generated by oc start-build. StartBuildStdErr string // StartBuildStdOut is the StdOut output generated by oc start-build. StartBuildStdOut string // StartBuildErr is the error, if any, returned by the direct invocation of the start-build command. StartBuildErr error // The buildconfig which generated this build. BuildConfigName string // Build is the resource created. May be nil if there was a timeout. Build *buildapi.Build // BuildAttempt represents that a Build resource was created. // false indicates a severe error unrelated to Build success or failure. BuildAttempt bool // BuildSuccess is true if the build was finshed successfully. BuildSuccess bool // BuildFailure is true if the build was finished with an error. BuildFailure bool // BuildCancelled is true if the build was canceled. BuildCancelled bool // BuildTimeout is true if there was a timeout waiting for the build to finish. BuildTimeout bool // Alternate log dumper function. If set, this is called instead of 'oc logs' LogDumper LogDumperFunc // The openshift client which created this build. Oc *CLI } // DumpLogs sends logs associated with this BuildResult to the GinkgoWriter. func (t *BuildResult) DumpLogs() { e2e.Logf("\n\n*****************************************\n") e2e.Logf("Dumping Build Result: %#v\n", *t) if t == nil { e2e.Logf("No build result available!\n\n") return } desc, err := t.Oc.Run("describe").Args(t.BuildPath).Output() e2e.Logf("\n** Build Description:\n") if err != nil { e2e.Logf("Error during description retrieval: %+v\n", err) } else { e2e.Logf("%s\n", desc) } e2e.Logf("\n** Build Logs:\n") buildOuput, err := t.Logs() if err != nil { e2e.Logf("Error during log retrieval: %+v\n", err) } else { e2e.Logf("%s\n", buildOuput) } e2e.Logf("\n\n") t.dumpRegistryLogs() // if we suspect that we are filling up the registry file system, call ExamineDiskUsage / ExaminePodDiskUsage // also see if manipulations of the quota around /mnt/openshift-xfs-vol-dir exist in the extended test set up scripts /* ExamineDiskUsage() ExaminePodDiskUsage(t.oc) e2e.Logf( "\n\n") */ } func (t *BuildResult) dumpRegistryLogs() { var buildStarted *time.Time oc := t.Oc e2e.Logf("\n** Registry Logs:\n") if t.Build != nil && !t.Build.CreationTimestamp.IsZero() { buildStarted = &t.Build.CreationTimestamp.Time } else { proj, err := oc.ProjectClient().Project().Projects().Get(oc.Namespace(), metav1.GetOptions{}) if err != nil { e2e.Logf("Failed to get project %s: %v\n", oc.Namespace(), err) } else { buildStarted = &proj.CreationTimestamp.Time } } if buildStarted == nil { e2e.Logf("Could not determine test' start time\n\n\n") return } since := time.Now().Sub(*buildStarted) // Changing the namespace on the derived client still changes it on the original client // because the kubeFramework field is only copied by reference. Saving the original namespace // here so we can restore it when done with registry logs savedNamespace := t.Oc.Namespace() oadm := t.Oc.AsAdmin().SetNamespace("default") out, err := oadm.Run("logs").Args("dc/docker-registry", "--since="+since.String()).Output() if err != nil { e2e.Logf("Error during log retrieval: %+v\n", err) } else { e2e.Logf("%s\n", out) } t.Oc.SetNamespace(savedNamespace) e2e.Logf("\n\n") } // Logs returns the logs associated with this build. func (t *BuildResult) Logs() (string, error) { if t == nil || t.BuildPath == "" { return "", fmt.Errorf("Not enough information to retrieve logs for %#v", *t) } if t.LogDumper != nil { return t.LogDumper(t.Oc, t) } buildOuput, err := t.Oc.Run("logs").Args("-f", t.BuildPath, "--timestamps").Output() if err != nil { return "", fmt.Errorf("Error retrieving logs for %#v: %v", *t, err) } return buildOuput, nil } // Dumps logs and triggers a Ginkgo assertion if the build did NOT succeed. func (t *BuildResult) AssertSuccess() *BuildResult { if !t.BuildSuccess { t.DumpLogs() } o.ExpectWithOffset(1, t.BuildSuccess).To(o.BeTrue()) return t } // Dumps logs and triggers a Ginkgo assertion if the build did NOT have an error (this will not assert on timeouts) func (t *BuildResult) AssertFailure() *BuildResult { if !t.BuildFailure { t.DumpLogs() } o.ExpectWithOffset(1, t.BuildFailure).To(o.BeTrue()) return t } func StartBuildResult(oc *CLI, args ...string) (result *BuildResult, err error) { args = append(args, "-o=name") // ensure that the build name is the only thing send to stdout stdout, stderr, err := StartBuild(oc, args...) // Usually, with -o=name, we only expect the build path. // However, the caller may have added --follow which can add // content to stdout. So just grab the first line. buildPath := strings.TrimSpace(strings.Split(stdout, "\n")[0]) result = &BuildResult{ Build: nil, BuildPath: buildPath, StartBuildStdOut: stdout, StartBuildStdErr: stderr, StartBuildErr: nil, BuildAttempt: false, BuildSuccess: false, BuildFailure: false, BuildCancelled: false, BuildTimeout: false, Oc: oc, } // An error here does not necessarily mean we could not run start-build. For example // when --wait is specified, start-build returns an error if the build fails. Therefore, // we continue to collect build information even if we see an error. result.StartBuildErr = err matches := buildPathPattern.FindStringSubmatch(buildPath) if len(matches) != 2 { return result, fmt.Errorf("Build path output did not match expected format 'build/name' : %q", buildPath) } result.BuildName = matches[1] return result, nil } // StartBuildAndWait executes OC start-build with the specified arguments on an existing buildconfig. // Note that start-build will be run with "-o=name" as a parameter when using this method. // If no error is returned from this method, it means that the build attempted successfully, NOT that // the build completed. For completion information, check the BuildResult object. func StartBuildAndWait(oc *CLI, args ...string) (result *BuildResult, err error) { result, err = StartBuildResult(oc, args...) if err != nil { return result, err } return result, WaitForBuildResult(oc.BuildClient().Build().Builds(oc.Namespace()), result) } // WaitForBuildResult updates result wit the state of the build func WaitForBuildResult(c buildtypedclientset.BuildResourceInterface, result *BuildResult) error { e2e.Logf("Waiting for %s to complete\n", result.BuildName) err := WaitForABuild(c, result.BuildName, func(b *buildapi.Build) bool { result.Build = b result.BuildSuccess = CheckBuildSuccessFn(b) return result.BuildSuccess }, func(b *buildapi.Build) bool { result.Build = b result.BuildFailure = CheckBuildFailedFn(b) return result.BuildFailure }, func(b *buildapi.Build) bool { result.Build = b result.BuildCancelled = CheckBuildCancelledFn(b) return result.BuildCancelled }, ) if result.Build == nil { // We only abort here if the build progress was unobservable. Only known cause would be severe, non-build related error in WaitForABuild. return fmt.Errorf("Severe error waiting for build: %v", err) } result.BuildAttempt = true result.BuildTimeout = !(result.BuildFailure || result.BuildSuccess || result.BuildCancelled) e2e.Logf("Done waiting for %s: %#v\n with error: %v\n", result.BuildName, *result, err) return nil } // WaitForABuild waits for a Build object to match either isOK or isFailed conditions. func WaitForABuild(c buildtypedclientset.BuildResourceInterface, name string, isOK, isFailed, isCanceled func(*buildapi.Build) bool) error { if isOK == nil { isOK = CheckBuildSuccessFn } if isFailed == nil { isFailed = CheckBuildFailedFn } if isCanceled == nil { isCanceled = CheckBuildCancelledFn } // wait 2 minutes for build to exist err := wait.Poll(1*time.Second, 2*time.Minute, func() (bool, error) { if _, err := c.Get(name, metav1.GetOptions{}); err != nil { return false, nil } return true, nil }) if err == wait.ErrWaitTimeout { return fmt.Errorf("Timed out waiting for build %q to be created", name) } if err != nil { return err } // wait longer for the build to run to completion err = wait.Poll(5*time.Second, 60*time.Minute, func() (bool, error) { list, err := c.List(metav1.ListOptions{FieldSelector: fields.Set{"metadata.name": name}.AsSelector().String()}) if err != nil { e2e.Logf("error listing builds: %v", err) return false, err } for i := range list.Items { if name == list.Items[i].Name && (isOK(&list.Items[i]) || isCanceled(&list.Items[i])) { return true, nil } if name != list.Items[i].Name { return false, fmt.Errorf("While listing builds named %s, found unexpected build %#v", name, list.Items[i]) } if isFailed(&list.Items[i]) { return false, fmt.Errorf("The build %q status is %q", name, list.Items[i].Status.Phase) } } return false, nil }) if err != nil { e2e.Logf("WaitForABuild returning with error: %v", err) } if err == wait.ErrWaitTimeout { return fmt.Errorf("Timed out waiting for build %q to complete", name) } return err } // CheckBuildSuccessFn returns true if the build succeeded var CheckBuildSuccessFn = func(b *buildapi.Build) bool { return b.Status.Phase == buildapi.BuildPhaseComplete } // CheckBuildFailedFn return true if the build failed var CheckBuildFailedFn = func(b *buildapi.Build) bool { return b.Status.Phase == buildapi.BuildPhaseFailed || b.Status.Phase == buildapi.BuildPhaseError } // CheckBuildCancelledFn return true if the build was canceled var CheckBuildCancelledFn = func(b *buildapi.Build) bool { return b.Status.Phase == buildapi.BuildPhaseCancelled } // WaitForBuilderAccount waits until the builder service account gets fully // provisioned func WaitForBuilderAccount(c kcoreclient.ServiceAccountInterface) error { waitFn := func() (bool, error) { sc, err := c.Get("builder", metav1.GetOptions{}) if err != nil { // If we can't access the service accounts, let's wait till the controller // create it. if errors.IsForbidden(err) { return false, nil } return false, err } for _, s := range sc.Secrets { if strings.Contains(s.Name, "dockercfg") { return true, nil } } return false, nil } return wait.Poll(time.Duration(100*time.Millisecond), 1*time.Minute, waitFn) } // WaitForAnImageStream waits for an ImageStream to fulfill the isOK function func WaitForAnImageStream(client imagetypeclientset.ImageStreamInterface, name string, isOK, isFailed func(*imageapi.ImageStream) bool) error { for { list, err := client.List(metav1.ListOptions{FieldSelector: fields.Set{"metadata.name": name}.AsSelector().String()}) if err != nil { return err } for i := range list.Items { if isOK(&list.Items[i]) { return nil } if isFailed(&list.Items[i]) { return fmt.Errorf("The image stream %q status is %q", name, list.Items[i].Annotations[imageapi.DockerImageRepositoryCheckAnnotation]) } } rv := list.ResourceVersion w, err := client.Watch(metav1.ListOptions{FieldSelector: fields.Set{"metadata.name": name}.AsSelector().String(), ResourceVersion: rv}) if err != nil { return err } defer w.Stop() for { val, ok := <-w.ResultChan() if !ok { // reget and re-watch break } if e, ok := val.Object.(*imageapi.ImageStream); ok { if isOK(e) { return nil } if isFailed(e) { return fmt.Errorf("The image stream %q status is %q", name, e.Annotations[imageapi.DockerImageRepositoryCheckAnnotation]) } } } } } // WaitForAnImageStreamTag waits until an image stream with given name has non-empty history for given tag. // Defaults to waiting for 300 seconds func WaitForAnImageStreamTag(oc *CLI, namespace, name, tag string) error { return TimedWaitForAnImageStreamTag(oc, namespace, name, tag, time.Second*300) } // TimedWaitForAnImageStreamTag waits until an image stream with given name has non-empty history for given tag. // Gives up waiting after the specified waitTimeout func TimedWaitForAnImageStreamTag(oc *CLI, namespace, name, tag string, waitTimeout time.Duration) error { g.By(fmt.Sprintf("waiting for an is importer to import a tag %s into a stream %s", tag, name)) start := time.Now() c := make(chan error) go func() { err := WaitForAnImageStream( oc.ImageClient().Image().ImageStreams(namespace), name, func(is *imageapi.ImageStream) bool { if history, exists := is.Status.Tags[tag]; !exists || len(history.Items) == 0 { return false } return true }, func(is *imageapi.ImageStream) bool { return time.Now().After(start.Add(waitTimeout)) }) c <- err }() select { case e := <-c: return e case <-time.After(waitTimeout): return fmt.Errorf("timed out while waiting of an image stream tag %s/%s:%s", namespace, name, tag) } } // CheckImageStreamLatestTagPopulatedFn returns true if the imagestream has a ':latest' tag filed var CheckImageStreamLatestTagPopulatedFn = func(i *imageapi.ImageStream) bool { _, ok := i.Status.Tags["latest"] return ok } // CheckImageStreamTagNotFoundFn return true if the imagestream update was not successful var CheckImageStreamTagNotFoundFn = func(i *imageapi.ImageStream) bool { return strings.Contains(i.Annotations[imageapi.DockerImageRepositoryCheckAnnotation], "not") || strings.Contains(i.Annotations[imageapi.DockerImageRepositoryCheckAnnotation], "error") } // WaitForDeploymentConfig waits for a DeploymentConfig to complete transition // to a given version and report minimum availability. func WaitForDeploymentConfig(kc kclientset.Interface, dcClient appstypeclientset.DeploymentConfigsGetter, namespace, name string, version int64, enforceNotProgressing bool, cli *CLI) error { e2e.Logf("waiting for deploymentconfig %s/%s to be available with version %d\n", namespace, name, version) var dc *appsapi.DeploymentConfig start := time.Now() err := wait.Poll(time.Second, 15*time.Minute, func() (done bool, err error) { dc, err = dcClient.DeploymentConfigs(namespace).Get(name, metav1.GetOptions{}) if err != nil { return false, err } // TODO re-enable this check once @mfojtik introduces a test that ensures we'll only ever get // exactly one deployment triggered. /* if dc.Status.LatestVersion > version { return false, fmt.Errorf("latestVersion %d passed %d", dc.Status.LatestVersion, version) } */ if dc.Status.LatestVersion < version { return false, nil } var progressing, available *appsapi.DeploymentCondition for i, condition := range dc.Status.Conditions { switch condition.Type { case appsapi.DeploymentProgressing: progressing = &dc.Status.Conditions[i] case appsapi.DeploymentAvailable: available = &dc.Status.Conditions[i] } } if enforceNotProgressing { if progressing != nil && progressing.Status == kapi.ConditionFalse { return false, fmt.Errorf("not progressing") } } if progressing != nil && progressing.Status == kapi.ConditionTrue && progressing.Reason == appsapi.NewRcAvailableReason && available != nil && available.Status == kapi.ConditionTrue { return true, nil } return false, nil }) if err != nil { e2e.Logf("got error %q when waiting for deploymentconfig %s/%s to be available with version %d\n", err, namespace, name, version) cli.Run("get").Args("dc", dc.Name, "-o", "yaml").Execute() DumpDeploymentLogs(name, version, cli) DumpApplicationPodLogs(name, cli) return err } requirement, err := labels.NewRequirement(appsapi.DeploymentLabel, selection.Equals, []string{appsutil.LatestDeploymentNameForConfig(dc)}) if err != nil { return err } podnames, err := GetPodNamesByFilter(kc.CoreV1().Pods(namespace), labels.NewSelector().Add(*requirement), func(kapiv1.Pod) bool { return true }) if err != nil { return err } e2e.Logf("deploymentconfig %s/%s available after %s\npods: %s\n", namespace, name, time.Now().Sub(start), strings.Join(podnames, ", ")) return nil } func isUsageSynced(received, expected kapi.ResourceList, expectedIsUpperLimit bool) bool { resourceNames := quota.ResourceNames(expected) masked := quota.Mask(received, resourceNames) if len(masked) != len(expected) { return false } if expectedIsUpperLimit { if le, _ := quota.LessThanOrEqual(masked, expected); !le { return false } } else { if le, _ := quota.LessThanOrEqual(expected, masked); !le { return false } } return true } // WaitForResourceQuotaSync watches given resource quota until its usage is updated to desired level or a // timeout occurs. If successful, used quota values will be returned for expected resources. Otherwise an // ErrWaitTimeout will be returned. If expectedIsUpperLimit is true, given expected usage must compare greater // or equal to quota's usage, which is useful for expected usage increment. Otherwise expected usage must // compare lower or equal to quota's usage, which is useful for expected usage decrement. func WaitForResourceQuotaSync( client kinternalcoreclient.ResourceQuotaInterface, name string, expectedUsage kapi.ResourceList, expectedIsUpperLimit bool, timeout time.Duration, ) (kapi.ResourceList, error) { startTime := time.Now() endTime := startTime.Add(timeout) expectedResourceNames := quota.ResourceNames(expectedUsage) list, err := client.List(metav1.ListOptions{FieldSelector: fields.Set{"metadata.name": name}.AsSelector().String()}) if err != nil { return nil, err } for i := range list.Items { used := quota.Mask(list.Items[i].Status.Used, expectedResourceNames) if isUsageSynced(used, expectedUsage, expectedIsUpperLimit) { return used, nil } } rv := list.ResourceVersion w, err := client.Watch(metav1.ListOptions{FieldSelector: fields.Set{"metadata.name": name}.AsSelector().String(), ResourceVersion: rv}) if err != nil { return nil, err } defer w.Stop() for time.Now().Before(endTime) { select { case val, ok := <-w.ResultChan(): if !ok { // reget and re-watch continue } if rq, ok := val.Object.(*kapi.ResourceQuota); ok { used := quota.Mask(rq.Status.Used, expectedResourceNames) if isUsageSynced(used, expectedUsage, expectedIsUpperLimit) { return used, nil } } case <-time.After(endTime.Sub(time.Now())): return nil, wait.ErrWaitTimeout } } return nil, wait.ErrWaitTimeout } // GetPodNamesByFilter looks up pods that satisfy the predicate and returns their names. func GetPodNamesByFilter(c kcoreclient.PodInterface, label labels.Selector, predicate func(kapiv1.Pod) bool) (podNames []string, err error) { podList, err := c.List(metav1.ListOptions{LabelSelector: label.String()}) if err != nil { return nil, err } for _, pod := range podList.Items { if predicate(pod) { podNames = append(podNames, pod.Name) } } return podNames, nil } func WaitForAJob(c kbatchclient.JobInterface, name string, timeout time.Duration) error { return wait.Poll(1*time.Second, timeout, func() (bool, error) { j, e := c.Get(name, metav1.GetOptions{}) if e != nil { return true, e } // TODO soltysh: replace this with a function once such exist, currently // it's private in the controller for _, c := range j.Status.Conditions { if (c.Type == batchv1.JobComplete || c.Type == batchv1.JobFailed) && c.Status == kapiv1.ConditionTrue { return true, nil } } return false, nil }) } // WaitForPods waits until given number of pods that match the label selector and // satisfy the predicate are found func WaitForPods(c kcoreclient.PodInterface, label labels.Selector, predicate func(kapiv1.Pod) bool, count int, timeout time.Duration) ([]string, error) { var podNames []string err := wait.Poll(1*time.Second, timeout, func() (bool, error) { p, e := GetPodNamesByFilter(c, label, predicate) if e != nil { return true, e } if len(p) != count { return false, nil } podNames = p return true, nil }) return podNames, err } // CheckPodIsRunningFn returns true if the pod is running var CheckPodIsRunningFn = func(pod kapiv1.Pod) bool { return pod.Status.Phase == kapiv1.PodRunning } // CheckPodIsSucceededFn returns true if the pod status is "Succdeded" var CheckPodIsSucceededFn = func(pod kapiv1.Pod) bool { return pod.Status.Phase == kapiv1.PodSucceeded } // CheckPodIsReadyFn returns true if the pod's ready probe determined that the pod is ready. var CheckPodIsReadyFn = func(pod kapiv1.Pod) bool { if pod.Status.Phase != kapiv1.PodRunning { return false } for _, cond := range pod.Status.Conditions { if cond.Type != kapiv1.PodReady { continue } return cond.Status == kapiv1.ConditionTrue } return false } // WaitUntilPodIsGone waits until the named Pod will disappear func WaitUntilPodIsGone(c kcoreclient.PodInterface, podName string, timeout time.Duration) error { return wait.Poll(1*time.Second, timeout, func() (bool, error) { _, err := c.Get(podName, metav1.GetOptions{}) if err != nil { if strings.Contains(err.Error(), "not found") { return true, nil } return true, err } return false, nil }) } // GetDockerImageReference retrieves the full Docker pull spec from the given ImageStream // and tag func GetDockerImageReference(c imagetypeclientset.ImageStreamInterface, name, tag string) (string, error) { imageStream, err := c.Get(name, metav1.GetOptions{}) if err != nil { return "", err } isTag, ok := imageStream.Status.Tags[tag] if !ok { return "", fmt.Errorf("ImageStream %q does not have tag %q", name, tag) } if len(isTag.Items) == 0 { return "", fmt.Errorf("ImageStreamTag %q is empty", tag) } return isTag.Items[0].DockerImageReference, nil } // GetPodForContainer creates a new Pod that runs specified container func GetPodForContainer(container kapiv1.Container) *kapiv1.Pod { name := apihelpers.GetPodName("test-pod", string(uuid.NewUUID())) return &kapiv1.Pod{ TypeMeta: metav1.TypeMeta{ Kind: "Pod", APIVersion: "v1", }, ObjectMeta: metav1.ObjectMeta{ Name: name, Labels: map[string]string{"name": name}, }, Spec: kapiv1.PodSpec{ Containers: []kapiv1.Container{container}, RestartPolicy: kapiv1.RestartPolicyNever, }, } } // KubeConfigPath returns the value of KUBECONFIG environment variable func KubeConfigPath() string { // can't use gomega in this method since it is used outside of It() return os.Getenv("KUBECONFIG") } //ArtifactDirPath returns the value of ARTIFACT_DIR environment variable func ArtifactDirPath() string { path := os.Getenv("ARTIFACT_DIR") o.Expect(path).NotTo(o.BeNil()) o.Expect(path).NotTo(o.BeEmpty()) return path } //ArtifactPath returns the absolute path to the fix artifact file //The path is relative to ARTIFACT_DIR func ArtifactPath(elem ...string) string { return filepath.Join(append([]string{ArtifactDirPath()}, elem...)...) } var ( fixtureDirLock sync.Once fixtureDir string ) // FixturePath returns an absolute path to a fixture file in test/extended/testdata/, // test/integration/, or examples/. func FixturePath(elem ...string) string { switch { case len(elem) == 0: panic("must specify path") case len(elem) > 3 && elem[0] == ".." && elem[1] == ".." && elem[2] == "examples": elem = elem[2:] case len(elem) > 3 && elem[0] == ".." && elem[1] == ".." && elem[2] == "install": elem = elem[2:] case len(elem) > 3 && elem[0] == ".." && elem[1] == "integration": elem = append([]string{"test"}, elem[1:]...) case elem[0] == "testdata": elem = append([]string{"test", "extended"}, elem...) default: panic(fmt.Sprintf("Fixtures must be in test/extended/testdata or examples not %s", path.Join(elem...))) } fixtureDirLock.Do(func() { dir, err := ioutil.TempDir("", "fixture-testdata-dir") if err != nil { panic(err) } fixtureDir = dir }) relativePath := path.Join(elem...) fullPath := path.Join(fixtureDir, relativePath) if err := testdata.RestoreAsset(fixtureDir, relativePath); err != nil { if err := testdata.RestoreAssets(fixtureDir, relativePath); err != nil { panic(err) } if err := filepath.Walk(fullPath, func(path string, info os.FileInfo, err error) error { if err := os.Chmod(path, 0640); err != nil { return err } if stat, err := os.Lstat(path); err == nil && stat.IsDir() { return os.Chmod(path, 0755) } return nil }); err != nil { panic(err) } } else { if err := os.Chmod(fullPath, 0640); err != nil { panic(err) } } p, err := filepath.Abs(fullPath) if err != nil { panic(err) } return p } // FetchURL grabs the output from the specified url and returns it. // It will retry once per second for duration retryTimeout if an error occurs during the request. func FetchURL(url string, retryTimeout time.Duration) (response string, err error) { waitFn := func() (bool, error) { r, err := http.Get(url) if err != nil || r.StatusCode != 200 { // lie to the poller that we didn't get an error even though we did // because otherwise it's going to give up. if err != nil { e2e.Logf("error fetching url: %v", err) } if r != nil { e2e.Logf("non-200 status code fetching url: %d", r.StatusCode) } return false, nil } defer r.Body.Close() bytes, err := ioutil.ReadAll(r.Body) response = string(bytes) return true, nil } pollErr := wait.Poll(time.Duration(1*time.Second), retryTimeout, waitFn) if pollErr == wait.ErrWaitTimeout { return "", fmt.Errorf("Timed out while fetching url %q", url) } if pollErr != nil { return "", pollErr } return } // ParseLabelsOrDie turns the given string into a label selector or // panics; for tests or other cases where you know the string is valid. // TODO: Move this to the upstream labels package. func ParseLabelsOrDie(str string) labels.Selector { ret, err := labels.Parse(str) if err != nil { panic(fmt.Sprintf("cannot parse '%v': %v", str, err)) } return ret } // GetEndpointAddress will return an "ip:port" string for the endpoint. func GetEndpointAddress(oc *CLI, name string) (string, error) { err := e2e.WaitForEndpoint(oc.KubeFramework().ClientSet, oc.Namespace(), name) if err != nil { return "", err } endpoint, err := oc.KubeClient().CoreV1().Endpoints(oc.Namespace()).Get(name, metav1.GetOptions{}) if err != nil { return "", err } return fmt.Sprintf("%s:%d", endpoint.Subsets[0].Addresses[0].IP, endpoint.Subsets[0].Ports[0].Port), nil } // CreateExecPodOrFail creates a simple busybox pod in a sleep loop used as a // vessel for kubectl exec commands. // Returns the name of the created pod. // TODO: expose upstream func CreateExecPodOrFail(client kcoreclient.CoreV1Interface, ns, name string) string { e2e.Logf("Creating new exec pod") execPod := e2e.NewHostExecPodSpec(ns, name) created, err := client.Pods(ns).Create(execPod) o.Expect(err).NotTo(o.HaveOccurred()) err = wait.PollImmediate(e2e.Poll, 5*time.Minute, func() (bool, error) { retrievedPod, err := client.Pods(execPod.Namespace).Get(created.Name, metav1.GetOptions{}) if err != nil { return false, nil } return retrievedPod.Status.Phase == kapiv1.PodRunning, nil }) o.Expect(err).NotTo(o.HaveOccurred()) return created.Name } // CheckForBuildEvent will poll a build for up to 1 minute looking for an event with // the specified reason and message template. func CheckForBuildEvent(client kcoreclient.CoreV1Interface, build *buildapi.Build, reason, message string) { var expectedEvent *kapiv1.Event err := wait.PollImmediate(e2e.Poll, 1*time.Minute, func() (bool, error) { events, err := client.Events(build.Namespace).Search(legacyscheme.Scheme, build) if err != nil { return false, err } for _, event := range events.Items { e2e.Logf("Found event %#v", event) if reason == event.Reason { expectedEvent = &event return true, nil } } return false, nil }) o.ExpectWithOffset(1, err).NotTo(o.HaveOccurred(), "Should be able to get events from the build") o.ExpectWithOffset(1, expectedEvent).NotTo(o.BeNil(), "Did not find a %q event on build %s/%s", reason, build.Namespace, build.Name) o.ExpectWithOffset(1, expectedEvent.Message).To(o.Equal(fmt.Sprintf(message, build.Namespace, build.Name))) } type podExecutor struct { client *CLI podName string } // NewPodExecutor returns an executor capable of running commands in a Pod. func NewPodExecutor(oc *CLI, name, image string) (*podExecutor, error) { out, err := oc.Run("run").Args(name, "--labels", "name="+name, "--image", image, "--restart", "Never", "--command", "--", "/bin/bash", "-c", "sleep infinity").Output() if err != nil { return nil, fmt.Errorf("error: %v\n(%s)", err, out) } _, err = WaitForPods(oc.KubeClient().CoreV1().Pods(oc.Namespace()), ParseLabelsOrDie("name="+name), CheckPodIsReadyFn, 1, 3*time.Minute) if err != nil { return nil, err } return &podExecutor{client: oc, podName: name}, nil } // Exec executes a single command or a bash script in the running pod. It returns the // command output and error if the command finished with non-zero status code or the // command took longer then 3 minutes to run. func (r *podExecutor) Exec(script string) (string, error) { var out string waitErr := wait.PollImmediate(1*time.Second, 3*time.Minute, func() (bool, error) { var err error out, err = r.client.Run("exec").Args(r.podName, "--", "/bin/bash", "-c", script).Output() return true, err }) return out, waitErr } type GitRepo struct { baseTempDir string upstream git.Repository upstreamPath string repo git.Repository RepoPath string } // AddAndCommit commits a file with its content to local repo func (r GitRepo) AddAndCommit(file, content string) error { if err := ioutil.WriteFile(filepath.Join(r.RepoPath, file), []byte(content), 0666); err != nil { return err } if err := r.repo.Add(r.RepoPath, file); err != nil { return err } if err := r.repo.Commit(r.RepoPath, "added file "+file); err != nil { return err } return nil } // Remove performs cleanup of no longer needed directories with local and "remote" git repo func (r GitRepo) Remove() { if r.baseTempDir != "" { os.RemoveAll(r.baseTempDir) } } // NewGitRepo creates temporary test directories with local and "remote" git repo func NewGitRepo(repoName string) (GitRepo, error) { testDir, err := ioutil.TempDir(util.GetBaseDir(), repoName) if err != nil { return GitRepo{}, err } repoPath := filepath.Join(testDir, repoName) upstreamPath := repoPath + `.git` upstream := git.NewRepository() if err = upstream.Init(upstreamPath, true); err != nil { return GitRepo{baseTempDir: testDir}, err } repo := git.NewRepository() if err = repo.Clone(repoPath, upstreamPath); err != nil { return GitRepo{baseTempDir: testDir}, err } return GitRepo{testDir, upstream, upstreamPath, repo, repoPath}, nil } // WaitForUserBeAuthorized waits a minute until the cluster bootstrap roles are available // and the provided user is authorized to perform the action on the resource. func WaitForUserBeAuthorized(oc *CLI, user, verb, resource string) error { sar := &authorization.SubjectAccessReview{ Spec: authorization.SubjectAccessReviewSpec{ ResourceAttributes: &authorization.ResourceAttributes{ Namespace: oc.Namespace(), Verb: verb, Resource: resource, }, User: user, }, } return wait.PollImmediate(1*time.Second, 1*time.Minute, func() (bool, error) { resp, err := oc.InternalAdminKubeClient().Authorization().SubjectAccessReviews().Create(sar) if err == nil && resp != nil && resp.Status.Allowed { return true, nil } return false, err }) }
apache-2.0
kameshsampath/vertx-maven-plugin
src/it/run-args-extended-launcher-it/src/main/java/demo/SimpleVerticle.java
1020
/* * * Copyright (c) 2016-2017 Red Hat, Inc. * * Red Hat 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 demo; import io.vertx.core.AbstractVerticle; import io.vertx.core.Future; public class SimpleVerticle extends AbstractVerticle { @Override public void start() throws Exception { String name = "vert.x"; String message = config().getString("prefix") + " " + name; System.out.println(message); vertx.close(); } }
apache-2.0
charybdeBE/Cytomine-core
web-app/lib/requirejs/build/jslib/optimize.js
11294
/** * @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/jrburke/requirejs for details */ /*jslint plusplus: false, nomen: false, regexp: false, strict: false */ /*global define: false */ define([ 'lang', 'logger', 'env!env/optimize', 'env!env/file', 'uglifyjs/index'], function (lang, logger, envOptimize, file, uglify) { var optimize, cssImportRegExp = /\@import\s+(url\()?\s*([^);]+)\s*(\))?([\w, ]*)(;)?/g, cssUrlRegExp = /\url\(\s*([^\)]+)\s*\)?/g; /** * If an URL from a CSS url value contains start/end quotes, remove them. * This is not done in the regexp, since my regexp fu is not that strong, * and the CSS spec allows for ' and " in the URL if they are backslash escaped. * @param {String} url */ function cleanCssUrlQuotes(url) { //Make sure we are not ending in whitespace. //Not very confident of the css regexps above that there will not be ending //whitespace. url = url.replace(/\s+$/, ""); if (url.charAt(0) === "'" || url.charAt(0) === "\"") { url = url.substring(1, url.length - 1); } return url; } /** * Inlines nested stylesheets that have @import calls in them. * @param {String} fileName * @param {String} fileContents * @param {String} [cssImportIgnore] */ function flattenCss(fileName, fileContents, cssImportIgnore) { //Find the last slash in the name. fileName = fileName.replace(lang.backSlashRegExp, "/"); var endIndex = fileName.lastIndexOf("/"), //Make a file path based on the last slash. //If no slash, so must be just a file name. Use empty string then. filePath = (endIndex !== -1) ? fileName.substring(0, endIndex + 1) : ""; //Make sure we have a delimited ignore list to make matching faster if (cssImportIgnore && cssImportIgnore.charAt(cssImportIgnore.length - 1) !== ",") { cssImportIgnore += ","; } return fileContents.replace(cssImportRegExp, function (fullMatch, urlStart, importFileName, urlEnd, mediaTypes) { //Only process media type "all" or empty media type rules. if (mediaTypes && ((mediaTypes.replace(/^\s\s*/, '').replace(/\s\s*$/, '')) !== "all")) { return fullMatch; } importFileName = cleanCssUrlQuotes(importFileName); //Ignore the file import if it is part of an ignore list. if (cssImportIgnore && cssImportIgnore.indexOf(importFileName + ",") !== -1) { return fullMatch; } //Make sure we have a unix path for the api of the operation. importFileName = importFileName.replace(lang.backSlashRegExp, "/"); try { //if a relative path, then tack on the filePath. //If it is not a relative path, then the readFile below will fail, //and we will just skip that import. var fullImportFileName = importFileName.charAt(0) === "/" ? importFileName : filePath + importFileName, importContents = file.readFile(fullImportFileName), i, importEndIndex, importPath, fixedUrlMatch, colonIndex, parts; //Make sure to flatten any nested imports. importContents = flattenCss(fullImportFileName, importContents); //Make the full import path importEndIndex = importFileName.lastIndexOf("/"); //Make a file path based on the last slash. //If no slash, so must be just a file name. Use empty string then. importPath = (importEndIndex !== -1) ? importFileName.substring(0, importEndIndex + 1) : ""; //Modify URL paths to match the path represented by this file. importContents = importContents.replace(cssUrlRegExp, function (fullMatch, urlMatch) { fixedUrlMatch = cleanCssUrlQuotes(urlMatch); fixedUrlMatch = fixedUrlMatch.replace(lang.backSlashRegExp, "/"); //Only do the work for relative URLs. Skip things that start with / or have //a protocol. colonIndex = fixedUrlMatch.indexOf(":"); if (fixedUrlMatch.charAt(0) !== "/" && (colonIndex === -1 || colonIndex > fixedUrlMatch.indexOf("/"))) { //It is a relative URL, tack on the path prefix urlMatch = importPath + fixedUrlMatch; } else { logger.trace(importFileName + "\n URL not a relative URL, skipping: " + urlMatch); } //Collapse .. and . parts = urlMatch.split("/"); for (i = parts.length - 1; i > 0; i--) { if (parts[i] === ".") { parts.splice(i, 1); } else if (parts[i] === "..") { if (i !== 0 && parts[i - 1] !== "..") { parts.splice(i - 1, 2); i -= 1; } } } return "url(" + parts.join("/") + ")"; }); return importContents; } catch (e) { logger.trace(fileName + "\n Cannot inline css import, skipping: " + importFileName); return fullMatch; } }); } optimize = { /** * Optimizes a file that contains JavaScript content. It will inline * text plugin files and run it through Google Closure Compiler * minification, if the config options specify it. * * @param {String} fileName the name of the file to optimize * @param {String} outFileName the name of the file to use for the * saved optimized content. * @param {Object} config the build config object. */ jsFile: function (fileName, outFileName, config) { var parts = (config.optimize + "").split('.'), optimizerName = parts[0], keepLines = parts[1] === 'keepLines', fileContents, optFunc; fileContents = file.readFile(fileName); //Optimize the JS files if asked. if (optimizerName && optimizerName !== 'none') { optFunc = envOptimize[optimizerName] || optimize.optimizers[optimizerName]; if (!optFunc) { throw new Error('optimizer with name of "' + optimizerName + '" not found for this environment'); } fileContents = optFunc(fileName, fileContents, keepLines, config[optimizerName]); } file.saveUtf8File(outFileName, fileContents); }, /** * Optimizes one CSS file, inlining @import calls, stripping comments, and * optionally removes line returns. * @param {String} fileName the path to the CSS file to optimize * @param {String} outFileName the path to save the optimized file. * @param {Object} config the config object with the optimizeCss and * cssImportIgnore options. */ cssFile: function (fileName, outFileName, config) { //Read in the file. Make sure we have a JS string. var originalFileContents = file.readFile(fileName), fileContents = flattenCss(fileName, originalFileContents, config.cssImportIgnore), startIndex, endIndex; //Do comment removal. try { startIndex = -1; //Get rid of comments. while ((startIndex = fileContents.indexOf("/*")) !== -1) { endIndex = fileContents.indexOf("*/", startIndex + 2); if (endIndex === -1) { throw "Improper comment in CSS file: " + fileName; } fileContents = fileContents.substring(0, startIndex) + fileContents.substring(endIndex + 2, fileContents.length); } //Get rid of newlines. if (config.optimizeCss.indexOf(".keepLines") === -1) { fileContents = fileContents.replace(/[\r\n]/g, ""); fileContents = fileContents.replace(/\s+/g, " "); fileContents = fileContents.replace(/\{\s/g, "{"); fileContents = fileContents.replace(/\s\}/g, "}"); } else { //Remove multiple empty lines. fileContents = fileContents.replace(/(\r\n)+/g, "\r\n"); fileContents = fileContents.replace(/(\n)+/g, "\n"); } } catch (e) { fileContents = originalFileContents; logger.error("Could not optimized CSS file: " + fileName + ", error: " + e); } file.saveUtf8File(outFileName, fileContents); }, /** * Optimizes CSS files, inlining @import calls, stripping comments, and * optionally removes line returns. * @param {String} startDir the path to the top level directory * @param {Object} config the config object with the optimizeCss and * cssImportIgnore options. */ css: function (startDir, config) { if (config.optimizeCss.indexOf("standard") !== -1) { var i, fileName, fileList = file.getFilteredFileList(startDir, /\.css$/, true); if (fileList) { for (i = 0; i < fileList.length; i++) { fileName = fileList[i]; logger.trace("Optimizing (" + config.optimizeCss + ") CSS file: " + fileName); optimize.cssFile(fileName, fileName, config); } } } }, optimizers: { uglify: function (fileName, fileContents, keepLines, config) { var parser = uglify.parser, processor = uglify.uglify, ast, genCodeConfig; config = config || {}; genCodeConfig = config.gen_codeOptions || keepLines; logger.trace("Uglifying file: " + fileName); try { ast = parser.parse(fileContents, config.strict_semicolons); ast = processor.ast_mangle(ast, config.do_toplevel); ast = processor.ast_squeeze(ast, config.ast_squeezeOptions); fileContents = processor.gen_code(ast, genCodeConfig); } catch (e) { logger.error('Cannot uglify file: ' + fileName + '. Skipping it. Error is:\n' + e.toString()); } return fileContents; } } }; return optimize; });
apache-2.0
aprescott/diffa
agent/src/main/webapp/js/data.js
17108
/** * Copyright (C) 2012 LShift Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ $(function() { Diffa.Views.InventoryUploader = Backbone.View.extend({ events: { 'submit form': 'uploadInventory', }, setListColumnThreshold: 10, templates: { rangeConstraint: _.template('<div class="category" data-constraint="<%= name %>" data-constraint-type="<%= dataType %>">' + '<h5 class="name"><%= name %> (<%= descriptiveDataType %> range)</h5>' + '<div>' + '<label for="<%= name %>_range_start">Start <%= descriptiveDataType %>:</label>' + '<span class="clearable_input">' + '<input id="<%= name %>_range_start" type="text" name="start" placeholder="Unbounded <%= descriptiveDataType %>">' + '<span class="clear"></span>' + '</span>' + '</div>' + '<div>' + '<label for="<%= name %>_range_end">End <%= descriptiveDataType %>:</label>' + '<span class="clearable_input">' + '<input id="<%= name %>_range_end" type="text" name="end" placeholder="Unbounded <%= descriptiveDataType %>">' + '<span class="clear"></span>' + '</span>' + '</div>' + '</div>'), prefixConstraint: _.template('<div class="category" data-constraint="<%= name %>">' + '<h5 class="name"><%= name %> (prefix)</h5>' + '<label for="<%= name %>_prefix">Prefix:</label>' + '<span class="clearable_input">' + '<input type="text" name="prefix" id="<%= name %>_prefix" placeholder="Unbounded prefix">' + '<span class="clear"></span>' + '</span>' + '</div>'), setConstraint: _.template('<div class="category" data-constraint="<%= name %>">' + '<h5 class="name"><%= name %> (set)</h5>' + '<% _.each(values, function(value) { %>' + '<input type="checkbox" value="<%= value %>" id="constraint_<%= name %>_<%= value %>">' + '<label for="constraint_<%= name %>_<%= value %>"><%= value %></label>' + '<br>' + '<% }); %>' + '</div>'), setConstraintWithColumns: _.template('<div class="category" data-constraint="<%= name %>">' + '<h5 class="name"><%= name %> (set)</h5>' + '<div class="column_1">' + '<% _.each(valuesFirst, function(value) { %>' + '<input type="checkbox" value="<%= value %>" id="constraint_<%= name %>_<%= value %>">' + '<label for="constraint_<%= name %>_<%= value %>"><%= value %></label>' + '<br>' + '<% }); %>' + '</div>' + '<div class="column_2">' + '<% _.each(valuesSecond, function(value) { %>' + '<input type="checkbox" value="<%= value %>" id="constraint_<%= name %>_<%= value %>">' + '<label for="constraint_<%= name %>_<%= value %>"><%= value %></label>' + '<br>' + '<% }); %>' + '</div>' + '</div>') }, initialize: function() { var self = this; _.bindAll(this, "render", "onEndpointListUpdate"); this.el.view = this; this.model.bind('reset', this.render); this.model.bind('remove', this.onEndpointListUpdate); var inventoryUploadTemplate = window.JST['data/inventory-upload']; var name = this.model.get("name"); var endpointDescription = "Endpoint"; var pairHalf = $(this.el).data("pair-half"); if (pairHalf) { endpointDescription = pairHalf.charAt(0).toUpperCase() + pairHalf.substr(1); } $(this.el).append(inventoryUploadTemplate({ name: name, endpointDescription: endpointDescription })); this.delegateEvents(this.events); this.endpoint = this.model; this.render(); this.model.fetch(); }, render: function() { this.onEndpointListUpdate(); return this; }, onEndpointListUpdate: function() { this.loadEndpoint(); // Trigger an endpoint selection to ensure the attributes are shown }, loadEndpoint: function(e) { var self = this; var selectedEndpoint = this.model; if (selectedEndpoint && this.currentEndpoint && selectedEndpoint.id == this.currentEndpoint.id) return; this.currentEndpoint = selectedEndpoint; var constraints = this.$('.constraints'); constraints.empty(); if (!selectedEndpoint) return; selectedEndpoint.rangeCategories.each(function(rangeCat) { var templateVars = rangeCat.toJSON(); var type = rangeCat.get("dataType"); var descriptiveDataType; switch(type) { case "date": descriptiveDataType = "date"; break; case "datetime": descriptiveDataType = "datetime"; break; case "int": descriptiveDataType = "integer"; break; } templateVars["descriptiveDataType"] = descriptiveDataType; constraints.append(self.templates.rangeConstraint(templateVars)); // add date picking to the range inputs var lowerBound = rangeCat.get("lower"); var upperBound = rangeCat.get("upper"); if (lowerBound) { var allowOld = false; var startDate = new Date(lowerBound); } else { var allowOld = true; var startDate = new Date(); } if (upperBound) { var endDate = new Date(upperBound); } else { var endDate = -1; } // if the category we're adding is a date range, apply datepickers if (type == "date" || type == "datetime") { $(".category:last-child input[type=text]").glDatePicker({ allowOld: allowOld, // as far back as possible or not startDate: startDate, endDate: endDate, // latest selectable date, days since start date (int), or no limit (-1) selectedDate: -1, // default select date, or nothing set (-1) onChange: function(target, newDate) { var result, year, month, day; // helper to pad our month/day values if needed var pad = function(s) { s = s.toString(); if (s.length < 2) { s = "0" + s; }; return s }; year = newDate.getFullYear(); month = pad(newDate.getMonth() + 1); day = pad(newDate.getDate()); result = year + "-" + month + "-" + day; if (type == "datetime") { result = result + " 00:00:00"; } target.val(result); target.change(); // fire the event as though we just typed it in } }); } }); selectedEndpoint.setCategories.each(function(setCat) { var values = setCat.get("values"); var threshold = self.setListColumnThreshold; // only split the values array when its size is > this number var template = self.templates.setConstraint; if (values.length >= threshold) { var first, second; // cut the list of items into two, ensuring X = [A, B] has |A| >= |B| var splitPoint = Math.ceil(values.length/2); first = values.slice(0, splitPoint); second = values.slice(splitPoint); setCat.set("valuesFirst", first); setCat.set("valuesSecond", second); template = self.templates.setConstraintWithColumns; } constraints.append(template(setCat.toJSON())); }); selectedEndpoint.prefixCategories.each(function(prefixCat) { constraints.append(self.templates.prefixConstraint(prefixCat.toJSON())); }); $(".category input").bind("change keydown focus blur", function() { if ($(this).val().length > 0) { $(this).addClass("nonempty"); } else { $(this).removeClass("nonempty"); } }); $(".clearable_input .clear").click(function() { $(this).siblings("input").val(""); $(this).siblings(".nonempty").removeClass("nonempty"); }); }, calculateConstraints: function(e) { var result = []; var constraints = this.$('.constraints'); var findContainer = function(name) { return constraints.find('[data-constraint=' + name + ']'); }; var addConstraint = function(key, value) { result.push(encodeURIComponent(key) + "=" + encodeURIComponent(value)); }; this.currentEndpoint.rangeCategories.each(function(rangeCat) { var start = findContainer(rangeCat.get('name')).find('input[name=start]').val(); var end = findContainer(rangeCat.get('name')).find('input[name=end]').val(); if (start.length > 0) addConstraint(rangeCat.get('name') + "-start", start); if (end.length > 0) addConstraint(rangeCat.get('name') + "-end", end); }); this.currentEndpoint.setCategories.each(function(setCat) { var selected = findContainer(setCat.get('name')). find('input[type=checkbox]:checked'). each(function(idx, c) { addConstraint(setCat.get('name'), $(c).val()); }); }); this.currentEndpoint.prefixCategories.each(function(prefixCat) { var prefix = findContainer(prefixCat.get('name')).find('input[name=prefix]').val(); if (prefix.length > 0) addConstraint(prefixCat.get('name') + "-prefix", prefix); }); return result.join('&'); }, uploadInventory: function(e) { e.preventDefault(); var endpoint = this.endpoint; var inventoryFiles = this.$('input[type=file]')[0].files; if (inventoryFiles.length < 1) { alert("No inventory files selected for upload"); return false; } var inventoryFile = inventoryFiles[0]; var constraints = this.calculateConstraints(); var submitButton = this.$('input[type=submit]'); submitButton.attr('disabled', 'disabled'); var statusPanel = this.$('.status'); var applyStatus = function(text, clazz) { statusPanel. removeClass('info success error'). addClass(clazz). text(text). show(); }; applyStatus('Uploading...', 'info'); endpoint.uploadInventory(inventoryFile, constraints, { global: false, // Don't invoke global event handlers - we'll deal with errors here locally success: function() { submitButton.removeAttr('disabled'); applyStatus('Inventory Submitted', 'success'); }, error: function(jqXHR, textStatus) { submitButton.removeAttr('disabled'); var message = "Unknown Cause"; if (jqXHR.status == 0) { message = textStatus; } else if (jqXHR.status == 400) { message = jqXHR.responseText; } else if (jqXHR.status == 403) { message = "Access Denied"; } else { message = "Server Error (" + jxXHR.status + ")"; } applyStatus('Inventory Submission Failed: ' + message, 'error'); } }); return false; } }); (function() { var pairSelectTemplate = _.template('<label>Pair:</label>' + '<select class="pair" data-placeholder="Select pair">' + '<option value="" selected="selected">Select pair</option>' + '<% _.each(pairs.models, function(pair) { %>' + '<option value="<%= pair.get("key") %>"><%= pair.get("key") %></option>' + '<% }); %> ' + '</select>'); var endpointSelectTemplate = _.template('<label>Endpoint:</label>' + '<select class="endpoint" data-placeholder="Select endpoint">' + '<option value="" selected="selected">Select endpoint</option>' + '<% _.each(endpoints.models, function(endpoint) { %>' + '<option value="<%= endpoint.get("name") %>"><%= endpoint.get("name") %></option>' + '<% }); %>' + '</select>'); var panel = $('.inventory-panel'); var domain = Diffa.DomainManager.get(currentDiffaDomain); var emptyAndUnbindUploaders = function() { $(".diffa-inventory-uploader").each(function(i, e) { var v = this.view; // if there's an associated view, make sure we remove // its events so that forms which are used on the same // DOM element don't fire more than one inventory // upload event from the backbone view. if (v) { v.unbind(); $(e).unbind(); } $(e).empty(); }); }; // returns 1 if an endpoint is being displayed, or 2 if a pair is being displayed. // returns 0 if nothing is displayed. var displayedUploaderCount = function() { if ($("#inventory-uploader-upstream").html().trim().length > 0) { return 2; } if ($("#inventory-uploader").html().trim().length > 0) { return 1; } return 0; }; var nothingDisplayed = function() { return displayedUploaderCount() == 0; }; var pairDisplayed = function() { return displayedUploaderCount() == 2; }; var endpointDisplayed = function() { return displayedUploaderCount() == 1; } // flashes the endpoint names. useful when changing between // one endpoint and another endpoint, where nothing much changes. var flashEndpointNames = function() { $(".diffa-inventory-uploader .endpoint-heading .endpoint-name").each(function() { var el = $(this); el.stop().css("opacity", "0.0").animate({ opacity: "1.0"}, 300); }); }; var pairChanged = function(pairName) { panel.find("select.endpoint").val(""); panel.find("select.endpoint").select2("val", ""); var flashNames = false; if (pairDisplayed()) { flashNames = true; } emptyAndUnbindUploaders(); // abort if there's nothing to do if (pairName.length == 0) { return; } var pair = domain.pairs.get(pairName); var downstream = domain.endpoints.get(pair.get("downstreamName")); var upstream = domain.endpoints.get(pair.get("upstreamName")); $('#inventory-uploader-upstream, #inventory-uploader-downstream').each(function() { var pairHalf = $(this).data("pair-half"); if (pairHalf == "upstream") { var m = upstream; } else if (pairHalf == "downstream") { var m = downstream; } else { throw 'Unknown half of pair "' + pairHalf + '", expected either "upstream" or "downstream"'; } new Diffa.Views.InventoryUploader({ el: $(this), model: m }); }); if (flashNames) { flashEndpointNames(); } }; var endpointChanged = function(endpointName) { $("select.pair").val(""); $("select.pair").select2("val", ""); var flashNames = false; if (endpointDisplayed()) { flashNames = true; } emptyAndUnbindUploaders(); // abort if there's nothing to do if (endpointName.length == 0) { return; } var endpoint = domain.endpoints.get(endpointName); $('#inventory-uploader').each(function() { new Diffa.Views.InventoryUploader({ el: $(this), model: endpoint }); }); if (flashNames) { flashEndpointNames(); } } if ($(".inventory-panel").length > 0) { panel.html('<h2>Upload an Inventory</h2>' + '<div id="inventory-selection"><p>Select a pair or an individual endpoint.</p></div>' + '<div id="inventory-uploader" class="diffa-inventory-uploader"></div>' + '<div id="inventory-uploader-upstream" class="diffa-inventory-uploader" data-pair-half="upstream"></div>' + '<div id="inventory-uploader-downstream" class="diffa-inventory-uploader" data-pair-half="downstream"></div>'); domain.loadAll(["endpoints", "pairs"], function() { panel.find("#inventory-selection").append(pairSelectTemplate({pairs: domain.pairs, domain: domain})); panel.find("#inventory-selection").append(endpointSelectTemplate({endpoints: domain.endpoints, domain: domain})); panel.find("select.pair").change(function() { pairChanged(panel.find("select.pair option:selected").val()); }); panel.find("select.endpoint").change(function() { endpointChanged(panel.find("select.endpoint option:selected").val()); }); $("#inventory-selection select").each(function(i, el) { // remove the empty-value <option> which is fine without Select2, but // with Select2 it causes problems because it's not a real choice which // should be listed in the Select2 dropdown; Select2 gives us what we need // with a placeholder. $(el).find("option:first-child").replaceWith("<option></option>"); $(el).css("width", "20em"); $(el).select2({ allowClear: true }); }); }); } })(); });
apache-2.0
mpgurucharan/vzhackathon
src/Extract.java
4648
import edu.stanford.nlp.ling.CoreAnnotations; import edu.stanford.nlp.pipeline.Annotation; import edu.stanford.nlp.pipeline.StanfordCoreNLP; import edu.stanford.nlp.semgraph.SemanticGraph; import edu.stanford.nlp.semgraph.SemanticGraphCoreAnnotations; import edu.stanford.nlp.trees.TypedDependency; import edu.stanford.nlp.util.CoreMap; import edu.stanford.nlp.ling.*; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.*; public class Extract { final String stopwordsFile = "stopwords.txt"; List<String> stopwords; public Extract() { try { stopwords = LoadStopwords(); } catch (IOException e) { e.printStackTrace(); } } private static List<Pattern> ExtractPrimaryPatterns(Collection<TypedDependency> tdl) { List<Pattern> primary = new ArrayList<Pattern>(); for (TypedDependency td : tdl) { Pattern pattern = TryExtractPattern(td); if (pattern != null) { primary.add(pattern); } } return primary; } private static Pattern TryExtractPattern(TypedDependency dependency) { String rel = dependency.reln().toString(); String gov = dependency.gov().value(); //String govTag = dependency.gov().label().tag(); String govTag = dependency.gov().backingLabel().tag(); String dep = dependency.dep().value(); //String depTag = dependency.dep().label().tag(); String depTag = dependency.dep().backingLabel().tag(); Pattern.Relation relation = Pattern.asRelation(rel); if (relation != null) { Pattern pattern = new Pattern(gov, govTag, dep, depTag, relation); if (pattern.isPrimaryPattern()) { return pattern; } } return null; } private static List<Pattern> ExtractCombinedPatterns(List<Pattern> combined, List<Pattern> primary) { List<Pattern> results = new ArrayList<Pattern>(); for (Pattern pattern : combined) { Pattern aspect = pattern.TryCombine(primary); if (aspect != null) { results.add(aspect); } } return results; } private HashSet<Pattern> ExtractSentencePatterns(CoreMap sentence) { SemanticGraph semanticGraph = sentence.get(SemanticGraphCoreAnnotations.CollapsedCCProcessedDependenciesAnnotation.class); List<Pattern> primary = ExtractPrimaryPatterns(semanticGraph.typedDependencies()); List<Pattern> combined; combined = ExtractCombinedPatterns(primary, primary); combined.addAll(ExtractCombinedPatterns(combined, primary)); combined.addAll(ExtractCombinedPatterns(combined, primary)); return PruneCombinedPatterns(combined); } private HashSet<Pattern> PruneCombinedPatterns(List<Pattern> combined) { List<Pattern> remove = new ArrayList<Pattern>(); HashSet<Pattern> patterns = new HashSet<Pattern>(combined); for (Pattern pattern : patterns) { if (patterns.contains(pattern.mother) && pattern.mother.relation != Pattern.Relation.conj_and && pattern.father.relation != Pattern.Relation.conj_and) { remove.add(pattern.mother); remove.add(pattern.father); } //remove patterns containing stopwords if (stopwords.contains(pattern.head) || stopwords.contains(pattern.modifier)) { remove.add(pattern); } } patterns.removeAll(remove); return patterns; } private List<String> LoadStopwords() throws IOException { List<String> words = new ArrayList<String>(); BufferedReader br = new BufferedReader(new FileReader(stopwordsFile)); String line; while ((line = br.readLine()) != null) { words.add(line); } br.close(); return words; } public List<Pattern> run(String text) { List<Pattern> patterns = new ArrayList<Pattern>(); Properties props = new Properties(); props.setProperty("annotators", "tokenize, ssplit, pos, parse"); StanfordCoreNLP pipeline = new StanfordCoreNLP(props); Annotation annotation = pipeline.process(text); List<CoreMap> sentences = annotation.get(CoreAnnotations.SentencesAnnotation.class); for (CoreMap sentence : sentences) { patterns.addAll(ExtractSentencePatterns(sentence)); } return patterns; } }
apache-2.0
googleads/google-ads-ruby
lib/google/ads/google_ads/v9/common/dates_pb.rb
1500
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/ads/googleads/v9/common/dates.proto require 'google/ads/google_ads/v9/enums/month_of_year_pb' require 'google/api/annotations_pb' require 'google/protobuf' Google::Protobuf::DescriptorPool.generated_pool.build do add_file("google/ads/googleads/v9/common/dates.proto", :syntax => :proto3) do add_message "google.ads.googleads.v9.common.DateRange" do proto3_optional :start_date, :string, 3 proto3_optional :end_date, :string, 4 end add_message "google.ads.googleads.v9.common.YearMonthRange" do optional :start, :message, 1, "google.ads.googleads.v9.common.YearMonth" optional :end, :message, 2, "google.ads.googleads.v9.common.YearMonth" end add_message "google.ads.googleads.v9.common.YearMonth" do optional :year, :int64, 1 optional :month, :enum, 2, "google.ads.googleads.v9.enums.MonthOfYearEnum.MonthOfYear" end end end module Google module Ads module GoogleAds module V9 module Common DateRange = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v9.common.DateRange").msgclass YearMonthRange = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v9.common.YearMonthRange").msgclass YearMonth = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v9.common.YearMonth").msgclass end end end end end
apache-2.0
KarloKnezevic/Ferko
src/java/hr/fer/zemris/jcms/service/reservations/impl/ferweb/FERWebReservationManagerFactory.java
43962
package hr.fer.zemris.jcms.service.reservations.impl.ferweb; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.log4j.Logger; import org.apache.xmlrpc.XmlRpcException; import org.apache.xmlrpc.client.XmlRpcClient; import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; import org.apache.xmlrpc.client.XmlRpcClientException; import org.apache.xmlrpc.client.XmlRpcCommonsTransportFactory; import hr.fer.zemris.jcms.parsers.TextService; import hr.fer.zemris.jcms.service.reservations.IReservationManager; import hr.fer.zemris.jcms.service.reservations.IReservationManagerFactory; import hr.fer.zemris.jcms.service.reservations.ReservationBackendException; import hr.fer.zemris.jcms.service.reservations.ReservationException; import hr.fer.zemris.jcms.service.reservations.RoomReservation; import hr.fer.zemris.jcms.service.reservations.RoomReservationEntry; import hr.fer.zemris.jcms.service.reservations.RoomReservationPeriod; import hr.fer.zemris.jcms.service.reservations.RoomReservationStatus; import hr.fer.zemris.jcms.service.reservations.RoomReservationTask; import hr.fer.zemris.util.DateUtil; public class FERWebReservationManagerFactory implements IReservationManagerFactory { private static final Logger logger = Logger.getLogger(FERWebReservationManagerFactory.class.getCanonicalName()); private static final String XMLRPC_URL_AUTH = "https://www.fer.hr/xmlrpc/xr_auth.php"; private static final String XMLRPC_URL_ROOMS = "https://www.fer.hr/xmlrpc/xr_dvorane.php"; private String ferkoUsername; private String ferkoPassword; private Set<String> controlledRooms = new HashSet<String>(); public FERWebReservationManagerFactory() { InputStream is = FERWebReservationManagerFactory.class.getClassLoader().getResourceAsStream("reservations-ferweb.properties"); if(is!=null) { Properties prop = new Properties(); try { prop.load(new InputStreamReader(is,"UTF-8")); } catch (Exception e) { logger.error("Error reading reservations-ferweb.properties."); e.printStackTrace(); } try { is.close(); } catch(Exception ignorable) {} ferkoUsername = prop.getProperty("username","invalid-user"); ferkoPassword = prop.getProperty("password","invalid-password"); } else { logger.warn("reservations-ferweb.properties not found."); } is = FERWebReservationManagerFactory.class.getClassLoader().getResourceAsStream("reservations-ferweb-rooms.txt"); if(is!=null) { try { List<String> rooms = TextService.inputStreamToUTF8StringList(is); controlledRooms.addAll(rooms); } catch (Exception e) { logger.error("Error reading reservations-ferweb-rooms.txt."); e.printStackTrace(); } try { is.close(); } catch(Exception ignorable) {} } else { logger.warn("reservations-ferweb-rooms.txt not found."); } } @Override public IReservationManager getInstance(Long userID, String jmbag, String username) throws ReservationException { return new ReservationManager(userID, jmbag, username); } /** * @author marcupic * */ private class ReservationManager implements IReservationManager { private String jmbag; private Integer login_id; public ReservationManager(Long userID, String jmbag, String username) throws ReservationException { super(); this.jmbag = jmbag; login_id = login(ferkoUsername, ferkoPassword); } @Override public Boolean isUnderControl(String roomShortName) { synchronized (controlledRooms) { return Boolean.valueOf(controlledRooms.contains(roomShortName)); } } @Override public void close() throws ReservationException { if(login_id==null) return; try { logout(login_id); } finally { login_id = null; } } public Integer login(String username, String password) throws ReservationException { int i = 0; while(true) { i++; try { return loginInternal(username, password); } catch(ReservationBackendException ex) { if(i<3) { logger.warn("Exception while communicating with FERWeb reservations for attempt "+i+"."); try { Thread.sleep(1000*(2*i)); } catch(Exception ignorable) {} continue; } else { logger.warn("Exception while communicating with FERWeb reservations for attempt "+i+" Giving up."); throw ex; } } } } /** * Prijava na FerWeb. Uvijek vraća broj koji je različit on <code>null</code>. * * @param url url za rezervacije * @param username korisničko ime * @param password zaporka * @return identifikator prijave korisnika * @throws ReservationException ako se prijava ne moze obaviti */ public Integer loginInternal(String username, String password) throws ReservationException { XmlRpcClient client = null; XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); try { config.setServerURL(new URL(XMLRPC_URL_AUTH)); config.setConnectionTimeout(60*1000); config.setReplyTimeout(60*1000); } catch (MalformedURLException e1) { throw new ReservationException("Could not login to FerWeb. Nested message:"+e1.getMessage(), e1); } client = new XmlRpcClient(); client.setTransportFactory(new XmlRpcCommonsTransportFactory(client)); client.setConfig(config); Object[] params = new Object[] {username,password}; Integer login_id = null; try { login_id = (Integer)client.execute("auth.rlogin", params); } catch(XmlRpcClientException e) { e.printStackTrace(); throw new ReservationBackendException("Could not login to FerWeb. Nested message: "+e.getMessage(), e); } catch (XmlRpcException e) { e.printStackTrace(); throw new ReservationException("Could not login to FerWeb. Nested message: "+e.getMessage(), e); } if(login_id==null) { throw new ReservationException("Could not login to FerWeb. FerWeb returned invalid user handle."); } return login_id; } public void logout(Integer login_id) throws ReservationException { int i = 0; while(true) { i++; try { logoutInternal(login_id); return; } catch(ReservationBackendException ex) { if(i<3) { logger.warn("Exception while communicating with FERWeb reservations for attempt "+i+"."); try { Thread.sleep(1000*(2*i)); } catch(Exception ignorable) {} continue; } else { logger.warn("Exception while communicating with FERWeb reservations for attempt "+i+" Giving up."); throw ex; } } } } public void logoutInternal(Integer login_id) throws ReservationException { XmlRpcClient client = null; XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); try { config.setServerURL(new URL(XMLRPC_URL_AUTH)); config.setConnectionTimeout(60*1000); config.setReplyTimeout(60*1000); } catch (MalformedURLException e1) { throw new ReservationException("Could not logout from FerWeb. Nested message:"+e1.getMessage(), e1); } client = new XmlRpcClient(); client.setTransportFactory(new XmlRpcCommonsTransportFactory(client)); client.setConfig(config); Object[] params = new Object[] {login_id}; try { client.execute("auth.rlogout",params); } catch(XmlRpcClientException e) { e.printStackTrace(); throw new ReservationBackendException("Could not logout from FerWeb. Nested message:"+e.getMessage(), e); } catch (XmlRpcException e) { throw new ReservationException("Could not logout from FerWeb. Nested message:"+e.getMessage(), e); } return; } @Override public boolean allocateRoom(String room, String dateTimeFrom, String dateTimeTo, String reason, String context) throws ReservationException { int i = 0; while(true) { i++; try { return allocateRoomInternal(room, dateTimeFrom, dateTimeTo, reason, context); } catch(ReservationBackendException ex) { if(i<3) { logger.warn("Exception while communicating with FERWeb reservations for attempt "+i+"."); try { Thread.sleep(1000*(2*i)); } catch(Exception ignorable) {} continue; } else { logger.warn("Exception while communicating with FERWeb reservations for attempt "+i+" Giving up."); throw ex; } } } } public boolean allocateRoom(String room, String dateTimeFrom, String dateTimeTo, String reason) throws ReservationException { return allocateRoom(room, dateTimeFrom, dateTimeTo, reason, null); } public boolean allocateRoomInternal(String room, String dateTimeFrom, String dateTimeTo, String reason, String context) throws ReservationException { XmlRpcClient client = null; Integer from; Integer to; try { from = unixTimeStamp(dateTimeFrom); to = unixTimeStamp(dateTimeTo); } catch (ParseException e2) { throw new ReservationException("Could not allocate room - wrong time format. Nested message: "+e2.getMessage(), e2); } XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); try { config.setServerURL(new URL(XMLRPC_URL_ROOMS)); config.setConnectionTimeout(60*1000); config.setReplyTimeout(60*1000); } catch (MalformedURLException e1) { throw new ReservationException("Could not allocate room. Nested message: "+e1.getMessage(), e1); } client = new XmlRpcClient(); client.setTransportFactory(new XmlRpcCommonsTransportFactory(client)); client.setConfig(config); Object[] cookies = updateContextCookie(null, context); Object[] params = new Object[] {login_id, room, jmbag, from, to, reason, cookies}; Boolean ok = Boolean.FALSE; try { ok = (Boolean)client.execute("dvorane.rezerviraj",params); } catch(XmlRpcClientException e) { e.printStackTrace(); throw new ReservationBackendException("Could not allocate room. Nested message: "+e.getMessage(), e); } catch (XmlRpcException e) { throw new ReservationException("Could not allocate room. Nested message: "+e.getMessage(), e); } return ok.booleanValue(); } public boolean allocateRooms(List<RoomReservationTask> rooms, String dateTimeFrom, String dateTimeTo, String reason) throws ReservationException { int i = 0; while(true) { i++; try { return allocateRoomsInternal(rooms, dateTimeFrom, dateTimeTo, reason); } catch(ReservationBackendException ex) { if(i<3) { logger.warn("Exception while communicating with FERWeb reservations for attempt "+i+"."); try { Thread.sleep(1000*(2*i)); } catch(Exception ignorable) {} continue; } else { logger.warn("Exception while communicating with FERWeb reservations for attempt "+i+" Giving up."); throw ex; } } } } public boolean allocateRoomsInternal(List<RoomReservationTask> rooms, String dateTimeFrom, String dateTimeTo, String reason) throws ReservationException { boolean allSuccessfull = true; for(RoomReservationTask task : rooms) { try { boolean success = allocateRoom(task.getRoomShortName(), dateTimeFrom, dateTimeTo, reason); task.setSuccess(success); if(!success) { allSuccessfull = false; task.setMessage("Dvoranu nije moguće rezervirati."); } } catch(ReservationException ex) { task.setSuccess(false); task.setMessage(ex.getMessage()); } } return allSuccessfull; } @Override public boolean updateReservationRoom(String room, String oldDateTimeFrom, String oldDateTimeTo, String newDateTimeFrom, String newDateTimeTo, String reason, String context, boolean justCheck) throws ReservationException { int i = 0; while(true) { i++; try { return updateReservationRoomInternal(room, oldDateTimeFrom, oldDateTimeTo, newDateTimeFrom, newDateTimeTo, reason, context, justCheck); } catch(ReservationBackendException ex) { if(i<3) { logger.warn("Exception while communicating with FERWeb reservations for attempt "+i+"."); try { Thread.sleep(1000*(2*i)); } catch(Exception ignorable) {} continue; } else { logger.warn("Exception while communicating with FERWeb reservations for attempt "+i+" Giving up."); throw ex; } } } } @SuppressWarnings("unchecked") public boolean updateReservationRoomInternal(String room, String oldDateTimeFrom, String oldDateTimeTo, String newDateTimeFrom, String newDateTimeTo, String reason, String context, boolean justCheck) throws ReservationException { XmlRpcClient client = null; Integer oldFrom; Integer oldTo; Integer newFrom; Integer newTo; try { oldFrom = unixTimeStamp(oldDateTimeFrom); oldTo = unixTimeStamp(oldDateTimeTo); newFrom = unixTimeStamp(newDateTimeFrom); newTo = unixTimeStamp(newDateTimeTo); } catch (ParseException e2) { throw new ReservationException("Could not update room - wrong time format. Nested message: "+e2.getMessage(), e2); } XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); try { config.setServerURL(new URL(XMLRPC_URL_ROOMS)); config.setConnectionTimeout(60*1000); config.setReplyTimeout(60*1000); } catch (MalformedURLException e1) { throw new ReservationException("Could not check room. Nested message: "+e1.getMessage(), e1); } client = new XmlRpcClient(); client.setTransportFactory(new XmlRpcCommonsTransportFactory(client)); client.setConfig(config); Object[] params = new Object[] {login_id, oldFrom, oldTo, new String[] {room}}; Object[] result = null; try { result = (Object[])client.execute("dvorane.rezervirano_interval",params); } catch(XmlRpcClientException e) { e.printStackTrace(); throw new ReservationBackendException("Could not update room. Nested message: "+e.getMessage(), e); } catch (XmlRpcException e) { throw new ReservationException("Could not update room. Nested message: "+e.getMessage(), e); } if(result==null || result.length==0) { return false; // te rezervacije uopce nema!!! } for(Object o : result) { Integer od = ((Map<String,Integer>)o).get("od"); Integer d = ((Map<String,Integer>)o).get("do"); // Ako nam ne smeta... if(od.intValue()!=oldFrom.intValue() || d.intValue()!=oldTo.intValue()) { continue; } // Ako je mi vec imamo... if(room.equals(((Map<String,String>)o).get("dvorana"))) { boolean nasa = false; if(reason.equals(((Map<String,String>)o).get("rez_zasto")) && jmbag.equals(((Map<String,String>)o).get("user_code"))) { nasa = true; } else if(context!=null) { if(contextCookiePresent((Object[])((Map<String,Object>)o).get("cookies"), context)) { nasa = true; } } if(nasa) { if(justCheck) return true; // Azuriraj trajanje! Map<String,Object> izvorniPodatci = new HashMap<String, Object>(); izvorniPodatci.put("room", room); izvorniPodatci.put("time_from", oldFrom); izvorniPodatci.put("time_to", oldTo); Object[] newCookies = updateContextCookie((Object[])((Map<String,Object>)o).get("cookies"), context); Map<String,Object> noviPodatci = new HashMap<String, Object>(); noviPodatci.put("room", room); noviPodatci.put("time_from", newFrom); noviPodatci.put("time_to", newTo); noviPodatci.put("description", reason); noviPodatci.put("cookies", newCookies); Object[] params2 = new Object[] {login_id, jmbag, izvorniPodatci, noviPodatci}; Boolean res = null; try { res = (Boolean)client.execute("dvorane.promjena",params2); } catch(XmlRpcClientException e) { e.printStackTrace(); throw new ReservationBackendException("Could not update room. Nested message: "+e.getMessage(), e); } catch (XmlRpcException e) { e.printStackTrace(); throw new ReservationException("Could not update room. Nested message: "+e.getMessage(), e); } if(res==null) return false; return res.booleanValue(); } else { // Nije nasa!!! return false; } } } // Nismo pronasli dvoranu!!! return false; } private Object[] updateContextCookie(Object[] cookies, String context) { if(context==null) { if(cookies!=null) return cookies; return new Object[0]; } String toFind = "context="+context; if(cookies==null || cookies.length==0) return new Object[] {toFind}; for(int i=0; i < cookies.length; i++) { Object o = cookies[i]; if(!(o instanceof String)) continue; String s = (String)o; if(s.startsWith("context=")) { cookies[i] = toFind; return cookies; } } Object[] newCookies = new Object[cookies.length+1]; System.arraycopy(cookies, 0, newCookies, 0, cookies.length); newCookies[newCookies.length-1] = toFind; return newCookies; } public boolean contextCookiePresent(Object[] cookies, String context) { if(context==null) return false; String toFind = "context="+context; if(cookies==null) return false; if(cookies.length==0) return false; for(int i=0; i < cookies.length; i++) { Object o = cookies[i]; if(!(o instanceof String)) continue; String s = (String)o; if(s.equals(toFind)) return true; } return false; } public RoomReservation checkRoom(String room, String dateTimeFrom, String dateTimeTo, String reason, String context) throws ReservationException { int i = 0; while(true) { i++; try { return checkRoomInternal(room, dateTimeFrom, dateTimeTo, reason, context); } catch(ReservationBackendException ex) { if(i<3) { logger.warn("Exception while communicating with FERWeb reservations for attempt "+i+"."); try { Thread.sleep(1000*(2*i)); } catch(Exception ignorable) {} continue; } else { logger.warn("Exception while communicating with FERWeb reservations for attempt "+i+" Giving up."); throw ex; } } } } public RoomReservation checkRoom(String room, String dateTimeFrom, String dateTimeTo, String reason) throws ReservationException { return checkRoom(room, dateTimeFrom, dateTimeTo, reason, null); } @SuppressWarnings("unchecked") public RoomReservation checkRoomInternal(String room, String dateTimeFrom, String dateTimeTo, String reason, String context) throws ReservationException { XmlRpcClient client = null; Integer from; Integer to; try { from = unixTimeStamp(dateTimeFrom); to = unixTimeStamp(dateTimeTo); } catch (ParseException e2) { throw new ReservationException("Could not check room - wrong time format. Nested message: "+e2.getMessage(), e2); } XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); try { config.setServerURL(new URL(XMLRPC_URL_ROOMS)); config.setConnectionTimeout(60*1000); config.setReplyTimeout(60*1000); } catch (MalformedURLException e1) { throw new ReservationException("Could not check room. Nested message: "+e1.getMessage(), e1); } client = new XmlRpcClient(); client.setTransportFactory(new XmlRpcCommonsTransportFactory(client)); client.setConfig(config); Object[] params = new Object[] {login_id, from, to, new String[] {room}}; Object[] result = null; try { result = (Object[])client.execute("dvorane.rezervirano_interval",params); } catch(XmlRpcClientException e) { e.printStackTrace(); throw new ReservationBackendException("Could not check room. Nested message: "+e.getMessage(), e); } catch (XmlRpcException e) { throw new ReservationException("Could not check room. Nested message: "+e.getMessage(), e); } if(result==null || result.length==0) { return new RoomReservation(room, RoomReservationStatus.FREE); // slobodno zauzmi } boolean konflikt = false; for(Object o : result) { Integer od = ((Map<String,Integer>)o).get("od"); Integer d = ((Map<String,Integer>)o).get("do"); // Ako nam ne smeta... if(od.intValue()>=to.intValue() || d.intValue()<=from.intValue()) { continue; } // Ako je mi vec imamo... if(from.equals(od) && to.equals(d) && room.equals(((Map<String,String>)o).get("dvorana"))) { boolean nasa = false; if(reason.equals(((Map<String,String>)o).get("rez_zasto")) && jmbag.equals(((Map<String,String>)o).get("user_code"))) { nasa = true; } else if(context!=null) { if(contextCookiePresent((Object[])((Map<String,Object>)o).get("cookies"), context)) { nasa = true; } } if(nasa) { return new RoomReservation(room, RoomReservationStatus.RESERVED_FOR_US); } else { konflikt = true; break; } } konflikt = true; break; } // Ako nije konflikt: if(!konflikt) { // Inace je mozemo zauzeti... return new RoomReservation(room, RoomReservationStatus.FREE); } return new RoomReservation(room, RoomReservationStatus.RESERVED_FOR_OTHER); // konflikt!!! } public List<RoomReservationEntry> listRoomReservations(List<String> rooms, String dateTimeFrom, String dateTimeTo) throws ReservationException { int i = 0; while(true) { i++; try { return listRoomReservationsInternal(rooms, dateTimeFrom, dateTimeTo); } catch(ReservationBackendException ex) { if(i<3) { logger.warn("Exception while communicating with FERWeb reservations for attempt "+i+"."); try { Thread.sleep(1000*(2*i)); } catch(Exception ignorable) {} continue; } else { logger.warn("Exception while communicating with FERWeb reservations for attempt "+i+" Giving up."); throw ex; } } } } @SuppressWarnings("unchecked") public List<RoomReservationEntry> listRoomReservationsInternal(List<String> rooms, String dateTimeFrom, String dateTimeTo) throws ReservationException { XmlRpcClient client = null; Integer from; Integer to; try { from = unixTimeStamp(dateTimeFrom); to = unixTimeStamp(dateTimeTo); } catch (ParseException e2) { throw new ReservationException("Could not check room - wrong time format. Nested message: "+e2.getMessage(), e2); } List<String> checkList = new ArrayList<String>(rooms.size()); for(int i = 0; i < rooms.size(); i++) { String roomName = rooms.get(i); if(isUnderControl(roomName)) { checkList.add(roomName); } } String[] roomsArray = new String[checkList.size()]; for(int i = 0; i < checkList.size(); i++) { roomsArray[i] = checkList.get(i); } XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); try { config.setServerURL(new URL(XMLRPC_URL_ROOMS)); config.setConnectionTimeout(60*1000); config.setReplyTimeout(60*1000); } catch (MalformedURLException e1) { throw new ReservationException("Could not check room. Nested message: "+e1.getMessage(), e1); } client = new XmlRpcClient(); client.setTransportFactory(new XmlRpcCommonsTransportFactory(client)); client.setConfig(config); Object[] params = new Object[] {login_id, from, to, roomsArray}; Object[] result = null; try { result = (Object[])client.execute("dvorane.rezervirano_interval",params); } catch(XmlRpcClientException e) { e.printStackTrace(); throw new ReservationBackendException("Could not obtain reservations list. Nested message: "+e.getMessage(), e); } catch (XmlRpcException e) { throw new ReservationException("Could not obtain reservations list. Nested message: "+e.getMessage(), e); } if(result==null || result.length==0) { return new ArrayList<RoomReservationEntry>(); } List<RoomReservationEntry> resultList = new ArrayList<RoomReservationEntry>(result.length); for(Object o : result) { Integer od = ((Map<String,Integer>)o).get("od"); Integer d = ((Map<String,Integer>)o).get("do"); // Ako nam ne smeta... if(od.intValue()>=to.intValue() || d.intValue()<=from.intValue()) { continue; } resultList.add(new RoomReservationEntry( ((Map<String,String>)o).get("dvorana"), ((Map<String,String>)o).get("user_code"), od.longValue()*1000L, d.longValue()*1000L, ((Map<String,String>)o).get("rez_zasto") )); } return resultList; } public void checkRoom(List<RoomReservation> rooms, String dateTimeFrom, String dateTimeTo, String reason, String context) throws ReservationException { int i = 0; while(true) { i++; try { checkRoomInternal(rooms, dateTimeFrom, dateTimeTo, reason, context); return; } catch(ReservationBackendException ex) { if(i<3) { logger.warn("Exception while communicating with FERWeb reservations for attempt "+i+"."); try { Thread.sleep(1000*(2*i)); } catch(Exception ignorable) {} continue; } else { logger.warn("Exception while communicating with FERWeb reservations for attempt "+i+" Giving up."); throw ex; } } } } public void checkRoom(List<RoomReservation> rooms, String dateTimeFrom, String dateTimeTo, String reason) throws ReservationException { checkRoom(rooms, dateTimeFrom, dateTimeTo, reason, null); } @SuppressWarnings("unchecked") public void checkRoomInternal(List<RoomReservation> rooms, String dateTimeFrom, String dateTimeTo, String reason, String context) throws ReservationException { XmlRpcClient client = null; Integer from; Integer to; try { from = unixTimeStamp(dateTimeFrom); to = unixTimeStamp(dateTimeTo); } catch (ParseException e2) { throw new ReservationException("Could not check room - wrong time format. Nested message: "+e2.getMessage(), e2); } // System.out.println("from = "+from+", to = "+to); XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); try { config.setServerURL(new URL(XMLRPC_URL_ROOMS)); config.setConnectionTimeout(60*1000); config.setReplyTimeout(60*1000); } catch (MalformedURLException e1) { throw new ReservationException("Could not check room. Nested message: "+e1.getMessage(), e1); } client = new XmlRpcClient(); client.setTransportFactory(new XmlRpcCommonsTransportFactory(client)); client.setConfig(config); List<RoomReservation> dupList = new ArrayList<RoomReservation>(rooms.size()); for(int i = 0; i < rooms.size(); i++) { RoomReservation roomRes = rooms.get(i); if(!isUnderControl(roomRes.getRoomShortName())) { roomRes.setStatus(RoomReservationStatus.NOT_UNDER_CONTROL); } else { dupList.add(roomRes); } } String[] roomsArray = new String[dupList.size()]; Map<String,RoomReservation> roomMap = new HashMap<String, RoomReservation>(); for(int i = 0; i < dupList.size(); i++) { roomsArray[i] = dupList.get(i).getRoomShortName(); roomMap.put(dupList.get(i).getRoomShortName(), dupList.get(i)); } Object[] params = new Object[] {login_id, from, to, roomsArray}; Object[] result = null; try { result = (Object[])client.execute("dvorane.rezervirano_interval",params); } catch(XmlRpcClientException e) { e.printStackTrace(); throw new ReservationBackendException("Could not check room. Nested message: "+e.getMessage(), e); } catch (XmlRpcException e) { throw new ReservationException("Could not check room. Nested message: "+e.getMessage(), e); } Map<String, List<Object>> results; results = new HashMap<String, List<Object>>(); if(result!=null && result.length!=0) { for(Object o : result) { String dvorana = ((Map<String,String>)o).get("dvorana"); List<Object> list = results.get(dvorana); if(list==null) { list = new ArrayList<Object>(); results.put(dvorana, list); } list.add(o); } } outer: for(String roomShortName : roomsArray) { // System.out.println("Dvorana:" + roomShortName); List<Object> list = results.get(roomShortName); RoomReservation roomRes = roomMap.get(roomShortName); // Ako nemam sobu koju je vratio FerWeb... if(roomRes==null) continue; if(list==null || list.isEmpty()) { roomRes.setStatus(RoomReservationStatus.FREE); continue; } boolean konflikt = false; for(Object o : list) { // System.out.println("Gledam: "+o); Integer od = ((Map<String,Integer>)o).get("od"); Integer d = ((Map<String,Integer>)o).get("do"); // Ako nam ne smeta... if(od.intValue()>=to.intValue() || d.intValue()<=from.intValue()) { continue; } // Ako je mi vec imamo... if(from.equals(od) && to.equals(d) && roomRes.getRoomShortName().equals(((Map<String,String>)o).get("dvorana"))) { boolean nasa = false; if(jmbag.equals(((Map<String,String>)o).get("user_code")) && reason.equals(((Map<String,String>)o).get("rez_zasto"))) { nasa = true; } else if(context!=null) { if(contextCookiePresent((Object[])((Map<String,Object>)o).get("cookies"), context)) { nasa = true; } } if(nasa) { roomRes.setStatus(RoomReservationStatus.RESERVED_FOR_US); continue outer; } else { roomRes.setStatus(RoomReservationStatus.RESERVED_FOR_OTHER); continue outer; } } konflikt = true; break; } // Ako nije konflikt: if(!konflikt) { roomRes.setStatus(RoomReservationStatus.FREE); } else { roomRes.setStatus(RoomReservationStatus.RESERVED_FOR_OTHER); } } } public boolean deallocateRoom(String room, String dateTimeFrom, String dateTimeTo) throws ReservationException { int i = 0; while(true) { i++; try { return deallocateRoomInternal(room, dateTimeFrom, dateTimeTo); } catch(ReservationBackendException ex) { if(i<3) { logger.warn("Exception while communicating with FERWeb reservations for attempt "+i+"."); try { Thread.sleep(1000*(2*i)); } catch(Exception ignorable) {} continue; } else { logger.warn("Exception while communicating with FERWeb reservations for attempt "+i+" Giving up."); throw ex; } } } } public boolean deallocateRoomInternal(String room, String dateTimeFrom, String dateTimeTo) throws ReservationException { XmlRpcClient client = null; Integer from; Integer to; try { from = unixTimeStamp(dateTimeFrom); to = unixTimeStamp(dateTimeTo); } catch (ParseException e2) { throw new ReservationException("Could not deallocate room - wrong time format. Nested message: "+e2.getMessage(), e2); } XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); try { config.setServerURL(new URL(XMLRPC_URL_ROOMS)); config.setConnectionTimeout(60*1000); config.setReplyTimeout(60*1000); } catch (MalformedURLException e1) { throw new ReservationException("Could not deallocate room. Nested message: "+e1.getMessage(), e1); } client = new XmlRpcClient(); client.setTransportFactory(new XmlRpcCommonsTransportFactory(client)); client.setConfig(config); // Ups: je li ovo FERWeb promijenio API? Odrezerviraj vise ne trazi jmbag korisnika! // Object[] params = new Object[] {login_id, room, jmbag, from, to}; Object[] params = new Object[] {login_id, room, from, to}; Boolean ok = Boolean.FALSE; try { ok = (Boolean)client.execute("dvorane.odrezerviraj",params); } catch(XmlRpcClientException e) { e.printStackTrace(); throw new ReservationBackendException("Could not deallocate room. Nested message: "+e.getMessage(), e); } catch (XmlRpcException e) { throw new ReservationException("Could not deallocate room. Nested message: "+e.getMessage(), e); } return ok.booleanValue(); } public boolean deallocateRooms(List<RoomReservationTask> rooms, String dateTimeFrom, String dateTimeTo) throws ReservationException { boolean allSuccessfull = true; for(RoomReservationTask task : rooms) { try { boolean success = deallocateRoom(task.getRoomShortName(), dateTimeFrom, dateTimeTo); task.setSuccess(success); if(!success) { allSuccessfull = false; task.setMessage("Dvoranu nije moguće odrezervirati."); } } catch(ReservationException ex) { task.setSuccess(false); task.setMessage(ex.getMessage()); } } return allSuccessfull; } private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); private Integer unixTimeStamp(String time) throws ParseException { Date d = sdf.parse(time); int stamp = (int)(d.getTime()/1000); return new Integer(stamp); } public List<RoomReservationPeriod> findAvailablePeriodsForRooms(List<String> rooms, String dateTimeFrom, String dateTimeTo) throws ReservationException { int i = 0; while(true) { i++; try { return findAvailablePeriodsForRoomsInternal(rooms, dateTimeFrom, dateTimeTo); } catch(ReservationBackendException ex) { if(i<3) { logger.warn("Exception while communicating with FERWeb reservations for attempt "+i+"."); try { Thread.sleep(1000*(2*i)); } catch(Exception ignorable) {} continue; } else { logger.warn("Exception while communicating with FERWeb reservations for attempt "+i+" Giving up."); throw ex; } } } } @SuppressWarnings("unchecked") public List<RoomReservationPeriod> findAvailablePeriodsForRoomsInternal(List<String> rooms, String dateTimeFrom, String dateTimeTo) throws ReservationException { XmlRpcClient client = null; if(!DateUtil.checkSemiFullDateFormat(dateTimeFrom)) { throw new ReservationException("Could not find available periods for rooms - wrong start time format."); } if(!DateUtil.checkSemiFullDateFormat(dateTimeTo)) { throw new ReservationException("Could not find available periods for rooms - wrong end time format."); } Integer from; Integer to; try { from = unixTimeStamp(dateTimeFrom); to = unixTimeStamp(dateTimeTo); } catch (ParseException e2) { throw new ReservationException("Could not find available periods for rooms - wrong time format. Nested message: "+e2.getMessage(), e2); } if(from>to) { throw new ReservationException("Could not find available periods for rooms - start time ("+dateTimeFrom+") is after end time ("+dateTimeTo+")."); } String[] dateRange = DateUtil.generateDateRange(dateTimeFrom.substring(0,10), dateTimeTo.substring(0,10), true); String[] middleDateRange = null; if(dateRange.length>2) { middleDateRange = new String[dateRange.length-2]; System.arraycopy(dateRange, 1, middleDateRange, 0, middleDateRange.length); } String prviDanOdTime = dateTimeFrom.substring(11); String zadnjiDanDoTime = dateTimeTo.substring(11); String prviDan = dateTimeFrom.substring(0,10); String zadnjiDan = dateTimeTo.substring(0,10); XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); try { config.setServerURL(new URL(XMLRPC_URL_ROOMS)); config.setConnectionTimeout(60*1000); config.setReplyTimeout(60*1000); } catch (MalformedURLException e1) { throw new ReservationException("Could not check room. Nested message: "+e1.getMessage(), e1); } client = new XmlRpcClient(); client.setTransportFactory(new XmlRpcCommonsTransportFactory(client)); client.setConfig(config); List<String> checkList = new ArrayList<String>(rooms.size()); List<String> notUnderControl = new ArrayList<String>(rooms.size()); for(int i = 0; i < rooms.size(); i++) { String roomName = rooms.get(i); if(!isUnderControl(roomName)) { notUnderControl.add(roomName); } else { checkList.add(roomName); } } String[] roomsArray = new String[checkList.size()]; for(int i = 0; i < checkList.size(); i++) { roomsArray[i] = checkList.get(i); } Object[] params = new Object[] {login_id, from, to, roomsArray}; Object[] result = null; try { result = (Object[])client.execute("dvorane.rezervirano_interval",params); } catch(XmlRpcClientException e) { e.printStackTrace(); throw new ReservationBackendException("Could not find available periods for rooms. Nested message: "+e.getMessage(), e); } catch (XmlRpcException e) { throw new ReservationException("Could not find available periods for rooms. Nested message: "+e.getMessage(), e); } Map<String, List<Object>> results; results = new HashMap<String, List<Object>>(); if(result!=null && result.length!=0) { for(Object o : result) { String dvorana = ((Map<String,String>)o).get("dvorana"); List<Object> list = results.get(dvorana); if(list==null) { list = new ArrayList<Object>(); results.put(dvorana, list); } list.add(o); } } List<RoomReservationPeriod> availabilityList = new ArrayList<RoomReservationPeriod>(checkList.size()*dateRange.length*3+notUnderControl.size()*dateRange.length); // Idemo za svaku sobu iz soba koje nisu pod nasom kontrolom: for(String roomShortName : notUnderControl) { if(dateRange.length==1) { availabilityList.add(new RoomReservationPeriod(roomShortName, RoomReservationStatus.FREE, dateRange[0], prviDanOdTime, zadnjiDanDoTime)); } else if(dateRange.length==2) { availabilityList.add(new RoomReservationPeriod(roomShortName, RoomReservationStatus.FREE, dateRange[0], prviDanOdTime, "20:00")); availabilityList.add(new RoomReservationPeriod(roomShortName, RoomReservationStatus.FREE, dateRange[dateRange.length-1], "08:00", zadnjiDanDoTime)); } else if(dateRange.length>2) { availabilityList.add(new RoomReservationPeriod(roomShortName, RoomReservationStatus.FREE, dateRange[0], prviDanOdTime, "20:00")); availabilityList.add(new RoomReservationPeriod(roomShortName, RoomReservationStatus.FREE, dateRange[dateRange.length-1], "08:00", zadnjiDanDoTime)); List<RoomReservationPeriod> res = generateAlwaysFree(roomShortName, middleDateRange, "08:00", "20:00"); availabilityList.addAll(res); } } // Idemo za svaku sobu iz soba koje su pod nasom kontrolom: for(String roomShortName : roomsArray) { Map<String, boolean[]> mapaZauzeca = new HashMap<String, boolean[]>(dateRange.length); for(String date : dateRange) { boolean[] dan = new boolean[24*60]; Arrays.fill(dan, false); mapaZauzeca.put(date, dan); } List<Object> list = results.get(roomShortName); // Ako za tu sobu nemam zauzeca: if(list==null || list.isEmpty()) { if(dateRange.length==1) { availabilityList.add(new RoomReservationPeriod(roomShortName, RoomReservationStatus.FREE, dateRange[0], prviDanOdTime, zadnjiDanDoTime)); } else if(dateRange.length==2) { availabilityList.add(new RoomReservationPeriod(roomShortName, RoomReservationStatus.FREE, dateRange[0], prviDanOdTime, "20:00")); availabilityList.add(new RoomReservationPeriod(roomShortName, RoomReservationStatus.FREE, dateRange[dateRange.length-1], "08:00", zadnjiDanDoTime)); } else if(dateRange.length>2) { availabilityList.add(new RoomReservationPeriod(roomShortName, RoomReservationStatus.FREE, dateRange[0], prviDanOdTime, "20:00")); availabilityList.add(new RoomReservationPeriod(roomShortName, RoomReservationStatus.FREE, dateRange[dateRange.length-1], "08:00", zadnjiDanDoTime)); List<RoomReservationPeriod> res = generateAlwaysFree(roomShortName, middleDateRange, "08:00", "20:00"); availabilityList.addAll(res); } continue; } // Inace idemo vidjeti kada su ta zauzeca: for(Object o : list) { Integer odTrenutka = ((Map<String,Integer>)o).get("od"); Integer doTrenutka = ((Map<String,Integer>)o).get("do"); if(odTrenutka.intValue()>doTrenutka.intValue()) { Integer tmp = odTrenutka; odTrenutka = doTrenutka; doTrenutka = tmp; } Date pocetak = new Date(odTrenutka.intValue()*1000L); Date kraj = new Date(doTrenutka.intValue()*1000L); String odStamp = sdf.format(pocetak); String doStamp = sdf.format(kraj); String odDate = odStamp.substring(0,10); String doDate = doStamp.substring(0,10); String odTime = odStamp.substring(11); String doTime = doStamp.substring(11); // Ako su to zauzeca unutar istog dana: if(odDate.equals(doDate)) { markAsTaken(mapaZauzeca, odDate, odTime, doTime); continue; } // Inace se interval proteze kroz nekoliko dana: String[] dani = DateUtil.generateDateRange(odDate, doDate, false); // prvi i zadnji dan imam granice; sve u sredini ide od jutra do navecer if(odTime.compareTo("20:00")<0) { markAsTaken(mapaZauzeca, dani[0], odTime, "20:00"); } if(doTime.compareTo("08:00")>0) { markAsTaken(mapaZauzeca, dani[dani.length-1], "08:00", doTime); } for(int k = 1; k < dani.length-1; k++) { markAsTaken(mapaZauzeca, dani[k], "08:00", "20:00"); } } for(String date : dateRange) { boolean[] dan = mapaZauzeca.get(date); int poc = DateUtil.shortTimeToMinutes(date.equals(prviDan) ? prviDanOdTime : "08:00"); int kra = DateUtil.shortTimeToMinutes(date.endsWith(zadnjiDan) ? zadnjiDanDoTime : "20:00"); int startOfPeriod = poc; while(startOfPeriod<dan.length) { int curr = startOfPeriod; // Vidi do kada je dvorana slobodna while(curr<dan.length && !dan[curr]) curr++; if(curr!=startOfPeriod) { // Imam jedan slobodan period if(curr>=kra) { curr=kra; if(startOfPeriod < kra) { availabilityList.add(new RoomReservationPeriod(roomShortName, RoomReservationStatus.FREE, date, DateUtil.minutesToShortTime(startOfPeriod), DateUtil.minutesToShortTime(curr))); } // Gotov sam s aktualnim danom break; } if(startOfPeriod < kra) { availabilityList.add(new RoomReservationPeriod(roomShortName, RoomReservationStatus.FREE, date, DateUtil.minutesToShortTime(startOfPeriod), DateUtil.minutesToShortTime(curr))); } } while(curr<dan.length && dan[curr]) curr++; startOfPeriod = curr; } } } return availabilityList; } /** * Pomoćna metoda koja označava zauzeti interval u mapi dvorane. Ključevi mape su datumi, vrijednosti polja booleana, * pri čemu i-ti element odgovara zauzetosti i-te minute u danu. Ako mapa nema podatke za zadani datum, zauzeće se * ignorira. * @param mapaZauzeca mapa zauzeća * @param odDate datum zauzeća * @param odTime početak zauzeća * @param doTime kraj zauzeća */ private void markAsTaken(Map<String, boolean[]> mapaZauzeca, String date, String odTime, String doTime) { int odMin = DateUtil.shortTimeToMinutes(odTime); int doMin = DateUtil.shortTimeToMinutes(doTime); boolean[] polje = mapaZauzeca.get(date); if(polje==null) return; for(int i = odMin; i < doMin; i++) { polje[i] = true; } } /** * Pomoćna metoda koja za zadanu prostoriju i raspon dana generira status koji odgovara uvijek-slobodnim terminima. * * @param roomShortName prostorija * @param dateRange raspon datuma (svaki element je formata yyyy-MM-dd) * @param fromTime pocetak vremena u danu (formata HH:mm) * @param toTime kraj vremena u danu (formata HH:mm) * @return listu statusa */ private List<RoomReservationPeriod> generateAlwaysFree(String roomShortName, String[] dateRange, String fromTime, String toTime) { List<RoomReservationPeriod> list = new ArrayList<RoomReservationPeriod>(dateRange.length); for(String date : dateRange) { list.add(new RoomReservationPeriod(roomShortName, RoomReservationStatus.FREE, date, fromTime, toTime)); } return list; } @Override public List<RoomReservationPeriod> findAvailableRoomPeriods(String room, String dateTimeFrom, String dateTimeTo) throws ReservationException { return findAvailablePeriodsForRooms(Arrays.asList(new String[] {room}), dateTimeFrom, dateTimeTo); } } }
apache-2.0
Torridity/dsworkbench
Core/src/main/java/de/tor/tribes/ui/models/REFSourceTableModel.java
3294
/* * Copyright 2015 Torridity. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tor.tribes.ui.models; import de.tor.tribes.types.ext.Village; import de.tor.tribes.ui.wiz.ref.types.REFSourceElement; import java.util.LinkedList; import java.util.List; import javax.swing.table.AbstractTableModel; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.Predicate; /** * * @author Torridity */ public class REFSourceTableModel extends AbstractTableModel { private String[] columnNames = new String[]{ "Dorf", "Verfügbare Unterstützungen" }; Class[] types = new Class[]{ Village.class, Integer.class }; private final List<REFSourceElement> elements = new LinkedList<>(); public void clear() { elements.clear(); fireTableDataChanged(); } public void addRow(Village pVillage) { elements.add(new REFSourceElement(pVillage)); fireTableDataChanged(); } public boolean removeRow(final Village pVillage, boolean pNotify) { REFSourceElement elem = (REFSourceElement) CollectionUtils.find(elements, new Predicate() { @Override public boolean evaluate(Object o) { return ((REFSourceElement) o).getVillage().equals(pVillage); } }); if (elem != null) { elements.remove(elem); } if (pNotify) { fireTableDataChanged(); } return elem != null; } @Override public int getRowCount() { if (elements == null) { return 0; } return elements.size(); } @Override public Class getColumnClass(int columnIndex) { return types[columnIndex]; } @Override public boolean isCellEditable(int row, int column) { return false; } @Override public String getColumnName(int column) { return columnNames[column]; } public void removeRow(int row) { elements.remove(row); fireTableDataChanged(); } public REFSourceElement getRow(int row) { return elements.get(row); } @Override public Object getValueAt(int row, int column) { if (elements == null || elements.size() - 1 < row) { return null; } REFSourceElement element = elements.get(row); switch (column) { case 0: return element.getVillage(); default: return element.getAvailableSupports(); } } @Override public int getColumnCount() { return columnNames.length; } }
apache-2.0
WeTheInternet/collide
client/src/main/java/com/google/collide/client/code/autocomplete/SignalEventEssence.java
2091
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.autocomplete; import org.waveprotocol.wave.client.common.util.SignalEvent; import org.waveprotocol.wave.client.common.util.SignalEvent.KeySignalType; import com.google.common.annotations.VisibleForTesting; // TODO: Replace with CharCodeWithModifiers. /** * Immutable holder of essential properties of * {@link SignalEvent} */ public class SignalEventEssence { public final int keyCode; public final boolean ctrlKey; public final boolean altKey; public final boolean shiftKey; public final boolean metaKey; public final KeySignalType type; @VisibleForTesting public SignalEventEssence(int keyCode, boolean ctrlKey, boolean altKey, boolean shiftKey, boolean metaKey, KeySignalType type) { this.keyCode = keyCode; this.ctrlKey = ctrlKey; this.altKey = altKey; this.shiftKey = shiftKey; this.metaKey = metaKey; this.type = type; } @VisibleForTesting public SignalEventEssence(int keyCode) { this(keyCode, false, false, false, false, KeySignalType.INPUT); } // TODO: Replace additional constructors with static methods. public SignalEventEssence(SignalEvent source) { this(source.getKeyCode(), source.getCtrlKey(), source.getAltKey(), source.getShiftKey(), source.getMetaKey(), source.getKeySignalType()); } public char getChar() { if (ctrlKey || altKey || metaKey || (type != KeySignalType.INPUT)) { return 0; } return (char) keyCode; } }
apache-2.0
souravbadami/oppia
core/templates/dev/head/domain/skill/SkillDifficultyObjectFactorySpec.ts
1801
// Copyright 2018 The Oppia Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unit tests for SkillDifficultyObjectFactory. */ import { SkillDifficultyObjectFactory } from 'domain/skill/SkillDifficultyObjectFactory.ts'; describe('Skill Difficulty object factory', function() { describe('SkillDifficultyObjectFactory', function() { let skillDifficultyObjectFactory: SkillDifficultyObjectFactory; beforeEach(() => { skillDifficultyObjectFactory = new SkillDifficultyObjectFactory(); }); it('should create a new skill difficulty instance', function() { var skillDifficulty = skillDifficultyObjectFactory.create('1', 'test skill', 0.3); expect(skillDifficulty.getId()).toEqual('1'); expect(skillDifficulty.getDescription()).toEqual('test skill'); expect(skillDifficulty.getDifficulty()).toEqual(0.3); }); it('should convert to a backend dictionary', function() { var skillDifficulty = skillDifficultyObjectFactory.create('1', 'test skill', 0.3); var skillDifficultyDict = { id: '1', description: 'test skill', difficulty: 0.3 }; expect(skillDifficulty.toBackendDict()).toEqual(skillDifficultyDict); }); }); });
apache-2.0
Dokman/CursoC-
Comparaciones en if/stdafx.cpp
327
// stdafx.cpp: archivo de código fuente que contiene sólo las inclusiones estándar // Comparaciones en if.pch será el encabezado precompilado // stdafx.obj contiene la información de tipos precompilada #include "stdafx.h" // TODO: mencionar los encabezados adicionales que se necesitan en STDAFX.H // pero no en este archivo
apache-2.0
johnewart/kensho
src/main/java/net/johnewart/kensho/views/QueriesView.java
1375
package net.johnewart.kensho.views; import io.dropwizard.views.View; import net.johnewart.kensho.core.Query; import net.johnewart.kensho.stats.QueryCache; import net.johnewart.kensho.stats.StatsEngine; import java.util.Collections; import java.util.Comparator; import java.util.List; public class QueriesView extends View { private final StatsEngine stats; public QueriesView(StatsEngine statsEngine) { super("/views/ftl/queries.ftl"); stats = statsEngine; } /** * Get all queries, reverse-sorted by total time * @return List<Query> all query objects */ public List<Query> getAllQueries() { List<Query> queries = QueryCache.QUERIES.getAllQueries(); Collections.sort(queries, new Comparator<Query>() { @Override public int compare(Query o1, Query o2) { return o2.getTotalQueryTime().compareTo(o1.getTotalQueryTime()); } }); return queries; } public List<Query> getSlowQueries() { List<Query> queries = QueryCache.SLOW_QUERIES.getAllQueries(); Collections.sort(queries, new Comparator<Query>() { @Override public int compare(Query o1, Query o2) { return o2.getTotalQueryTime().compareTo(o1.getTotalQueryTime()); } }); return queries; } }
apache-2.0
wlk/brainwallet-scala
src/test/scala/com/wlangiewicz/brainwallet/UnitSpec.scala
163
package com.wlangiewicz.brainwallet import org.scalatest._ abstract class UnitSpec extends FlatSpec with Matchers with OptionValues with Inside with Inspectors
apache-2.0
packerbobohu/ibas.initialfantasy
ibas.initialfantasy.service/src/main/webapp/bsapp/privilege/index.ts
467
/** * @license * Copyright color-coding studio. All Rights Reserved. * * Use of this source code is governed by an Apache License, Version 2.0 * that can be found in the LICENSE file at http://www.apache.org/licenses/LICENSE-2.0 */ // 模块索引文件,此文件集中导出类 export * from "./PrivilegeFunc"; export * from "./PrivilegeListApp"; export * from "./PrivilegeChooseApp"; export * from "./PrivilegeViewApp"; export * from "./PrivilegeEditApp";
apache-2.0
lxqfirst/bi-platform
tesseract/src/main/java/com/baidu/rigel/biplatform/tesseract/model/PosTreeNode.java
3516
/** * Copyright (c) 2014 Baidu, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.baidu.rigel.biplatform.tesseract.model; import java.util.List; /** * * 类PosTreeNode.java的实现描述 * * @author xiaoming.chen 2013-12-15 下午8:49:10 */ public class PosTreeNode implements TreeModel { /** * default generate serialVersionUID */ private static final long serialVersionUID = 8835259876881009914L; /** * 岗位ID */ private String posId; /** * 岗位名字 */ private String name; /** * 是否有孩子节点 */ private boolean hasChildren; /** * 当前节点管辖的一线节点ID列表 */ private List<String> csPosIds; /** * 当前岗位的子岗位 */ private List<PosTreeNode> children; /** * default generate get posId * * @return the posId */ public String getPosId() { return posId; } /** * default generate posId param set method * * @param posId the posId to set */ public void setPosId(String posId) { this.posId = posId; } /** * default generate get name * * @return the name */ public String getName() { return name; } /** * default generate name param set method * * @param name the name to set */ public void setName(String name) { this.name = name; } /** * default generate get hasChildren * * @return the hasChildren */ public boolean isHasChildren() { return hasChildren; } /** * default generate hasChildren param set method * * @param hasChildren the hasChildren to set */ public void setHasChildren(boolean hasChildren) { this.hasChildren = hasChildren; } /** * default generate get children * * @return the children */ public List<PosTreeNode> getChildren() { return children; } /** * default generate children param set method * * @param children the children to set */ public void setChildren(List<PosTreeNode> children) { this.children = children; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "PosTreeNode [posId=" + posId + ", name=" + name + ", hasChildren=" + hasChildren + ", leafPosids=" + csPosIds + ", children size=" + (children == null ? 0 : children.size()) + "]"; } /** * default generate get csPosIds * * @return the csPosIds */ public List<String> getCsPosIds() { return csPosIds; } /** * default generate csPosIds param set method * * @param csPosIds the csPosIds to set */ public void setCsPosIds(List<String> csPosIds) { this.csPosIds = csPosIds; } }
apache-2.0
janes/janes-master-thesis-ecommerce
src/main/webapp/app/entities/brand/brand-dialog.component.ts
2652
import { Component, OnInit, OnDestroy } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Response } from '@angular/http'; import { Observable } from 'rxjs/Rx'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { JhiEventManager, JhiAlertService } from 'ng-jhipster'; import { Brand } from './brand.model'; import { BrandPopupService } from './brand-popup.service'; import { BrandService } from './brand.service'; @Component({ selector: 'jhi-brand-dialog', templateUrl: './brand-dialog.component.html' }) export class BrandDialogComponent implements OnInit { brand: Brand; isSaving: boolean; dateAddedDp: any; dateModifiedDp: any; constructor( public activeModal: NgbActiveModal, private jhiAlertService: JhiAlertService, private brandService: BrandService, private eventManager: JhiEventManager ) { } ngOnInit() { this.isSaving = false; } clear() { this.activeModal.dismiss('cancel'); } save() { this.isSaving = true; if (this.brand.id !== undefined) { this.subscribeToSaveResponse( this.brandService.update(this.brand)); } else { this.subscribeToSaveResponse( this.brandService.create(this.brand)); } } private subscribeToSaveResponse(result: Observable<Brand>) { result.subscribe((res: Brand) => this.onSaveSuccess(res), (res: Response) => this.onSaveError()); } private onSaveSuccess(result: Brand) { this.eventManager.broadcast({ name: 'brandListModification', content: 'OK'}); this.isSaving = false; this.activeModal.dismiss(result); } private onSaveError() { this.isSaving = false; } private onError(error: any) { this.jhiAlertService.error(error.message, null, null); } } @Component({ selector: 'jhi-brand-popup', template: '' }) export class BrandPopupComponent implements OnInit, OnDestroy { routeSub: any; constructor( private route: ActivatedRoute, private brandPopupService: BrandPopupService ) {} ngOnInit() { this.routeSub = this.route.params.subscribe((params) => { if ( params['id'] ) { this.brandPopupService .open(BrandDialogComponent as Component, params['id']); } else { this.brandPopupService .open(BrandDialogComponent as Component); } }); } ngOnDestroy() { this.routeSub.unsubscribe(); } }
apache-2.0
Orange-OpenSource/matos-profiles
matos-android/src/main/java/gov/nist/javax/sip/header/ims/SecurityVerifyHeader.java
855
package gov.nist.javax.sip.header.ims; /* * #%L * Matos * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2010 - 2014 Orange SA * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ public interface SecurityVerifyHeader extends SecurityAgreeHeader { // Fields public static final java.lang.String NAME = "Security-Verify"; }
apache-2.0
AsherYang/ThreeLine
app/src/main/java/com/asher/threeline/ui/theme/ThemeHelper.java
1393
package com.asher.threeline.ui.theme; import android.content.Context; import com.asher.threeline.util.IPreferenceKey; import com.asher.threeline.util.PreferenceUtil; /** * Created by ouyangfan on 17/4/19. * <p> * 获取Theme相关的颜色值 */ public class ThemeHelper { private PreferenceUtil SP; public ThemeHelper(Context context) { this.SP = PreferenceUtil.getInstance(context); } public static ThemeHelper getThemeHelper(Context context) { return new ThemeHelper(context); } public Theme getBaseTheme() { return Theme.fromValue(SP.getInt(IPreferenceKey.BASE_THEME, Theme.LIGHT.value)); } // 不要删除,groovy中会用到 public static Theme getBaseTheme(Context context) { PreferenceUtil SP = PreferenceUtil.getInstance(context); return Theme.fromValue(SP.getInt(IPreferenceKey.BASE_THEME, Theme.LIGHT.value)); } public void setBaseTheme(Theme baseTheme) { SP.putInt(IPreferenceKey.BASE_THEME, baseTheme.getValue()); } /** * change theme to `toTheme` * <p> * 请注意: 这个方法不要删除,用于暴露给外部调用 * * @param toTheme theme */ public void changeTheme(Theme toTheme) { setBaseTheme(toTheme); // notice: the other notification code completed in javassist which named MyInject.groovy } }
apache-2.0
romanoid/buck
src/com/facebook/buck/cli/PerfManifestCommand.java
12844
/* * Copyright 2019-present Facebook, 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.facebook.buck.cli; import com.facebook.buck.cli.PerfManifestCommand.Context; import com.facebook.buck.core.build.context.BuildContext; import com.facebook.buck.core.build.engine.manifest.Manifest; import com.facebook.buck.core.io.ArchiveMemberPath; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.model.targetgraph.TargetGraph; import com.facebook.buck.core.rulekey.RuleKey; import com.facebook.buck.core.rules.ActionGraphBuilder; import com.facebook.buck.core.rules.BuildRule; import com.facebook.buck.core.rules.BuildRuleResolver; import com.facebook.buck.core.rules.SourcePathRuleFinder; import com.facebook.buck.core.rules.attr.SupportsDependencyFileRuleKey; import com.facebook.buck.core.sourcepath.SourcePath; import com.facebook.buck.core.sourcepath.resolver.SourcePathResolver; import com.facebook.buck.core.sourcepath.resolver.impl.DefaultSourcePathResolver; import com.facebook.buck.rules.keys.DefaultRuleKeyCache; import com.facebook.buck.rules.keys.RuleKeyAndInputs; import com.facebook.buck.rules.keys.RuleKeyFactories; import com.facebook.buck.rules.keys.TrackedRuleKeyCache; import com.facebook.buck.util.CommandLineException; import com.facebook.buck.util.NamedTemporaryFile; import com.facebook.buck.util.cache.InstrumentingCacheStatsTracker; import com.facebook.buck.util.cache.impl.StackedFileHashCache; import com.facebook.buck.util.exceptions.BuckUncheckedExecutionException; import com.facebook.buck.util.hashing.FileHashLoader; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.hash.HashCode; import com.google.common.hash.HashFunction; import com.google.common.hash.Hashing; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import java.util.Random; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.Option; /** * Tests performance of creating and manipulating {@link Manifest} objects. These are used for all * depfile-supporting rules. */ public class PerfManifestCommand extends AbstractPerfCommand<Context> { // TODO(cjhopman): We should consider a mode that does a --deep build and then computes these // keys... but this is so much faster and simpler. // TODO(cjhopman): We could actually get a build that just traverses the graph and builds only the // nodes that support InitializableFromDisk. // TODO(cjhopman): Or just delete InitializatableFromDisk. @Option( name = "--unsafe-init-from-disk", usage = "Run all rules from-disk initialization. This is unsafe and might cause problems with Buck's internal state.") private boolean unsafeInitFromDisk = false; // TODO(cjhopman): We should consider a mode that does a --deep build and then computes these // keys... but this is so much faster and simpler. // TODO(cjhopman): We could actually get a build that just traverses the graph and builds only the // nodes that support depfiles. @Option( name = "--unsafe-ask-for-rule-inputs", usage = "This will ask the rules for their inputs as though they were built. This is unsafe and might cause problems with Buck's internal state.") private boolean unsafeGetInputsAfterBuilding = false; @Argument private List<String> arguments = new ArrayList<>(); public List<String> getArguments() { return arguments; } @Override Context prepareTest(CommandRunnerParams params) { try { // Create a TargetGraph that is composed of the transitive closure of all of the dependent // BuildRules for the specified BuildTargetPaths. ImmutableSet<BuildTarget> targets = convertArgumentsToBuildTargets(params, getArguments()); if (targets.isEmpty()) { throw new CommandLineException("must specify at least one build target"); } TargetGraph targetGraph = getTargetGraph(params, targets); // Get a fresh action graph since we might unsafely run init from disks... // Also, we don't measure speed of this part. ActionGraphBuilder graphBuilder = params.getActionGraphProvider().getFreshActionGraph(targetGraph).getActionGraphBuilder(); StackedFileHashCache fileHashCache = createStackedFileHashCache(params); ImmutableList<BuildRule> rulesInGraph = getRulesInGraph(graphBuilder, targets); TrackedRuleKeyCache<RuleKey> ruleKeyCache = new TrackedRuleKeyCache<>( new DefaultRuleKeyCache<>(), new InstrumentingCacheStatsTracker()); RuleKeyFactories factories = RuleKeyFactories.of( params.getRuleKeyConfiguration(), fileHashCache, graphBuilder, Long.MAX_VALUE, ruleKeyCache); if (unsafeInitFromDisk) { printWarning(params, "Unsafely initializing rules from disk."); initializeRulesFromDisk(graphBuilder, rulesInGraph); } else { printWarning(params, "manipulating manifests may fail without --unsafe-init-from-disk."); } ImmutableMap<BuildRule, ImmutableSet<SourcePath>> usedInputs; if (unsafeGetInputsAfterBuilding) { printWarning(params, "Unsafely asking for rule inputs."); usedInputs = getInputsAfterBuildingLocally(params, graphBuilder, rulesInGraph); } else { usedInputs = ImmutableMap.of(); printWarning( params, "manipulating manifests may be innacurate without --unsafe-ask-for-rule-inputs"); } ImmutableMap<SupportsDependencyFileRuleKey, RuleKeyAndInputs> manifestKeys = computeManifestKeys(rulesInGraph, factories); return new Context(manifestKeys, graphBuilder, usedInputs); } catch (Exception e) { throw new BuckUncheckedExecutionException( e, "When inspecting serialization state of the action graph."); } } private static ImmutableMap<SupportsDependencyFileRuleKey, RuleKeyAndInputs> computeManifestKeys( ImmutableList<BuildRule> rulesInGraph, RuleKeyFactories factories) { return rulesInGraph .stream() .filter(rule -> rule instanceof SupportsDependencyFileRuleKey) .map(SupportsDependencyFileRuleKey.class::cast) .filter(SupportsDependencyFileRuleKey::useDependencyFileRuleKeys) .collect( ImmutableMap.toImmutableMap( rule -> rule, rule -> { try { return factories.getDepFileRuleKeyFactory().buildManifestKey(rule); } catch (IOException e) { throw new BuckUncheckedExecutionException( e, "When computing manifest key for %s.", rule.getBuildTarget()); } })); } private static ImmutableMap<BuildRule, ImmutableSet<SourcePath>> getInputsAfterBuildingLocally( CommandRunnerParams params, ActionGraphBuilder graphBuilder, ImmutableList<BuildRule> rulesInGraph) { ImmutableMap.Builder<BuildRule, ImmutableSet<SourcePath>> usedInputs = ImmutableMap.builder(); rulesInGraph.forEach( rule -> { if (rule instanceof SupportsDependencyFileRuleKey && ((SupportsDependencyFileRuleKey) rule).useDependencyFileRuleKeys()) { try { SourcePathResolver pathResolver = DefaultSourcePathResolver.from(new SourcePathRuleFinder(graphBuilder)); usedInputs.put( rule, ImmutableSet.copyOf( ((SupportsDependencyFileRuleKey) rule) .getInputsAfterBuildingLocally( BuildContext.builder() .setShouldDeleteTemporaries(false) .setBuildCellRootPath(params.getCell().getRoot()) .setEventBus(params.getBuckEventBus()) .setJavaPackageFinder(params.getJavaPackageFinder()) .setSourcePathResolver(pathResolver) .build(), params.getCell().getCellPathResolver()))); } catch (Exception e) { throw new BuckUncheckedExecutionException( e, "When asking %s for its inputs.", rule.getBuildTarget()); } } }); return usedInputs.build(); } /** Our test context. */ public static class Context { private final ImmutableMap<SupportsDependencyFileRuleKey, RuleKeyAndInputs> manifestKeys; private final BuildRuleResolver graphBuilder; private final ImmutableMap<BuildRule, ImmutableSet<SourcePath>> usedInputs; public Context( ImmutableMap<SupportsDependencyFileRuleKey, RuleKeyAndInputs> manifestKeys, ActionGraphBuilder graphBuilder, ImmutableMap<BuildRule, ImmutableSet<SourcePath>> usedInputs) { this.manifestKeys = manifestKeys; this.graphBuilder = graphBuilder; this.usedInputs = usedInputs; } } @Override protected String getComputationName() { return "manifest parse and manipulate"; } @Override void runPerfTest(CommandRunnerParams params, Context context) throws Exception { for (Entry<SupportsDependencyFileRuleKey, RuleKeyAndInputs> entry : context.manifestKeys.entrySet()) { Manifest manifest = new Manifest(entry.getValue().getRuleKey()); // Why do we add two entries? A lot of Manifest's complexity comes from de-duplicating entries // and data between multiple manifests. If we only add a single entry, it may not do that // work. Random random = new Random(); manifest.addEntry( getFileHashLoader(random.nextInt()), entry.getValue().getRuleKey(), DefaultSourcePathResolver.from(new SourcePathRuleFinder(context.graphBuilder)), entry.getValue().getInputs(), context.usedInputs.getOrDefault(entry.getKey(), ImmutableSet.of())); manifest.addEntry( getFileHashLoader(random.nextInt()), entry.getValue().getRuleKey(), DefaultSourcePathResolver.from(new SourcePathRuleFinder(context.graphBuilder)), entry.getValue().getInputs(), context.usedInputs.getOrDefault(entry.getKey(), ImmutableSet.of())); // Includes serializing + deserializing. This should be super-fast relative to the above, but // that's okay. try (NamedTemporaryFile temporaryFile = new NamedTemporaryFile("dont", "care")) { try (OutputStream output = entry.getKey().getProjectFilesystem().newFileOutputStream(temporaryFile.get())) { manifest.serialize(output); } try (InputStream input = entry.getKey().getProjectFilesystem().newFileInputStream(temporaryFile.get())) { new Manifest(input); } } } } private FileHashLoader getFileHashLoader(int seed) { HashFunction hashFunction = Hashing.sha1(); // We put Path hashcodes because we know that Path.toString() can be slow due to BuckUnixPath. return new FileHashLoader() { int getSeedFor(int hashCode) { // This just sort of gives us a stable value of 0 or 1 for a given hashCode w/ about 95% as // 0. That then means that between the two entries that we add, like 90% of paths will have // the same hash and 10% are different. Whether or not that reflects reality? ... return ((hashCode ^ seed) & 1024) > 960 ? 0 : 1; } @Override public HashCode get(Path path) { return hashFunction.newHasher().putInt(getSeedFor(path.hashCode())).hash(); } @Override public long getSize(Path path) { return 0; } @Override public HashCode get(ArchiveMemberPath archiveMemberPath) { return hashFunction.newHasher().putInt(getSeedFor(archiveMemberPath.hashCode())).hash(); } }; } @Override public String getShortDescription() { return "provides facilities to audit build targets' classpaths"; } }
apache-2.0
jeanca93/UTE
src/main/java/entidades/Horariosdetalletmp.java
3938
package entidades; // Generated Jul 4, 2016 12:16:49 PM by Hibernate Tools 4.0.0.Final import java.util.Date; /** * Horariosdetalletmp generated by hbm2java */ public class Horariosdetalletmp implements java.io.Serializable { private Integer idHorariosDetTmp; private int idHorarioCabTmp; private int idProfesor; private String idMateria; private String idCurso; private String paralelo; private String idAula; private String idDia; private int idHora; private int idEstado; private Date fechaCreacion; private int usuarioCrea; private Date fechaModificacion; private Integer usuarioModifica; public Horariosdetalletmp() { } public Horariosdetalletmp(int idHorarioCabTmp, int idProfesor, String idMateria, String idCurso, String paralelo, String idAula, String idDia, int idHora, int idEstado, Date fechaCreacion, int usuarioCrea) { this.idHorarioCabTmp = idHorarioCabTmp; this.idProfesor = idProfesor; this.idMateria = idMateria; this.idCurso = idCurso; this.paralelo = paralelo; this.idAula = idAula; this.idDia = idDia; this.idHora = idHora; this.idEstado = idEstado; this.fechaCreacion = fechaCreacion; this.usuarioCrea = usuarioCrea; } public Horariosdetalletmp(int idHorarioCabTmp, int idProfesor, String idMateria, String idCurso, String paralelo, String idAula, String idDia, int idHora, int idEstado, Date fechaCreacion, int usuarioCrea, Date fechaModificacion, Integer usuarioModifica) { this.idHorarioCabTmp = idHorarioCabTmp; this.idProfesor = idProfesor; this.idMateria = idMateria; this.idCurso = idCurso; this.paralelo = paralelo; this.idAula = idAula; this.idDia = idDia; this.idHora = idHora; this.idEstado = idEstado; this.fechaCreacion = fechaCreacion; this.usuarioCrea = usuarioCrea; this.fechaModificacion = fechaModificacion; this.usuarioModifica = usuarioModifica; } public Integer getIdHorariosDetTmp() { return this.idHorariosDetTmp; } public void setIdHorariosDetTmp(Integer idHorariosDetTmp) { this.idHorariosDetTmp = idHorariosDetTmp; } public int getIdHorarioCabTmp() { return this.idHorarioCabTmp; } public void setIdHorarioCabTmp(int idHorarioCabTmp) { this.idHorarioCabTmp = idHorarioCabTmp; } public int getIdProfesor() { return this.idProfesor; } public void setIdProfesor(int idProfesor) { this.idProfesor = idProfesor; } public String getIdMateria() { return this.idMateria; } public void setIdMateria(String idMateria) { this.idMateria = idMateria; } public String getIdCurso() { return this.idCurso; } public void setIdCurso(String idCurso) { this.idCurso = idCurso; } public String getParalelo() { return this.paralelo; } public void setParalelo(String paralelo) { this.paralelo = paralelo; } public String getIdAula() { return this.idAula; } public void setIdAula(String idAula) { this.idAula = idAula; } public String getIdDia() { return this.idDia; } public void setIdDia(String idDia) { this.idDia = idDia; } public int getIdHora() { return this.idHora; } public void setIdHora(int idHora) { this.idHora = idHora; } public int getIdEstado() { return this.idEstado; } public void setIdEstado(int idEstado) { this.idEstado = idEstado; } public Date getFechaCreacion() { return this.fechaCreacion; } public void setFechaCreacion(Date fechaCreacion) { this.fechaCreacion = fechaCreacion; } public int getUsuarioCrea() { return this.usuarioCrea; } public void setUsuarioCrea(int usuarioCrea) { this.usuarioCrea = usuarioCrea; } public Date getFechaModificacion() { return this.fechaModificacion; } public void setFechaModificacion(Date fechaModificacion) { this.fechaModificacion = fechaModificacion; } public Integer getUsuarioModifica() { return this.usuarioModifica; } public void setUsuarioModifica(Integer usuarioModifica) { this.usuarioModifica = usuarioModifica; } }
apache-2.0
syamantm/finatra
utils/src/test/scala/com/twitter/finatra/tests/conversions/ByteBufferConversionsTest.scala
335
package com.twitter.finatra.tests.conversions import com.twitter.finatra.conversions.bytebuffer._ import com.twitter.inject.Test import com.twitter.io.Buf class ByteBufferConversionsTest extends Test { "debug output" in { val buf = Buf.Utf8("hello") val bb = Buf.ByteBuffer.Shared.extract(buf) bb.debugOutput() } }
apache-2.0
lugenggeng/car
CarAssess/app/src/test/java/com/wanglibao/usedcar/carassess/ExampleUnitTest.java
324
package com.wanglibao.usedcar.carassess; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
apache-2.0
Sefford/material-in-30-minutes
app/src/main/java/com/sefford/material/sample/common/ui/application/MaterialApplication.java
2208
/* * Copyright (C) 2015 Saúl Díaz * * 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.sefford.material.sample.common.ui.application; import android.app.Application; import com.sefford.material.sample.common.injection.modules.ApplicationModule; import com.sefford.material.sample.common.injection.modules.DevelopmentLoggingModule; import dagger.ObjectGraph; /** * MaterialApplication application with the initialization of app-wide injection modules. */ public class MaterialApplication extends Application { /** * Object Injection Graph for development/production. * <p/> * We don't care this is static as the Application will live as long as the execution. */ ObjectGraph objectGraph; @Override public void onCreate() { super.onCreate(); // Initialize Dagger's Dependency injection object Graph objectGraph = initializeGraph(); objectGraph.inject(this); } ObjectGraph initializeGraph() { return ObjectGraph.create(new ApplicationModule(this), new DevelopmentLoggingModule()); } /** * Injection facility for the elements. * * @param instance Instance of the object to inject dependencies * @param <T> Class that will be injected */ public <T> void inject(T instance) { objectGraph.inject(instance); } /** * Provider facility for the elements. * * @param type Type of the instance to get * @param <T> Class that will be injected */ public <T> T get(Class<T> type) { return objectGraph.get(type); } public ObjectGraph getGraph() { return objectGraph; } }
apache-2.0
jiaozhujun/c3f
src-core/com/youcan/core/util/Captcha.java
2601
package com.youcan.core.util; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.util.Random; /** * 验证码 * @author HaoNing * @version 1.0 */ public class Captcha { public static String SOURCE = "abcdefghigklmnopqrstovwxwz1234567890"; public static String[] fontTypes = {"\u5b8b\u4f53","\u65b0\u5b8b\u4f53","\u9ed1\u4f53","\u6977\u4f53","\u96b6\u4e66"}; public static String sRand = ""; private int width; private int height; public Captcha(int width,int height){ this.width = width; this.height = height; } /** * 生成随机颜色 * @param fc * @param bc * @return */ @SuppressWarnings("static-method") private Color getColor(int fc, int bc){ fc = (fc > 255 ? 255 : fc); bc = (bc > 255 ? 255 : bc); Random random = new Random(); return new Color(fc+random.nextInt(bc - fc),fc+random.nextInt(bc - fc),fc+random.nextInt(bc - fc)); } public BufferedImage getImage(){ // 创建内存对象 BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR); // 获取图形上下文 Graphics g = image.getGraphics(); // 创建随机类的实例 Random random = new Random(); // 设定图像背景色 g.setColor(getColor(200, 250)); g.fillRect(0, 0, width, height); // 在图片背景上增加噪点 g.setColor(getColor(160,200)); g.drawRect(0,0,width-1,height-1); g.setFont(new Font("Times New Roman",Font.PLAIN,20)); for( int i = 0; i < 4; i++){ g.drawString("**********************", 0, 10*(i+2)); } // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到 for (int i=0;i<155;i++) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(12); int yl = random.nextInt(12); g.drawLine(x,y,x+xl,y+yl); } sRand = ""; // 取随机产生的认证码 for( int i = 0; i < 4; i++){ boolean isUpper = (random.nextInt(62)%2==0?true:false); int start = random.nextInt(36); String rand =(isUpper? SOURCE.toUpperCase().substring(start,start+1):SOURCE.substring(start,start+1)); sRand += rand; // 设置字体的颜色 g.setColor(getColor(20,150)); // 设置字体 g.setFont(new Font(fontTypes[random.nextInt(fontTypes.length)],Font.BOLD,18+random.nextInt(4))); // 将此字符以、画到图片上 g.drawString(rand,24*i + 10+random.nextInt(8),24); } g.dispose(); return image; } }
apache-2.0
shellposhy/lemon
src/main/java/cn/com/lemon/common/connection/Oracles.java
2088
package cn.com.lemon.common.connection; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * Static utility methods pertaining to {@code Connections} primitives. * <p> * The base utility contain basic operate by {@code newInstance} and * {@code close} * * @author shellpo shih * @version 1.0 */ public final class Oracles { private Oracles() { } public static final String url = "jdbc:oracle:thin:@192.168.5.249:1521:orcl"; public static final String name = "oracle.jdbc.OracleDriver"; public static final String user = "shfpdjpt"; public static final String password = "Shfpdbdj"; private static ThreadLocal<Connection> connectthreadLocal = new ThreadLocal<Connection>(); /** * Create the {@code Connection} * * @param url * @param name * @param user * @param password * @return * @return {@code Connection} the mysql connection */ public static Connection newInstance(String url, String name, String user, String password) { Connection connect = connectthreadLocal.get(); if (connect == null) { try { Class.forName(name); connect = DriverManager.getConnection(url, user, password); connectthreadLocal.set(connect); } catch (Exception e) { e.printStackTrace(); return null; } } return connect; } /** * Create the {@code Connection} * * @return {@code Connection} the mysql connection */ public static Connection newInstance() { Connection connect = connectthreadLocal.get(); if (connect == null) { try { Class.forName(name); connect = DriverManager.getConnection(url, user, password); connectthreadLocal.set(connect); } catch (Exception e) { e.printStackTrace(); return null; } } return connect; } /** * Close the database {@code Connection} * * @return {@code Boolean} */ public static boolean close(Connection conn) { try { if (!conn.isClosed()) { conn.close(); return true; } else { return true; } } catch (SQLException e) { e.printStackTrace(); return false; } } }
apache-2.0
leomicheloni/knockout-inheritance
model.js
249
var ko = require("knockout"); function model(){ this.name = ko.observable(""); this.lastName = ko.observable(""); this.fullName = ko.computed(function(){ return this.name() + ", " + this.lastName(); }, this); }; module.exports = model;
apache-2.0
iesl/fuse_ttl
src/factorie-factorie_2.11-1.1/src/main/scala/cc/factorie/app/nlp/embedding/CBOW.scala
7467
package cc.factorie.app.nlp.embedding import cc.factorie.variable.CategoricalDomain import cc.factorie.model._ import cc.factorie.la._ import cc.factorie.optimize._ import cc.factorie.util.{IntArrayBuffer} import scala.util.Random import java.io._ import cc.factorie.util.DoubleAccumulator import scala.collection.mutable.{ArrayOps,ArrayBuffer} import java.util.zip.GZIPOutputStream class CBOWOptions extends WindowWordEmbedderOptions { val margin = new CmdOption("margin", 0.1, "DOUBLE", "Margin for WSABIE training.") val loss = new CmdOption("loss", "wsabie", "STRING", "Loss function; options are wsabie and log.") } object CBOWExample { def apply(model:CBOW, wordIndices:Array[Int], centerPosition:Int, window:Int): Option[CBOWExample] = { val targetId = wordIndices(centerPosition) if (model.discard(targetId)) { // Skip some of the most common target words //println("CBOWExample skipping "+model.domain.category(array(target))+" "+discardProb) return None } val context = new IntArrayBuffer(window*2) var i = math.max(centerPosition - window, 0) val end = math.min(centerPosition + window, wordIndices.length) while (i < end) { val wi = wordIndices(i) // Next line sometimes discards frequent words from context if (i != centerPosition && !model.discard(wi)) context += wi i += 1 } if (context.length < model.opts.minContext.value) return None val result = model.opts.loss.value match { case "log" => new LogCBOWExample(model, targetId, context.asArray) case "wsabie" => new WsabieCBOWExample(model, targetId, context.asArray) case unk => throw new Error("Unknown loss "+unk) } if (false && model.random.nextDouble() < 0.005) { val start = math.max(centerPosition - window, 0) println(s"CBOWExample raw ${Range(start, end).map(i => model.domain.category(wordIndices(i))).mkString(" ")}") println(s"CBOWExample ${model.domain.category(targetId)} ${Range(0, context.length).map(i => model.domain.category(context(i))).mkString(" ")}") } Some(result) } } trait CBOWExample extends WindowWordEmbedderExample { def targetId: Int } class LogCBOWExample(val model:CBOW, val targetId:Int, val inputIndices:Array[Int]) extends CBOWExample { val changedWeights = new ArrayBuffer[Weights] def outputIndices: Array[Int] = Array(targetId) val samples = model.makeNegativeSamples // Do this once up front so that Example.testGradient will work def accumulateValueAndGradient(value: DoubleAccumulator, gradient: WeightsMapAccumulator): Unit = { var targetEmbedding = model.outputEmbedding(targetId) val contextEmbedding = new DenseTensor1(model.dims) val len = inputIndices.length var i = 0; while (i < len) { contextEmbedding += model.inputEmbedding(inputIndices(i)); i += 1 } if (model.opts.normalizeX.value) contextEmbedding *= (1.0 / len) //for (i <- start until start+length) contextEmbedding += model.embedding(context(i)) // Positive case var score = targetEmbedding dot contextEmbedding var expScore = math.exp(-score) // FIXME this log1p is actually really slow and we don't use it for anything! // if (value ne null) value.accumulate(-math.log1p(expScore)) if (gradient ne null) { val stepSize = expScore/(1.0 + expScore) gradient.accumulate(model.outputWeights(targetId), contextEmbedding, stepSize) changedWeights += model.outputWeights(targetId) i = 0; while (i < len) { gradient.accumulate(model.inputWeights(inputIndices(i)), targetEmbedding, stepSize); changedWeights += model.inputWeights(inputIndices(i)); i += 1 } } // Negative case for (n <- 0 until model.opts.negative.value) { val falseTarget = samples(n) targetEmbedding = model.outputEmbedding(falseTarget) score = targetEmbedding dot contextEmbedding expScore = math.exp(-score) // FIXME this log1p is actually really slow and we don't use it for anything! // if (value ne null) value.accumulate(-score - math.log1p(expScore)) if (gradient ne null) { val stepSize = -1.0 / (1.0 + expScore) gradient.accumulate(model.outputWeights(falseTarget), contextEmbedding, stepSize) changedWeights += model.outputWeights(falseTarget) i = 0; while (i < len) { gradient.accumulate(model.inputWeights(inputIndices(i)), targetEmbedding, stepSize); i += 1 } } } } } class WsabieCBOWExample(val model:CBOW, val targetId:Int, val inputIndices:Array[Int]) extends CBOWExample { val changedWeights = new ArrayBuffer[Weights] def outputIndices: Array[Int] = Array(targetId) val samples = model.makeNegativeSamples // Do this once up front so that Example.testGradient will work def accumulateValueAndGradient(value: DoubleAccumulator, gradient: WeightsMapAccumulator): Unit = { val contextEmbedding = new DenseTensor1(model.dims) val len = inputIndices.length var i = 0; while (i < len) { contextEmbedding += model.inputEmbedding(inputIndices(i)); i += 1 } // TODO FIX this is weird since normalizeX should average the contexts, not project things // Also this should only project onto ball, not surface of sphere since nonconvex -luke val inputNormalizer = if (model.opts.normalizeX.value) 1.0 / math.sqrt(len) else 1.0 // TODO Should we have this normalization? In my quick eyeing of results, it looks worse with normalization than without. if (inputNormalizer != 1.0) contextEmbedding *= inputNormalizer // Normalize the input embedding // Positive case val trueTargetEmbedding = model.outputEmbedding(targetId) val trueScore = trueTargetEmbedding dot contextEmbedding // Negative cases for (s <- samples) { val falseTargetId = s val falseTargetEmbedding = model.outputEmbedding(falseTargetId) val falseScore = falseTargetEmbedding dot contextEmbedding val objective = trueScore - falseScore - model.opts.margin.value if (objective < 0.0) { if (value ne null) value.accumulate(objective) if (gradient ne null) { gradient.accumulate(model.outputWeights(targetId), contextEmbedding, inputNormalizer) //; touchedWeights += model.outputWeights(targetId) gradient.accumulate(model.outputWeights(falseTargetId), contextEmbedding, -inputNormalizer) //; touchedWeights += model.outputWeights(falseTargetId) val trueFalseEmbeddingDiff = trueTargetEmbedding - falseTargetEmbedding i = 0; while (i < len) { gradient.accumulate(model.inputWeights(inputIndices(i)), trueFalseEmbeddingDiff, inputNormalizer); changedWeights += model.inputWeights(inputIndices(i)) i += 1 } } } } } } class CBOW(override val opts:CBOWOptions) extends WordEmbedder(opts) { def newExample(model:WordEmbedder, wordIndices:Array[Int], centerPosition:Int, window:Int): Option[CBOWExample] = CBOWExample(model.asInstanceOf[CBOW], wordIndices, centerPosition, window) } object CBOW { def main(args:Array[String]): Unit = { val opts = new CBOWOptions opts.parse(args) if (!opts.input.wasInvoked) { println("Option --input is required."); System.exit(-1) } Vocabulary.opts.maxWikiPages.value = opts.maxWikiPages.value // temporary kludge val cbow = new CBOW(opts) cbow.train(opts.input.value) cbow.writeInputEmbeddings("embeddings.txt") println("CBOW.main done.") } }
apache-2.0
panlover/designpattern
src/main/java/com/yudeyang/factory/simplefactory/TomatoEgg.java
223
package com.yudeyang.factory.simplefactory; /** * Created by deyang on 2016/12/5. */ public class TomatoEgg implements Food { @Override public void cook() { System.out.println("蕃茄炒鸡蛋"); } }
apache-2.0
conker84/eclairjs-nashorn
examples/ml/lda_example.js
2792
/* * Copyright 2016 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Usage: bin/eclairjs.sh examples/ml/lda_example.js" */ function run(sc) { var SQLContext = require('eclairjs/sql/SQLContext'); var StructField = require("eclairjs/sql/types/StructField"); var StructType = require("eclairjs/sql/types/StructType"); var Metadata = require("eclairjs/sql/types/Metadata"); var RowFactory = require("eclairjs/sql/RowFactory"); var Vectors = require("eclairjs/mllib/linalg/Vectors"); var LDA = require("eclairjs/ml/clustering/LDA"); var Vector = require("eclairjs/mllib/linalg/Vector"); var VectorUDT = require("eclairjs/mllib/linalg/VectorUDT"); var sqlContext = new SQLContext(sc); var inputFile = "examples/data/mllib/sample_lda_data.txt"; // Loads data var points = sc.textFile(inputFile).map(function(line, RowFactory, Vectors){ var tok = line.split(" "); var point = []; for (var i = 0; i < tok.length; ++i) { point[i] = parseFloat(tok[i]); } var points = Vectors.dense(point); return RowFactory.create(points); }, [RowFactory, Vectors]); var fields = [new StructField("features", new VectorUDT(), false, Metadata.empty())]; var schema = new StructType(fields); var dataset = sqlContext.createDataFrame(points, schema); // Trains a LDA model var lda = new LDA() .setK(10) .setMaxIter(10); var model = lda.fit(dataset); var ret = {}; ret.logLikelihood = model.logLikelihood(dataset); ret.logPerplexity = model.logPerplexity(dataset); // Shows the result ret.topics = model.describeTopics(3); ret.transformed = model.transform(dataset); return ret; } /* check if SparkContext is defined, if it is we are being run from Unit Test */ if (typeof sparkContext === 'undefined') { var SparkConf = require('eclairjs/SparkConf'); var SparkContext = require('eclairjs/SparkContext'); var sparkConf = new SparkConf().setAppName("Example"); var sc = new SparkContext(sparkConf); var result = run(sc); print(result.logLikelihood); print(result.logPerplexity); result.topics.show(false); result.transformed.show(false); sc.stop(); }
apache-2.0
daolinet/daolinet
cli/server.go
2646
package cli import ( "crypto/tls" "strings" "time" log "github.com/Sirupsen/logrus" "github.com/daolinet/daolinet/discovery" "github.com/daolinet/daolinet/discovery/kv" "github.com/samalba/dockerclient" "github.com/codegangsta/cli" "github.com/daolinet/daolinet/api" ) func server(c *cli.Context) { listenAddr := c.String("listen") swarmUrl := c.String("swarm") allowInsecure := c.Bool("allow-insecure") ofcUrl := c.String("ofc") if ofcUrl == "" { log.Fatalf("The openflow controller url '%s' is invalid.", ofcUrl) } uri := getDiscovery(c) if uri == "" { log.Fatalf("discovery required to manage a cluster. See '%s server --help'.", c.App.Name) } //kv.Init() discovery := createDiscovery(uri, c, c.StringSlice("discovery-opt")) kvDiscovery, ok := discovery.(*kv.Discovery) if !ok { log.Fatal("Discovery service is only supported with consul, etcd and zookeeper discovery.") } var tlsConfig *tls.Config client, err := dockerclient.NewDockerClient(swarmUrl, tlsConfig) if err != nil { log.Fatal(err) } log.Debugf("connected to swarm: url=%s", swarmUrl) apiConfig := api.ApiConfig{ ListenAddr: listenAddr, OfcUrl: ofcUrl, Client: client, Store: kvDiscovery, AllowInsecure: allowInsecure, } daolinetApi, err := api.NewApi(apiConfig) if err != nil { log.Fatal(err) } if err := daolinetApi.Run(); err != nil { log.Fatal(err) } } // Initialize the discovery service. func createDiscovery(uri string, c *cli.Context, discoveryOpt []string) discovery.Backend { hb, err := time.ParseDuration(c.String("heartbeat")) if err != nil { log.Fatalf("invalid --heartbeat: %v", err) } if hb < 1*time.Second { log.Fatal("--heartbeat should be at least one second") } // Set up discovery. discovery, err := discovery.New(uri, hb, 0, getDiscoveryOpt(c)) if err != nil { log.Fatal(err) } return discovery } func getDiscoveryOpt(c *cli.Context) map[string]string { // Process the store options options := map[string]string{} for _, option := range c.StringSlice("discovery-opt") { if !strings.Contains(option, "=") { log.Fatal("--discovery-opt must contain key=value strings") } kvpair := strings.SplitN(option, "=", 2) options[kvpair[0]] = kvpair[1] } if _, ok := options["kv.path"]; !ok { options["kv.path"] = api.PathGateway } return options }
apache-2.0
ontop/ontop
core/model/src/main/java/it/unibz/inf/ontop/model/term/functionsymbol/impl/geof/GeofSymDifferenceFunctionSymbolImpl.java
1329
package it.unibz.inf.ontop.model.term.functionsymbol.impl.geof; import com.google.common.collect.ImmutableList; import it.unibz.inf.ontop.model.term.DBConstant; import it.unibz.inf.ontop.model.term.ImmutableFunctionalTerm; import it.unibz.inf.ontop.model.term.ImmutableTerm; import it.unibz.inf.ontop.model.term.TermFactory; import it.unibz.inf.ontop.model.term.functionsymbol.db.DBFunctionSymbolFactory; import it.unibz.inf.ontop.model.term.functionsymbol.db.DBMathBinaryOperator; import it.unibz.inf.ontop.model.type.DBTypeFactory; import it.unibz.inf.ontop.model.type.ObjectRDFType; import it.unibz.inf.ontop.model.type.RDFDatatype; import it.unibz.inf.ontop.model.vocabulary.UOM; import org.apache.commons.rdf.api.IRI; import javax.annotation.Nonnull; import java.util.function.BiFunction; public class GeofSymDifferenceFunctionSymbolImpl extends AbstractBinaryGeofWKTFunctionSymbolDirectImpl { public GeofSymDifferenceFunctionSymbolImpl(@Nonnull IRI functionIRI, RDFDatatype wktLiteralType, ObjectRDFType iriType) { super("GEOF_SYMDIFFERENCE", functionIRI, ImmutableList.of(wktLiteralType, wktLiteralType), wktLiteralType); } @Override public BiFunction<ImmutableTerm, ImmutableTerm, ImmutableTerm> getDBFunction(TermFactory termFactory) { return termFactory::getDBSymDifference; } }
apache-2.0
gaaiatinc/valde-hapi
lib/index.js
1263
/** * Created by Ali on 4/9/2015. */ "use strict"; /** * */ class ValdeHapiPlatform { constructor() {} /** * * @param {[type]} application_root_folder [description] * @return {[type]} [description] */ init(application_root_folder) { this.application_root_folder = application_root_folder; let app_config_module = require("./app_config"); app_config_module.init(application_root_folder); this.app_config = app_config_module.get_config(); this.app_logger = require("./app_logger"); } /** * * @param {Function} next [description] * @return {[type]} [description] */ async launch() { return new Promise(async (resolve, reject) => { try { this.app_constants = require("./app_constants"); this.model = require("./model"); this.server = await require("./server"); await this.server.initialize(); await this.server.start(); return resolve(this.server); } catch (err) { return reject(err); } }); } } /** * * @type {Object} */ module.exports = new ValdeHapiPlatform();
apache-2.0
NationalSecurityAgency/ghidra
Ghidra/Debug/Debugger-agent-dbgeng/src/main/java/agent/dbgeng/impl/dbgeng/io/WrapCallbackIDebugInputCallbacks.java
2595
/* ### * IP: GHIDRA * * 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 agent.dbgeng.impl.dbgeng.io; import com.sun.jna.Pointer; import com.sun.jna.platform.win32.Guid.REFIID; import com.sun.jna.platform.win32.WinDef.ULONG; import com.sun.jna.platform.win32.WinError; import com.sun.jna.platform.win32.WinNT.HRESULT; import com.sun.jna.platform.win32.COM.IUnknown; import com.sun.jna.ptr.PointerByReference; import agent.dbgeng.dbgeng.DebugInputCallbacks; import agent.dbgeng.impl.dbgeng.client.DebugClientImpl1; import agent.dbgeng.jna.dbgeng.io.*; public class WrapCallbackIDebugInputCallbacks implements CallbackIDebugInputCallbacks { private final DebugClientImpl1 client; private final DebugInputCallbacks cb; private ListenerIDebugInputCallbacks listener; public WrapCallbackIDebugInputCallbacks(DebugClientImpl1 client, DebugInputCallbacks cb) { this.client = client; this.cb = cb; } public void setListener(ListenerIDebugInputCallbacks listener) { this.listener = listener; } @Override public Pointer getPointer() { return listener.getPointer(); } @Override public HRESULT QueryInterface(REFIID refid, PointerByReference ppvObject) { if (null == ppvObject) { return new HRESULT(WinError.E_POINTER); } else if (refid.getValue().equals(IDebugInputCallbacks.IID_IDEBUG_INPUT_CALLBACKS)) { ppvObject.setValue(this.getPointer()); return WinError.S_OK; } else if (refid.getValue().equals(IUnknown.IID_IUNKNOWN)) { ppvObject.setValue(this.getPointer()); return WinError.S_OK; } return new HRESULT(WinError.E_NOINTERFACE); } @Override public int AddRef() { return 0; } @Override public int Release() { return 0; } @Override public HRESULT StartInput(ULONG BufferSize) { try { cb.startInput(BufferSize.longValue()); return WinError.S_OK; } catch (Throwable e) { return new HRESULT(WinError.E_UNEXPECTED); } } @Override public HRESULT EndInput() { try { cb.endInput(); return WinError.S_OK; } catch (Throwable e) { return new HRESULT(WinError.E_UNEXPECTED); } } }
apache-2.0
Arcnor/Non-Dairy-Soy-Plugin
test/net/venaglia/nondairy/mocks/MockTreeNode.java
16186
/* * Copyright 2010 - 2012 Ed Venaglia * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.venaglia.nondairy.mocks; import com.intellij.lang.ASTNode; import com.intellij.lang.FileASTNode; import com.intellij.lang.Language; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.impl.source.IdentityCharTable; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.TokenSet; import com.intellij.util.CharTable; import net.venaglia.nondairy.soylang.elements.factory.PsiElementFactory; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; /** * User: ed * Date: 2/20/12 * Time: 1:17 PM */ @SuppressWarnings("CloneDoesntDeclareCloneNotSupportedException") public class MockTreeNode implements ASTNode { private static final IElementType ERROR = new IElementType("GENERIC_ERROR_NODE", Language.ANY); MockTreeNode parent; MockTreeNode prevSibling; MockTreeNode nextSibling; List<MockTreeNode> children; IElementType type; String errorMessage; int startOffset; CharSequence text; Map<Key<?>,Object> userData; Map<Key<?>,Object> copyableUserData; PsiElement psiElement; @Override public IElementType getElementType() { return type; } @Override public String getText() { return text.toString(); } @Override public CharSequence getChars() { return text; } @Override public boolean textContains(char c) { for (int i = 0, l = text.length(); i < l; ++i) { if (text.charAt(i) == c) { return true; } } return false; } @Override public int getStartOffset() { return startOffset; } @Override public int getTextLength() { return text.length(); } @Override public TextRange getTextRange() { return new TextRange(startOffset, startOffset + text.length()); } @Override public ASTNode getTreeParent() { return parent; } @Override public ASTNode getFirstChildNode() { return children == null ? null : children.get(0); } @Override public ASTNode getLastChildNode() { return children == null ? null : children.get(children.size() - 1); } @Override public ASTNode getTreeNext() { return nextSibling; } @Override public ASTNode getTreePrev() { return prevSibling; } public List<MockTreeNode> getMockChildren() { return children; } @Override public ASTNode[] getChildren(@Nullable TokenSet filter) { List<MockTreeNode> filtered = null; if (filter == null) { filtered = children; } else if (children != null) { filtered = new ArrayList<MockTreeNode>(children.size()); for (MockTreeNode node : children) { if (filter.contains(node.getElementType())) { filtered.add(node); } } } if (filtered == null || filtered.isEmpty()) { return EMPTY_ARRAY; } return filtered.toArray(new ASTNode[filtered.size()]); } @Override public void addChild(@NotNull ASTNode child) { if (children == null) { children = new ArrayList<MockTreeNode>(); } children.add(makeMeTheParent(coerce(child))); relinkChildren(); } @Override public void addChild(@NotNull ASTNode child, @Nullable ASTNode anchorBefore) { if (anchorBefore == null) { addChild(child); return; } children.add(indexOfChild(anchorBefore), makeMeTheParent(coerce(child))); relinkChildren(); } @Override public void addLeaf(@NotNull IElementType leafType, CharSequence leafText, ASTNode anchorBefore) { MockTreeNode node = new MockLeafNode(); node.type = leafType; node.text = text; node.startOffset = startOffset; addChild(node, anchorBefore); } @Override public void removeChild(@NotNull ASTNode child) { children.remove(indexOfChild(child)).orphan(); relinkChildren(); } @Override public void removeRange(@NotNull ASTNode firstNodeToRemove, ASTNode firstNodeToKeep) { children.subList(indexOfChild(firstNodeToRemove), indexOfChild(firstNodeToKeep)); relinkChildren(); } @Override public void replaceChild(@NotNull ASTNode oldChild, @NotNull ASTNode newChild) { children.set(indexOfChild(oldChild), makeMeTheParent(coerce(newChild))); relinkChildren(); } @Override public void replaceAllChildrenToChildrenOf(ASTNode anotherParent) { MockTreeNode parent = coerce(anotherParent); if (children != null) { for (MockTreeNode child : children) { child.orphan(); } children.clear(); } if (parent.children != null) { for (MockTreeNode child : parent.children) { child.orphan(); } if (children == null) { children = new ArrayList<MockTreeNode>(); } for (MockTreeNode node : parent.children) { children.add(makeMeTheParent(node)); } parent.children.clear(); relinkChildren(); } } @Override public void addChildren(ASTNode firstChild, ASTNode firstChildToNotAdd, ASTNode anchorBefore) { List<MockTreeNode> nodes = new ArrayList<MockTreeNode>(); int i = indexOfChild(anchorBefore); for (ASTNode child = firstChild; child != firstChildToNotAdd; child = child.getTreeNext()) { nodes.add(coerce(child)); } for (MockTreeNode node : nodes) { children.add(i++, makeMeTheParent(node)); } relinkChildren(); } protected MockTreeNode emptyNewOfSameType() { return new MockTreeNode(); } @Override public MockTreeNode copyElement() { MockTreeNode copy = emptyNewOfSameType(); if (children != null && children.size() > 0) { copy.children = new ArrayList<MockTreeNode>(children.size()); for (MockTreeNode node : children) { MockTreeNode childCopy = node.copyElement(); copy.children.add(childCopy); childCopy.parent = copy; } copy.relinkChildren(); } if (copyableUserData != null) { copy.copyableUserData = new HashMap<Key<?>,Object>(copyableUserData); } return copy; } @Override public ASTNode findLeafElementAt(int offset) { throw new UnsupportedOperationException(); } @SuppressWarnings("unchecked") @Override public <T> T getCopyableUserData(Key<T> key) { if (copyableUserData == null) { return null; } return (T)copyableUserData.get(key); } @Override public <T> void putCopyableUserData(Key<T> key, T value) { if (copyableUserData == null) { copyableUserData = new HashMap<Key<?>,Object>(); } copyableUserData.put(key, value); } @Override public ASTNode findChildByType(IElementType type) { if (children != null) { for (MockTreeNode node : children) { if (type.equals(node.getElementType())) { return node; } } } return null; } @Override public ASTNode findChildByType(@NotNull TokenSet typesSet) { if (children != null) { for (MockTreeNode node : children) { if (typesSet.contains(node.getElementType())) { return node; } } } return null; } @Override public ASTNode findChildByType(@NotNull IElementType type, @Nullable ASTNode anchor) { return findChildByType(TokenSet.create(type), anchor); } @Override public ASTNode findChildByType(@NotNull TokenSet typesSet, @Nullable ASTNode anchor) { if (children != null && anchor instanceof MockTreeNode) { for (int i = indexOfChild(anchor), l = children.size(); i < l; i++) { MockTreeNode node = children.get(i); if (typesSet.contains(node.getElementType())) { return node; } } } return null; } @Override public PsiElement getPsi() { return psiElement; } @Override public <T extends PsiElement> T getPsi(Class<T> clazz) { if (psiElement != null && clazz.isInstance(psiElement)) { return clazz.cast(psiElement); } return null; } @SuppressWarnings("unchecked") @Override public <T> T getUserData(@NotNull Key<T> key) { if (userData == null) { return null; } return (T)userData.get(key); } @Override public <T> void putUserData(@NotNull Key<T> key, @Nullable T value) { if (userData == null) { userData = new HashMap<Key<?>,Object>(); } userData.put(key, value); } @Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } private void orphan() { this.parent = null; if (this.prevSibling != null) { this.prevSibling.nextSibling = nextSibling; } if (this.nextSibling != null) { this.nextSibling.prevSibling = prevSibling; } } private void relinkChildren() { for (int i = 0, l = children.size(); i <= l; i++) { MockTreeNode prev = i > 0 ? children.get(i - 1) : null; MockTreeNode next = i < l ? children.get(i) : null; if (prev != null) { prev.nextSibling = next; prev.parent = this; } if (next != null) { next.prevSibling = prev; } } } private int indexOfChild(@NotNull ASTNode node) { if (children != null && children.size() > 0 && node instanceof MockTreeNode) { return children.indexOf(coerce(node)); } throw new NoSuchElementException(); } private MockTreeNode makeMeTheParent(MockTreeNode node) { if (node.parent != null) { if (node.parent == this) { return node; } node.parent.removeChild(node); node.parent = null; } node.parent = this; return node; } private MockTreeNode coerce(ASTNode node) { if (node == null || node instanceof MockTreeNode) { return (MockTreeNode)node; } throw new IllegalArgumentException("Only MockTreeNode objects are supported in tests"); } @Override public String toString() { return toString(false); } public String toString(boolean indent) { StringBuffer buffer = new StringBuffer(); toString(indent ? "\n " : null, buffer); return buffer.toString(); } private void toString(String indent, StringBuffer buffer) { String name = psiElement == null ? null : psiElement.getClass().getSimpleName(); String s = String.format("%s <%s> \"%s\"", type, name, text); //NON-NLS if (indent != null) { buffer.append(indent); } buffer.append(s); if (children != null) { String childIndent = indent == null ? null : indent + " "; for (MockTreeNode child : children) { child.toString(childIndent, buffer); } } } public static class MockFileNode extends MockTreeNode implements FileASTNode { @NotNull @Override public CharTable getCharTable() { return IdentityCharTable.INSTANCE; } @Override public boolean isParsed() { return true; } } private static class MockLeafNode extends MockTreeNode { private MockLeafNode() { // leaf nodes cannot have children children = Collections.emptyList(); } @Override protected MockLeafNode emptyNewOfSameType() { return new MockLeafNode(); } } public static class Builder { private IElementType type; private CharSequence text; private String errorMessage; private int startOffset = Integer.MIN_VALUE; private List<Builder> children; private PsiFile psiFile; private boolean built; public Builder() { } public Builder(Builder clone, PsiFile psiFile) { this.type = clone.type; this.startOffset = clone.startOffset; this.text = clone.text; this.children = clone.children; this.psiFile = psiFile; clone.children = null; clone.built = true; } public void setType(IElementType type) { this.type = type; } public void setText(CharSequence text) { this.text = text; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } public void setStartOffset(int startOffset) { this.startOffset = startOffset; } public void addChild(Builder child) { if (children == null) { children = new ArrayList<Builder>(); } children.add(child); } public MockTreeNode build(PsiElementFactory factory) { if (built) { throw new IllegalStateException(); } if (type == null || errorMessage != null) { type = ERROR; } if (type == null || startOffset == Integer.MIN_VALUE || text == null) { throw new IllegalStateException(); } MockTreeNode node = newNode(); node.type = type; node.text = text; node.startOffset = startOffset; node.errorMessage = errorMessage; if (children != null) { node.children = new ArrayList<MockTreeNode>(children.size()); for (Builder cb : children) { MockTreeNode child = cb.build(factory); child.parent = node; node.children.add(child); } node.relinkChildren(); node.psiElement = psiFile != null ? psiFile : factory.create(node); if (psiFile instanceof MockSoyFile) { ((MockSoyFile)psiFile).setNode((FileASTNode)node); } } else { node.psiElement = factory.create(node); } built = true; return node; } protected MockTreeNode newNode() { if (psiFile != null) { return new MockFileNode(); } return new MockTreeNode(); } } }
apache-2.0
pulibrary/plum
app/models/concerns/solr_dates.rb
766
module SolrDates extend ActiveSupport::Concern included do def date_modified formatted_date('date_modified') end def date_uploaded formatted_date('date_uploaded') end def system_modified formatted_date('system_modified') end def create_date formatted_date('system_create') end end def date_created self[Solrizer.solr_name('date_created')] end private def formatted_date(field_name) value = first(Solrizer.solr_name(field_name, :stored_sortable, type: :date)) begin DateTime.parse(value).in_time_zone(Time.zone).strftime("%D %r %Z") rescue Rails.logger.info "Unable to parse date: #{value.inspect} for #{self['id']}" nil end end end
apache-2.0
studiodev/archives
2009 - Portfolio V3/theme/news-detail.tpl.php
8369
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Studio-dev.fr - Actualité : {::titrePage::}</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <meta name="Description" content="Studio-dev.fr : Développements web 2.0 et design par Julien LAFONT alias YoTsumi - Portfolio, blog et tutoriaux" /> <meta name="Keywords" content="studio-web, studio, yotsumi, julien, lafont, orange, d&eacute;veloppeur, ajax, php, web, cr&eacute;ation, site, portfolio, blog, services, designer, graphiste, programmeur, freelance" /> <link rel="shortcut icon" href="/favicon.ico" /> <base href="{::baseUrl::}" /> <link rel="stylesheet" href="theme/pink.css" type="text/css" /> <script type="text/javascript" src="include/js/librairies/jquery.js"></script> <script type="text/javascript" src="include/js/general.js"></script> <script type="text/javascript" src="include/js/bulle_infos.js"></script> {::header::}{::jvs-admin::} </head> <body> <div id="couleurs"> <ul> <li id="lien_header"></li> <li id="liMin1"><a href="javascript:void(0);" title="Changer le th&egrave;me graphique"><img src="theme/images/min_bg5.jpg" id="bg1" alt="" /></a></li> <li id="liMin2"><a href="javascript:void(0);" title="Changer le th&egrave;me graphique"><img src="theme/images/min_bg9.jpg" id="bg2" class="active" alt="" /></a></li> <li id="liMin3"><a href="javascript:void(0);" title="Changer le th&egrave;me graphique"><img src="theme/images/min_bg7.jpg" id="bg3" alt="" /></a></li> </ul> </div> <div id="badge"> <img src="theme/images/badge_love_design_b.png" alt="Création de sites internet" height="130" width="130" /> </div> <div id="header"> <div class="inside"> <h1><a href="http://www.studio-dev.fr" title="Accueil Studio-dev.fr - Développement internet 2.0">Studio-dev.fr</a></h1> <h2>Développement d'applications web <strong>2.0</strong></h2> <br /> <h2>Sites internet perso, associatif ou marchand</h2><br /> </div> </div> <div id="menu"> <div class="inside"> <a class="nav" href="contact.htm" title="Me contacter pour toutes demandes, demis, questions" style="margin-left:5px" >&nbsp;Contact&nbsp;</a> <a class="nav" href="cv-julien-lafont.htm" title="Curriculum vitae de Julien LAFONT alias Yotsumi, développeur web 2.0 sur Montpellier" style="margin-left:5px">&nbsp;&nbsp;&nbsp; CV &nbsp;&nbsp;&nbsp;</a> <a class="nav" href="portfolio.htm" title="Mes dernières réalisations : développement, design, ajax" style="margin-left:5px" >Portfolio</a> <a class="nav" id="navigationOuvrir" href="javascript:void(0);" title="Afficher le menu de navigation">Navigation</a> <a class="nav" id="navigationFermer" href="javascript:void(0);" title="Cacher le menu de navigation" style="display: none;">Fermer nav</a> </div> </div> <div class="clear"></div> <!-- Panneau dynamique --> <div id="utils" style="display: none;"> <div class="ancillary"> <div class="inside"> <div class="block first"> <h2>Actu &rsaquo; Catégories</h2> <ul class="counts"> {::menu_categories::} </ul> </div> <div class="block"> <h2>Nuage de tag 2.0</h2> <i>Bientôt disponible</i> </div> <div class="block"> <h2>Bookmarks</h2> <ul class="counts"> <li><a href="http://www.di4art.net/" title"Blog graphique Di4art : tendances graphiques" target="_blank">Blog sur les tendances graphiques <strong>di4art</strong></a></li> <li><a href="http://www.fizzystudio.com/" title="Voir les dernières créations du graphiste webdesigner Fizzy">Portfolio de mon ami graphiste <strong>FizzyStudio</strong></a></li> <li><a href="http://www.jpnp.org" title="Association de jeunes développeurs jPnP">Association de développeurs : <strong>jPnP</strong></a></li> <li><a href="http://www.webrankinfo.com" title="WebRankInfo : Tout savoir sur le référencement">Référencement google : <strong>WebRankInfo</strong></a></li> <li><a href="http://blogmarks.net/search/ajax%2Bweb2.0" title="BlogMarks" target="_blank">BlogMarks <strong>Ajax-Web2.0</strong></a></li> </ul> </div> <div class="clear"></div> </div> </div> </div> <div id="primary" class="onecol-stories" style="background-image:url({::urlTheme::});"> <div id="wait"><img src="images/wait.gif" alt="wait" /></div> <div class="inside" id="primary_effect"> <div class="story first"> <h3 id="n_titre">{::news_titre::}</h3> <div class="details"> Posté le <span id="n_date">{::news_date::}</span> &rsaquo; <span id="n_cat">{::news_cat::}</span> <div id="fleches"> <a href="#" onclick="news_naviguer('precedente','detail'); return false" id="fleche_gauche"><img src="images/fleche_gauche.gif" alt="Pr&eacute;c&eacute;dente" /></a> <a href="#" onclick="news_naviguer('suivante','detail'); return false" id="fleche_droite" style="display:none"><img src="images/fleche_droite.gif" alt="Suivante" /></a> </div> </div> <div id="n_contenu">{::news_contenu::}</div> </div> </div> <div class="clear"></div> </div> <div class="ancillary"> <div class="inside"> <div class="block first"> <h2>Qui suis-je ? </h2> <p>Salut ! <br /> Mon nom est Julien LAFONT. Je suis actuellement étudiant mais pendant mon temps libre je deviens Développeur web 2.0 / Web designer. </p> <p>&nbsp;</p> <p>Je suis ouvert à tout travail en freelance ou en collaboration. <span style="border-bottom:1px solid #00A8FF">Offrez vous mes services ! </span></p> <p>&nbsp;</p> <p>Pour me contacter, rendez vous sur <a href="contact.htm" title="Contacter Julien LAFONT : développeur web 2.0">cette page</a> ou sinon envoyez un petit mail à <br /> <img src="images/email_black.png" class="noborder"/></p> <p class="img_no_border" style="margin:10px 0 0 10px"><img src="images/doc.png" style="vertical-align:middle; border:0" /> &nbsp;<a href="cv-julien-lafont.htm" title="Voir le CV de Julien Lafont alias Yotsumi" style="border-bottom:1px solid #f06; text-decoration:none">Afficher mon CV</a></p> </div> <div class="block"> <h2>Portfolio</h2> <ul id="thumbs"> {::portfolio::} </ul> <div class="clear"></div> <h2>Nos designs </h2> <ul id="thumbs2"> {::designs::} </ul> <div class="clear"></div> </div> <div class="block"> <h2>Actualité</h2> <ul class="dates"> {::dernieres_news::} </ul> </div> <div class="clear"></div> </div> </div> <hr class="hide" /> <div id="footer"> <div class="inside"> <div class="foot-notes"> <p>Développement <strong>php</strong> et <strong>ajax</strong> par <strong>Julien LAFONT</strong> alias Yotsumi, design par Jek2k. <br /> Contenus sous license <a href="http://creativecommons.org/licenses/by-nc/2.0/fr/">Creative Commons</a> | Valide <a href="http://validator.w3.org/check?uri=referer">XHTML</a> et <a href="http://jigsaw.w3.org/css-validator/validator?uri=#/wp/wp-content/themes/hemingway/style.css">CSS</a> (si tout va bien) </p> <p class="copyright">Développé à l'aide de <a href="http://ui.jquery.com/">Jquery UI</a> et <a href="http://jquery.com/demo/thickbox/">thickbox</a></p> <div style="border-top:1px solid #6B6B6B; margin-top:10px; color:#CACACA; font-size:10px"><br />Numéro SIRET : {::siret::} - Déclaré en tant qu'auteur souscrivant au régime de l'AGESSA<br /><br /></div> </div> <p class="attributes"><a href="plan-du-site-studio-dev.htm" title="SiteMap studio-dev.fr">Plan du site</a> // <a href="rss.htm" title="flux RSS">Flux RSS</a></p> </div> </div> <div id="connexion"> <h3 id="move">Connexion</h3> <div id="closeConnexion"></div> <div id="con_contenu" style="text-align:center"> {::zone_connexion::} </div> </div> <div class="hide"><div id="id_news_courante">{::news_id::}</div></div> </body> </html>
apache-2.0
dreedcon/DEV-S.E
Motor2D/Motor2D/j1Map.cpp
18305
#include "p2Defs.h" #include "p2Log.h" #include "j1App.h" #include "Player.h" #include "ManagerCriatures.h" #include "j1Render.h" #include "j1Textures.h" #include "ParticleManager.h" #include "j1Map.h" #include <math.h> j1Map::j1Map() : j1Module(), map_loaded(false) { name.create("map"); } // Destructor j1Map::~j1Map() {} // Called before render is available bool j1Map::Awake(pugi::xml_node& config) { LOG("Loading Map Parser"); bool ret = true; folder.create(config.attribute("file").as_string()); return ret; } void j1Map::Draw(int time) { BROFILER_CATEGORY("Draw Map", Profiler::Color::DarkBlue); if(map_loaded == false) return; p2List_item<MapLayer*>* item = mapdata.layers.start; for (; item != mapdata.layers.end->next; item = item->next) { MapLayer* layer = item->data; if (time == -1) { for (int y = 0; y < mapdata.height; ++y) { for (int x = 0; x < mapdata.width; ++x) { int tile_id = layer->Get(x, y); if (tile_id > 0) { TileSet* tileset = GetTilesetFromTileId(tile_id); SDL_Rect r = tileset->GetTileRect(tile_id); iPoint pos = MapToWorld(x, y); if (App->managerC->player->CanFollowPlayer() && App->managerC->player->isMove) { if (App->managerC->player->GetDirection() == LEFT) { posBackground.x += VelocityParallax; App->render->Blit(tileset->texture, pos.x + posBackground.x, pos.y, &r); } else if (App->managerC->player->GetDirection() == RIGHT) { posBackground.x -= VelocityParallax; App->render->Blit(tileset->texture, pos.x + posBackground.x, pos.y, &r); } } else { App->render->Blit(tileset->texture, pos.x + posBackground.x, pos.y, &r); } } } } return; } else { if (layer->properties.GetInt("Background") != 0) continue; if (layer->properties.GetInt("Draw") != 1) continue; if (time == 1) { if (layer->properties.GetInt("NoDraw") != 1) continue; } else { if (layer->properties.GetInt("NoDraw") != 0) continue; } for (int y = 0; y < mapdata.height; ++y) { for (int x = 0; x < mapdata.width; ++x) { int tile_id = layer->Get(x, y); if (tile_id > 0) { TileSet* tileset = GetTilesetFromTileId(tile_id); SDL_Rect r = tileset->GetTileRect(tile_id); iPoint pos = MapToWorld(x, y); App->render->Blit(tileset->texture, pos.x, pos.y, &r); } } } } } } int Properties::GetInt(const char* value, int default_value) const { p2List_item<Property*>* item = properties.start; while (item != properties.end->next) { if (strcmp(item->data->name.GetString(), value) == 0) return item->data->value; item = item->next; } return default_value; } float Properties::GetFloat(const char* value, float default_value) const { p2List_item<Property*>* item = properties.start; while (item != properties.end->next) { if (strcmp(item->data->name.GetString(), value) == 0) return item->data->valuefloat; item = item->next; } return default_value; } TileSet* j1Map::GetTilesetFromTileId(int id) const { TileSet* set = mapdata.tilesets.start->data; p2List_item<TileSet*>* item = mapdata.tilesets.start; for (uint i = 0; i < mapdata.tilesets.count(); i++) { if (id < item->data->firstgid) { set = item->prev->data; break; } set = item->data; item = item->next; } return set; } SDL_Rect TileSet::GetTileRect(int id) const { int relative_id = id - firstgid; SDL_Rect rect; rect.w = tile_width; rect.h = tile_height; rect.x = margin + ((rect.w + spacing) * (relative_id % num_tiles_width)); rect.y = margin + ((rect.h + spacing) * (relative_id / num_tiles_width)); return rect; } iPoint j1Map::MapToWorld(int x, int y) const { iPoint ret; if (mapdata.type == MAPTYPE_ORTHOGONAL) { ret.x = x * mapdata.tile_width; ret.y = y * mapdata.tile_height; } else if (mapdata.type == MAPTYPE_ISOMETRIC) { ret.x = (x - y) * (mapdata.tile_width * 0.5f); ret.y = (x + y) * (mapdata.tile_height * 0.5f); } else { LOG("Unknown map type"); ret.x = x; ret.y = y; } return ret; } iPoint j1Map::WorldToMap(int x, int y) const { iPoint ret(0, 0); if (mapdata.type == MAPTYPE_ORTHOGONAL) { ret.x = x / mapdata.tile_width; ret.y = y / mapdata.tile_height; } else if (mapdata.type == MAPTYPE_ISOMETRIC) { float half_width = mapdata.tile_width * 0.5f; float half_height = mapdata.tile_height * 0.5f; ret.x = int((x / half_width + y / half_height) / 2) - 1; ret.y = int((y / half_height - (x / half_width)) / 2); } else { LOG("Unknown map type"); ret.x = x; ret.y = y; } return ret; } // Called before quitting bool j1Map::CleanUp() { LOG("Unloading map"); // TODO 2: Make sure you clean up any memory allocated // from tilesets / map p2List_item<TileSet*>* tileitem; tileitem = mapdata.tilesets.start; while (tileitem != NULL) { RELEASE(tileitem->data); tileitem = tileitem->next; } mapdata.tilesets.clear(); p2List_item<MapLayer*>* layeritem; layeritem = mapdata.layers.start; while (layeritem != NULL) { RELEASE(layeritem->data); layeritem = layeritem->next; } mapdata.layers.clear(); posBackground.SetToZero(); p2List_item<ParticleObject*>* objectitem; objectitem = mapdata.particleobj.start; while (objectitem != NULL) { RELEASE(objectitem->data); objectitem = objectitem->next; } mapdata.particleobj.clear(); App->particles->DeleteFireGroup(); map_file.reset(); return true; } iPoint j1Map::GetPositionStart() { int start_position = mapdata.tilesets.start->next->data->firstgid + 3; //Tile Green const MapLayer* meta_layer = mapdata.layers.start->next->next->next->data; for (int y = 0; y < meta_layer->height; y++) { for (int x = 0; x < meta_layer->width; x++) { int up = meta_layer->Get(x, y); if (up == start_position) { return iPoint(MapToWorld(x, y)); } } } } bool j1Map::NextLvl(int x, int y, int width, int height) const //TODO ELLIOT NEED FIX { int blue_nextlvl = mapdata.tilesets.start->next->data->firstgid + 1; // RED TILE iPoint center = WorldToMap(x + width / 2, y + height / 2); //left position const MapLayer* meta_layer = mapdata.layers.start->next->next->next->data; int center_player = meta_layer->Get(center.x, center.y); if (center_player == blue_nextlvl) return true; return false; } bool j1Map::CheckDead(int x, int y, int width, int height) const //TODO ELLIOT NEED FIX { int blue_nextlvl = mapdata.tilesets.start->next->data->firstgid + 2; // RED TILE iPoint center = WorldToMap(x + width / 2, y + height / 2); //left position const MapLayer* meta_layer = mapdata.layers.start->next->next->next->data; int center_player = meta_layer->Get(center.x, center.y); if (center_player == blue_nextlvl) return true; return false; } bool j1Map::MovementCost(int x, int y, int width, int height, Direction dir) const //TODO ELLIOT NEED FIX { int red_wall = mapdata.tilesets.start->next->data->firstgid; // RED TILE bool ret = true; iPoint up_left = WorldToMap(x, y); //left position iPoint up_right = WorldToMap(x + width * 2, y); //left position iPoint down_right = WorldToMap(x + width * 2, y + height); //left position iPoint down_left = WorldToMap(x, y + height); //left position const MapLayer* meta_layer = mapdata.layers.start->next->next->next->data; int up = meta_layer->Get(up_left.x, up_left.y); int left = meta_layer->Get(up_left.x, up_left.y); int right = meta_layer->Get(up_right.x, up_right.y); int down = meta_layer->Get(down_right.x, down_right.y); //Special int up_right_special = meta_layer->Get(up_right.x, up_right.y); int down_left_special = meta_layer->Get(down_left.x, down_left.y); if (dir == UP) { if (up == red_wall || up_right_special == red_wall) { ret = false; } } if (dir == LEFT) { if (left == red_wall) { ret = false; } } if (dir == RIGHT) { if (right == red_wall) { ret = false; } } if (dir == DOWN) { if (down == red_wall || down_left_special == red_wall) { ret = false; } } return ret; } bool j1Map::IsWalkable(iPoint position) { const MapLayer* meta_layer = mapdata.layers.start->next->next->next->data; int red_wall = mapdata.tilesets.start->next->data->firstgid; // RED TILE if(position.x < meta_layer->width && position.y < meta_layer->height) return red_wall != meta_layer->Get(position.x, position.y); } // Load new map bool j1Map::Load(const char* file_name) { BROFILER_CATEGORY("Load Map", Profiler::Color::DarkBlue); bool ret = true; p2SString tmp("%s%s", folder.GetString(), file_name); pugi::xml_parse_result result = map_file.load_file(tmp.GetString()); if (result == NULL) { LOG("Could not load map xml file %s. pugi error: %s", file_name, result.description()); ret = false; } if (ret == true) { // TODO 3: Create and call a private function to load and fill // all your map data LoadMap(); } // TODO 4: Create and call a private function to load a tileset // remember to support more any number of tilesets! pugi::xml_node tiledata; tiledata = map_file.child("map"); for (tiledata = tiledata.child("tileset"); tiledata && ret; tiledata = tiledata.next_sibling("tileset")) { TileSet* tileset = new TileSet(); if (ret == true) { loadTileSet(tiledata, tileset); } if (ret == true) { ret = LoadTilesetImage(tiledata, tileset); } mapdata.tilesets.add(tileset); } // Load layer info ---------------------------------------------- pugi::xml_node layer; for (layer = map_file.child("map").child("layer"); layer && ret; layer = layer.next_sibling("layer")) { MapLayer* lay = new MapLayer(); ret = LoadLayer(layer, lay); if (ret == true) mapdata.layers.add(lay); } // Load ParticleObjects ---------------------------------------------- pugi::xml_node partcileObj; for (partcileObj = map_file.child("map").child("objectgroup").child("object"); partcileObj && ret; partcileObj = partcileObj.next_sibling("object")) { ParticleObject* partobj = new ParticleObject(); ret = LoadParticleObject(partcileObj, partobj); if (ret == true) mapdata.particleobj.add(partobj); } //Apply particles if(mapdata.particleobj.count() > 0) SetParticles(); // Load Enemies --------------------------------------------------------- LOG("Loading Enemies!"); App->managerC->player->position.create(App->map->GetPositionStart().x, App->map->GetPositionStart().y); LoadEnemies(); map_loaded = ret; return ret; } void j1Map::LoadEnemies() { int enemy_normal = mapdata.tilesets.start->next->data->firstgid + 4; // Yellow 1 int enemi_fly = mapdata.tilesets.start->next->data->firstgid + 5; // Yellow 2 const MapLayer* meta_layer = mapdata.layers.start->next->next->next->data; for (int y = 0; y < mapdata.height; ++y) { for (int x = 0; x < mapdata.width; ++x) { int tile = meta_layer->Get(x, y); if (enemy_normal == tile) { App->managerC->CreateEnemyNormal(MapToWorld(x, y)); } else if (enemi_fly == tile) { App->managerC->CreateEnemyFly(MapToWorld(x, y)); } } } } bool j1Map::LoadMap() { bool flag = true; pugi::xml_node map = map_file.child("map"); if (map == NULL) { LOG("couldn`t access to the .tmx for read the map propierties"); flag = false; } else { mapdata.width = map.attribute("width").as_int(); mapdata.height = map.attribute("height").as_int(); mapdata.tile_width = map.attribute("tilewidth").as_int(); mapdata.tile_height = map.attribute("tileheight").as_int(); p2SString types(map.attribute("orientation").as_string()); if (types == "orthogonal") { mapdata.type = MAPTYPE_ORTHOGONAL; } else if (types == "isometric") { mapdata.type = MAPTYPE_ISOMETRIC; } else if (types == "staggered") { mapdata.type = MAPTYPE_STAGGERED; } else { mapdata.type = MAPTYPE_UNKNOWN; } /*p2SString orientation(map.attribute("renderorder").as_string()); if (orientation == "right-down") { mapdata.pos_type = RIGHT_DOWN; } else if (orientation == "right-up") { mapdata.pos_type = RIGHT_UP; } else if (orientation == "left-down") { mapdata.pos_type = LEFT_DOWN; } else if (orientation == "left-up") { mapdata.pos_type = LEFT_UP; }*/ } return flag; } bool j1Map::loadTileSet(pugi::xml_node &tilest_data, TileSet* set) { bool flag = true; //load all data from the tileset of map //strings set->name.create(tilest_data.attribute("name").as_string()); //ints set->firstgid = tilest_data.attribute("firstgid").as_int(); set->margin = tilest_data.attribute("margin").as_int(); set->spacing = tilest_data.attribute("spacing").as_int(); set->tile_width = tilest_data.attribute("tilewidth").as_int(); set->tile_height = tilest_data.attribute("tileheight").as_int(); pugi::xml_node offset = tilest_data.child("tileoffset"); //struct terrain type //set->terraintype.name.create(tile_data.attribute("name").as_string()); //set->terraintype.tile = tile_data.attribute("tile").as_int(); if (offset != NULL) { set->offset_x = offset.attribute("x").as_int(); set->offset_y = offset.attribute("y").as_int(); } else { set->offset_x = 0; set->offset_y = 0; } //struct tiletype /*Tile* tile = new Tile; for (pugi::xml_node point = tilest_data.child("tile"); point != NULL; point = point.next_sibling("tile")) { set->LoadTile(point, tile); set->tiles.add(tile); }*/ return flag; } bool j1Map::LoadTilesetImage(pugi::xml_node& tileset_node, TileSet* set) { bool ret = true; pugi::xml_node image = tileset_node.child("image"); if (image == NULL) { LOG("Error parsing tileset xml file: Cannot find 'image' tag."); ret = false; } else { set->texture = App->tex->Load(PATH(folder.GetString(), image.attribute("source").as_string())); int w, h; SDL_QueryTexture(set->texture, NULL, NULL, &w, &h); set->tex_width = image.attribute("width").as_int(); if (set->tex_width <= 0) { set->tex_width = w; } set->tex_height = image.attribute("height").as_int(); if (set->tex_height <= 0) { set->tex_height = h; } set->num_tiles_width = set->tex_width / (set->tile_width + set->margin); set->num_tiles_height = set->tex_height / (set->tile_height + set->margin); } return ret; } bool j1Map::LoadLayer(pugi::xml_node& node, MapLayer* layer) { bool ret = true; layer->name = node.attribute("name").as_string(); layer->width = node.attribute("width").as_int(); layer->height = node.attribute("height").as_int(); LoadProperties(node, layer->properties); pugi::xml_node layer_data = node.child("data"); if (layer_data == NULL) { LOG("Error parsing map xml file: Cannot find 'layer/data' tag."); ret = false; RELEASE(layer); } else { layer->data = new uint[layer->width*layer->height]; memset(layer->data, 0, layer->width*layer->height); int i = 0; for (pugi::xml_node tile = layer_data.child("tile"); tile; tile = tile.next_sibling("tile")) { layer->data[i++] = tile.attribute("gid").as_int(0); } } return ret; } bool j1Map::LoadParticleObject(pugi::xml_node& node, ParticleObject* object) { object->name = node.attribute("name").as_string(); object->pos_x = node.attribute("x").as_int(); object->pos_y = node.attribute("y").as_int(); object->height = node.attribute("height").as_int(); object->width = node.attribute("width").as_int(); LoadProperties(node, object->properties); return true; } // Load a group of properties from a node and fill a list with it bool j1Map::LoadProperties(pugi::xml_node& node, Properties& properties) { bool ret = false; pugi::xml_node data = node.child("properties"); if (data != NULL) { pugi::xml_node prop; for (prop = data.child("property"); prop; prop = prop.next_sibling("property")) { Properties::Property* p = new Properties::Property(); p->name = prop.attribute("name").as_string(); p->value = prop.attribute("value").as_int(); p->valuefloat = prop.attribute("value").as_float(); properties.properties.add(p); } } return ret; } void j1Map::SetParticles() { p2List_item<ParticleObject*>* item; item = mapdata.particleobj.start; while (item != NULL) { ParticleObject* obj = item->data; if (obj->properties.GetInt("Type_particle") == 0)//FOLLOW player { SDL_Rect rect; rect.x = obj->properties.GetInt("Rect_X"); rect.y = obj->properties.GetInt("Rect_Y"); rect.w = obj->properties.GetInt("Rect_W"); rect.h = obj->properties.GetInt("Rect_H"); //Create Particle Follow App->particles->CreateFollow_P(App->managerC->player->GetpositionPointer(), fPoint(obj->properties.GetInt("Offset_X"),obj->properties.GetInt("Offset_Y")), rect, iPoint(obj->width, obj->height), iPoint(obj->properties.GetInt("TimeLifeMax"),obj->properties.GetInt("TimeLifeMin")), obj->properties.GetInt("Size"), obj->properties.GetInt("NumTextureParticle"), obj->properties.GetInt("NumParticles")); App->managerC->player->particlePlayer = App->particles->Group_Follow.start->data;//This is only use 1 Particle Follow } if (obj->properties.GetInt("Type_particle") == 1)//FIRE { SDL_Rect rect; rect.x = obj->properties.GetInt("Rect_X"); rect.y = obj->properties.GetInt("Rect_Y"); rect.w = obj->properties.GetInt("Rect_W"); rect.h = obj->properties.GetInt("Rect_H"); //Create Particle Fire App->particles->CreateFire_Particle(fPoint(obj->pos_x + (obj->width/2), obj->pos_y + (obj->height / 2)), rect, iPoint(obj->width, obj->height), iPoint(obj->properties.GetInt("TimeLifeMax"),obj->properties.GetInt("TimeLifeMin")), fPoint(obj->properties.GetFloat("Speed_X"), obj->properties.GetFloat("Speed_Y")), (P_Direction)obj->properties.GetInt("Particle_Direction"), obj->properties.GetInt("Size"), obj->properties.GetInt("NumParticles"), obj->properties.GetInt("NumTextureParticle"), true); } item = item->next; } } /*bool TileSet::LoadTile(pugi::xml_node &node, Tile *tile) { bool flag = true; tile->id = node.attribute("id").as_int(); char* pointer; p2SString terrainvalue; terrainvalue.create(node.attribute("terrain").value()); for (int i = 1; i<4; i++) { tile->terrain[0] = atoi(strtok_s((char*)terrainvalue.GetString(), ",", &pointer)); } return flag; }*/
apache-2.0
vtemian/uni-west
second_year/p3/tramways/src/tramways/graph/alghoritms/BFS.java
2224
package tramways.graph.alghoritms; import tramways.graph.exceptions.NodeNotFound; import tramways.graph.exceptions.NullNodeException; import tramways.graph.interfaces.ICostEdge; import tramways.graph.interfaces.INode; import tramways.graph.interfaces.IGraph; import java.util.*; public class BFS<Node extends INode, Edge extends ICostEdge<Node>, CostType extends Number> implements RouteGraphAlgorithm<Node, Edge, CostType> { protected IGraph graph; public Map<Node, ArrayList<Node>> routesMap = new HashMap<Node, ArrayList<Node>>(); public IGraph getGraph() { return graph; } public void setGraph(IGraph graph) { this.graph = graph; } public Map<Node, ArrayList<Node>> compute(Node startNode, Node endNode) throws NodeNotFound { ArrayList<Edge> neighbors = new ArrayList<Edge>(); ArrayList<Edge> visited = new ArrayList<Edge>(); routesMap.put(startNode, null); Queue<Edge> queue = new LinkedList<Edge>(); try { neighbors = graph.getNeighborsEdge(startNode); }catch (NodeNotFound notFound) { notFound.printStackTrace(); } catch (NullNodeException e) { e.printStackTrace(); } for(Edge neighbor: neighbors){ queue.add(neighbor); } while(!queue.isEmpty()) { Edge toVisit = queue.remove(); if(visited.contains(toVisit)) continue; ArrayList<Node> nearby = new ArrayList<Node>(); if(toVisit.getRightNode() != startNode && routesMap.containsKey(toVisit.getRightNode())) { nearby = routesMap.get(toVisit.getRightNode()); } nearby.add(toVisit.getLeftNode()); routesMap.put(toVisit.getRightNode(), nearby); try { neighbors = graph.getNeighborsEdge(toVisit.getRightNode()); }catch (NodeNotFound notFound) { continue; } catch (NullNodeException e) { e.printStackTrace(); } for(Edge neighbor: neighbors){ queue.add(neighbor); } visited.add(toVisit); } return routesMap; } }
apache-2.0
telstra/open-kilda
src-java/kilda-pce/src/main/java/org/openkilda/pce/model/FindPathResult.java
956
/* Copyright 2020 Telstra Open Source * * 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.openkilda.pce.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import org.apache.commons.lang3.tuple.Pair; import java.util.List; @Getter @AllArgsConstructor @Builder public class FindPathResult { Pair<List<Edge>, List<Edge>> foundPath; boolean backUpPathComputationWayUsed; }
apache-2.0
piola-frameworks/piola-php
piola/exceptions/UserErrorException.php
383
<?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ namespace piola\exceptions; /** * Description of UserErrorException * * @author Pablo */ class UserErrorException extends \ErrorException { //put your code here }
apache-2.0
FinchYang/study
teststudy/Request.cs
327
using System; using System.Collections.Generic; namespace study { public partial class Request { public int Ordinal { get; set; } public string Content { get; set; } public string Ip { get; set; } public string Method { get; set; } public DateTime Time { get; set; } } }
apache-2.0
esjewett/tdcode-examples
lib/openUI5/resources/sap/m/Carousel-dbg.js
42341
/*! * SAP UI development toolkit for HTML5 (SAPUI5/OpenUI5) * (c) Copyright 2009-2014 SAP AG or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ /* ---------------------------------------------------------------------------------- * Hint: This is a derived (generated) file. Changes should be done in the underlying * source files only (*.control, *.js) or they will be lost after the next generation. * ---------------------------------------------------------------------------------- */ // Provides control sap.m.Carousel. jQuery.sap.declare("sap.m.Carousel"); jQuery.sap.require("sap.m.library"); jQuery.sap.require("sap.ui.core.Control"); /** * Constructor for a new Carousel. * * Accepts an object literal <code>mSettings</code> that defines initial * property values, aggregated and associated objects as well as event handlers. * * If the name of a setting is ambiguous (e.g. a property has the same name as an event), * then the framework assumes property, aggregation, association, event in that order. * To override this automatic resolution, one of the prefixes "aggregation:", "association:" * or "event:" can be added to the name of the setting (such a prefixed name must be * enclosed in single or double quotes). * * The supported settings are: * <ul> * <li>Properties * <ul> * <li>{@link #getHeight height} : sap.ui.core.CSSSize (default: '100%')</li> * <li>{@link #getWidth width} : sap.ui.core.CSSSize (default: '100%')</li> * <li>{@link #getLoop loop} : boolean (default: false)</li> * <li>{@link #getVisible visible} : boolean (default: true)</li> * <li>{@link #getShowPageIndicator showPageIndicator} : boolean (default: true)</li> * <li>{@link #getPageIndicatorPlacement pageIndicatorPlacement} : sap.m.PlacementType (default: sap.m.PlacementType.Bottom)</li> * <li>{@link #getShowBusyIndicator showBusyIndicator} : boolean (default: true)</li> * <li>{@link #getBusyIndicatorSize busyIndicatorSize} : sap.ui.core.CSSSize (default: '6em')</li></ul> * </li> * <li>Aggregations * <ul> * <li>{@link #getPages pages} <strong>(default aggregation)</strong> : sap.ui.core.Control[]</li></ul> * </li> * <li>Associations * <ul> * <li>{@link #getActivePage activePage} : string | sap.ui.core.Control</li></ul> * </li> * <li>Events * <ul> * <li>{@link sap.m.Carousel#event:loadPage loadPage} : fnListenerFunction or [fnListenerFunction, oListenerObject] or [oData, fnListenerFunction, oListenerObject]</li> * <li>{@link sap.m.Carousel#event:unloadPage unloadPage} : fnListenerFunction or [fnListenerFunction, oListenerObject] or [oData, fnListenerFunction, oListenerObject]</li> * <li>{@link sap.m.Carousel#event:pageChanged pageChanged} : fnListenerFunction or [fnListenerFunction, oListenerObject] or [oData, fnListenerFunction, oListenerObject]</li></ul> * </li> * </ul> * * @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 * The Carousel control can be used to navigate through a list of sap.m controls just like flipping through the pages of a book by swiping right or left. An indicator shows the current position within the control list. When displayed in a desktop browser, a left- and right-arrow button is displayed on the carousel's sides, which can be used to navigate through the carousel. * * Note: when displa Internet Explorer 9, page changes are not animated. * @extends sap.ui.core.Control * * @author SAP AG * @version 1.22.10 * * @constructor * @public * @name sap.m.Carousel */ sap.ui.core.Control.extend("sap.m.Carousel", { metadata : { // ---- object ---- publicMethods : [ // methods "next", "previous" ], // ---- control specific ---- library : "sap.m", properties : { "height" : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : '100%'}, "width" : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : '100%'}, "loop" : {type : "boolean", group : "Misc", defaultValue : false}, "visible" : {type : "boolean", group : "Appearance", defaultValue : true}, "showPageIndicator" : {type : "boolean", group : "Appearance", defaultValue : true}, "pageIndicatorPlacement" : {type : "sap.m.PlacementType", group : "Appearance", defaultValue : sap.m.PlacementType.Bottom}, "showBusyIndicator" : {type : "boolean", group : "Appearance", defaultValue : true, deprecated: true}, "busyIndicatorSize" : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : '6em', deprecated: true} }, defaultAggregation : "pages", aggregations : { "pages" : {type : "sap.ui.core.Control", multiple : true, singularName : "page"} }, associations : { "activePage" : {type : "sap.ui.core.Control", multiple : false} }, events : { "loadPage" : {deprecated: true}, "unloadPage" : {deprecated: true}, "pageChanged" : {} } }}); /** * Creates a new subclass of class sap.m.Carousel with name <code>sClassName</code> * and enriches it with the information contained in <code>oClassInfo</code>. * * <code>oClassInfo</code> might contain the same kind of informations as described in {@link sap.ui.core.Element.extend Element.extend}. * * @param {string} sClassName name of the class to be created * @param {object} [oClassInfo] object literal with informations about the class * @param {function} [FNMetaImpl] constructor function for the metadata object. If not given, it defaults to sap.ui.core.ElementMetadata. * @return {function} the created class / constructor function * @public * @static * @name sap.m.Carousel.extend * @function */ sap.m.Carousel.M_EVENTS = {'loadPage':'loadPage','unloadPage':'unloadPage','pageChanged':'pageChanged'}; /** * Getter for property <code>height</code>. * The height of the carousel. Note that when a percentage value is used, the height of the surrounding container must be defined. * * Default value is <code>100%</code> * * @return {sap.ui.core.CSSSize} the value of property <code>height</code> * @public * @name sap.m.Carousel#getHeight * @function */ /** * Setter for property <code>height</code>. * * Default value is <code>100%</code> * * @param {sap.ui.core.CSSSize} sHeight new value for property <code>height</code> * @return {sap.m.Carousel} <code>this</code> to allow method chaining * @public * @name sap.m.Carousel#setHeight * @function */ /** * Getter for property <code>width</code>. * The width of the carousel. Note that when a percentage value is used, the height of the surrounding container must be defined. * * Default value is <code>100%</code> * * @return {sap.ui.core.CSSSize} the value of property <code>width</code> * @public * @name sap.m.Carousel#getWidth * @function */ /** * Setter for property <code>width</code>. * * Default value is <code>100%</code> * * @param {sap.ui.core.CSSSize} sWidth new value for property <code>width</code> * @return {sap.m.Carousel} <code>this</code> to allow method chaining * @public * @name sap.m.Carousel#setWidth * @function */ /** * Getter for property <code>loop</code>. * Defines whether the carousel should loop, i.e show the first page after the last page is reached and vice versa. * * Default value is <code>false</code> * * @return {boolean} the value of property <code>loop</code> * @public * @name sap.m.Carousel#getLoop * @function */ /** * Setter for property <code>loop</code>. * * Default value is <code>false</code> * * @param {boolean} bLoop new value for property <code>loop</code> * @return {sap.m.Carousel} <code>this</code> to allow method chaining * @public * @name sap.m.Carousel#setLoop * @function */ /** * Getter for property <code>visible</code>. * Shows or hides the carousel. * * Default value is <code>true</code> * * @return {boolean} the value of property <code>visible</code> * @public * @name sap.m.Carousel#getVisible * @function */ /** * Setter for property <code>visible</code>. * * Default value is <code>true</code> * * @param {boolean} bVisible new value for property <code>visible</code> * @return {sap.m.Carousel} <code>this</code> to allow method chaining * @public * @name sap.m.Carousel#setVisible * @function */ /** * Getter for property <code>showPageIndicator</code>. * Show or hide carousel's page indicator. * * Default value is <code>true</code> * * @return {boolean} the value of property <code>showPageIndicator</code> * @public * @name sap.m.Carousel#getShowPageIndicator * @function */ /** * Setter for property <code>showPageIndicator</code>. * * Default value is <code>true</code> * * @param {boolean} bShowPageIndicator new value for property <code>showPageIndicator</code> * @return {sap.m.Carousel} <code>this</code> to allow method chaining * @public * @name sap.m.Carousel#setShowPageIndicator * @function */ /** * Getter for property <code>pageIndicatorPlacement</code>. * Defines where the carousel's page indicator is displayed. Possible values are sap.m.PlacementType.Top, sap.m.PlacementType.Bottom. Other values are ignored and the default value will be applied. The default value is sap.m.PlacementType.Bottom. * * Default value is <code>Bottom</code> * * @return {sap.m.PlacementType} the value of property <code>pageIndicatorPlacement</code> * @public * @name sap.m.Carousel#getPageIndicatorPlacement * @function */ /** * Setter for property <code>pageIndicatorPlacement</code>. * * Default value is <code>Bottom</code> * * @param {sap.m.PlacementType} oPageIndicatorPlacement new value for property <code>pageIndicatorPlacement</code> * @return {sap.m.Carousel} <code>this</code> to allow method chaining * @public * @name sap.m.Carousel#setPageIndicatorPlacement * @function */ /** * Getter for property <code>showBusyIndicator</code>. * Show or hide busy indicator in the carousel when loading pages after swipe. * * Default value is <code>true</code> * * @return {boolean} the value of property <code>showBusyIndicator</code> * @public * @deprecated Since version 1.18.7. * Since 1.18.7 pages are no longer loaded or unloaded. Therefore busy indicator is not necessary any longer. * @name sap.m.Carousel#getShowBusyIndicator * @function */ /** * Setter for property <code>showBusyIndicator</code>. * * Default value is <code>true</code> * * @param {boolean} bShowBusyIndicator new value for property <code>showBusyIndicator</code> * @return {sap.m.Carousel} <code>this</code> to allow method chaining * @public * @deprecated Since version 1.18.7. * Since 1.18.7 pages are no longer loaded or unloaded. Therefore busy indicator is not necessary any longer. * @name sap.m.Carousel#setShowBusyIndicator * @function */ /** * Getter for property <code>busyIndicatorSize</code>. * Size of the busy indicators which can be displayed in the carousel. * * Default value is <code>6em</code> * * @return {sap.ui.core.CSSSize} the value of property <code>busyIndicatorSize</code> * @public * @deprecated Since version 1.18.7. * Since 1.18.7 pages are no longer loaded or unloaded. Therefore busy indicator is not necessary any longer. * @name sap.m.Carousel#getBusyIndicatorSize * @function */ /** * Setter for property <code>busyIndicatorSize</code>. * * Default value is <code>6em</code> * * @param {sap.ui.core.CSSSize} sBusyIndicatorSize new value for property <code>busyIndicatorSize</code> * @return {sap.m.Carousel} <code>this</code> to allow method chaining * @public * @deprecated Since version 1.18.7. * Since 1.18.7 pages are no longer loaded or unloaded. Therefore busy indicator is not necessary any longer. * @name sap.m.Carousel#setBusyIndicatorSize * @function */ /** * Getter for aggregation <code>pages</code>.<br/> * The content which the carousel displays. * * <strong>Note</strong>: this is the default aggregation for Carousel. * @return {sap.ui.core.Control[]} * @public * @name sap.m.Carousel#getPages * @function */ /** * Inserts a page into the aggregation named <code>pages</code>. * * @param {sap.ui.core.Control} * oPage the page to insert; if empty, nothing is inserted * @param {int} * iIndex the <code>0</code>-based index the page should be inserted at; for * a negative value of <code>iIndex</code>, the page is inserted at position 0; for a value * greater than the current size of the aggregation, the page is inserted at * the last position * @return {sap.m.Carousel} <code>this</code> to allow method chaining * @public * @name sap.m.Carousel#insertPage * @function */ /** * Adds some page <code>oPage</code> * to the aggregation named <code>pages</code>. * * @param {sap.ui.core.Control} * oPage the page to add; if empty, nothing is inserted * @return {sap.m.Carousel} <code>this</code> to allow method chaining * @public * @name sap.m.Carousel#addPage * @function */ /** * Removes an page from the aggregation named <code>pages</code>. * * @param {int | string | sap.ui.core.Control} vPage the page to remove or its index or id * @return {sap.ui.core.Control} the removed page or null * @public * @name sap.m.Carousel#removePage * @function */ /** * Removes all the controls in the aggregation named <code>pages</code>.<br/> * Additionally unregisters them from the hosting UIArea. * @return {sap.ui.core.Control[]} an array of the removed elements (might be empty) * @public * @name sap.m.Carousel#removeAllPages * @function */ /** * Checks for the provided <code>sap.ui.core.Control</code> in the aggregation named <code>pages</code> * and returns its index if found or -1 otherwise. * * @param {sap.ui.core.Control} * oPage the page whose index is looked for. * @return {int} the index of the provided control in the aggregation if found, or -1 otherwise * @public * @name sap.m.Carousel#indexOfPage * @function */ /** * Destroys all the pages in the aggregation * named <code>pages</code>. * @return {sap.m.Carousel} <code>this</code> to allow method chaining * @public * @name sap.m.Carousel#destroyPages * @function */ /** * Provides getter and setter for the currently displayed page. For the setter, argument may be the control itself, which must be member of the carousel's page list, or the control's id. * The getter will return the control id * * @return {string} Id of the element which is the current target of the <code>activePage</code> association, or null * @public * @name sap.m.Carousel#getActivePage * @function */ /** * Provides getter and setter for the currently displayed page. For the setter, argument may be the control itself, which must be member of the carousel's page list, or the control's id. * The getter will return the control id * * @param {string | sap.ui.core.Control} vActivePage * Id of an element which becomes the new target of this <code>activePage</code> association. * Alternatively, an element instance may be given. * @return {sap.m.Carousel} <code>this</code> to allow method chaining * @public * @name sap.m.Carousel#setActivePage * @function */ /** * Carousel requires a new page to be loaded. This event may be used to fill the content of that page * * @name sap.m.Carousel#loadPage * @event * @deprecated Since version 1.18.7. * Since 1.18.7 pages are no longer loaded or unloaded * @param {sap.ui.base.Event} oControlEvent * @param {sap.ui.base.EventProvider} oControlEvent.getSource * @param {object} oControlEvent.getParameters * @param {string} oControlEvent.getParameters.pageId Id of the page which will be loaded * @public */ /** * Attach event handler <code>fnFunction</code> to the 'loadPage' event of this <code>sap.m.Carousel</code>.<br/>. * When called, the context of the event handler (its <code>this</code>) will be bound to <code>oListener<code> if specified * otherwise to this <code>sap.m.Carousel</code>.<br/> itself. * * Carousel requires a new page to be loaded. This event may be used to fill the content of that page * * @param {object} * [oData] An application specific payload object, that will be passed to the event handler along with the event object when firing the event. * @param {function} * fnFunction The function to call, when the event occurs. * @param {object} * [oListener] Context object to call the event handler with. Defaults to this <code>sap.m.Carousel</code>.<br/> itself. * * @return {sap.m.Carousel} <code>this</code> to allow method chaining * @public * @deprecated Since version 1.18.7. * Since 1.18.7 pages are no longer loaded or unloaded * @name sap.m.Carousel#attachLoadPage * @function */ /** * Detach event handler <code>fnFunction</code> from the 'loadPage' event of this <code>sap.m.Carousel</code>.<br/> * * The passed function and listener object must match the ones used for event registration. * * @param {function} * fnFunction The function to call, when the event occurs. * @param {object} * oListener Context object on which the given function had to be called. * @return {sap.m.Carousel} <code>this</code> to allow method chaining * @public * @deprecated Since version 1.18.7. * Since 1.18.7 pages are no longer loaded or unloaded * @name sap.m.Carousel#detachLoadPage * @function */ /** * Fire event loadPage to attached listeners. * * Expects following event parameters: * <ul> * <li>'pageId' of type <code>string</code> Id of the page which will be loaded</li> * </ul> * * @param {Map} [mArguments] the arguments to pass along with the event. * @return {sap.m.Carousel} <code>this</code> to allow method chaining * @protected * @deprecated Since version 1.18.7. * Since 1.18.7 pages are no longer loaded or unloaded * @name sap.m.Carousel#fireLoadPage * @function */ /** * Carousel does not display a page any longer and unloads it. This event may be used to clean up the content of that page. * * @name sap.m.Carousel#unloadPage * @event * @deprecated Since version 1.18.7. * Since 1.18.7 pages are no longer loaded or unloaded * @param {sap.ui.base.Event} oControlEvent * @param {sap.ui.base.EventProvider} oControlEvent.getSource * @param {object} oControlEvent.getParameters * @param {string} oControlEvent.getParameters.pageId Id of the page which will be unloaded * @public */ /** * Attach event handler <code>fnFunction</code> to the 'unloadPage' event of this <code>sap.m.Carousel</code>.<br/>. * When called, the context of the event handler (its <code>this</code>) will be bound to <code>oListener<code> if specified * otherwise to this <code>sap.m.Carousel</code>.<br/> itself. * * Carousel does not display a page any longer and unloads it. This event may be used to clean up the content of that page. * * @param {object} * [oData] An application specific payload object, that will be passed to the event handler along with the event object when firing the event. * @param {function} * fnFunction The function to call, when the event occurs. * @param {object} * [oListener] Context object to call the event handler with. Defaults to this <code>sap.m.Carousel</code>.<br/> itself. * * @return {sap.m.Carousel} <code>this</code> to allow method chaining * @public * @deprecated Since version 1.18.7. * Since 1.18.7 pages are no longer loaded or unloaded * @name sap.m.Carousel#attachUnloadPage * @function */ /** * Detach event handler <code>fnFunction</code> from the 'unloadPage' event of this <code>sap.m.Carousel</code>.<br/> * * The passed function and listener object must match the ones used for event registration. * * @param {function} * fnFunction The function to call, when the event occurs. * @param {object} * oListener Context object on which the given function had to be called. * @return {sap.m.Carousel} <code>this</code> to allow method chaining * @public * @deprecated Since version 1.18.7. * Since 1.18.7 pages are no longer loaded or unloaded * @name sap.m.Carousel#detachUnloadPage * @function */ /** * Fire event unloadPage to attached listeners. * * Expects following event parameters: * <ul> * <li>'pageId' of type <code>string</code> Id of the page which will be unloaded</li> * </ul> * * @param {Map} [mArguments] the arguments to pass along with the event. * @return {sap.m.Carousel} <code>this</code> to allow method chaining * @protected * @deprecated Since version 1.18.7. * Since 1.18.7 pages are no longer loaded or unloaded * @name sap.m.Carousel#fireUnloadPage * @function */ /** * This event is fired after a carousel swipe has been completed. It is triggered both by physical swipe events and through API carousel manipulations such as calling 'next', 'previous' or 'setActivePageId' functions. * * @name sap.m.Carousel#pageChanged * @event * @param {sap.ui.base.Event} oControlEvent * @param {sap.ui.base.EventProvider} oControlEvent.getSource * @param {object} oControlEvent.getParameters * @param {string} oControlEvent.getParameters.oldActivePageId Id of the page which was active before the page change. * @param {string} oControlEvent.getParameters.newActivePageId Id of the page which is active after the page change. * @public */ /** * Attach event handler <code>fnFunction</code> to the 'pageChanged' event of this <code>sap.m.Carousel</code>.<br/>. * When called, the context of the event handler (its <code>this</code>) will be bound to <code>oListener<code> if specified * otherwise to this <code>sap.m.Carousel</code>.<br/> itself. * * This event is fired after a carousel swipe has been completed. It is triggered both by physical swipe events and through API carousel manipulations such as calling 'next', 'previous' or 'setActivePageId' functions. * * @param {object} * [oData] An application specific payload object, that will be passed to the event handler along with the event object when firing the event. * @param {function} * fnFunction The function to call, when the event occurs. * @param {object} * [oListener] Context object to call the event handler with. Defaults to this <code>sap.m.Carousel</code>.<br/> itself. * * @return {sap.m.Carousel} <code>this</code> to allow method chaining * @public * @name sap.m.Carousel#attachPageChanged * @function */ /** * Detach event handler <code>fnFunction</code> from the 'pageChanged' event of this <code>sap.m.Carousel</code>.<br/> * * The passed function and listener object must match the ones used for event registration. * * @param {function} * fnFunction The function to call, when the event occurs. * @param {object} * oListener Context object on which the given function had to be called. * @return {sap.m.Carousel} <code>this</code> to allow method chaining * @public * @name sap.m.Carousel#detachPageChanged * @function */ /** * Fire event pageChanged to attached listeners. * * Expects following event parameters: * <ul> * <li>'oldActivePageId' of type <code>string</code> Id of the page which was active before the page change.</li> * <li>'newActivePageId' of type <code>string</code> Id of the page which is active after the page change.</li> * </ul> * * @param {Map} [mArguments] the arguments to pass along with the event. * @return {sap.m.Carousel} <code>this</code> to allow method chaining * @protected * @name sap.m.Carousel#firePageChanged * @function */ /** * Call this method to display the next page (corresponds to a swipe right). Returns 'this' for method chaining. * * @name sap.m.Carousel.prototype.next * @function * @type sap.m.Carousel * @public */ /** * Call this method to display the previous page (corresponds to a swipe left). Returns 'this' for method chaining. * * @name sap.m.Carousel.prototype.previous * @function * @type sap.m.Carousel * @public */ // Start of sap\m\Carousel.js jQuery.sap.require("sap.ui.thirdparty.mobify-carousel"); //Constants convenient class selections sap.m.Carousel._INNER_SELECTOR = ".sapMCrslInner"; sap.m.Carousel._PAGE_INDICATOR_SELECTOR = ".sapMCrslBulleted"; sap.m.Carousel._HUD_SELECTOR = ".sapMCrslHud"; sap.m.Carousel._ITEM_SELECTOR = ".sapMCrslItem"; sap.m.Carousel._LEFTMOST_CLASS = "sapMCrslLeftmost"; sap.m.Carousel._RIGHTMOST_CLASS = "sapMCrslRightmost"; sap.m.Carousel._LATERAL_CLASSES = "sapMCrslLeftmost sapMCrslRightmost"; sap.m.Carousel._bIE9 = (sap.ui.Device.browser.internet_explorer && sap.ui.Device.browser.version < 10); /** * Initialize member variables which are needed later on. * * @private */ sap.m.Carousel.prototype.init = function() { //Scroll container list for clean- up this._aScrollContainers = []; //Initialize '_fnAdjustAfterResize' to be used by window //'resize' event this._fnAdjustAfterResize = jQuery.proxy(function() { var $carouselInner = this.$().find(sap.m.Carousel._INNER_SELECTOR); this._oMobifyCarousel.resize($carouselInner); }, this); }; /** * Called when the control is destroyed. * * @private */ sap.m.Carousel.prototype.exit = function() { if(this._oMobifyCarousel) { this._oMobifyCarousel.destroy(); delete this._oMobifyCarousel; } if(this._oArrowLeft) { this._oArrowLeft.destroy(); delete this._oArrowLeft; } if(this._oArrowRight) { this._oArrowRight.destroy(); delete this._oArrowRight; } if (this._sResizeListenerId) { sap.ui.core.ResizeHandler.deregister(this._sResizeListenerId); this._sResizeListenerId = null; } this.$().off('afterSlide'); this._cleanUpScrollContainer(); this._fnAdjustAfterResize = null; this._aScrollContainers = null; if(!sap.m.Carousel._bIE9 && this._$InnerDiv) { jQuery(window).off("resize", this._fnAdjustAfterResize); } this._$InnerDiv = null; }; /** * Housekeeping for scroll containers: Removes content for each container, * destroys the contianer and clears the local container list. * * @private */ sap.m.Carousel.prototype._cleanUpScrollContainer = function() { var oScrollCont; while (this.length > 0) { oScrollCont = this._aScrollContainers.pop(); oScrollCont.removeAllContent(); if(oScrollCont && typeof oScrollCont.destroy === 'function') { oScrollCont.destroy(); } } }; /** * Delegates 'touchstart' event to mobify carousel * * @param oEvent */ sap.m.Carousel.prototype.ontouchstart = function(oEvent) { if(this._oMobifyCarousel) { this._oMobifyCarousel.touchstart(oEvent); } }; /** * Delegates 'touchmove' event to mobify carousel * * @param oEvent */ sap.m.Carousel.prototype.ontouchmove = function(oEvent) { if(this._oMobifyCarousel) { this._oMobifyCarousel.touchmove(oEvent); } }; /** * Delegates 'touchend' event to mobify carousel * * @param oEvent */ sap.m.Carousel.prototype.ontouchend = function(oEvent) { if(this._oMobifyCarousel) { this._oMobifyCarousel.touchend(oEvent); } }; /** * Cleans up bindings * * @private */ sap.m.Carousel.prototype.onBeforeRendering = function() { //make sure, active page has an initial value var sActivePage = this.getActivePage(); if(!sActivePage && this.getPages().length > 0) { //if no active page is specified, set first page. this.setAssociation("activePage", this.getPages()[0].getId(), true); } if (this._sResizeListenerId) { sap.ui.core.ResizeHandler.deregister(this._sResizeListenerId); this._sResizeListenerId = null; } if(!sap.m.Carousel._bIE9 && this._$InnerDiv) { jQuery(window).off("resize", this._fnAdjustAfterResize); } return this; }; /** * When this method is called for the first time, a swipe-view instance is created which is renders * itself into its dedicated spot within the DOM tree. This instance is used throughout the * Carousel instance's lifecycle. * * @private */ sap.m.Carousel.prototype.onAfterRendering = function() { //Check if carousel has been initialized if(this._oMobifyCarousel) { //Clean up existing mobify carousel this._oMobifyCarousel.destroy(); } //Create and initialize new carousel this.$().carousel(); this._oMobifyCarousel = this.getDomRef()._carousel; this._oMobifyCarousel.setLoop(this.getLoop()); this._oMobifyCarousel.setRTL(sap.ui.getCore().getConfiguration().getRTL()); //Go to active page: this may be necessary after adding or //removing pages var sActivePage = this.getActivePage(); if(sActivePage) { var iIndex = this._getPageNumber(sActivePage); if(isNaN(iIndex) || iIndex == 0) { if(this.getPages().length > 0) { //First page is always shown as default //Do not fire page changed event, though this.setAssociation("activePage", this.getPages()[0].getId(), true); this._adjustHUDVisibility(1); } } else { this._oMobifyCarousel.changeAnimation('sapMCrslNoTransition'); //mobify carousel is 1-based this._oMobifyCarousel.move(iIndex + 1); this._changePage(iIndex + 1); } } //attach delegate for firing 'PageChanged' events to mobify carousel's //'afterSlide' this.$().on('afterSlide', jQuery.proxy(function(e, iPreviousSlide, iNextSlide) { //the event might bubble up from another carousel inside of this one. //in this case we ignore the event if(e.target !== this.getDomRef()) { return; } if(iNextSlide > 0){ this._changePage(iNextSlide); } }, this)); this._$InnerDiv = this.$().find(sap.m.Carousel._INNER_SELECTOR)[0]; if(sap.m.Carousel._bIE9) { this._sResizeListenerId = sap.ui.core.ResizeHandler.register(this._$InnerDiv, this._fnAdjustAfterResize); } else { jQuery(window).on("resize", this._fnAdjustAfterResize); } }; /** * Private method which adjusts the Hud visibility and fires a page change * event when the active page changes * * @param iNewPageIndex index of new page in 'pages' aggregation. * @private */ sap.m.Carousel.prototype._changePage = function(iNewPageIndex) { this._adjustHUDVisibility(iNewPageIndex); var sOldActivePageId = this.getActivePage(); var sNewActivePageId = this.getPages()[iNewPageIndex - 1].getId(); this.setAssociation("activePage", sNewActivePageId, true); jQuery.sap.log.debug("sap.m.Carousel: firing pageChanged event: old page: " + sOldActivePageId + ", new page: " + sNewActivePageId); this.firePageChanged( { oldActivePageId: sOldActivePageId, newActivePageId: sNewActivePageId}); }; /** * Sets HUD control's visibility after page has changed * * @param iNextSlide index of the next active page * @private * */ sap.m.Carousel.prototype._adjustHUDVisibility = function(iNextSlide) { if (sap.ui.Device.system.desktop && !this.getLoop() && this.getPages().length > 1) { //update HUD arrow visibility for left- and //rightmost pages var $HUDContainer = this.$().find(sap.m.Carousel._HUD_SELECTOR); //clear marker classes first $HUDContainer.removeClass(sap.m.Carousel._LATERAL_CLASSES); if(iNextSlide === 1) { $HUDContainer.addClass(sap.m.Carousel._LEFTMOST_CLASS); } else if (iNextSlide === this.getPages().length) { $HUDContainer.addClass(sap.m.Carousel._RIGHTMOST_CLASS); } } }; /** * Handler for 'tab previous' key event. Delegates handling to * '_tabKeyPressed' function. * * @param oEvent key event * @private * */ sap.m.Carousel.prototype.onsaptabprevious = function(oEvent) { this._bTabPrevious = true; }; /** * Handler for 'tab next' key event. Delegates handling to * '_tabKeyPressed' function. * * @param oEvent key event * @private * */ sap.m.Carousel.prototype.onsaptabnext = function(oEvent) { this._bTabNext = true; }; /** * Event handler for the focusin event. * If the focused element is the dedicated element (class sapMCrslFirstFE) at the beginning of a page, * the focus is set to the end of the previous page. If the dedicated element the end of a page * (class sapMCrslLastFE) is focussed, the first element of the next page is focused * @param {jQuery.EventObject} oEvent The event object * @private */ sap.m.Carousel.prototype.onfocusin = function(oEvent){ if (sap.ui.Device.system.desktop) { var oSourceDomRef = oEvent.target, iPageIndex = oSourceDomRef.getAttribute('pageIndex'), oNextFocusDomRef, oNextPage; //Invisible Element focused by tab previous if(oSourceDomRef.className === 'sapMCrslFirstFE' && this._bTabPrevious) { if(iPageIndex > 0) { iPageIndex--; } else if(this.getLoop()) { iPageIndex = this.getPages().length - 1; } oNextPage = this.getPages()[iPageIndex]; oNextFocusDomRef = oNextPage.$().parent().lastFocusableDomRef(); } else if(oSourceDomRef.className === 'sapMCrslLastFE' && this._bTabNext) { //Invisible Element focused by tab next if(iPageIndex < this.getPages().length - 1) { iPageIndex++; } else if(this.getLoop()) { iPageIndex = 0; } oNextPage = this.getPages()[iPageIndex]; oNextFocusDomRef = oNextPage.$().parent().firstFocusableDomRef(); } if(oNextFocusDomRef && oNextPage) { var fnRequestFocus = function() { oNextFocusDomRef.focus(); }; this._oMobifyCarousel.changeAnimation('', fnRequestFocus, this); this.setActivePage(oNextPage.getId()); } this._bTabPrevious = false; this._bTabNext = false; } }; /** * API method to set carousel's active page during runtime. * * @param vPage Id of the page or page which shall become active * @override * */ sap.m.Carousel.prototype.setActivePage = function (vPage) { var sPageId = null, bPageFound = false; if(typeof(vPage) == 'string') { sPageId = vPage; } else if (vPage instanceof sap.ui.core.Control) { sPageId = vPage.getId(); } if(sPageId) { if(sPageId === this.getActivePage()) { //page has not changed, nothing to do, return return this; } var iPageNr = this._getPageNumber(sPageId); if(!isNaN(iPageNr)) { if(this._oMobifyCarousel) { //mobify carousel's move function is '1' based this._oMobifyCarousel.move(iPageNr + 1); } // if oMobifyCarousel is not present yet, move takes place // 'onAfterRendering', when oMobifyCarousel is created } } this.setAssociation("activePage", sPageId, true); return this; }; /** * API method to set the carousel's height * * @param oHeight the new height as CSSSize * @public * @override */ sap.m.Carousel.prototype.setHeight = function(oHeight) { //do suppress rerendering this.setProperty("height", oHeight, true); this.$().css("height", oHeight); return this; }; /** * API method to set the carousel's width * * @param oWidth the new width as CSSSize * @public * @override */ sap.m.Carousel.prototype.setWidth = function(oWidth) { //do suppress rerendering this.setProperty("width", oWidth, true); this.$().css("width", oWidth); return this; }; /** * API method to place the page inidicator. * * @param sPlacement either sap.m.PlacementType.Top or sap.m.PlacementType.Bottom * @public * @override */ sap.m.Carousel.prototype.setPageIndicatorPlacement = function(sPlacement) { if(sap.m.PlacementType.Top != sPlacement && sap.m.PlacementType.Bottom != sPlacement) { jQuery.sap.assert(false, "sap.m.Carousel.prototype.setPageIndicatorPlacement: invalid value '" + sPlacement + "'. Valid values: sap.m.PlacementType.Top, sap.m.PlacementType.Bottom." + "\nUsing default value sap.m.PlacementType.Bottom"); sPlacement = sap.m.PlacementType.Bottom; } //do suppress rerendering this.setProperty("pageIndicatorPlacement", sPlacement, true); var $PageIndicator = this.$().find(sap.m.Carousel._PAGE_INDICATOR_SELECTOR); //set placement regardless of whether indicator is visible: it may become //visible later on and then it should be at the right place if(sap.m.PlacementType.Top === sPlacement) { this.$().prepend($PageIndicator); $PageIndicator.removeClass('sapMCrslBottomOffset'); this.$().find(sap.m.Carousel._ITEM_SELECTOR).removeClass('sapMCrslBottomOffset'); } else { this.$().append($PageIndicator); $PageIndicator.addClass('sapMCrslBottomOffset'); this.$().find(sap.m.Carousel._ITEM_SELECTOR).addClass('sapMCrslBottomOffset'); } return this; }; /** * API method to set whether the carousel should display the page indicator * * @param bShowPageIndicator the new show property * @public * @override */ sap.m.Carousel.prototype.setShowPageIndicator = function(bShowPageIndicator) { var $PageInd = this.$().find(sap.m.Carousel._PAGE_INDICATOR_SELECTOR); bShowPageIndicator ? $PageInd.show() : $PageInd.hide(); //do suppress rerendering this.setProperty("showPageIndicator", bShowPageIndicator, true); return this; }; /** * API method to set whether the carousel should loop, i.e * show the first page after the last page is reached and vice * versa. * * @param bLoop the new loop property * @public * @override */ sap.m.Carousel.prototype.setLoop = function(bLoop) { //do suppress rerendering this.setProperty("loop", bLoop, true); if(this._oMobifyCarousel) { this._oMobifyCarousel.setLoop(bLoop); } return this; }; /** * Gets the icon of the requested arrow (left/right). * @private * @param sName left or right * @returns icon of the requested arrow */ sap.m.Carousel.prototype._getNavigationArrow = function(sName) { jQuery.sap.require("sap.ui.core.IconPool"); var mProperties = { src : "sap-icon://navigation-" + sName + "-arrow" }; if (sName === "left") { if (!this._oArrowLeft) { this._oArrowLeft = sap.m.ImageHelper.getImageControl(this.getId() + "-arrowScrollLeft", this._oArrowLeft, this, mProperties); } return this._oArrowLeft; } else if (sName === "right") { if (!this._oArrowRight) { this._oArrowRight = sap.m.ImageHelper.getImageControl(this.getId() + "-arrowScrollRight", this._oArrowRight, this, mProperties); } return this._oArrowRight; } }; /** * Private method that places a given page control into * a scroll container which does not scroll. That container does * not scroll itself. This is necessary to achieve the 100% height * effect with an offset for the page indicator. * * @param oPage the page to check * @private */ sap.m.Carousel.prototype._createScrollContainer = function(oPage) { var cellClasses = oPage instanceof sap.m.Image ? "sapMCrslItemTableCell sapMCrslImg" : "sapMCrslItemTableCell", oContent = new sap.ui.core.HTML({ content : "<div class='sapMCrslItemTable'>" + "<div class='" + cellClasses + "'></div>" + "</div>", afterRendering : function(e) { var rm = sap.ui.getCore().createRenderManager(); rm.render(oPage, this.getDomRef().firstChild); rm.destroy(); } }); var oScrollContainer = new sap.m.ScrollContainer({ horizontal: false, vertical: false, content:[oContent], width:'100%', height:'100%', }); oScrollContainer.setParent(this, null, true); this._aScrollContainers.push(oScrollContainer); return oScrollContainer; }; /** * API method to show the next page in the page list. * @public */ sap.m.Carousel.prototype.previous = function () { if(this._oMobifyCarousel) { this._oMobifyCarousel.prev(); } else { jQuery.sap.log.warning("Unable to execute sap.m.Carousel.previous: carousel must be rendered first."); } return this; }; /** * API method to show the previous page in the page list. * @public */ sap.m.Carousel.prototype.next = function () { if(this._oMobifyCarousel) { this._oMobifyCarousel.next(); } else { jQuery.sap.log.warning("Unable to execute sap.m.Carousel.next: carousel must be rendered first."); } return this; }; /** * Determines the position of a given page in the carousel's page list * * @return the position of a given page in the carousel's page list or 'undefined' if it does not exist in the list. * @private */ sap.m.Carousel.prototype._getPageNumber = function(sPageId) { var i, result; for(i=0; i<this.getPages().length; i++) { if(this.getPages()[i].getId() == sPageId) { result = i; break; } } return result; }; //DEPRECATED METHODS /** * API method to set whether the carousel should display the busy indicators. * This property has been deprecated since 1.18.7. Does nothing and returns the carousel reference. * * @deprecated * @public */ sap.m.Carousel.prototype.setShowBusyIndicator = function() { jQuery.sap.log.warning("sap.m.Carousel: Deprecated function 'setShowBusyIndicator' called. " + "Does nothing."); return this; }; /** * API method to check whether the carousel should display the busy indicators. * This property has been deprecated since 1.18.7. Always returns false, * * @deprecated * @public */ sap.m.Carousel.prototype.getShowBusyIndicator = function() { jQuery.sap.log.warning("sap.m.Carousel: Deprecated function 'getShowBusyIndicator' called. " + "Does nothing."); return false; }; /** * API method to set the carousel's busy indicator size. * This property has been deprecated since 1.18.7. Does nothing and returns the carousel reference. * * @deprecated * @public */ sap.m.Carousel.prototype.setBusyIndicatorSize = function() { jQuery.sap.log.warning("sap.m.Carousel: Deprecated function 'setBusyIndicatorSize' called. " + "Does nothing."); return this; }; /** * API method to retrieve the carousel's busy indicator size. * This property has been deprecated since 1.18.6. Always returns an empty string. * * @deprecated * @public */ sap.m.Carousel.prototype.getBusyIndicatorSize = function() { jQuery.sap.log.warning("sap.m.Carousel: Deprecated function 'getBusyIndicatorSize' called. " + "Does nothing."); return ""; };
apache-2.0
anguslees/kubecfg-1
utils/meta.go
2521
package utils import ( "fmt" "strconv" "strings" log "github.com/sirupsen/logrus" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/version" "k8s.io/client-go/discovery" ) // ServerVersion captures k8s major.minor version in a parsed form type ServerVersion struct { Major int Minor int } // ParseVersion parses version.Info into a ServerVersion struct func ParseVersion(v *version.Info) (ret ServerVersion, err error) { ret.Major, err = strconv.Atoi(v.Major) if err != nil { return } // trim "+" in minor version (happened on GKE) v.Minor = strings.TrimSuffix(v.Minor, "+") ret.Minor, err = strconv.Atoi(v.Minor) if err != nil { return } return } // FetchVersion fetches version information from discovery client, and parses func FetchVersion(v discovery.ServerVersionInterface) (ret ServerVersion, err error) { version, err := v.ServerVersion() if err != nil { return ServerVersion{}, err } return ParseVersion(version) } // Compare returns -1/0/+1 iff v is less than / equal / greater than major.minor func (v ServerVersion) Compare(major, minor int) int { a := v.Major b := major if a == b { a = v.Minor b = minor } var res int if a > b { res = 1 } else if a == b { res = 0 } else { res = -1 } return res } func (v ServerVersion) String() string { return fmt.Sprintf("%d.%d", v.Major, v.Minor) } // SetMetaDataAnnotation sets an annotation value func SetMetaDataAnnotation(obj metav1.Object, key, value string) { a := obj.GetAnnotations() if a == nil { a = make(map[string]string) } a[key] = value obj.SetAnnotations(a) } // ResourceNameFor returns a lowercase plural form of a type, for // human messages. Returns lowercased kind if discovery lookup fails. func ResourceNameFor(disco discovery.ServerResourcesInterface, o runtime.Object) string { gvk := o.GetObjectKind().GroupVersionKind() rls, err := disco.ServerResourcesForGroupVersion(gvk.GroupVersion().String()) if err != nil { log.Debugf("Discovery failed for %s: %s, falling back to kind", gvk, err) return strings.ToLower(gvk.Kind) } for _, rl := range rls.APIResources { if rl.Kind == gvk.Kind { return rl.Name } } log.Debugf("Discovery failed to find %s, falling back to kind", gvk) return strings.ToLower(gvk.Kind) } // FqName returns "namespace.name" func FqName(o metav1.Object) string { if o.GetNamespace() == "" { return o.GetName() } return fmt.Sprintf("%s.%s", o.GetNamespace(), o.GetName()) }
apache-2.0
auxilium/JelloScrum
JelloScrum/JelloScrum.Repositories/Exceptions/JelloScrumRepositoryException.cs
1838
// Copyright 2009 Auxilium B.V. - http://www.auxilium.nl/ // // 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 JelloScrum.Repositories.Exceptions { using System; using System.Runtime.Serialization; using System.Text; using JelloScrum.Model.Services; public class JelloScrumRepositoryException : Exception { public JelloScrumRepositoryException(SerializationInfo info, StreamingContext context) : base(info, context) { } public JelloScrumRepositoryException(string message, Exception innerException) : base(message, innerException) { } public JelloScrumRepositoryException(string message) : base(message) { } public JelloScrumRepositoryException() { } public string LogMessage { get { StringBuilder sb = new StringBuilder(); sb.AppendLine(string.Format("{0} threw an exception", Source)); sb.AppendLine(Message); Exception inner = InnerException; while (inner != null) { sb.AppendLine(inner.Message); inner = inner.InnerException; } return sb.ToString(); } } } }
apache-2.0
lipprints/jjjx
JJJX/app/src/main/java/com/jjjx/function/entity/eventbus/LoginRefreshBus.java
431
package com.jjjx.function.entity.eventbus; /** * * @author xz * @date 2017/11/2 0002 * 用来刷新已登陆的界面 */ public class LoginRefreshBus { private boolean isRefresh; public LoginRefreshBus(boolean isRefresh) { this.isRefresh = isRefresh; } public boolean isRefresh() { return isRefresh; } public void setRefresh(boolean refresh) { isRefresh = refresh; } }
apache-2.0
knative-sandbox/eventing-kafka
pkg/channel/distributed/controller/util/compare_test.go
11810
/* Copyright 2021 The Knative 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 util import ( "math" "testing" "github.com/stretchr/testify/assert" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" logtesting "knative.dev/pkg/logging/testing" "knative.dev/eventing-kafka/pkg/channel/distributed/controller/constants" ) type deploymentOption func(service *appsv1.Deployment) type serviceOption func(*corev1.Service) // Tests the CheckDeploymentChanged functionality. Note that this is also tested fairly extensively // as part of the various reconciler tests, and as such the deployment structs used here are somewhat trivial. func TestCheckDeploymentChanged(t *testing.T) { logger := logtesting.TestLogger(t).Desugar() tests := []struct { name string existingDeployment *appsv1.Deployment newDeployment *appsv1.Deployment expectUpdated bool }{ { name: "Different Image", existingDeployment: getBasicDeployment(), newDeployment: getBasicDeployment(withDifferentImage), expectUpdated: true, }, { name: "Missing Required Deployment Label", existingDeployment: getBasicDeployment(), newDeployment: getBasicDeployment(withDeploymentLabel), expectUpdated: true, }, { name: "Missing Required Template Label", existingDeployment: getBasicDeployment(), newDeployment: getBasicDeployment(withTemplateLabel), expectUpdated: true, }, { name: "Missing Required Deployment Annotation", existingDeployment: getBasicDeployment(), newDeployment: getBasicDeployment(withDeploymentAnnotation), expectUpdated: true, }, { name: "Missing Required Template Annotation", existingDeployment: getBasicDeployment(), newDeployment: getBasicDeployment(withTemplateAnnotation), expectUpdated: true, }, { name: "Missing Existing Container", existingDeployment: getBasicDeployment(withoutContainer), newDeployment: getBasicDeployment(), expectUpdated: true, }, { name: "Extra Existing Deployment Label", existingDeployment: getBasicDeployment(withDeploymentLabel), newDeployment: getBasicDeployment(), }, { name: "Extra Existing Template Label", existingDeployment: getBasicDeployment(withTemplateLabel), newDeployment: getBasicDeployment(), }, { name: "Extra Existing Deployment Annotation", existingDeployment: getBasicDeployment(withDeploymentAnnotation), newDeployment: getBasicDeployment(), }, { name: "Extra Existing Template Annotation", existingDeployment: getBasicDeployment(withTemplateAnnotation), newDeployment: getBasicDeployment(), }, { name: "Missing New Container", existingDeployment: getBasicDeployment(), newDeployment: getBasicDeployment(withoutContainer), }, { name: "Multiple Existing Containers", existingDeployment: getBasicDeployment(withExtraContainer), newDeployment: getBasicDeployment(), }, { name: "Multiple Existing Containers, Incorrect First", existingDeployment: getBasicDeployment(withExtraContainerFirst), newDeployment: getBasicDeployment(), }, { name: "Multiple Existing Containers, Missing Required Deployment Annotation", existingDeployment: getBasicDeployment(withExtraContainer), newDeployment: getBasicDeployment(withDeploymentAnnotation), expectUpdated: true, }, { name: "Multiple Existing Containers, Missing Required Template Annotation", existingDeployment: getBasicDeployment(withExtraContainer), newDeployment: getBasicDeployment(withTemplateAnnotation), expectUpdated: true, }, { name: "Multiple Existing Containers, Incorrect First, Missing Required Deployment Annotation", existingDeployment: getBasicDeployment(withExtraContainerFirst), newDeployment: getBasicDeployment(withDeploymentAnnotation), expectUpdated: true, }, { name: "Multiple Existing Containers, Incorrect First, Missing Required Template Annotation", existingDeployment: getBasicDeployment(withExtraContainerFirst), newDeployment: getBasicDeployment(withTemplateAnnotation), expectUpdated: true, }, { name: "Container With Incorrect Name", existingDeployment: getBasicDeployment(withDifferentContainer), newDeployment: getBasicDeployment(), expectUpdated: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { newDeployment := tt.newDeployment if newDeployment == nil { newDeployment = getBasicDeployment() } updatedDeployment, isUpdated := CheckDeploymentChanged(logger, tt.existingDeployment, newDeployment) assert.NotNil(t, updatedDeployment) assert.Equal(t, tt.expectUpdated, isUpdated) }) } } // Tests the CheckServiceChanged functionality. Note that this is also tested fairly extensively // as part of the various reconciler tests, and as such the service structs used here are somewhat trivial. func TestCheckServiceChanged(t *testing.T) { logger := logtesting.TestLogger(t).Desugar() tests := []struct { name string existingService *corev1.Service newService *corev1.Service expectPatch bool expectUpdated bool }{ { name: "Different Cluster IP", existingService: getBasicService(), newService: getBasicService(withDifferentClusterIP), }, { name: "Missing Required Label", existingService: getBasicService(), newService: getBasicService(withServiceLabel), expectUpdated: true, expectPatch: true, }, { name: "Missing Required Annotation", existingService: getBasicService(), newService: getBasicService(withServiceAnnotation), expectUpdated: true, expectPatch: true, }, { name: "Missing Ports", existingService: getBasicService(withoutPorts), newService: getBasicService(), expectUpdated: true, expectPatch: true, }, { name: "Extra Existing Label", existingService: getBasicService(withServiceLabel), newService: getBasicService(), }, { name: "Extra Existing Annotation", existingService: getBasicService(withServiceAnnotation), newService: getBasicService(), }, { name: "Empty Services", existingService: &corev1.Service{}, newService: &corev1.Service{}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { newService := tt.newService if newService == nil { newService = getBasicService() } patch, isUpdated := CheckServiceChanged(logger, tt.existingService, newService) assert.Equal(t, tt.expectPatch, patch != nil) assert.Equal(t, tt.expectUpdated, isUpdated) }) } } func TestCreateJsonPatch(t *testing.T) { logger := logtesting.TestLogger(t).Desugar() tests := []struct { name string before interface{} after interface{} expectPatch bool expectOk bool }{ { name: "Invalid Content", before: math.Inf(1), after: math.Inf(1), }, { name: "No Difference", before: getBasicService(), after: getBasicService(), }, { name: "Missing Ports", before: getBasicService(withoutPorts), after: getBasicService(), expectPatch: true, expectOk: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { patch, ok := createJsonPatch(logger, tt.before, tt.after) assert.Equal(t, tt.expectPatch, patch != nil) assert.Equal(t, tt.expectOk, ok) }) } } func getBasicDeployment(options ...deploymentOption) *appsv1.Deployment { deployment := &appsv1.Deployment{ TypeMeta: metav1.TypeMeta{ APIVersion: appsv1.SchemeGroupVersion.String(), Kind: constants.DeploymentKind, }, ObjectMeta: metav1.ObjectMeta{ Name: "TestDeployment", Namespace: "TestNamespace", Labels: make(map[string]string), Annotations: make(map[string]string), }, Spec: appsv1.DeploymentSpec{ Template: corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: make(map[string]string), Annotations: make(map[string]string), }, Spec: corev1.PodSpec{ Containers: []corev1.Container{ {Name: "TestContainerName"}, }, }, }, }, } // Apply any desired customizations for _, option := range options { option(deployment) } return deployment } func withDeploymentLabel(deployment *appsv1.Deployment) { deployment.ObjectMeta.Labels["TestDeploymentLabelName"] = "TestDeploymentLabelValue" } func withTemplateLabel(deployment *appsv1.Deployment) { deployment.Spec.Template.ObjectMeta.Labels["TestTemplateLabelName"] = "TestTemplateLabelValue" } func withDeploymentAnnotation(deployment *appsv1.Deployment) { deployment.ObjectMeta.Annotations["TestDeploymentAnnotationName"] = "TestDeploymentAnnotationValue" } func withTemplateAnnotation(deployment *appsv1.Deployment) { deployment.Spec.Template.ObjectMeta.Annotations["TestTemplateAnnotationName"] = "TestTemplateAnnotationValue" } func withoutContainer(deployment *appsv1.Deployment) { deployment.Spec.Template.Spec.Containers = []corev1.Container{} } func withExtraContainer(deployment *appsv1.Deployment) { deployment.Spec.Template.Spec.Containers = append( deployment.Spec.Template.Spec.Containers, corev1.Container{ Name: "TestExtraContainerName", }) } func withExtraContainerFirst(deployment *appsv1.Deployment) { deployment.Spec.Template.Spec.Containers = append([]corev1.Container{{ Name: "TestExtraContainerName", }}, deployment.Spec.Template.Spec.Containers...) } func withDifferentContainer(deployment *appsv1.Deployment) { deployment.Spec.Template.Spec.Containers[0].Name = "TestDifferentContainerName" } func withDifferentImage(deployment *appsv1.Deployment) { deployment.Spec.Template.Spec.Containers[0].Image = "TestNewImage" } func getBasicService(options ...serviceOption) *corev1.Service { service := &corev1.Service{ TypeMeta: metav1.TypeMeta{ APIVersion: corev1.SchemeGroupVersion.String(), Kind: constants.ServiceKind, }, ObjectMeta: metav1.ObjectMeta{ Name: "TestService", Namespace: "TestNamespace", Labels: make(map[string]string), Annotations: make(map[string]string), }, Spec: corev1.ServiceSpec{ Ports: []corev1.ServicePort{{ Name: "TestServicePort", }}, }, } // Apply any desired customizations for _, option := range options { option(service) } return service } func withServiceLabel(service *corev1.Service) { service.ObjectMeta.Labels["TestServiceLabelName"] = "TestServiceLabelValue" } func withServiceAnnotation(service *corev1.Service) { service.ObjectMeta.Annotations["TestServiceAnnotationName"] = "TestServiceAnnotationValue" } func withDifferentClusterIP(service *corev1.Service) { service.Spec.ClusterIP = "DifferentClusterIP" } func withoutPorts(service *corev1.Service) { service.Spec.Ports = nil }
apache-2.0
googleapis/google-api-java-client-services
clients/google-api-services-dialogflow/v2/1.31.0/com/google/api/services/dialogflow/v2/model/GoogleCloudDialogflowV2ListAnswerRecordsResponse.java
4005
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.dialogflow.v2.model; /** * Response message for AnswerRecords.ListAnswerRecords. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Dialogflow API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GoogleCloudDialogflowV2ListAnswerRecordsResponse extends com.google.api.client.json.GenericJson { /** * The list of answer records. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<GoogleCloudDialogflowV2AnswerRecord> answerRecords; static { // hack to force ProGuard to consider GoogleCloudDialogflowV2AnswerRecord used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(GoogleCloudDialogflowV2AnswerRecord.class); } /** * A token to retrieve next page of results. Or empty if there are no more results. Pass this * value in the ListAnswerRecordsRequest.page_token field in the subsequent call to * `ListAnswerRecords` method to retrieve the next page of results. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String nextPageToken; /** * The list of answer records. * @return value or {@code null} for none */ public java.util.List<GoogleCloudDialogflowV2AnswerRecord> getAnswerRecords() { return answerRecords; } /** * The list of answer records. * @param answerRecords answerRecords or {@code null} for none */ public GoogleCloudDialogflowV2ListAnswerRecordsResponse setAnswerRecords(java.util.List<GoogleCloudDialogflowV2AnswerRecord> answerRecords) { this.answerRecords = answerRecords; return this; } /** * A token to retrieve next page of results. Or empty if there are no more results. Pass this * value in the ListAnswerRecordsRequest.page_token field in the subsequent call to * `ListAnswerRecords` method to retrieve the next page of results. * @return value or {@code null} for none */ public java.lang.String getNextPageToken() { return nextPageToken; } /** * A token to retrieve next page of results. Or empty if there are no more results. Pass this * value in the ListAnswerRecordsRequest.page_token field in the subsequent call to * `ListAnswerRecords` method to retrieve the next page of results. * @param nextPageToken nextPageToken or {@code null} for none */ public GoogleCloudDialogflowV2ListAnswerRecordsResponse setNextPageToken(java.lang.String nextPageToken) { this.nextPageToken = nextPageToken; return this; } @Override public GoogleCloudDialogflowV2ListAnswerRecordsResponse set(String fieldName, Object value) { return (GoogleCloudDialogflowV2ListAnswerRecordsResponse) super.set(fieldName, value); } @Override public GoogleCloudDialogflowV2ListAnswerRecordsResponse clone() { return (GoogleCloudDialogflowV2ListAnswerRecordsResponse) super.clone(); } }
apache-2.0
fdecampredon/jsx-typescript-old-version
tests/baselines/reference/inheritanceStaticFuncOverridingAccessor.js
765
//// [inheritanceStaticFuncOverridingAccessor.js] var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var a = (function () { function a() { } Object.defineProperty(a, "x", { get: function () { return "20"; }, set: function (aValue) { }, enumerable: true, configurable: true }); return a; })(); var b = (function (_super) { __extends(b, _super); function b() { _super.apply(this, arguments); } b.x = function () { return "20"; }; return b; })(a);
apache-2.0
saicheems/discovery-artifact-manager
toolkit/src/main/java/com/google/api/codegen/viewmodel/metadata/VersionIndexView.java
2237
/* Copyright 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.google.api.codegen.viewmodel.metadata; import com.google.api.codegen.SnippetSetRunner; import com.google.api.codegen.viewmodel.FileHeaderView; import com.google.api.codegen.viewmodel.ViewModel; import com.google.auto.value.AutoValue; import java.util.List; import javax.annotation.Nullable; @AutoValue public abstract class VersionIndexView implements ViewModel { @Override public String resourceRoot() { return SnippetSetRunner.SNIPPET_RESOURCE_ROOT; } @Override public abstract String templateFileName(); @Override public abstract String outputPath(); @Nullable public abstract VersionIndexRequireView primaryService(); public abstract String apiVersion(); public abstract String packageVersion(); public abstract List<VersionIndexRequireView> requireViews(); public abstract FileHeaderView fileHeader(); public boolean hasMultipleServices() { return requireViews().size() > 1; } public static Builder newBuilder() { // Use v1 as the default version. return new AutoValue_VersionIndexView.Builder().apiVersion("v1"); } @AutoValue.Builder public abstract static class Builder { public abstract Builder outputPath(String val); public abstract Builder templateFileName(String val); public abstract Builder primaryService(VersionIndexRequireView val); public abstract Builder apiVersion(String val); public abstract Builder packageVersion(String val); public abstract Builder requireViews(List<VersionIndexRequireView> val); public abstract Builder fileHeader(FileHeaderView val); public abstract VersionIndexView build(); } }
apache-2.0
fingeronthebutton/RIDE
src/robotide/namespace/namespace.py
21419
# Copyright 2008-2015 Nokia Solutions and Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys import re import operator import tempfile from itertools import chain from robotide import robotapi, utils from robotide.publish import PUBLISHER, RideSettingsChanged, RideLogMessage from robotide.robotapi import VariableFileSetter from robotide.spec.iteminfo import TestCaseUserKeywordInfo,\ ResourceUserKeywordInfo, VariableInfo, _UserKeywordInfo, ArgumentInfo from .cache import LibraryCache, ExpiringCache from .resourcefactory import ResourceFactory from .embeddedargs import EmbeddedArgsHandler class Namespace(object): def __init__(self, settings): self._settings = settings self._library_manager = None self._content_assist_hooks = [] self._update_listeners = set() self._init_caches() self._set_pythonpath() PUBLISHER.subscribe(self._setting_changed, RideSettingsChanged) def _init_caches(self): self._lib_cache = LibraryCache( self._settings, self.update, self._library_manager) self._resource_factory = ResourceFactory(self._settings) self._retriever = DatafileRetriever(self._lib_cache, self._resource_factory) self._context_factory = _RetrieverContextFactory() def _set_pythonpath(self): """Add user configured paths to PYTHONAPATH. """ for path in self._settings.get('pythonpath', []): if path not in sys.path: normalized = path.replace('/', os.sep) sys.path.insert(0, normalized) RideLogMessage(u'Inserted \'{0}\' to sys.path.' .format(normalized)).publish() def _setting_changed(self, message): section, setting = message.keys if section == '' and setting == 'pythonpath': for p in set(message.old).difference(message.new): if p in sys.path: sys.path.remove(p) self._set_pythonpath() def set_library_manager(self, library_manager): self._library_manager = library_manager self._lib_cache.set_library_manager(library_manager) def update(self, *args): self._retriever.expire_cache() self._context_factory = _RetrieverContextFactory() for listener in self._update_listeners: listener() def resource_filename_changed(self, old_name, new_name): self._resource_factory.resource_filename_changed(old_name, new_name) def reset_resource_and_library_cache(self): self._init_caches() def register_update_listener(self, listener): self._update_listeners.add(listener) def unregister_update_listener(self, listener): if listener in self._update_listeners: self._update_listeners.remove(listener) def clear_update_listeners(self): self._update_listeners.clear() def register_content_assist_hook(self, hook): self._content_assist_hooks.append(hook) def get_all_keywords(self, testsuites): kws = set() kws.update(self._get_default_keywords()) kws.update(self._retriever.get_keywords_from_several(testsuites)) return list(kws) def _get_default_keywords(self): return self._lib_cache.get_default_keywords() def get_suggestions_for(self, controller, start): datafile = controller.datafile ctx = self._context_factory.ctx_for_controller(controller) sugs = set() sugs.update(self._get_suggestions_from_hooks(datafile, start)) if self._blank(start) or not self._looks_like_variable(start): sugs.update(self._variable_suggestions(controller, start, ctx)) sugs.update(self._keyword_suggestions(datafile, start, ctx)) else: sugs.update(self._variable_suggestions(controller, start, ctx)) sugs_list = list(sugs) sugs_list.sort() return sugs_list def _get_suggestions_from_hooks(self, datafile, start): sugs = [] for hook in self._content_assist_hooks: sugs.extend(hook(datafile, start)) return sugs def get_all_cached_library_names(self): return self._retriever.get_all_cached_library_names() def _blank(self, start): return start == '' def _looks_like_variable(self, start): return len(start) == 1 and start[0] in ['$', '@', '&'] \ or (len(start) >= 2 and start[:2] in ['${', '@{', '&{']) def _variable_suggestions(self, controller, start, ctx): self._add_kw_arg_vars(controller, ctx.vars) variables = self._retriever.get_variables_from( controller.datafile, ctx) sugs = (v for v in variables if v.name_matches(start)) return sugs def _add_kw_arg_vars(self, controller, variables): for name, value in controller.get_local_variables().iteritems(): variables.set_argument(name, value) def _keyword_suggestions(self, datafile, start, ctx): start_normalized = utils.normalize(start) all_kws = chain(self._get_default_keywords(), self._retriever.get_keywords_from(datafile, ctx)) return (sug for sug in all_kws if sug.name_begins_with(start_normalized) or sug.longname_begins_with(start_normalized)) def get_resources(self, datafile): return self._retriever.get_resources_from(datafile) def get_resource(self, path, directory='', report_status=True): return self._resource_factory.get_resource( directory, path, report_status=report_status) def find_resource_with_import(self, imp): ctx = self._context_factory.ctx_for_datafile(imp.parent.parent) return self._resource_factory.get_resource_from_import(imp, ctx) def new_resource(self, path, directory=''): return self._resource_factory.new_resource(directory, path) def find_user_keyword(self, datafile, kw_name): kw = self.find_keyword(datafile, kw_name) return kw if isinstance(kw, _UserKeywordInfo) else None def is_user_keyword(self, datafile, kw_name): return bool(self.find_user_keyword(datafile, kw_name)) def find_library_keyword(self, datafile, kw_name): kw = self.find_keyword(datafile, kw_name) return kw if kw and kw.is_library_keyword() else None def is_library_import_ok(self, datafile, imp): return self._retriever.is_library_import_ok( datafile, imp, self._context_factory.ctx_for_datafile(datafile)) def is_variables_import_ok(self, datafile, imp): return self._retriever.is_variables_import_ok( datafile, imp, self._context_factory.ctx_for_datafile(datafile)) def find_keyword(self, datafile, kw_name): if not kw_name: return None kwds = self._retriever.get_keywords_cached(datafile, self._context_factory) return kwds.get(kw_name) def is_library_keyword(self, datafile, kw_name): return bool(self.find_library_keyword(datafile, kw_name)) def keyword_details(self, datafile, name): kw = self.find_keyword(datafile, name) return kw.details if kw else None class _RetrieverContextFactory(object): def __init__(self): self._context_cache = {} def ctx_for_controller(self, controller): if controller not in self._context_cache: self._context_cache[controller] = RetrieverContext() self._context_cache[controller.datafile ] = self._context_cache[controller] return self._context_cache[controller] def ctx_for_datafile(self, datafile): if datafile not in self._context_cache: ctx = RetrieverContext() ctx.set_variables_from_datafile_variable_table(datafile) self._context_cache[datafile] = ctx return self._context_cache[datafile] class RetrieverContext(object): def __init__(self): self.vars = _VariableStash() self.parsed = set() def set_variables_from_datafile_variable_table(self, datafile): self.vars.set_from_variable_table(datafile.variable_table) def replace_variables(self, text): return self.vars.replace_variables(text) def allow_going_through_resources_again(self): """Resets the parsed resources cache. Normally all resources that have been handled are added to 'parsed' and then not handled again, to prevent looping forever. If this same context is used for going through the resources again, this method should be called first. """ self.parsed = set() class _VariableStash(object): # Global variables copied from robot.variables.__init__.py global_variables = { '${TEMPDIR}': os.path.normpath(tempfile.gettempdir()), '${EXECDIR}': os.path.abspath('.'), '${/}': os.sep, '${:}': os.pathsep, '${SPACE}': ' ', '${EMPTY}': '', '${True}': True, '${False}': False, '${None}': None, '${null}': None, '${OUTPUT_DIR}': '', '${OUTPUT_FILE}': '', '${SUMMARY_FILE}': '', '${REPORT_FILE}': '', '${LOG_FILE}': '', '${DEBUG_FILE}': '', '${PREV_TEST_NAME}': '', '${PREV_TEST_STATUS}': '', '${PREV_TEST_MESSAGE}': '', '${CURDIR}': '.', '${TEST_NAME}': '', '@{TEST_TAGS}': [], '${TEST_STATUS}': '', '${TEST_MESSAGE}': '', '${SUITE_NAME}': '', '${SUITE_SOURCE}': '', '${SUITE_STATUS}': '', '${SUITE_MESSAGE}': '' } ARGUMENT_SOURCE = object() def __init__(self): self._vars = robotapi.RobotVariables() self._sources = {} for k, v in self.global_variables.iteritems(): self.set(k, v, 'built-in') def set(self, name, value, source): self._vars[name] = value self._sources[name[2:-1]] = source def set_argument(self, name, value): self.set(name, value, self.ARGUMENT_SOURCE) def replace_variables(self, value): try: return self._vars.replace_scalar(value) except robotapi.DataError: return self._vars.replace_string(value, ignore_errors=True) def set_from_variable_table(self, variable_table): reader = robotapi.VariableTableReader() for variable in variable_table: try: if variable.name not in self._vars.store: _, value = reader._get_name_and_value( variable.name, variable.value, variable.report_invalid_syntax ) self.set(variable.name, value.resolve(self._vars), variable_table.source) except robotapi.DataError: if robotapi.is_var(variable.name): val = self._empty_value_for_variable_type(variable.name) self.set(variable.name, val, variable_table.source) def _empty_value_for_variable_type(self, name): if name[0] == '$': return '' if name[0] == '@': return [] return {} def set_from_file(self, varfile_path, args): vars_from_file = VariableFileSetter(None)._import_if_needed( varfile_path, args) for name, value in vars_from_file: self.set(name, value, varfile_path) def _get_prefix(self, value): if utils.is_dict_like(value): return '&' elif utils.is_list_like(value): return '@' else: return '$' def __iter__(self): for name, value in self._vars.store.data.items(): source = self._sources[name] prefix = self._get_prefix(value) name = u'{0}{{{1}}}'.format(prefix, name) if source == self.ARGUMENT_SOURCE: yield ArgumentInfo(name, value) else: yield VariableInfo(name, value, source) class DatafileRetriever(object): def __init__(self, lib_cache, resource_factory): self._lib_cache = lib_cache self._resource_factory = resource_factory self.keyword_cache = ExpiringCache() self._default_kws = None def get_all_cached_library_names(self): return self._lib_cache.get_all_cached_library_names() @property def default_kws(self): if self._default_kws is None: self._default_kws = self._lib_cache.get_default_keywords() return self._default_kws def expire_cache(self): self.keyword_cache = ExpiringCache() self._lib_cache.expire() def get_keywords_from_several(self, datafiles): kws = set() kws.update(self.default_kws) for df in datafiles: kws.update(self.get_keywords_from(df, RetrieverContext())) return kws def get_keywords_from(self, datafile, ctx): self._get_vars_recursive(datafile, ctx) ctx.allow_going_through_resources_again() return sorted(set( self._get_datafile_keywords(datafile) + self._get_imported_resource_keywords(datafile, ctx) + self._get_imported_library_keywords(datafile, ctx))) def is_library_import_ok(self, datafile, imp, ctx): self._get_vars_recursive(datafile, ctx) return bool(self._lib_kw_getter(imp, ctx)) def is_variables_import_ok(self, datafile, imp, ctx): self._get_vars_recursive(datafile, ctx) return self._import_vars(ctx, datafile, imp) def _get_datafile_keywords(self, datafile): if isinstance(datafile, robotapi.ResourceFile): return [ResourceUserKeywordInfo(kw) for kw in datafile.keywords] return [TestCaseUserKeywordInfo(kw) for kw in datafile.keywords] def _get_imported_library_keywords(self, datafile, ctx): return self._collect_kws_from_imports(datafile, robotapi.Library, self._lib_kw_getter, ctx) def _collect_kws_from_imports(self, datafile, instance_type, getter, ctx): kws = [] for imp in self._collect_import_of_type(datafile, instance_type): kws.extend(getter(imp, ctx)) return kws def _lib_kw_getter(self, imp, ctx): name = ctx.replace_variables(imp.name) name = self._convert_to_absolute_path(name, imp) args = [ctx.replace_variables(a) for a in imp.args] alias = ctx.replace_variables(imp.alias) if imp.alias else None return self._lib_cache.get_library_keywords(name, args, alias) def _convert_to_absolute_path(self, name, import_): full_name = os.path.join(import_.directory, name) if os.path.exists(full_name): return full_name return name def _collect_import_of_type(self, datafile, instance_type): return [imp for imp in datafile.imports if isinstance(imp, instance_type)] def _get_imported_resource_keywords(self, datafile, ctx): return self._collect_kws_from_imports(datafile, robotapi.Resource, self._res_kw_recursive_getter, ctx) def _res_kw_recursive_getter(self, imp, ctx): kws = [] res = self._resource_factory.get_resource_from_import(imp, ctx) if not res or res in ctx.parsed: return kws ctx.parsed.add(res) ctx.set_variables_from_datafile_variable_table(res) for child in self._collect_import_of_type(res, robotapi.Resource): kws.extend(self._res_kw_recursive_getter(child, ctx)) kws.extend(self._get_imported_library_keywords(res, ctx)) return [ResourceUserKeywordInfo(kw) for kw in res.keywords] + kws def get_variables_from(self, datafile, ctx=None): return self._get_vars_recursive(datafile, ctx or RetrieverContext()).vars def _get_vars_recursive(self, datafile, ctx): ctx.set_variables_from_datafile_variable_table(datafile) self._collect_vars_from_variable_files(datafile, ctx) self._collect_each_res_import(datafile, ctx, self._var_collector) return ctx def _collect_vars_from_variable_files(self, datafile, ctx): for imp in self._collect_import_of_type(datafile, robotapi.Variables): self._import_vars(ctx, datafile, imp) def _import_vars(self, ctx, datafile, imp): varfile_path = os.path.join(datafile.directory, ctx.replace_variables(imp.name)) args = [ctx.replace_variables(a) for a in imp.args] try: ctx.vars.set_from_file(varfile_path, args) return True except robotapi.DataError: return False # TODO: log somewhere def _var_collector(self, res, ctx, items): self._get_vars_recursive(res, ctx) def get_keywords_cached(self, datafile, context_factory): values = self.keyword_cache.get(datafile.source) if not values: words = self.get_keywords_from( datafile, context_factory.ctx_for_datafile(datafile)) words.extend(self.default_kws) values = _Keywords(words) self.keyword_cache.put(datafile.source, values) return values def _get_user_keywords_from(self, datafile): return list(self._get_user_keywords_recursive(datafile, RetrieverContext())) def _get_user_keywords_recursive(self, datafile, ctx): kws = set() kws.update(datafile.keywords) kws_from_res = self._collect_each_res_import( datafile, ctx, lambda res, ctx, kws: kws.update(self._get_user_keywords_recursive(res, ctx))) kws.update(kws_from_res) return kws def _collect_each_res_import(self, datafile, ctx, collector): items = set() ctx.set_variables_from_datafile_variable_table(datafile) for imp in self._collect_import_of_type(datafile, robotapi.Resource): res = self._resource_factory.get_resource_from_import(imp, ctx) if res and res not in ctx.parsed: ctx.parsed.add(res) collector(res, ctx, items) return items def get_resources_from(self, datafile): resources = list(self._get_resources_recursive(datafile, RetrieverContext())) resources.sort(key=operator.attrgetter('name')) return resources def _get_resources_recursive(self, datafile, ctx): resources = set() res = self._collect_each_res_import(datafile, ctx, self._add_resource) resources.update(res) for child in datafile.children: resources.update(self.get_resources_from(child)) return resources def _add_resource(self, res, ctx, items): items.add(res) items.update(self._get_resources_recursive(res, ctx)) class _Keywords(object): regexp = re.compile("\s*(given|when|then|and)\s*(.*)", re.IGNORECASE) def __init__(self, keywords): self.keywords = robotapi.NormalizedDict(ignore=['_']) self.embedded_keywords = {} self._add_keywords(keywords) def _add_keywords(self, keywords): for kw in keywords: self._add_keyword(kw) def _add_keyword(self, kw): # TODO: this hack creates a preference for local keywords over # resources and libraries Namespace should be rewritten to handle # keyword preference order if kw.name not in self.keywords: self.keywords[kw.name] = kw self._add_embedded(kw) self.keywords[kw.longname] = kw def _add_embedded(self, kw): if '$' not in kw.name: return try: handler = EmbeddedArgsHandler(kw) self.embedded_keywords[handler.name_regexp] = kw except Exception: pass def get(self, kw_name): if kw_name in self.keywords: return self.keywords[kw_name] bdd_name = self._get_bdd_name(kw_name) if bdd_name and bdd_name in self.keywords: return self.keywords[bdd_name] for regexp in self.embedded_keywords: if regexp.match(kw_name) or (bdd_name and regexp.match(bdd_name)): return self.embedded_keywords[regexp] return None def _get_bdd_name(self, kw_name): match = self.regexp.match(kw_name) return match.group(2) if match else None
apache-2.0
jacarrichan/eoffice
src/main/webapp/js/admin/FixedAssetsView.js
7938
Ext.ns("FixedAssetsView"); var FixedAssetsView = function() { }; FixedAssetsView.prototype.setTypeId = function(a) { this.typeId = a; FixedAssetsView.typeId = a; }; FixedAssetsView.prototype.getTypeId = function() { return this.typeId; }; FixedAssetsView.prototype.getView = function() { return new Ext.Panel( { id : "FixedAssetsView", title : "固定资产列表", layout : "anchor", region : "center", autoScroll : true, items : [ new Ext.FormPanel( { id : "FixedAssetsSearchForm", height : 40, frame : false, border : false, layout : "hbox", layoutConfig : { padding : "5", align : "middle" }, defaults : { xtype : "label", margins : { top : 0, right : 4, bottom : 4, left : 4 } }, items : [ { text : "查询条件:" }, { text : "资产名称" }, { xtype : "textfield", name : "Q_assetsName_S_LK" }, { text : "所属部门" }, { xtype : "textfield", name : "Q_beDep_S_LK" }, { xtype : "button", text : "查询", iconCls : "search", handler : function() { var a = Ext.getCmp("FixedAssetsSearchForm"); var b = Ext.getCmp("FixedAssetsGrid"); if (a.getForm().isValid()) { $search( { searchPanel : a, gridPanel : b }); } } } ] }), this.setup() ] }); }; FixedAssetsView.prototype.setup = function() { return this.grid(); }; FixedAssetsView.prototype.grid = function() { var d = new Ext.grid.CheckboxSelectionModel(); var a = new Ext.grid.ColumnModel( { columns : [ d, new Ext.grid.RowNumberer(), { header : "assetsId", dataIndex : "assetsId", hidden : true }, { header : "资产编号", dataIndex : "assetsNo" }, { header : "资产名称", dataIndex : "assetsName" }, { header : "资产类别", dataIndex : "assetsTypeName" }, { header : "折旧类型", dataIndex : "depType", renderer : function(e) { return e.typeName; } }, { header : "开始折旧日期", dataIndex : "startDepre" }, { header : "资产值", dataIndex : "assetValue" }, { header : "资产当前值", dataIndex : "assetCurValue" }, { header : "管理", dataIndex : "assetsId", width : 50, sortable : false, renderer : function(i, h, f, l, g) { var k = f.data.assetsId; var e = f.data.depType.calMethod; var j = ""; if (isGranted("_Depreciate")) { j = '<button title="开始折算" value=" " class="btn-pred" onclick="FixedAssetsView.depreciate(' + k + "," + e + ')">&nbsp;</button>'; } if (isGranted("_FixedAssetsDel")) { j += '&nbsp;<button title="删除" value=" " class="btn-del" onclick="FixedAssetsView.remove(' + k + ')">&nbsp;</button>'; } if (isGranted("_FixedAssetsEdit")) { j += '&nbsp;<button title="编辑" value=" " class="btn-edit" onclick="FixedAssetsView.edit(' + k + ')">&nbsp;</button>'; } return j; } } ], defaults : { sortable : true, menuDisabled : false, width : 100 } }); var b = this.store(); b.load( { params : { start : 0, limit : 25 } }); var c = new Ext.grid.GridPanel( { id : "FixedAssetsGrid", tbar : this.topbar(), store : b, trackMouseOver : true, disableSelection : false, loadMask : true, autoHeight : true, cm : a, sm : d, viewConfig : { forceFit : true, enableRowBody : false, showPreview : false }, bbar : new Ext.PagingToolbar( { pageSize : 25, store : b, displayInfo : true, displayMsg : "当前显示从{0}至{1}, 共{2}条记录", emptyMsg : "当前没有记录" }) }); c.addListener("rowdblclick", function(g, f, h) { g.getSelectionModel().each(function(e) { if (isGranted("_FixedAssetsEdit")) { FixedAssetsView.edit(e.data.assetsId); } }); }); return c; }; FixedAssetsView.prototype.store = function() { var a = new Ext.data.Store( { proxy : new Ext.data.HttpProxy( { url : __ctxPath + "/admin/listFixedAssets.do" }), reader : new Ext.data.JsonReader( { root : "result", totalProperty : "totalCounts", id : "id", fields : [ { name : "assetsId", type : "int" }, "assetsNo", "assetsName", "model", { name : "assetsTypeName", mapping : "assetsType.typeName" }, "manufacturer", "manuDate", "buyDate", "beDep", "custodian", "notes", "remainValRate", { name : "depType", mapping : "depreType" }, "startDepre", "intendTerm", "intendWorkGross", "workGrossUnit", "assetValue", "assetCurValue", "depreRate" ] }), remoteSort : true }); a.setDefaultSort("assetsId", "desc"); return a; }; FixedAssetsView.prototype.topbar = function() { var a = new Ext.Toolbar( { id : "FixedAssetsFootBar", height : 30, bodyStyle : "text-align:left", items : [] }); if (isGranted("_FixedAssetsAdd")) { a.add(new Ext.Button( { iconCls : "btn-add", text : "创建固定资产项", handler : function() { new FixedAssetsForm().show(); Ext.getCmp("intendTermContainer").hide(); Ext.getCmp("WorkGrossPanel").hide(); Ext.getCmp("FixedAssetsForm").remove("assetCurValue"); Ext.getCmp("depreTypeId").getStore().reload(); Ext.getCmp("assetsTypeId").getStore().reload(); Ext.getCmp("FixedAssetsForm").remove("assetsNoContainer"); } })); } if (isGranted("_FixedAssetsDel")) { a.add(new Ext.Button( { iconCls : "btn-del", text : "删除固定资产项", handler : function() { var d = Ext.getCmp("FixedAssetsGrid"); var b = d.getSelectionModel().getSelections(); if (b.length == 0) { Ext.ux.Toast.msg("信息", "请选择要删除的记录!"); return; } var e = Array(); for ( var c = 0; c < b.length; c++) { e.push(b[c].data.assetsId); } FixedAssetsView.remove(e); } })); } return a; }; FixedAssetsView.remove = function(b) { var a = Ext.getCmp("FixedAssetsGrid"); Ext.Msg.confirm("信息确认", "将折算记录一起删除,您确认要删除该记录吗?", function(c) { if (c == "yes") { Ext.Ajax.request( { url : __ctxPath + "/admin/multiDelFixedAssets.do", params : { ids : b }, method : "post", success : function() { Ext.ux.Toast.msg("信息提示", "成功删除所选记录!"); a.getStore().reload( { params : { start : 0, limit : 25 } }); } }); } }); }; FixedAssetsView.edit = function(a) { new FixedAssetsForm( { assetsId : a }).show(); Ext.getCmp("intendTermContainer").hide(); Ext.getCmp("WorkGrossPanel").hide(); Ext.getCmp("depreTypeId").getStore().reload(); Ext.getCmp("assetsTypeId").getStore().reload(); }; FixedAssetsView.depreciate = function(b, a) { if (a == 2) { new WorkGrossWin(b); } else { if (a == 1 || a == 3 || a == 4) { Ext.Msg.confirm("操作提示", "你决定开始折算了吗?", function(c) { if (c == "yes") { Ext.Ajax.request( { url : __ctxPath + "/admin/depreciateDepreRecord.do", params : { ids : b }, method : "post", success : function(e, f) { var d = Ext.util.JSON.decode(e.responseText); if (d.success) { Ext.ux.Toast.msg("信息提示", "成功产生折旧记录!"); } else { Ext.ux.Toast.msg("信息提示", d.message); } }, failure : function(e, f) { var d = Ext.util.JSON.decode(e.responseText); Ext.ux.Toast.msg("信息提示", d.message); } }); } }); } else { Ext.ux.Toast.msg("信息提示", "抱歉,该类型的折算方法待实现!"); } } };
apache-2.0
pulcy/prometheus-conf
deps/github.com/coreos/fleet/fleetd/fleetd.go
8443
// Copyright 2014 CoreOS, 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 main import ( "encoding/json" "flag" "fmt" "os" "os/signal" "sync" "syscall" "github.com/rakyll/globalconf" "github.com/coreos/fleet/agent" "github.com/coreos/fleet/config" "github.com/coreos/fleet/log" "github.com/coreos/fleet/pkg" "github.com/coreos/fleet/registry" "github.com/coreos/fleet/server" "github.com/coreos/fleet/version" ) const ( DefaultConfigFile = "/etc/fleet/fleet.conf" FleetdDescription = "fleetd is the server component of fleet, a simple orchestration system for scheduling systemd units in a cluster." ) func main() { userset := flag.NewFlagSet("fleet", flag.ExitOnError) printVersion := userset.Bool("version", false, "Print the version and exit") cfgPath := userset.String("config", "", fmt.Sprintf("Path to config file. Fleet will look for a config at %s by default.", DefaultConfigFile)) userset.Usage = func() { fmt.Fprintf(os.Stderr, "%s\nUsage of %s:\n", FleetdDescription, os.Args[0]) userset.PrintDefaults() } err := userset.Parse(os.Args[1:]) if err != nil { userset.Usage() os.Exit(1) } args := userset.Args() if len(args) > 0 { // support `fleetd version` the same as `fleetd --version` if args[0] == "version" { *printVersion = true } else { fmt.Fprintf(os.Stderr, "%s takes no arguments. Did you mean to invoke fleetctl instead?\n", os.Args[0]) userset.Usage() os.Exit(1) } } if *printVersion { fmt.Println("fleetd version", version.Version) os.Exit(0) } log.Infof("Starting fleetd version %v", version.Version) cfgset := flag.NewFlagSet("fleet", flag.ExitOnError) cfgset.Int("verbosity", 0, "Logging level") cfgset.Var(&pkg.StringSlice{"http://127.0.0.1:2379", "http://127.0.0.1:4001"}, "etcd_servers", "List of etcd endpoints") cfgset.String("etcd_keyfile", "", "SSL key file used to secure etcd communication") cfgset.String("etcd_certfile", "", "SSL certification file used to secure etcd communication") cfgset.String("etcd_cafile", "", "SSL Certificate Authority file used to secure etcd communication") cfgset.String("etcd_key_prefix", registry.DefaultKeyPrefix, "Keyspace for fleet data in etcd") cfgset.Float64("etcd_request_timeout", 1.0, "Amount of time in seconds to allow a single etcd request before considering it failed.") cfgset.Float64("engine_reconcile_interval", 2.0, "Interval at which the engine should reconcile the cluster schedule in etcd.") cfgset.String("public_ip", "", "IP address that fleet machine should publish") cfgset.String("metadata", "", "List of key-value metadata to assign to the fleet machine") cfgset.String("agent_ttl", agent.DefaultTTL, "TTL in seconds of fleet machine state in etcd") cfgset.Int("token_limit", 100, "Maximum number of entries per page returned from API requests") cfgset.Bool("disable_engine", false, "Disable the engine entirely, use with care") cfgset.Bool("disable_watches", false, "Disable the use of etcd watches. Increases scheduling latency") cfgset.Bool("verify_units", false, "DEPRECATED - This option is ignored") cfgset.String("authorized_keys_file", "", "DEPRECATED - This option is ignored") globalconf.Register("", cfgset) cfg, err := getConfig(cfgset, *cfgPath) if err != nil { log.Fatalf(err.Error()) } log.Debugf("Creating Server") srv, err := server.New(*cfg, nil) if err != nil { log.Fatalf("Failed creating Server: %v", err.Error()) } srv.Run() srvMutex := sync.Mutex{} reconfigure := func() { log.Infof("Reloading configuration from %s", *cfgPath) srvMutex.Lock() defer srvMutex.Unlock() cfg, err := getConfig(cfgset, *cfgPath) if err != nil { log.Fatalf(err.Error()) } log.Infof("Restarting server components") srv.SetReconfigServer(true) // Get Server.listeners[] to keep it for a new server, // before killing the old server. oldListeners := srv.GetApiServerListeners() srv.Kill() // The new server takes the original listeners. srv, err = server.New(*cfg, oldListeners) if err != nil { log.Fatalf(err.Error()) } srv.Run() srv.SetReconfigServer(false) } shutdown := func() { log.Infof("Gracefully shutting down") srvMutex.Lock() defer srvMutex.Unlock() srv.Kill() srv.Purge() os.Exit(0) } writeState := func() { log.Infof("Dumping server state") srvMutex.Lock() defer srvMutex.Unlock() encoded, err := json.Marshal(srv) if err != nil { log.Errorf("Failed to dump server state: %v", err) return } if _, err := os.Stdout.Write(encoded); err != nil { log.Errorf("Failed to dump server state: %v", err) return } os.Stdout.Write([]byte("\n")) log.Debugf("Finished dumping server state") } signals := map[os.Signal]func(){ syscall.SIGHUP: reconfigure, syscall.SIGTERM: shutdown, syscall.SIGINT: shutdown, syscall.SIGUSR1: writeState, } listenForSignals(signals) } func getConfig(flagset *flag.FlagSet, userCfgFile string) (*config.Config, error) { opts := globalconf.Options{EnvPrefix: "FLEET_"} if userCfgFile != "" { // Fail hard if a user-provided config is not usable fi, err := os.Stat(userCfgFile) if err != nil { log.Fatalf("Unable to use config file %s: %v", userCfgFile, err) } if fi.IsDir() { log.Fatalf("Provided config %s is a directory, not a file", userCfgFile) } log.Infof("Using provided config file %s", userCfgFile) opts.Filename = userCfgFile } else if _, err := os.Stat(DefaultConfigFile); err == nil { log.Infof("Using default config file %s", DefaultConfigFile) opts.Filename = DefaultConfigFile } else { log.Infof("No provided or default config file found - proceeding without") } gconf, err := globalconf.NewWithOptions(&opts) if err != nil { return nil, err } gconf.ParseSet("", flagset) cfg := config.Config{ Verbosity: (*flagset.Lookup("verbosity")).Value.(flag.Getter).Get().(int), EtcdServers: (*flagset.Lookup("etcd_servers")).Value.(flag.Getter).Get().(pkg.StringSlice), EtcdKeyPrefix: (*flagset.Lookup("etcd_key_prefix")).Value.(flag.Getter).Get().(string), EtcdKeyFile: (*flagset.Lookup("etcd_keyfile")).Value.(flag.Getter).Get().(string), EtcdCertFile: (*flagset.Lookup("etcd_certfile")).Value.(flag.Getter).Get().(string), EtcdCAFile: (*flagset.Lookup("etcd_cafile")).Value.(flag.Getter).Get().(string), EtcdRequestTimeout: (*flagset.Lookup("etcd_request_timeout")).Value.(flag.Getter).Get().(float64), EngineReconcileInterval: (*flagset.Lookup("engine_reconcile_interval")).Value.(flag.Getter).Get().(float64), PublicIP: (*flagset.Lookup("public_ip")).Value.(flag.Getter).Get().(string), RawMetadata: (*flagset.Lookup("metadata")).Value.(flag.Getter).Get().(string), AgentTTL: (*flagset.Lookup("agent_ttl")).Value.(flag.Getter).Get().(string), DisableEngine: (*flagset.Lookup("disable_engine")).Value.(flag.Getter).Get().(bool), DisableWatches: (*flagset.Lookup("disable_watches")).Value.(flag.Getter).Get().(bool), VerifyUnits: (*flagset.Lookup("verify_units")).Value.(flag.Getter).Get().(bool), TokenLimit: (*flagset.Lookup("token_limit")).Value.(flag.Getter).Get().(int), AuthorizedKeysFile: (*flagset.Lookup("authorized_keys_file")).Value.(flag.Getter).Get().(string), } if cfg.VerifyUnits { log.Error("Config option verify_units is no longer supported - ignoring") } if len(cfg.AuthorizedKeysFile) > 0 { log.Error("Config option authorized_keys_file is no longer supported - ignoring") } if cfg.Verbosity > 0 { log.EnableDebug() } return &cfg, nil } func listenForSignals(sigmap map[os.Signal]func()) { sigchan := make(chan os.Signal, 1) for k := range sigmap { signal.Notify(sigchan, k) } for true { sig := <-sigchan handler, ok := sigmap[sig] if ok { handler() } } }
apache-2.0
firejack-open/Firejack-Platform
platform/src/main/webapp/js/net/firejack/platform/core/component/editor/FieldAllowedValueGrid.js
4072
/* * 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. */ //@tag opf-editor Ext.define('OPF.core.component.editor.AllowedValue', { extend: 'Ext.data.Model', fields: [ { name: 'allowedValue', type: 'string' } ] }); Ext.define('OPF.core.component.editor.FieldAllowedValuesGrid', { extend: 'Ext.grid.Panel', cls: 'border-radius-grid-body border-radius-grid-docked-top', height: 150, autoScroll: true, store: new Ext.data.Store({ model: 'OPF.core.component.editor.AllowedValue', proxy: { type: 'memory', reader: { type: 'json', idProperty: 'allowedValue', root: 'allowedValue' }, writer: { type: 'json' } } }), initComponent: function() { var grid = this; this.store = Ext.create('Ext.data.Store', { model: 'OPF.core.component.editor.AllowedValue', proxy: { type: 'memory', reader: { type: 'json', idProperty: 'allowedValue', root: 'allowedValue' }, writer: { type: 'json' } }, listeners: { datachanged: function(store) { grid.determineScrollbars(); } } }); this.rowEditor = Ext.create('Ext.grid.plugin.RowEditing'); this.allowedValueColumn = OPF.Ui.populateColumn('allowedValue', 'Allowed Value', { flex: 1, editor: 'textfield', renderer: 'htmlEncode' }); this.plugins = [this.rowEditor]; this.columns = [this.allowedValueColumn]; this.addBtn = Ext.create('Ext.button.Button', { text: 'Add', iconCls: 'silk-add', handler: function(btn) { var grid = btn.up('grid'); var allowedValueModel = Ext.create('OPF.core.component.editor.AllowedValue'); allowedValueModel.set('allowedValue', ''); grid.store.insert(0, allowedValueModel); grid.getRowEditor().startEdit(allowedValueModel, grid.allowedValueColumn) } }); this.deleteBtn = Ext.create('Ext.button.Button', { text: 'Delete', iconCls: 'silk-delete', handler: function(btn) { var grid = btn.up('grid'); var records = grid.getSelectionModel().getSelection(); grid.store.remove(records); } }); this.tbar = [this.addBtn, '-', this.deleteBtn]; this.callParent(arguments); }, getRowEditor: function() { if (this.rowEditor == null) { this.rowEditor = Ext.create('Ext.grid.plugin.RowEditing'); } return this.rowEditor; }, cleanFieldStore: function() { this.store.removeAll(); }, disableAllowedValuesGrid: function(disabled) { if (disabled) { this.cleanFieldStore(); this.addBtn.disable(); this.deleteBtn.disable(); } else { this.addBtn.enable(); this.deleteBtn.enable(); } } });
apache-2.0
xasx/camunda-bpm-platform
engine-spring/src/test/java/org/camunda/bpm/engine/spring/test/transaction/ServiceTaskBean.java
1235
/* * Copyright © 2013-2018 camunda services GmbH and various authors (info@camunda.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.camunda.bpm.engine.spring.test.transaction; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.camunda.bpm.engine.delegate.JavaDelegate; import org.springframework.transaction.annotation.Transactional; public class ServiceTaskBean implements JavaDelegate{ private BeanWithException beanWithException; public void setBeanWithException(BeanWithException bean){ this.beanWithException = bean; } @Transactional @Override public void execute(DelegateExecution execution) throws Exception { beanWithException.doSomething(); } }
apache-2.0
cyberh0me/IoTCoreSetSettings
App_IoTCoreSetSettings_Core_UWP/Data/Configuration.cs
664
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace cyberh0me.net.IoTCoreSetSettings.Data { public class Configuration { public string Interface { get; set; } public bool DHCP1 { get; set; } public string IPAddress { get; set; } public string Subnet { get; set; } public string Gateway { get; set; } public bool DHCP2 { get; set; } public string DNS1 { get; set; } public string DNS2 { get; set; } public Configuration(string Interface) { this.Interface = Interface; } } }
apache-2.0
rgooch/Dominator
imagepublishers/amipublisher/api.go
8505
package amipublisher import ( "time" "github.com/Cloud-Foundations/Dominator/lib/awsutil" "github.com/Cloud-Foundations/Dominator/lib/filesystem" "github.com/Cloud-Foundations/Dominator/lib/log" libtags "github.com/Cloud-Foundations/Dominator/lib/tags" ) const ExpiresAtFormat = "2006-01-02 15:04:05" type Image struct { awsutil.Target AmiId string AmiName string CreationDate string Description string Size uint // Size in GiB. Tags libtags.Tags } type Instance struct { awsutil.Target AmiId string InstanceId string LaunchTime string Tags libtags.Tags } type InstanceResult struct { awsutil.Target InstanceId string PrivateIp string Error error } func (v InstanceResult) MarshalJSON() ([]byte, error) { return v.marshalJSON() } type publishData struct { imageServerAddress string streamName string imageLeafName string minFreeBytes uint64 amiName string tags map[string]string unpackerName string s3BucketExpression string s3Folder string sharingAccountName string publishOptions *PublishOptions // Computed data follow. fileSystem *filesystem.FileSystem } type PublishOptions struct { EnaSupport bool } type Resource struct { awsutil.Target SharedFrom string SnapshotId string S3Bucket string S3ManifestFile string AmiId string } type Results []TargetResult type TargetResult struct { awsutil.Target SharedFrom string SnapshotId string S3Bucket string S3ManifestFile string AmiId string Size uint // Size in GiB. Error error } type TargetUnpackers struct { awsutil.Target Unpackers []Unpacker } type Unpacker struct { InstanceId string IpAddress string State string TimeSinceLastUsed string `json:",omitempty"` } type UnusedImagesResult struct { UnusedImages []Image OldInstances []Instance } type UsedImagesResult struct { UsedImages []Image UsingInstances []Instance } func (v TargetResult) MarshalJSON() ([]byte, error) { return v.marshalJSON() } func AddVolumes(targets awsutil.TargetList, skipList awsutil.TargetList, tags libtags.Tags, unpackerName string, size uint64, logger log.Logger) error { return addVolumes(targets, skipList, tags, unpackerName, size, logger) } func CopyBootstrapImage(streamName string, targets awsutil.TargetList, skipList awsutil.TargetList, marketplaceImage, marketplaceLoginName string, newImageTags libtags.Tags, unpackerName string, vpcSearchTags, subnetSearchTags, securityGroupSearchTags libtags.Tags, instanceType string, sshKeyName string, logger log.Logger) error { return copyBootstrapImage(streamName, targets, skipList, marketplaceImage, marketplaceLoginName, newImageTags, unpackerName, vpcSearchTags, subnetSearchTags, securityGroupSearchTags, instanceType, sshKeyName, logger) } func DeleteResources(resources []Resource, logger log.Logger) error { return deleteResources(resources, logger) } func DeleteTags(resources []Resource, tagKeys []string, logger log.Logger) error { return deleteTags(resources, tagKeys, logger) } func DeleteTagsOnUnpackers(targets awsutil.TargetList, skipList awsutil.TargetList, name string, tagKeys []string, logger log.Logger) error { return deleteTagsOnUnpackers(targets, skipList, name, tagKeys, logger) } func DeleteUnusedImages(targets awsutil.TargetList, skipList awsutil.TargetList, searchTags, excludeSearchTags libtags.Tags, minImageAge time.Duration, logger log.DebugLogger) (UnusedImagesResult, error) { return deleteUnusedImages(targets, skipList, searchTags, excludeSearchTags, minImageAge, logger) } func ExpireResources(targets awsutil.TargetList, skipList awsutil.TargetList, logger log.Logger) error { return expireResources(targets, skipList, logger) } func ImportKeyPair(targets awsutil.TargetList, skipList awsutil.TargetList, keyName string, publicKey []byte, logger log.Logger) error { return importKeyPair(targets, skipList, keyName, publicKey, logger) } func LaunchInstances(targets awsutil.TargetList, skipList awsutil.TargetList, imageSearchTags, vpcSearchTags, subnetSearchTags, securityGroupSearchTags libtags.Tags, instanceType string, rootVolumeSize uint, sshKeyName string, tags map[string]string, replaceInstances bool, logger log.Logger) ([]InstanceResult, error) { return launchInstances(targets, skipList, imageSearchTags, vpcSearchTags, subnetSearchTags, securityGroupSearchTags, instanceType, rootVolumeSize, sshKeyName, tags, replaceInstances, logger) } func LaunchInstancesForImages(images []Resource, vpcSearchTags, subnetSearchTags, securityGroupSearchTags libtags.Tags, instanceType string, rootVolumeSize uint, sshKeyName string, tags map[string]string, logger log.Logger) ([]InstanceResult, error) { return launchInstancesForImages(images, vpcSearchTags, subnetSearchTags, securityGroupSearchTags, instanceType, rootVolumeSize, sshKeyName, tags, logger) } func ListImages(targets awsutil.TargetList, skipList awsutil.TargetList, searchTags, excludeSearchTags libtags.Tags, minImageAge time.Duration, logger log.DebugLogger) ([]Image, error) { return listImages(targets, skipList, searchTags, excludeSearchTags, minImageAge, logger) } func ListStreams(targets awsutil.TargetList, skipList awsutil.TargetList, unpackerName string, logger log.Logger) (map[string]struct{}, error) { return listStreams(targets, skipList, unpackerName, logger) } func ListUnpackers(targets awsutil.TargetList, skipList awsutil.TargetList, unpackerName string, logger log.Logger) ( []TargetUnpackers, error) { return listUnpackers(targets, skipList, unpackerName, logger) } func ListUnusedImages(targets awsutil.TargetList, skipList awsutil.TargetList, searchTags, excludeSearchTags libtags.Tags, minImageAge time.Duration, logger log.DebugLogger) (UnusedImagesResult, error) { return listUnusedImages(targets, skipList, searchTags, excludeSearchTags, minImageAge, logger) } func ListUsedImages(targets awsutil.TargetList, skipList awsutil.TargetList, searchTags, excludeSearchTags libtags.Tags, logger log.DebugLogger) (UsedImagesResult, error) { return listUsedImages(targets, skipList, searchTags, excludeSearchTags, logger) } func PrepareUnpackers(streamName string, targets awsutil.TargetList, skipList awsutil.TargetList, name string, logger log.Logger) error { return prepareUnpackers(streamName, targets, skipList, name, logger) } func Publish(imageServerAddress string, streamName string, imageLeafName string, minFreeBytes uint64, amiName string, tags map[string]string, targets awsutil.TargetList, skipList awsutil.TargetList, unpackerName string, s3Bucket string, s3Folder string, sharingAccountName string, publishOptions PublishOptions, logger log.Logger) (Results, error) { pData := &publishData{ imageServerAddress: imageServerAddress, streamName: streamName, imageLeafName: imageLeafName, minFreeBytes: minFreeBytes, amiName: amiName, tags: tags, unpackerName: unpackerName, s3BucketExpression: s3Bucket, s3Folder: s3Folder, sharingAccountName: sharingAccountName, publishOptions: &publishOptions, } return pData.publish(targets, skipList, logger) } func RemoveUnusedVolumes(targets awsutil.TargetList, skipList awsutil.TargetList, unpackerName string, logger log.Logger) error { return removeUnusedVolumes(targets, skipList, unpackerName, logger) } func SetExclusiveTags(resources []Resource, tagKey string, tagValue string, logger log.Logger) error { return setExclusiveTags(resources, tagKey, tagValue, logger) } func SetTags(targets awsutil.TargetList, skipList awsutil.TargetList, name string, tags map[string]string, logger log.Logger) error { return setTags(targets, skipList, name, tags, logger) } func StartInstances(targets awsutil.TargetList, skipList awsutil.TargetList, name string, logger log.Logger) ( []InstanceResult, error) { return startInstances(targets, skipList, name, logger) } func StopIdleUnpackers(targets awsutil.TargetList, skipList awsutil.TargetList, name string, idleTimeout time.Duration, logger log.Logger) error { return stopIdleUnpackers(targets, skipList, name, idleTimeout, logger) } func TerminateInstances(targets awsutil.TargetList, skipList awsutil.TargetList, name string, logger log.Logger) error { return terminateInstances(targets, skipList, name, logger) }
apache-2.0
palmer159/openstack-test
packstack/plugins/ironic_275.py
4394
# -*- coding: utf-8 -*- # 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. """ Installs and configures Ironic """ from packstack.installer import utils from packstack.installer import validators from packstack.installer import processors from packstack.modules.shortcuts import get_mq from packstack.modules.ospluginutils import appendManifestFile from packstack.modules.ospluginutils import createFirewallResources from packstack.modules.ospluginutils import getManifestTemplate # ------------------ Ironic Packstack Plugin initialization ------------------ PLUGIN_NAME = "OS-Ironic" PLUGIN_NAME_COLORED = utils.color_text(PLUGIN_NAME, 'blue') def initConfig(controller): ironic_params = [ {"CONF_NAME": "CONFIG_IRONIC_DB_PW", "CMD_OPTION": "os-ironic-db-passwd", "PROMPT": "Enter the password for the Ironic DB user", "USAGE": "The password to use for the Ironic DB access", "OPTION_LIST": [], "VALIDATORS": [validators.validate_not_empty], "DEFAULT_VALUE": "PW_PLACEHOLDER", "PROCESSORS": [processors.process_password], "MASK_INPUT": True, "LOOSE_VALIDATION": False, "USE_DEFAULT": True, "NEED_CONFIRM": True, "CONDITION": False}, {"CONF_NAME": "CONFIG_IRONIC_KS_PW", "CMD_OPTION": "os-ironic-ks-passwd", "USAGE": ("The password to use for Ironic to authenticate " "with Keystone"), "PROMPT": "Enter the password for Ironic Keystone access", "OPTION_LIST": [], "VALIDATORS": [validators.validate_not_empty], "DEFAULT_VALUE": "PW_PLACEHOLDER", "PROCESSORS": [processors.process_password], "MASK_INPUT": True, "LOOSE_VALIDATION": False, "USE_DEFAULT": True, "NEED_CONFIRM": True, "CONDITION": False}, ] ironic_group = {"GROUP_NAME": "IRONIC", "DESCRIPTION": "Ironic Options", "PRE_CONDITION": "CONFIG_IRONIC_INSTALL", "PRE_CONDITION_MATCH": "y", "POST_CONDITION": False, "POST_CONDITION_MATCH": True} controller.addGroup(ironic_group, ironic_params) def initSequences(controller): if controller.CONF['CONFIG_IRONIC_INSTALL'] != 'y': return steps = [ {'title': 'Adding Ironic Keystone manifest entries', 'functions': [create_keystone_manifest]}, {'title': 'Adding Ironic manifest entries', 'functions': [create_manifest]}, ] controller.addSequence("Installing OpenStack Ironic", [], [], steps) # -------------------------- step functions -------------------------- def create_manifest(config, messages): if config['CONFIG_UNSUPPORTED'] != 'y': config['CONFIG_STORAGE_HOST'] = config['CONFIG_CONTROLLER_HOST'] manifestfile = "%s_ironic.pp" % config['CONFIG_CONTROLLER_HOST'] manifestdata = getManifestTemplate(get_mq(config, "ironic")) manifestdata += getManifestTemplate("ironic.pp") fw_details = dict() key = "ironic-api" fw_details.setdefault(key, {}) fw_details[key]['host'] = "ALL" fw_details[key]['service_name'] = "ironic-api" fw_details[key]['chain'] = "INPUT" fw_details[key]['ports'] = ['6385'] fw_details[key]['proto'] = "tcp" config['FIREWALL_IRONIC_API_RULES'] = fw_details manifestdata += createFirewallResources('FIREWALL_IRONIC_API_RULES') appendManifestFile(manifestfile, manifestdata, 'pre') def create_keystone_manifest(config, messages): if config['CONFIG_UNSUPPORTED'] != 'y': config['CONFIG_IRONIC_HOST'] = config['CONFIG_CONTROLLER_HOST'] manifestfile = "%s_keystone.pp" % config['CONFIG_CONTROLLER_HOST'] manifestdata = getManifestTemplate("keystone_ironic.pp") appendManifestFile(manifestfile, manifestdata)
apache-2.0
drnic/noop-cf-boshrelease
src/github.com/cloudfoundry-incubator/routing-api/Godeps/_workspace/src/github.com/cloudfoundry/dropsonde/integration_test/log_integration_test.go
3212
package integration_test import ( "fmt" "github.com/cloudfoundry/dropsonde" "github.com/cloudfoundry/dropsonde/log_sender" "github.com/cloudfoundry/dropsonde/metric_sender" "github.com/cloudfoundry/dropsonde/metricbatcher" "github.com/cloudfoundry/dropsonde/metrics" "github.com/cloudfoundry/loggregatorlib/loggertesthelper" "github.com/cloudfoundry/sonde-go/events" "github.com/gogo/protobuf/proto" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "net" "strings" "sync" "time" ) var ( logLock sync.RWMutex logMessages []*events.LogMessage udpConn net.PacketConn ) var _ = Describe("LogIntegration", func() { Context("with standard initialization", func() { origin := []string{"test-origin"} BeforeEach(func() { var err error logMessages = nil udpConn, err = net.ListenPacket("udp4", ":0") Expect(err).ToNot(HaveOccurred()) go listenForLogs() udpAddr := udpConn.LocalAddr().(*net.UDPAddr) dropsonde.Initialize(fmt.Sprintf("localhost:%d", udpAddr.Port), origin...) sender := metric_sender.NewMetricSender(dropsonde.AutowiredEmitter()) batcher := metricbatcher.New(sender, 100*time.Millisecond) metrics.Initialize(sender, batcher) }) AfterEach(func() { udpConn.Close() }) It("sends dropped error message for messages which are just under 64k and don't fit in UDP packet", func() { logSender := log_sender.NewLogSender(dropsonde.AutowiredEmitter(), time.Second, loggertesthelper.Logger()) const length = 64*1024 - 1 reader := strings.NewReader(strings.Repeat("s", length) + "\n") logSender.ScanErrorLogStream("someId", "app", "0", reader) Eventually(func() []*events.LogMessage { logLock.RLock() defer logLock.RUnlock() return logMessages }).Should(HaveLen(1)) Expect(logMessages[0].MessageType).To(Equal(events.LogMessage_ERR.Enum())) Expect(string(logMessages[0].GetMessage())).To(ContainSubstring("message could not fit in UDP packet")) }) It("sends dropped error message for messages which are over 64k", func() { logSender := log_sender.NewLogSender(dropsonde.AutowiredEmitter(), time.Second, loggertesthelper.Logger()) const length = 64*1024 + 1 reader := strings.NewReader(strings.Repeat("s", length) + "\n") logSender.ScanErrorLogStream("someId", "app", "0", reader) Eventually(func() []*events.LogMessage { logLock.RLock() defer logLock.RUnlock() return logMessages }).Should(HaveLen(2)) Expect(logMessages[0].MessageType).To(Equal(events.LogMessage_ERR.Enum())) Expect(string(logMessages[0].GetMessage())).To(ContainSubstring(" message too long (>64K without a newline)")) Expect(string(logMessages[1].GetMessage())).To(ContainSubstring("s")) }) }) }) func listenForLogs() { for { buffer := make([]byte, 1024) n, _, err := udpConn.ReadFrom(buffer) if err != nil { return } if n == 0 { panic("Received empty packet") } envelope := new(events.Envelope) err = proto.Unmarshal(buffer[0:n], envelope) if err != nil { panic(err) } if envelope.GetEventType() == events.Envelope_LogMessage { logLock.Lock() logMessages = append(logMessages, envelope.GetLogMessage()) logLock.Unlock() } } }
apache-2.0
dev-alberto/Bachelor2017
Code/FastArithmetic/joint_multiplication.py
5828
from Code.util import w_NAF, right_to_left_scalar_mul from Code.DataStructures.interfaces import AbstractPoint from Code.FastArithmetic.scalar_multiplication import FastScalarMultiplier class JointMultiplication: def __init__(self, point1, point2, w1, w2): assert isinstance(point1, AbstractPoint) assert isinstance(point2, AbstractPoint) self.point1 = point1 self.point2 = point2 self.multiplier1 = FastScalarMultiplier(point1) self.multiplier2 = FastScalarMultiplier(point2) self.w1 = w1 self.w2 = w2 self._P = {} self._Q = {} # precom stage for i in range(1, 2 ** (w1 - 1), 2): self._P[i] = self.multiplier1.sliding_window_left_to_right_scalar_mul(i) for j in range(1, 2 ** (w2 - 1), 2): self._Q[j] = self.multiplier2.sliding_window_left_to_right_scalar_mul(j) self.precom = ( (None, self.point2, self.point2.inverse()), (self.point1, self.point1.add(self.point2), self.point1.add(self.point2.inverse())), (self.point1.inverse(), self.point2.add(self.point1.inverse()), self.point1.inverse().add(self.point2.inverse())) ) def brute_joint_multiplication(self, k, l): result1 = self.multiplier1.sliding_window_left_to_right_scalar_mul(k) #print(result1) result2 = self.multiplier2.sliding_window_left_to_right_scalar_mul(l) #print(result2) return result1.add(result2) @staticmethod def JSF(a, b): _u = [[] for i in range(2)] d = [0 for i in range(2)] _l = [0 for i in range(2)] while (a + d[0] > 0) or (b + d[1] > 0): _l[0] = d[0] + a _l[1] = d[1] + b for i in range(2): if _l[i] % 2 == 0: u = 0 else: u = 2 - _l[i] % 4 if (_l[i] % 8 == 5 or _l[i] % 8 == 3) and (_l[1-i] % 4 == 2): u = -u _u[i].append(u) for i in range(2): if 2 * d[i] == 1 + _u[i][-1]: d[i] = 1 - d[i] if i == 0: #a = floor(a/2) a //= 2 else: #b = floor(b/2) b //= 2 return list(reversed(_u[0])), list(reversed(_u[1])) def JSF_Multiplication(self, k, l): """Add using Shamir Trick, variation of algorithm 3.48, Menezez Book""" jsf = self.JSF(k, l) #print(jsf) R = None for i, j in zip(jsf[0], jsf[1]): if R is None: R = None else: R = R.point_double() if i or j: R = self.precom[i][j].add(R) return R def interleaving_sliding_window(self, k, l): """Algorithm 3.5.1 menezez, 'Interleaving with NAF' """ #_P = {} # _Q = {} R = None naf = [w_NAF(k, self.w1), w_NAF(l, self.w2)] #print(naf) _l = max([len(naf[0]), len(naf[1])]) #precom stage # for i in range(1, 2**(w1 - 1), 2): # _P[i] = self.point1.right_to_left_scalar_mul(i) # for j in range(1, 2**(w2 - 1), 2): # _Q[j] = self.point2.right_to_left_scalar_mul(j) #padding stage for i in range(_l - len(naf[0])): naf[0].insert(i, 0) for i in range(_l - len(naf[1])): naf[1].insert(i, 0) for i in range(_l): if R is None: R = None else: R = R.point_double() for j in range(2): if naf[j][i] != 0: if naf[j][i] > 0: if j == 0: R = self._P[naf[j][i]].add(R) else: R = self._Q[naf[j][i]].add(R) else: if j == 0: R = self._P[-naf[j][i]].inverse().add(R) else: R = self._Q[-naf[j][i]].inverse().add(R) return R class FastJointMultiplier: def __init__(self, point1, point2, w1=4, w2=4): assert isinstance(point1, AbstractPoint) assert isinstance(point2, AbstractPoint) self.point1 = point1 self.point2 = point2 self.w1 = w1 self.w2 = w2 self._P = {} self._Q = {} # precom stage for i in range(1, 2 ** (w1 - 1), 2): self._P[i] = right_to_left_scalar_mul(point1, i) for j in range(1, 2 ** (w2 - 1), 2): self._Q[j] = right_to_left_scalar_mul(point2, j) def interleaving_sliding_window(self, k, l): """Algorithm 3.5.1 menezez, 'Interleaving with NAF' """ R = None naf = [w_NAF(k, self.w1), w_NAF(l, self.w2)] #print(naf) _l = max([len(naf[0]), len(naf[1])]) #padding stage for i in range(_l - len(naf[0])): naf[0].insert(i, 0) for i in range(_l - len(naf[1])): naf[1].insert(i, 0) for i in range(_l): if R is None: R = None else: R = R.point_double() for j in range(2): if naf[j][i] != 0: if naf[j][i] > 0: if j == 0: R = self._P[naf[j][i]].add(R) else: R = self._Q[naf[j][i]].add(R) else: if j == 0: R = self._P[-naf[j][i]].inverse().add(R) else: R = self._Q[-naf[j][i]].inverse().add(R) return R
apache-2.0
dongjunpeng/whale
src/main/java/com/buterfleoge/whale/service/weixin/protocol/WxPayJsapiNotifyRequest.java
19378
package com.buterfleoge.whale.service.weixin.protocol; import java.io.Serializable; import javax.xml.bind.annotation.XmlRootElement; import com.buterfleoge.whale.type.WxCode; import com.buterfleoge.whale.type.protocol.Request; /** * @author xiezhenzong * */ @XmlRootElement(name = "xml") public class WxPayJsapiNotifyRequest extends Request implements Serializable { /** * serial version uid */ private static final long serialVersionUID = 554643097201031097L; private String return_code; private String return_msg; // 以下字段在return_code为SUCCESS的时候有返回 private String appid; private String mch_id; private String device_info; private String nonce_str; private String sign; private String result_code; private String err_code; private String err_code_des; private String trade_type; private String openid; private String is_subscribe; private String bank_type; private Integer total_fee; private Integer settlement_total_fee; private String fee_type; private Integer cash_fee; private String cash_fee_type; private Integer coupon_fee; private Integer coupon_count; // 妈的,智障 private Integer coupon_type_0; private Integer coupon_type_1; private Integer coupon_type_2; private Integer coupon_type_3; private Integer coupon_type_4; private Integer coupon_type_5; private Integer coupon_type_6; private Integer coupon_type_7; private Integer coupon_type_8; private Integer coupon_type_9; private String coupon_id_0; private String coupon_id_1; private String coupon_id_2; private String coupon_id_3; private String coupon_id_4; private String coupon_id_5; private String coupon_id_6; private String coupon_id_7; private String coupon_id_8; private String coupon_id_9; private Integer coupon_fee_0; private Integer coupon_fee_1; private Integer coupon_fee_2; private Integer coupon_fee_3; private Integer coupon_fee_4; private Integer coupon_fee_5; private Integer coupon_fee_6; private Integer coupon_fee_7; private Integer coupon_fee_8; private Integer coupon_fee_9; private String transaction_id; private String out_trade_no; private String attach; private String time_end; public boolean isReturnCodeSuccess() { return WxCode.SUCCESS.code.equalsIgnoreCase(return_code); } public boolean isResultCodeSuccess() { return WxCode.SUCCESS.code.equalsIgnoreCase(result_code); } public boolean isCodeSuccess() { return isReturnCodeSuccess() && isResultCodeSuccess(); } /** * @return the return_code */ public String getReturn_code() { return return_code; } /** * @param return_code * the return_code to set */ public void setReturn_code(String return_code) { this.return_code = return_code; } /** * @return the return_msg */ public String getReturn_msg() { return return_msg; } /** * @param return_msg * the return_msg to set */ public void setReturn_msg(String return_msg) { this.return_msg = return_msg; } /** * @return the appid */ public String getAppid() { return appid; } /** * @param appid * the appid to set */ public void setAppid(String appid) { this.appid = appid; } /** * @return the mch_id */ public String getMch_id() { return mch_id; } /** * @param mch_id * the mch_id to set */ public void setMch_id(String mch_id) { this.mch_id = mch_id; } /** * @return the device_info */ public String getDevice_info() { return device_info; } /** * @param device_info * the device_info to set */ public void setDevice_info(String device_info) { this.device_info = device_info; } /** * @return the nonce_str */ public String getNonce_str() { return nonce_str; } /** * @param nonce_str * the nonce_str to set */ public void setNonce_str(String nonce_str) { this.nonce_str = nonce_str; } /** * @return the sign */ public String getSign() { return sign; } /** * @param sign * the sign to set */ public void setSign(String sign) { this.sign = sign; } /** * @return the result_code */ public String getResult_code() { return result_code; } /** * @param result_code * the result_code to set */ public void setResult_code(String result_code) { this.result_code = result_code; } /** * @return the err_code */ public String getErr_code() { return err_code; } /** * @param err_code * the err_code to set */ public void setErr_code(String err_code) { this.err_code = err_code; } /** * @return the err_code_des */ public String getErr_code_des() { return err_code_des; } /** * @param err_code_des * the err_code_des to set */ public void setErr_code_des(String err_code_des) { this.err_code_des = err_code_des; } /** * @return the trade_type */ public String getTrade_type() { return trade_type; } /** * @param trade_type * the trade_type to set */ public void setTrade_type(String trade_type) { this.trade_type = trade_type; } /** * @return the openid */ public String getOpenid() { return openid; } /** * @param openid * the openid to set */ public void setOpenid(String openid) { this.openid = openid; } /** * @return the is_subscribe */ public String getIs_subscribe() { return is_subscribe; } /** * @param is_subscribe * the is_subscribe to set */ public void setIs_subscribe(String is_subscribe) { this.is_subscribe = is_subscribe; } /** * @return the bank_type */ public String getBank_type() { return bank_type; } /** * @param bank_type * the bank_type to set */ public void setBank_type(String bank_type) { this.bank_type = bank_type; } /** * @return the total_fee */ public Integer getTotal_fee() { return total_fee; } /** * @param total_fee * the total_fee to set */ public void setTotal_fee(Integer total_fee) { this.total_fee = total_fee; } /** * @return the settlement_total_fee */ public Integer getSettlement_total_fee() { return settlement_total_fee; } /** * @param settlement_total_fee * the settlement_total_fee to set */ public void setSettlement_total_fee(Integer settlement_total_fee) { this.settlement_total_fee = settlement_total_fee; } /** * @return the fee_type */ public String getFee_type() { return fee_type; } /** * @param fee_type * the fee_type to set */ public void setFee_type(String fee_type) { this.fee_type = fee_type; } /** * @return the cash_fee */ public Integer getCash_fee() { return cash_fee; } /** * @param cash_fee * the cash_fee to set */ public void setCash_fee(Integer cash_fee) { this.cash_fee = cash_fee; } /** * @return the cash_fee_type */ public String getCash_fee_type() { return cash_fee_type; } /** * @param cash_fee_type * the cash_fee_type to set */ public void setCash_fee_type(String cash_fee_type) { this.cash_fee_type = cash_fee_type; } /** * @return the coupon_fee */ public Integer getCoupon_fee() { return coupon_fee; } /** * @param coupon_fee * the coupon_fee to set */ public void setCoupon_fee(Integer coupon_fee) { this.coupon_fee = coupon_fee; } /** * @return the coupon_count */ public Integer getCoupon_count() { return coupon_count; } /** * @param coupon_count * the coupon_count to set */ public void setCoupon_count(Integer coupon_count) { this.coupon_count = coupon_count; } /** * @return the coupon_type_0 */ public Integer getCoupon_type_0() { return coupon_type_0; } /** * @param coupon_type_0 * the coupon_type_0 to set */ public void setCoupon_type_0(Integer coupon_type_0) { this.coupon_type_0 = coupon_type_0; } /** * @return the coupon_type_1 */ public Integer getCoupon_type_1() { return coupon_type_1; } /** * @param coupon_type_1 * the coupon_type_1 to set */ public void setCoupon_type_1(Integer coupon_type_1) { this.coupon_type_1 = coupon_type_1; } /** * @return the coupon_type_2 */ public Integer getCoupon_type_2() { return coupon_type_2; } /** * @param coupon_type_2 * the coupon_type_2 to set */ public void setCoupon_type_2(Integer coupon_type_2) { this.coupon_type_2 = coupon_type_2; } /** * @return the coupon_type_3 */ public Integer getCoupon_type_3() { return coupon_type_3; } /** * @param coupon_type_3 * the coupon_type_3 to set */ public void setCoupon_type_3(Integer coupon_type_3) { this.coupon_type_3 = coupon_type_3; } /** * @return the coupon_type_4 */ public Integer getCoupon_type_4() { return coupon_type_4; } /** * @param coupon_type_4 * the coupon_type_4 to set */ public void setCoupon_type_4(Integer coupon_type_4) { this.coupon_type_4 = coupon_type_4; } /** * @return the coupon_type_5 */ public Integer getCoupon_type_5() { return coupon_type_5; } /** * @param coupon_type_5 * the coupon_type_5 to set */ public void setCoupon_type_5(Integer coupon_type_5) { this.coupon_type_5 = coupon_type_5; } /** * @return the coupon_type_6 */ public Integer getCoupon_type_6() { return coupon_type_6; } /** * @param coupon_type_6 * the coupon_type_6 to set */ public void setCoupon_type_6(Integer coupon_type_6) { this.coupon_type_6 = coupon_type_6; } /** * @return the coupon_type_7 */ public Integer getCoupon_type_7() { return coupon_type_7; } /** * @param coupon_type_7 * the coupon_type_7 to set */ public void setCoupon_type_7(Integer coupon_type_7) { this.coupon_type_7 = coupon_type_7; } /** * @return the coupon_type_8 */ public Integer getCoupon_type_8() { return coupon_type_8; } /** * @param coupon_type_8 * the coupon_type_8 to set */ public void setCoupon_type_8(Integer coupon_type_8) { this.coupon_type_8 = coupon_type_8; } /** * @return the coupon_type_9 */ public Integer getCoupon_type_9() { return coupon_type_9; } /** * @param coupon_type_9 * the coupon_type_9 to set */ public void setCoupon_type_9(Integer coupon_type_9) { this.coupon_type_9 = coupon_type_9; } /** * @return the coupon_id_0 */ public String getCoupon_id_0() { return coupon_id_0; } /** * @param coupon_id_0 * the coupon_id_0 to set */ public void setCoupon_id_0(String coupon_id_0) { this.coupon_id_0 = coupon_id_0; } /** * @return the coupon_id_1 */ public String getCoupon_id_1() { return coupon_id_1; } /** * @param coupon_id_1 * the coupon_id_1 to set */ public void setCoupon_id_1(String coupon_id_1) { this.coupon_id_1 = coupon_id_1; } /** * @return the coupon_id_2 */ public String getCoupon_id_2() { return coupon_id_2; } /** * @param coupon_id_2 * the coupon_id_2 to set */ public void setCoupon_id_2(String coupon_id_2) { this.coupon_id_2 = coupon_id_2; } /** * @return the coupon_id_3 */ public String getCoupon_id_3() { return coupon_id_3; } /** * @param coupon_id_3 * the coupon_id_3 to set */ public void setCoupon_id_3(String coupon_id_3) { this.coupon_id_3 = coupon_id_3; } /** * @return the coupon_id_4 */ public String getCoupon_id_4() { return coupon_id_4; } /** * @param coupon_id_4 * the coupon_id_4 to set */ public void setCoupon_id_4(String coupon_id_4) { this.coupon_id_4 = coupon_id_4; } /** * @return the coupon_id_5 */ public String getCoupon_id_5() { return coupon_id_5; } /** * @param coupon_id_5 * the coupon_id_5 to set */ public void setCoupon_id_5(String coupon_id_5) { this.coupon_id_5 = coupon_id_5; } /** * @return the coupon_id_6 */ public String getCoupon_id_6() { return coupon_id_6; } /** * @param coupon_id_6 * the coupon_id_6 to set */ public void setCoupon_id_6(String coupon_id_6) { this.coupon_id_6 = coupon_id_6; } /** * @return the coupon_id_7 */ public String getCoupon_id_7() { return coupon_id_7; } /** * @param coupon_id_7 * the coupon_id_7 to set */ public void setCoupon_id_7(String coupon_id_7) { this.coupon_id_7 = coupon_id_7; } /** * @return the coupon_id_8 */ public String getCoupon_id_8() { return coupon_id_8; } /** * @param coupon_id_8 * the coupon_id_8 to set */ public void setCoupon_id_8(String coupon_id_8) { this.coupon_id_8 = coupon_id_8; } /** * @return the coupon_id_9 */ public String getCoupon_id_9() { return coupon_id_9; } /** * @param coupon_id_9 * the coupon_id_9 to set */ public void setCoupon_id_9(String coupon_id_9) { this.coupon_id_9 = coupon_id_9; } /** * @return the coupon_fee_0 */ public Integer getCoupon_fee_0() { return coupon_fee_0; } /** * @param coupon_fee_0 * the coupon_fee_0 to set */ public void setCoupon_fee_0(Integer coupon_fee_0) { this.coupon_fee_0 = coupon_fee_0; } /** * @return the coupon_fee_1 */ public Integer getCoupon_fee_1() { return coupon_fee_1; } /** * @param coupon_fee_1 * the coupon_fee_1 to set */ public void setCoupon_fee_1(Integer coupon_fee_1) { this.coupon_fee_1 = coupon_fee_1; } /** * @return the coupon_fee_2 */ public Integer getCoupon_fee_2() { return coupon_fee_2; } /** * @param coupon_fee_2 * the coupon_fee_2 to set */ public void setCoupon_fee_2(Integer coupon_fee_2) { this.coupon_fee_2 = coupon_fee_2; } /** * @return the coupon_fee_3 */ public Integer getCoupon_fee_3() { return coupon_fee_3; } /** * @param coupon_fee_3 * the coupon_fee_3 to set */ public void setCoupon_fee_3(Integer coupon_fee_3) { this.coupon_fee_3 = coupon_fee_3; } /** * @return the coupon_fee_4 */ public Integer getCoupon_fee_4() { return coupon_fee_4; } /** * @param coupon_fee_4 * the coupon_fee_4 to set */ public void setCoupon_fee_4(Integer coupon_fee_4) { this.coupon_fee_4 = coupon_fee_4; } /** * @return the coupon_fee_5 */ public Integer getCoupon_fee_5() { return coupon_fee_5; } /** * @param coupon_fee_5 * the coupon_fee_5 to set */ public void setCoupon_fee_5(Integer coupon_fee_5) { this.coupon_fee_5 = coupon_fee_5; } /** * @return the coupon_fee_6 */ public Integer getCoupon_fee_6() { return coupon_fee_6; } /** * @param coupon_fee_6 * the coupon_fee_6 to set */ public void setCoupon_fee_6(Integer coupon_fee_6) { this.coupon_fee_6 = coupon_fee_6; } /** * @return the coupon_fee_7 */ public Integer getCoupon_fee_7() { return coupon_fee_7; } /** * @param coupon_fee_7 * the coupon_fee_7 to set */ public void setCoupon_fee_7(Integer coupon_fee_7) { this.coupon_fee_7 = coupon_fee_7; } /** * @return the coupon_fee_8 */ public Integer getCoupon_fee_8() { return coupon_fee_8; } /** * @param coupon_fee_8 * the coupon_fee_8 to set */ public void setCoupon_fee_8(Integer coupon_fee_8) { this.coupon_fee_8 = coupon_fee_8; } /** * @return the coupon_fee_9 */ public Integer getCoupon_fee_9() { return coupon_fee_9; } /** * @param coupon_fee_9 * the coupon_fee_9 to set */ public void setCoupon_fee_9(Integer coupon_fee_9) { this.coupon_fee_9 = coupon_fee_9; } /** * @return the transaction_id */ public String getTransaction_id() { return transaction_id; } /** * @param transaction_id * the transaction_id to set */ public void setTransaction_id(String transaction_id) { this.transaction_id = transaction_id; } /** * @return the out_trade_no */ public String getOut_trade_no() { return out_trade_no; } /** * @param out_trade_no * the out_trade_no to set */ public void setOut_trade_no(String out_trade_no) { this.out_trade_no = out_trade_no; } /** * @return the attach */ public String getAttach() { return attach; } /** * @param attach * the attach to set */ public void setAttach(String attach) { this.attach = attach; } /** * @return the time_end */ public String getTime_end() { return time_end; } /** * @param time_end * the time_end to set */ public void setTime_end(String time_end) { this.time_end = time_end; } }
apache-2.0
quantumlib/Cirq
cirq-core/cirq/testing/consistent_qasm_test.py
2890
# Copyright 2018 The Cirq Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Tuple import warnings import numpy as np import pytest import cirq class Fixed(cirq.Operation): def __init__(self, unitary: np.ndarray, qasm: str) -> None: self.unitary = unitary self.qasm = qasm def _unitary_(self): return self.unitary @property def qubits(self): return cirq.LineQubit.range(self.unitary.shape[0].bit_length() - 1) def with_qubits(self, *new_qubits): raise NotImplementedError() def _qasm_(self, args: cirq.QasmArgs): return args.format(self.qasm, *self.qubits) class QuditGate(cirq.Gate): def _qid_shape_(self) -> Tuple[int, ...]: return (3, 3) def _unitary_(self): return np.eye(9) def _qasm_(self, args: cirq.QasmArgs, qubits: Tuple[cirq.Qid, ...]): return NotImplemented def test_assert_qasm_is_consistent_with_unitary(): try: import qiskit as _ except ImportError: # coverage: ignore warnings.warn( "Skipped test_assert_qasm_is_consistent_with_unitary " "because qiskit isn't installed to verify against." ) return # Checks matrix. cirq.testing.assert_qasm_is_consistent_with_unitary( Fixed(np.array([[1, 0], [0, 1]]), 'z {0}; z {0};') ) cirq.testing.assert_qasm_is_consistent_with_unitary( Fixed(np.array([[1, 0], [0, -1]]), 'z {0};') ) with pytest.raises(AssertionError, match='Not equal'): cirq.testing.assert_qasm_is_consistent_with_unitary( Fixed(np.array([[1, 0], [0, -1]]), 'x {0};') ) # Checks qubit ordering. cirq.testing.assert_qasm_is_consistent_with_unitary(cirq.CNOT) cirq.testing.assert_qasm_is_consistent_with_unitary( cirq.CNOT.on(cirq.NamedQubit('a'), cirq.NamedQubit('b')) ) cirq.testing.assert_qasm_is_consistent_with_unitary( cirq.CNOT.on(cirq.NamedQubit('b'), cirq.NamedQubit('a')) ) # Checks that code is valid. with pytest.raises(AssertionError, match='Check your OPENQASM'): cirq.testing.assert_qasm_is_consistent_with_unitary( Fixed(np.array([[1, 0], [0, -1]]), 'JUNK$&*@($#::=[];') ) # Checks that the test handles qudits cirq.testing.assert_qasm_is_consistent_with_unitary(QuditGate())
apache-2.0
syamantm/finatra
http/src/test/scala/com/twitter/finatra/http/tests/integration/doeverything/main/domain/SomethingStreamedRequest.scala
325
package com.twitter.finatra.http.tests.integration.doeverything.main.domain import com.twitter.finatra.request.QueryParam import com.twitter.finatra.validation.NotEmpty case class SomethingStreamedRequest( @NotEmpty @QueryParam somethingId: String, @QueryParam field1: Option[String], @QueryParam field2: Option[Int])
apache-2.0
eSDK/esdk_cloud_fc_cli
test/demo/FC/eSDK_FC_1.5_Native_Demo_BS_JAVA/src/com/huawei/esdk/fusioncompute/demo/servlet/QuerySiteUriServlet.java
3580
package com.huawei.esdk.fusioncompute.demo.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import com.google.gson.Gson; import com.huawei.esdk.fusioncompute.demo.factory.ServiceManageFactory; import com.huawei.esdk.fusioncompute.demo.utils.ParametersUtils; import com.huawei.esdk.fusioncompute.local.model.FCSDKResponse; import com.huawei.esdk.fusioncompute.local.model.common.LoginResp; import com.huawei.esdk.fusioncompute.local.model.site.SiteBasicInfo; /** * “查询SiteUri”请求处理类 * @author * @see * @since eSDK Cloud V100R003C30 */ public class QuerySiteUriServlet extends HttpServlet { /** * 序列化版本标识 */ private static final long serialVersionUID = 190954570327110272L; /** * log日志对象 */ private static final Logger LOGGER = Logger .getLogger(QuerySiteUriServlet.class); /** * gson,用于转换String和json之间的转换 */ private Gson gson = new Gson(); @Override protected void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } @Override protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置request的编码 request.setCharacterEncoding("UTF-8"); // 获取需要调用的方法名 String methodName = request.getParameter("method"); String resp = ""; if ("querySiteUri".equals(methodName)) { // 查询VDC resp = querySiteUri(request); } // 设置response的编码 response.setContentType("application/json;charset=UTF-8"); // 输出流 PrintWriter pw = response.getWriter(); // 将结果放到浏览器中 pw.print(resp); // 关闭输出流 pw.close(); } /** * 查VDC信息 * * @param request * HttpServletRequest对象 * @return json格式的字符串 * @see * @since eSDK Cloud V100R003C50 */ public String querySiteUri(HttpServletRequest request) { // 定义返回结果 String response = null; // 获取用户名 String userName = ParametersUtils.userName; // 获取密码 String password = ParametersUtils.password; // 调用鉴权接口 FCSDKResponse<LoginResp> loginResp = ServiceManageFactory.getUserService().login(userName, password); if (!"00000000".equals(loginResp.getErrorCode())) { // 鉴权失败 LOGGER.error("Failed to Login FC System!"); return gson.toJson(loginResp); } LOGGER.info("Login Success!"); LOGGER.info("Begin to query SiteUri information."); // 调用“查询所有站点信息”接口 FCSDKResponse<List<SiteBasicInfo>> resp = ServiceManageFactory.getSiteResource().querySites(); // 根据接口返回数据生成JSON字符串,以便于页面展示 response = gson.toJson(resp); LOGGER.info("Finish to query SiteUri, response is : " + response); return response; } }
apache-2.0
bluelatex/bluelatex-web
test/spec/entities/SessionTest.js
1451
describe("User entity", function () { "use strict"; var mockSessionResource, $httpBackend, ServerService; beforeEach(angular.mock.module("bluelatex")); beforeEach(function () { angular.mock.inject(function ($injector) { ServerService = $injector.get("ServerService"); $httpBackend = $injector.get("$httpBackend"); mockSessionResource = $injector.get("Session"); }); }); describe("login user", function () { it("should call login", inject(function () { $httpBackend.expectPOST(ServerService.urlServer + "/session") .respond("true"); mockSessionResource.login({ username: "username", password: "password" }); $httpBackend.flush(); })); }); describe("get user session", function () { it("should call login", inject(function () { $httpBackend.expectGET(ServerService.urlServer + "/session") .respond("true"); mockSessionResource.get(); $httpBackend.flush(); })); }); describe("lougout user", function () { it("should call logout", inject(function () { $httpBackend.expectDELETE(ServerService.urlServer + "/session") .respond("true"); mockSessionResource.logout(); $httpBackend.flush(); })); }); });
apache-2.0
vvv1559/algorytms-and-data-structures
leetcode/src/main/java/com/github/vvv1559/algorithms/leetcode/math/Sqrt.java
515
package com.github.vvv1559.algorithms.leetcode.math; import com.github.vvv1559.algorithms.annotations.Difficulty; import com.github.vvv1559.algorithms.annotations.Level; /* * Original text: https://leetcode.com/problems/sqrtx/description/ * * Implement int sqrt(int x). * * Compute and return the square root of x. * */ @Difficulty(Level.EASY) class Sqrt { int mySqrt(int x) { long r = x; while (r * r > x) { r = (r + x / r) / 2; } return (int) r; } }
apache-2.0
Orange-OpenSource/matos-profiles
matos-android/src/main/java/com/android/internal/view/menu/SubMenuBuilder.java
2688
package com.android.internal.view.menu; /* * #%L * Matos * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2010 - 2014 Orange SA * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ @com.francetelecom.rd.stubs.annotation.ClassDone(0) public class SubMenuBuilder extends MenuBuilder implements android.view.SubMenu { // Constructors public SubMenuBuilder(android.content.Context arg1, MenuBuilder arg2, MenuItemImpl arg3){ super((android.content.Context) null); } // Methods public android.view.MenuItem getItem(){ return (android.view.MenuItem) null; } public android.view.SubMenu setIcon(android.graphics.drawable.Drawable arg1){ return (android.view.SubMenu) null; } public android.view.SubMenu setIcon(int arg1){ return (android.view.SubMenu) null; } public void setCallback(@com.francetelecom.rd.stubs.annotation.FieldSet("callback") @com.francetelecom.rd.stubs.annotation.CallBackRegister("call") MenuBuilder.Callback arg1){ } public boolean expandItemActionView(MenuItemImpl arg1){ return false; } public boolean collapseItemActionView(MenuItemImpl arg1){ return false; } public void setQwertyMode(boolean arg1){ } public android.view.SubMenu setHeaderTitle(java.lang.CharSequence arg1){ return (android.view.SubMenu) null; } public android.view.SubMenu setHeaderTitle(int arg1){ return (android.view.SubMenu) null; } public android.view.SubMenu setHeaderIcon(android.graphics.drawable.Drawable arg1){ return (android.view.SubMenu) null; } public android.view.SubMenu setHeaderIcon(int arg1){ return (android.view.SubMenu) null; } public android.view.SubMenu setHeaderView(android.view.View arg1){ return (android.view.SubMenu) null; } public MenuBuilder getRootMenu(){ return (MenuBuilder) null; } public boolean isShortcutsVisible(){ return false; } public java.lang.String getActionViewStatesKey(){ return (java.lang.String) null; } public void setShortcutsVisible(boolean arg1){ } public boolean isQwertyMode(){ return false; } public android.view.Menu getParentMenu(){ return (android.view.Menu) null; } }
apache-2.0
ctripcorp/x-pipe
core/src/test/java/com/ctrip/xpipe/testutils/SpringApplicationStarter.java
2228
package com.ctrip.xpipe.testutils; import com.ctrip.xpipe.lifecycle.AbstractStartStoppable; import org.springframework.boot.Banner; import org.springframework.boot.SpringApplication; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.MutablePropertySources; import org.springframework.web.context.support.StandardServletEnvironment; import java.util.HashMap; import java.util.Map; /** * @author wenchao.meng * <p> * Sep 07, 2017 */ public class SpringApplicationStarter extends AbstractStartStoppable { private SpringApplication application; private ConfigurableApplicationContext context; protected int port; protected int maxThreads = 200; public SpringApplicationStarter(Class<?> resource, int port) { this(resource, port, 200); } public SpringApplicationStarter(Class<?> resource, int port, int maxThreads) { application = new SpringApplication(resource); application.setBannerMode(Banner.Mode.OFF); this.port = port; this.maxThreads = maxThreads; application.setEnvironment(createEnvironment()); } public int getPort() { return port; } @Override protected void doStart() throws Exception { context = application.run(); } @Override protected void doStop() throws Exception { if (context != null) { context.close(); } } protected ConfigurableEnvironment createEnvironment() { return new MyEnvironment(); } class MyEnvironment extends StandardServletEnvironment { @Override protected void customizePropertySources(MutablePropertySources propertySources) { super.customizePropertySources(propertySources); Map<String, Object> properties = new HashMap<>(); properties.put("server.port", String.valueOf(port)); properties.put("server.tomcat.max-threads", String.valueOf(maxThreads)); propertySources.addFirst(new MapPropertySource("TestAppServerProperty", properties)); } } }
apache-2.0
OasisDigital/nges
src/test/java/com/oasisdigital/nges/event/jdbc/EventStreamListITest.java
4439
package com.oasisdigital.nges.event.jdbc; import static java.time.OffsetDateTime.now; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import java.util.UUID; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.oasisdigital.nges.event.EventStoreConflict; import com.oasisdigital.nges.event.EventStream; import com.oasisdigital.nges.event.TestGroups; import com.oasisdigital.nges.event.jdbc.ConnectionSource; import com.oasisdigital.nges.event.jdbc.EventStreamListDao; @Test(groups = TestGroups.INTEGRATION) public class EventStreamListITest extends BaseITest { private ConnectionSource connectionSource; private EventStreamListDao streamList; private UUID id; @BeforeMethod public void setUp() throws Exception { this.connectionSource = new ConnectionSource(dataSource); this.streamList = new EventStreamListDao(connectionSource); this.id = UUID.randomUUID(); } @Test public void shouldInitNewStream() throws Exception { initStreamIfNeeded(id, "StreamType"); EventStream stream = streamList.findByStreamId(id); assertThat(stream.getStreamId(), is(id)); assertThat(stream.getStreamType(), is("StreamType")); assertThat(stream.getLastEventId(), is(nullValue())); assertThat(stream.getLastSeqNo(), is(nullValue())); assertThat(stream.getLastTransactionTime(), is(nullValue())); } @Test public void shouldUpdateStream() throws Exception { initStreamIfNeeded(id, "StreamType"); streamList.update(id, 112, 29, 0); EventStream stream = streamList.findByStreamId(id); assertThat(stream.getStreamId(), is(id)); assertThat(stream.getStreamType(), is("StreamType")); assertThat(stream.getLastEventId(), is(112L)); assertThat(stream.getLastSeqNo(), is(29L)); assertThat(stream.getLastTransactionTime(), is(not(nullValue()))); assertThat(stream.getLastTransactionTime().isAfter(now().minusSeconds(10)), is(true)); } @Test public void initStreamIfNeeded_shouldDoNothingIfStreamAlreadyExists() throws Exception { initStreamIfNeeded(id, "StreamType"); update(id, 112, 29, 0); initStreamIfNeeded(id, "StreamType"); EventStream stream = streamList.findByStreamId(id); assertThat(stream.getStreamId(), is(id)); assertThat(stream.getStreamType(), is("StreamType")); assertThat(stream.getLastEventId(), is(112L)); assertThat(stream.getLastSeqNo(), is(29L)); assertThat(stream.getLastTransactionTime(), is(not(nullValue()))); assertThat(stream.getLastTransactionTime().isAfter(now().minusSeconds(10)), is(true)); } @Test(expectedExceptions = EventStoreConflict.class) public void initStreamIfNeeded_shouldThrowConflictIfStreamExistsAndHasDifferentType() throws Exception { initStreamIfNeeded(id, "StreamType"); initStreamIfNeeded(id, "AnotherType"); } @Test(expectedExceptions = EventStoreConflict.class) public void initStream_shouldThrowConflictIfStreamExists() throws Exception { initStream(id, "StreamType"); initStream(id, "StreamType"); } @Test(expectedExceptions = EventStoreConflict.class) public void updateShouldThrowConflictIfTheIdInTableIsDifferentFromExpected() throws Exception { initStream(id, "StreamType"); update(id, 100, 12, 0); update(id, 150, 20, 12); update(id, 160, 22, 12); } private void initStream(UUID streamId, String streamType) throws Exception { connectionSource.inTransaction(conn -> { streamList.initStream(streamId, streamType); return null; }); } private boolean initStreamIfNeeded(UUID streamId, String streamType) throws Exception { return connectionSource.inTransaction(conn -> { return streamList.initStreamIfNeeded(streamId, streamType); }); } private void update(UUID streamId, long lastEventId, long lastSequence, long expectedSequence) throws Exception { connectionSource.inTransaction(conn -> { streamList.update(streamId, lastEventId, lastSequence, expectedSequence); return null; }); } }
apache-2.0
sjaco002/incubator-asterixdb
asterix-events/src/main/java/edu/uci/ics/asterix/event/error/VerificationUtil.java
5435
/* * Copyright 2009-2012 by The Regents of the University of California * 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 from * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.uci.ics.asterix.event.error; import java.io.File; import java.util.ArrayList; import java.util.List; import edu.uci.ics.asterix.event.model.AsterixInstance; import edu.uci.ics.asterix.event.model.AsterixInstance.State; import edu.uci.ics.asterix.event.model.AsterixRuntimeState; import edu.uci.ics.asterix.event.model.ProcessInfo; import edu.uci.ics.asterix.event.schema.cluster.Cluster; import edu.uci.ics.asterix.event.schema.cluster.Node; import edu.uci.ics.asterix.event.service.AsterixEventService; import edu.uci.ics.asterix.event.service.AsterixEventServiceUtil; public class VerificationUtil { private static final String VERIFY_SCRIPT_PATH = AsterixEventService.getEventHome() + File.separator + "scripts" + File.separator + "verify.sh"; public static AsterixRuntimeState getAsterixRuntimeState(AsterixInstance instance) throws Exception { Cluster cluster = instance.getCluster(); List<String> args = new ArrayList<String>(); args.add(instance.getName()); args.add(instance.getCluster().getMasterNode().getClusterIp()); for (Node node : cluster.getNode()) { args.add(node.getClusterIp()); args.add(instance.getName() + "_" + node.getId()); } Thread.sleep(2000); String output = AsterixEventServiceUtil.executeLocalScript(VERIFY_SCRIPT_PATH, args); boolean ccRunning = true; List<String> failedNCs = new ArrayList<String>(); String[] infoFields; ProcessInfo pInfo; List<ProcessInfo> processes = new ArrayList<ProcessInfo>(); for (String line : output.split("\n")) { String nodeid = null; infoFields = line.split(":"); try { int pid = Integer.parseInt(infoFields[3]); if (infoFields[0].equals("NC")) { nodeid = infoFields[2].split("_")[1]; } else { nodeid = instance.getCluster().getMasterNode().getId(); } pInfo = new ProcessInfo(infoFields[0], infoFields[1], nodeid, pid); processes.add(pInfo); } catch (Exception e) { if (infoFields[0].equalsIgnoreCase("CC")) { ccRunning = false; } else { failedNCs.add(infoFields[1]); } } } return new AsterixRuntimeState(processes, failedNCs, ccRunning); } public static void updateInstanceWithRuntimeDescription(AsterixInstance instance, AsterixRuntimeState state, boolean expectedRunning) { StringBuffer summary = new StringBuffer(); if (expectedRunning) { if (!state.isCcRunning()) { summary.append("Cluster Controller not running at " + instance.getCluster().getMasterNode().getId() + "\n"); instance.setState(State.UNUSABLE); } if (state.getFailedNCs() != null && !state.getFailedNCs().isEmpty()) { summary.append("Node Controller not running at the following nodes" + "\n"); for (String failedNC : state.getFailedNCs()) { summary.append(failedNC + "\n"); } // instance.setState(State.UNUSABLE); } if (!(instance.getState().equals(State.UNUSABLE))) { instance.setState(State.ACTIVE); } } else { if (state.getProcesses() != null && state.getProcesses().size() > 0) { summary.append("Following process still running " + "\n"); for (ProcessInfo pInfo : state.getProcesses()) { summary.append(pInfo + "\n"); } // instance.setState(State.UNUSABLE); } else { // instance.setState(State.INACTIVE); } } state.setSummary(summary.toString()); instance.setAsterixRuntimeStates(state); } public static void verifyBackupRestoreConfiguration(String hdfsUrl, String hadoopVersion, String hdfsBackupDir) throws Exception { StringBuffer errorCheck = new StringBuffer(); if (hdfsUrl == null || hdfsUrl.length() == 0) { errorCheck.append("\n HDFS Url not configured"); } if (hadoopVersion == null || hadoopVersion.length() == 0) { errorCheck.append("\n HDFS version not configured"); } if (hdfsBackupDir == null || hdfsBackupDir.length() == 0) { errorCheck.append("\n HDFS backup directory not configured"); } if (errorCheck.length() > 0) { throw new Exception("Incomplete hdfs configuration" + errorCheck); } } }
apache-2.0
avatartwo/avatar2
avatar2/peripherals/__init__.py
34
from .avatar_peripheral import *
apache-2.0
zoozooll/MyExercise
meep/MeepCommunicator/src/com/oregonscientific/meep/communicator/User.java
3265
package com.oregonscientific.meep.communicator; /** * Copyright (C) 2013 IDT International Ltd. */ import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.j256.ormlite.dao.ForeignCollection; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.field.ForeignCollectionField; import com.j256.ormlite.table.DatabaseTable; import com.oregonscientific.meep.database.Model; /** * The User object that represents an account object in the underlying datastore */ @DatabaseTable(tableName = "users") public class User extends Model<User, Long> { // For QueryBuilder to be able to find the fields public static final String ID_FIELD_NAME = "id"; public static final String MEEP_TAG_FIELD_NAME = "meeptag"; public static final String USER_FRIENDS_FIELD_NAME = "userFriends"; public static final String ICON_ADDRESS_FIELD_NAME = "iconAddress"; public static final String FIRST_NAME_FIELD_NAME = "firstName"; public static final String ACCOUNT_ID_FIELD_NAME = "accountId"; @DatabaseField( columnName = ID_FIELD_NAME, canBeNull = false, generatedId = true, allowGeneratedIdInsert = true, indexName = "user_idx") @SerializedName(ID_FIELD_NAME) @Expose private long id; @DatabaseField( columnName = MEEP_TAG_FIELD_NAME, uniqueIndex = true) @SerializedName(MEEP_TAG_FIELD_NAME) @Expose private String meepTag; @DatabaseField( columnName = ICON_ADDRESS_FIELD_NAME, canBeNull = true) @SerializedName(ICON_ADDRESS_FIELD_NAME) @Expose private String iconAddress; @DatabaseField( columnName = FIRST_NAME_FIELD_NAME, canBeNull = true) @SerializedName(FIRST_NAME_FIELD_NAME) @Expose private String firstName; @ForeignCollectionField(eager = false) @SerializedName(USER_FRIENDS_FIELD_NAME) private ForeignCollection<UserFriend> userFriends; @DatabaseField( columnName = ACCOUNT_ID_FIELD_NAME, canBeNull = true) @SerializedName(ACCOUNT_ID_FIELD_NAME) @Expose private String accountId; public User() { // all persisted classes must define a no-arg constructor with at least // package visibility } public User(String accountId) { this.accountId = accountId; } public User(String accountId, String iconAddress, String firstName, String meepTag) { this.accountId = accountId; this.iconAddress = iconAddress; this.firstName = firstName; this.meepTag = meepTag; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getMeepTag() { return meepTag; } public void setMeepTag(String meepTag) { this.meepTag = meepTag; } public void setUserFriends(ForeignCollection<UserFriend> userFriends) { this.userFriends = userFriends; } public ForeignCollection<UserFriend> getUserFriends() { return userFriends; } public String getIconAddress() { return iconAddress; } public void setIconAddress(String iconAddress) { this.iconAddress = iconAddress; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getAccountId() { return accountId; } public void setAccountId(String accountId) { this.accountId = accountId; } }
apache-2.0
eFaps/eFaps-WebApp
src/main/java/org/efaps/ui/wicket/components/tree/StructurBrowserTreeTable.java
7996
/* * Copyright 2003 - 2017 The eFaps Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.efaps.ui.wicket.components.tree; import java.util.Optional; import org.apache.wicket.AttributeModifier; import org.apache.wicket.Component; import org.apache.wicket.MarkupContainer; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.extensions.markup.html.repeater.tree.NestedTree; import org.apache.wicket.extensions.markup.html.repeater.tree.Node; import org.apache.wicket.extensions.markup.html.repeater.tree.theme.HumanTheme; import org.apache.wicket.extensions.markup.html.repeater.tree.theme.WindowsTheme; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.util.SetModel; import org.efaps.admin.ui.field.FieldTable; import org.efaps.ui.wicket.components.table.field.FieldPanel; import org.efaps.ui.wicket.models.field.AbstractUIField; import org.efaps.ui.wicket.models.objects.UIFieldStructurBrowser; import org.efaps.ui.wicket.models.objects.UIStructurBrowser; import org.efaps.ui.wicket.resources.AbstractEFapsHeaderItem; import org.efaps.ui.wicket.resources.EFapsContentReference; import org.efaps.ui.wicket.util.Configuration; import org.efaps.ui.wicket.util.Configuration.ConfigAttribute; import org.efaps.util.cache.CacheReloadException; /** * This class renders a TreeTable, which loads the children asynchron.<br> * The items of the tree consists of junction link, icon and label. * The table shows the columns as defined in the model. * * @author The eFaps Team */ public class StructurBrowserTreeTable extends NestedTree<UIStructurBrowser> { /** * Needed for serialization. */ private static final long serialVersionUID = 1L; /** * ResourceReference to the StyleSheet used for this TreeTable. */ private static final EFapsContentReference CSS = new EFapsContentReference(StructurBrowserTreeTable.class, "StructurTreeTable.css"); /** The topic name. */ private final String topicName; /** * Constructor. * * @param _wicketId wicket id for this component * @param _model model * @throws CacheReloadException on error */ public StructurBrowserTreeTable(final String _wicketId, final IModel<UIStructurBrowser> _model) throws CacheReloadException { super(_wicketId, new StructurBrowserProvider(_model), new SetModel<>(_model.getObject().getExpandedBrowsers())); if (_model.getObject() instanceof UIFieldStructurBrowser) { final FieldTable field = FieldTable.get(((UIFieldStructurBrowser) _model.getObject()).getFieldTabelId()); this.topicName = field.getName(); } else { this.topicName = _model.getObject().getTable().getName(); } if ("human".equals(Configuration.getAttribute(ConfigAttribute.STRUCBRWSRTREE_CLASS))) { add(new HumanTheme()); } else if ("windows".equals(Configuration.getAttribute(ConfigAttribute.STRUCBRWSRTREE_CLASS))) { add(new WindowsTheme()); } } @Override public void renderHead(final IHeaderResponse _response) { super.renderHead(_response); _response.render(AbstractEFapsHeaderItem.forCss(StructurBrowserTreeTable.CSS)); } @Override protected Component newContentComponent(final String _wicketId, final IModel<UIStructurBrowser> _model) { final UIStructurBrowser strucBrws = _model.getObject(); final AbstractUIField uiField = strucBrws.getColumns().get(strucBrws.getBrowserFieldIndex()); return new FieldPanel(_wicketId, Model.of(uiField)); } @Override public void expand(final UIStructurBrowser _uiStrBrws) { super.expand(_uiStrBrws); _uiStrBrws.setExpanded(true); final Optional<AjaxRequestTarget> optionalTarget = getRequestCycle().find(AjaxRequestTarget.class); final StringBuilder js = new StringBuilder() .append("highlight();positionTableColumns(eFapsTable").append(_uiStrBrws.getTableId()).append(");") .append("require([\"dojo/topic\"], function(topic){\n") .append("topic.publish(\"eFaps/expand/").append(this.topicName).append("\");\n") .append("})\n"); optionalTarget.ifPresent(target -> target.appendJavaScript(js)); } /** * Collapse the given node, tries to update the affected branch if the * change happens on an {@link AjaxRequestTarget}. * * @param _uiStrBrws the object to collapse */ @Override public void collapse(final UIStructurBrowser _uiStrBrws) { super.collapse(_uiStrBrws); _uiStrBrws.setExpanded(false); final Optional<AjaxRequestTarget> optionalTarget = getRequestCycle().find(AjaxRequestTarget.class); final StringBuilder js = new StringBuilder() .append("positionTableColumns(eFapsTable").append(_uiStrBrws.getTableId()).append(");") .append("require([\"dojo/topic\"], function(topic){\n") .append("topic.publish(\"eFaps/collapse/").append(this.topicName).append("\");\n") .append("})\n"); optionalTarget.ifPresent(target -> target.appendJavaScript(js)); } /** * Create a new component for a node. * * @param _wicketId the component id * @param _model the model containing the node * @return created component */ @Override public Component newNodeComponent(final String _wicketId, final IModel<UIStructurBrowser> _model) { return new Node<UIStructurBrowser>(_wicketId, this, _model) { private static final long serialVersionUID = 1L; @Override protected Component createContent(final String _wicketId, final IModel<UIStructurBrowser> _model) { return newContentComponent(_wicketId, _model); } @Override protected MarkupContainer createJunctionComponent(final String _id) { final UIStructurBrowser strucBrws = (UIStructurBrowser) getDefaultModelObject(); final MarkupContainer ret; if (strucBrws.hasChildren() && strucBrws.isForceExpanded()) { ret = new WebMarkupContainer(_id); } else { ret = super.createJunctionComponent(_id); } if (strucBrws.getLevel() > 0) { ret.add(AttributeModifier.append("style", "margin-left:" + 15 * (strucBrws.getLevel() - 1) + "px")); } return ret; } }; } /** * Create a new subtree. * * @param _wicketId wicket id for this component * @param _model the model of the new subtree * @return the created component */ @Override public Component newSubtree(final String _wicketId, final IModel<UIStructurBrowser> _model) { return new SubElement(_wicketId, this, _model); } }
apache-2.0
thebestpol/Effective
data/src/main/java/es/polgomez/data/repository/datasources/api/entities/ApiPointOfInterest.java
2130
package es.polgomez.data.repository.datasources.api.entities; import java.io.Serializable; /** * Point of interest detailed api entity */ public class ApiPointOfInterest implements Serializable{ private String id; private String title; private String address; private String transport; private String email; private String geocoordinates; private String description; private String phone; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getTransport() { return transport; } public void setTransport(String transport) { this.transport = transport; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getGeocoordinates() { return geocoordinates; } public void setGeocoordinates(String geocoordinates) { this.geocoordinates = geocoordinates; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } @Override public String toString() { return "ApiPointOfInterest{" + "id='" + id + '\'' + ", title='" + title + '\'' + ", address='" + address + '\'' + ", transport='" + transport + '\'' + ", email='" + email + '\'' + ", geocoordinates='" + geocoordinates + '\'' + ", description='" + description + '\'' + ", phone='" + phone + '\'' + '}'; } }
apache-2.0
junkieDolphin/tbdc15
workflows/2016-10-04-origin-destination-tensor/mktensor.py
6968
#!/usr/bin/env python """Create a tensor from compressed infoblu archive.""" import numpy import pandas import argparse import tarfile column_names = ['trip', 'timestamp', 'lat', 'lon', 'vehicle', 'speed'] use_columns = ['trip', 'timestamp', 'lat', 'lon'] def digitize(lat, lon, box, scale): ''' Transform one or more lat/lon pairs into 2D grid coordinates relative to a box and a given resolution (scale). ''' i = numpy.floor(scale * (lat - box['lat_min'])).astype('int') j = numpy.floor(scale * (lon - box['lon_min'])).astype('int') return i, j def gridshape(box, scale): ''' Return the dimensions of the grid for the given resolution (scale). ''' i_max, j_max = digitize(box['lat_max'], box['lon_max'], box, scale) shape = (i_max + 1, j_max + 1) return shape def tocells(df, box, scale): ''' Digitize latitude/longitude coordinates (see function digitize), and convert the resulting 2D grid coordinates into the corresponding ordinal cell numbers, relative to the box and given resolution (scale). Given an NxM matrix the ordinal number of cell (i, j) is: c = i + j * N Where indices start at 0 according to the Python convention. Returns a data frame where the lat and lon columns have been dropped and have been replaced with a column named 'c'. ''' shape = gridshape(box, scale) i, j = digitize(df['lat'], df['lon'], box, scale) df['c'] = i + j * shape[0] return df.drop(['lat', 'lon'], axis=1) def makeparser(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('trips_file', metavar='trips', help='Tar archive with daily trip dumps', type=argparse.FileType()) parser.add_argument('box_file', metavar='box_file', help='Text file with coordinates of all city boxes', type=argparse.FileType()) parser.add_argument('output_file', metavar='output', help='Write data to HDF file') parser.add_argument('city_code', metavar='city', help='One-letter city code. Available: %(choices)s', choices=list('bmnprtv')) parser.add_argument('-s', '--scale', help='spatial grid resolution (default: %(default)s per degree)', type=int, default=1000) parser.add_argument('--min-duration', metavar='STRING', help='Count only trips with minimum duration (%(metavar)s can be e.g. "1h", see pandas.Timedelta). Default: %(default)r', type=pandas.Timedelta, default=pandas.Timedelta('1m')) parser.add_argument('--max-duration', metavar='STRING', help='Count only trips with maximum duration (%(metavar)s can be e.g. "1h", see pandas.Timedelta). Default: %(default)r', type=pandas.Timedelta, default=pandas.Timedelta('1h')) parser.add_argument('--only', metavar='NUM', help='Read only %(metavar)s dumps from the Tar file.', type=int) return parser def main(): parser = makeparser() args = parser.parse_args() df_box = pandas.read_csv(args.box_file, index_col='city') box = df_box.ix[args.city_code].to_dict() # open tar file in random access mode with on-the-fly gzip decompression with tarfile.open(fileobj=args.trips_file, mode='r:gz') as tf: frames = [] cnt = 0 for member in tf: if args.only is not None and cnt >= args.only: break print member.name f = tf.extractfile(member) df = processframe(f, box, args.scale, args.min_duration, args.max_duration) frames.append(df) cnt += 1 df = pandas.concat(frames) ts0 = df['timestamp'].min() vals = df['trips'] df['timestamp_index'] = (df['timestamp'] - ts0).astype('m8[h]').astype(int) subs = df[['timestamp_index', 'origin', 'destination']] timestamps = df['timestamp'] lat_dim, lon_dim = gridshape(box, args.scale) shape_df = pandas.DataFrame({0: {'lat': lat_dim, 'lon': lon_dim}}).T with pandas.HDFStore(args.output_file, mode='w', complevel=9, complib='blosc') as store: store['/{}/vals'.format(args.city_code)] = vals store['/{}/subs'.format(args.city_code)] = subs store['/{}/shape'.format(args.city_code)] = shape_df store['/{}/timestamps'.format(args.city_code)] = timestamps print 'Data written to {}:/{}'.format(args.output_file, args.city_code) return df def processframe(fileobj, box, scale, min_duration, max_duration): """ Converts infoblu trips data into hour-origin-destination counts. Returns a data frame with the following columns: - timestamp with hourly frequencies - origin ordinal cell number - destination ordinal cell number - trips number of trips from origin to destination started within that hour """ df = pandas.read_csv(fileobj, sep=';', names=column_names, usecols=use_columns, parse_dates=['timestamp']) # get the cell number of the trip origin df_orig = tocells(df.groupby('trip').first(), box, scale) # get the cell number of the trip destination df_dest = tocells(df.groupby('trip').last(), box, scale) # join origins to destinations and compute trip durations df_od = df_orig.join(df_dest, lsuffix='_orig', rsuffix='_dest') df_od['duration'] = df_od['timestamp_dest'] - df_od['timestamp_orig'] # take only trips whose duration falls within requested min/max durations idx = (df_od['duration'] > min_duration) & (df_od['duration'] < max_duration) df_od = df_od[idx] # adjust column names, drop columns that are not needed anymore df_od.drop(['timestamp_dest', 'duration'], axis=1, inplace=True) df_od.rename(columns={'c_orig': 'origin', 'c_dest': 'destination', 'timestamp_orig': 'timestamp'}, inplace=True) # group trips by origin, destination, and hourly timestamp of departure df_od.reset_index(inplace=True) df_od.rename(columns={'trip': 'trips'}, inplace=True) tg = pandas.TimeGrouper(freq='H') groupby_cols = [tg, 'origin', 'destination'] return df_od.set_index('timestamp').groupby(groupby_cols).count().reset_index() if __name__ == '__main__': df = main()
apache-2.0
schleichardt/akka-persistence-snapshot-testkit
src/main/scala/SnapshotStoreSpec.scala
2916
package info.schleichardt.akka.persistence.snapshotstore import akka.actor._ import akka.persistence._ import akka.testkit._ import com.typesafe.config._ import org.scalatest._ import java.util.UUID import akka.testkit.TestKitBase private[snapshotstore] case class TestStateClass(foo: String, bar: Int) private[snapshotstore] class TestProcessor(override val processorId: String, notificationActor: ActorRef) extends Processor { var state: TestStateClass = TestProcessor.testState def receive = { case "snap" => saveSnapshot(state) notificationActor ! "snap" case s@SnapshotOffer(metadata, offeredSnapshot) => state = offeredSnapshot.asInstanceOf[TestStateClass] notificationActor ! state case s@SaveSnapshotSuccess(metadata) => notificationActor ! s case s@SaveSnapshotFailure(metadata, reason) => notificationActor ! s case Persistent(payload: TestStateClass, sequenceNr) => state = payload notificationActor ! state case _ => //ignore } } private[snapshotstore] object TestProcessor { def props(processorId: String, notificationActor: ActorRef) = Props(new TestProcessor(processorId, notificationActor)) val testState = TestStateClass("foo", 1) } trait SnapshotStoreSpec extends SnapshotSpecDetails { "A snapshot store" must { "asynchronously save and load a snapshot" in { val processorId = UUID.randomUUID().toString val processor = system.actorOf(TestProcessor.props(processorId, testActor)) processor ! "snap" expectMsg("snap") expectMsgType[SaveSnapshotSuccess] processor ! PoisonPill val processorReincarnation = system.actorOf(TestProcessor.props(processorId, testActor)) expectMsg(TestProcessor.testState) } "multiple snapshots and find the right one" in { val processorId = UUID.randomUUID().toString val processor = system.actorOf(TestProcessor.props(processorId, testActor)) val to = 9 for (i <- 0 to to) { val newState = TestStateClass("bar", i) processor ! Persistent(newState) expectMsg(newState) processor ! "snap" expectMsg("snap") expectMsgType[SaveSnapshotSuccess] } processor ! PoisonPill val processorReincarnation = system.actorOf(TestProcessor.props(processorId, testActor)) expectMsg(TestStateClass("bar", to)) } "delete a snapshot" in pending "delete all snapshots matching a criteria" in pending } } private[snapshotstore] trait SnapshotSpecDetails extends TestKitBase with WordSpecLike with Matchers with BeforeAndAfterAll with BeforeAndAfterEach { /** * override this for your snapshot storage plugin specific configuration * @return */ def testConfig: Config implicit lazy val system: ActorSystem = ActorSystem("SnapshotSpec", testConfig) override protected def afterAll(): Unit = shutdown(system) }
apache-2.0
CA-APM/ca-apm-example-webservice
webservice-example/src/main/java/com/wily/introscope/webservices/alerts/IAlertPollingService.java
2945
/** * IAlertPollingService.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package com.wily.introscope.webservices.alerts; public interface IAlertPollingService extends java.rmi.Remote { public com.wily.introscope.server.webservicesapi.alerts.DMgmtModuleSnapshot getManagementModule(java.lang.String manModuleName) throws java.rmi.RemoteException, com.wily.introscope.server.webservicesapi.IntroscopeWebServicesException; public com.wily.introscope.server.webservicesapi.alerts.DEMConfig getEMConfig() throws java.rmi.RemoteException, com.wily.introscope.server.webservicesapi.IntroscopeWebServicesException; public com.wily.introscope.server.webservicesapi.alerts.DMgmtModuleAlertDefnSnapshot getAlertSnapshot(java.lang.String manModuleName, java.lang.String agentIdentifier, java.lang.String alertDefName) throws java.rmi.RemoteException, com.wily.introscope.server.webservicesapi.IntroscopeWebServicesException; public com.wily.introscope.server.webservicesapi.alerts.DMgmtModuleAlertDefnSnapshot[] getAlertSnapshots(java.lang.String manModuleName, java.lang.String agentIdentifier) throws java.rmi.RemoteException, com.wily.introscope.server.webservicesapi.IntroscopeWebServicesException; public com.wily.introscope.server.webservicesapi.alerts.DMgmtModuleSnapshot[] getManagedModules() throws java.rmi.RemoteException, com.wily.introscope.server.webservicesapi.IntroscopeWebServicesException; public com.wily.introscope.server.webservicesapi.alerts.ManagementModuleBean[] getAllIscopeManagmentModules() throws java.rmi.RemoteException, com.wily.introscope.server.webservicesapi.IntroscopeWebServicesException; public com.wily.introscope.server.webservicesapi.alerts.ManagementModuleBean[] getAllFilteredIscopeManagmentModules() throws java.rmi.RemoteException, com.wily.introscope.server.webservicesapi.IntroscopeWebServicesException; public com.wily.introscope.server.webservicesapi.alerts.DAllAlertsSnapshot[] getAllAlertsSnapshot() throws java.rmi.RemoteException, com.wily.introscope.server.webservicesapi.IntroscopeWebServicesException; public com.wily.introscope.server.webservicesapi.alerts.DAllAlertsSnapshot[] getAllAlertsSnapshotForManagementModule(java.lang.String managementModule) throws java.rmi.RemoteException, com.wily.introscope.server.webservicesapi.IntroscopeWebServicesException; public com.wily.introscope.server.webservicesapi.alerts.DMgmtModuleAgentSnapshot getAgentSnapshot(java.lang.String manModuleName, java.lang.String agentIdentifier) throws java.rmi.RemoteException, com.wily.introscope.server.webservicesapi.IntroscopeWebServicesException; public com.wily.introscope.server.webservicesapi.alerts.DMgmtModuleAgentSnapshot[] getAgentSnapshots(java.lang.String manModuleName) throws java.rmi.RemoteException, com.wily.introscope.server.webservicesapi.IntroscopeWebServicesException; }
apache-2.0
ganesh2shiv/jump-ninja
andengine/src/main/java/org/andengine/util/modifier/IModifier.java
3485
package org.andengine.util.modifier; import org.andengine.util.exception.AndEngineRuntimeException; import java.util.Comparator; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:17:50 - 19.03.2010 */ public interface IModifier<T> { // =========================================================== // Constants // =========================================================== public static final Comparator<IModifier<?>> MODIFIER_COMPARATOR_DURATION_DESCENDING = new Comparator<IModifier<?>>() { @Override public int compare(final IModifier<?> pModifierA, final IModifier<?> pModifierB) { final float durationA = pModifierA.getDuration(); final float durationB = pModifierB.getDuration(); if (durationA < durationB) { return 1; } else if (durationA > durationB) { return -1; } else { return 0; } } }; // =========================================================== // Methods // =========================================================== public void reset(); public boolean isFinished(); public boolean isAutoUnregisterWhenFinished(); public void setAutoUnregisterWhenFinished(final boolean pRemoveWhenFinished); public IModifier<T> deepCopy() throws DeepCopyNotSupportedException; public float getSecondsElapsed(); public float getDuration(); public float onUpdate(final float pSecondsElapsed, final T pItem); public void addModifierListener(final IModifierListener<T> pModifierListener); public boolean removeModifierListener(final IModifierListener<T> pModifierListener); // =========================================================== // Inner and Anonymous Classes // =========================================================== public static interface IModifierListener<T> { // =========================================================== // Constants // =========================================================== // =========================================================== // Methods // =========================================================== public void onModifierStarted(final IModifier<T> pModifier, final T pItem); public void onModifierFinished(final IModifier<T> pModifier, final T pItem); } public static class DeepCopyNotSupportedException extends AndEngineRuntimeException { // =========================================================== // Constants // =========================================================== private static final long serialVersionUID = -5838035434002587320L; // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } }
apache-2.0
JetBrains/intellij-scala
scala/scala-impl/test/org/jetbrains/plugins/scala/annotator/template/AbstractInstantiationTest.scala
2885
package org.jetbrains.plugins.scala package annotator package template import org.jetbrains.plugins.scala.annotator.element.ScNewTemplateDefinitionAnnotator import org.jetbrains.plugins.scala.lang.psi.api.expr.ScNewTemplateDefinition /** * Pavel Fatin */ class AbstractInstantiationTest extends AnnotatorTestBase[ScNewTemplateDefinition] { def testOrdinaryClass(): Unit = { assertNothing(messages("class C; new C")) assertNothing(messages("class C; new C {}")) assertNothing(messages("class C; new C with Object")) assertNothing(messages("class C; new C with Object {}")) assertNothing(messages("class C; new Object with C")) assertNothing(messages("class C; new Object with C {}")) assertNothing(messages("class C; class X extends C")) assertNothing(messages("class C; class X extends C {}")) assertNothing(messages("class C; class X extends C with Object")) assertNothing(messages("class C; class X extends C with Object {}")) assertNothing(messages("class C; class X extends Object with C")) assertNothing(messages("class C; class X extends Object with C {}")) } def testAbstractClass(): Unit = { val firstMessage = message("Trait", "T") assertMatches(messages("trait T; new T")) { case Error("T", `firstMessage`) :: Nil => } val secondMessage = message("Class", "C") assertMatches(messages("abstract class C; new C")) { case Error("C", `secondMessage`) :: Nil => } assertNothing(messages("abstract class C; new C {}")) assertNothing(messages("abstract class C; new C with Object")) assertNothing(messages("abstract class C; new C with Object {}")) assertNothing(messages("abstract class C; new Object with C")) assertNothing(messages("abstract class C; new Object with C {}")) assertNothing(messages("abstract class C; class X extends C")) assertNothing(messages("abstract class C; class X extends C {}")) assertNothing(messages("abstract class C; class X extends C with Object")) assertNothing(messages("abstract class C; class X extends C with Object {}")) assertNothing(messages("abstract class C; class X extends Object with C")) assertNothing(messages("abstract class C; class X extends Object with C {}")) } def testAbstractClassEarlyDefinition(): Unit = { val firstMessage = message("Class", "C") assertMatches(messages("abstract class C; new {} with C")) { case Error("C", `firstMessage`) :: Nil => } assertNothing(messages("abstract class C; new { val a = 0 } with C")) } override protected def annotate(element: ScNewTemplateDefinition) (implicit holder: ScalaAnnotationHolder): Unit = ScNewTemplateDefinitionAnnotator.annotateAbstractInstantiation(element) private def message(params: String*) = ScalaBundle.message("illegal.instantiation", params: _*) }
apache-2.0