code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
package org.eso.ias.cdb;
import org.eso.ias.cdb.json.CdbFiles;
import org.eso.ias.cdb.json.CdbJsonFiles;
import org.eso.ias.cdb.json.JsonReader;
import org.eso.ias.cdb.rdb.RdbReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Constructor;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/**
* The factory to get the CdbReader implementation to use.
*
* This class checks the parameters of the command line, the java properties
* and the environment variable to build and return the {@link CdbReader} to use
* for reading the CDB.
*
* It offers a common strategy to be used consistently by all the IAS tools.
*
* The strategy is as follow:
* - if -cdbClass java.class param is present in the command line then the passed class
* is dynamically loaded and built (empty constructor); the configuration
* parameters eventually expected by such class will be passed by means of java
* properties (-D...)
* - else if jCdb file.path param is present in the command line then the JSON CDB
* implementation will be returned passing the passed file path
* - else the RDB implementation is returned (note that the parameters to connect to the RDB are passed
* in the hibernate configuration file
*
* RDB implementation is the fallback if none of the other possibilities succeeds.
*
*/
public class CdbReaderFactory {
/**
* The logger
*/
private static final Logger logger = LoggerFactory.getLogger(CdbReaderFactory.class);
/**
* The parameter to set in the command line to build a CdbReader from a custom java class
*/
public static final String cdbClassCmdLineParam="-cdbClass";
/**
* The long parameter to set in the command line to build a JSON CdbReader
*/
public static final String jsonCdbCmdLineParamLong ="-jCdb";
/**
* The short parameter to set in the command line to build a JSON CdbReader
*/
public static final String jsonCdbCmdLineParamShort ="-j";
/**
* get the value of the passed parameter from the eray of strings.
*
* The value of the parameter is in the position next to the passed param name like in
* -jcdb path
*
* @param paramName the not null nor empty parameter
* @param cmdLine the command line
* @return the value of the parameter or empty if not found in the command line
*/
private static Optional<String> getValueOfParam(String paramName, String cmdLine[]) {
if (paramName==null || paramName.isEmpty()) {
throw new IllegalArgumentException("Invalid null/empty name of parameter");
}
if (cmdLine==null || cmdLine.length<2) {
return Optional.empty();
}
List<String> params = Arrays.asList(cmdLine);
int pos=params.indexOf(paramName);
if (pos==-1) {
// Not found
return Optional.empty();
}
String ret = null;
try {
ret=params.get(pos+1);
} catch (IndexOutOfBoundsException e) {
logger.error("Missing parameter for {}}",paramName);
}
return Optional.ofNullable(ret);
}
/**
* Build and return the user provided CdbReader from the passed class using introspection
*
* @param cls The class implementing the CdbReader
* @return the user defined CdbReader
*/
private static final CdbReader loadUserDefinedReader(String cls) throws IasCdbException {
if (cls==null || cls.isEmpty()) {
throw new IllegalArgumentException("Invalid null/empty class");
}
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Class<?> theClass=null;
try {
theClass=classLoader.loadClass(cls);
} catch (Exception e) {
throw new IasCdbException("Error loading the external class "+cls,e);
}
Constructor constructor = null;
try {
constructor=theClass.getConstructor(null);
} catch (Exception e) {
throw new IasCdbException("Error getting the default (empty) constructor of the external class "+cls,e);
}
Object obj=null;
try {
obj=constructor.newInstance(null);
} catch (Exception e) {
throw new IasCdbException("Error building an object of the external class "+cls,e);
}
return (CdbReader)obj;
}
/**
* Gets and return the CdbReader to use to read the CDB applying the policiy described in the javadoc
* of the class
*
* @param cmdLine The command line
* @return the CdbReader to read th CDB
* @throws Exception in case of error building the CdbReader
*/
public static CdbReader getCdbReader(String[] cmdLine) throws Exception {
Objects.requireNonNull(cmdLine,"Invalid null command line");
Optional<String> userCdbReader = getValueOfParam(cdbClassCmdLineParam,cmdLine);
if (userCdbReader.isPresent()) {
logger.info("Using external (user provided) CdbReader from class {}",userCdbReader.get());
return loadUserDefinedReader(userCdbReader.get());
} else {
logger.debug("No external CdbReader found");
}
Optional<String> jsonCdbReaderS = getValueOfParam(jsonCdbCmdLineParamShort,cmdLine);
Optional<String> jsonCdbReaderL = getValueOfParam(jsonCdbCmdLineParamLong,cmdLine);
if (jsonCdbReaderS.isPresent() && jsonCdbReaderL.isPresent()) {
throw new Exception("JSON CDB path defined twice: check "+jsonCdbCmdLineParamShort+"and "+jsonCdbCmdLineParamLong+" params in cmd line");
}
if (jsonCdbReaderL.isPresent() || jsonCdbReaderS.isPresent()) {
String cdbPath = jsonCdbReaderL.orElseGet(() -> jsonCdbReaderS.get());
logger.info("Loading JSON CdbReader with folder {}",cdbPath);
CdbFiles cdbfiles = new CdbJsonFiles(cdbPath);
return new JsonReader(cdbfiles);
} else {
logger.debug("NO JSON CdbReader requested");
}
return new RdbReader();
}
}
| IntegratedAlarmSystem-Group/ias | Cdb/src/main/java/org/eso/ias/cdb/CdbReaderFactory.java | Java | lgpl-3.0 | 6,266 |
<?php
/**
* Contao Bootstrap form.
*
* @package contao-bootstrap
* @author David Molineus <david.molineus@netzmacht.de>
* @copyright 2017-2019 netzmacht David Molineus. All rights reserved.
* @license LGPL 3.0-or-later
* @filesource
*/
$GLOBALS['TL_LANG']['MSC']['bootstrapUploadButton'] = 'Choose file';
| contao-bootstrap/form | src/Resources/contao/languages/en/default.php | PHP | lgpl-3.0 | 326 |
/**
*A PUBLIC CLASS FOR ACTIONS.JAVA
*/
class Actions{
public Fonts font = new Fonts();
/**
*@see FONTS.JAVA
*this is a font class which is for changing the font, style & size
*/
public void fonT(){
font.setVisible(true); //setting the visible is true
font.pack(); //pack the panel
//making an action for ok button, so we can change the font
font.getOkjb().addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
n.getTextArea().setFont(font.font());
//after we chose the font, then the JDialog will be closed
font.setVisible(false);
}
});
//making an action for cancel button, so we can return to the old font.
font.getCajb().addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
//after we cancel the, then the JDialog will be closed
font.setVisible(false);
}
});
}
//for wraping the line & wraping the style word
public void lineWraP(){
if(n.getLineWrap().isSelected()){
/**
*make the line wrap & wrap style word is true
*when the line wrap is selected
*/
n.getTextArea().setLineWrap(true);
n.getTextArea().setWrapStyleWord(true);
}
else{
/**
*make the line wrap & wrap style word is false
*when the line wrap isn't selected
*/
n.getTextArea().setLineWrap(false);
n.getTextArea().setWrapStyleWord(false);
}
}
}
| SergiyKolesnikov/fuji | examples/Notepad_casestudies/NotepadBenDelaware/features/Font/Actions.java | Java | lgpl-3.0 | 1,444 |
"""General-use classes to interact with the ApplicationAutoScaling service through CloudFormation.
See Also:
`AWS developer guide for ApplicationAutoScaling
<https://docs.aws.amazon.com/autoscaling/application/APIReference/Welcome.html>`_
"""
# noinspection PyUnresolvedReferences
from .._raw import applicationautoscaling as _raw
# noinspection PyUnresolvedReferences
from .._raw.applicationautoscaling import *
| garyd203/flying-circus | src/flyingcircus/service/applicationautoscaling.py | Python | lgpl-3.0 | 424 |
# == Schema Information
#
# Table name: listing_shapes
#
# id :integer not null, primary key
# community_id :integer not null
# transaction_process_id :integer not null
# price_enabled :boolean not null
# shipping_enabled :boolean not null
# name :string(255) not null
# name_tr_key :string(255) not null
# action_button_tr_key :string(255) not null
# sort_priority :integer default(0), not null
# created_at :datetime not null
# updated_at :datetime not null
# deleted :boolean default(FALSE)
#
# Indexes
#
# index_listing_shapes_on_community_id (community_id)
# index_listing_shapes_on_name (name)
# multicol_index (community_id,deleted,sort_priority)
#
class ListingShape < ActiveRecord::Base
attr_accessible(
:community_id,
:transaction_process_id,
:price_enabled,
:shipping_enabled,
:name,
:sort_priority,
:name_tr_key,
:action_button_tr_key,
:price_quantity_placeholder,
:deleted
)
has_and_belongs_to_many :categories, -> { order("sort_priority") }, join_table: "category_listing_shapes"
has_many :listing_units
def self.columns
super.reject { |c| c.name == "transaction_type_id" || c.name == "price_quantity_placeholder" }
end
end
| ziyoucaishi/marketplace | app/models/listing_shape.rb | Ruby | lgpl-3.0 | 1,463 |
/*
* This file is part of BlendInt (a Blender-like Interface Library in
* OpenGL).
*
* BlendInt (a Blender-like Interface Library in OpenGL) is free
* software: you can redistribute it and/or modify it under the terms
* of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* BlendInt (a Blender-like Interface Library in OpenGL) is
* distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
* Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with BlendInt. If not, see
* <http://www.gnu.org/licenses/>.
*
* Contributor(s): Freeman Zhang <zhanggyb@gmail.com>
*/
#pragma once
#include <blendint/opengl/gl-buffer.hpp>
#include <blendint/core/color.hpp>
#include <blendint/gui/abstract-button.hpp>
#include <blendint/gui/color-selector.hpp>
namespace BlendInt {
/**
* @brief The most common button class
*
* @ingroup blendint_gui_widgets_buttons
*/
class ColorButton: public AbstractButton
{
DISALLOW_COPY_AND_ASSIGN(ColorButton);
public:
ColorButton ();
virtual ~ColorButton ();
void SetColor (const Color& color);
virtual bool IsExpandX () const override;
virtual Size GetPreferredSize () const override;
protected:
virtual void PerformSizeUpdate (const AbstractView* source,
const AbstractView* target,
int width,
int height) final;
virtual void PerformRoundTypeUpdate (int round_type) final;
virtual void PerformRoundRadiusUpdate (float radius) final;
virtual void PerformHoverIn (AbstractWindow* context) final;
virtual void PerformHoverOut (AbstractWindow* context) final;
virtual Response Draw (AbstractWindow* context) final;
private:
void InitializeColorButton ();
void OnClick ();
void OnSelectorDestroyed (AbstractFrame* sender);
GLuint vao_[2];
GLBuffer<ARRAY_BUFFER, 2> vbo_;
Color color0_;
Color color1_;
ColorSelector* selector_;
};
}
| zhanggyb/BlendInt | include/blendint/gui/color-button.hpp | C++ | lgpl-3.0 | 2,260 |
import java.util.*;
import Jakarta.util.FixDosOutputStream;
import java.io.*;
public class ImpQual {
/* returns name of AST_QualifiedName */
public String GetName() {
String result = ( ( AST_QualifiedName ) arg[0] ).GetName();
if ( arg[1].arg[0] != null )
result = result + ".*";
return result;
}
}
| SergiyKolesnikov/fuji | examples/AHEAD/preprocess/ImpQual.java | Java | lgpl-3.0 | 369 |
package com.ihidea.component.datastore.archive;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import com.ihidea.component.datastore.FileSupportService;
import com.ihidea.component.datastore.fileio.FileIoEntity;
import com.ihidea.core.CoreConstants;
import com.ihidea.core.support.exception.ServiceException;
import com.ihidea.core.support.servlet.ServletHolderFilter;
import com.ihidea.core.util.ImageUtilsEx;
import com.ihidea.core.util.ServletUtilsEx;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
* 收件扫描
* @author TYOTANN
*/
@Controller
public class ArchiveController {
protected Log logger = LogFactory.getLog(getClass());
@Autowired
private FileSupportService fileSupportService;
@Autowired
private ArchiveService archiveService;
@RequestMapping("/twain.do")
public String doTwain(ModelMap model, HttpServletRequest request) {
String twainHttp = CoreConstants.twainHost;
model.addAttribute("path", request.getParameter("path"));
model.addAttribute("params", request.getParameter("cs"));
model.addAttribute("picname", request.getParameter("picname"));
model.addAttribute("frame", request.getParameter("frame"));
model.addAttribute("HostIP", twainHttp.split(":")[0]);
model.addAttribute("HTTPPort", twainHttp.split(":")[1]);
model.addAttribute("storeName", "ds_archive");
model.addAttribute("storeType", "2");
return "archive/twain";
}
@RequestMapping("/editPicture.do")
public String doEditPicture(ModelMap model, HttpServletRequest request) {
model.addAttribute("ywid", request.getParameter("ywid"));
model.addAttribute("img", request.getParameter("img"));
model.addAttribute("name", request.getParameter("name"));
return "aie/imageeditor";
}
@RequestMapping("/showPicture.do")
public void showPicture(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
OutputStream os = null;
String id = request.getParameter("id");
FileIoEntity file = fileSupportService.get(id);
byte[] b = file.getContent();
response.setContentType("image/png");
try {
os = response.getOutputStream();
FileCopyUtils.copy(b, os);
} catch (IOException e) {
logger.debug("出错啦!", e);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
logger.debug("出错啦!", e);
}
}
}
}
/**
* 扫描收件获取图片信息
* @param request
* @param response
* @param model
*/
@RequestMapping("/doPictureData.do")
public void doPictureData(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
String tid = request.getParameter("id");
String spcode = request.getParameter("spcode");
String sncode = request.getParameter("sncode");
String typeid = request.getParameter("typeid");
String dm = request.getParameter("dm");
String dwyq = request.getParameter("dwyq");
if (tid == null || tid.trim().equals("") || tid.trim().equals("null")) {
tid = "-1";
}
List<Map<String, Object>> pList = null;
// 根据sncode或spcode查询所有收件
if (StringUtils.isBlank(spcode) && StringUtils.isBlank(sncode)) {
pList = archiveService.getPicture(Integer.valueOf(tid));
} else {
Map<String, Object> params = new HashMap<String, Object>();
params.put("spcode", spcode);
params.put("sncode", sncode);
params.put("typeid", typeid);
params.put("dm", dm);
pList = archiveService.getPicture("09100E", params);
}
// 查询单位印签只需要最后一张
List<Map<String, Object>> picList = new ArrayList<Map<String, Object>>();
if (!StringUtils.isBlank(dwyq)) {
for (int i = 0; i < pList.size(); i++) {
Map<String, Object> pic = pList.get(i);
if (dwyq.equals(pic.get("ino").toString())) {
picList.add(pic);
break;
}
}
} else {
picList = pList;
}
Map<String, List<Map<String, Object>>> map = new HashMap<String, List<Map<String, Object>>>();
map.put("images", picList);
ServletUtilsEx.renderJson(response, map);
}
@SuppressWarnings({ "unchecked" })
@RequestMapping("/uploadDataFile.do")
public String uploadFjToFile(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
String ino = null;
int id = request.getParameter("id") == null ? 0 : Integer.valueOf(request.getParameter("id"));
String strFileName = request.getParameter("filename");
Map<String, Object> paramMap = ServletHolderFilter.getContext().getParamMap();
FileItem cfile = null;
// 得到上传的文件
for (String key : paramMap.keySet()) {
if (paramMap.get(key) instanceof List) {
if (((List) paramMap.get(key)).get(0) instanceof FileItem)
cfile = ((List<FileItem>) paramMap.get(key)).get(0);
break;
}
}
ino = fileSupportService.add(cfile.getName(), cfile.get(), "ds_archive");
fileSupportService.submit(ino, "收件扫描-扫描");
// 保存到收件明细表ARCSJMX
archiveService.savePicture(id, ino, strFileName, "");
return null;
}
/**
* 扫描收件时上传图片
* @param request
* @param response
* @param model
* @return
* @throws Exception
*/
@SuppressWarnings({ "unchecked" })
@RequestMapping("/uploadUnScanDataFile.do")
public String uploadUnScanFjToFile(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception {
Map<String, Object> paramMap = ServletHolderFilter.getContext().getParamMap();
int id = paramMap.get("id") == null ? 0 : Integer.valueOf(String.valueOf(paramMap.get("id")));
String strFileName = paramMap.get("filename") == null ? StringUtils.EMPTY : String.valueOf(paramMap.get("filename"));
String storeName = "ds_archive";
FileOutputStream fos = null;
String ino = null;
try {
List<FileItem> remoteFile = (List<FileItem>) paramMap.get("uploadFile");
FileItem cfile = remoteFile.get(0);
String cfileOrjgName = cfile.getName();
String cfileName = cfileOrjgName.substring(0, cfileOrjgName.lastIndexOf("."));
ino = fileSupportService.add(cfile.getName(), cfile.get(), "ds_archive");
fileSupportService.submit(ino, "收件扫描-本地上传");
if (strFileName != null) {
cfileName = strFileName;
}
// 保存到收件明细表ARCSJMX
archiveService.savePicture(id, ino, cfileName, "");
} catch (Exception e) {
throw new ServiceException(e.getMessage());
} finally {
if (fos != null) {
fos.flush();
fos.close();
}
}
model.addAttribute("isSubmit", "1");
model.addAttribute("params", id);
model.addAttribute("path", "");
model.addAttribute("picname", strFileName);
model.addAttribute("storeName", storeName);
model.addAttribute("success", "上传成功!");
model.addAttribute("ino", ino);
return "archive/twain";
}
/**
* 扫描收件时查看
* @param request
* @param response
* @param model
* @return
*/
@RequestMapping("/doPicture.do")
public String doPicture(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
String img = request.getParameter("img");
String ywid = request.getParameter("ywid");
model.addAttribute("img", img);
model.addAttribute("ywid", ywid);
model.addAttribute("storeName", "ds_archive");
return "aie/showPicture";
}
/**
* 下载图片
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/downloadFj.do")
public void downloadFj(HttpServletRequest request, HttpServletResponse response) throws Exception {
String id = request.getParameter("id") == null ? "" : String.valueOf(request.getParameter("id"));
if (StringUtils.isBlank(id)) {
id = request.getParameter("file") == null ? "" : String.valueOf(request.getParameter("file"));
}
ServletOutputStream fos = null;
try {
fos = response.getOutputStream();
response.setContentType("application/octet-stream");
FileIoEntity file = fileSupportService.get(id);
FileCopyUtils.copy(file.getContent(), fos);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (fos != null) {
fos.flush();
fos.close();
}
}
}
@RequestMapping("/changePicture.do")
public void changePicture(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
String type = request.getParameter("type");
String path = request.getParameter("imagepath");
// 旋转
if (type.equals("rotate")) {
String aktion = request.getParameter("aktion");
// 角度
if (aktion.equals("rotieren")) {
int degree = Integer.valueOf(request.getParameter("degree"));
try {
Image imageOriginal = ImageIO.read(new ByteArrayInputStream(fileSupportService.get(path).getContent()));
// if (uploadType.equals("file")) { // 文件方式存储
// File tfile = new File(path);
// if (!tfile.exists()) {
// return;
// }
// imageOriginal = ImageIO.read(tfile);
// } else { // 数据库方式存储
// String errfilename =
// this.getClass().getResource("/").getPath()
// .replace("WEB-INF/classes",
// "resources/images/sjerr.png");
// ByteArrayOutputStream os = new ByteArrayOutputStream();
// archiveService.getPictureFromDB(request.getParameter("imagepath"),
// errfilename, os);
// byte[] data = os.toByteArray();
// InputStream is = new ByteArrayInputStream(data);
// imageOriginal = ImageIO.read(is);
// }
int widthOriginal = imageOriginal.getWidth(null);
int heightOriginal = imageOriginal.getHeight(null);
BufferedImage bi = new BufferedImage(widthOriginal, heightOriginal, BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g2d = bi.createGraphics();
g2d.drawImage(imageOriginal, 0, 0, null);
BufferedImage bu = ImageUtilsEx.rotateImage(bi, degree);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
encoder.encode(bu);
byte[] data = bos.toByteArray();
// 更新文件内容
fileSupportService.updateContent(path, data);
// if (uploadType.equals("file")) { // 文件方式存储
// FileOutputStream fos = new FileOutputStream(path);
// JPEGImageEncoder encoder =
// JPEGCodec.createJPEGEncoder(fos);
// encoder.encode(bu);
//
// fos.flush();
// fos.close();
// fos = null;
// } else { // 数据库方式存储
// ByteArrayOutputStream bos = new ByteArrayOutputStream();
// JPEGImageEncoder encoder =
// JPEGCodec.createJPEGEncoder(bos);
// encoder.encode(bu);
// byte[] data = bos.toByteArray();
// InputStream is = new ByteArrayInputStream(data);
// archiveService.updatePictureToDB(request.getParameter("imagepath"),
// is, data.length);
//
// bos.flush();
// bos.close();
// bos = null;
//
// is.close();
// is = null;
// }
} catch (IOException e) {
e.printStackTrace();
logger.error("错误:" + e.getMessage());
}
// 翻转
} else {
String degree = request.getParameter("degree");
try {
Image imageOriginal = ImageIO.read(new ByteArrayInputStream(fileSupportService.get(path).getContent()));
// if (uploadType.equals("file")) { // 文件方式存储
// File tfile = new File(path);
// if (!tfile.exists()) {
// return;
// }
// imageOriginal = ImageIO.read(tfile);
// } else { // 数据库方式存储
// String errfilename =
// this.getClass().getResource("/").getPath()
// .replace("WEB-INF/classes",
// "resources/images/sjerr.png");
// ByteArrayOutputStream os = new ByteArrayOutputStream();
// archiveService.getPictureFromDB(request.getParameter("imagepath"),
// errfilename, os);
// byte[] data = os.toByteArray();
// InputStream is = new ByteArrayInputStream(data);
// imageOriginal = ImageIO.read(is);
// }
int widthOriginal = imageOriginal.getWidth(null);
int heightOriginal = imageOriginal.getHeight(null);
BufferedImage bi = new BufferedImage(widthOriginal, heightOriginal, BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g2d = bi.createGraphics();
g2d.drawImage(imageOriginal, 0, 0, null);
BufferedImage bu = null;
if (degree.equals("flip")) {
bu = ImageUtilsEx.flipImage(bi);
} else {
bu = ImageUtilsEx.flopImage(bi);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
encoder.encode(bu);
byte[] data = bos.toByteArray();
// 更新文件内容
fileSupportService.updateContent(path, data);
// if (uploadType.equals("file")) { // 文件方式存储
// FileOutputStream fos = new FileOutputStream(path);
// JPEGImageEncoder encoder =
// JPEGCodec.createJPEGEncoder(fos);
// encoder.encode(bu);
//
// fos.flush();
// fos.close();
// fos = null;
// } else { // 数据库方式存储
// ByteArrayOutputStream bos = new ByteArrayOutputStream();
// JPEGImageEncoder encoder =
// JPEGCodec.createJPEGEncoder(bos);
// encoder.encode(bu);
// byte[] data = bos.toByteArray();
// InputStream is = new ByteArrayInputStream(data);
// archiveService.updatePictureToDB(request.getParameter("imagepath"),
// is, data.length);
//
// bos.flush();
// bos.close();
// bos = null;
//
// is.close();
// is = null;
// }
} catch (IOException e) {
e.printStackTrace();
logger.error("错误:" + e.getMessage());
}
}
}
}
// 公共方法
// 下载附件
@RequestMapping("/arcDownloadFj.do")
public void arcDownloadFj(HttpServletRequest request, HttpServletResponse response) {
int id = Integer.parseInt(request.getParameter("id"));
Map<String, Object> map = this.archiveService.getArcfj(id);
if (map == null) {
return;
}
ServletOutputStream fos = null;
FileInputStream fis = null;
BufferedInputStream bfis = null;
BufferedOutputStream bfos = null;
try {
File file = new File(map.get("filepath").toString());
if (!file.exists()) {
response.setCharacterEncoding("GBK");
response.getWriter().write("<script>alert('文件不存在');window.history.back();</script>");
return;
}
fos = response.getOutputStream();
response.setHeader("Content-Disposition", "attachment; filename=\""
+ new String(map.get("filename").toString().getBytes("GBK"), "ISO8859_1") + "\"");
fis = new FileInputStream(file);
bfis = new BufferedInputStream(fis);
bfos = new BufferedOutputStream(fos);
FileCopyUtils.copy(bfis, bfos);
} catch (Exception e) {
// e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
if (bfis != null) {
bfis.close();
}
if (bfos != null) {
bfos.close();
}
if (fis != null) {
fis.close();
}
} catch (Exception e) {
}
}
}
}
| tyotann/tyo-java-frame | src/com/ihidea/component/datastore/archive/ArchiveController.java | Java | lgpl-3.0 | 15,946 |
/*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.almsettings.ws;
import org.sonar.api.server.ServerSide;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.alm.setting.ALM;
import org.sonar.db.alm.setting.AlmSettingDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.almsettings.MultipleAlmFeatureProvider;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.AlmSettings;
import static java.lang.String.format;
import static org.sonar.api.web.UserRole.ADMIN;
@ServerSide
public class AlmSettingsSupport {
private final DbClient dbClient;
private final UserSession userSession;
private final ComponentFinder componentFinder;
private final MultipleAlmFeatureProvider multipleAlmFeatureProvider;
public AlmSettingsSupport(DbClient dbClient, UserSession userSession, ComponentFinder componentFinder,
MultipleAlmFeatureProvider multipleAlmFeatureProvider) {
this.dbClient = dbClient;
this.userSession = userSession;
this.componentFinder = componentFinder;
this.multipleAlmFeatureProvider = multipleAlmFeatureProvider;
}
public MultipleAlmFeatureProvider getMultipleAlmFeatureProvider() {
return multipleAlmFeatureProvider;
}
public void checkAlmSettingDoesNotAlreadyExist(DbSession dbSession, String almSetting) {
dbClient.almSettingDao().selectByKey(dbSession, almSetting)
.ifPresent(a -> {
throw new IllegalArgumentException(format("An ALM setting with key '%s' already exists", a.getKey()));
});
}
public void checkAlmMultipleFeatureEnabled(ALM alm) {
try (DbSession dbSession = dbClient.openSession(false)) {
if (!multipleAlmFeatureProvider.enabled() && !dbClient.almSettingDao().selectByAlm(dbSession, alm).isEmpty()) {
throw BadRequestException.create("A " + alm + " setting is already defined");
}
}
}
public ProjectDto getProjectAsAdmin(DbSession dbSession, String projectKey) {
return getProject(dbSession, projectKey, ADMIN);
}
public ProjectDto getProject(DbSession dbSession, String projectKey, String projectPermission) {
ProjectDto project = componentFinder.getProjectByKey(dbSession, projectKey);
userSession.checkProjectPermission(projectPermission, project);
return project;
}
public AlmSettingDto getAlmSetting(DbSession dbSession, String almSetting) {
return dbClient.almSettingDao().selectByKey(dbSession, almSetting)
.orElseThrow(() -> new NotFoundException(format("ALM setting with key '%s' cannot be found", almSetting)));
}
public static AlmSettings.Alm toAlmWs(ALM alm) {
switch (alm) {
case GITHUB:
return AlmSettings.Alm.github;
case BITBUCKET:
return AlmSettings.Alm.bitbucket;
case BITBUCKET_CLOUD:
return AlmSettings.Alm.bitbucketcloud;
case AZURE_DEVOPS:
return AlmSettings.Alm.azure;
case GITLAB:
return AlmSettings.Alm.gitlab;
default:
throw new IllegalStateException(format("Unknown ALM '%s'", alm.name()));
}
}
}
| SonarSource/sonarqube | server/sonar-webserver-webapi/src/main/java/org/sonar/server/almsettings/ws/AlmSettingsSupport.java | Java | lgpl-3.0 | 4,030 |
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#include <osgOcean/SiltEffect>
#include <osgOcean/ShaderManager>
#include <stdlib.h>
#include <OpenThreads/ScopedLock>
#include <osg/Texture2D>
#include <osg/PointSprite>
#include <osgUtil/CullVisitor>
#include <osgUtil/GLObjectsVisitor>
#include <osg/Notify>
#include <osg/io_utils>
#include <osg/Timer>
#include <osg/Version>
using namespace osgOcean;
static float random(float min,float max) { return min + (max-min)*(float)rand()/(float)RAND_MAX; }
static void fillSpotLightImage(unsigned char* ptr, const osg::Vec4& centerColour, const osg::Vec4& backgroudColour, unsigned int size, float power)
{
if (size==1)
{
float r = 0.5f;
osg::Vec4 color = centerColour*r+backgroudColour*(1.0f-r);
*ptr++ = (unsigned char)((color[0])*255.0f);
*ptr++ = (unsigned char)((color[1])*255.0f);
*ptr++ = (unsigned char)((color[2])*255.0f);
*ptr++ = (unsigned char)((color[3])*255.0f);
return;
}
float mid = (float(size)-1.0f)*0.5f;
float div = 2.0f/float(size);
for(unsigned int r=0;r<size;++r)
{
//unsigned char* ptr = image->data(0,r,0);
for(unsigned int c=0;c<size;++c)
{
float dx = (float(c) - mid)*div;
float dy = (float(r) - mid)*div;
float r = powf(1.0f-sqrtf(dx*dx+dy*dy),power);
if (r<0.0f) r=0.0f;
osg::Vec4 color = centerColour*r+backgroudColour*(1.0f-r);
*ptr++ = (unsigned char)((color[0])*255.0f);
*ptr++ = (unsigned char)((color[1])*255.0f);
*ptr++ = (unsigned char)((color[2])*255.0f);
*ptr++ = (unsigned char)((color[3])*255.0f);
}
}
}
static osg::Image* createSpotLightImage(const osg::Vec4& centerColour, const osg::Vec4& backgroudColour, unsigned int size, float power)
{
#if 0
osg::Image* image = new osg::Image;
unsigned char* ptr = image->data(0,0,0);
fillSpotLightImage(ptr, centerColour, backgroudColour, size, power);
return image;
#else
osg::Image* image = new osg::Image;
osg::Image::MipmapDataType mipmapData;
unsigned int s = size;
unsigned int totalSize = 0;
unsigned i;
for(i=0; s>0; s>>=1, ++i)
{
if (i>0) mipmapData.push_back(totalSize);
totalSize += s*s*4;
}
unsigned char* ptr = new unsigned char[totalSize];
image->setImage(size, size, size, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, ptr, osg::Image::USE_NEW_DELETE,1);
image->setMipmapLevels(mipmapData);
s = size;
for(i=0; s>0; s>>=1, ++i)
{
fillSpotLightImage(ptr, centerColour, backgroudColour, s, power);
ptr += s*s*4;
}
return image;
#endif
}
SiltEffect::SiltEffect()
{
setNumChildrenRequiringUpdateTraversal(1);
setUpGeometries(1024);
setIntensity(0.5);
}
void SiltEffect::setIntensity(float intensity)
{
_wind.set(0.0f,0.0f,0.0f);
_particleSpeed = -0.75f - 0.25f*intensity;
_particleSize = 0.02f + 0.03f*intensity;
_particleColor = osg::Vec4(0.85f, 0.85f, 0.85f, 1.0f) - osg::Vec4(0.1f, 0.1f, 0.1f, 1.0f)* intensity;
_maximumParticleDensity = intensity * 8.2f;
_cellSize.set(5.0f / (0.25f+intensity), 5.0f / (0.25f+intensity), 5.0f);
_nearTransition = 25.f;
_farTransition = 100.0f - 60.0f*sqrtf(intensity);
if (!_fog) _fog = new osg::Fog;
_fog->setMode(osg::Fog::EXP);
_fog->setDensity(0.01f*intensity);
_fog->setColor(osg::Vec4(0.6, 0.6, 0.6, 1.0));
_dirty = true;
update();
}
SiltEffect::SiltEffect(const SiltEffect& copy, const osg::CopyOp& copyop):
osg::Node(copy,copyop)
{
setNumChildrenRequiringUpdateTraversal(getNumChildrenRequiringUpdateTraversal()+1);
_dirty = true;
update();
}
void SiltEffect::compileGLObjects(osg::RenderInfo& renderInfo) const
{
if (_quadGeometry.valid())
{
_quadGeometry->compileGLObjects(renderInfo);
if (_quadGeometry->getStateSet()) _quadGeometry->getStateSet()->compileGLObjects(*renderInfo.getState());
}
if (_pointGeometry.valid())
{
_pointGeometry->compileGLObjects(renderInfo);
if (_pointGeometry->getStateSet()) _pointGeometry->getStateSet()->compileGLObjects(*renderInfo.getState());
}
}
void SiltEffect::traverse(osg::NodeVisitor& nv)
{
if (nv.getVisitorType() == osg::NodeVisitor::UPDATE_VISITOR)
{
if (_dirty) update();
if (nv.getFrameStamp())
{
double currentTime = nv.getFrameStamp()->getSimulationTime();
static double previousTime = currentTime;
double delta = currentTime - previousTime;
_origin += _wind * delta;
previousTime = currentTime;
}
return;
}
if (nv.getVisitorType() == osg::NodeVisitor::NODE_VISITOR)
{
if (_dirty) update();
osgUtil::GLObjectsVisitor* globjVisitor = dynamic_cast<osgUtil::GLObjectsVisitor*>(&nv);
if (globjVisitor)
{
if (globjVisitor->getMode() & osgUtil::GLObjectsVisitor::COMPILE_STATE_ATTRIBUTES)
{
compileGLObjects(globjVisitor->getRenderInfo());
}
}
return;
}
if (nv.getVisitorType() != osg::NodeVisitor::CULL_VISITOR)
{
return;
}
osgUtil::CullVisitor* cv = dynamic_cast<osgUtil::CullVisitor*>(&nv);
if (!cv)
{
return;
}
ViewIdentifier viewIndentifier(cv, nv.getNodePath());
{
SiltDrawableSet* SiltDrawableSet = 0;
{
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);
SiltDrawableSet = &(_viewDrawableMap[viewIndentifier]);
if (!SiltDrawableSet->_quadSiltDrawable)
{
SiltDrawableSet->_quadSiltDrawable = new SiltDrawable;
SiltDrawableSet->_quadSiltDrawable->setGeometry(_quadGeometry.get());
SiltDrawableSet->_quadSiltDrawable->setStateSet(_quadStateSet.get());
SiltDrawableSet->_quadSiltDrawable->setDrawType(GL_QUADS);
SiltDrawableSet->_pointSiltDrawable = new SiltDrawable;
SiltDrawableSet->_pointSiltDrawable->setGeometry(_pointGeometry.get());
SiltDrawableSet->_pointSiltDrawable->setStateSet(_pointStateSet.get());
SiltDrawableSet->_pointSiltDrawable->setDrawType(GL_POINTS);
}
}
cull(*SiltDrawableSet, cv);
cv->pushStateSet(_stateset.get());
float depth = 0.0f;
if (!SiltDrawableSet->_quadSiltDrawable->getCurrentCellMatrixMap().empty())
{
cv->pushStateSet(SiltDrawableSet->_quadSiltDrawable->getStateSet());
cv->addDrawableAndDepth(SiltDrawableSet->_quadSiltDrawable.get(),cv->getModelViewMatrix(),depth);
cv->popStateSet();
}
if (!SiltDrawableSet->_pointSiltDrawable->getCurrentCellMatrixMap().empty())
{
cv->pushStateSet(SiltDrawableSet->_pointSiltDrawable->getStateSet());
cv->addDrawableAndDepth(SiltDrawableSet->_pointSiltDrawable.get(),cv->getModelViewMatrix(),depth);
cv->popStateSet();
}
cv->popStateSet();
}
}
void SiltEffect::update()
{
_dirty = false;
osg::notify(osg::INFO)<<"SiltEffect::update()"<<std::endl;
float length_u = _cellSize.x();
float length_v = _cellSize.y();
float length_w = _cellSize.z();
// time taken to get from start to the end of cycle
_period = fabsf(_cellSize.z() / _particleSpeed);
_du.set(length_u, 0.0f, 0.0f);
_dv.set(0.0f, length_v, 0.0f);
_dw.set(0.0f, 0.0f, length_w);
_inverse_du.set(1.0f/length_u, 0.0f, 0.0f);
_inverse_dv.set(0.0f, 1.0f/length_v, 0.0f);
_inverse_dw.set(0.0f, 0.0f, 1.0f/length_w);
osg::notify(osg::INFO)<<"Cell size X="<<length_u<<std::endl;
osg::notify(osg::INFO)<<"Cell size Y="<<length_v<<std::endl;
osg::notify(osg::INFO)<<"Cell size Z="<<length_w<<std::endl;
{
OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);
_viewDrawableMap.clear();
}
// set up state/
{
if (!_stateset)
{
_stateset = new osg::StateSet;
_stateset->addUniform(new osg::Uniform("osgOcean_BaseTexture",0));
_stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
_stateset->setMode(GL_BLEND, osg::StateAttribute::ON);
osg::Texture2D* texture = new osg::Texture2D(createSpotLightImage(osg::Vec4(0.55f,0.55f,0.55f,0.65f),osg::Vec4(0.55f,0.55f,0.55f,0.0f),32,1.0));
_stateset->setTextureAttribute(0, texture);
}
if (!_inversePeriodUniform)
{
_inversePeriodUniform = new osg::Uniform("osgOcean_InversePeriod",1.0f/_period);
_stateset->addUniform(_inversePeriodUniform.get());
}
else _inversePeriodUniform->set(1.0f/_period);
if (!_particleColorUniform)
{
_particleColorUniform = new osg::Uniform("osgOcean_ParticleColour", _particleColor);
_stateset->addUniform(_particleColorUniform.get());
}
else _particleColorUniform->set(_particleColor);
if (!_particleSizeUniform)
{
_particleSizeUniform = new osg::Uniform("osgOcean_ParticleSize", _particleSize);
_stateset->addUniform(_particleSizeUniform.get());
}
else
_particleSizeUniform->set(_particleSize);
}
}
void SiltEffect::createGeometry(unsigned int numParticles,
osg::Geometry* quad_geometry,
osg::Geometry* point_geometry )
{
// particle corner offsets
osg::Vec2 offset00(0.0f,0.0f);
osg::Vec2 offset10(1.0f,0.0f);
osg::Vec2 offset01(0.0f,1.0f);
osg::Vec2 offset11(1.0f,1.0f);
osg::Vec2 offset0(0.5f,0.0f);
osg::Vec2 offset1(0.5f,1.0f);
osg::Vec2 offset(0.5f,0.5f);
// configure quad_geometry;
osg::Vec3Array* quad_vertices = 0;
osg::Vec2Array* quad_offsets = 0;
osg::Vec3Array* quad_vectors = 0;
if (quad_geometry)
{
quad_geometry->setName("quad");
quad_vertices = new osg::Vec3Array(numParticles*4);
quad_offsets = new osg::Vec2Array(numParticles*4);
quad_vectors = new osg::Vec3Array(numParticles*4);
quad_geometry->setVertexArray(quad_vertices);
quad_geometry->setTexCoordArray(0, quad_offsets);
quad_geometry->setNormalArray(quad_vectors);
quad_geometry->setNormalBinding(osg::Geometry::BIND_PER_VERTEX);
}
// configure point_geometry;
osg::Vec3Array* point_vertices = 0;
osg::Vec2Array* point_offsets = 0;
osg::Vec3Array* point_vectors = 0;
if (point_geometry)
{
point_geometry->setName("point");
point_vertices = new osg::Vec3Array(numParticles);
point_offsets = new osg::Vec2Array(numParticles);
point_vectors = new osg::Vec3Array(numParticles);
point_geometry->setVertexArray(point_vertices);
point_geometry->setTexCoordArray(0, point_offsets);
point_geometry->setNormalArray(point_vectors);
point_geometry->setNormalBinding(osg::Geometry::BIND_PER_VERTEX);
}
// set up vertex attribute data.
for(unsigned int i=0; i< numParticles; ++i)
{
osg::Vec3 pos( random(0.0f, 1.0f), random(0.0f, 1.0f), random(0.0f, 1.0f));
osg::Vec3 dir( random(-1.f, 1.f), random(-1.f,1.f), random(-1.f,1.f) );
// quad particles
if (quad_vertices)
{
(*quad_vertices)[i*4] = pos;
(*quad_vertices)[i*4+1] = pos;
(*quad_vertices)[i*4+2] = pos;
(*quad_vertices)[i*4+3] = pos;
(*quad_offsets)[i*4] = offset00;
(*quad_offsets)[i*4+1] = offset01;
(*quad_offsets)[i*4+2] = offset11;
(*quad_offsets)[i*4+3] = offset10;
(*quad_vectors)[i*4] = dir;
(*quad_vectors)[i*4+1] = dir;
(*quad_vectors)[i*4+2] = dir;
(*quad_vectors)[i*4+3] = dir;
}
// point particles
if (point_vertices)
{
(*point_vertices)[i] = pos;
(*point_offsets)[i] = offset;
(*point_vectors)[i] = dir;
}
}
}
#include <osgOcean/shaders/osgOcean_silt_quads_vert.inl>
#include <osgOcean/shaders/osgOcean_silt_quads_frag.inl>
#include <osgOcean/shaders/osgOcean_silt_points_vert.inl>
#include <osgOcean/shaders/osgOcean_silt_points_frag.inl>
void SiltEffect::setUpGeometries(unsigned int numParticles)
{
unsigned int quadRenderBin = 12;
unsigned int pointRenderBin = 11;
osg::notify(osg::INFO)<<"SiltEffect::setUpGeometries("<<numParticles<<")"<<std::endl;
bool needGeometryRebuild = false;
if (!_quadGeometry || _quadGeometry->getVertexArray()->getNumElements() != 4*numParticles)
{
_quadGeometry = new osg::Geometry;
_quadGeometry->setUseVertexBufferObjects(true);
needGeometryRebuild = true;
}
if (!_pointGeometry || _pointGeometry->getVertexArray()->getNumElements() != numParticles)
{
_pointGeometry = new osg::Geometry;
_pointGeometry->setUseVertexBufferObjects(true);
needGeometryRebuild = true;
}
if (needGeometryRebuild)
{
createGeometry(numParticles, _quadGeometry.get(), _pointGeometry.get());
}
if (!_quadStateSet)
{
_quadStateSet = new osg::StateSet;
_quadStateSet->setRenderBinDetails(quadRenderBin,"DepthSortedBin");
static const char osgOcean_silt_quads_vert_file[] = "osgOcean/shaders/osgOcean_silt_quads.vert";
static const char osgOcean_silt_quads_frag_file[] = "osgOcean/shaders/osgOcean_silt_quads.frag";
osg::Program* program =
ShaderManager::instance().createProgram("silt_quads",
osgOcean_silt_quads_vert_file, osgOcean_silt_quads_frag_file,
osgOcean_silt_quads_vert, osgOcean_silt_quads_frag );
_quadStateSet->setAttribute(program);
}
if (!_pointStateSet)
{
_pointStateSet = new osg::StateSet;
static const char osgOcean_silt_points_vert_file[] = "osgOcean/shaders/osgOcean_silt_points.vert";
static const char osgOcean_silt_points_frag_file[] = "osgOcean/shaders/osgOcean_silt_points.frag";
osg::Program* program =
ShaderManager::instance().createProgram("silt_point",
osgOcean_silt_points_vert_file, osgOcean_silt_points_frag_file,
osgOcean_silt_points_vert, osgOcean_silt_points_frag );
_pointStateSet->setAttribute(program);
/// Setup the point sprites
osg::PointSprite *sprite = new osg::PointSprite();
_pointStateSet->setTextureAttributeAndModes(0, sprite, osg::StateAttribute::ON);
_pointStateSet->setMode(GL_VERTEX_PROGRAM_POINT_SIZE, osg::StateAttribute::ON);
_pointStateSet->setRenderBinDetails(pointRenderBin,"DepthSortedBin");
}
}
void SiltEffect::cull(SiltDrawableSet& pds, osgUtil::CullVisitor* cv) const
{
#ifdef DO_TIMING
osg::Timer_t startTick = osg::Timer::instance()->tick();
#endif
float cellVolume = _cellSize.x() * _cellSize.y() * _cellSize.z();
int numberOfParticles = (int)(_maximumParticleDensity * cellVolume);
if (numberOfParticles==0)
return;
pds._quadSiltDrawable->setNumberOfVertices(numberOfParticles*4);
pds._pointSiltDrawable->setNumberOfVertices(numberOfParticles);
pds._quadSiltDrawable->newFrame();
pds._pointSiltDrawable->newFrame();
osg::Matrix inverse_modelview;
inverse_modelview.invert(*(cv->getModelViewMatrix()));
osg::Vec3 eyeLocal = osg::Vec3(0.0f,0.0f,0.0f) * inverse_modelview;
//osg::notify(osg::NOTICE)<<" eyeLocal "<<eyeLocal<<std::endl;
float eye_k = (eyeLocal-_origin)*_inverse_dw;
osg::Vec3 eye_kPlane = eyeLocal-_dw*eye_k-_origin;
// osg::notify(osg::NOTICE)<<" eye_kPlane "<<eye_kPlane<<std::endl;
float eye_i = eye_kPlane*_inverse_du;
float eye_j = eye_kPlane*_inverse_dv;
osg::Polytope frustum;
frustum.setToUnitFrustum(false,false);
frustum.transformProvidingInverse(*(cv->getProjectionMatrix()));
frustum.transformProvidingInverse(*(cv->getModelViewMatrix()));
float i_delta = _farTransition * _inverse_du.x();
float j_delta = _farTransition * _inverse_dv.y();
float k_delta = 1;//_nearTransition * _inverse_dw.z();
int i_min = (int)floor(eye_i - i_delta);
int j_min = (int)floor(eye_j - j_delta);
int k_min = (int)floor(eye_k - k_delta);
int i_max = (int)ceil(eye_i + i_delta);
int j_max = (int)ceil(eye_j + j_delta);
int k_max = (int)ceil(eye_k + k_delta);
//osg::notify(osg::NOTICE)<<"i_delta="<<i_delta<<" j_delta="<<j_delta<<" k_delta="<<k_delta<<std::endl;
unsigned int numTested=0;
unsigned int numInFrustum=0;
float iCyle = 0.43;
float jCyle = 0.64;
for(int i = i_min; i<=i_max; ++i)
{
for(int j = j_min; j<=j_max; ++j)
{
for(int k = k_min; k<=k_max; ++k)
{
float startTime = (float)(i)*iCyle + (float)(j)*jCyle;
startTime = (startTime-floor(startTime))*_period;
if (build(eyeLocal, i,j,k, startTime, pds, frustum, cv))
++numInFrustum;
++numTested;
}
}
}
#ifdef DO_TIMING
osg::Timer_t endTick = osg::Timer::instance()->tick();
osg::notify(osg::NOTICE)<<"time for cull "<<osg::Timer::instance()->delta_m(startTick,endTick)<<"ms numTested= "<<numTested<<" numInFrustum= "<<numInFrustum<<std::endl;
osg::notify(osg::NOTICE)<<" quads "<<pds._quadSiltDrawable->getCurrentCellMatrixMap().size()<<" points "<<pds._pointSiltDrawable->getCurrentCellMatrixMap().size()<<std::endl;
#endif
}
bool SiltEffect::build(const osg::Vec3 eyeLocal, int i, int j, int k, float startTime, SiltDrawableSet& pds, osg::Polytope& frustum, osgUtil::CullVisitor* cv) const
{
osg::Vec3 position = _origin + osg::Vec3(float(i)*_du.x(), float(j)*_dv.y(), float(k+1)*_dw.z());
osg::Vec3 scale(_du.x(), _dv.y(), -_dw.z());
osg::BoundingBox bb(position.x(), position.y(), position.z()+scale.z(),
position.x()+scale.x(), position.y()+scale.y(), position.z());
if ( !frustum.contains(bb) )
return false;
osg::Vec3 center = position + scale*0.5f;
float distance = (center-eyeLocal).length();
osg::Matrix* mymodelview = 0;
if (distance < _nearTransition)
{
SiltDrawable::DepthMatrixStartTime& mstp
= pds._quadSiltDrawable->getCurrentCellMatrixMap()[SiltDrawable::Cell(i,k,j)];
mstp.depth = distance;
mstp.startTime = startTime;
mymodelview = &mstp.modelview;
}
else if (distance <= _farTransition)
{
SiltDrawable::DepthMatrixStartTime& mstp
= pds._pointSiltDrawable->getCurrentCellMatrixMap()[SiltDrawable::Cell(i,k,j)];
mstp.depth = distance;
mstp.startTime = startTime;
mymodelview = &mstp.modelview;
}
else
{
return false;
}
*mymodelview = *(cv->getModelViewMatrix());
#if OPENSCENEGRAPH_MAJOR_VERSION > 2 || \
(OPENSCENEGRAPH_MAJOR_VERSION == 2 && OPENSCENEGRAPH_MINOR_VERSION > 7) || \
(OPENSCENEGRAPH_MAJOR_VERSION == 2 && OPENSCENEGRAPH_MINOR_VERSION == 7 && OPENSCENEGRAPH_PATCH_VERSION >= 3)
// preMultTranslate and preMultScale introduced in rev 8868, which was
// before OSG 2.7.3.
mymodelview->preMultTranslate(position);
mymodelview->preMultScale(scale);
#else
// Otherwise use unoptimized versions
mymodelview->preMult(osg::Matrix::translate(position));
mymodelview->preMult(osg::Matrix::scale(scale));
#endif
cv->updateCalculatedNearFar(*(cv->getModelViewMatrix()),bb);
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Precipitation Drawable
//
////////////////////////////////////////////////////////////////////////////////////////////////////
SiltEffect::SiltDrawable::SiltDrawable():
_drawType(GL_QUADS),
_numberOfVertices(0)
{
setSupportsDisplayList(false);
}
SiltEffect::SiltDrawable::SiltDrawable(const SiltDrawable& copy, const osg::CopyOp& copyop):
osg::Drawable(copy,copyop),
_geometry(copy._geometry),
_drawType(copy._drawType),
_numberOfVertices(copy._numberOfVertices)
{
}
void SiltEffect::SiltDrawable::drawImplementation(osg::RenderInfo& renderInfo) const
{
if (!_geometry) return;
const osg::Geometry::Extensions* extensions = osg::Geometry::getExtensions(renderInfo.getContextID(),true);
glPushMatrix();
typedef std::vector<const CellMatrixMap::value_type*> DepthMatrixStartTimeVector;
DepthMatrixStartTimeVector orderedEntries;
orderedEntries.reserve(_currentCellMatrixMap.size());
for(CellMatrixMap::const_iterator citr = _currentCellMatrixMap.begin();
citr != _currentCellMatrixMap.end();
++citr)
{
orderedEntries.push_back(&(*citr));
}
std::sort(orderedEntries.begin(),orderedEntries.end(),LessFunctor());
for(DepthMatrixStartTimeVector::reverse_iterator itr = orderedEntries.rbegin();
itr != orderedEntries.rend();
++itr)
{
extensions->glMultiTexCoord1f(GL_TEXTURE0+1, (*itr)->second.startTime);
glMatrixMode( GL_MODELVIEW );
glLoadMatrix((*itr)->second.modelview.ptr());
_geometry->draw(renderInfo);
unsigned int numVertices = osg::minimum(_geometry->getVertexArray()->getNumElements(), _numberOfVertices);
glDrawArrays(_drawType, 0, numVertices);
}
glPopMatrix();
}
| onox/osgocean | src/osgOcean/SiltEffect.cpp | C++ | lgpl-3.0 | 23,252 |
/**
* Copyright (C) 2005-2015 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
/**
*
* @module alfresco/search/FacetFilter
* @extends external:dijit/_WidgetBase
* @mixes external:dojo/_TemplatedMixin
* @mixes module:alfresco/core/Core
* @mixes module:alfresco/documentlibrary/_AlfDocumentListTopicMixin
* @author Dave Draper
*/
define(["dojo/_base/declare",
"dijit/_WidgetBase",
"dijit/_TemplatedMixin",
"dijit/_OnDijitClickMixin",
"dojo/text!./templates/FacetFilter.html",
"alfresco/core/Core",
"dojo/_base/lang",
"dojo/_base/array",
"dojo/dom-construct",
"dojo/dom-class",
"dojo/on",
"alfresco/util/hashUtils",
"dojo/io-query",
"alfresco/core/ArrayUtils"],
function(declare, _WidgetBase, _TemplatedMixin, _OnDijitClickMixin, template, AlfCore, lang, array, domConstruct, domClass, on, hashUtils, ioQuery, arrayUtils) {
return declare([_WidgetBase, _TemplatedMixin, AlfCore], {
/**
* An array of the i18n files to use with this widget.
*
* @instance
* @type {object[]}
* @default [{i18nFile: "./i18n/FacetFilter.properties"}]
*/
i18nRequirements: [{i18nFile: "./i18n/FacetFilter.properties"}],
/**
* An array of the CSS files to use with this widget.
*
* @instance cssRequirements {Array}
* @type {object[]}
* @default [{cssFile:"./css/FacetFilter.css"}]
*/
cssRequirements: [{cssFile:"./css/FacetFilter.css"}],
/**
* The HTML template to use for the widget.
* @instance
* @type {string}
*/
templateString: template,
/**
* Indicate whether or not the filter is currently applied
*
* @instance
* @type {boolean}
* @default
*/
applied: false,
/**
* The alt-text to use for the image that indicates that a filter has been applied
*
* @instance
* @type {string}
* @default
*/
appliedFilterAltText: "facet.filter.applied.alt-text",
/**
* The path to use as the source for the image that indicates that a filter has been applied
*
* @instance
* @type {string}
* @default
*/
appliedFilterImageSrc: "12x12-selected-icon.png",
/**
* The facet qname
*
* @instance
* @type {string}
* @default
*/
facet: null,
/**
* The filter (or more accurately the filterId) for this filter
*
* @instance
* @type {string}
* @default
*/
filter: null,
/**
* Additional data for the filter (appended after the filter with a bar, e.g. tag|sometag)
*
* @instance
* @type {string}
* @default
*/
filterData: "",
/**
* Indicates that the filter should be hidden. This will be set to "true" if any required data is missing
*
* @instance
* @type {boolean}
* @default
*/
hide: false,
/**
* When this is set to true the current URL hash fragment will be used to initialise the facet selection
* and when the facet is selected the hash fragment will be updated with the facet selection.
*
* @instance
* @type {boolean}
* @default
*/
useHash: false,
/**
* Sets up the attributes required for the HTML template.
* @instance
*/
postMixInProperties: function alfresco_search_FacetFilter__postMixInProperties() {
if (this.label && this.facet && this.filter && this.hits)
{
this.label = this.message(this.label);
// Localize the alt-text for the applied filter message...
this.appliedFilterAltText = this.message(this.appliedFilterAltText, {0: this.label});
// Set the source for the image to use to indicate that a filter is applied...
this.appliedFilterImageSrc = require.toUrl("alfresco/search") + "/css/images/" + this.appliedFilterImageSrc;
}
else
{
// Hide the filter if there is no label or no link...
this.alfLog("warn", "Not enough information provided for filter. It will not be displayed", this);
this.hide = true;
}
},
/**
* @instance
*/
postCreate: function alfresco_search_FacetFilter__postCreate() {
if (this.hide === true)
{
domClass.add(this.domNode, "hidden");
}
if (this.applied)
{
domClass.remove(this.removeNode, "hidden");
domClass.add(this.labelNode, "applied");
}
},
/**
* If the filter has previously been applied then it is removed, if the filter is not applied
* then it is applied.
*
* @instance
*/
onToggleFilter: function alfresco_search_FacetFilter__onToggleFilter(/*jshint unused:false*/ evt) {
if (this.applied)
{
this.onClearFilter();
}
else
{
this.onApplyFilter();
}
},
/**
* Applies the current filter by publishing the details of the filter along with the facet to
* which it belongs and then displays the "applied" image.
*
* @instance
*/
onApplyFilter: function alfresco_search_FacetFilter__onApplyFilter() {
var fullFilter = this.facet + "|" + this.filter;
if(this.useHash)
{
this._updateHash(fullFilter, "add");
}
else
{
this.alfPublish("ALF_APPLY_FACET_FILTER", {
filter: fullFilter
});
}
domClass.remove(this.removeNode, "hidden");
domClass.add(this.labelNode, "applied");
this.applied = true;
},
/**
* Removes the current filter by publishing the details of the filter along with the facet
* to which it belongs and then hides the "applied" image
*
* @instance
*/
onClearFilter: function alfresco_search_FacetFilter__onClearFilter() {
var fullFilter = this.facet + "|" + this.filter;
if(this.useHash)
{
this._updateHash(fullFilter, "remove");
}
else
{
this.alfPublish("ALF_REMOVE_FACET_FILTER", {
filter: fullFilter
});
}
domClass.add(this.removeNode, "hidden");
domClass.remove(this.labelNode, "applied");
this.applied = false;
},
/**
* Performs updates to the url hash as facets are selected and de-selected
*
* @instance
*/
_updateHash: function alfresco_search_FacetFilter___updateHash(fullFilter, mode) {
// Get the existing hash and extract the individual facetFilters into an array
var aHash = hashUtils.getHash(),
facetFilters = ((aHash.facetFilters) ? aHash.facetFilters : ""),
facetFiltersArr = (facetFilters === "") ? [] : facetFilters.split(",");
// Add or remove the filter from the hash object
if(mode === "add" && !arrayUtils.arrayContains(facetFiltersArr, fullFilter))
{
facetFiltersArr.push(fullFilter);
}
else if (mode === "remove" && arrayUtils.arrayContains(facetFiltersArr, fullFilter))
{
facetFiltersArr.splice(facetFiltersArr.indexOf(fullFilter), 1);
}
// Put the manipulated filters back into the hash object or remove the property if empty
if(facetFiltersArr.length < 1)
{
delete aHash.facetFilters;
}
else
{
aHash.facetFilters = facetFiltersArr.join();
}
// Send the hash value back to navigation
this.alfPublish("ALF_NAVIGATE_TO_PAGE", {
url: ioQuery.objectToQuery(aHash),
type: "HASH"
}, true);
}
});
}); | nzheyuti/Aikau | aikau/src/main/resources/alfresco/search/FacetFilter.js | JavaScript | lgpl-3.0 | 8,856 |
<?php
/**
* This file is part of Goodahead_Core extension
*
* This extension is supplied with every Goodahead extension and provide common
* features, used by Goodahead extensions.
*
* Copyright (C) 2013 Goodahead Ltd. (http://www.goodahead.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* and GNU General Public License along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*
* @category Goodahead
* @package Goodahead_Core
* @copyright Copyright (c) 2013 Goodahead Ltd. (http://www.goodahead.com)
* @license http://www.gnu.org/licenses/lgpl-3.0-standalone.html
*/
class Goodahead_Core_Model_Resource_Cms_Update_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
{
protected function _construct()
{
$this->_init('goodahead_core/cms_update');
return $this;
}
} | goodahead/core | Goodahead_Core/app/code/community/Goodahead/Core/Model/Resource/Cms/Update/Collection.php | PHP | lgpl-3.0 | 1,396 |
/******************************************************************************/
/* */
/* EntityCollection.hpp */
/* */
/* Copyright (C) 2015, Joseph Andrew Staedelin IV */
/* */
/* This file is part of the FastGdk project. */
/* */
/* The FastGdk is free software: you can redistribute it and/or modify */
/* it under the terms of the GNU Lesser General Public License as published */
/* by the Free Software Foundation, either version 3 of the License, or */
/* (at your option) any later version. */
/* */
/* The FastGdk is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU Lesser General Public License for more details. */
/* */
/* You should have received a copy of the GNU Lesser General Public License */
/* along with the FastGdk. If not, see <http://www.gnu.org/licenses/>. */
/* */
/******************************************************************************/
#ifndef FastEntityCollectionHppIncluded
#define FastEntityCollectionHppIncluded
#include <Fast/Types.hpp>
#include <Fast/Array.hpp>
#include <Fast/EntityEntry.hpp>
namespace Fast
{
class GraphicsContext;
class PhysicsScene;
class Entity;
template class FastApi Array<EntityEntry>;
class FastApi EntityCollection
{
private:
PhysicsScene &mPhysicsScene;
Array<EntityEntry> mEntityEntries;
// Hide these functions. No copying collections!
EntityCollection(const EntityCollection &that)
: mPhysicsScene(that.mPhysicsScene)
{}
EntityCollection& operator=(const EntityCollection &that)
{ return *this; }
public:
// (Con/De)structors
EntityCollection(PhysicsScene *physicsScene);
~EntityCollection();
// Entity functions
Int AddEntity(Entity *entity);
void RemoveEntity(Int id);
void RemoveAllEntities();
Entity* GetEntity(Int id);
const Entity& GetEntity(Int id) const;
PhysicsScene* GetPhysicsScene();
const PhysicsScene& GetPhysicsScene() const;
void Update(Long deltaTimeMicroseconds);
void Draw();
};
}
#endif // FastEntityCollectionHppIncluded
| JSandrew4/FastGdk | include/Fast/EntityCollection.hpp | C++ | lgpl-3.0 | 2,905 |
<?php
$oForm=new plugin_form($this->oAdresse);
$oForm->setMessage($this->tMessage);
?>
<form class="form-horizontal" action="" method="POST" >
<div class="form-group">
<label class="col-sm-2 control-label">rue</label>
<div class="col-sm-10"><?php echo $oForm->getInputText('rue',array('class'=>'form-control')) ?></div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">ville</label>
<div class="col-sm-10"><?php echo $oForm->getInputText('ville',array('class'=>'form-control')) ?></div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">pays</label>
<div class="col-sm-10"><?php echo $oForm->getInputText('pays',array('class'=>'form-control')) ?></div>
</div>
<?php echo $oForm->getToken('token',$this->token)?>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" class="btn btn-success" value="Ajouter" /> <a class="btn btn-link" href="<?php echo $this->getLink('adresse::list')?>">Annuler</a>
</div>
</div>
</form>
| totobill/CadosProject | data/genere/proj/module/adresse/view/new.php | PHP | lgpl-3.0 | 1,034 |
<import resource="classpath:alfresco/site-webscripts/org/alfresco/callutils.js">
if (!json.isNull("wikipage"))
{
var wikipage = String(json.get("wikipage"));
model.pagecontent = getPageText(wikipage);
model.title = wikipage.replace(/_/g, " ");
}
else
{
model.pagecontent = "<h3>" + msg.get("message.nopage") + "</h3>";
model.title = "";
}
function getPageText(wikipage)
{
var c = sitedata.getComponent(url.templateArgs.componentId);
c.properties["wikipage"] = wikipage;
c.save();
var siteId = String(json.get("siteId"));
var uri = "/slingshot/wiki/page/" + siteId + "/" + encodeURIComponent(wikipage) + "?format=mediawiki";
var connector = remote.connect("alfresco");
var result = connector.get(uri);
if (result.status == status.STATUS_OK)
{
/**
* Always strip unsafe tags here.
* The config to option this is currently webscript-local elsewhere, so this is the safest option
* until the config can be moved to share-config scope in a future version.
*/
return stringUtils.stripUnsafeHTML(result.response);
}
else
{
return "";
}
} | loftuxab/community-edition-old | projects/slingshot/config/alfresco/site-webscripts/org/alfresco/modules/wiki/config-wiki.post.json.js | JavaScript | lgpl-3.0 | 1,134 |
package org.eso.ias.plugin;
/**
* The exception returned by the Plugin
* @author acaproni
*
*/
public class PluginException extends Exception {
public PluginException() {
}
public PluginException(String message) {
super(message);
}
public PluginException(Throwable cause) {
super(cause);
}
public PluginException(String message, Throwable cause) {
super(message, cause);
}
public PluginException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
| IntegratedAlarmSystem-Group/ias | plugin/src/main/java/org/eso/ias/plugin/PluginException.java | Java | lgpl-3.0 | 581 |
package clearvolume.renderer;
/**
* Overlays that implement this interface can declare a key binding that will be
* used to toggle it's display on/off
*
* @author Loic Royer (2015)
*
*/
public interface SingleKeyToggable
{
/**
* Returns key code of toggle key combination.
*
* @return toggle key as short code.
*/
public short toggleKeyCode();
/**
* Returns modifier of toggle key combination.
*
* @return toggle key as short code.
*/
public int toggleKeyModifierMask();
/**
* Toggle on/off
*
* @return new state
*/
public boolean toggle();
}
| ClearVolume/ClearVolume | src/java/clearvolume/renderer/SingleKeyToggable.java | Java | lgpl-3.0 | 587 |
// Copyright 2020 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package abi
import (
"math/big"
"github.com/matthieu/go-ethereum/common"
)
type packUnpackTest struct {
def string
unpacked interface{}
packed string
}
var packUnpackTests = []packUnpackTest{
// Booleans
{
def: `[{ "type": "bool" }]`,
packed: "0000000000000000000000000000000000000000000000000000000000000001",
unpacked: true,
},
{
def: `[{ "type": "bool" }]`,
packed: "0000000000000000000000000000000000000000000000000000000000000000",
unpacked: false,
},
// Integers
{
def: `[{ "type": "uint8" }]`,
unpacked: uint8(2),
packed: "0000000000000000000000000000000000000000000000000000000000000002",
},
{
def: `[{ "type": "uint8[]" }]`,
unpacked: []uint8{1, 2},
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
},
{
def: `[{ "type": "uint16" }]`,
unpacked: uint16(2),
packed: "0000000000000000000000000000000000000000000000000000000000000002",
},
{
def: `[{ "type": "uint16[]" }]`,
unpacked: []uint16{1, 2},
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
},
{
def: `[{"type": "uint17"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000001",
unpacked: big.NewInt(1),
},
{
def: `[{"type": "uint32"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000001",
unpacked: uint32(1),
},
{
def: `[{"type": "uint32[]"}]`,
unpacked: []uint32{1, 2},
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
},
{
def: `[{"type": "uint64"}]`,
unpacked: uint64(2),
packed: "0000000000000000000000000000000000000000000000000000000000000002",
},
{
def: `[{"type": "uint64[]"}]`,
unpacked: []uint64{1, 2},
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
},
{
def: `[{"type": "uint256"}]`,
unpacked: big.NewInt(2),
packed: "0000000000000000000000000000000000000000000000000000000000000002",
},
{
def: `[{"type": "uint256[]"}]`,
unpacked: []*big.Int{big.NewInt(1), big.NewInt(2)},
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
},
{
def: `[{"type": "int8"}]`,
unpacked: int8(2),
packed: "0000000000000000000000000000000000000000000000000000000000000002",
},
{
def: `[{"type": "int8[]"}]`,
unpacked: []int8{1, 2},
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
},
{
def: `[{"type": "int16"}]`,
unpacked: int16(2),
packed: "0000000000000000000000000000000000000000000000000000000000000002",
},
{
def: `[{"type": "int16[]"}]`,
unpacked: []int16{1, 2},
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
},
{
def: `[{"type": "int17"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000001",
unpacked: big.NewInt(1),
},
{
def: `[{"type": "int32"}]`,
unpacked: int32(2),
packed: "0000000000000000000000000000000000000000000000000000000000000002",
},
{
def: `[{"type": "int32"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000001",
unpacked: int32(1),
},
{
def: `[{"type": "int32[]"}]`,
unpacked: []int32{1, 2},
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
},
{
def: `[{"type": "int64"}]`,
unpacked: int64(2),
packed: "0000000000000000000000000000000000000000000000000000000000000002",
},
{
def: `[{"type": "int64[]"}]`,
unpacked: []int64{1, 2},
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
},
{
def: `[{"type": "int256"}]`,
unpacked: big.NewInt(2),
packed: "0000000000000000000000000000000000000000000000000000000000000002",
},
{
def: `[{"type": "int256"}]`,
packed: "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
unpacked: big.NewInt(-1),
},
{
def: `[{"type": "int256[]"}]`,
unpacked: []*big.Int{big.NewInt(1), big.NewInt(2)},
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
},
// Address
{
def: `[{"type": "address"}]`,
packed: "0000000000000000000000000100000000000000000000000000000000000000",
unpacked: common.Address{1},
},
{
def: `[{"type": "address[]"}]`,
unpacked: []common.Address{{1}, {2}},
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000100000000000000000000000000000000000000" +
"0000000000000000000000000200000000000000000000000000000000000000",
},
// Bytes
{
def: `[{"type": "bytes1"}]`,
unpacked: [1]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes2"}]`,
unpacked: [2]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes3"}]`,
unpacked: [3]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes4"}]`,
unpacked: [4]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes5"}]`,
unpacked: [5]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes6"}]`,
unpacked: [6]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes7"}]`,
unpacked: [7]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes8"}]`,
unpacked: [8]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes9"}]`,
unpacked: [9]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes10"}]`,
unpacked: [10]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes11"}]`,
unpacked: [11]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes12"}]`,
unpacked: [12]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes13"}]`,
unpacked: [13]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes14"}]`,
unpacked: [14]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes15"}]`,
unpacked: [15]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes16"}]`,
unpacked: [16]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes17"}]`,
unpacked: [17]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes18"}]`,
unpacked: [18]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes19"}]`,
unpacked: [19]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes20"}]`,
unpacked: [20]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes21"}]`,
unpacked: [21]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes22"}]`,
unpacked: [22]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes23"}]`,
unpacked: [23]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes24"}]`,
unpacked: [24]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes25"}]`,
unpacked: [25]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes26"}]`,
unpacked: [26]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes27"}]`,
unpacked: [27]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes28"}]`,
unpacked: [28]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes29"}]`,
unpacked: [29]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes30"}]`,
unpacked: [30]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes31"}]`,
unpacked: [31]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes32"}]`,
unpacked: [32]byte{1},
packed: "0100000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "bytes32"}]`,
packed: "0100000000000000000000000000000000000000000000000000000000000000",
unpacked: [32]byte{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
},
{
def: `[{"type": "bytes"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000020" +
"0100000000000000000000000000000000000000000000000000000000000000",
unpacked: common.Hex2Bytes("0100000000000000000000000000000000000000000000000000000000000000"),
},
{
def: `[{"type": "bytes32"}]`,
packed: "0100000000000000000000000000000000000000000000000000000000000000",
unpacked: [32]byte{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
},
// Functions
{
def: `[{"type": "function"}]`,
packed: "0100000000000000000000000000000000000000000000000000000000000000",
unpacked: [24]byte{1},
},
// Slice and Array
{
def: `[{"type": "uint8[]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
unpacked: []uint8{1, 2},
},
{
def: `[{"type": "uint8[]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000000",
unpacked: []uint8{},
},
{
def: `[{"type": "uint256[]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000000",
unpacked: []*big.Int{},
},
{
def: `[{"type": "uint8[2]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
unpacked: [2]uint8{1, 2},
},
{
def: `[{"type": "int8[2]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
unpacked: [2]int8{1, 2},
},
{
def: `[{"type": "int16[]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
unpacked: []int16{1, 2},
},
{
def: `[{"type": "int16[2]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
unpacked: [2]int16{1, 2},
},
{
def: `[{"type": "int32[]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
unpacked: []int32{1, 2},
},
{
def: `[{"type": "int32[2]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
unpacked: [2]int32{1, 2},
},
{
def: `[{"type": "int64[]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
unpacked: []int64{1, 2},
},
{
def: `[{"type": "int64[2]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
unpacked: [2]int64{1, 2},
},
{
def: `[{"type": "int256[]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
unpacked: []*big.Int{big.NewInt(1), big.NewInt(2)},
},
{
def: `[{"type": "int256[3]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000003",
unpacked: [3]*big.Int{big.NewInt(1), big.NewInt(2), big.NewInt(3)},
},
// multi dimensional, if these pass, all types that don't require length prefix should pass
{
def: `[{"type": "uint8[][]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000000",
unpacked: [][]uint8{},
},
{
def: `[{"type": "uint8[][]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000040" +
"00000000000000000000000000000000000000000000000000000000000000a0" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
unpacked: [][]uint8{{1, 2}, {1, 2}},
},
{
def: `[{"type": "uint8[][]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000040" +
"00000000000000000000000000000000000000000000000000000000000000a0" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000003" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000003",
unpacked: [][]uint8{{1, 2}, {1, 2, 3}},
},
{
def: `[{"type": "uint8[2][2]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
unpacked: [2][2]uint8{{1, 2}, {1, 2}},
},
{
def: `[{"type": "uint8[][2]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000040" +
"0000000000000000000000000000000000000000000000000000000000000060" +
"0000000000000000000000000000000000000000000000000000000000000000" +
"0000000000000000000000000000000000000000000000000000000000000000",
unpacked: [2][]uint8{{}, {}},
},
{
def: `[{"type": "uint8[][2]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000040" +
"0000000000000000000000000000000000000000000000000000000000000080" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000001",
unpacked: [2][]uint8{{1}, {1}},
},
{
def: `[{"type": "uint8[2][]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000000",
unpacked: [][2]uint8{},
},
{
def: `[{"type": "uint8[2][]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
unpacked: [][2]uint8{{1, 2}},
},
{
def: `[{"type": "uint8[2][]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
unpacked: [][2]uint8{{1, 2}, {1, 2}},
},
{
def: `[{"type": "uint16[]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
unpacked: []uint16{1, 2},
},
{
def: `[{"type": "uint16[2]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
unpacked: [2]uint16{1, 2},
},
{
def: `[{"type": "uint32[]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
unpacked: []uint32{1, 2},
},
{
def: `[{"type": "uint32[2][3][4]"}]`,
unpacked: [4][3][2]uint32{{{1, 2}, {3, 4}, {5, 6}}, {{7, 8}, {9, 10}, {11, 12}}, {{13, 14}, {15, 16}, {17, 18}}, {{19, 20}, {21, 22}, {23, 24}}},
packed: "0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000003" +
"0000000000000000000000000000000000000000000000000000000000000004" +
"0000000000000000000000000000000000000000000000000000000000000005" +
"0000000000000000000000000000000000000000000000000000000000000006" +
"0000000000000000000000000000000000000000000000000000000000000007" +
"0000000000000000000000000000000000000000000000000000000000000008" +
"0000000000000000000000000000000000000000000000000000000000000009" +
"000000000000000000000000000000000000000000000000000000000000000a" +
"000000000000000000000000000000000000000000000000000000000000000b" +
"000000000000000000000000000000000000000000000000000000000000000c" +
"000000000000000000000000000000000000000000000000000000000000000d" +
"000000000000000000000000000000000000000000000000000000000000000e" +
"000000000000000000000000000000000000000000000000000000000000000f" +
"0000000000000000000000000000000000000000000000000000000000000010" +
"0000000000000000000000000000000000000000000000000000000000000011" +
"0000000000000000000000000000000000000000000000000000000000000012" +
"0000000000000000000000000000000000000000000000000000000000000013" +
"0000000000000000000000000000000000000000000000000000000000000014" +
"0000000000000000000000000000000000000000000000000000000000000015" +
"0000000000000000000000000000000000000000000000000000000000000016" +
"0000000000000000000000000000000000000000000000000000000000000017" +
"0000000000000000000000000000000000000000000000000000000000000018",
},
{
def: `[{"type": "bytes32[]"}]`,
unpacked: []common.Hash{{1}, {2}},
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0100000000000000000000000000000000000000000000000000000000000000" +
"0200000000000000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "uint32[2]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
unpacked: [2]uint32{1, 2},
},
{
def: `[{"type": "uint64[]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
unpacked: []uint64{1, 2},
},
{
def: `[{"type": "uint64[2]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
unpacked: [2]uint64{1, 2},
},
{
def: `[{"type": "uint256[]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
unpacked: []*big.Int{big.NewInt(1), big.NewInt(2)},
},
{
def: `[{"type": "uint256[3]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000003",
unpacked: [3]*big.Int{big.NewInt(1), big.NewInt(2), big.NewInt(3)},
},
{
def: `[{"type": "string[4]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000080" +
"00000000000000000000000000000000000000000000000000000000000000c0" +
"0000000000000000000000000000000000000000000000000000000000000100" +
"0000000000000000000000000000000000000000000000000000000000000140" +
"0000000000000000000000000000000000000000000000000000000000000005" +
"48656c6c6f000000000000000000000000000000000000000000000000000000" +
"0000000000000000000000000000000000000000000000000000000000000005" +
"576f726c64000000000000000000000000000000000000000000000000000000" +
"000000000000000000000000000000000000000000000000000000000000000b" +
"476f2d657468657265756d000000000000000000000000000000000000000000" +
"0000000000000000000000000000000000000000000000000000000000000008" +
"457468657265756d000000000000000000000000000000000000000000000000",
unpacked: [4]string{"Hello", "World", "Go-ethereum", "Ethereum"},
},
{
def: `[{"type": "string[]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000040" +
"0000000000000000000000000000000000000000000000000000000000000080" +
"0000000000000000000000000000000000000000000000000000000000000008" +
"457468657265756d000000000000000000000000000000000000000000000000" +
"000000000000000000000000000000000000000000000000000000000000000b" +
"676f2d657468657265756d000000000000000000000000000000000000000000",
unpacked: []string{"Ethereum", "go-ethereum"},
},
{
def: `[{"type": "bytes[]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000040" +
"0000000000000000000000000000000000000000000000000000000000000080" +
"0000000000000000000000000000000000000000000000000000000000000003" +
"f0f0f00000000000000000000000000000000000000000000000000000000000" +
"0000000000000000000000000000000000000000000000000000000000000003" +
"f0f0f00000000000000000000000000000000000000000000000000000000000",
unpacked: [][]byte{{0xf0, 0xf0, 0xf0}, {0xf0, 0xf0, 0xf0}},
},
{
def: `[{"type": "uint256[2][][]"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000040" +
"00000000000000000000000000000000000000000000000000000000000000e0" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"00000000000000000000000000000000000000000000000000000000000000c8" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"00000000000000000000000000000000000000000000000000000000000003e8" +
"0000000000000000000000000000000000000000000000000000000000000002" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"00000000000000000000000000000000000000000000000000000000000000c8" +
"0000000000000000000000000000000000000000000000000000000000000001" +
"00000000000000000000000000000000000000000000000000000000000003e8",
unpacked: [][][2]*big.Int{{{big.NewInt(1), big.NewInt(200)}, {big.NewInt(1), big.NewInt(1000)}}, {{big.NewInt(1), big.NewInt(200)}, {big.NewInt(1), big.NewInt(1000)}}},
},
// struct outputs
{
def: `[{"name":"int1","type":"int256"},{"name":"int2","type":"int256"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
unpacked: struct {
Int1 *big.Int
Int2 *big.Int
}{big.NewInt(1), big.NewInt(2)},
},
{
def: `[{"name":"int_one","type":"int256"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000001",
unpacked: struct {
IntOne *big.Int
}{big.NewInt(1)},
},
{
def: `[{"name":"int__one","type":"int256"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000001",
unpacked: struct {
IntOne *big.Int
}{big.NewInt(1)},
},
{
def: `[{"name":"int_one_","type":"int256"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000001",
unpacked: struct {
IntOne *big.Int
}{big.NewInt(1)},
},
{
def: `[{"name":"int_one","type":"int256"}, {"name":"intone","type":"int256"}]`,
packed: "0000000000000000000000000000000000000000000000000000000000000001" +
"0000000000000000000000000000000000000000000000000000000000000002",
unpacked: struct {
IntOne *big.Int
Intone *big.Int
}{big.NewInt(1), big.NewInt(2)},
},
{
def: `[{"type": "string"}]`,
unpacked: "foobar",
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000006" +
"666f6f6261720000000000000000000000000000000000000000000000000000",
},
{
def: `[{"type": "string[]"}]`,
unpacked: []string{"hello", "foobar"},
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" + // len(array) = 2
"0000000000000000000000000000000000000000000000000000000000000040" + // offset 64 to i = 0
"0000000000000000000000000000000000000000000000000000000000000080" + // offset 128 to i = 1
"0000000000000000000000000000000000000000000000000000000000000005" + // len(str[0]) = 5
"68656c6c6f000000000000000000000000000000000000000000000000000000" + // str[0]
"0000000000000000000000000000000000000000000000000000000000000006" + // len(str[1]) = 6
"666f6f6261720000000000000000000000000000000000000000000000000000", // str[1]
},
{
def: `[{"type": "string[2]"}]`,
unpacked: [2]string{"hello", "foobar"},
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000040" + // offset to i = 0
"0000000000000000000000000000000000000000000000000000000000000080" + // offset to i = 1
"0000000000000000000000000000000000000000000000000000000000000005" + // len(str[0]) = 5
"68656c6c6f000000000000000000000000000000000000000000000000000000" + // str[0]
"0000000000000000000000000000000000000000000000000000000000000006" + // len(str[1]) = 6
"666f6f6261720000000000000000000000000000000000000000000000000000", // str[1]
},
{
def: `[{"type": "bytes32[][]"}]`,
unpacked: [][][32]byte{{{1}, {2}}, {{3}, {4}, {5}}},
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" + // len(array) = 2
"0000000000000000000000000000000000000000000000000000000000000040" + // offset 64 to i = 0
"00000000000000000000000000000000000000000000000000000000000000a0" + // offset 160 to i = 1
"0000000000000000000000000000000000000000000000000000000000000002" + // len(array[0]) = 2
"0100000000000000000000000000000000000000000000000000000000000000" + // array[0][0]
"0200000000000000000000000000000000000000000000000000000000000000" + // array[0][1]
"0000000000000000000000000000000000000000000000000000000000000003" + // len(array[1]) = 3
"0300000000000000000000000000000000000000000000000000000000000000" + // array[1][0]
"0400000000000000000000000000000000000000000000000000000000000000" + // array[1][1]
"0500000000000000000000000000000000000000000000000000000000000000", // array[1][2]
},
{
def: `[{"type": "bytes32[][2]"}]`,
unpacked: [2][][32]byte{{{1}, {2}}, {{3}, {4}, {5}}},
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000040" + // offset 64 to i = 0
"00000000000000000000000000000000000000000000000000000000000000a0" + // offset 160 to i = 1
"0000000000000000000000000000000000000000000000000000000000000002" + // len(array[0]) = 2
"0100000000000000000000000000000000000000000000000000000000000000" + // array[0][0]
"0200000000000000000000000000000000000000000000000000000000000000" + // array[0][1]
"0000000000000000000000000000000000000000000000000000000000000003" + // len(array[1]) = 3
"0300000000000000000000000000000000000000000000000000000000000000" + // array[1][0]
"0400000000000000000000000000000000000000000000000000000000000000" + // array[1][1]
"0500000000000000000000000000000000000000000000000000000000000000", // array[1][2]
},
{
def: `[{"type": "bytes32[3][2]"}]`,
unpacked: [2][3][32]byte{{{1}, {2}, {3}}, {{3}, {4}, {5}}},
packed: "0100000000000000000000000000000000000000000000000000000000000000" + // array[0][0]
"0200000000000000000000000000000000000000000000000000000000000000" + // array[0][1]
"0300000000000000000000000000000000000000000000000000000000000000" + // array[0][2]
"0300000000000000000000000000000000000000000000000000000000000000" + // array[1][0]
"0400000000000000000000000000000000000000000000000000000000000000" + // array[1][1]
"0500000000000000000000000000000000000000000000000000000000000000", // array[1][2]
},
{
// static tuple
def: `[{"name":"a","type":"int64"},
{"name":"b","type":"int256"},
{"name":"c","type":"int256"},
{"name":"d","type":"bool"},
{"name":"e","type":"bytes32[3][2]"}]`,
unpacked: struct {
A int64
B *big.Int
C *big.Int
D bool
E [2][3][32]byte
}{1, big.NewInt(1), big.NewInt(-1), true, [2][3][32]byte{{{1}, {2}, {3}}, {{3}, {4}, {5}}}},
packed: "0000000000000000000000000000000000000000000000000000000000000001" + // struct[a]
"0000000000000000000000000000000000000000000000000000000000000001" + // struct[b]
"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" + // struct[c]
"0000000000000000000000000000000000000000000000000000000000000001" + // struct[d]
"0100000000000000000000000000000000000000000000000000000000000000" + // struct[e] array[0][0]
"0200000000000000000000000000000000000000000000000000000000000000" + // struct[e] array[0][1]
"0300000000000000000000000000000000000000000000000000000000000000" + // struct[e] array[0][2]
"0300000000000000000000000000000000000000000000000000000000000000" + // struct[e] array[1][0]
"0400000000000000000000000000000000000000000000000000000000000000" + // struct[e] array[1][1]
"0500000000000000000000000000000000000000000000000000000000000000", // struct[e] array[1][2]
},
{
def: `[{"name":"a","type":"string"},
{"name":"b","type":"int64"},
{"name":"c","type":"bytes"},
{"name":"d","type":"string[]"},
{"name":"e","type":"int256[]"},
{"name":"f","type":"address[]"}]`,
unpacked: struct {
FieldA string `abi:"a"` // Test whether abi tag works
FieldB int64 `abi:"b"`
C []byte
D []string
E []*big.Int
F []common.Address
}{"foobar", 1, []byte{1}, []string{"foo", "bar"}, []*big.Int{big.NewInt(1), big.NewInt(-1)}, []common.Address{{1}, {2}}},
packed: "00000000000000000000000000000000000000000000000000000000000000c0" + // struct[a] offset
"0000000000000000000000000000000000000000000000000000000000000001" + // struct[b]
"0000000000000000000000000000000000000000000000000000000000000100" + // struct[c] offset
"0000000000000000000000000000000000000000000000000000000000000140" + // struct[d] offset
"0000000000000000000000000000000000000000000000000000000000000220" + // struct[e] offset
"0000000000000000000000000000000000000000000000000000000000000280" + // struct[f] offset
"0000000000000000000000000000000000000000000000000000000000000006" + // struct[a] length
"666f6f6261720000000000000000000000000000000000000000000000000000" + // struct[a] "foobar"
"0000000000000000000000000000000000000000000000000000000000000001" + // struct[c] length
"0100000000000000000000000000000000000000000000000000000000000000" + // []byte{1}
"0000000000000000000000000000000000000000000000000000000000000002" + // struct[d] length
"0000000000000000000000000000000000000000000000000000000000000040" + // foo offset
"0000000000000000000000000000000000000000000000000000000000000080" + // bar offset
"0000000000000000000000000000000000000000000000000000000000000003" + // foo length
"666f6f0000000000000000000000000000000000000000000000000000000000" + // foo
"0000000000000000000000000000000000000000000000000000000000000003" + // bar offset
"6261720000000000000000000000000000000000000000000000000000000000" + // bar
"0000000000000000000000000000000000000000000000000000000000000002" + // struct[e] length
"0000000000000000000000000000000000000000000000000000000000000001" + // 1
"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" + // -1
"0000000000000000000000000000000000000000000000000000000000000002" + // struct[f] length
"0000000000000000000000000100000000000000000000000000000000000000" + // common.Address{1}
"0000000000000000000000000200000000000000000000000000000000000000", // common.Address{2}
},
{
def: `[{"components": [{"name": "a","type": "uint256"},
{"name": "b","type": "uint256[]"}],
"name": "a","type": "tuple"},
{"name": "b","type": "uint256[]"}]`,
unpacked: struct {
A struct {
FieldA *big.Int `abi:"a"`
B []*big.Int
}
B []*big.Int
}{
A: struct {
FieldA *big.Int `abi:"a"` // Test whether abi tag works for nested tuple
B []*big.Int
}{big.NewInt(1), []*big.Int{big.NewInt(1), big.NewInt(2)}},
B: []*big.Int{big.NewInt(1), big.NewInt(2)}},
packed: "0000000000000000000000000000000000000000000000000000000000000040" + // a offset
"00000000000000000000000000000000000000000000000000000000000000e0" + // b offset
"0000000000000000000000000000000000000000000000000000000000000001" + // a.a value
"0000000000000000000000000000000000000000000000000000000000000040" + // a.b offset
"0000000000000000000000000000000000000000000000000000000000000002" + // a.b length
"0000000000000000000000000000000000000000000000000000000000000001" + // a.b[0] value
"0000000000000000000000000000000000000000000000000000000000000002" + // a.b[1] value
"0000000000000000000000000000000000000000000000000000000000000002" + // b length
"0000000000000000000000000000000000000000000000000000000000000001" + // b[0] value
"0000000000000000000000000000000000000000000000000000000000000002", // b[1] value
},
{
def: `[{"components": [{"name": "a","type": "int256"},
{"name": "b","type": "int256[]"}],
"name": "a","type": "tuple[]"}]`,
unpacked: []struct {
A *big.Int
B []*big.Int
}{
{big.NewInt(-1), []*big.Int{big.NewInt(1), big.NewInt(3)}},
{big.NewInt(1), []*big.Int{big.NewInt(2), big.NewInt(-1)}},
},
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000002" + // tuple length
"0000000000000000000000000000000000000000000000000000000000000040" + // tuple[0] offset
"00000000000000000000000000000000000000000000000000000000000000e0" + // tuple[1] offset
"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" + // tuple[0].A
"0000000000000000000000000000000000000000000000000000000000000040" + // tuple[0].B offset
"0000000000000000000000000000000000000000000000000000000000000002" + // tuple[0].B length
"0000000000000000000000000000000000000000000000000000000000000001" + // tuple[0].B[0] value
"0000000000000000000000000000000000000000000000000000000000000003" + // tuple[0].B[1] value
"0000000000000000000000000000000000000000000000000000000000000001" + // tuple[1].A
"0000000000000000000000000000000000000000000000000000000000000040" + // tuple[1].B offset
"0000000000000000000000000000000000000000000000000000000000000002" + // tuple[1].B length
"0000000000000000000000000000000000000000000000000000000000000002" + // tuple[1].B[0] value
"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", // tuple[1].B[1] value
},
{
def: `[{"components": [{"name": "a","type": "int256"},
{"name": "b","type": "int256"}],
"name": "a","type": "tuple[2]"}]`,
unpacked: [2]struct {
A *big.Int
B *big.Int
}{
{big.NewInt(-1), big.NewInt(1)},
{big.NewInt(1), big.NewInt(-1)},
},
packed: "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" + // tuple[0].a
"0000000000000000000000000000000000000000000000000000000000000001" + // tuple[0].b
"0000000000000000000000000000000000000000000000000000000000000001" + // tuple[1].a
"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", // tuple[1].b
},
{
def: `[{"components": [{"name": "a","type": "int256[]"}],
"name": "a","type": "tuple[2]"}]`,
unpacked: [2]struct {
A []*big.Int
}{
{[]*big.Int{big.NewInt(-1), big.NewInt(1)}},
{[]*big.Int{big.NewInt(1), big.NewInt(-1)}},
},
packed: "0000000000000000000000000000000000000000000000000000000000000020" +
"0000000000000000000000000000000000000000000000000000000000000040" + // tuple[0] offset
"00000000000000000000000000000000000000000000000000000000000000c0" + // tuple[1] offset
"0000000000000000000000000000000000000000000000000000000000000020" + // tuple[0].A offset
"0000000000000000000000000000000000000000000000000000000000000002" + // tuple[0].A length
"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" + // tuple[0].A[0]
"0000000000000000000000000000000000000000000000000000000000000001" + // tuple[0].A[1]
"0000000000000000000000000000000000000000000000000000000000000020" + // tuple[1].A offset
"0000000000000000000000000000000000000000000000000000000000000002" + // tuple[1].A length
"0000000000000000000000000000000000000000000000000000000000000001" + // tuple[1].A[0]
"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", // tuple[1].A[1]
},
}
| matthieu/go-ethereum | accounts/abi/packing_test.go | GO | lgpl-3.0 | 44,516 |
package co.edu.unal.sistemasinteligentes.ajedrez.agentes;
import co.edu.unal.sistemasinteligentes.ajedrez.base.*;
import co.edu.unal.sistemasinteligentes.ajedrez.reversi.Tablero;
import co.edu.unal.sistemasinteligentes.ajedrez.reversi.Reversi.EstadoReversi;
import java.io.PrintStream;
/**
* Created by jiacontrerasp on 3/30/15.
*/
public class AgenteHeuristicoBasico extends _AgenteHeuristico {
private Jugador jugador;
private PrintStream output = null;
private int niveles;
/**
* Constructor de AgenteHeuristico1
* @param niveles: niveles de recursión
*/
public AgenteHeuristicoBasico(int niveles)
{
super();
this.niveles = niveles;
}
public AgenteHeuristicoBasico(int niveles, PrintStream output)
{
super();
this.niveles = niveles;
this.output = output;
}
@Override public Jugador jugador() {
return jugador;
}
@Override public void comienzo(Jugador jugador, Estado estado) {
this.jugador = jugador;
}
@Override public void fin(Estado estado) {
// No hay implementación.
}
@Override public void movimiento(Movimiento movimiento, Estado estado) {
if(output != null){
output.println(String.format("Jugador %s mueve %s.", movimiento.jugador(), movimiento));
printEstado(estado);
}
}
protected void printEstado(Estado estado) {
if(output != null){
output.println("\t"+ estado.toString().replace("\n", "\n\t"));
}
}
@Override public String toString() {
return String.format("Agente Heuristico Basico " + jugador.toString());
}
@Override
public double darHeuristica(Estado estado) {
char miFicha = (jugador().toString() == "JugadorNegras" ? 'N' :'B');
char fichaContrario = (jugador().toString() == "JugadorNegras" ? 'B' :'N');
Tablero tablero = ((EstadoReversi)(estado)).getTablero();
int misFichas = tablero.cantidadFichas(miFicha);
int fichasContrario = tablero.cantidadFichas(fichaContrario);
return misFichas - fichasContrario;
}
@Override
public int niveles() {
return niveles;
}
@Override
public double maximoValorHeuristica() {
return 18;
}
}
| UNColombia/bog-2025995-2-2015-01 | elCinco/MinMax/src/co/edu/unal/sistemasinteligentes/ajedrez/agentes/AgenteHeuristicoBasico.java | Java | lgpl-3.0 | 2,312 |
namespace ZeroMQ
{
/// <summary>
/// Specifies possible results for socket receive operations.
/// </summary>
public enum ReceiveStatus
{
/// <summary>
/// No receive operation has been performed.
/// </summary>
None,
/// <summary>
/// The receive operation returned a message that contains data.
/// </summary>
Received,
/// <summary>
/// Non-blocking mode was requested and no messages are available at the moment.
/// </summary>
TryAgain,
/// <summary>
/// The receive operation was interrupted, likely by terminating the containing context.
/// </summary>
Interrupted
}
}
| zeromq/clrzmq | src/ZeroMQ/ReceiveStatus.cs | C# | lgpl-3.0 | 734 |
<?php
/**
* @author jurgenhaas
*/
namespace GMJH\SQRL\Sample;
use GMJH\SQRL\ClientException;
/**
* An override class for Sample SQRL account
*
* @author jurgenhaas
*
* @link
*/
class Account extends \GMJH\SQRL\Account {
#region Command ==============================================================
/**
* @param Client $client
* @param bool $additional
* @return bool
* @throws ClientException
*/
public function command_setkey($client, $additional = FALSE) {
return FALSE;
}
/**
* @param Client $client
* @return bool
* @throws ClientException
*/
public function command_setlock($client) {
return FALSE;
}
/**
* @param Client $client
* @return bool
* @throws ClientException
*/
public function command_disable($client) {
return FALSE;
}
/**
* @param Client $client
* @return bool
* @throws ClientException
*/
public function command_enable($client) {
return FALSE;
}
/**
* @param Client $client
* @return bool
* @throws ClientException
*/
public function command_delete($client) {
return FALSE;
}
/**
* @param Client $client
* @return bool
* @throws ClientException
*/
public function command_login($client) {
return TRUE;
}
/**
* @param Client $client
* @return bool
* @throws ClientException
*/
public function command_logme($client) {
return FALSE;
}
/**
* @param Client $client
* @return bool
* @throws ClientException
*/
public function command_logoff($client) {
return FALSE;
}
#endregion
}
| GMJH/SQRL-PHP-Library | sample/includes/Account.php | PHP | lgpl-3.0 | 1,602 |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Threading;
namespace CoCoL
{
/// <summary>
/// Static helper class to create channels
/// </summary>
public static class Channel
{
/// <summary>
/// Gets or creates a named channel.
/// </summary>
/// <returns>The named channel.</returns>
/// <param name="name">The name of the channel to find.</param>
/// <param name="buffersize">The number of buffers in the channel.</param>
/// <param name="scope">The scope to create a named channel in, defaults to null which means the current scope</param>
/// <param name="maxPendingReaders">The maximum number of pending readers. A negative value indicates infinite</param>
/// <param name="maxPendingWriters">The maximum number of pending writers. A negative value indicates infinite</param>
/// <param name="pendingReadersOverflowStrategy">The strategy for dealing with overflow for read requests</param>
/// <param name="pendingWritersOverflowStrategy">The strategy for dealing with overflow for write requests</param>
/// <param name="broadcast"><c>True</c> will create the channel as a broadcast channel, the default <c>false</c> will create a normal channel</param>
/// <param name="initialBroadcastBarrier">The number of readers required on the channel before sending the first broadcast, can only be used with broadcast channels</param>
/// <param name="broadcastMinimum">The minimum number of readers required on the channel, before a broadcast can be performed, can only be used with broadcast channels</param>
/// <typeparam name="T">The channel type.</typeparam>
public static IChannel<T> Get<T>(string name, int buffersize = 0, ChannelScope scope = null, int maxPendingReaders = -1, int maxPendingWriters = -1, QueueOverflowStrategy pendingReadersOverflowStrategy = QueueOverflowStrategy.Reject, QueueOverflowStrategy pendingWritersOverflowStrategy = QueueOverflowStrategy.Reject, bool broadcast = false, int initialBroadcastBarrier = -1, int broadcastMinimum = -1)
{
return ChannelManager.GetChannel<T>(name, buffersize, scope, maxPendingReaders, maxPendingWriters, pendingReadersOverflowStrategy, pendingWritersOverflowStrategy, broadcast, initialBroadcastBarrier, broadcastMinimum);
}
/// <summary>
/// Gets or creates a named channel.
/// </summary>
/// <returns>The named channel.</returns>
/// <param name="attr">The attribute describing the channel.</param>
/// <param name="scope">The scope to create a named channel in, defaults to null which means the current scope</param>
/// <typeparam name="T">The channel type.</typeparam>
public static IChannel<T> Get<T>(ChannelNameAttribute attr, ChannelScope scope = null)
{
return ChannelManager.GetChannel<T>(attr, scope);
}
/// <summary>
/// Gets or creates a named channel from a marker setup
/// </summary>
/// <returns>The named channel.</returns>
/// <param name="marker">The channel marker instance that describes the channel.</param>
/// <typeparam name="T">The channel type.</typeparam>
public static IChannel<T> Get<T>(ChannelMarkerWrapper<T> marker)
{
return ChannelManager.GetChannel<T>(marker);
}
/// <summary>
/// Gets a write channel from a marker interface.
/// </summary>
/// <returns>The requested channel.</returns>
/// <param name="channel">The marker interface, or a real channel instance.</param>
/// <typeparam name="T">The channel type.</typeparam>
public static IWriteChannelEnd<T> Get<T>(IWriteChannel<T> channel)
{
return ChannelManager.GetChannel<T>(channel);
}
/// <summary>
/// Gets a read channel from a marker interface.
/// </summary>
/// <returns>The requested channel.</returns>
/// <param name="channel">The marker interface, or a real channel instance.</param>
/// <typeparam name="T">The channel type.</typeparam>
public static IReadChannelEnd<T> Get<T>(IReadChannel<T> channel)
{
return ChannelManager.GetChannel<T>(channel);
}
/// <summary>
/// Creates a channel, possibly unnamed.
/// If a channel name is provided, the channel is created in the supplied scope.
/// If a channel with the given name is already found in the supplied scope, the named channel is returned.
/// </summary>
/// <returns>The channel.</returns>
/// <param name="name">The name of the channel, or null.</param>
/// <param name="buffersize">The number of buffers in the channel.</param>
/// <param name="scope">The scope to create a named channel in, defaults to null which means the current scope</param>
/// <param name="maxPendingReaders">The maximum number of pending readers. A negative value indicates infinite</param>
/// <param name="maxPendingWriters">The maximum number of pending writers. A negative value indicates infinite</param>
/// <param name="pendingReadersOverflowStrategy">The strategy for dealing with overflow for read requests</param>
/// <param name="pendingWritersOverflowStrategy">The strategy for dealing with overflow for write requests</param>
/// <param name="broadcast"><c>True</c> will create the channel as a broadcast channel, the default <c>false</c> will create a normal channel</param>
/// <param name="initialBroadcastBarrier">The number of readers required on the channel before sending the first broadcast, can only be used with broadcast channels</param>
/// <param name="broadcastMinimum">The minimum number of readers required on the channel, before a broadcast can be performed, can only be used with broadcast channels</param>
/// <typeparam name="T">The channel type.</typeparam>
public static IChannel<T> Create<T>(string name = null, int buffersize = 0, ChannelScope scope = null, int maxPendingReaders = -1, int maxPendingWriters = -1, QueueOverflowStrategy pendingReadersOverflowStrategy = QueueOverflowStrategy.Reject, QueueOverflowStrategy pendingWritersOverflowStrategy = QueueOverflowStrategy.Reject, bool broadcast = false, int initialBroadcastBarrier = -1, int broadcastMinimum = -1)
{
return ChannelManager.CreateChannel<T>(name, buffersize, scope, maxPendingReaders, maxPendingWriters, pendingReadersOverflowStrategy, pendingWritersOverflowStrategy, broadcast, initialBroadcastBarrier, broadcastMinimum);
}
/// <summary>
/// Creates a channel, possibly unnamed.
/// If a channel name is provided, the channel is created in the supplied scope.
/// If a channel with the given name is already found in the supplied scope, the named channel is returned.
/// </summary>
/// <returns>The named channel.</returns>
/// <param name="attr">The attribute describing the channel.</param>
/// <param name="scope">The scope to create a named channel in, defaults to null which means the current scope</param>
/// <typeparam name="T">The channel type.</typeparam>
public static IChannel<T> Create<T>(ChannelNameAttribute attr, ChannelScope scope = null)
{
return ChannelManager.CreateChannel<T>(attr, scope);
}
}
/// <summary>
/// A channel that uses continuation callbacks
/// </summary>
public class Channel<T> : IChannel<T>, IUntypedChannel, IJoinAbleChannel, INamedItem
{
/// <summary>
/// The minium value for the cleanup threshold
/// </summary>
protected const int MIN_QUEUE_CLEANUP_THRESHOLD = 100;
/// <summary>
/// Interface for an offer
/// </summary>
protected interface IEntry
{
/// <summary>
/// The two-phase offer instance
/// </summary>
/// <value>The offer.</value>
ITwoPhaseOffer Offer { get; }
}
/// <summary>
/// Structure for keeping a read request
/// </summary>
protected struct ReaderEntry : IEntry, IEquatable<ReaderEntry>
{
/// <summary>
/// The offer handler for the request
/// </summary>
public readonly ITwoPhaseOffer Offer;
/// <summary>
/// The callback method for reporting progress
/// </summary>
public readonly TaskCompletionSource<T> Source;
#if !NO_TASK_ASYNCCONTINUE
/// <summary>
/// A flag indicating if signalling task completion must be enqued on the task pool
/// </summary>
public readonly bool EnqueueContinuation;
#endif
/// <summary>
/// Initializes a new instance of the <see cref="CoCoL.Channel<T>.ReaderEntry"/> struct.
/// </summary>
/// <param name="offer">The offer handler</param>
public ReaderEntry(ITwoPhaseOffer offer)
{
Offer = offer;
#if NO_TASK_ASYNCCONTINUE
Source = new TaskCompletionSource<T>();
#else
EnqueueContinuation = ExecutionScope.Current.IsLimitingPool;
Source = new TaskCompletionSource<T>(
EnqueueContinuation
? TaskCreationOptions.None
: TaskCreationOptions.RunContinuationsAsynchronously);
#endif
}
/// <summary>
/// The offer handler for the request
/// </summary>
ITwoPhaseOffer IEntry.Offer { get { return Offer; } }
/// <summary>
/// Gets a value indicating whether this <see cref="T:CoCoL.Channel`1.ReaderEntry"/> is timed out.
/// </summary>
public bool IsTimeout => Offer is IExpiringOffer expOffer && expOffer.IsExpired;
/// <summary>
/// Gets a value indicating whether this <see cref="T:CoCoL.Channel`1.ReaderEntry"/> is cancelled.
/// </summary>
public bool IsCancelled => Offer is ICancelAbleOffer canOffer && canOffer.CancelToken.IsCancellationRequested;
/// <summary>
/// Gets a value representing the expiration time of this entry
/// </summary>
public DateTime Expires => Offer is IExpiringOffer expOffer ? expOffer.Expires : new DateTime(0);
/// <summary>
/// Signals that the probe phase has finished
/// </summary>
public void ProbeCompleted()
{
if (Offer is IExpiringOffer offer)
offer.ProbeComplete();
}
/// <summary>
/// Explict disable of compares
/// </summary>
/// <param name="other">The item to compare with</param>
/// <returns>Always throws an exception to avoid compares</returns>
public bool Equals(ReaderEntry other)
{
throw new NotImplementedException();
}
}
/// <summary>
/// Structure for keeping a write request
/// </summary>
protected struct WriterEntry : IEntry, IEquatable<WriterEntry>
{
/// <summary>
/// The offer handler for the request
/// </summary>
public readonly ITwoPhaseOffer Offer;
/// <summary>
/// The callback method for reporting progress
/// </summary>
public readonly TaskCompletionSource<bool> Source;
/// <summary>
/// The cancellation token
/// </summary>
public readonly CancellationToken CancelToken;
/// <summary>
/// The value being written
/// </summary>
public readonly T Value;
#if !NO_TASK_ASYNCCONTINUE
/// <summary>
/// A flag indicating if signalling task completion must be enqued on the task pool
/// </summary>
public readonly bool EnqueueContinuation;
#endif
/// <summary>
/// Initializes a new instance of the <see cref="CoCoL.Channel<T>.WriterEntry"/> struct.
/// </summary>
/// <param name="offer">The offer handler</param>
/// <param name="value">The value being written.</param>
public WriterEntry(ITwoPhaseOffer offer, T value)
{
Offer = offer;
#if NO_TASK_ASYNCCONTINUE
Source = new TaskCompletionSource<bool>();
#else
EnqueueContinuation = ExecutionScope.Current.IsLimitingPool;
Source = new TaskCompletionSource<bool>(
EnqueueContinuation
? TaskCreationOptions.None
: TaskCreationOptions.RunContinuationsAsynchronously);
#endif
Value = value;
}
/// <summary>
/// Initializes a new empty instance of the <see cref="CoCoL.Channel<T>.WriterEntry"/> struct.
/// </summary>
/// <param name="value">The value being written.</param>
public WriterEntry(T value)
{
Offer = null;
Source = null;
Value = value;
#if !NO_TASK_ASYNCCONTINUE
EnqueueContinuation = false;
#endif
}
/// <summary>
/// The offer handler for the request
/// </summary>
ITwoPhaseOffer IEntry.Offer { get { return Offer; } }
/// <summary>
/// Gets a value indicating whether this <see cref="T:CoCoL.Channel`1.ReaderEntry"/> is timed out.
/// </summary>
public bool IsTimeout => Offer is IExpiringOffer && ((IExpiringOffer)Offer).IsExpired;
/// <summary>
/// Gets a value indicating whether this <see cref="T:CoCoL.Channel`1.ReaderEntry"/> is cancelled.
/// </summary>
public bool IsCancelled => Offer is ICancelAbleOffer && ((ICancelAbleOffer)Offer).CancelToken.IsCancellationRequested;
/// <summary>
/// Gets a value representing the expiration time of this entry
/// </summary>
public DateTime Expires => Offer is IExpiringOffer ? ((IExpiringOffer)Offer).Expires : new DateTime(0);
/// <summary>
/// Signals that the probe phase has finished
/// </summary>
public void ProbeCompleted()
{
if (Offer is IExpiringOffer offer)
offer.ProbeComplete();
}
/// <summary>
/// Explict disable of compares
/// </summary>
/// <param name="other">The item to compare with</param>
/// <returns>Always throws an exception to avoid compares</returns>
public bool Equals(WriterEntry other)
{
throw new NotImplementedException();
}
}
/// <summary>
/// The queue with pending readers
/// </summary>
protected List<ReaderEntry> m_readerQueue = new List<ReaderEntry>(1);
/// <summary>
/// The queue with pending writers
/// </summary>
protected List<WriterEntry> m_writerQueue = new List<WriterEntry>(1);
/// <summary>
/// The maximal size of the queue
/// </summary>
protected readonly int m_bufferSize;
/// <summary>
/// The lock object protecting access to the queues
/// </summary>
protected readonly AsyncLock m_asynclock = new AsyncLock();
/// <summary>
/// Gets or sets the name of the channel
/// </summary>
/// <value>The name.</value>
public string Name { get; private set; }
/// <summary>
/// Gets a value indicating whether this instance is retired.
/// </summary>
/// <value><c>true</c> if this instance is retired; otherwise, <c>false</c>.</value>
public Task<bool> IsRetiredAsync { get { return GetIsRetiredAsync(); } }
/// <summary>
/// Gets a value indicating whether this instance is retired.
/// </summary>
protected bool m_isRetired;
/// <summary>
/// The number of messages to process before marking the channel as retired
/// </summary>
protected int m_retireCount = -1;
/// <summary>
/// The number of reader processes having joined the channel
/// </summary>
protected int m_joinedReaderCount = 0;
/// <summary>
/// The number of writer processes having joined the channel
/// </summary>
protected int m_joinedWriterCount = 0;
/// <summary>
/// The threshold for performing writer queue cleanup
/// </summary>
protected int m_writerQueueCleanup = MIN_QUEUE_CLEANUP_THRESHOLD;
/// <summary>
/// The threshold for performing reader queue cleanup
/// </summary>
protected int m_readerQueueCleanup = MIN_QUEUE_CLEANUP_THRESHOLD;
/// <summary>
/// The maximum number of pending readers to allow
/// </summary>
protected readonly int m_maxPendingReaders;
/// <summary>
/// The strategy for selecting pending readers to discard on overflow
/// </summary>
protected readonly QueueOverflowStrategy m_pendingReadersOverflowStrategy;
/// <summary>
/// The maximum number of pending writers to allow
/// </summary>
protected readonly int m_maxPendingWriters;
/// <summary>
/// The strategy for selecting pending writers to discard on overflow
/// </summary>
protected readonly QueueOverflowStrategy m_pendingWritersOverflowStrategy;
/// <summary>
/// Initializes a new instance of the <see cref="CoCoL.Channel<T>"/> class.
/// </summary>
/// <param name="attribute">The attribute describing the channel</param>
internal Channel(ChannelNameAttribute attribute)
{
if (attribute == null)
throw new ArgumentNullException(nameof(attribute));
if (attribute.BufferSize < 0)
throw new ArgumentOutOfRangeException(nameof(attribute), "The size parameter must be greater than or equal to zero");
this.Name = attribute.Name;
m_bufferSize = attribute.BufferSize;
m_maxPendingReaders = attribute.MaxPendingReaders;
m_maxPendingWriters = attribute.MaxPendingWriters;
m_pendingReadersOverflowStrategy = attribute.PendingReadersOverflowStrategy;
m_pendingWritersOverflowStrategy = attribute.PendingWritersOverflowStrategy;
}
/// <summary>
/// Helper method for accessor to get the retired state
/// </summary>
/// <returns>The is retired async.</returns>
protected async Task<bool> GetIsRetiredAsync()
{
using (await m_asynclock.LockAsync())
return m_isRetired;
}
/// <summary>
/// Offers a transaction to the write end
/// </summary>
/// <param name="wr">The writer entry.</param>
protected async Task<bool> Offer(WriterEntry wr)
{
Exception tex = null;
bool accept = false;
System.Diagnostics.Debug.Assert(wr.Source == m_writerQueue[0].Source);
try
{
accept =
(wr.Source == null || wr.Source.Task.Status == TaskStatus.WaitingForActivation)
&&
(wr.Offer == null || await wr.Offer.OfferAsync(this).ConfigureAwait(false));
}
catch (Exception ex)
{
tex = ex; // Workaround to support C# 5.0, with no await in catch clause
}
if (tex != null)
{
TrySetException(wr, tex);
m_writerQueue.RemoveAt(0);
return false;
}
if (!accept)
{
TrySetCancelled(wr);
m_writerQueue.RemoveAt(0);
return false;
}
return true;
}
/// <summary>
/// Offersa transaction to the read end
/// </summary>
/// <param name="rd">The reader entry.</param>
protected async Task<bool> Offer(ReaderEntry rd)
{
Exception tex = null;
bool accept = false;
System.Diagnostics.Debug.Assert(rd.Source == m_readerQueue[0].Source);
try
{
accept =
(rd.Source == null || rd.Source.Task.Status == TaskStatus.WaitingForActivation)
&&
(rd.Offer == null || await rd.Offer.OfferAsync(this).ConfigureAwait(false));
}
catch (Exception ex)
{
tex = ex; // Workaround to support C# 5.0, with no await in catch clause
}
if (tex != null)
{
TrySetException(rd, tex);
m_readerQueue.RemoveAt(0);
return false;
}
if (!accept)
{
TrySetCancelled(rd);
m_readerQueue.RemoveAt(0);
return false;
}
return true;
}
/// <summary>
/// Method that examines the queues and matches readers with writers
/// </summary>
/// <returns>An awaitable that signals if the caller has been accepted or rejected.</returns>
/// <param name="asReader"><c>True</c> if the caller method is a reader, <c>false</c> otherwise.</param>
/// <param name="caller">The caller task.</param>
protected virtual async Task<bool> MatchReadersAndWriters(bool asReader, Task caller)
{
var processed = false;
while (m_writerQueue != null && m_readerQueue != null && m_writerQueue.Count > 0 && m_readerQueue.Count > 0)
{
var wr = m_writerQueue[0];
var rd = m_readerQueue[0];
bool offerWriter;
bool offerReader;
// If the caller is a reader, we assume that the
// read call will always proceed, and start emptying
// the write queue, and vice versa if the caller
// is a writer
if (asReader)
{
offerWriter = await Offer(wr).ConfigureAwait(false);
if (!offerWriter)
continue;
offerReader = await Offer(rd).ConfigureAwait(false);
}
else
{
offerReader = await Offer(rd).ConfigureAwait(false);
if (!offerReader)
continue;
offerWriter = await Offer(wr).ConfigureAwait(false);
}
// We flip the first entry, so we do not repeatedly
// offer the side that agrees, and then discover
// that the other side denies
asReader = !asReader;
// If the ends disagree, the declining end
// has been removed from the queue, so we just
// withdraw the offer from the other end
if (!(offerReader && offerWriter))
{
if (wr.Offer != null && offerWriter)
await wr.Offer.WithdrawAsync(this).ConfigureAwait(false);
if (rd.Offer != null && offerReader)
await rd.Offer.WithdrawAsync(this).ConfigureAwait(false);
}
else
{
// transaction complete
m_writerQueue.RemoveAt(0);
m_readerQueue.RemoveAt(0);
if (wr.Offer != null)
await wr.Offer.CommitAsync(this).ConfigureAwait(false);
if (rd.Offer != null)
await rd.Offer.CommitAsync(this).ConfigureAwait(false);
if (caller == rd.Source.Task || (wr.Source != null && caller == wr.Source.Task))
processed = true;
SetResult(rd, wr.Value);
SetResult(wr, true);
// Release items if there is space in the buffer
await ProcessWriteQueueBufferAfterReadAsync(true).ConfigureAwait(false);
// Adjust the cleanup threshold
if (m_writerQueue.Count <= m_writerQueueCleanup - MIN_QUEUE_CLEANUP_THRESHOLD)
m_writerQueueCleanup = Math.Max(MIN_QUEUE_CLEANUP_THRESHOLD, m_writerQueue.Count + MIN_QUEUE_CLEANUP_THRESHOLD);
// Adjust the cleanup threshold
if (m_readerQueue.Count <= m_readerQueueCleanup - MIN_QUEUE_CLEANUP_THRESHOLD)
m_readerQueueCleanup = Math.Max(MIN_QUEUE_CLEANUP_THRESHOLD, m_readerQueue.Count + MIN_QUEUE_CLEANUP_THRESHOLD);
// If this was the last item before the retirement,
// flush all following and set the retired flag
await EmptyQueueIfRetiredAsync(true).ConfigureAwait(false);
}
}
return processed || caller.Status != TaskStatus.WaitingForActivation;
}
/// <summary>
/// Registers a desire to read from the channel
/// </summary>
public Task<T> ReadAsync()
{
return ReadAsync(null);
}
/// <summary>
/// Registers a desire to read from the channel
/// </summary>
/// <param name="offer">A callback method for offering an item, use null to unconditionally accept</param>
public async Task<T> ReadAsync(ITwoPhaseOffer offer)
{
var rd = new ReaderEntry(offer);
if (rd.IsCancelled)
throw new TaskCanceledException();
using (await m_asynclock.LockAsync())
{
if (m_isRetired)
{
TrySetException(rd, new RetiredException(this.Name));
return await rd.Source.Task.ConfigureAwait(false);
}
m_readerQueue.Add(rd);
if (!await MatchReadersAndWriters(true, rd.Source.Task).ConfigureAwait(false))
{
rd.ProbeCompleted();
System.Diagnostics.Debug.Assert(m_readerQueue[m_readerQueue.Count - 1].Source == rd.Source);
// If this was a probe call, return a timeout now
if (rd.IsTimeout)
{
m_readerQueue.RemoveAt(m_readerQueue.Count - 1);
TrySetException(rd, new TimeoutException());
}
else if (rd.IsCancelled)
{
m_readerQueue.RemoveAt(m_readerQueue.Count - 1);
TrySetException(rd, new TaskCanceledException());
}
else
{
// Make room if we have too many
if (m_maxPendingReaders > 0 && (m_readerQueue.Count - 1) >= m_maxPendingReaders)
{
switch (m_pendingReadersOverflowStrategy)
{
case QueueOverflowStrategy.FIFO:
{
var exp = m_readerQueue[0];
m_readerQueue.RemoveAt(0);
TrySetException(exp, new ChannelOverflowException(this.Name));
}
break;
case QueueOverflowStrategy.LIFO:
{
var exp = m_readerQueue[m_readerQueue.Count - 2];
m_readerQueue.RemoveAt(m_readerQueue.Count - 2);
TrySetException(exp, new ChannelOverflowException(this.Name));
}
break;
//case QueueOverflowStrategy.Reject:
default:
{
var exp = m_readerQueue[m_readerQueue.Count - 1];
m_readerQueue.RemoveAt(m_readerQueue.Count - 1);
TrySetException(exp, new ChannelOverflowException(this.Name));
}
break;
}
}
// If we have expanded the queue with a new batch, see if we can purge old entries
m_readerQueueCleanup = await PerformQueueCleanupAsync(m_readerQueue, true, m_readerQueueCleanup).ConfigureAwait(false);
if (rd.Offer is IExpiringOffer && ((IExpiringOffer)rd.Offer).Expires != Timeout.InfiniteDateTime)
ExpirationManager.AddExpirationCallback(((IExpiringOffer)rd.Offer).Expires, () => ExpireItemsAsync().FireAndForget());
}
}
}
return await rd.Source.Task.ConfigureAwait(false);
}
/// <summary>
/// Registers a desire to write to the channel
/// </summary>
/// <param name="value">The value to write to the channel.</param>
public Task WriteAsync(T value)
{
return WriteAsync(value, null);
}
/// <summary>
/// Registers a desire to write to the channel
/// </summary>
/// <param name="offer">A callback method for offering an item, use null to unconditionally accept</param>
/// <param name="value">The value to write to the channel.</param>
public async Task WriteAsync(T value, ITwoPhaseOffer offer)
{
var wr = new WriterEntry(offer, value);
if (wr.IsCancelled)
throw new TaskCanceledException();
using (await m_asynclock.LockAsync())
{
if (m_isRetired)
{
TrySetException(wr, new RetiredException(this.Name));
await wr.Source.Task.ConfigureAwait(false);
return;
}
m_writerQueue.Add(wr);
if (!await MatchReadersAndWriters(false, wr.Source.Task).ConfigureAwait(false))
{
System.Diagnostics.Debug.Assert(m_writerQueue[m_writerQueue.Count - 1].Source == wr.Source);
// If we have a buffer slot to use
if (m_writerQueue.Count <= m_bufferSize && m_retireCount < 0)
{
if (offer == null || await offer.OfferAsync(this))
{
if (offer != null)
await offer.CommitAsync(this).ConfigureAwait(false);
m_writerQueue[m_writerQueue.Count - 1] = new WriterEntry(value);
TrySetResult(wr, true);
}
else
{
TrySetCancelled(wr);
}
// For good measure, we also make sure the probe phase is completed
wr.ProbeCompleted();
}
else
{
wr.ProbeCompleted();
// If this was a probe call, return a timeout now
if (wr.IsTimeout)
{
m_writerQueue.RemoveAt(m_writerQueue.Count - 1);
TrySetException(wr, new TimeoutException());
}
else if (wr.IsCancelled)
{
m_writerQueue.RemoveAt(m_writerQueue.Count - 1);
TrySetException(wr, new TaskCanceledException());
}
else
{
// Make room if we have too many
if (m_maxPendingWriters > 0 && (m_writerQueue.Count - m_bufferSize - 1) >= m_maxPendingWriters)
{
switch (m_pendingWritersOverflowStrategy)
{
case QueueOverflowStrategy.FIFO:
{
var exp = m_writerQueue[m_bufferSize];
m_writerQueue.RemoveAt(m_bufferSize);
TrySetException(exp, new ChannelOverflowException(this.Name));
}
break;
case QueueOverflowStrategy.LIFO:
{
var exp = m_writerQueue[m_writerQueue.Count - 2];
m_writerQueue.RemoveAt(m_writerQueue.Count - 2);
TrySetException(exp, new ChannelOverflowException(this.Name));
}
break;
//case QueueOverflowStrategy.Reject:
default:
{
var exp = m_writerQueue[m_writerQueue.Count - 1];
m_writerQueue.RemoveAt(m_writerQueue.Count - 1);
TrySetException(exp, new ChannelOverflowException(this.Name));
}
break;
}
}
// If we have expanded the queue with a new batch, see if we can purge old entries
m_writerQueueCleanup = await PerformQueueCleanupAsync(m_writerQueue, true, m_writerQueueCleanup).ConfigureAwait(false);
if (wr.Offer is IExpiringOffer && ((IExpiringOffer)wr.Offer).Expires != Timeout.InfiniteDateTime)
ExpirationManager.AddExpirationCallback(((IExpiringOffer)wr.Offer).Expires, () => ExpireItemsAsync().FireAndForget());
}
}
}
}
await wr.Source.Task.ConfigureAwait(false);
return;
}
/// <summary>
/// Purges items in the queue that are no longer active
/// </summary>
/// <param name="queue">The queue to remove from.</param>
/// <param name="queueCleanup">The threshold parameter.</param>
/// <param name="isLocked"><c>True</c> if we are already holding the lock, <c>false</c> otherwise</param>
/// <typeparam name="Tx">The type of list data.</typeparam>
private async Task<int> PerformQueueCleanupAsync<Tx>(List<Tx> queue, bool isLocked, int queueCleanup)
where Tx : IEntry
{
var res = queueCleanup;
using(isLocked ? default(AsyncLock.Releaser) : await m_asynclock.LockAsync())
{
if (queue.Count > queueCleanup)
{
for (var i = queue.Count - 1; i >= 0; i--)
{
if (queue[i].Offer != null)
if (await queue[i].Offer.OfferAsync(this).ConfigureAwait(false))
await queue[i].Offer.WithdrawAsync(this).ConfigureAwait(false);
else
{
TrySetCancelled(queue[i]);
queue.RemoveAt(i);
}
}
// Prevent repeated cleanup requests
res = Math.Max(MIN_QUEUE_CLEANUP_THRESHOLD, queue.Count + MIN_QUEUE_CLEANUP_THRESHOLD);
}
}
return res;
}
/// <summary>
/// Helper method for dequeueing write requests after space has been allocated in the writer queue
/// </summary>
/// <param name="isLocked"><c>True</c> if we are already holding the lock, <c>false</c> otherwise</param>
private async Task ProcessWriteQueueBufferAfterReadAsync(bool isLocked)
{
using(isLocked ? default(AsyncLock.Releaser) : await m_asynclock.LockAsync())
{
// If there is now a buffer slot in the queue, trigger a callback to a waiting item
while (m_retireCount < 0 && m_bufferSize > 0 && m_writerQueue.Count >= m_bufferSize)
{
var nextItem = m_writerQueue[m_bufferSize - 1];
if (nextItem.Offer == null || await nextItem.Offer.OfferAsync(this).ConfigureAwait(false))
{
if (nextItem.Offer != null)
await nextItem.Offer.CommitAsync(this).ConfigureAwait(false);
SetResult(nextItem, true);
// Now that the transaction has completed for the writer, record it as waiting forever
m_writerQueue[m_bufferSize - 1] = new WriterEntry(nextItem.Value);
// We can have at most one, since we process at most one read
break;
}
else
m_writerQueue.RemoveAt(m_bufferSize - 1);
}
}
}
/// <summary>
/// Stops this channel from processing messages
/// </summary>
public Task RetireAsync()
{
return RetireAsync(false, false);
}
/// <summary>
/// Stops this channel from processing messages
/// </summary>
/// <param name="immediate">Retires the channel without processing the queue, which may cause lost messages</param>
public Task RetireAsync(bool immediate)
{
return RetireAsync(immediate, false);
}
/// <summary>
/// Stops this channel from processing messages
/// </summary>
/// <param name="immediate">Retires the channel without processing the queue, which may cause lost messages</param>
/// <param name="isLocked"><c>True</c> if we are already holding the lock, <c>false</c> otherwise</param>
private async Task RetireAsync(bool immediate, bool isLocked)
{
using (isLocked ? default(AsyncLock.Releaser) : await m_asynclock.LockAsync())
{
if (m_isRetired)
return;
if (m_retireCount < 0)
{
// If we have responded to buffered writes,
// make sure we pair those before retiring
m_retireCount = Math.Min(m_writerQueue.Count, m_bufferSize) + 1;
// For immediate retire, remove buffered writes
if (immediate)
while (m_retireCount > 1)
{
if (m_writerQueue[0].Source != null)
TrySetException(m_writerQueue[0], new RetiredException(this.Name));
m_writerQueue.RemoveAt(0);
m_retireCount--;
}
}
await EmptyQueueIfRetiredAsync(true).ConfigureAwait(false);
}
}
/// <summary>
/// Join the channel
/// </summary>
/// <param name="asReader"><c>true</c> if joining as a reader, <c>false</c> otherwise</param>
public virtual async Task JoinAsync(bool asReader)
{
using (await m_asynclock.LockAsync())
{
// Do not allow anyone to join after we retire the channel
if (m_isRetired)
throw new RetiredException(this.Name);
if (asReader)
m_joinedReaderCount++;
else
m_joinedWriterCount++;
}
}
/// <summary>
/// Leave the channel.
/// </summary>
/// <param name="asReader"><c>true</c> if leaving as a reader, <c>false</c> otherwise</param>
public virtual async Task LeaveAsync(bool asReader)
{
using (await m_asynclock.LockAsync())
{
// If we are already retired, skip this call
if (m_isRetired)
return;
// Countdown
if (asReader)
m_joinedReaderCount--;
else
m_joinedWriterCount--;
// Retire if required
if ((asReader && m_joinedReaderCount <= 0) || (!asReader && m_joinedWriterCount <= 0))
await RetireAsync(false, true).ConfigureAwait(false);
}
}
/// <summary>
/// Empties the queue if the channel is retired.
/// </summary>
/// <param name="isLocked"><c>True</c> if we are already holding the lock, <c>false</c> otherwise</param>
private async Task EmptyQueueIfRetiredAsync(bool isLocked)
{
List<ReaderEntry> readers = null;
List<WriterEntry> writers = null;
using (isLocked ? default(AsyncLock.Releaser) : await m_asynclock.LockAsync())
{
// Countdown as required
if (m_retireCount > 0)
{
m_retireCount--;
if (m_retireCount == 0)
{
// Empty the queues, as we are now retired
readers = m_readerQueue;
writers = m_writerQueue;
// Make sure nothing new enters the queues
m_isRetired = true;
m_readerQueue = null;
m_writerQueue = null;
}
}
}
// If there are pending retire messages, send them
if (readers != null || writers != null)
{
if (readers != null)
foreach (var r in readers)
TrySetException(r, new RetiredException(this.Name));
if (writers != null)
foreach (var w in writers)
TrySetException(w, new RetiredException(this.Name));
}
}
/// <summary>
/// Callback method used to signal timeout on expired items
/// </summary>
private async Task ExpireItemsAsync()
{
KeyValuePair<int, ReaderEntry>[] expiredReaders;
KeyValuePair<int, WriterEntry>[] expiredWriters;
// Extract all expired items from their queues
using (await m_asynclock.LockAsync())
{
// If the channel is retired, there is nothing to do here
if (m_readerQueue == null || m_writerQueue == null)
return;
var now = DateTime.Now;
expiredReaders = m_readerQueue.Zip(Enumerable.Range(0, m_readerQueue.Count), (n, i) => new KeyValuePair<int, ReaderEntry>(i, n)).Where(x => x.Value.Expires.Ticks != 0 && (x.Value.Expires - now).Ticks <= ExpirationManager.ALLOWED_ADVANCE_EXPIRE_TICKS).ToArray();
expiredWriters = m_writerQueue.Zip(Enumerable.Range(0, m_writerQueue.Count), (n, i) => new KeyValuePair<int, WriterEntry>(i, n)).Where(x => x.Value.Expires.Ticks != 0 && (x.Value.Expires - now).Ticks <= ExpirationManager.ALLOWED_ADVANCE_EXPIRE_TICKS).ToArray();
foreach (var r in expiredReaders.OrderByDescending(x => x.Key))
m_readerQueue.RemoveAt(r.Key);
foreach (var r in expiredWriters.OrderByDescending(x => x.Key))
m_writerQueue.RemoveAt(r.Key);
}
// Send the notifications
foreach (var r in expiredReaders.OrderBy(x => x.Value.Expires))
TrySetException(r.Value, new TimeoutException());
// Send the notifications
foreach (var w in expiredWriters.OrderBy(x => x.Value.Expires))
TrySetException(w.Value, new TimeoutException());
}
#region Task continuation support methods
/// <summary>
/// Sets the task to be failed
/// </summary>
/// <param name="entry">The task to set</param>
/// <param name="ex">The exception to set</param>
private static void TrySetException(ReaderEntry entry, Exception ex)
{
#if NO_TASK_ASYNCCONTINUE
ThreadPool.QueueItem(() => entry.Source.TrySetException(ex));
#else
if (entry.EnqueueContinuation)
ThreadPool.QueueItem(() => entry.Source.TrySetException(ex));
else
entry.Source.TrySetException(ex);
#endif
}
/// <summary>
/// Sets the task to be failed
/// </summary>
/// <param name="entry">The task to set</param>
/// <param name="ex">The exception to set</param>
private static void TrySetException(WriterEntry entry, Exception ex)
{
if (entry.Source != null)
{
#if NO_TASK_ASYNCCONTINUE
ThreadPool.QueueItem(() => entry.Source.TrySetException(ex));
#else
if (entry.EnqueueContinuation)
ThreadPool.QueueItem(() => entry.Source.TrySetException(ex));
else
entry.Source.TrySetException(ex);
#endif
}
}
/// <summary>
/// Tries to set the source to Cancelled
/// </summary>
/// <param name="entry">The entry to signal</param>
private static void TrySetCancelled(IEntry entry)
{
if (entry is ReaderEntry re)
TrySetCancelled(re);
else if (entry is WriterEntry we)
TrySetCancelled(we);
else
throw new InvalidOperationException("No such type");
}
/// <summary>
/// Tries to set the source to Cancelled
/// </summary>
/// <param name="entry">The entry to signal</param>
private static void TrySetCancelled(ReaderEntry entry)
{
#if NO_TASK_ASYNCCONTINUE
ThreadPool.QueueItem(() => entry.Source.TrySetCanceled());
#else
if (entry.EnqueueContinuation)
ThreadPool.QueueItem(() => entry.Source.TrySetCanceled());
else
entry.Source.TrySetCanceled();
#endif
}
/// <summary>
/// Tries to set the source to Cancelled
/// </summary>
/// <param name="entry">The entry to signal</param>
private static void TrySetCancelled(WriterEntry entry)
{
if (entry.Source != null)
{
#if NO_TASK_ASYNCCONTINUE
ThreadPool.QueueItem(() => entry.Source.TrySetCanceled());
#else
if (entry.EnqueueContinuation)
ThreadPool.QueueItem(() => entry.Source.TrySetCanceled());
else
entry.Source.TrySetCanceled();
#endif
}
}
/// <summary>
/// Tries to set the source result
/// </summary>
/// <param name="entry">The entry to signal</param>
/// <param name="value">The value to signal</param>
private static void TrySetResult(WriterEntry entry, bool value)
{
if (entry.Source != null)
{
#if NO_TASK_ASYNCCONTINUE
ThreadPool.QueueItem(() => entry.Source.TrySetResult(value));
#else
if (entry.EnqueueContinuation)
ThreadPool.QueueItem(() => entry.Source.TrySetResult(value));
else
entry.Source.TrySetResult(value);
#endif
}
}
/// <summary>
/// Sets the source result
/// </summary>
/// <param name="entry">The entry to signal</param>
/// <param name="value">The value to signal</param>
private static void SetResult(WriterEntry entry, bool value)
{
if (entry.Source != null)
{
#if NO_TASK_ASYNCCONTINUE
ThreadPool.QueueItem(() => entry.Source.SetResult(value));
#else
if (entry.EnqueueContinuation)
ThreadPool.QueueItem(() => entry.Source.SetResult(value));
else
entry.Source.SetResult(value);
#endif
}
}
/// <summary>
/// Sets the source result
/// </summary>
/// <param name="entry">The entry to signal</param>
/// <param name="value">The value to signal</param>
private static void SetResult(ReaderEntry entry, T value)
{
#if NO_TASK_ASYNCCONTINUE
ThreadPool.QueueItem(() => entry.Source.SetResult(value));
#else
if (entry.EnqueueContinuation)
ThreadPool.QueueItem(() => entry.Source.SetResult(value));
else
entry.Source.SetResult(value);
#endif
}
#endregion
}
}
| kenkendk/cocol | src/CoCoL/Channel.cs | C# | lgpl-3.0 | 43,301 |
<?php
class CsvTest extends \PHPUnit_Framework_TestCase
{
use ExcelFileTestCase;
protected $class = '\Maatwebsite\Clerk\Files\Csv';
protected $ext = 'csv';
}
| Maatwebsite/Clerk | tests/Files/CsvTest.php | PHP | lgpl-3.0 | 173 |
#region Dapplo 2017 - GNU Lesser General Public License
// Dapplo - building blocks for .NET applications
// Copyright (C) 2017 Dapplo
//
// For more information see: http://dapplo.net/
// Dapplo repositories are hosted on GitHub: https://github.com/dapplo
//
// This file is part of Dapplo.Jira
//
// Dapplo.Jira is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Dapplo.Jira is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have a copy of the GNU Lesser General Public License
// along with Dapplo.Jira. If not, see <http://www.gnu.org/licenses/lgpl.txt>.
#endregion
namespace Dapplo.Jira.Domains
{
/// <summary>
/// The marker interface of the user domain
/// </summary>
public interface IUserDomain : IJiraDomain
{
}
} | alfadormx/Dapplo.Jira | src/Dapplo.Jira/Domains/IUserDomain.cs | C# | lgpl-3.0 | 1,161 |
package tk.teemocode.module.base.vo;
import java.io.Serializable;
public class Vo implements Serializable, Cloneable {
private Long id;
private String uuid;
private Integer tag;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public Integer getTag() {
return tag;
}
public void setTag(Integer tag) {
this.tag = tag;
}
}
| yangylsky/teemocode | teemocode-modulebase/src/main/java/tk/teemocode/module/base/vo/Vo.java | Java | lgpl-3.0 | 520 |
/*******************************************************************************
* Copyright (c) 2011 Dipanjan Das
* Language Technologies Institute,
* Carnegie Mellon University,
* All Rights Reserved.
*
* IntCounter.java is part of SEMAFOR 2.0.
*
* SEMAFOR 2.0 is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SEMAFOR 2.0 is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with SEMAFOR 2.0. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package edu.cmu.cs.lti.ark.util.ds.map;
import gnu.trove.TObjectIntHashMap;
import gnu.trove.TObjectIntIterator;
import gnu.trove.TObjectIntProcedure;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Simple integer counter: stores integer values for keys; lookup on nonexistent keys returns 0.
* Stores the sum of all values and provides methods for normalizing them.
*
* A {@code null} key is allowed, although the Iterator returned by {@link #getIterator()}
* will not include an entry whose key is {@code null}.
*
* @author Nathan Schneider (nschneid)
* @since 2009-03-19
* @param <T> Type for keys
*/
public class IntCounter<T> extends AbstractCounter<T, Integer> implements java.io.Serializable {
private static final long serialVersionUID = -5622820446958578575L;
protected TObjectIntHashMap<T> m_map;
protected int m_sum = 0;
public final int DEFAULT_VALUE = 0;
public IntCounter() {
m_map = new TObjectIntHashMap<T>();
}
public IntCounter(TObjectIntHashMap<T> map) {
m_map = map;
int vals[] = map.getValues();
for (int val : vals) {
m_sum += val;
}
}
/**
* @param key
* @return The value stored for a particular key (if present), or 0 otherwise
*/
public int getT(T key) {
if (m_map.containsKey(key))
return m_map.get(key);
return DEFAULT_VALUE;
}
/** Calls {@link #getT(T)}; required for compliance with {@link Map} */
@SuppressWarnings("unchecked")
public Integer get(Object key) {
return getT((T)key);
}
/**
* @param key
* @param newValue
* @return Previous value for the key
*/
public int set(T key, int newValue) {
int preval = getT(key);
m_map.put(key, newValue);
m_sum += newValue - preval;
return preval;
}
/**
* Increments a value in the counter by 1.
* @param key
* @return The new value
*/
public int increment(T key) {
return incrementBy(key, 1);
}
/**
* Changes a value in the counter by adding the specified delta to its current value.
* @param key
* @param delta
* @return The new value
*/
public int incrementBy(T key, int delta) {
int curval = getT(key);
int newValue = curval+delta;
set(key, newValue);
return newValue;
}
/**
* Returns a new counter containing only keys with nonzero values in
* at least one of the provided counters. Each key's value is the
* number of counters in which it occurs.
*/
public static <T> IntCounter<T> or(Collection<IntCounter<? extends T>> counters) {
IntCounter<T> result = new IntCounter<T>();
for (IntCounter<? extends T> counter : counters) {
for (TObjectIntIterator<? extends T> iter = counter.getIterator();
iter.hasNext();) {
iter.advance();
if (iter.value()!=0)
result.increment(iter.key());
}
}
return result;
}
/**
* @return Sum of all values currently in the Counter
*/
public int getSum() {
return m_sum;
}
public IntCounter<T> add(final int val) {
final IntCounter<T> result = new IntCounter<T>();
m_map.forEachEntry(new TObjectIntProcedure<T>() {
private boolean first = true;
public boolean execute(T key, int value) {
if ( first ) first = false;
int newValue = value + val;
result.set(key, newValue);
return true;
}
});
return result;
}
/**
* @return Iterator for the counter. Ignores the {@code null} key (if present).
*/
public TObjectIntIterator<T> getIterator() {
return m_map.iterator();
}
@SuppressWarnings("unchecked")
public Set<T> keySet() {
Object[] okeys = m_map.keys();
HashSet<T> keyset = new HashSet<T>();
for(Object o:okeys) {
keyset.add((T)o);
}
return keyset;
}
/**
* @param valueThreshold
* @return New IntCounter containing only entries whose value equals or exceeds the given threshold
*/
public IntCounter<T> filter(int valueThreshold) {
IntCounter<T> result = new IntCounter<T>();
for (TObjectIntIterator<T> iter = getIterator();
iter.hasNext();) {
iter.advance();
T key = iter.key();
int value = getT(key);
if (value >= valueThreshold) {
result.set(key, value);
}
}
int nullValue = getT(null);
if (containsKey(null) && nullValue >= valueThreshold)
result.set(null, nullValue);
return result;
}
/** Calls {@link #containsKeyT(T)}; required for compliance with {@link Map} */
@SuppressWarnings("unchecked")
public boolean containsKey(Object key) {
return containsKeyT((T)key);
}
public boolean containsKeyT(T key) {
return m_map.containsKey(key);
}
public int size() {
return m_map.size();
}
public String toString() {
return toString(Integer.MIN_VALUE, null);
}
public String toString(int valueThreshold) {
return toString(valueThreshold, null);
}
/**
* @param sep Array with two Strings: an entry separator ("," by default, if this is {@code null}), and a key-value separator ("=" by default)
*/
public String toString(String[] sep) {
return toString(Integer.MIN_VALUE, sep);
}
/**
* @param valueThreshold
* @param sep Array with two Strings: an entry separator ("," by default, if this is {@code null}), and a key-value separator ("=" by default)
* @return A string representation of all (key, value) pairs such that the value equals or exceeds the given threshold
*/
public String toString(final int valueThreshold, String[] sep) {
String entrySep = ","; // default
String kvSep = "="; // default
if (sep!=null && sep.length>0) {
if (sep[0]!=null)
entrySep = sep[0];
if (sep.length>1 && sep[1]!=null)
kvSep = sep[1];
}
final String ENTRYSEP = entrySep;
final String KVSEP = kvSep;
final StringBuilder buf = new StringBuilder("{");
m_map.forEachEntry(new TObjectIntProcedure<T>() {
private boolean first = true;
public boolean execute(T key, int value) {
if (value >= valueThreshold) {
if ( first ) first = false;
else buf.append(ENTRYSEP);
buf.append(key);
buf.append(KVSEP);
buf.append(value);
}
return true;
}
});
buf.append("}");
return buf.toString();
}
public IntCounter<T> clone() {
return new IntCounter<T>(m_map.clone());
}
// Other methods implemented by the Map interface
@Override
public void clear() {
throw new UnsupportedOperationException("IntCounter.clear() unsupported");
}
@Override
public boolean containsValue(Object value) {
return m_map.containsValue((Integer)value);
}
@Override
public Set<java.util.Map.Entry<T, Integer>> entrySet() {
throw new UnsupportedOperationException("IntCounter.entrySet() unsupported");
}
@Override
public boolean isEmpty() {
return m_map.isEmpty();
}
@Override
public Integer put(T key, Integer value) {
return set(key,value);
}
@Override
public void putAll(Map<? extends T, ? extends Integer> m) {
throw new UnsupportedOperationException("IntCounter.putAll() unsupported");
}
@Override
public Integer remove(Object key) {
throw new UnsupportedOperationException("IntCounter.remove() unsupported");
}
@Override
public Collection<Integer> values() {
throw new UnsupportedOperationException("IntCounter.values() unsupported");
}
}
| jtraviesor/semafor-parser | semafor/src/main/java/edu/cmu/cs/lti/ark/util/ds/map/IntCounter.java | Java | lgpl-3.0 | 8,362 |
<?php
/**
* Custom factory for photos with method to get next sort order
*
* @package Modules
* @subpackage PhotoGallery
* @author Peter Epp
* @version $Id: photo_factory.php 13843 2011-07-27 19:45:49Z teknocat $
*/
class PhotoFactory extends ModelFactory {
/**
* Find and return the next sort order to use
*
* @return void
* @author Peter Epp
*/
public function next_sort_order($album_id) {
return parent::next_highest('sort_order',1,"`album_id` = {$album_id}");
}
}
| theteknocat/Biscuit-PhotoGallery | factories/photo_factory.php | PHP | lgpl-3.0 | 490 |
/*
* Copyright (C) 2010 Tieto Czech, s.r.o.
* All rights reserved.
* Contact: Tomáš Hanák <tomas.hanak@tieto.com>
* Radek Valášek <radek.valasek@tieto.com>
* Martin Kampas <martin.kampas@tieto.com>
* Jiří Litomyský <jiri.litomysky@tieto.com>
*
* This file is part of sfd [Simple Form Designer].
*
* SFD is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/*! \file
* \brief This is an automatically included header file.
*
* This file should mostly contain imports of things defined somewhere else.
* Usual piece of code put in this file is supposed to looks like
*
* \code
#include "path/to/some/header/file.hpp"
namespace sfd {
using some::symbol;
using some::other_symbol;
}
* \endcode
*
* \author Martin Kampas <martin.kampas@tieto.com>, 01/2010
*/
#pragma once
//////////////////////////////////////////////////////////////////////////////
// IMPORTS
#include "tools/PIMPL.hpp"
namespace sfd {
using tools::p_ptr;
}
//////////////////////////////////////////////////////////////////////////////
// OTHER STUFF
//! Redefinition to make use of GCC's __PRETTY_FUNCTION__
#define __func__ __PRETTY_FUNCTION__
//! Use it to mark deprecated symbols
#define SFD_DEPRECATED __attribute__((deprecated))
#include <QtCore/QDebug>
| tomhanak/form-designer | src/common.hpp | C++ | lgpl-3.0 | 1,967 |
/*
* Project: NextGIS Mobile
* Purpose: Mobile GIS for Android.
* Author: Dmitry Baryshnikov (aka Bishop), bishop.dev@gmail.com
* Author: NikitaFeodonit, nfeodonit@yandex.com
* Author: Stanislav Petriakov, becomeglory@gmail.com
* *****************************************************************************
* Copyright (c) 2015-2017, 2019 NextGIS, info@nextgis.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextgis.maplib.util;
import android.accounts.Account;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SyncInfo;
import android.os.Build;
import android.util.Base64;
import com.nextgis.maplib.api.IGISApplication;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;
import static com.nextgis.maplib.util.Constants.JSON_END_DATE_KEY;
import static com.nextgis.maplib.util.Constants.JSON_SIGNATURE_KEY;
import static com.nextgis.maplib.util.Constants.JSON_START_DATE_KEY;
import static com.nextgis.maplib.util.Constants.JSON_SUPPORTED_KEY;
import static com.nextgis.maplib.util.Constants.JSON_USER_ID_KEY;
import static com.nextgis.maplib.util.Constants.SUPPORT;
public class AccountUtil {
public static boolean isProUser(Context context) {
File support = context.getExternalFilesDir(null);
if (support == null)
support = new File(context.getFilesDir(), SUPPORT);
else
support = new File(support, SUPPORT);
try {
String jsonString = FileUtil.readFromFile(support);
JSONObject json = new JSONObject(jsonString);
if (json.optBoolean(JSON_SUPPORTED_KEY)) {
final String id = json.getString(JSON_USER_ID_KEY);
final String start = json.getString(JSON_START_DATE_KEY);
final String end = json.getString(JSON_END_DATE_KEY);
final String data = id + start + end + "true";
final String signature = json.getString(JSON_SIGNATURE_KEY);
return verifySignature(data, signature);
}
} catch (JSONException | IOException ignored) { }
return false;
}
private static boolean verifySignature(String data, String signature) {
try {
// add public key
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
String key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzbmnrTLjTLxqCnIqXgIJ\n" +
"jebXVOn4oV++8z5VsBkQwK+svDkGK/UcJ4YjXUuPqyiZwauHGy1wizGCgVIRcPNM\n" +
"I0n9W6797NMFaC1G6Rp04ISv7DAu0GIZ75uDxE/HHDAH48V4PqQeXMp01Uf4ttti\n" +
"XfErPKGio7+SL3GloEqtqGbGDj6Yx4DQwWyIi6VvmMsbXKmdMm4ErczWFDFHIxpV\n" +
"ln/VfX43r/YOFxqt26M7eTpaBIvAU6/yWkIsvidMNL/FekQVTiRCl/exPgioDGrf\n" +
"06z5a0sd3NDbS++GMCJstcKxkzk5KLQljAJ85Jciiuy2vv14WU621ves8S9cMISO\n" + "HwIDAQAB";
byte[] keyBytes = Base64.decode(key.getBytes("UTF-8"), Base64.DEFAULT);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
PublicKey publicKey = keyFactory.generatePublic(spec);
// verify signature
Signature signCheck = Signature.getInstance("SHA256withRSA");
signCheck.initVerify(publicKey);
signCheck.update(data.getBytes("UTF-8"));
byte[] sigBytes = Base64.decode(signature, Base64.DEFAULT);
return signCheck.verify(sigBytes);
} catch (Exception e) {
return false;
}
}
public static boolean isSyncActive(Account account, String authority) {
return isSyncActiveHoneycomb(account, authority);
}
public static boolean isSyncActiveHoneycomb(Account account, String authority) {
for (SyncInfo syncInfo : ContentResolver.getCurrentSyncs()) {
if (syncInfo.account.equals(account) && syncInfo.authority.equals(authority)) {
return true;
}
}
return false;
}
public static AccountData getAccountData(Context context, String accountName) throws IllegalStateException {
IGISApplication app = (IGISApplication) context.getApplicationContext();
Account account = app.getAccount(accountName);
if (null == account) {
throw new IllegalStateException("Account is null");
}
AccountData accountData = new AccountData();
accountData.url = app.getAccountUrl(account);
accountData.login = app.getAccountLogin(account);
accountData.password = app.getAccountPassword(account);
return accountData;
}
public static class AccountData {
public String url;
public String login;
public String password;
}
}
| nextgis/android_maplib | src/main/java/com/nextgis/maplib/util/AccountUtil.java | Java | lgpl-3.0 | 5,591 |
package edu.ucsd.arcum.interpreter.ast;
import java.util.List;
import java.util.Set;
import org.eclipse.core.runtime.CoreException;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import edu.ucsd.arcum.exceptions.ArcumError;
import edu.ucsd.arcum.exceptions.SourceLocation;
import edu.ucsd.arcum.interpreter.ast.expressions.ConstraintExpression;
import edu.ucsd.arcum.interpreter.query.EntityDataBase;
import edu.ucsd.arcum.interpreter.query.OptionMatchTable;
import edu.ucsd.arcum.util.StringUtil;
public class MapTraitArgument extends MapNameValueBinding
{
private RequireMap map;
private ConstraintExpression patternExpr;
private List<FormalParameter> formals;
// TODO: paramNames should be allowed to have the types explicit, just like
// any other realize statement
public MapTraitArgument(SourceLocation location, RequireMap map, String traitName,
List<FormalParameter> formals, ConstraintExpression patternExpr)
{
super(location, traitName);
this.map = map;
this.patternExpr = patternExpr;
this.formals = formals;
}
public void initializeValue(EntityDataBase edb, Option option, OptionMatchTable table)
throws CoreException
{
StaticRealizationStatement pseudoStmt;
OptionInterface optionIntf = option.getOptionInterface();
List<FormalParameter> allParams = optionIntf.getSingletonParameters();
List<FormalParameter> formals = null;
for (FormalParameter param : allParams) {
if (param.getIdentifier().equals(getName())) {
formals = param.getTraitArguments();
break;
}
}
if (formals == null) {
ArcumError.fatalUserError(getLocation(), "Couldn't find %s", getName());
}
pseudoStmt = StaticRealizationStatement.makeNested(map, getName(), patternExpr,
formals, this.getLocation());
pseudoStmt.typeCheckAndValidate(optionIntf);
List<StaticRealizationStatement> stmts = Lists.newArrayList(pseudoStmt);
try {
EntityDataBase.pushCurrentDataBase(edb);
RealizationStatement.collectivelyRealizeStatements(stmts, edb, table);
}
finally {
EntityDataBase.popMostRecentDataBase();
}
}
@Override public Object getValue() {
return this;
}
@Override public String toString() {
return String.format("%s(%s): %s", getName(), StringUtil.separate(formals),
patternExpr.toString());
}
public void checkUserDefinedPredicates(List<TraitSignature> tupleSets) {
Set<String> names = Sets.newHashSet();
names.addAll(Lists.transform(formals, FormalParameter.getIdentifier));
patternExpr.checkUserDefinedPredicates(tupleSets, names);
}
} | mshonle/Arcum | src/edu/ucsd/arcum/interpreter/ast/MapTraitArgument.java | Java | lgpl-3.0 | 2,934 |
package edu.hm.gamedev.server.packets.client2server;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonProperty;
import edu.hm.gamedev.server.packets.Packet;
import edu.hm.gamedev.server.packets.Type;
public class JoinGame extends Packet {
private final String gameName;
@JsonCreator
public JoinGame(@JsonProperty("gameName") String gameName) {
super(Type.JOIN_GAME);
this.gameName = gameName;
}
public String getGameName() {
return gameName;
}
@Override
public String toString() {
return "JoinGame{" +
"gameName='" + gameName + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
JoinGame joinGame = (JoinGame) o;
if (gameName != null ? !gameName.equals(joinGame.gameName) : joinGame.gameName != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (gameName != null ? gameName.hashCode() : 0);
return result;
}
}
| phxql/gamedev-server | src/main/java/edu/hm/gamedev/server/packets/client2server/JoinGame.java | Java | lgpl-3.0 | 1,227 |
#!/usr/bin/env python
import sys, argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', type=str, action='store', dest='input', default=None, help="Input file")
args = parser.parse_args()
stats = dict()
if args.input is None:
print "Error: No input file"
with open(args.input) as in_file:
for line in in_file.readlines():
time = int(line.split()[0])
tx_bytes = int(line.split()[1])
stats[time] = tx_bytes
stats = sorted(stats.items())
start_time = stats[0][0]
prev_tx = stats[0][1]
no_traffic_flag = True
for time, tx_bytes in stats:
if no_traffic_flag:
if tx_bytes > (prev_tx+100000):
no_traffic_flag = False
start_time, prev_tx = time, tx_bytes
else:
print (time-start_time), (tx_bytes-prev_tx)
prev_tx = tx_bytes
if __name__ == "__main__":
main()
| merlin-lang/kulfi | experiments/testbed/results/plot/sort.py | Python | lgpl-3.0 | 989 |
// Copyright 2017 The AriseID Authors
// This file is part AriseID.
//
// AriseID free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// AriseID distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with AriseID. If not, see <http://www.gnu.org/licenses/>.
package main
import (
"bytes"
"fmt"
"math/big"
"math/rand"
"time"
"github.com/ariseid/ariseid-core/common"
"github.com/ariseid/ariseid-core/core"
"github.com/ariseid/ariseid-core/log"
"github.com/ariseid/ariseid-core/params"
)
// makeGenesis creates a new genesis struct based on some user input.
func (w *wizard) makeGenesis() {
// Construct a default genesis block
genesis := &core.Genesis{
Timestamp: uint64(time.Now().Unix()),
LifeLimit: 4700000,
Difficulty: big.NewInt(1048576),
Alloc: make(core.GenesisAlloc),
Config: ¶ms.ChainConfig{
HomesteadBlock: big.NewInt(1),
EIP150Block: big.NewInt(2),
EIP155Block: big.NewInt(3),
EIP158Block: big.NewInt(3),
},
}
// Figure out which consensus engine to choose
fmt.Println()
fmt.Println("Which consensus engine to use? (default = clique)")
fmt.Println(" 1. Idhash - proof-of-work")
fmt.Println(" 2. Clique - proof-of-authority")
choice := w.read()
switch {
case choice == "1":
// In case of idhash, we're pretty much done
genesis.Config.Idhash = new(params.IdhashConfig)
genesis.ExtraData = make([]byte, 32)
case choice == "" || choice == "2":
// In the case of clique, configure the consensus parameters
genesis.Difficulty = big.NewInt(1)
genesis.Config.Clique = ¶ms.CliqueConfig{
Period: 15,
Epoch: 30000,
}
fmt.Println()
fmt.Println("How many seconds should blocks take? (default = 15)")
genesis.Config.Clique.Period = uint64(w.readDefaultInt(15))
// We also need the initial list of signers
fmt.Println()
fmt.Println("Which accounts are allowed to seal? (mandatory at least one)")
var signers []common.Address
for {
if address := w.readAddress(); address != nil {
signers = append(signers, *address)
continue
}
if len(signers) > 0 {
break
}
}
// Sort the signers and embed into the extra-data section
for i := 0; i < len(signers); i++ {
for j := i + 1; j < len(signers); j++ {
if bytes.Compare(signers[i][:], signers[j][:]) > 0 {
signers[i], signers[j] = signers[j], signers[i]
}
}
}
genesis.ExtraData = make([]byte, 32+len(signers)*common.AddressLength+65)
for i, signer := range signers {
copy(genesis.ExtraData[32+i*common.AddressLength:], signer[:])
}
default:
log.Crit("Invalid consensus engine choice", "choice", choice)
}
// Consensus all set, just ask for initial funds and go
fmt.Println()
fmt.Println("Which accounts should be pre-funded? (advisable at least one)")
for {
// Read the address of the account to fund
if address := w.readAddress(); address != nil {
genesis.Alloc[*address] = core.GenesisAccount{
Balance: new(big.Int).Lsh(big.NewInt(1), 256-7), // 2^256 / 128 (allow many pre-funds without balance overflows)
}
continue
}
break
}
// Add a batch of precompile balances to avoid them getting deleted
for i := int64(0); i < 256; i++ {
genesis.Alloc[common.BigToAddress(big.NewInt(i))] = core.GenesisAccount{Balance: big.NewInt(1)}
}
fmt.Println()
// Query the user for some custom extras
fmt.Println()
fmt.Println("Specify your chain/network ID if you want an explicit one (default = random)")
genesis.Config.ChainId = new(big.Int).SetUint64(uint64(w.readDefaultInt(rand.Intn(65536))))
fmt.Println()
fmt.Println("Anything fun to embed into the genesis block? (max 32 bytes)")
extra := w.read()
if len(extra) > 32 {
extra = extra[:32]
}
genesis.ExtraData = append([]byte(extra), genesis.ExtraData[len(extra):]...)
// All done, store the genesis and flush to disk
w.conf.genesis = genesis
}
| AriseID/ariseid-core | cmd/puppeth/wizard_genesis.go | GO | lgpl-3.0 | 4,285 |
package uk.co.wehavecookies56.kk.common.container.slot;
import net.minecraft.item.ItemStack;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.SlotItemHandler;
import uk.co.wehavecookies56.kk.common.item.ItemSynthesisBagS;
import uk.co.wehavecookies56.kk.common.item.base.ItemSynthesisMaterial;
public class SlotSynthesisBag extends SlotItemHandler {
public SlotSynthesisBag (IItemHandler inventory, int index, int x, int y) {
super(inventory, index, x, y);
}
@Override
public boolean isItemValid (ItemStack stack) {
return !(stack.getItem() instanceof ItemSynthesisBagS) && stack.getItem() instanceof ItemSynthesisMaterial;
}
}
| Wehavecookies56/Kingdom-Keys-Re-Coded | src/main/java/uk/co/wehavecookies56/kk/common/container/slot/SlotSynthesisBag.java | Java | lgpl-3.0 | 697 |
/*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.duplications.statement;
import org.sonar.duplications.statement.matcher.AnyTokenMatcher;
import org.sonar.duplications.statement.matcher.BridgeTokenMatcher;
import org.sonar.duplications.statement.matcher.ExactTokenMatcher;
import org.sonar.duplications.statement.matcher.ForgetLastTokenMatcher;
import org.sonar.duplications.statement.matcher.OptTokenMatcher;
import org.sonar.duplications.statement.matcher.TokenMatcher;
import org.sonar.duplications.statement.matcher.UptoTokenMatcher;
public final class TokenMatcherFactory {
private TokenMatcherFactory() {
}
public static TokenMatcher from(String token) {
return new ExactTokenMatcher(token);
}
public static TokenMatcher to(String... tokens) {
return new UptoTokenMatcher(tokens);
}
public static TokenMatcher bridge(String lToken, String rToken) {
return new BridgeTokenMatcher(lToken, rToken);
}
public static TokenMatcher anyToken() {
// TODO Godin: we can return singleton instance
return new AnyTokenMatcher();
}
public static TokenMatcher opt(TokenMatcher optMatcher) {
return new OptTokenMatcher(optMatcher);
}
public static TokenMatcher forgetLastToken() {
// TODO Godin: we can return singleton instance
return new ForgetLastTokenMatcher();
}
public static TokenMatcher token(String token) {
return new ExactTokenMatcher(token);
}
}
| SonarSource/sonarqube | sonar-duplications/src/main/java/org/sonar/duplications/statement/TokenMatcherFactory.java | Java | lgpl-3.0 | 2,239 |
package com.farevee.groceries;
public class BulkItem
implements Item
{
//+--------+------------------------------------------------------
// | Fields |
// +--------+
/**
* The type of food of the bulk item
*/
BulkFood food;
/**
* The unit of the bulk item
*/
Units unit;
/**
* The amount of bulk item
*/
int amount;
// +--------------+------------------------------------------------
// | Constructor |
// +--------------+
public BulkItem(BulkFood food, Units unit, int amount)
{
this.food = food;
this.unit = unit;
this.amount = amount;
} // BulkItem (BulkFood, Units, int)
//+-----------+---------------------------------------------------
// | Methods |
// +-----------+
/**
* Retrieve the Weight of BulkItem, including unit and amount
*/
public Weight getWeight()
{
return new Weight(this.unit, this.amount);
}//getWeight()
/**
* Retrieve the amount of Weight of BulkItem
*/
@Override
public int getWeightAmount()
{
return this.getWeight().amount;
}//getWeightAmount()
//Get the unit of weight
@Override
public Units getWeightUnit()
{
return this.unit;
}//getWeightUnit()
//Get the price
public int getPrice()
{
return this.food.pricePerUnit * this.amount;
}//getPrice()
//Creates a string for the name
public String toString()
{
return (amount + " " + unit.name + " of " + food.name);
}//toString()
//Gets the name
@Override
public String getName()
{
return this.food.name;
}//getName()
//Get the type of BulkFood
public BulkFood getBulkFoodType()
{
return this.food;
}//getBulkFoodType()
//Get the amount of BulkItem
public int getBulkItemAmount()
{
return this.amount;
}//getBulkItemAmount()
//Compares two BulkItem
public boolean equalZ(Object thing)
{
if (thing instanceof BulkItem)
{
BulkItem anotherBulkItem = (BulkItem) thing;
return ((this.food.name.equals(anotherBulkItem.food.name)) && (this.unit.name.equals(anotherBulkItem.unit.name)));
}
else
{
return Boolean.FALSE;
}
}//equals(Object)
public void increaseAmount(int x)
{
this.amount += x;
}//increaseAmount(int)
}
| lordzason/csc207-hw07-combined-with-hw06 | src/com/farevee/groceries/BulkItem.java | Java | lgpl-3.0 | 2,267 |
package org.logicobjects.converter.old;
import java.util.Arrays;
import java.util.List;
import org.jpc.term.Term;
import org.jpc.util.ParadigmLeakUtil;
import org.logicobjects.converter.IncompatibleAdapterException;
import org.logicobjects.converter.context.old.AdaptationContext;
import org.logicobjects.converter.context.old.AnnotatedElementAdaptationContext;
import org.logicobjects.converter.context.old.BeanPropertyAdaptationContext;
import org.logicobjects.converter.context.old.ClassAdaptationContext;
import org.logicobjects.converter.descriptor.LogicObjectDescriptor;
import org.logicobjects.core.LogicObject;
import org.logicobjects.methodadapter.LogicAdapter;
import org.minitoolbox.reflection.BeansUtil;
public class AnnotatedObjectToTermConverter<From> extends LogicAdapter<From, Term> {
@Override
public Term adapt(From object) {
return adapt(object, null);
}
public Term adapt(From object, AdaptationContext context) {
AnnotatedElementAdaptationContext annotatedContext;
if(context != null) {
if(understandsContext(context))
annotatedContext = (AnnotatedElementAdaptationContext)context;
else
throw new UnrecognizedAdaptationContextException(this.getClass(), context);
} else {
annotatedContext = new ClassAdaptationContext(object.getClass()); //the current context is null, then create default context
}
if(annotatedContext.hasObjectToTermConverter()) { //first check if there is an explicit adapter, in the current implementation, an Adapter annotation overrides any method invoker description
return adaptToTermWithAdapter(object, annotatedContext);
}
else if(annotatedContext.hasLogicObjectDescription()) {
return adaptToTermFromDescription(object, annotatedContext);
}
throw new IncompatibleAdapterException(this.getClass(), object);
}
protected Term adaptToTermWithAdapter(From object, AnnotatedElementAdaptationContext annotatedContext) {
ObjectToTermConverter termAdapter = annotatedContext.getObjectToTermConverter();
return termAdapter.adapt(object);
}
protected Term adaptToTermFromDescription(From object, AnnotatedElementAdaptationContext annotatedContext) {
LogicObjectDescriptor logicObjectDescription = annotatedContext.getLogicObjectDescription();
String logicObjectName = logicObjectDescription.name();
if(logicObjectName.isEmpty())
logicObjectName = infereLogicObjectName(annotatedContext);
List<Term> arguments;
String argsListPropertyName = logicObjectDescription.argsList();
if(argsListPropertyName != null && !argsListPropertyName.isEmpty()) {
BeanPropertyAdaptationContext adaptationContext = new BeanPropertyAdaptationContext(object.getClass(), argsListPropertyName);
Object argsListObject = BeansUtil.getProperty(object, argsListPropertyName, adaptationContext.getGuidingClass());
List argsList = null;
if(List.class.isAssignableFrom(argsListObject.getClass()))
argsList = (List) argsListObject;
else if(Object[].class.isAssignableFrom(argsListObject.getClass()))
argsList = Arrays.asList((Object[])argsListObject);
else
throw new RuntimeException("Property " + argsListPropertyName + " is neither a list nor an array");
arguments = new ObjectToTermConverter().adaptObjects(argsList, adaptationContext);
} else {
arguments = LogicObject.propertiesAsTerms(object, logicObjectDescription.args());
}
return new LogicObject(logicObjectName, arguments).asTerm();
}
/**
* In case the id is not explicitly specified (e.g., with an annotation), it will have to be inferred
* It can be inferred from a class id (if the transformation context is a class instance to a logic object), from a field id (if the context is the transformation of a field), etc
* Different context override this method to specify how they infer the logic id of the object
* @return
*/
public String infereLogicObjectName(AnnotatedElementAdaptationContext annotatedContext) {
return ParadigmLeakUtil.javaClassNameToProlog(annotatedContext.getGuidingClass().getSimpleName());
}
public static boolean understandsContext(AdaptationContext context) {
return context != null && context instanceof AnnotatedElementAdaptationContext;
}
}
| java-prolog-connectivity/logicobjects | src/main/java/org/logicobjects/converter/old/AnnotatedObjectToTermConverter.java | Java | lgpl-3.0 | 4,202 |
<?php
/**
* @copyright Copyright (c) Metaways Infosystems GmbH, 2011
* @license LGPLv3, http://www.arcavias.com/en/license
*/
return array(
'item' => array(
'delete' => '
DELETE FROM "mshop_product"
WHERE :cond AND siteid = ?
',
'insert' => '
INSERT INTO "mshop_product" (
"siteid", "typeid", "code", "suppliercode", "label", "status",
"start", "end", "mtime", "editor", "ctime"
) VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
)
',
'update' => '
UPDATE "mshop_product"
SET "siteid" = ?, "typeid" = ?, "code" = ?, "suppliercode" = ?,
"label" = ?, "status" = ?, "start" = ?, "end" = ?, "mtime" = ?,
"editor" = ?
WHERE "id" = ?
',
'search' => '
SELECT DISTINCT mpro."id", mpro."siteid", mpro."typeid",
mpro."label", mpro."status", mpro."start", mpro."end",
mpro."code", mpro."suppliercode", mpro."ctime", mpro."mtime",
mpro."editor"
FROM "mshop_product" AS mpro
:joins
WHERE :cond
/*-orderby*/ ORDER BY :order /*orderby-*/
LIMIT :size OFFSET :start
',
'count' => '
SELECT COUNT(*) AS "count"
FROM (
SELECT DISTINCT mpro."id"
FROM "mshop_product" AS mpro
:joins
WHERE :cond
LIMIT 10000 OFFSET 0
) AS list
',
),
);
| Arcavias/arcavias-core | lib/mshoplib/config/common/mshop/product/manager/default.php | PHP | lgpl-3.0 | 1,235 |
package net.anthavio.sewer.test;
import net.anthavio.sewer.ServerInstance;
import net.anthavio.sewer.ServerInstanceManager;
import net.anthavio.sewer.ServerMetadata;
import net.anthavio.sewer.ServerMetadata.CacheScope;
import net.anthavio.sewer.ServerType;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
/**
*
* public class MyCoolTests {
*
* @Rule
* private SewerRule sewer = new SewerRule(ServerType.JETTY, "src/test/jetty8", 0);
*
* @Test
* public void test() {
* int port = sewer.getServer().getLocalPorts()[0];
* }
*
* }
*
* Can interact with method annotations - http://www.codeaffine.com/2012/09/24/junit-rules/
*
* @author martin.vanek
*
*/
public class SewerRule implements TestRule {
private final ServerInstanceManager manager = ServerInstanceManager.INSTANCE;
private final ServerMetadata metadata;
private ServerInstance server;
public SewerRule(ServerType type, String home) {
this(type, home, -1, null, CacheScope.JVM);
}
public SewerRule(ServerType type, String home, int port) {
this(type, home, port, null, CacheScope.JVM);
}
public SewerRule(ServerType type, String home, int port, CacheScope cache) {
this(type, home, port, null, cache);
}
public SewerRule(ServerType type, String home, int port, String[] configs, CacheScope cache) {
this.metadata = new ServerMetadata(type, home, port, configs, cache);
}
public ServerInstance getServer() {
return server;
}
@Override
public Statement apply(Statement base, Description description) {
return new SewerStatement(base);
}
public class SewerStatement extends Statement {
private final Statement base;
public SewerStatement(Statement base) {
this.base = base;
}
@Override
public void evaluate() throws Throwable {
server = manager.borrowServer(metadata);
try {
base.evaluate();
} finally {
manager.returnServer(metadata);
}
}
}
}
| anthavio/anthavio-sewer | src/main/java/net/anthavio/sewer/test/SewerRule.java | Java | lgpl-3.0 | 1,989 |
/*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.ce.posttask;
/**
* @since 5.5
*/
public interface CeTask {
/**
* Id of the Compute Engine task.
* <p>
* This is the id under which the processing of the project analysis report has been added to the Compute Engine
* queue.
*
*/
String getId();
/**
* Indicates whether the Compute Engine task ended successfully or not.
*/
Status getStatus();
enum Status {
SUCCESS, FAILED
}
}
| lbndev/sonarqube | sonar-plugin-api/src/main/java/org/sonar/api/ce/posttask/CeTask.java | Java | lgpl-3.0 | 1,287 |
/*
Copyright 2013-2021 Paul Colby
This file is part of QtAws.
QtAws is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QtAws is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with the QtAws. If not, see <http://www.gnu.org/licenses/>.
*/
#include "applypendingmaintenanceactionrequest.h"
#include "applypendingmaintenanceactionrequest_p.h"
#include "applypendingmaintenanceactionresponse.h"
#include "rdsrequest_p.h"
namespace QtAws {
namespace RDS {
/*!
* \class QtAws::RDS::ApplyPendingMaintenanceActionRequest
* \brief The ApplyPendingMaintenanceActionRequest class provides an interface for RDS ApplyPendingMaintenanceAction requests.
*
* \inmodule QtAwsRDS
*
* <fullname>Amazon Relational Database Service</fullname>
*
*
* </p
*
* Amazon Relational Database Service (Amazon RDS) is a web service that makes it easier to set up, operate, and scale a
* relational database in the cloud. It provides cost-efficient, resizeable capacity for an industry-standard relational
* database and manages common database administration tasks, freeing up developers to focus on what makes their
* applications and businesses
*
* unique>
*
* Amazon RDS gives you access to the capabilities of a MySQL, MariaDB, PostgreSQL, Microsoft SQL Server, Oracle, or Amazon
* Aurora database server. These capabilities mean that the code, applications, and tools you already use today with your
* existing databases work with Amazon RDS without modification. Amazon RDS automatically backs up your database and
* maintains the database software that powers your DB instance. Amazon RDS is flexible: you can scale your DB instance's
* compute resources and storage capacity to meet your application's demand. As with all Amazon Web Services, there are no
* up-front investments, and you pay only for the resources you
*
* use>
*
* This interface reference for Amazon RDS contains documentation for a programming or command line interface you can use
* to manage Amazon RDS. Amazon RDS is asynchronous, which means that some interfaces might require techniques such as
* polling or callback functions to determine when a command has been applied. In this reference, the parameter
* descriptions indicate whether a command is applied immediately, on the next instance reboot, or during the maintenance
* window. The reference structure is as follows, and we list following some related topics from the user
*
* guide>
*
* <b>Amazon RDS API Reference</b>
*
* </p <ul> <li>
*
* For the alphabetical list of API actions, see <a
* href="https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_Operations.html">API
*
* Actions</a>> </li> <li>
*
* For the alphabetical list of data types, see <a
* href="https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_Types.html">Data
*
* Types</a>> </li> <li>
*
* For a list of common query parameters, see <a
* href="https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/CommonParameters.html">Common
*
* Parameters</a>> </li> <li>
*
* For descriptions of the error codes, see <a
* href="https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/CommonErrors.html">Common
*
* Errors</a>> </li> </ul>
*
* <b>Amazon RDS User Guide</b>
*
* </p <ul> <li>
*
* For a summary of the Amazon RDS interfaces, see <a
* href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Welcome.html#Welcome.Interfaces">Available RDS
*
* Interfaces</a>> </li> <li>
*
* For more information about how to use the Query API, see <a
* href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Using_the_Query_API.html">Using the Query
*
* \sa RdsClient::applyPendingMaintenanceAction
*/
/*!
* Constructs a copy of \a other.
*/
ApplyPendingMaintenanceActionRequest::ApplyPendingMaintenanceActionRequest(const ApplyPendingMaintenanceActionRequest &other)
: RdsRequest(new ApplyPendingMaintenanceActionRequestPrivate(*other.d_func(), this))
{
}
/*!
* Constructs a ApplyPendingMaintenanceActionRequest object.
*/
ApplyPendingMaintenanceActionRequest::ApplyPendingMaintenanceActionRequest()
: RdsRequest(new ApplyPendingMaintenanceActionRequestPrivate(RdsRequest::ApplyPendingMaintenanceActionAction, this))
{
}
/*!
* \reimp
*/
bool ApplyPendingMaintenanceActionRequest::isValid() const
{
return false;
}
/*!
* Returns a ApplyPendingMaintenanceActionResponse object to process \a reply.
*
* \sa QtAws::Core::AwsAbstractClient::send
*/
QtAws::Core::AwsAbstractResponse * ApplyPendingMaintenanceActionRequest::response(QNetworkReply * const reply) const
{
return new ApplyPendingMaintenanceActionResponse(*this, reply);
}
/*!
* \class QtAws::RDS::ApplyPendingMaintenanceActionRequestPrivate
* \brief The ApplyPendingMaintenanceActionRequestPrivate class provides private implementation for ApplyPendingMaintenanceActionRequest.
* \internal
*
* \inmodule QtAwsRDS
*/
/*!
* Constructs a ApplyPendingMaintenanceActionRequestPrivate object for Rds \a action,
* with public implementation \a q.
*/
ApplyPendingMaintenanceActionRequestPrivate::ApplyPendingMaintenanceActionRequestPrivate(
const RdsRequest::Action action, ApplyPendingMaintenanceActionRequest * const q)
: RdsRequestPrivate(action, q)
{
}
/*!
* Constructs a copy of \a other, with public implementation \a q.
*
* This copy-like constructor exists for the benefit of the ApplyPendingMaintenanceActionRequest
* class' copy constructor.
*/
ApplyPendingMaintenanceActionRequestPrivate::ApplyPendingMaintenanceActionRequestPrivate(
const ApplyPendingMaintenanceActionRequestPrivate &other, ApplyPendingMaintenanceActionRequest * const q)
: RdsRequestPrivate(other, q)
{
}
} // namespace RDS
} // namespace QtAws
| pcolby/libqtaws | src/rds/applypendingmaintenanceactionrequest.cpp | C++ | lgpl-3.0 | 6,272 |
var KevoreeEntity = require('./KevoreeEntity');
/**
* AbstractChannel entity
*
* @type {AbstractChannel} extends KevoreeEntity
*/
module.exports = KevoreeEntity.extend({
toString: 'AbstractChannel',
construct: function () {
this.remoteNodes = {};
this.inputs = {};
},
internalSend: function (portPath, msg) {
var remoteNodeNames = this.remoteNodes[portPath];
for (var remoteNodeName in remoteNodeNames) {
this.onSend(remoteNodeName, msg);
}
},
/**
*
* @param remoteNodeName
* @param msg
*/
onSend: function (remoteNodeName, msg) {
},
remoteCallback: function (msg) {
for (var name in this.inputs) {
this.inputs[name].getCallback().call(this, msg);
}
},
addInternalRemoteNodes: function (portPath, remoteNodes) {
this.remoteNodes[portPath] = remoteNodes;
},
addInternalInputPort: function (port) {
this.inputs[port.getName()] = port;
}
}); | barais/kevoree-js | library/kevoree-entities/lib/AbstractChannel.js | JavaScript | lgpl-3.0 | 938 |
package calc.lib;
/** Class (POJO) used to store Uninhabited Solar System JSON objects
*
* @author Carlin Robertson
* @version 1.0
*
*/
public class SolarSystemUninhabited {
private String[] information;
private String requirePermit;
private Coords coords;
private String name;
public String[] getInformation ()
{
return information;
}
public void setInformation (String[] information)
{
this.information = information;
}
public String getRequirePermit ()
{
return requirePermit;
}
public void setRequirePermit (String requirePermit)
{
this.requirePermit = requirePermit;
}
public Coords getCoords ()
{
return coords;
}
public void setCoords (Coords coords)
{
this.coords = coords;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
}
| TheJavaMagician/CalculusBot | src/main/java/calc/lib/SolarSystemUninhabited.java | Java | lgpl-3.0 | 977 |
<?php
require_once '../../../config.php';
require_once $config['root_path'] . '/system/functions.php';
include_once $config['system_path'] . '/start_system.php';
admin_login();
if (isset($_POST['delete']) && isset($_POST['id']) && isset($_SESSION['member']['access']['countries'])) {
require_once ROOT_PATH . '/applications/news/modeles/news.class.php';
$cms = new news();
$cms->delete(intval($_POST['id']));
die (
json_encode(
array_merge(
$_POST, array (
'status' => 'true'
)
)
)
);
}
echo json_encode (
array_merge (
$_POST, array (
'status' => 'unknown error'
)
)
);
die ();
?> | UniPixen/Niradrien | applications/news/ajax/delete.php | PHP | lgpl-3.0 | 681 |
// Catalano Fuzzy Library
// The Catalano Framework
//
// Copyright © Diego Catalano, 2013
// diego.catalano at live.com
//
// Copyright © Andrew Kirillov, 2007-2008
// andrew.kirillov at gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
package Catalano.Fuzzy;
/**
* Interface with the common methods of Fuzzy Unary Operator.
* @author Diego Catalano
*/
public interface IUnaryOperator {
/**
* Calculates the numerical result of a Unary operation applied to one fuzzy membership value.
* @param membership A fuzzy membership value, [0..1].
* @return The numerical result of the operation applied to <paramref name="membership"/>.
*/
float Evaluate( float membership );
}
| accord-net/java | Catalano.Fuzzy/src/Catalano/Fuzzy/IUnaryOperator.java | Java | lgpl-3.0 | 1,453 |
<?php
namespace Google\AdsApi\Dfp\v201708;
/**
* This file was generated from WSDL. DO NOT EDIT.
*/
class ReportQueryAdUnitView
{
const TOP_LEVEL = 'TOP_LEVEL';
const FLAT = 'FLAT';
const HIERARCHICAL = 'HIERARCHICAL';
}
| advanced-online-marketing/AOM | vendor/googleads/googleads-php-lib/src/Google/AdsApi/Dfp/v201708/ReportQueryAdUnitView.php | PHP | lgpl-3.0 | 240 |
package flabs.mods.magitech.aura;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.WorldSavedData;
public class AuraSavedData extends WorldSavedData{
public static final String nbtName="MagiAura";
public AuraSavedData(String name) {
super(name);
}
@Override
public void readFromNBT(NBTTagCompound nbttagcompound) {
System.out.println("Reading Aura Data");
}
@Override
public void writeToNBT(NBTTagCompound nbttagcompound) {
System.out.println("Writing Aura Data");
}
}
| froschi3b/Magitech | magitech_common/flabs/mods/magitech/aura/AuraSavedData.java | Java | lgpl-3.0 | 532 |
package edu.ut.mobile.network;
public class NetInfo{
//public static byte[] IPAddress = {Integer.valueOf("54").byteValue(),Integer.valueOf("73").byteValue(),Integer.valueOf("28").byteValue(),Integer.valueOf("236").byteValue()};
static byte[] IPAddress = {Integer.valueOf("192").byteValue(),Integer.valueOf("168").byteValue(),Integer.valueOf("1").byteValue(),Integer.valueOf("67").byteValue()};
static int port = 6000;
static int waitTime = 100000;
}
| huberflores/BenchmarkingAndroidx86 | Simulator/MobileOffloadSimulator/src/main/java/edu/ut/mobile/network/NetInfo.java | Java | lgpl-3.0 | 473 |
/*
Copyright 2009 Semantic Discovery, Inc. (www.semanticdiscovery.com)
This file is part of the Semantic Discovery Toolkit.
The Semantic Discovery Toolkit is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The Semantic Discovery Toolkit is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with The Semantic Discovery Toolkit. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sd.text;
import org.sd.io.FileUtil;
import org.sd.nlp.AbstractLexicon;
import org.sd.nlp.AbstractNormalizer;
import org.sd.nlp.Break;
import org.sd.nlp.BreakStrategy;
import org.sd.nlp.Categories;
import org.sd.nlp.Category;
import org.sd.nlp.CategoryFactory;
import org.sd.nlp.GeneralNormalizer;
import org.sd.nlp.GenericLexicon;
import org.sd.nlp.Lexicon;
import org.sd.nlp.LexiconPipeline;
import org.sd.nlp.TokenizationStrategy;
import org.sd.nlp.TokenizerWrapper;
import org.sd.nlp.StringWrapper;
import org.sd.util.PropertiesParser;
import org.sd.util.tree.Tree;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* Utility to find meaningful words in strings.
* <p>
* @author Spence Koehler
*/
public class MungedWordFinder {
private static final String UNDETERMINED_LETTER = "X";
private static final String UNDETERMINED_WORD = "U";
private static final String WORD = "W";
private static final String NUMBER = "N";
private static final String SEQUENCE = "S";
private static final String CONSTITUENT = "C";
private static final String[] CATEGORIES = new String[] {
UNDETERMINED_LETTER,
UNDETERMINED_WORD,
WORD,
NUMBER,
SEQUENCE,
CONSTITUENT,
};
private static final AbstractNormalizer NORMALIZER = GeneralNormalizer.getCaseInsensitiveInstance();
private static final BreakStrategy BREAK_STRATEGY = new MyBreakStrategy();
private static final Comparator<WordSequence> SEQUENCE_COMPARATOR = new Comparator<WordSequence>() {
public int compare(WordSequence ws1, WordSequence ws2) {
return ws1.size() - ws2.size();
}
public boolean equals(Object o) {
return this == o;
}
};
private CategoryFactory categoryFactory;
private Map<String, File> wordFiles;
private Map<String, String[]> wordSets;
private List<Lexicon> lexicons;
private TokenizerWrapper _tokenizerWrapper;
/**
* Construct without any dictionaries.
* <p>
* Add dictionaries to use for finding munged words using the
* addWordFile, addWordSet, and addLexicon methods.
*/
public MungedWordFinder() {
this.categoryFactory = new CategoryFactory(CATEGORIES);
this.wordFiles = new HashMap<String, File>();
this.wordSets = new HashMap<String, String[]>();
this.lexicons = new ArrayList<Lexicon>();
this._tokenizerWrapper = null;
}
/**
* Add a word file defining words to recognize.
*/
public final void addWordFile(String name, File wordFile) {
this.wordFiles.put(name, wordFile);
this._tokenizerWrapper = null; // force rebuild.
}
/**
* Add a word set defining words to recognize.
*/
public final void addWordSet(String name, String[] words) {
this.wordSets.put(name, words);
this._tokenizerWrapper = null; // force rebuild.
}
/**
* Add a lexicon defining words to recognize.
*/
public final void addLexicon(Lexicon lexicon) {
this.lexicons.add(lexicon);
this._tokenizerWrapper = null; // force rebuild.
}
protected final TokenizerWrapper getTokenizerWrapper() {
if (_tokenizerWrapper == null) {
try {
final Lexicon lexicon = new LexiconPipeline(buildLexicons());
_tokenizerWrapper = new TokenizerWrapper(
lexicon, categoryFactory,
TokenizationStrategy.Type.LONGEST_TO_SHORTEST,
NORMALIZER, BREAK_STRATEGY,
false, 0, false); //NOTE: lexicon should classify every token
}
catch (IOException e) {
throw new IllegalStateException(e);
}
}
return _tokenizerWrapper;
}
private final Lexicon[] buildLexicons() throws IOException {
final List<Lexicon> result = new ArrayList<Lexicon>();
final Category wordCategory = categoryFactory.getCategory(WORD);
// add a lexicon that identifies/recognizes number sequences.
result.add(new NumberLexicon(categoryFactory.getCategory(NUMBER)));
// add a lexicon for each wordSet
for (Map.Entry<String, String[]> wordSetEntry : wordSets.entrySet()) {
final String name = wordSetEntry.getKey();
final String[] terms = wordSetEntry.getValue();
final GenericLexicon genericLexicon =
new GenericLexicon(terms, NORMALIZER, wordCategory, false, true, false,
"name=" + name);
genericLexicon.setMaxNumWords(0); // disable "word" limit. each char counts as a word with our break strategy.
result.add(genericLexicon);
}
// add a lexicon for each wordFile
for (Map.Entry<String, File> wordFileEntry : wordFiles.entrySet()) {
final String name = wordFileEntry.getKey();
final File wordFile = wordFileEntry.getValue();
final GenericLexicon genericLexicon =
new GenericLexicon(FileUtil.getInputStream(wordFile),
NORMALIZER, wordCategory, false, true, false,
"name=" + name);
genericLexicon.setMaxNumWords(0); // disable "word" limit. each char counts as a word with our break strategy.
result.add(genericLexicon);
}
// add each lexicon
for (Lexicon lexicon : lexicons) {
result.add(lexicon);
}
// add a lexicon that identifies a single letter as unknown.
result.add(new UnknownLexicon(categoryFactory.getCategory(UNDETERMINED_LETTER)));
return result.toArray(new Lexicon[result.size()]);
//todo: what about conjugations?
}
public List<WordSequence> getBestSplits(String string) {
List<WordSequence> result = new ArrayList<WordSequence>();
final TokenizerWrapper tokenizerWrapper = getTokenizerWrapper();
final Tree<StringWrapper.SubString> tokenTree = tokenizerWrapper.tokenize(string);
final List<Tree<StringWrapper.SubString>> leaves = tokenTree.gatherLeaves();
int maxScore = -1;
for (Tree<StringWrapper.SubString> leaf : leaves) {
final WordSequence wordSequence = new WordSequence(leaf);
final int curScore = wordSequence.getScore();
if (curScore >= maxScore) {
if (curScore > maxScore) {
result.clear();
maxScore = curScore;
}
result.add(wordSequence);
}
}
if (result.size() > 0) {
Collections.sort(result, SEQUENCE_COMPARATOR);
}
return result;
}
public List<WordSequence> getBestDomainSplits(String domain) {
final int dotPos = domain.indexOf('.');
if (dotPos > 0 && dotPos < domain.length() - 1) {
final DetailedUrl dUrl = new DetailedUrl(domain);
domain = dUrl.getHost(false, false, false);
}
return getBestSplits(domain);
}
public String getSplitsAsString(List<WordSequence> splits) {
final StringBuilder result = new StringBuilder();
if (splits != null) {
for (Iterator<WordSequence> splitIter = splits.iterator(); splitIter.hasNext(); ) {
final WordSequence split = splitIter.next();
result.append(split.toString());
if (splitIter.hasNext()) result.append('|');
}
}
return result.toString();
}
// symbols are hard breaks... letters are soft breaks... consecutive digits aren't (don't break numbers)
private static final class MyBreakStrategy implements BreakStrategy {
public Break[] computeBreaks(int[] codePoints) {
final Break[] result = new Break[codePoints.length];
boolean inNumber = false;
for (int i = 0; i < codePoints.length; ++i) {
Break curBreak = Break.NONE;
final int cp = codePoints[i];
if (Character.isDigit(cp)) {
if (i > 0 && !inNumber && result[i - 1] != Break.HARD) {
curBreak = Break.SOFT_SPLIT;
}
else {
curBreak = Break.NONE;
}
inNumber = true;
}
else if (Character.isLetter(cp)) {
// first letter after a hard break (or at start) isn't a break
if (i == 0 || result[i - 1] == Break.HARD) {
curBreak = Break.NONE;
}
else {
curBreak = Break.SOFT_SPLIT;
}
inNumber = false;
}
else {
// if following a digit or with-digit-symbol, then consider the number parts as a whole
if (inNumber) {
curBreak = Break.NONE;
}
// else if a digit or digit-symbol follows, then consider the number parts as a whole
else if (i + 1 < codePoints.length &&
(Character.isDigit(codePoints[i + 1]) ||
(i + 2 < codePoints.length && Character.isDigit(codePoints[i + 2])))) {
curBreak = Break.NONE;
inNumber = true;
}
else {
curBreak = Break.HARD;
inNumber = false;
}
}
result[i] = curBreak;
}
return result;
}
}
private static final class NumberLexicon extends AbstractLexicon {
private Category category;
public NumberLexicon(Category category) {
super(null);
this.category = category;
}
/**
* Define applicable categories in the subString.
* <p>
* In this case, if a digit is found in the subString, then the NUMBER category is added.
*
* @param subString The substring to define.
* @param normalizer The normalizer to use.
*/
protected void define(StringWrapper.SubString subString, AbstractNormalizer normalizer) {
if (!subString.hasDefinitiveDefinition()) {
boolean isNumber = true;
int lastNumberPos = -1;
for (int i = subString.startPos; i < subString.endPos; ++i) {
final int cp = subString.stringWrapper.getCodePoint(i);
if (cp > '9' || cp < '0') {
isNumber = false;
break;
}
lastNumberPos = i;
}
if (!isNumber) {
// check for "text" numbers
if (lastNumberPos >= 0 && lastNumberPos == subString.endPos - 3) {
// check for number suffix
isNumber = TextNumber.isNumberEnding(subString.originalSubString.substring(lastNumberPos + 1).toLowerCase());
}
else if (lastNumberPos < 0) {
// check for number word
isNumber = TextNumber.isNumber(subString.originalSubString.toLowerCase());
}
}
if (isNumber) {
subString.setAttribute("name", NUMBER);
subString.addCategory(category);
subString.setDefinitive(true);
}
}
}
/**
* Determine whether the categories container already has category type(s)
* that this lexicon would add.
* <p>
* NOTE: this is used to avoid calling "define" when categories already exist
* for the substring.
*
* @return true if this lexicon's category type(s) are already present.
*/
protected boolean alreadyHasTypes(Categories categories) {
return categories.hasType(category);
}
}
private static final class UnknownLexicon extends AbstractLexicon {
private Category category;
public UnknownLexicon(Category category) {
super(null);
this.category = category;
}
/**
* Define applicable categories in the subString.
* <p>
* In this case, if a digit is found in the subString, then the NUMBER category is added.
*
* @param subString The substring to define.
* @param normalizer The normalizer to use.
*/
protected void define(StringWrapper.SubString subString, AbstractNormalizer normalizer) {
if (!subString.hasDefinitiveDefinition() && subString.length() == 1) {
subString.addCategory(category);
subString.setAttribute("name", UNDETERMINED_WORD);
}
}
/**
* Determine whether the categories container already has category type(s)
* that this lexicon would add.
* <p>
* NOTE: this is used to avoid calling "define" when categories already exist
* for the substring.
*
* @return true if this lexicon's category type(s) are already present.
*/
protected boolean alreadyHasTypes(Categories categories) {
return categories.hasType(category);
}
}
/**
* Container class for a word.
*/
public static final class Word {
public final StringWrapper.SubString word;
public final String type;
private Integer _score;
public Word(StringWrapper.SubString word, String type) {
this.word = word;
this.type = type;
this._score = null;
}
/**
* Get this word's score.
* <p>
* A word's score is its number of defined letters.
*/
public int getScore() {
if (_score == null) {
_score = UNDETERMINED_WORD.equals(type) ? 0 : word.length() * word.length();
}
return _score;
}
public String toString() {
final StringBuilder result = new StringBuilder();
result.append(type).append('=').append(word.originalSubString);
return result.toString();
}
}
/**
* Container for a sequence of words for a string.
*/
public static final class WordSequence {
public final String string;
public final List<Word> words;
private int score;
public WordSequence(Tree<StringWrapper.SubString> leaf) {
final LinkedList<Word> theWords = new LinkedList<Word>();
this.words = theWords;
this.score = 0;
String theString = null;
while (leaf != null) {
final StringWrapper.SubString subString = leaf.getData();
if (subString == null) break; // hit root.
final String nameValue = subString.getAttribute("name");
final Word word = new Word(subString, nameValue == null ? UNDETERMINED_WORD : nameValue);
theWords.addFirst(word);
score += word.getScore();
if (theString == null) theString = subString.stringWrapper.string;
leaf = leaf.getParent();
}
this.string = theString;
}
/**
* Get this sequence's score.
* <p>
* The score is the total number of defined letters in the sequence's words.
*/
public int getScore() {
return score;
}
public int size() {
return words.size();
}
public String toString() {
return asString(",");
}
public String asString(String delim) {
final StringBuilder result = new StringBuilder();
for (Iterator<Word> wordIter = words.iterator(); wordIter.hasNext(); ) {
final Word word = wordIter.next();
result.append(word.toString());
if (wordIter.hasNext()) result.append(delim);
}
// result.append('(').append(getScore()).append(')');
return result.toString();
}
}
//java -Xmx640m org.sd.nlp.MungedWordFinder wordSet="foo,bar,baz" wordSetName="fbb" foobarbaz "foo-bar-baz" "foobArbaz" gesundheit
public static final void main(String[] args) throws IOException {
// properties:
// wordFiles="file1,file2,..."
// wordSet="word1,word2,..."
// wordSetName="name"
// non-property arguments are munged strings to split.
// STDIN has other munged strings or domains to split.
final PropertiesParser propertiesParser = new PropertiesParser(args);
final Properties properties = propertiesParser.getProperties();
final String wordFileNames = properties.getProperty("wordFiles");
final String wordSet = properties.getProperty("wordSet");
final String wordSetName = properties.getProperty("wordSetName");
final MungedWordFinder mungedWordFinder = new MungedWordFinder();
if (wordFileNames != null) {
for (String wordFile : wordFileNames.split("\\s*,\\s*")) {
final File file = new File(wordFile);
mungedWordFinder.addWordFile(file.getName().split("\\.")[0], file);
}
}
if (wordSet != null) {
mungedWordFinder.addWordSet(wordSetName, wordSet.split("\\s*,\\s*"));
}
final String[] mungedWords = propertiesParser.getArgs();
for (String mungedWord : mungedWords) {
final List<WordSequence> splits = mungedWordFinder.getBestDomainSplits(mungedWord);
final String splitsString = mungedWordFinder.getSplitsAsString(splits);
System.out.println(mungedWord + "|" + splitsString);
}
final BufferedReader reader = FileUtil.getReader(System.in);
String line = null;
while ((line = reader.readLine()) != null) {
final List<WordSequence> splits = mungedWordFinder.getBestDomainSplits(line);
final String splitsString = mungedWordFinder.getSplitsAsString(splits);
System.out.println(line + "|" + splitsString);
}
reader.close();
}
}
| jtsay362/semanticdiscoverytoolkit-text | src/main/java/org/sd/text/MungedWordFinder.java | Java | lgpl-3.0 | 17,721 |
/*******************************************************************************
* Copyright (c) 2015 Open Software Solutions GmbH.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-3.0.html
*
* Contributors:
* Open Software Solutions GmbH
******************************************************************************/
package org.oss.pdfreporter.sql.factory;
import java.io.InputStream;
import java.util.Date;
import org.oss.pdfreporter.sql.IBlob;
import org.oss.pdfreporter.sql.IConnection;
import org.oss.pdfreporter.sql.IDate;
import org.oss.pdfreporter.sql.IDateTime;
import org.oss.pdfreporter.sql.ITime;
import org.oss.pdfreporter.sql.ITimestamp;
import org.oss.pdfreporter.sql.SQLException;
/**
* Sql connectivity factory.
* The interface supports queries with prepared statements.
* No DDL or modifying operations are supported, neither transactions or cursors.
* @author donatmuller, 2013, last change 5:39:58 PM
*/
public interface ISqlFactory {
/**
* Returns a connection for the connection parameter.
* It is up to the implementor to define the syntax of the connection parameter.<br>
* The parameter could include a driver class name or just an url and assume that a driver
* was already loaded.
* @param url
* @param user
* @param password
* @return
*/
IConnection newConnection(String url, String user, String password) throws SQLException;
/**
* used by dynamic loading of specific database driver and JDBC-URL, when the implementation don't know about the specific driver-implementation.
* @param jdbcUrl
* @param user
* @param password
* @return
* @throws SQLException
*/
IConnection createConnection(String jdbcUrl, String user, String password) throws SQLException;
/**
* Creates a Date.
* @param date
* @return
*/
IDate newDate(Date date);
/**
* Creates a Time.
* @param time
* @return
*/
ITime newTime(Date time);
/**
* Creates a Timestamp.
* @param timestamp
* @return
*/
ITimestamp newTimestamp(long milliseconds);
/**
* Creates a DateTime.
* @param datetime
* @return
*/
IDateTime newDateTime(Date datetime);
/**
* Creates a Blob.
* @param is
* @return
*/
IBlob newBlob(InputStream is);
/**
* Creates a Blob.
* @param bytes
* @return
*/
IBlob newBlob(byte[] bytes);
}
| OpenSoftwareSolutions/PDFReporter | pdfreporter-core/src/org/oss/pdfreporter/sql/factory/ISqlFactory.java | Java | lgpl-3.0 | 2,507 |
/*
* Copyright (C) 2005-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.repo.admin.registry;
import java.io.Serializable;
import java.util.Collection;
/**
* Interface for service providing access to key-value pairs for storage
* of system-controlled metadata.
*
* @author Derek Hulley
*/
public interface RegistryService
{
/**
* Assign a value to the registry key, which must be of the form <b>/a/b/c</b>.
*
* @param key the registry key.
* @param value any value that can be stored in the repository.
*/
void addProperty(RegistryKey key, Serializable value);
/**
* @param key the registry key.
* @return Returns the value stored in the key or <tt>null</tt> if
* no value exists at the path and name provided
*
* @see #addProperty(String, Serializable)
*/
Serializable getProperty(RegistryKey key);
/**
* Fetches all child elements for the given path. The key's property should be
* <tt>null</tt> as it is completely ignored.
* <code><pre>
* ...
* registryService.addValue(KEY_A_B_C_1, VALUE_ONE);
* registryService.addValue(KEY_A_B_C_2, VALUE_TWO);
* ...
* assertTrue(registryService.getChildElements(KEY_A_B_null).contains("C"));
* ...
* </pre></code>
*
* @param key the registry key with the path. The last element in the path
* will be ignored, and can be any acceptable value localname or <tt>null</tt>.
* @return Returns all child elements (not values) for the given key, ignoring
* the last element in the key.
*
* @see RegistryKey#getPath()
*/
Collection<String> getChildElements(RegistryKey key);
/**
* Copies the path or value from the source to the target location. The source and target
* keys <b>must</b> be both either path-specific or property-specific. If the source doesn't
* exist, then nothing will be done; there is no guarantee that the target will exist after
* the call.
* <p>
* This is essentially a merge operation. Use {@link #delete(RegistryKey) delete} first
* if the target must be cleaned.
*
* @param sourceKey the source registry key to take values from
* @param targetKey the target registyr key to move the path or value to
*/
void copy(RegistryKey sourceKey, RegistryKey targetKey);
/**
* Delete the path element or value described by the key. If the key points to nothing,
* then nothing is done.
* <code>delete(/a/b/c)</code> will remove value <b>c</b> from path <b>/a/b</b>.<br/>
* <code>delete(/a/b/null)</code> will remove node <b>/a/b</b> along with all values and child
* elements.
*
* @param key the path or value to delete
*/
void delete(RegistryKey key);
}
| loftuxab/community-edition-old | projects/repository/source/java/org/alfresco/repo/admin/registry/RegistryService.java | Java | lgpl-3.0 | 3,781 |
import java.util.*;
import Jakarta.util.FixDosOutputStream;
import java.io.*;
//------------------------ j2jBase layer -------------------
//------ mixin-layer for dealing with Overrides and New Modifier
//------ offhand, I wonder why we can't let j2j map these modifiers
//------ to nothing, instead of letting PJ do some of this mapping
// it would make more sense for PJ and Mixin to have similar
// output.
public class ModOverrides {
public void reduce2java( AstProperties props ) {
// Step 1: the overrides modifier should not be present, UNLESS
// there is a SoUrCe property. It's an error otherwise.
if ( props.getProperty( "SoUrCe" ) == null ) {
AstNode.error( tok[0], "overrides modifier should not be present" );
return;
}
// Step 2: it's OK to be present. If so, the reduction is to
// print the white-space in front for pretty-printing
props.print( getComment() );
}
}
| SergiyKolesnikov/fuji | examples/AHEAD/j2jBase/ModOverrides.java | Java | lgpl-3.0 | 1,048 |
# -*- coding: utf-8 -*-
"""digitalocean API to manage droplets"""
__version__ = "1.16.0"
__author__ = "Lorenzo Setale ( http://who.is.lorenzo.setale.me/? )"
__author_email__ = "lorenzo@setale.me"
__license__ = "LGPL v3"
__copyright__ = "Copyright (c) 2012-2020 Lorenzo Setale"
from .Manager import Manager
from .Droplet import Droplet, DropletError, BadKernelObject, BadSSHKeyFormat
from .Region import Region
from .Size import Size
from .Image import Image
from .Action import Action
from .Account import Account
from .Balance import Balance
from .Domain import Domain
from .Record import Record
from .SSHKey import SSHKey
from .Kernel import Kernel
from .FloatingIP import FloatingIP
from .Volume import Volume
from .baseapi import Error, EndPointError, TokenError, DataReadError, NotFoundError
from .Tag import Tag
from .LoadBalancer import LoadBalancer
from .LoadBalancer import StickySessions, ForwardingRule, HealthCheck
from .Certificate import Certificate
from .Snapshot import Snapshot
from .Project import Project
from .Firewall import Firewall, InboundRule, OutboundRule, Destinations, Sources
from .VPC import VPC
| koalalorenzo/python-digitalocean | digitalocean/__init__.py | Python | lgpl-3.0 | 1,128 |
/*
* Copyright (C) 2003-2014 eXo Platform SAS.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.exoplatform.social.core.storage.proxy;
import java.lang.reflect.Proxy;
import org.exoplatform.social.core.activity.model.ExoSocialActivity;
/**
* Created by The eXo Platform SAS
* Author : eXoPlatform
* exo@exoplatform.com
* Apr 28, 2014
*/
public class ActivityProxyBuilder {
@SuppressWarnings("unchecked")
static <T> T of(ProxyInvocation invocation) {
Class<?> targetClass = invocation.getTargetClass();
//1. loader - the class loader to define the proxy class
//2. the list of interfaces for the proxy class to implement
//3. the invocation handler to dispatch method invocations to
return (T) Proxy.newProxyInstance(targetClass.getClassLoader(),
new Class<?>[]{targetClass}, invocation);
}
public static <T> T of(Class<T> aClass, ExoSocialActivity activity) {
return of(new ProxyInvocation(aClass, activity));
}
}
| thanhvc/poc-sam | services/src/main/java/org/exoplatform/social/core/storage/proxy/ActivityProxyBuilder.java | Java | lgpl-3.0 | 1,655 |
<?php
namespace Tests\Browser\Pages\Admin;
use Laravel\Dusk\Browser;
use Laravel\Dusk\Page as BasePage;
class FilterAdd extends BasePage
{
/**
* Get the URL for the page.
*
* @return string
*/
public function url()
{
return '/admin/filter/create';
}
/**
* Assert that the browser is on the page.
*
* @param Browser $browser
* @return void
*/
public function assert(Browser $browser)
{
$browser->assertPathIs($this->url());
}
/**
* Get the element shortcuts for the page.
*
* @return array
*/
public function elements()
{
return [
'@status' => 'select[name="properties[status]"]',
'@display' => 'select[name="properties[display]"]',
'@displayCount' => 'input[name="properties[display_count]"]',
'@roundTo' => 'input[name="properties[other][round_to]"]',
'@title' => 'input[name="properties[title]"]',
'@type' => 'select[name="properties[type]"]',
'@feature' => 'select[name="properties[feature_id]"]',
'@categories' => 'select[name="categories[]"]',
'@submit' => '#submit'
];
}
}
| myindexd/laravelcms | tests/Browser/Pages/Admin/FilterAdd.php | PHP | lgpl-3.0 | 1,239 |
/*
* XAdES4j - A Java library for generation and verification of XAdES signatures.
* Copyright (C) 2010 Luis Goncalves.
*
* XAdES4j is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3 of the License, or any later version.
*
* XAdES4j is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License along
* with XAdES4j. If not, see <http://www.gnu.org/licenses/>.
*/
package xades4j.xml.unmarshalling;
import xades4j.algorithms.Algorithm;
import xades4j.properties.SignatureTimeStampProperty;
import xades4j.properties.data.SignatureTimeStampData;
import xades4j.xml.bind.xades.XmlUnsignedSignaturePropertiesType;
/**
*
* @author Luís
*/
class FromXmlSignatureTimeStampConverter
extends FromXmlBaseTimeStampConverter<SignatureTimeStampData>
implements UnsignedSigPropFromXmlConv
{
FromXmlSignatureTimeStampConverter()
{
super(SignatureTimeStampProperty.PROP_NAME);
}
@Override
public void convertFromObjectTree(
XmlUnsignedSignaturePropertiesType xmlProps,
QualifyingPropertiesDataCollector propertyDataCollector) throws PropertyUnmarshalException
{
super.convertTimeStamps(xmlProps.getSignatureTimeStamp(), propertyDataCollector);
}
@Override
protected SignatureTimeStampData createTSData(Algorithm c14n)
{
return new SignatureTimeStampData(c14n);
}
@Override
protected void setTSData(
SignatureTimeStampData tsData,
QualifyingPropertiesDataCollector propertyDataCollector)
{
propertyDataCollector.addSignatureTimeStamp(tsData);
}
}
| entaksi/xades4j | src/main/java/xades4j/xml/unmarshalling/FromXmlSignatureTimeStampConverter.java | Java | lgpl-3.0 | 1,991 |
/*
* Unitex
*
* Copyright (C) 2001-2014 Université Paris-Est Marne-la-Vallée <unitex@univ-mlv.fr>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*
*/
package fr.umlv.unitex.cassys;
public class ConfigurationFileAnalyser {
private String fileName;
private boolean mergeMode;
private boolean replaceMode;
private boolean disabled;
private boolean star;
private boolean commentFound;
/**
* @return the fileName
*/
public String getFileName() {
return fileName;
}
/**
* @return the mergeMode
*/
public boolean isMergeMode() {
return mergeMode;
}
/**
* @return the replaceMode
*/
public boolean isReplaceMode() {
return replaceMode;
}
/**
* @return the commentFound
*/
public boolean isCommentFound() {
return commentFound;
}
/**
*
* @return disabled
*/
public boolean isDisabled(){
return disabled;
}
public boolean isStar(){
return star;
}
public ConfigurationFileAnalyser(String line) throws EmptyLineException,
InvalidLineException {
// extract line comment
final String lineSubstring[] = line.split("#", 2);
if (lineSubstring.length > 1) {
commentFound = true;
}
if (lineSubstring[0] == null || lineSubstring[0].equals("")) {
throw new EmptyLineException();
}
final String lineCore[] = lineSubstring[0].split(" ");
if (!lineCore[0].startsWith("\"") || !lineCore[0].endsWith("\"")) {
throw new InvalidLineException(lineSubstring[0]
+ " --> FileName must start and end with quote\n");
}
lineCore[0] = lineCore[0].substring(1, lineCore[0].length() - 1);
if (lineCore.length > 1) {
fileName = lineCore[0];
if (lineCore[1].equals("M") || lineCore[1].equals("Merge")
|| lineCore[1].equals("merge")) {
mergeMode = true;
replaceMode = false;
} else if (lineCore[1].equals("R") || lineCore[1].equals("Replace")
|| lineCore[1].equals("replace")) {
mergeMode = false;
replaceMode = true;
} else {
throw new InvalidLineException(lineSubstring[0]
+ " --> Second argument should be Merge or Replace\n");
}
} else {
throw new InvalidLineException(
lineSubstring[0]
+ " --> FileName should be followed by a white space and Merge or Replace\n");
}
if(lineCore.length>2){
if(lineCore[2].equals("Disabled")||lineCore[2].equals("Disabled")){
disabled = true;
} else if(lineCore[2].equals("Enabled")){
disabled = false;
} else {
throw new InvalidLineException(lineSubstring[0]
+ " --> Third argument should be Disabled or Enabled\n");
}
if(lineCore.length>3){
if(lineCore[3].equals("*")){
star = true;
} else if(lineCore[3].equals("1")){
star = false;
} else {
throw new InvalidLineException(lineSubstring[0]
+ " --> Fourth argument should be 1 or *\n");
}
} else {
star = false;
}
} else {
disabled = false;
star = false;
}
}
public class InvalidLineException extends Exception {
public InvalidLineException(String s) {
super(s);
}
public InvalidLineException() {
/* NOP */
}
}
public class EmptyLineException extends Exception {
public EmptyLineException() {
/* NOP */
}
}
}
| mdamis/unilabIDE | Unitex-Java/src/fr/umlv/unitex/cassys/ConfigurationFileAnalyser.java | Java | lgpl-3.0 | 3,912 |
# Copyright (c) 2010 by Yaco Sistemas <pmartin@yaco.es>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this programe. If not, see <http://www.gnu.org/licenses/>.
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('autoreports.views',
url(r'^ajax/fields/tree/$', 'reports_ajax_fields', name='reports_ajax_fields'),
url(r'^ajax/fields/options/$', 'reports_ajax_fields_options', name='reports_ajax_fields_options'),
url(r'^(category/(?P<category_key>[\w-]+)/)?$', 'reports_list', name='reports_list'),
url(r'^(?P<registry_key>[\w-]+)/$', 'reports_api', name='reports_api'),
url(r'^(?P<registry_key>[\w-]+)/(?P<report_id>\d+)/$', 'reports_api', name='reports_api'),
url(r'^(?P<registry_key>[\w-]+)/reports/$', 'reports_api_list', name='reports_api_list'),
url(r'^(?P<registry_key>[\w-]+)/wizard/$', 'reports_api_wizard', name='reports_api_wizard'),
url(r'^(?P<registry_key>[\w-]+)/wizard/(?P<report_id>\d+)/$', 'reports_api_wizard', name='reports_api_wizard'),
url(r'^(?P<app_name>[\w-]+)/(?P<model_name>[\w-]+)/$', 'reports_view', name='reports_view'),
)
| Yaco-Sistemas/django-autoreports | autoreports/urls.py | Python | lgpl-3.0 | 1,686 |
<?php
/*!
* Schedule builder
*
* Copyright (c) 2011, Edwin Choi
*
* Licensed under LGPL 3.0
* http://www.gnu.org/licenses/lgpl-3.0.txt
*/
//ini_set("display_errors", 1);
//ini_set("display_startup_errors", 1);
date_default_timezone_set("GMT");
$timezone = date_default_timezone_get();
if ( !isset($_GET['p'])) {
header("HTTP/1.1 400 Bad Request");
header("Status: Bad Request");
exit;
}
$t_start = microtime(true);
$data = array();
require_once "./dbconnect.php";
require_once "./terminfo.php";
if ( !$conn ) {
header("HTTP/1.1 400 Bad Request");
header("Status: Bad Request");
echo "Failed to connect to DB: $conn->connect_error\n";
exit;
}
$headers = getallheaders();
if (isset($headers["If-Modified-Since"])) {
$lastmodcheck = strtotime($headers["If-Modified-Since"]);
if ($lastmodcheck >= $last_run_timestamp) {
header("HTTP/1.0 304 Not Modified");
exit;
}
}
if ( strpos($_GET['p'], '/') !== 0 ) {
header("HTTP/1.1 400 Bad Request");
header("Status: Bad Request");
echo "Invalid path spec";
exit;
}
$paths = explode(';', $_GET['p']);
if (count($paths) == 1) {
$path = explode('/', $paths[0]);
array_shift($path);
if (count($path) > 1 && $path[0] != "") {
$cond = "course = '" . implode("", $path) . "'";
} else {
$cond = "TRUE";
}
} else {
$names = array();
$cond = "";
foreach ($paths as $p) {
$path = explode('/', $p);
array_shift($path);
if (count($path) == 1 && $path[0] == "") {
continue;
}
if ($cond !== "")
$cond .= " OR\n";
$cond .= "course = '" . implode("", $path) . "'";
}
}
$result_array = array();
if (true) {
define("CF_SUBJECT" ,0);
define("CF_COURSE" ,0);
define("CF_TITLE" ,1);
define("CF_CREDITS" ,2);
//define("CF_SECTIONS" ,3);
//define("CF_CRSID" ,0);
/*
struct {
const char* course;
const char* title;
float credits;
struct {
const char* course;
const char* section;
short callnr;
const char* seats;
const char* instructor;
bool online;
bool honors;
const char* comments;
const char* alt_title;
const void* slots;
} sections[1];
};
*/
define("SF_COURSE" ,0);
define("SF_SECTION" ,1);
define("SF_CALLNR" ,2);
//define("SF_ENROLLED" ,3);
//define("SF_CAPACITY" ,4);
define("SF_SEATS" ,3);
define("SF_INSTRUCTOR" ,4);
define("SF_ONLINE" ,5);
define("SF_HONORS" ,6);
//define("SF_FLAGS" ,7);
define("SF_COMMENTS" ,7);
define("SF_ALT_TITLE" ,8);
define("SF_SLOTS" ,9);
define("SF_SUBJECT" ,10);
} else {
define("CF_CRSID", "_id");
define("CF_COURSE", "course");
define("CF_TITLE","title");
define("CF_CREDITS","credits");
define("CF_SECTIONS","sections");
define("SF_SUBJECT","subject");
define("SF_COURSE","course");
define("SF_SECTION","section");
define("SF_CALLNR","callnr");
define("SF_ENROLLED", "enrolled");
define("SF_CAPACITY", "capacity");
define("SF_SEATS","seats");
define("SF_INSTRUCTOR","instructor");
define("SF_ONLINE","online");
define("SF_HONORS","honors");
define("SF_FLAGS","flags");
define("SF_COMMENTS","comments");
define("SF_ALT_TITLE","alt_title");
define("SF_SLOTS", "slots");
}
$query = <<<_
SELECT
course, title, credits,
callnr, flags, section, enrolled, capacity, instructor, comments
FROM
NX_COURSE
WHERE
($cond)
_;
$res = $conn->query($query);
if ( !$res ) {
header("HTTP/1.1 400 Bad Request");
header("Status: Bad Request");
echo "MySQL Query Failed: $conn->error";
exit;
}
$num_sects = $res->num_rows;
class Flags {
const ONLINE = 1;
const HONORS = 2;
const ST = 4;
const CANCELLED = 8;
};
$map = array();
$ctable = array();
$result = array();
$secFields = array(SF_INSTRUCTOR, SF_COMMENTS, SF_ALT_TITLE);
$callnrToSlots = array();
while ($row = $res->fetch_row()) {
if (!isset($ctable[$row[0]])) {
$ctable[$row[0]] = array();
$arr = &$ctable[$row[0]];
$arr[CF_COURSE] = $row[0];
$arr[CF_TITLE] = $row[1];
$arr[CF_CREDITS] = floatval($row[2]);
if (defined("CF_SECTIONS"))
$arr[CF_SECTIONS] = array();
} else {
$arr = &$ctable[$row[0]];
}
if (defined("CF_SECTIONS")) {
$map[$row[3]] = array($row[0], count($arr[CF_SECTIONS]));
} else {
$map[$row[3]] = array($row[0], count($arr) - 3);
}
$sec = array();
$sec[SF_COURSE] = $row[0];
$sec[SF_SECTION] = $row[5];
$sec[SF_CALLNR] = intval($row[3]);
if (defined("SF_ENROLLED")) {
$sec[SF_ENROLLED] = intval($row[6]);
$sec[SF_CAPACITY] = intval($row[7]);
} else {
$sec[SF_SEATS] = "$row[6] / $row[7]";
}
$sec[SF_INSTRUCTOR] = $row[8];
if (defined("SF_FLAGS")) {
$sec[SF_FLAGS] = intval($row[4]);
} else {
$sec[SF_ONLINE] = ($row[4] & Flags::ONLINE) != 0;
$sec[SF_HONORS] = ($row[4] & Flags::HONORS) != 0;
}
$sec[SF_COMMENTS] = $row[9];
$sec[SF_ALT_TITLE] = $row[1];
$sec[SF_SLOTS] = array();
$callnrToSlots[$sec[SF_CALLNR]] = &$sec[SF_SLOTS];
if (defined("CF_SECTIONS"))
$arr[CF_SECTIONS][] = $sec;
else
$arr[] = $sec;
//$data[] = &$arr;
}
if (count($map) > 0) {
//$in_cond = 'callnr=' . implode(' OR callnr=', array_keys($map));
$in_cond = implode(',', array_keys($map));
$query = <<<_
SELECT DISTINCT callnr, day, TIME_TO_SEC(start), TIME_TO_SEC(end), room
FROM TIMESLOT
WHERE callnr IN ($in_cond)
_;
$res = $conn->query($query) or die("abc: $conn->error\nQuery: $query");
while ($row = $res->fetch_row()) {
$callnrToSlots[$row[0]][] = array(
/*"day" => */intval($row[1]),
/*"start" => */intval($row[2]),
/*"end" => */intval($row[3]),
/*"location" => */trim($row[4])
);
}
}
$data = array_values($ctable);
unset($ctable);
unset($map);
if (!defined("INTERNAL")) {
header("Content-Type: application/x-javascript");
header("Cache-Control: no-cache, private, must-revalidate");
header("Last-Modified: " . gmdate("D, d M Y H:i:s", $last_run_timestamp). " GMT");
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
echo "var COURSE_DATA = ";
}
// echo json_encode(array("data" => &$data, "t" => microtime(true) - $t_start, "n" => $num_sects));
echo json_encode($data);
/*
foreach($data as $row) {
$sects = $row[CF_SECTIONS];
$row[CF_SECTIONS] = array();
//unset($row[CF_SECTIONS]);
echo "db.courses.insert( " . json_encode($row) . " );\n";
echo "db.courses.ensureIndex({course:1});\n";
foreach($sects as $sec) {
foreach ($secFields as $nullable) {
if (!$sec[$nullable]) {
unset($sec[$nullable]);
}
}
if (count($sec[SF_SLOTS]) == 0)
unset($sec[SF_SLOTS]);
else
foreach($sec[SF_SLOTS] as &$slot) {
if ($slot["location"] == "") {
unset($slot["location"]);
}
}
echo "db.courses.update( { course:'" . $row[CF_COURSE] . "'}, { \$push: { " . CF_SECTIONS . ":". json_encode($sec) . " } } );\n";
}
}
*/
}
?>
| JoeParrinello/schedule-builder | datasvc.php | PHP | lgpl-3.0 | 6,667 |
<?php
return array(
'code' => 'ANG',
'sign' => 'f',
'sign_position' => 0,
'sign_delim' => '',
'title' => 'Netherlands Antillean guilder',
'name' => array(
array('', ''),
'NAƒ',
'NAf',
'ƒ',
),
'frac_name' => array(
array('cent', 'cents'),
)
); | dmitriyzhdankin/avantmarketcomua | wa-system/currency/data/ANG.php | PHP | lgpl-3.0 | 338 |
# encoding: utf-8
from __future__ import absolute_import, unicode_literals
from apiview.model import AbstractUserMixin, BaseModel
from django.contrib.auth.base_user import AbstractBaseUser
from django.db import models
class User(AbstractUserMixin, BaseModel, AbstractBaseUser):
is_staff = False
def get_short_name(self):
return self.name
def get_full_name(self):
return self.nickname
USERNAME_FIELD = 'username'
username = models.CharField('用户名', unique=True, max_length=64, editable=False, null=False, blank=False)
password = models.CharField('密码', max_length=128, unique=True, editable=False, null=False, blank=True)
nickname = models.CharField('昵称', unique=True, max_length=64, editable=False, null=False, blank=False)
class Meta:
db_table = 'example_user'
app_label = 'example_app'
verbose_name = verbose_name_plural = "用户"
| 007gzs/django_restframework_apiview | example/example_app/models.py | Python | lgpl-3.0 | 925 |
/**
* Copyright(C) 2009-2012
* @author Jing HUANG
* @file EtoileImageToTexturePlugin.cpp
* @brief
* @date 1/2/2011
*/
#include "EtoileImageToTexturePlugin.h"
#include "util/File.h"
#include "QtTextureLoader.h"
/**
* @brief For tracking memory leaks under windows using the crtdbg
*/
#if ( defined( _DEBUG ) || defined( DEBUG ) ) && defined( _MSC_VER )
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
#define new DEBUG_NEW
#endif
Etoile::EPlugin* loadEtoileImageToTexturePlugin()
{
return new Etoile::EtoileImageToTexturePlugin("ImageToTexture");
}
namespace Etoile
{
ImageToTextureStringInputSocket::ImageToTextureStringInputSocket(const std::string& name) : StringInputSocket(name)
{
}
void ImageToTextureStringInputSocket::perform(std::string* signal)
{
if(signal == NULL) return;
EtoileImageToTexturePlugin* plugin = (EtoileImageToTexturePlugin*)(this->getNode());
plugin->openFile(*signal);
}
void ImageToTextureStringInputSocket::retrieve(std::string* signal)
{
EtoileImageToTexturePlugin* plugin = (EtoileImageToTexturePlugin*)(this->getNode());
plugin->openFile("");
}
ImageToTextureOutputSocket::ImageToTextureOutputSocket(const std::string& name) : TextureOutputSocket(name)
{
}
EtoileImageToTexturePlugin::EtoileImageToTexturePlugin(const std::string& name): EPlugin(), SocketNode()
{
this->getType()._description = "ImageToTexture";
this->getType()._name = name;
this->getType()._w = 80;
this->getType()._h = 60;
this->getType()._color._r = 120;
this->getType()._color._g = 240;
this->getType()._color._b = 250;
this->getType()._color._a = 240;
_pInput = new ImageToTextureStringInputSocket();
this->addInputSocket(_pInput);
_pOutput = new ImageToTextureOutputSocket();
this->addOutputSocket(_pOutput);
}
EtoileImageToTexturePlugin::~EtoileImageToTexturePlugin()
{
}
void EtoileImageToTexturePlugin::openFile(const std::string& filename)
{
if(filename.empty()) return;
std::string ext = File::getFileExtension(filename);
Mesh *mesh = new Mesh(filename);
QtTextureLoader textureloader;
Texture* t = textureloader.loadFromFile(filename);
_pOutput->set(t);
_pOutput->signalEmit(t);
}
} | billhj/Etoile | applications/EtoileQtRendererPlugins/EtoileImageToTexturePlugin.cpp | C++ | lgpl-3.0 | 2,341 |
/*
* #--------------------------------------------------------------------------
* # Copyright (c) 2013 VITRO FP7 Consortium.
* # All rights reserved. This program and the accompanying materials
* # are made available under the terms of the GNU Lesser Public License v3.0 which accompanies this distribution, and is available at
* # http://www.gnu.org/licenses/lgpl-3.0.html
* #
* # Contributors:
* # Antoniou Thanasis (Research Academic Computer Technology Institute)
* # Paolo Medagliani (Thales Communications & Security)
* # D. Davide Lamanna (WLAB SRL)
* # Alessandro Leoni (WLAB SRL)
* # Francesco Ficarola (WLAB SRL)
* # Stefano Puglia (WLAB SRL)
* # Panos Trakadas (Technological Educational Institute of Chalkida)
* # Panagiotis Karkazis (Technological Educational Institute of Chalkida)
* # Andrea Kropp (Selex ES)
* # Kiriakos Georgouleas (Hellenic Aerospace Industry)
* # David Ferrer Figueroa (Telefonica Investigación y Desarrollo S.A.)
* #
* #--------------------------------------------------------------------------
*/
package vitro.vspEngine.service.common.abstractservice.dao;
import javax.persistence.EntityManager;
import vitro.vspEngine.logic.model.Gateway;
import vitro.vspEngine.service.common.abstractservice.model.ServiceInstance;
import vitro.vspEngine.service.persistence.DBRegisteredGateway;
import java.util.List;
public class GatewayDAO {
private static GatewayDAO instance = new GatewayDAO();
private GatewayDAO(){
super();
}
public static GatewayDAO getInstance(){
return instance;
}
/**
*
* @param manager
* @param incId the incremental auto id in the db
* @return
*/
public DBRegisteredGateway getGatewayByIncId(EntityManager manager, int incId){
DBRegisteredGateway dbRegisteredGateway = manager.find(DBRegisteredGateway.class, incId);
return dbRegisteredGateway;
}
/**
*
* @param manager
* @param name the gateway (registered) name
* @return
*/
public DBRegisteredGateway getGateway(EntityManager manager, String name){
StringBuffer sb = new StringBuffer();
sb.append("SELECT g ");
sb.append("FROM DBRegisteredGateway g ");
sb.append("WHERE g.registeredName = :gname ");
DBRegisteredGateway result = manager.createQuery(sb.toString(), DBRegisteredGateway.class).
setParameter("gname", name).
getSingleResult();
return result;
}
public List<DBRegisteredGateway> getInstanceList(EntityManager manager){
List<DBRegisteredGateway> result = manager.createQuery("SELECT instance FROM DBRegisteredGateway instance", DBRegisteredGateway.class).getResultList();
return result;
}
}
| vitrofp7/vitro | source/trunk/Demo/vitroUI/vspEngine/src/main/java/vitro/vspEngine/service/common/abstractservice/dao/GatewayDAO.java | Java | lgpl-3.0 | 2,739 |
package org.teaminfty.math_dragon.view.math.source.operation;
import static org.teaminfty.math_dragon.view.math.Expression.lineWidth;
import org.teaminfty.math_dragon.view.math.Empty;
import org.teaminfty.math_dragon.view.math.source.Expression;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
/** A class that represents a source for new {@link Root}s in the drag-and-drop interface */
public class Root extends Expression
{
/** The paint we use to draw the operator */
private Paint paintOperator = new Paint();
/** Default constructor */
public Root()
{
// Initialise the paint
paintOperator.setStyle(Paint.Style.STROKE);
paintOperator.setAntiAlias(true);
}
@Override
public org.teaminfty.math_dragon.view.math.Expression createMathObject()
{ return new org.teaminfty.math_dragon.view.math.operation.binary.Root(); }
@Override
public void draw(Canvas canvas, int w, int h)
{
// The width of the gap between the big box and the small box
final int gapWidth = (int) (3 * lineWidth);
// Get a boxes that fit the given width and height (we'll use it to draw the empty boxes)
// We'll want one big and one small (2/3 times the big one) box
Rect bigBox = getRectBoundingBox(3 * (w - gapWidth) / 5, 3 * h / 4, Empty.RATIO);
Rect smallBox = getRectBoundingBox(2 * (w - gapWidth) / 5, 2 * h / 4, Empty.RATIO);
// Position the boxes
smallBox.offsetTo((w - bigBox.width() - smallBox.width() - gapWidth) / 2, (h - bigBox.height() - smallBox.height() / 2) / 2);
bigBox.offsetTo(smallBox.right + gapWidth, smallBox.centerY());
// Draw the boxes
drawEmptyBox(canvas, bigBox);
drawEmptyBox(canvas, smallBox);
// Create a path for the operator
Path path = new Path();
path.moveTo(smallBox.left, smallBox.bottom + 2 * lineWidth);
path.lineTo(smallBox.right - 2 * lineWidth, smallBox.bottom + 2 * lineWidth);
path.lineTo(smallBox.right + 1.5f * lineWidth, bigBox.bottom - lineWidth / 2);
path.lineTo(smallBox.right + 1.5f * lineWidth, bigBox.top - 2 * lineWidth);
path.lineTo(bigBox.right, bigBox.top - 2 * lineWidth);
// Draw the operator
paintOperator.setStrokeWidth(lineWidth);
canvas.drawPath(path, paintOperator);
}
}
| Divendo/math-dragon | mathdragon/src/main/java/org/teaminfty/math_dragon/view/math/source/operation/Root.java | Java | lgpl-3.0 | 2,494 |
js.Offset = function(rawptr) {
this.rawptr = rawptr;
}
js.Offset.prototype = new konoha.Object();
js.Offset.prototype._new = function(rawptr) {
this.rawptr = rawptr;
}
js.Offset.prototype.getTop = function() {
return this.rawptr.top;
}
js.Offset.prototype.getLeft = function() {
return this.rawptr.left;
}
js.jquery = {};
var initJQuery = function() {
var verifyArgs = function(args) {
for (var i = 0; i < args.length; i++) {
if (args[i].rawptr) {
args[i] = args[i].rawptr;
}
}
return args;
}
var jquery = function(rawptr) {
this.rawptr = rawptr;
}
jquery.prototype = new konoha.Object();
jquery.konohaclass = "js.jquery.JQuery";
/* Selectors */
jquery.prototype.each_ = function(callback) {
this.rawptr.each(callback.rawptr);
}
jquery.prototype.size = function() {
return this.rawptr.size();
}
jquery.prototype.getSelector = function() {
return new konoha.String(this.rawptr.getSelector());
}
jquery.prototype.getContext = function() {
return new js.dom.Node(this.rawptr.getContext());
}
jquery.prototype.getNodeList = function() {
return new js.dom.NodeList(this.rawptr.get());
}
jquery.prototype.getNode = function(index) {
return new js.dom.Node(this.rawptr.get(index));
}
/* Attributes */
jquery.prototype.getAttr = function(arg) {
return new konoha.String(this.rawptr.attr(arg.rawptr));
}
jquery.prototype.attr = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.attr.apply(this.rawptr, args));
}
jquery.prototype.removeAttr = function(name) {
return new jquery(this.rawptr.removeAttr(name.rawptr));
}
jquery.prototype.addClass = function(className) {
return new jquery(this.rawptr.addClass(className.rawptr));
}
jquery.prototype.removeClass = function(className) {
return new jquery(this.rawptr.removeClass(className.rawptr));
}
jquery.prototype.toggleClass = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.toggleClass.apply(this.rawptr, args));
}
jquery.prototype.getHTML = function() {
return new konoha.String(this.rawptr.html());
}
jquery.prototype.html = function(val) {
return new jquery(this.rawptr.html(val.rawptr));
}
jquery.prototype.getText = function() {
return new konoha.String(this.rawptr.text());
}
jquery.prototype.text = function(val) {
return new jquery(this.rawptr.text(val.rawptr));
}
jquery.prototype.getVal = function() {
return new konoha.Array(this.rawptr.val())
}
jquery.prototype.val = function(val) {
return new jquery(this.rawptr.val(val.rawptr));
}
/* Traversing */
jquery.prototype.eq = function(position) {
return new jquery(this.rawptr.eq(position));
}
jquery.prototype.filter = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.filter.apply(this.rawptr, args));
}
jquery.prototype.is = function(expr) {
return this.rawptr.is(expr.rawptr);
}
jquery.prototype.opnot = function(expr) {
return this.rawptr.not(expr.rawptr);
}
jquery.prototype.slice = function() {
return new jquery(this.rawptr.slice.apply(this.rawptr, Array.prototype.slice.call(arguments)));
}
jquery.prototype.add = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.add.apply(this.rawptr, args));
}
jquery.prototype.children = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.children.apply(this.rawptr, args));
}
jquery.prototype.closest = function() {
var args =verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.closest.apply(this.rawptr, args));
}
jquery.prototype.contents = function() {
return new jquery(this.rawptr.contents());
}
jquery.prototype.find = function(expr) {
return new jquery(this.rawptr.find(expr.rawptr));
}
jquery.prototype.next = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.next.apply(this.rawptr, args));
}
jquery.prototype.nextAll = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.nextAll.apply(this.rawptr, args));
}
jquery.prototype.parent = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.parent.apply(this.rawptr, args));
}
jquery.prototype.parents = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.parents.apply(this.rawptr, args));
}
jquery.prototype.prev = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.prev.apply(this.rawptr, args));
}
jquery.prototype.prevAll = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.prevAll.apply(this.rawptr, args));
}
jquery.prototype.siblings = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.siblings.apply(this.rawptr, args));
}
jquery.prototype.andSelf = function() {
return new jquery(this.rawptr.andSelf());
}
jquery.prototype.end = function() {
return new jquery(this.rawptr.end());
}
/* Manipulation */
jquery.prototype.append = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.append.apply(this.rawptr, args));
}
jquery.prototype.appendTo = function(content) {
return new jquery(this.rawptr.appendTo(content.rawptr));
}
jquery.prototype.prepend = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.prepend.apply(this.rawptr, args));
}
jquery.prototype.prependTo = function(content) {
return new jquery(this.rawptr.prependTo(content.rawptr));
}
jquery.prototype.after = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.after.apply(this.rawptr, args));
}
jquery.prototype.before = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.before.apply(this.rawptr, args));
}
jquery.prototype.insertAfter = function(content) {
return new jquery(this.rawptr.insertAfter(content.rawptr));
}
jquery.prototype.insertBefore = function(content) {
return new jquery(this.rawptr.insertBefore(content.rawptr));
}
jquery.prototype.wrap = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.wrap.apply(this.rawptr, args));
}
jquery.prototype.wrapAll = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.wrapAll.apply(this.rawptr, args));
}
jquery.prototype.wrapInner = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.wrapInner.apply(this.rawptr, args));
}
jquery.prototype.replaceWith = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.replaceWith.apply(this.rawptr, args));
}
jquery.prototype.replaceAll = function(selector) {
return new jquery(this.rawptr.replaceAll(selector.rawptr));
}
jquery.prototype.empty = function() {
return new jquery(this.rawptr.empty());
}
jquery.prototype.remove = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.remove.apply(this.rawptr, args));
}
jquery.prototype.clone = function() {
return new jquery(this.rawptr.clone.apply(this.rawptr, Array.prototype.slice.call(arguments)));
}
/* CSS */
jquery.prototype.getCss = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new konoha.String(this.rawptr.css.apply(this.rawptr, args));
}
jquery.prototype.css = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.css.apply(this.rawptr, args));
}
jquery.prototype.offset = function() {
return new js.Offset(this.rawptr.offset());
}
jquery.prototype.position = function() {
return new js.Offset(this.rawptr.position());
}
jquery.prototype.scrollTop = function() {
return this.rawptr.scrollTop.apply(this.rawptr, Array.prototype.slice.call(arguments));
}
jquery.prototype.scrollLeft = function() {
return this.rawptr.scrollLeft.apply(this.rawptr, Array.prototype.slice.call(arguments));
}
jquery.prototype.height = function() {
return this.rawptr.height.apply(this.rawptr, Array.prototype.slice.call(arguments));
}
jquery.prototype.width = function() {
return this.rawptr.width.apply(this.rawptr, Array.prototype.slice.call(arguments));
}
jquery.prototype.innerHeight = function() {
return this.rawptr.innerHeight();
}
jquery.prototype.innerWidth = function() {
return this.rawptr.innerWidth();
}
jquery.prototype.outerHeight = function() {
return this.rawptr.outerHeight();
}
jquery.prototype.outerWidth = function() {
return this.rawptr.outerWidth();
}
/* Events */
jquery.prototype.ready = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.ready.apply(this.rawptr, args));
}
jquery.prototype.bind = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.bind.apply(this.rawptr, args));
}
jquery.prototype.one = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.one.apply(this.rawptr, args));
}
jquery.prototype.trigger = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.trigger.apply(this.rawptr, args));
}
jquery.prototype.triggerHandler = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.triggerHandler.apply(this.rawptr, args));
}
jquery.prototype.unbind = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.unbind.apply(this.rawptr, args));
}
jquery.prototype.hover = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.hover.apply(this.rawptr, args));
}
jquery.prototype.toggleEvent = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
args = verifyArgs(args[0]);
return new jquery(this.rawptr.toggle.apply(this.rawptr, args));
}
jquery.prototype.live = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.live.apply(this.rawptr, args));
}
jquery.prototype.die = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.die.apply(this.rawptr, args));
}
jquery.prototype.blur = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
if (args.length == 0) {
return new jquery(this.rawptr.blur.apply(this.rawptr, args));
} else {
return new jquery(this.rawptr.blur(function(e) {
args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]);
}));
}
}
jquery.prototype.change = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
if (args.length == 0) {
return new jquery(this.rawptr.change.apply(this.rawptr, args));
} else {
return new jquery(this.rawptr.change(function(e) {
args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]);
}));
}
}
jquery.prototype.click = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
if (args.length == 0) {
return new jquery(this.rawptr.click.apply(this.rawptr, args));
} else {
return new jquery(this.rawptr.click(function(e) {
args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]);
}));
}
}
jquery.prototype.dblclick = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
if (args.length == 0) {
return new jquery(this.rawptr.dblclick.apply(this.rawptr, args));
} else {
return new jquery(this.rawptr.dblclick(function(e) {
args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]);
}));
}
}
jquery.prototype.error = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
if (args.length == 0) {
return new jquery(this.rawptr.error.apply(this.rawptr, args));
} else {
return new jquery(this.rawptr.error(function(e) {
args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]);
}));
}
}
jquery.prototype.focus = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
if (args.length == 0) {
return new jquery(this.rawptr.focus.apply(this.rawptr, args));
} else {
return new jquery(this.rawptr.focus(function(e) {
args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]);
}));
}
}
jquery.prototype.keydown = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
if (args.length == 0) {
return new jquery(this.rawptr.keydown.apply(this.rawptr, args));
} else {
return new jquery(this.rawptr.keydown(function(e) {
args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]);
}));
}
}
jquery.prototype.keypress = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
if (args.length == 0) {
return new jquery(this.rawptr.keypress.apply(this.rawptr, args));
} else {
return new jquery(this.rawptr.keypress(function(e) {
args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]);
}));
}
}
jquery.prototype.keyup = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
if (args.length == 0) {
return new jquery(this.rawptr.keyup.apply(this.rawptr, args));
} else {
return new jquery(this.rawptr.keyup(function(e) {
args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]);
}));
}
}
jquery.prototype.load = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
if (args.length == 0) {
return new jquery(this.rawptr.load.apply(this.rawptr, args));
} else {
return new jquery(this.rawptr.load(function(e) {
args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]);
}));
}
}
jquery.prototype.mousedown = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
if (args.length == 0) {
return new jquery(this.rawptr.mousedown.apply(this.rawptr, args));
} else {
return new jquery(this.rawptr.mousedown(function(e) {
args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]);
}));
}
}
jquery.prototype.mousemove = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
if (args.length == 0) {
return new jquery(this.rawptr.mousemove.apply(this.rawptr, args));
} else {
return new jquery(this.rawptr.mousemove(function(e) {
args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]);
}));
}
}
jquery.prototype.mouseout = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
if (args.length == 0) {
return new jquery(this.rawptr.mouseout.apply(this.rawptr, args));
} else {
return new jquery(this.rawptr.mouseout(function(e) {
args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]);
}));
}
}
jquery.prototype.mouseover = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
if (args.length == 0) {
return new jquery(this.rawptr.mouseover.apply(this.rawptr, args));
} else {
return new jquery(this.rawptr.mouseover(function(e) {
args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]);
}));
}
}
jquery.prototype.mouseup = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
if (args.length == 0) {
return new jquery(this.rawptr.mouseup.apply(this.rawptr, args));
} else {
return new jquery(this.rawptr.mouseup(function(e) {
args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]);
}));
}
}
jquery.prototype.resize = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
if (args.length == 0) {
return new jquery(this.rawptr.resize.apply(this.rawptr, args));
} else {
return new jquery(this.rawptr.resize(function(e) {
args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]);
}));
}
}
jquery.prototype.scroll = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
if (args.length == 0) {
return new jquery(this.rawptr.scroll.apply(this.rawptr, args));
} else {
return new jquery(this.rawptr.scroll(function(e) {
args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]);
}));
}
}
jquery.prototype.select = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
if (args.length == 0) {
return new jquery(this.rawptr.select.apply(this.rawptr, args));
} else {
return new jquery(this.rawptr.select(function(e) {
args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]);
}));
}
}
jquery.prototype.submit = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
if (args.length == 0) {
return new jquery(this.rawptr.submit.apply(this.rawptr, args));
} else {
return new jquery(this.rawptr.select(function(e) {
args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]);
}));
}
}
jquery.prototype.unload = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
if (args.length == 0) {
return new jquery(this.rawptr.unload.apply(this.rawptr, args));
} else {
return new jquery(this.rawptr.unload(function(e) {
args[0].apply(new js.dom.Element(this), [new js.jquery.JEvent(e)]);
}));
}
}
/* Effects */
jquery.prototype.show = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.show.apply(this.rawptr, args));
}
jquery.prototype.hide = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.hide.apply(this.rawptr, args));
}
jquery.prototype.toggle = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.toggle.apply(this.rawptr, args));
}
jquery.prototype.slideDown = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.slideDown.apply(this.rawptr, args));
}
jquery.prototype.slideUp = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.slideUp.apply(this.rawptr, args));
}
jquery.prototype.slideToggle = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.slideToggle.apply(this.rawptr, args));
}
jquery.prototype.fadeIn = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.fadeIn.apply(this.rawptr, args));
}
jquery.prototype.fadeOut = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.fadeOut.apply(this.rawptr, args));
}
jquery.prototype.fadeTo = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
return new jquery(this.rawptr.fadeTo.apply(this.rawptr, args));
}
jquery.prototype._new = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
if (arguments.length == 1) {
this.rawptr = new $(args[0]);
} else if (arguments.length == 2) {
this.rawptr = new $(args[0], args[1]);
} else {
throw ("Script !!");
}
return this;
}
return jquery;
}
js.jquery.JQuery = new initJQuery();
js.jquery.JEvent = new function() {
var jevent = function(rawptr) {
this.rawptr = rawptr;
}
jevent.prototype = new konoha.Object();
jevent.konohaclass = "js.jquery.JEvent";
jevent.prototype.type = function() {
return new konoha.String(this.rawptr.type);
}
jevent.prototype.target = function() {
return new konoha.dom.Element(this.rawptr.target);
}
jevent.prototype.relatedTarget = function() {
return new konoha.dom.Element(this.rawptr.relatedTarget);
}
jevent.prototype.currentTarget = function() {
return new konoha.dom.Element(this.rawptr.currentTarget);
}
jevent.prototype.pageX = function() {
return this.rawptr.pageX;
}
jevent.prototype.pageY = function() {
return this.rawptr.pageY;
}
jevent.prototype.timeStamp = function() {
return this.rawptr.timeStamp;
}
jevent.prototype.preventDefault = function() {
return new jevent(this.rawptr.preventDefault());
}
jevent.prototype.isDefaultPrevented = function() {
return this.rawptr.isDefaultPrevented();
}
jevent.prototype.stopPropagation = function() {
return new jevent(this.rawptr.stopPropagation());
}
jevent.prototype.isPropagationStopped = function() {
return this.rawptr.isPropagationStopped();
}
jevent.prototype.stopImmediatePropagation = function() {
return new jevent(this.rawptr.stopImmediatePropagation());
}
jevent.prototype.isImmediatePropagationStopped = function() {
return this.rawptr.isImmediatePropagationStopped();
}
jevent.prototype._new = function() {
var args = verifyArgs(Array.prototype.slice.call(arguments));
if (arguments.length == 1) {
this.rawptr = new $(args[0]);
} else if (arguments.length == 2) {
this.rawptr = new $(args[0], args[1]);
} else {
throw ("Script !!");
}
return this;
}
return jevent;
}();
| imasahiro/konohascript | package/konoha.compiler.js/runtime/js.jquery.js | JavaScript | lgpl-3.0 | 24,892 |
package br.gov.serpro.infoconv.proxy.businesscontroller;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import br.gov.frameworkdemoiselle.stereotype.BusinessController;
import br.gov.serpro.infoconv.proxy.exception.AcessoNegadoException;
import br.gov.serpro.infoconv.proxy.exception.CNPJNaoEncontradoException;
import br.gov.serpro.infoconv.proxy.exception.CpfNaoEncontradoException;
import br.gov.serpro.infoconv.proxy.exception.DadosInvalidosException;
import br.gov.serpro.infoconv.proxy.exception.InfraException;
import br.gov.serpro.infoconv.proxy.exception.PerfilInvalidoException;
import br.gov.serpro.infoconv.proxy.rest.dto.cnpj.Perfil1CNPJ;
import br.gov.serpro.infoconv.proxy.rest.dto.cnpj.Perfil2CNPJ;
import br.gov.serpro.infoconv.proxy.rest.dto.cnpj.Perfil3CNPJ;
import br.gov.serpro.infoconv.proxy.util.InfoconvConfig;
import br.gov.serpro.infoconv.ws.cnpj.ArrayOfCNPJPerfil1;
import br.gov.serpro.infoconv.ws.cnpj.ArrayOfCNPJPerfil2;
import br.gov.serpro.infoconv.ws.cnpj.ArrayOfCNPJPerfil3;
import br.gov.serpro.infoconv.ws.cnpj.CNPJPerfil1;
import br.gov.serpro.infoconv.ws.cnpj.CNPJPerfil2;
import br.gov.serpro.infoconv.ws.cnpj.CNPJPerfil3;
/**
* Classe responsável por interagir com o componente infoconv-ws para obter as
* consultas de cnpj e transformar os erros previstos em exceções.
*
*/
@BusinessController
public class ConsultaCNPJBC {
/** Classe de configuração do infoconv. */
@Inject
InfoconvConfig infoconv;
private static final String CPF_CONSULTANTE = "79506240949";
/**
* Verifica a propriedade ERRO para saber se houve algum problema na
* consulta.
*
* Como se trata de um webservice sempre retorna com codigo http 200 e
* dentro da msg de retorno o campo "erro" informa se teve algum problema.
*
* Alguns "erros" são na verdade avisos por isso não levantam exceção. segue
* os erros que levantam exceção:
*
* - AcessoNegadoException: Todos os erros que começãm com ACS - Erro. Podem
* ser por falta de permissão ou algum problema com certificado. A mensagem
* explica qual o problema.
*
* - CNPJNaoEncontradoException: Quando o cpf não está na base. Erros: CPJ
* 04
*
* - DadosInvalidosException: Qualquer problema de validação no servidor.
* Erros: CPJ 02,06 e 11
*
* - InfraException: Erros no lado do servidor (WS) Erros: CPF 00 , 01, 03,
* 08, 09
*
* Documentação dos códigos de Erros:
* https://github.com/infoconv/infoconv-ws
*
* @param response
* @throws AcessoNegadoException
* @throws DadosInvalidosException
* @throws InfraException
* @throws CNPJNaoEncontradoException
*/
private void verificarErros(final Object retorno)
throws AcessoNegadoException, DadosInvalidosException, InfraException, CNPJNaoEncontradoException {
try {
Class<?> c = retorno.getClass();
Field erroField = c.getDeclaredField("erro");
erroField.setAccessible(true);
String erroMsg = (String) erroField.get(retorno);
if (erroMsg.indexOf("ACS - Erro") > -1) {
throw new AcessoNegadoException(erroMsg);
} else if (erroMsg.indexOf("CPJ - Erro 04") > -1) {
throw new CNPJNaoEncontradoException(erroMsg);
} else if (erroMsg.indexOf("CPJ - Erro 02") > -1
|| erroMsg.indexOf("CPJ - Erro 06") > -1
|| erroMsg.indexOf("CPJ - Erro 11") > -1) {
throw new DadosInvalidosException(erroMsg);
} else if (erroMsg.indexOf("CPJ - Erro 01") > -1
|| erroMsg.indexOf("CPJ - Erro 03") > -1
|| erroMsg.indexOf("CPJ - Erro 00") > -1
|| erroMsg.indexOf("CPJ - Erro 08") > -1
|| erroMsg.indexOf("CPJ - Erro 09") > -1) {
throw new InfraException(erroMsg);
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
/**
* Baseado no perfil indicado monta uma lista generia com o tipo de CNPJ do
* perfil como Object.
*
* @param listaCNPJs
* @param perfil
* @return
* @throws PerfilInvalidoException
* @throws InfraException
* @throws DadosInvalidosException
* @throws AcessoNegadoException
* @throws CNPJNaoEncontradoException
*/
public List<Object> consultarListaDeCnpjPorPerfil(final String listaCNPJs, final String perfil)
throws PerfilInvalidoException, AcessoNegadoException, DadosInvalidosException,
InfraException, CNPJNaoEncontradoException {
List<Object> lista = new ArrayList<Object>();
String perfilUpper = perfil.toUpperCase();
if (perfil == null || "P1".equals(perfilUpper)) {
ArrayOfCNPJPerfil1 p = infoconv.consultarCNPJSoap.consultarCNPJP1(listaCNPJs, CPF_CONSULTANTE);
lista.addAll(p.getCNPJPerfil1());
} else if ("P1T".equals(perfilUpper)) {
ArrayOfCNPJPerfil1 p = infoconv.consultarCNPJSoap.consultarCNPJP1T(listaCNPJs, CPF_CONSULTANTE);
lista.addAll(p.getCNPJPerfil1());
} else if ("P2".equals(perfilUpper)) {
ArrayOfCNPJPerfil2 p = infoconv.consultarCNPJSoap.consultarCNPJP2(listaCNPJs, CPF_CONSULTANTE);
lista.addAll(p.getCNPJPerfil2());
} else if ("P2T".equals(perfilUpper)) {
ArrayOfCNPJPerfil2 p = infoconv.consultarCNPJSoap.consultarCNPJP2T(listaCNPJs, CPF_CONSULTANTE);
lista.addAll(p.getCNPJPerfil2());
} else if ("P3".equals(perfilUpper)) {
ArrayOfCNPJPerfil3 p = infoconv.consultarCNPJSoap.consultarCNPJP3(listaCNPJs, CPF_CONSULTANTE);
lista.addAll(p.getCNPJPerfil3());
} else if ("P3T".equals(perfilUpper)) {
ArrayOfCNPJPerfil3 p = infoconv.consultarCNPJSoap.consultarCNPJP3T(listaCNPJs, CPF_CONSULTANTE);
lista.addAll(p.getCNPJPerfil3());
} else {
throw new PerfilInvalidoException();
}
verificarErros(lista.get(0));
return lista;
}
/**
* Consulta o webservice do infoconv ConsultarCNPJSoap/ConsultarCNPJP1
*
* @param listaCNPJs
* @return
* @throws AcessoNegadoException
* @throws CpfNaoEncontradoException
* @throws DadosInvalidosException
* @throws InfraException
*/
public List<Perfil1CNPJ> listarPerfil1(String listaCNPJs) throws AcessoNegadoException, CNPJNaoEncontradoException, DadosInvalidosException, InfraException{
ArrayOfCNPJPerfil1 result = infoconv.consultarCNPJSoap.consultarCNPJP1(listaCNPJs, CPF_CONSULTANTE);
verificarErros(result.getCNPJPerfil1().get(0));
List<Perfil1CNPJ> lista = new ArrayList<Perfil1CNPJ>();
for (CNPJPerfil1 perfil1 : result.getCNPJPerfil1()) {
lista.add(new Perfil1CNPJ(perfil1));
}
return lista;
}
/**
* Consulta o webservice do infoconv ConsultarCNPJSoap/ConsultarCNPJP2
*
* @param listaCNPJs
* @return
* @throws AcessoNegadoException
* @throws CpfNaoEncontradoException
* @throws DadosInvalidosException
* @throws InfraException
*/
public List<Perfil2CNPJ> listarPerfil2(String listaCNPJs) throws AcessoNegadoException, CNPJNaoEncontradoException, DadosInvalidosException, InfraException{
ArrayOfCNPJPerfil2 result = infoconv.consultarCNPJSoap.consultarCNPJP2(listaCNPJs, CPF_CONSULTANTE);
verificarErros(result.getCNPJPerfil2().get(0));
List<Perfil2CNPJ> lista = new ArrayList<Perfil2CNPJ>();
for (CNPJPerfil2 perfil1 : result.getCNPJPerfil2()) {
lista.add(new Perfil2CNPJ(perfil1));
}
return lista;
}
/**
* Consulta o webservice do infoconv ConsultarCNPJSoap/ConsultarCNPJP3
*
* @param listaCNPJs
* @return
* @throws AcessoNegadoException
* @throws CpfNaoEncontradoException
* @throws DadosInvalidosException
* @throws InfraException
*/
public List<Perfil3CNPJ> listarPerfil3(String listaCNPJs) throws AcessoNegadoException, CNPJNaoEncontradoException, DadosInvalidosException, InfraException{
ArrayOfCNPJPerfil3 result = infoconv.consultarCNPJSoap.consultarCNPJP3(listaCNPJs, CPF_CONSULTANTE);
verificarErros(result.getCNPJPerfil3().get(0));
List<Perfil3CNPJ> lista = new ArrayList<Perfil3CNPJ>();
for (CNPJPerfil3 perfil1 : result.getCNPJPerfil3()) {
lista.add(new Perfil3CNPJ(perfil1));
}
return lista;
}
}
| infoconv/infoconv-proxy | src/main/java/br/gov/serpro/infoconv/proxy/businesscontroller/ConsultaCNPJBC.java | Java | lgpl-3.0 | 8,058 |
/**
* This file is part of the CRISTAL-iSE kernel.
* Copyright (c) 2001-2015 The CRISTAL Consortium. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; with out even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*
* http://www.fsf.org/licensing/licenses/lgpl.html
*/
package org.cristalise.kernel.lifecycle.instance.stateMachine;
import lombok.Getter;
import lombok.Setter;
@Getter @Setter
public class TransitionQuery {
/**
* Name & version of the query to be run by the agent during this transition
*/
String name, version;
public TransitionQuery() {}
public TransitionQuery(String n, String v) {
name = n;
version = v;
}
}
| cristal-ise/kernel | src/main/java/org/cristalise/kernel/lifecycle/instance/stateMachine/TransitionQuery.java | Java | lgpl-3.0 | 1,327 |
<?php
namespace rocket\si\content\impl\iframe;
use n2n\util\type\attrs\DataSet;
use n2n\util\type\ArgUtils;
use rocket\si\content\impl\InSiFieldAdapter;
class IframeInSiField extends InSiFieldAdapter {
private $iframeData;
private $params = [];
public function __construct(IframeData $iframeData) {
$this->iframeData = $iframeData;
}
/**
* @return string
*/
function getType(): string {
return 'iframe-in';
}
/**
* @return array
*/
function getParams(): array {
return $this->params;
}
/**
* @param array $params
* @return IframeInSiField
*/
function setParams(array $params) {
ArgUtils::valArray($params, ['scalar', 'null']);
$this->params = $params;
return $this;
}
/**
* {@inheritDoc}
* @see \rocket\si\content\SiField::getData()
*/
function getData(): array {
$data = $this->iframeData->toArray();
$data['params'] = $this->getParams();
$data['messages'] = $this->getMessageStrs();
return $data;
}
/**
* {@inheritDoc}
* @see \rocket\si\content\SiField::handleInput()
*/
function handleInput(array $data) {
$ds = new DataSet($data);
$this->params = $ds->reqScalarArray('params', false, true);
}
}
| n2n/rocket | src/app/rocket/si/content/impl/iframe/IframeInSiField.php | PHP | lgpl-3.0 | 1,178 |
using System.Collections;
using System.Linq;
using System.Reflection;
namespace System.ComponentModel.DataAnnotations
{
public class EnsureNoDuplicatesAttribute : ValidationAttribute
{
public EnsureNoDuplicatesAttribute(Type type, string comparassionMethodName)
{
this.type = type;
method = type.GetMethod(comparassionMethodName, BindingFlags.Static | BindingFlags.Public);
if (method != null)
{
if (method.ReturnType == typeof(bool))
{
var pars = method.GetParameters();
if (pars.Count() != 2)
throw new ArgumentException($"Method '{comparassionMethodName}' in type '{type.Name}' specified for this '{nameof(EnsureNoDuplicatesAttribute)}' must has 2 parameters. Both of them must be of type of property.");
}
else throw new ArgumentException($"Method '{comparassionMethodName}' in type '{type.Name}' specified for this '{nameof(EnsureNoDuplicatesAttribute)}' must return 'bool'.");
}
else throw new ArgumentException($"Method '{comparassionMethodName}' in type '{type.Name}' specified for this '{nameof(EnsureNoDuplicatesAttribute)}' was not found. This method must be public and static.");
}
Type type;
MethodInfo? method;
string? lastDuplicateValue;
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name, lastDuplicateValue);
}
public override bool IsValid(object? value)
{
if (value is IList list)
{
if (list.Count < 2) return true;
for (int i = 1; i < list.Count; i++)
{
if ((bool?)method?.Invoke(null, new[] { list[i - 1], list[i] }) ?? false)
{
lastDuplicateValue = list[i]?.ToString();
return false;
}
}
return true;
}
return false;
}
//public override bool RequiresValidationContext => true;
//protected override ValidationResult IsValid(object value, ValidationContext context)
//{
// if (value is IList list)
// {
// if (list.Count < 2) return ValidationResult.Success;
// for (int i = 1; i < list.Count; i++)
// {
// if ((bool)method.Invoke(null, new[] { list[i - 1], list[i] }))
// {
// lastDuplicateValue = list[i].ToString();
// return new ValidationResult(string.Format(ErrorMessageString, context.DisplayName, list[i]));
// }
// }
// return ValidationResult.Success;
// }
// return new ValidationResult("Value isn't IList");
//}
}
}
| osjimenez/fuxion | src/core/Fuxion/ComponentModel/DataAnnotations/EnsureNoDuplicatesAttribute.cs | C# | lgpl-3.0 | 2,398 |
#include "NodoTipo.h"
NodoTipo::NodoTipo(Tipo* obj)
{
setTipo(obj);
setDer(NULL);
setIzq(NULL);
_listaISBN = new ListaISBN();
}
NodoTipo*&NodoTipo::getIzq() {
return _izq;
}
void NodoTipo::setIzq(NodoTipo* _izq) {
this->_izq = _izq;
}
NodoTipo*& NodoTipo::getDer() {
return _der;
}
void NodoTipo::setDer(NodoTipo* _der) {
this->_der = _der;
}
Tipo* NodoTipo::getTipo()const {
return _Tipo;
}
void NodoTipo::setTipo(Tipo* _Tipo) {
this->_Tipo = _Tipo;
}
NodoTipo::~NodoTipo() {
_listaISBN->destruir();
delete _listaISBN;
delete _Tipo;
}
ListaISBN* NodoTipo::getListaISBN(){
return _listaISBN;
}
void NodoTipo::setListaISBN(ListaISBN* l){
_listaISBN = l;
}
void NodoTipo::agregarISBN(int isbn){
_listaISBN->Inserta(isbn);
}
bool NodoTipo::borrarISBN(int isbn){
return _listaISBN->borrar(isbn);
}
void NodoTipo::destruirISBN(){
_listaISBN->destruir();
}
string NodoTipo::MostrarListaISBN(){
return _listaISBN->toString();
}
| jloriag/Bibliotc | NodoTipo.cpp | C++ | lgpl-3.0 | 958 |
<?php
/****************************************************************************
* Name: quiverext.php *
* Project: Cambusa/ryQuiver *
* Version: 1.69 *
* Description: Arrows-oriented Library *
* Copyright (C): 2015 Rodolfo Calzetti *
* License GNU LESSER GENERAL PUBLIC LICENSE Version 3 *
* Contact: https://github.com/cambusa *
* postmaster@rudyz.net *
****************************************************************************/
function qv_extension($maestro, $data, $prefix, $SYSID, $TYPOLOGYID, $oper){
global $babelcode, $babelparams, $global_cache;
if($oper!=2){ // 0 insert, 1 update, 2 virtual delete, 3 delete
$tabletypes=$prefix."TYPES";
$tableviews=$prefix."VIEWS";
if($t=_qv_cacheloader($maestro, $tabletypes, $TYPOLOGYID)){
$TABLENAME=$t["TABLENAME"];
$DELETABLE=$t["DELETABLE"];
unset($t);
if($TABLENAME!=""){
if($oper==3){
if($DELETABLE)
$sql="DELETE FROM $TABLENAME WHERE SYSID='$SYSID'";
else
$sql="UPDATE $TABLENAME SET SYSID=NULL WHERE SYSID='$SYSID'";
if(!maestro_execute($maestro, $sql, false)){
$babelcode="QVERR_EXECUTE";
$trace=debug_backtrace();
$b_params=array("FUNCTION" => $trace[0]["function"] );
$b_pattern=$maestro->errdescr;
throw new Exception( qv_babeltranslate($b_pattern, $b_params) );
}
}
elseif($DELETABLE || $oper==1){
if(isset($global_cache["$tableviews-$TYPOLOGYID"])){
// REPERISCO LE INFO DALLA CACHE
$infos=$global_cache["$tableviews-$TYPOLOGYID"];
}
else{
// REPERISCO LE INFO DAL DATABASE
$infos=array();
maestro_query($maestro,"SELECT * FROM $tableviews WHERE TYPOLOGYID='$TYPOLOGYID'",$r);
for($i=0;$i<count($r);$i++){
$FIELDTYPE=$r[$i]["FIELDTYPE"];
$TABLEREF="";
$NOTEMPTY=false;
if(substr($FIELDTYPE,0,5)=="SYSID"){
$TABLEREF=substr($FIELDTYPE, 6, -1);
if(substr($TABLEREF,0,1)=="#"){
$NOTEMPTY=true;
$TABLEREF=substr($TABLEREF,1);
}
}
$infos[$i]["FIELDNAME"]=$r[$i]["FIELDNAME"];
$infos[$i]["FIELDTYPE"]=$FIELDTYPE;
$infos[$i]["FORMULA"]=$r[$i]["FORMULA"];
$infos[$i]["WRITABLE"]=intval($r[$i]["WRITABLE"]);
$infos[$i]["TABLEREF"]=$TABLEREF;
$infos[$i]["NOTEMPTY"]=$NOTEMPTY;
}
// INSERISCO LE INFO NELLA CACHE
$global_cache["$tableviews-$TYPOLOGYID"]=$infos;
}
if(count($infos)>0 || $oper==0){ // Ci sono campi estensione oppure solo il SYSID in inserimento
if($oper==0){
$columns="SYSID";
$values="'$SYSID'";
$helpful=true;
}
else{
$sets="";
$where="SYSID='$SYSID'";
$helpful=false;
}
$clobs=false;
for($i=0;$i<count($infos);$i++){
$FIELDNAME=$infos[$i]["FIELDNAME"];
$FIELDTYPE=$infos[$i]["FIELDTYPE"];
$FORMULA=$infos[$i]["FORMULA"];
$WRITABLE=$infos[$i]["WRITABLE"];
$TABLEREF=$infos[$i]["TABLEREF"];
$NOTEMPTY=$infos[$i]["NOTEMPTY"];
if($WRITABLE){
// IL CAMPO PUO' ESSERE AGGIORNATO
// DETERMINO IL NOME DEL CAMPO
if($FORMULA=="")
$ACTUALNAME=$FIELDNAME;
else
$ACTUALNAME=str_replace("$TABLENAME.", "", $FORMULA);
// DETERMINO IL VALORE DEL CAMPO
if(isset($data[$ACTUALNAME])){
// FORMATTAZIONE IN BASE AL TIPO
if($TABLEREF!=""){ // SYSID(Tabella referenziata)
$value=ryqEscapize($data[$ACTUALNAME]);
if($value!=""){
// Controllo che esista l'oggetto con SYSID=$value nella tabella $TABLEREF
qv_linkable($maestro, $TABLEREF, $value);
}
elseif($NOTEMPTY){
$babelcode="QVERR_EMPTYSYSID";
$trace=debug_backtrace();
$b_params=array("FUNCTION" => $trace[0]["function"], "ACTUALNAME" => $ACTUALNAME );
$b_pattern="Campo [{2}] obbligatorio";
throw new Exception( qv_babeltranslate($b_pattern, $b_params) );
}
$value="'$value'";
}
elseif($FIELDTYPE=="TEXT"){
$value=ryqNormalize($data[$ACTUALNAME]);
qv_setclob($maestro, $ACTUALNAME, $value, $value, $clobs);
}
elseif(substr($FIELDTYPE, 0, 4)=="JSON"){
$value=ryqNormalize($data[$ACTUALNAME]);
if(substr($FIELDTYPE, 0, 5)=="JSON("){
$len=intval(substr($FIELDTYPE, 5));
$value=substr($value, 0, $len);
}
if($value!=""){
if(!json_decode($value)){
$babelcode="QVERR_JSON";
$trace=debug_backtrace();
$b_params=array("FUNCTION" => $trace[0]["function"], "ACTUALNAME" => $ACTUALNAME );
$b_pattern="Documento JSON [{2}] non corretto o troppo esteso";
throw new Exception( qv_babeltranslate($b_pattern, $b_params) );
}
}
qv_setclob($maestro, $ACTUALNAME, $value, $value, $clobs);
}
else{
$value=ryqEscapize($data[$ACTUALNAME]);
$value=qv_sqlize($value, $FIELDTYPE);
}
if($oper==0){
qv_appendcomma($columns, $ACTUALNAME);
qv_appendcomma($values, $value);
}
else{
qv_appendcomma($sets,"$ACTUALNAME=$value");
$helpful=true;
}
}
else{
if($oper==0){
if($NOTEMPTY){
$babelcode="QVERR_EMPTYSYSID";
$trace=debug_backtrace();
$b_params=array("FUNCTION" => $trace[0]["function"], "ACTUALNAME" => $ACTUALNAME );
$b_pattern="Campo [{2}] obbligatorio";
throw new Exception( qv_babeltranslate($b_pattern, $b_params) );
}
$value=qv_sqlize("", $FIELDTYPE);
qv_appendcomma($columns, $ACTUALNAME);
qv_appendcomma($values, $value);
}
}
}
}
unset($r);
if($helpful){
if($oper==0)
$sql="INSERT INTO $TABLENAME ($columns) VALUES($values)";
else
$sql="UPDATE $TABLENAME SET $sets WHERE $where";
if(!maestro_execute($maestro, $sql, false, $clobs)){
$babelcode="QVERR_EXECUTE";
$trace=debug_backtrace();
$b_params=array("FUNCTION" => $trace[0]["function"] );
$b_pattern=$maestro->errdescr;
throw new Exception( qv_babeltranslate($b_pattern, $b_params) );
}
}
}
}
}
}
}
}
function qv_sqlize($value, $FIELDTYPE){
$FIELDTYPE=strtoupper($FIELDTYPE);
switch($FIELDTYPE){
case "INTEGER":
$value=strval(intval($value));
break;
case "RATIONAL":
$value=strval(round(floatval($value),7));
break;
case "DATE":
if(strlen($value)<8)
$value=LOWEST_DATE;
$value="[:DATE($value)]";
break;
case "TIMESTAMP":
if(strlen($value)<8)
$value=LOWEST_TIME;
$value="[:TIME($value)]";
break;
case "BOOLEAN":
if(intval($value)!=0)
$value="1";
else
$value="0";
break;
default:
if(substr($FIELDTYPE, 0, 9)=="RATIONAL("){
$dec=intval(substr($FIELDTYPE, 9));
$value=strval(round(floatval($value), $dec));
}
elseif(substr($FIELDTYPE, 0, 5)=="CHAR("){
$len=intval(substr($FIELDTYPE, 5));
$value="'".substr(qv_inputUTF8($value), 0, $len)."'";
}
elseif(substr($value, 0, 2)!="[:" || substr($value, -1, 1)!="]"){
$value="'$value'";
}
break;
}
return $value;
}
function _qv_historicizing($maestro, $prefix, $SYSID, $TYPOLOGYID, $oper){
global $global_quiveruserid, $global_quiverroleid;
global $babelcode, $babelparams;
$tablebase=$prefix."S";
$tabletypes=$prefix."TYPES";
if($t=_qv_cacheloader($maestro, $tabletypes, $TYPOLOGYID)){
if( intval($t["HISTORICIZING"]) ){
$TABLE=$t["VIEWNAME"];
if($TABLE==""){
$TABLE=$tablebase;
}
if($r=_qv_cacheloader($maestro, $TABLE, $SYSID)){
$clobs=false;
$DATABAG=json_encode($r);
qv_setclob($maestro, "DATABAG", $DATABAG, $DATABAG, $clobs);
$HISTORYID=qv_createsysid($maestro);
$DESCRIPTION=ryqEscapize($r["DESCRIPTION"]);
$TIMEINSERT=qv_strtime($r["TIMEINSERT"]);
$RECORDTIME=qv_strtime($r["TIMEUPDATE"]);
if($RECORDTIME<$TIMEINSERT){
$RECORDTIME=$TIMEINSERT;
}
$RECORDTIME="[:TIME($RECORDTIME)]";
$EVENTTIME="[:NOW()]";
// PREDISPONGO COLONNE E VALORI DA REGISTRARE
$columns="SYSID,RECORDID,DESCRIPTION,RECORDTIME,TABLEBASE,TYPOLOGYID,OPERTYPE,ROLEID,USERID,EVENTTIME,DATABAG";
$values="'$HISTORYID','$SYSID','$DESCRIPTION',$RECORDTIME,'$tablebase','$TYPOLOGYID','$oper','$global_quiverroleid','$global_quiveruserid',$EVENTTIME,$DATABAG";
$sql="INSERT INTO QVHISTORY($columns) VALUES($values)";
if(!maestro_execute($maestro, $sql, false, $clobs)){
$babelcode="QVERR_EXECUTE";
$trace=debug_backtrace();
$b_params=array("FUNCTION" => $trace[0]["function"] );
$b_pattern=$maestro->errdescr;
throw new Exception( qv_babeltranslate($b_pattern, $b_params) );
}
}
}
}
}
?> | cambusa/corsaro | _master/cambusa/ryquiver/quiverext.php | PHP | lgpl-3.0 | 13,735 |
# -*- coding: utf-8 -*-
# Copyright(C) 2014 smurail
#
# This file is part of a weboob module.
#
# This weboob module is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This weboob module is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this weboob module. If not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
import re
from weboob.exceptions import BrowserIncorrectPassword
from weboob.browser.pages import HTMLPage, JsonPage, pagination, LoggedPage
from weboob.browser.elements import ListElement, ItemElement, TableElement, method
from weboob.browser.filters.standard import CleanText, CleanDecimal, DateGuesser, Env, Field, Filter, Regexp, Currency, Date
from weboob.browser.filters.html import Link, Attr, TableCell
from weboob.capabilities.bank import Account, Investment
from weboob.capabilities.base import NotAvailable
from weboob.tools.capabilities.bank.transactions import FrenchTransaction
from weboob.tools.compat import urljoin
from weboob.tools.capabilities.bank.investments import is_isin_valid
__all__ = ['LoginPage']
class UselessPage(HTMLPage):
pass
class PasswordCreationPage(HTMLPage):
def get_message(self):
xpath = '//div[@class="bienvenueMdp"]/following-sibling::div'
return '%s%s' % (CleanText(xpath + '/strong')(self.doc), CleanText(xpath, children=False)(self.doc))
class ErrorPage(HTMLPage):
pass
class SubscriptionPage(LoggedPage, JsonPage):
pass
class LoginPage(HTMLPage):
pass
class CMSOPage(HTMLPage):
@property
def logged(self):
if len(self.doc.xpath('//b[text()="Session interrompue"]')) > 0:
return False
return True
class AccountsPage(CMSOPage):
TYPES = {'COMPTE CHEQUES': Account.TYPE_CHECKING,
'COMPTE TITRES': Account.TYPE_MARKET,
"ACTIV'EPARGNE": Account.TYPE_SAVINGS,
"TRESO'VIV": Account.TYPE_SAVINGS,
}
@method
class iter_accounts(ListElement):
item_xpath = '//div[has-class("groupe-comptes")]//li'
class item(ItemElement):
klass = Account
class Type(Filter):
def filter(self, label):
for pattern, actype in AccountsPage.TYPES.items():
if label.startswith(pattern):
return actype
return Account.TYPE_UNKNOWN
obj__history_url = Link('.//a[1]')
obj_id = CleanText('.//span[has-class("numero-compte")]') & Regexp(pattern=r'(\d{3,}[\w]+)', default='')
obj_label = CleanText('.//span[has-class("libelle")][1]')
obj_currency = Currency('//span[has-class("montant")]')
obj_balance = CleanDecimal('.//span[has-class("montant")]', replace_dots=True)
obj_type = Type(Field('label'))
# Last numbers replaced with XX... or we have to send sms to get RIB.
obj_iban = NotAvailable
# some accounts may appear on multiple areas, but the area where they come from is indicated
obj__owner = CleanText('(./preceding-sibling::tr[@class="LnMnTiers"])[last()]')
def validate(self, obj):
if obj.id is None:
obj.id = obj.label.replace(' ', '')
return True
def on_load(self):
if self.doc.xpath('//p[contains(text(), "incident technique")]'):
raise BrowserIncorrectPassword("Vous n'avez aucun compte sur cet espace. " \
"Veuillez choisir un autre type de compte.")
class InvestmentPage(CMSOPage):
def has_error(self):
return CleanText('//span[@id="id_error_msg"]')(self.doc)
@method
class iter_accounts(ListElement):
item_xpath = '//table[@class="Tb" and tr[1][@class="LnTit"]]/tr[@class="LnA" or @class="LnB"]'
class item(ItemElement):
klass = Account
def obj_id(self):
area_id = Regexp(CleanText('(./preceding-sibling::tr[@class="LnMnTiers"][1])//span[@class="CelMnTiersT1"]'),
r'\((\d+)\)', default='')(self)
acc_id = Regexp(CleanText('./td[1]'), r'(\d+)\s*(\d+)', r'\1\2')(self)
if area_id:
return '%s.%s' % (area_id, acc_id)
return acc_id
def obj__formdata(self):
js = Attr('./td/a[1]', 'onclick', default=None)(self)
if js is None:
return
args = re.search(r'\((.*)\)', js).group(1).split(',')
form = args[0].strip().split('.')[1]
idx = args[2].strip()
idroot = args[4].strip().replace("'", "")
return (form, idx, idroot)
obj_url = Link('./td/a[1]', default=None)
def go_account(self, form, idx, idroot):
form = self.get_form(name=form)
form['indiceCompte'] = idx
form['idRacine'] = idroot
form.submit()
class CmsoTableElement(TableElement):
head_xpath = '//table[has-class("Tb")]/tr[has-class("LnTit")]/td'
item_xpath = '//table[has-class("Tb")]/tr[has-class("LnA") or has-class("LnB")]'
class InvestmentAccountPage(CMSOPage):
@method
class iter_investments(CmsoTableElement):
col_label = 'Valeur'
col_code = 'Code'
col_quantity = 'Qté'
col_unitvalue = 'Cours'
col_valuation = 'Valorisation'
col_vdate = 'Date cours'
class item(ItemElement):
klass = Investment
obj_label = CleanText(TableCell('label'))
obj_quantity = CleanDecimal(TableCell('quantity'), replace_dots=True)
obj_unitvalue = CleanDecimal(TableCell('unitvalue'), replace_dots=True)
obj_valuation = CleanDecimal(TableCell('valuation'), replace_dots=True)
obj_vdate = Date(CleanText(TableCell('vdate')), dayfirst=True, default=NotAvailable)
def obj_code(self):
if Field('label')(self) == "LIQUIDITES":
return 'XX-liquidity'
code = CleanText(TableCell('code'))(self)
return code if is_isin_valid(code) else NotAvailable
def obj_code_type(self):
return Investment.CODE_TYPE_ISIN if is_isin_valid(Field('code')(self)) else NotAvailable
class Transaction(FrenchTransaction):
PATTERNS = [(re.compile(r'^RET DAB (?P<dd>\d{2})/?(?P<mm>\d{2})(/?(?P<yy>\d{2}))? (?P<text>.*)'),
FrenchTransaction.TYPE_WITHDRAWAL),
(re.compile(r'CARTE (?P<dd>\d{2})/(?P<mm>\d{2}) (?P<text>.*)'),
FrenchTransaction.TYPE_CARD),
(re.compile(r'^(?P<category>VIR(EMEN)?T? (SEPA)?(RECU|FAVEUR)?)( /FRM)?(?P<text>.*)'),
FrenchTransaction.TYPE_TRANSFER),
(re.compile(r'^PRLV (?P<text>.*)( \d+)?$'), FrenchTransaction.TYPE_ORDER),
(re.compile(r'^(CHQ|CHEQUE) .*$'), FrenchTransaction.TYPE_CHECK),
(re.compile(r'^(AGIOS /|FRAIS) (?P<text>.*)'), FrenchTransaction.TYPE_BANK),
(re.compile(r'^(CONVENTION \d+ |F )?COTIS(ATION)? (?P<text>.*)'),
FrenchTransaction.TYPE_BANK),
(re.compile(r'^REMISE (?P<text>.*)'), FrenchTransaction.TYPE_DEPOSIT),
(re.compile(r'^(?P<text>.*)( \d+)? QUITTANCE .*'),
FrenchTransaction.TYPE_ORDER),
(re.compile(r'^.* LE (?P<dd>\d{2})/(?P<mm>\d{2})/(?P<yy>\d{2})$'),
FrenchTransaction.TYPE_UNKNOWN),
(re.compile(r'^.* PAIEMENT (?P<dd>\d{2})/(?P<mm>\d{2}) (?P<text>.*)'),
FrenchTransaction.TYPE_UNKNOWN),
]
class CmsoTransactionElement(ItemElement):
klass = Transaction
def condition(self):
return len(self.el) >= 5 and not self.el.get('id', '').startswith('libelleLong')
class HistoryPage(CMSOPage):
def get_date_range_list(self):
return [d for d in self.doc.xpath('//select[@name="date"]/option/@value') if d]
@pagination
@method
class iter_history(ListElement):
item_xpath = '//div[contains(@class, "master-table")]//ul/li'
def next_page(self):
pager = self.page.doc.xpath('//div[@class="pager"]')
if pager: # more than one page if only enough transactions
assert len(pager) == 1
next_links = pager[0].xpath('./span/following-sibling::a[@class="page"]')
if next_links:
url_next_page = Link('.')(next_links[0])
url_next_page = urljoin(self.page.url, url_next_page)
return self.page.browser.build_request(url_next_page)
class item(CmsoTransactionElement):
def date(selector):
return DateGuesser(Regexp(CleanText(selector), r'\w+ (\d{2}/\d{2})'), Env('date_guesser')) | Transaction.Date(selector)
# CAUTION: this website write a 'Date valeur' inside a div with a class == 'c-ope'
# and a 'Date opération' inside a div with a class == 'c-val'
# so actually i assume 'c-val' class is the real operation date and 'c-ope' is value date
obj_date = date('./div[contains(@class, "c-val")]')
obj_vdate = date('./div[contains(@class, "c-ope")]')
obj_raw = Transaction.Raw(Regexp(CleanText('./div[contains(@class, "c-libelle-long")]'), r'Libellé étendu (.+)'))
obj_amount = Transaction.Amount('./div[contains(@class, "c-credit")]', './div[contains(@class, "c-debit")]')
class UpdateTokenMixin(object):
def on_load(self):
if 'Authentication' in self.response.headers:
self.browser.token = self.response.headers['Authentication'].split(' ')[-1]
class SSODomiPage(JsonPage, UpdateTokenMixin):
def get_sso_url(self):
return self.doc['urlSSO']
class AuthCheckUser(HTMLPage):
pass
| laurentb/weboob | modules/cmso/pro/pages.py | Python | lgpl-3.0 | 10,804 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Sigfox lib")]
[assembly: AssemblyDescription("RPi Sigfox shield support library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Pospa.NET")]
[assembly: AssemblyProduct("Sigfox lib")]
[assembly: AssemblyCopyright("Copyright © Pospa.NET 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)] | pospanet/TurrisGadgets | Sigfox lib/Properties/AssemblyInfo.cs | C# | lgpl-3.0 | 1,091 |
// Copyright 2016 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package gomaasapi
import "github.com/juju/utils/set"
const (
// Capability constants.
NetworksManagement = "networks-management"
StaticIPAddresses = "static-ipaddresses"
IPv6DeploymentUbuntu = "ipv6-deployment-ubuntu"
DevicesManagement = "devices-management"
StorageDeploymentUbuntu = "storage-deployment-ubuntu"
NetworkDeploymentUbuntu = "network-deployment-ubuntu"
)
// Controller represents an API connection to a MAAS Controller. Since the API
// is restful, there is no long held connection to the API server, but instead
// HTTP calls are made and JSON response structures parsed.
type Controller interface {
// Capabilities returns a set of capabilities as defined by the string
// constants.
Capabilities() set.Strings
BootResources() ([]BootResource, error)
// Fabrics returns the list of Fabrics defined in the MAAS controller.
Fabrics() ([]Fabric, error)
// Spaces returns the list of Spaces defined in the MAAS controller.
Spaces() ([]Space, error)
// Zones lists all the zones known to the MAAS controller.
Zones() ([]Zone, error)
// Machines returns a list of machines that match the params.
Machines(MachinesArgs) ([]Machine, error)
// AllocateMachine will attempt to allocate a machine to the user.
// If successful, the allocated machine is returned.
AllocateMachine(AllocateMachineArgs) (Machine, ConstraintMatches, error)
// ReleaseMachines will stop the specified machines, and release them
// from the user making them available to be allocated again.
ReleaseMachines(ReleaseMachinesArgs) error
// Devices returns a list of devices that match the params.
Devices(DevicesArgs) ([]Device, error)
// CreateDevice creates and returns a new Device.
CreateDevice(CreateDeviceArgs) (Device, error)
// Files returns all the files that match the specified prefix.
Files(prefix string) ([]File, error)
// Return a single file by its filename.
GetFile(filename string) (File, error)
// AddFile adds or replaces the content of the specified filename.
// If or when the MAAS api is able to return metadata about a single
// file without sending the content of the file, we can return a File
// instance here too.
AddFile(AddFileArgs) error
}
// File represents a file stored in the MAAS controller.
type File interface {
// Filename is the name of the file. No path, just the filename.
Filename() string
// AnonymousURL is a URL that can be used to retrieve the conents of the
// file without credentials.
AnonymousURL() string
// Delete removes the file from the MAAS controller.
Delete() error
// ReadAll returns the content of the file.
ReadAll() ([]byte, error)
}
// Fabric represents a set of interconnected VLANs that are capable of mutual
// communication. A fabric can be thought of as a logical grouping in which
// VLANs can be considered unique.
//
// For example, a distributed network may have a fabric in London containing
// VLAN 100, while a separate fabric in San Francisco may contain a VLAN 100,
// whose attached subnets are completely different and unrelated.
type Fabric interface {
ID() int
Name() string
ClassType() string
VLANs() []VLAN
}
// VLAN represents an instance of a Virtual LAN. VLANs are a common way to
// create logically separate networks using the same physical infrastructure.
//
// Managed switches can assign VLANs to each port in either a “tagged” or an
// “untagged” manner. A VLAN is said to be “untagged” on a particular port when
// it is the default VLAN for that port, and requires no special configuration
// in order to access.
//
// “Tagged” VLANs (traditionally used by network administrators in order to
// aggregate multiple networks over inter-switch “trunk” lines) can also be used
// with nodes in MAAS. That is, if a switch port is configured such that
// “tagged” VLAN frames can be sent and received by a MAAS node, that MAAS node
// can be configured to automatically bring up VLAN interfaces, so that the
// deployed node can make use of them.
//
// A “Default VLAN” is created for every Fabric, to which every new VLAN-aware
// object in the fabric will be associated to by default (unless otherwise
// specified).
type VLAN interface {
ID() int
Name() string
Fabric() string
// VID is the VLAN ID. eth0.10 -> VID = 10.
VID() int
// MTU (maximum transmission unit) is the largest size packet or frame,
// specified in octets (eight-bit bytes), that can be sent.
MTU() int
DHCP() bool
PrimaryRack() string
SecondaryRack() string
}
// Zone represents a physical zone that a Machine is in. The meaning of a
// physical zone is up to you: it could identify e.g. a server rack, a network,
// or a data centre. Users can then allocate nodes from specific physical zones,
// to suit their redundancy or performance requirements.
type Zone interface {
Name() string
Description() string
}
// BootResource is the bomb... find something to say here.
type BootResource interface {
ID() int
Name() string
Type() string
Architecture() string
SubArchitectures() set.Strings
KernelFlavor() string
}
// Device represents some form of device in MAAS.
type Device interface {
// TODO: add domain
SystemID() string
Hostname() string
FQDN() string
IPAddresses() []string
Zone() Zone
// Parent returns the SystemID of the Parent. Most often this will be a
// Machine.
Parent() string
// Owner is the username of the user that created the device.
Owner() string
// InterfaceSet returns all the interfaces for the Device.
InterfaceSet() []Interface
// CreateInterface will create a physical interface for this machine.
CreateInterface(CreateInterfaceArgs) (Interface, error)
// Delete will remove this Device.
Delete() error
}
// Machine represents a physical machine.
type Machine interface {
SystemID() string
Hostname() string
FQDN() string
Tags() []string
OperatingSystem() string
DistroSeries() string
Architecture() string
Memory() int
CPUCount() int
IPAddresses() []string
PowerState() string
// Devices returns a list of devices that match the params and have
// this Machine as the parent.
Devices(DevicesArgs) ([]Device, error)
// Consider bundling the status values into a single struct.
// but need to check for consistent representation if exposed on other
// entities.
StatusName() string
StatusMessage() string
// BootInterface returns the interface that was used to boot the Machine.
BootInterface() Interface
// InterfaceSet returns all the interfaces for the Machine.
InterfaceSet() []Interface
// Interface returns the interface for the machine that matches the id
// specified. If there is no match, nil is returned.
Interface(id int) Interface
// PhysicalBlockDevices returns all the physical block devices on the machine.
PhysicalBlockDevices() []BlockDevice
// PhysicalBlockDevice returns the physical block device for the machine
// that matches the id specified. If there is no match, nil is returned.
PhysicalBlockDevice(id int) BlockDevice
// BlockDevices returns all the physical and virtual block devices on the machine.
BlockDevices() []BlockDevice
Zone() Zone
// Start the machine and install the operating system specified in the args.
Start(StartArgs) error
// CreateDevice creates a new Device with this Machine as the parent.
// The device will have one interface that is linked to the specified subnet.
CreateDevice(CreateMachineDeviceArgs) (Device, error)
}
// Space is a name for a collection of Subnets.
type Space interface {
ID() int
Name() string
Subnets() []Subnet
}
// Subnet refers to an IP range on a VLAN.
type Subnet interface {
ID() int
Name() string
Space() string
VLAN() VLAN
Gateway() string
CIDR() string
// dns_mode
// DNSServers is a list of ip addresses of the DNS servers for the subnet.
// This list may be empty.
DNSServers() []string
}
// Interface represents a physical or virtual network interface on a Machine.
type Interface interface {
ID() int
Name() string
// The parents of an interface are the names of interfaces that must exist
// for this interface to exist. For example a parent of "eth0.100" would be
// "eth0". Parents may be empty.
Parents() []string
// The children interfaces are the names of those that are dependent on this
// interface existing. Children may be empty.
Children() []string
Type() string
Enabled() bool
Tags() []string
VLAN() VLAN
Links() []Link
MACAddress() string
EffectiveMTU() int
// Params is a JSON field, and defaults to an empty string, but is almost
// always a JSON object in practice. Gleefully ignoring it until we need it.
// Update the name, mac address or VLAN.
Update(UpdateInterfaceArgs) error
// Delete this interface.
Delete() error
// LinkSubnet will attempt to make this interface available on the specified
// Subnet.
LinkSubnet(LinkSubnetArgs) error
// UnlinkSubnet will remove the Link to the subnet, and release the IP
// address associated if there is one.
UnlinkSubnet(Subnet) error
}
// Link represents a network link between an Interface and a Subnet.
type Link interface {
ID() int
Mode() string
Subnet() Subnet
// IPAddress returns the address if one has been assigned.
// If unavailble, the address will be empty.
IPAddress() string
}
// FileSystem represents a formatted filesystem mounted at a location.
type FileSystem interface {
// Type is the format type, e.g. "ext4".
Type() string
MountPoint() string
Label() string
UUID() string
}
// Partition represents a partition of a block device. It may be mounted
// as a filesystem.
type Partition interface {
ID() int
Path() string
// FileSystem may be nil if not mounted.
FileSystem() FileSystem
UUID() string
// UsedFor is a human readable string.
UsedFor() string
// Size is the number of bytes in the partition.
Size() uint64
}
// BlockDevice represents an entire block device on the machine.
type BlockDevice interface {
ID() int
Name() string
Model() string
Path() string
UsedFor() string
Tags() []string
BlockSize() uint64
UsedSize() uint64
Size() uint64
Partitions() []Partition
// There are some other attributes for block devices, but we can
// expose them on an as needed basis.
}
| voidspace/gomaasapi | interfaces.go | GO | lgpl-3.0 | 10,327 |
/* ==========================================
* JGraphT : a free Java graph-theory library
* ==========================================
*
* Project Info: http://jgrapht.sourceforge.net/
* Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh)
*
* (C) Copyright 2003-2008, by Barak Naveh and Contributors.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation,
* Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
/* -------------------------
* GraphEdgeChangeEvent.java
* -------------------------
* (C) Copyright 2003-2008, by Barak Naveh and Contributors.
*
* Original Author: Barak Naveh
* Contributor(s): Christian Hammer
*
* $Id: GraphEdgeChangeEvent.java 645 2008-09-30 19:44:48Z perfecthash $
*
* Changes
* -------
* 10-Aug-2003 : Initial revision (BN);
* 11-Mar-2004 : Made generic (CH);
*
*/
package edu.nd.nina.event;
/**
* An event which indicates that a graph edge has changed, or is about to
* change. The event can be used either as an indication <i>after</i> the edge
* has been added or removed, or <i>before</i> it is added. The type of the
* event can be tested using the {@link
* edu.nd.nina.event.GraphChangeEvent#getType()} method.
*
* @author Barak Naveh
* @since Aug 10, 2003
*/
public class GraphEdgeChangeEvent<V, E>
extends GraphChangeEvent
{
//~ Static fields/initializers ---------------------------------------------
private static final long serialVersionUID = 3618134563335844662L;
/**
* Before edge added event. This event is fired before an edge is added to a
* graph.
*/
public static final int BEFORE_EDGE_ADDED = 21;
/**
* Before edge removed event. This event is fired before an edge is removed
* from a graph.
*/
public static final int BEFORE_EDGE_REMOVED = 22;
/**
* Edge added event. This event is fired after an edge is added to a graph.
*/
public static final int EDGE_ADDED = 23;
/**
* Edge removed event. This event is fired after an edge is removed from a
* graph.
*/
public static final int EDGE_REMOVED = 24;
//~ Instance fields --------------------------------------------------------
/**
* The edge that this event is related to.
*/
protected E edge;
//~ Constructors -----------------------------------------------------------
/**
* Constructor for GraphEdgeChangeEvent.
*
* @param eventSource the source of this event.
* @param type the event type of this event.
* @param e the edge that this event is related to.
*/
public GraphEdgeChangeEvent(Object eventSource, int type, E e)
{
super(eventSource, type);
edge = e;
}
//~ Methods ----------------------------------------------------------------
/**
* Returns the edge that this event is related to.
*
* @return the edge that this event is related to.
*/
public E getEdge()
{
return edge;
}
}
// End GraphEdgeChangeEvent.java
| tweninger/nina | src/edu/nd/nina/event/GraphEdgeChangeEvent.java | Java | lgpl-3.0 | 3,785 |
<?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
namespace pocketmine\level\format\mcregion;
use pocketmine\level\format\FullChunk;
use pocketmine\level\format\LevelProvider;
use pocketmine\nbt\NBT;
use pocketmine\nbt\tag\Byte;
use pocketmine\nbt\tag\ByteArray;
use pocketmine\nbt\tag\Compound;
use pocketmine\nbt\tag\Enum;
use pocketmine\nbt\tag\Int;
use pocketmine\nbt\tag\IntArray;
use pocketmine\nbt\tag\Long;
use pocketmine\utils\Binary;
use pocketmine\utils\ChunkException;
use pocketmine\utils\MainLogger;
class RegionLoader{
const VERSION = 1;
const COMPRESSION_GZIP = 1;
const COMPRESSION_ZLIB = 2;
const MAX_SECTOR_LENGTH = 256 << 12; //256 sectors, (1 MiB)
public static $COMPRESSION_LEVEL = 7;
protected $x;
protected $z;
protected $filePath;
protected $filePointer;
protected $lastSector;
/** @var LevelProvider */
protected $levelProvider;
protected $locationTable = [];
public $lastUsed;
public function __construct(LevelProvider $level, $regionX, $regionZ){
$this->x = $regionX;
$this->z = $regionZ;
$this->levelProvider = $level;
$this->filePath = $this->levelProvider->getPath() . "region/r.$regionX.$regionZ.mcr";
$exists = file_exists($this->filePath);
touch($this->filePath);
$this->filePointer = fopen($this->filePath, "r+b");
stream_set_read_buffer($this->filePointer, 1024 * 16); //16KB
stream_set_write_buffer($this->filePointer, 1024 * 16); //16KB
if(!$exists){
$this->createBlank();
}else{
$this->loadLocationTable();
}
$this->lastUsed = time();
}
public function __destruct(){
if(is_resource($this->filePointer)){
$this->writeLocationTable();
fclose($this->filePointer);
}
}
protected function isChunkGenerated($index){
return !($this->locationTable[$index][0] === 0 or $this->locationTable[$index][1] === 0);
}
public function readChunk($x, $z, $generate = true, $forward = false){
$index = self::getChunkOffset($x, $z);
if($index < 0 or $index >= 4096){
return null;
}
$this->lastUsed = time();
if(!$this->isChunkGenerated($index)){
if($generate === true){
//Allocate space
$this->locationTable[$index][0] = ++$this->lastSector;
$this->locationTable[$index][1] = 1;
fseek($this->filePointer, $this->locationTable[$index][0] << 12);
fwrite($this->filePointer, str_pad(Binary::writeInt(0) . chr(self::COMPRESSION_ZLIB), 4096, "\x00", STR_PAD_RIGHT));
$this->writeLocationIndex($index);
}else{
return null;
}
}
fseek($this->filePointer, $this->locationTable[$index][0] << 12);
$length = Binary::readInt(fread($this->filePointer, 4));
$compression = ord(fgetc($this->filePointer));
if($length <= 0 or $length > self::MAX_SECTOR_LENGTH){ //Not yet generated / corrupted
if($length >= self::MAX_SECTOR_LENGTH){
$this->locationTable[$index][0] = ++$this->lastSector;
$this->locationTable[$index][1] = 1;
MainLogger::getLogger()->error("Corrupted chunk header detected");
}
$this->generateChunk($x, $z);
fseek($this->filePointer, $this->locationTable[$index][0] << 12);
$length = Binary::readInt(fread($this->filePointer, 4));
$compression = ord(fgetc($this->filePointer));
}
if($length > ($this->locationTable[$index][1] << 12)){ //Invalid chunk, bigger than defined number of sectors
MainLogger::getLogger()->error("Corrupted bigger chunk detected");
$this->locationTable[$index][1] = $length >> 12;
$this->writeLocationIndex($index);
}elseif($compression !== self::COMPRESSION_ZLIB and $compression !== self::COMPRESSION_GZIP){
MainLogger::getLogger()->error("Invalid compression type");
return null;
}
$chunk = Chunk::fromBinary(fread($this->filePointer, $length - 1), $this->levelProvider);
if($chunk instanceof Chunk){
return $chunk;
}elseif($forward === false){
MainLogger::getLogger()->error("Corrupted chunk detected");
$this->generateChunk($x, $z);
return $this->readChunk($x, $z, $generate, true);
}else{
return null;
}
}
public function chunkExists($x, $z){
return $this->isChunkGenerated(self::getChunkOffset($x, $z));
}
public function generateChunk($x, $z){
$nbt = new Compound("Level", []);
$nbt->xPos = new Int("xPos", ($this->getX() * 32) + $x);
$nbt->zPos = new Int("zPos", ($this->getZ() * 32) + $z);
$nbt->LastUpdate = new Long("LastUpdate", 0);
$nbt->LightPopulated = new Byte("LightPopulated", 0);
$nbt->TerrainPopulated = new Byte("TerrainPopulated", 0);
$nbt->V = new Byte("V", self::VERSION);
$nbt->InhabitedTime = new Long("InhabitedTime", 0);
$nbt->Biomes = new ByteArray("Biomes", str_repeat(Binary::writeByte(-1), 256));
$nbt->HeightMap = new IntArray("HeightMap", array_fill(0, 256, 127));
$nbt->BiomeColors = new IntArray("BiomeColors", array_fill(0, 256, Binary::readInt("\x00\x85\xb2\x4a")));
$nbt->Blocks = new ByteArray("Blocks", str_repeat("\x00", 32768));
$nbt->Data = new ByteArray("Data", $half = str_repeat("\x00", 16384));
$nbt->SkyLight = new ByteArray("SkyLight", $half);
$nbt->BlockLight = new ByteArray("BlockLight", $half);
$nbt->Entities = new Enum("Entities", []);
$nbt->Entities->setTagType(NBT::TAG_Compound);
$nbt->TileEntities = new Enum("TileEntities", []);
$nbt->TileEntities->setTagType(NBT::TAG_Compound);
$nbt->TileTicks = new Enum("TileTicks", []);
$nbt->TileTicks->setTagType(NBT::TAG_Compound);
$writer = new NBT(NBT::BIG_ENDIAN);
$nbt->setName("Level");
$writer->setData(new Compound("", ["Level" => $nbt]));
$chunkData = $writer->writeCompressed(ZLIB_ENCODING_DEFLATE, self::$COMPRESSION_LEVEL);
if($chunkData !== false){
$this->saveChunk($x, $z, $chunkData);
}
}
protected function saveChunk($x, $z, $chunkData){
$length = strlen($chunkData) + 1;
if($length + 4 > self::MAX_SECTOR_LENGTH){
throw new ChunkException("Chunk is too big! ".($length + 4)." > ".self::MAX_SECTOR_LENGTH);
}
$sectors = (int) ceil(($length + 4) / 4096);
$index = self::getChunkOffset($x, $z);
if($this->locationTable[$index][1] < $sectors){
$this->locationTable[$index][0] = $this->lastSector + 1;
$this->lastSector += $sectors; //The GC will clean this shift "later"
}
$this->locationTable[$index][1] = $sectors;
$this->locationTable[$index][2] = time();
fseek($this->filePointer, $this->locationTable[$index][0] << 12);
fwrite($this->filePointer, str_pad(Binary::writeInt($length) . chr(self::COMPRESSION_ZLIB) . $chunkData, $sectors << 12, "\x00", STR_PAD_RIGHT));
$this->writeLocationIndex($index);
}
public function removeChunk($x, $z){
$index = self::getChunkOffset($x, $z);
$this->locationTable[$index][0] = 0;
$this->locationTable[$index][1] = 0;
}
public function writeChunk(FullChunk $chunk){
$this->lastUsed = time();
$chunkData = $chunk->toBinary();
if($chunkData !== false){
$this->saveChunk($chunk->getX() - ($this->getX() * 32), $chunk->getZ() - ($this->getZ() * 32), $chunkData);
}
}
protected static function getChunkOffset($x, $z){
return $x + ($z << 5);
}
public function close(){
$this->writeLocationTable();
fclose($this->filePointer);
$this->levelProvider = null;
}
public function doSlowCleanUp(){
for($i = 0; $i < 1024; ++$i){
if($this->locationTable[$i][0] === 0 or $this->locationTable[$i][1] === 0){
continue;
}
fseek($this->filePointer, $this->locationTable[$i][0] << 12);
$chunk = fread($this->filePointer, $this->locationTable[$i][1] << 12);
$length = Binary::readInt(substr($chunk, 0, 4));
if($length <= 1){
$this->locationTable[$i] = [0, 0, 0]; //Non-generated chunk, remove it from index
}
try{
$chunk = zlib_decode(substr($chunk, 5));
}catch(\Exception $e){
$this->locationTable[$i] = [0, 0, 0]; //Corrupted chunk, remove it
continue;
}
$chunk = chr(self::COMPRESSION_ZLIB) . zlib_encode($chunk, ZLIB_ENCODING_DEFLATE, 9);
$chunk = Binary::writeInt(strlen($chunk)) . $chunk;
$sectors = (int) ceil(strlen($chunk) / 4096);
if($sectors > $this->locationTable[$i][1]){
$this->locationTable[$i][0] = $this->lastSector + 1;
$this->lastSector += $sectors;
}
fseek($this->filePointer, $this->locationTable[$i][0] << 12);
fwrite($this->filePointer, str_pad($chunk, $sectors << 12, "\x00", STR_PAD_RIGHT));
}
$this->writeLocationTable();
$n = $this->cleanGarbage();
$this->writeLocationTable();
return $n;
}
private function cleanGarbage(){
$sectors = [];
foreach($this->locationTable as $index => $data){ //Calculate file usage
if($data[0] === 0 or $data[1] === 0){
$this->locationTable[$index] = [0, 0, 0];
continue;
}
for($i = 0; $i < $data[1]; ++$i){
$sectors[$data[0]] = $index;
}
}
if(count($sectors) === ($this->lastSector - 2)){ //No collection needed
return 0;
}
ksort($sectors);
$shift = 0;
$lastSector = 1; //First chunk - 1
fseek($this->filePointer, 8192);
$sector = 2;
foreach($sectors as $sector => $index){
if(($sector - $lastSector) > 1){
$shift += $sector - $lastSector - 1;
}
if($shift > 0){
fseek($this->filePointer, $sector << 12);
$old = fread($this->filePointer, 4096);
fseek($this->filePointer, ($sector - $shift) << 12);
fwrite($this->filePointer, $old, 4096);
}
$this->locationTable[$index][0] -= $shift;
$lastSector = $sector;
}
ftruncate($this->filePointer, ($sector + 1) << 12); //Truncate to the end of file written
return $shift;
}
protected function loadLocationTable(){
fseek($this->filePointer, 0);
$this->lastSector = 1;
$table = fread($this->filePointer, 4 * 1024 * 2); //1024 records * 4 bytes * 2 times
for($i = 0; $i < 1024; ++$i){
$index = unpack("N", substr($table, $i << 2, 4))[1];
$this->locationTable[$i] = [$index >> 8, $index & 0xff, unpack("N", substr($table, 4096 + ($i << 2), 4))[1]];
if(($this->locationTable[$i][0] + $this->locationTable[$i][1] - 1) > $this->lastSector){
$this->lastSector = $this->locationTable[$i][0] + $this->locationTable[$i][1] - 1;
}
}
}
private function writeLocationTable(){
$write = [];
for($i = 0; $i < 1024; ++$i){
$write[] = (($this->locationTable[$i][0] << 8) | $this->locationTable[$i][1]);
}
for($i = 0; $i < 1024; ++$i){
$write[] = $this->locationTable[$i][2];
}
fseek($this->filePointer, 0);
fwrite($this->filePointer, pack("N*", ...$write), 4096 * 2);
}
protected function writeLocationIndex($index){
fseek($this->filePointer, $index << 2);
fwrite($this->filePointer, Binary::writeInt(($this->locationTable[$index][0] << 8) | $this->locationTable[$index][1]), 4);
fseek($this->filePointer, 4096 + ($index << 2));
fwrite($this->filePointer, Binary::writeInt($this->locationTable[$index][2]), 4);
}
protected function createBlank(){
fseek($this->filePointer, 0);
ftruncate($this->filePointer, 0);
$this->lastSector = 1;
$table = "";
for($i = 0; $i < 1024; ++$i){
$this->locationTable[$i] = [0, 0];
$table .= Binary::writeInt(0);
}
$time = time();
for($i = 0; $i < 1024; ++$i){
$this->locationTable[$i][2] = $time;
$table .= Binary::writeInt($time);
}
fwrite($this->filePointer, $table, 4096 * 2);
}
public function getX(){
return $this->x;
}
public function getZ(){
return $this->z;
}
}
| NickY5/mitko_e_prostak | src/pocketmine/level/format/mcregion/RegionLoader.php | PHP | lgpl-3.0 | 11,885 |
<?php namespace Pardisan\Support\Facades;
use Illuminate\Support\Facades\Facade;
class Menu extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'menu';
}
}
| lucknerjb/hammihan-online | app/Pardisan/Support/Facades/Menu.php | PHP | lgpl-3.0 | 294 |
package edu.mit.blocks.codeblockutil;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JToolTip;
import javax.swing.KeyStroke;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import edu.mit.blocks.renderable.BlockLabel;
public class LabelWidget extends JComponent {
public static final int DROP_DOWN_MENU_WIDTH = 7;
private static final long serialVersionUID = 837647234895L;
/** Border of textfield*/
private static final Border textFieldBorder = new CompoundBorder(BorderFactory.createLoweredBevelBorder(), new EmptyBorder(1, 2, 1, 2));
/** Number formatter for this label */
private static final NumberFormatter nf = new NumberFormatter(NumberFormatter.MEDIUM_PRECISION);
/** Label that is visable iff editingText is false */
private final ShadowLabel textLabel = new ShadowLabel();
/** TextField that is visable iff editingText is true */
private final BlockLabelTextField textField = new BlockLabelTextField();
/** drop down menu icon */
private final LabelMenu menu = new LabelMenu();
;
/** The label text before user begins edit (applies only to editable labels)*/
private String labelBeforeEdit = "";
/** If this is a number, then only allow nagatvie signs and periods at certain spots */
private boolean isNumber = false;
/** Is labelText editable by the user -- default true */
private boolean isEditable = false;
/** If focus is true, then show the combo pop up menu */
private boolean isFocused = false;
/** Has ComboPopup accessable selections */
private boolean hasSiblings = false;
/** True if TEXTFIELD is being edited by user. */
private boolean editingText;
/** the background color of the tooltip */
private Color tooltipBackground = new Color(255, 255, 225);
private double zoom = 1.0;
private BlockLabel blockLabel;
/**
* BlockLabel Constructor that takes in BlockID as well.
* Unfortunately BlockID is needed, so the label can redirect mouse actions.
*
*/
public LabelWidget(String initLabelText, Color fieldColor, Color tooltipBackground) {
if (initLabelText == null) {
initLabelText = "";
}
this.setFocusTraversalKeysEnabled(false);//MOVE DEFAULT FOCUS TRAVERSAL KEYS SUCH AS TABS
this.setLayout(new BorderLayout());
this.tooltipBackground = tooltipBackground;
this.labelBeforeEdit = initLabelText;
//set up textfield colors
textField.setForeground(Color.WHITE);//white text
textField.setBackground(fieldColor);//background matching block color
textField.setCaretColor(Color.WHITE);//white caret
textField.setSelectionColor(Color.BLACK);//black highlight
textField.setSelectedTextColor(Color.WHITE);//white text when highlighted
textField.setBorder(textFieldBorder);
textField.setMargin(textFieldBorder.getBorderInsets(textField));
}
public void setBlockLabel(BlockLabel blockLabel) {
this.blockLabel = blockLabel;
}
protected void fireTextChanged(String text) {
blockLabel.textChanged(text);
}
protected void fireGenusChanged(String genus) {
blockLabel.genusChanged(genus);
}
protected void fireDimensionsChanged(Dimension value) {
blockLabel.dimensionsChanged(value);
}
protected boolean isTextValid(String text) {
return blockLabel.textValid(text);
}
public void addKeyListenerToTextField(KeyListener l) {
textField.addKeyListener(l);
}
public void addMouseListenerToLabel(MouseListener l) {
textLabel.addMouseListener(l);
}
public void addMouseMotionListenerToLabel(MouseMotionListener l) {
textLabel.addMouseMotionListener(l);
}
//////////////////////////////
//// LABEL CONFIGURATION /////
/////////////////////////////
public void showMenuIcon(boolean show) {
if (this.hasSiblings) {
isFocused = show;
// repaints the menu and items with the new zoom level
menu.popupmenu.setZoomLevel(zoom);
menu.repaint();
}
}
/**
* setEditingState sets the current editing state of the BlockLabel.
* Repaints BlockLabel to reflect the change.
*/
public void setEditingState(boolean editing) {
if (editing) {
editingText = true;
textField.setText(textLabel.getText().trim());
labelBeforeEdit = textLabel.getText();
this.removeAll();
this.add(textField);
textField.grabFocus();
} else {
//update to current textfield.text
//if text entered was not empty and if it was editing before
if (editingText) {
//make sure to remove leading and trailing spaces before testing if text is valid
//TODO if allow labels to have leading and trailing spaces, will need to modify this if statement
if (isTextValid(textField.getText().trim())) {
setText(textField.getText());
} else {
setText(labelBeforeEdit);
}
}
editingText = false;
}
}
/**
* editingText returns if BlockLable is being edited
* @return editingText
*/
public boolean editingText() {
return editingText;
}
/**
* setEditable state of BlockLabel
* @param isEditable specifying editable state of BlockLabel
*/
public void setEditable(boolean isEditable) {
this.isEditable = isEditable;
}
/**
* isEditable returns if BlockLable is editable
* @return isEditable
*/
public boolean isEditable() {
return isEditable;
}
public void setNumeric(boolean isNumber) {
this.isNumber = isNumber;
}
/**
* isEditable returns if BlockLable is editable
* @return isEditable
*/
public boolean isNumeric() {
return isNumber;
}
public void setSiblings(boolean hasSiblings, String[][] siblings) {
this.hasSiblings = hasSiblings;
this.menu.setSiblings(siblings);
}
public boolean hasSiblings() {
return this.hasSiblings;
}
/**
* set up fonts
* @param font
*/
public void setFont(Font font) {
super.setFont(font);
textLabel.setFont(font);
textField.setFont(font);
menu.setFont(font);
}
/**
* sets the tool tip of the label
*/
public void assignToolTipToLabel(String text) {
this.textLabel.setToolTipText(text);
}
/**
* getText
* @return String of the current BlockLabel
*/
public String getText() {
return textLabel.getText().trim();
}
/**
* setText to a NumberFormatted double
* @param value
*/
public void setText(double value) {
//check for +/- Infinity
if (Math.abs(value - Double.MAX_VALUE) < 1) {
updateLabelText("Infinity");
} else if (Math.abs(value + Double.MAX_VALUE) < 1) {
updateLabelText("-Infinity");
} else {
updateLabelText(nf.format(value));
}
}
/**
* setText to a String (trimmed to remove excess spaces)
* @param string
*/
public void setText(String string) {
if (string != null) {
updateLabelText(string.trim());
}
}
/**
* setText to a boolean
* @param bool
*/
public void setText(boolean bool) {
updateLabelText(bool ? "True" : "False");
}
/**
* updateLabelText updates labelText and sychronizes textField and textLabel to it
* @param text
*/
public void updateLabelText(String text) {
//leave some space to click on
if (text.equals("")) {
text = " ";
}
//update the text everywhere
textLabel.setText(text);
textField.setText(text);
//resize to new text
updateDimensions();
//the blockLabel needs to update the data in Block
this.fireTextChanged(text);
//show text label and additional ComboPopup if one exists
this.removeAll();
this.add(textLabel, BorderLayout.CENTER);
if (hasSiblings) {
this.add(menu, BorderLayout.EAST);
}
}
////////////////////
//// RENDERING /////
////////////////////
/**
* Updates the dimensions of the textRect, textLabel, and textField to the minimum size needed
* to contain all of the text in the current font.
*/
private void updateDimensions() {
Dimension updatedDimension = new Dimension(
textField.getPreferredSize().width,
textField.getPreferredSize().height);
if (this.hasSiblings) {
updatedDimension.width += LabelWidget.DROP_DOWN_MENU_WIDTH;
}
textField.setSize(updatedDimension);
textLabel.setSize(updatedDimension);
this.setSize(updatedDimension);
this.fireDimensionsChanged(this.getSize());
}
/**
* high lights the text of the editing text field from
* 0 to the end of textfield
*/
public void highlightText() {
this.textField.setSelectionStart(0);
}
/**
* Toggles the visual suggestion that this label may be editable depending on the specified
* suggest flag and properties of the block and label. If suggest is true, the visual suggestion will display. Otherwise, nothing
* is shown. For now, the visual suggestion is a simple white line boder.
* Other requirements for indicator to show:
* - label type must be NAME
* - label must be editable
* - block can not be a factory block
* @param suggest
*/
protected void suggestEditable(boolean suggest) {
if (isEditable) {
if (suggest) {
setBorder(BorderFactory.createLineBorder(Color.white));//show white border
} else {
setBorder(null);//hide white border
}
}
}
public void setZoomLevel(double newZoom) {
this.zoom = newZoom;
Font renderingFont;// = new Font(font.getFontName(), font.getStyle(), (int)(font.getSize()*newZoom));
AffineTransform at = new AffineTransform();
at.setToScale(newZoom, newZoom);
renderingFont = this.getFont().deriveFont(at);
this.setFont(renderingFont);
this.repaint();
this.updateDimensions();
}
public String toString() {
return "Label at " + this.getLocation() + " with text: \"" + textLabel.getText() + "\"";
}
/**
* returns true if this block should can accept a negative sign
*/
public boolean canProcessNegativeSign() {
if (this.getText() != null && this.getText().contains("-")) {
//if it already has a negative sign,
//make sure we're highlighting it
if (textField.getSelectedText() != null && textField.getSelectedText().contains("-")) {
return true;
} else {
return false;
}
} else {
//if it does not have negative sign,
//make sure our highlight covers index 0
if (textField.getCaretPosition() == 0) {
return true;
} else {
if (textField.getSelectionStart() == 0) {
return true;
}
}
}
return false;
}
/**
* BlockLabelTextField is a java JtextField that internally handles various events
* and provides the semantic to interface with the user. Unliek typical JTextFields,
* the blockLabelTextField allows clients to only enter certain keys board input.
* It also reacts to enters and escapse by delegating the KeyEvent to the parent
* RenderableBlock.
*/
private class BlockLabelTextField extends JTextField implements MouseListener, DocumentListener, FocusListener, ActionListener {
private static final long serialVersionUID = 873847239234L;
/** These Key inputs are processed by this text field */
private final char[] validNumbers = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '.'};
/** These Key inputs are processed by this text field if NOT a number block*/
private final char[] validChar = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j',
'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm',
'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F',
'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M',
'\'', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+',
'-', '=', '{', '}', '|', '[', ']', '\\', ' ',
':', '"', ';', '\'', '<', '>', '?', ',', '.', '/', '`', '~'};
/** These Key inputs are processed by all this text field */
private final int[] validMasks = {KeyEvent.VK_BACK_SPACE,
KeyEvent.VK_UP, KeyEvent.VK_DOWN, KeyEvent.VK_LEFT,
KeyEvent.VK_RIGHT, KeyEvent.VK_END, KeyEvent.VK_HOME,
'-', KeyEvent.VK_DELETE, KeyEvent.VK_SHIFT, KeyEvent.VK_CONTROL,
InputEvent.SHIFT_MASK, InputEvent.SHIFT_DOWN_MASK};
/**
* Contructs new block label text field
*/
private BlockLabelTextField() {
this.addActionListener(this);
this.getDocument().addDocumentListener(this);
this.addFocusListener(this);
this.addMouseListener(this);
/*
* Sets whether focus traversal keys are enabled
* for this Component. Components for which focus
* traversal keys are disabled receive key events
* for focus traversal keys.
*/
this.setFocusTraversalKeysEnabled(false);
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
public void mouseExited(MouseEvent arg0) {
//remove the white line border
//note: make call here since text fields consume mouse events
//preventing parent from responding to mouse exited events
suggestEditable(false);
}
public void actionPerformed(ActionEvent e) {
setEditingState(false);
}
public void changedUpdate(DocumentEvent e) {
//listens for change in attributes
}
public void insertUpdate(DocumentEvent e) {
updateDimensions();
}
public void removeUpdate(DocumentEvent e) {
updateDimensions();
}
public void focusGained(FocusEvent e) {
}
public void focusLost(FocusEvent e) {
setEditingState(false);
}
/**
* for all user-generated AND/OR system generated key inputs,
* either perform some action that should be triggered by
* that key or
*/
protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
if (isNumber) {
if (e.getKeyChar() == '-' && canProcessNegativeSign()) {
return super.processKeyBinding(ks, e, condition, pressed);
}
if (this.getText().contains(".") && e.getKeyChar() == '.') {
return false;
}
for (char c : validNumbers) {
if (e.getKeyChar() == c) {
return super.processKeyBinding(ks, e, condition, pressed);
}
}
} else {
for (char c : validChar) {
if (e.getKeyChar() == c) {
return super.processKeyBinding(ks, e, condition, pressed);
}
}
}
for (int i : validMasks) {
if (e.getKeyCode() == i) {
return super.processKeyBinding(ks, e, condition, pressed);
}
}
if ((e.getModifiers() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0) {
return super.processKeyBinding(ks, e, condition, pressed);
}
return false;
}
}
private class LabelMenu extends JPanel implements MouseListener, MouseMotionListener {
private static final long serialVersionUID = 328149080240L;
private CPopupMenu popupmenu;
private GeneralPath triangle;
private LabelMenu() {
this.setOpaque(false);
this.addMouseListener(this);
this.addMouseMotionListener(this);
this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
this.popupmenu = new CPopupMenu();
}
/**
* @param siblings = array of siblin's genus and initial label
* { {genus, label}, {genus, label}, {genus, label} ....}
*/
private void setSiblings(String[][] siblings) {
popupmenu = new CPopupMenu();
//if connected to a block, add self and add siblings
for (int i = 0; i < siblings.length; i++) {
final String selfGenus = siblings[i][0];
CMenuItem selfItem = new CMenuItem(siblings[i][1]);
selfItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fireGenusChanged(selfGenus);
showMenuIcon(false);
}
});
popupmenu.add(selfItem);
}
}
public boolean contains(Point p) {
return triangle != null && triangle.contains(p);
}
public boolean contains(int x, int y) {
return triangle != null && triangle.contains(x, y);
}
public void paint(Graphics g) {
super.paint(g);
if (isFocused) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
triangle = new GeneralPath();
triangle.moveTo(0, this.getHeight() / 4);
triangle.lineTo(this.getWidth() - 1, this.getHeight() / 4);
triangle.lineTo(this.getWidth() / 2 - 1, this.getHeight() / 4 + LabelWidget.DROP_DOWN_MENU_WIDTH);
triangle.lineTo(0, this.getHeight() / 4);
triangle.closePath();
g2.setColor(new Color(255, 255, 255, 100));
g2.fill(triangle);
g2.setColor(Color.BLACK);
g2.draw(triangle);
}
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
if (hasSiblings) {
popupmenu.show(this, 0, 0);
}
}
public void mouseReleased(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
}
/**
* Much like a JLabel, only the text is displayed with a shadow like outline
*/
private class ShadowLabel extends JLabel implements MouseListener, MouseMotionListener {
private static final long serialVersionUID = 90123787382L;
//To get the shadow effect the text must be displayed multiple times at
//multiple locations. x represents the center, white label.
// o is color values (0,0,0,0.5f) and b is black.
// o o
// o x b o
// o b o
// o
//offsetArrays representing the translation movement needed to get from
// the center location to a specific offset location given in {{x,y},{x,y}....}
//..........................................grey points.............................................black points
private final int[][] shadowPositionArray = {{0, -1}, {1, -1}, {-1, 0}, {2, 0}, {-1, 1}, {1, 1}, {0, 2}, {1, 0}, {0, 1}};
private final float[] shadowColorArray = {0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0, 0};
private double offsetSize = 1;
private ShadowLabel() {
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
//DO NOT DRAW SUPER's to prevent drawing of label's string.
//Implecations: background not automatically drawn
//super.paint(g);
//draw shadows
for (int i = 0; i < shadowPositionArray.length; i++) {
int dx = shadowPositionArray[i][0];
int dy = shadowPositionArray[i][1];
g2.setColor(new Color(0, 0, 0, shadowColorArray[i]));
g2.drawString(this.getText(), (int) ((4 + dx) * offsetSize), this.getHeight() + (int) ((dy - 6) * offsetSize));
}
//draw main Text
g2.setColor(Color.white);
g2.drawString(this.getText(), (int) ((4) * offsetSize), this.getHeight() + (int) ((-6) * offsetSize));
}
public JToolTip createToolTip() {
return new CToolTip(tooltipBackground);
}
/**
* Set to editing state upon mouse click if this block label is editable
*/
public void mouseClicked(MouseEvent e) {
//if clicked and if the label is editable,
if ((e.getClickCount() == 1) && isEditable) {
//if clicked and if the label is editable,
//then set it to the editing state when the label is clicked on
setEditingState(true);
textField.setSelectionStart(0);
}
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
suggestEditable(true);
}
public void mouseExited(MouseEvent e) {
suggestEditable(false);
}
public void mouseDragged(MouseEvent e) {
suggestEditable(false);
}
public void mouseMoved(MouseEvent e) {
suggestEditable(true);
}
}
}
| laurentschall/openblocks | src/main/java/edu/mit/blocks/codeblockutil/LabelWidget.java | Java | lgpl-3.0 | 24,554 |
'use strict';
const chai = require('chai');
const assert = chai.assert;
const sinon = require('sinon');
const responseError = require('../../../server/utils/errors/responseError');
describe('responseError', () => {
let spyCall;
const res = {};
let error = 'An error message';
beforeEach(() => {
res.status = sinon.stub().returns(res);
res.json = sinon.stub();
responseError(error, res);
});
it('Calls response method with default(500) error code', () => {
spyCall = res.status.getCall(0);
assert.isTrue(res.status.calledOnce);
assert.isTrue(spyCall.calledWithExactly(500));
});
it('Returns error wrapped in json response', () => {
spyCall = res.json.getCall(0);
assert.isTrue(res.json.calledOnce);
assert.isObject(spyCall.args[0]);
assert.property(spyCall.args[0], 'response', 'status');
});
it('Calls response method with custom error code', () => {
error = {
description: 'Bad request',
status_code: 400,
};
responseError(error, res);
spyCall = res.status.getCall(0);
assert.isTrue(res.status.called);
assert.isTrue(res.status.calledWithExactly(400));
});
});
| kn9ts/project-mulla | test/utils/errors/reponseError.js | JavaScript | lgpl-3.0 | 1,168 |
#include "sensorcontrol.h"
using namespace oi;
/*!
* \brief SensorControl::SensorControl
* \param station
* \param parent
*/
SensorControl::SensorControl(QPointer<Station> &station, QObject *parent) : QObject(parent), station(station), sensorValid(false){
this->worker = new SensorWorker();
this->connectSensorWorker();
}
/*!
* \brief SensorControl::~SensorControl
*/
SensorControl::~SensorControl(){
this->disconnectSensorWorker();
}
/*!
* \brief SensorControl::getSensor
* Returns a copy of the current sensor
* \return
*/
Sensor SensorControl::getSensor(){
//get sensor
Sensor sensor;
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "getSensor", Qt::DirectConnection,
Q_RETURN_ARG(Sensor, sensor));
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
return sensor;
}
/*!
* \brief SensorControl::setSensor
* Sets the current sensor to the given one
* \param sensor
*/
void SensorControl::setSensor(const QPointer<Sensor> &sensor){
//check sensor
if(sensor.isNull()){
return;
}
//check old sensor and add it to the list of used sensors
if(sensorValid){
this->usedSensors.append(this->getSensor());
}
//call method of sensor worker
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "setSensor", Qt::DirectConnection,
Q_ARG(QPointer<Sensor>, sensor));
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
//set sensor valid
this->sensorValid = true;
}
/*!
* \brief SensorControl::takeSensor
* Returns the current sensor instance. That sensor will no longer be used by the sensor worker
* \return
*/
QPointer<Sensor> SensorControl::takeSensor(){
//check old sensor and add it to the list of used sensors
if(sensorValid){
this->usedSensors.append(this->getSensor());
}
//call method of sensor worker
QPointer<Sensor> sensor(NULL);
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "takeSensor", Qt::DirectConnection,
Q_RETURN_ARG(QPointer<Sensor>, sensor));
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
//set sensor invalid
this->sensorValid = false;
return sensor;
}
/*!
* \brief SensorControl::resetSensor
* Disconnects and deletes the current sensor
*/
void SensorControl::resetSensor(){
//check old sensor and add it to the list of used sensors
if(sensorValid){
this->usedSensors.append(this->getSensor());
}
//call method of sensor worker
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "resetSensor", Qt::QueuedConnection);
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
//set sensor invalid
this->sensorValid = false;
}
/*!
* \brief SensorControl::getUsedSensors
* \return
*/
const QList<Sensor> &SensorControl::getUsedSensors(){
return this->usedSensors;
}
/*!
* \brief SensorControl::setUsedSensors
* \param sensors
*/
void SensorControl::setUsedSensors(const QList<Sensor> &sensors){
this->usedSensors = sensors;
}
/*!
* \brief SensorControl::getStreamFormat
* \return
*/
ReadingTypes SensorControl::getStreamFormat(){
//call method of sensor worker
ReadingTypes type = eUndefinedReading;
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "getStreamFormat", Qt::DirectConnection,
Q_RETURN_ARG(ReadingTypes, type));
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
return type;
}
/*!
* \brief SensorControl::setStreamFormat
* \param streamFormat
*/
void SensorControl::setStreamFormat(ReadingTypes streamFormat){
//call method of sensor worker
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "setStreamFormat", Qt::QueuedConnection,
Q_ARG(ReadingTypes, streamFormat));
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
}
/*!
* \brief SensorControl::getIsSensorSet
* \return
*/
bool SensorControl::getIsSensorSet(){
return this->sensorValid;
}
/*!
* \brief SensorControl::getIsSensorConnected
* \return
*/
bool SensorControl::getIsSensorConnected(){
//call method of sensor worker
bool isConnected = false;
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "getIsSensorConnected", Qt::DirectConnection,
Q_RETURN_ARG(bool, isConnected));
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
return isConnected;
}
/*!
* \brief SensorControl::getIsReadyForMeasurement
* \return
*/
bool SensorControl::getIsReadyForMeasurement(){
//call method of sensor worker
bool isReady = false;
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "getIsReadyForMeasurement", Qt::DirectConnection,
Q_RETURN_ARG(bool, isReady));
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
return isReady;
}
/*!
* \brief SensorControl::getIsBusy
* \return
*/
bool SensorControl::getIsBusy(){
//call method of sensor worker
bool isBusy = false;
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "getIsBusy", Qt::DirectConnection,
Q_RETURN_ARG(bool, isBusy));
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
return isBusy;
}
/*!
* \brief SensorControl::getSensorStatus
* \return
*/
QMap<QString, QString> SensorControl::getSensorStatus(){
//call method of sensor worker
QMap<QString, QString> status;
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "getSensorStatus", Qt::DirectConnection,
Q_RETURN_ARG(StringStringMap, status));
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
return status;
}
/*!
* \brief SensorControl::getActiveSensorType
* \return
*/
SensorTypes SensorControl::getActiveSensorType(){
//call method of sensor worker
SensorTypes type;
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "getActiveSensorType", Qt::DirectConnection,
Q_RETURN_ARG(SensorTypes, type));
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
return type;
}
/*!
* \brief SensorControl::getSupportedReadingTypes
* \return
*/
QList<ReadingTypes> SensorControl::getSupportedReadingTypes(){
//call method of sensor worker
QList<ReadingTypes> types;
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "getSupportedReadingTypes", Qt::DirectConnection,
Q_RETURN_ARG(QList<ReadingTypes>, types));
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
return types;
}
/*!
* \brief SensorControl::getSupportedConnectionTypes
* \return
*/
QList<ConnectionTypes> SensorControl::getSupportedConnectionTypes(){
//call method of sensor worker
QList<ConnectionTypes> types;
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "getSupportedConnectionTypes", Qt::DirectConnection,
Q_RETURN_ARG(QList<ConnectionTypes>, types));
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
return types;
}
/*!
* \brief SensorControl::getSupportedSensorActions
* \return
*/
QList<SensorFunctions> SensorControl::getSupportedSensorActions(){
//call method of sensor worker
QList<SensorFunctions> actions;
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "getSupportedSensorActions", Qt::DirectConnection,
Q_RETURN_ARG(QList<SensorFunctions>, actions));
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
return actions;
}
/*!
* \brief SensorControl::getSelfDefinedActions
* \return
*/
QStringList SensorControl::getSelfDefinedActions(){
//call method of sensor worker
QStringList actions;
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "getSelfDefinedActions", Qt::DirectConnection,
Q_RETURN_ARG(QStringList, actions));
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
return actions;
}
/*!
* \brief SensorControl::getSensorConfiguration
* \return
*/
SensorConfiguration SensorControl::getSensorConfiguration(){
//call method of sensor worker
SensorConfiguration sConfig;
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "getSensorConfiguration", Qt::DirectConnection,
Q_RETURN_ARG(SensorConfiguration, sConfig));
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
return sConfig;
}
/*!
* \brief SensorControl::setSensorConfiguration
* \param sConfig
*/
void SensorControl::setSensorConfiguration(const SensorConfiguration &sConfig){
//call method of sensor worker
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "setSensorConfiguration", Qt::QueuedConnection,
Q_ARG(SensorConfiguration, sConfig));
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
}
/*!
* \brief SensorControl::connectSensor
*/
void SensorControl::connectSensor(){
//call method of sensor worker
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "connectSensor", Qt::QueuedConnection);
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
}
/*!
* \brief SensorControl::disconnectSensor
*/
void SensorControl::disconnectSensor(){
//call method of sensor worker
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "disconnectSensor", Qt::QueuedConnection);
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
}
/*!
* \brief SensorControl::measure
* \param geomId
* \param mConfig
*/
void SensorControl::measure(const int &geomId, const MeasurementConfig &mConfig){
//call method of sensor worker
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "measure", Qt::QueuedConnection,
Q_ARG(int, geomId), Q_ARG(MeasurementConfig, mConfig));
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
}
/*!
* \brief SensorControl::move
* \param azimuth
* \param zenith
* \param distance
* \param isRelative
* \param measure
* \param geomId
* \param mConfig
*/
void SensorControl::move(const double &azimuth, const double &zenith, const double &distance, const bool &isRelative, const bool &measure, const int &geomId, const MeasurementConfig &mConfig){
//call method of sensor worker
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "move", Qt::QueuedConnection,
Q_ARG(double, azimuth), Q_ARG(double, zenith), Q_ARG(double, distance),
Q_ARG(bool, isRelative), Q_ARG(bool, measure), Q_ARG(int, geomId),
Q_ARG(MeasurementConfig, mConfig));
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
}
/*!
* \brief SensorControl::move
* \param x
* \param y
* \param z
* \param measure
* \param geomId
* \param mConfig
*/
void SensorControl::move(const double &x, const double &y, const double &z, const bool &measure, const int &geomId, const MeasurementConfig &mConfig){
//call method of sensor worker
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "move", Qt::QueuedConnection,
Q_ARG(double, x), Q_ARG(double, y), Q_ARG(double, z),
Q_ARG(bool, measure), Q_ARG(int, geomId), Q_ARG(MeasurementConfig, mConfig));
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
}
/*!
* \brief SensorControl::initialize
*/
void SensorControl::initialize(){
//call method of sensor worker
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "initialize", Qt::QueuedConnection);
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
}
/*!
* \brief SensorControl::motorState
*/
void SensorControl::motorState(){
//call method of sensor worker
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "motorState", Qt::QueuedConnection);
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
}
/*!
* \brief SensorControl::home
*/
void SensorControl::home(){
//call method of sensor worker
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "home", Qt::QueuedConnection);
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
}
/*!
* \brief SensorControl::toggleSight
*/
void SensorControl::toggleSight(){
//call method of sensor worker
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "toggleSight", Qt::QueuedConnection);
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
}
/*!
* \brief SensorControl::compensation
*/
void SensorControl::compensation(){
//call method of sensor worker
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "compensation", Qt::QueuedConnection);
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
}
/*!
* \brief SensorControl::selfDefinedAction
* \param action
*/
void SensorControl::selfDefinedAction(const QString &action){
//call method of sensor worker
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "selfDefinedAction", Qt::QueuedConnection,
Q_ARG(QString, action));
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
}
void SensorControl::search(){
//call method of sensor worker
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "search", Qt::QueuedConnection);
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
}
/*!
* \brief SensorControl::startReadingStream
*/
void SensorControl::startReadingStream(){
//call method of sensor worker
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "startReadingStream", Qt::QueuedConnection);
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
}
/*!
* \brief SensorControl::stopReadingStream
*/
void SensorControl::stopReadingStream(){
//call method of sensor worker
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "stopReadingStream", Qt::QueuedConnection);
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
}
/*!
* \brief SensorControl::startConnectionMonitoringStream
*/
void SensorControl::startConnectionMonitoringStream(){
//call method of sensor worker
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "startConnectionMonitoringStream", Qt::QueuedConnection);
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
}
/*!
* \brief SensorControl::stopConnectionMonitoringStream
*/
void SensorControl::stopConnectionMonitoringStream(){
//call method of sensor worker
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "stopConnectionMonitoringStream", Qt::QueuedConnection);
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
}
/*!
* \brief SensorControl::startStatusMonitoringStream
*/
void SensorControl::startStatusMonitoringStream(){
//call method of sensor worker
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "startStatusMonitoringStream", Qt::QueuedConnection);
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
}
/*!
* \brief SensorControl::stopStatusMonitoringStream
*/
void SensorControl::stopStatusMonitoringStream(){
//call method of sensor worker
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "stopStatusMonitoringStream", Qt::QueuedConnection);
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
}
void SensorControl::finishMeasurement(){
//call method of sensor worker
bool hasInvoked = QMetaObject::invokeMethod(this->worker, "finishMeasurement", Qt::DirectConnection);
if(!hasInvoked){
emit this->sensorMessage("Cannot invoke getSensor method of sensor worker", eErrorMessage, eConsoleMessage);
}
}
/*!
* \brief SensorControl::connectSensorWorker
*/
void SensorControl::connectSensorWorker(){
//connect sensor action results
QObject::connect(this->worker, &SensorWorker::commandFinished, this, &SensorControl::commandFinished, Qt::QueuedConnection);
QObject::connect(this->worker, &SensorWorker::measurementFinished, this, &SensorControl::measurementFinished, Qt::QueuedConnection);
QObject::connect(this->worker, &SensorWorker::measurementDone, this, &SensorControl::measurementDone, Qt::QueuedConnection);
//connect streaming results
QObject::connect(this->worker, &SensorWorker::realTimeReading, this, &SensorControl::realTimeReading, Qt::QueuedConnection);
QObject::connect(this->worker, &SensorWorker::realTimeStatus, this, &SensorControl::realTimeStatus, Qt::QueuedConnection);
QObject::connect(this->worker, &SensorWorker::connectionLost, this, &SensorControl::connectionLost, Qt::QueuedConnection);
QObject::connect(this->worker, &SensorWorker::connectionReceived, this, &SensorControl::connectionReceived, Qt::QueuedConnection);
QObject::connect(this->worker, &SensorWorker::isReadyForMeasurement, this, &SensorControl::isReadyForMeasurement, Qt::QueuedConnection);
//connect sensor messages
QObject::connect(this->worker, &SensorWorker::sensorMessage, this, &SensorControl::sensorMessage, Qt::QueuedConnection);
}
/*!
* \brief SensorControl::disconnectSensorWorker
*/
void SensorControl::disconnectSensorWorker(){
}
void SensorControl::setSensorWorkerThread(QPointer<QThread> t) {
this->worker->moveToThread(t);
}
| OpenIndy/OpenIndy-Core | src/sensorcontrol.cpp | C++ | lgpl-3.0 | 20,686 |
# Copyright (C) 2014 Optiv, Inc. (brad.spengler@optiv.com)
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
from lib.cuckoo.common.abstracts import Signature
class InjectionRWX(Signature):
name = "injection_rwx"
description = "Creates RWX memory"
severity = 2
confidence = 50
categories = ["injection"]
authors = ["Optiv"]
minimum = "1.2"
evented = True
def __init__(self, *args, **kwargs):
Signature.__init__(self, *args, **kwargs)
filter_apinames = set(["NtAllocateVirtualMemory","NtProtectVirtualMemory","VirtualProtectEx"])
filter_analysistypes = set(["file"])
def on_call(self, call, process):
if call["api"] == "NtAllocateVirtualMemory" or call["api"] == "VirtualProtectEx":
protection = self.get_argument(call, "Protection")
# PAGE_EXECUTE_READWRITE
if protection == "0x00000040":
return True
elif call["api"] == "NtProtectVirtualMemory":
protection = self.get_argument(call, "NewAccessProtection")
# PAGE_EXECUTE_READWRITE
if protection == "0x00000040":
return True
| lixiangning888/whole_project | modules/signatures_orginal_20151110/injection_rwx.py | Python | lgpl-3.0 | 1,229 |
using System;
namespace MakingSense.AspNetCore.HypermediaApi.Linking.StandardRelations
{
public class RelatedRelation : IRelation
{
public Type InputModel => null;
public bool IsVirtual => false;
public HttpMethod? Method => null;
public Type OutputModel => null;
public string RelationName => "related";
}
}
| MakingSense/aspnet-hypermedia-api | src/MakingSense.AspNetCore.HypermediaApi/Linking/StandardRelations/RelatedRelation.cs | C# | lgpl-3.0 | 330 |
/*
* Copyright (c) 2005–2012 Goethe Center for Scientific Computing - Simulation and Modelling (G-CSC Frankfurt)
* Copyright (c) 2012-2015 Goethe Center for Scientific Computing - Computational Neuroscience (G-CSC Frankfurt)
*
* This file is part of NeuGen.
*
* NeuGen is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* as published by the Free Software Foundation.
*
* see: http://opensource.org/licenses/LGPL-3.0
* file://path/to/NeuGen/LICENSE
*
* NeuGen is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* This version of NeuGen includes copyright notice and attribution requirements.
* According to the LGPL this information must be displayed even if you modify
* the source code of NeuGen. The copyright statement/attribution may not be removed.
*
* Attribution Requirements:
*
* If you create derived work you must do the following regarding copyright
* notice and author attribution.
*
* Add an additional notice, stating that you modified NeuGen. In addition
* you must cite the publications listed below. A suitable notice might read
* "NeuGen source code modified by YourName 2012".
*
* Note, that these requirements are in full accordance with the LGPL v3
* (see 7. Additional Terms, b).
*
* Publications:
*
* S. Wolf, S. Grein, G. Queisser. NeuGen 2.0 -
* Employing NeuGen 2.0 to automatically generate realistic
* morphologies of hippocapal neurons and neural networks in 3D.
* Neuroinformatics, 2013, 11(2), pp. 137-148, doi: 10.1007/s12021-012-9170-1
*
*
* J. P. Eberhard, A. Wanner, G. Wittum. NeuGen -
* A tool for the generation of realistic morphology
* of cortical neurons and neural networks in 3D.
* Neurocomputing, 70(1-3), pp. 327-343, doi: 10.1016/j.neucom.2006.01.028
*
*/
package org.neugen.gui;
import org.jdesktop.application.Action;
/**
* @author Sergei Wolf
*/
public final class NGAboutBox extends javax.swing.JDialog {
private static final long serialVersionUID = 1L;
public NGAboutBox(java.awt.Frame parent) {
super(parent);
initComponents();
getRootPane().setDefaultButton(closeButton);
}
@Action
public void closeAboutBox() {
dispose();
}
/**
* This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
closeButton = new javax.swing.JButton();
javax.swing.JLabel appTitleLabel = new javax.swing.JLabel();
javax.swing.JLabel versionLabel = new javax.swing.JLabel();
javax.swing.JLabel appVersionLabel = new javax.swing.JLabel();
javax.swing.JLabel vendorLabel = new javax.swing.JLabel();
javax.swing.JLabel appVendorLabel = new javax.swing.JLabel();
javax.swing.JLabel homepageLabel = new javax.swing.JLabel();
javax.swing.JLabel appHomepageLabel = new javax.swing.JLabel();
javax.swing.JLabel appDescLabel = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(org.neugen.gui.NeuGenApp.class).getContext().getResourceMap(NGAboutBox.class);
setTitle(resourceMap.getString("title")); // NOI18N
setModal(true);
setName("aboutBox"); // NOI18N
setResizable(false);
javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(org.neugen.gui.NeuGenApp.class).getContext().getActionMap(NGAboutBox.class, this);
closeButton.setAction(actionMap.get("closeAboutBox")); // NOI18N
closeButton.setName("closeButton"); // NOI18N
appTitleLabel.setFont(appTitleLabel.getFont().deriveFont(appTitleLabel.getFont().getStyle() | java.awt.Font.BOLD, appTitleLabel.getFont().getSize()+4));
appTitleLabel.setText(resourceMap.getString("Application.title")); // NOI18N
appTitleLabel.setName("appTitleLabel"); // NOI18N
versionLabel.setFont(versionLabel.getFont().deriveFont(versionLabel.getFont().getStyle() | java.awt.Font.BOLD));
versionLabel.setText(resourceMap.getString("versionLabel.text")); // NOI18N
versionLabel.setName("versionLabel"); // NOI18N
appVersionLabel.setText(resourceMap.getString("Application.version")); // NOI18N
appVersionLabel.setName("appVersionLabel"); // NOI18N
vendorLabel.setFont(vendorLabel.getFont().deriveFont(vendorLabel.getFont().getStyle() | java.awt.Font.BOLD));
vendorLabel.setText(resourceMap.getString("vendorLabel.text")); // NOI18N
vendorLabel.setName("vendorLabel"); // NOI18N
appVendorLabel.setText(resourceMap.getString("Application.vendor")); // NOI18N
appVendorLabel.setName("appVendorLabel"); // NOI18N
homepageLabel.setFont(homepageLabel.getFont().deriveFont(homepageLabel.getFont().getStyle() | java.awt.Font.BOLD));
homepageLabel.setText(resourceMap.getString("homepageLabel.text")); // NOI18N
homepageLabel.setName("homepageLabel"); // NOI18N
appHomepageLabel.setText(resourceMap.getString("Application.homepage")); // NOI18N
appHomepageLabel.setName("appHomepageLabel"); // NOI18N
appDescLabel.setText(resourceMap.getString("appDescLabel.text")); // NOI18N
appDescLabel.setName("appDescLabel"); // NOI18N
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(vendorLabel)
.add(appTitleLabel)
.add(appDescLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 269, Short.MAX_VALUE)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(versionLabel)
.add(homepageLabel))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(appVendorLabel)
.add(appVersionLabel)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(closeButton)
.add(appHomepageLabel)))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.add(appTitleLabel)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(appDescLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(versionLabel)
.add(appVersionLabel))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(layout.createSequentialGroup()
.add(appVendorLabel)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(appHomepageLabel))
.add(homepageLabel))
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(vendorLabel)
.add(49, 49, 49))
.add(layout.createSequentialGroup()
.add(18, 18, 18)
.add(closeButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
);
pack();
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton closeButton;
// End of variables declaration//GEN-END:variables
}
| NeuroBox3D/NeuGen | NeuGen/src/org/neugen/gui/NGAboutBox.java | Java | lgpl-3.0 | 9,348 |
/*
* HA-JDBC: High-Availability JDBC
* Copyright (C) 2013 Paul Ferraro
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.hajdbc.sql.io;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.Map;
import net.sf.hajdbc.Database;
import net.sf.hajdbc.invocation.Invoker;
import net.sf.hajdbc.sql.ProxyFactory;
/**
* @author Paul Ferraro
*/
public class OutputStreamProxyFactory<Z, D extends Database<Z>, P> extends OutputProxyFactory<Z, D, P, OutputStream>
{
public OutputStreamProxyFactory(P parentProxy, ProxyFactory<Z, D, P, SQLException> parent, Invoker<Z, D, P, OutputStream, SQLException> invoker, Map<D, OutputStream> outputs)
{
super(parentProxy, parent, invoker, outputs);
}
@Override
public OutputStream createProxy()
{
return new OutputStreamProxy<>(this);
}
}
| ha-jdbc/ha-jdbc | core/src/main/java/net/sf/hajdbc/sql/io/OutputStreamProxyFactory.java | Java | lgpl-3.0 | 1,449 |
/**
* Copyright © 2002 Instituto Superior Técnico
*
* This file is part of FenixEdu Academic.
*
* FenixEdu Academic is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FenixEdu Academic is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>.
*/
package org.fenixedu.academic.domain.accounting;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;
import org.apache.commons.lang.StringUtils;
import org.fenixedu.academic.domain.Person;
import org.fenixedu.academic.domain.exceptions.DomainException;
import org.fenixedu.academic.domain.exceptions.DomainExceptionWithLabelFormatter;
import org.fenixedu.academic.domain.organizationalStructure.Party;
import org.fenixedu.academic.util.LabelFormatter;
import org.fenixedu.academic.util.Money;
import org.fenixedu.bennu.core.domain.Bennu;
import org.fenixedu.bennu.core.domain.User;
import org.fenixedu.bennu.core.security.Authenticate;
import org.fenixedu.bennu.core.signals.DomainObjectEvent;
import org.fenixedu.bennu.core.signals.Signal;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.YearMonthDay;
/**
* Two-ledged accounting transaction
*
* @author naat
*
*/
public class AccountingTransaction extends AccountingTransaction_Base {
public static final String SIGNAL_ANNUL = AccountingTransaction.class.getName() + ".annul";
public static Comparator<AccountingTransaction> COMPARATOR_BY_WHEN_REGISTERED =
(leftAccountingTransaction, rightAccountingTransaction) -> {
int comparationResult =
leftAccountingTransaction.getWhenRegistered().compareTo(rightAccountingTransaction.getWhenRegistered());
return (comparationResult == 0) ? leftAccountingTransaction.getExternalId().compareTo(
rightAccountingTransaction.getExternalId()) : comparationResult;
};
protected AccountingTransaction() {
super();
super.setRootDomainObject(Bennu.getInstance());
}
public AccountingTransaction(User responsibleUser, Event event, Entry debit, Entry credit,
AccountingTransactionDetail transactionDetail) {
this();
init(responsibleUser, event, debit, credit, transactionDetail);
}
private AccountingTransaction(User responsibleUser, Entry debit, Entry credit, AccountingTransactionDetail transactionDetail,
AccountingTransaction transactionToAdjust) {
this();
init(responsibleUser, transactionToAdjust.getEvent(), debit, credit, transactionDetail, transactionToAdjust);
}
protected void init(User responsibleUser, Event event, Entry debit, Entry credit,
AccountingTransactionDetail transactionDetail) {
init(responsibleUser, event, debit, credit, transactionDetail, null);
}
protected void init(User responsibleUser, Event event, Entry debit, Entry credit,
AccountingTransactionDetail transactionDetail, AccountingTransaction transactionToAdjust) {
checkParameters(event, debit, credit);
// check for operations after registered date
List<String> operationsAfter = event.getOperationsAfter(transactionDetail.getWhenProcessed());
if (!operationsAfter.isEmpty()) {
throw new DomainException("error.accounting.AccountingTransaction.cannot.create.transaction",
String.join(",", operationsAfter));
}
super.setEvent(event);
super.setResponsibleUser(responsibleUser);
super.addEntries(debit);
super.addEntries(credit);
super.setAdjustedTransaction(transactionToAdjust);
super.setTransactionDetail(transactionDetail);
}
private void checkParameters(Event event, Entry debit, Entry credit) {
if (event == null) {
throw new DomainException("error.accounting.accountingTransaction.event.cannot.be.null");
}
if (debit == null) {
throw new DomainException("error.accounting.accountingTransaction.debit.cannot.be.null");
}
if (credit == null) {
throw new DomainException("error.accounting.accountingTransaction.credit.cannot.be.null");
}
}
@Override
public void addEntries(Entry entries) {
throw new DomainException("error.accounting.accountingTransaction.cannot.add.entries");
}
@Override
public Set<Entry> getEntriesSet() {
return Collections.unmodifiableSet(super.getEntriesSet());
}
@Override
public void removeEntries(Entry entries) {
throw new DomainException("error.accounting.accountingTransaction.cannot.remove.entries");
}
@Override
public void setEvent(Event event) {
super.setEvent(event);
}
@Override
public void setResponsibleUser(User responsibleUser) {
throw new DomainException("error.accounting.accountingTransaction.cannot.modify.responsibleUser");
}
@Override
public void setAdjustedTransaction(AccountingTransaction adjustedTransaction) {
throw new DomainException("error.accounting.accountingTransaction.cannot.modify.adjustedTransaction");
}
@Override
public void setTransactionDetail(AccountingTransactionDetail transactionDetail) {
throw new DomainException("error.accounting.AccountingTransaction.cannot.modify.transactionDetail");
}
@Override
public void addAdjustmentTransactions(AccountingTransaction accountingTransaction) {
throw new DomainException(
"error.org.fenixedu.academic.domain.accounting.AccountingTransaction.cannot.add.accountingTransaction");
}
@Override
public Set<AccountingTransaction> getAdjustmentTransactionsSet() {
return Collections.unmodifiableSet(super.getAdjustmentTransactionsSet());
}
public Stream<AccountingTransaction> getAdjustmentTransactionStream() {
return super.getAdjustmentTransactionsSet().stream();
}
@Override
public void removeAdjustmentTransactions(AccountingTransaction adjustmentTransactions) {
throw new DomainException(
"error.org.fenixedu.academic.domain.accounting.AccountingTransaction.cannot.remove.accountingTransaction");
}
public LabelFormatter getDescriptionForEntryType(EntryType entryType) {
return getEvent().getDescriptionForEntryType(entryType);
}
public Account getFromAccount() {
return getEntry(false).getAccount();
}
public Account getToAccount() {
return getEntry(true).getAccount();
}
public Entry getToAccountEntry() {
return getEntry(true);
}
public Entry getFromAccountEntry() {
return getEntry(false);
}
private Entry getEntry(boolean positive) {
for (final Entry entry : super.getEntriesSet()) {
if (entry.isPositiveAmount() == positive) {
return entry;
}
}
throw new DomainException("error.accounting.accountingTransaction.transaction.data.is.corrupted");
}
public AccountingTransaction reimburse(User responsibleUser, PaymentMethod paymentMethod,String
paymentReference, Money amountToReimburse) {
return reimburse(responsibleUser, paymentMethod,paymentReference, amountToReimburse, null);
}
public AccountingTransaction reimburse(User responsibleUser, PaymentMethod paymentMethod, String
paymentReference, Money amountToReimburse, String comments) {
return reimburse(responsibleUser, paymentMethod, paymentReference, amountToReimburse, comments, true);
}
public AccountingTransaction reimburse(User responsibleUser, PaymentMethod paymentMethod, String
paymentReference, Money amountToReimburse,
DateTime reimburseDate, String comments) {
return reimburse(responsibleUser, paymentMethod, paymentReference, amountToReimburse, comments, true, reimburseDate);
}
public AccountingTransaction reimburseWithoutRules(User responsibleUser, PaymentMethod paymentMethod, String
paymentReference, Money amountToReimburse) {
return reimburseWithoutRules(responsibleUser, paymentMethod, paymentReference, amountToReimburse, null);
}
public AccountingTransaction reimburseWithoutRules(User responsibleUser, PaymentMethod paymentMethod, String
paymentReference, Money amountToReimburse,
String comments) {
return reimburse(responsibleUser, paymentMethod, paymentReference, amountToReimburse, comments, false);
}
public void annul(final User responsibleUser, final String reason) {
if (StringUtils.isEmpty(reason)) {
throw new DomainException(
"error.org.fenixedu.academic.domain.accounting.AccountingTransaction.cannot.annul.without.reason");
}
checkRulesToAnnul();
annulReceipts();
Signal.emit(SIGNAL_ANNUL, new DomainObjectEvent<AccountingTransaction>(this));
reimburseWithoutRules(responsibleUser, getTransactionDetail().getPaymentMethod(), getTransactionDetail()
.getPaymentReference(), getAmountWithAdjustment(), reason);
}
private void checkRulesToAnnul() {
final List<String> operationsAfter = getEvent().getOperationsAfter(getWhenProcessed());
if (!operationsAfter.isEmpty()) {
throw new DomainException("error.accounting.AccountingTransaction.cannot.annul.operations.after",
String.join(",", operationsAfter));
}
}
private void annulReceipts() {
getToAccountEntry().getReceiptsSet().stream().filter(Receipt::isActive).forEach(r -> {
Person responsible = Optional.ofNullable(Authenticate.getUser()).map(User::getPerson).orElse(null);
r.annul(responsible);
});
}
private AccountingTransaction reimburse(User responsibleUser, PaymentMethod paymentMethod, String paymentReference, Money
amountToReimburse,
String comments, boolean checkRules) {
return reimburse(responsibleUser, paymentMethod, paymentReference, amountToReimburse, comments, checkRules, new DateTime
());
}
private AccountingTransaction reimburse(User responsibleUser, PaymentMethod paymentMethod, String paymentReference, Money
amountToReimburse,
String comments, boolean checkRules, DateTime reimburseDate) {
if (checkRules && !canApplyReimbursement(amountToReimburse)) {
throw new DomainException("error.accounting.AccountingTransaction.cannot.reimburse.events.that.may.open");
}
if (!getToAccountEntry().canApplyReimbursement(amountToReimburse)) {
throw new DomainExceptionWithLabelFormatter(
"error.accounting.AccountingTransaction.amount.to.reimburse.exceeds.entry.amount", getToAccountEntry()
.getDescription());
}
final AccountingTransaction transaction =
new AccountingTransaction(responsibleUser, new Entry(EntryType.ADJUSTMENT, amountToReimburse.negate(),
getToAccount()), new Entry(EntryType.ADJUSTMENT, amountToReimburse, getFromAccount()),
new AccountingTransactionDetail(reimburseDate, paymentMethod, paymentReference, comments), this);
getEvent().recalculateState(new DateTime());
return transaction;
}
public DateTime getWhenRegistered() {
return getTransactionDetail().getWhenRegistered();
}
public DateTime getWhenProcessed() {
return getTransactionDetail().getWhenProcessed();
}
public String getComments() {
return getTransactionDetail().getComments();
}
public boolean isPayed(final int civilYear) {
return getWhenRegistered().getYear() == civilYear;
}
public boolean isAdjustingTransaction() {
return getAdjustedTransaction() != null;
}
public boolean hasBeenAdjusted() {
return !super.getAdjustmentTransactionsSet().isEmpty();
}
public Entry getEntryFor(final Account account) {
for (final Entry accountingEntry : super.getEntriesSet()) {
if (accountingEntry.getAccount() == account) {
return accountingEntry;
}
}
throw new DomainException(
"error.accounting.accountingTransaction.transaction.data.is.corrupted.because.no.entry.belongs.to.account");
}
private boolean canApplyReimbursement(final Money amount) {
return getEvent().canApplyReimbursement(amount);
}
public boolean isSourceAccountFromParty(Party party) {
return getFromAccount().getParty() == party;
}
@Override
protected void checkForDeletionBlockers(Collection<String> blockers) {
super.checkForDeletionBlockers(blockers);
blockers.addAll(getEvent().getOperationsAfter(getWhenProcessed()));
}
public void delete() {
DomainException.throwWhenDeleteBlocked(getDeletionBlockers());
super.setAdjustedTransaction(null);
for (; !getAdjustmentTransactionsSet().isEmpty(); getAdjustmentTransactionsSet().iterator().next().delete()) {
;
}
if (getTransactionDetail() != null) {
getTransactionDetail().delete();
}
for (; !getEntriesSet().isEmpty(); getEntriesSet().iterator().next().delete()) {
;
}
super.setResponsibleUser(null);
super.setEvent(null);
setRootDomainObject(null);
super.deleteDomainObject();
}
public Money getAmountWithAdjustment() {
return getToAccountEntry().getAmountWithAdjustment();
}
public boolean isInsidePeriod(final YearMonthDay startDate, final YearMonthDay endDate) {
return isInsidePeriod(startDate.toLocalDate(), endDate.toLocalDate());
}
public boolean isInsidePeriod(final LocalDate startDate, final LocalDate endDate) {
return !getWhenRegistered().toLocalDate().isBefore(startDate) && !getWhenRegistered().toLocalDate().isAfter(endDate);
}
public boolean isInstallment() {
return false;
}
public PaymentMethod getPaymentMethod() {
return getTransactionDetail().getPaymentMethod();
}
public Money getOriginalAmount() {
return getToAccountEntry().getOriginalAmount();
}
}
| sergiofbsilva/fenixedu-academic | src/main/java/org/fenixedu/academic/domain/accounting/AccountingTransaction.java | Java | lgpl-3.0 | 15,077 |
/* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2014, Arnaud Roques
*
* Project Info: http://plantuml.sourceforge.net
*
* This file is part of PlantUML.
*
* PlantUML is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* PlantUML distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
*
* Original Author: Arnaud Roques
*/
package net.sourceforge.plantuml.graphic;
import java.awt.geom.Dimension2D;
import net.sourceforge.plantuml.ugraphic.UChangeBackColor;
import net.sourceforge.plantuml.ugraphic.UChangeColor;
import net.sourceforge.plantuml.ugraphic.UGraphic;
import net.sourceforge.plantuml.ugraphic.URectangle;
import net.sourceforge.plantuml.ugraphic.UStroke;
public class TextBlockGeneric implements TextBlock {
private final TextBlock textBlock;
private final HtmlColor background;
private final HtmlColor border;
public TextBlockGeneric(TextBlock textBlock, HtmlColor background, HtmlColor border) {
this.textBlock = textBlock;
this.border = border;
this.background = background;
}
public Dimension2D calculateDimension(StringBounder stringBounder) {
final Dimension2D dim = textBlock.calculateDimension(stringBounder);
return dim;
}
public void drawU(UGraphic ug) {
ug = ug.apply(new UChangeBackColor(background));
ug = ug.apply(new UChangeColor(border));
final Dimension2D dim = calculateDimension(ug.getStringBounder());
ug.apply(new UStroke(2, 2, 1)).draw(new URectangle(dim.getWidth(), dim.getHeight()));
textBlock.drawU(ug);
}
}
| mar9000/plantuml | src/net/sourceforge/plantuml/graphic/TextBlockGeneric.java | Java | lgpl-3.0 | 2,272 |
/*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.authentication.ws;
import org.junit.Test;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
public class AuthenticationWsModuleTest {
@Test
public void verify_count_of_added_components() {
ListContainer container = new ListContainer();
new AuthenticationWsModule().configure(container);
assertThat(container.getAddedObjects()).hasSize(4);
}
}
| SonarSource/sonarqube | server/sonar-webserver-webapi/src/test/java/org/sonar/server/authentication/ws/AuthenticationWsModuleTest.java | Java | lgpl-3.0 | 1,286 |
<?php
/*************************************************************************************/
/* This file is part of the RainbowPHP package. If you think this file is lost, */
/* please send it to anyone kind enough to take care of it. Thank you. */
/* */
/* email : bperche9@gmail.com */
/* web : http://www.benjaminperche.fr */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace RainbowPHP\Generator;
use RainbowPHP\DataProvider\DataProviderInterface;
use RainbowPHP\File\FileHandlerInterface;
use RainbowPHP\Formatter\FormatterInterface;
use RainbowPHP\Formatter\LineFormatter;
use RainbowPHP\Transformer\TransformerInterface;
/**
* Class FileGenerator
* @package RainbowPHP\Generator
* @author Benjamin Perche <bperche9@gmail.com>
*/
class FileGenerator implements FileGeneratorInterface
{
protected $fileHandler;
protected $transformer;
protected $dataProvider;
protected $formatter;
public function __construct(
FileHandlerInterface $fileHandler,
TransformerInterface $transformer,
DataProviderInterface $dataProvider,
FormatterInterface $formatter = null
) {
$this->fileHandler = $fileHandler;
$this->transformer = $transformer;
$this->dataProvider = $dataProvider;
$this->formatter = $formatter ?: new LineFormatter();
}
public function generateFile()
{
foreach ($this->dataProvider->generate() as $value) {
if (null !== $value) {
$this->fileHandler->writeLine($this->formatter->format($value, $this->transformer->transform($value)));
}
}
}
}
| lovenunu/RainbowPHP | src/RainbowPHP/Generator/FileGenerator.php | PHP | lgpl-3.0 | 2,135 |
<?php
namespace pocketmine\entity;
use pocketmine\item\Item as ItemItem;
use pocketmine\nbt\tag\IntTag;
class Slime extends Monster{
const NETWORK_ID = self::SLIME;
const DATA_SIZE = 16;
public $height = 2;
public $width = 2;
public $lenght = 2;//TODO: Size
protected $exp_min = 1;
protected $exp_max = 1;//TODO: Size
public function initEntity(){
$this->setMaxHealth(1);
parent::initEntity();
if (!isset($this->namedtag->Size)){
$this->setSize(mt_rand(0, 3));
}
$this->setSize($this->getSize());
}
public function getName(): string{
return "Slime";
}
public function getDrops(): array{
return [
ItemItem::get(ItemItem::SLIMEBALL, 0, mt_rand(0, 2))
];
}
public function setSize($value){
$this->namedtag->Size = new IntTag("Size", $value);
$this->setDataProperty(self::DATA_SIZE, self::DATA_TYPE_INT, $value);
}
public function getSize(){
return $this->namedtag["Size"];
}
}
| ClearSkyTeam/PocketMine-MP | src/pocketmine/entity/Slime.php | PHP | lgpl-3.0 | 931 |
#include "GAPhysicsBaseTemp.h"
//------------------------------GAPhysicsBase------------------------------------------
GAPhysicsBase::GAPhysicsBase()
{
}
int GAPhysicsBase::testCollideWith(GAPhysicsBase* object2,GAVector3& collidePoint)
{
return 0;
}
//--------------------------------GALine-----------------------------------------------
GALine::GALine()
{
p1=GAVector3(0,0,0);
p2=GAVector3(1,1,1);
}
GALine::GALine(GAVector3 p1_,GAVector3 p2_)
{
p1=p1_;
p2=p2_;
}
//-------------------------------GASegment---------------------------------------------
GASegment::GASegment()
{
pstart=GAVector3(0,0,0);
pend=GAVector3(1,1,1);
}
GASegment::GASegment(GAVector3 pstart_,GAVector3 pend_)
{
pstart=pstart_;
pend=pend_;
}
//-------------------------------GAPlane-----------------------------------------------
GAPlane::GAPlane()
{
}
int GAPlane::testCollideWith(GAPhysicsBase* object2,GAVector3& collidePoint)
{
return 0;
}
//-----------------------------------GACube--------------------------------------------
GACube::GACube()
{
}
int GACube::testCollideWith(GAPhysicsBase* object2,GAVector3& collidePoint)
{
return 0;
}
int GACube::testCollideWithCube(GACube* object2,GAVector3& collidePoint)
{
return 0;
}
//--------------------------------GACylinder-------------------------------------------
//--------------------------------GASphere---------------------------------------------
//--------------------------------GACapsule-------------------------------------------- | grandiazhao/Grandia-Engine | GrandArtProcessor/GrandArtProcessor/GAPhysicsBaseTemp.cpp | C++ | lgpl-3.0 | 1,506 |
/*******************************************************************************
* Este arquivo é parte do Biblivre5.
*
* Biblivre5 é um software livre; você pode redistribuí-lo e/ou
* modificá-lo dentro dos termos da Licença Pública Geral GNU como
* publicada pela Fundação do Software Livre (FSF); na versão 3 da
* Licença, ou (caso queira) qualquer versão posterior.
*
* Este programa é distribuído na esperança de que possa ser útil,
* mas SEM NENHUMA GARANTIA; nem mesmo a garantia implícita de
* MERCANTIBILIDADE OU ADEQUAÇÃO PARA UM FIM PARTICULAR. Veja a
* Licença Pública Geral GNU para maiores detalhes.
*
* Você deve ter recebido uma cópia da Licença Pública Geral GNU junto
* com este programa, Se não, veja em <http://www.gnu.org/licenses/>.
*
* @author Alberto Wagner <alberto@biblivre.org.br>
* @author Danniel Willian <danniel@biblivre.org.br>
******************************************************************************/
package biblivre.core;
import java.io.File;
import java.util.LinkedList;
import org.json.JSONArray;
public class JavascriptCacheableList<T extends IFJson> extends LinkedList<T> implements IFCacheableJavascript {
private static final long serialVersionUID = 1L;
private String variable;
private String prefix;
private String suffix;
private JavascriptCache cache;
public JavascriptCacheableList(String variable, String prefix, String suffix) {
this.variable = variable;
this.prefix = prefix;
this.suffix = suffix;
}
@Override
public String getCacheFileNamePrefix() {
return this.prefix;
}
@Override
public String getCacheFileNameSuffix() {
return this.suffix;
}
@Override
public String toJavascriptString() {
JSONArray array = new JSONArray();
for (T el : this) {
array.put(el.toJSONObject());
}
return this.variable + " = " + array.toString() + ";";
}
@Override
public File getCacheFile() {
if (this.cache == null) {
this.cache = new JavascriptCache(this);
}
return this.cache.getCacheFile();
}
@Override
public String getCacheFileName() {
if (this.cache == null) {
this.cache = new JavascriptCache(this);
}
return this.cache.getFileName();
}
@Override
public void invalidateCache() {
this.cache = null;
}
}
| Biblivre/Biblivre-5 | src/java/biblivre/core/JavascriptCacheableList.java | Java | lgpl-3.0 | 2,296 |
// Copyright © 2004, 2010, Oracle and/or its affiliates. All rights reserved.
//
// MySQL Connector/NET is licensed under the terms of the GPLv2
// <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
// MySQL Connectors. There are special exceptions to the terms and
// conditions of the GPLv2 as it is applied to this software, see the
// FLOSS License Exception
// <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published
// by the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Security;
using System.Security.Permissions;
namespace MySql.Data.MySqlClient
{
[Serializable, AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)]
public sealed class MySqlClientPermissionAttribute : DBDataPermissionAttribute
{
// Methods
public MySqlClientPermissionAttribute(SecurityAction action) : base(action)
{
}
public override IPermission CreatePermission()
{
return new MySqlClientPermission(this);
}
}
}
| ramayasket/Kwisatz-Haderach | MySql.Data/MySqlClientPermissionAttribute.cs | C# | lgpl-3.0 | 1,830 |
using System;
using System.Linq;
using System.Threading;
using System.Web.Mvc;
using Arashi.Core;
using Arashi.Core.Domain;
using Arashi.Services.Localization;
namespace Arashi.Web.Mvc.Views
{
public abstract class AdminViewUserControlBase : WebViewPage //ViewUserControl
{
private ILocalizationService localizationService;
/// <summary>
/// Constructor
/// </summary>
protected AdminViewUserControlBase()
{
localizationService = IoC.Resolve<ILocalizationService>();
}
/// <summary>
/// Get the current RequestContext
/// </summary>
public IRequestContext RequestContext
{
get
{
if (ViewData.ContainsKey("Context") && ViewData["Context"] != null)
return ViewData["Context"] as IRequestContext;
else
return null;
}
}
#region Localization Support
/// <summary>
/// Get a localized global resource
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
protected string GlobalResource(string token)
{
return localizationService.GlobalResource(token, Thread.CurrentThread.CurrentUICulture);
}
/// <summary>
/// Get a localized global resource filled with format parameters
/// </summary>
/// <param name="token"></param>
/// <param name="args"></param>
/// <returns></returns>
protected string GlobalResource(string token, params object[] args)
{
return string.Format(GlobalResource(token), args);
}
#endregion
}
public abstract class AdminViewUserControlBase<TModel> : WebViewPage<TModel> // ViewUserControl<TModel>
where TModel : class
{
private ILocalizationService localizationService;
/// <summary>
/// Constructor
/// </summary>
protected AdminViewUserControlBase()
{
localizationService = IoC.Resolve<ILocalizationService>();
}
/// <summary>
/// Get the current RequestContext
/// </summary>
public IRequestContext RequestContext
{
get
{
if (ViewData.ContainsKey("Context") && ViewData["Context"] != null)
return ViewData["Context"] as IRequestContext;
else
return null;
}
}
#region Localization Support
/// <summary>
/// Get a localized global resource
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
protected string GlobalResource(string token)
{
return localizationService.GlobalResource(token, Thread.CurrentThread.CurrentUICulture);
}
/// <summary>
/// Get a localized global resource filled with format parameters
/// </summary>
/// <param name="token"></param>
/// <param name="args"></param>
/// <returns></returns>
protected string GlobalResource(string token, params object[] args)
{
return string.Format(GlobalResource(token), args);
}
#endregion
}
} | aozora/arashi | src/Web.Mvc/Views/AdminViewUserControlBase.cs | C# | lgpl-3.0 | 3,173 |
<?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
namespace pocketmine\entity;
use pocketmine\nbt\tag\String;
class Creeper extends Monster implements Explosive{
protected function initEntity(){
$this->namedtag->id = new String("id", "Creeper");
}
} | zxl777/PocketMine-MP | src/pocketmine/entity/Creeper.php | PHP | lgpl-3.0 | 920 |
/**********************************************************
DO NOT EDIT
This file was generated from stone specification "users"
www.prokarpaty.net
***********************************************************/
#include "dropbox/users/UsersFullAccount.h"
using namespace dropboxQt;
namespace dropboxQt{
namespace users{
///FullAccount
FullAccount::operator QJsonObject()const{
QJsonObject js;
this->toJson(js);
return js;
}
void FullAccount::toJson(QJsonObject& js)const{
Account::toJson(js);
if(!m_country.isEmpty())
js["country"] = QString(m_country);
if(!m_locale.isEmpty())
js["locale"] = QString(m_locale);
if(!m_referral_link.isEmpty())
js["referral_link"] = QString(m_referral_link);
js["team"] = (QJsonObject)m_team;
if(!m_team_member_id.isEmpty())
js["team_member_id"] = QString(m_team_member_id);
js["is_paired"] = m_is_paired;
m_account_type.toJson(js, "account_type");
}
void FullAccount::fromJson(const QJsonObject& js){
Account::fromJson(js);
m_country = js["country"].toString();
m_locale = js["locale"].toString();
m_referral_link = js["referral_link"].toString();
m_team.fromJson(js["team"].toObject());
m_team_member_id = js["team_member_id"].toString();
m_is_paired = js["is_paired"].toVariant().toBool();
m_account_type.fromJson(js["account_type"].toObject());
}
QString FullAccount::toString(bool multiline)const
{
QJsonObject js;
toJson(js);
QJsonDocument doc(js);
QString s(doc.toJson(multiline ? QJsonDocument::Indented : QJsonDocument::Compact));
return s;
}
std::unique_ptr<FullAccount> FullAccount::factory::create(const QByteArray& data)
{
QJsonDocument doc = QJsonDocument::fromJson(data);
QJsonObject js = doc.object();
return create(js);
}
std::unique_ptr<FullAccount> FullAccount::factory::create(const QJsonObject& js)
{
std::unique_ptr<FullAccount> rv;
rv = std::unique_ptr<FullAccount>(new FullAccount);
rv->fromJson(js);
return rv;
}
}//users
}//dropboxQt
| kratos83/FabariaGest | qtdropbox/dropbox/users/UsersFullAccount.cpp | C++ | lgpl-3.0 | 2,066 |
# Define helper methods to create test data
# for mail view
module MailViewTestData
def admin_email
@admin_email ||= FactoryGirl.build(:email, address: "admin@marketplace.com")
end
def admin
@admin ||= FactoryGirl.build(:person, emails: [admin_email])
end
def author
@author ||= FactoryGirl.build(:person)
end
def starter
@starter ||= FactoryGirl.build(:person)
end
def member
return @member unless @member.nil?
@member ||= FactoryGirl.build(:person)
@member.emails.first.confirmation_token = "123456abcdef"
@member
end
def community_memberships
@community_memberships ||= [
FactoryGirl.build(:community_membership, person: admin, admin: true),
FactoryGirl.build(:community_membership, person: author),
FactoryGirl.build(:community_membership, person: starter),
FactoryGirl.build(:community_membership, person: member)
]
end
def members
@members ||= [admin, author, starter, member]
end
def payment_gateway
@braintree_payment_gateway ||= FactoryGirl.build(:braintree_payment_gateway)
end
def checkout_payment_gateway
@checkout_payment_gateway ||= FactoryGirl.build(:checkout_payment_gateway)
end
def payment
return @payment unless @payment.nil?
@payment ||= FactoryGirl.build(:braintree_payment,
id: 55,
payment_gateway:
payment_gateway,
payer: starter,
recipient: author
)
# Avoid infinite loop, set conversation here
@payment.transaction = transaction
@payment
end
def checkout_payment
return @checkout_payment unless @checkout_payment.nil?
@checkout_payment ||= FactoryGirl.build(:checkout_payment,
id: 55,
payment_gateway: checkout_payment_gateway,
payer: starter,
recipient: author
)
# Avoid infinite loop, set conversation here
@checkout_payment.conversation = conversation
@checkout_payment
end
def listing
@listing ||= FactoryGirl.build(:listing,
author: author,
id: 123
)
end
def participations
@participations ||= [
FactoryGirl.build(:participation, person: author),
FactoryGirl.build(:participation, person: starter, is_starter: true)
]
end
def transaction
@transaction ||= FactoryGirl.build(:transaction,
id: 99,
community: community,
listing: listing,
payment: payment,
conversation: conversation,
automatic_confirmation_after_days: 5
)
end
def paypal_transaction
@paypal_transaction ||= FactoryGirl.build(:transaction,
id: 100,
community: paypal_community,
listing: listing,
conversation: conversation,
payment_gateway: :paypal,
current_state: :paid,
shipping_price_cents: 100
)
end
def paypal_community
@paypal_community ||= FactoryGirl.build(:community,
custom_color1: "00FF99",
id: 999
)
end
def conversation
@conversation ||= FactoryGirl.build(:conversation,
id: 99,
community: community,
listing: listing,
participations: participations,
participants: [author, starter],
messages: [message]
)
end
def message
@message ||= FactoryGirl.build(:message,
sender: starter,
id: 123
)
end
def community
@community ||= FactoryGirl.build(:community,
payment_gateway: payment_gateway,
custom_color1: "FF0099",
admins: [admin],
members: members,
community_memberships: community_memberships
)
end
def checkout_community
@checkout_community ||= FactoryGirl.build(:community,
payment_gateway: checkout_payment_gateway,
custom_color1: "FF0099",
admins: [admin],
members: members,
community_memberships: community_memberships
)
end
end
| ziyoucaishi/marketplace | app/mailers/mail_view_test_data.rb | Ruby | lgpl-3.0 | 3,816 |
package br.com.vepo.datatransform.model;
import org.springframework.beans.factory.annotation.Autowired;
public abstract class Repository<T> {
@Autowired
protected MongoConnection mongoConnection;
public <V> T find(Class<T> clazz, V key) {
return mongoConnection.getMorphiaDataStore().get(clazz, key);
}
public void persist(T obj) {
mongoConnection.getMorphiaDataStore().save(obj);
}
}
| vepo/data-refine | src/main/java/br/com/vepo/datatransform/model/Repository.java | Java | lgpl-3.0 | 399 |
// Copyright 2012, 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package charmrepo_test
import (
jc "github.com/juju/testing/checkers"
gc "gopkg.in/check.v1"
"gopkg.in/juju/charm.v6-unstable"
"gopkg.in/juju/charmrepo.v0"
"gopkg.in/juju/charmrepo.v0/csclient"
charmtesting "gopkg.in/juju/charmrepo.v0/testing"
)
var TestCharms = charmtesting.NewRepo("internal/test-charm-repo", "quantal")
type inferRepoSuite struct{}
var _ = gc.Suite(&inferRepoSuite{})
var inferRepositoryTests = []struct {
url string
localRepoPath string
err string
}{{
url: "cs:trusty/django",
}, {
url: "local:precise/wordpress",
err: "path to local repository not specified",
}, {
url: "local:precise/haproxy-47",
localRepoPath: "/tmp/repo-path",
}}
func (s *inferRepoSuite) TestInferRepository(c *gc.C) {
for i, test := range inferRepositoryTests {
c.Logf("test %d: %s", i, test.url)
ref := charm.MustParseReference(test.url)
repo, err := charmrepo.InferRepository(
ref, charmrepo.NewCharmStoreParams{}, test.localRepoPath)
if test.err != "" {
c.Assert(err, gc.ErrorMatches, test.err)
c.Assert(repo, gc.IsNil)
continue
}
c.Assert(err, jc.ErrorIsNil)
switch store := repo.(type) {
case *charmrepo.LocalRepository:
c.Assert(store.Path, gc.Equals, test.localRepoPath)
case *charmrepo.CharmStore:
c.Assert(store.URL(), gc.Equals, csclient.ServerURL)
default:
c.Fatal("unknown repository type")
}
}
}
| jrwren/charmrepo | repo_test.go | GO | lgpl-3.0 | 1,499 |
<?php
namespace Clearbooks\Labs\Toggle\Entity;
class Parasol extends ToggleStub
{
protected $name = "Parasol";
protected $desc = "An MASsIVE Umbrella";
protected $id = 2;
protected $toggleTitle = "Parasols 4 Dayz";
} | clearbooks/labs | test/Toggle/Entity/Parasol.php | PHP | lgpl-3.0 | 233 |
package org.com.json;
/*
Copyright (c) 2002 JSON.org
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 shall be used for Good, not Evil.
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.
*/
import java.util.Iterator;
/**
* This provides static methods to convert an XML text into a JSONObject,
* and to covert a JSONObject into an XML text.
* @author JSON.org
* @version 2008-10-14
*/
public class XML {
/** The Character '&'. */
public static final Character AMP = new Character('&');
/** The Character '''. */
public static final Character APOS = new Character('\'');
/** The Character '!'. */
public static final Character BANG = new Character('!');
/** The Character '='. */
public static final Character EQ = new Character('=');
/** The Character '>'. */
public static final Character GT = new Character('>');
/** The Character '<'. */
public static final Character LT = new Character('<');
/** The Character '?'. */
public static final Character QUEST = new Character('?');
/** The Character '"'. */
public static final Character QUOT = new Character('"');
/** The Character '/'. */
public static final Character SLASH = new Character('/');
/**
* Replace special characters with XML escapes:
* <pre>
* & <small>(ampersand)</small> is replaced by &amp;
* < <small>(less than)</small> is replaced by &lt;
* > <small>(greater than)</small> is replaced by &gt;
* " <small>(double quote)</small> is replaced by &quot;
* </pre>
* @param string The string to be escaped.
* @return The escaped string.
*/
public static String escape(String string) {
StringBuffer sb = new StringBuffer();
for (int i = 0, len = string.length(); i < len; i++) {
char c = string.charAt(i);
switch (c) {
case '&':
sb.append("&");
break;
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case '"':
sb.append(""");
break;
default:
sb.append(c);
}
}
return sb.toString();
}
/**
* Throw an exception if the string contains whitespace.
* Whitespace is not allowed in tagNames and attributes.
* @param string
* @throws JSONException
*/
public static void noSpace(String string) throws JSONException {
int i, length = string.length();
if (length == 0) {
throw new JSONException("Empty string.");
}
for (i = 0; i < length; i += 1) {
if (Character.isWhitespace(string.charAt(i))) {
throw new JSONException("'" + string +
"' contains a space character.");
}
}
}
/**
* Scan the content following the named tag, attaching it to the context.
* @param x The XMLTokener containing the source string.
* @param context The JSONObject that will include the new material.
* @param name The tag name.
* @return true if the close tag is processed.
* @throws JSONException
*/
private static boolean parse(XMLTokener x, JSONObject context,
String name) throws JSONException {
char c;
int i;
String n;
JSONObject o = null;
String s;
Object t;
// Test for and skip past these forms:
// <!-- ... -->
// <! ... >
// <![ ... ]]>
// <? ... ?>
// Report errors for these forms:
// <>
// <=
// <<
t = x.nextToken();
// <!
if (t == BANG) {
c = x.next();
if (c == '-') {
if (x.next() == '-') {
x.skipPast("-->");
return false;
}
x.back();
} else if (c == '[') {
t = x.nextToken();
if (t.equals("CDATA")) {
if (x.next() == '[') {
s = x.nextCDATA();
if (s.length() > 0) {
context.accumulate("content", s);
}
return false;
}
}
throw x.syntaxError("Expected 'CDATA['");
}
i = 1;
do {
t = x.nextMeta();
if (t == null) {
throw x.syntaxError("Missing '>' after '<!'.");
} else if (t == LT) {
i += 1;
} else if (t == GT) {
i -= 1;
}
} while (i > 0);
return false;
} else if (t == QUEST) {
// <?
x.skipPast("?>");
return false;
} else if (t == SLASH) {
// Close tag </
t = x.nextToken();
if (name == null) {
throw x.syntaxError("Mismatched close tag" + t);
}
if (!t.equals(name)) {
throw x.syntaxError("Mismatched " + name + " and " + t);
}
if (x.nextToken() != GT) {
throw x.syntaxError("Misshaped close tag");
}
return true;
} else if (t instanceof Character) {
throw x.syntaxError("Misshaped tag");
// Open tag <
} else {
n = (String)t;
t = null;
o = new JSONObject();
for (;;) {
if (t == null) {
t = x.nextToken();
}
// attribute = value
if (t instanceof String) {
s = (String)t;
t = x.nextToken();
if (t == EQ) {
t = x.nextToken();
if (!(t instanceof String)) {
throw x.syntaxError("Missing value");
}
o.accumulate(s, JSONObject.stringToValue((String)t));
t = null;
} else {
o.accumulate(s, "");
}
// Empty tag <.../>
} else if (t == SLASH) {
if (x.nextToken() != GT) {
throw x.syntaxError("Misshaped tag");
}
context.accumulate(n, o);
return false;
// Content, between <...> and </...>
} else if (t == GT) {
for (;;) {
t = x.nextContent();
if (t == null) {
if (n != null) {
throw x.syntaxError("Unclosed tag " + n);
}
return false;
} else if (t instanceof String) {
s = (String)t;
if (s.length() > 0) {
o.accumulate("content", JSONObject.stringToValue(s));
}
// Nested element
} else if (t == LT) {
if (parse(x, o, n)) {
if (o.length() == 0) {
context.accumulate(n, "");
} else if (o.length() == 1 &&
o.opt("content") != null) {
context.accumulate(n, o.opt("content"));
} else {
context.accumulate(n, o);
}
return false;
}
}
}
} else {
throw x.syntaxError("Misshaped tag");
}
}
}
}
/**
* Convert a well-formed (but not necessarily valid) XML string into a
* JSONObject. Some information may be lost in this transformation
* because JSON is a data format and XML is a document format. XML uses
* elements, attributes, and content text, while JSON uses unordered
* collections of name/value pairs and arrays of values. JSON does not
* does not like to distinguish between elements and attributes.
* Sequences of similar elements are represented as JSONArrays. Content
* text may be placed in a "content" member. Comments, prologs, DTDs, and
* <code><[ [ ]]></code> are ignored.
* @param string The source string.
* @return A JSONObject containing the structured data from the XML string.
* @throws JSONException
*/
public static JSONObject toJSONObject(String string) throws JSONException {
JSONObject o = new JSONObject();
XMLTokener x = new XMLTokener(string);
while (x.more() && x.skipPast("<")) {
parse(x, o, null);
}
return o;
}
/**
* Convert a JSONObject into a well-formed, element-normal XML string.
* @param o A JSONObject.
* @return A string.
* @throws JSONException
*/
public static String toString(Object o) throws JSONException {
return toString(o, null);
}
/**
* Convert a JSONObject into a well-formed, element-normal XML string.
* @param o A JSONObject.
* @param tagName The optional name of the enclosing tag.
* @return A string.
* @throws JSONException
*/
public static String toString(Object o, String tagName)
throws JSONException {
StringBuffer b = new StringBuffer();
int i;
JSONArray ja;
JSONObject jo;
String k;
Iterator keys;
int len;
String s;
Object v;
if (o instanceof JSONObject) {
// Emit <tagName>
if (tagName != null) {
b.append('<');
b.append(tagName);
b.append('>');
}
// Loop thru the keys.
jo = (JSONObject)o;
keys = jo.keys();
while (keys.hasNext()) {
k = keys.next().toString();
v = jo.opt(k);
if (v == null) {
v = "";
}
if (v instanceof String) {
s = (String)v;
} else {
s = null;
}
// Emit content in body
if (k.equals("content")) {
if (v instanceof JSONArray) {
ja = (JSONArray)v;
len = ja.length();
for (i = 0; i < len; i += 1) {
if (i > 0) {
b.append('\n');
}
b.append(escape(ja.get(i).toString()));
}
} else {
b.append(escape(v.toString()));
}
// Emit an array of similar keys
} else if (v instanceof JSONArray) {
ja = (JSONArray)v;
len = ja.length();
for (i = 0; i < len; i += 1) {
v = ja.get(i);
if (v instanceof JSONArray) {
b.append('<');
b.append(k);
b.append('>');
b.append(toString(v));
b.append("</");
b.append(k);
b.append('>');
} else {
b.append(toString(v, k));
}
}
} else if (v.equals("")) {
b.append('<');
b.append(k);
b.append("/>");
// Emit a new tag <k>
} else {
b.append(toString(v, k));
}
}
if (tagName != null) {
// Emit the </tagname> close tag
b.append("</");
b.append(tagName);
b.append('>');
}
return b.toString();
// XML does not have good support for arrays. If an array appears in a place
// where XML is lacking, synthesize an <array> element.
} else if (o instanceof JSONArray) {
ja = (JSONArray)o;
len = ja.length();
for (i = 0; i < len; ++i) {
v = ja.opt(i);
b.append(toString(v, (tagName == null) ? "array" : tagName));
}
return b.toString();
} else {
s = (o == null) ? "null" : escape(o.toString());
return (tagName == null) ? "\"" + s + "\"" :
(s.length() == 0) ? "<" + tagName + "/>" :
"<" + tagName + ">" + s + "</" + tagName + ">";
}
}
} | jongos/Question_Box_Desktop | Json/src/org/com/json/XML.java | Java | lgpl-3.0 | 14,112 |