repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
mongocn/jcommerce | sandbox/web/src/main/java/com/jcommerce/gwt/client/panels/member/AddApply.java | package com.jcommerce.gwt.client.panels.member;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.InfoConfig;
import com.extjs.gxt.ui.client.widget.Label;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.button.ButtonBar;
import com.extjs.gxt.ui.client.widget.form.TextArea;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RadioButton;
import com.jcommerce.gwt.client.ContentWidget;
import com.jcommerce.gwt.client.ModelNames;
import com.jcommerce.gwt.client.PageState;
import com.jcommerce.gwt.client.form.BeanObject;
import com.jcommerce.gwt.client.model.GoodsTypeForm;
import com.jcommerce.gwt.client.model.IUser;
import com.jcommerce.gwt.client.model.IUserAccount;
import com.jcommerce.gwt.client.panels.data.ImportPanel.State;
import com.jcommerce.gwt.client.panels.privilege.AdminLog;
import com.jcommerce.gwt.client.service.CreateService;
import com.jcommerce.gwt.client.service.ReadService;
import com.jcommerce.gwt.client.widgets.ColumnPanel;
import com.jcommerce.gwt.client.widgets.UserSelector;
/**
* 添加申请
* @author monkey
*/
public class AddApply extends ContentWidget {
public static class State extends PageState {
private BeanObject user;
public BeanObject getUser() {
return user;
}
public void setUser(BeanObject user) {
this.user = user;
setEditting(user != null);
}
public String getPageClassName() {
return AddApply.class.getName();
}
public String getMenuDisplayName() {
return "添加申请";
}
}
public State getCurState() {
if (curState == null ) {
curState = new State();
}
return (State)curState;
}
@Override
public String getDescription() {
return "AddApplyDescription";
}
@Override
public String getName() {
return "添加申请";
}
public String getButtonText() {
return "充值和提现申请列表";
}
protected void buttonClicked() {
clear();
MemberApplication.State state = new MemberApplication.State();
state.execute();
}
private ColumnPanel contentPanel;
private RadioButton save; // 转账
private RadioButton take; // 提现
private RadioButton notConfirm; // 未确认
private RadioButton complete; // 已完成
private RadioButton cancel; // 取消
private Button btnOK = new Button(); // OK
private Button btnCancel = new Button(); // cancel
private UserSelector userSelector;
private TextField accountField;
private ListBox paymentType;
private TextArea manager;
private TextArea user;
protected void onRender(Element parent, int index) {
super.onRender(parent, index);
add(createMainPanel()); // 主界面
}
/**
* 添加信息界面
* @return contentPanel
*/
private ColumnPanel createMainPanel() {
contentPanel = new ColumnPanel();
userSelector = new UserSelector();
userSelector.setBean(ModelNames.USER);
userSelector.setCaption("Select User");
userSelector.setMessage("Select User");
accountField = GoodsTypeForm.getNameField("金额:");
accountField.setWidth(300);
contentPanel.createPanel(IUserAccount.USER, "会员名称:", userSelector); // 会员名称
contentPanel.createPanel(IUserAccount.AMOUNT, "金额:", accountField); // 金额
paymentType = new ListBox();
paymentType.addItem("请选择...");
paymentType.addItem("银行汇帐/转账");
paymentType.addItem("余额支付");
paymentType.addItem("邮局汇款");
contentPanel.createPanel(IUserAccount.PAYMENT, "支付方式:", paymentType); // 支付方式
HorizontalPanel typePanel = new HorizontalPanel();
save = new RadioButton(IUserAccount.PROCESSTYPE, "充值");
take = new RadioButton(IUserAccount.PROCESSTYPE, "提现");
save.setChecked(true);
typePanel.add(save);
Label sep = new Label();
sep.setWidth(20);
typePanel.add(sep);
typePanel.add(take);
contentPanel.createPanel(IUserAccount.PROCESSTYPE, "类型:", typePanel); // 类型
manager = new TextArea();
manager.setWidth(400);
contentPanel.createPanel(IUserAccount.ADMINNOTE, "管理员备注:", manager); // 管理员备注
user = new TextArea();
user.setWidth(400);
contentPanel.createPanel(IUserAccount.USERNOTE, "会员描述:", user); // 会员描述
HorizontalPanel statePanel = new HorizontalPanel();
notConfirm = new RadioButton(IUserAccount.PAID, "未确认");
complete = new RadioButton(IUserAccount.PAID, "已完成");
cancel = new RadioButton(IUserAccount.PAID, "取消");
statePanel.add(notConfirm);
sep = new Label();
sep.setWidth(20);
statePanel.add(sep);
statePanel.add(complete);
sep = new Label();
sep.setWidth(20);
statePanel.add(sep);
statePanel.add(cancel);
notConfirm.setChecked(true);
contentPanel.createPanel(IUserAccount.PAID, "到款状态:", statePanel); // 到款状态
HorizontalPanel buttonPanel = new HorizontalPanel();
buttonPanel.setSpacing(10);
btnOK.setText("确定");
btnCancel.setText("重置");
btnOK.addSelectionListener(new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
if( !getCurState().isEditting() ) {
Map<String, Object> values = new HashMap<String, Object>();
String userName = userSelector.getValue();// 会员名称
values.put(IUserAccount.USER, userName);
String account = accountField.getRawValue();// 金额
values.put(IUserAccount.AMOUNT, account);
String payment = paymentType.getItemText(paymentType.getSelectedIndex());// 支付方式
values.put(IUserAccount.PAYMENT, payment);
// 类型
if( save.isChecked() ) {
values.put(IUserAccount.PROCESSTYPE, IUserAccount.TYPE_SAVING);
} else {
values.put(IUserAccount.PROCESSTYPE, IUserAccount.TYPE_DRAWING);
}
values.put(IUserAccount.ADMINNOTE, manager.getRawValue()); // 管理员备注
values.put(IUserAccount.USERNOTE, user.getRawValue()); // 会员描述
// 到款状态
if( notConfirm.isChecked() ) {
values.put(IUserAccount.PAID, false);
} else {
values.put(IUserAccount.PAID, true);
}
// 操作时间
Date currentTime = new Date();
Timestamp nowTime = new Timestamp(currentTime.getTime());
values.put(IUserAccount.ADDTIME, nowTime);
// 管理员
values.put(IUserAccount.ADMINUSER, "admin");
BeanObject applyBean = new BeanObject(ModelNames.USERACCOUNT, values);
new CreateService().createBean(applyBean, new CreateService.Listener() {
@Override
public void onSuccess(String id) {
Info info = new Info();
info.show(new InfoConfig("恭喜", "添加申请成功!"));
MemberApplication.State state = new MemberApplication.State();
state.execute();
AdminLog.createAdminLog("添加充值与体现申请;");
}
});
clear();
} else {
clear();
MemberApplication.State state = new MemberApplication.State();
state.execute();
AdminLog.createAdminLog("确认充值与体现申请;");
}
}
});
btnCancel.addSelectionListener(new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
clear();
}
});
buttonPanel.add(btnOK);
buttonPanel.add(btnCancel);
contentPanel.createPanel(null, null, buttonPanel);
contentPanel.setBorders(true);
return contentPanel;
}
/**
* 初始化界面时,将数据显示
* @param object
*/
// public void setData( BeanObject bean ) {
// this.object = bean;
// isNew = (object != null) ? false : true;
// }
public void refresh() {
BeanObject object = getCurState().getUser();
if (object != null) {
new ReadService().getBean(ModelNames.USER, object.getString(IUserAccount.USER), new ReadService.Listener() {
public synchronized void onSuccess(BeanObject result) {
userSelector.setText(result.getString(IUser.NAME)); // 用户名
}
});
accountField.setRawValue(object.getString(IUserAccount.AMOUNT));
accountField.setEnabled(false); // 金额
Map<String, Integer> paymentTypes = new HashMap<String, Integer>();
paymentTypes.put("银行汇帐/转账", 1);
paymentTypes.put("余额支付", 2);
paymentTypes.put("邮局汇款", 3);
paymentType.setSelectedIndex(paymentTypes.get(object.getString(IUserAccount.PAYMENT)));
paymentType.setEnabled(false);
Integer in = object.get(IUserAccount.PROCESSTYPE);
if( in.intValue() == IUserAccount.TYPE_SAVING ) {
save.setChecked(true);
} else {
take.setChecked(true);
}
save.setEnabled(false);
take.setEnabled(false);
manager.setRawValue(object.getString(IUserAccount.ADMINNOTE));
manager.setEnabled(false);
user.setRawValue(object.getString(IUserAccount.USERNOTE));
user.setEnabled(false);
Boolean isConfirm = object.get(IUserAccount.PAID);
if( isConfirm.booleanValue() ) {
complete.setChecked(true);
} else {
notConfirm.setChecked(true);
}
complete.setEnabled(false);
notConfirm.setEnabled(false);
cancel.setEnabled(false);
} else {
accountField.setEnabled(true);
complete.setEnabled(true);
notConfirm.setEnabled(true);
cancel.setEnabled(true);
paymentType.setEnabled(true);
save.setEnabled(true);
take.setEnabled(true);
user.setEnabled(true);
manager.setEnabled(true);
}
}
private void clear() {
accountField.setRawValue("");
paymentType.setSelectedIndex(0);
manager.setRawValue("");
user.setRawValue("");
userSelector.setText("");
}
}
|
CarlosRoGuerra/rpaas-operator | internal/web/blocks.go | // Copyright 2019 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package web
import (
"fmt"
"net/http"
"strings"
"github.com/labstack/echo/v4"
"github.com/tsuru/rpaas-operator/internal/pkg/rpaas"
)
func deleteBlock(c echo.Context) error {
ctx := c.Request().Context()
manager, err := getManager(ctx)
if err != nil {
return err
}
err = manager.DeleteBlock(ctx, c.Param("instance"), c.Param("block"))
if err != nil {
return err
}
return c.NoContent(http.StatusOK)
}
func listBlocks(c echo.Context) error {
ctx := c.Request().Context()
manager, err := getManager(ctx)
if err != nil {
return err
}
blocks, err := manager.ListBlocks(ctx, c.Param("instance"))
if err != nil {
return err
}
if blocks == nil {
blocks = make([]rpaas.ConfigurationBlock, 0)
}
return c.JSON(http.StatusOK, struct {
Blocks []rpaas.ConfigurationBlock `json:"blocks"`
}{blocks})
}
func updateBlock(c echo.Context) error {
if c.Request().ContentLength == 0 {
return echo.NewHTTPError(http.StatusBadRequest, "Request body can't be empty")
}
ctx := c.Request().Context()
manager, err := getManager(ctx)
if err != nil {
return err
}
var block rpaas.ConfigurationBlock
if err = c.Bind(&block); err != nil {
return err
}
err = manager.UpdateBlock(ctx, c.Param("instance"), block)
if err != nil {
return err
}
return c.NoContent(http.StatusOK)
}
func deleteLuaBlock(c echo.Context) error {
ctx := c.Request().Context()
manager, err := getManager(ctx)
if err != nil {
return err
}
luaBlockType, err := formValue(c.Request(), "lua_module_type")
if err != nil {
return err
}
err = manager.DeleteBlock(ctx, c.Param("instance"), luaBlockName(luaBlockType))
if err != nil {
return err
}
return c.NoContent(http.StatusOK)
}
func listLuaBlocks(c echo.Context) error {
ctx := c.Request().Context()
manager, err := getManager(ctx)
if err != nil {
return err
}
blocks, err := manager.ListBlocks(ctx, c.Param("instance"))
if err != nil {
return err
}
type luaBlock struct {
LuaName string `json:"lua_name"`
Content string `json:"content"`
}
luaBlocks := []luaBlock{}
for _, block := range blocks {
if strings.HasPrefix(block.Name, luaBlockName("")) {
luaBlocks = append(luaBlocks, luaBlock{
LuaName: block.Name,
Content: block.Content,
})
}
}
return c.JSON(http.StatusOK, struct {
Modules []luaBlock `json:"modules"`
}{Modules: luaBlocks})
}
func updateLuaBlock(c echo.Context) error {
ctx := c.Request().Context()
manager, err := getManager(ctx)
if err != nil {
return err
}
in := struct {
LuaModuleType string `form:"lua_module_type"`
Content string `form:"content"`
}{}
if err = c.Bind(&in); err != nil {
return err
}
block := rpaas.ConfigurationBlock{
Name: luaBlockName(in.LuaModuleType),
Content: in.Content,
}
err = manager.UpdateBlock(ctx, c.Param("instance"), block)
if err != nil {
return err
}
return c.NoContent(http.StatusOK)
}
func luaBlockName(blockType string) string {
return fmt.Sprintf("lua-%s", blockType)
}
|
HeartCommunity/uiKit | packages/core/navigation-next/docs/examples/ui-components/GoToItem.js | <gh_stars>1-10
// @flow
import React, { Component } from 'react';
import { colors } from '@findable/theme';
import IssuesIcon from '@findable/icon/glyph/issues';
import { JiraWordmark } from '@findable/logo';
import {
BackItem,
GoToItem,
HeaderSection,
Item,
NavigationProvider,
MenuSection,
SectionHeading,
withNavigationViewController,
ViewController,
Wordmark,
} from '../../../src';
import { CONTENT_NAV_WIDTH } from '../../../src/common/constants';
const SectionWrapper = props => (
<div
css={{
backgroundColor: colors.N20,
marginTop: '8px',
overflow: 'hidden',
position: 'relative',
width: `${CONTENT_NAV_WIDTH}px`,
}}
{...props}
/>
);
const RootMenu = ({ className }: { className: string }) => (
<div className={className}>
<GoToItem
before={IssuesIcon}
goTo="issues"
text="Issues"
testKey="product-item-issues"
/>
</div>
);
const IssuesMenu = ({ className }: { className: string }) => (
<div className={className}>
<BackItem goTo="root" />
<SectionHeading>Issues and filters</SectionHeading>
<Item id="search-issues" text="Search issues" />
</div>
);
const VIEWS = {
root: RootMenu,
issues: IssuesMenu,
};
const Noop = () => null;
class ViewRegistry extends Component<{
navigationViewController: ViewController,
}> {
componentDidMount() {
const { navigationViewController } = this.props;
Object.keys(VIEWS).forEach(viewId => {
navigationViewController.addView({
id: viewId,
type: 'product',
getItems: () => [],
});
});
navigationViewController.setView('root');
}
render() {
return null;
}
}
const ProductNavigation = ({
navigationViewController: {
state: { activeView },
},
}: {
navigationViewController: ViewController,
}) => {
const CurrentMenu = activeView ? VIEWS[activeView.id] : Noop;
const id = (activeView && activeView.id) || undefined;
const parentId =
activeView && activeView.id === 'issues' ? 'root' : undefined;
return (
<SectionWrapper>
<HeaderSection>
{({ className }) => (
<div className={className}>
<Wordmark wordmark={JiraWordmark} />
</div>
)}
</HeaderSection>
<MenuSection id={id} parentId={parentId}>
{CurrentMenu}
</MenuSection>
</SectionWrapper>
);
};
const ConnectedProductNavigation = withNavigationViewController(
ProductNavigation,
);
const ConnectedViewRegistry = withNavigationViewController(ViewRegistry);
export default () => (
<NavigationProvider>
<SectionWrapper>
<ConnectedViewRegistry />
<ConnectedProductNavigation />
</SectionWrapper>
</NavigationProvider>
);
|
helabed/GraphISEP_1 | CConcLoadObject/CConcLoadObject.h | <gh_stars>0
/****
* CConcLoadObject.h
*
* Load object class for a typical CTrussPane class.
*
****/
#define _H_CConcLoadObject /* Include this file only once */
#include <Global.h>
#include "CAbstractObject.h"
#include "TrussCommands.h"
struct CConcLoadObject : CAbstractObject {
/* Instance variables */
Point itsCenterPoint;
Point its1stEnd;
Point its2ndEnd;
Point offSet;
Boolean itsCenterPointFlag;
Boolean its1stEndFlag;
Boolean its2ndEndFlag;
Boolean the2ndEndConnected;
struct CNodeObject *the1stEndNode;
struct CNodeObject *the2ndEndNode;
Boolean the1stEndConnected;
struct CTrussElementObject *itsTElement;
RgnHandle itsRegion;
float LoadCounterMoneyValue;
float LoadCounterDaysValue;
float TElementConnectionRatio;
/* Methods */
void Draw( void );
void UpDateItsRegion( void );
void SelectYourself( void );
void UnSelectYourself( void );
void UpDateObject( void );
void ResizeYourself( void );
Boolean WhichOneOfUsGotSelected( Point aPoint );
void DrawResizingHandles( Point aPoint );
void MoveYourself( void );
void InitializeYourself( void );
void FromtheHitPointToCorners( void );
void FromCornersToItsCenterPoint( void );
void HandleTheArrow( void );
void DoDraw( void );
void DrawFinal( void );
void DoDialogItemsCounter(void);
void DoYourDialog( void );
void Dispose( void );
void PrepareYourselfToBeUpdated( void );
void PrepareYourselfToBeUpdatedByNode( void );
Boolean ConnectYourselfToTE( struct CTrussElementObject
*theTElementObject );
Boolean ConnectYourselfToNode( struct CNodeObject
*theNodeObject );
void DisconnectYourself( void );
void DeleteYourself( void );
};
|
5nefarious/icarous | Modules/ACCoRD/inc/WCV_tvar.h | /*
* Copyright (c) 2015-2017 United States Government as represented by
* the National Aeronautics and Space Administration. No copyright
* is claimed in the United States under Title 17, U.S.Code. All Other
* Rights Reserved.
*/
#ifndef WCV_TVAR_H_
#define WCV_TVAR_H_
#include "Detection3D.h"
#include "Vect3.h"
#include "Velocity.h"
#include "WCVTable.h"
#include "ConflictData.h"
#include "LossData.h"
#include "WCV_Vertical.h"
#include <string>
namespace larcfm {
class WCV_tvar : public Detection3D {
protected:
WCVTable table;
WCV_Vertical* wcv_vertical;
std::string id;
public:
virtual ~WCV_tvar();
/**
* Sets the internal table to be a copy of the supplied one.
**/
void setWCVTable(const WCVTable& tables);
double getDTHR() const;
double getDTHR(const std::string& u) const;
double getZTHR() const;
double getZTHR(const std::string& u) const;
double getTTHR() const;
double getTTHR(const std::string& u) const;
double getTCOA() const;
double getTCOA(const std::string& u) const;
void setDTHR(double val);
void setDTHR(double val, const std::string& u);
void setZTHR(double val);
void setZTHR(double val, const std::string& u);
void setTTHR(double val);
void setTTHR(double val, const std::string& u);
void setTCOA(double val);
void setTCOA(double val, const std::string& u);
virtual double horizontal_tvar(const Vect2& s, const Vect2& v) const = 0;
virtual LossData horizontal_WCV_interval(double T, const Vect2& s, const Vect2& v) const = 0;
bool horizontal_WCV(const Vect2& s, const Vect2& v) const;
bool violation(const Vect3& so, const Velocity& vo, const Vect3& si, const Velocity& vi) const;
bool conflict(const Vect3& so, const Velocity& vo, const Vect3& si, const Velocity& vi, double B, double T) const;
ConflictData conflictDetection(const Vect3& so, const Velocity& vo, const Vect3& si, const Velocity& vi, double B, double T) const;
LossData WCV3D(const Vect3& so, const Velocity& vo, const Vect3& si, const Velocity& vi, double B, double T) const;
LossData WCV_interval(const Vect3& so, const Velocity& vo, const Vect3& si, const Velocity& vi, double B, double T) const;
bool containsTable(WCV_tvar* wcv) const;
virtual std::string toString() const;
virtual std::string toPVS(int prec) const;
ParameterData getParameters() const;
void updateParameterData(ParameterData& p) const;
void setParameters(const ParameterData& p);
virtual Detection3D* copy() const = 0;
virtual Detection3D* make() const = 0;
virtual std::string getSimpleClassName() const = 0;
virtual std::string getSimpleSuperClassName() const {
return "WCV_tvar";
}
virtual std::string getIdentifier() const;
virtual void setIdentifier(const std::string& s);
virtual bool equals(Detection3D* o) const;
};
}
#endif
|
Rtoli-adam/springbootexamples | spring-boot-2.x-restful-api/src/main/java/cn/lijunkui/restful/basic/controller/UserController.java | <reponame>Rtoli-adam/springbootexamples
package cn.lijunkui.restful.basic.controller;
import java.util.ArrayList;
import java.util.List;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.lijunkui.restful.basic.model.User;
/**
* User restful api
*/
@RestController()
@RequestMapping("/user")
public class UserController {
Logger log = LoggerFactory.getLogger(UserController.class);
/**
* 根据用户id 查询用户
* @return
*/
@GetMapping("/{id}")
public ResponseEntity<User> get(@PathVariable(name = "id") Long id){
User user = new User("lijunkui",18);
log.info("查询用户成功:"+"id:{}",id);
return ResponseEntity.ok(user);
}
/**
* 根据用户id 查询所有用户
* @return
*/
@GetMapping("/")
public ResponseEntity<List<User>> getAll(){
List<User> userList = new ArrayList<User>(){{
add(new User("lijunkui1",18));
add(new User("lijunkui2",18));
add(new User("lijunkui3",18));
}};
return ResponseEntity.ok(userList);
}
/**
* 添加用户
*/
@PostMapping("/")
public ResponseEntity<User> add(@RequestBody User user){
log.info("添加用户成功:"+"name:{},age:{}",user.getName(),user.getAge());
return ResponseEntity.status(HttpStatus.CREATED).body(user);
}
/**
* 更新用户
* @param user
* @return
*/
@PutMapping("/")
public ResponseEntity<Void> updatePut(@RequestBody User user){
log.info("修改用户成功:"+"name:{},age:{}",user.getName(),user.getAge());
return ResponseEntity.ok().build();
}
/**
* 局部更新
* @return
*/
@PatchMapping("/{name}")
public ResponseEntity<Void> updatePatch(@PathVariable("name") String name){
log.info("修改用户成功:"+"name:{}",name);
return ResponseEntity.ok().build();
}
/**
* 删除用户
*/
@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable("id") Long id){
log.info("删除用户成功:"+"id:{}",id);
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}
}
|
jjdcabasolo/another-moviedb-rip-off | src/utils/components/Tooltip.js | import React from 'react';
import PropTypes from 'prop-types';
import { Tooltip as MuiTooltip } from '@material-ui/core';
const Tooltip = ({
children,
placement,
title,
visible,
}) => (visible
? (
<MuiTooltip title={title} placement={placement}>
{children}
</MuiTooltip>
)
: children);
Tooltip.propTypes = {
children: PropTypes.node.isRequired,
placement: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
visible: PropTypes.bool.isRequired,
};
export default Tooltip;
|
HerbrichCorporation/ZabellJS | library/simplicity/manager/context-manager.js | import {get, viewManager} from "./view-manager.js";
import MatContextMenu from "../components/modal/mat-context-menu.js";
export const contextManager = new class ContextManager {
openContext(url, options) {
let executor = (resolve, reject) => {
viewManager.load("#" + url).then((view) => {
if (options?.data) {
Object.assign(view, options.data);
}
let configuration = get(view.localName);
let viewPort = document.querySelector("viewport");
let viewPortRect = viewPort.getBoundingClientRect();
let matContextMenu = new MatContextMenu();
matContextMenu.appendChild(view);
matContextMenu.style.top = options.pageY - viewPortRect.top - 2 + "px";
matContextMenu.style.left = options.pageX - viewPortRect.left - 2 + "px";
viewPort.appendChild(matContextMenu);
resolve(matContextMenu);
});
}
return new Promise(executor);
}
} |
ut-osa/syncchar | linux-2.6.16-unmod/include/asm-arm/arch-at91rm9200/at91rm9200_usart.h | /*
* include/asm-arm/arch-at91rm9200/at91rm9200_usart.h
*
* Copyright (C) 2005 <NAME>
* Copyright (C) <NAME>
*
* USART registers.
* Based on AT91RM9200 datasheet revision E.
*
* 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; either version 2 of the License, or
* (at your option) any later version.
*/
#ifndef AT91RM9200_USART_H
#define AT91RM9200_USART_H
#define AT91_US_CR 0x00 /* Control Register */
#define AT91_US_RSTRX (1 << 2) /* Reset Receiver */
#define AT91_US_RSTTX (1 << 3) /* Reset Transmitter */
#define AT91_US_RXEN (1 << 4) /* Receiver Enable */
#define AT91_US_RXDIS (1 << 5) /* Receiver Disable */
#define AT91_US_TXEN (1 << 6) /* Transmitter Enable */
#define AT91_US_TXDIS (1 << 7) /* Transmitter Disable */
#define AT91_US_RSTSTA (1 << 8) /* Reset Status Bits */
#define AT91_US_STTBRK (1 << 9) /* Start Break */
#define AT91_US_STPBRK (1 << 10) /* Stop Break */
#define AT91_US_STTTO (1 << 11) /* Start Time-out */
#define AT91_US_SENDA (1 << 12) /* Send Address */
#define AT91_US_RSTIT (1 << 13) /* Reset Iterations */
#define AT91_US_RSTNACK (1 << 14) /* Reset Non Acknowledge */
#define AT91_US_RETTO (1 << 15) /* Rearm Time-out */
#define AT91_US_DTREN (1 << 16) /* Data Terminal Ready Enable */
#define AT91_US_DTRDIS (1 << 17) /* Data Terminal Ready Disable */
#define AT91_US_RTSEN (1 << 18) /* Request To Send Enable */
#define AT91_US_RTSDIS (1 << 19) /* Request To Send Disable */
#define AT91_US_MR 0x04 /* Mode Register */
#define AT91_US_USMODE (0xf << 0) /* Mode of the USART */
#define AT91_US_USMODE_NORMAL 0
#define AT91_US_USMODE_RS485 1
#define AT91_US_USMODE_HWHS 2
#define AT91_US_USMODE_MODEM 3
#define AT91_US_USMODE_ISO7816_T0 4
#define AT91_US_USMODE_ISO7816_T1 6
#define AT91_US_USMODE_IRDA 8
#define AT91_US_USCLKS (3 << 4) /* Clock Selection */
#define AT91_US_CHRL (3 << 6) /* Character Length */
#define AT91_US_CHRL_5 (0 << 6)
#define AT91_US_CHRL_6 (1 << 6)
#define AT91_US_CHRL_7 (2 << 6)
#define AT91_US_CHRL_8 (3 << 6)
#define AT91_US_SYNC (1 << 8) /* Synchronous Mode Select */
#define AT91_US_PAR (7 << 9) /* Parity Type */
#define AT91_US_PAR_EVEN (0 << 9)
#define AT91_US_PAR_ODD (1 << 9)
#define AT91_US_PAR_SPACE (2 << 9)
#define AT91_US_PAR_MARK (3 << 9)
#define AT91_US_PAR_NONE (4 << 9)
#define AT91_US_PAR_MULTI_DROP (6 << 9)
#define AT91_US_NBSTOP (3 << 12) /* Number of Stop Bits */
#define AT91_US_NBSTOP_1 (0 << 12)
#define AT91_US_NBSTOP_1_5 (1 << 12)
#define AT91_US_NBSTOP_2 (2 << 12)
#define AT91_US_CHMODE (3 << 14) /* Channel Mode */
#define AT91_US_CHMODE_NORMAL (0 << 14)
#define AT91_US_CHMODE_ECHO (1 << 14)
#define AT91_US_CHMODE_LOC_LOOP (2 << 14)
#define AT91_US_CHMODE_REM_LOOP (3 << 14)
#define AT91_US_MSBF (1 << 16) /* Bit Order */
#define AT91_US_MODE9 (1 << 17) /* 9-bit Character Length */
#define AT91_US_CLKO (1 << 18) /* Clock Output Select */
#define AT91_US_OVER (1 << 19) /* Oversampling Mode */
#define AT91_US_INACK (1 << 20) /* Inhibit Non Acknowledge */
#define AT91_US_DSNACK (1 << 21) /* Disable Successive NACK */
#define AT91_US_MAX_ITER (7 << 24) /* Max Iterations */
#define AT91_US_FILTER (1 << 28) /* Infrared Receive Line Filter */
#define AT91_US_IER 0x08 /* Interrupt Enable Register */
#define AT91_US_RXRDY (1 << 0) /* Receiver Ready */
#define AT91_US_TXRDY (1 << 1) /* Transmitter Ready */
#define AT91_US_RXBRK (1 << 2) /* Break Received / End of Break */
#define AT91_US_ENDRX (1 << 3) /* End of Receiver Transfer */
#define AT91_US_ENDTX (1 << 4) /* End of Transmitter Transfer */
#define AT91_US_OVRE (1 << 5) /* Overrun Error */
#define AT91_US_FRAME (1 << 6) /* Framing Error */
#define AT91_US_PARE (1 << 7) /* Parity Error */
#define AT91_US_TIMEOUT (1 << 8) /* Receiver Time-out */
#define AT91_US_TXEMPTY (1 << 9) /* Transmitter Empty */
#define AT91_US_ITERATION (1 << 10) /* Max number of Repetitions Reached */
#define AT91_US_TXBUFE (1 << 11) /* Transmission Buffer Empty */
#define AT91_US_RXBUFF (1 << 12) /* Reception Buffer Full */
#define AT91_US_NACK (1 << 13) /* Non Acknowledge */
#define AT91_US_RIIC (1 << 16) /* Ring Indicator Input Change */
#define AT91_US_DSRIC (1 << 17) /* Data Set Ready Input Change */
#define AT91_US_DCDIC (1 << 18) /* Data Carrier Detect Input Change */
#define AT91_US_CTSIC (1 << 19) /* Clear to Send Input Change */
#define AT91_US_RI (1 << 20) /* RI */
#define AT91_US_DSR (1 << 21) /* DSR */
#define AT91_US_DCD (1 << 22) /* DCD */
#define AT91_US_CTS (1 << 23) /* CTS */
#define AT91_US_IDR 0x0c /* Interrupt Disable Register */
#define AT91_US_IMR 0x10 /* Interrupt Mask Register */
#define AT91_US_CSR 0x14 /* Channel Status Register */
#define AT91_US_RHR 0x18 /* Receiver Holding Register */
#define AT91_US_THR 0x1c /* Transmitter Holding Register */
#define AT91_US_BRGR 0x20 /* Baud Rate Generator Register */
#define AT91_US_CD (0xffff << 0) /* Clock Divider */
#define AT91_US_RTOR 0x24 /* Receiver Time-out Register */
#define AT91_US_TO (0xffff << 0) /* Time-out Value */
#define AT91_US_TTGR 0x28 /* Transmitter Timeguard Register */
#define AT91_US_TG (0xff << 0) /* Timeguard Value */
#define AT91_US_FIDI 0x40 /* FI DI Ratio Register */
#define AT91_US_NER 0x44 /* Number of Errors Register */
#define AT91_US_IF 0x4c /* IrDA Filter Register */
#endif
|
uk-gov-mirror/hmcts.fpl-ccd-configuration | service/src/main/java/uk/gov/hmcts/reform/fpl/model/notify/payment/FailedPBANotificationData.java | <filename>service/src/main/java/uk/gov/hmcts/reform/fpl/model/notify/payment/FailedPBANotificationData.java<gh_stars>0
package uk.gov.hmcts.reform.fpl.model.notify.payment;
import lombok.Builder;
import lombok.Data;
import uk.gov.hmcts.reform.fpl.model.notify.NotifyData;
@Data
@Builder
public class FailedPBANotificationData implements NotifyData {
private String caseUrl;
private String applicationType;
}
|
haseeAmarathunga/canner | src/hocs/components/pagination.js | // @flow
import React, {Component, Fragment} from 'react';
import {Button, Icon} from 'antd';
import styled from 'styled-components';
const ButtonGroup = Button.Group;
const Wrapper = styled.div`
text-align: right;
margin-top: ${props => props.marginTop}px;
`;
type Props = {
nextPage: () => void,
prevPage: () => void,
hasNextPage: boolean,
hasPreviousPage: boolean,
changeSize: (size: number) => void,
size: number
}
export default class PaginationPlugin extends Component<Props> {
render() {
const {nextPage, prevPage, hasNextPage, hasPreviousPage} = this.props;
return <Fragment>
<Wrapper>
<ButtonGroup>
<Button disabled={!hasPreviousPage} onClick={prevPage}>
<Icon type="left" />
Previous
</Button>
<Button disabled={!hasNextPage} onClick={nextPage}>
Next
<Icon type="right" />
</Button>
</ButtonGroup>
</Wrapper>
{/*
FIX
*/}
{/* <Wrapper marginTop={16}>
<span>Page size: </span>
<Select style={{width: 150}} onChange={changeSize} defaultValue={10}>
<Option value={1}>1</Option>
<Option value={10}>10</Option>
<Option value={20}>20</Option>
<Option value={50}>50</Option>
<Option value={100}>100</Option>
</Select>
</Wrapper> */}
</Fragment>;
}
}
|
fluorumlabs/disconnect-project | disconnect-classlib/src/main/java/js/web/permissions/PermissionDescriptor.java | <gh_stars>1-10
package js.web.permissions;
import js.lang.Any;
import org.teavm.jso.JSProperty;
public interface PermissionDescriptor extends Any {
@JSProperty
PermissionName getName();
@JSProperty
void setName(PermissionName device);
}
|
freitassp/Java | Heranca/src/principal/Principal.java | <gh_stars>0
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package principal;
/**
*
* @author Samuel
*/
public class Principal {
public static void main(String[] args) {
Animal meuGato = new Gato();
meuGato.som();
}
}
|
code-review-doctor/lite-frontend-1 | unit_tests/exporter/applications/views/test_goods.py | import pytest
from exporter.applications.views import goods
def test_is_firearm_certificate_needed_has_section_five_certificate():
actual = goods.is_firearm_certificate_needed(
application={
"organisation": {"documents": [{"document_type": "section-five-certificate", "is_expired": False}]}
},
selected_section="firearms_act_section5",
)
assert actual is False
def test_is_firearm_certificate_needed_no_section_five_certificate():
actual = goods.is_firearm_certificate_needed(
application={"organisation": {"documents": []}}, selected_section="firearms_act_section5"
)
assert actual is True
def test_is_firearm_certificate_needed_not_section_five_selected():
actual = goods.is_firearm_certificate_needed(
application={
"organisation": {"documents": [{"document_type": "section-five-certificate", "is_expired": False}]}
},
selected_section="firearms_act_section2",
)
assert actual is True
@pytest.mark.parametrize(
"expiry_date,error",
(
("2020-01-01", ["Expiry date must be in the future"]), # Past
("2050-01-01", ["Expiry date is too far in the future"]), # Too far in the future
),
)
def test_upload_firearm_registered_dealer_certificate_error(authorized_client, expiry_date, error):
# How do I write this?
pass
@pytest.mark.parametrize(
"expiry_date,error",
(
("2020-01-01", ["Expiry date must be in the future"]), # Past
("2050-01-01", ["Expiry date is too far in the future"]), # Too far in the future
),
)
def test_upload_firearm_section_five_certificate_error(authorized_client, expiry_date, error):
# How do I write this?
pass
|
Deng11Sc/publicManager | Category/UIView/UIView+Configure.h | //
// UIView+Configure.h
// MerryS
//
// Created by SongChang on 2018/1/8.
// Copyright © 2018年 SongChang. All rights reserved.
//
#import <UIKit/UIKit.h>
///初始化UIView
@interface UIView (Configure)
-(void)cc_configure;
@end
///初始化Label
@interface UILabel (Configure)
-(void)cc_configure;
@end
///初始化UIButton
@interface UIButton (Configure)
-(void)cc_configure;
@end
///初始化UIImage
@interface UIImage (Configure)
-(void)cc_configure;
@end
///初始化UIImage
@interface UITextField (Configure)
-(void)cc_configure;
@end
|
humboldtux-tmp/buildingapis | exercises/11-alternative-mux/gorilla/helper_test.go | package main
import (
"testing"
"time"
)
func TestCourseValidation(t *testing.T) {
// table driven tests are awesome
// use them every chance you get
// to save typing!
tests := []struct {
Course Course
Valid bool
}{
{Course: Course{
ID: 1,
Name: "<NAME>",
Location: "Denver",
StartTime: time.Now(),
EndTime: time.Now(),
}, Valid: true},
{Course: Course{
ID: 2,
Name: "My", // min length
Location: "Denver",
StartTime: time.Now(),
EndTime: time.Now(),
}, Valid: false},
{Course: Course{ // missing name
ID: 2,
Location: "Denver",
StartTime: time.Now(),
EndTime: time.Now(),
}, Valid: false},
{Course: Course{ // missing location
ID: 2,
Name: "My Course",
StartTime: time.Now(),
EndTime: time.Now(),
}, Valid: false},
{Course: Course{ // missing start time
ID: 2,
Name: "My Course",
Location: "Denver",
EndTime: time.Now(),
}, Valid: false},
{Course: Course{ // missing end time
ID: 1,
Name: "My Course",
Location: "Denver",
StartTime: time.Now(),
}, Valid: false},
}
for _, ct := range tests {
err := validateCourse(&ct.Course)
if !ct.Valid && err == nil {
t.Errorf("Expected Validation Error")
}
}
}
|
openbudgets/os-viewer | app/front/scripts/directives/visualizations/controls/breadcrumbs/index.js | <reponame>openbudgets/os-viewer
'use strict';
var ngModule = require('../../../../module');
ngModule.directive('breadcrumbs', [
'Configuration',
function(Configuration) {
return {
template: require('./template.html'),
replace: true,
restrict: 'E',
scope: {
breadcrumbs: '='
},
link: function($scope) {
$scope.breadcrumbClick = function(breadcrumb) {
$scope.$emit(Configuration.events.visualizations.breadcrumbClick,
breadcrumb);
};
}
};
}
]);
|
ketnipz/property-tycoon | src/tycoon/ui/ui.js | /**
* @namespace UI
*/ |
brauli0/social-blockly | backend/src/main/java/es/udc/paproject/backend/model/services/CommentServiceImpl.java | <gh_stars>0
package es.udc.paproject.backend.model.services;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import es.udc.paproject.backend.model.common.exceptions.InstanceNotFoundException;
import es.udc.paproject.backend.model.entities.Comment;
import es.udc.paproject.backend.model.entities.CommentDao;
import es.udc.paproject.backend.model.entities.CommentDaoImpl;
import es.udc.paproject.backend.model.entities.Program;
import es.udc.paproject.backend.model.entities.ProgramDao;
import es.udc.paproject.backend.model.entities.User;
import es.udc.paproject.backend.model.entities.UserDao;
@Service
@Transactional
public class CommentServiceImpl implements CommentService {
@Autowired
private UserDao userDao;
@Autowired
private ProgramDao programDao;
@Autowired
private CommentDao commentDao;
@Autowired
private CommentDaoImpl commentDaoImpl;
@Override
public Comment createComment(Long userId, Long programId, String commentText)
throws InstanceNotFoundException {
Optional<User> opUser = userDao.findById(userId);
if (!opUser.isPresent()) {
throw new InstanceNotFoundException("project.entities.user", userId);
}
User user = opUser.get();
Optional<Program> opProgram = programDao.findById(programId);
if (!opProgram.isPresent()) {
throw new InstanceNotFoundException("project.entities.program", programId);
}
Program program = opProgram.get();
Comment comment = new Comment(user, program, commentText);
return commentDao.save(comment);
}
@Override
public Comment replyComment(Long commentOrigId, Long userId, Long programId, String commentText)
throws InstanceNotFoundException {
Optional<User> opUser = userDao.findById(userId);
if (!opUser.isPresent()) {
throw new InstanceNotFoundException("project.entities.user", userId);
}
User user = opUser.get();
Optional<Program> opProgram = programDao.findById(programId);
if (!opProgram.isPresent()) {
throw new InstanceNotFoundException("project.entities.program", programId);
}
Program program = opProgram.get();
Optional<Comment> opComment = commentDao.findById(commentOrigId);
if (!opComment.isPresent()) {
throw new InstanceNotFoundException("project.entities.comment", commentOrigId);
}
Comment comment = new Comment(commentOrigId, user, program, commentText);
return commentDao.save(comment);
}
@Override
public void deleteComment(Long commentId) throws InstanceNotFoundException {
Optional<Comment> comment = commentDao.findById(commentId);
if (comment.isPresent())
commentDao.delete(comment.get());
else
throw new InstanceNotFoundException("project.entities.comment", commentId);
}
@Override
public List<Comment> getCommentsByProgram(Long programId) throws InstanceNotFoundException {
Optional<Program> opProgram = programDao.findById(programId);
if (!opProgram.isPresent()) {
throw new InstanceNotFoundException("project.entities.program", programId);
}
return commentDaoImpl.getCommentsByProgram(programId);
}
@Override
public List<Comment> getCommentReplies(Long commentId) throws InstanceNotFoundException {
Optional<Comment> opComment= commentDao.findById(commentId);
if (!opComment.isPresent()) {
throw new InstanceNotFoundException("project.entities.comment", commentId);
}
return commentDaoImpl.getCommentReplies(commentId);
}
@Override
public Comment getComment(Long commentId) throws InstanceNotFoundException {
Optional<Comment> opComment = commentDao.findById(commentId);
if (!opComment.isPresent()) {
throw new InstanceNotFoundException("project.entities.program", commentId);
}
return opComment.get();
}
}
|
tdprogramming/xfltools | bin/js-debug/org/apache/royale/html/Button.js | /**
* Generated by Apache Royale Compiler from org\apache\royale\html\Button.as
* org.apache.royale.html.Button
*
* @fileoverview
*
* @suppress {missingRequire|checkTypes|accessControls}
*/
goog.provide('org.apache.royale.html.Button');
/* Royale Dependency List: org.apache.royale.core.WrappedHTMLElement*/
goog.require('org.apache.royale.html.ButtonBase');
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion Royale 0.0
* @constructor
* @extends {org.apache.royale.html.ButtonBase}
*/
org.apache.royale.html.Button = function() {
org.apache.royale.html.Button.base(this, 'constructor');
};
goog.inherits(org.apache.royale.html.Button, org.apache.royale.html.ButtonBase);
/**
* Prevent renaming of class. Needed for reflection.
*/
goog.exportSymbol('org.apache.royale.html.Button', org.apache.royale.html.Button);
/**
* @asprivate
* @protected
* @override
*/
org.apache.royale.html.Button.prototype.createElement = function() {
org.apache.royale.html.Button.superClass_.createElement.apply(this);
this.typeNames = "Button";
return this.element;
};
/**
* Metadata
*
* @type {Object.<string, Array.<Object>>}
*/
org.apache.royale.html.Button.prototype.ROYALE_CLASS_INFO = { names: [{ name: 'Button', qName: 'org.apache.royale.html.Button', kind: 'class' }] };
/**
* Reflection
*
* @return {Object.<string, Function>}
*/
org.apache.royale.html.Button.prototype.ROYALE_REFLECTION_INFO = function () {
return {
variables: function () {return {};},
accessors: function () {return {};},
methods: function () {
return {
'Button': { type: '', declaredBy: 'org.apache.royale.html.Button'}
};
},
metadata: function () { return [ ]; }
};
};
|
implydata/jackson-databind | src/main/java/com/fasterxml/jackson/databind/type/SimpleType.java | <filename>src/main/java/com/fasterxml/jackson/databind/type/SimpleType.java
package com.fasterxml.jackson.databind.type;
import com.fasterxml.jackson.databind.JavaType;
/**
* Simple types are defined as anything other than one of recognized
* container types (arrays, Collections, Maps). For our needs we
* need not know anything further, since we have no way of dealing
* with generic types other than Collections and Maps.
*/
public class SimpleType // note: until 2.6 was final
extends TypeBase
{
private static final long serialVersionUID = 1L;
/*
/**********************************************************
/* Life-cycle
/**********************************************************
*/
/**
* Constructor only used by core Jackson databind functionality;
* should never be called by application code.
*<p>
* As with other direct construction that by-passes {@link TypeFactory},
* no introspection occurs with respect to super-types; caller must be
* aware of consequences if using this method.
*/
protected SimpleType(Class<?> cls) {
this(cls, TypeBindings.emptyBindings(), null, null);
}
protected SimpleType(Class<?> cls, TypeBindings bindings,
JavaType superClass, JavaType[] superInts) {
this(cls, bindings, superClass, superInts, null, null, false);
}
/**
* Simple copy-constructor, usually used when upgrading/refining a simple type
* into more specialized type.
*/
protected SimpleType(TypeBase base) {
super(base);
}
protected SimpleType(Class<?> cls, TypeBindings bindings,
JavaType superClass, JavaType[] superInts,
Object valueHandler, Object typeHandler, boolean asStatic)
{
super(cls, bindings, superClass, superInts,
0, valueHandler, typeHandler, asStatic);
}
/**
* Pass-through constructor used by {@link ReferenceType}.
*
* @since 2.6
*/
protected SimpleType(Class<?> cls, TypeBindings bindings,
JavaType superClass, JavaType[] superInts, int extraHash,
Object valueHandler, Object typeHandler, boolean asStatic)
{
super(cls, bindings, superClass, superInts,
extraHash, valueHandler, typeHandler, asStatic);
}
/**
* Method used by core Jackson classes: NOT to be used by application code:
* it does NOT properly handle inspection of super-types, so neither parent
* Classes nor implemented Interfaces are accessible with resulting type
* instance.
*<p>
* NOTE: public only because it is called by <code>ObjectMapper</code> which is
* not in same package
*/
public static SimpleType constructUnsafe(Class<?> raw) {
return new SimpleType(raw, null,
// 18-Oct-2015, tatu: Should be ok to omit possible super-types, right?
null, null, null, null, false);
}
/*
* Method that should NOT to be used by application code:
* it does NOT properly handle inspection of super-types, so neither parent
* Classes nor implemented Interfaces are accessible with resulting type
* instance. Instead, please use {@link TypeFactory}'s <code>constructType</code>
* methods which handle introspection appropriately.
*<p>
* Note that prior to 2.7, method usage was not limited and would typically
* have worked acceptably: the problem comes from inability to resolve super-type
* information, for which {@link TypeFactory} is needed.
*
@Deprecated
public static SimpleType construct(Class<?> cls)
{
// Let's add sanity checks, just to ensure no
// Map/Collection entries are constructed
if (Map.class.isAssignableFrom(cls)) {
throw new IllegalArgumentException("Cannot construct SimpleType for a Map (class: "+cls.getName()+")");
}
if (Collection.class.isAssignableFrom(cls)) {
throw new IllegalArgumentException("Cannot construct SimpleType for a Collection (class: "+cls.getName()+")");
}
// ... and while we are at it, not array types either
if (cls.isArray()) {
throw new IllegalArgumentException("Cannot construct SimpleType for an array (class: "+cls.getName()+")");
}
TypeBindings b = TypeBindings.emptyBindings();
return new SimpleType(cls, b,
_buildSuperClass(cls.getSuperclass(), b), null, null, null, false);
}
*/
@Override
public JavaType withContentType(JavaType contentType) {
throw new IllegalArgumentException("Simple types have no content types; cannot call withContentType()");
}
@Override
public SimpleType withTypeHandler(Object h) {
if (_typeHandler == h) {
return this;
}
return new SimpleType(_class, _bindings, _superClass, _superInterfaces, _valueHandler, h, _asStatic);
}
@Override
public JavaType withContentTypeHandler(Object h) {
// no content type, so:
throw new IllegalArgumentException("Simple types have no content types; cannot call withContenTypeHandler()");
}
@Override
public SimpleType withValueHandler(Object h) {
if (h == _valueHandler) {
return this;
}
return new SimpleType(_class, _bindings, _superClass, _superInterfaces, h, _typeHandler, _asStatic);
}
@Override
public SimpleType withContentValueHandler(Object h) {
// no content type, so:
throw new IllegalArgumentException("Simple types have no content types; cannot call withContenValueHandler()");
}
@Override
public SimpleType withStaticTyping() {
return _asStatic ? this : new SimpleType(_class, _bindings,
_superClass, _superInterfaces, _valueHandler, _typeHandler, true);
}
@Override
public JavaType refine(Class<?> rawType, TypeBindings bindings,
JavaType superClass, JavaType[] superInterfaces) {
// SimpleType means something not-specialized, so:
return null;
}
@Override
protected String buildCanonicalName()
{
StringBuilder sb = new StringBuilder();
sb.append(_class.getName());
final int count = _bindings.size();
if (count > 0) {
sb.append('<');
for (int i = 0; i < count; ++i) {
JavaType t = containedType(i);
if (i > 0) {
sb.append(',');
}
sb.append(t.toCanonical());
}
sb.append('>');
}
return sb.toString();
}
/*
/**********************************************************
/* Public API
/**********************************************************
*/
@Override
public boolean isContainerType() { return false; }
@Override
public boolean hasContentType() { return false; }
@Override
public StringBuilder getErasedSignature(StringBuilder sb) {
return _classSignature(_class, sb, true);
}
@Override
public StringBuilder getGenericSignature(StringBuilder sb)
{
_classSignature(_class, sb, false);
final int count = _bindings.size();
if (count > 0) {
sb.append('<');
for (int i = 0; i < count; ++i) {
sb = containedType(i).getGenericSignature(sb);
}
sb.append('>');
}
sb.append(';');
return sb;
}
/*
/**********************************************************
/* Standard methods
/**********************************************************
*/
@Override
public String toString()
{
StringBuilder sb = new StringBuilder(40);
sb.append("[simple type, class ").append(buildCanonicalName()).append(']');
return sb.toString();
}
@Override
public boolean equals(Object o)
{
if (o == this) return true;
if (o == null) return false;
if (o.getClass() != getClass()) return false;
SimpleType other = (SimpleType) o;
// Classes must be identical...
if (other._class != this._class) return false;
// And finally, generic bindings, if any
TypeBindings b1 = _bindings;
TypeBindings b2 = other._bindings;
return b1.equals(b2);
}
}
|
fossabot/jymfony | src/Component/VarExporter/fixtures/exported/wakeup.js | (() => {
let o;
return Jymfony.Component.VarExporter.Internal.Hydrator.hydrate(
o = [
(new ReflectionClass("Jymfony.Component.VarExporter.Fixtures.MyWakeup")).newInstanceWithoutConstructor(),
(new ReflectionClass("Jymfony.Component.VarExporter.Fixtures.MyWakeup")).newInstanceWithoutConstructor()
],
null,
{
"Jymfony.Component.VarExporter.Fixtures.MyWakeup": {
["sub"]: {
["0"]: o[1],
["1"]: 123,
},
["baz"]: {
["1"]: 123,
},
},
},
o[0],
[
1,
0,
]
);
})();
|
ducanhnguyen/cft4cpp-for-dummy | data-test/ducanh/coreutils-8.24/lib/faccessat.c | <reponame>ducanhnguyen/cft4cpp-for-dummy<gh_stars>0
/* Check the access rights of a file relative to an open directory.
Copyright (C) 2009-2015 Free Software Foundation, Inc.
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; 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* written by <NAME> */
#include <config.h>
#include <unistd.h>
#include <fcntl.h>
#ifndef HAVE_ACCESS
/* Mingw lacks access, but it also lacks real vs. effective ids, so
the gnulib euidaccess module is good enough. */
# undef access
# define access euidaccess
#endif
/* Invoke access or euidaccess on file, FILE, using mode MODE, in the directory
open on descriptor FD. If possible, do it without changing the
working directory. Otherwise, resort to using save_cwd/fchdir, then
(access|euidaccess)/restore_cwd. If either the save_cwd or the
restore_cwd fails, then give a diagnostic and exit nonzero.
Note that this implementation only supports AT_EACCESS, although some
native versions also support AT_SYMLINK_NOFOLLOW. */
#define AT_FUNC_NAME faccessat
#define AT_FUNC_F1 euidaccess
#define AT_FUNC_F2 access
#define AT_FUNC_USE_F1_COND AT_EACCESS
#define AT_FUNC_POST_FILE_PARAM_DECLS , int mode, int flag
#define AT_FUNC_POST_FILE_ARGS , mode
#include "at-func.c"
|
nfco/netforce | netforce_mfg/netforce_mfg/models/report_production_order.py | # Copyright (c) 2012-2015 Netforce Co. Ltd.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
# OR OTHER DEALINGS IN THE SOFTWARE.
from netforce.model import Model, fields, get_model
from netforce.database import get_connection
from dateutil.relativedelta import *
from datetime import *
class ReportProductionOrder(Model):
_name = "report.production.order"
_transient = True
_fields = {
"date_from": fields.Date("Order Date From"),
"date_to": fields.Date("Order Date To"),
"product_id": fields.Many2One("product", "Product"),
"state": fields.Selection([["draft", "Draft"], ["waiting_confirm", "Waiting Confirmation"], ["waiting_suborder", "Waiting Suborder"], ["waiting_material", "Waiting Material"], ["ready", "Ready To Start"], ["in_progress", "In Progress"], ["done", "Completed"], ["voided", "Voided"], ["split", "Split"]], "Status"),
"production_order": fields.Many2One("production.order", "Production Order"),
"production_location_id": fields.Many2One("stock.location", "Production Location"),
"sale_order": fields.Char("Sales Order"),
}
def default_get(self, field_names=None, context={}, **kw):
defaults = context.get("defaults", {})
date_from = defaults.get("date_from")
date_to = defaults.get("date_to")
if not date_from and not date_to:
date_from = date.today().strftime("%Y-%m-01")
date_to = (date.today() + relativedelta(day=31)).strftime("%Y-%m-%d")
elif not date_from and date_to:
date_from = get_model("settings").get_fiscal_year_start(date=date_to)
return {
"date_from": date_from,
"date_to": date_to,
}
def get_report_data(self, ids, context={}):
if ids:
params = self.read(ids, load_m2o=False)[0]
else:
params = self.default_get(load_m2o=False, context=context)
condition = []
if params.get("date_from"):
date_from = params.get("date_from") + " 00:00:00"
condition.append(["order_date", ">=", date_from])
if params.get("date_to"):
date_to = params.get("date_to") + " 23:59:59"
condition.append(["order_date", "<=", date_to])
if params.get("product_id"):
condition.append(["product_id", "=", params.get("product_id")])
if params.get("production_location_id"):
condition.append(["production_location_id", "=", params.get("production_location_id")])
if params.get("state"):
condition.append(["state", "=", params.get("state")])
prod_order_list = get_model("production.order").search_browse(condition)
lines = []
item_no = 0
status_map = {
"draft": "Draft",
"waiting_confirm": "Waiting Confirmation",
"waiting_suborder": "Waiting Suborder",
"waiting_material": "Waiting Material",
"ready": "Ready To Start",
"in_progress": "In Progress",
"done": "Complete",
"voided": "Voided",
}
for prod_order in prod_order_list:
item_no += 1
line = self.get_line_data(context={"prod_order": prod_order})
line["state"] = status_map[line["state"]] if line["state"] in status_map else line["state"]
line["_item_no"] = item_no
lines.append(line)
return {"lines": lines}
def get_line_data(self, context={}):
prod_order = context["prod_order"]
return {
"number": prod_order.number,
"order_date": prod_order.order_date,
"sale_order_number": prod_order.sale_id.number,
"product_code": prod_order.product_id.code,
"product_name": prod_order.product_id.name,
"production_location": prod_order.production_location_id.name,
"qty_planned": prod_order.qty_planned,
"qty_received": prod_order.qty_received,
"uom": prod_order.product_id.uom_id.name,
"time_start": prod_order.time_start,
"time_stop": prod_order.time_stop,
"duration": prod_order.duration,
"state": prod_order.state,
}
ReportProductionOrder.register()
|
slachiewicz/lightwave | vmafd/vmauthsvc/include/vmauthsvcerrorcode.h | <reponame>slachiewicz/lightwave
/*
* Copyright © 2012-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
/*
* Module Name: VMAUTHSVC
*
* Filename: vmauthsvcerrorcode.h
*
* Abstract:
*
* Common error code map
*
*/
#ifndef __VMAUTHSVCERRORCODE_H__
#define __VMAUTHSVCERRORCODE_H__
#ifdef __cplusplus
extern "C" {
#endif
/*
* <asm-generic/errno-base.h>
* <asm-generic/errno.h>
*/
#define ERROR_OPERATION_NOT_PERMITTED EPERM // 1
#define ERROR_NO_SUCH_FILE_OR_DIRECTORY ENOENT // 2
#define ERROR_NO_SUCH_PROCESS ESRCH // 3
#define ERROR_INT_SYSTEM_CALL EINTR // 4
#define ERROR_IO EIO // 5
#define ERROR_NO_SUCH_DEVICE_OR_ADDR ENXIO // 6
#define ERROR_ARG_LIST_TOO_LONG E2BIG // 7
#define ERROR_EXEC_FORMT ENOEXEC // 8
#define ERROR_BAD_FILE_NUMUMBER EBADF // 9
#define ERROR_NO_CHILD_PROCESS ECHILD // 10
#define ERROR_TRY_AGAIN EAGIN // 11
#define ERROR_NO_MEMORY ENOMEM // 12
// #define ERROR_ACCESS_DENIED EACCES // 13
#define ERROR_RESOURCE_BUSY EBUSY // 16
// // #define ERROR_FILE_EXISTS EEXIST // 17
#define ERROR_NO_SUCH_DEVICE ENODEV // 19
#define ERROR_NOT_A_DIRECTORY ENOTDIR // 20
#define ERROR_IS_A_DIRECTORY EISDIR // 21
// #define ERROR_INVALID_PARAMETER EINVAL // 22
// #define ERROR_FILE_TOO_LARGE EFBIG // 27
#define ERROR_NO_SPACE ENOSPC // 28
#define ERROR_ILLEGAL_SEEK ESPIPE // 29
#define ERROR_READ_ONLY_FILESYSTEM EROFS // 30
// #define ERROR_BROKEN_PIPE EPIPE // 32
#define ERROR_OUT_OF_RANGE ERANGE // 34
#define ERROR_DEADL_LOCK EDEADLK // 35
#define ERROR_NAME_TOO_LONG ENAMETOOLONG // 36
#define ERROR_NO_DATA_AVAILABLE ENODATA // 61
#define ERROR_TIME_EXPIRED ETIME // 62
// #define ERROR_NO_NETWORK ENONET // 64
#define ERROR_COMMUNICATION ECOMM // 70
#define ERROR_PROTOCOL EPROTO // 71
#define ERROR_VALUE_OVERFLOW EOVERFLOW // 75
#define ERROR_NAME_NOT_UNIQUE ENOTUNIQ // 76
#define ERROR_BAD_FILE_DESCRIPTOR EBADFD // 77
/*
* vmauthsvc defined error code
*/
#define VMAUTHSVC_RANGE(n,x,y) (((x) <= (n)) && ((n) <= (y)))
// generic error (range 1000 - 1999)
#define ERROR_INVALID_CONFIGURATION 1000
#define ERROR_DATA_CONSTRAIN_VIOLATION 1001
#define ERROR_OPERATION_INTERRUPT 1002
// object sid generation
#define ERROR_ORG_LIMIT_EXCEEDED 1003
#define ERROR_RID_LIMIT_EXCEEDED 1004
#define ERROR_ORG_ID_GEN_FAILED 1005
#define ERROR_NO_OBJECT_SID_GEN 1006
// ACL/SD
#define ERROR_NO_SECURITY_DESCRIPTOR 1007
#define ERROR_NO_OBJECTSID_ATTR 1008
#define ERROR_TOKEN_IN_USE 1009
#define ERROR_NO_MYSELF 1010
#define ERROR_BAD_ATTRIBUTE_DATA 1011
#define ERROR_PASSWORD_TOO_LONG 1012
#ifdef __cplusplus
}
#endif
#endif /* __VMAUTHSVCERRORCODE_H__ */
|
ivkalgin/openvino | src/bindings/python/src/pyopenvino/frontend/extensions.cpp | // Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <pybind11/functional.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>
#include "extension/json_config.hpp"
#include "manager.hpp"
#include "openvino/frontend/exception.hpp"
#include "openvino/frontend/extension/decoder_transformation.hpp"
#include "openvino/frontend/extension/progress_reporter_extension.hpp"
#include "openvino/frontend/extension/telemetry.hpp"
#include "pyopenvino/graph/model.hpp"
namespace py = pybind11;
using namespace ov::frontend;
void regclass_frontend_TelemetryExtension(py::module m) {
py::class_<TelemetryExtension, std::shared_ptr<TelemetryExtension>, ov::Extension> ext(m,
"TelemetryExtension",
py::dynamic_attr());
ext.def(py::init([](const std::string& event_category,
const TelemetryExtension::event_callback& send_event,
const TelemetryExtension::error_callback& send_error,
const TelemetryExtension::error_callback& send_stack_trace) {
return std::make_shared<TelemetryExtension>(event_category, send_event, send_error, send_stack_trace);
}));
ext.def("send_event", &TelemetryExtension::send_event);
ext.def("send_error", &TelemetryExtension::send_error);
ext.def("send_stack_trace", &TelemetryExtension::send_stack_trace);
}
void regclass_frontend_DecoderTransformationExtension(py::module m) {
py::class_<ov::frontend::DecoderTransformationExtension,
std::shared_ptr<ov::frontend::DecoderTransformationExtension>,
ov::Extension>
ext(m, "DecoderTransformationExtension", py::dynamic_attr());
}
void regclass_frontend_JsonConfigExtension(py::module m) {
py::class_<ov::frontend::JsonConfigExtension,
std::shared_ptr<ov::frontend::JsonConfigExtension>,
ov::frontend::DecoderTransformationExtension>
ext(m, "JsonConfigExtension", py::dynamic_attr());
ext.doc() = "Extension class to load and process ModelOptimizer JSON config file";
ext.def(py::init([](const std::string& path) {
return std::make_shared<ov::frontend::JsonConfigExtension>(path);
}));
}
void regclass_frontend_ProgressReporterExtension(py::module m) {
py::class_<ProgressReporterExtension, std::shared_ptr<ProgressReporterExtension>, ov::Extension> ext{
m,
"ProgressReporterExtension",
py::dynamic_attr()};
ext.doc() = "An extension class intented to use as progress reporting utility";
ext.def(py::init([]() {
return std::make_shared<ProgressReporterExtension>();
}));
ext.def(py::init([](const ProgressReporterExtension::progress_notifier_callback& callback) {
return std::make_shared<ProgressReporterExtension>(callback);
}));
ext.def(py::init([](ProgressReporterExtension::progress_notifier_callback&& callback) {
return std::make_shared<ProgressReporterExtension>(std::move(callback));
}));
ext.def("report_progress", &ProgressReporterExtension::report_progress);
}
|
GregChase/incubator-geode | gemfire-jgroups/src/main/java/com/gemstone/org/jgroups/protocols/PRINTMETHODS.java | <reponame>GregChase/incubator-geode<filename>gemfire-jgroups/src/main/java/com/gemstone/org/jgroups/protocols/PRINTMETHODS.java
/** Notice of modification as required by the LGPL
* This file was modified by Gemstone Systems Inc. on
* $Date$
**/
// $Id: PRINTMETHODS.java,v 1.3 2004/03/30 06:47:21 belaban Exp $
package com.gemstone.org.jgroups.protocols;
import com.gemstone.org.jgroups.Event;
import com.gemstone.org.jgroups.Message;
import com.gemstone.org.jgroups.blocks.MethodCall;
import com.gemstone.org.jgroups.stack.Protocol;
public class PRINTMETHODS extends Protocol {
public PRINTMETHODS() {}
@Override // GemStoneAddition
public String getName() {return "PRINTMETHODS";}
@Override // GemStoneAddition
public void up(Event evt) {
Object obj=null;
// byte[] buf; GemStoneAddition
Message msg;
if(evt.getType() == Event.MSG) {
msg=(Message)evt.getArg();
if(msg.getLength() > 0) {
try {
obj=msg.getObject();
if(obj != null && obj instanceof MethodCall)
System.out.println("--> PRINTMETHODS: received " + obj);
}
catch(ClassCastException cast_ex) {}
catch(Exception e) {}
}
}
passUp(evt);
}
@Override // GemStoneAddition
public void down(Event evt) {
// Object obj=null; GemStoneAddition
// byte[] buf; GemStoneAddition
// Message msg; GemStoneAddition
if(evt.getType() == Event.MSG) {
}
passDown(evt);
}
}
|
pfroad/rocketmq-mysql | vendor/github.com/sevennt/rocketmq/producer_test.go | package rocketmq
import (
"strconv"
"testing"
)
// dev-goProducerConsumerTest
var group = "dev-goProducerConsumerTest"
// goProducerConsumerTest
var topic = "goProducerConsumerTest"
var conf = &Config{
//Nameserver: "192.168.7.101:9876;192.168.7.102:9876;192.168.7.103:9876",
Namesrv: "192.168.6.69:9876",
ClientIp: "192.168.23.137",
InstanceName: "DEFAULT_tt",
}
func TestSend(t *testing.T) {
producer, err := NewDefaultProducer(group, conf)
producer.Start()
if err != nil {
t.Fatalf("NewDefaultProducer err, %s", err)
}
for i := 0; i < 3; i++ {
msg := NewMessage(topic, []byte("Hello RocketMQ "+strconv.Itoa(i)))
if sendResult, err := producer.Send(msg); err != nil {
t.Error("Sync send fail!") // 如果不是如预期的那么就报错
t.Fatalf("err->%s", err)
} else {
t.Logf("sendResult", sendResult)
t.Logf("Sync send success, %d", i)
//t.Logf("sendResult.sendStatus", sendResult.sendStatus)
//t.Logf("sendResult.msgId", sendResult.msgId)
//t.Logf("sendResult.messageQueue", sendResult.messageQueue)
//t.Logf("sendResult.queueOffset", sendResult.queueOffset)
//t.Logf("sendResult.transactionId", sendResult.transactionId)
//t.Logf("sendResult.offsetMsgId", sendResult.offsetMsgId)
//t.Logf("sendResult.regionId", sendResult.regionId)
}
}
t.Log("Sync send success!")
}
func TestSendOneway(t *testing.T) {
producer, err := NewDefaultProducer(group, conf)
producer.Start()
if err != nil {
t.Fatalf("NewDefaultProducer err, %s", err)
}
for i := 0; i < 3; i++ {
msg := NewMessage(topic, []byte("Hello RocketMQ "+strconv.Itoa(i)))
if err := producer.SendOneway(msg); err != nil {
t.Error("Oneway send fail!") // 如果不是如预期的那么就报错
t.Fatalf("err->%s", err)
} else {
t.Logf("Oneway send success, %d", i)
}
}
t.Log("Oneway send success!")
}
func TestSendAsync(t *testing.T) {
producer, err := NewDefaultProducer(group, conf)
producer.Start()
if err != nil {
t.Fatalf("NewDefaultProducer err, %s", err)
}
for i := 0; i < 3; i++ {
msg := NewMessage(topic, []byte("Hello RocketMQ "+strconv.Itoa(i)))
sendCallback := func() error {
t.Logf("I am callback")
return nil
}
if err := producer.SendAsync(msg, sendCallback); err != nil {
t.Error("Async send fail!") // 如果不是如预期的那么就报错
t.Fatalf("err->%s", err)
} else {
t.Logf("Async send success, %d", i)
}
}
t.Log("Async send success!")
}
|
phakhruddin/allowance | app/controllers/advance.js | <gh_stars>1-10
exports.openMainWindow = function(_tab) {
_tab.open($.advance_window);
Ti.API.info("This is child widow advance.js" +JSON.stringify(_tab));
};
var someInfo = Alloy.Models.info;
someInfo.fetch();
console.log("advance::checkInfo: json stringify: "+JSON.stringify(someInfo));
function checkInfo(){
var info=JSON.parse(JSON.stringify(someInfo));
console.log("advance::checkInfo: name: "+info.name);
}
function createDir(){
var info=JSON.parse(JSON.stringify(someInfo));
var name = info.name.replace(/ /g,"_");
console.log("advance::checkInfo: name: "+name);
if(Alloy.Globals.license == "demo"){
var parentid=Titanium.App.Properties.getString("publicrepo");
} else var parentid=Titanium.App.Properties.getString("privaterepo") ;
console.log("advance:createDir:: createFolder("+name+","+parentid+"): ");
Alloy.Globals.createFolder(name,parentid);
}
function getMaster(){
Alloy.Globals.getMaster();
}
function setPrivate() {
Alloy.Globals.setPrivate(sid);
}
function createCreditDebit() {
var info=JSON.parse(JSON.stringify(someInfo));
var name = info.name.replace(/ /g,"_");
console.log("advance::checkInfo: name: "+name);
Alloy.Globals.locateIndexCreateSpreadsheet(name);
}
function unrelatedtest() {
Alloy.Globals.getPrivateMaster();
}
function getMaster() {
Alloy.Globals.getMaster();
}
|
thienkimlove/time-machine | src/main/java/com/booking/replication/binlog/event/QueryEventType.java | package com.booking.replication.binlog.event;
/**
* Created by edmitriev on 8/1/17.
*/
public enum QueryEventType {
BEGIN,
COMMIT,
DDLDEFINER,
DDLTABLE,
DDLTEMPORARYTABLE,
DDLVIEW,
PSEUDOGTID,
ANALYZE,
UNKNOWN;
QueryEventType() {
}
}
|
prathamesh-sonpatki/jruby | spec/ruby/library/logger/severity_spec.rb | require File.expand_path('../../../spec_helper', __FILE__)
require 'logger'
describe "Logger::Severity" do
it "defines Logger severity constants" do
Logger::DEBUG.should == 0
Logger::INFO.should == 1
Logger::WARN.should == 2
Logger::ERROR.should == 3
Logger::FATAL.should == 4
Logger::UNKNOWN.should == 5
end
end
|
gematik-fue/hapi-fhir | examples/src/main/java/example/ServerMetadataExamples.java | package example;
import ca.uhn.fhir.model.api.Tag;
import ca.uhn.fhir.rest.annotation.Search;
import org.hl7.fhir.r4.model.InstantType;
import org.hl7.fhir.r4.model.Patient;
import java.util.ArrayList;
import java.util.List;
public class ServerMetadataExamples {
// START SNIPPET: serverMethod
@Search
public List<Patient> getAllPatients() {
ArrayList<Patient> retVal = new ArrayList<Patient>();
// Create a patient to return
Patient patient = new Patient();
retVal.add(patient);
patient.setId("Patient/123");
patient.addName().setFamily("Smith").addGiven("John");
// Add tags
patient.getMeta().addTag()
.setSystem(Tag.HL7_ORG_FHIR_TAG)
.setCode("some_tag")
.setDisplay("Some tag");
patient.getMeta().addTag()
.setSystem(Tag.HL7_ORG_FHIR_TAG)
.setCode("another_tag")
.setDisplay("Another tag");
// Set the last updated date
patient.getMeta().setLastUpdatedElement(new InstantType("2011-02-22T11:22:00.0122Z"));
return retVal;
}
// END SNIPPET: serverMethod
}
|
CAt0mIcS/Ray | Ray/Graphics/Pipelines/Shader/DataAccess/RSampler2DUniform.cpp | #include "RSampler2DUniform.h"
#include "../../RPipeline.h"
#include "../../Shader/RShader.h"
#include "RDescriptor.h"
namespace At0::Ray
{
Sampler2DUniform::Sampler2DUniform(
std::string_view name, ShaderStage stage, const Pipeline& pipeline)
: m_Name(name)
{
RAY_MEXPECTS(pipeline.GetShader().GetReflection(stage).HasUniform(name, true),
"[BufferUniform] Uniform \"{0}\" was not found in shader stage \"{1}\"", name,
String::Construct(stage));
const auto& uniform = pipeline.GetShader().GetReflection(stage).GetUniform(name);
m_Binding = uniform.binding;
}
Sampler2DUniform::Sampler2DUniform(std::string_view name, uint32_t binding)
: m_Name(name), m_Binding(binding)
{
}
void Sampler2DUniform::SetTexture(Ref<Texture> texture, DescriptorSet& descSet)
{
descSet.BindUniform(*this, std::move(texture));
}
} // namespace At0::Ray
|
bcongdon/advent_of_code_2017 | Day1-9/5.py | <reponame>bcongdon/advent_of_code_2017<filename>Day1-9/5.py<gh_stars>10-100
def first_jump_outside(jumps, mutator):
c = 0
steps = 0
while c >= 0 and c < len(jumps):
j = jumps[c]
jumps[c] = mutator(j)
steps += 1
c += j
return steps
if __name__ == '__main__':
with open('5.txt') as f:
jumps = [int(i) for i in f.readlines()]
part1 = (lambda x: x+1)
part2 = (lambda x: x-1 if x >= 3 else x+1)
# example = [0, 3, 0, 1, -3]
# assert first_jump_outside(example[:], part1) == 5
# assert first_jump_outside(example[:], part2) == 10
print("Part 1: {}".format(
first_jump_outside(jumps[:], lambda x: x+1)
))
print("Part 2: {}".format(
first_jump_outside(jumps[:], lambda x: x-1 if x >= 3 else x+1)
))
|
ChristianWilkie/Chronicle-Queue | src/main/java/net/openhft/chronicle/queue/QueueSystemProperties.java | <reponame>ChristianWilkie/Chronicle-Queue
package net.openhft.chronicle.queue;
import net.openhft.chronicle.core.Jvm;
public final class QueueSystemProperties {
private QueueSystemProperties() {
}
/**
* Returns if Chronicle Queue shall assert certain index invariants on various
* occasions throughout the code. Setting this property to "", "yes" or "true"
* will enable this feature. Enabling the feature will slow down execution if
* assertions (-ea) are enabled.
* <p>
* System Property key: "queue.check.index"
* Default unset value: false
* Activation values : "", "yes", or "true"
*/
public static final boolean CHECK_INDEX = Jvm.getBoolean("queue.check.index");
/**
* Name of a system property used to specify the default roll cycle.
* <p>
* System Property key: "net.openhft.queue.builder.defaultRollCycle"
* Default unset value: net.openhft.chronicle.queue.RollCycles.DEFAULT
* Valid values : Any name of an entity implementing RollCycle such as "net.openhft.chronicle.queue.RollCycles.MINUTELY"
*/
public static final String DEFAULT_ROLL_CYCLE_PROPERTY = "net.openhft.queue.builder.defaultRollCycle";
/**
* Name of a system property used to specify the default epoch offset property.
* <p>
* System Property key: "net.openhft.queue.builder.defaultEpoch"
* Default unset value: 0L
* Valid values : Any long value
*/
public static final String DEFAULT_EPOCH_PROPERTY = "net.openhft.queue.builder.defaultEpoch";
// The name space of the system properties should be managed. Eg. map.x.y, queue.a.b
}
|
kaykhuq/stream-on | app/containers/PackContainer/reducer.js | /*
*
* PackContainer reducer
*
*/
import { fromJS } from 'immutable';
import {
LOAD_PACK,
SEARCH
} from './constants';
const initialState = fromJS({
packs: {},
keyword: '',
});
function packContainerReducer(state = initialState, action) {
switch (action.type) {
case LOAD_PACK:
return state.set('packs', action.packs);
case SEARCH:
// console.log(action);
return state.set('keyword', action.keyword);
default:
return state;
}
}
export default packContainerReducer;
|
EBRD-ProzorroSale/openprocurement.auctions.core | openprocurement/auctions/core/plugins/awarding/v2/includeme.py | <reponame>EBRD-ProzorroSale/openprocurement.auctions.core<gh_stars>1-10
# -*- coding: utf-8 -*-
from openprocurement.auctions.core.plugins.awarding.base.interfaces import (
IAwardManagerAdapter,
)
def includeme(config):
from .adapters import AwardManagerV2Adapter
from .interfaces import IAwardV2
config.registry.registerAdapter(
AwardManagerV2Adapter,
(IAwardV2, ),
IAwardManagerAdapter
)
|
lytics/amphtml | src/amp-story-player/amp-story-entry-point/amp-story-entry-point-impl.js | /**
* Copyright 2020 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Source for this constant is css/amp-story-entry-point.css
import {cssText} from '../../../build/amp-story-entry-point.css';
/**
* <amp-story-entry-point> component for embedding stories and launching them in
* the <amp-story-player>.
*
* Note that this is a vanilla JavaScript class and should not depend on AMP
* services, as v0.js is not expected to be loaded in this context.
*/
export class AmpStoryEntryPoint {
/**
* @param {!Window} win
* @param {!Element} element
* @constructor
*/
constructor(win, element) {
/** @private {!Window} */
this.win_ = win;
/** @private {!Element} */
this.element_ = element;
/** @private {!Document} */
this.doc_ = this.win_.document;
/** @private {boolean} */
this.isBuilt_ = false;
/** @private {boolean} */
this.isLaidOut_ = false;
/** @private {?Element} */
this.rootEl_ = null;
}
/** @public */
buildCallback() {
if (this.isBuilt_) {
return;
}
this.initializeShadowRoot_();
this.isBuilt_ = true;
}
/** @public */
layoutCallback() {
if (this.isLaidOut_) {
return;
}
this.isLaidOut_ = true;
}
/** @private */
initializeShadowRoot_() {
this.rootEl_ = this.doc_.createElement('main');
// Create shadow root
const shadowRoot = this.element_.attachShadow({mode: 'open'});
// Inject default styles
const styleEl = this.doc_.createElement('style');
styleEl.textContent = cssText;
shadowRoot.appendChild(styleEl);
shadowRoot.appendChild(this.rootEl_);
}
/**
* @public
* @return {!Element}
*/
getElement() {
return this.element_;
}
}
|
Bhaskers-Blu-Org2/NFC-Class-Extension-Driver | Cx/NfcCxSCCommon.h | /*++
Copyright (c) Microsoft Corporation. All Rights Reserved
Module Name:
NfcCxSCCommon.h
Abstract:
SmartCard Common functions/types.
Environment:
User-mode Driver Framework
--*/
#pragma once
// ISO 7816-3 2006, Section 8.1 (TS byte + 32 characters)
#define MAXIMUM_ATR_LENGTH 33
typedef
NTSTATUS
NFCCX_SC_DISPATCH_HANDLER(
_In_ WDFDEVICE Device,
_In_ WDFREQUEST Request,
_In_opt_bytecount_(InputBufferLength) PVOID InputBuffer,
_In_ size_t InputBufferLength,
_Out_opt_bytecap_(OutputBufferLength) PVOID OutputBuffer,
_In_ size_t OutputBufferLength
);
typedef NFCCX_SC_DISPATCH_HANDLER *PFN_NFCCX_SC_DISPATCH_HANDLER;
// {D6B5B883-18BD-4B4D-B2EC-9E38AFFEDA82}, 2, DEVPROP_TYPE_BYTE
DEFINE_DEVPROPKEY(DEVPKEY_Device_ReaderKind, 0xD6B5B883, 0x18BD, 0x4B4D, 0xB2, 0xEC, 0x9E, 0x38, 0xAF, 0xFE, 0xDA, 0x82, 0x02);
// {D6B5B883-18BD-4B4D-B2EC-9E38AFFEDA82}, D, DEVPROP_TYPE_GUID
DEFINE_DEVPROPKEY(DEVPKEY_Device_ReaderSecureElementId,
0xD6B5B883, 0x18BD, 0x4B4D, 0xB2, 0xEC, 0x9E, 0x38, 0xAF, 0xFE, 0xDA, 0x82, 0x0D);
static const DWORD SCReaderCurrentProtocolType = SCARD_PROTOCOL_T1;
NTSTATUS
NfcCxSCCommonGetAttribute(
_In_ DWORD AttributeId,
_Out_writes_bytes_to_(*OutputBufferLength, *OutputBufferLength) PVOID OutputBuffer,
_Inout_ size_t* OutputBufferLength);
NFCCX_SC_DISPATCH_HANDLER NfcCxSCCommonDispatchNotSupported;
NFCCX_SC_DISPATCH_HANDLER NfcCxSCCommonDispatchGetLastError;
NTSTATUS
NfcCxSCCommonCopyTrasmitResponseData(
_Out_opt_bytecap_(OutputBufferLength) PVOID OutputBuffer,
_In_ ULONG OutputBufferLength,
_In_bytecount_(DataLength) PVOID Data,
_In_ ULONG DataLength,
_Out_ PULONG BufferUsed
);
|
zregvart/atlasmap-1 | runtime/api/src/main/java/io/atlasmap/spi/AtlasModule.java | /**
* Copyright (C) 2017 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.atlasmap.spi;
import java.util.List;
import io.atlasmap.api.AtlasConversionService;
import io.atlasmap.api.AtlasException;
import io.atlasmap.api.AtlasFieldActionService;
import io.atlasmap.v2.Field;
public interface AtlasModule {
void init();
void destroy();
void processPreValidation(AtlasInternalSession session) throws AtlasException;
void processPreSourceExecution(AtlasInternalSession session) throws AtlasException;
void processPreTargetExecution(AtlasInternalSession session) throws AtlasException;
void processSourceFieldMapping(AtlasInternalSession session) throws AtlasException;
void processTargetFieldMapping(AtlasInternalSession session) throws AtlasException;
void processPostSourceExecution(AtlasInternalSession session) throws AtlasException;
void processPostTargetExecution(AtlasInternalSession session) throws AtlasException;
void processPostValidation(AtlasInternalSession session) throws AtlasException;
AtlasModuleMode getMode();
void setMode(AtlasModuleMode atlasModuleMode);
AtlasConversionService getConversionService();
void setConversionService(AtlasConversionService atlasConversionService);
AtlasFieldActionService getFieldActionService();
void setFieldActionService(AtlasFieldActionService atlasFieldActionService);
List<AtlasModuleMode> listSupportedModes();
String getDocId();
void setDocId(String docId);
String getUri();
void setUri(String uri);
Boolean isStatisticsSupported();
Boolean isStatisticsEnabled();
Boolean isSupportedField(Field field);
Field cloneField(Field field) throws AtlasException;
int getCollectionSize(AtlasInternalSession session, Field field) throws AtlasException;
}
|
talend-spatial/talend-spatial | main/plugins/org.talend.sdi.designer.components.sextante/src/main/java/org/talend/sdi/designer/components/sextante/SextanteComponentsProvider.java | <reponame>talend-spatial/talend-spatial<filename>main/plugins/org.talend.sdi.designer.components.sextante/src/main/java/org/talend/sdi/designer/components/sextante/SextanteComponentsProvider.java
// ============================================================================
//
// Copyright (C) 2008 Camptocamp. - www.camptocamp.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.sdi.designer.components.sextante;
import java.io.File;
import org.talend.commons.ui.runtime.exception.ExceptionHandler;
import org.talend.core.model.components.AbstractComponentsProvider;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Path;
import java.net.URL;
/**
* Components provider for sdi sextante components.
*
* @author fxprunayre
*/
public class SextanteComponentsProvider extends AbstractComponentsProvider {
/**
* SextanteComponentsProvider constructor.
*/
public SextanteComponentsProvider() {
}
@Override
protected File getExternalComponentsLocation() {
URL url = FileLocator.find(SextantePlugin.getDefault().getBundle(),
new Path("components"), null);
URL fileUrl;
try {
fileUrl = FileLocator.toFileURL(url);
return new File(fileUrl.getPath());
} catch (Exception e) {
ExceptionHandler.process(e);
}
return null;
}
}
|
maidiHaitai/haitaibrowser | chrome/browser/media/pepper_cdm_test_helper.cc | <reponame>maidiHaitai/haitaibrowser
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/media/pepper_cdm_test_helper.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/path_service.h"
#include "base/strings/utf_string_conversions.h"
#include "content/public/common/content_switches.h"
#include "widevine_cdm_version.h" // In SHARED_INTERMEDIATE_DIR.
const char kClearKeyCdmDisplayName[] = "Clear Key CDM";
const char kClearKeyCdmAdapterFileName[] =
#if defined(OS_MACOSX)
"clearkeycdmadapter.plugin";
#elif defined(OS_WIN)
"clearkeycdmadapter.dll";
#elif defined(OS_POSIX)
"libclearkeycdmadapter.so";
#endif
const char kClearKeyCdmPepperMimeType[] = "application/x-ppapi-clearkey-cdm";
base::FilePath::StringType BuildPepperCdmRegistration(
const std::string& adapter_file_name,
const std::string& display_name,
const std::string& mime_type,
bool expect_adapter_exists) {
base::FilePath adapter_path;
PathService::Get(base::DIR_MODULE, &adapter_path);
adapter_path = adapter_path.AppendASCII(adapter_file_name);
DCHECK_EQ(expect_adapter_exists, base::PathExists(adapter_path));
base::FilePath::StringType pepper_cdm_registration = adapter_path.value();
std::string string_to_append = "#";
string_to_append.append(display_name);
string_to_append.append("#CDM#0.1.0.0;");
string_to_append.append(mime_type);
#if defined(OS_WIN)
pepper_cdm_registration.append(base::ASCIIToUTF16(string_to_append));
#else
pepper_cdm_registration.append(string_to_append);
#endif
return pepper_cdm_registration;
}
void RegisterPepperCdm(base::CommandLine* command_line,
const std::string& adapter_file_name,
const std::string& display_name,
const std::string& mime_type,
bool expect_adapter_exists) {
base::FilePath::StringType pepper_cdm_registration =
BuildPepperCdmRegistration(adapter_file_name, display_name, mime_type,
expect_adapter_exists);
// Append the switch to register the CDM Adapter.
command_line->AppendSwitchNative(switches::kRegisterPepperPlugins,
pepper_cdm_registration);
}
|
npocmaka/Windows-Server-2003 | admin/wmi/wbem/providers/win32provider/providers/win32programgroupcontents.cpp | <reponame>npocmaka/Windows-Server-2003
//=================================================================
//
// Win32ProgramCollectionProgramGroup.cpp -- Win32_ProgramGroup to Win32_ProgramGroupORItem
//
// Copyright (c) 1998-2001 Microsoft Corporation, All Rights Reserved
//
// Revisions: 11/20/98 a-kevhu Created
//
// Comment: Relationship between Win32_ProgramGroup and Win32_ProgramGroupORItem it contains
//
//=================================================================
#include "precomp.h"
#include "Win32ProgramGroupContents.h"
#include "LogicalProgramGroupItem.h"
#include "LogicalProgramGroup.h"
#include <frqueryex.h>
#include <utils.h>
// Property set declaration
//=========================
CW32ProgGrpCont MyCW32ProgGrpCont(PROPSET_NAME_WIN32PROGRAMGROUPCONTENTS, IDS_CimWin32Namespace);
/*****************************************************************************
*
* FUNCTION : CW32ProgGrpCont::CW32ProgGrpCont
*
* DESCRIPTION : Constructor
*
* INPUTS : none
*
* OUTPUTS : none
*
* RETURNS : nothing
*
* COMMENTS : Registers property set with framework
*
*****************************************************************************/
CW32ProgGrpCont::CW32ProgGrpCont(LPCWSTR setName, LPCWSTR pszNamespace)
:Provider(setName, pszNamespace)
{
}
/*****************************************************************************
*
* FUNCTION : CW32ProgGrpCont::~CW32ProgGrpCont
*
* DESCRIPTION : Destructor
*
* INPUTS : none
*
* OUTPUTS : none
*
* RETURNS : nothing
*
* COMMENTS : Deregisters property set from framework
*
*****************************************************************************/
CW32ProgGrpCont::~CW32ProgGrpCont()
{
}
/*****************************************************************************
*
* FUNCTION : CW32ProgGrpCont::GetObject
*
* DESCRIPTION : Assigns values to property set according to key value
* already set by framework
*
* INPUTS : none
*
* OUTPUTS : none
*
* RETURNS : HRESULT
*
* COMMENTS :
*
*****************************************************************************/
HRESULT CW32ProgGrpCont::GetObject(CInstance *pInstance, long lFlags /*= 0L*/)
{
HRESULT hr = WBEM_E_NOT_FOUND;
TRefPointerCollection<CInstance> GroupDirs;
CHString chstrPGCGroupComponent;
CHString chstrPGCPartComponent;
if(pInstance == NULL)
{
return WBEM_E_FAILED;
}
pInstance->GetCHString(IDS_GroupComponent, chstrPGCGroupComponent);
pInstance->GetCHString(IDS_PartComponent, chstrPGCPartComponent);
if(AreSimilarPaths(chstrPGCGroupComponent, chstrPGCPartComponent))
{
CHString chstrPGCPartComponentFilenameOnly;
chstrPGCPartComponentFilenameOnly = chstrPGCPartComponent.Mid(chstrPGCPartComponent.ReverseFind(_T('\\')));
chstrPGCPartComponentFilenameOnly = chstrPGCPartComponentFilenameOnly.Left(chstrPGCPartComponentFilenameOnly.GetLength() - 1);
// Need version of chstrPGCGroupComponent with escaped backslashes for the following query.
CHString chstrPGCGroupComponentDblEsc;
EscapeBackslashes(chstrPGCGroupComponent,chstrPGCGroupComponentDblEsc);
// Also need to escape the quotes...
CHString chstrPGCGroupComponentDblEscQuoteEsc;
EscapeQuotes(chstrPGCGroupComponentDblEsc,chstrPGCGroupComponentDblEscQuoteEsc);
CHString chstrProgGroupDirQuery;
chstrProgGroupDirQuery.Format(L"SELECT * FROM Win32_LogicalProgramGroupDirectory WHERE Antecedent = \"%s\"", chstrPGCGroupComponentDblEscQuoteEsc);
if(SUCCEEDED(CWbemProviderGlue::GetInstancesByQuery(chstrProgGroupDirQuery,
&GroupDirs,
pInstance->GetMethodContext(),
IDS_CimWin32Namespace)))
{
REFPTRCOLLECTION_POSITION pos;
CInstancePtr pProgramGroupDirInstance;
// We'll need a normalized path for chstrPGCGroupComponent...
CHString chstrPGCGroupComponentNorm;
if(NormalizePath(chstrPGCGroupComponent, GetLocalComputerName(), IDS_CimWin32Namespace, NORMALIZE_NULL, chstrPGCGroupComponentNorm) == e_OK)
{
if(GroupDirs.BeginEnum(pos))
{
CHString chstrPGDAntecedent;
CHString chstrPGDDependent;
CHString chstrPGDDependentFullFileName;
CHString chstrTemp;
CHString chstrLPGIClassName(PROPSET_NAME_LOGICALPRGGROUPITEM);
chstrLPGIClassName.MakeLower();
// Determine if the dependent (of this association class - PC) was a programgroup or a programgroupitem
chstrPGCPartComponent.MakeLower();
if(chstrPGCPartComponent.Find(chstrLPGIClassName) != -1)
{
// The dependent was a programgroupitem, so will look for matching file
// Go through PGD instances (should only be one) until find a PGDAntecedent that matches the PCAntecedent
for(pProgramGroupDirInstance.Attach(GroupDirs.GetNext(pos));
(pProgramGroupDirInstance != NULL) ;
pProgramGroupDirInstance.Attach(GroupDirs.GetNext(pos)))
{
pProgramGroupDirInstance->GetCHString(IDS_Antecedent, chstrPGDAntecedent);
pProgramGroupDirInstance->GetCHString(IDS_Dependent, chstrPGDDependent);
// Need a normalized version of the antecedent for the comparison below...
CHString chstrPGDAntecedentNorm;
if(NormalizePath(chstrPGDAntecedent, GetLocalComputerName(), IDS_CimWin32Namespace, NORMALIZE_NULL, chstrPGDAntecedentNorm) == e_OK)
{
// See if the PGDAntecedent matches the chstrPGCGroupComponentNorm
if(chstrPGDAntecedentNorm.CompareNoCase(chstrPGCGroupComponentNorm) == 0)
{
// Got the proposed filename from the PCDependent at the beginning of GetObject.
// Now Get the directory of the PGD (PGDDependent) associated with the PC antecedent
chstrPGDDependentFullFileName = chstrPGDDependent.Mid(chstrPGDDependent.Find(_T('='))+2);
chstrPGDDependentFullFileName = chstrPGDDependentFullFileName.Left(chstrPGDDependentFullFileName.GetLength() - 1);
RemoveDoubleBackslashes(chstrPGDDependentFullFileName);
chstrTemp.Format(L"%s%s",chstrPGDDependentFullFileName,chstrPGCPartComponentFilenameOnly);
hr = DoesFileOrDirExist(_bstr_t(chstrTemp),ID_FILEFLAG);
if(SUCCEEDED(hr))
{
hr = WBEM_S_NO_ERROR;
break;
}
}
} // got normalized path for the antecedent
}
}
else
{
// The dependent was a programgroup, so will look for matching dir
// Go through PGD instances until find a PGDAntecedent that matches the PCAntecedent
for (pProgramGroupDirInstance.Attach(GroupDirs.GetNext(pos));
pProgramGroupDirInstance != NULL;
pProgramGroupDirInstance.Attach(GroupDirs.GetNext(pos)))
{
pProgramGroupDirInstance->GetCHString(IDS_Antecedent, chstrPGDAntecedent);
pProgramGroupDirInstance->GetCHString(IDS_Dependent, chstrPGDDependent);
// Need a normalized version of the antecedent for the comparison below...
CHString chstrPGDAntecedentNorm;
if(NormalizePath(chstrPGDAntecedent, GetLocalComputerName(), IDS_CimWin32Namespace, NORMALIZE_NULL, chstrPGDAntecedentNorm) == e_OK)
{
// See if the PGDAntecedent matches the PCAntecedent
if(chstrPGDAntecedentNorm.CompareNoCase(chstrPGCGroupComponentNorm) == 0)
{
// Got the proposed filename (which is a directory name in this case) from the PCDependent at the beginning of GetObject.
// Now Get the directory of the PGD (PGDDependent) associated with the PC antecedent
chstrPGDDependentFullFileName = chstrPGDDependent.Mid(chstrPGDDependent.Find(_T('='))+2);
chstrPGDDependentFullFileName = chstrPGDDependentFullFileName.Left(chstrPGDDependentFullFileName.GetLength() - 1);
RemoveDoubleBackslashes(chstrPGDDependentFullFileName);
chstrTemp.Format(L"%s\\%s",chstrPGDDependentFullFileName,chstrPGCPartComponentFilenameOnly);
hr = DoesFileOrDirExist(_bstr_t(chstrTemp),ID_DIRFLAG);
if(SUCCEEDED(hr))
{
hr = WBEM_S_NO_ERROR;
break;
}
}
} // got normalized path for the antecedent
}
}
GroupDirs.EndEnum();
} // IF BeginEnum
} // got a normalized path successfully
}
}
return hr;
}
/*****************************************************************************
*
* FUNCTION : CW32ProgGrpCont::ExecQuery
*
* DESCRIPTION : Analyses query and returns appropriate instances
*
* INPUTS :
*
* OUTPUTS : none
*
* RETURNS : HRESULT
*
* COMMENTS :
*
*****************************************************************************/
HRESULT CW32ProgGrpCont::ExecQuery(MethodContext *pMethodContext, CFrameworkQuery& pQuery, long lFlags /*= 0L*/ )
{
HRESULT hr = WBEM_S_NO_ERROR;
BOOL f3TokenOREqualArgs = FALSE;
BOOL fGroupCompIsGroup = FALSE;
_bstr_t bstrtGroupComponent;
_bstr_t bstrtPartComponent;
// I'm only going to optimize queries that had Antecedent and Dependent arguements OR'd together
CFrameworkQueryEx *pQuery2 = static_cast <CFrameworkQueryEx *>(&pQuery);
if (pQuery2 != NULL)
{
variant_t vGroupComponent;
variant_t vPartComponent;
if(pQuery2->Is3TokenOR(L"GroupComponent", L"PartComponent", vGroupComponent, vPartComponent))
{
bstrtGroupComponent = V_BSTR(&vGroupComponent);
bstrtPartComponent = V_BSTR(&vPartComponent);
// I'm also going to insist that the arguements of the dependent and the antecedent be the same
if(bstrtGroupComponent == bstrtPartComponent)
{
f3TokenOREqualArgs = TRUE;
}
}
}
// Only want to proceed if the Antecedent was a program group (Dependent can be either group or item, however).
if(f3TokenOREqualArgs)
{
if(wcsstr((wchar_t*)bstrtGroupComponent,(wchar_t*)_bstr_t(PROPSET_NAME_LOGICALPRGGROUP)))
{
fGroupCompIsGroup = TRUE;
}
}
if(fGroupCompIsGroup)
{
CHString chstrPGCPartComponent((wchar_t*)bstrtPartComponent);
CHString chstrPGCGroupComponent((wchar_t*)bstrtGroupComponent);
// We will get here is someone had a particular program group and asked for its associations. This
// provider will give back program groups and program group items associated with (underneath) the
// supplied program group. The query will look like the following:
// select * from Win32_ProgramGroupContents where (PartComponent = "Win32_LogicalProgramGroup.Name=\"Default User:Accessories\"" OR GroupComponent = "Win32_LogicalProgramGroup.Name=\"Default User:Accessories\"")
// Step 1: Do a GetInstanceByQuery to obtain the specific directory associated with the program group
//==================================================================================================
// Need version of chstrPGCGroupComponent with escaped backslashes for the following query...
CHString chstrPGCGroupComponentDblEsc;
EscapeBackslashes(chstrPGCGroupComponent,chstrPGCGroupComponentDblEsc);
// Also need to escape the quotes...
CHString chstrPGCGroupComponentDblEscQuoteEsc;
EscapeQuotes(chstrPGCGroupComponentDblEsc,chstrPGCGroupComponentDblEscQuoteEsc);
CHString chstrProgGroupDirQuery;
TRefPointerCollection<CInstance> GroupDirs;
chstrProgGroupDirQuery.Format(L"SELECT * FROM Win32_LogicalProgramGroupDirectory WHERE Antecedent = \"%s\"", (LPCWSTR)chstrPGCGroupComponentDblEscQuoteEsc);
if(SUCCEEDED(CWbemProviderGlue::GetInstancesByQuery(chstrProgGroupDirQuery,
&GroupDirs,
pMethodContext,
IDS_CimWin32Namespace)))
{
// Step 2: Eunumerate all the program groups (dirs) and program group items (files) found underneath it
//=====================================================================================================
REFPTRCOLLECTION_POSITION pos;
if(GroupDirs.BeginEnum(pos))
{
CHString chstrDependent;
CHString chstrFullPathName;
CHString chstrPath;
CHString chstrDrive;
CHString chstrAntecedent;
CHString chstrSearchPath;
CInstancePtr pProgramGroupDirInstance;
for (pProgramGroupDirInstance.Attach(GroupDirs.GetNext(pos)) ;
(pProgramGroupDirInstance != NULL) && (SUCCEEDED(hr)) ;
pProgramGroupDirInstance.Attach(GroupDirs.GetNext(pos)) )
{
// For each program group, get the drive and path associated on disk with it:
pProgramGroupDirInstance->GetCHString(IDS_Dependent, chstrDependent);
chstrFullPathName = chstrDependent.Mid(chstrDependent.Find(_T('='))+1);
chstrDrive = chstrFullPathName.Mid(1,2);
chstrPath = chstrFullPathName.Mid(3);
chstrPath = chstrPath.Left(chstrPath.GetLength() - 1);
chstrPath += L"\\\\";
// Query that directory for all the **CIM_LogicalFile** instances (of any type) it contains:
chstrSearchPath.Format(L"%s%s",chstrDrive,chstrPath);
// The function QueryForSubItemsAndCommit needs a search string with single backslashes...
RemoveDoubleBackslashes(chstrSearchPath);
#ifdef NTONLY
hr = QueryForSubItemsAndCommitNT(chstrPGCGroupComponent, chstrSearchPath, pMethodContext);
#endif
}
GroupDirs.EndEnum();
}
} // GetInstancesByQuery succeeded
}
else
{
hr = EnumerateInstances(pMethodContext);
}
return hr;
}
/*****************************************************************************
*
* FUNCTION : CW32ProgGrpCont::EnumerateInstances
*
* DESCRIPTION : Creates instance of property set for cd rom
*
* INPUTS : none
*
* OUTPUTS : none
*
* RETURNS : HRESULT
*
* COMMENTS :
*
*****************************************************************************/
HRESULT CW32ProgGrpCont::EnumerateInstances(MethodContext* pMethodContext, long lFlags /*= 0L*/)
{
HRESULT hr = WBEM_S_NO_ERROR;
TRefPointerCollection<CInstance> ProgGroupDirs;
// Step 1: Get an enumeration of all the ProgramGroupDirectory association class instances
if SUCCEEDED(hr = CWbemProviderGlue::GetAllInstances(L"Win32_LogicalProgramGroupDirectory", &ProgGroupDirs, IDS_CimWin32Namespace, pMethodContext))
{
REFPTRCOLLECTION_POSITION pos;
if(ProgGroupDirs.BeginEnum(pos))
{
CHString chstrDependent;
CHString chstrFullPathName;
CHString chstrPath;
CHString chstrDrive;
CHString chstrAntecedent;
CHString chstrSearchPath;
CInstancePtr pProgramGroupDirInstance;
for (pProgramGroupDirInstance.Attach(ProgGroupDirs.GetNext(pos)) ;
(pProgramGroupDirInstance != NULL) && (SUCCEEDED(hr)) ;
pProgramGroupDirInstance.Attach(ProgGroupDirs.GetNext(pos)) )
{
// Step 2: For each program group, get the drive and path associated on disk with it:
pProgramGroupDirInstance->GetCHString(IDS_Dependent, chstrDependent);
chstrFullPathName = chstrDependent.Mid(chstrDependent.Find(_T('='))+1);
chstrDrive = chstrFullPathName.Mid(1,2);
chstrPath = chstrFullPathName.Mid(3);
chstrPath = chstrPath.Left(chstrPath.GetLength() - 1);
chstrPath += _T("\\\\");
// Step 3: For each program group, get the user account it is associated with:
pProgramGroupDirInstance->GetCHString(IDS_Antecedent, chstrAntecedent);
// Step 4: Query that directory for all the **CIM_LogicalFile** instances (of any type) it contains:
chstrSearchPath.Format(L"%s%s",chstrDrive,chstrPath);
// The function QueryForSubItemsAndCommit needs a search string with single backslashes...
RemoveDoubleBackslashes(chstrSearchPath);
#ifdef NTONLY
hr = QueryForSubItemsAndCommitNT(chstrAntecedent, chstrSearchPath, pMethodContext);
#endif
}
ProgGroupDirs.EndEnum();
}
}
return hr;
}
/*****************************************************************************
*
* FUNCTION : QueryForSubItemsAndCommit
*
* DESCRIPTION : Helper to fill property and commit instances of progcollectionproggroup
*
* INPUTS :
*
* OUTPUTS :
*
* RETURNS :
*
* COMMENTS :
*
*****************************************************************************/
#ifdef NTONLY
HRESULT CW32ProgGrpCont::QueryForSubItemsAndCommitNT(CHString& chstrGroupComponentPATH,
CHString& chstrQuery,
MethodContext* pMethodContext)
{
HRESULT hr = WBEM_S_NO_ERROR;
WIN32_FIND_DATAW stFindData;
ZeroMemory(&stFindData,sizeof(stFindData));
SmartFindClose hFind;
_bstr_t bstrtSearchString((LPCTSTR)chstrQuery);
WCHAR wstrDriveAndPath[_MAX_PATH];
CHString chstrUserAccountAndGroup;
CHString chstrPartComponent;
wcscpy(wstrDriveAndPath,(wchar_t*)bstrtSearchString);
bstrtSearchString += L"*.*";
hFind = FindFirstFileW((wchar_t*)bstrtSearchString, &stFindData);
DWORD dw = GetLastError();
if (hFind == INVALID_HANDLE_VALUE || dw != ERROR_SUCCESS)
{
hr = WinErrorToWBEMhResult(GetLastError());
}
if(hr == WBEM_E_ACCESS_DENIED) // keep going - might have access to others
{
hr = WBEM_S_NO_ERROR;
}
if(hr == WBEM_E_NOT_FOUND)
{
return WBEM_S_NO_ERROR; // didn't find any files, but don't want the calling routine to abort
}
do
{
if((wcscmp(stFindData.cFileName, L".") != 0) &&
(wcscmp(stFindData.cFileName, L"..") != 0))
{
if(!(stFindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
// It is a program group item (a file)
CInstancePtr pInstance(CreateNewInstance(pMethodContext),false);
if(pInstance != NULL)
{
// Need to set antecedent and dependent. Antecedent is the group we were passed
// in (in chstrGroupComponentPATH); dependent is the (in this case) a Win32_ProgramGroupItem,
// since we found a file.
chstrUserAccountAndGroup = chstrGroupComponentPATH.Mid(chstrGroupComponentPATH.Find(_T('='))+2);
chstrUserAccountAndGroup = chstrUserAccountAndGroup.Left(chstrUserAccountAndGroup.GetLength() - 1);
chstrPartComponent.Format(_T("\\\\%s\\%s:%s.Name=\"%s\\\\%s\""),
(LPCTSTR)GetLocalComputerName(),
IDS_CimWin32Namespace,
_T("Win32_LogicalProgramGroupItem"),
chstrUserAccountAndGroup,
(LPCTSTR)CHString(stFindData.cFileName));
pInstance->SetCHString(IDS_GroupComponent, chstrGroupComponentPATH);
pInstance->SetCHString(IDS_PartComponent, chstrPartComponent);
hr = pInstance->Commit();
}
else
{
hr = WBEM_E_OUT_OF_MEMORY;
}
}
else if(stFindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
// It is a program group (a directory)
CInstancePtr pInstance (CreateNewInstance(pMethodContext),false);
if(pInstance != NULL)
{
// Need to set antecedent and dependent. Antecedent is the group we were passed
// in (in chstrGroupComponentPATH); dependent is the (in this case) a Win32_LogicalProgramGroup,
// since we found a directory.
chstrUserAccountAndGroup = chstrGroupComponentPATH.Mid(chstrGroupComponentPATH.Find(_T('='))+2);
chstrUserAccountAndGroup = chstrUserAccountAndGroup.Left(chstrUserAccountAndGroup.GetLength() - 1);
chstrPartComponent.Format(_T("\\\\%s\\%s:%s.Name=\"%s\\\\%s\""),
(LPCTSTR)GetLocalComputerName(),
IDS_CimWin32Namespace,
_T("Win32_LogicalProgramGroup"),
chstrUserAccountAndGroup,
(LPCTSTR)CHString(stFindData.cFileName));
pInstance->SetCHString(IDS_GroupComponent, chstrGroupComponentPATH);
pInstance->SetCHString(IDS_PartComponent, chstrPartComponent);
hr = pInstance->Commit();
}
else
{
hr = WBEM_E_OUT_OF_MEMORY;
}
}
}
if(hr == WBEM_E_ACCESS_DENIED) // keep going - might have access to others
{
hr = WBEM_S_NO_ERROR;
}
}while((FindNextFileW(hFind, &stFindData)) && (SUCCEEDED(hr)));
return(hr);
}
#endif
/*****************************************************************************
*
* FUNCTION : RemoveDoubleBackslashes
*
* DESCRIPTION : Helper to change double backslashes to single backslashes
*
* INPUTS : CHString& containing the string with double backslashes,
* which will be changed by this function to the new string.
*
* OUTPUTS :
*
* RETURNS :
*
* COMMENTS :
*
*****************************************************************************/
VOID CW32ProgGrpCont::RemoveDoubleBackslashes(CHString& chstrIn)
{
CHString chstrBuildString;
CHString chstrInCopy = chstrIn;
BOOL fDone = FALSE;
LONG lPos = -1;
while(!fDone)
{
lPos = chstrInCopy.Find(L"\\\\");
if(lPos != -1)
{
chstrBuildString += chstrInCopy.Left(lPos);
chstrBuildString += _T("\\");
chstrInCopy = chstrInCopy.Mid(lPos+2);
}
else
{
chstrBuildString += chstrInCopy;
fDone = TRUE;
}
}
chstrIn = chstrBuildString;
}
/*****************************************************************************
*
* FUNCTION : DoesFileOrDirExist
*
* DESCRIPTION : Helper to determine if a file or a directory exists
*
* INPUTS : wstrFullFileName, the full path name of the file
* dwFileOrDirFlag, a flag indicating whether we want to check
* for the existence of a file or a directory
*
* OUTPUTS :
*
* RETURNS :
*
* COMMENTS :
*
*****************************************************************************/
HRESULT CW32ProgGrpCont::DoesFileOrDirExist(WCHAR* wstrFullFileName, DWORD dwFileOrDirFlag)
{
HRESULT hr = WBEM_E_NOT_FOUND;
#ifdef NTONLY
{
WIN32_FIND_DATAW stFindData;
//HANDLE hFind = NULL;
SmartFindClose hFind;
hFind = FindFirstFileW(wstrFullFileName, &stFindData);
DWORD dw = GetLastError();
if(hFind != INVALID_HANDLE_VALUE && dw == ERROR_SUCCESS)
{
if((stFindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && (dwFileOrDirFlag == ID_DIRFLAG))
{
hr = S_OK;
}
if(!(stFindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && (dwFileOrDirFlag == ID_FILEFLAG))
{
hr = S_OK;
}
}
}
#endif
return hr;
}
bool CW32ProgGrpCont::AreSimilarPaths(CHString& chstrPGCGroupComponent, CHString& chstrPGCPartComponent)
{
bool fRet = false;
long EqualSign1 = -1L;
long EqualSign2 = -1L;
EqualSign1 = chstrPGCPartComponent.Find(L'=');
EqualSign2 = chstrPGCGroupComponent.Find(L'=');
if(EqualSign1 != -1L && EqualSign2 != -1L)
{
CHString chstrPartPath = chstrPGCPartComponent.Mid(EqualSign1+1);
CHString chstrGroupPath = chstrPGCGroupComponent.Mid(EqualSign2+1);
chstrGroupPath = chstrGroupPath.Left(chstrGroupPath.GetLength()-1);
long lPosLastBackslash = chstrPartPath.ReverseFind(L'\\');
if(lPosLastBackslash != -1L)
{
chstrPartPath = chstrPartPath.Left(lPosLastBackslash - 1);
if(chstrPartPath.CompareNoCase(chstrGroupPath) == 0)
{
fRet = true;
}
}
}
return fRet;
}
|
fanscribed/fanscribed | fanscribed/urls.py | <reponame>fanscribed/fanscribed<filename>fanscribed/urls.py
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from .sitemaps import SITEMAPS
admin.autodiscover()
# Attach this to kwargs of an url to require login.
LOGGED_IN_USER = {
'login_required': True,
}
# URL patterns used by all projects based on fanscribed core.
urlpatterns = patterns(
'',
url(r'^robots\.txt$',
include('fanscribed.apps.robots.urls')),
# TODO: use allauth's own signup-disabling techniques
url(r'^accounts/signup/$' if not settings.ACCOUNT_ALLOW_SIGNUPS else r'^ $',
view=TemplateView.as_view(template_name='account/signup_closed.html')),
url(r'^accounts/',
include('allauth.urls')),
url(r'^admin/',
include(admin.site.urls)),
url(r'api/',
include('fanscribed.api.urls')),
url(r'^help/',
name='help',
view=TemplateView.as_view(template_name='help.html')),
url(r'^podcasts/',
include('fanscribed.apps.podcasts.urls', 'podcasts')),
url(r'^profiles/',
include('fanscribed.apps.profiles.urls', 'profiles')),
url(r'^sitemap\.xml$',
view='django.contrib.sitemaps.views.sitemap',
kwargs=dict(sitemaps=SITEMAPS)),
url(r'^transcripts/',
include('fanscribed.apps.transcripts.urls', 'transcripts')),
url(r'^transcription-engine/',
name='transcription-engine',
view=TemplateView.as_view(template_name='transcription-engine.html')),
url(r'^$',
name='home',
view=TemplateView.as_view(template_name='home.html')),
)
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
jarick/didji | client/src/actions/load.actions.js |
import {SEND_LOAD, FAILED_LOAD, SUCCESS_LOAD} from '../contracts/load.contracts';
export const send = () => ({
type: SEND_LOAD
});
export const success = () => ({
type: SUCCESS_LOAD
});
export const failed = () => ({
type: FAILED_LOAD
}); |
malkhamis-panw/gaia | automationtemplate.go | package gaia
import (
"fmt"
"github.com/globalsign/mgo/bson"
"github.com/mitchellh/copystructure"
"go.aporeto.io/elemental"
)
// AutomationTemplateKindValue represents the possible values for attribute "kind".
type AutomationTemplateKindValue string
const (
// AutomationTemplateKindAction represents the value Action.
AutomationTemplateKindAction AutomationTemplateKindValue = "Action"
// AutomationTemplateKindCondition represents the value Condition.
AutomationTemplateKindCondition AutomationTemplateKindValue = "Condition"
)
// AutomationTemplateIdentity represents the Identity of the object.
var AutomationTemplateIdentity = elemental.Identity{
Name: "automationtemplate",
Category: "automationtemplates",
Package: "sephiroth",
Private: false,
}
// AutomationTemplatesList represents a list of AutomationTemplates
type AutomationTemplatesList []*AutomationTemplate
// Identity returns the identity of the objects in the list.
func (o AutomationTemplatesList) Identity() elemental.Identity {
return AutomationTemplateIdentity
}
// Copy returns a pointer to a copy the AutomationTemplatesList.
func (o AutomationTemplatesList) Copy() elemental.Identifiables {
copy := append(AutomationTemplatesList{}, o...)
return ©
}
// Append appends the objects to the a new copy of the AutomationTemplatesList.
func (o AutomationTemplatesList) Append(objects ...elemental.Identifiable) elemental.Identifiables {
out := append(AutomationTemplatesList{}, o...)
for _, obj := range objects {
out = append(out, obj.(*AutomationTemplate))
}
return out
}
// List converts the object to an elemental.IdentifiablesList.
func (o AutomationTemplatesList) List() elemental.IdentifiablesList {
out := make(elemental.IdentifiablesList, len(o))
for i := 0; i < len(o); i++ {
out[i] = o[i]
}
return out
}
// DefaultOrder returns the default ordering fields of the content.
func (o AutomationTemplatesList) DefaultOrder() []string {
return []string{
"name",
}
}
// ToSparse returns the AutomationTemplatesList converted to SparseAutomationTemplatesList.
// Objects in the list will only contain the given fields. No field means entire field set.
func (o AutomationTemplatesList) ToSparse(fields ...string) elemental.Identifiables {
out := make(SparseAutomationTemplatesList, len(o))
for i := 0; i < len(o); i++ {
out[i] = o[i].ToSparse(fields...).(*SparseAutomationTemplate)
}
return out
}
// Version returns the version of the content.
func (o AutomationTemplatesList) Version() int {
return 1
}
// AutomationTemplate represents the model of a automationtemplate
type AutomationTemplate struct {
// Description of the object.
Description string `json:"description" msgpack:"description" bson:"description" mapstructure:"description,omitempty"`
// Contains the entitlements needed for executing the function.
Entitlements map[string][]elemental.Operation `json:"entitlements" msgpack:"entitlements" bson:"-" mapstructure:"entitlements,omitempty"`
// Function contains the code.
Function string `json:"function" msgpack:"function" bson:"-" mapstructure:"function,omitempty"`
// Contains the unique identifier key for the template.
Key string `json:"key" msgpack:"key" bson:"-" mapstructure:"key,omitempty"`
// Represents the kind of template.
Kind AutomationTemplateKindValue `json:"kind" msgpack:"kind" bson:"-" mapstructure:"kind,omitempty"`
// Name of the entity.
Name string `json:"name" msgpack:"name" bson:"name" mapstructure:"name,omitempty"`
// Contains the computed parameters.
Parameters map[string]interface{} `json:"parameters" msgpack:"parameters" bson:"-" mapstructure:"parameters,omitempty"`
// Contains all the steps with parameters.
Steps []*UIStep `json:"steps" msgpack:"steps" bson:"-" mapstructure:"steps,omitempty"`
ModelVersion int `json:"-" msgpack:"-" bson:"_modelversion"`
}
// NewAutomationTemplate returns a new *AutomationTemplate
func NewAutomationTemplate() *AutomationTemplate {
return &AutomationTemplate{
ModelVersion: 1,
Entitlements: map[string][]elemental.Operation{},
Kind: AutomationTemplateKindCondition,
Parameters: map[string]interface{}{},
Steps: []*UIStep{},
}
}
// Identity returns the Identity of the object.
func (o *AutomationTemplate) Identity() elemental.Identity {
return AutomationTemplateIdentity
}
// Identifier returns the value of the object's unique identifier.
func (o *AutomationTemplate) Identifier() string {
return ""
}
// SetIdentifier sets the value of the object's unique identifier.
func (o *AutomationTemplate) SetIdentifier(id string) {
}
// GetBSON implements the bson marshaling interface.
// This is used to transparently convert ID to MongoDBID as ObectID.
func (o *AutomationTemplate) GetBSON() (interface{}, error) {
if o == nil {
return nil, nil
}
s := &mongoAttributesAutomationTemplate{}
s.Description = o.Description
s.Name = o.Name
return s, nil
}
// SetBSON implements the bson marshaling interface.
// This is used to transparently convert ID to MongoDBID as ObectID.
func (o *AutomationTemplate) SetBSON(raw bson.Raw) error {
if o == nil {
return nil
}
s := &mongoAttributesAutomationTemplate{}
if err := raw.Unmarshal(s); err != nil {
return err
}
o.Description = s.Description
o.Name = s.Name
return nil
}
// Version returns the hardcoded version of the model.
func (o *AutomationTemplate) Version() int {
return 1
}
// BleveType implements the bleve.Classifier Interface.
func (o *AutomationTemplate) BleveType() string {
return "automationtemplate"
}
// DefaultOrder returns the list of default ordering fields.
func (o *AutomationTemplate) DefaultOrder() []string {
return []string{
"name",
}
}
// Doc returns the documentation for the object
func (o *AutomationTemplate) Doc() string {
return `Templates that can be used in automations.`
}
func (o *AutomationTemplate) String() string {
return fmt.Sprintf("<%s:%s>", o.Identity().Name, o.Identifier())
}
// GetDescription returns the Description of the receiver.
func (o *AutomationTemplate) GetDescription() string {
return o.Description
}
// SetDescription sets the property Description of the receiver using the given value.
func (o *AutomationTemplate) SetDescription(description string) {
o.Description = description
}
// GetName returns the Name of the receiver.
func (o *AutomationTemplate) GetName() string {
return o.Name
}
// SetName sets the property Name of the receiver using the given value.
func (o *AutomationTemplate) SetName(name string) {
o.Name = name
}
// ToSparse returns the sparse version of the model.
// The returned object will only contain the given fields. No field means entire field set.
func (o *AutomationTemplate) ToSparse(fields ...string) elemental.SparseIdentifiable {
if len(fields) == 0 {
// nolint: goimports
return &SparseAutomationTemplate{
Description: &o.Description,
Entitlements: &o.Entitlements,
Function: &o.Function,
Key: &o.Key,
Kind: &o.Kind,
Name: &o.Name,
Parameters: &o.Parameters,
Steps: &o.Steps,
}
}
sp := &SparseAutomationTemplate{}
for _, f := range fields {
switch f {
case "description":
sp.Description = &(o.Description)
case "entitlements":
sp.Entitlements = &(o.Entitlements)
case "function":
sp.Function = &(o.Function)
case "key":
sp.Key = &(o.Key)
case "kind":
sp.Kind = &(o.Kind)
case "name":
sp.Name = &(o.Name)
case "parameters":
sp.Parameters = &(o.Parameters)
case "steps":
sp.Steps = &(o.Steps)
}
}
return sp
}
// Patch apply the non nil value of a *SparseAutomationTemplate to the object.
func (o *AutomationTemplate) Patch(sparse elemental.SparseIdentifiable) {
if !sparse.Identity().IsEqual(o.Identity()) {
panic("cannot patch from a parse with different identity")
}
so := sparse.(*SparseAutomationTemplate)
if so.Description != nil {
o.Description = *so.Description
}
if so.Entitlements != nil {
o.Entitlements = *so.Entitlements
}
if so.Function != nil {
o.Function = *so.Function
}
if so.Key != nil {
o.Key = *so.Key
}
if so.Kind != nil {
o.Kind = *so.Kind
}
if so.Name != nil {
o.Name = *so.Name
}
if so.Parameters != nil {
o.Parameters = *so.Parameters
}
if so.Steps != nil {
o.Steps = *so.Steps
}
}
// DeepCopy returns a deep copy if the AutomationTemplate.
func (o *AutomationTemplate) DeepCopy() *AutomationTemplate {
if o == nil {
return nil
}
out := &AutomationTemplate{}
o.DeepCopyInto(out)
return out
}
// DeepCopyInto copies the receiver into the given *AutomationTemplate.
func (o *AutomationTemplate) DeepCopyInto(out *AutomationTemplate) {
target, err := copystructure.Copy(o)
if err != nil {
panic(fmt.Sprintf("Unable to deepcopy AutomationTemplate: %s", err))
}
*out = *target.(*AutomationTemplate)
}
// Validate valides the current information stored into the structure.
func (o *AutomationTemplate) Validate() error {
errors := elemental.Errors{}
requiredErrors := elemental.Errors{}
if err := elemental.ValidateMaximumLength("description", o.Description, 1024, false); err != nil {
errors = errors.Append(err)
}
if err := elemental.ValidateStringInList("kind", string(o.Kind), []string{"Action", "Condition"}, false); err != nil {
errors = errors.Append(err)
}
if err := elemental.ValidateRequiredString("name", o.Name); err != nil {
requiredErrors = requiredErrors.Append(err)
}
if err := elemental.ValidateMaximumLength("name", o.Name, 256, false); err != nil {
errors = errors.Append(err)
}
for _, sub := range o.Steps {
if sub == nil {
continue
}
elemental.ResetDefaultForZeroValues(sub)
if err := sub.Validate(); err != nil {
errors = errors.Append(err)
}
}
if len(requiredErrors) > 0 {
return requiredErrors
}
if len(errors) > 0 {
return errors
}
return nil
}
// SpecificationForAttribute returns the AttributeSpecification for the given attribute name key.
func (*AutomationTemplate) SpecificationForAttribute(name string) elemental.AttributeSpecification {
if v, ok := AutomationTemplateAttributesMap[name]; ok {
return v
}
// We could not find it, so let's check on the lower case indexed spec map
return AutomationTemplateLowerCaseAttributesMap[name]
}
// AttributeSpecifications returns the full attribute specifications map.
func (*AutomationTemplate) AttributeSpecifications() map[string]elemental.AttributeSpecification {
return AutomationTemplateAttributesMap
}
// ValueForAttribute returns the value for the given attribute.
// This is a very advanced function that you should not need but in some
// very specific use cases.
func (o *AutomationTemplate) ValueForAttribute(name string) interface{} {
switch name {
case "description":
return o.Description
case "entitlements":
return o.Entitlements
case "function":
return o.Function
case "key":
return o.Key
case "kind":
return o.Kind
case "name":
return o.Name
case "parameters":
return o.Parameters
case "steps":
return o.Steps
}
return nil
}
// AutomationTemplateAttributesMap represents the map of attribute for AutomationTemplate.
var AutomationTemplateAttributesMap = map[string]elemental.AttributeSpecification{
"Description": {
AllowedChoices: []string{},
BSONFieldName: "description",
ConvertedName: "Description",
Description: `Description of the object.`,
Exposed: true,
Getter: true,
MaxLength: 1024,
Name: "description",
Orderable: true,
Setter: true,
Stored: true,
Type: "string",
},
"Entitlements": {
AllowedChoices: []string{},
ConvertedName: "Entitlements",
Description: `Contains the entitlements needed for executing the function.`,
Exposed: true,
Name: "entitlements",
SubType: "_automation_entitlements",
Type: "external",
},
"Function": {
AllowedChoices: []string{},
ConvertedName: "Function",
Description: `Function contains the code.`,
Exposed: true,
Name: "function",
Type: "string",
},
"Key": {
AllowedChoices: []string{},
ConvertedName: "Key",
Description: `Contains the unique identifier key for the template.`,
Exposed: true,
Name: "key",
Type: "string",
},
"Kind": {
AllowedChoices: []string{"Action", "Condition"},
ConvertedName: "Kind",
DefaultValue: AutomationTemplateKindCondition,
Description: `Represents the kind of template.`,
Exposed: true,
Name: "kind",
Type: "enum",
},
"Name": {
AllowedChoices: []string{},
BSONFieldName: "name",
ConvertedName: "Name",
Description: `Name of the entity.`,
Exposed: true,
Filterable: true,
Getter: true,
MaxLength: 256,
Name: "name",
Orderable: true,
Required: true,
Setter: true,
Stored: true,
Type: "string",
},
"Parameters": {
AllowedChoices: []string{},
ConvertedName: "Parameters",
Description: `Contains the computed parameters.`,
Exposed: true,
Name: "parameters",
SubType: "map[string]interface{}",
Type: "external",
},
"Steps": {
AllowedChoices: []string{},
ConvertedName: "Steps",
Description: `Contains all the steps with parameters.`,
Exposed: true,
Name: "steps",
SubType: "uistep",
Type: "refList",
},
}
// AutomationTemplateLowerCaseAttributesMap represents the map of attribute for AutomationTemplate.
var AutomationTemplateLowerCaseAttributesMap = map[string]elemental.AttributeSpecification{
"description": {
AllowedChoices: []string{},
BSONFieldName: "description",
ConvertedName: "Description",
Description: `Description of the object.`,
Exposed: true,
Getter: true,
MaxLength: 1024,
Name: "description",
Orderable: true,
Setter: true,
Stored: true,
Type: "string",
},
"entitlements": {
AllowedChoices: []string{},
ConvertedName: "Entitlements",
Description: `Contains the entitlements needed for executing the function.`,
Exposed: true,
Name: "entitlements",
SubType: "_automation_entitlements",
Type: "external",
},
"function": {
AllowedChoices: []string{},
ConvertedName: "Function",
Description: `Function contains the code.`,
Exposed: true,
Name: "function",
Type: "string",
},
"key": {
AllowedChoices: []string{},
ConvertedName: "Key",
Description: `Contains the unique identifier key for the template.`,
Exposed: true,
Name: "key",
Type: "string",
},
"kind": {
AllowedChoices: []string{"Action", "Condition"},
ConvertedName: "Kind",
DefaultValue: AutomationTemplateKindCondition,
Description: `Represents the kind of template.`,
Exposed: true,
Name: "kind",
Type: "enum",
},
"name": {
AllowedChoices: []string{},
BSONFieldName: "name",
ConvertedName: "Name",
Description: `Name of the entity.`,
Exposed: true,
Filterable: true,
Getter: true,
MaxLength: 256,
Name: "name",
Orderable: true,
Required: true,
Setter: true,
Stored: true,
Type: "string",
},
"parameters": {
AllowedChoices: []string{},
ConvertedName: "Parameters",
Description: `Contains the computed parameters.`,
Exposed: true,
Name: "parameters",
SubType: "map[string]interface{}",
Type: "external",
},
"steps": {
AllowedChoices: []string{},
ConvertedName: "Steps",
Description: `Contains all the steps with parameters.`,
Exposed: true,
Name: "steps",
SubType: "uistep",
Type: "refList",
},
}
// SparseAutomationTemplatesList represents a list of SparseAutomationTemplates
type SparseAutomationTemplatesList []*SparseAutomationTemplate
// Identity returns the identity of the objects in the list.
func (o SparseAutomationTemplatesList) Identity() elemental.Identity {
return AutomationTemplateIdentity
}
// Copy returns a pointer to a copy the SparseAutomationTemplatesList.
func (o SparseAutomationTemplatesList) Copy() elemental.Identifiables {
copy := append(SparseAutomationTemplatesList{}, o...)
return ©
}
// Append appends the objects to the a new copy of the SparseAutomationTemplatesList.
func (o SparseAutomationTemplatesList) Append(objects ...elemental.Identifiable) elemental.Identifiables {
out := append(SparseAutomationTemplatesList{}, o...)
for _, obj := range objects {
out = append(out, obj.(*SparseAutomationTemplate))
}
return out
}
// List converts the object to an elemental.IdentifiablesList.
func (o SparseAutomationTemplatesList) List() elemental.IdentifiablesList {
out := make(elemental.IdentifiablesList, len(o))
for i := 0; i < len(o); i++ {
out[i] = o[i]
}
return out
}
// DefaultOrder returns the default ordering fields of the content.
func (o SparseAutomationTemplatesList) DefaultOrder() []string {
return []string{
"name",
}
}
// ToPlain returns the SparseAutomationTemplatesList converted to AutomationTemplatesList.
func (o SparseAutomationTemplatesList) ToPlain() elemental.IdentifiablesList {
out := make(elemental.IdentifiablesList, len(o))
for i := 0; i < len(o); i++ {
out[i] = o[i].ToPlain()
}
return out
}
// Version returns the version of the content.
func (o SparseAutomationTemplatesList) Version() int {
return 1
}
// SparseAutomationTemplate represents the sparse version of a automationtemplate.
type SparseAutomationTemplate struct {
// Description of the object.
Description *string `json:"description,omitempty" msgpack:"description,omitempty" bson:"description,omitempty" mapstructure:"description,omitempty"`
// Contains the entitlements needed for executing the function.
Entitlements *map[string][]elemental.Operation `json:"entitlements,omitempty" msgpack:"entitlements,omitempty" bson:"-" mapstructure:"entitlements,omitempty"`
// Function contains the code.
Function *string `json:"function,omitempty" msgpack:"function,omitempty" bson:"-" mapstructure:"function,omitempty"`
// Contains the unique identifier key for the template.
Key *string `json:"key,omitempty" msgpack:"key,omitempty" bson:"-" mapstructure:"key,omitempty"`
// Represents the kind of template.
Kind *AutomationTemplateKindValue `json:"kind,omitempty" msgpack:"kind,omitempty" bson:"-" mapstructure:"kind,omitempty"`
// Name of the entity.
Name *string `json:"name,omitempty" msgpack:"name,omitempty" bson:"name,omitempty" mapstructure:"name,omitempty"`
// Contains the computed parameters.
Parameters *map[string]interface{} `json:"parameters,omitempty" msgpack:"parameters,omitempty" bson:"-" mapstructure:"parameters,omitempty"`
// Contains all the steps with parameters.
Steps *[]*UIStep `json:"steps,omitempty" msgpack:"steps,omitempty" bson:"-" mapstructure:"steps,omitempty"`
ModelVersion int `json:"-" msgpack:"-" bson:"_modelversion"`
}
// NewSparseAutomationTemplate returns a new SparseAutomationTemplate.
func NewSparseAutomationTemplate() *SparseAutomationTemplate {
return &SparseAutomationTemplate{}
}
// Identity returns the Identity of the sparse object.
func (o *SparseAutomationTemplate) Identity() elemental.Identity {
return AutomationTemplateIdentity
}
// Identifier returns the value of the sparse object's unique identifier.
func (o *SparseAutomationTemplate) Identifier() string {
return ""
}
// SetIdentifier sets the value of the sparse object's unique identifier.
func (o *SparseAutomationTemplate) SetIdentifier(id string) {
}
// GetBSON implements the bson marshaling interface.
// This is used to transparently convert ID to MongoDBID as ObectID.
func (o *SparseAutomationTemplate) GetBSON() (interface{}, error) {
if o == nil {
return nil, nil
}
s := &mongoAttributesSparseAutomationTemplate{}
if o.Description != nil {
s.Description = o.Description
}
if o.Name != nil {
s.Name = o.Name
}
return s, nil
}
// SetBSON implements the bson marshaling interface.
// This is used to transparently convert ID to MongoDBID as ObectID.
func (o *SparseAutomationTemplate) SetBSON(raw bson.Raw) error {
if o == nil {
return nil
}
s := &mongoAttributesSparseAutomationTemplate{}
if err := raw.Unmarshal(s); err != nil {
return err
}
if s.Description != nil {
o.Description = s.Description
}
if s.Name != nil {
o.Name = s.Name
}
return nil
}
// Version returns the hardcoded version of the model.
func (o *SparseAutomationTemplate) Version() int {
return 1
}
// ToPlain returns the plain version of the sparse model.
func (o *SparseAutomationTemplate) ToPlain() elemental.PlainIdentifiable {
out := NewAutomationTemplate()
if o.Description != nil {
out.Description = *o.Description
}
if o.Entitlements != nil {
out.Entitlements = *o.Entitlements
}
if o.Function != nil {
out.Function = *o.Function
}
if o.Key != nil {
out.Key = *o.Key
}
if o.Kind != nil {
out.Kind = *o.Kind
}
if o.Name != nil {
out.Name = *o.Name
}
if o.Parameters != nil {
out.Parameters = *o.Parameters
}
if o.Steps != nil {
out.Steps = *o.Steps
}
return out
}
// GetDescription returns the Description of the receiver.
func (o *SparseAutomationTemplate) GetDescription() (out string) {
if o.Description == nil {
return
}
return *o.Description
}
// SetDescription sets the property Description of the receiver using the address of the given value.
func (o *SparseAutomationTemplate) SetDescription(description string) {
o.Description = &description
}
// GetName returns the Name of the receiver.
func (o *SparseAutomationTemplate) GetName() (out string) {
if o.Name == nil {
return
}
return *o.Name
}
// SetName sets the property Name of the receiver using the address of the given value.
func (o *SparseAutomationTemplate) SetName(name string) {
o.Name = &name
}
// DeepCopy returns a deep copy if the SparseAutomationTemplate.
func (o *SparseAutomationTemplate) DeepCopy() *SparseAutomationTemplate {
if o == nil {
return nil
}
out := &SparseAutomationTemplate{}
o.DeepCopyInto(out)
return out
}
// DeepCopyInto copies the receiver into the given *SparseAutomationTemplate.
func (o *SparseAutomationTemplate) DeepCopyInto(out *SparseAutomationTemplate) {
target, err := copystructure.Copy(o)
if err != nil {
panic(fmt.Sprintf("Unable to deepcopy SparseAutomationTemplate: %s", err))
}
*out = *target.(*SparseAutomationTemplate)
}
type mongoAttributesAutomationTemplate struct {
Description string `bson:"description"`
Name string `bson:"name"`
}
type mongoAttributesSparseAutomationTemplate struct {
Description *string `bson:"description,omitempty"`
Name *string `bson:"name,omitempty"`
}
|
Testiduk/gitlabhq | spec/lib/gitlab/ci/reports/security/vulnerability_reports_comparer_spec.rb | <filename>spec/lib/gitlab/ci/reports/security/vulnerability_reports_comparer_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe Gitlab::Ci::Reports::Security::VulnerabilityReportsComparer do
let(:identifier) { build(:ci_reports_security_identifier) }
let_it_be(:project) { create(:project, :repository) }
let(:location_param) { build(:ci_reports_security_locations_sast, :dynamic) }
let(:vulnerability_params) { vuln_params(project.id, [identifier], confidence: :low, severity: :critical) }
let(:base_vulnerability) { build(:ci_reports_security_finding, location: location_param, **vulnerability_params) }
let(:base_report) { build(:ci_reports_security_aggregated_reports, findings: [base_vulnerability]) }
let(:head_vulnerability) { build(:ci_reports_security_finding, location: location_param, uuid: base_vulnerability.uuid, **vulnerability_params) }
let(:head_report) { build(:ci_reports_security_aggregated_reports, findings: [head_vulnerability]) }
shared_context 'comparing reports' do
let(:vul_params) { vuln_params(project.id, [identifier]) }
let(:base_vulnerability) { build(:ci_reports_security_finding, :dynamic, **vul_params) }
let(:head_vulnerability) { build(:ci_reports_security_finding, :dynamic, **vul_params) }
let(:head_vul_findings) { [head_vulnerability, vuln] }
end
subject { described_class.new(project, base_report, head_report) }
where(vulnerability_finding_signatures: [true, false])
with_them do
before do
stub_licensed_features(vulnerability_finding_signatures: vulnerability_finding_signatures)
end
describe '#base_report_out_of_date' do
context 'no base report' do
let(:base_report) { build(:ci_reports_security_aggregated_reports, reports: [], findings: []) }
it 'is not out of date' do
expect(subject.base_report_out_of_date).to be false
end
end
context 'base report older than one week' do
let(:report) { build(:ci_reports_security_report, created_at: 1.week.ago - 60.seconds) }
let(:base_report) { build(:ci_reports_security_aggregated_reports, reports: [report]) }
it 'is not out of date' do
expect(subject.base_report_out_of_date).to be true
end
end
context 'base report less than one week old' do
let(:report) { build(:ci_reports_security_report, created_at: 1.week.ago + 60.seconds) }
let(:base_report) { build(:ci_reports_security_aggregated_reports, reports: [report]) }
it 'is not out of date' do
expect(subject.base_report_out_of_date).to be false
end
end
end
describe '#added' do
let(:new_location) {build(:ci_reports_security_locations_sast, :dynamic) }
let(:vul_params) { vuln_params(project.id, [identifier], confidence: :high) }
let(:vuln) { build(:ci_reports_security_finding, severity: Enums::Vulnerability.severity_levels[:critical], location: new_location, **vul_params) }
let(:low_vuln) { build(:ci_reports_security_finding, severity: Enums::Vulnerability.severity_levels[:low], location: new_location, **vul_params) }
context 'with new vulnerability' do
let(:head_report) { build(:ci_reports_security_aggregated_reports, findings: [head_vulnerability, vuln]) }
it 'points to source tree' do
expect(subject.added).to eq([vuln])
end
end
context 'when comparing reports with different fingerprints' do
include_context 'comparing reports'
let(:head_report) { build(:ci_reports_security_aggregated_reports, findings: head_vul_findings) }
it 'does not find any overlap' do
expect(subject.added).to eq(head_vul_findings)
end
end
context 'order' do
let(:head_report) { build(:ci_reports_security_aggregated_reports, findings: [head_vulnerability, vuln, low_vuln]) }
it 'does not change' do
expect(subject.added).to eq([vuln, low_vuln])
end
end
end
describe '#fixed' do
let(:vul_params) { vuln_params(project.id, [identifier]) }
let(:vuln) { build(:ci_reports_security_finding, :dynamic, **vul_params ) }
let(:medium_vuln) { build(:ci_reports_security_finding, confidence: ::Enums::Vulnerability.confidence_levels[:high], severity: Enums::Vulnerability.severity_levels[:medium], uuid: vuln.uuid, **vul_params) }
context 'with fixed vulnerability' do
let(:base_report) { build(:ci_reports_security_aggregated_reports, findings: [base_vulnerability, vuln]) }
it 'points to base tree' do
expect(subject.fixed).to eq([vuln])
end
end
context 'when comparing reports with different fingerprints' do
include_context 'comparing reports'
let(:base_report) { build(:ci_reports_security_aggregated_reports, findings: [base_vulnerability, vuln]) }
it 'does not find any overlap' do
expect(subject.fixed).to eq([base_vulnerability, vuln])
end
end
context 'order' do
let(:vul_findings) { [vuln, medium_vuln] }
let(:base_report) { build(:ci_reports_security_aggregated_reports, findings: [*vul_findings, base_vulnerability]) }
it 'does not change' do
expect(subject.fixed).to eq(vul_findings)
end
end
end
describe 'with empty vulnerabilities' do
let(:empty_report) { build(:ci_reports_security_aggregated_reports, reports: [], findings: []) }
it 'returns empty array when reports are not present' do
comparer = described_class.new(project, empty_report, empty_report)
expect(comparer.fixed).to eq([])
expect(comparer.added).to eq([])
end
it 'returns added vulnerability when base is empty and head is not empty' do
comparer = described_class.new(project, empty_report, head_report)
expect(comparer.fixed).to eq([])
expect(comparer.added).to eq([head_vulnerability])
end
it 'returns fixed vulnerability when head is empty and base is not empty' do
comparer = described_class.new(project, base_report, empty_report)
expect(comparer.fixed).to eq([base_vulnerability])
expect(comparer.added).to eq([])
end
end
end
def vuln_params(project_id, identifiers, confidence: :high, severity: :critical)
{
project_id: project_id,
report_type: :sast,
identifiers: identifiers,
confidence: ::Enums::Vulnerability.confidence_levels[confidence],
severity: ::Enums::Vulnerability.severity_levels[severity]
}
end
end
|
ethansaxenian/RosettaDecode | lang/C/queue-definition-3.c | int main()
{
int i, n;
queue q = q_new();
for (i = 0; i < 100000000; i++) {
n = rand();
if (n > RAND_MAX / 2) {
// printf("+ %d\n", n);
enqueue(q, n);
} else {
if (!dequeue(q, &n)) {
// printf("empty\n");
continue;
}
// printf("- %d\n", n);
}
}
while (dequeue(q, &n));// printf("- %d\n", n);
return 0;
}
|
niekert/TranslateQL | src/components/NavLink.js | <reponame>niekert/TranslateQL<gh_stars>0
import { NavLink } from 'react-router-dom';
import styled from 'styled-components';
import { prop } from 'styled-tools';
const StyledNavLink = styled(NavLink).attrs({
activeClassName: 'active',
})`
color: green;
text-decoration: none;
&.active {
color: ${prop('theme.color.primary')};
}
`;
export default StyledNavLink;
|
lygyuyun/SmartCity | app/src/main/java/com/tourcool/core/module/activity/BaseWebActivity.java | <reponame>lygyuyun/SmartCity
package com.tourcool.core.module.activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import androidx.annotation.ColorInt;
import androidx.core.content.ContextCompat;
import com.frame.library.core.UiManager;
import com.frame.library.core.control.TitleBarViewControl;
import com.frame.library.core.module.activity.FrameTitleActivity;
import com.frame.library.core.util.FrameUtil;
import com.frame.library.core.util.ToastUtil;
import com.aries.ui.helper.navigation.NavigationViewHelper;
import com.aries.ui.util.DrawableUtil;
import com.aries.ui.widget.BasisDialog;
import com.aries.ui.widget.action.sheet.UIActionSheetDialog;
import com.aries.ui.widget.i.NavigationBarControl;
import com.frame.library.core.widget.titlebar.TitleBarView;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.DefaultWebCreator;
import com.just.agentweb.MiddlewareWebChromeBase;
import com.tourcool.smartcity.R;
/**
* @Author: JenkinsZhou on 2018/6/28 14:59
* @E-Mail: <EMAIL>
* Function: App内快速实现WebView功能
* Description:
* 1、调整WebView自适应屏幕代码属性{@link #initAgentWeb()}
* 2、2019-3-20 11:45:07 增加url自动添加http://功能及规范url
*/
public abstract class BaseWebActivity extends FrameTitleActivity implements NavigationBarControl {
protected ViewGroup mContainer;
/**
* {@use mUrl}
*/
@Deprecated
protected String url = "";
protected String mUrl = "";
protected String mCurrentUrl;
protected AlertDialog mAlertDialog;
protected AgentWeb mAgentWeb;
protected AgentWeb.CommonBuilder mAgentBuilder;
protected UIActionSheetDialog mActionSheetView;
private TitleBarViewControl mTitleBarViewControl;
/**
* WebView是否处于暂停状态
*/
private boolean mIsPause;
public void onWebViewPause() {
onPause();
}
public void onWebViewResume() {
onResume();
}
protected static void start(Context mActivity, Class<? extends BaseWebActivity> activity, String url) {
Bundle bundle = new Bundle();
bundle.putString("url", url);
FrameUtil.startActivity(mActivity, activity, bundle);
}
protected void setAgentWeb(AgentWeb mAgentWeb) {
}
protected void setAgentWeb(AgentWeb.CommonBuilder mAgentBuilder) {
}
/**
* 设置进度条颜色
*
* @return
*/
@ColorInt
protected int getProgressColor() {
return -1;
}
/**
* 设置进度条高度 注意此处最终AgentWeb会将其作为float 转dp2px
* {@link DefaultWebCreator#createWebView()} height_dp}
*
* @return
*/
protected int getProgressHeight() {
return 2;
}
@Override
public void beforeSetContentView() {
super.beforeSetContentView();
mTitleBarViewControl = UiManager.getInstance().getTitleBarViewControl();
}
@Override
public void beforeInitView(Bundle savedInstanceState) {
mContainer = findViewById(R.id.lLayout_containerFastWeb);
mUrl = getIntent().getStringExtra("url");
if (!TextUtils.isEmpty(mUrl)) {
mUrl = mUrl.startsWith("http") ? mUrl : "http://" + mUrl;
getIntent().putExtra("url", mUrl);
}
url = mUrl;
mCurrentUrl = mUrl;
initAgentWeb();
super.beforeInitView(savedInstanceState);
}
@Override
public void beforeSetTitleBar(TitleBarView titleBar) {
super.beforeSetTitleBar(titleBar);
if (mTitleBarViewControl != null) {
mTitleBarViewControl.createTitleBarViewControl(titleBar, this.getClass());
}
titleBar.setOnLeftTextClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
})
.setRightTextDrawable(DrawableUtil.setTintDrawable(
ContextCompat.getDrawable(mContext, R.drawable.fast_ic_more),
ContextCompat.getColor(mContext, R.color.colorTitleText)))
.setOnRightTextClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showActionSheet();
}
})
.addLeftAction(titleBar.new ImageAction(
DrawableUtil.setTintDrawable(ContextCompat.getDrawable(mContext, R.drawable.fast_ic_close),
ContextCompat.getColor(mContext, R.color.colorTitleText)), new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog();
}
}));
}
@Override
public int getContentLayout() {
return R.layout.frame_activity_base_web;
}
protected void initAgentWeb() {
mAgentBuilder = AgentWeb.with(this)
.setAgentWebParent(mContainer, new ViewGroup.LayoutParams(-1, -1))
.useDefaultIndicator(getProgressColor() != -1 ? getProgressColor() : ContextCompat.getColor(mContext, R.color.colorTitleText),
getProgressHeight())
.useMiddlewareWebChrome(new MiddlewareWebChromeBase(){
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
mCurrentUrl = view.getUrl();
mTitleBar.setTitleMainText(title);
}
})
.setSecurityType(AgentWeb.SecurityType.STRICT_CHECK);
setAgentWeb(mAgentBuilder);
mAgentWeb = mAgentBuilder
.createAgentWeb()//
.ready()
.go(mUrl);
WebSettings webSettings = mAgentWeb.getAgentWebSettings().getWebSettings();
//设置webView自适应屏幕
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
setAgentWeb(mAgentWeb);
}
protected void showDialog() {
if (mAlertDialog == null) {
mAlertDialog = new AlertDialog.Builder(this)
.setTitle(R.string.fast_web_alert_title)
.setMessage(R.string.fast_web_alert_msg)
.setNegativeButton(R.string.fast_web_alert_left, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (mAlertDialog != null) {
mAlertDialog.dismiss();
}
}
})
.setPositiveButton(R.string.fast_web_alert_right, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (mAlertDialog != null) {
mAlertDialog.dismiss();
}
mContext.finish();
}
}).create();
}
mAlertDialog.show();
//show之后可获取对应Button对象设置文本颜色--show之前获取对象为null
mAlertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setTextColor(Color.RED);
}
protected void showActionSheet() {
if (mActionSheetView == null) {
mActionSheetView = new UIActionSheetDialog.ListSheetBuilder(mContext)
.addItems(R.array.fast_arrays_web_more)
.setOnItemClickListener(new UIActionSheetDialog.OnItemClickListener() {
@Override
public void onClick(BasisDialog dialog, View itemView, int i) {
switch (i) {
case 0:
mAgentWeb.getUrlLoader().reload();
break;
case 1:
FrameUtil.copyToClipboard(mContext, mCurrentUrl);
ToastUtil.show(R.string.fast_copy_success);
break;
case 2:
FrameUtil.startShareText(mContext, mCurrentUrl);
break;
}
}
})
.setCancel(R.string.fast_cancel)
.setTextSizeUnit(TypedValue.COMPLEX_UNIT_DIP)
.create();
}
mActionSheetView.setNavigationBarControl(this);
mActionSheetView.show();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mAgentWeb.handleKeyEvent(keyCode, event)) {
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onBackPressed() {
if (mAgentWeb != null && mAgentWeb.back()) {
return;
}
super.onBackPressed();
}
@Override
protected void onPause() {
if (mAgentWeb != null && mAgentWeb.getWebLifeCycle() != null && !mIsPause && !isFinishing()) {
mAgentWeb.getWebLifeCycle().onPause();
mIsPause = true;
}
super.onPause();
}
@Override
protected void onResume() {
if (mAgentWeb != null && mAgentWeb.getWebLifeCycle() != null && mIsPause) {
mAgentWeb.getWebLifeCycle().onResume();
mIsPause = false;
}
super.onResume();
}
@Override
protected void onDestroy() {
if (mAgentWeb != null && mAgentWeb.getWebLifeCycle() != null) {
mAgentWeb.getWebLifeCycle().onDestroy();
}
super.onDestroy();
}
@Override
public boolean setNavigationBar(Dialog dialog, NavigationViewHelper helper, View bottomView) {
return false;
}
}
|
electricalwind/tuna | joern/src/main/java/ast/expressions/SizeofExpr.java | package ast.expressions;
import ast.walking.ASTNodeVisitor;
public class SizeofExpr extends Expression {
public void accept(ASTNodeVisitor visitor) {
visitor.visit(this);
}
}
|
josuerf/rf-online-gs-editor | src/containers/App/sagas/projectExport/serverBoxItemOutResolve.js | <filename>src/containers/App/sagas/projectExport/serverBoxItemOutResolve.js
import { delay } from 'redux-saga';
import { put } from 'redux-saga/effects';
import gql from 'graphql-tag';
import path from 'path';
import {
TOTAL_SIZE,
BLOCK_SIZE,
COUNT,
COUNT_COLUMNS,
} from '~/classes/constants';
import Struct from '~/classes/Struct';
import BufferGenerator from '~/classes/BufferGenerator';
import serverBoxItemOutReaderStruct from '~/structs/server/boxItemOut/reader_struct';
import { getReleaseFilesPath } from '~/utils/path';
import { mkdirSync, writeFile } from '~/utils/fs';
import { RELEASE_FILES_SERVER_FOLDER } from '~/utils/constants';
import apolloClient from '~/apollo';
import projectBoxItemOutsTotalQuery from '~/apollo/queries/sub/boxItemOuts_total';
function buildQueryObjects(fieldNames = []) {
return gql`
query($take: Int, $skip: Int, $sort: JSON, $where: JSON) {
boxItemOuts(take: $take, skip: $skip, sort: $sort, where: $where) {
items {
id
${fieldNames instanceof Array ? fieldNames.join('\n') : fieldNames}
}
total
}
}
`;
}
function* loadObjects({ projectId, fieldNames, loaded, changeLoaded }) {
let nextLoaded = loaded;
const objects = [];
const QUERY_OBJECTS = buildQueryObjects(fieldNames);
// eslint-disable-next-line
while (true) {
const result = yield apolloClient.query({
query: QUERY_OBJECTS,
variables: {
skip: objects.length,
take: 100,
sort: { nIndex: 1 },
where: { projectId },
},
});
objects.push(...result.data.boxItemOuts.items);
nextLoaded += result.data.boxItemOuts.items.length;
yield put(changeLoaded(nextLoaded));
if (result.data.boxItemOuts.items.length <= 0) {
break;
}
}
return objects;
}
function fillBuffer(
bufferGenerator,
{ block, header },
objects = [],
fnValues,
) {
const blockFields = block.getFields();
const headerFields = header instanceof Struct ? header.getFields() : header;
const headerValues = {
[TOTAL_SIZE]: block.getWeight() * objects.length + 8,
[BLOCK_SIZE]: block.getWeight(),
[COUNT]: objects.length,
[COUNT_COLUMNS]: blockFields.length,
};
headerFields.forEach(field => {
bufferGenerator.addByField(field, headerValues[field.getName()]);
});
const buffers = [];
objects.forEach(object => {
const values = typeof fnValues === 'function' ? fnValues(object) : {};
const buffer = new BufferGenerator();
blockFields.forEach(field => {
buffer.addByField(field, values[field.getName()], undefined, values);
});
buffers.push(buffer.getBuffer());
});
bufferGenerator.concat(...buffers);
}
/**
* Export Server Items Resolver
*/
export default function* defaultSaga({
projectId,
actions,
fileData,
releasePath,
}) {
yield delay(1000);
const readerStruct = serverBoxItemOutReaderStruct;
const total = yield apolloClient.query({
query: projectBoxItemOutsTotalQuery,
variables: { where: { projectId } },
});
yield put(actions.changeTotal(total.data.boxItemOuts.total));
let i = 0;
let loaded = 0;
const bufferGenerator = new BufferGenerator();
while (readerStruct.length > i) {
const objects = yield loadObjects({
projectId,
fieldNames: readerStruct[i].block.getFieldNames(),
loaded,
changeLoaded: actions.changeLoaded,
});
loaded += objects.length;
fillBuffer(bufferGenerator, readerStruct[i], objects, object => object);
i += 1;
}
const parsePath = path.parse(fileData.path);
const fileDir = parsePath.dir;
yield mkdirSync(
getReleaseFilesPath(releasePath, RELEASE_FILES_SERVER_FOLDER, fileDir),
);
yield writeFile(
getReleaseFilesPath(
releasePath,
RELEASE_FILES_SERVER_FOLDER,
fileDir,
parsePath.base,
),
bufferGenerator.getBuffer(),
);
}
|
Sushiwave/graphics-lib | src/GraphicsLib/Graphics/GPUResource/ShaderResource/Texture/Texture2D/D3D11/Components/RawTexture/D3D11RawTexture2D.cpp | <gh_stars>1-10
#include "D3D11RawTexture2D.hpp"
#include <Graphics/Components/D3D11/Device/D3D11Device.hpp>
#include <Graphics/GPUResource/Helper/D3D11/D3D11CreateFunctions.hpp>
#include <GraphicsLib/Graphics/GPUState/GPUStateRecorder.hpp>
#include <ThirdParty/DirectXTex/DirectXTex.h>
#include <limits>
#define MAX_TEXTURE_FILENAME_STR_SIZE 256
#define SHADERSTAGE_NUM 6
namespace cg
{
namespace d3d11
{
RawTexture2D::RawTexture2D(cpp::com_ptr<ID3D11Texture2D> textureBuffer, bool isResolvedTexture, TextureFormat format, int mostDetailedMipLevel, const Resolver& resolver)
: m_textureBuffer(textureBuffer),
m_format(format),
m_resolve(resolver),
m_isResolvedTexture(isResolvedTexture)
{
auto desc = D3D11CreateFunctions::fetchTexture2DDescFrom(textureBuffer.Get());
desc.Format = static_cast<DXGI_FORMAT>(format);
m_cpuAccessType = static_cast<CPUAccessType>(desc.CPUAccessFlags);
m_size = cpp::Vector2D<int>(desc.Width, desc.Height);
m_mostDetailedMipLevel = mostDetailedMipLevel;
m_mostRoughedMipLevel = m_mostDetailedMipLevel+desc.MipLevels-1;
m_cpuAccessType = static_cast<CPUAccessType>(desc.CPUAccessFlags);
switch (desc.Usage)
{
case D3D11_USAGE_STAGING:
m_gpuAccessType = GPUAccessType::none;
break;
case D3D11_USAGE_IMMUTABLE:
m_gpuAccessType = GPUAccessType::R;
break;
default:
m_gpuAccessType = GPUAccessType::RW;
break;
}
if (desc.BindFlags & D3D11_BIND_SHADER_RESOURCE)
{
cpp::com_ptr<ID3D11ShaderResourceView> cpSRV;
auto hr = D3D11CreateFunctions::createTexture2DSRV(Device::getDevice().Get(), desc, mostDetailedMipLevel, textureBuffer.Get(), cpSRV.ReleaseAndGetAddressOf());
if(FAILED(hr))
{
throw COM_RUNTIME_ERROR(hr, "Failed to create ShaderResourceView.");
}
m_SRV = std::make_shared<ShaderResourceView>(ShaderResourceType::Texture, cpSRV);
if (desc.BindFlags & D3D11_BIND_UNORDERED_ACCESS)
{
cpp::com_ptr<ID3D11UnorderedAccessView> cpUAV;
hr = D3D11CreateFunctions::createTexture2DUAV(Device::getDevice().Get(), desc, textureBuffer.Get(), cpUAV.ReleaseAndGetAddressOf());
if(FAILED(hr))
{
throw COM_RUNTIME_ERROR(hr, "Failed to create UnorderedAccessView.");
}
m_UAV = std::make_shared<UnorderedAccessView>(ShaderResourceType::Texture, cpUAV);
}
}
}
RawTexture2D::RawTexture2D(cpp::com_ptr<ID3D11Texture2D> textureBuffer, int mostDetailedMipLevel)
: RawTexture2D(textureBuffer, static_cast<TextureFormat>(D3D11CreateFunctions::fetchTexture2DDescFrom(textureBuffer.Get()).Format), mostDetailedMipLevel)
{
}
RawTexture2D::RawTexture2D(cpp::com_ptr<ID3D11Texture2D> textureBuffer, TextureFormat format, int mostDetailedMipLevel)
: RawTexture2D(textureBuffer, false, format, mostDetailedMipLevel, []() {})
{
}
RawTexture2D::RawTexture2D(cpp::com_ptr<ID3D11Texture2D> textureBuffer, bool isResolvedTexture, int mostDetailedMipLevel, const Resolver& resolver
)
: RawTexture2D(textureBuffer, isResolvedTexture, static_cast<TextureFormat>(D3D11CreateFunctions::fetchTexture2DDescFrom(textureBuffer.Get()).Format), mostDetailedMipLevel, resolver)
{
}
RawTexture2D::RawTexture2D(int width, int height, TextureFormat format, CPUAccessType cpuAccessType, GPUAccessType gpuAccessType, int mostDetailedMipLevel, int mostRoughedMipLevel, bool useMipMap, const ImageXY* pImage)
: RawTexture2D([&]()
{
D3D11_SUBRESOURCE_DATA* pData = nullptr;
D3D11_SUBRESOURCE_DATA data;
if (pImage)
{
Assert(pImage->getSize() == cpp::Vector2D<int>(width, height), "The size of Texture2D must be the same as the size of ImageXY.");
auto dxgiFormat = static_cast<DXGI_FORMAT>(m_format);
auto dimension = D3D11CreateFunctions::checkTextureColorDimension(dxgiFormat);
auto precision = D3D11CreateFunctions::checkTexturePrecision(dxgiFormat);
int byteStride = 0;
switch (precision)
{
case TexturePrecision::Float32:
case TexturePrecision::Float16:
data.pSysMem = pImage->create1DArray<float>(dimension, true).get();
byteStride = sizeof(float);
break;
case TexturePrecision::Int32:
data.pSysMem = pImage->create1DArray<int32_t>(dimension, true).get();
byteStride = sizeof(int32_t);
break;
case TexturePrecision::Int16:
data.pSysMem = pImage->create1DArray<int16_t>(dimension, true).get();
byteStride = sizeof(int16_t);
break;
case TexturePrecision::Int8:
data.pSysMem = pImage->create1DArray<int8_t>(dimension, true).get();
byteStride = sizeof(int8_t);
break;
case TexturePrecision::UInt32:
data.pSysMem = pImage->create1DArray<uint32_t>(dimension, true).get();
byteStride = sizeof(uint32_t);
break;
case TexturePrecision::UInt16:
data.pSysMem = pImage->create1DArray<uint16_t>(dimension, true).get();
byteStride = sizeof(uint16_t);
break;
case TexturePrecision::UInt8:
data.pSysMem = pImage->create1DArray<uint8_t>(dimension, true).get();
byteStride = sizeof(uint8_t);
break;
default:
Assert(false, "The given TexturePrecision is not supported.");
break;
}
data.SysMemPitch = m_size.x*dimension*byteStride;
data.SysMemSlicePitch = 0;
pData = &data;
}
D3D11_TEXTURE2D_DESC desc;
auto pDevice = Device::getDevice().Get();
cpp::com_ptr<ID3D11Texture2D> textureBuffer;
D3D11CreateFunctions::createTexture2DDesc(pDevice, width, height, static_cast<DXGI_FORMAT>(format), cpuAccessType, gpuAccessType, mostDetailedMipLevel, mostRoughedMipLevel, useMipMap, 1, RawTexture2DType::Texture, &desc);
auto hr = D3D11CreateFunctions::createTexture2D(pDevice, desc, pData, textureBuffer.ReleaseAndGetAddressOf());
if(FAILED(hr))
{
throw COM_RUNTIME_ERROR(hr, "Failed to create a buffer for Texture2D.");
}
return textureBuffer;
}(),
mostDetailedMipLevel)
{
}
RawTexture2D::RawTexture2D(const std::string& filename, CPUAccessType cpuAccessType, GPUAccessType gpuAccessType, bool forceSRGB)
: RawTexture2D([&]()
{
auto pDevice = Device::getDevice().Get();
DirectX::ScratchImage scratchImage;
cpp::com_ptr<ID3D11ShaderResourceView> cpSRV;
cpp::com_ptr<ID3D11Texture2D> textureBuffer;
auto hr = D3D11CreateFunctions::createScratchImage(pDevice, filename, &scratchImage);
if(FAILED(hr))
{
throw COM_RUNTIME_ERROR(hr, "Failed to create ScratchImage from " + filename + ".");
}
hr = D3D11CreateFunctions::createTexture2D(pDevice, scratchImage, RawTexture2DType::Texture, cpuAccessType, gpuAccessType, forceSRGB, textureBuffer.ReleaseAndGetAddressOf());
if(FAILED(hr))
{
throw COM_RUNTIME_ERROR(hr, "Failed to create a buffer for Texture2D from " + filename + ".");
}
return textureBuffer;
}(),
0)
{
}
RawTexture2D::RawTexture2D(const std::string& filename, bool forceSRGB)
: RawTexture2D(filename, CPUAccessType::none, GPUAccessType::RW, forceSRGB)
{
}
RawTexture2D::RawTexture2D(int width, int height, TextureFormat format, const ImageXY* pImage)
: RawTexture2D(width, height, format, CPUAccessType::none, GPUAccessType::RW, 0, 0, false, pImage)
{
}
RawTexture2D::RawTexture2D(int width, int height, TextureFormat format, CPUAccessType cpuAccessType, GPUAccessType gpuAccessType, const ImageXY* pImage)
: RawTexture2D(width , height, format, cpuAccessType, gpuAccessType, 0, 0, false, pImage)
{
}
RawTexture2D::RawTexture2D(int width, int height, TextureFormat format, int mostDetailedMipLevel, int mostRoughedMipLevel, const ImageXY* pImage)
: RawTexture2D(width, height, format, CPUAccessType::none, GPUAccessType::RW, mostDetailedMipLevel, mostRoughedMipLevel, pImage)
{
}
RawTexture2D::RawTexture2D(int width, int height, TextureFormat format, CPUAccessType cpuAccessType, GPUAccessType gpuAccessType, int mostDetailedMipLevel, int mostRoughedMipLevel, const ImageXY* pImage)
: RawTexture2D(width, height, format, cpuAccessType, gpuAccessType, mostDetailedMipLevel, mostRoughedMipLevel, true, pImage)
{
}
void RawTexture2D::saveTo(const std::string& filename, ImageFileFormat format)
{
std::string fileExtension = "";
auto imageCodec = DirectX::WIC_CODEC_JPEG;
switch (format)
{
case ImageFileFormat::jpg:
imageCodec = DirectX::WIC_CODEC_JPEG;
fileExtension = "jpg";
break;
case ImageFileFormat::png:
imageCodec = DirectX::WIC_CODEC_PNG;
fileExtension = "png";
break;
default:
Assert(false, "The given ImageFileFormat is not supported.");
break;
}
const auto& filenameWithExtension = filename+"."+fileExtension;
wchar_t wFilename[MAX_TEXTURE_FILENAME_STR_SIZE];
size_t len;
mbstowcs_s(&len, wFilename, MAX_TEXTURE_FILENAME_STR_SIZE, filenameWithExtension.c_str(), _TRUNCATE);
DirectX::ScratchImage image;
auto hr = DirectX::CaptureTexture(Device::getDevice().Get(), Device::getDeviceContext().Get(), m_textureBuffer.Get(), image);
if(FAILED(hr))
{
throw COM_RUNTIME_ERROR(hr, "Failed to capture the screen.");
}
hr = DirectX::SaveToWICFile(image.GetImages()[0], DirectX::WIC_FLAGS_NONE, DirectX::GetWICCodec(imageCodec), wFilename);
if(FAILED(hr))
{
throw COM_RUNTIME_ERROR(hr, "Failed to save the captured image to " + filename + ".");
}
}
void RawTexture2D::copy(const RawTexture2D& src)
{
Assert(m_id != src.m_id, "The source and destination resources must be different resources.");
Assert((m_gpuAccessType == GPUAccessType::R && m_cpuAccessType == CPUAccessType::none) == false, "Immutable resources are not allowed to perform copy operations.");
Assert(m_size == src.m_size, "The source and destination resources must have identical dimensions.");
Assert(D3D11CreateFunctions::checkCompatibilityBetweenTwoTextureFormats(static_cast<DXGI_FORMAT>(m_format), static_cast<DXGI_FORMAT>(src.m_format)), "The source and destination resources must have compatible formats.");
Device::getDeviceContext()->CopyResource(m_textureBuffer.Get(), src.m_textureBuffer.Get());
}
void RawTexture2D::write(const ImageXY& image)
{
if ((static_cast<int>(m_cpuAccessType) & static_cast<int>(CPUAccessType::W)) == 0) { return; }
auto dxgiFormat = static_cast<DXGI_FORMAT>(m_format);
auto dimension = D3D11CreateFunctions::checkTextureColorDimension(dxgiFormat);
auto precision = D3D11CreateFunctions::checkTexturePrecision(dxgiFormat);
switch (precision)
{
case TexturePrecision::Float32:
case TexturePrecision::Float16:
m_write<float>(image, dimension, true);
break;
case TexturePrecision::Int32:
m_write<int32_t>(image, dimension, false);
break;
case TexturePrecision::Int16:
m_write<int16_t>(image, dimension, false);
break;
case TexturePrecision::Int8:
m_write<int8_t>(image, dimension, false);
break;
case TexturePrecision::UInt32:
m_write<uint32_t>(image, dimension, false);
break;
case TexturePrecision::UInt16:
m_write<uint16_t>(image, dimension, false);
break;
case TexturePrecision::UInt8:
m_write<uint8_t>(image, dimension, false);
break;
default:
Assert(false, "The given TexturePrecision is not supported.");
break;
}
}
std::shared_ptr<IShaderResourceMemoryAccessor> RawTexture2D::getSRV() const
{
return m_SRV;
}
std::shared_ptr<IShaderResourceMemoryAccessor> RawTexture2D::getUAV() const
{
return m_UAV;
}
cpp::Vector2D<int> RawTexture2D::getSize() const noexcept
{
return m_size;
}
void RawTexture2D::resolve()
{
if (isResolvedTexture())
{
m_resolve();
}
}
void RawTexture2D::generateMipMaps()
{
m_SRV->generateMipMaps();
}
int RawTexture2D::getMostDetailedMipLevel() const noexcept
{
return m_mostDetailedMipLevel;
}
int RawTexture2D::getMostRoughedMipLevel() const noexcept
{
return m_mostRoughedMipLevel;
}
bool RawTexture2D::isResolvedTexture() const noexcept
{
return m_isResolvedTexture;
}
}
} |
vzhabiuk/sensei | clients/java/src/test/java/com/senseidb/test/client/TweetsTest.java | package com.senseidb.test.client;
import com.senseidb.search.client.SenseiServiceProxy;
import com.senseidb.search.client.req.FacetInit;
import com.senseidb.search.client.req.FacetType;
import com.senseidb.search.client.req.Selection;
import com.senseidb.search.client.req.SenseiClientRequest;
import org.junit.Test;
public class TweetsTest {
public static void main(String[] args) throws Exception {
SenseiClientRequest request = SenseiClientRequest.builder().addSelection(Selection.terms("timeRange", "000120000")).
addFacetInit("timeRange", "time", FacetInit.build(FacetType.type_long, System.currentTimeMillis())).build();
SenseiServiceProxy senseiServiceProxy = new SenseiServiceProxy("localhost", 8080);
System.out.println(senseiServiceProxy.sendSearchRequest(request));
}
@Test
public void bareEntry() throws Exception
{
}
}
|
xiaobai/swift-lldb | packages/Python/lldbsuite/test/lang/swift/struct_change_rerun/TestSwiftStructChangeRerun.py | # TestSwiftStructChangeRerun.py
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
# ------------------------------------------------------------------------------
"""
Test that we display self correctly for an inline-initialized struct
"""
import lldb
from lldbsuite.test.lldbtest import *
from lldbsuite.test.decorators import *
import lldbsuite.test.lldbutil as lldbutil
import os
import shutil
import unittest2
class TestSwiftStructChangeRerun(TestBase):
mydir = TestBase.compute_mydir(__file__)
def setUp(self):
TestBase.setUp(self)
@swiftTest
def test_swift_struct_change_rerun(self):
"""Test that we display self correctly for an inline-initialized struct"""
copied_main_swift = self.getBuildArtifact("main.swift")
# Cleanup the copied source file
def cleanup():
if os.path.exists(copied_main_swift):
os.unlink(copied_main_swift)
# Execute the cleanup function during test case tear down.
self.addTearDownHook(cleanup)
print('build with main1.swift')
cleanup()
shutil.copyfile("main1.swift", copied_main_swift)
self.build()
(target, process, thread, breakpoint) = \
lldbutil.run_to_source_breakpoint(
self, 'Set breakpoint here', lldb.SBFileSpec('main.swift'))
var_a = self.frame().EvaluateExpression("a")
var_a_a = var_a.GetChildMemberWithName("a")
lldbutil.check_variable(self, var_a_a, False, value="12")
var_a_b = var_a.GetChildMemberWithName("b")
lldbutil.check_variable(self, var_a_b, False, '"Hey"')
var_a_c = var_a.GetChildMemberWithName("c")
self.assertFalse(var_a_c.IsValid(), "make sure a.c doesn't exist")
process.Kill()
print('build with main2.swift')
cleanup()
shutil.copyfile("main2.swift", copied_main_swift)
self.build()
# Launch the process, and do not stop at the entry point.
process = target.LaunchSimple(None, None, os.getcwd())
self.assertTrue(process, PROCESS_IS_VALID)
# Frame #0 should be at our breakpoint.
threads = lldbutil.get_threads_stopped_at_breakpoint(
process, breakpoint)
self.assertTrue(len(threads) == 1)
var_a = self.frame().EvaluateExpression("a")
var_a_a = var_a.GetChildMemberWithName("a")
lldbutil.check_variable(self, var_a_a, False, value="12")
var_a_b = var_a.GetChildMemberWithName("b")
lldbutil.check_variable(self, var_a_b, False, '"Hey"')
var_a_c = var_a.GetChildMemberWithName("c")
self.assertTrue(var_a_c.IsValid(), "make sure a.c does exist")
lldbutil.check_variable(self, var_a_c, False, value='12.125')
if __name__ == '__main__':
import atexit
lldb.SBDebugger.Initialize()
atexit.register(lldb.SBDebugger.Terminate)
unittest2.main()
|
adele-robots/fiona | SPARKS/VideoConsumerSpark/stdAfx.h | // stdafx.h: archivo de inclusión de los archivos de inclusión estándar del sistema
// o archivos de inclusión específicos de un proyecto utilizados frecuentemente,
// pero rara vez modificados
//
#pragma once
#include "config.h"
#ifndef _WIN32_WINNT // Permitir el uso de características específicas de Windows XP o posterior.
#define _WIN32_WINNT 0x0501 // Cambiar al valor apropiado correspondiente a otras versiones de Windows.
#endif
#define WIN32_LEAN_AND_MEAN // Excluir material rara vez utilizado de encabezados de Windows
// TODO: mencionar aquí los encabezados adicionales que el programa necesita
#include "ErrorHandling.h"
|
juarezpaulino/coderemite | problemsets/UVA/12081.cpp | /**
*
* Author: <NAME>(coderemite)
* Email: <EMAIL>
*
*/
#include <cstdio>
int main() {
int i, j, k, n, m, *v = 314+new int[100000];
for (scanf("%d", &n); n-- && scanf("%d", &m); printf("%d\n", k))
for (*v=i=(k=1)-1; i++<m; ) {
scanf("%d", v-i);
for (j=i; j<=i; ++j)
v[v[-j]%k]-k ? v[v[-j]%k]=k : *(v+k++)=(j=-1)++;
}
return 0;
}
|
boselor/slc | src/cv/common/MatrixOperator.cpp | //
// Created by xiaoyong on 2021/1/1.
//
#include <cv/common/MatrixOperator.h>
namespace slc{
MatrixOperator::MatrixOperator() {}
MatrixOperator::~MatrixOperator() {}
MatrixOperator MatrixOperator::load(cv::Mat matrix) {
this->entity = matrix;
return *this;
}
MatrixOperator MatrixOperator::show(EString title, int waitKey, int width, int height, bool openGL) {
cv::namedWindow(title.toStdString(),cv::WindowFlags::WINDOW_NORMAL);
cv::resizeWindow(title.toStdString(), width <= 0? this->entity.cols: width, height <= 0 ?this->entity.rows: height);
cv::moveWindow(title.toStdString(), 100, 0);
cv::imshow(title.toStdString(),this->entity);
cv::waitKey(waitKey);
return *this;
}
} |
dupliaka/droolsjbpm-integration | kie-server-parent/kie-server-remote/kie-server-client/src/main/java/org/kie/server/client/admin/impl/CaseAdminServicesClientImpl.java | /*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.server.client.admin.impl;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.kie.server.api.KieServerConstants;
import org.kie.server.api.commands.CommandScript;
import org.kie.server.api.commands.DescriptorCommand;
import org.kie.server.api.model.KieServerCommand;
import org.kie.server.api.model.ServiceResponse;
import org.kie.server.api.model.cases.CaseInstance;
import org.kie.server.api.model.cases.CaseInstanceList;
import org.kie.server.api.model.cases.CaseMigrationReportInstance;
import org.kie.server.client.KieServicesConfiguration;
import org.kie.server.client.admin.CaseAdminServicesClient;
import org.kie.server.client.admin.ProcessAdminServicesClient;
import org.kie.server.client.impl.AbstractKieServicesClientImpl;
import static org.kie.server.api.rest.RestURI.*;
public class CaseAdminServicesClientImpl extends AbstractKieServicesClientImpl implements CaseAdminServicesClient {
public CaseAdminServicesClientImpl(KieServicesConfiguration config) {
super(config);
}
public CaseAdminServicesClientImpl(KieServicesConfiguration config, ClassLoader classLoader) {
super(config, classLoader);
}
@Override
public List<CaseInstance> getCaseInstances(Integer page, Integer pageSize) {
return getCaseInstances(null, page, pageSize, "", true);
}
@Override
public List<CaseInstance> getCaseInstances(List<String> status, Integer page, Integer pageSize) {
return getCaseInstances(status, page, pageSize, "", true);
}
@Override
public List<CaseInstance> getCaseInstances(Integer page, Integer pageSize, String sort, boolean sortOrder) {
return getCaseInstances(null, page, pageSize, sort, sortOrder);
}
@Override
public List<CaseInstance> getCaseInstances(List<String> status, Integer page, Integer pageSize, String sort, boolean sortOrder) {
CaseInstanceList list = null;
if( config.isRest() ) {
Map<String, Object> valuesMap = new HashMap<String, Object>();
String queryString = getPagingQueryString("", page, pageSize);
queryString = getAdditionalParams(queryString, "status", status);
queryString = getSortingQueryString(queryString, sort, sortOrder);
list = makeHttpGetRequestAndCreateCustomResponse(
build(loadBalancer.getUrl(), ADMIN_CASE_URI + "/" + ADMIN_CASE_ALL_INSTANCES_GET_URI, valuesMap) + queryString, CaseInstanceList.class);
} else {
CommandScript script = new CommandScript( Collections.singletonList(
(KieServerCommand) new DescriptorCommand("CaseQueryService", "getCaseInstances", new Object[]{safeList(status), page, pageSize, sort, sortOrder})) );
ServiceResponse<CaseInstanceList> response = (ServiceResponse<CaseInstanceList>)
executeJmsCommand( script, DescriptorCommand.class.getName(), KieServerConstants.CAPABILITY_CASE ).getResponses().get(0);
throwExceptionOnFailure(response);
if (shouldReturnWithNullResponse(response)) {
return null;
}
list = response.getResult();
}
if (list != null) {
return list.getItems();
}
return Collections.emptyList();
}
@Override
public CaseMigrationReportInstance migrateCaseInstance(String containerId, String caseId, String targetContainerId, Map<String, String> processMapping) {
return migrateCaseInstance(containerId, caseId, targetContainerId, processMapping, new HashMap<>());
}
@Override
public CaseMigrationReportInstance migrateCaseInstance(String containerId, String caseId, String targetContainerId, Map<String, String> processMapping, Map<String, String> nodeMapping) {
CaseMigrationReportInstance report = null;
Map<String, Object> mappings = new HashMap<>();
mappings.put("ProcessMapping", processMapping);
mappings.put("NodeMapping", nodeMapping);
if( config.isRest() ) {
Map<String, Object> valuesMap = new HashMap<String, Object>();
valuesMap.put(CONTAINER_ID, containerId);
valuesMap.put(CASE_ID, caseId);
String queryString = "?targetContainerId=" + targetContainerId;
report = makeHttpPutRequestAndCreateCustomResponse(
build(loadBalancer.getUrl(), ADMIN_CASE_URI + "/" + MIGRATE_CASE_INST_PUT_URI, valuesMap) + queryString, serialize(mappings), CaseMigrationReportInstance.class, new HashMap<>());
} else {
CommandScript script = new CommandScript( Collections.singletonList(
(KieServerCommand) new DescriptorCommand("CaseAdminService", "migrateCaseInstance", serialize(safeMap(mappings)), marshaller.getFormat().getType(), new Object[]{containerId, caseId, targetContainerId})) );
ServiceResponse<CaseMigrationReportInstance> response = (ServiceResponse<CaseMigrationReportInstance>)
executeJmsCommand( script, DescriptorCommand.class.getName(), KieServerConstants.CAPABILITY_CASE ).getResponses().get(0);
throwExceptionOnFailure(response);
if (shouldReturnWithNullResponse(response)) {
return null;
}
report = response.getResult();
}
return report;
}
}
|
gharia/kurento-java | kurento-integration-tests/kurento-test/src/main/java/org/kurento/test/base/ScalabilityTest.java | /*
* (C) Copyright 2015 Kurento (http://kurento.org/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.kurento.test.base;
import org.junit.experimental.categories.Category;
import org.kurento.commons.testing.SystemScalabilityTests;
import org.kurento.test.browser.WebRtcTestPage;
/**
* Scalability tests.
*
* @author <NAME> (<EMAIL>)
* @since 6.1.1
*/
@Category(SystemScalabilityTests.class)
public class ScalabilityTest extends KurentoClientBrowserTest<WebRtcTestPage> {
public ScalabilityTest() {
setDeleteLogsIfSuccess(false);
}
}
|
Elidriel/diploma | admin/src/main/java/com/example/diploma/admin/controller/CatalogController.java | <reponame>Elidriel/diploma
package com.example.diploma.admin.controller;
import com.example.diploma.admin.service.CatalogService;
import com.example.diploma.persistence.dto.admin.CatalogDto;
import com.example.diploma.persistence.exeption.CatalogUrlExistsException;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/admin/catalog")
@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)
public class CatalogController {
CatalogService catalogService;
@GetMapping("/get-all")
public List<CatalogDto> getAllCatalogs() {
return catalogService.getAllCatalogs();
}
@GetMapping("/get/{id}")
public CatalogDto getById(@PathVariable Long id) {
return catalogService.getById(id);
}
@PostMapping("/save")
public CatalogDto save(@RequestBody CatalogDto catalogDto) {
try {
if (catalogDto.getId() != null) {
return CatalogService.convertToDto(catalogService.save(catalogDto));
}
return CatalogService.convertToDto(catalogService.create(catalogDto));
} catch (CatalogUrlExistsException e) {
log.warn(e.getMessage());
return new CatalogDto();
}
}
@DeleteMapping("/delete")
public List<CatalogDto> delete(@RequestParam("id") Long id) {
catalogService.delete(id);
return catalogService.getAllCatalogs();
}
}
|
vnandwana/killbill-admin-ui | test/dummy/config/initializers/killbill_client.rb | <reponame>vnandwana/killbill-admin-ui<gh_stars>10-100
KillBillClient.url = ENV['KILLBILL_URL'] || 'http://127.0.0.1:8080'
KillBillClient.read_timeout = (ENV['KILLBILL_READ_TIMEOUT'] || 60000).to_i
KillBillClient.connection_timeout = (ENV['KILLBILL_CONNECTION_TIMEOUT'] || 60000).to_i
|
wultra/powerauth-client-core | PowerAuth/src/PowerAuth/crypto/PRNG.cpp | /*
* Copyright 2021 <NAME>.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "PRNG.h"
#include <openssl/rand.h>
#if defined(CC7_APPLE) || defined(CC7_ANDROID)
#include <fcntl.h>
#include <unistd.h>
#endif
namespace com
{
namespace wultra
{
namespace powerAuth
{
namespace crypto
{
static bool GetBytesFromSystemGenerator(void * out_buffer, size_t nbytes);
// MARK: - Public functions -
cc7::ByteArray GetRandomData(size_t size, bool reject_sequence_of_zeros)
{
cc7::ByteArray data(size, 0);
cc7::ByteArray zeros;
size_t attempts = 16;
while (size > 0) {
int rc = RAND_bytes(data.data(), (int)size);
if (rc != 1 || attempts == 0) {
CC7_ASSERT(false, "Random data generation failed!");
return cc7::ByteArray();
}
if (!reject_sequence_of_zeros) {
break;
}
if (zeros.size() != size) {
zeros.assign(size, 0);
}
if (data != zeros) {
break;
}
--attempts;
}
return data;
}
cc7::ByteArray GetUniqueRandomData(size_t size, const std::vector<const cc7::ByteRange> & reject_byte_sequences)
{
cc7::ByteArray data(size, 0);
size_t attempts = 16;
while (size > 0) {
int rc = RAND_bytes(data.data(), (int)size);
if (rc != 1 || attempts == 0) {
CC7_ASSERT(false, "Random data generation failed!");
return cc7::ByteArray();
}
bool unique = true;
for (auto && other_data : reject_byte_sequences) {
if (data.byteRange() == other_data) {
unique = false;
break;
}
}
if (unique) {
break;
}
--attempts;
}
return data;
}
void ReseedPRNG()
{
static bool s_initial_seed = true;
size_t nbytes;
if (s_initial_seed) {
// This is an initial seed. The recommended size for OpenSSL's PRNG is 1024 bytes
s_initial_seed = false;
nbytes = 1024;
} else {
// All subsequent re-seeds may be shorter.
unsigned char count = 16;
RAND_bytes(&count, sizeof(unsigned char));
if (count < 16) {
count = 16;
} else if (count > 64) {
count = 64;
}
nbytes = count;
}
uint8_t * buffer = new uint8_t[nbytes];
if (CC7_CHECK(GetBytesFromSystemGenerator(buffer, nbytes), "Unable to seed PRNG")) {
RAND_seed(buffer, (int)nbytes);
}
delete []buffer;
}
// MARK: - Platform specific implementations -
#if defined(CC7_APPLE) || defined(CC7_ANDROID)
static bool GetBytesFromSystemGenerator(void * out_buffer, size_t nbytes)
{
int fd = open("/dev/urandom", O_RDONLY);
bool result = false;
if (fd >= 0 && out_buffer != nullptr) {
ssize_t readed = read(fd, out_buffer, nbytes);
result = readed == nbytes;
close(fd);
}
return result;
}
#else
#error Unsupported platform
#endif
} // com::wultra::powerAuth::crypto
} // com::wultra::powerAuth
} // com::wultra
} // com
|
ge-enrique-cano/uaa | server/src/main/java/org/cloudfoundry/identity/uaa/impl/config/AliasSupportingTypeDescription.java | package org.cloudfoundry.identity.uaa.impl.config;
import org.yaml.snakeyaml.TypeDescription;
import org.yaml.snakeyaml.introspector.Property;
import java.util.HashMap;
import java.util.Map;
/**
* Created by taitz.
*/
class AliasSupportingTypeDescription extends TypeDescription {
private final Map<String, Property> aliases = new HashMap<>();
AliasSupportingTypeDescription(Class<?> clazz) {
super(clazz);
}
@Override
public Property getProperty(String name) {
return aliases.containsKey(name) ? aliases.get(name) : super.getProperty(name);
}
public void put(String alias, Property property) {
aliases.put(alias, property);
}
}
|
zhuyadong/COS | CosStd/src/Functor.c | <reponame>zhuyadong/COS
/**
* C Object System
* COS Functor
*
* Copyright 2006+ <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* NOTE-INFO: PlaceHolder specializations
PlaceHolders should only override Object's methods, no more,
since High Order Messages are commonly built with delegation.
*/
#include <cos/Functor.h>
#include <cos/gen/object.h>
// ----- allocator
defmethod(OBJ, galloc, pmFunctor) // lazy alloc
retmethod(_1);
endmethod
// ----- class cluster root classes
makclass(Expression, Any);
// ----- functor operator (iterate, compose)
makclass(IterateFun, Functor);
makclass(ComposeFun, Functor);
// ------------------------------------------------------------
// ----- variable expression
makclass(VarExpr, Expression);
makclass(FunArg , VarExpr);
// ------------------------------------------------------------
// ----- functor expression
makclass(Functor, Expression);
makclass(FunExpr, Functor);
makclass(MsgExpr, Functor);
makclass(FunExpr0, FunExpr);
makclass(FunExpr1, FunExpr);
makclass(FunExpr2, FunExpr);
makclass(FunExpr3, FunExpr);
makclass(FunExpr4, FunExpr);
makclass(FunExpr5, FunExpr);
makclass(FunExpr6, FunExpr);
makclass(FunExpr7, FunExpr);
makclass(FunExpr8, FunExpr);
makclass(FunExpr9, FunExpr);
// ----- specializations
makclass(FunExpr11, FunExpr1);
makclass(FunExpr12, FunExpr1);
makclass(FunExpr21, FunExpr2);
makclass(FunExpr22, FunExpr2);
makclass(FunExpr23, FunExpr2);
makclass(FunExpr24, FunExpr2);
makclass(FunExpr31, FunExpr3);
makclass(FunExpr32, FunExpr3);
makclass(FunExpr33, FunExpr3);
makclass(FunExpr34, FunExpr3);
makclass(FunExpr35, FunExpr3);
makclass(FunExpr36, FunExpr3);
makclass(FunExpr37, FunExpr3);
makclass(FunExpr38, FunExpr3);
|
logginghub/core | logginghub-server/src/main/java/com/logginghub/logging/transaction/EventReporter.java | package com.logginghub.logging.transaction;
import com.logginghub.logging.DefaultLogEvent;
import com.logginghub.logging.LogEvent;
import com.logginghub.logging.LogEventBuilder;
import com.logginghub.logging.transaction.configuration.EventReporterConfiguration;
import com.logginghub.logging.transaction.configuration.LogEventTemplateConfiguration;
import com.logginghub.utils.*;
import com.logginghub.utils.logging.Logger;
import com.logginghub.utils.module.Module;
import com.logginghub.utils.module.ServiceDiscovery;
public class EventReporter implements StreamListener<TransactionModel>, Module<EventReporterConfiguration> {
private static final Logger logger = Logger.getLoggerFor(EventReporter.class);
private Destination<LogEvent> failureDestination;
private Destination<LogEvent> successDestination;
private LogEventTemplateConfiguration successEventTemplate;
private LogEventTemplateConfiguration failureEventTemplate;
private String sourceAddress;
private String sourceHost;
private EventReporterConfiguration configuration;
public EventReporter() {
sourceAddress = NetUtils.getLocalIP();
sourceHost = NetUtils.getLocalHostname();
}
@Override public void onNewItem(TransactionModel t) {
LogEventTemplateConfiguration config;
Destination<LogEvent> destination;
if (t.isSuccess()) {
config = successEventTemplate;
destination = successDestination;
} else {
config = failureEventTemplate;
destination = failureDestination;
}
long warningInterval = Long.MAX_VALUE;
if (StringUtils.isNotNullOrEmpty(this.configuration.getWarningAt())) {
warningInterval = TimeUtils.parseInterval(this.configuration.getWarningAt());
}
boolean okToReport;
if (t.isSuccess() && !this.configuration.isReportSuccess()) {
double elapsed = t.calculateElapsedMilliseconds();
if (elapsed > warningInterval) {
// This is ok, its a warning
okToReport = true;
} else {
// We shouldn't report this
okToReport = false;
}
} else {
okToReport = true;
}
if (okToReport) {
report(t, config, destination, warningInterval);
}
}
private void report(TransactionModel t,
LogEventTemplateConfiguration config,
Destination<LogEvent> destination,
long warningInterval) {
ReportGenerator generator = new ReportGenerator();
String report;
if (configuration.isSingleLine()) {
report = generator.generateSingleLineReport(t, warningInterval);
} else {
report = generator.generateReport(t, warningInterval);
}
// Turn all this into a log event
DefaultLogEvent event = LogEventBuilder.start()
.setLevel(config.getLevel())
.setChannel(config.getChannel())
.setMessage(report)
.setSourceAddress(sourceAddress)
.setSourceHost(sourceHost)
.setSourceApplication(config.getSourceApplication())
.setSourceClassName(config.getSourceClassName())
.setSourceMethodName(config.getSourceMethodName())
.setThreadName(config.getThreadName())
.setLoggerName(config.getLoggerName())
.toLogEvent();
// Send it on its way
destination.send(event);
}
@SuppressWarnings("unchecked") public void configure(EventReporterConfiguration eventReporterConfiguration,
ServiceDiscovery serviceDiscovery) {
this.configuration = eventReporterConfiguration;
successEventTemplate = eventReporterConfiguration.getSuccessEventTemplate();
failureEventTemplate = eventReporterConfiguration.getFailureEventTemplate();
this.successDestination = serviceDiscovery.findService(Destination.class,
LogEvent.class,
eventReporterConfiguration.getSuccessDestination());
this.failureDestination = serviceDiscovery.findService(Destination.class,
LogEvent.class,
eventReporterConfiguration.getFailureDestination());
}
@Override public void start() {
}
@Override public void stop() {
}
}
|
readr-media/news-projecrs | src/components/PoliticalContribution/components/charts/data/index.js | <reponame>readr-media/news-projecrs
export const DATA_ALL_ORDINAL_DONATES_FROM_LEGENDS = [
{
type: 'square-icon',
text: '營利事業',
color: '#9e005d'
},
{
type: 'square-icon',
text: '個人',
color: '#000000'
},
{
type: 'square-icon',
text: '政黨',
color: '#636363'
},
{
type: 'square-icon',
text: '人民團體',
color: '#a8a8a8'
},
{
type: 'square-icon',
text: '匿名',
color: '#c3c3c3'
},
{
type: 'square-icon',
text: '其他',
color: '#e6e5e5'
}
]
export const DATA_ALL_ORDINAL_DONATES_FROM = [
{
ordinal: 'seventh',
ordinalString: '第七屆',
總收入: 2200994360,
個人: 778615685,
營利事業: 901992830,
政黨: 450578350,
人民團體: 62650308,
匿名: 6200799,
其他: 1440388
},
{
ordinal: 'eighth',
ordinalString: '第八屆',
總收入: 2361748527,
個人: 1175200927,
營利事業: 819306661,
政黨: 303443343,
人民團體: 48149800,
匿名: 14916277,
其他: 231519
},
{
ordinal: 'ninth',
ordinalString: '第九屆',
總收入: 2817453078,
個人: 1304940626,
營利事業: 902948872,
政黨: 521873800,
人民團體: 60290720,
匿名: 27078812,
其他: 320206
},
{
ordinal: 'tenth',
ordinalString: '第十屆',
總收入: 2158871745,
個人: 1179613024,
營利事業: 791107771,
政黨: 115346967,
人民團體: 52127837,
匿名: 20572257,
其他: 103889
}
]
export const DATA_ORDINAL_TOP_FIVE_DONATES_LEGENDS = [
{
type: 'round-icon',
text: '中國國民黨',
color: '#0071bc'
},
{
type: 'round-icon',
text: '民主進步黨',
color: '#53a66f'
},
{
type: 'image',
text: '當選註記',
imgsrc: '/proj-assets/political-contribution/elected.png'
}
]
export const DATA_ORDINAL_TOP_FIVE_DONATES_TOTAL = {
seventh: [
{
candidate: '周守訓',
amount: 43717569,
party: '中國國民黨',
isWon: true,
division: '臺北市第02選區'
},
{
candidate: '吳育昇',
amount: 40285000,
party: '中國國民黨',
isWon: true,
division: '臺北縣第01選區'
},
{
candidate: '林郁方',
amount: 39103644,
party: '中國國民黨',
isWon: true,
division: '臺北市第05選區'
},
{
candidate: '盧秀燕',
amount: 36089833,
party: '中國國民黨',
isWon: true,
division: '臺中市第02選區'
},
{
candidate: '丁守中',
amount: 35497248,
party: '中國國民黨',
isWon: true,
division: '臺北市第01選區'
}
],
eighth: [
{
candidate: '丁守中',
amount: 56757081,
party: '中國國民黨',
isWon: true,
division: '臺北市第01選區'
},
{
candidate: '周守訓',
amount: 53177447,
party: '中國國民黨',
isWon: false,
division: '臺北市第02選區'
},
{
candidate: '吳育昇',
amount: 49884737,
party: '中國國民黨',
isWon: true,
division: '新北市第01選區'
},
{
candidate: '費鴻泰',
amount: 41700364,
party: '中國國民黨',
isWon: true,
division: '臺北市第07選區'
},
{
candidate: '侯彩鳳',
amount: 38829664,
party: '中國國民黨',
isWon: false,
division: '高雄市第06選區'
}
],
ninth: [
{
candidate: '柯建銘',
amount: 51641147,
party: '民主進步黨',
isWon: true,
division: '新竹市第01選區'
},
{
candidate: '吳秉叡',
amount: 50205014,
party: '民主進步黨',
isWon: true,
division: '新北市第04選區'
},
{
candidate: '丁守中',
amount: 49603735,
party: '中國國民黨',
isWon: false,
division: '臺北市第01選區'
},
{
candidate: '管碧玲',
amount: 45831478,
party: '民主進步黨',
isWon: true,
division: '高雄市第05選區'
},
{
candidate: '吳育昇',
amount: 45556665,
party: '中國國民黨',
isWon: false,
division: '新北市第01選區'
}
],
tenth: [
{
candidate: '邱志偉',
amount: 47530712,
party: '民主進步黨',
isWon: true,
division: '高雄市第02選區'
},
{
candidate: '林岱樺',
amount: 46952278,
party: '民主進步黨',
isWon: true,
division: '高雄市第04選區'
},
{
candidate: '蔡其昌',
amount: 45928848,
party: '民主進步黨',
isWon: true,
division: '臺中市第01選區'
},
{
candidate: '黃國書',
amount: 40807042,
party: '民主進步黨',
isWon: true,
division: '臺中市第06選區'
},
{
candidate: '吳秉叡',
amount: 40581091,
party: '民主進步黨',
isWon: true,
division: '新北市第04選區'
}
]
}
export const DATA_ORDINAL_TOP_FIVE_DONATES_COMPANY = {
seventh: [
{
candidate: '周守訓',
amount: 19934048,
party: '中國國民黨',
isWon: true,
division: '臺北市第02選區'
},
{
candidate: '林郁方',
amount: 18751200,
party: '中國國民黨',
isWon: true,
division: '臺北市第05選區'
},
{
candidate: '吳育昇',
amount: 18072900,
party: '中國國民黨',
isWon: true,
division: '臺北縣第01選區'
},
{
candidate: '顏清標',
amount: 18058000,
party: '無黨團結聯盟',
isWon: true,
division: '臺中縣第02選區'
},
{
candidate: '丁守中',
amount: 17018120,
party: '中國國民黨',
isWon: true,
division: '臺北市第01選區'
}
],
eighth: [
{
candidate: '周守訓',
amount: 25520000,
party: '中國國民黨',
isWon: false,
division: '臺北市第02選區'
},
{
candidate: '丁守中',
amount: 25300000,
party: '中國國民黨',
isWon: true,
division: '臺北市第01選區'
},
{
candidate: '吳育昇',
amount: 21231000,
party: '中國國民黨',
isWon: true,
division: '新北市第01選區'
},
{
candidate: '李乾龍',
amount: 20850000,
party: '中國國民黨',
isWon: false,
division: '新北市第03選區'
},
{
candidate: '顏清標',
amount: 17739000,
party: '無黨團結聯盟',
isWon: true,
division: '臺中市第02選區'
}
],
ninth: [
{
candidate: '柯建銘',
amount: 26915133,
party: '民主進步黨',
isWon: true,
division: '新竹市第01選區'
},
{
candidate: '邱志偉',
amount: 21244000,
party: '民主進步黨',
isWon: true,
division: '高雄市第02選區'
},
{
candidate: '吳秉叡',
amount: 20961000,
party: '民主進步黨',
isWon: true,
division: '新北市第04選區'
},
{
candidate: '丁守中',
amount: 19499800,
party: '中國國民黨',
isWon: false,
division: '臺北市第01選區'
},
{
candidate: '吳育昇',
amount: 19478481,
party: '中國國民黨',
isWon: false,
division: '新北市第01選區'
}
],
tenth: [
{
candidate: '邱志偉',
amount: 28668910,
party: '民主進步黨',
isWon: true,
division: '高雄市第02選區'
},
{
candidate: '李彥秀',
amount: 18971300,
party: '中國國民黨',
isWon: false,
division: '臺北市第04選區'
},
{
candidate: '林岱樺',
amount: 17860000,
party: '民主進步黨',
isWon: true,
division: '高雄市第04選區'
},
{
candidate: '陳超明',
amount: 16519000,
party: '中國國民黨',
isWon: true,
division: '苗栗縣第01選區'
},
{
candidate: '顏寬恒',
amount: 15909904,
party: '中國國民黨',
isWon: false,
division: '臺中市第02選區'
}
]
}
export const DATA_ORDINAL_TOP_FIVE_DONATES_COMPANY_COUNT = {
seventh: [
{
candidate: '廖本煙',
amount: 178,
donatesMoney: 11902600,
party: '民主進步黨',
isWon: false,
division: '臺北縣第05選區'
},
{
candidate: '周守訓',
amount: 127,
donatesMoney: 19934048,
party: '中國國民黨',
isWon: true,
division: '臺北市第02選區'
},
{
candidate: '段宜康',
amount: 123,
donatesMoney: 11212400,
party: '民主進步黨',
isWon: false,
division: '臺北市第05選區'
},
{
candidate: '丁守中',
amount: 115,
donatesMoney: 17018120,
party: '中國國民黨',
isWon: true,
division: '臺北市第01選區'
},
{
candidate: '何敏豪',
amount: 112,
donatesMoney: 6917200,
party: '民主進步黨',
isWon: false,
division: '臺中市第03選區'
}
],
eighth: [
{
candidate: '周守訓',
amount: 158,
donatesMoney: 25520000,
party: '中國國民黨',
isWon: false,
division: '臺北市第02選區'
},
{
candidate: '林岱樺',
amount: 135,
donatesMoney: 9924000,
party: '民主進步黨',
isWon: true,
division: '高雄市第04選區'
},
{
candidate: '林佳龍',
amount: 124,
donatesMoney: 7025700,
party: '民主進步黨',
isWon: true,
division: '臺中市第06選區'
},
{
candidate: '管碧玲',
amount: 114,
donatesMoney: 9130500,
party: '民主進步黨',
isWon: true,
division: '高雄市第05選區'
},
{
candidate: '吳育昇',
amount: 98,
donatesMoney: 21231000,
party: '中國國民黨',
isWon: true,
division: '新北市第01選區'
}
],
ninth: [
{
candidate: '王定宇',
amount: 163,
donatesMoney: 16430000,
party: '民主進步黨',
isWon: true,
division: '臺南市第05選區'
},
{
candidate: '陳亭妃',
amount: 143,
donatesMoney: 11275990,
party: '民主進步黨',
isWon: true,
division: '臺南市第03選區'
},
{
candidate: '邱志偉',
amount: 133,
donatesMoney: 21244000,
party: '民主進步黨',
isWon: true,
division: '高雄市第02選區'
},
{
candidate: '王惠美',
amount: 132,
donatesMoney: 16750470,
party: '中國國民黨',
isWon: true,
division: '彰化縣第01選區'
},
{
candidate: '管碧玲',
amount: 130,
donatesMoney: 14440000,
party: '民主進步黨',
isWon: true,
division: '高雄市第05選區'
}
],
tenth: [
{
candidate: '邱志偉',
amount: 187,
donatesMoney: 28668910,
party: '民主進步黨',
isWon: true,
division: '高雄市第02選區'
},
{
candidate: '林岱樺',
amount: 130,
donatesMoney: 17860000,
party: '民主進步黨',
isWon: true,
division: '高雄市第04選區'
},
{
candidate: '吳秉叡',
amount: 118,
donatesMoney: 14940000,
party: '民主進步黨',
isWon: true,
division: '新北市第04選區'
},
{
candidate: '賴瑞隆',
amount: 107,
donatesMoney: 11950000,
party: '民主進步黨',
isWon: true,
division: '高雄市第08選區'
},
{
candidate: '羅致政',
amount: 100,
donatesMoney: 8338600,
party: '民主進步黨',
isWon: true,
division: '新北市第07選區'
}
]
}
export const DATA_ORDINAL_TOP_FIVE_DONATES_BUT_LOST = {
seventh: [
{
candidate: '姚文智',
amount: 26530658,
party: '民主進步黨',
isWon: false,
division: '高雄市第01選區'
},
{
candidate: '吳秉叡',
amount: 25563530,
party: '民主進步黨',
isWon: false,
division: '臺北縣第04選區'
},
{
candidate: '蔡其昌',
amount: 24416304,
party: '民主進步黨',
isWon: false,
division: '臺中縣第01選區'
},
{
candidate: '段宜康',
amount: 24269521,
party: '民主進步黨',
isWon: false,
division: '臺北市第05選區'
},
{
candidate: '余政憲',
amount: 24045796,
party: '民主進步黨',
isWon: false,
division: '高雄縣第02選區'
}
],
eighth: [
{
candidate: '周守訓',
amount: 53177447,
party: '中國國民黨',
isWon: false,
division: '臺北市第02選區'
},
{
candidate: '侯彩鳳',
amount: 38829664,
party: '中國國民黨',
isWon: false,
division: '高雄市第06選區'
},
{
candidate: '黃義交',
amount: 30864746,
party: '中國國民黨',
isWon: false,
division: '臺中市第06選區'
},
{
candidate: '李乾龍',
amount: 30390544,
party: '中國國民黨',
isWon: false,
division: '新北市第03選區'
},
{
candidate: '林益世',
amount: 29399551,
party: '中國國民黨',
isWon: false,
division: '高雄市第02選區'
}
],
ninth: [
{
candidate: '丁守中',
amount: 49603735,
party: '中國國民黨',
isWon: false,
division: '臺北市第01選區'
},
{
candidate: '吳育昇',
amount: 45556665,
party: '中國國民黨',
isWon: false,
division: '新北市第01選區'
},
{
candidate: '林郁方',
amount: 28132351,
party: '中國國民黨',
isWon: false,
division: '臺北市第05選區'
},
{
candidate: '楊瓊瓔',
amount: 27469012,
party: '中國國民黨',
isWon: false,
division: '臺中市第03選區'
},
{
candidate: '楊麗環',
amount: 24846677,
party: '中國國民黨',
isWon: false,
division: '桃園市第04選區'
}
],
tenth: [
{
candidate: '李彥秀',
amount: 30516876,
party: '中國國民黨',
isWon: false,
division: '臺北市第04選區'
},
{
candidate: '顏寬恒',
amount: 28582013,
party: '中國國民黨',
isWon: false,
division: '臺中市第02選區'
},
{
candidate: '吳怡農',
amount: 28322399,
party: '民主進步黨',
isWon: false,
division: '臺北市第03選區'
},
{
candidate: '洪秀柱',
amount: 26996519,
party: '中國國民黨',
isWon: false,
division: '臺南市第06選區'
},
{
candidate: '蕭美琴',
amount: 25870509,
party: '民主進步黨',
isWon: false,
division: '花蓮縣第01選區'
}
]
}
export const DATA_ORDINAL_DUEL_RE_ELECTED_OR_NOT = {
seventh: {
dominate: 'left',
left: {
title: '現任立委',
countCandidates: 117,
countWon: 62,
donatesAverage: 14953578,
donatesQ3: 18879864,
donatesQ2: 13196691,
donatesQ1: 9039990
},
right: {
title: '非現任立委',
countCandidates: 74,
countWon: 13,
donatesAverage: 6100348,
donatesQ3: 9411407,
donatesQ2: 1900546,
donatesQ1: 584300
}
},
eighth: {
dominate: 'left',
left: {
title: '現任立委',
countCandidates: 73,
countWon: 53,
donatesAverage: 19288440,
donatesQ3: 25619999,
donatesQ2: 17937825,
donatesQ1: 10837396
},
right: {
title: '非現任立委',
countCandidates: 118,
countWon: 25,
donatesAverage: 8082139,
donatesQ3: 12152235,
donatesQ2: 6357631,
donatesQ1: 2005988
}
},
ninth: {
dominate: 'left',
left: {
title: '現任立委',
countCandidates: 72,
countWon: 49,
donatesAverage: 22716845,
donatesQ3: 28395649,
donatesQ2: 21492708,
donatesQ1: 14605871
},
right: {
title: '非現任立委',
countCandidates: 189,
countWon: 30,
donatesAverage: 6253123,
donatesQ3: 9475771,
donatesQ2: 2642785,
donatesQ1: 260110
}
},
tenth: {
dominate: 'left',
left: {
title: '現任立委',
countCandidates: 74,
countWon: 59,
donatesAverage: 19077799,
donatesQ3: 24524578,
donatesQ2: 17791800,
donatesQ1: 11810030
},
right: {
title: '非現任立委',
countCandidates: 214,
countWon: 17,
donatesAverage: 3491190,
donatesQ3: 4274996,
donatesQ2: 760528,
donatesQ1: 200000
}
}
}
export const DATA_ORDINAL_DUEL_NEWBIE_ELECTED_OR_NOT = {
ninth: {
dominate: 'left',
left: {
title: '現任立委',
countCandidates: 72,
countWon: 49,
donatesAverage: 22716845,
donatesQ3: 28395649,
donatesQ2: 21492708,
donatesQ1: 14605871
},
right: {
title: '第一次參選<br>公職者',
countCandidates: 93,
countWon: 8,
donatesAverage: 3449722,
donatesQ3: 3669675,
donatesQ2: 824125,
donatesQ1: 200000
}
}
}
export const DATA_ORDINAL_TOP_TEN_DONATES_INDUSTRY = {
seventh: [
{
name: '電子工業',
money: 43979000
},
{
name: '其他',
money: 36309500
},
{
name: '建材營造',
money: 31080000
},
{
name: '紡織纖維',
money: 27194000
},
{
name: '鋼鐵工業',
money: 20151000
},
{
name: '水泥工業',
money: 17910000
},
{
name: '証券',
money: 17530000
},
{
name: '食品工業',
money: 15921800
},
{
name: '金融業',
money: 14900000
},
{
name: '電機機械',
money: 14346000
}
],
eighth: [
{
name: '電子工業',
money: 41951000
},
{
name: '建材營造',
money: 37800000
},
{
name: '其他',
money: 37378100
},
{
name: '紡織纖維',
money: 32500000
},
{
name: '汽車工業',
money: 30856720
},
{
name: '水泥工業',
money: 22850000
},
{
name: '食品工業',
money: 17040000
},
{
name: '化學生技醫',
money: 15590000
},
{
name: '塑膠工業',
money: 11750000
},
{
name: '航運業',
money: 11560000
}
],
ninth: [
{
name: '其他',
money: 48016200
},
{
name: '電子工業',
money: 40386000
},
{
name: '建材營造',
money: 38970000
},
{
name: '水泥工業',
money: 32550000
},
{
name: '汽車工業',
money: 27980000
},
{
name: '紡織纖維',
money: 23500000
},
{
name: '航運業',
money: 20250000
},
{
name: '食品工業',
money: 18731200
},
{
name: '化學生技醫',
money: 17350000
},
{
name: '貿易百貨',
money: 12770000
}
],
tenth: [
{
name: '其他',
money: 48016200
},
{
name: '電子工業',
money: 40386000
},
{
name: '建材營造',
money: 38970000
},
{
name: '水泥工業',
money: 32550000
},
{
name: '汽車工業',
money: 27980000
},
{
name: '紡織纖維',
money: 23500000
},
{
name: '航運業',
money: 20250000
},
{
name: '食品工業',
money: 18731200
},
{
name: '化學生技醫',
money: 17350000
},
{
name: '貿易百貨',
money: 12770000
}
]
}
export const DATA_ORDINAL_TOP_TEN_DONATES_INDUSTRY_NEW = {
seventh: [
{
name: '批發及零售業',
money: 336205637
},
{
name: '製造業',
money: 331416680
},
{
name: '不動產業',
money: 162462104
},
{
name: '營建工程業',
money: 105223434
},
{
name: '金融及保險業',
money: 94453890
},
{
name: '專業、科學及技術服務業',
money: 64853880
},
{
name: '無法辨識(沒有財政部登記資料)',
money: 62350245
},
{
name: '運輸及倉儲業',
money: 42665396
},
{
name: '住宿及餐飲業',
money: 24400750
},
{
name: '出版、影音製作、傳播及資通訊服務業',
money: 24396250
}
],
eighth: [
{
name: '製造業',
money: 334577609
},
{
name: '批發及零售業',
money: 334454824
},
{
name: '不動產業',
money: 157771200
},
{
name: '營建工程業',
money: 105464400
},
{
name: '金融及保險業',
money: 82333000
},
{
name: '專業、科學及技術服務業',
money: 58222600
},
{
name: '運輸及倉儲業',
money: 34796500
},
{
name: '支援服務業',
money: 31355848
},
{
name: '無法辨識(沒有財政部登記資料)',
money: 26481940
},
{
name: '出版、影音製作、傳播及資通訊服務業',
money: 26153938
}
],
ninth: [
{
name: '批發及零售業',
money: 370972393
},
{
name: '製造業',
money: 326942117
},
{
name: '不動產業',
money: 178249300
},
{
name: '金融及保險業',
money: 124262688
},
{
name: '營建工程業',
money: 111931581
},
{
name: '專業、科學及技術服務業',
money: 82225919
},
{
name: '運輸及倉儲業',
money: 53452000
},
{
name: '支援服務業',
money: 32375500
},
{
name: '用水供應及污染整治業',
money: 30956985
},
{
name: '出版、影音製作、傳播及資通訊服務業',
money: 29357400
}
],
tenth: [
{
name: '批發及零售業',
money: 325796217
},
{
name: '製造業',
money: 263980246
},
{
name: '不動產業',
money: 178488914
},
{
name: '營建工程業',
money: 95597417
},
{
name: '金融及保險業',
money: 88784022
},
{
name: '專業、科學及技術服務業',
money: 72552263
},
{
name: '支援服務業',
money: 37691081
},
{
name: '運輸及倉儲業',
money: 35595276
},
{
name: '出版、影音製作、傳播及資通訊服務業',
money: 31320711
},
{
name: '用水供應及污染整治業',
money: 21815530
}
]
}
export const DATA_ORDINAL_TOP_TEN_PARTICIPATE_INDUSTRY_LEGENDS = [
{
type: 'crony',
text: '屬於裙帶關係產業'
}
]
export const DATA_ORDINAL_TOP_TEN_PARTICIPATE_INDUSTRY = {
seventh: [
{
name: '油電燃氣業',
percentage: 12.9,
donatesMoney: 2520000,
isCrony: true
},
{
name: '水泥工業',
percentage: 11.6,
donatesMoney: 17910000,
isCrony: true
},
{
name: '玻璃陶瓷業',
percentage: 9.9,
donatesMoney: 3540000,
isCrony: false
},
{
name: '鋼鐵工業',
percentage: 9.7,
donatesMoney: 20151000,
isCrony: true
},
{
name: '橡膠工業',
percentage: 9.4,
donatesMoney: 6099025,
isCrony: false
},
{
name: '建材營造業',
percentage: 8.1,
donatesMoney: 31080000,
isCrony: true
},
{
name: '紡織纖維業',
percentage: 8.1,
donatesMoney: 27194000,
isCrony: false
},
{
name: '文化創意業',
percentage: 6.3,
donatesMoney: 800000,
isCrony: false
},
{
name: '電器電纜業',
percentage: 6.0,
donatesMoney: 5600000,
isCrony: true
},
{
name: '証券業',
percentage: 5.6,
donatesMoney: 17530000,
isCrony: true
}
],
eighth: [
{
name: '文化創意業',
percentage: 12.5,
donatesMoney: 1880000,
isCrony: false
},
{
name: '油電燃氣業',
percentage: 12.5,
donatesMoney: 1310000,
isCrony: true
},
{
name: '水泥工業',
percentage: 12.1,
donatesMoney: 22850000,
isCrony: true
},
{
name: '橡膠工業',
percentage: 11.8,
donatesMoney: 9615000,
isCrony: true
},
{
name: '紡織纖維業',
percentage: 7.1,
donatesMoney: 32500000,
isCrony: false
},
{
name: '汽車工業',
percentage: 6.8,
donatesMoney: 30856720,
isCrony: false
},
{
name: '建材營造業',
percentage: 6.4,
donatesMoney: 37800000,
isCrony: true
},
{
name: '鋼鐵工業',
percentage: 5.4,
donatesMoney: 8340000,
isCrony: true
},
{
name: '証券業',
percentage: 3.7,
donatesMoney: 6100000,
isCrony: true
},
{
name: '電器電纜業',
percentage: 3.3,
donatesMoney: 2500000,
isCrony: true
}
],
ninth: [
{
name: '油電燃氣業',
percentage: 9.6,
donatesMoney: 2600000,
isCrony: true
},
{
name: '文化創意業',
percentage: 5.7,
donatesMoney: 247500,
isCrony: false
},
{
name: '建材營造業',
percentage: 4.9,
donatesMoney: 38970000,
isCrony: true
},
{
name: '水泥工業',
percentage: 3.2,
donatesMoney: 32550000,
isCrony: true
},
{
name: '橡膠工業',
percentage: 3.0,
donatesMoney: 2900000,
isCrony: true
},
{
name: '證券業',
percentage: 2.9,
donatesMoney: 5820000,
isCrony: true
},
{
name: '鋼鐵工業',
percentage: 2.9,
donatesMoney: 3600000,
isCrony: true
},
{
name: '玻璃陶瓷業',
percentage: 2.9,
donatesMoney: 2320000,
isCrony: false
},
{
name: '紡織纖維業',
percentage: 2.6,
donatesMoney: 23500000,
isCrony: false
},
{
name: '塑膠工業',
percentage: 2.4,
donatesMoney: 3600000,
isCrony: false
}
],
tenth: [
{
name: '油電燃氣業',
percentage: 9.6,
donatesMoney: 2600000,
isCrony: true
},
{
name: '文化創意業',
percentage: 5.7,
donatesMoney: 247500,
isCrony: false
},
{
name: '建材營造業',
percentage: 4.9,
donatesMoney: 38970000,
isCrony: true
},
{
name: '水泥工業',
percentage: 3.2,
donatesMoney: 32550000,
isCrony: true
},
{
name: '橡膠工業',
percentage: 3.0,
donatesMoney: 2900000,
isCrony: true
},
{
name: '證券業',
percentage: 2.9,
donatesMoney: 5820000,
isCrony: true
},
{
name: '鋼鐵工業',
percentage: 2.9,
donatesMoney: 3600000,
isCrony: true
},
{
name: '玻璃陶瓷業',
percentage: 2.9,
donatesMoney: 2320000,
isCrony: false
},
{
name: '紡織纖維業',
percentage: 2.6,
donatesMoney: 23500000,
isCrony: false
},
{
name: '塑膠工業',
percentage: 2.4,
donatesMoney: 3600000,
isCrony: false
}
]
}
export const DATA_ORDINAL_TOP_TEN_PARTICIPATE_INDUSTRY_NEW = {
seventh: [
{
name: '電力及燃氣供應業',
percentage: 12.7,
donatesMoney: 7976000,
isCrony: true
},
{
name: '礦業及土石採取業',
percentage: 3.78,
donatesMoney: 6542000,
isCrony: true
},
{
name: '不動產業',
percentage: 3.17,
donatesMoney: 162462104,
isCrony: true
},
{
name: '用水供應及污染整治業',
percentage: 2.28,
donatesMoney: 20283800,
isCrony: true
},
{
name: '教育業',
percentage: 1.93,
donatesMoney: 272000,
isCrony: false
},
{
name: '醫療保健及社會工作服務業',
percentage: 1.78,
donatesMoney: 130000,
isCrony: false
},
{
name: '製造業',
percentage: 1.33,
donatesMoney: 331416680,
isCrony: false
},
{
name: '金融及保險業',
percentage: 1.02,
donatesMoney: 94453890,
isCrony: true
},
{
name: '專業、科學及技術服務業',
percentage: 1.02,
donatesMoney: 64853880,
isCrony: false
},
{
name: '支援服務業',
percentage: 0.8,
donatesMoney: 21676892,
isCrony: false
}
],
eighth: [
{
name: '礦業及土石採取業',
percentage: 3.65,
donatesMoney: 5117785,
isCrony: true
},
{
name: '電力及燃氣供應業',
percentage: 2.71,
donatesMoney: 3776000,
isCrony: true
},
{
name: '不動產業',
percentage: 1.95,
donatesMoney: 157771200,
isCrony: true
},
{
name: '用水供應及污染整治業',
percentage: 1.51,
donatesMoney: 15228600,
isCrony: true
},
{
name: '製造業',
percentage: 1.02,
donatesMoney: 334577609,
isCrony: false
},
{
name: '教育業',
percentage: 0.98,
donatesMoney: 791000,
isCrony: false
},
{
name: '金融及保險業',
percentage: 0.86,
donatesMoney: 82333000,
isCrony: true
},
{
name: '專業、科學及技術服務業',
percentage: 0.85,
donatesMoney: 58222600,
isCrony: false
},
{
name: '出版、影音製作、傳播及資通訊服務業',
percentage: 0.68,
donatesMoney: 26153938,
isCrony: false
},
{
name: '支援服務業',
percentage: 0.64,
donatesMoney: 31355848,
isCrony: false
}
],
ninth: [
{
name: '礦業及土石採取業',
percentage: 2.88,
donatesMoney: 5966000,
isCrony: true
},
{
name: '電力及燃氣供應業',
percentage: 2.34,
donatesMoney: 5276800,
isCrony: true
},
{
name: '用水供應及污染整治業',
percentage: 1.68,
donatesMoney: 30956985,
isCrony: true
},
{
name: '不動產業',
percentage: 1.65,
donatesMoney: 178249300,
isCrony: true
},
{
name: '製造業',
percentage: 1.01,
donatesMoney: 326942117,
isCrony: false
},
{
name: '金融及保險業',
percentage: 0.78,
donatesMoney: 124262688,
isCrony: true
},
{
name: '支援服務業',
percentage: 0.69,
donatesMoney: 32375500,
isCrony: false
},
{
name: '專業、科學及技術服務業',
percentage: 0.68,
donatesMoney: 82225919,
isCrony: false
},
{
name: '出版、影音製作、傳播及資通訊服務業',
percentage: 0.52,
donatesMoney: 29357400,
isCrony: false
},
{
name: '營建工程業',
percentage: 0.51,
donatesMoney: 111931581,
isCrony: true
}
]
}
export const DATA_NINTH_TOP_TEN_NOT_RE_ELECTED_LEGENDS = [
{
type: 'round-icon',
text: '中國國民黨',
color: '#0071bc'
},
{
type: 'round-icon',
text: '民主進步黨',
color: '#53a66f'
},
{
type: 'round-icon',
text: '時代力量',
color: '#fcc037'
},
{
type: 'round-icon',
text: '親民黨',
color: '#eb6c1f'
},
{
type: 'round-icon',
text: '台灣民眾黨',
color: '#29C7C7'
},
{
type: 'round-icon',
text: '台灣基進',
color: '#A63F24'
}
]
export const DATA_NINTH_TOP_TEN_NOT_RE_ELECTED = {
heads: [
'排名',
'姓名',
'政治獻金<br>總收入',
'營利事業<br>佔總收入比',
'當選',
'第一次參選<br>民選公職'
],
candidates: [
{
name: '王定宇',
party: '民主進步黨',
donatesTotal: 38696425,
donatesCompanyPercentage: '42.46%',
isWon: true,
isChecked: false
},
{
name: '劉世芳',
party: '民主進步黨',
donatesTotal: 34688370,
donatesCompanyPercentage: '37.68%',
isWon: true,
isChecked: false
},
{
name: '黃國昌',
party: '時代力量',
donatesTotal: 32986008,
donatesCompanyPercentage: '14.93%',
isWon: true,
isChecked: true
},
{
name: '洪慈庸',
party: '時代力量',
donatesTotal: 28413178,
donatesCompanyPercentage: '17.59%',
isWon: true,
isChecked: true
},
{
name: '張廖萬堅',
party: '民主進步黨',
donatesTotal: 28311305,
donatesCompanyPercentage: '27.15%',
isWon: true,
isChecked: false
},
{
name: '羅致政',
party: '民主進步黨',
donatesTotal: 27091601,
donatesCompanyPercentage: '26.28%',
isWon: true,
isChecked: false
},
{
name: '李彥秀',
party: '中國國民黨',
donatesTotal: 23941655,
donatesCompanyPercentage: '51.99%',
isWon: true,
isChecked: false
},
{
name: '林俊憲',
party: '民主進步黨',
donatesTotal: 23538660,
donatesCompanyPercentage: '43.64%',
isWon: true,
isChecked: false
},
{
name: '李乾龍',
party: '中國國民黨',
donatesTotal: 23058022,
donatesCompanyPercentage: '34.83%',
isWon: false,
isChecked: false
},
{
name: '黃珊珊',
party: '親民黨',
donatesTotal: 21911229,
donatesCompanyPercentage: '40.14%',
isWon: false,
isChecked: false
}
]
}
export const DATA_NINTH_TOP_TEN_NOT_NEWBIE_ELECTED_LEGENDS = [
{
type: 'round-icon',
text: '中國國民黨',
color: '#0071bc'
},
{
type: 'round-icon',
text: '民主進步黨',
color: '#53a66f'
},
{
type: 'round-icon',
text: '時代力量',
color: '#fcc037'
}
]
export const DATA_NINTH_TOP_TEN_NOT_NEWBIE_ELECTED = {
heads: [
'排名',
'姓名',
'政治獻金<br>總收入',
'營利事業<br>佔總收入比',
'當選',
'政治世家'
],
candidates: [
{
name: '黃國昌',
party: '時代力量',
donatesTotal: 32986008,
donatesCompanyPercentage: '14.93%',
isWon: true,
isChecked: false
},
{
name: '洪慈庸',
party: '時代力量',
donatesTotal: 28413178,
donatesCompanyPercentage: '17.59%',
isWon: true,
isChecked: false
},
{
name: '蘇巧慧',
party: '民主進步黨',
donatesTotal: 20398298,
donatesCompanyPercentage: '32.89%',
isWon: true,
isChecked: true
},
{
name: '鍾易仲',
party: '中國國民黨',
donatesTotal: 16367803,
donatesCompanyPercentage: '15.21%',
isWon: false,
isChecked: true
},
{
name: '張鎔麒',
party: '中國國民黨',
donatesTotal: 15464175,
donatesCompanyPercentage: '54.05%',
isWon: false,
isChecked: true
},
{
name: '陳文彬',
party: '民主進步黨',
donatesTotal: 13876594,
donatesCompanyPercentage: '39.09%',
isWon: false,
isChecked: false
},
{
name: '賴瑞隆',
party: '民主進步黨',
donatesTotal: 13801207,
donatesCompanyPercentage: '47.6%',
isWon: true,
isChecked: false
},
{
name: '蔣萬安',
party: '中國國民黨',
donatesTotal: 13466432,
donatesCompanyPercentage: '30.63%',
isWon: true,
isChecked: true
},
{
name: '林昶佐',
party: '時代力量',
donatesTotal: 12580453,
donatesCompanyPercentage: '19.51%',
isWon: true,
isChecked: false
},
{
name: '黃韻涵',
party: '中國國民黨',
donatesTotal: 10241024,
donatesCompanyPercentage: '30.72%',
isWon: false,
isChecked: true
}
]
}
export const DATA_NINTH_CANDIDATE_DONATES_EXP_LEGENDS = [
{
type: 'round-icon',
text: '中國國民黨',
color: '#0071bc'
},
{
type: 'round-icon',
text: '民主進步黨',
color: '#53a66f'
},
{
type: 'round-icon',
text: '時代力量',
color: '#fcc037'
},
{
type: 'round-icon',
text: '親民黨',
color: '#eb6c1f'
},
{
type: 'round-icon',
text: '民國黨',
color: '#d8d8d8'
},
{
type: 'round-icon',
text: '無黨籍',
color: '#736357'
},
{
type: 'round-icon',
text: '無黨團結聯盟',
color: '#c7195c'
}
]
export const DATA_NINTH_CANDIDATE_DONATES_EXP = [
{
name: '柯建銘',
party: '民主進步黨',
donatesTotal: 51641147,
donatesCompany: 26915133,
exp: 23
},
{
name: '李慶華',
party: '中國國民黨',
donatesTotal: 14134468,
donatesCompany: 5700000,
exp: 23
},
{
name: '丁守中',
party: '中國國民黨',
donatesTotal: 49603735,
donatesCompany: 19499800,
exp: 20
},
{
name: '蔡煌瑯',
party: '民主進步黨',
donatesTotal: 23668969,
donatesCompany: 8180000,
exp: 17.4
},
{
name: '盧秀燕',
party: '中國國民黨',
donatesTotal: 36927974,
donatesCompany: 15213900,
exp: 17
},
{
name: '羅明才',
party: '中國國民黨',
donatesTotal: 28683969,
donatesCompany: 14098000,
exp: 17
},
{
name: '楊瓊瓔',
party: '中國國民黨',
donatesTotal: 27469012,
donatesCompany: 8966000,
exp: 17
},
{
name: '林郁方',
party: '中國國民黨',
donatesTotal: 28132351,
donatesCompany: 8838000,
exp: 17
},
{
name: '陳根德',
party: '中國國民黨',
donatesTotal: 23318220,
donatesCompany: 7508000,
exp: 17
},
{
name: '葉宜津',
party: '民主進步黨',
donatesTotal: 18817904,
donatesCompany: 7348000,
exp: 17
},
{
name: '沈智慧',
party: '中國國民黨',
donatesTotal: 13537229,
donatesCompany: 2363800,
exp: 15
},
{
name: '高志鵬',
party: '民主進步黨',
donatesTotal: 28658947,
donatesCompany: 11318000,
exp: 14
},
{
name: '賴士葆',
party: '中國國民黨',
donatesTotal: 26831760,
donatesCompany: 10650000,
exp: 14
},
{
name: '楊麗環',
party: '中國國民黨',
donatesTotal: 24846677,
donatesCompany: 8973600,
exp: 14
},
{
name: '林德福',
party: '民主進步黨',
donatesTotal: 25041408,
donatesCompany: 7890000,
exp: 14
},
{
name: '廖國棟',
party: '中國國民黨',
donatesTotal: 15807032,
donatesCompany: 7200000,
exp: 14
},
{
name: '孫大千',
party: '中國國民黨',
donatesTotal: 14485818,
donatesCompany: 7000000,
exp: 14
},
{
name: '高金素梅',
party: '無黨團結聯盟',
donatesTotal: 1807031,
donatesCompany: 1500000,
exp: 14
},
{
name: '紀國棟',
party: '中國國民黨',
donatesTotal: 1457373,
donatesCompany: 100000,
exp: 13.5
},
{
name: '廖婉汝',
party: '中國國民黨',
donatesTotal: 6162689,
donatesCompany: 24000,
exp: 13
},
{
name: '陳朝容',
party: '親民黨',
donatesTotal: 3648443,
donatesCompany: 1140000,
exp: 12
},
{
name: '吳育昇',
party: '中國國民黨',
donatesTotal: 45556665,
donatesCompany: 19478481,
exp: 11
},
{
name: '管碧玲',
party: '民主進步黨',
donatesTotal: 45831478,
donatesCompany: 14440000,
exp: 11
},
{
name: '邱議瑩',
party: '民主進步黨',
donatesTotal: 24547958,
donatesCompany: 12038000,
exp: 11
},
{
name: '費鴻泰',
party: '中國國民黨',
donatesTotal: 34231446,
donatesCompany: 10939000,
exp: 11
},
{
name: '蔡錦隆',
party: '中國國民黨',
donatesTotal: 21139370,
donatesCompany: 6842900,
exp: 11
},
{
name: '林滄敏',
party: '中國國民黨',
donatesTotal: 18473735,
donatesCompany: 6212000,
exp: 11
},
{
name: '黃志雄',
party: '中國國民黨',
donatesTotal: 17677620,
donatesCompany: 3351500,
exp: 11
},
{
name: '黃偉哲',
party: '民主進步黨',
donatesTotal: 14012382,
donatesCompany: 3218000,
exp: 11
},
{
name: '林淑芬',
party: '民主進步黨',
donatesTotal: 16525720,
donatesCompany: 2610000,
exp: 11
},
{
name: '張慶忠',
party: '中國國民黨',
donatesTotal: 3774045,
donatesCompany: 2191000,
exp: 11
},
{
name: '孔文吉',
party: '中國國民黨',
donatesTotal: 8581591,
donatesCompany: 2140000,
exp: 11
},
{
name: '林岱樺',
party: '民主進步黨',
donatesTotal: 30102629,
donatesCompany: 8639000,
exp: 10.9
},
{
name: '蕭美琴',
party: '民主進步黨',
donatesTotal: 27116307,
donatesCompany: 9985600,
exp: 10
},
{
name: '陳學聖',
party: '中國國民黨',
donatesTotal: 23972541,
donatesCompany: 9577600,
exp: 10
},
{
name: '劉文雄',
party: '親民黨',
donatesTotal: 8702245,
donatesCompany: 1500000,
exp: 9
},
{
name: '陳明文',
party: '民主進步黨',
donatesTotal: 14969316,
donatesCompany: 6516000,
exp: 8.8
},
{
name: '陳亭妃',
party: '民主進步黨',
donatesTotal: 28087860,
donatesCompany: 11275990,
exp: 8
},
{
name: '蘇震清',
party: '民主進步黨',
donatesTotal: 21846045,
donatesCompany: 7457985,
exp: 8
},
{
name: '王進士',
party: '中國國民黨',
donatesTotal: 18106328,
donatesCompany: 4398000,
exp: 8
},
{
name: '鄭汝芬',
party: '中國國民黨',
donatesTotal: 16630839,
donatesCompany: 3524000,
exp: 8
},
{
name: '簡東明',
party: '中國國民黨',
donatesTotal: 8933287,
donatesCompany: 2387000,
exp: 8
},
{
name: '盧嘉辰',
party: '中國國民黨',
donatesTotal: 11213279,
donatesCompany: 1900000,
exp: 7.9
},
{
name: '陳淑慧',
party: '中國國民黨',
donatesTotal: 16873862,
donatesCompany: 1680000,
exp: 7.6
},
{
name: '吳秉叡',
party: '民主進步黨',
donatesTotal: 50205014,
donatesCompany: 20961000,
exp: 7
},
{
name: '蔡其昌',
party: '民主進步黨',
donatesTotal: 44137502,
donatesCompany: 17190000,
exp: 7
},
{
name: '陳超明',
party: '中國國民黨',
donatesTotal: 29502803,
donatesCompany: 13320000,
exp: 7
},
{
name: '李昆澤',
party: '民主進步黨',
donatesTotal: 29726607,
donatesCompany: 10888000,
exp: 7
},
{
name: '張顯耀',
party: '中國國民黨',
donatesTotal: 18185106,
donatesCompany: 6039988,
exp: 7
},
{
name: '陳瑩',
party: '民主進步黨',
donatesTotal: 11190630,
donatesCompany: 3070000,
exp: 7
},
{
name: '蔣乃辛',
party: '中國國民黨',
donatesTotal: 18538521,
donatesCompany: 4660000,
exp: 6.8
},
{
name: '劉建國',
party: '民主進步黨',
donatesTotal: 17779210,
donatesCompany: 4179000,
exp: 6.3
},
{
name: '馬文君',
party: '中國國民黨',
donatesTotal: 16426213,
donatesCompany: 6823000,
exp: 6.1
},
{
name: '鄭寶清',
party: '民主進步黨',
donatesTotal: 12738604,
donatesCompany: 3151000,
exp: 6
},
{
name: '杜文卿',
party: '民主進步黨',
donatesTotal: 3461146,
donatesCompany: 1790000,
exp: 6
},
{
name: '吳成典',
party: '中國國民黨',
donatesTotal: 6774600,
donatesCompany: 200000,
exp: 6
},
{
name: '鄭永金',
party: '無黨籍',
donatesTotal: 4468116,
donatesCompany: 2445000,
exp: 5.9
},
{
name: '王廷升',
party: '中國國民黨',
donatesTotal: 10242283,
donatesCompany: 1300000,
exp: 5.9
},
{
name: '廖正井',
party: '中國國民黨',
donatesTotal: 20953142,
donatesCompany: 8805000,
exp: 5.7
},
{
name: '郝龍斌',
party: '中國國民黨',
donatesTotal: 20052500,
donatesCompany: 8380000,
exp: 5.1
},
{
name: '張碩文',
party: '親民黨',
donatesTotal: 7358957,
donatesCompany: 1200000,
exp: 4.4
},
{
name: '邱志偉',
party: '民主進步黨',
donatesTotal: 38603507,
donatesCompany: 21244000,
exp: 4
},
{
name: '王惠美',
party: '中國國民黨',
donatesTotal: 40045127,
donatesCompany: 16750470,
exp: 4
},
{
name: '許智傑',
party: '民主進步黨',
donatesTotal: 26575413,
donatesCompany: 12684000,
exp: 4
},
{
name: '姚文智',
party: '民主進步黨',
donatesTotal: 32062954,
donatesCompany: 12474000,
exp: 4
},
{
name: '趙天麟',
party: '民主進步黨',
donatesTotal: 36633614,
donatesCompany: 11768000,
exp: 4
},
{
name: '何欣純',
party: '民主進步黨',
donatesTotal: 31704443,
donatesCompany: 8893000,
exp: 4
},
{
name: '陳歐珀',
party: '民主進步黨',
donatesTotal: 16775101,
donatesCompany: 6223000,
exp: 4
},
{
name: '江惠貞',
party: '中國國民黨',
donatesTotal: 22363741,
donatesCompany: 5750000,
exp: 4
},
{
name: '李俊俋',
party: '民主進步黨',
donatesTotal: 21080039,
donatesCompany: 5424836,
exp: 4
},
{
name: '江啟臣',
party: '中國國民黨',
donatesTotal: 22789873,
donatesCompany: 4726470,
exp: 4
},
{
name: '劉櫂豪',
party: '民主進步黨',
donatesTotal: 9865283,
donatesCompany: 3151000,
exp: 4
},
{
name: '林國正',
party: '中國國民黨',
donatesTotal: 12197628,
donatesCompany: 2967000,
exp: 4
},
{
name: '吳宜臻',
party: '民主進步黨',
donatesTotal: 9276301,
donatesCompany: 1889000,
exp: 4
},
{
name: '楊曜',
party: '民主進步黨',
donatesTotal: 7150834,
donatesCompany: 1696000,
exp: 4
},
{
name: '陳雪生',
party: '無黨籍',
donatesTotal: 6812273,
donatesCompany: 1150000,
exp: 4
},
{
name: '呂玉玲',
party: '中國國民黨',
donatesTotal: 8574500,
donatesCompany: 1120000,
exp: 4
},
{
name: '吳育仁',
party: '中國國民黨',
donatesTotal: 8908389,
donatesCompany: 955000,
exp: 4
},
{
name: '顏寬恒',
party: '中國國民黨',
donatesTotal: 27809014,
donatesCompany: 13349000,
exp: 3
},
{
name: '蘇治芬',
party: '民主進步黨',
donatesTotal: 18920419,
donatesCompany: 8644000,
exp: 3
},
{
name: '鄭運鵬',
party: '民主進步黨',
donatesTotal: 14278367,
donatesCompany: 6217000,
exp: 3
},
{
name: '林為洲',
party: '中國國民黨',
donatesTotal: 5885624,
donatesCompany: 400000,
exp: 3
},
{
name: '康世儒',
party: '民國黨',
donatesTotal: 1658013,
donatesCompany: 220000,
exp: 2.8
},
{
name: '黃國書',
party: '民主進步黨',
donatesTotal: 33422365,
donatesCompany: 8943500,
exp: 1
},
{
name: '莊瑞雄',
party: '民主進步黨',
donatesTotal: 14645889,
donatesCompany: 7148000,
exp: 1
},
{
name: '陳素月',
party: '民主進步黨',
donatesTotal: 22267253,
donatesCompany: 6739500,
exp: 1
},
{
name: '許淑華',
party: '中國國民黨',
donatesTotal: 15975245,
donatesCompany: 5940000,
exp: 1
},
{
name: '徐志榮',
party: '中國國民黨',
donatesTotal: 13313980,
donatesCompany: 4130000,
exp: 1
},
{
name: '劉世芳',
party: '民主進步黨',
donatesTotal: 34688370,
donatesCompany: 13070000,
exp: 0.4
},
{
name: '王定宇',
party: '民主進步黨',
donatesTotal: 38696425,
donatesCompany: 16430000,
exp: 0
},
{
name: '李彥秀',
party: '中國國民黨',
donatesTotal: 23941655,
donatesCompany: 12446800,
exp: 0
},
{
name: '林俊憲',
party: '民主進步黨',
donatesTotal: 23538660,
donatesCompany: 10272500,
exp: 0
},
{
name: '蔡易餘',
party: '民主進步黨',
donatesTotal: 19647445,
donatesCompany: 7981604,
exp: 0
},
{
name: '張廖萬堅',
party: '民主進步黨',
donatesTotal: 28311305,
donatesCompany: 7686000,
exp: 0
},
{
name: '羅致政',
party: '民主進步黨',
donatesTotal: 27091601,
donatesCompany: 7118600,
exp: 0
},
{
name: '吳思瑤',
party: '民主進步黨',
donatesTotal: 18063968,
donatesCompany: 7097200,
exp: 0
},
{
name: '蘇巧慧',
party: '民主進步黨',
donatesTotal: 20398298,
donatesCompany: 6710000,
exp: 0
},
{
name: '賴瑞隆',
party: '民主進步黨',
donatesTotal: 13801207,
donatesCompany: 6569000,
exp: 0
},
{
name: '鍾佳濱',
party: '民主進步黨',
donatesTotal: 21041164,
donatesCompany: 5430350,
exp: 0
},
{
name: '洪慈庸',
party: '時代力量',
donatesTotal: 28413178,
donatesCompany: 4996646,
exp: 0
},
{
name: '黃國昌',
party: '時代力量',
donatesTotal: 32986008,
donatesCompany: 4925000,
exp: 0
},
{
name: '吳琪銘',
party: '民主進步黨',
donatesTotal: 9963400,
donatesCompany: 4898000,
exp: 0
},
{
name: '張宏陸',
party: '民主進步黨',
donatesTotal: 9849551,
donatesCompany: 4543000,
exp: 0
},
{
name: '蔡適應',
party: '民主進步黨',
donatesTotal: 9779983,
donatesCompany: 4360000,
exp: 0
},
{
name: '陳賴素美',
party: '民主進步黨',
donatesTotal: 10665888,
donatesCompany: 4207600,
exp: 0
},
{
name: '蔣萬安',
party: '中國國民黨',
donatesTotal: 13466432,
donatesCompany: 4125000,
exp: 0
},
{
name: '黃秀芳',
party: '民主進步黨',
donatesTotal: 13442557,
donatesCompany: 3941310,
exp: 0
},
{
name: '洪宗熠',
party: '民主進步黨',
donatesTotal: 13547434,
donatesCompany: 3646000,
exp: 0
},
{
name: '林昶佐',
party: '時代力量',
donatesTotal: 12580453,
donatesCompany: 2454666,
exp: 0
},
{
name: '楊鎮浯',
party: '中國國民黨',
donatesTotal: 8572853,
donatesCompany: 2100000,
exp: 0
},
{
name: '趙正宇',
party: '無黨籍',
donatesTotal: 3550319,
donatesCompany: 1500000,
exp: 0
},
{
name: '江永昌',
party: '民主進步黨',
donatesTotal: 10074838,
donatesCompany: 1491700,
exp: 0
},
{
name: '呂孫綾',
party: '民主進步黨',
donatesTotal: 782640,
donatesCompany: 100000,
exp: 0
}
]
export const DATA_ORDINAL_PARTY_DONATES_FROM_LEGENDS = {
seventh: [
{
type: 'round-icon',
text: '第七屆中國國民黨',
color: '#0071bc'
},
{
type: 'round-icon',
text: '第七屆民主進步黨',
color: '#53a66f'
}
],
eighth: [
{
type: 'round-icon',
text: '第八屆中國國民黨',
color: '#0071bc'
},
{
type: 'round-icon',
text: '第八屆民主進步黨',
color: '#53a66f'
}
],
ninth: [
{
type: 'round-icon',
text: '第九屆中國國民黨',
color: '#0071bc'
},
{
type: 'round-icon',
text: '第九屆民主進步黨',
color: '#53a66f'
},
{
type: 'round-icon',
text: '第九屆時代力量',
color: '#fcc037'
}
],
tenth: [
{
type: 'round-icon',
text: '第十屆民主進步黨',
color: '#53a66f'
},
{
type: 'round-icon',
text: '第十屆時代力量',
color: '#fcc037'
},
{
type: 'round-icon',
text: '第十屆台灣基進',
color: '#A63F24'
},
{
type: 'round-icon',
text: '第十屆中國國民黨',
color: '#0071bc'
}
]
}
export const DATA_ORDINAL_PARTY_DONATES_FROM = {
categories: [
'個人',
'營利事業',
'政黨',
'人民團體',
'匿名',
'其他收入'
],
seventh: {
kmt: [
{
party: '中國國民黨',
category: '個人',
percentage: 27.39
},
{
party: '中國國民黨',
category: '營利事業',
percentage: 36.83
},
{
party: '中國國民黨',
category: '政黨',
percentage: 32.77
},
{
party: '中國國民黨',
category: '人民團體',
percentage: 2.72
},
{
party: '中國國民黨',
category: '匿名',
percentage: 0.18
},
{
party: '中國國民黨',
category: '其他收入',
percentage: 0.06
}
],
dpp: [
{
party: '民主進步黨',
category: '個人',
percentage: 46.81
},
{
party: '民主進步黨',
category: '營利事業',
percentage: 46.06
},
{
party: '民主進步黨',
category: '政黨',
percentage: 3.69
},
{
party: '民主進步黨',
category: '人民團體',
percentage: 2.93
},
{
party: '民主進步黨',
category: '匿名',
percentage: 0.40
},
{
party: '民主進步黨',
category: '其他收入',
percentage: 0.07
}
]
},
eighth: {
kmt: [
{
party: '中國國民黨',
category: '個人',
percentage: 40.61
},
{
party: '中國國民黨',
category: '營利事業',
percentage: 37.15
},
{
party: '中國國民黨',
category: '政黨',
percentage: 19.86
},
{
party: '中國國民黨',
category: '人民團體',
percentage: 2.18
},
{
party: '中國國民黨',
category: '匿名',
percentage: 0.16
},
{
party: '中國國民黨',
category: '其他收入',
percentage: 0.008
}
],
dpp: [
{
party: '民主進步黨',
category: '個人',
percentage: 65.51
},
{
party: '民主進步黨',
category: '營利事業',
percentage: 28.94
},
{
party: '民主進步黨',
category: '政黨',
percentage: 2.19
},
{
party: '民主進步黨',
category: '人民團體',
percentage: 1.84
},
{
party: '民主進步黨',
category: '匿名',
percentage: 1.48
},
{
party: '民主進步黨',
category: '其他收入',
percentage: 0.007
}
]
},
ninth: {
kmt: [
{
party: '中國國民黨',
category: '個人',
percentage: 30.65
},
{
party: '中國國民黨',
category: '營利事業',
percentage: 30.84
},
{
party: '中國國民黨',
category: '政黨',
percentage: 36.43
},
{
party: '中國國民黨',
category: '人民團體',
percentage: 1.97
},
{
party: '中國國民黨',
category: '匿名',
percentage: 0.08
},
{
party: '中國國民黨',
category: '其他收入',
percentage: 0.01
}
],
dpp: [
{
party: '民主進步黨',
category: '個人',
percentage: 58.24
},
{
party: '民主進步黨',
category: '營利事業',
percentage: 36.65
},
{
party: '民主進步黨',
category: '政黨',
percentage: 1.18
},
{
party: '民主進步黨',
category: '人民團體',
percentage: 2.50
},
{
party: '民主進步黨',
category: '匿名',
percentage: 1.39
},
{
party: '民主進步黨',
category: '其他收入',
percentage: 0.01
}
],
npp: [
{
party: '時代力量',
category: '個人',
percentage: 74.25
},
{
party: '時代力量',
category: '營利事業',
percentage: 15.96
},
{
party: '時代力量',
category: '政黨',
percentage: 2.14
},
{
party: '時代力量',
category: '人民團體',
percentage: 1.28
},
{
party: '時代力量',
category: '匿名',
percentage: 6.33
},
{
party: '時代力量',
category: '其他收入',
percentage: 0.01
}
]
},
tenth: {
dpp: [
{
party: '民主進步黨',
category: '個人',
percentage: 54.69
},
{
party: '民主進步黨',
category: '營利事業',
percentage: 35.24
},
{
party: '民主進步黨',
category: '政黨',
percentage: 7.17
},
{
party: '民主進步黨',
category: '人民團體',
percentage: 2.23
},
{
party: '民主進步黨',
category: '匿名',
percentage: 0.68
},
{
party: '民主進步黨',
category: '其他收入',
percentage: 0.01
}
],
npp: [
{
party: '時代力量',
category: '個人',
percentage: 79.16
},
{
party: '時代力量',
category: '營利事業',
percentage: 7.66
},
{
party: '時代力量',
category: '政黨',
percentage: 4.40
},
{
party: '時代力量',
category: '人民團體',
percentage: 1.14
},
{
party: '時代力量',
category: '匿名',
percentage: 7.63
},
{
party: '時代力量',
category: '其他收入',
percentage: 0.00
}
],
tsp: [
{
party: '台灣基進',
category: '個人',
percentage: 83.13
},
{
party: '台灣基進',
category: '營利事業',
percentage: 6.15
},
{
party: '台灣基進',
category: '政黨',
percentage: 0.00
},
{
party: '台灣基進',
category: '人民團體',
percentage: 0.00
},
{
party: '台灣基進',
category: '匿名',
percentage: 10.71
},
{
party: '台灣基進',
category: '其他收入',
percentage: 0.01
}
],
kmt: [
{
party: '中國國民黨',
category: '個人',
percentage: 52.47
},
{
party: '中國國民黨',
category: '營利事業',
percentage: 42.30
},
{
party: '中國國民黨',
category: '政黨',
percentage: 1.92
},
{
party: '中國國民黨',
category: '人民團體',
percentage: 2.87
},
{
party: '中國國民黨',
category: '匿名',
percentage: 0.43
},
{
party: '中國國民黨',
category: '其他收入',
percentage: 0.00
}
]
}
}
export const GROUPS_TOP_TEN_DONATES_SEVENTH_EIGHTH_NINTH = [
'遠東集團',
'興富發集團',
'金鼎證券集團',
'仰德集團',
'宏泰集團',
'櫻花集團',
'燁聯鋼鐵集團',
'中纖集團',
'建新',
'日月光集團'
]
|
zj-dreamly/my-program-learning | java/io/src/main/java/com/github/zj/dreamly/socket/chatroom/library/box/AbsByteArrayReceivePacket.java | <filename>java/io/src/main/java/com/github/zj/dreamly/socket/chatroom/library/box/AbsByteArrayReceivePacket.java<gh_stars>10-100
package com.github.zj.dreamly.socket.chatroom.library.box;
import com.github.zj.dreamly.socket.chatroom.library.core.ReceivePacket;
import java.io.ByteArrayOutputStream;
/**
* 定义最基础的基于{@link ByteArrayOutputStream}的输出接收包
*
* @param <Entity> 对应的实体范性,需定义{@link ByteArrayOutputStream}流最终转化为什么数据实体
* @author 苍海之南
*/
public abstract class AbsByteArrayReceivePacket<Entity> extends ReceivePacket<ByteArrayOutputStream, Entity> {
public AbsByteArrayReceivePacket(long len) {
super(len);
}
/**
* 创建流操作直接返回一个{@link ByteArrayOutputStream}流
*
* @return {@link ByteArrayOutputStream}
*/
@Override
protected final ByteArrayOutputStream createStream() {
return new ByteArrayOutputStream((int) length);
}
}
|
Abhisheknishant/Flint | src/gui/main-frame.h | /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */
#ifndef FLINT_GUI_MAIN_FRAME_H_
#define FLINT_GUI_MAIN_FRAME_H_
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-qual"
#include <wx/wx.h>
#include <wx/aui/aui.h>
#include <wx/filehistory.h>
#pragma GCC diagnostic pop
#include "flint/ctrl.h"
namespace flint {
namespace gui {
class Document;
class MainFrame : public wxFrame
{
public:
explicit MainFrame(wxArrayString &input_files);
~MainFrame();
ctrl::Argument &arg() {return arg_;}
void MakePauseAvailable();
void MakeResumeAvailable();
void ResetControl();
bool OpenFile(const wxString &path);
void OpenSubFrame(Document *document);
private:
void OnOpen(wxCommandEvent &event);
void OnRecentFile(wxCommandEvent &event);
void OnClose(wxCommandEvent &event);
void OnAbout(wxCommandEvent &event);
void OnExit(wxCommandEvent &event);
void OnSaveConfig(wxCommandEvent &event);
void OnSaveConfigAs(wxCommandEvent &event);
void OnExportToC(wxCommandEvent &event);
void OnNotebookPageClose(wxAuiNotebookEvent &event);
void OnNotebookPageClosed(wxAuiNotebookEvent &event);
void OnRun(wxCommandEvent &event);
void OnPause(wxCommandEvent &event);
void OnResume(wxCommandEvent &event);
void OnPreferences(wxCommandEvent &event);
void OnIdle(wxIdleEvent &event);
void OnCloseWindow(wxCloseEvent &event);
wxArrayString &input_files_;
wxAuiManager manager_;
wxAuiNotebook *notebook_;
wxFileHistory history_;
wxMenuItem *item_save_config_;
wxMenuItem *item_save_config_as_;
wxMenuItem *item_export_to_c_;
wxMenuItem *item_run_;
wxMenuItem *item_pause_;
wxMenuItem *item_resume_;
wxButton *button_run_;
int next_open_id_;
int next_simulation_id_;
wxString last_dir_;
wxString config_dir_; // initially empty, meaning user choose a directory first
ctrl::Argument arg_;
};
}
}
#endif
|
kajsa/bson4jackson | src/main/java/de/undercouch/bson4jackson/types/JavaScript.java | package de.undercouch.bson4jackson.types;
import java.util.Map;
/**
* Embedded JavaScript code with an optional scope (i.e. an embedded BSON document)
* @author <NAME>
*/
public class JavaScript {
/**
* The actual code
*/
protected final String _code;
/**
* The scope (may be null)
*/
protected final Map<String, Object> _scope;
/**
* Constructs a new JavaScript object
* @param code the actual code
*/
public JavaScript(String code) {
this(code, null);
}
/**
* Constructs a new JavaScript object
* @param code the actual code
* @param scope the scope (may be null)
*/
public JavaScript(String code, Map<String, Object> scope) {
_code = code;
_scope = scope;
}
/**
* @return the actual code
*/
public String getCode() {
return _code;
}
/**
* @return the scope (may be null)
*/
public Map<String, Object> getScope() {
return _scope;
}
}
|
juliocnsouzadev/eip | jms_labs/jms-log/jms1.1/src/share/javax/jms/TopicSession.java | <gh_stars>0
/*
* @(#)TopicSession.java 1.40 02/04/10
*
* Copyright 1997-2002 Sun Microsystems, Inc. All Rights Reserved.
*
* SUN PROPRIETARY/CONFIDENTIAL.
* This software is the proprietary information of Sun Microsystems, Inc.
* Use is subject to license terms.
*
*/
package javax.jms;
/** A <CODE>TopicSession</CODE> object provides methods for creating
* <CODE>TopicPublisher</CODE>, <CODE>TopicSubscriber</CODE>, and
* <CODE>TemporaryTopic</CODE> objects. It also provides a method for
* deleting its client's durable subscribers.
*
*<P>A <CODE>TopicSession</CODE> is used for creating Pub/Sub specific
* objects. In general, use the <CODE>Session</CODE> object, and
* use <CODE>TopicSession</CODE> only to support
* existing code. Using the <CODE>Session</CODE> object simplifies the
* programming model, and allows transactions to be used across the two
* messaging domains.
*
* <P>A <CODE>TopicSession</CODE> cannot be used to create objects specific to the
* point-to-point domain. The following methods inherit from
* <CODE>Session</CODE>, but must throw an
* <CODE>IllegalStateException</CODE>
* if used from <CODE>TopicSession</CODE>:
*<UL>
* <LI><CODE>createBrowser</CODE>
* <LI><CODE>createQueue</CODE>
* <LI><CODE>createTemporaryQueue</CODE>
*</UL>
*
* @version 1.1 - April 9, 2002
* @author <NAME>
* @author <NAME>
* @author <NAME>
*
* @see javax.jms.Session
* @see javax.jms.Connection#createSession(boolean, int)
* @see javax.jms.TopicConnection#createTopicSession(boolean, int)
* @see javax.jms.XATopicSession#getTopicSession()
*/
public interface TopicSession extends Session {
/** Creates a topic identity given a <CODE>Topic</CODE> name.
*
* <P>This facility is provided for the rare cases where clients need to
* dynamically manipulate topic identity. This allows the creation of a
* topic identity with a provider-specific name. Clients that depend
* on this ability are not portable.
*
* <P>Note that this method is not for creating the physical topic.
* The physical creation of topics is an administrative task and is not
* to be initiated by the JMS API. The one exception is the
* creation of temporary topics, which is accomplished with the
* <CODE>createTemporaryTopic</CODE> method.
*
* @param topicName the name of this <CODE>Topic</CODE>
*
* @return a <CODE>Topic</CODE> with the given name
*
* @exception JMSException if the session fails to create a topic
* due to some internal error.
*/
Topic
createTopic(String topicName) throws JMSException;
/** Creates a nondurable subscriber to the specified topic.
*
* <P>A client uses a <CODE>TopicSubscriber</CODE> object to receive
* messages that have been published to a topic.
*
* <P>Regular <CODE>TopicSubscriber</CODE> objects are not durable.
* They receive only messages that are published while they are active.
*
* <P>In some cases, a connection may both publish and subscribe to a
* topic. The subscriber <CODE>NoLocal</CODE> attribute allows a subscriber
* to inhibit the delivery of messages published by its own connection.
* The default value for this attribute is false.
*
* @param topic the <CODE>Topic</CODE> to subscribe to
*
* @exception JMSException if the session fails to create a subscriber
* due to some internal error.
* @exception InvalidDestinationException if an invalid topic is specified.
*/
TopicSubscriber
createSubscriber(Topic topic) throws JMSException;
/** Creates a nondurable subscriber to the specified topic, using a
* message selector or specifying whether messages published by its
* own connection should be delivered to it.
*
* <P>A client uses a <CODE>TopicSubscriber</CODE> object to receive
* messages that have been published to a topic.
*
* <P>Regular <CODE>TopicSubscriber</CODE> objects are not durable.
* They receive only messages that are published while they are active.
*
* <P>Messages filtered out by a subscriber's message selector will
* never be delivered to the subscriber. From the subscriber's
* perspective, they do not exist.
*
* <P>In some cases, a connection may both publish and subscribe to a
* topic. The subscriber <CODE>NoLocal</CODE> attribute allows a subscriber
* to inhibit the delivery of messages published by its own connection.
* The default value for this attribute is false.
*
* @param topic the <CODE>Topic</CODE> to subscribe to
* @param messageSelector only messages with properties matching the
* message selector expression are delivered. A value of null or
* an empty string indicates that there is no message selector
* for the message consumer.
* @param noLocal if set, inhibits the delivery of messages published
* by its own connection
*
* @exception JMSException if the session fails to create a subscriber
* due to some internal error.
* @exception InvalidDestinationException if an invalid topic is specified.
* @exception InvalidSelectorException if the message selector is invalid.
*/
TopicSubscriber
createSubscriber(Topic topic,
String messageSelector,
boolean noLocal) throws JMSException;
/** Creates a durable subscriber to the specified topic.
*
* <P>If a client needs to receive all the messages published on a
* topic, including the ones published while the subscriber is inactive,
* it uses a durable <CODE>TopicSubscriber</CODE>. The JMS provider
* retains a record of this
* durable subscription and insures that all messages from the topic's
* publishers are retained until they are acknowledged by this
* durable subscriber or they have expired.
*
* <P>Sessions with durable subscribers must always provide the same
* client identifier. In addition, each client must specify a name that
* uniquely identifies (within client identifier) each durable
* subscription it creates. Only one session at a time can have a
* <CODE>TopicSubscriber</CODE> for a particular durable subscription.
*
* <P>A client can change an existing durable subscription by creating
* a durable <CODE>TopicSubscriber</CODE> with the same name and a new
* topic and/or
* message selector. Changing a durable subscriber is equivalent to
* unsubscribing (deleting) the old one and creating a new one.
*
* <P>In some cases, a connection may both publish and subscribe to a
* topic. The subscriber <CODE>NoLocal</CODE> attribute allows a subscriber
* to inhibit the delivery of messages published by its own connection.
* The default value for this attribute is false.
*
* @param topic the non-temporary <CODE>Topic</CODE> to subscribe to
* @param name the name used to identify this subscription
*
* @exception JMSException if the session fails to create a subscriber
* due to some internal error.
* @exception InvalidDestinationException if an invalid topic is specified.
*/
TopicSubscriber
createDurableSubscriber(Topic topic,
String name) throws JMSException;
/** Creates a durable subscriber to the specified topic, using a
* message selector or specifying whether messages published by its
* own connection should be delivered to it.
*
* <P>If a client needs to receive all the messages published on a
* topic, including the ones published while the subscriber is inactive,
* it uses a durable <CODE>TopicSubscriber</CODE>. The JMS provider
* retains a record of this
* durable subscription and insures that all messages from the topic's
* publishers are retained until they are acknowledged by this
* durable subscriber or they have expired.
*
* <P>Sessions with durable subscribers must always provide the same
* client identifier. In addition, each client must specify a name which
* uniquely identifies (within client identifier) each durable
* subscription it creates. Only one session at a time can have a
* <CODE>TopicSubscriber</CODE> for a particular durable subscription.
* An inactive durable subscriber is one that exists but
* does not currently have a message consumer associated with it.
*
* <P>A client can change an existing durable subscription by creating
* a durable <CODE>TopicSubscriber</CODE> with the same name and a new
* topic and/or
* message selector. Changing a durable subscriber is equivalent to
* unsubscribing (deleting) the old one and creating a new one.
*
* @param topic the non-temporary <CODE>Topic</CODE> to subscribe to
* @param name the name used to identify this subscription
* @param messageSelector only messages with properties matching the
* message selector expression are delivered. A value of null or
* an empty string indicates that there is no message selector
* for the message consumer.
* @param noLocal if set, inhibits the delivery of messages published
* by its own connection
*
* @exception JMSException if the session fails to create a subscriber
* due to some internal error.
* @exception InvalidDestinationException if an invalid topic is specified.
* @exception InvalidSelectorException if the message selector is invalid.
*/
TopicSubscriber
createDurableSubscriber(Topic topic,
String name,
String messageSelector,
boolean noLocal) throws JMSException;
/** Creates a publisher for the specified topic.
*
* <P>A client uses a <CODE>TopicPublisher</CODE> object to publish
* messages on a topic.
* Each time a client creates a <CODE>TopicPublisher</CODE> on a topic, it
* defines a
* new sequence of messages that have no ordering relationship with the
* messages it has previously sent.
*
* @param topic the <CODE>Topic</CODE> to publish to, or null if this is an
* unidentified producer
*
* @exception JMSException if the session fails to create a publisher
* due to some internal error.
* @exception InvalidDestinationException if an invalid topic is specified.
*/
TopicPublisher
createPublisher(Topic topic) throws JMSException;
/** Creates a <CODE>TemporaryTopic</CODE> object. Its lifetime will be that
* of the <CODE>TopicConnection</CODE> unless it is deleted earlier.
*
* @return a temporary topic identity
*
* @exception JMSException if the session fails to create a temporary
* topic due to some internal error.
*/
TemporaryTopic
createTemporaryTopic() throws JMSException;
/** Unsubscribes a durable subscription that has been created by a client.
*
* <P>This method deletes the state being maintained on behalf of the
* subscriber by its provider.
*
* <P>It is erroneous for a client to delete a durable subscription
* while there is an active <CODE>TopicSubscriber</CODE> for the
* subscription, or while a consumed message is part of a pending
* transaction or has not been acknowledged in the session.
*
* @param name the name used to identify this subscription
*
* @exception JMSException if the session fails to unsubscribe to the
* durable subscription due to some internal error.
* @exception InvalidDestinationException if an invalid subscription name
* is specified.
*/
void
unsubscribe(String name) throws JMSException;
}
|
jeonghoonkang/BerePi | apps/hue/512_hue_set.py | # -*- coding: utf-8 -*-
# Author : jeonghoonkang, https://github.com/jeonghoonkang
import httplib
import time
from time import strftime, localtime
hue_uid = "c274b3c285d19cf3480c91439329147"
restcmd = "/api"+hue_uid+"/lights"
str = " "
ip='10.255.255.65x'
latest_time = "initial status"
xhue = [10000,25000,46000,56280]
def shifthue() :
global str
global xhue
global latest_time
xhue.insert(0,xhue[-1])
xhue = xhue[0:4]
#print xhue
try :
conn = httplib.HTTPConnection(ip)
except :
print "fail to connect to Hue GW..."
return
callurl = restcmd + "/4/state"
"""
try:
conn.request("PUT",callurl ,'{"on":false}')
response = conn.getresponse()
data = response.read()
except:
print "keep goging...."
time.sleep(4)
time.sleep(1)
"""
for num in [4,3,2,1] :
callurl = restcmd + "/%s/state"%(num)
#print callurl
huenumber = (xhue[4-num])
try :
conn.request("PUT",callurl ,'{"on":false}')
response = conn.getresponse()
data = response.read()
time.sleep(1)
conn.request("PUT",callurl ,'{"on":true, "sat":254, "bri":254, "hue":%s}'%huenumber)
response = conn.getresponse()
data = response.read()
#print data
time.sleep(1)
latest_time = time_chk()
except (httplib.HTTPException) as e :
print latest_time, "HTTPException", e.args[0]
time.sleep(4)
conn = httplib.HTTPConnection(ip)
#지속적으로 http exception 발생시 email 로 통보
finally :
#print latest_time, "Finally"
time.sleep(0.3)
conn = httplib.HTTPConnection(ip)
def time_chk():
time = strftime("%Y-%m%d %H:%M",localtime())
return time
def hue4on():
global str
conn.request("PUT",restcmd+"/4/state", '{"on":true}')
response = conn.getresponse()
data = response.read()
str = data + '<br>'
time.sleep(2)
return web()
def hue4off():
global str
conn.request("PUT",restcmd+"/4/state", '{"on":false}')
response = conn.getresponse()
data = response.read()
str = data + '<br>'
time.sleep(2)
return web()
if __name__ == "__main__":
# print web()
while True :
shifthue()
time.sleep(5)
|
simon04/radiance | substance/src/main/java/org/pushingpixels/substance/api/watermark/SubstanceWatermark.java | <reponame>simon04/radiance<filename>substance/src/main/java/org/pushingpixels/substance/api/watermark/SubstanceWatermark.java<gh_stars>1-10
/*
* Copyright (c) 2005-2020 <NAME>. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* o Neither the name of the copyright holder nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.pushingpixels.substance.api.watermark;
import org.pushingpixels.substance.api.SubstanceSkin;
import org.pushingpixels.substance.api.trait.SubstanceTrait;
import java.awt.*;
/**
* Interface for watermarks. This class is part of officially supported API.
*
* @author <NAME>
*/
public interface SubstanceWatermark extends SubstanceTrait {
/**
* Draws the watermark on the specified graphics context in the specified
* region.
*
* @param graphics
* Graphics context.
* @param c
* Component that is painted.
* @param x
* Left X of the region.
* @param y
* Top Y of the region.
* @param width
* Region width.
* @param height
* Region height.
*/
void drawWatermarkImage(Graphics graphics, Component c, int x,
int y, int width, int height);
/**
* Updates the current watermark image.
*
* @param skin
* Skin for the watermark.
* @return <code>true</code> if the watermark has been updated successfully,
* <code>false</code> otherwise.
*/
boolean updateWatermarkImage(SubstanceSkin skin);
/**
* Draws the preview of the watermark image.
*
* @param g
* Graphic context.
* @param skin
* Optional skin to use for the preview. Can be ignored by the
* implementation.
* @param x
* the <i>x</i> coordinate of the watermark to be drawn.
* @param y
* The <i>y</i> coordinate of the watermark to be drawn.
* @param width
* The width of the watermark to be drawn.
* @param height
* The height of the watermark to be drawn.
*/
void previewWatermark(Graphics g, SubstanceSkin skin, int x, int y,
int width, int height);
/**
* Disposes the memory associated with <code>this</code> watermark.
*/
void dispose();
}
|
neonkingfr/netzhaut | src/lib/nhrenderer/Main/Renderer.h | <gh_stars>0
#ifndef NH_RENDERER_RENDERER_H
#define NH_RENDERER_RENDERER_H
#ifndef DOXYGEN_SHOULD_SKIP_THIS
/**
* netzhaut - Web Browser Engine
* Copyright (C) 2020 The netzhaut Authors
* Published under MIT
*/
#include "../Common/Types/Private.h"
#endif
/** @addtogroup lib_nhrenderer_structs
* @{
*/
typedef struct nh_renderer_RenderTarget {
nh_gfx_Viewport *Viewport_p;
NH_BOOL render;
} nh_renderer_RenderTarget;
typedef struct nh_renderer_Renderer {
nh_css_LayoutEngine *LayoutEngine_p;
nh_Array RenderTargets;
} nh_renderer_Renderer;
/** @} */
/** @addtogroup lib_nhrenderer_typedefs
* @{
*/
typedef nh_renderer_Renderer *(*nh_renderer_createRenderer_f)(
nh_css_LayoutEngine *LayoutEngine_p
);
typedef NH_RENDERER_RESULT (*nh_renderer_addViewport_f)(
nh_renderer_Renderer *Renderer_p, nh_gfx_Viewport *Viewport_p
);
/** @} */
/** @addtogroup lib_nhrenderer_functions
* @{
*/
nh_renderer_Renderer *nh_renderer_createRenderer(
nh_css_LayoutEngine *LayoutEngine_p
);
NH_RENDERER_RESULT nh_renderer_addViewport(
nh_renderer_Renderer *Renderer_p, nh_gfx_Viewport *Viewport_p
);
/** @} */
#endif
|
allisonverdam/cubes | cubes/sql/query.py | <gh_stars>0
# -*- encoding=utf -*-
"""
cubes.sql.query
~~~~~~~~~~~~~~~
Star/snowflake schema query construction structures
"""
# Note for developers and maintainers
# -----------------------------------
#
# This module is to be remained implemented in a way that it does not use any
# of the Cubes objects. It might use duck-typing and assume objects with
# similar attributes. No calls to Cubes object functions should be allowed
# here.
import logging
from collections import namedtuple
import sqlalchemy as sa
import sqlalchemy.sql as sql
from sqlalchemy.sql.expression import and_
from ..metadata import object_dict
from ..errors import InternalError, ModelError, ArgumentError, HierarchyError
from .. import compat
from ..query import SPLIT_DIMENSION_NAME
from ..query import PointCut, SetCut, RangeCut
from .expressions import compile_attributes
# Default label for all fact keys
FACT_KEY_LABEL = '__fact_key__'
# Attribute -> Column
# IF attribute has no 'expression' then mapping is used
# IF attribute has expression, the expression is used and underlying mappings
"""Physical column (or column expression) reference. `schema` is a database
schema name, `table` is a table (or table expression) name containing the
`column`. `extract` is an element to be extracted from complex data type such
as date or JSON (in postgres). `function` is name of unary function to be
applied on the `column`.
Note that either `extract` or `function` can be used, not both."""
Column = namedtuple("Column", ["schema", "table", "column",
"extract", "function"])
#
# IMPORTANT: If you decide to extend the above Mapping functionality by adding
# other mapping attributes (not recommended, but still) or by changing the way
# how existing attributes are used, make sure that there are NO OTHER COLUMNS
# than the `column` used. Every column used MUST be accounted in the
# relevant_joins() call.
#
# See similar comment in the column() method of the StarSchema.
#
def to_column(obj, default_table=None, default_schema=None):
"""Utility function that will create a `Column` reference object from an
anonymous tuple, dictionary or a similar object. `obj` can also be a
string in form ``schema.table.column`` where shcema or both schema and
table can be ommited. `default_table` and `default_schema` are used when
no table or schema is provided in `obj`.
.. versionadded:: 1.1
"""
if obj is None:
raise ArgumentError("Mapping object can not be None")
if isinstance(obj, compat.string_type):
obj = obj.split(".")
if isinstance(obj, (tuple, list)):
if len(obj) == 1:
column = obj[0]
table = None
schema = None
elif len(obj) == 2:
table, column = obj
schema = None
elif len(obj) == 3:
schema, table, column = obj
else:
raise ArgumentError("Join key can have 1 to 3 items"
" has {}: {}".format(len(obj), obj))
extract = None
function = None
elif hasattr(obj, "get"):
schema = obj.get("schema")
table = obj.get("table")
column = obj.get("column")
extract = obj.get("extract")
function = obj.get("function")
else: # pragma nocover
schema = obj.schema
table = obj.table
extract = obj.extract
function = obj.function
table = table or default_table
schema = schema or default_schema
return Column(schema, table, column, extract, function)
# TODO: remove this and use just Column
JoinKey = namedtuple("JoinKey",
["schema",
"table",
"column"])
def to_join_key(obj):
"""Utility function that will create JoinKey tuple from an anonymous
tuple, dictionary or similar object. `obj` can also be a string in form
``schema.table.column`` where schema or both schema and table can be
ommited. Dictionary representation of a join key has values: ``schema``,
``table`` and ``column``. With the dicitonary representation, the
``column`` can be a list of columns in the same table. Both master and
detail joins have to have the same number of columns in the join key.
Note that Cubes at this low level does not know which table is used for a
dimension, therefore the default dimension schema from mapper's naming can
not be assumed here and has to be explicitly mentioned.
.. versionadded:: 1.1
"""
if obj is None:
return JoinKey(None, None, None)
if isinstance(obj, compat.string_type):
obj = obj.split(".")
if isinstance(obj, (tuple, list)):
if len(obj) == 1:
column = obj[0]
table = None
schema = None
elif len(obj) == 2:
table, column = obj
schema = None
elif len(obj) == 3:
schema, table, column = obj
else:
raise ArgumentError("Join key can have 1 to 3 items"
" has {}: {}".format(len(obj), obj))
elif hasattr(obj, "get"):
schema = obj.get("schema")
table = obj.get("table")
column = obj.get("column")
else: # pragma nocover
schema = obj.schema
table = obj.table
column = obj.column
# Make it immutable and hashable, as the whole Join object has to be
# hashable
if isinstance(column, list):
column = tuple(column)
return JoinKey(schema, table, column)
"""Table join specification. `master` and `detail` are TableColumnReference
tuples. `method` denotes which table members should be considered in the join:
*master* – all master members (left outer join), *detail* – all detail members
(right outer join) and *match* – members must match (inner join)."""
Join = namedtuple("Join",
["master", # Master table (fact in star schema)
"detail", # Detail table (dimension in star schema)
"alias", # Optional alias for the detail table
"method" # Method how the table is joined
]
)
def to_join(obj):
"""Utility conversion function that will create `Join` tuple from an
anonymous tuple, dictionary or similar object.
.. versionadded:: 1.1
"""
if isinstance(obj, (tuple, list)):
alias = None
method = None
if len(obj) == 3:
alias = obj[2]
elif len(obj) == 4:
alias, method = obj[2], obj[3]
elif len(obj) < 2 or len(obj) > 4:
raise ArgumentError("Join object can have 1 to 4 items"
" has {}: {}".format(len(obj), obj))
master = to_join_key(obj[0])
detail = to_join_key(obj[1])
return Join(master, detail, alias, method)
elif hasattr(obj, "get"): # pragma nocover
return Join(to_join_key(obj.get("master")),
to_join_key(obj.get("detail")),
obj.get("alias"),
obj.get("method"))
else: # pragma nocover
return Join(to_join_key(obj.master),
to_join_key(obj.detail),
obj.alias,
obj.method)
# Internal table reference
_TableRef = namedtuple("_TableRef",
["schema", # Database schema
"name", # Table name
"alias", # Optional table alias instead of name
"key", # Table key (for caching or referencing)
"table", # SQLAlchemy Table object, reflected
"join" # join which joins this table as a detail
]
)
class SchemaError(InternalError):
"""Error related to the physical star schema."""
pass
class NoSuchTableError(SchemaError):
"""Error related to the physical star schema."""
pass
class NoSuchAttributeError(SchemaError):
"""Error related to the physical star schema."""
pass
def _format_key(key):
"""Format table key `key` to a string."""
schema, table = key
table = table or "(FACT)"
if schema:
return "{}.{}".format(schema, table)
else:
return table
def _make_compound_key(table, key):
"""Returns a list of columns from `column_key` for `table` representing
potentially a compound key. The `column_key` can be a name of a single
column or list of column names."""
if not isinstance(key, (list, tuple)):
key = [key]
return [table.columns[name] for name in key]
class StarSchema(object):
"""Represents a star/snowflake table schema. Attributes:
* `label` – user specific label for the star schema, used for the schema
identification, debug purposes and logging. Has no effect on the
execution or statement composition.
* `metadata` is a SQLAlchemy metadata object where the snowflake tables
are described.
* `mappings` is a dictionary of snowflake attributes. The keys are
attribute names, the values can be strings, dictionaries or objects with
specific attributes (see below)
* `fact` is a name or a reference to a fact table
* `joins` is a list of join specification (see below)
* `tables` are SQL Alchemy selectables (tables or statements) that are
referenced in the attributes. This dictionary is looked-up first before
the actual metadata. Only table name has to be specified and database
schema should not be used in this case.
* `schema` – default database schema containing tables
The columns can be specified as:
* a string with format: `column`, `table.column` or `schema.table.column`.
When no table is specified, then the fact table is considered.
* as a list of arguments `[[schema,] table,] column`
* `StarColumn` or any object with attributes `schema`, `table`,
`column`, `extract`, `function` can be used.
* a dictionary with keys same as the attributes of `StarColumn` object
Non-object arguments will be stored as a `StarColumn` objects internally.
The joins can be specified as a list of:
* tuples of column specification in form of (`master`, `detail`)
* a dictionary with keys or object with attributes: `master`, `detail`,
`alias` and `method`.
`master` is a specification of a column in the master table (fact) and
`detail` is a specification of a column in the detail table (usually a
dimension). `alias` is an alternative name for the `detail` table to be
joined.
The `method` can be: `match` – ``LEFT INNER JOIN``, `master` – ``LEFT
OUTER JOIN`` or `detail` – ``RIGHT OUTER JOIN``.
Note: It is not in the responsibilities of the `StarSchema` to resolve
arithmetic expressions neither attribute dependencies. It is up to the
caller to resolve these and ask for basic columns only.
.. note::
The `tables` statements need to be aliased.
.. versionadded:: 1.1
"""
def __init__(self, label, metadata, mappings, fact, fact_key='id',
joins=None, tables=None, schema=None):
# TODO: expectation is, that the snowlfake is already localized, the
# owner of the snowflake should generate one snowflake per locale.
# TODO: use `facts` instead of `fact`
if fact is None:
raise ArgumentError("Fact table or table name not specified "
"for star/snowflake schema {}"
.format(label))
self.label = label
self.metadata = metadata
self.mappings = mappings or {}
self.joins = joins or []
self.schema = schema
self.table_expressions = tables or {}
# Cache
# -----
# Keys are logical column labels (keys from `mapping` attribute)
self._columns = {}
# Keys are tuples (schema, table)
self._tables = {}
self.logger = logging.getLogger("cubes.starschema")
# TODO: perform JOIN discovery based on foreign keys
# Fact Table
# ----------
# Fact Initialization
if isinstance(fact, compat.string_type):
self.fact_name = fact
self.fact_table = self.physical_table(fact)
else:
# We expect fact to be a statement
try:
self.fact_name = fact.name
except AttributeError:
raise ArgumentError("Fact table statement requires alias()")
self.fact_table = fact
self.fact_key = fact_key
# Try to get the fact key, if does not exist, then consider the first
# table column as the fact key.
try:
self.fact_key_column = self.fact_table.columns[self.fact_key]
except KeyError:
try:
self.fact_key_column = list(self.fact_table.columns)[0]
except Exception as e:
raise ModelError("Unable to get key column for fact "
"table '%s' in '%s'. Reason: %s"
% (self.fact_name, label, str(e)))
else:
self.fact_key = self.fact_key_column.name
self.fact_key_column = self.fact_key_column.label(FACT_KEY_LABEL)
# Rest of the initialization
# --------------------------
self._collect_tables()
def _collect_tables(self):
"""Collect and prepare all important information about the tables in
the schema. The collected information is a list:
* `table` – SQLAlchemy table or selectable object
* `schema` – original schema name
* `name` – original table or selectable object
* `alias` – alias given to the table or statement
* `join` – join object that joins the table as a detail to the star
Input: schema, fact name, fact table, joins
Output: tables[table_key] = SonwflakeTable()
"""
# Collect the fact table as the root master table
#
fact_table = _TableRef(schema=self.schema,
name=self.fact_name,
alias=self.fact_name,
key=(self.schema, self.fact_name),
table=self.fact_table,
join=None
)
self._tables[fact_table.key] = fact_table
# Collect all the detail tables
# We don't need to collect the master tables as they are expected to
# be referenced as 'details'. The exception is the fact table that is
# provided explicitly for the snowflake schema.
# Collect details for duplicate verification. It sohuld not be
# possible to join one detail multiple times with the same name. Alias
# has to be used.
details = set()
for join in self.joins:
# just ask for the table
if not join.detail.table:
raise ModelError("No detail table specified for a join in "
"schema '{}'. Master of the join is '{}'"
.format(self.label,
_format_key(self._master_key(join))))
table = self.physical_table(join.detail.table,
join.detail.schema)
if join.alias:
table = table.alias(join.alias)
alias = join.alias
else:
alias = join.detail.table
key = (join.detail.schema or self.schema, alias)
if key in details:
raise ModelError("Detail table '{}' joined twice in star"
" schema {}. Join alias is required."
.format(_format_key(key), self.label))
details.add(key)
ref = _TableRef(table=table,
schema=join.detail.schema,
name=join.detail.table,
alias=alias,
key=key,
join=join
)
self._tables[key] = ref
def table(self, key, role=None):
"""Return a table reference for `key` which has form of a
tuple (`schema`, `table`). `schema` should be ``None`` for named table
expressions, which take precedence before the physical tables in the
default schema. If there is no named table expression then physical
table is considered.
The returned object has the following properties:
* `name` – real table name
* `alias` – table alias – always contains a value, regardless whether
the table join provides one or not. If there was no alias provided by
the join, then the physical table name is used.
* `key` – table key – the same as the `key` argument
* `join` – `Join` object that joined the table to the star schema
* `table` – SQLAlchemy `Table` or table expression object
`role` is for debugging purposes to display when there is no such
table, which role of the table was expected, such as master or detail.
"""
if key is None:
raise ArgumentError("Table key should not be None")
key = (key[0] or self.schema, key[1] or self.fact_name)
try:
return self._tables[key]
except KeyError:
if role:
for_role = " (as {})".format(role)
else:
for_role = ""
schema = '"{}".'.format(key[0]) if key[0] else ""
raise SchemaError("Unknown star table {}\"{}\"{}. Missing join?"
.format(schema, key[1], for_role))
def physical_table(self, name, schema=None):
"""Return a physical table or table expression, regardless whether it
exists or not in the star."""
# Return a statement or an explicitly craeted table if it exists
if not schema and name in self.table_expressions:
return self.table_expressions[name]
coalesced_schema = schema or self.schema
try:
table = sa.Table(name,
self.metadata,
autoload=True,
schema=coalesced_schema)
except sa.exc.NoSuchTableError:
in_schema = (" in schema '{}'"
.format(schema)) if schema else ""
msg = "No such fact table '{}'{}.".format(name, in_schema)
raise NoSuchTableError(msg)
return table
def column(self, logical):
"""Return a column for `logical` reference. The returned column will
have a label same as the `logical`.
"""
# IMPORTANT
#
# Note to developers: any column returned from this method
# MUST be somehow represented in the logical model and MUST be
# accounted in the relevant_joins(). For example in custom expressions
# operating on multiple physical columns all physical
# columns must be defined at the higher level attributes objects in
# the cube. This is to access the very base column, that has physical
# representation in a table or a table-like statement.
#
# Yielding non-represented column might result in undefined behavior,
# very likely in unwanted cartesian join – one per unaccounted column.
#
# -- END OF IMPORTANT MESSAGE ---
if logical in self._columns:
return self._columns[logical]
try:
mapping = self.mappings[logical]
except KeyError:
if logical == FACT_KEY_LABEL:
return self.fact_key_column
else:
raise NoSuchAttributeError(logical)
key = (mapping.schema or self.schema, mapping.table or self.fact_name)
ref = self.table(key)
table = ref.table
try:
column = table.columns[mapping.column]
except KeyError:
avail = ", ".join(str(c) for c in table.columns)
raise SchemaError("Unknown column '%s' in table '%s' possible: %s"
% (mapping.column, mapping.table, avail))
# Extract part of the date
if mapping.extract:
column = sql.expression.extract(mapping.extract, column)
if mapping.function:
# FIXME: add some protection here for the function name!
column = getattr(sql.expression.func, mapping.function)(column)
column = column.label(logical)
self._columns[logical] = column
return column
def _master_key(self, join):
"""Generate join master key, use schema defaults"""
return (join.master.schema or self.schema,
join.master.table or self.fact_name)
def _detail_key(self, join):
"""Generate join detail key, use schema defaults"""
# Note: we don't include fact as detail table by default. Fact can not
# be detail (at least for now, we don't have a case where it could be)
return (join.detail.schema or self.schema,
join.alias or join.detail.table)
def required_tables(self, attributes):
"""Get all tables that are required to be joined to get `attributes`.
`attributes` is a list of `StarSchema` attributes (or objects with
same kind of attributes).
"""
# Attribute: (schema, table, column)
# Join: ((schema, table, column), (schema, table, column), alias)
if not self.joins:
self.logger.debug("no joins to be searched for")
# Get the physical mappings for attributes
mappings = [self.mappings[attr] for attr in attributes]
# Generate table keys
relevant = set(self.table((m.schema, m.table)) for m in mappings)
# Dependencies
# ------------
# `required` now contains tables that contain requested `attributes`.
# Nowe we have to resolve all dependencies.
required = {}
while relevant:
table = relevant.pop()
required[table.key] = table
if not table.join:
continue
master = self._master_key(table.join)
if master not in required:
relevant.add(self.table(master))
detail = self._detail_key(table.join)
if detail not in required:
relevant.add(self.table(detail))
# Sort the tables
# ---------------
fact_key = (self.schema, self.fact_name)
fact = self.table(fact_key, "fact master")
masters = {fact_key: fact}
sorted_tables = [fact]
while required:
details = [table for table in list(required.values())
if table.join
and self._master_key(table.join) in masters]
if not details:
break
for detail in details:
masters[detail.key] = detail
sorted_tables.append(detail)
del required[detail.key]
if len(required) > 1:
keys = [_format_key(table.key)
for table in list(required.values())
if table.key != fact_key]
raise ModelError("Some tables are not joined: {}"
.format(", ".join(keys)))
return sorted_tables
# Note: This is "The Method"
# ==========================
def get_star(self, attributes):
"""The main method for generating underlying star schema joins.
Returns a denormalized JOIN expression that includes all relevant
tables containing base `attributes` (attributes representing actual
columns).
Example use:
.. code-block:: python
star = star_schema.star(attributes)
statement = sql.expression.statement(selection,
from_obj=star,
whereclause=condition)
result = engine.execute(statement)
"""
attributes = [str(attr) for attr in attributes]
# Collect all the tables first:
tables = self.required_tables(attributes)
# Dictionary of raw tables and their joined products
# At the end this should contain only one item representing the whole
# star.
star_tables = {table_ref.key:table_ref.table for table_ref in tables}
# Here the `star` contains mapping table key -> table, which will be
# gradually replaced by JOINs
# Perform the joins
# =================
#
# 1. find the column
# 2. construct the condition
# 3. use the appropriate SQL JOIN
# 4. wrap the star with detail
#
# TODO: support MySQL partition (see Issue list)
# First table does not need to be joined. It is the "fact" (or other
# central table) of the schema.
star = tables[0].table
for table in tables[1:]:
if not table.join:
raise ModelError("Missing join for table '{}'"
.format(_format_key(table.key)))
join = table.join
# Get the physical table object (aliased) and already constructed
# key (properly aliased)
detail_table = table.table
detail_key = table.key
# The `table` here is a detail table to be joined. We need to get
# the master table this table joins to:
master = join.master
master_key = self._master_key(join)
# We need plain tables to get columns for prepare the join
# condition. We can't get it form `star`.
# Master table.column
# -------------------
master_table = self.table(master_key).table
try:
master_columns = _make_compound_key(master_table,
master.column)
except KeyError as e:
raise ModelError('Unable to find master key column "{key}" '
'in table "{table}" for star {schema} '
.format(schema=self.label,
key=e,
table=_format_key(master_key)))
# Detail table.column
# -------------------
try:
detail_columns = _make_compound_key(detail_table,
join.detail.column)
except KeyError as e:
raise ModelError('Unable to find detail key column "{key}" '
'in table "{table}" for star {schema} '
.format(schema=self.label,
key=e,
table=_format_key(detail_key)))
if len(master_columns) != len(detail_columns):
raise ModelError("Compound keys for master '{}' and detail "
"'{}' table in star {} have different number"
" of columns"
.format(_format_key(master_key),
_format_key(detail_key),
self.label))
# The JOIN ON condition
# ---------------------
key_conditions = [left == right
for left, right
in zip(master_columns, detail_columns)]
onclause = and_(*key_conditions)
# Determine the join type based on the join method. If the method
# is "detail" then we need to swap the order of the tables
# (products), because SQLAlchemy provides inteface only for
# left-outer join.
left, right = (star, detail_table)
if join.method is None or join.method == "match":
is_outer = False
elif join.method == "master":
is_outer = True
elif join.method == "detail":
# Swap the master and detail tables to perform RIGHT OUTER JOIN
left, right = (right, left)
is_outer = True
else:
raise ModelError("Unknown join method '%s'" % join.method)
star = sql.expression.join(left, right,
onclause=onclause,
isouter=is_outer)
# Consume the detail
if detail_key not in star_tables:
raise ModelError("Detail table '{}' not in star. Missing join?"
.format(_format_key(detail_key)))
# The table is consumed by the join product, becomes the join
# product itself.
star_tables[detail_key] = star
star_tables[master_key] = star
return star
class QueryContext(object):
"""Context for execution of a query with given set of attributes and
underlying star schema. The context is used for providing columns for
attributes and generating conditions for cells. Context is reponsible for
proper compilation of attribute expressions.
Attributes:
* `star` – a SQL expression object representing joined star for base
attributes of the query. See :meth:`StarSchema.get_star` for more
information
.. versionadded:: 1.1
"""
def __init__(self, star_schema, attributes, hierarchies=None,
parameters=None, safe_labels=None):
"""Creates a query context for `cube`.
* `attributes` – list of all attributes that are relevant to the
query. The attributes must be sorted by their dependency.
* `hierarchies` is a dictionary of dimension hierarchies. Keys are
tuples of names (`dimension`, `hierarchy`). The dictionary should
contain default dimensions as (`dimension`, Null) tuples.
* `safe_labels` – if `True` then safe column labels are created. Used
for SQL dialects that don't support characters such as dot ``.`` in
column labels. See :meth:`QueryContext.column` for more
information.
`attributes` are objects that have attributes: `ref` – attribute
reference, `is_base` – `True` when attribute does not depend on any
other attribute and can be directly mapped to a column, `expression` –
arithmetic expression, `function` – aggregate function (for
aggregates only).
Note: in the future the `hierarchies` dictionary might change just to
a hierarchy name (a string), since hierarchies and dimensions will be
both top-level objects.
"""
# Note on why attributes have to be sorted: We don'd have enough
# information here to get all the dependencies and we don't want this
# object to depend on the complex Cube model object, just attributes.
self.star_schema = star_schema
self.attributes = object_dict(attributes, True)
self.hierarchies = hierarchies
self.safe_labels = safe_labels
# Collect base attributes
#
base_names = [attr.ref for attr in attributes if attr.is_base]
dependants = [attr for attr in attributes if not attr.is_base]
# This is "the star" to be used by the owners of the context to select
# from.
#
self.star = star_schema.get_star(base_names)
# TODO: determne from self.star
# Collect all the columns
#
bases = {attr:self.star_schema.column(attr) for attr in base_names}
bases[FACT_KEY_LABEL] = self.star_schema.fact_key_column
self._columns = compile_attributes(bases, dependants, parameters,
star_schema.label)
self.label_attributes = {}
if self.safe_labels:
# Re-label the columns using safe labels. It is up to the owner of
# the context to determine which column is which attribute
for i, item in enumerate(list(self._columns.items())):
attr, column = item
label = "a{}".format(i)
self._columns[attr] = column.label(label)
self.label_attributes[label] = attr
else:
for attr in attributes:
attr = attr.ref
column = self._columns[attr]
self._columns[attr] = column.label(attr)
# Identity mappign
self.label_attributes[attr] = attr
def column(self, ref):
"""Get a column expression for attribute with reference `ref`. Column
has the same label as the attribute reference, unless `safe_labels` is
provided to the query context. If `safe_labels` translation is
provided, then the column has label according to the translation
dictionary."""
try:
return self._columns[ref]
except KeyError as e:
# This should not happen under normal circumstances. If this
# exception is raised, it very likely means that the owner of the
# query contexts forgot to do something.
raise InternalError("Missing column '{}'. Query context not "
"properly initialized or dependencies were "
"not correctly ordered?".format(ref))
def get_labels(self, columns):
"""Returns real attribute labels for columns `columns`. It is highly
recommended that the owner of the context uses this method before
iterating over statement result."""
if self.safe_labels:
return [self.label_attributes.get(column.name, column.name)
for column in columns]
else:
return [col.name for col in columns]
def get_columns(self, refs):
"""Get columns for attribute references `refs`. """
return [self._columns[ref] for ref in refs]
def condition_for_cell(self, cell):
"""Returns a condition for cell `cell`. If cell is empty or cell is
`None` then returns `None`."""
if not cell:
return None
condition = and_(*self.conditions_for_cuts(cell.cuts))
return condition
def conditions_for_cuts(self, cuts):
"""Constructs conditions for all cuts in the `cell`. Returns a list of
SQL conditional expressions.
"""
conditions = []
for cut in cuts:
hierarchy = str(cut.hierarchy) if cut.hierarchy else None
if isinstance(cut, PointCut):
path = cut.path
condition = self.condition_for_point(str(cut.dimension),
path,
hierarchy, cut.invert)
elif isinstance(cut, SetCut):
set_conds = []
for path in cut.paths:
condition = self.condition_for_point(str(cut.dimension),
path,
str(cut.hierarchy),
invert=False)
set_conds.append(condition)
condition = sql.expression.or_(*set_conds)
if cut.invert:
condition = sql.expression.not_(condition)
elif isinstance(cut, RangeCut):
condition = self.range_condition(str(cut.dimension),
hierarchy,
cut.from_path,
cut.to_path, cut.invert)
else:
raise ArgumentError("Unknown cut type %s" % type(cut))
conditions.append(condition)
return conditions
def condition_for_point(self, dim, path, hierarchy=None, invert=False):
"""Returns a `Condition` tuple (`attributes`, `conditions`,
`group_by`) dimension `dim` point at `path`. It is a compound
condition - one equality condition for each path element in form:
``level[i].key = path[i]``"""
conditions = []
levels = self.level_keys(dim, hierarchy, path)
for level_key, value in zip(levels, path):
# Prepare condition: dimension.level_key = path_value
column = self.column(level_key)
conditions.append(column == value)
condition = sql.expression.and_(*conditions)
if invert:
condition = sql.expression.not_(condition)
return condition
def range_condition(self, dim, hierarchy, from_path, to_path,
invert=False):
"""Return a condition for a hierarchical range (`from_path`,
`to_path`). Return value is a `Condition` tuple."""
lower = self._boundary_condition(dim, hierarchy, from_path, 0)
upper = self._boundary_condition(dim, hierarchy, to_path, 1)
conditions = []
if lower is not None:
conditions.append(lower)
if upper is not None:
conditions.append(upper)
condition = sql.expression.and_(*conditions)
if invert:
condition = sql.expression.not_(condition)
return condition
def _boundary_condition(self, dim, hierarchy, path, bound, first=True):
"""Return a `Condition` tuple for a boundary condition. If `bound` is
1 then path is considered to be upper bound (operators < and <= are
used), otherwise path is considered as lower bound (operators > and >=
are used )"""
# TODO: make this non-recursive
if not path:
return None
last = self._boundary_condition(dim, hierarchy, path[:-1], bound,
first=False)
levels = self.level_keys(dim, hierarchy, path)
conditions = []
for level_key, value in zip(levels[:-1], path[:-1]):
column = self.column(level_key)
conditions.append(column == value)
# Select required operator according to bound
# 0 - lower bound
# 1 - upper bound
if bound == 1:
# 1 - upper bound (that is <= and < operator)
operator = sql.operators.le if first else sql.operators.lt
else:
# else - lower bound (that is >= and > operator)
operator = sql.operators.ge if first else sql.operators.gt
column = self.column(levels[-1])
conditions.append(operator(column, path[-1]))
condition = sql.expression.and_(*conditions)
if last is not None:
condition = sql.expression.or_(condition, last)
return condition
def level_keys(self, dimension, hierarchy, path):
"""Return list of key attributes of levels for `path` in `hierarchy`
of `dimension`."""
# Note: If something does not work here, make sure that hierarchies
# contains "default hierarchy", that is (dimension, None) tuple.
#
try:
levels = self.hierarchies[(str(dimension), hierarchy)]
except KeyError as e:
raise InternalError("Unknown hierarchy '{}'. Hierarchies are "
"not properly initialized (maybe missing "
"default?)".format(e))
depth = 0 if not path else len(path)
if depth > len(levels):
levels_str = ", ".join(levels)
raise HierarchyError("Path '{}' is longer than hierarchy. "
"Levels: {}".format(path, levels))
return levels[0:depth]
def column_for_split(self, split_cell, label=None):
"""Create a column for a cell split from list of `cust`."""
condition = self.condition_for_cell(split_cell)
split_column = sql.expression.case([(condition, True)],
else_=False)
label = label or SPLIT_DIMENSION_NAME
return split_column.label(label)
|
techkey/PTVS | Python/Tests/TestData/Coverage/Simple/test.py | <filename>Python/Tests/TestData/Coverage/Simple/test.py<gh_stars>100-1000
def f(): x = 1
def g():
if True:
print('hi')
else:
print('bye')
x = 2
pass
return x
f()
f()
g() |
fredmorcos/attic | Projects/Graffer/0.2/grafer/ui/MainMenu.py | '''
This file is part of Camarillo.
Copyright (C) 2008 <NAME> <<EMAIL>>
Camarillo 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.
Camarillo 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 Camarillo. If not, see <http://www.gnu.org/licenses/>.
'''
from gtk import MenuItem, MenuBar, Menu, ImageMenuItem, SeparatorMenuItem, \
STOCK_NEW, STOCK_OPEN, STOCK_CLOSE, STOCK_SAVE, STOCK_SAVE_AS, \
STOCK_CONVERT, STOCK_QUIT, STOCK_ABOUT
class MainMenu(MenuBar):
def __init__(self):
MenuBar.__init__(self)
self.append(self.createMenuFile())
self.append(self.createMenuHelp())
def createMenuFile(self):
menuFile = MenuItem('_File')
menuFilePop = Menu()
self.menuNew = ImageMenuItem(STOCK_NEW)
self.menuOpen = ImageMenuItem(STOCK_OPEN)
self.menuClose = ImageMenuItem(STOCK_CLOSE)
self.menuSave = ImageMenuItem(STOCK_SAVE)
self.menuSaveAs = ImageMenuItem(STOCK_SAVE_AS)
self.menuConvert = ImageMenuItem(STOCK_CONVERT)
self.menuQuit = ImageMenuItem(STOCK_QUIT)
menuFilePop.append(self.menuNew)
menuFilePop.append(self.menuOpen)
menuFilePop.append(self.menuClose)
menuFilePop.append(SeparatorMenuItem())
menuFilePop.append(self.menuSave)
menuFilePop.append(self.menuSaveAs)
menuFilePop.append(self.menuConvert)
menuFilePop.append(SeparatorMenuItem())
menuFilePop.append(self.menuQuit)
menuFile.set_submenu(menuFilePop)
return menuFile
def createMenuHelp(self):
menuHelp = MenuItem('_Help')
menuHelpPop = Menu()
self.menuAbout = ImageMenuItem(STOCK_ABOUT)
menuHelpPop.append(self.menuAbout)
menuHelp.set_submenu(menuHelpPop)
return menuHelp
|
npocmaka/Windows-Server-2003 | drivers/storage/volsnap/vss/server/tests/multilayer/mlutil.cpp | <reponame>npocmaka/Windows-Server-2003
/*
**++
**
** Copyright (c) 2000-2001 Microsoft Corporation
**
**
** Module Name:
**
** mlutil.cpp
**
**
** Abstract:
**
** Utility functions for the VSML test.
**
** Author:
**
** <NAME> [aoltean] 03/05/2001
**
** The sample is based on the Metasnap test program written by <NAME>.
**
**
** Revision History:
**
**--
*/
///////////////////////////////////////////////////////////////////////////////
// Includes
#include "ml.h"
#include "ntddsnap.h"
#include "ntddvol.h"
///////////////////////////////////////////////////////////////////////////////
// Command line parsing
bool CVssMultilayerTest::PrintUsage(bool bThrow /* = true */)
{
wprintf(
L"\nUsage:\n"
L" 1) For snapshot creation:\n"
L" vsml [-xt|-xa|-xp] [-s <seed_number>] <volumes>\n"
L" 2) For query:\n"
L" vsml [-xt|-xa|-xp|-xf] -qs [-P <ProviderID>]\n"
L" vsml [-xt|-xa|-xp|-xf] -qsv <volume> [-P <ProviderID>]\n"
L" vsml [-xt|-xa|-xp|-xf] -qv [-P <ProviderID>]\n"
L" vsml -qi <volume>\n"
L" vsml -is <volume>\n"
L" vsml -lw\n"
L" 3) For diff area:\n"
L" vsml -da <vol> <diff vol> <max size> [-P <ProviderID>]\n"
L" vsml -dr <vol> <diff vol> [-P <ProviderID>]\n"
L" vsml -ds <vol> <diff vol> <max size> [-P <ProviderID>]\n"
L" vsml -dqv [-v original_volume] [-P <ProviderID>]\n"
L" vsml -dqf <volume> [-P <ProviderID>]\n"
L" vsml -dqo <volume> [-P <ProviderID>]\n"
L" vsml -dqs {SnapshotID} [-P <ProviderID>]\n"
L" 4) For deleting snapshots:\n"
L" vsml [-xt|-xa|-xp] -r {snapshot id}\n"
L" vsml [-xt|-xa|-xp] -rs {snapshot set id}\n"
L" 5) For various tests:\n"
L" vsml [-xt|-xa|-xp] -sp {snapshot id} PropertyId string\n"
L" vsml -test_sc\n"
L" 6) For displaying various constants:\n"
L" vsml -const\n"
L" 7) For diagnosing writers:\n"
L" vsml -diag\n"
L" vsml -diag log\n"
L" vsml -diag csv\n"
L" vsml -diag on\n"
L" vsml -diag off\n"
L"\nOptions:\n"
L" -s Specifies a seed for the random number generator\n"
L" -xt Operates in the Timewarp context\n"
L" -xa Operates in the 'ALL' context\n"
L" -xp Operates in the 'Nas Rollback' context\n"
L" -xr Operates in the 'App Rollback' context\n"
L" -xf Operates in the File Share Backup context\n"
L" -qs Queries the existing snapshots\n"
L" -qi Queries the VOLSNAP snapshots (through ioctl)\n"
L" -is Checks if the volume is snapshotted (through C API)\n"
L" -qsv Queries the snapshots on the given volume\n"
L" -qv Queries the supported volumes.\n"
L" -P Specifies a provider Id\n"
L" -da Adds a diff area association.\n"
L" -dr Removes a diff area association.\n"
L" -ds Change diff area max size.\n"
L" -dqv Query the volumes supported for diff area.\n"
L" -dqf Query the diff area associations for volume.\n"
L" -dqo Query the diff area associations on volume.\n"
L" -dqs Query the diff area associations for snapshot.\n"
L" -r Remove the snapshot with that ID.\n"
L" -rs Remove the snapshots from the set with that ID.\n"
L" -sp Set snapshot properties.\n"
L" -test_sc Test SID collection.\n"
L" -const Prints out various constants.\n"
L" -? Displays this help.\n"
L" -D Pops up an assert for attaching a debugger.\n"
L" -diag Diagnose all writers. Print all writers.\n"
L" -diag log Diagnose all writers. Print only pending writers.\n"
L" -diag csv Diagnose all writers. Print information in CSV format.\n"
L" -diag on Turn on diagnose.\n"
L" -diag off Turn off diagnose.\n"
L" -lw List writers.\n"
L"\n"
L"\nExample:\n"
L" The following command will create a backup snapshot set\n"
L" on the volumes mounted under c:\\ and d:\\\n"
L"\n"
L" vsml c:\\ d:\\ \n"
L"\n"
);
if (bThrow)
throw(E_INVALIDARG);
return false;
}
#define VSS_PRINT_VALUE(x) wprintf(L" 0x%08lx - %S\n", x, #x);
#define VSS_PRINT_GUID(X) wprintf( L" {%.8x-%.4x-%.4x-%.2x%.2x-%.2x%.2x%.2x%.2x%.2x%.2x} - %S\n", \
(X).Data1, \
(X).Data2, \
(X).Data3, \
(X).Data4[0], (X).Data4[1], (X).Data4[2], (X).Data4[3], \
(X).Data4[4], (X).Data4[5], (X).Data4[6], (X).Data4[7], \
#X);
bool CVssMultilayerTest::ParseCommandLine()
{
if (!TokensLeft() || Match(L"-?"))
return PrintUsage(false);
// Check for context options
if (Match(L"-D"))
m_bAttachYourDebuggerNow = true;
// displays all ioctls
if (Match(L"-const")) {
m_eTest = VSS_TEST_NONE;
wprintf (L"\nVolsnap ioctls:\n");
VSS_PRINT_VALUE(IOCTL_VOLSNAP_FLUSH_AND_HOLD_WRITES);
VSS_PRINT_VALUE(IOCTL_VOLSNAP_RELEASE_WRITES);
VSS_PRINT_VALUE(IOCTL_VOLSNAP_PREPARE_FOR_SNAPSHOT);
VSS_PRINT_VALUE(IOCTL_VOLSNAP_ABORT_PREPARED_SNAPSHOT);
VSS_PRINT_VALUE(IOCTL_VOLSNAP_COMMIT_SNAPSHOT);
VSS_PRINT_VALUE(IOCTL_VOLSNAP_END_COMMIT_SNAPSHOT);
VSS_PRINT_VALUE(IOCTL_VOLSNAP_QUERY_NAMES_OF_SNAPSHOTS);
VSS_PRINT_VALUE(IOCTL_VOLSNAP_CLEAR_DIFF_AREA);
VSS_PRINT_VALUE(IOCTL_VOLSNAP_ADD_VOLUME_TO_DIFF_AREA);
VSS_PRINT_VALUE(IOCTL_VOLSNAP_QUERY_DIFF_AREA);
VSS_PRINT_VALUE(IOCTL_VOLSNAP_SET_MAX_DIFF_AREA_SIZE);
VSS_PRINT_VALUE(IOCTL_VOLSNAP_QUERY_DIFF_AREA_SIZES);
VSS_PRINT_VALUE(IOCTL_VOLSNAP_DELETE_OLDEST_SNAPSHOT);
VSS_PRINT_VALUE(IOCTL_VOLSNAP_AUTO_CLEANUP);
VSS_PRINT_VALUE(IOCTL_VOLSNAP_DELETE_SNAPSHOT);
VSS_PRINT_VALUE(IOCTL_VOLSNAP_QUERY_ORIGINAL_VOLUME_NAME);
VSS_PRINT_VALUE(IOCTL_VOLSNAP_QUERY_CONFIG_INFO);
VSS_PRINT_VALUE(IOCTL_VOLSNAP_SET_APPLICATION_INFO);
VSS_PRINT_VALUE(IOCTL_VOLSNAP_QUERY_APPLICATION_INFO);
VSS_PRINT_VALUE(FSCTL_DISMOUNT_VOLUME);
VSS_PRINT_VALUE(IOCTL_VOLUME_OFFLINE);
wprintf (L"\n\nVolsnap contexes:\n");
VSS_PRINT_VALUE(VSS_CTX_BACKUP);
VSS_PRINT_VALUE(VSS_CTX_FILE_SHARE_BACKUP);
VSS_PRINT_VALUE(VSS_CTX_NAS_ROLLBACK);
VSS_PRINT_VALUE(VSS_CTX_APP_ROLLBACK);
VSS_PRINT_VALUE(VSS_CTX_CLIENT_ACCESSIBLE);
VSS_PRINT_VALUE(VSS_CTX_ALL);
wprintf (L"\n\nVolsnap guids:\n");
VSS_PRINT_GUID(VOLSNAP_APPINFO_GUID_BACKUP_CLIENT_SKU);
VSS_PRINT_GUID(VOLSNAP_APPINFO_GUID_BACKUP_SERVER_SKU);
VSS_PRINT_GUID(VOLSNAP_APPINFO_GUID_SYSTEM_HIDDEN);
VSS_PRINT_GUID(VOLSNAP_APPINFO_GUID_NAS_ROLLBACK);
VSS_PRINT_GUID(VOLSNAP_APPINFO_GUID_APP_ROLLBACK);
VSS_PRINT_GUID(VOLSNAP_APPINFO_GUID_FILE_SHARE_BACKUP);
wprintf(L"\n\nValid attributes for SetContext:\n");
wprintf(L" VSS_VOLSNAP_ATTR_EXPOSED_LOCALLY = %d\n", VSS_VOLSNAP_ATTR_EXPOSED_LOCALLY);
wprintf(L" VSS_VOLSNAP_ATTR_EXPOSED_REMOTELY = %d\n", VSS_VOLSNAP_ATTR_EXPOSED_REMOTELY);
wprintf(L" VSS_VOLSNAP_ATTR_EXPOSED_LOCALLY | VSS_..._REMOTELY = %d\n",
VSS_VOLSNAP_ATTR_EXPOSED_LOCALLY | VSS_VOLSNAP_ATTR_EXPOSED_REMOTELY);
wprintf(L"\n\nValid property IDs:\n");
wprintf(L" VSS_SPROPID_SNAPSHOT_ATTRIBUTES = %d\n", VSS_SPROPID_SNAPSHOT_ATTRIBUTES);
wprintf(L" VSS_SPROPID_EXPOSED_NAME = %d\n", VSS_SPROPID_EXPOSED_NAME);
wprintf(L" VSS_SPROPID_EXPOSED_PATH = %d\n", VSS_SPROPID_EXPOSED_PATH);
wprintf(L" VSS_SPROPID_SERVICE_MACHINE = %d\n", VSS_SPROPID_SERVICE_MACHINE);
wprintf(L"\n");
return TokensLeft()? PrintUsage(): true;
}
// Test CSidCollection
if (Match(L"-test_sc")) {
m_eTest = VSS_TEST_ACCESS_CONTROL_SD;
return TokensLeft()? PrintUsage(): true;
}
// Diagnose writers
if (Match(L"-diag")) {
if (Match(L"on")) {
m_eTest = VSS_TEST_DIAG_WRITERS_ON;
return TokensLeft()? PrintUsage(): true;
}
if (Match(L"off")) {
m_eTest = VSS_TEST_DIAG_WRITERS_OFF;
return TokensLeft()? PrintUsage(): true;
}
if (Match(L"log")) {
m_eTest = VSS_TEST_DIAG_WRITERS_LOG;
return TokensLeft()? PrintUsage(): true;
}
if (Match(L"csv")) {
m_eTest = VSS_TEST_DIAG_WRITERS_CSV;
return TokensLeft()? PrintUsage(): true;
}
if (!TokensLeft()) {
m_eTest = VSS_TEST_DIAG_WRITERS;
return true;
}
return PrintUsage();
}
// Check for List Writers
if (Match(L"-lw"))
{
m_eTest = VSS_TEST_LIST_WRITERS;
return TokensLeft()? PrintUsage(): true;
}
// Query using the IOCTL
if (Match(L"-qi")) {
m_eTest = VSS_TEST_VOLSNAP_QUERY;
// Get the original volume
if (!Extract(m_pwszVolume) || !IsVolume(m_pwszVolume))
return PrintUsage();
return TokensLeft()? PrintUsage(): true;
}
// Query using the IOCTL
if (Match(L"-is")) {
m_eTest = VSS_TEST_IS_VOLUME_SNAPSHOTTED_C;
// Get the original volume
if (!Extract(m_pwszVolume) || !IsVolume(m_pwszVolume))
return PrintUsage();
return TokensLeft()? PrintUsage(): true;
}
// Check for context options
if (Match(L"-xt"))
m_lContext = VSS_CTX_CLIENT_ACCESSIBLE;
if (Match(L"-xa"))
m_lContext = VSS_CTX_ALL;
if (Match(L"-xp"))
m_lContext = VSS_CTX_NAS_ROLLBACK;
if (Match(L"-xr"))
m_lContext = VSS_CTX_APP_ROLLBACK;
if (Match(L"-xf"))
m_lContext = VSS_CTX_FILE_SHARE_BACKUP;
// Set the snapshot property
if (Match(L"-sp")) {
m_eTest = VSS_TEST_SET_SNAPSHOT_PROPERTIES;
// Extract the snapshot id
if (!Extract(m_SnapshotId))
return PrintUsage();
// Extract the property ID
Extract(m_uPropertyId);
UINT uNewAttributes = 0;
LPWSTR pwszString = NULL;
switch(m_uPropertyId)
{
case VSS_SPROPID_SNAPSHOT_ATTRIBUTES:
// Extract the snapshot attributes
Extract(uNewAttributes);
switch(uNewAttributes)
{
default:
wprintf(L"\nInvalid attributes ID (%lu). Valid ones:\n", uNewAttributes);
wprintf(L" VSS_VOLSNAP_ATTR_EXPOSED_LOCALLY = %d\n", VSS_VOLSNAP_ATTR_EXPOSED_LOCALLY);
wprintf(L" VSS_VOLSNAP_ATTR_EXPOSED_REMOTELY = %d\n", VSS_VOLSNAP_ATTR_EXPOSED_REMOTELY);
wprintf(L" VSS_VOLSNAP_ATTR_EXPOSED_LOCALLY | VSS_..._REMOTELY = %d\n",
VSS_VOLSNAP_ATTR_EXPOSED_LOCALLY | VSS_VOLSNAP_ATTR_EXPOSED_REMOTELY);
return false;
case VSS_VOLSNAP_ATTR_EXPOSED_LOCALLY:
case VSS_VOLSNAP_ATTR_EXPOSED_REMOTELY:
case VSS_VOLSNAP_ATTR_EXPOSED_LOCALLY | VSS_VOLSNAP_ATTR_EXPOSED_REMOTELY:
break;
}
m_value = (LONG)uNewAttributes;
break;
case VSS_SPROPID_EXPOSED_NAME:
case VSS_SPROPID_EXPOSED_PATH:
case VSS_SPROPID_SERVICE_MACHINE:
// Extract the snapshot attributes
if (Extract(pwszString))
{
m_value = pwszString;
::VssFreeString(pwszString);
}
else
m_value = L"";
break;
default:
wprintf(L"\nInvalid property ID (%ld). Valid ones:\n", m_uPropertyId);
wprintf(L" VSS_SPROPID_SNAPSHOT_ATTRIBUTES = %d\n", VSS_SPROPID_SNAPSHOT_ATTRIBUTES);
wprintf(L" VSS_SPROPID_EXPOSED_NAME = %d\n", VSS_SPROPID_EXPOSED_NAME);
wprintf(L" VSS_SPROPID_EXPOSED_PATH = %d\n", VSS_SPROPID_EXPOSED_PATH);
wprintf(L" VSS_SPROPID_SERVICE_MACHINE = %d\n", VSS_SPROPID_SERVICE_MACHINE);
return false;
}
return TokensLeft()? PrintUsage(): true;
}
// Add the Diff Area
if (Match(L"-da")) {
m_eTest = VSS_TEST_ADD_DIFF_AREA;
// Get the original volume
if (!Extract(m_pwszVolume) || !IsVolume(m_pwszVolume))
return PrintUsage();
// Get the diff area volume
if (!Extract(m_pwszDiffAreaVolume) || !IsVolume(m_pwszDiffAreaVolume))
return PrintUsage();
// Check to see if we specified a max diff area (i.e. -P is not present)
if (!Peek(L"-P"))
Extract(m_llMaxDiffArea);
// Check to see if we specified a provider ID
if (Match(L"-P")) {
if (!Extract(m_ProviderId))
return PrintUsage();
Extract(m_llMaxDiffArea);
}
return TokensLeft()? PrintUsage(): true;
}
// Remove the Diff Area
if (Match(L"-dr")) {
m_eTest = VSS_TEST_REMOVE_DIFF_AREA;
// Get the original volume
if (!Extract(m_pwszVolume) || !IsVolume(m_pwszVolume))
return PrintUsage();
// Get the diff area volume
if (!Extract(m_pwszDiffAreaVolume) || !IsVolume(m_pwszDiffAreaVolume))
return PrintUsage();
// Check to see if we specified a provider ID
if (Match(L"-P"))
if (!Extract(m_ProviderId))
return PrintUsage();
return TokensLeft()? PrintUsage(): true;
}
// Change Diff Area max size
if (Match(L"-ds")) {
m_eTest = VSS_TEST_CHANGE_DIFF_AREA_MAX_SIZE;
// Get the original volume
if (!Extract(m_pwszVolume) || !IsVolume(m_pwszVolume))
return PrintUsage();
// Get the diff area volume
if (!Extract(m_pwszDiffAreaVolume) || !IsVolume(m_pwszDiffAreaVolume))
return PrintUsage();
// Check to see if we specified a max diff area (i.e. -P is not present)
if (!Peek(L"-P"))
Extract(m_llMaxDiffArea);
// Check to see if we specified a provider ID
if (Match(L"-P")) {
if (!Extract(m_ProviderId))
return PrintUsage();
Extract(m_llMaxDiffArea);
}
return TokensLeft()? PrintUsage(): true;
}
// Query the volumes supported for Diff Area
if (Match(L"-dqv")) {
m_eTest = VSS_TEST_QUERY_SUPPORTED_VOLUMES_FOR_DIFF_AREA;
// Check to see if we specified a max diff area (i.e. -P is not present)
if (!Peek(L"-v"))
if (!Extract(m_pwszVolume) || !IsVolume(m_pwszVolume))
return PrintUsage();
// Check to see if we specified a provider ID
if (Match(L"-P"))
if (!Extract(m_ProviderId))
return PrintUsage();
return TokensLeft()? PrintUsage(): true;
}
// Query the volumes supported for Diff Area
if (Match(L"-dqf")) {
m_eTest = VSS_TEST_QUERY_DIFF_AREAS_FOR_VOLUME;
// Get the original volume
if (!Extract(m_pwszVolume) || !IsVolume(m_pwszVolume))
return PrintUsage();
// Check to see if we specified a provider ID
if (Match(L"-P"))
if (!Extract(m_ProviderId))
return PrintUsage();
return TokensLeft()? PrintUsage(): true;
}
// Query the volumes supported for Diff Area
if (Match(L"-dqo")) {
m_eTest = VSS_TEST_QUERY_DIFF_AREAS_ON_VOLUME;
// Get the original volume
if (!Extract(m_pwszDiffAreaVolume) || !IsVolume(m_pwszDiffAreaVolume))
return PrintUsage();
// Check to see if we specified a provider ID
if (Match(L"-P"))
if (!Extract(m_ProviderId))
return PrintUsage();
return TokensLeft()? PrintUsage(): true;
}
// Query the volumes supported for Diff Area
if (Match(L"-dqs")) {
m_eTest = VSS_TEST_QUERY_DIFF_AREAS_FOR_SNAPSHOT;
// Get the original volume
if (!Extract(m_SnapshotId))
return PrintUsage();
// Check to see if we specified a provider ID
if (Match(L"-P"))
if (!Extract(m_ProviderId))
return PrintUsage();
return TokensLeft()? PrintUsage(): true;
}
// Check for Query
if (Match(L"-qs")) {
m_eTest = VSS_TEST_QUERY_SNAPSHOTS;
// Check to see if we specified a provider ID
if (Match(L"-P"))
if (!Extract(m_ProviderId))
return PrintUsage();
return TokensLeft()? PrintUsage(): true;
}
// Check for Query
if (Match(L"-qsv")) {
m_eTest = VSS_TEST_QUERY_SNAPSHOTS_ON_VOLUME;
// Extract the volume volume
if (!Extract(m_pwszVolume) || !IsVolume(m_pwszVolume))
return PrintUsage();
// Check to see if we specified a provider ID
if (Match(L"-P"))
if (!Extract(m_ProviderId))
return PrintUsage();
return TokensLeft()? PrintUsage(): true;
}
// Check for Query Supported Volumes
if (Match(L"-qv")) {
m_eTest = VSS_TEST_QUERY_VOLUMES;
// Check to see if we specified a provider ID
if (Match(L"-P"))
if (!Extract(m_ProviderId))
return PrintUsage();
return TokensLeft()? PrintUsage(): true;
}
// Check for Delete by snapshot Id
if (Match(L"-r")) {
m_eTest = VSS_TEST_DELETE_BY_SNAPSHOT_ID;
// Extract the snapshot id
if (!Extract(m_SnapshotId))
return PrintUsage();
return TokensLeft()? PrintUsage(): true;
}
// Check for Delete by snapshot set Id
if (Match(L"-rs")) {
m_eTest = VSS_TEST_DELETE_BY_SNAPSHOT_SET_ID;
// Extract the snapshot id
if (!Extract(m_SnapshotSetId))
return PrintUsage();
return TokensLeft()? PrintUsage(): true;
}
// Check for Seed option
if (Match(L"-s"))
if (!Extract(m_uSeed))
return PrintUsage();
// We are in snapshot creation mode
if (!TokensLeft())
return PrintUsage();
bool bVolumeAdded = false;
VSS_PWSZ pwszVolumeName = NULL;
while (TokensLeft()) {
Extract(pwszVolumeName);
if (!AddVolume(pwszVolumeName, bVolumeAdded)) {
wprintf(L"\nError while parsing the command line:\n"
L"\t%s is not a valid option or a mount point [0x%08lx]\n\n",
GetCurrentToken(), GetLastError() );
return PrintUsage();
}
// Check if the same volume is added twice
if (!bVolumeAdded) {
wprintf(L"\nError while parsing the command line:\n"
L"\tThe volume %s is specified twice\n\n", GetCurrentToken() );
return PrintUsage();
}
::VssFreeString(pwszVolumeName);
}
m_eTest = VSS_TEST_CREATE;
return true;
}
// Check if there are tokens left
bool CVssMultilayerTest::TokensLeft()
{
return (m_nCurrentArgsCount != 0);
}
// Returns the current token
VSS_PWSZ CVssMultilayerTest::GetCurrentToken()
{
return (*m_ppwszCurrentArgsArray);
}
// Go to next token
void CVssMultilayerTest::Shift()
{
BS_ASSERT(m_nCurrentArgsCount);
m_nCurrentArgsCount--;
m_ppwszCurrentArgsArray++;
}
// Check if the current command line token matches with the given pattern
// Do not shift to the next token
bool CVssMultilayerTest::Peek(
IN VSS_PWSZ pwszPattern
) throw(HRESULT)
{
if (!TokensLeft())
return false;
// Try to find a match
if (wcscmp(GetCurrentToken(), pwszPattern))
return false;
// Go to the next token
return true;
}
// Match the current command line token with the given pattern
// If succeeds, then switch to the next token
bool CVssMultilayerTest::Match(
IN VSS_PWSZ pwszPattern
) throw(HRESULT)
{
if (!Peek(pwszPattern))
return false;
// Go to the next token
Shift();
return true;
}
// Converts the current token to a guid
// If succeeds, then switch to the next token
bool CVssMultilayerTest::Extract(
IN OUT VSS_ID& Guid
) throw(HRESULT)
{
if (!TokensLeft())
return false;
// Try to extract the guid
if (!SUCCEEDED(::CLSIDFromString(W2OLE(const_cast<WCHAR*>(GetCurrentToken())), &Guid)))
return false;
// Go to the next token
Shift();
return true;
}
// Converts the current token to a string
// If succeeds, then switch to the next token
bool CVssMultilayerTest::Extract(
IN OUT VSS_PWSZ& pwsz
) throw(HRESULT)
{
if (!TokensLeft())
return false;
// Extract the string
::VssDuplicateStr(pwsz, GetCurrentToken());
if (!pwsz)
throw(E_OUTOFMEMORY);
// Go to the next token
Shift();
return true;
}
// Converts the current token to an UINT
// If succeeds, then switch to the next token
bool CVssMultilayerTest::Extract(
IN OUT UINT& uint
) throw(HRESULT)
{
if (!TokensLeft())
return false;
// Extract the unsigned value
uint = ::_wtoi(GetCurrentToken());
// Go to the next token
Shift();
return true;
}
// Converts the current token to an UINT
// If succeeds, then switch to the next token
bool CVssMultilayerTest::Extract(
IN OUT LONGLONG& llValue
) throw(HRESULT)
{
if (!TokensLeft())
return false;
// Extract the unsigned value
llValue = ::_wtoi64(GetCurrentToken());
// Go to the next token
Shift();
return true;
}
// Returns true if the given string is a volume
bool CVssMultilayerTest::IsVolume(
IN WCHAR* pwszVolumeDisplayName
)
{
CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CVssMultilayerTest::IsVolume");
// Check if the volume represents a real mount point
WCHAR wszVolumeName[MAX_TEXT_BUFFER];
if (!GetVolumeNameForVolumeMountPoint(pwszVolumeDisplayName, wszVolumeName, MAX_TEXT_BUFFER))
return false; // Invalid volume
return true;
}
// Add the given volume in the list of potential candidates for snapshots
// - Returns "false" if the volume does not correspond to a real mount point
// (and GetLastError() will contain the correct Win32 error code)
// - Sets "true" in the bAdded parameter if the volume is actually added
bool CVssMultilayerTest::AddVolume(
IN WCHAR* pwszVolumeDisplayName,
OUT bool & bAdded
)
{
CVssFunctionTracer ft(VSSDBG_VSSTEST, L"CVssMultilayerTest::AddVolume");
// Initialize [out] parameters
bAdded = false;
// Check if the volume represents a real mount point
WCHAR wszVolumeName[MAX_TEXT_BUFFER];
if (!GetVolumeNameForVolumeMountPoint(pwszVolumeDisplayName, wszVolumeName, MAX_TEXT_BUFFER))
return false; // Invalid volume
// Check if the volume is already added.
WCHAR* pwszVolumeNameToBeSearched = wszVolumeName;
if (m_mapVolumes.FindKey(pwszVolumeNameToBeSearched) != -1)
return true; // Volume already added. Stop here.
// Create the volume info object
CVssVolumeInfo* pVolInfo = new CVssVolumeInfo(wszVolumeName, pwszVolumeDisplayName);
if (pVolInfo == NULL)
ft.Err(VSSDBG_VSSTEST, E_OUTOFMEMORY, L"Memory allcation error");
// Add the volume in our internal list of snapshotted volumes
if (!m_mapVolumes.Add(pVolInfo->GetVolumeDisplayName(), pVolInfo)) {
delete pVolInfo;
ft.Err(VSSDBG_VSSTEST, E_OUTOFMEMORY, L"Memory allcation error");
}
bAdded = true;
return true;
}
///////////////////////////////////////////////////////////////////////////////
// Utility functions
// Convert a failure type into a string
LPCWSTR CVssMultilayerTest::GetStringFromFailureType( IN HRESULT hrStatus )
{
static WCHAR wszBuffer[MAX_TEXT_BUFFER];
switch (hrStatus)
{
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_WRITERERROR_INCONSISTENTSNAPSHOT)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_WRITERERROR_OUTOFRESOURCES)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_WRITERERROR_TIMEOUT)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_WRITERERROR_NONRETRYABLE)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_WRITERERROR_RETRYABLE)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_BAD_STATE)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_PROVIDER_ALREADY_REGISTERED)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_PROVIDER_NOT_REGISTERED)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_PROVIDER_VETO)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_PROVIDER_IN_USE)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_OBJECT_NOT_FOUND)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_S_ASYNC_PENDING)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_S_ASYNC_FINISHED)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_S_ASYNC_CANCELLED)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_VOLUME_NOT_SUPPORTED)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_VOLUME_NOT_SUPPORTED_BY_PROVIDER)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_OBJECT_ALREADY_EXISTS)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_UNEXPECTED_PROVIDER_ERROR)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_CORRUPT_XML_DOCUMENT)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_INVALID_XML_DOCUMENT)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_MAXIMUM_NUMBER_OF_VOLUMES_REACHED)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_FLUSH_WRITES_TIMEOUT)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_HOLD_WRITES_TIMEOUT)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_UNEXPECTED_WRITER_ERROR)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_SNAPSHOT_SET_IN_PROGRESS)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_MAXIMUM_NUMBER_OF_SNAPSHOTS_REACHED)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_WRITER_INFRASTRUCTURE)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_WRITER_NOT_RESPONDING)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_WRITER_ALREADY_SUBSCRIBED)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_UNSUPPORTED_CONTEXT)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_VOLUME_IN_USE)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_MAXIMUM_DIFFAREA_ASSOCIATIONS_REACHED)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_E_INSUFFICIENT_STORAGE)
case NOERROR:
break;
default:
::FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM,
NULL, hrStatus, 0, (LPWSTR)&wszBuffer, MAX_TEXT_BUFFER - 1, NULL);
break;
}
return (wszBuffer);
}
// Convert a writer status into a string
LPCWSTR CVssMultilayerTest::GetStringFromWriterState( IN VSS_WRITER_STATE state )
{
static WCHAR wszBuffer[MAX_TEXT_BUFFER];
switch (state)
{
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_WS_UNKNOWN)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_WS_STABLE)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_WS_WAITING_FOR_FREEZE)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_WS_WAITING_FOR_THAW)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_WS_WAITING_FOR_POST_SNAPSHOT)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_WS_WAITING_FOR_BACKUP_COMPLETE)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_WS_FAILED_AT_PREPARE_BACKUP)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_WS_FAILED_AT_PREPARE_SNAPSHOT)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_WS_FAILED_AT_FREEZE)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_WS_FAILED_AT_THAW)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_WS_FAILED_AT_POST_SNAPSHOT)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_WS_FAILED_AT_BACKUP_COMPLETE)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_WS_FAILED_AT_PRE_RESTORE)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_WS_FAILED_AT_POST_RESTORE)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_WS_FAILED_AT_BACKUPSHUTDOWN)
VSS_ERROR_CASE(wszBuffer, MAX_TEXT_BUFFER, VSS_WS_COUNT)
default:
swprintf(wszBuffer, L" Unknown state %d", state);
break;
}
return (wszBuffer);
}
INT CVssMultilayerTest::RndDecision(
IN INT nVariants /* = 2 */
)
{
return (rand() % nVariants);
}
LPWSTR CVssMultilayerTest::DateTimeToString(
IN LONGLONG llTimestamp
)
{
CVssFunctionTracer ft( VSSDBG_VSSTEST, L"CVssMultilayerTest::DateTimeToString" );
SYSTEMTIME stLocal;
FILETIME ftLocal;
WCHAR pwszDate[ 64 ];
WCHAR pwszTime[ 64 ];
BS_ASSERT(sizeof(FILETIME) == sizeof(LONGLONG));
// Compensate for local TZ
::FileTimeToLocalFileTime( (FILETIME *) &llTimestamp, &ftLocal );
// Finally convert it to system time
::FileTimeToSystemTime( &ftLocal, &stLocal );
// Convert timestamp to a date string
::GetDateFormatW( GetThreadLocale( ),
DATE_SHORTDATE,
&stLocal,
NULL,
pwszDate,
sizeof( pwszDate ) / sizeof( pwszDate[0] ));
// Convert timestamp to a time string
::GetTimeFormatW( GetThreadLocale( ),
0,
&stLocal,
NULL,
pwszTime,
sizeof( pwszTime ) / sizeof( pwszTime[0] ));
// Now combine the strings and return it
CVssAutoLocalString pwszDateTime;
pwszDateTime.Append(pwszDate);
pwszDateTime.Append(L" ");
pwszDateTime.Append(pwszTime);
return pwszDateTime.Detach();
}
|
SaatCoffeeMUD/SAATCoffeeMUD | com/planet_ink/coffee_mud/Abilities/Skills/Skill_ResearchItem.java | package com.planet_ink.coffee_mud.Abilities.Skills;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.util.*;
/*
Copyright 2002-2022 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class Skill_ResearchItem extends StdSkill
{
@Override
public String ID()
{
return "Skill_ResearchItem";
}
private final static String localizedName = CMLib.lang().L("Research Item");
@Override
public String name()
{
return localizedName;
}
protected String displayText = L("(Researching)");
@Override
public String displayText()
{
return displayText;
}
@Override
protected int canAffectCode()
{
return CAN_MOBS;
}
@Override
protected int canTargetCode()
{
return CAN_ITEMS;
}
@Override
public int abstractQuality()
{
return Ability.QUALITY_INDIFFERENT;
}
private static final String[] triggerStrings = I(new String[] { "RESEARCHITEM" });
@Override
public String[] triggerStrings()
{
return triggerStrings;
}
@Override
public int classificationCode()
{
return Ability.ACODE_SKILL | Ability.DOMAIN_EDUCATIONLORE;
}
@Override
public int usageType()
{
return USAGE_MOVEMENT|USAGE_MANA;
}
@Override
public void unInvoke()
{
if(!unInvoked)
{
final Physical affected=this.affected;
if(affected instanceof MOB)
{
final MOB mob=(MOB)affected;
if(itemsFound.size()==0)
mob.tell(L("Your research fails to find anything on '@x1'.",what));
else
{
for(final String found : itemsFound)
mob.tell(found);
}
}
}
super.unInvoke();
}
protected final List<String> itemsFound=new Vector<String>();
protected Room theRoom = null;
protected Iterator<Room> checkIter=null;
protected String what = "";
protected int ticksToRemain = 0;
protected int numBooksInRoom = 1;
protected int numRoomsToDo = 0;
@Override
public void setMiscText(final String newMiscText)
{
super.setMiscText(newMiscText);
itemsFound.clear();
numBooksInRoom = 1;
what = newMiscText;
ticksToRemain = 0;
theRoom=null;
numRoomsToDo=0;
checkIter=null;
final Physical affected = this.affected;
if(affected instanceof MOB)
numBooksInLibrary((MOB)affected); // sets the appropriate variables
}
@Override
public boolean tick(final Tickable ticking, final int tickID)
{
if(!super.tick(ticking,tickID))
return false;
if(tickID==Tickable.TICKID_MOB)
{
final Physical affected=this.affected;
if(!(affected instanceof MOB))
return true;
final MOB mob=(MOB)affected;
Room R;
synchronized(this)
{
R=theRoom;
}
if(R == null)
{
if(numBooksInLibrary(mob)==0)
{
mob.tell(L("You fail researching."));
unInvoke();
return false;
}
R=theRoom;
if(R==null)
{
unInvoke();
return false;
}
}
if(!R.isInhabitant(mob)
||(mob.isInCombat())
||(!CMLib.flags().canBeSeenBy(R, mob))
||(!CMLib.flags().isAliveAwakeMobileUnbound(mob,true)))
{
this.itemsFound.clear();
mob.tell(L("You stop researching."));
unInvoke();
return false;
}
if((tickDown==4)&&(checkIter != null)&&(!checkIter.hasNext()))
{
if(!R.show(mob,null,CMMsg.MSG_QUIETMOVEMENT,L("<S-NAME> <S-IS-ARE> almost done researching '@x1'",what)))
{
unInvoke();
return false;
}
}
else
if((tickDown%4)==0)
{
if(!R.show(mob,null,CMMsg.MSG_QUIETMOVEMENT,L("<S-NAME> continue(s) researching '@x1'",what)))
{
unInvoke();
return false;
}
}
if(checkIter==null)
{
final HashSet<Area> areas=new HashSet<Area>();
Area A=null;
final HashSet<Area> areasTried=new HashSet<Area>();
int numAreas = 0;
numAreas=(int)Math.round(CMath.mul(CMLib.map().numAreas(),0.90))+1;
if(numAreas>CMLib.map().numAreas())
numAreas=CMLib.map().numAreas();
int tries=numAreas*numAreas;
while((areas.size()<numAreas)&&(((--tries)>0)))
{
A=CMLib.map().getRandomArea();
if((A!=null)&&(!areasTried.contains(A)))
{
areasTried.add(A);
if((CMLib.flags().canAccess(mob,A))
&&(!CMath.bset(A.flags(),Area.FLAG_INSTANCE_CHILD)))
areas.add(A);
else
numAreas--;
}
}
final TrackingLibrary.TrackingFlags flags=CMLib.tracking().newFlags();
final int range=25 + (2*super.getXLEVELLevel(mob))+(10*super.getXMAXRANGELevel(mob));
final List<Room> checkSet=CMLib.tracking().getRadiantRooms(mob.location(),flags,range);
checkIter=checkSet.iterator();
numRoomsToDo=(checkSet.size()/(tickDown-1))+1;
return true;
}
else
if((tickDown > 1)&&(checkIter.hasNext()))
{
final int maxFound=1+(super.getXLEVELLevel(mob));
// look for it!
MOB inhab=null;
Environmental item=null;
Room room=null;
ShopKeeper SK=null;
if(tickDown<3)
numRoomsToDo=Integer.MAX_VALUE;
final CMFlagLibrary flags=CMLib.flags();
final LegalLibrary law=CMLib.law();
final WorldMap map=CMLib.map();
for (int r=0;(r<numRoomsToDo) && checkIter.hasNext();r++)
{
room=map.getRoom(checkIter.next());
if((!flags.canAccess(mob,room))
||((law.isLandOwnable(room))&&(!law.doesHavePriviledgesHere(mob, room))))
continue;
item=room.findItem(null,what);
if((item!=null)
&&(flags.canBeLocated((Item)item)))
{
final String str=L("@x1 is in a place called '@x2' in @x3.",item.name(),room.displayText(mob),room.getArea().name());
itemsFound.add(str);
if(item instanceof Physical)
{
ticksToRemain += (2*((Physical)item).phyStats().level())-adjustedLevel(mob,0)-numBooksInRoom;
if(ticksToRemain<0)
ticksToRemain=0;
}
}
for(int i=0;i<room.numInhabitants();i++)
{
inhab=room.fetchInhabitant(i);
if(inhab==null)
break;
if(((!flags.isCloaked(inhab))
||((CMSecurity.isAllowedAnywhere(mob,CMSecurity.SecFlag.CLOAK)||CMSecurity.isAllowedAnywhere(mob,CMSecurity.SecFlag.WIZINV))
&&(mob.phyStats().level()>=inhab.phyStats().level()))))
{
item=inhab.findItem(what);
SK=CMLib.coffeeShops().getShopKeeper(inhab);
if((item==null)&&(SK!=null))
item=SK.getShop().getStock(what,mob);
if((item instanceof Item)
&&(flags.canBeLocated((Item)item)))
{
final CMMsg msg2=CMClass.getMsg(mob,inhab,this,verbalCastCode(mob,null,false),null);
if(room.okMessage(mob,msg2))
{
room.send(mob,msg2);
if(item instanceof Physical)
{
ticksToRemain += (2*((Physical)item).phyStats().level())-adjustedLevel(mob,0)-numBooksInRoom;
if(ticksToRemain <0)
ticksToRemain=0;
}
final String str=L("@x1@x2 is being carried by @x3 in a place called '@x4' in @x5."
,item.name(),"",inhab.name(),room.displayText(mob),room.getArea().name());
itemsFound.add(str);
break;
}
}
}
}
if(itemsFound.size()>=maxFound)
break;
while(itemsFound.size()>maxFound)
itemsFound.remove(CMLib.dice().roll(1,itemsFound.size(),-1));
}
if((!checkIter.hasNext())||(tickDown==2)) // set the final time remaning
tickDown += ticksToRemain;
}
}
return true;
}
protected int numBooksInLibrary(final MOB mob)
{
if(mob==null)
return 0;
final Room R=mob.location();
if(R==null)
return 0;
if(theRoom == null)
{
numBooksInRoom = 0;
theRoom=R;
if(CMLib.english().containsString(R.displayText(), "library"))
numBooksInRoom += 10;
for(final Enumeration<Item> i=R.items();i.hasMoreElements();)
{
final Item I=i.nextElement();
if((I instanceof Book)
&&(((Book)I).getUsedPages()>0))
numBooksInRoom++;
}
for(final Enumeration<Item> i=mob.items();i.hasMoreElements();)
{
final Item I=i.nextElement();
if((I instanceof Book)
&&(((Book)I).getUsedPages()>0))
numBooksInRoom++;
}
for(final Enumeration<MOB> m=R.inhabitants();m.hasMoreElements();)
{
final MOB M=m.nextElement();
if(M==null)
continue;
final ShopKeeper SK=CMLib.coffeeShops().getShopKeeper(M);
if(SK==null)
continue;
final CoffeeShop shop=SK.getShop();
if(shop!=null)
{
for(final Iterator<Environmental> i=shop.getStoreInventory();i.hasNext();)
{
final Environmental I=i.next();
if((I instanceof Book)
&&(((Book)I).getUsedPages()>0))
numBooksInRoom++;
}
}
}
}
return numBooksInRoom;
}
@Override
public boolean invoke(final MOB mob, final List<String> commands, final Physical givenTarget, final boolean auto, final int asLevel)
{
final String itemName=CMParms.combine(commands);
if(itemName.trim().length()==0)
{
mob.tell(L("Research what item?"));
return false;
}
final Room R=mob.location();
if(R==null)
return false;
if(this.numBooksInLibrary(mob)==0)
{
mob.tell(L("I don't think you'll get much research done here."));
return false;
}
if(mob.isInCombat())
{
mob.tell(L("You are too busy to do that right now."));
return false;
}
if(!CMLib.flags().canBeSeenBy(R, mob))
{
mob.tell(L("You need to be able to see to do that."));
return false;
}
if(!CMLib.flags().isAliveAwakeMobileUnbound(mob,true))
{
mob.tell(L("You can't do that right now."));
return false;
}
if(!super.invoke(mob, commands, givenTarget, auto, asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,null,this,CMMsg.MSG_QUIETMOVEMENT,mob.isMonster()?null:L("<S-NAME> begin(s) to research the location of '@x1'.",itemName));
if(R.okMessage(mob,msg))
{
R.send(mob,msg);
final Skill_ResearchItem researchA = (Skill_ResearchItem)beneficialAffect(mob,mob,asLevel,10);
if(researchA != null)
{
researchA.tickDown=10; // override any expertise!
researchA.setMiscText(itemName);
}
}
}
else
return beneficialVisualFizzle(mob,null,L("<S-NAME> attempt(s) to engage in research, but can't get started."));
// return whether it worked
return success;
}
}
|
75py/My-pkgs | app/src/androidTest/java/com/nagopy/android/mypkgs/uiautomator/UITest.java | package com.nagopy.android.mypkgs.uiautomator;
import android.os.Environment;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiScrollable;
import android.support.test.uiautomator.UiSelector;
import android.support.v4.view.ViewPager;
import android.test.ActivityInstrumentationTestCase2;
import android.text.TextUtils;
import android.widget.ListView;
import android.widget.TextView;
import com.nagopy.android.mypkgs.BuildConfig;
import com.nagopy.android.mypkgs.MainActivity;
import com.nagopy.android.mypkgs.R;
import com.viewpagerindicator.TabPageIndicator;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@RunWith(AndroidJUnit4.class)
public class UITest extends ActivityInstrumentationTestCase2<MainActivity> {
private MainActivity mActivity;
private UiDevice uiDevice;
public UITest() {
super(MainActivity.class);
}
@Before
public void setUp() throws Exception {
super.setUp();
injectInstrumentation(InstrumentationRegistry.getInstrumentation());
mActivity = getActivity();
UiAutomatorUtil.initConfigure();
uiDevice = UiDevice.getInstance(getInstrumentation());
}
@After
public void tearDown() throws Exception {
uiDevice.pressBack();
UiAutomatorUtil.finishApp(uiDevice, BuildConfig.APPLICATION_ID);
super.tearDown();
}
@Test
public void allApps() throws Exception {
validateCurrentPageTitle(mActivity.getString(R.string.title_all));
UiScrollable listView = new UiScrollable(new UiSelector().className(ListView.class).scrollable(true));
listView.scrollToBeginning(10);
// リストの一つ一つをチェックする前に、現状のスクリーンショットを撮っておく
UiAutomatorUtil.takeScreenshot(uiDevice, mActivity.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "LIST.jpg");
List<String> errorAppList = validateAllItems(listView, new InstalledAppDetailValidator() {
@Override
public boolean validate(String packageName) throws UiObjectNotFoundException {
// とりあえず落ちなければいいので何でもOK
return true;
}
}
);
}
/**
* ViewPagerを左スワイプ(=右から左へスワイプ=右の画面へ移動)する.
*
* @return {@link android.support.test.uiautomator.UiScrollable#swipeLeft(int)}の戻り値
* @throws UiObjectNotFoundException
*/
private boolean swipeLeft() throws UiObjectNotFoundException {
return new UiScrollable((new UiSelector().className(ViewPager.class))).swipeLeft(10);
}
/**
* ViewPagerを右スワイプ(=左から右へスワイプ=右の画面へ移動)する.
*
* @return {@link android.support.test.uiautomator.UiScrollable#swipeLeft(int)}の戻り値
* @throws UiObjectNotFoundException
*/
private boolean swipeRight() throws UiObjectNotFoundException {
return new UiScrollable((new UiSelector().className(ViewPager.class))).swipeRight(10);
}
private interface InstalledAppDetailValidator {
/**
* 検証を行う.
*
* @param packageName 対象パッケージ名(警告がある場合のメッセージ出力に使用)
* @return 検証エラーがなければtrue、エラーがあればfalse.<br>
* 警告がある場合はtrueを返し、標準出力にメッセージを出力する。
* @throws UiObjectNotFoundException
*/
boolean validate(String packageName) throws UiObjectNotFoundException;
}
/**
* ListViewの各要素を検証する.
*
* @param listView ListViewを取得した UiScrollable
* @param validator InstalledAppDetailValidatorを実装したクラス
* @return エラーがあったアプリのパッケージ名のリスト
* @throws UiObjectNotFoundException
*/
private List<String> validateAllItems(UiScrollable listView, InstalledAppDetailValidator validator) throws UiObjectNotFoundException {
try {
listView.setSwipeDeadZonePercentage(0.2); // デッドゾーンを若干大きめにして、スクロール幅を縮小する
} catch (NoSuchMethodError e) {
// API16以上のはずだが、SH-02Eでエラーになる。テストに大きく支障があるわけではないため無視する。
UiAutomatorUtil.errorLog(e);
}
List<String> errorAppList = new ArrayList<>();
Set<String> testedPackages = new HashSet<>();
boolean hasNext;
do { // ListViewのスクロールをループするdo-whileループ
hasNext = false;
for (int i = 0; ; i++) { // ListViewに今表示されている要素を一つ一つ見ていくforループ
try {
UiObject clickable = uiDevice.findObject(
new UiSelector()
.resourceId(mActivity.getResources().getResourceName(R.id.list_parent))
.description("listItem")
.index(i)
);
if (!clickable.exists()) {
// i番目の要素が見つからない場合
break;
}
UiObject titleTextView;
String label;
try {
titleTextView =
clickable.getChild(
new UiSelector()
.resourceId(mActivity.getResources().getResourceName(R.id.list_title))
.className(TextView.class)
.description("application name")
);
label = titleTextView.getText();
} catch (UiObjectNotFoundException e) {
// タイトルが取得できない場合
UiAutomatorUtil.debugLog("continue (title not found)");
continue;
}
UiObject packageNameTextView =
clickable.getChild(
new UiSelector()
.resourceId(mActivity.getResources().getResourceName(R.id.list_package_name))
.className(TextView.class)
.description("package name")
);
String packageName = packageNameTextView.getText();
if (TextUtils.isEmpty(packageName) || testedPackages.contains(packageName)) {
UiAutomatorUtil.debugLog("continue " + packageName);
continue;
}
UiAutomatorUtil.infoLog(label + " [" + packageName + "]");
hasNext = true;
testedPackages.add(packageName);
titleTextView.clickAndWaitForNewWindow();
UiAutomatorUtil.takeScreenshot(uiDevice, mActivity.getExternalFilesDir(Environment.DIRECTORY_PICTURES), packageName + ".png");
if (!validator.validate(packageName)) {
// バリデータでエラーになった場合
if (UiAutomatorUtil.isIgnorePackage(packageName)) {
// 無視リストに入っている場合はエラーにせず、ログ出力のみで次へ進む
UiAutomatorUtil.infoLog("[Info] Ignore application:" + packageName);
} else {
// バリデータでエラーになり、かつ無視リストに入っていない場合はエラーとする
errorAppList.add(packageName);
}
}
uiDevice.pressBack();
} catch (UiObjectNotFoundException e) {
// 画面に表示されているListViewの要素のi番目が見つからない OR パッケージ名が見つからない
// = 今表示されている分は全部見た
// = forループは抜け、次へ進む
UiAutomatorUtil.debugLog(i + ", continue(e) " + e.getMessage());
break;
}
}
listView.scrollForward();
} while (hasNext);
return errorAppList;
}
private void validateCurrentPageTitle(String title) throws UiObjectNotFoundException {
UiAutomatorUtil.debugLog("validateCurrentPageTitle " + title);
UiObject titlePageIndicator = uiDevice.findObject(
new UiSelector()
.className(TabPageIndicator.class)
);
assertEquals("TabPageIndicatorが【" + title + "】であることを確認", title, titlePageIndicator.getText());
}
} |
AllenWilliamson/happo.io | src/loadUserConfig.js | import request from 'request-promise-native';
import requireRelative from 'require-relative';
import Logger from './Logger';
import WrappedError from './WrappedError';
import * as defaultConfig from './DEFAULTS';
function load(pathToConfigFile) {
try {
return Object.assign({}, defaultConfig, requireRelative(pathToConfigFile, process.cwd()));
} catch (e) {
// We only check for the default config file here, so that a missing custom
// config path isn't ignored.
if (e.message && /Cannot find.*\.happo\.js/.test(e.message)) {
return defaultConfig;
}
throw new Error(e);
}
}
async function getPullRequestSecret({ endpoint }, env) {
const { secret } = await request({
url: `${endpoint}/api/pull-request-token`,
method: 'POST',
json: true,
body: {
prUrl: env.CHANGE_URL,
},
});
return secret;
}
export default async function loadUserConfig(
pathToConfigFile,
env = process.env,
) {
const { CHANGE_URL, HAPPO_CONFIG_FILE } = env;
if (HAPPO_CONFIG_FILE) {
pathToConfigFile = HAPPO_CONFIG_FILE;
}
const config = load(pathToConfigFile);
if (!config.apiKey || !config.apiSecret) {
if (!CHANGE_URL) {
throw new Error(
'You need an `apiKey` and `apiSecret` in your config. ' +
'To obtain one, go to https://happo.io/settings',
);
}
try {
// Reassign api tokens to temporary ones provided for the PR
new Logger().info(
'No `apiKey` or `apiSecret` found in config. Falling back to pull-request authentication.',
);
config.apiKey = CHANGE_URL;
config.apiSecret = await getPullRequestSecret(config, env);
} catch (e) {
throw new WrappedError('Failed to obtain temporary pull-request token', e);
}
}
if (!config.targets || Object.keys(config.targets).length === 0) {
throw new Error(
'You need at least one target defined under `targets`. ' +
'See https://github.com/happo/happo.io#targets for more info.',
);
}
const defaultKeys = Object.keys(defaultConfig);
const usedKeys = Object.keys(config);
usedKeys.forEach((key) => {
if (!defaultKeys.includes(key)) {
new Logger().warn(`Unknown config key used in .happo.js: "${key}"`);
}
});
config.publicFolders.push(config.tmpdir);
config.plugins.forEach(({ publicFolders }) => {
if (publicFolders) {
config.publicFolders.push(...publicFolders);
}
});
return config;
}
|
peopledoc/ml-versioning-tools | mlvtools/cmd.py | import logging
import sys
import traceback
import os.path
import argparse
from argparse import ArgumentParser, Namespace
from typing import Tuple, Any, List
from mlvtools.conf.conf import get_conf_file_default_path, load_conf_or_default, MlVToolConf
from mlvtools.exception import MlVToolException
from mlvtools.helper import to_sanitized_path
class SanitizePath(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, to_sanitized_path(values))
class CommandHelper:
def set_log_level(self, args: Namespace):
logging.addLevelName(logging.WARNING + 1, 'mlvtools')
log_format = '%(levelname).8s:%(message)s'
if args.debug:
logging.basicConfig(level=logging.DEBUG, format=log_format)
elif args.verbose:
logging.basicConfig(level=logging.INFO, format=log_format)
def check_force(self, force: bool, outputs: List[str]):
if force:
return
for output in outputs:
if os.path.exists(output):
raise MlVToolException(f'Output file {output} already exists, '
f'use --force option to overwrite it')
def get_conf(self, working_dir_arg: str, input_file_arg: str, conf_path_arg: str) -> MlVToolConf:
conf_path = conf_path_arg or get_conf_file_default_path(working_dir_arg)
return load_conf_or_default(conf_path, working_dir_arg)
def run_cmd(self, *args, **kwargs):
try:
self.run(*args, **kwargs)
except MlVToolException as e:
logging.critical(e)
logging.debug(traceback.format_exc())
sys.exit(1)
except Exception as e:
logging.critical(f'Unexpected error happened: {e}')
logging.info('Reason: ', exc_info=True)
sys.exit(1)
def run(self, *args, **kwargs):
raise NotImplementedError()
class ArgumentBuilder:
def __init__(self, **kwargs):
self.parser = ArgumentParser(**kwargs)
def add_work_dir_argument(self) -> 'ArgumentBuilder':
self.parser.add_argument('-w', '--working-directory', type=str, default=os.path.curdir,
help='Working directory. Other paths are relative to the '
'working directory. Defaults to the current directory.')
return self
def add_conf_path_argument(self) -> 'ArgumentBuilder':
self.parser.add_argument('-c', '--conf-path', type=str,
help='Path to configuration file. Defaults to '
'[working_directory]/.mlvtools.')
return self
def add_force_argument(self) -> 'ArgumentBuilder':
self.parser.add_argument('-f', '--force', action='store_true',
help='Force output overwrite.')
return self
def add_docstring_conf(self) -> 'ArgumentBuilder':
self.parser.add_argument('--docstring-conf', type=str,
help='Path to user configuration used for docstring templating. '
'Relative to working directory.')
return self
def add_argument(self, *args, **kwargs) -> 'ArgumentBuilder':
self.parser.add_argument(*args, **kwargs)
return self
def add_path_argument(self, *args, **kwargs) -> 'ArgumentBuilder':
self.parser.add_argument(*args, **kwargs, action=SanitizePath)
return self
def parse(self, args: Tuple[Any] = None):
self.parser.add_argument('-v', '--verbose', action='store_true',
help='Increase the log level to INFO.')
self.parser.add_argument('--debug', action='store_true',
help='Increase the log level to DEBUG.')
# Args must be explicitly None if they are empty
return self.parser.parse_args(args=args if args else None)
|
xellio/myra-shell | api/domain.go | <filename>api/domain.go
package api
import (
"net/http"
"github.com/Myra-Security-GmbH/myra-shell/api/vo"
)
//
// DomainList ...
//
func (a *myraAPI) DomainList(search string) ([]vo.DomainVO, error) {
ret, err := a.request(http.MethodGet, "/domains/1?search="+search, nil)
if err != nil {
return []vo.DomainVO{}, err
}
queryVO := struct {
vo.QueryVO
List []vo.DomainVO `json:"list"`
}{}
err = a.unmarshalResponse(ret, &queryVO)
if err != nil {
return []vo.DomainVO{}, err
}
return queryVO.List, nil
}
//
// DomainByName ...
//
func (a *myraAPI) DomainByName(name string) (*vo.DomainVO, error) {
list, _ := a.DomainList(name)
if len(list) == 1 {
return &list[0], nil
}
return nil, nil
}
|
codelieche/codelieche.com | apps/article/urls/api/main.py | # -*- coding:utf-8 -*-
from django.urls import path, include
urlpatterns = [
# 前缀:/api/v1/article/
# 文章分类
path('category/', include(arg=("article.urls.api.category", "article"), namespace="category")),
# 文章标签
path('tag/', include(arg=("article.urls.api.tag", "article"), namespace="tag")),
# 文章api
path('post/', include(arg=("article.urls.api.post", "article"), namespace="post")),
# 文章图片api
path('image/', include(arg=("article.urls.api.image", "article"), namespace="image")),
]
|
rockandsalt/conan-center-index | recipes/libaom-av1/all/conanfile.py | <reponame>rockandsalt/conan-center-index
from conans import ConanFile, tools, CMake
from conans.errors import ConanInvalidConfiguration
import os
required_conan_version = ">=1.33.0"
class LibaomAv1Conan(ConanFile):
name = "libaom-av1"
description = "AV1 Codec Library"
topics = ("av1", "codec", "video", "encoding", "decoding")
url = "https://github.com/conan-io/conan-center-index"
homepage = "https://aomedia.googlesource.com/aom"
license = "BSD-2-Clause"
settings = "os", "arch", "compiler", "build_type"
options = {
"shared": [True, False],
"fPIC": [True, False],
"assembly": [True, False],
}
default_options = {
"shared": False,
"fPIC": True,
"assembly": False,
}
generators = "cmake"
exports_sources = "CMakeLists.txt", "patches/*"
_cmake = None
@property
def _source_subfolder(self):
return "source_subfolder"
@property
def _build_subfolder(self):
return "build_subfolder"
@property
def _settings_build(self):
return getattr(self, "settings_build", self.settings)
def config_options(self):
if self.settings.os == "Windows":
del self.options.fPIC
def configure(self):
if self.options.shared:
del self.options.fPIC
if self.settings.arch not in ("x86", "x86_64"):
del self.options.assembly
def build_requirements(self):
if self.options.get_safe("assembly", False):
self.build_requires("nasm/2.15.05")
if self._settings_build.os == "Windows":
self.build_requires("strawberryperl/5.30.0.1")
def validate(self):
if self.settings.compiler.cppstd:
tools.check_min_cppstd(self, 11)
# Check compiler version
compiler = str(self.settings.compiler)
compiler_version = tools.Version(self.settings.compiler.version.value)
minimal_version = {
"Visual Studio": "15",
"gcc": "5",
"clang": "5",
"apple-clang": "6"
}
if compiler not in minimal_version:
self.output.warn(
"%s recipe lacks information about the %s compiler standard version support" % (self.name, compiler))
elif compiler_version < minimal_version[compiler]:
raise ConanInvalidConfiguration("{} requires a {} version >= {}".format(self.name, compiler, compiler_version))
def source(self):
tools.get(**self.conan_data["sources"][self.version],
destination=self._source_subfolder)
def _patch_sources(self):
for patch in self.conan_data.get("patches", {}).get(self.version, []):
tools.patch(**patch)
def _configure_cmake(self):
if self._cmake:
return self._cmake
self._cmake = CMake(self)
self._cmake.definitions["ENABLE_EXAMPLES"] = False
self._cmake.definitions["ENABLE_TESTS"] = False
self._cmake.definitions["ENABLE_DOCS"] = False
self._cmake.definitions["ENABLE_TOOLS"] = False
if not self.options.get_safe("assembly", False):
# make non-assembly build
self._cmake.definitions["AOM_TARGET_CPU"] = "generic"
# libyuv is used for examples, tests and non-essential 'dump_obu' tool so it is disabled
# required to be 1/0 instead of False
self._cmake.definitions["CONFIG_LIBYUV"] = 0
# webm is not yet packaged
self._cmake.definitions["CONFIG_WEBM_IO"] = 0
# required out-of-source build
self._cmake.configure(build_folder=self._build_subfolder)
return self._cmake
def build(self):
self._patch_sources()
cmake = self._configure_cmake()
cmake.build()
def package(self):
self.copy("LICENSE", dst="licenses", src=self._source_subfolder)
cmake = self._configure_cmake()
cmake.install()
tools.rmdir(os.path.join(self.package_folder, "lib", "pkgconfig"))
if self.options.shared:
tools.remove_files_by_mask(os.path.join(self.package_folder, "lib"), "*.a")
def package_info(self):
self.cpp_info.libs = ["aom"]
self.cpp_info.names["cmake_find_package"] = "aom"
self.cpp_info.names["cmake_find_package_multi"] = "aom"
self.cpp_info.names["pkg_config"] = "libaom"
if self.settings.os in ("FreeBSD", "Linux"):
self.cpp_info.system_libs = ["pthread", "m"]
|
bianapis/sd-branch-location-operations-v3 | src/main/java/org/bian/dto/SDBranchLocationOperationsActivateInputModelBranchLocationOperationsServiceConfigurationRecord.java | <reponame>bianapis/sd-branch-location-operations-v3
package org.bian.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.bian.dto.SDBranchLocationOperationsActivateInputModelBranchLocationOperationsServiceConfigurationRecordBranchLocationOperationsServiceConfigurationSetup;
import javax.validation.Valid;
/**
* SDBranchLocationOperationsActivateInputModelBranchLocationOperationsServiceConfigurationRecord
*/
public class SDBranchLocationOperationsActivateInputModelBranchLocationOperationsServiceConfigurationRecord {
private String branchLocationOperationsServiceConfigurationSettingReference = null;
private String branchLocationOperationsServiceConfigurationSettingType = null;
private SDBranchLocationOperationsActivateInputModelBranchLocationOperationsServiceConfigurationRecordBranchLocationOperationsServiceConfigurationSetup branchLocationOperationsServiceConfigurationSetup = null;
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Refers to the service configuration parameter for the service
* @return branchLocationOperationsServiceConfigurationSettingReference
**/
public String getBranchLocationOperationsServiceConfigurationSettingReference() {
return branchLocationOperationsServiceConfigurationSettingReference;
}
public void setBranchLocationOperationsServiceConfigurationSettingReference(String branchLocationOperationsServiceConfigurationSettingReference) {
this.branchLocationOperationsServiceConfigurationSettingReference = branchLocationOperationsServiceConfigurationSettingReference;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: The type of service configuration parameter
* @return branchLocationOperationsServiceConfigurationSettingType
**/
public String getBranchLocationOperationsServiceConfigurationSettingType() {
return branchLocationOperationsServiceConfigurationSettingType;
}
public void setBranchLocationOperationsServiceConfigurationSettingType(String branchLocationOperationsServiceConfigurationSettingType) {
this.branchLocationOperationsServiceConfigurationSettingType = branchLocationOperationsServiceConfigurationSettingType;
}
/**
* Get branchLocationOperationsServiceConfigurationSetup
* @return branchLocationOperationsServiceConfigurationSetup
**/
public SDBranchLocationOperationsActivateInputModelBranchLocationOperationsServiceConfigurationRecordBranchLocationOperationsServiceConfigurationSetup getBranchLocationOperationsServiceConfigurationSetup() {
return branchLocationOperationsServiceConfigurationSetup;
}
public void setBranchLocationOperationsServiceConfigurationSetup(SDBranchLocationOperationsActivateInputModelBranchLocationOperationsServiceConfigurationRecordBranchLocationOperationsServiceConfigurationSetup branchLocationOperationsServiceConfigurationSetup) {
this.branchLocationOperationsServiceConfigurationSetup = branchLocationOperationsServiceConfigurationSetup;
}
}
|
nocke/photocmd | src/app/main/tests/getapp.js | import { Application } from 'spectron'
import { resolve } from 'app-root-path'
export default () => (
new Application({
path: resolve('./node_modules/.bin/electron' + (process.platform === 'win32' ? '.cmd' : '')),
args: [resolve('.')],
startTimeout: 10000,
waitTimeout: 10000,
env: {
ELECTRON_IS_DEV: '0'
}
})
)
|
joansmith2/basex | basex-core/src/main/java/org/basex/query/expr/ValueAccess.java | package org.basex.query.expr;
import static org.basex.query.QueryText.*;
import static org.basex.util.Token.*;
import java.util.*;
import org.basex.data.*;
import org.basex.index.*;
import org.basex.index.query.*;
import org.basex.query.*;
import org.basex.query.expr.path.*;
import org.basex.query.func.*;
import org.basex.query.iter.*;
import org.basex.query.util.*;
import org.basex.query.value.item.*;
import org.basex.query.value.node.*;
import org.basex.query.var.*;
import org.basex.util.*;
import org.basex.util.hash.*;
/**
* This index class retrieves texts and attribute values from the index.
*
* @author BaseX Team 2005-15, BSD License
* @author <NAME>
*/
public final class ValueAccess extends IndexAccess {
/** Expression. */
private Expr expr;
/** Text index. */
private final boolean text;
/** Parent name test. */
private final NameTest test;
/**
* Constructor.
* @param info input info
* @param expr index expression
* @param text text index
* @param test test test
* @param ictx index context
*/
public ValueAccess(final InputInfo info, final Expr expr, final boolean text, final NameTest test,
final IndexContext ictx) {
super(ictx, info);
this.expr = expr;
this.text = text;
this.test = test;
}
@Override
public BasicNodeIter iter(final QueryContext qc) throws QueryException {
final ArrayList<BasicNodeIter> iter = new ArrayList<>();
final Iter ir = qc.iter(expr);
for(Item it; (it = ir.next()) != null;) iter.add(index(it.string(info)));
final int is = iter.size();
return is == 0 ? BasicNodeIter.EMPTY : is == 1 ? iter.get(0) :
new Union(info, expr).eval(iter.toArray(new NodeIter[is])).iter();
}
/**
* Returns an index iterator.
* @param term term to be found
* @return iterator
*/
private BasicNodeIter index(final byte[] term) {
// special case: empty text node
// - no element name: return 0 results (empty text nodes are non-existent)
// - otherwise, return scan-based element iterator
final int tl = term.length;
if(tl == 0 && text) return test == null ? BasicNodeIter.EMPTY : scanEmpty();
// use index traversal if index exists and if term is not too long.
// otherwise, scan data sequentially
final Data data = ictx.data;
final IndexIterator ii = (text ? data.meta.textindex : data.meta.attrindex) &&
tl > 0 && tl <= data.meta.maxlen ? data.iter(new StringToken(text, term)) : scan(term);
final int kind = text ? Data.TEXT : Data.ATTR;
final DBNode tmp = new DBNode(data, 0, test == null ? kind : Data.ELEM);
return new BasicNodeIter() {
@Override
public ANode next() {
while(ii.more()) {
if(test == null) {
tmp.pre(ii.pre());
} else {
tmp.pre(data.parent(ii.pre(), kind));
if(!test.eq(tmp)) continue;
}
return tmp.finish();
}
return null;
}
};
}
/**
* Returns a scan-based index iterator, which looks for text nodes with the specified value.
* @param value value to be looked up
* @return node iterator
*/
private IndexIterator scan(final byte[] value) {
return new IndexIterator() {
final Data data = ictx.data;
final byte kind = text ? Data.TEXT : Data.ATTR;
final int sz = data.meta.size;
int pre = -1;
@Override
public int pre() {
return pre;
}
@Override
public boolean more() {
while(++pre < sz) {
if(data.kind(pre) == kind && eq(data.text(pre, text), value)) return true;
}
return false;
}
@Override
public int size() {
return Math.max(1, sz >>> 1);
}
};
}
/**
* Returns a scan-based iterator, which returns elements
* a) matching the name test and
* b) having no descendants.
* @return node iterator
*/
private BasicNodeIter scanEmpty() {
return new BasicNodeIter() {
final Data data = ictx.data;
final DBNode tmp = new DBNode(data, 0, Data.ELEM);
final int sz = data.meta.size;
int pre = -1;
@Override
public DBNode next() {
while(++pre < sz) {
if(data.kind(pre) == Data.ELEM && data.size(pre, Data.ELEM) == 1) {
tmp.pre(pre);
if(test == null || test.eq(tmp)) return tmp.finish();
}
}
return null;
}
};
}
@Override
public boolean has(final Flag flag) {
return expr.has(flag);
}
@Override
public boolean removable(final Var var) {
return expr.removable(var);
}
@Override
public VarUsage count(final Var var) {
return expr.count(var);
}
@Override
public Expr inline(final QueryContext qc, final VarScope scp, final Var var, final Expr ex)
throws QueryException {
final Expr sub = expr.inline(qc, scp, var, ex);
if(sub == null) return null;
expr = sub;
return optimize(qc, scp);
}
@Override
public Expr copy(final QueryContext qc, final VarScope scp, final IntObjMap<Var> vs) {
return copyType(new ValueAccess(info, expr.copy(qc, scp, vs), text, test, ictx));
}
@Override
public boolean accept(final ASTVisitor visitor) {
return expr.accept(visitor) && super.accept(visitor);
}
@Override
public int exprSize() {
return expr.exprSize() + 1;
}
@Override
public void plan(final FElem plan) {
addPlan(plan, planElem(DATA, ictx.data.meta.name, TYP,
text ? IndexType.TEXT : IndexType.ATTRIBUTE, NAM, test), expr);
}
@Override
public String toString() {
final TokenBuilder string = new TokenBuilder();
string.add((text ? Function._DB_TEXT : Function._DB_ATTRIBUTE).get(
null, info, Str.get(ictx.data.meta.name), expr).toString());
if(test != null) string.add("/parent::").addExt(test);
return string.toString();
}
}
|
zicla/Webzic | compass/src/main/java/com/logzc/webzic/compass/dao/UserDao.java | <reponame>zicla/Webzic<filename>compass/src/main/java/com/logzc/webzic/compass/dao/UserDao.java
package com.logzc.webzic.compass.dao;
import com.logzc.webzic.annotation.Repository;
import com.logzc.webzic.compass.model.User;
import com.logzc.webzic.orm.dao.Dao;
/**
* Created by lishuang on 2016/10/11.
*/
@Repository
public interface UserDao extends Dao<User,Long>{
}
|
Layton85/akordyukov | chapter_002/src/test/java/ru/job4j/chess/BoardTest.java | package ru.job4j.chess;
import org.junit.Test;
import ru.job4j.chess.figures.*;
import static org.junit.Assert.*;
/**
* BoardTest.
*
* @author <NAME> (<EMAIL>)
* @version $Id$
* @since 0.1
*/
public class BoardTest {
@Test
public void whenMoveD5E4ThenCorrect() {
Board board = new Board();
board.add(new Bishop(Cell.D5));
board.move(Cell.D5, Cell.E4);
try {
board.move(Cell.E4, Cell.F3);
} catch (FigureNotFoundException fnfe) {
fail("The figure hasn't been correctly moved");
}
}
@Test
public void whenMoveD5F3ThenCorrect() {
Board board = new Board();
board.add(new Bishop(Cell.D5));
board.move(Cell.D5, Cell.F3);
try {
board.move(Cell.F3, Cell.G2);
} catch (FigureNotFoundException fnfe) {
fail("The figure hasn't been correctly moved");
}
}
@Test
public void whenMoveD5E6ThenCorrect() {
Board board = new Board();
board.add(new Bishop(Cell.D5));
board.move(Cell.D5, Cell.E6);
try {
board.move(Cell.E6, Cell.F7);
} catch (FigureNotFoundException fnfe) {
fail("The figure hasn't been correctly moved");
}
}
@Test
public void whenMoveD5F7ThenCorrect() {
Board board = new Board();
board.add(new Bishop(Cell.D5));
board.move(Cell.D5, Cell.F7);
try {
board.move(Cell.F7, Cell.G8);
} catch (FigureNotFoundException fnfe) {
fail("The figure hasn't been correctly moved");
}
}
@Test
public void whenMoveD5C6ThenCorrect() {
Board board = new Board();
board.add(new Bishop(Cell.D5));
board.move(Cell.D5, Cell.C6);
try {
board.move(Cell.C6, Cell.B7);
} catch (FigureNotFoundException fnfe) {
fail("The figure hasn't been correctly moved");
}
}
@Test
public void whenMoveD5B7ThenCorrect() {
Board board = new Board();
board.add(new Bishop(Cell.D5));
board.move(Cell.D5, Cell.B7);
try {
board.move(Cell.B7, Cell.A8);
} catch (FigureNotFoundException fnfe) {
fail("The figure hasn't been correctly moved");
}
}
@Test
public void whenMoveD5C4ThenCorrect() {
Board board = new Board();
board.add(new Bishop(Cell.D5));
board.move(Cell.D5, Cell.C4);
try {
board.move(Cell.C4, Cell.B3);
} catch (FigureNotFoundException fnfe) {
fail("The figure hasn't been correctly moved");
}
}
@Test
public void whenMoveD5B3ThenCorrect() {
Board board = new Board();
board.add(new Bishop(Cell.D5));
board.move(Cell.D5, Cell.B3);
try {
board.move(Cell.B3, Cell.A2);
} catch (FigureNotFoundException fnfe) {
fail("The figure hasn't been correctly moved");
}
}
@Test(expected = OccupiedWayException.class)
public void whenMoveOnAnotherFigureThenOccupiedWayException() {
Board board = new Board();
board.add(new Bishop(Cell.D5));
board.add(new Bishop(Cell.F3));
board.move(Cell.D5, Cell.F3);
}
@Test(expected = OccupiedWayException.class)
public void whenMoveThroughAnotherFigureThenOccupiedWayException() {
Board board = new Board();
board.add(new Bishop(Cell.D5));
board.add(new Bishop(Cell.F3));
board.move(Cell.D5, Cell.G2);
}
@Test(expected = ImpossibleMoveException.class)
public void whenMoveD5D4ThenImpossible() {
Board board = new Board();
board.add(new Bishop(Cell.D5));
board.move(Cell.D5, Cell.D4);
}
@Test(expected = ImpossibleMoveException.class)
public void whenMoveD5D3ThenImpossible() {
Board board = new Board();
board.add(new Bishop(Cell.D5));
board.move(Cell.D5, Cell.D3);
}
@Test(expected = ImpossibleMoveException.class)
public void whenMoveD5E5ThenImpossible() {
Board board = new Board();
board.add(new Bishop(Cell.D5));
board.move(Cell.D5, Cell.E5);
}
@Test(expected = ImpossibleMoveException.class)
public void whenMoveD5F5ThenImpossible() {
Board board = new Board();
board.add(new Bishop(Cell.D5));
board.move(Cell.D5, Cell.F5);
}
@Test(expected = ImpossibleMoveException.class)
public void whenMoveD5D6ThenImpossible() {
Board board = new Board();
board.add(new Bishop(Cell.D5));
board.move(Cell.D5, Cell.D6);
}
@Test(expected = ImpossibleMoveException.class)
public void whenMoveD5D7ThenImpossible() {
Board board = new Board();
board.add(new Bishop(Cell.D5));
board.move(Cell.D5, Cell.D7);
}
@Test(expected = ImpossibleMoveException.class)
public void whenMoveD5C5ThenImpossible() {
Board board = new Board();
board.add(new Bishop(Cell.D5));
board.move(Cell.D5, Cell.C5);
}
@Test(expected = ImpossibleMoveException.class)
public void whenMoveD5B5ThenImpossible() {
Board board = new Board();
board.add(new Bishop(Cell.D5));
board.move(Cell.D5, Cell.B5);
}
}
|
isaoshiaoki/CursosAndroidDaUdemy | LIVRO.GOOGLE.5D/ZIPS/4ed-master/4ed-master/carros/Passo06-RecyclerView/Carros/app/src/main/java/br/com/livroandroid/carros/fragments/CarrosTabFragment.java | package br.com.livroandroid.carros.fragments;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import br.com.livroandroid.carros.R;
import br.com.livroandroid.carros.adapter.TabsAdapter;
/**
* Fragment que controla as Tabs dos carros (classicos,esportivos,luxo)
*/
public class CarrosTabFragment extends BaseFragment implements TabLayout.OnTabSelectedListener {
private ViewPager mViewPager;
private TabLayout tabLayout;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_carros_tab, container, false);
mViewPager = (ViewPager) view.findViewById(R.id.viewpager);
mViewPager.setAdapter(new TabsAdapter(getContext(), getChildFragmentManager()));
tabLayout = (TabLayout) view.findViewById(R.id.tabLayout);
int cor = getContext().getResources().getColor(R.color.white);
// Cor branca no texto (fundo azul foi definido no layout)
tabLayout.setTabTextColors(cor, cor);
// Adiciona as tabs.
tabLayout.addTab(tabLayout.newTab().setText(R.string.classicos));
tabLayout.addTab(tabLayout.newTab().setText(R.string.esportivos));
tabLayout.addTab(tabLayout.newTab().setText(R.string.luxo));
// Listener para tratar eventos de clique na tab.
tabLayout.setOnTabSelectedListener(this);
// Se mudar o ViewPager atualiza a tab selecionada.
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
return view;
}
@Override
public void onTabSelected(TabLayout.Tab tab) {
// Se alterar a tab, atualiza o ViewPager
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) { }
@Override
public void onTabReselected(TabLayout.Tab tab) { }
} |
moutainhigh/ses-server | ses-app/ses-mobile-rps/src/main/java/com/redescooter/ses/mobile/rps/dao/base/OpeInvoiceScooterDetailBMapper.java | package com.redescooter.ses.mobile.rps.dao.base;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.redescooter.ses.mobile.rps.dm.OpeInvoiceScooterDetailB;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface OpeInvoiceScooterDetailBMapper extends BaseMapper<OpeInvoiceScooterDetailB> {
int updateBatch(List<OpeInvoiceScooterDetailB> list);
int batchInsert(@Param("list") List<OpeInvoiceScooterDetailB> list);
int insertOrUpdate(OpeInvoiceScooterDetailB record);
int insertOrUpdateSelective(OpeInvoiceScooterDetailB record);
} |
wilsonleung-gep/dot-plot-viewer | js/seq_reader.js | /*global jQuery */
(function($) {
"use strict";
var GEP = $.fn.GEP,
SeqReader = (function () {
var defaults = {
eventPrefix: "seqReader",
headerMarker: ">",
headerWithDescription: /^>(\S+)\s+(.*)$/,
headerWithoutDescription: /^>(\S+)/
};
function SeqReader(lines, cfg) {
this.settings = GEP.util.mergeConfig(defaults, cfg);
this.records = this.createSeqRecords(lines);
}
SeqReader.prototype.getRecord = function(idx) {
idx = idx || 0;
return this.records[idx];
};
SeqReader.prototype.createSeqRecords = function(lines) {
var numLines = lines.length,
headerMarker = this.settings.headerMarker,
seqInfo,
records = [],
line, i;
for (i = 0; i < numLines; i += 1) {
line = lines[i];
if (line.indexOf(headerMarker) === 0) {
this.addSeqRecord(records, seqInfo);
seqInfo = this.initSeqRecord(line);
} else {
seqInfo.sequence.push(line);
}
}
this.addSeqRecord(records, seqInfo);
return records;
};
SeqReader.prototype.initSeqRecord = function(headerLine) {
var id, description, m;
m = headerLine.match(this.settings.headerWithDescription);
if (m) {
id = m[1];
description = m[2];
} else {
m = headerLine.match(this.settings.headerWithoutDescription);
id = m[1];
description = "";
}
return {
id: id,
description: description,
sequence: []
};
};
SeqReader.prototype.addSeqRecord = function(records, seqInfo) {
if (!seqInfo) {
return;
}
var seqArray = seqInfo.sequence;
seqInfo.sequence = seqArray.join("").replace(/\s+/g, "");
records.push(new GEP.SeqRecord(seqInfo));
};
return SeqReader;
}());
GEP.SeqReader = SeqReader;
}(jQuery));
|
spring2go/geekstore | src/main/java/io/geekstore/resolver/dataloader/CollectionChildrenDataLoader.java | /*
* Copyright (c) 2020 GeekStore.
* All rights reserved.
*/
package io.geekstore.resolver.dataloader;
import io.geekstore.common.utils.BeanMapper;
import io.geekstore.entity.CollectionEntity;
import io.geekstore.mapper.CollectionEntityMapper;
import io.geekstore.types.collection.Collection;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.dataloader.MappedBatchLoader;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.stream.Collectors;
/**
* Created on Nov, 2020 by @author bobo
*/
@RequiredArgsConstructor
public class CollectionChildrenDataLoader implements MappedBatchLoader<Long, List<Collection>> {
private final CollectionEntityMapper collectionEntityMapper;
@Override
public CompletionStage<Map<Long, List<Collection>>> load(Set<Long> parentIds) {
return CompletableFuture.supplyAsync(() -> {
QueryWrapper<CollectionEntity> queryWrapper = new QueryWrapper<>();
queryWrapper.lambda().in(CollectionEntity::getParentId, parentIds);
List<CollectionEntity> collectionEntities = collectionEntityMapper
.selectList(queryWrapper);
if (collectionEntities.size() == 0) {
Map<Long, List<Collection>> emptyMap = new HashMap<>();
parentIds.forEach(id -> emptyMap.put(id, new ArrayList<>()));
return emptyMap;
}
Map<Long, List<Collection>> groupByCollectionId = collectionEntities.stream()
.collect(Collectors.groupingBy(CollectionEntity::getParentId,
Collectors.mapping(collectionEntity -> BeanMapper.map(collectionEntity, Collection.class),
Collectors.toList()
)));
return groupByCollectionId;
});
}
}
|
Ujjawalgupta42/Hacktoberfest2021-DSA | 27. LeetCode Problems/DiameterofBinaryTree.cpp | <reponame>Ujjawalgupta42/Hacktoberfest2021-DSA<filename>27. LeetCode Problems/DiameterofBinaryTree.cpp
// Problem Link : https://leetcode.com/problems/diameter-of-binary-tree/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int solve(TreeNode* root, int &maxi)
{
if(root == NULL)
return 0;
int l = solve(root->left, maxi);
int r = solve(root->right, maxi);
int temp = l + r + 1;
maxi = max(maxi, temp);
return (1 + max(l, r));
}
int diameterOfBinaryTree(TreeNode* root)
{
int maxi = INT_MIN;
int h = solve(root, maxi);
return maxi-1;
}
};
|
Mavennix/eltaj | src/pages/digital-signage.js | import React from 'react'
import PrimaryDemoBanner from '../components/primary-demo-banner'
import QmaticLogo from '../images/qmatic-logo-2.svg'
import HeroImg from "../images/product-qmatic/digital-signage.png"
import EltajImage from '../components/eltaj-image/eltaj-image'
import EltajList from '../components/eltaj-list'
import { Row, Container } from 'react-bootstrap'
import InfoSection from '../components/info-section/info-section'
import Layout from '../components/layout'
import QmaticCloudFeatures from '../data/qmatic-cloud-feature'
import SelfKioskFeatures from '../data/self-kiosk-features'
import DigitalSignageFeatures from '../data/digital-signage-features'
const digitalSignage = () => (
<div>
<Layout>
{/* hero section */}
<section className="pb-5">
<div className="container py-5 my-5">
<div className="row">
<div className="col-md-6 my-auto pb-md-0 pb-5">
<div className="row">
<div className="col-md-10">
<h1 className="mb-4">
DIGITAL SIGNAGE
</h1>
<h6 className="text-muted">
Display content with context
</h6>
</div>
</div>
<button className="btn btn-primary rounded-0 text-center px-4 mt-5">
Book a free demo
</button>
<h6 className="text-muted pt-3">Powered by</h6>
<img src={QmaticLogo} />
</div>
<div className="col-md-6">
<EltajImage image={HeroImg} isImageRight={true} />
</div>
</div>
</div>
</section>
{/* */}
<section>
<Container>
<div className="text-center">
<Row>
<div className="col-md-10 mx-auto">
<h4 className="text-capitalize">Personalise customers’ experience with the right content.</h4>
</div>
</Row>
<Row>
<div className="col-md-9 mx-auto">
<p className="text-muted mt-3">Every minute a customer spends interacting with your business is an opportunity to keep them delighted. Inform, educate and engage them with the right content to keep them coming back for more .</p>
<p className="text-muted mt-3">The ELTAJ digital solution allows you to inform customers of queue status, educate them with valuable content and promote your products and services.</p>
</div>
</Row>
</div>
</Container>
</section>
{/* */}
<section className="my-5 pt-5">
<Container>
{DigitalSignageFeatures.map((solo, index) => (
<InfoSection textFirst={index % 2 === 0 ? true : false} image={solo.image}>
<h2 className="mb-4">
{solo.title}
</h2>
<div className="mb-5">
{solo.features.map((feature, index) => (
<EltajList text={feature} />
))}
</div>
</InfoSection>
))}
</Container>
</section>
{/* Primary Demo Banner */}
<PrimaryDemoBanner />
</Layout>
</div>
)
export default digitalSignage
|
bagseye/mbdev | src/components/DashboardArea.js | <gh_stars>1-10
import React from "react";
import Layout from "./Layout";
import SEO from "./SEO";
import CardContainer from "./Cards/CardContainer";
import Card from "./Cards/Card";
import useAllAgency from "../hooks/use-all-agency";
const DashboardArea = () => {
const agencyData = useAllAgency();
return (
<>
<SEO title="Agency Projects" noIndex />
<Layout>
<div className="container sectiongap">
<div className="content__area">
<h1>Agency Projects</h1>
</div>
</div>
<CardContainer>
{agencyData.map((node, index) => {
return (
<Card key={index} node={node} to={node.slug} route="/agency" />
);
})}
</CardContainer>
</Layout>
</>
);
};
export default DashboardArea;
|
h4091/OhMyBiliBili | app/src/main/java/com/hotbitmapgg/ohmybilibili/config/OhMyBiliBiliApp.java | package com.hotbitmapgg.ohmybilibili.config;
import android.app.Application;
import android.os.Environment;
import com.hotbitmapgg.ohmybilibili.utils.FileUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.Serializable;
/**
* OhMyBiliBiliApp
* 高仿哔哩哔哩动画
*
* @HotBitmapGG
*/
public class OhMyBiliBiliApp extends Application
{
public static OhMyBiliBiliApp mInstance;
//OPlayer SD卡缓存路径
public static final String OPLAYER_CACHE_BASE = Environment.getExternalStorageDirectory() + "/oplayer";
//视频截图缓冲路径
public static final String OPLAYER_VIDEO_THUMB = OPLAYER_CACHE_BASE + "/thumb/";
//首次扫描
public static final String PREF_KEY_FIRST = "application_first";
@Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
mInstance = this;
init();
}
private void init()
{
//创建缓存目录
FileUtils.createIfNoExists(OPLAYER_CACHE_BASE);
FileUtils.createIfNoExists(OPLAYER_VIDEO_THUMB);
}
public static OhMyBiliBiliApp getInstance()
{
return mInstance;
}
/**
* 读取对象
*
* @param file
* @return
* @throws IOException
*/
public Serializable readObject(String file, long... time)
{
if (!isExistDataCache(file, time))
return null;
FileInputStream fis = null;
ObjectInputStream ois = null;
try
{
fis = openFileInput(file);
ois = new ObjectInputStream(fis);
return (Serializable) ois.readObject();
} catch (FileNotFoundException e)
{
} catch (Exception e)
{
e.printStackTrace();
// 反序列化失败 - 删除缓存文件
if (e instanceof InvalidClassException)
{
File data = getFileStreamPath(file);
data.delete();
}
} finally
{
try
{
ois.close();
} catch (Exception e)
{
}
try
{
fis.close();
} catch (Exception e)
{
}
}
return null;
}
/**
* 判断缓存是否存在
*
* @param cachefile
* @return
*/
public boolean isExistDataCache(String cachefile, long... time)
{
boolean exist = false;
File data = getFileStreamPath(cachefile);
if (data.exists())
exist = true;
boolean persistent = time == null || time.length == 0;
return exist && (persistent || isEffictiveData(data.lastModified(), time[0]));
}
/**
* 删除本地缓存数据
*
* @param cachefile
* @return
*/
public synchronized boolean delCache(String cachefile)
{
boolean isDel = false;
File data = getFileStreamPath(cachefile);
if (data.exists())
{
isDel = data.delete();
}
return isDel;
}
/**
* @param modifyTime 文件创建时间
* @param effictTime 文件有效期
* @return
*/
private boolean isEffictiveData(long modifyTime, long effictTime)
{
long diff = System.currentTimeMillis() - modifyTime;
return diff > effictTime ? false : true;
}
}
|
uniqueleon/frameworks | api/src/main/java/org/aztec/framework/api/rest/entity/WSMessageRequest.java | package org.aztec.framework.api.rest.entity;
import java.util.List;
import java.util.Map;
public class WSMessageRequest {
private String sourceId;//`source_id` varchar(20) comment NULL COMMENT '来源ID,发送消息的实体ID',
//`content` text DEFAULT '' COMMENT '消息内容',
private Integer msgType;
private Object sourceObj;//`source_id` varchar(100) comment NULL COMMENT '来源ID,发送消息的实体ID',
//`content` text DEFAULT '' COMMENT '消息内容',
private String consumerId;
private List<String> consumerIds;
private String consumerInfo;
private String content;
//`topic` varchar(200) DEFAULT '' COMMENT '消息主题',
private String topic;
//`title` varchar(400) DEFAULT '' COMMENT '消息标题',
private String title;
private List<Long> hasReadMsgIds;
private Boolean unreadOnly;
public Integer getMsgType() {
return msgType;
}
public void setMsgType(Integer msgType) {
this.msgType = msgType;
}
public Object getSourceObj() {
return sourceObj;
}
public void setSourceObj(Object sourceObj) {
this.sourceObj = sourceObj;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Long> getHasReadMsgIds() {
return hasReadMsgIds;
}
public void setHasReadMsgIds(List<Long> hasReadMsgIds) {
this.hasReadMsgIds = hasReadMsgIds;
}
public String getConsumerInfo() {
return consumerInfo;
}
public void setConsumerInfo(String consumerInfo) {
this.consumerInfo = consumerInfo;
}
public Boolean getUnreadOnly() {
return unreadOnly;
}
public void setUnreadOnly(Boolean unreadOnly) {
this.unreadOnly = unreadOnly;
}
public String getConsumerId() {
return consumerId;
}
public void setConsumerId(String consumerId) {
this.consumerId = consumerId;
}
public List<String> getConsumerIds() {
return consumerIds;
}
public void setConsumerIds(List<String> consumerIds) {
this.consumerIds = consumerIds;
}
public String getSourceId() {
return sourceId;
}
public void setSourceId(String sourceId) {
this.sourceId = sourceId;
}
}
|
tangtaoshadow/Propro-Server | src/main/java/com/westlake/air/propro/domain/bean/learner/ErrorStat.java | <gh_stars>1-10
package com.westlake.air.propro.domain.bean.learner;
import com.westlake.air.propro.domain.bean.score.SimpleFeatureScores;
import lombok.Data;
import java.util.List;
/**
* Created by <NAME>
* Time: 2018-06-13 21:34
*/
@Data
public class ErrorStat {
List<SimpleFeatureScores> bestFeatureScoresList;
StatMetrics statMetrics;
Pi0Est pi0Est;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.