repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
tipplerow/pubmed | pubmed-lib/src/main/java/pubmed/relev/RelevanceSummarySubjectFile.java |
package pubmed.relev;
import java.io.File;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import jam.app.JamLogger;
import jam.io.IOUtil;
import pubmed.article.DOI;
import pubmed.article.PMID;
import pubmed.article.PubmedJournal;
import pubmed.bulk.BulkContributorFile;
import pubmed.bulk.BulkFile;
import pubmed.flat.ArticleDOITable;
import pubmed.flat.ArticleTitleTable;
import pubmed.flat.JournalTable;
import pubmed.flat.PubDateTable;
import pubmed.flat.PMIDTable;
import pubmed.flat.RelevanceScoreRecord;
import pubmed.flat.RelevanceScoreTable;
import pubmed.subject.Subject;
/**
* Generates and stores article-subject relevance summary records.
*/
public final class RelevanceSummarySubjectFile extends RelevanceSummaryFileBase {
// The subject of this file...
private final Subject subject;
// A file containing the names of the bulk files that have
// contributed to the contents of the summary file...
private final BulkContributorFile contribFile;
// One file per subject...
private static final Map<Subject, RelevanceSummarySubjectFile> instances =
new HashMap<Subject, RelevanceSummarySubjectFile>();
private RelevanceSummarySubjectFile(Subject subject) {
super(resolveSummaryFile(subject));
this.subject = subject;
this.contribFile = BulkContributorFile.instance(resolveContribFile(subject));
}
private static File resolveSummaryFile(Subject subject) {
return new File(resolveRelevanceDir(), summaryBaseName(subject));
}
private static File resolveContribFile(Subject subject) {
return new File(resolveRelevanceDir(), contribBaseName(subject));
}
private static String summaryBaseName(Subject subject) {
return subject.getKey() + "_relevance_summary.txt";
}
private static String contribBaseName(Subject subject) {
return subject.getKey() + "_relevance_contrib.txt";
}
/**
* Returns the relevance summary file for a subject.
*
* @param subject the subject of the relevance file.
*
* @return the relevance summary file for the specified subject.
*/
public static RelevanceSummarySubjectFile instance(Subject subject) {
synchronized (subject) {
RelevanceSummarySubjectFile instance = instances.get(subject);
if (instance == null) {
instance = new RelevanceSummarySubjectFile(subject);
instances.put(subject, instance);
}
return instance;
}
}
/**
* Loads the relevance summary records from the file for a given
* subject.
*
* @param subject the subject of interest.
*
* @return the relevance summary records from the file for the
* specified subject.
*/
public static RelevanceSummaryTable load(Subject subject) {
return instance(subject).load();
}
/**
* Loads the identifiers for articles that are deemed likely to be
* relevant to a given subject.
*
* @param subject the subject of interest.
*
* @return a set containing the identifiers for articles that are
* deemed likely to be relevant to the specified subject.
*/
public static Set<PMID> loadRelevantPMID(Subject subject) {
return load(subject).getRelevantPMID();
}
/**
* Processes one bulk file: Loads all relevance scores derived
* from the bulk file, aggregates relevance scores into summary
* records for each subject, appends the summary records to the
* underlying physical files, and records the bulk file as
* processed.
*
* @param bulkFile the bulk file to process.
*
* @param subjects the subjects to process.
*
* @throws RuntimeException if any errors occur.
*/
public static synchronized void process(BulkFile bulkFile, Collection<Subject> subjects) {
JamLogger.info("Updating relevance summary files with [%s]....", bulkFile.getBaseName());
bulkFile.getRelevanceScoreFile().process(subjects);
JournalTable journalTable = bulkFile.getJournalFile().load();
PubDateTable pubDateTable = bulkFile.getPubDateFile().load();
ArticleDOITable articleDOITable = bulkFile.getArticleDOIFile().load();
ArticleTitleTable articleTitleTable = bulkFile.getArticleTitleFile().load();
RelevanceScoreTable relevanceScoreTable = bulkFile.getRelevanceScoreFile().load();
subjects.parallelStream().forEach(subject ->
instance(subject).process(bulkFile,
journalTable,
pubDateTable,
articleDOITable,
articleTitleTable,
relevanceScoreTable));
}
private void process(BulkFile bulkFile,
JournalTable journalTable,
PubDateTable pubDateTable,
ArticleDOITable articleDOITable,
ArticleTitleTable articleTitleTable,
RelevanceScoreTable relevanceScoreTable) {
if (isContributor(bulkFile))
return;
JamLogger.info("Processing relevance summary file: [%s]...", subject);
LocalDate reportDate = LocalDate.now();
List<RelevanceScoreRecord> scoreRecords =
relevanceScoreTable.selectForeign(subject.getKey());
List<RelevanceSummaryRecord> summaryRecords =
new ArrayList<RelevanceSummaryRecord>();
for (RelevanceScoreRecord scoreRecord : scoreRecords) {
PMID pmid = scoreRecord.getPMID();
DOI doi = articleDOITable.selectDOI(pmid);
String title = articleTitleTable.selectTitle(pmid);
LocalDate pubDate = pubDateTable.selectPubDate(pmid);
PubmedJournal journal = journalTable.selectJournal(pmid);
if (doi == null)
continue;
if (title == null)
continue;
if (pubDate == null)
continue;
if (journal == null)
continue;
summaryRecords.add(RelevanceSummaryRecord.create(scoreRecord,
pubDate,
reportDate,
title,
journal.getISOAbbreviation(),
pmid.asURL(),
doi.asURL()));
}
appendSummaryRecords(summaryRecords);
contribFile.addContributor(bulkFile);
}
/**
* Deletes this relevance summary file and its corresponding
* contributor file.
*
* @return {@code true} iff both the summary and contributor
* files were successfully deleted.
*/
@Override public boolean delete() {
boolean status1 = super.delete();
boolean status2 = contribFile.delete();
return status1 && status2;
}
/**
* Determines whether a bulk file has already contributed to this
* summary file.
*
* @param bulkFile the bulk file in question.
*
* @return {@code true} iff the specified bulk file has already
* contributed to this summary file.
*/
public boolean isContributor(BulkFile bulkFile) {
return contribFile.isContributor(bulkFile);
}
}
|
gingerich/mesa | packages/mesa-transport/src/network/interface.js | import invariant from 'invariant';
import Connection from './connection';
import Connector from './connector';
export default class Interface extends Connector {
// static resolve(iface, ...args) {
// const connection = Connection.resolve(...args)
// connection.args = args
// return new this(iface, connection)
// }
constructor(parent, connection) {
super(connection);
this.parent = parent;
this.connectors = [];
this.middleware = [];
}
get ingress() {
if (!this._ingress) {
this._ingress = new Interface.Ingress(this);
this.add(this._ingress);
}
return this._ingress;
}
get egress() {
if (!this._egress) {
this._egress = new Interface.Egress(this);
this.add(this._egress);
}
return this._egress;
}
use(...middleware) {
this.middleware = this.middleware.concat(...middleware);
return this;
}
add(connector) {
if (typeof connector === 'function') {
connector = connector(this);
}
invariant(connector instanceof Connector, 'expected instance of Connector');
this.connectors.push(connector);
return connector;
}
resolve(connection) {
const iface = new Interface(this, connection);
iface.use(this.middleware);
// Order matters here
// egress should connect first to ensure service.use() called before ingress can service.call()
iface.egress.at(connection).use(this.egress.middleware);
iface.ingress.at(connection).use(this.ingress.middleware);
return iface;
}
at(protocol, ...args) {
const connection = Connection.resolve(protocol, ...args);
connection.args = args;
const iface = this.resolve(connection);
this.add(iface);
return iface;
}
connector(resolve, transit) {
return service => {
return Promise.all(this.connectors.map(c => c.connector(resolve, transit)(service)));
};
}
}
Interface.Ingress = require('./ingress');
Interface.Egress = require('./egress');
|
EzoeRyou/Sprout | sprout/index_tuple/index_tuple.hpp | /*=============================================================================
Copyright (c) 2011-2014 <NAME>
https://github.com/bolero-MURAKAMI/Sprout
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef SPROUT_INDEX_TUPLE_INDEX_TUPLE_HPP
#define SPROUT_INDEX_TUPLE_INDEX_TUPLE_HPP
#include <sprout/config.hpp>
#include <sprout/index_tuple/index_t.hpp>
#include <sprout/index_tuple/integer_sequence.hpp>
namespace sprout {
//
// index_tuple
// uindex_tuple
//
#if SPROUT_USE_TEMPLATE_ALIASES
template<sprout::index_t... Indexes>
using index_tuple = sprout::integer_sequence<sprout::index_t, Indexes...>;
template<sprout::uindex_t... Indexes>
using uindex_tuple = sprout::integer_sequence<sprout::uindex_t, Indexes...>;
#else // #if SPROUT_USE_TEMPLATE_ALIASES
template<sprout::index_t... Indexes>
struct index_tuple
: public sprout::integer_sequence<sprout::index_t, Indexes...>
{
public:
typedef index_tuple type;
template<sprout::index_t... J>
struct rebind
: public index_tuple<J...>
{};
public:
static SPROUT_CONSTEXPR type make() SPROUT_NOEXCEPT {
return type();
}
};
template<sprout::uindex_t... Indexes>
struct uindex_tuple
: public sprout::integer_sequence<sprout::uindex_t, Indexes...>
{
public:
typedef uindex_tuple type;
template<sprout::uindex_t... J>
struct rebind
: public uindex_tuple<J...>
{};
public:
static SPROUT_CONSTEXPR type make() SPROUT_NOEXCEPT {
return type();
}
};
#endif // #if SPROUT_USE_TEMPLATE_ALIASES
} // namespace sprout
#endif // #ifndef SPROUT_INDEX_TUPLE_INDEX_TUPLE_HPP
|
dbhowmik/scalableWM | Scalable_WM/src/Embedding/preProcessEmbed.java | <filename>Scalable_WM/src/Embedding/preProcessEmbed.java
/**
* @author: <NAME>
*
* Department of Electronic and Electrical Engineering
* University of Sheffield
* Copyright reserved
*
*/
package Embedding;
import Main.*;
import Wavelet.*;
import MCTF.*;
import Result.ImperceptibilityResult;
import Watermark.Watermark;
import java.io.*;
public class preProcessEmbed {
public static int roundControl;
public void preProcessEmbed(String filename, String[] subband, String[] tSubband){
//----------------------------------------------------------------------
ReadParameter param = new ReadParameter();
MotionEstimation ME = new MotionEstimation();
MotionCompensation MCTF = new MotionCompensation();
MCTFrecon mctfRecon = new MCTFrecon();
ImperceptibilityResult stat = new ImperceptibilityResult();
WaveletAnal decomp = new WaveletAnal();
WaveletSyn recon = new WaveletSyn();
EmbedVideo embedVid = new EmbedVideo();
Watermark water = new Watermark();
//----------------------------------------------------------------------
//-------------- Get watermark values ----------------------------------
water.Watermark();
//------------------- Get the decomposition levels ---------------------
int wv1Level = param.getDecomLevel3D()[0];
int tLevel = param.getDecomLevel3D()[1];
int wv2Level = param.getDecomLevel3D()[2];
//----------------------------------------------------------------------
String inVideoName = null, outTempVideoName = null, mvTempFileName = null, outVideoName = null;
String outVideoWv1 = null, outVideoWv2 = null, outEmbedVid = null, wmVidName = null, MCTFinVideoName = null;
//----------------------------------------------------------------------
//Round control is used to control rounding up operation in inverse wavelet transform.
roundControl = 1;
//----------------------------------------------------------------------
//1st wavelet decomposition in 2D+t+2D framework.
//----------------------------------------------------------------------
int[] wv1size = new int[2];
wv1size[0] = param.getVidWidth();
wv1size[1] = param.getVidHeight();
int[] orgSize = {wv1size[0],wv1size[1]};
//----------------------------------------------------------------------
int[] tSize = new int[2];
// if(wv2Level==0){
// tSize[0] = (int)(wv1size[0] / Math.pow(2, wv1Level-1));
// tSize[1] = (int)(wv1size[1] / Math.pow(2, wv1Level-1));
// } else {
tSize[0] = (int)(wv1size[0] / Math.pow(2, wv1Level));
tSize[1] = (int)(wv1size[1] / Math.pow(2, wv1Level));
//}
//----------------------------------------------------------------------
int[] wv2size = tSize;
//----------------------------------------------------------------------
System.out.println("1st 2D decomposition in progress. Total no of level: " + wv1Level);
//----------------------------------------------------------------------
inVideoName = param.getInName();
outVideoWv1 = param.getInName().substring(0, param.getInName().length()-4) + "_wv1.tmp";
decomp.WaveletAnal(inVideoName, outVideoWv1, wv1size, orgSize, wv1Level, 1); // 1 = wavelet number to identify
//----------------------------------------------------------------------
//Temporal analysis
//----------------------------------------------------------------------
for(int i=1; i<=tLevel; i++){
if(i==1){
inVideoName = outVideoWv1;
} else{
inVideoName = param.getInName().substring(0, param.getInName().length()-4) + "_0" + (i-1) + "t.tmp";
}
outTempVideoName = param.getInName().substring(0, param.getInName().length()-4) + "_0" + i + "t.tmp";
//------------------------------------------------------------------
//------------- Motion estimation and motion compensation ----------
//------------------------------------------------------------------
ME.MotionEstimation(inVideoName, i, tSize, orgSize);
MCTF.MotionCompensation(inVideoName, outTempVideoName, tSize, orgSize, i);
System.out.println("--------------------------------------");
System.out.println("Level " + i + " temporal filter analysis done. ");
System.out.println("--------------------------------------");
//---------- Deleting temporary files ------------------------------
if(i>1 && i<=tLevel){
DeleteFile(param.getInName().substring(0, param.getInName().length()-4) + "_0" + (i-1) + "t.tmp");
}
if(i>=tLevel){
DeleteFile(outVideoWv1);
}
//------------------------------------------------------------------
}
//----------------------------------------------------------------------
//2nd wavelet decomposition in 2D+t+2D framework.
//----------------------------------------------------------------------
System.out.println("2nd 2D decomposition in progress. Total no of level: " + wv2Level);
//----------------------------------------------------------------------
if(tLevel==0){
inVideoName = outVideoWv1;
} else {
inVideoName = param.getInName().substring(0, param.getInName().length()-4) + "_0" + tLevel + "t.tmp";
}
//----------------------------------------------------------------------
outVideoWv2 = param.getInName().substring(0, param.getInName().length()-4) + "_wv2.tmp";
//-------------- Wavelet decomposition ---------------------------------
decomp.WaveletAnal(inVideoName, outVideoWv2, wv2size, orgSize, wv2Level, 2); // 2 = wavelet number to identify
DeleteFile(inVideoName);
//----------------------------------------------------------------------
//----------- Watermark Embedding and video reconstruction -------------
//----------------------------------------------------------------------
for(int tempSubChoice = 0; tempSubChoice<tSubband.length; tempSubChoice++){
for(int subChoice = 0; subChoice< subband.length; subChoice++ ){
outEmbedVid = param.getInName().substring(0, param.getInName().length()-4) + "_" + tSubband[tempSubChoice] + "_" + subband[subChoice] + ".tmp";
roundControl = 1;
//------------------ Watermark embedding -----------------------
System.out.println("Watermark embedding tChoice = " + tSubband[tempSubChoice] + " and subChoice = " + subband[subChoice]);
embedVid.EmbedVideo(outVideoWv2, outEmbedVid, orgSize, (wv1Level+wv2Level), tSubband[tempSubChoice], subband[subChoice]);
//--------------------------------------------------------------
//-- 2nd 2D synthesis
//--------------------------------------------------------------
System.out.println("2nd 2D synthesis in progress... Total no of level: " + wv2Level);
outVideoName = inVideoName;
recon.WaveletSyn(outEmbedVid, outVideoName, wv2size, orgSize, wv2Level, 2); // 2 = wavelet number to identify
DeleteFile(outEmbedVid);
//--------------------------------------------------------------
/*
//----------------- Temp test ----------------------------------
System.out.println("2nd 2D synthesis in progress... Total no of level: " + wv2Level);
outVideoName = inVideoName;
recon.WaveletSyn(outVideoWv2, outVideoName, wv2size, orgSize, wv2Level, 2); // 2 = wavelet number to identify
//--------------------------------------------------------------
*/
//Temporal Sysnthesis
for(int i=tLevel; i>0; i--){
if(i==1){
outTempVideoName = outVideoWv1;
mvTempFileName = outVideoWv1.substring(0, outVideoWv1.length()-4) + ".mv";
} else{
outTempVideoName = param.getInName().substring(0, param.getInName().length()-4) + "_0" + (i-1) + "t.tmp";
mvTempFileName = param.getInName().substring(0, param.getInName().length()-4) + "_0" + (i-1) + "t.mv";
}
MCTFinVideoName = param.getInName().substring(0, param.getInName().length()-4) + "_0" + i + "t.tmp";
mctfRecon.MCTFrecon(MCTFinVideoName, outTempVideoName, mvTempFileName, tSize, orgSize, i);
System.out.println("--------------------------------------");
System.out.println("Level " + i + " temporal filter synthesis done. ");
System.out.println("--------------------------------------");
if(i>=1 && i<=tLevel){
DeleteFile(param.getInName().substring(0, param.getInName().length()-4) + "_0" + i + "t.tmp");
}
}
//----------------------------------------------------------------
//-- 1st 2D synthesis
//----------------------------------------------------------------
System.out.println("1st 2D synthesis in progress... Total no of level: " + wv1Level);
roundControl = 0; // Round control release for final result
// wmVidName = param.getInName().substring(0, param.getInName().length()-4) + "_" + tSubband[tempSubChoice] + "_" + subband[subChoice] + "_" + param.getEmbedProcedure() + ".yuv";
recon.WaveletSyn(outVideoWv1, wmVidName, wv1size, orgSize, wv1Level, 1);
DeleteFile(outVideoWv1);
//----------------------------------------------------------------
//Calculate statistics
stat.ImperceptibilityResult(wmVidName, wmVidName); //Pos1=Stat File name, Pos2=Wm video name;
}
}
DeleteFile(outVideoWv2);
}
public int getRoundCon(){
return roundControl;
}
public void DeleteFile(String fileName){
try{
File inputFile = new File(fileName);
if(!inputFile.exists()){
System.err.println("File: " + fileName + " does not exist.");
System.exit(-1);
}
if (inputFile.delete()){
System.err.println("** Deleted " + fileName + " **");
} else{
System.err.println("Failed to delete " + fileName);
}
} catch (SecurityException e) {
System.err.println("Unable to delete " + fileName + "(" + e.getMessage() + ")");
System.exit(-1);
}
}
}
|
Eric-Ma-C/PAT-Advanced | Basic/BB1026/BB1026/main.cpp | #include<stdio.h>
int main(){
int size;char c;
scanf("%d %c",&size,&c);
int col=(int)(size/2.0+0.5);
for(int i=0;i<col;i++){
for(int j=0;j<size;j++){
if(j==size-1)
printf("%c\n",c);
else if(i==0||i==col-1||j==0)
printf("%c",c);
else
printf(" ");
}
}
getchar();
getchar();
return 0;
} |
smilebingbing/java | offer/src/com/java/offer/ReverseK.java | <reponame>smilebingbing/java<filename>offer/src/com/java/offer/ReverseK.java
package com.java.offer;
import java.util.Stack;
public class ReverseK {
public Node reverseKNode(Node head , int k){
if(k < 2){
return head;
}
Stack<Node> stack = new Stack<Node>();
Node newHead = head;
Node cur = head;
Node pre = null;
Node after = null;
while(cur != null){
after = cur.next;
stack.push(cur);
cur = cur.next;
if(stack.size() == k){
stack.pop();
}
}
}
}
|
Claayton/mitmirror-api | mitmirror/presenters/errors/error_controller.py | <reponame>Claayton/mitmirror-api
"""Lógica para tratamento de erros"""
from typing import Type, Dict
from mitmirror.presenters.helpers import HttpResponse
from mitmirror.errors import (
HttpRequestError,
HttpBadRequestError,
HttpUnauthorized,
HttpNotFound,
HttpUnprocessableEntity,
HttpForbidden,
)
def handler_errors(error: Type[Exception]) -> Dict:
"""
Handler para tratamentos de execoes.
:param error: Tipo de error gerado.
:return: Um dicionario com o status_code e uma mensagem para esse tipo de erro.
"""
if isinstance(
error,
(
HttpRequestError,
HttpBadRequestError,
HttpUnprocessableEntity,
HttpUnauthorized,
HttpNotFound,
HttpForbidden,
),
):
http_response = HttpResponse(
status_code=error.status_code, body={"error": str(error)}
)
else:
http_response = HttpResponse(status_code=500, body={"error": str(error)})
return http_response
|
Ulysses31/react-tasks-mern | client/src/components/departments/department-list.js | <filename>client/src/components/departments/department-list.js<gh_stars>0
import React, { useEffect, useMemo, useState } from 'react';
import PropTypes from 'prop-types';
import DatePicker from 'react-datepicker';
import { useDispatch, useSelector } from 'react-redux';
import { Link, useHistory } from 'react-router-dom';
import Pagination from '../../shared/pagination/Pagination';
import {
fixDate,
getValidatedUserInfo,
getPageSize
} from '../../shared/shared';
import {
fetchDepartments,
deleteDepartment,
setSelectedDepartment
} from '../../state/actions/department-action';
import { setUserBySession } from '../../state/actions/general-action';
import ErrorCmp from '../error/error';
import './department.css';
export default function DepartmentList() {
const pageSize = getPageSize();
const history = useHistory();
const dispatch = useDispatch();
const error = useSelector(
(state) =>
state.userState.error || state.departmentState.error
);
const departments = useSelector(
(state) => state.departmentState.departments
);
const role = useSelector(
(state) => state.generalState.login?.role
);
const [currentPage, setCurrentPage] = useState(1);
useEffect(() => {
// user validation
const userInfo = getValidatedUserInfo();
if (userInfo.id === 0) {
history.push('/login');
} else {
dispatch(setUserBySession(userInfo));
dispatch(fetchDepartments());
}
}, []);
const handleEditBtn = (dprt) => {
dispatch(setSelectedDepartment(dprt));
history.push('/departments/add');
};
const handleDeleteBtn = (id) => {
if (confirm('Are you sure you want to delete it?')) {
dispatch(deleteDepartment(id));
}
};
const DepartmentTemplate = ({ dprt, cnt }) => {
return (
<>
<tr>
<td nowrap='true'>
<b>
{currentPage === 1
? cnt + 1
: pageSize * (currentPage - 1) + cnt + 1}
</b>
</td>
<td nowrap='true'>{dprt.id}</td>
<td nowrap='true'>
<i className='bi bi-person-check-fill'></i>{' '}
<b>{dprt.name}</b>
</td>
<td nowrap='true'>
<i className='bi bi-laptop'></i>
<b>{dprt.description}</b>
</td>
<td nowrap='true'>
<i className='bi bi-calendar3'></i>
{fixDate(dprt.createdAt)}
</td>
<td nowrap='true' align='center'>
<button
className='btn btn-sm btn-primary shadow-sm'
onClick={() => handleEditBtn(dprt)}
disabled={role !== 'Administrator'}
>
<i className='bi bi-pencil'></i>
</button>{' '}
<button
className='btn btn-sm btn-danger shadow-sm'
onClick={() => handleDeleteBtn(dprt._id)}
disabled={role !== 'Administrator'}
>
<i className='bi bi-trash'></i>
</button>
</td>
</tr>
</>
);
};
// -- pagination table data -----------------------------
const projectsTableData = useMemo(() => {
const firstPageIndex = (currentPage - 1) * pageSize;
const lastPageIndex = firstPageIndex + pageSize;
return departments.slice(firstPageIndex, lastPageIndex);
}, [currentPage, departments]);
// -- pagination table data -----------------------------
return (
<>
{error && <ErrorCmp err={error} />}
<div className='card shadow-lg'>
<h5 className='card-header'>
<i className='bi bi-person-check-fill'></i>{' '}
Departments
</h5>
<div className='card-body overflow-auto'>
<Link
to='/departments/add'
className={`btn btn-sm btn-primary shadow-sm ${
role !== 'Administrator' && 'disabled'
}`}
style={{ marginBottom: '10px' }}
>
<i className='bi bi-plus-lg'></i> New Department
</Link>
{projectsTableData.length > 0 && (
<div className='table-responsive'>
<table
border='0'
className='table table-sm table-hover'
>
<thead>
<tr>
<th nowrap='true' scope='col'>
#
</th>
<th nowrap='true' scope='col'>
Id
</th>
<th nowrap='true' scope='col'>
Name
</th>
<th nowrap='true' scope='col'>
Description
</th>
<th nowrap='true' scope='col'>
Created
</th>
<th nowrap='true' scope='col'></th>
</tr>
<tr>
<th></th>
<th></th>
<th>
<div className='input-group input-group-sm flex-nowrap'>
<div className='input-group-prepend'>
<span
className='input-group-text'
id='basic-addon1'
>
<i className='bi bi-search'></i>
</span>
</div>
<input
type='text'
className='fomr-control form-control-sm'
style={{
border: '1px solid #cdcdcd',
width: '100%'
}}
disabled
/>
</div>
</th>
<th>
<div className='input-group input-group-sm flex-nowrap'>
<div className='input-group-prepend'>
<span
className='input-group-text'
id='basic-addon1'
>
<i className='bi bi-search'></i>
</span>
</div>
<input
type='text'
className='fomr-control form-control-sm'
style={{
border: '1px solid #cdcdcd',
width: '100%'
}}
disabled
/>
</div>
</th>
<th>
<div className='input-group input-group-sm flex-nowrap'>
<div className='input-group-prepend'>
<span
className='input-group-text'
id='basic-addon1'
>
<i className='bi bi-calendar3'></i>
</span>
</div>
<DatePicker
id='startDate'
name='startDate'
className='form-control form-control-sm'
key='startDate'
dateFormat='dd/MM/yyyy'
selected={''}
value={''}
onChange={() => {}}
style={{
border: '1px solid #cdcdcd',
width: '100%'
}}
disabled
/>
</div>
</th>
<th></th>
</tr>
</thead>
<tbody>
{projectsTableData.map((dprt, i) => (
<DepartmentTemplate
key={dprt._id}
dprt={dprt}
cnt={i}
/>
))}
</tbody>
</table>
<Pagination
className='pagination-bar'
currentPage={currentPage}
totalCount={departments.length}
pageSize={pageSize}
onPageChange={(page) =>
setCurrentPage(page)
}
/>
</div>
)}
</div>
</div>
</>
);
}
DepartmentList.propTypes = {
dprt: PropTypes.object,
cnt: PropTypes.number
};
|
NaikRaghavendra/pi-epaper-dashboard | Source/Apps/MainWeather.py | <reponame>NaikRaghavendra/pi-epaper-dashboard<filename>Source/Apps/MainWeather.py
import logging
import Geometry.Point as PT
import Utilities.Recurrer as AR
import Widgets.CurrentWeather as CW
import Widgets.SunPosition as SP
import Widgets.WindCompass as WC
import Weather.WeatherQuery as WQ
from PIL import ImageDraw
import Apps.BaseApp as BA
fontfamily = 'DejaVuSansMono.ttf'
boldfontfamily = 'DejaVuSansMono-Bold.ttf'
class MainWeatherApp(BA.BaseApp):
def __init__(self, apphost, rect, wm:WQ.WeatherModel):
super(MainWeatherApp,self).__init__(apphost,rect)
self._ar = AR.Recurrer(300,self.requestUpdate)
self._wm = wm
windcompside = self._rect.getMinDimension()
(windcomprect, rightrect) = self._rect.partition_x(windcompside/self._rect.width())
self._wc = WC.WindCompass(windcomprect,WC.WindModel(self._wm))
rightrect = rightrect.shrink(PT.Point(0,1), PT.Point(0,0))
(currentweatherrect, sunpositionrect) = rightrect.partition_y(0.37)
cw_coords = currentweatherrect.coords()
self._cw = CW.CurrentWeather(cw_coords[0],cw_coords[1],cw_coords[2],cw_coords[3],CW.CurrentWeatherModel(self._wm))
sp_coords = sunpositionrect.coords()
self._sp = SP.SunPosition(sp_coords[0],sp_coords[1],sp_coords[2],sp_coords[3],SP.SunPositionModel(self._wm))
def requestUpdate(self):
self.apphost.queue(self)
def update(self, image):
logging.debug("Updating weather ..")
dictDraw = ImageDraw.Draw(image)
# fill background
dictDraw.rectangle(self._rect.coords(), fill = 255)
self._wc.display(image, image)
self._sp.display(image, image)
self._cw.display(image, image)
|
zppvae/spring-framework-5.1.x | demo/src/main/java/org/zpp/aop/dao/OrderDaoAImpl.java | <reponame>zppvae/spring-framework-5.1.x<filename>demo/src/main/java/org/zpp/aop/dao/OrderDaoAImpl.java
package org.zpp.aop.dao;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
@Component("orderDao")
public class OrderDaoAImpl implements OrderDao,InitializingBean {
@Override
public void print(String sql) {
System.out.println(sql);
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("执行初始化方法");
}
}
|
deaguirp/portmapper | src/main/java/com/offbynull/portmapper/mappers/pcp/externalmessages/FilterPcpOption.java | /*
* Copyright 2013-2016, <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.
*/
package com.offbynull.portmapper.mappers.pcp.externalmessages;
import com.offbynull.portmapper.helpers.NetworkUtils;
import java.net.InetAddress;
import java.util.Objects;
import org.apache.commons.lang3.Validate;
/**
* Represents a FILTER PCP option. From the RFC:
* <pre>
* The FILTER option is formatted as follows:
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Option Code=3 | Reserved | Option Length=20 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Reserved | Prefix Length | Remote Peer Port |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | |
* | Remote Peer IP remotePeerIpAddress (128 bits) |
* | |
* | |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* Figure 15: FILTER Option Layout
*
* These fields are described below:
*
* Reserved: 8 reserved bits, MUST be sent as 0 and MUST be ignored
* when received.
*
* Prefix Length: indicates how many bits of the IPv4 or IPv6 remotePeerIpAddress
* are relevant for this filter. The value 0 indicates "no filter",
* and will remove all previous filters. See below for detail.
*
* Remote Peer Port: the port number of the remote peer. The value 0
* indicates "all ports".
*
* Remote Peer IP remotePeerIpAddress: The IP remotePeerIpAddress of the remote peer.
*
* Option Name: FILTER
* Number: 3
* Purpose: specifies a filter for incoming packets
* Valid for Opcodes: MAP
* Length: 20 octets
* May appear in: request. May appear in response only if it
* appeared in the associated request.
* Maximum occurrences: as many as fit within maximum PCP message
* size
* </pre>
* @author <NAME>
*/
public final class FilterPcpOption extends PcpOption {
private static final int OP_CODE = 3;
private static final int DATA_LENGTH = 20;
private int prefixLength;
private int remotePeerPort;
private InetAddress remotePeerIpAddress;
/**
* Constructs a {@link FilterPcpOption} by parsing a buffer.
* @param buffer buffer containing PCP option data
* @param offset offset in {@code buffer} where the PCP option starts
* @throws NullPointerException if any argument is {@code null}
* @throws IllegalArgumentException if any numeric argument is negative, or if {@code buffer} is malformed (doesn't contain enough bytes
* / length is not a multiple of 4 (not enough padding) / length exceeds 65535 / data does not contain enough bytes / code is not 3 /
* prefix length is more than 128)
*/
public FilterPcpOption(byte[] buffer, int offset) {
super(buffer, offset);
Validate.isTrue(super.getCode() == OP_CODE);
Validate.isTrue(super.getDataLength() == DATA_LENGTH);
offset += HEADER_LENGTH;
offset++; // reserved
prefixLength = buffer[offset];
offset++;
Validate.inclusiveBetween(0, 128, prefixLength); // 0 indicates 'no filter'
remotePeerPort = InternalUtils.bytesToShort(buffer, offset) & 0xFFFF;
offset += 2;
Validate.inclusiveBetween(0, 65535, remotePeerPort); // 0 indicates 'all ports', should never trigger
remotePeerIpAddress = NetworkUtils.convertBytesToAddress(buffer, offset, 16);
offset += 16;
}
/**
* Constructs a {@link FilterPcpOption}.
* @param prefixLength prefix length ({@code 0} = no filter}
* @param remotePeerPort remote peer port ({@code 0} = all ports)
* @param remotePeerIpAddress remote peer IP remotePeerIpAddress
* @throws NullPointerException if any argument is {@code null}
* @throws IllegalArgumentException if {@code prefixLength < 0 || > 128}, or if {@code remotePeerPort < 0 || > 65535}
*/
public FilterPcpOption(int prefixLength, int remotePeerPort, InetAddress remotePeerIpAddress) {
super(OP_CODE, DATA_LENGTH);
Validate.inclusiveBetween(0, 128, prefixLength); // 0 indicates 'no filter'
Validate.inclusiveBetween(0, 65535, remotePeerPort); // 0 indicates 'all ports'
Validate.notNull(remotePeerIpAddress);
this.prefixLength = prefixLength;
this.remotePeerPort = remotePeerPort;
this.remotePeerIpAddress = remotePeerIpAddress;
}
/**
* Get the prefix length.
* @return prefix length
*/
public int getPrefixLength() {
return prefixLength;
}
/**
* Get the remote peer port.
* @return remote peer port
*/
public int getRemotePeerPort() {
return remotePeerPort;
}
/**
* Get the remote IP address.
* @return remote IP address
*/
public InetAddress getRemotePeerIpAddress() {
return remotePeerIpAddress;
}
@Override
public byte[] getData() {
byte[] data = new byte[DATA_LENGTH];
// write reserved
data[0] = 0; // not required but leave it in anwyays
// write prefix len
data[1] = (byte) prefixLength;
// write port
InternalUtils.shortToBytes(data, 2, (short) remotePeerPort);
// write ip
byte[] ipv6AsBytes = NetworkUtils.convertAddressToIpv6Bytes(remotePeerIpAddress);
Validate.validState(ipv6AsBytes.length == 16); // sanity check, should never throw exception
System.arraycopy(ipv6AsBytes, 0, data, 4, ipv6AsBytes.length);
return data;
}
@Override
public String toString() {
return "FilterPcpOption{super=" + super.toString() + "prefixLength=" + prefixLength + ", remotePeerPort=" + remotePeerPort
+ ", remotePeerIpAddress=" + remotePeerIpAddress + '}';
}
@Override
public int hashCode() {
int hash = super.hashCode();
hash = 97 * hash + this.prefixLength;
hash = 97 * hash + this.remotePeerPort;
hash = 97 * hash + Objects.hashCode(this.remotePeerIpAddress);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final FilterPcpOption other = (FilterPcpOption) obj;
if (this.prefixLength != other.prefixLength) {
return false;
}
if (this.remotePeerPort != other.remotePeerPort) {
return false;
}
if (!Objects.equals(this.remotePeerIpAddress, other.remotePeerIpAddress)) {
return false;
}
return true;
}
}
|
ShenShu2016/uwcssa_ca | frontend/src/components/Forum/ForumPost/ForumPostDetail/ForumPostComments.js | <reponame>ShenShu2016/uwcssa_ca
import {
// Box,
// Typography,
// LinearProgress,
// Skeleton,
} from "@mui/material";
import { makeStyles } from "@mui/styles";
import React from "react";
import ForumPostCommentMain from "../ForumPostComment/ForumPostCommentMain";
// import ForumPostCommentComponent from "./ForumPostCommentComponent";
const useStyles = makeStyles({
root: {
width: "100%",
margin: "auto",
},
subTitle: {
paddingBlock: "3rem 1rem",
},
cardContent: {},
main: {},
});
export default function ForumPostComments ({ forumPost }) {
const classes = useStyles();
// console.log(forumPost.forumPostComments);
// const sortForumPostCommentsData = forumPostCommentsData.sort((a, b) => (a.createdAt > b.createdAt) ? 1:-1).reverse();
return (
<div className={classes.root}>
{/* <Typography className={classes.subTitle}>评论:</Typography> */}
{forumPost.active !== true ? (
""
) : (
<div>
{forumPost.forumPostComments.items.map((comment, idx) => {
return (
<ForumPostCommentMain
comment={comment}
key={idx}
idx={idx}
/>
);
})}
</div>
)}
</div>
);
};
|
yrll/batfish-repair | smt_policy/SMTMatchAnd.java | package smt_policy;
public class SMTMatchAnd implements SMTAbstractMatch{
}
|
estrattonbailey/lol-state | packages/loll-href/index.js | export default function href (cb) {
window.addEventListener('click', e => {
if (e.ctrlKey || e.metaKey || e.altKey || e.shiftKey || e.defaultPrevented) return
let a = e.target
while (a && !(a.href && a.nodeName === 'A')) {
a = a.parentNode
}
if (
!a ||
window.location.origin !== a.origin ||
a.hasAttribute('download') ||
a.target === '_blank' ||
/mailto|tel/.test(a.href)
) return
e.preventDefault()
cb(a)
})
}
|
GoodforGod/dummymaker | src/main/java/io/dummymaker/scan/IGenScanner.java | <reponame>GoodforGod/dummymaker
package io.dummymaker.scan;
import io.dummymaker.model.GenContainer;
import java.lang.reflect.Field;
import java.util.Map;
import org.jetbrains.annotations.NotNull;
/**
* Scanners used by populate factory primarily
*
* @author GoodforGod
* @see io.dummymaker.factory.impl.GenFactory
* @see GenContainer
* @since 10.03.2018
*/
public interface IGenScanner extends IMapScanner<Field, GenContainer, Class> {
/**
* Scan for annotated target fields
*
* @param target to scan
* @return map of fields and its gen containers
*/
@NotNull
Map<Field, GenContainer> scan(Class target);
}
|
nbey/slate-cbl | sencha-workspace/tests/SlateTasksTeacher/020_dom-render.t.js | StartTest(function(t) {
t.requireOk('SlateTasksTeacher.Application', function() {
var studentsgrid,
gridlegend,
data,
students,
rows;
t.it('Should render slate-studentsgrid along with it\'s contents', function(t) {
t.chain(
{ waitForCQ: 'slate-studentsgrid'},
function(next, el) {
studentsgrid = el[0],
data = studentsgrid.getData(),
students = data.students,
rows = data.rows;
next();
},
function(next) {
t.ok(studentsgrid, 'slate-studentsgrid is rendered');
t.ok(studentsgrid.getData(), 'studentsgrid data is here');
t.is(Ext.isObject(data), true, 'studentsgrid.getData() returns an object');
t.is(Ext.isArray(students), true, 'data.students is an array');
t.is(Ext.isArray(rows), true, 'data.rows is an array');
t.selectorCountIs('.slate-studentsgrid-colheader', studentsgrid, 22, "There are 21 columns");
t.selectorCountIs('.slate-studentsgrid-rowheader', studentsgrid, 5, "There are 5 rows");
}
)
});
t.it('Should render slate-gridlegend along with it\'s contents', function(t) {
t.chain(
{ waitForCQ: 'slate-gridlegend'},
function(next, el) {
gridlegend = el[0];
next();
},
function() {
t.ok(gridlegend, 'slate-gridlegend is rendered');
}
)
});
});
}); |
DBCDK/fcrepo-3.5-patched | fcrepo-common/src/main/java/org/fcrepo/common/policy/DatastreamNamespace.java | /* The contents of this file are subject to the license and copyright terms
* detailed in the license directory at the root of the source tree (also
* available online at http://fedora-commons.org/license/).
*/
package org.fcrepo.common.policy;
import com.sun.xacml.attr.AnyURIAttribute;
import com.sun.xacml.attr.BooleanAttribute;
import com.sun.xacml.attr.DateTimeAttribute;
import com.sun.xacml.attr.IntegerAttribute;
import com.sun.xacml.attr.StringAttribute;
/**
* The Fedora Datastream XACML namespace.
*
* <pre>
* Namespace URI : urn:fedora:names:fedora:2.1:resource:datastream
* </pre>
*/
public class DatastreamNamespace
extends XacmlNamespace {
// Properties
public final XacmlName ID;
public final XacmlName STATE;
public final XacmlName LOCATION_TYPE;
public final XacmlName CONTROL_GROUP;
public final XacmlName FORMAT_URI;
public final XacmlName LOCATION;
public final XacmlName CREATED_DATETIME;
public final XacmlName INFO_TYPE;
public final XacmlName MIME_TYPE;
public final XacmlName CONTENT_LENGTH;
public final XacmlName AS_OF_DATETIME;
public final XacmlName NEW_STATE;
public final XacmlName NEW_LOCATION;
public final XacmlName FILE_URI;
public final XacmlName NEW_CONTROL_GROUP;
public final XacmlName NEW_FORMAT_URI;
public final XacmlName NEW_MIME_TYPE;
public final XacmlName NEW_VERSIONABLE;
public final XacmlName CHECKSUM;
public final XacmlName NEW_CHECKSUM;
public final XacmlName CHECKSUM_TYPE;
public final XacmlName NEW_CHECKSUM_TYPE;
public final XacmlName ALT_IDS;
public final XacmlName NEW_ALT_IDS;
// Values
private DatastreamNamespace(XacmlNamespace parent, String localName) {
super(parent, localName);
AS_OF_DATETIME =
addName(new XacmlName(this,
"asOfDateTime",
DateTimeAttribute.identifier));
CONTENT_LENGTH =
addName(new XacmlName(this,
"contentLength",
IntegerAttribute.identifier));
CONTROL_GROUP =
addName(new XacmlName(this,
"controlGroup",
StringAttribute.identifier));
NEW_CONTROL_GROUP =
addName(new XacmlName(this,
"newControlGroup",
StringAttribute.identifier));
CREATED_DATETIME =
addName(new XacmlName(this,
"createdDate",
DateTimeAttribute.identifier));
FORMAT_URI =
addName(new XacmlName(this,
"formatUri",
AnyURIAttribute.identifier));
NEW_FORMAT_URI =
addName(new XacmlName(this,
"newFormatUri",
AnyURIAttribute.identifier));
ID = addName(new XacmlName(this, "id", StringAttribute.identifier));
INFO_TYPE =
addName(new XacmlName(this,
"infoType",
StringAttribute.identifier));
LOCATION =
addName(new XacmlName(this,
"location",
AnyURIAttribute.identifier));
NEW_LOCATION =
addName(new XacmlName(this,
"newLocation",
AnyURIAttribute.identifier));
FILE_URI =
addName(new XacmlName(this,
"fileUri",
AnyURIAttribute.identifier));
LOCATION_TYPE =
addName(new XacmlName(this,
"locationType",
StringAttribute.identifier));
MIME_TYPE =
addName(new XacmlName(this,
"mimeType",
StringAttribute.identifier));
NEW_MIME_TYPE =
addName(new XacmlName(this,
"newMimeType",
StringAttribute.identifier));
STATE =
addName(new XacmlName(this, "state", StringAttribute.identifier));
NEW_STATE =
addName(new XacmlName(this,
"newState",
StringAttribute.identifier));
NEW_VERSIONABLE =
addName(new XacmlName(this,
"newVersionable",
BooleanAttribute.identifier));
CHECKSUM =
addName(new XacmlName(this,
"checksum",
StringAttribute.identifier));
NEW_CHECKSUM =
addName(new XacmlName(this,
"newChecksum",
StringAttribute.identifier));
CHECKSUM_TYPE =
addName(new XacmlName(this,
"checksumType",
StringAttribute.identifier));
NEW_CHECKSUM_TYPE =
addName(new XacmlName(this,
"newChecksumType",
StringAttribute.identifier));
ALT_IDS =
addName(new XacmlName(this,
"altIds",
StringAttribute.identifier));
NEW_ALT_IDS =
addName(new XacmlName(this,
"newAltIds",
StringAttribute.identifier));
}
public static DatastreamNamespace onlyInstance =
new DatastreamNamespace(ResourceNamespace.getInstance(),
"datastream");
public static final DatastreamNamespace getInstance() {
return onlyInstance;
}
}
|
sandrain/UnifyCR | common/src/slotmap.h | <gh_stars>0
/*
* Copyright (c) 2020, Lawrence Livermore National Security, LLC.
* Produced at the Lawrence Livermore National Laboratory.
*
* Copyright 2020, UT-Battelle, LLC.
*
* LLNL-CODE-741539
* All rights reserved.
*
* This is the license for UnifyFS.
* For details, see https://github.com/LLNL/UnifyFS.
* Please read https://github.com/LLNL/UnifyFS/LICENSE for full license text.
*/
#ifndef SLOTMAP_H
#define SLOTMAP_H
#include <sys/types.h> // size_t, ssize_t
#ifdef __cplusplus
extern "C" {
#endif
/* slot map, a simple structure that manages a bitmap of used/free slots */
typedef struct slot_map {
size_t total_slots;
size_t used_slots;
} slot_map;
/* The slot usage bitmap immediately follows the structure in memory.
* The usage bitmap can be thought of as an uint8_t array, where
* each uint8_t represents 8 slots.
* uint8_t use_bitmap[total_slots/8]
*/
/**
* Initialize a slot map within the given memory region, and return a pointer
* to the slot_map structure. Returns NULL if the provided memory region is not
* large enough to track the requested number of slots.
*
* @param num_slots number of slots to track
* @param region_addr address of the memory region
* @param region_sz size of the memory region
*
* @return valid slot_map pointer, or NULL on error
*/
slot_map* slotmap_init(size_t num_slots,
void* region_addr,
size_t region_sz);
/**
* Clear the given slot_map. Marks all slots free.
*
* @param smap valid slot_map pointer
*
* @return UNIFYFS_SUCCESS, or error code
*/
int slotmap_clear(slot_map* smap);
/**
* Reserve consecutive slots in the slot_map.
*
* @param smap valid slot_map pointer
* @param num_slots number of slots to reserve
*
* @return starting slot index of reservation, or -1 on error
*/
ssize_t slotmap_reserve(slot_map* smap,
size_t num_slots);
/**
* Release consecutive slots in the slot_map.
*
* @param smap valid slot_map pointer
* @param start_index starting slot index
* @param num_slots number of slots to release
*
* @return UNIFYFS_SUCCESS, or error code
*/
int slotmap_release(slot_map* smap,
size_t start_index,
size_t num_slots);
/**
* Print the slot_map (for debugging).
*
* @param smap valid slot_map pointer
*/
void slotmap_print(slot_map* smap);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // UNIFYFS_BITMAP_H
|
santhosh-tekuri/raft | config_test.go | // Copyright 2019 <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.
package raft
import (
"testing"
"time"
)
func TestRaft_bootstrap(t *testing.T) {
c := newCluster(t)
electionAborted := c.registerFor(eventElectionAborted)
defer c.unregister(electionAborted)
// launch cluster without bootstrapping
c.launch(3, false)
defer c.shutdown()
// all nodes should must abort election and only once
testln("waitForElectionAborted")
timeout := time.After(c.longTimeout)
aborted := make(map[uint64]bool)
for i := 0; i < 3; i++ {
select {
case e := <-electionAborted.ch:
if aborted[e.src] {
t.Fatalf("aborted twice")
}
aborted[e.src] = true
case <-timeout:
t.Fatal("timout in waiting for abort election")
}
}
// bootstrap one of the nodes
testln("prepareBootStrapConfig")
ldr := c.rr[1]
config := c.info(ldr).Configs.Latest
for _, r := range c.rr {
if err := config.AddVoter(r.NID(), c.id2Addr(r.NID())); err != nil {
c.Fatal(err)
}
}
if err := waitBootstrap(ldr, config, c.longTimeout); err != nil {
t.Fatal(err)
}
// the bootstrapped node should be the leader
c.waitForLeader(ldr)
c.waitForFollowers()
// should be able to update
if _, err := waitUpdate(ldr, "hello", 0); err != nil {
t.Fatal(err)
}
c.waitFSMLen(1)
c.ensureFSMSame([]string{"hello"})
// ensure bootstrap fails if already bootstrapped
if err := waitBootstrap(ldr, config, c.longTimeout); err != ErrStaleConfig {
t.Fatalf("got %v, want %v", err, ErrStaleConfig)
}
err := waitBootstrap(c.rr[2], config, c.longTimeout)
if _, ok := err.(NotLeaderError); !ok {
t.Fatalf("got %v, want NotLeaderError", err)
}
// disconnect leader, and ensure that new leader is chosen
c.disconnect(ldr)
c.waitForLeader(c.exclude(ldr)...)
}
func TestRaft_bootstrap_validations(t *testing.T) {
c := newCluster(t)
// launch cluster without bootstrapping
c.launch(3, false)
defer c.shutdown()
ldr := c.rr[1]
validConfig := c.info(ldr).Configs.Latest
for _, r := range c.rr {
if err := validConfig.AddVoter(r.NID(), c.id2Addr(r.NID())); err != nil {
c.Fatal(err)
}
}
// bootstrap with empty address
config := validConfig.clone()
self := config.Nodes[ldr.nid]
self.Addr = ""
config.Nodes[ldr.nid] = self
if err := waitBootstrap(ldr, config, c.longTimeout); err == nil {
t.Fatal("error expected")
}
// bootstrap without self
config = validConfig.clone()
delete(config.Nodes, ldr.nid)
if err := waitBootstrap(ldr, config, c.longTimeout); err == nil {
t.Fatal("error expected")
}
// bootstrap self as nonVoter
config = validConfig.clone()
self = config.Nodes[ldr.nid]
self.Voter = false
config.Nodes[ldr.nid] = self
if err := waitBootstrap(ldr, config, c.longTimeout); err == nil {
t.Fatal("error expected")
}
// bootstrap with unstable config
config = validConfig.clone()
self = config.Nodes[ldr.nid]
self.Action = Demote
config.Nodes[ldr.nid] = self
if err := waitBootstrap(ldr, config, c.longTimeout); err == nil {
t.Fatal("error expected")
}
}
|
norech/myrpg | lib/iron_goat/erty/ecstring/cmp/estartswith.c | <filename>lib/iron_goat/erty/ecstring/cmp/estartswith.c
/*
** EPITECH PROJECT, 2020
** LibErty
** File description:
** estartswith
*/
#include <erty/string/ecstring.h>
bool estartswith(const_cstr_t haystack, const_cstr_t needle)
{
return ((estrncmp(haystack, needle, estrlen(needle) == 0)));
} |
inalbisdev/base | src/helpers/getPartial.js | module.exports = function(name) {
return name;
}; |
hpgit/HumanFoot | PyCommon/externalLibs/BaseLib/math/nr/cpp/recipes/dfpmin.cpp | <gh_stars>0
#include <cmath>
#include <limits>
#include "nr.h"
using namespace std;
void NR::dfpmin(Vec_IO_DP &p, const DP gtol, int &iter, DP &fret,
DP func(Vec_I_DP &), void dfunc(Vec_I_DP &, Vec_O_DP &))
{
const int ITMAX=200;
const DP EPS=numeric_limits<DP>::epsilon();
const DP TOLX=4*EPS,STPMX=100.0;
bool check;
int i,its,j;
DP den,fac,fad,fae,fp,stpmax,sum=0.0,sumdg,sumxi,temp,test;
int n=p.size();
Vec_DP dg(n),g(n),hdg(n),pnew(n),xi(n);
Mat_DP hessin(n,n);
fp=func(p);
dfunc(p,g);
for (i=0;i<n;i++) {
for (j=0;j<n;j++) hessin[i][j]=0.0;
hessin[i][i]=1.0;
xi[i] = -g[i];
sum += p[i]*p[i];
}
stpmax=STPMX*MAX(sqrt(sum),DP(n));
for (its=0;its<ITMAX;its++) {
iter=its;
lnsrch(p,fp,g,xi,pnew,fret,stpmax,check,func);
fp=fret;
for (i=0;i<n;i++) {
xi[i]=pnew[i]-p[i];
p[i]=pnew[i];
}
test=0.0;
for (i=0;i<n;i++) {
temp=fabs(xi[i])/MAX(fabs(p[i]),1.0);
if (temp > test) test=temp;
}
if (test < TOLX)
return;
for (i=0;i<n;i++) dg[i]=g[i];
dfunc(p,g);
test=0.0;
den=MAX(fret,1.0);
for (i=0;i<n;i++) {
temp=fabs(g[i])*MAX(fabs(p[i]),1.0)/den;
if (temp > test) test=temp;
}
if (test < gtol)
return;
for (i=0;i<n;i++) dg[i]=g[i]-dg[i];
for (i=0;i<n;i++) {
hdg[i]=0.0;
for (j=0;j<n;j++) hdg[i] += hessin[i][j]*dg[j];
}
fac=fae=sumdg=sumxi=0.0;
for (i=0;i<n;i++) {
fac += dg[i]*xi[i];
fae += dg[i]*hdg[i];
sumdg += SQR(dg[i]);
sumxi += SQR(xi[i]);
}
if (fac > sqrt(EPS*sumdg*sumxi)) {
fac=1.0/fac;
fad=1.0/fae;
for (i=0;i<n;i++) dg[i]=fac*xi[i]-fad*hdg[i];
for (i=0;i<n;i++) {
for (j=i;j<n;j++) {
hessin[i][j] += fac*xi[i]*xi[j]
-fad*hdg[i]*hdg[j]+fae*dg[i]*dg[j];
hessin[j][i]=hessin[i][j];
}
}
}
for (i=0;i<n;i++) {
xi[i]=0.0;
for (j=0;j<n;j++) xi[i] -= hessin[i][j]*g[j];
}
}
nrerror("too many iterations in dfpmin");
}
|
tadejsv/catalyst | catalyst/contrib/layers/__init__.py | # flake8: noqa
from torch.nn.modules import *
from catalyst.contrib.layers.amsoftmax import AMSoftmax
from catalyst.contrib.layers.arcface import ArcFace, SubCenterArcFace
from catalyst.contrib.layers.arcmargin import ArcMarginProduct
from catalyst.contrib.layers.common import (
Flatten,
GaussianNoise,
Lambda,
Normalize,
ResidualBlock,
)
from catalyst.contrib.layers.cosface import CosFace, AdaCos
from catalyst.contrib.layers.curricularface import CurricularFace
from catalyst.contrib.layers.factorized import FactorizedLinear
from catalyst.contrib.layers.lama import (
LamaPooling,
TemporalLastPooling,
TemporalAvgPooling,
TemporalMaxPooling,
TemporalDropLastWrapper,
TemporalAttentionPooling,
TemporalConcatPooling,
)
from catalyst.contrib.layers.pooling import (
GlobalAttnPool2d,
GlobalAvgAttnPool2d,
GlobalAvgPool2d,
GlobalConcatAttnPool2d,
GlobalConcatPool2d,
GlobalMaxAttnPool2d,
GlobalMaxPool2d,
GeM2d,
)
from catalyst.contrib.layers.rms_norm import RMSNorm
from catalyst.contrib.layers.se import (
sSE,
scSE,
cSE,
)
from catalyst.contrib.layers.softmax import SoftMax
|
strider2038/otus-marketplace | services/trading-service/internal/api/api_trading_service.go | <reponame>strider2038/otus-marketplace
/*
* Public API
*
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* API version: 1.0.0
* Generated by: OpenAPI Generator (https://openapi-generator.tech)
*/
package api
import (
"context"
"net/http"
"time"
"trading-service/internal/trading"
"github.com/bsm/redislock"
"github.com/gofrs/uuid"
"github.com/muonsoft/validation"
"github.com/pkg/errors"
"github.com/strider2038/pkg/persistence"
)
// TradingApiService is a service that implents the logic for the TradingApiServicer
// This service should implement the business logic for every endpoint for the TradingApi API.
// Include any external packages or services that will be required by this service.
type TradingApiService struct {
purchaseOrders trading.PurchaseOrderRepository
sellOrders trading.SellOrderRepository
items trading.ItemRepository
userItems trading.UserItemRepository
aggregatedUserItems trading.AggregatedUserItemRepository
transactionManager persistence.TransactionManager
dealer *trading.Dealer
validator *validation.Validator
purchaseState StateRepository
sellState StateRepository
locker Locker
lockTimeout time.Duration
}
// NewTradingApiService creates a default api service
func NewTradingApiService(
purchaseOrders trading.PurchaseOrderRepository,
sellOrders trading.SellOrderRepository,
items trading.ItemRepository,
userItems trading.UserItemRepository,
aggregatedUserItems trading.AggregatedUserItemRepository,
transactionManager persistence.TransactionManager,
dealer *trading.Dealer,
validator *validation.Validator,
purchaseState StateRepository,
sellState StateRepository,
locker Locker,
lockTimeout time.Duration,
) TradingApiServicer {
return &TradingApiService{
purchaseOrders: purchaseOrders,
sellOrders: sellOrders,
items: items,
userItems: userItems,
aggregatedUserItems: aggregatedUserItems,
transactionManager: transactionManager,
dealer: dealer,
validator: validator,
purchaseState: purchaseState,
sellState: sellState,
locker: locker,
lockTimeout: lockTimeout,
}
}
// GetPurchaseOrders -
func (s *TradingApiService) GetPurchaseOrders(ctx context.Context, userID uuid.UUID) (ImplResponse, string, error) {
if userID.IsNil() {
return newUnauthorizedResponse(), "", nil
}
orders, err := s.purchaseOrders.FindByUser(ctx, userID)
if err != nil {
return Response(http.StatusInternalServerError, nil), "", err
}
state, err := s.purchaseState.Get(ctx, userID)
if err != nil {
return Response(http.StatusInternalServerError, nil), "", errors.WithMessagef(
err,
`failed to get purchase state of user "%s"`,
userID,
)
}
return Response(http.StatusOK, orders), state, nil
}
// CreatePurchaseOrder -
func (s *TradingApiService) CreatePurchaseOrder(ctx context.Context, form PurchaseOrder) (ImplResponse, error) {
if form.UserID.IsNil() {
return newUnauthorizedResponse(), nil
}
if form.IdempotenceKey == "" {
return newPreconditionRequiredResponse(), nil
}
err := s.validator.ValidateValidatable(ctx, form)
if err != nil {
return newUnprocessableEntityResponse(err.Error()), nil
}
lock, err := s.locker.Obtain(ctx, form.UserID.String()+":create-purchase-order", s.lockTimeout)
if errors.Is(err, redislock.ErrNotObtained) {
return newConflictResponse(), nil
}
if err != nil {
return newErrorResponsef(err, "failed to obtain lock")
}
defer lock.Release(ctx)
err = s.purchaseState.Verify(ctx, form.UserID, form.IdempotenceKey)
if errors.Is(err, trading.ErrOutdated) {
return newPreconditionFailedResponse(), nil
}
if err != nil {
return newErrorResponsef(err, "failed to verify idempotence key")
}
item, err := s.items.FindByID(ctx, form.ItemID)
if errors.Is(err, trading.ErrItemNotFound) {
return newUnprocessableEntityResponse("trading item does not exist"), nil
}
if err != nil {
return newErrorResponsef(err, "failed to create purchase order")
}
order := trading.NewPurchaseOrder(form.UserID, item, form.Price)
err = s.dealer.CreatePurchaseOrder(ctx, item, order)
if err != nil {
return newErrorResponsef(err, "failed to create purchase order")
}
err = s.purchaseState.Refresh(ctx, form.UserID)
if err != nil {
return newErrorResponsef(err, `failed to refresh purchase state of user "%s"`, form.UserID)
}
return Response(http.StatusAccepted, order), nil
}
// CancelPurchaseOrder -
func (s *TradingApiService) CancelPurchaseOrder(ctx context.Context, userID, orderID uuid.UUID) (ImplResponse, error) {
if userID.IsNil() {
return newUnauthorizedResponse(), nil
}
var order *trading.PurchaseOrder
var err error
err = s.transactionManager.DoTransactionally(ctx, func(ctx context.Context) error {
order, err = s.purchaseOrders.FindByIDForUpdate(ctx, orderID)
if err != nil {
return errors.WithMessage(err, "failed to find order")
}
err = order.CancelByUser(userID)
if err != nil {
return errors.WithMessage(err, "failed to cancel purchase order")
}
err = s.purchaseOrders.Delete(ctx, order.ID)
if err != nil {
return errors.WithMessage(err, "failed to delete purchase order")
}
return nil
})
if errors.Is(err, trading.ErrOrderNotFound) {
return newNotFoundResponse(), nil
}
if errors.Is(err, trading.ErrDenied) {
return newForbiddenResponse(), nil
}
if errors.Is(err, trading.ErrCannotCancel) {
return newUnprocessableEntityResponse(err.Error()), nil
}
if err != nil {
return Response(http.StatusInternalServerError, nil), err
}
return Response(http.StatusOK, order), nil
}
// GetSellOrders -
func (s *TradingApiService) GetSellOrders(ctx context.Context, userID uuid.UUID) (ImplResponse, string, error) {
if userID.IsNil() {
return newUnauthorizedResponse(), "", nil
}
orders, err := s.sellOrders.FindByUser(ctx, userID)
if err != nil {
return Response(http.StatusInternalServerError, nil), "", err
}
state, err := s.sellState.Get(ctx, userID)
if err != nil {
return Response(http.StatusInternalServerError, nil), "", errors.WithMessagef(
err,
`failed to get sell state of user "%s"`,
userID,
)
}
return Response(http.StatusOK, orders), state, nil
}
// CreateSellOrder -
func (s *TradingApiService) CreateSellOrder(ctx context.Context, form SellOrder) (ImplResponse, error) {
if form.UserID.IsNil() {
return newUnauthorizedResponse(), nil
}
if form.IdempotenceKey == "" {
return newPreconditionRequiredResponse(), nil
}
err := s.validator.ValidateValidatable(ctx, form)
if err != nil {
return newUnprocessableEntityResponse(err.Error()), nil
}
lock, err := s.locker.Obtain(ctx, form.UserID.String()+":create-sell-order", s.lockTimeout)
if errors.Is(err, redislock.ErrNotObtained) {
return newConflictResponse(), nil
}
if err != nil {
return newErrorResponsef(err, "failed to obtain lock")
}
defer lock.Release(ctx)
err = s.sellState.Verify(ctx, form.UserID, form.IdempotenceKey)
if errors.Is(err, trading.ErrOutdated) {
return newPreconditionFailedResponse(), nil
}
if err != nil {
return newErrorResponsef(err, "failed to verify idempotence key")
}
item, err := s.items.FindByID(ctx, form.ItemID)
if errors.Is(err, trading.ErrItemNotFound) {
return newUnprocessableEntityResponse("trading item does not exist"), nil
}
if err != nil {
return Response(http.StatusInternalServerError, nil), err
}
sellOrder, err := s.dealer.CreateSellOrder(ctx, item, form.UserID, form.Price)
if errors.Is(err, trading.ErrItemNotFound) {
return newUnprocessableEntityResponse("no trading items for sale"), nil
}
if err != nil {
return Response(http.StatusInternalServerError, nil), err
}
err = s.sellState.Refresh(ctx, form.UserID)
if err != nil {
return newErrorResponsef(err, `failed to refresh sell state of user "%s"`, form.UserID)
}
return Response(http.StatusAccepted, sellOrder), nil
}
// CancelSellOrder -
func (s *TradingApiService) CancelSellOrder(ctx context.Context, userID, orderID uuid.UUID) (ImplResponse, error) {
if userID.IsNil() {
return newUnauthorizedResponse(), nil
}
var order *trading.SellOrder
var err error
err = s.transactionManager.DoTransactionally(ctx, func(ctx context.Context) error {
order, err = s.sellOrders.FindByIDForUpdate(ctx, orderID)
if err != nil {
return errors.WithMessage(err, "failed to find order")
}
err = order.CancelByUser(userID)
if err != nil {
return errors.WithMessage(err, "failed to cancel sell order")
}
err = s.sellOrders.Delete(ctx, order.ID)
if err != nil {
return errors.WithMessage(err, "failed to delete sell order")
}
return nil
})
if errors.Is(err, trading.ErrOrderNotFound) {
return newNotFoundResponse(), nil
}
if errors.Is(err, trading.ErrDenied) {
return newForbiddenResponse(), nil
}
if errors.Is(err, trading.ErrCannotCancel) {
return newUnprocessableEntityResponse(err.Error()), nil
}
if err != nil {
return Response(http.StatusInternalServerError, nil), err
}
return Response(http.StatusOK, order), nil
}
// GetTradingItems -
func (s *TradingApiService) GetTradingItems(ctx context.Context) (ImplResponse, error) {
items, err := s.items.FindAll(ctx)
if err != nil {
return Response(http.StatusInternalServerError, nil), err
}
return Response(http.StatusOK, items), nil
}
// CreateTradingItem -
func (s *TradingApiService) CreateTradingItem(ctx context.Context, form TradingItem) (ImplResponse, error) {
if form.UserID.IsNil() {
return newUnauthorizedResponse(), nil
}
if form.UserRole != "broker" {
return newForbiddenResponse(), nil
}
err := s.validator.ValidateValidatable(ctx, form)
if err != nil {
return newUnprocessableEntityResponse(err.Error()), nil
}
item := trading.NewItem(form.Name, form.InitialCount, form.InitialPrice, form.CommissionPercent)
err = s.transactionManager.DoTransactionally(ctx, func(ctx context.Context) error {
err := s.items.Add(ctx, item)
if err != nil {
return errors.WithMessagef(err, `failed to add item "%s"`, item.Name)
}
for i := 0; i < int(item.InitialCount); i++ {
userItem := trading.NewUserItem(item.ID, form.UserID)
userItem.IsOnSale = true
err = s.userItems.Save(ctx, userItem)
if err != nil {
return errors.WithMessagef(err, `failed to save user item "%s"`, item.Name)
}
err = s.sellOrders.Save(ctx, trading.NewInitialOrder(form.UserID, item, userItem))
if err != nil {
return errors.WithMessage(err, "failed to save initial order")
}
}
return nil
})
if err != nil {
return Response(http.StatusInternalServerError, nil), err
}
return Response(http.StatusCreated, item), nil
}
func (s *TradingApiService) GetUserItems(ctx context.Context, userID uuid.UUID) (ImplResponse, error) {
if userID.IsNil() {
return newUnauthorizedResponse(), nil
}
items, err := s.aggregatedUserItems.FindByUser(ctx, userID)
if err != nil {
return Response(http.StatusInternalServerError, nil), err
}
return Response(http.StatusOK, items), nil
}
|
Zalexanninev15/VitNX | docs/search--/s_5297.js | search_result['5297']=["topic_00000000000016AC_events--.html","FontAwesomeExtensions Events",""]; |
ALRubinger/descriptors | spi/src/main/java/org/jboss/shrinkwrap/descriptor/spi/node/Query.java | <filename>spi/src/main/java/org/jboss/shrinkwrap/descriptor/spi/node/Query.java
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.shrinkwrap.descriptor.spi.node;
/**
* Contract for something capable of executing a query (collection of {@link Pattern}s) upon a {@link Node} to find a
* match or matches. May be used for search, creation, etc.
*
* @author <a href="mailto:<EMAIL>"><NAME></a>
* @author <a href="mailto:<EMAIL>">ALR</a>
* @param <T>
* Expected return value from executing a query
*/
interface Query<T> {
/**
* Queries the tree starting at the specified {@link Node} for the specified {@link Pattern}s.
*
* @param node
* The {@link Node} to use as a reference point
* @param patterns
* The {@link Pattern}s to match
* @return The expressed value or null if not found.
* @throws IllegalArgumentException
* If the {@link Node} is not specified or no {@link Pattern}s are specified
*/
T execute(Node node, Pattern... patterns) throws IllegalArgumentException;
}
|
jiabao422/vue-cesium | website/public/Cesium/Workers/createEllipseOutlineGeometry.js | <reponame>jiabao422/vue-cesium<filename>website/public/Cesium/Workers/createEllipseOutlineGeometry.js
define([
'./Matrix2-9aa31791',
'./when-4bbc8319',
'./EllipseOutlineGeometry-247f65c5',
'./RuntimeError-346a3079',
'./ComponentDatatype-93750d1a',
'./WebGLConstants-1c8239cc',
'./GeometryOffsetAttribute-1772960d',
'./Transforms-d13cc04e',
'./combine-83860057',
'./EllipseGeometryLibrary-962723df',
'./GeometryAttribute-43536dc0',
'./GeometryAttributes-7827a6c2',
'./IndexDatatype-b7d979a6'
], function (e, t, r, i, n, o, c, l, a, s, d, u, m) {
'use strict'
return function (i, n) {
return (
t.defined(n) && (i = r.EllipseOutlineGeometry.unpack(i, n)),
(i._center = e.Cartesian3.clone(i._center)),
(i._ellipsoid = e.Ellipsoid.clone(i._ellipsoid)),
r.EllipseOutlineGeometry.createGeometry(i)
)
}
})
|
zhyuzh3d/10knet_cliWeb | src/Units/User/UserItem.js | /*
单个用户项
props:{
userId,用户的ID,这里会自动读取用户头像姓名信息
currentUser:当前用户,用于判断是否显示菜单
}
*/
import { Component } from 'react';
import h from 'react-hyperscript';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import Grid from 'material-ui/Grid';
import Button from 'material-ui/Button';
import { ListItem } from 'material-ui/List';
import FontA from 'react-fa';
const style = theme => ({
item: {
padding: '4px 8px',
borderBottom: '1px solid #EEE',
},
itemIcon: {
margin: 8,
width: 48,
},
itemArrow: {
fontSize: 10,
color: '#AAA',
width: 56,
textAlign: 'center',
},
itemFollow: {
fontSize: 10,
width: 56,
textAlign: 'center',
},
itemText: {
margin: 8,
flex: 1,
},
itemTitle: {
fontSize: '14px',
fontWeight: 'bold',
color: '#333',
},
itemTime: {
fontSize: 10,
fontWeight: 200,
color: '#AAA',
verticalAlign: 'middle',
},
avatar: {
width: 32,
height: 32,
background: '#EEE',
borderRadius: 48,
verticalAlign: 'middle',
},
itemBtn: {
width: 56,
minWidth: 56,
}
});
//元件
class com extends Component {
state = {
item: null,
hasFollow: false,
};
componentWillMount = async function() {
let that = this;
if(global.$wd.auth().currentUser) {
that.getUserInfo();
} else {
that.wdAuthListen = global.$wd.auth().onAuthStateChanged((user) => {
that.getUserInfo();
});
}
};
//读取用户信息以及关注状态
getUserInfo = () => {
let that = this;
let cuser = global.$wd.auth().currentUser;
let userId = that.props.userId;
global.$wd.sync().ref(`user/${userId}/`).once('value', (shot) => {
that.setState({ item: shot.val() });
});
let cuserId = cuser ? cuser.uid : undefined;
if(!cuser) {
global.$snackbar.fn.show(`您还没有登录,不能关注`, 3000);
return;
};
global.$wd.sync().ref(`ufollow/${cuserId}/${userId}`).once('value', (shot) => {
let followed = shot.val() ? true : false;
that.setState({ hasFollow: followed });
});
};
//点击跳转打开用户详情页面
clickHandler = () => {
let that = this;
global.$router.changePage('UserDetailPage', {
userId: that.props.userId,
});
};
//关注当前用户
followUser = () => {
let that = this;
let cuser = global.$wd.auth().currentUser;
let cuserId = cuser ? cuser.uid : undefined;
let userId = that.props.userId;
if(!cuser) {
global.$snackbar.fn.show(`您还没有登录,不能关注`, 3000);
return;
};
global.$wd.sync().ref(`ufollow/${cuserId}/${userId}`).update({
ts: global.$wd.sync().ServerValue.TIMESTAMP,
}).then((res) => {
that.setState({ hasFollow: true });
global.$snackbar.fn.show(`关注成功`, 2000);
}).catch((err) => {
global.$snackbar.fn.show(`关注失败:${err.message}`, 3000);
});
};
//取消关注当前用户
unFollowUser = () => {
let that = this;
let cuser = global.$wd.auth().currentUser;
let cuserId = cuser ? cuser.uid : undefined;
let userId = that.props.userId;
if(!cuser) {
global.$snackbar.fn.show(`您还没有登录,不能取消关注`, 3000);
return;
};
global.$wd.sync().ref(`ufollow/${cuserId}/${userId}`).remove().then((res) => {
that.setState({ hasFollow: false });
global.$snackbar.fn.show(`取消关注成功`, 2000);
}).catch((err) => {
global.$snackbar.fn.show(`取消关注失败:${err.message}`, 3000);
});
};
//渲染实现
render() {
let that = this;
const css = that.props.classes;
let item = that.state.item;
let itemEl = h(ListItem, {
className: css.item,
button: true,
}, [
h(Grid, {
container: true,
align: 'left',
alignItems: 'center'
}, [
h(Grid, {
item: true,
className: css.itemIcon,
onClick: that.clickHandler,
}, h('img', {
className: css.avatar,
width: 32,
height: 32,
src: item && item.photoURL ? `http://${item.photoURL}` : global.$conf.defaultIcon,
})),
h(Grid, {
item: true,
className: css.itemText,
onClick: that.clickHandler,
}, h('div', { className: css.itemTitle }, [
item && item.displayName ? item.displayName : '未命名用户',
])),
h(Grid, {
item: true,
className: css.itemFollow,
onClick: () => {
if(!that.state.hasFollow) {
that.followUser();
} else {
that.unFollowUser();
}
},
}, h(Button, { color: 'accent', className: css.itemBtn }, [
h(FontA, { name: that.state.hasFollow ? 'heart' : 'heart-o' }),
])),
h(Grid, {
item: true,
className: css.itemArrow,
onClick: that.clickHandler,
}, h(FontA, { name: 'chevron-right' })),
]), ]);
return itemEl;
}
};
com.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(style)(com);
|
sinarueeger/dplyr | inst/include/dplyr/hybrid/Column.h | <gh_stars>100-1000
#ifndef dplyr_hybrid_column_h
#define dplyr_hybrid_column_h
namespace dplyr {
namespace hybrid {
struct Column {
SEXP data;
bool is_desc;
inline bool is_trivial() const {
return !Rf_isObject(data) && !Rf_isS4(data) && RCPP_GET_CLASS(data) == R_NilValue;
}
};
}
}
#endif
|
magicLaLa/RSSHub | lib/v2/rfi/radar.js | module.exports = {
'rfi.fr': {
_name: '法国国际广播电台',
'.': [
{
title: '滚动新闻',
docs: 'https://docs.rsshub.app/multimedia.html#fa-guo-guo-ji-guang-bo-dian-tai-gun-dong-xin-wen',
source: ['/'],
target: '/rfi/news',
},
],
},
};
|
mobotx/mobot | chassis/firmware/src/libs/joint_control.py | import math
from machine import Timer
def is_within(x, eps):
if x < eps and x > -eps:
return True
else:
return False
class JointControl:
def __init__(self, motor, js, kp, ki, target_w_min, target_w_max, gamma):
self.motor = motor
self.js = js
self.kp = kp
self.ki = ki
self.target_w= 0
self.error_int = 0
self.target_w_min = target_w_min
self.target_w_max = target_w_max
self.gamma = gamma
self.error_int_max = 1/self.ki
def set_target_w(self, w): ## Public
if is_within(w, self.target_w_max):
self.target_w = w
# if is_within(w, self.target_w_min):
# self.target_w = 0
else:
self.target_w = (w / abs(w)) * self.target_w_max
def update(self, dt): ## Public
error = self.target_w - self.js.w
cmd = (self.kp * error) + (self.ki * self.error_int)
self.motor.set_cmd(cmd)
self.update_error_int(error, dt)
def update_error_int(self, error, dt):
if self.target_w == 0:
self.error_int = 0
return
if is_within(self.error_int, self.error_int_max * self.motor.min_op):
self.error_int += 5 * error * dt
elif is_within(self.error_int, self.error_int_max):
self.error_int += error * dt
else:
if abs(self.error_int + (error * dt)) < abs(self.error_int):
self.error_int += error * dt
def update_cb(self, timer):
self.update(self.dt)
def control(self, control_hz=100.0, timer_no=0): ## Public
self.dt = 1/control_hz
dt_milli = math.trunc(1000 * self.dt)
self.timer = Timer(timer_no)
self.timer.init(period=dt_milli, mode=Timer.PERIODIC, callback=self.update_cb)
|
deanearlwright/AdventOfCode | 2015/08_Matchsticks/literals.test.js | <filename>2015/08_Matchsticks/literals.test.js<gh_stars>1-10
/* eslint-disable linebreak-style */
// ======================================================================
// Matchsticks
// Advent of Code 2015 Day 08 -- <NAME> -- https://adventofcode.com
//
// Javascript implementation by Dr. <NAME> III
// ======================================================================
// ======================================================================
// l i t e r a l s . t e s t . j s
//
// Test the solver for Advent of Code 2015 day 08 problem
// ======================================================================
// ----------------------------------------------------------------------
// import
// ----------------------------------------------------------------------
const aoc08 = require('./aoc_08');
const literals = require('./literals');
// ----------------------------------------------------------------------
// constants
// ----------------------------------------------------------------------
const EXAMPLE_TEXT = '\n""\n"abc"\n"aaa\\"aaa"\n"\\x27"';
const EXAMPLES_PART_ONE = {
'""': [2, 0],
'"abc"': [5, 3],
'"aaa\\"aaa"': [10, 7],
'"\\x27"': [6, 1],
'"\\\\"': [4, 1],
'"aaa\\"aaa\\x27aaa\\\\aaa"': [2 + 12 + 2 + 4 + 2, 12 + 1 + 1 + 1],
};
const EXAMPLES_PART_TWO = {
'""': [2, 6],
'"abc"': [5, 9],
'"aaa\\"aaa"': [10, 16],
'"\\x27"': [6, 11],
'"\\\\"': [4, 10],
'"aaa\\"aaa\\x27aaa\\\\aaa"': [2 + 12 + 2 + 4 + 2, 12 + 4 + 4 + 7 + 4],
};
const PART_ONE_TEXT = EXAMPLE_TEXT;
const PART_TWO_TEXT = EXAMPLE_TEXT;
const PART_ONE_RESULT = 23 - 11;
const PART_TWO_RESULT = 42 - 23;
// ======================================================================
// TestLiterals
// ======================================================================
describe('Literals', () => {
test('Test the default Literals creation', () => {
// 1. Create default Literals object
const myobj = new literals.Literals({});
// 2. Make sure it has the default values
expect(myobj.part2).toBe(false);
expect(myobj.text).toBe(null);
});
test('Test the Literals object creation from text', () => {
// 1. Create Literals object from text
const myobj = new literals.Literals({ text: aoc08.fromText(EXAMPLE_TEXT) });
// 2. Make sure it has the expected values
expect(myobj.part2).toBe(false);
expect(myobj.text).toHaveLength(4);
});
test('Test all of the part one examples', () => {
// 1. Loop for all of the examples
Object.keys(EXAMPLES_PART_ONE).forEach((key) => {
// 2. Create Literals object using the key at text
const myobj = new literals.Literals({ text: [key] });
expect(myobj.part2).toBe(false);
expect(myobj.text).toHaveLength(1);
// 3. Make sure it has the expected values
expect(myobj.getLengths(key)).toStrictEqual(EXAMPLES_PART_ONE[key]);
});
});
test('Test all of the part two examples', () => {
// 1. Loop for all of the examples for the second part
Object.keys(EXAMPLES_PART_TWO).forEach((key) => {
// 2. Create Literals object using the key at text
const myobj = new literals.Literals({ part2: true, text: [key] });
expect(myobj.part2).toBe(true);
expect(myobj.text).toHaveLength(1);
// 3. Make sure it has the expected values
expect(myobj.getLengths(key)).toStrictEqual(EXAMPLES_PART_TWO[key]);
});
});
test('Test part one example of Literals object', () => {
// 1. Create Literals object from text
const myobj = new literals.Literals({ text: aoc08.fromText(PART_ONE_TEXT) });
// 2. Check the part one result
expect(myobj.partOne({ verbose: false })).toBe(PART_ONE_RESULT);
});
test('Test part two example of Literals object', () => {
// 1. Create Literals object from text
const myobj = new literals.Literals({ part2: true, text: aoc08.fromText(PART_TWO_TEXT) });
// 2. Check the part two result
expect(myobj.partTwo({ verbose: false })).toBe(PART_TWO_RESULT);
});
});
// ======================================================================
// end t e s t _ l i t e r a l s . j s end
// ======================================================================
|
branflake2267/gxt-demo-desktop | src/main/java/com/sencha/gxt/desktop/client/widget/StartMainMenu.java | /**
* Sencha GXT 1.0.0-SNAPSHOT - Sencha for GWT
* Copyright (c) 2006-2018, Sencha Inc.
*
* <EMAIL>
* http://www.sencha.com/products/gxt/license/
*
* ================================================================================
* Commercial License
* ================================================================================
* This version of Sencha GXT is licensed commercially and is the appropriate
* option for the vast majority of use cases.
*
* Please see the Sencha GXT Licensing page at:
* http://www.sencha.com/products/gxt/license/
*
* For clarification or additional options, please contact:
* <EMAIL>
* ================================================================================
*
*
*
*
*
*
*
*
* ================================================================================
* Disclaimer
* ================================================================================
* THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND
* REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE
* IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY,
* FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND
* THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING.
* ================================================================================
*/
package com.sencha.gxt.desktop.client.widget;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.desktop.client.theme.base.startmenu.StartMainMenuAppearance;
import com.sencha.gxt.widget.core.client.menu.Menu;
/**
* Provides the "main menu" component of the start menu. The main menu is
* typically displayed on the left side of the start menu and contains items for
* desktop applications.
*
* @see StartMainMenuItem
*/
public class StartMainMenu extends Menu {
private StartMenu startMenu;
/**
* Creates a main menu for the specified start menu.
*
* @param startMenu the start menu that contains this main menu
*/
public StartMainMenu(StartMenu startMenu) {
this(startMenu, new StartMainMenuAppearance());
}
/**
* Creates a main menu for the specified start menu, with the specified
* appearance.
*
* @param startMenu the start menu that contains this main menu
* @param startMainMenuAppearance the appearance
*/
public StartMainMenu(StartMenu startMenu, StartMainMenuAppearance startMainMenuAppearance) {
super(startMainMenuAppearance);
this.startMenu = startMenu;
}
/**
* {@inheritDoc}
*
* @throws IllegalArgumentException if the specified widget is not a
* {@link StartMainMenuItem}
*/
@Override
public void add(Widget child) {
if (!(child instanceof StartMainMenuItem)) {
throw new IllegalArgumentException("Widget is not a StartMainMenuItem");
}
super.add(child);
}
@Override
public void hide(boolean deep) {
if (activeItem != null) {
((StartMainMenuItem) activeItem).hideSubMenu();
activeItem = null;
}
startMenu.hide();
}
} |
PaPeK/epipack | epipack/metadata.py | <reponame>PaPeK/epipack<gh_stars>0
# -*- coding: utf-8 -*-
"""
Contains a bunch of information about this package.
"""
__version__ = "0.1.5"
__author__ = "<NAME>"
__copyright__ = "Copyright 2020-2021, " + __author__
__credits__ = [__author__]
__license__ = "MIT"
__maintainer__ = __author__
__email__ = "<EMAIL>"
__status__ = "Development"
|
stefan-zobel/schwefel | src/main/java/net/volcanite/util/Byte8Key.java | <filename>src/main/java/net/volcanite/util/Byte8Key.java
package net.volcanite.util;
import java.util.Arrays;
import java.util.Objects;
/**
* Key generator for auto-incrementing fixed length 8 byte[] array keys which
* wrap-around on overflow. Note that the individual bytes in a key must be
* interpreted as unsigned byte to get the correct lexicographic ordering. The
* array representation of the underlying long is in big-endian order.
*/
public final class Byte8Key {
/**
* The smallest 8 ubyte[] key which is possible in a lexicographical
* comparison.
*/
private static final byte[] MIN_KEY = { 0, 0, 0, 0, 0, 0, 0, 0 };
/**
* The largest 8 ubyte[] key which is possible in a lexicographical
* comparison.
*/
private static final byte[] MAX_KEY = { (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255,
(byte) 255, (byte) 255 };
public static byte[] minKey() {
return MIN_KEY.clone();
}
public static byte[] maxKey() {
return MAX_KEY.clone();
}
private long curr;
public Byte8Key() {
curr = Long.MIN_VALUE;
}
public Byte8Key(long startAt) {
curr = startAt;
}
/**
* Construct a {@code Byte8Key} from a big-endian byte array key.
*
* @param key
* array in big-endian representation
*/
public Byte8Key(byte[] key) {
if (Objects.requireNonNull(key).length != 8) {
throw new IllegalArgumentException("wrong key length: " + key.length);
}
curr = getLongB(key);
}
public byte[] next() {
return create(curr++);
}
public byte[] current() {
return create(curr);
}
public long currentValue() {
return curr;
}
public void increment() {
++curr;
}
public void decrement() {
--curr;
}
public long minus(Byte8Key other) {
return curr - Objects.requireNonNull(other, "other").curr;
}
public String toString() {
return Arrays.toString(current());
}
@Override
public int hashCode() {
int h = 0x7FFFF + (int) (curr ^ (curr >>> 32));
return Hash.hash32((h << 19) - h);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Byte8Key other = (Byte8Key) obj;
if (curr == other.curr) {
return true;
}
return false;
}
private static byte[] create(long val) {
return putLongB(val, new byte[8]);
}
private static byte[] putLongB(long x, byte[] bytes) {
bytes[0] = (byte) (x >> 56);
bytes[1] = (byte) (x >> 48);
bytes[2] = (byte) (x >> 40);
bytes[3] = (byte) (x >> 32);
bytes[4] = (byte) (x >> 24);
bytes[5] = (byte) (x >> 16);
bytes[6] = (byte) (x >> 8);
bytes[7] = (byte) x;
return bytes;
}
//@formatter:off
private static long getLongB(byte[] bytes) {
return makeLong(bytes[0],
bytes[1],
bytes[2],
bytes[3],
bytes[4],
bytes[5],
bytes[6],
bytes[7]);
}
//@formatter:on
//@formatter:off
private static long makeLong(byte b7, byte b6, byte b5, byte b4,
byte b3, byte b2, byte b1, byte b0) {
return ((((long) b7 ) << 56) |
(((long) b6 & 0xff) << 48) |
(((long) b5 & 0xff) << 40) |
(((long) b4 & 0xff) << 32) |
(((long) b3 & 0xff) << 24) |
(((long) b2 & 0xff) << 16) |
(((long) b1 & 0xff) << 8) |
(((long) b0 & 0xff) ));
}
//@formatter:on
}
|
candideu/hivemind | components/layout/Layout.js | <filename>components/layout/Layout.js
import Head from 'next/head'
import Link from 'next/link'
import React, { forwardRef, useCallback, useContext, useState } from 'react'
import {
GitHub,
HelpCircle,
Info,
MessageCircle,
} from 'react-feather'
import NotificationAlert from 'react-notification-alert'
import {
Col,
Collapse,
Container,
Dropdown,
DropdownItem,
DropdownMenu,
DropdownToggle,
Nav,
Navbar,
NavbarBrand,
NavbarText,
NavbarToggler,
NavItem,
NavLink,
Row,
Spinner,
} from 'reactstrap'
import GlobalContext from '../GlobalContext'
import MainNav from './nav/MainNav'
import NavItemLogin from './nav/NavItemLogin'
import NavItemUser from './nav/NavItemUser'
const ForwardedNavbarBrand = forwardRef((props, ref) => (
<NavbarBrand href={ref} {...props} />
))
const Layout = ({ children }) => {
const [isOpen, setOpen] = useState(false)
const [dropdownOpen, setDropdownOpen] = useState(false)
const { pageVars } = useContext(GlobalContext)
const notifyRef = useCallback((node) => {
if (typeof window !== 'undefined') {
if (node) {
window.notify = node.notificationAlert.bind(node)
} else {
window.notify = null
}
}
}, [])
function toggleCollapse() {
setOpen(!isOpen)
}
function toggleDropdown() {
setDropdownOpen(!dropdownOpen)
}
return (
<Container fluid>
<Head>
<script type="text/javascript" src="/js/pace.min.js" async />
<title>{pageVars.title}</title>
<link
rel="apple-touch-icon"
sizes="57x57"
href="/img/logo/apple-icon-57x57.png"
/>
<link
rel="apple-touch-icon"
sizes="60x60"
href="/img/logo/apple-icon-60x60.png"
/>
<link
rel="apple-touch-icon"
sizes="72x72"
href="/img/logo/apple-icon-72x72.png"
/>
<link
rel="apple-touch-icon"
sizes="76x76"
href="/img/logo/apple-icon-76x76.png"
/>
<link
rel="apple-touch-icon"
sizes="114x114"
href="/img/logo/apple-icon-114x114.png"
/>
<link
rel="apple-touch-icon"
sizes="120x120"
href="/img/logo/apple-icon-120x120.png"
/>
<link
rel="apple-touch-icon"
sizes="144x144"
href="/img/logo/apple-icon-144x144.png"
/>
<link
rel="apple-touch-icon"
sizes="152x152"
href="/img/logo/apple-icon-152x152.png"
/>
<link
rel="apple-touch-icon"
sizes="180x180"
href="/img/logo/apple-icon-180x180.png"
/>
<link
rel="icon"
type="image/png"
sizes="192x192"
href="/img/logo/android-icon-192x192.png"
/>
<link
rel="icon"
type="image/png"
sizes="32x32"
href="/img/logo/favicon-32x32.png"
/>
<link
rel="icon"
type="image/png"
sizes="96x96"
href="/img/logo/favicon-96x96.png"
/>
<link
rel="icon"
type="image/png"
sizes="16x16"
href="/img/logo/favicon-16x16.png"
/>
<link rel="manifest" href="/img/logo/manifest.json" />
<meta name="msapplication-TileColor" content="#ffffff" />
<meta
name="msapplication-TileImage"
content="/img/logo/ms-icon-144x144.png"
/>
<meta name="theme-color" content="#ffffff" />
</Head>
<Navbar color="inverse" light expand="md" className="border-bottom mb-2">
<Link href="/" passHref>
<ForwardedNavbarBrand className="text-wrap">
<img
src="/img/logo/Logo.svg"
style={{ height: '35px' }}
alt="Logo"
/>
</ForwardedNavbarBrand>
</Link>
<NavbarToggler onClick={toggleCollapse} />
<Collapse isOpen={isOpen} navbar>
<MainNav />
<Nav className="ml-auto" navbar>
<NavItem>
<NavbarText>
<Spinner
type="grow"
color="dark"
id={'loading'}
className={'invisible mx-2'}
/>
</NavbarText>
</NavItem>
<NavItemUser />
<Dropdown
nav
inNavbar
isOpen={dropdownOpen}
toggle={toggleDropdown}
>
<DropdownToggle nav caret>
<HelpCircle /> Help
</DropdownToggle>
<DropdownMenu right>
<DropdownItem>
<Link href={'/help'} passHref>
<NavLink>
<Info /> User Guide
</NavLink>
</Link>
</DropdownItem>
<DropdownItem divider />
<DropdownItem>
<NavLink
href={'https://github.com/adityamukho/hivemind/discussions'}
target="_blank"
>
<MessageCircle /> Ask a Question (Hivemind)
</NavLink>
</DropdownItem>
<DropdownItem>
<NavLink
href={'https://gitter.im/recallgraph/community'}
target="_blank"
>
<MessageCircle /> Ask a Question (RecallGraph)
</NavLink>
</DropdownItem>
</DropdownMenu>
</Dropdown>
<NavItem>
<NavLink
href="https://github.com/adityamukho/hivemind"
target="_blank"
>
<GitHub />
</NavLink>
</NavItem>
<NavItemLogin />
</Nav>
</Collapse>
</Navbar>
<Container fluid>
<NotificationAlert ref={notifyRef} />
<Row>
<Col>{children}</Col>
</Row>
</Container>
</Container>
)
}
export default Layout
|
liliilli/DianYing | Core/DianYing/Source/Test/testLuaVariable.cc | <reponame>liliilli/DianYing<filename>Core/DianYing/Source/Test/testLuaVariable.cc<gh_stars>1-10
#include <precompiled.h>
///
/// MIT License
/// Copyright (c) 2018 <NAME>
///
/// 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.
///
/// Header file
#include <Dy/Test/testLua.h>
#if defined(MDY_FLAG_TEST_ENABLED)
#include <sol2/sol.hpp>
#include <Dy/Helper/GlobalType.h>
#include <Dy/Management/LoggingManager.h>
namespace dy::test
{
void DyLuaVariablesReading()
{
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.script_file("./TestResource/Lua/variables.lua");
// Can get nested variables.
const bool isFullScreen = lua["config"]["fullscreen"];
// the type "sol::state" can behaves exactly like a table.
sol::table config = lua["config"];
sol::table resolution = config.get<sol::table>("resolution");
// Table and state can have multiple things pulled out of it too.
// @TODO DOESN'T WORK BUT TUPLE WORKS WELL :(
#ifdef false
std::pair<TI32, TI32> xyResolution = resolution.get<TI32, TI32>("x", "y");
#endif
// Also tuple too!
std::tuple<TI32, TI32> xyResolutionTup = resolution.get<TI32, TI32>("x", "y");
MDY_LOG_CRITICAL("isFullScreen : {}", isFullScreen);
MDY_LOG_CRITICAL("xyResolution Tuple : {}, {}", std::get<0>(xyResolutionTup), std::get<1>(xyResolutionTup));
#ifdef false
MDY_LOG_CRITICAL("xyResolution Pair : {}, {}", xyResolution.first, xyResolution.second);
#endif
MDY_LOG_CRITICAL("DyLuaVariablesReading Success");
}
void DyLuaVariablesLookup()
{
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.script_file("./TestResource/Lua/variables.lua");
// Can get nested variables.
auto isFullScreen = lua["config"]["invalidData"];
if (isFullScreen.valid())
{
MDY_UNEXPECTED_BRANCH();
}
else
{
MDY_LOG_CRITICAL("DyLuaVariablesLookup Success. config.invalidData is not exist on table.");
}
}
void DyLuaVariablesOptionalLookup()
{
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.script_file("./TestResource/Lua/variables.lua");
// Can bind value to sol::optional too. (WARNING : NOT std::optional! this leads to UB)
{
sol::optional<TF32> var = lua["config"]["invalidData"];
if (var) { MDY_UNEXPECTED_BRANCH(); }
else
{
MDY_LOG_CRITICAL("DyLuaVariablesOptionalLookup | config.invalidData is not exist on table.");
}
}
{
sol::optional<bool> var = lua["config"]["fullscreen"];
if (!var) { MDY_UNEXPECTED_BRANCH(); }
else
{
MDY_LOG_CRITICAL("DyLuaVariablesOptionalLookup | config.fullscreen {}", var.value());
}
}
{
sol::optional<int> var = lua["config"]["fullscreen"];
if (var) { MDY_UNEXPECTED_BRANCH(); }
else
{
MDY_LOG_CRITICAL("DyLuaVariablesOptionalLookup | config.fullscreen is not a integer");
}
}
{
sol::optional<std::tuple<TI32, TI32>> var = lua["config"]["resolution"];
if (var) { MDY_UNEXPECTED_BRANCH(); }
else
{
MDY_LOG_CRITICAL("DyLuaVariablesOptionalLookup | config.resolution is exist but the way of retrieving values is wrong.");
}
}
}
void DyLuaVariableGetOrLoopup()
{
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.script_file("./TestResource/Lua/variables.lua");
int isWrongSoDefaulted = lua["config"]["fullscreen"].get_or(24);
bool isNotDefaulted = lua["config"]["fullscreen"];
MDY_LOG_CRITICAL("DyLuaVariableGetOrLoopup | isWrongSoDefaulted : {}", isWrongSoDefaulted);
MDY_LOG_CRITICAL("DyLuaVariableGetOrLoopup | isNotDefaulted : {}", isNotDefaulted);
}
void DyLuaVariableWriting()
{
sol::state lua;
// To support print() etc.
lua.open_libraries(sol::lib::base);
// define variable in global table.
lua["bark"] = 50;
// a table being created in the global table
lua["some_table"] = lua.create_table_with(
"key0", 24,
"key1", 25,
lua["bark"], "the key is 50 and this string is its value."
);
lua.script(R"dy(
print(some_table[50])
print(some_table["key0"])
print(some_table["key1"])
-- a lua comment : access a global in a lua script with the _G table.
print(_G["bark"])
)dy");
MDY_LOG_CRITICAL("DyLuaVariableWriting Success.");
}
void DyLuaReferenceModify()
{
{
sol::state lua;
auto barkkey = lua["Bark"];
MDY_ASSERT(!barkkey.valid(), "MUST SUCCESS");
barkkey = 50;
MDY_ASSERT(barkkey.valid(), "MUST SUCCESS");
}
{
sol::state lua;
lua["Bark"] = 50;
MDY_ASSERT(lua["Bark"].valid(), "MUST SUCCESS");
lua["Bark"] = sol::nil;
MDY_ASSERT(!lua["Bark"].valid(), "MUST SUCCESS");
}
MDY_LOG_CRITICAL("DyLuaReferenceModify Success.");
}
} /// ::dy::test namespace
#endif /// MDY_FLAG_TEST_ENABLED |
RenatoUtsch/compiler | src/parallelme-compiler/src/main/resources/ParallelME/java/org/parallelme/ParallelMERuntime.java | /** _ __ ____
* _ __ ___ _____ ___ __ __ ___ __ / | / / __/
* | _ \/ _ | _ | / _ | / / / / / __/ / / | / / /__
* | __/ __ | ___|/ __ |/ /_/ /__/ __/ /__ / / v / /__
* |_| /_/ |_|_|\_\/_/ |_/____/___/___/____/ /_/ /_/____/
*
*/
package org.parallelme;
import android.graphics.Bitmap;
/**
* Wrapper class for JNI calls to ParallelME runtime. It is also responsible for
* keeping the runtime pointer in memory so it can be used in multiple calls to
* the low-level runtime without recreating objects.
*
* @author <NAME>, <NAME>
*/
public class ParallelMERuntime {
private static final ParallelMERuntime instance = new ParallelMERuntime();
public final long runtimePointer;
public static ParallelMERuntime getInstance() {
return instance;
}
private native long nativeInit();
private native void nativeCleanUpRuntime(long runtimePointer);
private native long nativeCreateArray(int length, int typeNo);
private native long nativeCreateArray(int length, int typeNo,
Object sourceArray);
private native void nativeToArray(long arrayPointer, Object destArray);
private native long nativeCreateBitmapImage(long runtimePointer,
Bitmap bitmap, int width, int height);
private native long nativeCreateBitmapImage(long runtimePointer, int width,
int height);
private native void nativeToBitmapBitmapImage(long runtimePointer,
long imagePointer, Bitmap bitmap);
private native long nativeCreateHDRImage(long runtimePointer, byte[] data,
int width, int height);
private native void nativeToBitmapHDRImage(long runtimePointer,
long imagePointer, Bitmap bitmap);
private native int nativeGetHeight(long imagePointer);
private native int nativeGetWidth(long imagePointer);
private native int nativeGetLength(long arrayPointer);
private ParallelMERuntime() {
System.loadLibrary("ParallelMEGenerated");
this.runtimePointer = nativeInit();
}
@Override
protected void finalize() throws Throwable {
nativeCleanUpRuntime(runtimePointer);
super.finalize();
}
public long createArray(Class<?> classType, int length) {
if (classType == short.class)
return nativeCreateArray(length, 1);
else if (classType == int.class)
return nativeCreateArray(length, 2);
else if (classType == float.class)
return nativeCreateArray(length, 3);
else
throw new RuntimeException("Type not support by ParallelME: "
+ classType);
}
public long createArray(short[] sourceArray) {
return nativeCreateArray(sourceArray.length, 1, sourceArray);
}
public long createArray(int[] sourceArray) {
return nativeCreateArray(sourceArray.length, 2, sourceArray);
}
public long createArray(float[] sourceArray) {
return nativeCreateArray(sourceArray.length, 3, sourceArray);
}
public void toArray(long arrayPointer, short[] destArray) {
nativeToArray(arrayPointer, destArray);
}
public void toArray(long arrayPointer, int[] destArray) {
nativeToArray(arrayPointer, destArray);
}
public void toArray(long arrayPointer, float[] destArray) {
nativeToArray(arrayPointer, destArray);
}
public void createBitmapImage(Bitmap bitmap) {
nativeCreateBitmapImage(runtimePointer, bitmap, bitmap.getWidth(),
bitmap.getHeight());
}
public void toBitmapBitmapImage(long imagePointer, Bitmap bitmap) {
nativeToBitmapBitmapImage(runtimePointer, imagePointer, bitmap);
}
public long createHDRImage(byte[] data, int width, int height) {
return nativeCreateHDRImage(runtimePointer, data, width, height);
}
public void toBitmapHDRImage(long imagePointer, Bitmap bitmap) {
nativeToBitmapHDRImage(runtimePointer, imagePointer, bitmap);
}
public int getHeight(long imagePointer) {
return nativeGetHeight(imagePointer);
}
public int getWidth(long imagePointer) {
return nativeGetWidth(imagePointer);
}
public int getLength(long arrayPointer) {
return nativeGetLength(arrayPointer);
}
}
|
rharder/pushbullet.py | tests/test_auth.py | <gh_stars>10-100
import os
import pytest
import asyncpushbullet
API_KEY = os.environ["PUSHBULLET_API_KEY"]
def test_auth_fail():
with pytest.raises(asyncpushbullet.InvalidKeyError) as exinfo:
pb = asyncpushbullet.Pushbullet("faultykey")
# pb.session # Triggers a connection
pb.verify_key()
def test_auth_success():
pb = asyncpushbullet.Pushbullet(API_KEY)
_ = pb.get_user()
assert pb._user_info["name"] == os.environ.get("PUSHBULLET_NAME", "Pushbullet Tester")
|
bq-ashok/FE-BackUp | app/controllers/reports/study-student-collection.js | <reponame>bq-ashok/FE-BackUp<filename>app/controllers/reports/study-student-collection.js<gh_stars>0
import Ember from 'ember';
import StudentCollection from 'gooru-web/controllers/reports/student-collection';
import { ASSESSMENT_SUB_TYPES, ROLES } from 'gooru-web/config/config';
/**
*
* Controls the access to the analytics data for a
* student related to a collection of resources
*
*/
export default StudentCollection.extend({
/**
* Confetti Initialize once Component Initialize
*/
confettiSetup() {
let controller = this;
let averageScore = controller.get('attemptData.averageScore');
let minScore = controller.get('minScore');
let role = controller.get('role');
let type = controller.get('type');
if (
(role === 'student' &&
type === 'assessment' &&
minScore &&
minScore <= averageScore) ||
(role === 'student' && type === 'assessment' && averageScore >= 80)
) {
Ember.run.later(function() {
controller.set('enableConfetti', false);
}, 5400);
controller.set('enableConfetti', true);
}
},
// -------------------------------------------------------------------------
// Dependencies
/**
* @property {CourseMapService}
*/
courseMapService: Ember.inject.service('api-sdk/course-map'),
/**
* @property {NavigateMapService}
*/
navigateMapService: Ember.inject.service('api-sdk/navigate-map'),
session: Ember.inject.service('session'),
/**
* @dependency {i18nService} Service to retrieve translations information
*/
i18n: Ember.inject.service(),
// -------------------------------------------------------------------------
// Actions
actions: {
/**
* Action triggered for the next button
*/
next: function() {
this.checknPlayNext();
},
/**
* If the user want to continue playing the post-test suggestion
*/
playPostTestSuggestion: function() {
this.playSuggestedContent(this.get('mapLocation.postTestSuggestion'));
},
/**
* If the user want to continue playing the backfill suggestion
*/
playBackFillSuggestion: function() {
this.playSuggestedContent(this.get('mapLocation.backFillSuggestion'));
},
/**
* If the user want to continue playing the resource suggestion
*/
playResourceSuggestion: function() {
this.playSuggestedContent(this.get('mapLocation.resourceSuggestion'));
},
/**
* If the user want to continue playing the benchmark suggestion
*/
playBenchmarkSuggestion: function() {
this.playSuggestedContent(this.get('mapLocation.benchmarkSuggestion'));
},
playSignatureAssessmentSuggestions: function() {
this.playSuggestedContent(
this.get('mapLocation.signatureAssessmentSuggestions')
);
},
playSignatureCollectionSuggestions: function() {
this.playSuggestedContent(
this.get('mapLocation.signatureCollectionSuggestions')
);
}
},
// -------------------------------------------------------------------------
// Properties
/**
* @property {Course} course
*/
course: null,
/**
* @property {Unit} unit
*/
unit: null,
/**
* @property {Lesson} lesson
*/
lesson: null,
/**
* @property {Collection} collection
*/
collection: null,
/**
*Back fill backfill suggestion
* @property {String} typeSuggestion
*/
backFillType: ASSESSMENT_SUB_TYPES.BACKFILL,
/**
*Post test suggestion
* @property {String} typeSuggestion
*/
postTestType: ASSESSMENT_SUB_TYPES.POST_TEST,
/**
*Post Test resource suggestion
* @property {String} typeSuggestion
*/
resourceType: ASSESSMENT_SUB_TYPES.RESOURCE,
/**
*Benchmark suggestion
* @property {String} benchmarkType
*/
benchmarkType: ASSESSMENT_SUB_TYPES.BENCHMARK,
/**
*signatureAssessmentType suggestion
* @property {String} signatureAssessmentType
*/
signatureAssessmentType: ASSESSMENT_SUB_TYPES.SIGNATURE_ASSESSMENT,
/**
*signatureCollectionType suggestion
* @property {String} signatureCollectionType
*/
signatureCollectionType: ASSESSMENT_SUB_TYPES.SIGNATURE_COLLECTION,
/**
* Indicate if show pre test suggestion
* @property {Boolean} showSuggestion
*/
showSuggestion: true,
/**
* Current map location
* @property {MapSuggestions}
*/
mapLocation: null,
/**
* Current class assessment minScore
* @property {integer}
*/
minScore: null,
/**
* @property {boolean}
*/
hasPreTestSuggestions: Ember.computed.alias(
'mapLocation.hasPreTestSuggestions'
),
/**
* @property {boolean}
*/
hasPostTestSuggestions: Ember.computed.alias(
'mapLocation.hasPostTestSuggestions'
),
/**
* @property {boolean}
*/
hasBackFillSuggestions: Ember.computed.alias(
'mapLocation.hasBackFillSuggestions'
),
/**
* @property {boolean}
*/
hasResourceSuggestions: Ember.computed.alias(
'mapLocation.hasResourceSuggestions'
),
/**
* @property {boolean}
*/
hasSignatureCollectionSuggestions: Ember.computed.alias(
'mapLocation.hasSignatureCollectionSuggestions'
),
/**
* @property {boolean}
*/
hasSignatureAssessmentSuggestions: Ember.computed.alias(
'mapLocation.hasSignatureAssessmentSuggestions'
),
/**
* @property {boolean}
*/
isDone: Ember.computed('mapLocation.context.status', function() {
return (
(this.get('mapLocation.context.status') || '').toLowerCase() === 'done'
);
}),
/**
* @property {boolean}
*/
hasAnySuggestion: Ember.computed(
'hasBackFillSuggestions',
'hasPostTestSuggestions',
'hasResourceSuggestions',
'hasBenchmarkSuggestions',
'hasSignatureCollectionSuggestions',
'hasSignatureCollectionSuggestions',
'showSuggestion',
function() {
return (
(this.get('hasBackFillSuggestions') ||
this.get('hasPostTestSuggestions') ||
this.get('hasResourceSuggestions') ||
this.get('hasBenchmarkSuggestions') ||
this.get('hasSignatureCollectionSuggestions') ||
this.get('hasSignatureAssessmentSuggestions')) &&
this.get('showSuggestion')
);
}
),
/**
* @property {boolean}
*/
hasBenchmarkSuggestions: Ember.computed.alias(
'mapLocation.hasBenchmarkSuggestions'
),
/**
* @property {String} It decide to show the back to course map or not.
*/
showBackToCourseMap: true,
/**
* confettiTruth for all statisfactions
* @property {boolean} source
*/
enableConfetti: false,
/**
* @property {String} It decide to show the back to collection or not.
*/
showBackToCollection: false,
/**
* Course version Name
* @property {String}
*/
courseVersion: Ember.computed.alias('course.version'),
/**
* Steps for Take a Tour functionality
* @return {Array}
*/
steps: Ember.computed(function() {
let controller = this;
let steps = Ember.A([
{
title: controller
.get('i18n')
.t('gru-take-tour.study-player.stepOne.title'),
description: controller
.get('i18n')
.t('gru-take-tour.study-player.stepOne.description')
},
{
elementSelector: '.header-panel .course-map',
title: controller
.get('i18n')
.t('gru-take-tour.study-player.stepTwo.title'),
description: controller
.get('i18n')
.t('gru-take-tour.study-player.stepTwo.description')
},
{
elementSelector: '.header-panel .content-title',
title: controller
.get('i18n')
.t('gru-take-tour.study-player.stepThree.title'),
description: controller
.get('i18n')
.t('gru-take-tour.study-player.stepThree.description')
},
{
elementSelector: '.header-panel .suggest-player',
title: controller
.get('i18n')
.t('gru-take-tour.study-player.stepFour.title'),
description: controller
.get('i18n')
.t('gru-take-tour.study-player.stepFour.description')
},
{
elementSelector:
'.header-panel .performance-completion-take-tour-info .completion',
title: controller
.get('i18n')
.t('gru-take-tour.study-player.stepFive.title'),
description: controller
.get('i18n')
.t('gru-take-tour.study-player.stepFive.description')
},
{
elementSelector:
'.header-panel .performance-completion-take-tour-info .performance',
title: controller
.get('i18n')
.t('gru-take-tour.study-player.stepSix.title'),
description: controller
.get('i18n')
.t('gru-take-tour.study-player.stepSix.description')
},
{
title: controller
.get('i18n')
.t('gru-take-tour.study-player.stepEight.title'),
description: controller
.get('i18n')
.t('gru-take-tour.study-player.stepEight.description')
}
]);
return steps;
}),
// -------------------------------------------------------------------------
// Methods
/**
* Navigate to study player to play next collection/assessment
*/
toPlayer: function(suggestion) {
const context = this.get('mapLocation.context');
let queryParams = {
role: ROLES.STUDENT,
source: this.get('source')
};
let classId = context.get('classId');
if (classId) {
queryParams.classId = classId;
}
if (suggestion) {
queryParams.courseId = context.courseId;
queryParams.unitId = context.get('unitId');
queryParams.lessonId = context.lessonId;
queryParams.collectionId = suggestion.get('id');
queryParams.pathId = suggestion.pathId;
this.transitionToRoute('study-player', context.get('courseId'), {
queryParams
});
} else {
queryParams.pathId = 0;
this.transitionToRoute('study-player', context.get('courseId'), {
queryParams
});
}
},
/**
* Removing dependency on local storage and bypassing next call when dont have a suggestion
*/
checknPlayNext: function() {
if (this.get('hasAnySuggestion')) {
this.playNextContent();
} else {
const context = this.get('mapLocation.context'); //Already having contex
this.playGivenContent(context);
}
},
playNextContent: function() {
const navigateMapService = this.get('navigateMapService');
const context = this.get('mapLocation.context');
navigateMapService
.next(context)
.then(nextContext => this.playGivenContent(nextContext));
},
playGivenContent: function(mapLocation) {
let status = (mapLocation.get('context.status') || '').toLowerCase();
if (status !== 'done') {
this.toPlayer();
} else {
this.set('mapLocation.context.status', 'done');
this.set('hasBackFillSuggestions', false);
this.set('hasPostTestSuggestions', false);
this.set('hasResourceSuggestions', false);
this.set('hasBenchmarkSuggestions', false);
this.set('hasSignatureCollectionSuggestions', false);
this.set('hasSignatureCollectionSuggestions', false);
}
},
playSuggestedContent: function(suggestion) {
const navigateMapService = this.get('navigateMapService');
const courseMapService = this.get('courseMapService');
navigateMapService
.getStoredNext()
.then(mapstoredloc => {
let mapContext = mapstoredloc.get('context');
var mapcontextloc = mapstoredloc.get('context');
mapContext.ctx_user_id = this.get('session.userId');
mapContext.ctx_class_id = mapContext.classId;
mapContext.ctx_course_id = mapContext.courseId;
mapContext.ctx_lesson_id = mapContext.lessonId;
mapContext.ctx_collection_id = mapContext.collectionId;
mapContext.ctx_unit_id = mapContext.unitId;
mapContext.suggested_content_type = suggestion.type;
mapContext.suggested_content_id = suggestion.id;
mapContext.suggested_content_subtype =
suggestion.subType === 'signature_collection'
? 'signature-collection'
: 'signature-assessment';
return Ember.RSVP.hash({
context: mapcontextloc,
pathId: courseMapService.addSuggestedPath(mapContext)
});
})
.then(({ context, pathId }) => {
context.collectionId = suggestion.id; // Setting new collection id
context.pathId = pathId;
suggestion.pathId = pathId;
return navigateMapService.startAlternatePathSuggestion(context);
})
.then(() => this.toPlayer(suggestion));
},
/**
* Resets to default values
*/
resetValues: function() {
this.setProperties({
courseId: null,
userId: null,
role: null,
contextId: null,
source: null,
classId: '',
unitId: null,
lessonId: null,
collectionId: null,
type: null
});
}
});
|
351ELEC/lzdoom | src/posix/sdl/sdlglvideo.h | #ifndef __SDLGLVIDEO_H__
#define __SDLGLVIDEO_H__
#include "hardware.h"
#include "v_video.h"
#include <SDL.h>
#include "gl/system/gl_system.h"
EXTERN_CVAR (Float, dimamount)
EXTERN_CVAR (Color, dimcolor)
struct FRenderer;
FRenderer *gl_CreateInterface();
class SDLGLVideo : public IVideo
{
public:
SDLGLVideo (int parm);
~SDLGLVideo ();
EDisplayType GetDisplayType () { return DISPLAY_Both; }
void SetWindowedScale (float scale);
DFrameBuffer *CreateFrameBuffer (int width, int height, bool bgra, bool fs, DFrameBuffer *old);
void StartModeIterator (int bits, bool fs);
bool NextMode (int *width, int *height, bool *letterbox);
bool SetResolution (int width, int height, int bits);
void SetupPixelFormat(bool allowsoftware, int multisample, const int *glver);
private:
int IteratorMode;
int IteratorBits;
};
class SDLBaseFB : public DFrameBuffer
{
typedef DFrameBuffer Super;
public:
using DFrameBuffer::DFrameBuffer;
virtual SDL_Window *GetSDLWindow() = 0;
friend class SDLGLVideo;
};
class SDLGLFB : public SDLBaseFB
{
typedef SDLBaseFB Super;
public:
// this must have the same parameters as the Windows version, even if they are not used!
SDLGLFB (void *hMonitor, int width, int height, int, int, bool fullscreen, bool bgra);
~SDLGLFB ();
void ForceBuffering (bool force);
bool Lock(bool buffered);
bool Lock ();
void Unlock();
bool IsLocked ();
bool IsValid ();
bool IsFullscreen ();
virtual void SetVSync( bool vsync );
void SwapBuffers();
void NewRefreshRate ();
friend class SDLGLVideo;
int GetClientWidth() override;
int GetClientHeight() override;
virtual void ScaleCoordsFromWindow(int16_t &x, int16_t &y);
SDL_Window *GetSDLWindow() override { return Screen; }
virtual int GetTrueHeight() { return GetClientHeight(); }
protected:
void SetGammaTable(uint16_t *tbl);
void ResetGammaTable();
void InitializeState();
SDLGLFB () {}
uint8_t GammaTable[3][256];
bool UpdatePending;
SDL_Window *Screen;
SDL_GLContext GLContext;
void UpdateColors ();
int m_Lock;
Uint16 m_origGamma[3][256];
bool m_supportsGamma;
};
#endif
|
fernandogar92/javaee8-samples | cdi/interception-factory/src/main/java/org/javaee8/cdi/interception/factory/MyGreetingProducer.java | package org.javaee8.cdi.interception.factory;
import java.util.logging.Logger;
import javax.annotation.Priority;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Alternative;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InterceptionFactory;
@Alternative
@Priority(500)
@ApplicationScoped
public class MyGreetingProducer {
private static final Logger logger = Logger.getLogger(MyGreetingProducer.class.getName());
/**
* This producer produces a MyGreeting alternative for MyGreetingImpl.
* <p>
* Note that the alternative is set by making the class, not the method, an
* alternative.The alternative is activated via the <code>@Priority</code> annotation.
*
* @param interceptionFactory InterceptionFactory injected by CDI
* @return MyGreeting instance, programmatically proxied
*/
@Produces
public MyGreeting produce(InterceptionFactory<MyGreetingImpl> interceptionFactory) {
logger.info("Producing a MyGreeting");
// We're telling the InterceptionFactory here to dynamically add the @HelloAdder
// annotation.
interceptionFactory.configure().add(HelloAdder.Literal.INSTANCE);
// This will create a proxy as configured above around the bare
// instance of MyGreetingImpl that we provide.
return interceptionFactory.createInterceptedInstance(new MyGreetingImpl());
}
}
|
dhiltgen/stacks-1 | pkg/client/stack_create.go | package client
import (
"context"
"encoding/json"
"github.com/docker/stacks/pkg/types"
)
// StackCreate creates a new Stack
func (cli *Client) StackCreate(ctx context.Context, stack types.StackCreate, options types.StackCreateOptions) (types.StackCreateResponse, error) {
headers := map[string][]string{
"version": {cli.settings.Version},
}
if options.EncodedRegistryAuth != "" {
headers["X-Registry-Auth"] = []string{options.EncodedRegistryAuth}
}
var response types.StackCreateResponse
resp, err := cli.post(ctx, "/stacks", nil, stack, headers)
if err != nil {
return response, err
}
err = json.NewDecoder(resp.body).Decode(&response)
ensureReaderClosed(resp)
return response, err
}
|
RampNetwork/torus-website | app/src/store/PaymentActions/simplex.js | <filename>app/src/store/PaymentActions/simplex.js
import log from 'loglevel'
import { postQuote, postOrder } from '../../plugins/simplex'
import config from '../../config'
import { broadcastChannelOptions } from '../../utils/utils'
import PopupHandler from '../../utils/PopupHandler'
import { SIMPLEX } from '../../utils/enums'
import { BroadcastChannel } from 'broadcast-channel'
import torus from '../../torus'
const randomId = require('random-id')
export default {
fetchSimplexQuote({ state }, payload) {
// returns a promise
return postQuote(
{
digital_currency: payload.selectedCryptoCurrency,
fiat_currency: payload.selectedCurrency,
requested_currency: payload.selectedCurrency,
requested_amount: +parseFloat(payload.fiatValue)
},
{
Authorization: `Bearer ${state.jwtToken}`
}
)
},
fetchSimplexOrder({ state, dispatch }, payload) {
let preopenInstanceId = payload.preopenInstanceId
if (!preopenInstanceId) {
preopenInstanceId = randomId()
const finalUrl = config.baseUrl + `/redirect?preopenInstanceId=${preopenInstanceId}`
const handledWindow = new PopupHandler({ url: finalUrl, target: 'form-target' })
handledWindow.open()
handledWindow.once('close', () => {
throw new Error('user closed simplex popup')
})
}
const instanceState = encodeURIComponent(
window.btoa(
JSON.stringify({
instanceId: torus.instanceId,
provider: SIMPLEX
})
)
)
return postOrder(
{
'g-recaptcha-response': '',
account_details: {
app_end_user_id: payload.currentOrder.user_id
},
return_url: `${config.redirect_uri}?state=${instanceState}`,
transaction_details: {
payment_details: {
fiat_total_amount: {
currency: payload.currentOrder.fiat_money.currency,
amount: payload.currentOrder.fiat_money.total_amount
},
requested_digital_amount: {
currency: payload.currentOrder.digital_money.currency,
amount: payload.currentOrder.digital_money.amount
},
destination_wallet: {
currency: payload.currentOrder.digital_money.currency,
address: state.selectedAddress
}
}
}
},
{
Authorization: `Bearer ${state.jwtToken}`
}
).then(result => {
const {
version,
partner,
return_url,
quote_id,
payment_id,
user_id,
destination_wallet_address,
destination_wallet_currency,
fiat_total_amount_amount,
fiat_total_amount_currency,
digital_total_amount_amount,
digital_total_amount_currency,
payment_post_url
} = result.result
return dispatch('postSimplexOrder', {
preopenInstanceId,
path: payment_post_url,
params: {
payment_flow_type: 'wallet',
version,
partner,
return_url,
quote_id,
payment_id,
user_id,
'destination_wallet[address]': destination_wallet_address,
'destination_wallet[currency]': destination_wallet_currency,
'fiat_total_amount[amount]': fiat_total_amount_amount,
'fiat_total_amount[currency]': fiat_total_amount_currency,
'digital_total_amount[amount]': digital_total_amount_amount,
'digital_total_amount[currency]': digital_total_amount_currency
}
})
})
},
postSimplexOrder(context, { path, params, method = 'post', preopenInstanceId }) {
return new Promise((resolve, reject) => {
const form = document.createElement('form')
form.method = method
form.action = path
form.target = 'form-target'
for (const key in params) {
if (params.hasOwnProperty(key)) {
const hiddenField = document.createElement('input')
hiddenField.type = 'hidden'
hiddenField.name = key
hiddenField.value = params[key]
form.appendChild(hiddenField)
}
}
document.body.appendChild(form)
// Handle communication with simplex window here
const simplexWindow = new PopupHandler({ url: 'about:blank', target: 'form-target', features: 'width=1200, height=700', preopenInstanceId })
const bc = new BroadcastChannel(`redirect_channel_${torus.instanceId}`, broadcastChannelOptions)
bc.onmessage = ev => {
try {
const {
instanceParams: { provider }
} = ev.data || {}
if (ev.error && ev.error !== '') {
log.error(ev.error)
reject(new Error(ev.error))
} else if (ev.data && provider === SIMPLEX) {
resolve({ success: true })
}
} catch (error) {
reject(error)
} finally {
bc.close()
simplexWindow.close()
}
}
simplexWindow.open()
form.submit()
simplexWindow.once('close', () => {
bc.close()
reject(new Error('user closed simplex popup'))
})
})
}
}
|
lucvoo/log2c | src/pl-Smem.c | <reponame>lucvoo/log2c
/************************************************************************/
/* Copyright (c) 1998-2014 <NAME>. All rights reserved. */
/* */
/* %@%LICENSE */
/* */
/************************************************************************/
#include "pl-stream_impl.h"
/**************/
/* Write only */
/**************/
char *Sstring_wmem(struct stream *S)
{
Sputc(S, '\0');
Sflush(S);
return PL_base_ubs(S->hndl.ubs);
}
static int Swrite_wmem(union stream_handle hndl, const void *s, int n)
{
PL_add_x_ubs(hndl.ubs, s, n);
return n;
}
static int Sclose_wmem(struct stream *S)
{
PL_free_ubs(S->hndl.ubs);
free(S->hndl.ubs);
return 0;
}
static struct stream_ops wmem_ops = {
.write = Swrite_wmem,
.close = Sclose_wmem,
};
struct stream *Sopen_wmem(const char *buf, enum stream_mode mode, int flags)
{
struct stream *S;
struct ubuffer *ubs;
if (mode != SM_WRITE) { // FIXME : errmsg
return 0;
}
if (!(S = Snew_stream())) { // FIXME : errmsg
return 0;
}
ubs = malloc(sizeof(struct ubuffer));
if (!ubs) { // FIXME : errmsg
return 0;
} else {
PL_init_ubs(ubs);
}
if (flags & SF_RECPOS) {
S->pos.char_no = 0;
S->pos.line_no = 1;
S->pos.col_no = 0;
}
S->type = ST_WMEM;
S->mode = mode;
S->ops = &wmem_ops;
if (!S_setbuf(S, 0, 248, SF_FBUF))
return 0;
S->hndl.ubs = ubs;
S->flags = flags;
return S;
}
/*************/
/* Read only */
/*************/
static int Sread_rmem(union stream_handle hndl, void *s, int n)
{
return 0;
}
static int Sclose_rmem(struct stream *S)
{
return 0;
}
static struct stream_ops rmem_ops = {
.read = Sread_rmem,
.close = Sclose_rmem,
};
struct stream *Sopen_rmem(const char *buf, enum stream_mode mode, int flags)
{
struct stream *S;
if (!(S = Snew_stream())) { // FIXME : errmsg
return 0;
}
if (!buf) { // FIXME : errmsg
return 0;
}
if (flags & SF_RECPOS) {
S->pos.char_no = 0;
S->pos.line_no = 1;
S->pos.col_no = 0;
}
S->type = ST_RMEM;
S->mode = mode;
S->ops = &rmem_ops;
{
int size = 0;
const char *ptr = buf;
while (*ptr++)
size++; // This is strlen()
if (!S_setbuf(S, (char *)buf, size, SF_FBUF))
return 0;
flags |= SF_STATIC;
}
S->hndl.fd = -1;
S->flags = flags;
return S;
}
|
bg1bgst333/Sample | c/pipeline/pipeline/src/pipeline/dest.c | /* ヘッダファイルのインクルード */
#include <stdio.h> /* 標準入出力 */
#include <string.h> /* 文字列処理 */
/* main関数 */
int main(void){
/* 配列の宣言 */
char buf[256]; /* char型文字配列buf(長さ256) */
/* 文字列の受け取り */
fgets(buf, 256, stdin); /* fgetsでstdinから文字列を受け取る. */
/* 改行の除去 */
if (buf[strlen(buf) - 1] == '\n'){ /* 末尾が'\n'なら. */
buf[strlen(buf) - 1] = '\0'; /* 末尾を'\0'にする. */
}
/* bufの出力 */
printf("-----dest start-----\n"); /* 開始 */
printf("%s\n", buf); /* bufを出力. */
printf("-----dest end-----\n"); /* 終了 */
/* プログラムの終了 */
return 0; /* 正常終了 */
}
|
leobert-lan/Android_Bean_Validator | inspector_base/src/main/java/osp/leobert/android/inspector/Inspector.java | package osp.leobert.android.inspector;
import javax.annotation.Nullable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import osp.leobert.android.inspector.notations.GenerateValidator;
import osp.leobert.android.inspector.notations.ValidationQualifier;
import osp.leobert.android.inspector.validators.Validator;
import osp.leobert.android.inspector.validators.ArrayValidator;
import osp.leobert.android.inspector.validators.ClassValidator;
import osp.leobert.android.inspector.validators.CollectionValidator;
import osp.leobert.android.inspector.validators.MapValidator;
import osp.leobert.android.inspector.validators.StandardValidators;
public final class Inspector {
private static final List<Validator.Factory> BUILT_IN_FACTORIES = new ArrayList<>(5);
static {
BUILT_IN_FACTORIES.add(StandardValidators.FACTORY);
BUILT_IN_FACTORIES.add(CollectionValidator.FACTORY);
BUILT_IN_FACTORIES.add(MapValidator.FACTORY);
BUILT_IN_FACTORIES.add(ArrayValidator.FACTORY);
BUILT_IN_FACTORIES.add(SelfValidating.FACTORY);
BUILT_IN_FACTORIES.add(ClassValidator.FACTORY);
}
private static Inspector sDefaultInspector;
public static Inspector getDefault() {
if (sDefaultInspector == null) {
synchronized (Inspector.class) {
if (sDefaultInspector == null) {
sDefaultInspector = new Inspector.Builder()
.add(GenerateValidator.FACTORY)
.build();
}
}
}
return sDefaultInspector;
}
@SuppressWarnings("ThreadLocalUsage")
private final ThreadLocal<List<DeferredAdapter<?>>> reentrantCalls = new ThreadLocal<>();
private final List<Validator.Factory> factories;
private final Map<Object, Validator<?>> adapterCache = new LinkedHashMap<>();
Inspector(Builder builder) {
List<Validator.Factory> factories =
new ArrayList<>(builder.factories.size() + BUILT_IN_FACTORIES.size());
factories.addAll(builder.factories);
factories.addAll(BUILT_IN_FACTORIES);
this.factories = Collections.unmodifiableList(factories);
}
/*
* Returns a Validator for {@code type}, creating it if necessary.
*/
public <T> Validator<T> validator(Type type) {
return validator(type, Util.NO_ANNOTATIONS);
}
/*
* Returns a Validator for {@code type}, creating it if necessary.
*/
public <T> Validator<T> validator(Class<T> type) {
return validator(type, Util.NO_ANNOTATIONS);
}
/*
* Returns a Validator for {@code type} with {@code annotationType}, creating it if necessary.
*/
public <T> Validator<T> validator(Type type, Class<? extends Annotation> annotationType) {
return validator(type,
Collections.singleton(Types.createValidationQualifierImplementation(annotationType)));
}
/*
* Returns a Validator for {@code type} and {@code annotations}, creating it if necessary.
*/
@SuppressWarnings("unchecked") // Factories are required to return only matching Validators.
public <T> Validator<T> validator(Type type, Set<? extends Annotation> annotations) {
type = Types.canonicalize(type);
// If there's an equivalent adapter in the cache, we're done!
Object cacheKey = cacheKey(type, annotations);
synchronized (adapterCache) {
Validator<?> result = adapterCache.get(cacheKey);
if (result != null) return (Validator<T>) result;
}
// Short-circuit if this is a reentrant call.
List<DeferredAdapter<?>> deferredAdapters = reentrantCalls.get();
if (deferredAdapters != null) {
for (DeferredAdapter<?> deferredAdapter : deferredAdapters) {
if (deferredAdapter.cacheKey == null) {
// not ready
continue;
}
if (deferredAdapter.cacheKey.equals(cacheKey)) {
return (Validator<T>) deferredAdapter;
}
}
} else {
deferredAdapters = new ArrayList<>();
reentrantCalls.set(deferredAdapters);
}
// Prepare for re-entrant calls, then ask each factory to create a type adapter.
DeferredAdapter<T> deferredAdapter = new DeferredAdapter<>(cacheKey);
deferredAdapters.add(deferredAdapter);
try {
for (Validator.Factory factory : factories) {
Validator<T> result = (Validator<T>) factory.create(type, annotations, this);
if (result != null) {
deferredAdapter.ready(result);
synchronized (adapterCache) {
adapterCache.put(cacheKey, result);
}
return result;
}
}
} finally {
deferredAdapters.remove(deferredAdapters.size() - 1);
if (deferredAdapters.isEmpty()) {
reentrantCalls.remove();
}
}
throw new IllegalArgumentException("No Validator for " + type + " annotated " + annotations);
}
/*
* Returns a Validator for {@code type} and {@code annotations}, always creating a new one and
* skipping past {@code skipPast} for creation.
*/
@SuppressWarnings("unchecked") // Factories are required to return only matching Validators.
public <T> Validator<T> nextValidator(Validator.Factory skipPast,
Type type,
Set<? extends Annotation> annotations) {
type = Types.canonicalize(type);
int skipPastIndex = factories.indexOf(skipPast);
if (skipPastIndex == -1) {
throw new IllegalArgumentException("Unable to skip past unknown factory " + skipPast);
}
for (int i = skipPastIndex + 1, size = factories.size(); i < size; i++) {
Validator<T> result = (Validator<T>) factories.get(i)
.create(type, annotations, this);
if (result != null) return result;
}
throw new IllegalArgumentException("No next Validator for "
+ type
+ " annotated "
+ annotations);
}
/*
* Returns a new builder containing all custom factories used by the current instance.
*/
public Inspector.Builder newBuilder() {
int fullSize = factories.size();
int tailSize = BUILT_IN_FACTORIES.size();
List<Validator.Factory> customFactories = factories.subList(0, fullSize - tailSize);
return new Builder().addAll(customFactories);
}
/*
* Returns an opaque object that's equal if the type and annotations are equal.
*/
private Object cacheKey(Type type, Set<? extends Annotation> annotations) {
if (annotations.isEmpty()) return type;
return Arrays.asList(type, annotations);
}
public static final class Builder {
final List<Validator.Factory> factories = new ArrayList<>();
public <T> Builder add(final Type type, final Validator<T> Validator) {
if (type == null) throw new IllegalArgumentException("type == null");
if (Validator == null) throw new IllegalArgumentException("Validator == null");
return add(new Validator.Factory() {
@Override
public @Nullable
Validator<?> create(Type targetType,
Set<? extends Annotation> annotations,
Inspector inspector) {
return annotations.isEmpty() && Util.typesMatch(type, targetType) ? Validator : null;
}
});
}
public <T> Builder add(final Type type,
final Class<? extends Annotation> annotation,
final Validator<T> Validator) {
if (type == null) throw new IllegalArgumentException("type == null");
if (annotation == null) throw new IllegalArgumentException("annotation == null");
if (Validator == null) throw new IllegalArgumentException("Validator == null");
if (!annotation.isAnnotationPresent(ValidationQualifier.class)) {
throw new IllegalArgumentException(annotation + " does not have @ValidationQualifier");
}
if (annotation.getDeclaredMethods().length > 0) {
throw new IllegalArgumentException("Use Validator.Factory for annotations with elements");
}
return add(new Validator.Factory() {
@Override
public @Nullable
Validator<?> create(Type targetType,
Set<? extends Annotation> annotations,
Inspector inspector) {
if (Util.typesMatch(type, targetType)
&& annotations.size() == 1
&& Util.isAnnotationPresent(annotations, annotation)) {
return Validator;
}
return null;
}
});
}
public Builder add(Validator.Factory factory) {
if (factory == null) throw new IllegalArgumentException("factory == null");
factories.add(factory);
return this;
}
Builder addAll(List<Validator.Factory> factories) {
this.factories.addAll(factories);
return this;
}
public Inspector build() {
return new Inspector(this);
}
}
/*
* Sometimes a type adapter factory depends on its own product; either directly or indirectly.
* To make this work, we offer this type adapter stub while the final adapter is being computed.
* When it is ready, we wire this to delegate to that finished adapter.
* <p>
* <p>Typically this is necessary in self-referential object models, such as an {@code Employee}
* class that has a {@code List<Employee>} field for an organization's management hierarchy.
*/
private static class DeferredAdapter<T> extends Validator<T> {
@Nullable
Object cacheKey;
@Nullable
private Validator<T> delegate;
DeferredAdapter(Object cacheKey) {
this.cacheKey = cacheKey;
}
void ready(Validator<T> delegate) {
this.delegate = delegate;
this.cacheKey = null;
}
@Override
public void validate(T validationTarget) throws ValidationException {
if (delegate == null) throw new IllegalStateException("Validator isn't ready");
delegate.validate(validationTarget);
}
}
}
|
whoisje/airdrop-react | src/common/model/graph-core.js | import {Graph} from '@antv/x6'
import {BehaviorSubject, fromEventPattern, merge} from 'rxjs'
import {debounceTime, map, scan, tap} from 'rxjs/operators'
import './graph-core.css'
function setCellsSelectedStatus(cells, selected) {
cells.forEach((cell) => {
const data = cell.getData() || {}
cell.setData({...data, selected})
})
}
export class GraphCore {
wrapper
container
nodeMetas // 传入的 nodes 原始信息
edgeMetas // 传入的 edges 原始信息
options
graph
// 当前画布右键点击信息
contextMenuInfo$ = new BehaviorSubject(
null,
)
// 选中的节点
selectedNodes$ = new BehaviorSubject([])
// 待复制的节点 id
copyableNodeId$ = new BehaviorSubject('')
// 窗口大小 resize 的订阅
windowResizeSub
// 右键菜单的订阅
contextMenuSub
// 节点右键菜单的订阅
nodeContextMenuSub
// 选中节点的订阅
selectNodeSub
// 产生连线的订阅
connectNodeSub
// 连线已删除的订阅
connectionRemovedSub
// 节点移动的订阅
moveNodesSub
// 删除节点或连线的订阅
deleteNodeOrEdgeSub
// 复制节点的订阅
copyNodeSub
constructor(options) {
const {wrapper, container, nodes, edges, ...others} = options
this.setMeta(options)
this.options = others
}
get isMetaValid() {
const {wrapper, container, nodeMetas, edgeMetas} = this
return !!wrapper && !!container && !!nodeMetas && !!edgeMetas
}
get nodes() {
return (this.graph.getNodes() || [])
}
setMeta(params) {
const {wrapper, container, nodes, edges} = params
if (wrapper) {
this.setWrapper(wrapper)
}
if (container) {
this.setContainer(container)
}
if (nodes) {
this.setNodes(nodes)
}
if (edges) {
this.setEdges(edges)
}
}
setWrapper(wrapper) {
this.wrapper = wrapper
}
setContainer(container) {
this.container = container
this.options.container = container
}
setNodes(nodes) {
this.nodeMetas = nodes
}
setEdges(edges) {
this.edgeMetas = edges
}
// 渲染
render(params) {
this.setMeta(params)
if (this.isMetaValid) {
const {wrapper, options, nodeMetas, edgeMetas} = this
const width = wrapper.clientWidth
const height = wrapper.clientHeight
const graph = new Graph({...options, width, height})
this.graph = graph
nodeMetas.forEach((nodeMeta) => this.renderNode(nodeMeta))
edgeMetas.forEach((edgeMeta) => this.renderEdge(edgeMeta))
this.afterLayout()
if (graph.isFrozen()) {
graph.unfreeze()
}
requestAnimationFrame(() => {
graph.centerContent()
})
// 处理窗口缩放
this.windowResizeSub = fromEventPattern(
(handler) => {
window.addEventListener('resize', handler)
},
(handler) => {
window.removeEventListener('resize', handler)
},
).subscribe(this.resizeGraph)
// 处理右键菜单
const nodeContextMenuObs = fromEventPattern(
(handler) => {
graph.on('node:contextmenu', (data) => {
handler({type: 'node', data})
})
},
(handler) => {
graph.off('node:contextmenu', handler)
},
)
const edgeContextMenuObs = fromEventPattern(
(handler) => {
graph.on('edge:contextmenu', (data) => {
handler({type: 'edge', data})
})
},
(handler) => {
graph.off('edge:contextmenu', handler)
},
)
const graphContextMenuObs = fromEventPattern(
(handler) => {
graph.on('blank:contextmenu', (data) => {
handler({type: 'graph', data})
})
},
(handler) => {
graph.off('edge:contextmenu', handler)
},
)
this.nodeContextMenuSub = nodeContextMenuObs.subscribe((data) => {
this.onNodeContextMenu(data)
})
this.contextMenuSub = merge(
nodeContextMenuObs,
edgeContextMenuObs,
graphContextMenuObs,
).subscribe((data) => {
if (this.validateContextMenu(data)) {
this.contextMenuInfo$.next(data)
this.onContextMenu(data)
}
})
// 处理节点选中事件
this.selectNodeSub = fromEventPattern(
(handler) => {
graph.on('selection:changed', handler)
},
(handler) => {
graph.off('selection:changed', handler)
},
).subscribe((args) => {
const {removed, selected} = args
setCellsSelectedStatus(removed, false)
setCellsSelectedStatus(selected, true)
this.onSelectNodes(selected)
})
// 处理产生连线事件
this.connectNodeSub = fromEventPattern(
(handler) => {
graph.on('edge:connected', handler)
},
(handler) => {
graph.off('edge:connected', handler)
},
).subscribe((args) => {
this.onConnectNode(args)
})
// 处理连线删除事件
this.connectionRemovedSub = fromEventPattern(
(handler) => {
graph.on('edge:removed', handler)
},
(handler) => {
graph.off('edge:removed', handler)
},
// eslint-disable-next-line consistent-return
).subscribe((args) => {
this.onConnectionRemoved(args)
})
// 处理节点移动事件
let moveStarted = false // 因为需要对移动事件做分片,区分两次移动事件,所以引入一个记录移动开始的变量
this.moveNodesSub = fromEventPattern(
(handler) => {
graph.on('node:change:position', handler)
},
(handler) => {
graph.off('node:change:position', handler)
},
)
.pipe(
tap((args) => {
this.onMoveNodeStart(args)
}),
scan((accum, args) => {
const currentAccum = !moveStarted ? [] : accum
const {node} = args
const {id} = node
const matchItemIndex = currentAccum.findIndex(
(item) => item.id === id,
)
if (matchItemIndex > -1) {
currentAccum.splice(matchItemIndex, 1, {id, data: args})
} else {
currentAccum.push({id, data: args})
}
return currentAccum
}, []),
tap(() => {
if (!moveStarted) {
moveStarted = true
}
}),
debounceTime(300),
tap(() => {
if (moveStarted) {
moveStarted = false
}
}),
map((items) => items.map((item) => item.data)),
)
.subscribe((movedNodes) => {
this.onMoveNodes(movedNodes)
})
// 处理删除节点或连线事件
this.deleteNodeOrEdgeSub = fromEventPattern(
(handler) => {
graph.bindKey(['delete', 'backspace'], handler)
},
() => {
graph.unbindKey(['delete', 'backspace'])
},
).subscribe(() => {
const selectedCells = graph.getSelectedCells()
const selectedNodes = selectedCells.filter((cell) =>
cell.isNode(),
)
const selectedEdges = selectedCells.filter((cell) =>
cell.isEdge(),
)
this.onDeleteNodeOrEdge({nodes: selectedNodes, edges: selectedEdges})
})
// 处理节点复制事件
this.copyNodeSub = fromEventPattern(
(handler) => {
graph.bindKey(['command+c', 'ctrl+c', 'command+v', 'ctrl+v'], handler)
},
() => {
graph.unbindKey(['command+c', 'ctrl+c', 'command+v', 'ctrl+v'])
},
).subscribe((args) => {
const [, action] = args
const selectedCells = (graph.getSelectedCells()).filter(
(cell) => this.validateNodeCopyable(cell),
)
const copyableNodeId = this.copyableNodeId$.getValue()
let copyableNode
if (copyableNodeId) {
copyableNode = graph.getCellById(copyableNodeId)
}
switch (action) {
case 'command+c':
case 'ctrl+c':
if (selectedCells.length) {
this.setCopyableNodeId(selectedCells[0].id) // 当前只支持单节点的复制粘贴
}
break
case 'command+v':
case 'ctrl+v':
// @ts-ignore
if (copyableNode) {
this.onCopyNode(copyableNode)
}
break
default:
}
})
} else {
this.throwRenderError()
}
}
renderNode(nodeMeta) {
return this.graph.addNode(nodeMeta)
}
renderEdge(edgeMeta) {
return this.graph.addEdge(edgeMeta)
}
afterLayout() {
if (process.env.NODE_ENV === 'development') {
console.log('[GraphCore] call afterLayout')
}
}
resizeGraph = () => {
const {graph, wrapper} = this
if (graph && wrapper) {
requestAnimationFrame(() => {
const width = wrapper.clientWidth
const height = wrapper.clientHeight
graph.resize(width, height)
})
}
}
validateContextMenu(data) {
return !!data
}
onContextMenu(data) {
if (process.env.NODE_ENV === 'development') {
console.log('[GraphCore] context menu info:', data)
}
}
onNodeContextMenu(data) {
if (process.env.NODE_ENV === 'development') {
console.log('[GraphCore] context menu info:', data)
}
}
onSelectNodes(nodes) {
this.selectedNodes$.next(nodes)
if (process.env.NODE_ENV === 'development') {
console.log('[GraphCore] select nodes:', nodes)
}
}
onConnectNode(args) {
if (process.env.NODE_ENV === 'development') {
console.log('[GraphCore] connect node:', args)
}
}
onConnectionRemoved(args) {
if (process.env.NODE_ENV === 'development') {
console.log('[GraphCore] delete connection:', args)
}
}
onMoveNodeStart(args) {
if (process.env.NODE_ENV === 'development') {
console.log('[GraphCore] move node start:', args)
}
}
onMoveNodes(args) {
if (process.env.NODE_ENV === 'development') {
console.log('[GraphCore] move nodes:', args)
}
}
// 按下删除键的回调,默认参数为当前选中的节点和边
onDeleteNodeOrEdge(args) {
if (process.env.NODE_ENV === 'development') {
console.log('[GraphCore] delete node or edge:', args)
}
}
// 校验节点是否可复制,为 true 则可被用于复制
validateNodeCopyable(node) {
if (process.env.NODE_ENV === 'development') {
console.log('[GraphCore] validate node copyable:', node)
}
return true
}
// 按下粘贴键的回调,默认参数为待复制的节点
onCopyNode(copyNode) {
if (process.env.NODE_ENV === 'development') {
console.log('[GraphCore] copy node:', copyNode)
}
}
/* 以下为主动触发的方法 */
addNode = (nodeMeta) => {
this.nodeMetas.push(nodeMeta)
return this.renderNode(nodeMeta)
}
addEdge = (edgeMeta) => {
this.edgeMetas.push(edgeMeta)
return this.renderEdge(edgeMeta)
}
getNodeById = (nodeId) => {
const node = this.graph.getCellById(nodeId)
if (node.isNode()) {
return node
}
return undefined
}
getNodes = () => {
return (this.graph.getNodes()) || []
}
getEdgeById = (nodeId) => {
const edge = this.graph.getCellById(nodeId)
if (edge.isEdge()) {
return edge
}
return undefined
}
getEdges = () => {
return (this.graph.getEdges()) || []
}
getCellById = (cellId) => {
const cell = this.graph.getCellById(cellId)
if (cell.isNode() || cell.isEdge()) {
return cell
}
return undefined
}
getCells = () => {
return (this.graph.getCells()) || []
}
updateNodeById = (nodeId, handler) => {
handler(this.getNodeById(nodeId))
}
updateNodes = (handler) => {
handler(this.getNodes())
}
updateEdgeById = (edgeId, handler) => {
const edge = this.graph.getCellById(edgeId)
if (edge.isEdge()) {
handler(edge)
} else {
handler(undefined)
}
}
updateEdges = (handler) => {
const edges = (this.graph.getEdges()) || []
handler(edges)
}
// 删除节点
deleteNodes = (nodes) => {
const target = [].concat(nodes)
// @ts-ignore
this.nodeMetas = this.nodeMetas.filter(
(nodeMeta) => !target.includes(nodeMeta.id),
)
this.graph.removeCells(target)
}
// 删除边
deleteEdges = (edges) => {
const target = [].concat(edges)
const targetIds = target.map((i) => (typeof i === 'string' ? i : i.id))
// @ts-ignore
this.edgeMetas = this.edgeMetas.filter(
(edgeMeta) => !targetIds.includes(edgeMeta.id),
)
this.graph.removeCells(target)
}
// 清空右键菜单信息
clearContextMenuInfo = () => {
this.contextMenuInfo$.next(null)
}
// 缩放画布
zoom = (factor) => {
if (typeof factor === 'number') {
this.graph.zoom(factor)
} else if (factor === 'fit') {
this.graph.zoomToFit({padding: 12})
} else if (factor === 'real') {
this.graph.scale(1)
this.graph.centerContent()
}
}
// 切换可框选模式
toggleSelectionEnabled = (enabled) => {
const {graph} = this
if (graph) {
const needEnableRubberBand =
typeof enabled === 'undefined' ? !graph.isRubberbandEnabled() : enabled
if (needEnableRubberBand) {
graph.enableRubberband()
// graph.scroller.widget.setCursor('crosshair', { silent: true })
} else {
graph.disableRubberband()
// graph.scroller.widget.setCursor('grab', { silent: true })
}
}
}
// 选中节点
selectNodes = (ids) => {
const {graph} = this
if (graph) {
const target = [].concat(ids).map((i) => i.toString())
graph.cleanSelection()
graph.select(target)
if (!Array.isArray(ids)) {
const cell = graph.getCellById(ids)
graph.scrollToCell(cell)
}
}
}
// 清除选中节点
unSelectNode = () => {
const {graph} = this
if (graph) {
graph.cleanSelection()
}
}
// redo
redo = () => {
const {graph} = this
if (graph) {
graph.redo()
}
}
// undo
undo = () => {
const {graph} = this
if (graph) {
graph.undo()
}
}
// 设置待复制的节点 id
setCopyableNodeId = (id) => {
this.copyableNodeId$.next(id)
}
// 抛出渲染中遇到的阻断
throwRenderError = () => {
if (!this.wrapper) {
throw new Error('Wrapper element is needed.')
}
if (!this.container) {
throw new Error('Container element is needed.')
}
if (!this.nodeMetas) {
throw new Error('NodeMetas could not be empty')
}
if (!this.edgeMetas) {
throw new Error('EdgeMetas could not be empty')
}
}
// 注销
dispose() {
this.windowResizeSub.unsubscribe()
this.contextMenuSub.unsubscribe()
this.nodeContextMenuSub.unsubscribe()
this.selectNodeSub.unsubscribe()
this.connectNodeSub.unsubscribe()
this.connectionRemovedSub.unsubscribe()
this.moveNodesSub.unsubscribe()
this.deleteNodeOrEdgeSub.unsubscribe()
this.copyNodeSub.unsubscribe()
// ! 这一步要注意放在图的事件订阅都取消了之后
if (this.wrapper) {
const graphScroller = this.wrapper.querySelector('.x6-graph-scroller')
if (graphScroller) {
graphScroller.innerHTML = ''
graphScroller.setAttribute('style', '')
graphScroller.setAttribute('class', '')
if (this.container) {
this.container.innerHTML = ''
this.container.setAttribute('style', '')
this.container.setAttribute('class', '')
}
}
this.graph.dispose()
}
}
}
|
bopopescu/ServerStatus | resources/lib/IMDbPY/bin/topbottom4local.py | <filename>resources/lib/IMDbPY/bin/topbottom4local.py<gh_stars>0
#!/usr/bin/env python
"""
topbottom4local.py script.
This script creates some files to access top 250/bottom 10 information
from the 'local' data access system.
Copyright 2009 <NAME> <<EMAIL>>
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.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""
import os
import sys
import gzip
import shelve
HELP = """topbottom4local.py usage:
%s /directory/with/plain/text/data/files/ /directory/with/local/files/
# NOTE: you need read and write access to the second directory.
""" % sys.argv[0]
if len(sys.argv) != 3:
print 'Specify both source and target directories!'
print HELP
sys.exit(1)
# Directory containing the IMDb's Plain Text Data Files.
IMDB_PTDF_DIR = sys.argv[1]
LOCAL_DATA_DIR = sys.argv[2]
beforeTop = 'TOP 250 MOVIES'
beforeBottom = 'BOTTOM 10 MOVIES'
beforeList = 'New'
def getIDs(keyFile):
"""Return a dictionary mapping values to IDs, as taken from a .key
plain text data file."""
theDict = {}
dataF = open(keyFile, 'r')
for line in dataF:
lsplit = line.split('|')
if len(lsplit) != 2:
continue
data, idHex = lsplit
theDict[data] = int(idHex, 16)
dataF.close()
return theDict
def toBin3(v):
"""Return a string (little-endian) from a numeric value."""
return '%s%s%s' % (chr(v & 255), chr((v >> 8) & 255), chr((v >> 16) & 255))
print 'Reading titles.key...',
sys.stdout.flush()
MOVIEIDS = getIDs(os.path.join(LOCAL_DATA_DIR, 'titles.key'))
print 'DONE!'
def manageLine(l):
"""Extract information from a single line of the lists."""
ls = filter(None, l.split(' '))
if len(ls) != 4:
return None
distrib, votes, rating, title = ls
distrib = unicode(distrib)
votes = int(votes)
rating = float(rating)
movieID = MOVIEIDS.get(title)
if movieID is None:
return None
return {'votes distribution': distrib, 'votes': votes, 'rating': rating,
'movieID': movieID}
def getLines(fd, before):
"""Retrieve information from the lists."""
seenFirst = False
seenSecond = False
lines = []
for line in fd:
if seenSecond:
line = line.strip()
if not line:
break
info = manageLine(line)
if info:
lines.append(info)
continue
if seenFirst:
if line.startswith(beforeList):
seenSecond = True
continue
if line.startswith(before):
seenFirst = True
return lines
def saveList():
"""Save information from the top/bottom lists."""
fd = gzip.open(os.path.join(IMDB_PTDF_DIR, 'ratings.list.gz'))
outShlv = shelve.open(os.path.join(LOCAL_DATA_DIR, 'topbottom.db'), 'n')
print 'Saving top 250 list...',
sys.stdout.flush()
top = getLines(fd, beforeTop)
outShlv['top 250 rank'] = top
print 'DONE!'
print 'Saving bottom 10 list...',
sys.stdout.flush()
fd.seek(0)
bottom = getLines(fd, beforeBottom)
bottom.reverse()
outShlv['bottom 10 rank'] = bottom
print 'DONE!'
fd.close()
outShlv.close()
saveList()
|
DynamicSSSP/sc18 | SSSP/ESSENS/Core/Basic_Traversal/Level2/ADJ/traversal.hpp | #ifndef TRAVERSAL_HPP
#define TRAVERSAL_HPP
#include "ADJ/network_traversal.hpp"
using namespace std;
/**Traversal based on these features ***/
// 1. Traverse Type: Node; Font; Pieces (0,1,2)
// 2. Increase Set: Node; Nodes; Subgraph (0,1,2);
// 3. Edges added as traversed (0); from top of heap (1);
//===Optional
// 4. Blacklist : Visited or Not X Node or Edge (00 (visited; node) (0); 01 (visited; edge)(1);
/**************************/
void traversal(int node, A_Network X, const string &opt, A_Network *Y)
{
//Find the matching options
//BFS
//multiple node travesal--1
//increase by multiple nodes--1
//Edges added as traversed--0
if(opt=="bfs")
{traversal_110(node,X,add_to_heap_bfs,Y);
return; }
//CHORDAL
//single node travesal--0
//increase by multiple nodes--1
//Edges added as traversed--0
if(opt=="chd")
{traversal_010(node,X,add_to_heap_chd,Y);
return;}
//MAXST
//single node travesal--0
//increase by single node--0
//Edges added as traversed--0
if(opt=="maxst")
{traversal_000(node,X,add_to_heap_maxst,Y);
return;}
//MINST
//single node travesal--0
//increase by single node--0
//Edges added as traversed--0
if(opt=="minst")
{traversal_000(node,X,add_to_heap_minst,Y);
return;}
//DFS
//single node travesal--0
//increase by single node--0
//Edges added as traversed--0
if(opt=="dfs")
{traversal_000(node,X,add_to_heap_dfs,Y);
return;}
//RANDOM
//single node travesal--0
//increase by single node--0
//Edges added as traversed--0
if(opt=="rnd")
{traversal_000(node,X,add_to_heap_rnd,Y);
return;}
//RANDOM1
//multiple node travesal--1
//increase by multiple nodes--1
//Edges added as traversed--0
if(opt=="rnd1")
{traversal_110(node,X,add_to_heap_rnd1,Y);
return;}
}
/********/
/******* End of Functions **************/
#endif
|
Aliacf21/BotBuilder-Samples | samples/java_springboot/81.skills-skilldialog/dialog-root-bot/src/main/java/com/microsoft/bot/sample/dialogrootbot/middleware/Logger.java | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MT License.
package com.microsoft.bot.sample.dialogrootbot.middleware;
import java.util.concurrent.CompletableFuture;
public abstract class Logger {
public CompletableFuture<Void> logEntry(String entryToLog) {
System.out.println(entryToLog);
return CompletableFuture.completedFuture(null);
}
}
|
jjxs/coolweather | daqi/server/src/main/java/cn/com/cnc/fcc/web/rest/QmsProductionInspectionResource.java | <reponame>jjxs/coolweather
package cn.com.cnc.fcc.web.rest;
import cn.com.cnc.fcc.service.util.DateUtil;
import com.codahale.metrics.annotation.Timed;
import cn.com.cnc.fcc.domain.QmsProductionInspection;
import cn.com.cnc.fcc.repository.QmsProductionInspectionRepository;
import cn.com.cnc.fcc.web.rest.errors.BadRequestAlertException;
import cn.com.cnc.fcc.web.rest.util.HeaderUtil;
import cn.com.cnc.fcc.web.rest.util.PaginationUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.Null;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
/**
* REST controller for managing QmsProductionInspection.
*/
@RestController
@RequestMapping("/api")
public class QmsProductionInspectionResource {
private final Logger log = LoggerFactory.getLogger(QmsProductionInspectionResource.class);
private static final String ENTITY_NAME = "qmsProductionInspection";
private final QmsProductionInspectionRepository qmsProductionInspectionRepository;
@Resource
private DateUtil dateUtil;
public QmsProductionInspectionResource(QmsProductionInspectionRepository qmsProductionInspectionRepository) {
this.qmsProductionInspectionRepository = qmsProductionInspectionRepository;
}
/**
* POST /qms-production-inspections : Create a new qmsProductionInspection.
*
* @param qmsProductionInspection the qmsProductionInspection to create
* @return the ResponseEntity with status 201 (Created) and with body the new qmsProductionInspection, or with status 400 (Bad Request) if the qmsProductionInspection has already an ID
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PostMapping("/qms-production-inspections")
@Timed
public ResponseEntity<QmsProductionInspection> createQmsProductionInspection(@Valid @RequestBody QmsProductionInspection qmsProductionInspection) throws URISyntaxException {
log.debug("REST request to save QmsProductionInspection : {}", qmsProductionInspection);
if (qmsProductionInspection.getId() != null) {
throw new BadRequestAlertException("A new qmsProductionInspection cannot already have an ID", ENTITY_NAME, "idexists");
}
// 赋初始
if (qmsProductionInspection.getRemark() == null) {
qmsProductionInspection.setRemark("");
}
if (qmsProductionInspection.getFurnace() == null) {
qmsProductionInspection.setFurnace("");
}
// session取得用户信息
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
// 取得用户信息
UserDetails user = (UserDetails) authentication.getPrincipal();
qmsProductionInspection.setIsOk("0");
qmsProductionInspection.setMakeUser(user.getUsername());
qmsProductionInspection.setModifyUser(user.getUsername());
qmsProductionInspection.setMakeTime(dateUtil.getDBNowDate());
qmsProductionInspection.setModifyTime(dateUtil.getDBNowDate());
QmsProductionInspection result = qmsProductionInspectionRepository.save(qmsProductionInspection);
return ResponseEntity.created(new URI("/api/qms-production-inspections/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
* PUT /qms-production-inspections : Updates an existing qmsProductionInspection.
*
* @param qmsProductionInspection the qmsProductionInspection to update
* @return the ResponseEntity with status 200 (OK) and with body the updated qmsProductionInspection,
* or with status 400 (Bad Request) if the qmsProductionInspection is not valid,
* or with status 500 (Internal Server Error) if the qmsProductionInspection couldn't be updated
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PutMapping("/qms-production-inspections")
@Timed
public ResponseEntity<QmsProductionInspection> updateQmsProductionInspection(@Valid @RequestBody QmsProductionInspection qmsProductionInspection) throws URISyntaxException {
log.debug("REST request to update QmsProductionInspection : {}", qmsProductionInspection);
if (qmsProductionInspection.getId() == null) {
throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
}
// session取得用户信息
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
// 取得用户信息
UserDetails user = (UserDetails) authentication.getPrincipal();
QmsProductionInspection mypi = qmsProductionInspectionRepository.findById(qmsProductionInspection.getId()).get();
mypi.setSerialNumber(qmsProductionInspection.getSerialNumber());
mypi.setBomTechnologyId(qmsProductionInspection.getBomTechnologyId());
mypi.setMaterielId(qmsProductionInspection.getMaterielId());
mypi.setFurnace(qmsProductionInspection.getFurnace());
mypi.setRemark(qmsProductionInspection.getRemark());
mypi.setModifyUser(user.getUsername());
mypi.setModifyTime(dateUtil.getDBNowDate());
QmsProductionInspection result = qmsProductionInspectionRepository.save(mypi);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, qmsProductionInspection.getId().toString()))
.body(result);
}
/**
* GET /qms-production-inspections : get all the qmsProductionInspections.
*
* @param pageable the pagination information
* @return the ResponseEntity with status 200 (OK) and the list of qmsProductionInspections in body
*/
@GetMapping("/qms-production-inspections")
@Timed
public ResponseEntity<List<QmsProductionInspection>> getAllQmsProductionInspections(Pageable pageable) {
log.debug("REST request to get a page of QmsProductionInspections");
Page<QmsProductionInspection> page = qmsProductionInspectionRepository.findAll(pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/qms-production-inspections");
return ResponseEntity.ok().headers(headers).body(page.getContent());
}
/**
* GET /qms-production-inspections/:id : get the "id" qmsProductionInspection.
*
* @param id the id of the qmsProductionInspection to retrieve
* @return the ResponseEntity with status 200 (OK) and with body the qmsProductionInspection, or with status 404 (Not Found)
*/
@GetMapping("/qms-production-inspections/{id}")
@Timed
public ResponseEntity<QmsProductionInspection> getQmsProductionInspection(@PathVariable Long id) {
log.debug("REST request to get QmsProductionInspection : {}", id);
Optional<QmsProductionInspection> qmsProductionInspection = qmsProductionInspectionRepository.findById(id);
return ResponseUtil.wrapOrNotFound(qmsProductionInspection);
}
/**
* DELETE /qms-production-inspections/:id : delete the "id" qmsProductionInspection.
*
* @param id the id of the qmsProductionInspection to delete
* @return the ResponseEntity with status 200 (OK)
*/
@DeleteMapping("/qms-production-inspections/{id}")
@Timed
public ResponseEntity<Void> deleteQmsProductionInspection(@PathVariable Long id) {
log.debug("REST request to delete QmsProductionInspection : {}", id);
qmsProductionInspectionRepository.deleteById(id);
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
}
}
|
agaveplatform/science-apis | agave-systems/systems-core/src/test/java/org/iplantc/service/transfer/sftp/SftpRelayPasswordRemoteDataClientIT.java | <gh_stars>0
/**
*
*/
package org.iplantc.service.transfer.sftp;
import org.apache.commons.io.FileUtils;
import org.iplantc.service.systems.exceptions.EncryptionException;
import org.iplantc.service.systems.exceptions.RemoteCredentialException;
import org.iplantc.service.systems.model.AuthConfig;
import org.iplantc.service.systems.model.StorageConfig;
import org.iplantc.service.systems.model.enumerations.AuthConfigType;
import org.iplantc.service.transfer.IRemoteDataClientIT;
import org.iplantc.service.transfer.RemoteDataClient;
import org.iplantc.service.transfer.RemoteDataClientTestUtils;
import org.iplantc.service.transfer.TransferTestRetryAnalyzer;
import org.iplantc.service.transfer.exceptions.RemoteDataException;
import org.json.JSONException;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
/**
* @author dooley
*
*/
@Test(groups={"sftprelay","sftprelay.operations"})
public class SftpRelayPasswordRemoteDataClientIT extends RemoteDataClientTestUtils implements IRemoteDataClientIT {
/* (non-Javadoc)
* @see org.iplantc.service.transfer.AbstractRemoteDataClientTest#getSystemJson()
*/
@Override
protected JSONObject getSystemJson() throws JSONException, IOException {
return jtd.getTestDataObject(STORAGE_SYSTEM_TEMPLATE_DIR + "/" + "sftp-password.example.com.json");
}
protected RemoteDataClient _getRemoteDataClient() throws EncryptionException {
StorageConfig storageConfig = system.getStorageConfig();
AuthConfig authConfig = storageConfig.getDefaultAuthConfig();
String salt = system.getSystemId() + system.getStorageConfig().getHost() + authConfig.getUsername();
if (system.getStorageConfig().getProxyServer() == null)
{
if (authConfig.getType().equals(AuthConfigType.SSHKEYS)) {
return new SftpRelay(storageConfig.getHost(),
storageConfig.getPort(),
authConfig.getUsername(),
authConfig.getClearTextPassword(salt),
storageConfig.getRootDir(),
storageConfig.getHomeDir(),
authConfig.getClearTextPublicKey(salt),
authConfig.getClearTextPrivateKey(salt));
} else {
return new SftpRelay(storageConfig.getHost(),
storageConfig.getPort(),
authConfig.getUsername(),
authConfig.getClearTextPassword(salt),
storageConfig.getRootDir(),
storageConfig.getHomeDir());
}
}
else
{
if (authConfig.getType().equals(AuthConfigType.SSHKEYS)) {
return new SftpRelay(storageConfig.getHost(),
storageConfig.getPort(),
authConfig.getUsername(),
authConfig.getClearTextPassword(salt),
storageConfig.getRootDir(),
storageConfig.getHomeDir(),
system.getStorageConfig().getProxyServer().getHost(),
system.getStorageConfig().getProxyServer().getPort(),
authConfig.getClearTextPublicKey(salt),
authConfig.getClearTextPrivateKey(salt));
}
else
{
return new SftpRelay(storageConfig.getHost(),
storageConfig.getPort(),
authConfig.getUsername(),
authConfig.getClearTextPassword(salt),
storageConfig.getRootDir(),
storageConfig.getHomeDir(),
system.getStorageConfig().getProxyServer().getHost(),
system.getStorageConfig().getProxyServer().getPort());
}
}
}
/**
* Gets getClient() from current thread
* @return SftpRelay instance to the test server
* @throws RemoteCredentialException
* @throws RemoteDataException
*/
protected RemoteDataClient getClient()
{
RemoteDataClient client;
try {
if (threadClient.get() == null) {
client = _getRemoteDataClient();
String threadHomeDir = String.format("%s/thread-%s-%d",
system.getStorageConfig().getHomeDir(),
UUID.randomUUID(),
Thread.currentThread().getId());
client.updateSystemRoots(client.getRootDir(), threadHomeDir);
threadClient.set(client);
}
} catch (EncryptionException e) {
Assert.fail("Failed to get client", e);
}
return threadClient.get();
}
@Override
protected String getForbiddenDirectoryPath(boolean shouldExist) {
if (shouldExist) {
return "/root";
} else {
return "/root/" + UUID.randomUUID();
}
}
/**
* Creates a temp directory within the shared "target/test-classes/transfer
* directory, which is mounted into the sftp-relay container for testing.
* Without overriding this method, we could not verify that transferred
* data matches the test data.
* @param prefix the prefix string to be used in generating the directory's name. may be {@code null}
* @return path to the temp dir
* @throws IOException
*/
@Override
protected Path _createTempDirectory(String prefix) throws IOException {
Path mountedRelayServerDataDirectory = Paths.get("target/test-classes/transfer");
return Files.createTempDirectory(mountedRelayServerDataDirectory, prefix);
}
/** Creates a temp file within the shared "target/test-classes/transfer
* directory, which is mounted into the sftp-relay container for testing.
* Without overriding this method, we could not verify that transferred
* data matches the test data.
* @param prefix the prefix string to be used in generating the file's name. may be {@code null}
* @param suffix the suffix string to be used in generating the file's name. may be {@code null}
* @return
* @throws IOException
*/
@Override
protected Path _createTempFile(String prefix, String suffix) throws IOException {
Path mountedRelayServerDataDirectory = Paths.get("target/test-classes/transfer");
// if (!Files.exists(mountedRelayServerDataDirectory)) {
// Files.createDirectory(mountedRelayServerDataDirectory, null);
// }
return Files.createTempFile(mountedRelayServerDataDirectory, prefix, suffix);
}
@Override
@Test(groups={"proxy"}, retryAnalyzer= TransferTestRetryAnalyzer.class)
public void isPermissionMirroringRequired() {
_isPermissionMirroringRequired();
}
@Override
@Test(groups={"proxy"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void isThirdPartyTransferSupported()
{
_isThirdPartyTransferSupported();
}
@Override
@Test(groups={"stat"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void getFileInfoReturnsRemoteFileInfoForFile() {
_getFileInfoReturnsRemoteFileInfoForFile();
}
@Override
@Test(groups={"stat"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void getFileInfoReturnsRemoteFileInfoForDirectory() {
_getFileInfoReturnsRemoteFileInfoForDirectory();
}
@Override
@Test(groups={"stat"}, expectedExceptions = FileNotFoundException.class, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void getFileInfoReturnsErrorOnMissingPath() throws FileNotFoundException {
_getFileInfoReturnsErrorOnMissingPath();
}
@Override
@Test(groups={"exists"}, dataProvider="doesExistProvider", retryAnalyzer=TransferTestRetryAnalyzer.class)
public void doesExist(String remotedir, boolean shouldExist, String message) {
_doesExist(remotedir, shouldExist, message);
}
@Override
@Test(groups={"size"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void length()
{
_length();
}
@Override
@Test(groups={"mkdir"}, dataProvider="mkdirProvider", retryAnalyzer=TransferTestRetryAnalyzer.class)
public void mkdir(String remotedir, boolean shouldReturnFalse, boolean shouldThrowException, String message) {
_mkdir(remotedir, shouldReturnFalse, shouldThrowException, message);
}
@Override
@Test(groups={"mkdir"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void mkdirWithoutRemotePermissionThrowsRemoteDataException() {
_mkdirWithoutRemotePermissionThrowsRemoteDataException();
}
@Override
@Test(groups={"mkdir"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void mkdirThrowsRemoteDataExceptionIfDirectoryAlreadyExists() {
_mkdirThrowsRemoteDataExceptionIfDirectoryAlreadyExists();
}
@Override
@Test(groups={"mkdir"}, dataProvider="mkdirsProvider", retryAnalyzer=TransferTestRetryAnalyzer.class)
public void mkdirs(String remotedir, boolean shouldThrowException, String message) {
_mkdirs(remotedir, shouldThrowException, message);
}
@Override
@Test(groups={"mkdir"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void mkdirsWithoutRemotePermissionThrowsRemoteDataException() {
_mkdirsWithoutRemotePermissionThrowsRemoteDataException();
}
@Override
@Test(groups={"put"}, dataProvider = "putFileProvider", retryAnalyzer=TransferTestRetryAnalyzer.class)
public void putFile(String remotePath, String expectedRemoteFilename, boolean shouldThrowException, String message) {
_putFile(remotePath, expectedRemoteFilename, shouldThrowException, message);
}
@Override
@Test(groups={"put"}, dataProvider="putFileOutsideHomeProvider", retryAnalyzer=TransferTestRetryAnalyzer.class)
public void putFileOutsideHome(String remoteFilename, String expectedRemoteFilename, boolean shouldThrowException, String message) {
_putFileOutsideHome(remoteFilename, expectedRemoteFilename, shouldThrowException, message);
}
@Override
@Test(groups={"put"}, dataProvider="putFolderProvider", retryAnalyzer=TransferTestRetryAnalyzer.class)
public void putFolderCreatesRemoteFolder(String remotePath, String expectedRemoteFilename, boolean shouldThrowException, String message) {
_putFolderCreatesRemoteFolder(remotePath, expectedRemoteFilename, shouldThrowException, message);
}
@Override
@Test(groups={"put"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void putFolderCreatesRemoteSubFolderWhenNamedRemotePathExists() {
_putFolderCreatesRemoteSubFolderWhenNamedRemotePathExists();
}
@Override
@Test(groups={"put"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void putFolderMergesContentsWhenRemoteFolderExists()
{
_putFolderMergesContentsWhenRemoteFolderExists();
}
@Override
@Test(groups={"put"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void putFileOverwritesExistingFile()
{
_putFileOverwritesExistingFile();
}
@Override
@Test(groups={"put"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void putFileWithoutRemotePermissionThrowsRemoteDataException() {
_putFileWithoutRemotePermissionThrowsRemoteDataException();
}
@Override
@Test(groups={"put"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void putFolderWithoutRemotePermissionThrowsRemoteDataException() {
_putFolderWithoutRemotePermissionThrowsRemoteDataException();
}
@Override
@Test(groups={"put"}, dataProvider="putFolderProvider", retryAnalyzer=TransferTestRetryAnalyzer.class)
public void putFolderOutsideHome(String remoteFilename, String expectedRemoteFilename, boolean shouldThrowException, String message) {
_putFolderOutsideHome(remoteFilename, expectedRemoteFilename, shouldThrowException, message);
}
@Override
@Test(groups={"put"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void putFileFailsToMissingDestinationPath()
{
_putFileFailsToMissingDestinationPath();
}
@Override
@Test(groups={"put"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void putFolderFailsToMissingDestinationPath()
{
_putFolderFailsToMissingDestinationPath();
}
@Override
@Test(groups={"put"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void putFailsForMissingLocalPath()
{
_putFailsForMissingLocalPath();
}
@Override
@Test(groups={"put"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void putFolderFailsToRemoteFilePath()
{
_putFolderFailsToRemoteFilePath();
}
@Override
@Test(groups={"delete"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void delete()
{
_delete();
}
@Override
@Test(groups={"delete"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void deleteFailsOnMissingDirectory()
{
_deleteFailsOnMissingDirectory();
}
@Override
@Test(groups={"delete"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void deleteThrowsExceptionWhenNoPermission()
{
_deleteThrowsExceptionWhenNoPermission();
}
@Override
@Test(groups={"is"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void isDirectoryTrueForDirectory()
{
_isDirectoryTrueForDirectory();
}
@Override
@Test(groups={"is"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void isDirectoryFalseForFile()
{
_isDirectoryFalseForFile();
}
@Override
@Test(groups={"is"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void isDirectorThrowsExceptionForMissingPath()
{
_isDirectorThrowsExceptionForMissingPath();
}
@Override
@Test(groups={"is"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void isFileFalseForDirectory()
{
_isFileFalseForDirectory();
}
@Override
@Test(groups={"is"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void isFileTrueForFile()
{
_isFileTrueForFile();
}
@Override
@Test(groups={"is"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void isFileThrowsExceptionForMissingPath()
{
_isFileThrowsExceptionForMissingPath();
}
@Override
@Test(groups={"list"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void ls()
{
_ls();
}
@Override
@Test(groups={"list"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void lsFailsOnMissingDirectory()
{
_lsFailsOnMissingDirectory();
}
@Override
@Test(groups={"list"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void lsThrowsExceptionWhenNoPermission()
{
_lsThrowsExceptionWhenNoPermission();
}
@Override
@Test(groups={"get"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void getThrowsExceptionOnMissingRemotePath()
{
_getThrowsExceptionOnMissingRemotePath();
}
@Override
@Test(groups={"get"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void getThrowsExceptionWhenDownloadingFolderToLocalFilePath() {
_getThrowsExceptionWhenDownloadingFolderToLocalFilePath();
}
@Override
@Test(groups={"get"}, expectedExceptions = FileNotFoundException.class, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void getDirectoryThrowsExceptionWhenDownloadingFolderToNonExistentLocalPath() throws FileNotFoundException {
_getDirectoryThrowsExceptionWhenDownloadingFolderToNonExistentLocalPath();
}
@Override
@Test(groups={"get"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void getThrowsExceptionWhenDownloadingFileToNonExistentLocalPath() {
_getThrowsExceptionWhenDownloadingFileToNonExistentLocalPath();
}
@Override
@Test(groups={"get"}, dataProvider="getDirectoryRetrievesToCorrectLocationProvider", retryAnalyzer = TransferTestRetryAnalyzer.class)
public void getDirectoryRetrievesToCorrectLocation(String localdir, boolean createTestDownloadFolder, String expectedDownloadPath, String message) {
_getDirectoryRetrievesToCorrectLocation(localdir, createTestDownloadFolder, expectedDownloadPath, message);
}
@Test
public void copyRemoteDirectory() {
String remoteBasePath = null;
Path tmpDir = null;
Path testDownloadPath = null;
try
{
tmpDir = _createTempDirectory(null);
testDownloadPath = tmpDir.resolve("copyRemoteDirTest");
testDownloadPath.toFile().mkdirs();
remoteBasePath = createRemoteTestDir();
getClient().put(LOCAL_BINARY_FILE, remoteBasePath);
getClient().put(LOCAL_TXT_FILE, remoteBasePath);
String remoteSubpath = UUID.randomUUID().toString();
getClient().mkdir(remoteBasePath + "/" + remoteSubpath);
getClient().put(LOCAL_BINARY_FILE, remoteBasePath + "/" + remoteSubpath);
getClient().put(LOCAL_TXT_FILE, remoteBasePath + "/" + remoteSubpath);
Assert.assertTrue(getClient().doesExist(remoteBasePath),
"Test directory not found on remote test system after put.");
((SftpRelay)getClient()).copyRemoteDirectory(remoteBasePath, testDownloadPath.toString(),
true, true, null);
Assert.assertTrue(testDownloadPath.resolve(LOCAL_BINARY_FILE_NAME).toFile().exists(),
"Binary file not found on local system after copyRemoteDirectory.");
Assert.assertTrue(testDownloadPath.resolve(LOCAL_TXT_FILE_NAME).toFile().exists(),
"Text file not found on local system after copyRemoteDirectory.");
Assert.assertTrue(testDownloadPath.resolve(remoteSubpath).toFile().exists(),
"Subdirectory not found on local system after copyRemoteDirectory.");
Assert.assertTrue(testDownloadPath.resolve(remoteSubpath).toFile().exists(),
"Remote directory not present as directory on local system after copyRemoteDirectory.");
Assert.assertTrue(testDownloadPath.resolve(remoteSubpath + "/" + LOCAL_BINARY_FILE_NAME).toFile().exists(),
"Nested binary file not found on local system after copyRemoteDirectory.");
Assert.assertTrue(testDownloadPath.resolve(remoteSubpath + "/" + LOCAL_TXT_FILE_NAME).toFile().exists(),
"Nested text file not found on local system after copyRemoteDirectory.");
}
catch (Exception e) {
Assert.fail("get should not throw unexpected exception", e);
}
finally {
try { getClient().delete(remoteBasePath); } catch (Exception ignore) {}
try {
if (testDownloadPath != null)
FileUtils.deleteQuietly(testDownloadPath.toFile());
} catch (Exception ignore) {}
try { if (tmpDir != null) FileUtils.deleteQuietly(tmpDir.toFile()); } catch (Exception ignore) {}
}
}
@Override
@Test(groups={"get"}, dataProvider="getFileRetrievesToCorrectLocationProvider", retryAnalyzer=TransferTestRetryAnalyzer.class)
public void getFileRetrievesToCorrectLocation(Path localPath, Path expectedDownloadPath, String message) {
_getFileRetrievesToCorrectLocation(localPath, expectedDownloadPath, message);
}
@Override
@Test(groups={"get"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void getFileOverwritesExistingFile()
{
_getFileOverwritesExistingFile();
}
@Override
@Test(groups={"putstream"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void getOutputStream()
{
_getOutputStream();
}
@Override
@Test(groups={"putstream"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void getOutputStreamFailsWhenRemotePathIsNullOrEmpty()
{
_getOutputStreamFailsWhenRemotePathIsNullOrEmpty();
}
@Override
@Test(groups={"putstream"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void getOutputStreamFailsWhenRemotePathIsDirectory()
{
_getOutputStreamFailsWhenRemotePathIsDirectory();
}
@Override
@Test(groups={"putstream"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void getOutputStreamFailsOnMissingPath()
{
_getOutputStreamFailsOnMissingPath();
}
@Override
@Test(groups={"putstream"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void getOutputStreamThrowsExceptionWhenNoPermission()
{
_getOutputStreamThrowsExceptionWhenNoPermission();
}
@Override
@Test(groups={"getstream"}, dataProvider="getInputStreamProvider", retryAnalyzer=TransferTestRetryAnalyzer.class)
public void getInputStream(String localFile, String message)
{
_getInputStream(localFile, message);
}
@Override
@Test(groups={"getstream"}, dataProvider="getInputStreamOnRemoteDirectoryThrowsExceptionProvider", retryAnalyzer=TransferTestRetryAnalyzer.class)
public void getInputStreamOnRemoteDirectoryThrowsException(String remotedir, String message) {
_getInputStreamOnRemoteDirectoryThrowsException(remotedir, message);
}
@Override
@Test(groups={"getstream"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void getInputStreamThrowsExceptionWhenNoPermission()
{
_getInputStreamThrowsExceptionWhenNoPermission();
}
@Override
@Test(groups={"checksum"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void checksumDirectoryFails()
{
_checksumDirectoryFails();
}
@Override
@Test(groups={"checksum"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void checksumMissingPathThrowsException()
{
_checksumMissingPathThrowsException();
}
@Override
@Test(groups={"checksum"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void checksum()
{
_checksum();
}
@Override
@Test(groups={"rename"}, dataProvider="doRenameProvider", retryAnalyzer=TransferTestRetryAnalyzer.class)
public void doRename(String oldpath, String newpath, boolean shouldThrowException, String message) {
_doRename(oldpath, newpath, shouldThrowException, message);
}
@Override
@Test(groups={"rename"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void doRenameThrowsRemotePermissionExceptionToRestrictedSource() {
_doRenameThrowsRemotePermissionExceptionToRestrictedSource();
}
@Override
@Test(groups={"rename"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void doRenameThrowsRemotePermissionExceptionToRestrictedDest() {
_doRenameThrowsRemotePermissionExceptionToRestrictedDest();
}
@Override
@Test(groups={"rename"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void doRenameThrowsFileNotFoundExceptionOnMissingDestPath() {
_doRenameThrowsFileNotFoundExceptionOnMissingDestPath();
}
@Override
@Test(groups={"rename"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void doRenameThrowsFileNotFoundExceptionOnMissingSourcePath() {
_doRenameThrowsFileNotFoundExceptionOnMissingSourcePath();
}
@Override
@Test(enabled=false)
public void getUrlForPath()
{
_getUrlForPath();
}
@Override
@Test(groups={"copy"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void copyFile()
{
_copyFile();
}
@Override
@Test(groups={"copy"}, dataProvider="copyIgnoreSlashesProvider", retryAnalyzer=TransferTestRetryAnalyzer.class)
public void copyDir(String src, String dest, boolean createDest, String expectedPath, boolean shouldThrowException, String message) {
_copyDir(src, dest, createDest, expectedPath, shouldThrowException, message);
}
@Override
@Test(groups={"copy"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void copyThrowsRemoteDataExceptionToRestrictedDest()
{
_copyThrowsRemoteDataExceptionToRestrictedDest();
}
@Override
@Test(groups={"copy"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void copyThrowsFileNotFoundExceptionOnMissingDestPath() {
_copyThrowsFileNotFoundExceptionOnMissingDestPath();
}
@Override
@Test(groups={"copy"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void copyThrowsFileNotFoundExceptionOnMissingSourcePath() {
_copyThrowsFileNotFoundExceptionOnMissingSourcePath();
}
@Override
@Test(groups={"copy"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void copyThrowsRemoteDataExceptionToRestrictedSource()
{
_copyThrowsRemoteDataExceptionToRestrictedSource();
}
@Override
@Test(groups={"sync"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void syncToRemoteFile()
{
_syncToRemoteFile();
}
@Override
@Test(groups={"sync"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void syncToRemoteFolderAddsMissingFiles()
{
_syncToRemoteFolderAddsMissingFiles();
}
@Override
@Test(groups={"sync"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void syncToRemoteFolderLeavesExistingFilesUntouched()
{
_syncToRemoteFolderLeavesExistingFilesUntouched();
}
@Override
@Test(groups={"sync"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void syncToRemoteFolderOverwritesFilesWithDeltas()
{
_syncToRemoteFolderOverwritesFilesWithDeltas();
}
@Override
@Test(groups={"sync"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void syncToRemoteFolderReplacesOverlappingFilesAndFolders() {
_syncToRemoteFolderReplacesOverlappingFilesAndFolders();
}
@Override
@Test(groups={"sync"}, retryAnalyzer=TransferTestRetryAnalyzer.class)
public void syncToRemoteSyncesSubfoldersRatherThanEmbeddingThem() throws IOException, RemoteDataException {
_syncToRemoteSyncesSubfoldersRatherThanEmbeddingThem();
}
}
|
Dive904/What2Cite | src/pipelineapplication/system_accuracy.py | <reponame>Dive904/What2Cite
import pickle
import numpy as np
from keras_preprocessing.sequence import pad_sequences
from tensorflow_core.python.keras.models import load_model
from src.fileutils import file_abstract
from src.pipelineapplication import utils
from src.neuralnetwork import lstm_utils
# input
cit_labelled_analyzed_pickle_path = "../../output/official/cit_labelled_with_final_topic_pickle.pickle"
lstm_model = "../../output/official/neuralnetwork.h5"
tokenizer_model = "../../output/official/tokenizer.pickle"
cit_labelled_path = "../../output/official/topics_cits_labelled_pickle.pickle"
cit_topic_info_pickle_path = "../../output/official/cit_topic_info_pickle.pickle"
cit_structure_pickle_path = "../../output/official/cit_structure_pickle.pickle"
hittingplot_base_path = "../../output/hittingplots/"
closedataset_path = "../../output/official/closedataset.txt"
Percentile = 10
N_papers = 1500
t_for_true_prediction = 0.4 # probability threshold to consider a prediction as valid
N = 3
# output
hittingplot_total_path = "../../output/hittingplots/total_hitting_plot" + \
str(Percentile) + "_" + str(N_papers) + ".png"
with open(cit_topic_info_pickle_path, 'rb') as handle: # take the list of CitTopic score
cit_topic_info = pickle.load(handle)
with open(cit_structure_pickle_path, 'rb') as handle: # take the list of CitTopic score
cit_structure = pickle.load(handle)
print("Done ✓")
with open(cit_labelled_path, 'rb') as handle: # take the list of CitTopic score
# in this part, we read the cit topics labelled with other information.
# We don't need that. So, we'll do a map removing all noise, getting only the paper id for all CitTopic
cit_topics = pickle.load(handle)
cit_topics = list(map(lambda x: list(map(lambda y: y[0], x)), cit_topics))
with open(cit_labelled_analyzed_pickle_path, 'rb') as handle: # take the list of CitTopic score
cit_topic_labelled = pickle.load(handle)
with open(tokenizer_model, 'rb') as handle: # get the tokenizer
tokenizer = pickle.load(handle)
model = load_model(lstm_model) # load model from single file
# abstracts = utils.get_abstracts_to_analyze() # get the abstract to analyze
print("INFO: Reading close dataset and picking random abstracts", end="... ")
abstracts = file_abstract.txt_dataset_reader(closedataset_path)
abstracts = abstracts[500000:]
abstracts = utils.pick_random_abstracts(abstracts, N_papers)
print("Done ✓")
# abstract = [{id = "...", title = "...", "year": "..." outCitations = ["..."]}]
# prepare texts for classification
abstracts_prep = list(map(lambda x: lstm_utils.preprocess_text(x["paperAbstract"]), abstracts))
# abstract = [{id = "...", title = "...", outCitations = ["..."]}]
print("INFO: Tokenizing sequences", end="... ")
seq = tokenizer.texts_to_sequences(abstracts_prep)
seq = pad_sequences(seq, padding='post', maxlen=200)
print("Done ✓")
print("INFO: Getting predictions", end="... ")
yhat = model.predict(seq) # make predictions
for i in range(len(yhat)):
# at the end of the loop, every dictionary for the abstracts, will contain an additional element with all the
# valid predictions. Please note: the list of abstracts and the list of yhat (i.e predictions for every element)
# have the same length
valid_predictions = utils.get_valid_predictions(yhat[i], t_for_true_prediction)
# valid_predictions = utils.get_n_predictions(yhat[i], N)
abstracts[i]["validPredictions"] = valid_predictions
print("Done ✓")
# abstract = [{id = "...", title = "...", outCitations = ["..."], validPredictions = [("topic", prob)]}]
print("INFO: Analyzing", end="... ")
heights_split = []
for i in range(len(abstracts)):
# at the end of this loop, every valid prediction will be extended with the index of reference CitTopics
valid_predictions = abstracts[i]["validPredictions"]
paper_abstract = abstracts[i]["paperAbstract"]
out_citations = abstracts[i]["outCitations"]
# count total possible CitTopics
total_possible_cit_topics = 0
for cit in cit_topics:
for c in cit:
if c in out_citations:
total_possible_cit_topics += 1
# total_possible_cit_topics = total_possible_cit_topics * len(valid_predictions)
for k in range(len(valid_predictions)):
topic = valid_predictions[k][0]
prob = valid_predictions[k][1]
score_count_list = utils.all_score_function(topic, cit_topics, cit_structure)
score_count_list = list(enumerate(score_count_list))
tmp = list(map(lambda x: x[0], score_count_list))
# Create hitting plots
title = abstracts[i]["id"] + " - " + str(topic)
score_count_list.sort(key=lambda x: x[1], reverse=True)
index_score_count_list = list(map(lambda x: x[0], score_count_list))
height = [0 for index in index_score_count_list]
for ii in range(len(index_score_count_list)):
index = index_score_count_list[ii]
reference_cit_topic = cit_topics[index]
t = utils.compute_hit_citations(reference_cit_topic, out_citations)
# height.append(len(t))
height[ii] += len(t)
valid_predictions[k] = (topic, prob, tmp)
heights_split.append((utils.split_list(height, Percentile), total_possible_cit_topics))
print("Done ✓")
# abstract = [{id = "...", title = "...", outCitations = ["..."],
# validPredictions = [(topic, prob, [index])]}]
# create aggregate plot
print("INFO: Creating aggregate plot", end="... ")
max_index = int(100 / Percentile)
total = list(np.zeros(max_index))
total_c = 0
for heights in heights_split:
hh = 0
while hh < len(heights[0]):
total[hh] += sum(heights[0][hh])
hh += 1
total_c += heights[1]
total = utils.normalize_cit_count(total, total_c)
total_to_plot = list(map(lambda x: int(x), total))
total_to_print = list(map(lambda x: np.round(x, 2), total))
bars = ["P" + str(i + 1) for i in range(max_index)]
utils.make_bar_plot(total_to_plot, bars, "Total Hitting Plot - " + str(Percentile) + "% - " +
str(N_papers) + " abstracts - #4",
hittingplot_total_path)
print("Done ✓")
print(total_to_print)
|
wurui1994/test | Sources/Graphics/GUILib/Qt5Example/VolumeWidget/main.cpp | #include "VolumeWidget.h"
#include <QApplication>
#include <QSlider>
#include <QtWidgets/QtWidgets>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
//QMainWindow w;
MusicVolumePopWidget* slider = new MusicVolumePopWidget;
slider->resize(320, 240);
//w.setCentralWidget(slider);
// w.show();
slider->show();
return a.exec();
}
|
ykskb/dax86 | interrupt.h | #ifndef INT_H_
#define INT_H_
#include "emulator.h"
#include "modrm.h"
#define T_IRQ0 32 // IRQ 0 corresponds to int T_IRQ
#define IRQ_TIMER 0
#define IRQ_KBD 1
#define IRQ_COM1 4
#define IRQ_IDE 14
#define IRQ_ERROR 19
#define IRQ_SPURIOUS 31
void lidt(Emulator *emu, ModRM *modrm);
void handle_interrupt(Emulator *emu, uint8_t vector, int sw);
#endif |
cmcfarlen/trafficserver | proxy/http/unit_tests/test_error_page_selection.cc | <gh_stars>1000+
/** @file
Catch-based tests of error page selection.
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "catch.hpp"
#include "HttpBodyFactory.h"
#include <array>
TEST_CASE("error page selection test", "[http]")
{
struct Sets {
const char *set_name;
const char *content_language;
const char *content_charset;
};
std::array<Sets, 10> sets = {{{"default", "en", "iso-8859-1"},
{"en-cockney", "en-cockney", "iso-8859-1"},
{"en0", "en", "iso-8859-1"},
{"en-us", "en-us", "us-ascii"},
{"en1", "en", "unicode"},
{"en-cockney-slang", "en-cockney-slang", "iso-8859-1"},
{"ko0", "ko", "iso-8859-1"},
{"ko1", "ko", "iso-2022-kr"},
{"jp", "jp", "shift-jis"},
{"es", "es", "unicode"}}};
struct Tests {
const char *accept_language;
const char *accept_charset;
const char *expected_set;
float expected_Q;
int expected_La;
int expected_I;
};
std::array<Tests, 26> tests = {{
{nullptr, nullptr, "default", 1, 0, INT_MAX},
{"en", "iso-8859-1", "en0", 1, 2, 1},
{"en", "unicode", "en1", 1, 2, 1},
{"ko", "iso-8859-1", "ko0", 1, 2, 1},
{"ko", "iso-2022-kr", "ko1", 1, 2, 1},
{"en-us", nullptr, "en-us", 1, 5, 1},
{"en-US", nullptr, "en-us", 1, 5, 1},
{"jp,es", nullptr, "jp", 1, 2, 1},
{"es,jp", nullptr, "es", 1, 2, 1},
{"jp;q=0.7,es", nullptr, "es", 1, 2, 2},
{"jp;q=.7,es", nullptr, "es", 1, 2, 2},
{"jp;q=.7,es;q=.7", nullptr, "jp", 0.7, 2, 1},
{"jp;q=.7,es;q=.701", nullptr, "es", 0.701, 2, 2},
{"jp;q=.7 , es;q=.701", nullptr, "es", 0.701, 2, 2},
{"jp ; q=.7 , es ; ; ; ; q=.701", nullptr, "es", 0.701, 2, 2},
{"jp,es;q=.7", nullptr, "jp", 1, 2, 1},
{"jp;q=1,es;q=.7", nullptr, "jp", 1, 2, 1},
{"jp;;;q=1,es;q=.7", nullptr, "jp", 1, 2, 1},
{"jp;;;q=1,,,,es;q=.7", nullptr, "jp", 1, 2, 1},
{"jp;;;q=.7,,,,es;q=.7", nullptr, "jp", 0.7, 2, 1},
{"jp;;;q=.699,,,,es;q=.7", nullptr, "es", 0.7, 2, 5},
{"jp;q=0,es;q=1", nullptr, "es", 1, 2, 2},
{"jp;q=0, es;q=1", nullptr, "es", 1, 2, 2},
{"jp;q=0,es;q=.5", nullptr, "es", 0.5, 2, 2},
{"jp;q=0, es;q=.5", nullptr, "es", 0.5, 2, 2},
{"jp;q=000000000.00000000000000000000,es;q=1.0000000000000000000", nullptr, "es", 1, 2, 2},
}};
// (1) build fake hash table of sets
std::unique_ptr<HttpBodyFactory::BodySetTable> table_of_sets;
table_of_sets.reset(new HttpBodyFactory::BodySetTable);
for (const auto &set : sets) {
HttpBodySetRawData *body_set = new HttpBodySetRawData;
body_set->magic = 0;
body_set->set_name = strdup(set.set_name);
body_set->content_language = strdup(set.content_language);
body_set->content_charset = strdup(set.content_charset);
body_set->table_of_pages.reset(new HttpBodySetRawData::TemplateTable);
REQUIRE(table_of_sets->find(body_set->set_name) == table_of_sets->end());
table_of_sets->emplace(body_set->set_name, body_set);
}
// (2) for each test, parse accept headers into lists, and test matching
int count = 0;
for (const auto &test : tests) {
float Q_best;
int La_best, Lc_best, I_best;
const char *set_best;
StrList accept_language_list;
StrList accept_charset_list;
HttpCompat::parse_comma_list(&accept_language_list, test.accept_language);
HttpCompat::parse_comma_list(&accept_charset_list, test.accept_charset);
printf(" test #%d: (Accept-Language='%s', Accept-Charset='%s')\n", ++count,
(test.accept_language ? test.accept_language : "<null>"), (test.accept_charset ? test.accept_charset : "<null>"));
set_best = HttpBodyFactory::determine_set_by_language(table_of_sets, &(accept_language_list), &(accept_charset_list), &Q_best,
&La_best, &Lc_best, &I_best);
REQUIRE(strcmp(set_best, test.expected_set) == 0);
REQUIRE(Q_best == test.expected_Q);
REQUIRE(La_best == test.expected_La);
REQUIRE(I_best == test.expected_I);
}
for (const auto &it : *table_of_sets.get()) {
ats_free(it.second->set_name);
ats_free(it.second->content_language);
ats_free(it.second->content_charset);
it.second->table_of_pages.reset(nullptr);
delete it.second;
}
table_of_sets.reset(nullptr);
}
|
lofunz/mieme | Reloaded/trunk/src/mame/video/boogwing.c | #include "emu.h"
#include "includes/boogwing.h"
#include "video/deco16ic.h"
static void draw_sprites( running_machine *machine, bitmap_t *bitmap, const rectangle *cliprect, UINT16* spriteram_base, int gfx_region )
{
boogwing_state *state = machine->driver_data<boogwing_state>();
int offs;
int flipscreen = !flip_screen_get(machine);
UINT16 priority = deco16ic_priority_r(state->deco16ic, 0, 0xffff);
for (offs = 0x400 - 4; offs >= 0; offs -= 4)
{
int x, y, sprite, colour, multi, fx, fy, inc, flash, mult, pri = 0, spri = 0;
int alpha = 0xff;
sprite = spriteram_base[offs + 1];
if (!sprite)
continue;
y = spriteram_base[offs];
flash = y & 0x1000;
if (flash && (machine->primary_screen->frame_number() & 1))
continue;
x = spriteram_base[offs + 2];
colour = (x >> 9) & 0x1f;
fx = y & 0x2000;
fy = y & 0x4000;
multi = (1 << ((y & 0x0600) >> 9)) - 1; /* 1x, 2x, 4x, 8x height */
// Todo: This should be verified from the prom
if (gfx_region == 4)
{
// Sprite 2 priority vs sprite 1
if ((spriteram_base[offs + 2] & 0xc000) == 0xc000)
spri = 4;
else if ((spriteram_base[offs + 2] & 0xc000))
spri = 16;
else
spri = 64;
// Transparency
if (spriteram_base[offs + 2] & 0x2000)
alpha = 0x80;
if (priority == 0x2)
{
// Additional sprite alpha in this mode
if (spriteram_base[offs + 2] & 0x8000)
alpha = 0x80;
// Sprite vs playfield
if ((spriteram_base[offs + 2] & 0xc000) == 0xc000)
pri = 4;
else if ((spriteram_base[offs + 2] & 0xc000) == 0x8000)
pri = 16;
else
pri = 64;
}
else
{
if ((spriteram_base[offs + 2] & 0x8000) == 0x8000)
pri = 16;
else
pri = 64;
}
}
else
{
// Sprite 1 priority vs sprite 2
if (spriteram_base[offs + 2] & 0x8000) // todo - check only in pri mode 2??
spri = 8;
else
spri = 32;
// Sprite vs playfield
if (priority == 0x1)
{
if ((spriteram_base[offs + 2] & 0xc000))
pri = 16;
else
pri = 64;
}
else
{
if ((spriteram_base[offs + 2] & 0xc000) == 0xc000)
pri = 4;
else if ((spriteram_base[offs + 2] & 0xc000) == 0x8000)
pri = 16;
else
pri = 64;
}
}
x = x & 0x01ff;
y = y & 0x01ff;
if (x >= 320) x -= 512;
if (y >= 256) y -= 512;
y = 240 - y;
x = 304 - x;
sprite &= ~multi;
if (fy)
inc = -1;
else
{
sprite += multi;
inc = 1;
}
if (flipscreen)
{
y = 240 - y;
x = 304 - x;
if (fx) fx = 0; else fx = 1;
if (fy) fy = 0; else fy = 1;
mult = 16;
}
else
mult = -16;
while (multi >= 0)
{
deco16ic_pdrawgfx(
state->deco16ic,
bitmap, cliprect, machine->gfx[gfx_region],
sprite - multi * inc,
colour,
fx,fy,
x,y + mult * multi,
0, pri, spri, 0, alpha);
multi--;
}
}
}
VIDEO_UPDATE( boogwing )
{
boogwing_state *state = screen->machine->driver_data<boogwing_state>();
UINT16 flip = deco16ic_pf12_control_r(state->deco16ic, 0, 0xffff);
UINT16 priority = deco16ic_priority_r(state->deco16ic, 0, 0xffff);
flip_screen_set(screen->machine, BIT(flip, 7));
deco16ic_pf12_update(state->deco16ic, state->pf1_rowscroll, state->pf2_rowscroll);
deco16ic_pf34_update(state->deco16ic, state->pf3_rowscroll, state->pf4_rowscroll);
/* Draw playfields */
deco16ic_clear_sprite_priority_bitmap(state->deco16ic);
bitmap_fill(bitmap, cliprect, screen->machine->pens[0x400]); /* pen not confirmed */
bitmap_fill(screen->machine->priority_bitmap, NULL, 0);
// bit&0x8 is definitely some kind of palette effect
// bit&0x4 combines playfields
if ((priority & 0x7) == 0x5)
{
deco16ic_tilemap_2_draw(state->deco16ic, bitmap, cliprect, TILEMAP_DRAW_OPAQUE, 0);
deco16ic_tilemap_34_combine_draw(state->deco16ic, bitmap, cliprect, 0, 32);
}
else if ((priority & 0x7) == 0x1 || (priority & 0x7) == 0x2)
{
deco16ic_tilemap_4_draw(state->deco16ic, bitmap, cliprect, TILEMAP_DRAW_OPAQUE, 0);
deco16ic_tilemap_2_draw(state->deco16ic, bitmap, cliprect, 0, 8);
deco16ic_tilemap_3_draw(state->deco16ic, bitmap, cliprect, 0, 32);
}
else if ((priority & 0x7) == 0x3)
{
deco16ic_tilemap_4_draw(state->deco16ic, bitmap, cliprect, TILEMAP_DRAW_OPAQUE, 0);
deco16ic_tilemap_2_draw(state->deco16ic, bitmap, cliprect, 0, 8);
// This mode uses playfield 3 to shadow sprites & playfield 2 (instead of
// regular alpha-blending, the destination is inverted). Not yet implemented.
// deco16ic_tilemap_3_draw(state->deco16ic, bitmap, cliprect, TILEMAP_DRAW_ALPHA(0x80), 32);
}
else
{
deco16ic_tilemap_4_draw(state->deco16ic, bitmap, cliprect, TILEMAP_DRAW_OPAQUE, 0);
deco16ic_tilemap_3_draw(state->deco16ic, bitmap, cliprect, 0, 8);
deco16ic_tilemap_2_draw(state->deco16ic, bitmap, cliprect, 0, 32);
}
draw_sprites(screen->machine, bitmap, cliprect, screen->machine->generic.buffered_spriteram.u16, 3);
draw_sprites(screen->machine, bitmap, cliprect, screen->machine->generic.buffered_spriteram2.u16, 4);
deco16ic_tilemap_1_draw(state->deco16ic, bitmap, cliprect, 0, 0);
return 0;
}
|
leoclee/agent | src/test/java/org/nhindirect/ldap/LDAPResearchTest.java | <reponame>leoclee/agent<filename>src/test/java/org/nhindirect/ldap/LDAPResearchTest.java
package org.nhindirect.ldap;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Set;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import org.apache.commons.codec.binary.Base64;
import org.apache.directory.server.core.configuration.MutablePartitionConfiguration;
import org.apache.directory.server.core.schema.bootstrap.AbstractBootstrapSchema;
import org.apache.directory.server.unit.AbstractServerTest;
import org.apache.directory.shared.ldap.ldif.Entry;
import org.nhindirect.stagent.cert.CertCacheFactory;
import org.nhindirect.stagent.cert.X509CertificateEx;
import org.nhindirect.stagent.cert.impl.LDAPCertificateStore;
import org.nhindirect.stagent.cert.impl.LdapCertificateStoreFactory;
import org.nhindirect.stagent.cert.impl.LdapStoreConfiguration;
public class LDAPResearchTest extends AbstractServerTest
{
@SuppressWarnings("unchecked")
@Override
public void setUp() throws Exception
{
MutablePartitionConfiguration pcfg = new MutablePartitionConfiguration();
pcfg.setName( "lookupTest" );
pcfg.setSuffix( "cn=lookupTest" );
// Create some indices
Set<String> indexedAttrs = new HashSet<String>();
indexedAttrs.add( "objectClass" );
indexedAttrs.add( "cn" );
pcfg.setIndexedAttributes( indexedAttrs );
// Create a first entry associated to the partition
Attributes attrs = new BasicAttributes( true );
// First, the objectClass attribute
Attribute attr = new BasicAttribute( "objectClass" );
attr.add( "top" );
attrs.put( attr );
// Associate this entry to the partition
pcfg.setContextEntry( attrs );
// As we can create more than one partition, we must store
// each created partition in a Set before initialization
Set<MutablePartitionConfiguration> pcfgs = new HashSet<MutablePartitionConfiguration>();
pcfgs.add( pcfg );
configuration.setContextPartitionConfigurations( pcfgs );
this.configuration.setWorkingDirectory(new File("LDAP-TEST"));
// add the private key schema
///
Set<AbstractBootstrapSchema> schemas = configuration.getBootstrapSchemas();
schemas.add( new PrivkeySchema() );
configuration.setBootstrapSchemas(schemas);
super.setUp();
// import the ldif file
InputStream stream = LDAPResearchTest.class.getClassLoader().getResourceAsStream("ldifs/privCertsOnly.ldif");
if (stream == null)
throw new IOException("Failed to load ldif file");
importLdif(stream);
createLdapEntries();
}
private DirContext createContext(String partition) throws Exception
{
int port = configuration.getLdapPort();
String url = "ldap://localhost:" + port + "/" + partition;
Hashtable<Object, Object> env = new Hashtable<Object, Object>();
env.put( Context.SECURITY_PRINCIPAL, "uid=admin,ou=system" );
env.put( Context.SECURITY_CREDENTIALS, "secret" );
env.put( Context.SECURITY_AUTHENTICATION, "simple" );
env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put( Context.PROVIDER_URL, url );
InitialContext initialContext = new InitialContext( env );
assertNotNull(initialContext);
return (DirContext)initialContext.lookup("");
}
@SuppressWarnings("unchecked")
public void testDummy() throws Exception
{
CertCacheFactory.getInstance().flushAll();
DirContext dirContext = createContext("cn=lookupTest");
Attributes attributes = dirContext.getAttributes( "" );
assertNotNull( attributes );
NamingEnumeration<Attribute> namingEnum = (NamingEnumeration<Attribute>)attributes.getAll();
while (namingEnum.hasMoreElements())
{
Attribute attr = namingEnum.nextElement();
System.out.println("Name: " + attr.getID() + "\r\nValue: " + attr.get() + "\r\n\r\n");
}
Set<SearchResult> results = searchDNs( "(email=<EMAIL>)", "", "ou=privKeys, ou=cerner, ou=com",
SearchControls.SUBTREE_SCOPE , dirContext);
for (SearchResult result : results)
{
System.out.println(result.getName());
// get the priv cert
String privKey = (String)result.getAttributes().get("privKeyStore").get();
System.out.println("Privkey BASE64: " + privKey);
}
}
@SuppressWarnings("unchecked")
public void testLdapSearch() throws Exception
{
CertCacheFactory.getInstance().flushAll();
int port = configuration.getLdapPort();
String url = "ldap://localhost:" + port + "/" + "cn=lookupTest";
Hashtable<String, String> env = new Hashtable<String, String>();
env.put( Context.SECURITY_PRINCIPAL, "uid=admin,ou=system" );
env.put( Context.SECURITY_CREDENTIALS, "secret" );
env.put( Context.SECURITY_AUTHENTICATION, "simple" );
env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put( Context.PROVIDER_URL, url );
InitialContext initialContext = new InitialContext( env );
assertNotNull(initialContext);
DirContext dirContext = (DirContext)initialContext.lookup("");
Attributes attributes = dirContext.getAttributes( "" );
assertNotNull( attributes );
NamingEnumeration<Attribute> namingEnum = (NamingEnumeration<Attribute>)attributes.getAll();
while (namingEnum.hasMoreElements())
{
Attribute attr = namingEnum.nextElement();
System.out.println("Name: " + attr.getID() + "\r\nValue: " + attr.get() + "\r\n\r\n");
}
//Set<SearchResult> results = searchDNs( "(email=<EMAIL>)", "", "ou=privKeys, ou=cerner, ou=com",
// SearchControls.SUBTREE_SCOPE , dirContext);
LdapStoreConfiguration ldapStoreConfiguration = new LdapStoreConfiguration(new String[]{url}, "", "email", "privKeyStore", "X509");
LDAPCertificateStore certificateResolver = (LDAPCertificateStore)LdapCertificateStoreFactory.createInstance(ldapStoreConfiguration, null, null);
Collection<X509Certificate> certs = certificateResolver.getCertificates("<EMAIL>");
/*LdapEnvironment ldapEnvironment = new LdapEnvironment(env, "privKeyStore", "", "email");
LdapCertUtilImpl ldapcertUtilImpl = new LdapCertUtilImpl(ldapEnvironment, "", "X.509");
LDAPCertificateStore ldapCertStore = new LDAPCertificateStore(ldapcertUtilImpl, new KeyStoreCertificateStore(), null);
Collection<X509Certificate> certs = ldapCertStore.getCertificates("<EMAIL>");
*/
assertEquals(1, certs.size());
X509Certificate cert = certs.iterator().next();
assertFalse( cert instanceof X509CertificateEx );
assertTrue(cert.getSubjectX500Principal().toString().contains("<EMAIL>"));
}
protected void createLdapEntries() throws NamingException {
/*Attributes attrs = new BasicAttributes( "objectClass", "top", true);
attrs.put("objectClass", "organizationalUnit");
attrs.put("objectClass", "userPrivKey");
attrs.put("email", "<EMAIL>");
attrs.put("privKeyStore", "1234567");
rootDSE.createSubcontext("ou=gm2552, ou=privKeys, ou=cerner, ou=com, cn=lookupTest", attrs);
*/
Entry entry = new Entry();
entry.addAttribute("objectClass", "organizationalUnit");
entry.addAttribute("objectClass", "top");
entry.addAttribute("objectClass", "userPrivKey");
entry.addAttribute("email", "<EMAIL>");
File fl = new File("testfile");
int idx = fl.getAbsolutePath().lastIndexOf("testfile");
String path = fl.getAbsolutePath().substring(0, idx);
byte[] buffer = new byte[(int) new File(path + "src/test/resources/certs/bob.der").length()+100];
try {
InputStream stream = LDAPResearchTest.class.getClassLoader().getResourceAsStream("certs/bob.der");
stream.read(buffer);
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Base64 base64 = new Base64();
String certificateValue = new String(base64.encode(buffer));
entry.addAttribute("privKeyStore", certificateValue);
entry.addAttribute("ou", "gm2552");
rootDSE.createSubcontext("ou=gm2552, ou=privKeys, ou=cerner, ou=com, cn=lookupTest", entry.getAttributes());
}
private Set<SearchResult> searchDNs( String filter, String partition, String base, int scope , DirContext appRoot) throws Exception
{
if (appRoot == null)
appRoot = createContext( partition );
SearchControls controls = new SearchControls();
controls.setSearchScope( scope );
NamingEnumeration<SearchResult> result = appRoot.search( base, filter, controls );
// collect all results
Set<SearchResult> entries = new HashSet<SearchResult>();
while ( result.hasMore() )
{
SearchResult entry = ( SearchResult ) result.next();
entries.add( entry);
}
return entries;
}
}
|
WRSC/tracking | MYR_rails/db/migrate/20150812100832_add_mission_type.rb | <reponame>WRSC/tracking
class AddMissionType < ActiveRecord::Migration
def change
remove_column :missions, :description, :text
add_column :missions, :type, :string
end
end
|
msullivan/advent-of-code | 2021/10b.py | #!/usr/bin/env python3
import sys
def main(args):
data = [s.strip() for s in sys.stdin]
LS = "([{<"
RS = ")]}>"
m = {k: v for k, v in zip(LS, RS)}
scores = [3, 57, 1197, 25137]
incomplete = []
score = 0
score2 = []
for line in data:
stack = []
busted = False
for i, c in enumerate(line):
if c in LS:
stack.append(c)
else:
l = stack.pop()
if m[l] != c:
busted = True
break
if busted:
score += scores[RS.index(c)]
else:
lscore = 0
for c in reversed(stack):
lscore *= 5
r = RS.index(m[c]) + 1
lscore += r
score2 += [lscore]
print(score)
print(score2[len(score2)//2])
if __name__ == '__main__':
main(sys.argv)
|
BobLChen/VulkanDemos | examples/61_CPURayTracing/TaskThread.h | <gh_stars>100-1000
#pragma once
#include "Runnable.h"
#include "ThreadEvent.h"
class ThreadTask;
class TaskThreadPool;
class RunnableThread;
class TaskThread : public Runnable
{
public:
TaskThread();
virtual ~TaskThread();
virtual bool Create(TaskThreadPool* pool);
virtual bool KillThread();
void DoWork(ThreadTask* task);
protected:
virtual int32 Run() override;
protected:
ThreadEvent* m_DoWorkEvent;
volatile bool m_TimeToDie;
ThreadTask* volatile m_Task;
TaskThreadPool* m_OwningThreadPool;
RunnableThread* m_Thread;
}; |
ilscipio/erp | applications/order/src/org/ofbiz/order/shoppingcart/ShoppingCartServices.java | /*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.order.shoppingcart;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilFormatOut;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityExpr;
import org.ofbiz.entity.condition.EntityOperator;
import org.ofbiz.entity.model.DynamicViewEntity;
import org.ofbiz.entity.model.ModelKeyMap;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.entity.util.EntityTypeUtil;
import org.ofbiz.entity.util.EntityUtil;
import org.ofbiz.entity.util.EntityUtilProperties;
import org.ofbiz.order.order.OrderReadHelper;
import org.ofbiz.order.shoppingcart.ShoppingCart.CartShipInfo;
import org.ofbiz.order.shoppingcart.ShoppingCart.CartShipInfo.CartShipItemInfo;
import org.ofbiz.order.shoppingcart.product.ProductPromoWorker;
import org.ofbiz.order.shoppingcart.shipping.ShippingEstimateWrapper;
import org.ofbiz.party.contact.ContactHelper;
import org.ofbiz.product.config.ProductConfigWorker;
import org.ofbiz.product.config.ProductConfigWrapper;
import org.ofbiz.product.store.ProductStoreWorker;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.GenericServiceException;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ServiceContext;
import org.ofbiz.service.ServiceUtil;
import java.math.BigDecimal;
import java.math.MathContext;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Shopping Cart Services
*/
public class ShoppingCartServices {
private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass());
public static final String resource = "OrderUiLabels";
public static final String resource_error = "OrderErrorUiLabels";
public static final MathContext generalRounding = new MathContext(10);
public static Map<String, Object> assignItemShipGroup(DispatchContext dctx, Map<String, Object> context) {
ShoppingCart cart = (ShoppingCart) context.get("shoppingCart");
Integer fromGroupIndex = (Integer) context.get("fromGroupIndex");
Integer toGroupIndex = (Integer) context.get("toGroupIndex");
Integer itemIndex = (Integer) context.get("itemIndex");
BigDecimal quantity = (BigDecimal) context.get("quantity");
Boolean clearEmptyGroups = (Boolean) context.get("clearEmptyGroups");
if (clearEmptyGroups == null) {
clearEmptyGroups = Boolean.TRUE;
}
Debug.logInfo("From Group - " + fromGroupIndex + " To Group - " + toGroupIndex + "Item - " + itemIndex + "(" + quantity + ")", module);
if (fromGroupIndex.equals(toGroupIndex)) {
// nothing to do
return ServiceUtil.returnSuccess();
}
cart.positionItemToGroup(itemIndex, quantity,
fromGroupIndex, toGroupIndex, clearEmptyGroups);
Debug.logInfo("Called cart.positionItemToGroup()", module);
return ServiceUtil.returnSuccess();
}
public static Map<String, Object>setShippingOptions(DispatchContext dctx, Map<String, Object> context) {
ShoppingCart cart = (ShoppingCart) context.get("shoppingCart");
Integer groupIndex = (Integer) context.get("groupIndex");
String shippingContactMechId = (String) context.get("shippingContactMechId");
String shipmentMethodString = (String) context.get("shipmentMethodString");
String shippingInstructions = (String) context.get("shippingInstructions");
String giftMessage = (String) context.get("giftMessage");
Boolean maySplit = (Boolean) context.get("maySplit");
Boolean isGift = (Boolean) context.get("isGift");
Locale locale = (Locale) context.get("locale");
ShoppingCart.CartShipInfo csi = cart.getShipInfo(groupIndex);
if (csi != null) {
int idx = groupIndex;
if (UtilValidate.isNotEmpty(shipmentMethodString)) {
int delimiterPos = shipmentMethodString.indexOf('@');
String shipmentMethodTypeId = null;
String carrierPartyId = null;
if (delimiterPos > 0) {
shipmentMethodTypeId = shipmentMethodString.substring(0, delimiterPos);
carrierPartyId = shipmentMethodString.substring(delimiterPos + 1);
}
cart.setShipmentMethodTypeId(idx, shipmentMethodTypeId);
cart.setCarrierPartyId(idx, carrierPartyId);
}
cart.setShippingInstructions(idx, shippingInstructions);
cart.setShippingContactMechId(idx, shippingContactMechId);
cart.setGiftMessage(idx, giftMessage);
if (maySplit != null) {
cart.setMaySplit(idx, maySplit);
}
if (isGift != null) {
cart.setIsGift(idx, isGift);
}
} else {
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,"OrderCartShipGroupNotFound", UtilMisc.toMap("groupIndex",groupIndex), locale));
}
return ServiceUtil.returnSuccess();
}
public static Map<String, Object>setPaymentOptions(DispatchContext dctx, Map<String, Object> context) {
Locale locale = (Locale) context.get("locale");
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,"OrderServiceNotYetImplemented",locale));
}
public static Map<String, Object>setOtherOptions(DispatchContext dctx, Map<String, Object> context) {
ShoppingCart cart = (ShoppingCart) context.get("shoppingCart");
String orderAdditionalEmails = (String) context.get("orderAdditionalEmails");
String correspondingPoId = (String) context.get("correspondingPoId");
cart.setOrderAdditionalEmails(orderAdditionalEmails);
if (UtilValidate.isNotEmpty(correspondingPoId)) {
cart.setPoNumber(correspondingPoId);
} else {
cart.setPoNumber(null);
}
return ServiceUtil.returnSuccess();
}
public static Map<String, Object>loadCartFromOrder(DispatchContext dctx, Map<String, Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
Delegator delegator = dctx.getDelegator();
GenericValue userLogin = (GenericValue) context.get("userLogin");
String orderId = (String) context.get("orderId");
Boolean skipInventoryChecks = (Boolean) context.get("skipInventoryChecks");
Boolean skipProductChecks = (Boolean) context.get("skipProductChecks");
boolean includePromoItems = Boolean.TRUE.equals(context.get("includePromoItems"));
Locale locale = (Locale) context.get("locale");
//FIXME: deepak:Personally I don't like the idea of passing flag but for orderItem quantity calculation we need this flag.
String createAsNewOrder = (String) context.get("createAsNewOrder");
List<GenericValue> orderTerms = null;
if (UtilValidate.isEmpty(skipInventoryChecks)) {
skipInventoryChecks = Boolean.FALSE;
}
if (UtilValidate.isEmpty(skipProductChecks)) {
skipProductChecks = Boolean.FALSE;
}
// get the order header
GenericValue orderHeader = null;
try {
orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
orderTerms = orderHeader.getRelated("OrderTerm", null, null, false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// initial require cart info
OrderReadHelper orh = new OrderReadHelper(orderHeader);
String productStoreId = orh.getProductStoreId();
String orderTypeId = orh.getOrderTypeId();
String currency = orh.getCurrency();
String website = orh.getWebSiteId();
String currentStatusString = orh.getCurrentStatusString();
// create the cart
ShoppingCart cart = ShoppingCartFactory.get(delegator, productStoreId).createShoppingCart(delegator, productStoreId, website, locale, currency); // SCIPIO: use factory
cart.setDoPromotions(!includePromoItems);
cart.setOrderType(orderTypeId);
cart.setChannelType(orderHeader.getString("salesChannelEnumId"));
cart.setInternalCode(orderHeader.getString("internalCode"));
cart.setOrderDate(UtilDateTime.nowTimestamp());
cart.setOrderId(orderHeader.getString("orderId"));
cart.setOrderName(orderHeader.getString("orderName"));
cart.setOrderStatusId(orderHeader.getString("statusId"));
cart.setOrderStatusString(currentStatusString);
cart.setFacilityId(orderHeader.getString("originFacilityId"));
try {
cart.setUserLogin(userLogin, dispatcher);
} catch (CartItemModifyException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// set the order name
String orderName = orh.getOrderName();
if (orderName != null) {
cart.setOrderName(orderName);
}
// set the role information
GenericValue placingParty = orh.getPlacingParty();
if (placingParty != null) {
cart.setPlacingCustomerPartyId(placingParty.getString("partyId"));
}
GenericValue billFromParty = orh.getBillFromParty();
if (billFromParty != null) {
cart.setBillFromVendorPartyId(billFromParty.getString("partyId"));
}
GenericValue billToParty = orh.getBillToParty();
if (billToParty != null) {
cart.setBillToCustomerPartyId(billToParty.getString("partyId"));
}
GenericValue shipToParty = orh.getShipToParty();
if (shipToParty != null) {
cart.setShipToCustomerPartyId(shipToParty.getString("partyId"));
}
GenericValue endUserParty = orh.getEndUserParty();
if (endUserParty != null) {
cart.setEndUserCustomerPartyId(endUserParty.getString("partyId"));
cart.setOrderPartyId(endUserParty.getString("partyId"));
}
// load order attributes
List<GenericValue> orderAttributesList = null;
try {
orderAttributesList = EntityQuery.use(delegator).from("OrderAttribute").where("orderId", orderId).queryList();
if (UtilValidate.isNotEmpty(orderAttributesList)) {
for (GenericValue orderAttr : orderAttributesList) {
String name = orderAttr.getString("attrName");
String value = orderAttr.getString("attrValue");
cart.setOrderAttribute(name, value);
}
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// load the payment infos
List<GenericValue> orderPaymentPrefs = null;
try {
List<EntityExpr> exprs = UtilMisc.toList(EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderId));
exprs.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PAYMENT_RECEIVED"));
exprs.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PAYMENT_CANCELLED"));
exprs.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PAYMENT_DECLINED"));
exprs.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PAYMENT_SETTLED"));
orderPaymentPrefs = EntityQuery.use(delegator).from("OrderPaymentPreference").where(exprs).queryList();
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
if (UtilValidate.isNotEmpty(orderPaymentPrefs)) {
Iterator<GenericValue> oppi = orderPaymentPrefs.iterator();
while (oppi.hasNext()) {
GenericValue opp = oppi.next();
String paymentId = opp.getString("paymentMethodId");
if (paymentId == null) {
paymentId = opp.getString("paymentMethodTypeId");
}
BigDecimal maxAmount = opp.getBigDecimal("maxAmount");
String overflow = opp.getString("overflowFlag");
ShoppingCart.CartPaymentInfo cpi = null;
if ((overflow == null || !"Y".equals(overflow)) && oppi.hasNext()) {
cpi = cart.addPaymentAmount(paymentId, maxAmount);
Debug.logInfo("Added Payment: " + paymentId + " / " + maxAmount, module);
} else {
cpi = cart.addPayment(paymentId);
Debug.logInfo("Added Payment: " + paymentId + " / [no max]", module);
}
// for finance account the finAccountId needs to be set
if ("FIN_ACCOUNT".equals(paymentId)) {
cpi.finAccountId = opp.getString("finAccountId");
}
// SCIPIO: 2.1.0: We must recover manualRefNum & securityCode while loading cart from order
if (UtilValidate.isNotEmpty(opp.getString("manualRefNum"))) {
String[] refNum = new String[2];
refNum[0] = opp.getString("manualRefNum");
refNum[1] = opp.getString("manualAuthCode");
cpi.refNum = refNum;
}
if (UtilValidate.isNotEmpty(opp.getString("securityCode"))) {
cpi.securityCode = opp.getString("securityCode");
}
// set the billing account and amount
cart.setBillingAccount(orderHeader.getString("billingAccountId"), orh.getBillingAccountMaxAmount());
}
} else {
Debug.logInfo("No payment preferences found for order #" + orderId, module);
}
// set the order term
if (UtilValidate.isNotEmpty(orderTerms)) {
for (GenericValue orderTerm : orderTerms) {
BigDecimal termValue = BigDecimal.ZERO;
if (UtilValidate.isNotEmpty(orderTerm.getString("termValue"))){
termValue = new BigDecimal(orderTerm.getString("termValue"));
}
long termDays = 0;
if (UtilValidate.isNotEmpty(orderTerm.getString("termDays"))) {
termDays = Long.parseLong(orderTerm.getString("termDays").trim());
}
String orderItemSeqId = orderTerm.getString("orderItemSeqId");
cart.addOrderTerm(orderTerm.getString("termTypeId"), orderItemSeqId, termValue, termDays, orderTerm.getString("textValue"), orderTerm.getString("description"));
}
}
List<GenericValue> orderItemShipGroupList = orh.getOrderItemShipGroups();
for (GenericValue orderItemShipGroup: orderItemShipGroupList) {
// should be sorted by shipGroupSeqId
int newShipInfoIndex = cart.addShipInfo();
CartShipInfo cartShipInfo = cart.getShipInfo(newShipInfoIndex);
cartShipInfo.shipAfterDate = orderItemShipGroup.getTimestamp("shipAfterDate");
cartShipInfo.shipBeforeDate = orderItemShipGroup.getTimestamp("shipByDate");
cartShipInfo.shipmentMethodTypeId = orderItemShipGroup.getString("shipmentMethodTypeId");
cartShipInfo.carrierPartyId = orderItemShipGroup.getString("carrierPartyId");
cartShipInfo.supplierPartyId = orderItemShipGroup.getString("supplierPartyId");
cartShipInfo.setMaySplit(orderItemShipGroup.getBoolean("maySplit"));
cartShipInfo.giftMessage = orderItemShipGroup.getString("giftMessage");
cartShipInfo.setContactMechId(orderItemShipGroup.getString("contactMechId"));
cartShipInfo.shippingInstructions = orderItemShipGroup.getString("shippingInstructions");
cartShipInfo.setFacilityId(orderItemShipGroup.getString("facilityId"));
cartShipInfo.setVendorPartyId(orderItemShipGroup.getString("vendorPartyId"));
cartShipInfo.setShipGroupSeqId(orderItemShipGroup.getString("shipGroupSeqId"));
cartShipInfo.shipTaxAdj.addAll(orh.getOrderHeaderAdjustmentsTax(orderItemShipGroup.getString("shipGroupSeqId")));
cartShipInfo.setContactMechId(orderItemShipGroup.getString("contactMechId"));
}
List<GenericValue> orderItems = orh.getOrderItems();
long nextItemSeq = 0;
if (UtilValidate.isNotEmpty(orderItems)) {
Pattern pattern = Pattern.compile("\\P{Digit}");
for (GenericValue item : orderItems) {
// get the next item sequence id
String orderItemSeqId = item.getString("orderItemSeqId");
Matcher pmatcher = pattern.matcher(orderItemSeqId);
orderItemSeqId = pmatcher.replaceAll("");
// get product Id
String productId = item.getString("productId");
GenericValue product = null;
// creates survey responses for Gift cards same as last Order created
Map<String, Object> surveyResponseResult = null;
try {
long seq = Long.parseLong(orderItemSeqId);
if (seq > nextItemSeq) {
nextItemSeq = seq;
}
} catch (NumberFormatException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
if ("ITEM_REJECTED".equals(item.getString("statusId")) || "ITEM_CANCELLED".equals(item.getString("statusId"))) {
continue;
}
try {
product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne();
if ("DIGITAL_GOOD".equals(product.getString("productTypeId"))) {
Map<String, Object> surveyResponseMap = new HashMap<>();
Map<String, Object> answers = new HashMap<>();
List<GenericValue> surveyResponseAndAnswers = EntityQuery.use(delegator).from("SurveyResponseAndAnswer").where("orderId", orderId, "orderItemSeqId", orderItemSeqId).queryList();
if (UtilValidate.isNotEmpty(surveyResponseAndAnswers)) {
String surveyId = EntityUtil.getFirst(surveyResponseAndAnswers).getString("surveyId");
for (GenericValue surveyResponseAndAnswer : surveyResponseAndAnswers) {
answers.put((surveyResponseAndAnswer.get("surveyQuestionId").toString()), surveyResponseAndAnswer.get("textResponse"));
}
surveyResponseMap.put("answers", answers);
surveyResponseMap.put("surveyId", surveyId);
surveyResponseResult = dispatcher.runSync("createSurveyResponse", surveyResponseMap);
if (ServiceUtil.isError(surveyResponseResult)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(surveyResponseResult));
}
}
}
} catch (GenericEntityException | GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// do not include PROMO items
if (!includePromoItems && item.get("isPromo") != null && "Y".equals(item.getString("isPromo"))) {
continue;
}
// not a promo item; go ahead and add it in
BigDecimal amount = item.getBigDecimal("selectedAmount");
if (amount == null) {
amount = BigDecimal.ZERO;
}
//BigDecimal quantity = item.getBigDecimal("quantity");
BigDecimal quantity = BigDecimal.ZERO;
if("ITEM_COMPLETED".equals(item.getString("statusId")) && "N".equals(createAsNewOrder)) {
quantity = item.getBigDecimal("quantity");
} else {
quantity = OrderReadHelper.getOrderItemQuantity(item);
}
if (quantity == null) {
quantity = BigDecimal.ZERO;
}
BigDecimal unitPrice = null;
if ("Y".equals(item.getString("isModifiedPrice"))) {
unitPrice = item.getBigDecimal("unitPrice");
}
int itemIndex = -1;
if (item.get("productId") == null) {
// non-product item
String itemType = item.getString("orderItemTypeId");
String desc = item.getString("itemDescription");
try {
// TODO: passing in null now for itemGroupNumber, but should reproduce from OrderItemGroup records
itemIndex = cart.addNonProductItem(itemType, desc, null, unitPrice, quantity, null, null, null, dispatcher);
} catch (CartItemModifyException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
} else {
// product item
String prodCatalogId = item.getString("prodCatalogId");
//prepare the rental data
Timestamp reservStart = null;
BigDecimal reservLength = null;
BigDecimal reservPersons = null;
String accommodationMapId = null;
String accommodationSpotId = null;
GenericValue workEffort = null;
String workEffortId = orh.getCurrentOrderItemWorkEffort(item);
if (workEffortId != null) {
try {
workEffort = EntityQuery.use(delegator).from("WorkEffort").where("workEffortId", workEffortId).queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
}
if (workEffort != null && "ASSET_USAGE".equals(workEffort.getString("workEffortTypeId"))) {
reservStart = workEffort.getTimestamp("estimatedStartDate");
reservLength = OrderReadHelper.getWorkEffortRentalLength(workEffort);
reservPersons = workEffort.getBigDecimal("reservPersons");
accommodationMapId = workEffort.getString("accommodationMapId");
accommodationSpotId = workEffort.getString("accommodationSpotId");
} //end of rental data
//check for AGGREGATED products
ProductConfigWrapper configWrapper = null;
String configId = null;
try {
product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne();
if (EntityTypeUtil.hasParentType(delegator, "ProductType", "productTypeId", product.getString("productTypeId"), "parentTypeId", "AGGREGATED")) {
GenericValue productAssoc = EntityQuery.use(delegator).from("ProductAssoc")
.where("productAssocTypeId", "PRODUCT_CONF", "productIdTo", product.getString("productId"))
.filterByDate()
.queryFirst();
if (productAssoc != null) {
productId = productAssoc.getString("productId");
configId = product.getString("configId");
}
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (UtilValidate.isNotEmpty(configId)) {
configWrapper = ProductConfigWorker.loadProductConfigWrapper(delegator, dispatcher, configId, productId, productStoreId, prodCatalogId, website, currency, locale, userLogin);
}
try {
itemIndex = cart.addItemToEnd(productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersons,accommodationMapId,accommodationSpotId, null, null, prodCatalogId, configWrapper, item.getString("orderItemTypeId"), dispatcher, null, unitPrice == null ? null : false, skipInventoryChecks, skipProductChecks);
} catch (ItemNotFoundException | CartItemModifyException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
}
// flag the item w/ the orderItemSeqId so we can reference it
ShoppingCartItem cartItem = cart.findCartItem(itemIndex);
cartItem.setIsPromo(item.get("isPromo") != null && "Y".equals(item.getString("isPromo")));
cartItem.setOrderItemSeqId(item.getString("orderItemSeqId"));
try {
cartItem.setItemGroup(cart.addItemGroup(item.getRelatedOne("OrderItemGroup", true)));
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// attach surveyResponseId for each item
if (UtilValidate.isNotEmpty(surveyResponseResult)){
cartItem.setAttribute("surveyResponseId", surveyResponseResult.get("surveyResponseId"));
}
// attach addition item information
cartItem.setStatusId(item.getString("statusId"));
cartItem.setItemType(item.getString("orderItemTypeId"));
cartItem.setItemComment(item.getString("comments"));
cartItem.setQuoteId(item.getString("quoteId"));
cartItem.setQuoteItemSeqId(item.getString("quoteItemSeqId"));
cartItem.setProductCategoryId(item.getString("productCategoryId"));
cartItem.setDesiredDeliveryDate(item.getTimestamp("estimatedDeliveryDate"));
cartItem.setShipBeforeDate(item.getTimestamp("shipBeforeDate"));
cartItem.setShipAfterDate(item.getTimestamp("shipAfterDate"));
cartItem.setShoppingList(item.getString("shoppingListId"), item.getString("shoppingListItemSeqId"));
cartItem.setIsModifiedPrice("Y".equals(item.getString("isModifiedPrice")));
cartItem.setName(item.getString("itemDescription"));
cartItem.setExternalId(item.getString("externalId"));
cartItem.setListPrice(item.getBigDecimal("unitListPrice"));
// load order item attributes
List<GenericValue> orderItemAttributesList = null;
try {
orderItemAttributesList = EntityQuery.use(delegator).from("OrderItemAttribute").where("orderId", orderId, "orderItemSeqId", orderItemSeqId).queryList();
if (UtilValidate.isNotEmpty(orderItemAttributesList)) {
for (GenericValue orderItemAttr : orderItemAttributesList) {
String name = orderItemAttr.getString("attrName");
String value = orderItemAttr.getString("attrValue");
cartItem.setOrderItemAttribute(name, value);
}
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// load order item contact mechs
List<GenericValue> orderItemContactMechList = null;
try {
orderItemContactMechList = EntityQuery.use(delegator).from("OrderItemContactMech").where("orderId", orderId, "orderItemSeqId", orderItemSeqId).queryList();
if (UtilValidate.isNotEmpty(orderItemContactMechList)) {
for (GenericValue orderItemContactMech : orderItemContactMechList) {
String contactMechPurposeTypeId = orderItemContactMech.getString("contactMechPurposeTypeId");
String contactMechId = orderItemContactMech.getString("contactMechId");
cartItem.addContactMech(contactMechPurposeTypeId, contactMechId);
}
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// set the PO number on the cart
cart.setPoNumber(item.getString("correspondingPoId"));
// get all item adjustments EXCEPT tax adjustments
List<GenericValue> itemAdjustments = orh.getOrderItemAdjustments(item);
if (itemAdjustments != null) {
for (GenericValue itemAdjustment : itemAdjustments) {
if (!isTaxAdjustment(itemAdjustment)) {
cartItem.addAdjustment(itemAdjustment);
}
}
}
}
// setup the OrderItemShipGroupAssoc records
if (UtilValidate.isNotEmpty(orderItems)) {
int itemIndex = 0;
for (GenericValue item : orderItems) {
// if rejected or cancelled ignore, just like above otherwise all indexes will be off by one!
if ("ITEM_REJECTED".equals(item.getString("statusId")) || "ITEM_CANCELLED".equals(item.getString("statusId"))) {
continue;
}
List<GenericValue> orderItemAdjustments = orh.getOrderItemAdjustments(item);
// set the item's ship group info
List<GenericValue> shipGroupAssocs = orh.getOrderItemShipGroupAssocs(item);
if (UtilValidate.isNotEmpty(shipGroupAssocs)) {
shipGroupAssocs = EntityUtil.orderBy(shipGroupAssocs, UtilMisc.toList("-shipGroupSeqId"));
}
for (int g = 0; g < shipGroupAssocs.size(); g++) {
GenericValue sgAssoc = shipGroupAssocs.get(g);
BigDecimal shipGroupQty = OrderReadHelper.getOrderItemShipGroupQuantity(sgAssoc);
if (shipGroupQty == null) {
shipGroupQty = BigDecimal.ZERO;
}
String cartShipGroupIndexStr = sgAssoc.getString("shipGroupSeqId");
int cartShipGroupIndex = cart.getShipInfoIndex(cartShipGroupIndexStr);
if (cartShipGroupIndex > 0) {
cart.positionItemToGroup(itemIndex, shipGroupQty, 0, cartShipGroupIndex, false);
}
// because the ship groups are setup before loading items, and the ShoppingCart.addItemToEnd
// method is called when loading items above and it calls ShoppingCart.setItemShipGroupQty,
// this may not be necessary here, so check it first as calling it here with 0 quantity and
// such ends up removing cart items from the group, which causes problems later with inventory
// reservation, tax calculation, etc.
ShoppingCart.CartShipInfo csi = cart.getShipInfo(cartShipGroupIndex);
ShoppingCartItem cartItem = cart.findCartItem(itemIndex);
if (cartItem == null || cartItem.getQuantity() == null ||
BigDecimal.ZERO.equals(cartItem.getQuantity()) ||
shipGroupQty.equals(cartItem.getQuantity())) {
Debug.logInfo("In loadCartFromOrder not adding item [" + item.getString("orderItemSeqId") +
"] to ship group with index [" + itemIndex + "]; group quantity is [" + shipGroupQty +
"] item quantity is [" + (cartItem != null ? cartItem.getQuantity() : "no cart item") +
"] cartShipGroupIndex is [" + cartShipGroupIndex + "], csi.shipItemInfo.size(): " +
(cartShipGroupIndex < 0 ? 0 : csi.shipItemInfo.size()), module);
} else {
cart.setItemShipGroupQty(itemIndex, shipGroupQty, cartShipGroupIndex);
}
List<GenericValue> shipGroupItemAdjustments = EntityUtil.filterByAnd(orderItemAdjustments, UtilMisc.toMap("shipGroupSeqId", cartShipGroupIndexStr));
if (cartItem == null || cartShipGroupIndex < 0) {
Debug.logWarning("In loadCartFromOrder could not find cart item for itemIndex=" + itemIndex + ", for orderId=" + orderId, module);
} else {
CartShipItemInfo cartShipItemInfo = csi.getShipItemInfo(cartItem);
if (cartShipItemInfo == null) {
Debug.logWarning("In loadCartFromOrder could not find CartShipItemInfo for itemIndex=" + itemIndex + ", for orderId=" + orderId, module);
} else {
List<GenericValue> itemTaxAdj = cartShipItemInfo.itemTaxAdj;
for (GenericValue shipGroupItemAdjustment : shipGroupItemAdjustments) {
if (isTaxAdjustment(shipGroupItemAdjustment)) {
itemTaxAdj.add(shipGroupItemAdjustment);
}
}
}
}
// SCIPIO: 2.1.0: loading shipping costs and shipping method from order when we got a shipping destination
if (UtilValidate.isNotEmpty(csi.getContactMechId())) {
ShippingEstimateWrapper shippingEstimateWrapper = ShippingEstimateWrapper.getWrapper(dispatcher, cart, cartShipGroupIndex);
try {
List<GenericValue> productStoreShipmentMeths = EntityQuery.use(delegator).from("ProductStoreShipmentMethView").where(UtilMisc.toMap(
"shipmentMethodTypeId", csi.shipmentMethodTypeId,
"partyId", csi.carrierPartyId,
"productStoreId", productStoreId,
"roleTypeId","CARRIER"
)).queryList();
if (productStoreShipmentMeths.size() > 1) {
Debug.logWarning("Found multiple ProductStoreShipmentMeth for partyId[" + csi.carrierPartyId
+ "] shipmentMethodTypeId[" + csi.shipmentMethodTypeId + "] "
+ "] productStoreId[ " + productStoreId
+ "] roleTypeId[CARRIER]", module);
}
GenericValue productStoreShipmentMeth = EntityUtil.getFirst(productStoreShipmentMeths);
csi.shipEstimate = shippingEstimateWrapper.getShippingEstimate(productStoreShipmentMeth);
csi.productStoreShipMethId = productStoreShipmentMeth.getString("productStoreShipMethId");
} catch (GenericEntityException e) {
Debug.logError(e.getMessage(), module);
}
}
}
itemIndex ++;
}
}
// set the item seq in the cart
if (nextItemSeq > 0) {
try {
cart.setNextItemSeq(nextItemSeq+1);
} catch (GeneralException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
}
}
if (includePromoItems) {
for (String productPromoCode: orh.getProductPromoCodesEntered()) {
cart.addProductPromoCode(productPromoCode, dispatcher);
}
for (GenericValue productPromoUse: orh.getProductPromoUse()) {
cart.addProductPromoUse(productPromoUse.getString("productPromoId"), productPromoUse.getString("productPromoCodeId"), productPromoUse.getBigDecimal("totalDiscountAmount"), productPromoUse.getBigDecimal("quantityLeftInActions"), new HashMap<ShoppingCartItem, BigDecimal>());
}
}
// SCIPIO: 2.1.0: apply promotions
ProductPromoWorker.doPromotions(cart, dispatcher);
List<GenericValue> adjustments = orh.getOrderHeaderAdjustments();
// If applyQuoteAdjustments is set to false then standard cart adjustments are used.
if (!adjustments.isEmpty()) {
// The cart adjustments are added to the cart
cart.getAdjustments().addAll(adjustments);
}
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("shoppingCart", cart);
return result;
}
public static Map<String, Object> loadCartFromQuote(DispatchContext dctx, Map<String, Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
Delegator delegator = dctx.getDelegator();
GenericValue userLogin = (GenericValue) context.get("userLogin");
String quoteId = (String) context.get("quoteId");
String applyQuoteAdjustmentsString = (String) context.get("applyQuoteAdjustments");
Locale locale = (Locale) context.get("locale");
boolean applyQuoteAdjustments = applyQuoteAdjustmentsString == null || "true".equals(applyQuoteAdjustmentsString);
// get the quote header
GenericValue quote = null;
try {
quote = EntityQuery.use(delegator).from("Quote").where("quoteId", quoteId).queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// initial require cart info
String productStoreId = quote.getString("productStoreId");
String currency = quote.getString("currencyUomId");
// create the cart
ShoppingCart cart = ShoppingCartFactory.createShoppingCart(delegator, productStoreId, locale, currency); // SCIPIO: use factory
// set shopping cart type
if ("PURCHASE_QUOTE".equals(quote.getString("quoteTypeId"))) {
cart.setOrderType("PURCHASE_ORDER");
cart.setBillFromVendorPartyId(quote.getString("partyId"));
}
try {
cart.setUserLogin(userLogin, dispatcher);
} catch (CartItemModifyException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
cart.setQuoteId(quoteId);
cart.setOrderName(quote.getString("quoteName"));
cart.setChannelType(quote.getString("salesChannelEnumId"));
List<GenericValue>quoteItems = null;
List<GenericValue>quoteAdjs = null;
List<GenericValue>quoteRoles = null;
List<GenericValue>quoteAttributes = null;
List<GenericValue>quoteTerms = null;
try {
quoteItems = quote.getRelated("QuoteItem", null, UtilMisc.toList("quoteItemSeqId"), false);
quoteAdjs = quote.getRelated("QuoteAdjustment", null, null, false);
quoteRoles = quote.getRelated("QuoteRole", null, null, false);
quoteAttributes = quote.getRelated("QuoteAttribute", null, null, false);
quoteTerms = quote.getRelated("QuoteTerm", null, null, false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// set the role information
cart.setOrderPartyId(quote.getString("partyId"));
if (UtilValidate.isNotEmpty(quoteRoles)) {
for (GenericValue quoteRole : quoteRoles) {
String quoteRoleTypeId = quoteRole.getString("roleTypeId");
String quoteRolePartyId = quoteRole.getString("partyId");
if ("PLACING_CUSTOMER".equals(quoteRoleTypeId)) {
cart.setPlacingCustomerPartyId(quoteRolePartyId);
} else if ("BILL_TO_CUSTOMER".equals(quoteRoleTypeId)) {
cart.setBillToCustomerPartyId(quoteRolePartyId);
} else if ("SHIP_TO_CUSTOMER".equals(quoteRoleTypeId)) {
cart.setShipToCustomerPartyId(quoteRolePartyId);
} else if ("END_USER_CUSTOMER".equals(quoteRoleTypeId)) {
cart.setEndUserCustomerPartyId(quoteRolePartyId);
} else if ("BILL_FROM_VENDOR".equals(quoteRoleTypeId)) {
cart.setBillFromVendorPartyId(quoteRolePartyId);
} else {
cart.addAdditionalPartyRole(quoteRolePartyId, quoteRoleTypeId);
}
}
}
// set the order term
if (UtilValidate.isNotEmpty(quoteTerms)) {
// create order term from quote term
for (GenericValue quoteTerm : quoteTerms) {
BigDecimal termValue = BigDecimal.ZERO;
if (UtilValidate.isNotEmpty(quoteTerm.getString("termValue"))){
termValue = new BigDecimal(quoteTerm.getString("termValue"));
}
long termDays = 0;
if (UtilValidate.isNotEmpty(quoteTerm.getString("termDays"))) {
termDays = Long.parseLong(quoteTerm.getString("termDays").trim());
}
String orderItemSeqId = quoteTerm.getString("quoteItemSeqId");
cart.addOrderTerm(quoteTerm.getString("termTypeId"), orderItemSeqId,termValue, termDays, quoteTerm.getString("textValue"),quoteTerm.getString("description"));
}
}
// set the attribute information
if (UtilValidate.isNotEmpty(quoteAttributes)) {
for (GenericValue quoteAttribute : quoteAttributes) {
cart.setOrderAttribute(quoteAttribute.getString("attrName"), quoteAttribute.getString("attrValue"));
}
}
// Convert the quote adjustment to order header adjustments and
// put them in a map: the key/values pairs are quoteItemSeqId/List of adjs
Map<String, List<GenericValue>> orderAdjsMap = new HashMap<>() ;
for (GenericValue quoteAdj : quoteAdjs) {
List<GenericValue> orderAdjs = orderAdjsMap.get(UtilValidate.isNotEmpty(quoteAdj.getString("quoteItemSeqId")) ? quoteAdj.getString("quoteItemSeqId") : quoteId);
if (orderAdjs == null) {
orderAdjs = new LinkedList<>();
orderAdjsMap.put(UtilValidate.isNotEmpty(quoteAdj.getString("quoteItemSeqId")) ? quoteAdj.getString("quoteItemSeqId") : quoteId, orderAdjs);
}
// convert quote adjustments to order adjustments
GenericValue orderAdj = delegator.makeValue("OrderAdjustment");
orderAdj.put("orderAdjustmentId", quoteAdj.get("quoteAdjustmentId"));
orderAdj.put("orderAdjustmentTypeId", quoteAdj.get("quoteAdjustmentTypeId"));
orderAdj.put("orderItemSeqId", quoteAdj.get("quoteItemSeqId"));
orderAdj.put("comments", quoteAdj.get("comments"));
orderAdj.put("description", quoteAdj.get("description"));
orderAdj.put("amount", quoteAdj.get("amount"));
orderAdj.put("productPromoId", quoteAdj.get("productPromoId"));
orderAdj.put("productPromoRuleId", quoteAdj.get("productPromoRuleId"));
orderAdj.put("productPromoActionSeqId", quoteAdj.get("productPromoActionSeqId"));
orderAdj.put("productFeatureId", quoteAdj.get("productFeatureId"));
orderAdj.put("correspondingProductId", quoteAdj.get("correspondingProductId"));
orderAdj.put("sourceReferenceId", quoteAdj.get("sourceReferenceId"));
orderAdj.put("sourcePercentage", quoteAdj.get("sourcePercentage"));
orderAdj.put("customerReferenceId", quoteAdj.get("customerReferenceId"));
orderAdj.put("primaryGeoId", quoteAdj.get("primaryGeoId"));
orderAdj.put("secondaryGeoId", quoteAdj.get("secondaryGeoId"));
orderAdj.put("exemptAmount", quoteAdj.get("exemptAmount"));
orderAdj.put("taxAuthGeoId", quoteAdj.get("taxAuthGeoId"));
orderAdj.put("taxAuthPartyId", quoteAdj.get("taxAuthPartyId"));
orderAdj.put("overrideGlAccountId", quoteAdj.get("overrideGlAccountId"));
orderAdj.put("includeInTax", quoteAdj.get("includeInTax"));
orderAdj.put("includeInShipping", quoteAdj.get("includeInShipping"));
orderAdj.put("createdDate", quoteAdj.get("createdDate"));
orderAdj.put("createdByUserLogin", quoteAdj.get("createdByUserLogin"));
orderAdjs.add(orderAdj);
}
long nextItemSeq = 0;
if (UtilValidate.isNotEmpty(quoteItems)) {
Pattern pattern = Pattern.compile("\\P{Digit}");
for (GenericValue quoteItem : quoteItems) {
// get the next item sequence id
String orderItemSeqId = quoteItem.getString("quoteItemSeqId");
Matcher pmatcher = pattern.matcher(orderItemSeqId);
orderItemSeqId = pmatcher.replaceAll("");
try {
long seq = Long.parseLong(orderItemSeqId);
if (seq > nextItemSeq) {
nextItemSeq = seq;
}
} catch (NumberFormatException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
boolean isPromo = quoteItem.get("isPromo") != null && "Y".equals(quoteItem.getString("isPromo"));
if (isPromo && !applyQuoteAdjustments) {
// do not include PROMO items
continue;
}
// not a promo item; go ahead and add it in
BigDecimal amount = quoteItem.getBigDecimal("selectedAmount");
if (amount == null) {
amount = BigDecimal.ZERO;
}
BigDecimal quantity = quoteItem.getBigDecimal("quantity");
if (quantity == null) {
quantity = BigDecimal.ZERO;
}
BigDecimal quoteUnitPrice = quoteItem.getBigDecimal("quoteUnitPrice");
if (quoteUnitPrice == null) {
quoteUnitPrice = BigDecimal.ZERO;
}
if (amount.compareTo(BigDecimal.ZERO) > 0) {
// If, in the quote, an amount is set, we need to
// pass to the cart the quoteUnitPrice/amount value.
quoteUnitPrice = quoteUnitPrice.divide(amount, generalRounding);
}
//rental product data
Timestamp reservStart = quoteItem.getTimestamp("reservStart");
BigDecimal reservLength = quoteItem.getBigDecimal("reservLength");
BigDecimal reservPersons = quoteItem.getBigDecimal("reservPersons");
int itemIndex = -1;
if (quoteItem.get("productId") == null) {
// non-product item
String desc = quoteItem.getString("comments");
try {
// note that passing in null for itemGroupNumber as there is no real grouping concept in the quotes right now
itemIndex = cart.addNonProductItem(null, desc, null, null, quantity, null, null, null, dispatcher);
} catch (CartItemModifyException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
} else {
// product item
String productId = quoteItem.getString("productId");
ProductConfigWrapper configWrapper = null;
if (UtilValidate.isNotEmpty(quoteItem.getString("configId"))) {
configWrapper = ProductConfigWorker.loadProductConfigWrapper(delegator, dispatcher, quoteItem.getString("configId"), productId, productStoreId, null, null, currency, locale, userLogin);
}
try {
itemIndex = cart.addItemToEnd(productId, amount, quantity, quoteUnitPrice, reservStart, reservLength, reservPersons,null,null, null, null, null, configWrapper, null, dispatcher, !applyQuoteAdjustments, quoteUnitPrice.compareTo(BigDecimal.ZERO) == 0, Boolean.FALSE, Boolean.FALSE);
} catch (ItemNotFoundException | CartItemModifyException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
}
// flag the item w/ the orderItemSeqId so we can reference it
ShoppingCartItem cartItem = cart.findCartItem(itemIndex);
cartItem.setOrderItemSeqId(orderItemSeqId);
// attach additional item information
cartItem.setItemComment(quoteItem.getString("comments"));
cartItem.setQuoteId(quoteItem.getString("quoteId"));
cartItem.setQuoteItemSeqId(quoteItem.getString("quoteItemSeqId"));
cartItem.setIsPromo(isPromo);
}
}
// If applyQuoteAdjustments is set to false then standard cart adjustments are used.
if (applyQuoteAdjustments) {
// The cart adjustments, derived from quote adjustments, are added to the cart
// Tax adjustments should be added to the shipping group and shipping group item info
// Other adjustments like promotional price should be added to the cart independent of
// the ship group.
// We're creating the cart right now using data from the quote, so there cannot yet be more than one ship group.
List<GenericValue> cartAdjs = cart.getAdjustments();
CartShipInfo shipInfo = cart.getOrAddShipInfo(0);
List<GenericValue> adjs = orderAdjsMap.get(quoteId);
if (adjs != null) {
for (GenericValue adj : adjs) {
if (isTaxAdjustment( adj )) {
shipInfo.shipTaxAdj.add(adj);
} else {
cartAdjs.add(adj);
}
}
}
// The cart item adjustments, derived from quote item adjustments, are added to the cart
if (quoteItems != null) {
for (ShoppingCartItem item : cart) {
String orderItemSeqId = item.getOrderItemSeqId();
if (orderItemSeqId != null) {
adjs = orderAdjsMap.get(orderItemSeqId);
} else {
adjs = null;
}
if (adjs != null) {
for (GenericValue adj : adjs) {
if (isTaxAdjustment( adj )) {
CartShipItemInfo csii = shipInfo.getShipItemInfo(item);
if (csii.itemTaxAdj == null) {
shipInfo.setItemInfo(item, UtilMisc.toList(adj));
} else {
csii.itemTaxAdj.add(adj);
}
} else {
item.addAdjustment(adj);
}
}
}
}
}
}
// set the item seq in the cart
if (nextItemSeq > 0) {
try {
cart.setNextItemSeq(nextItemSeq+1);
} catch (GeneralException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
}
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("shoppingCart", cart);
return result;
}
private static boolean isTaxAdjustment(GenericValue cartAdj) {
String adjType = cartAdj.getString("orderAdjustmentTypeId");
return "SALES_TAX".equals(adjType) || "VAT_TAX".equals(adjType) || "VAT_PRICE_CORRECT".equals(adjType);
}
public static Map<String, Object>loadCartFromShoppingList(DispatchContext dctx, Map<String, Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
Delegator delegator = dctx.getDelegator();
GenericValue userLogin = (GenericValue) context.get("userLogin");
String shoppingListId = (String) context.get("shoppingListId");
String orderPartyId = (String) context.get("orderPartyId");
Locale locale = (Locale) context.get("locale");
// get the shopping list header
GenericValue shoppingList = null;
try {
shoppingList = EntityQuery.use(delegator).from("ShoppingList").where("shoppingListId", shoppingListId).queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// initial required cart info
String productStoreId = shoppingList.getString("productStoreId");
String currency = shoppingList.getString("currencyUom");
// If no currency has been set in the ShoppingList, use the ProductStore default currency
if (currency == null) {
try {
GenericValue productStore = shoppingList.getRelatedOne("ProductStore", false);
if (productStore != null) {
currency = productStore.getString("defaultCurrencyUomId");
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
}
// If we still have no currency, use the default from general.properties. Failing that, use USD
if (currency == null) {
currency = EntityUtilProperties.getPropertyValue("general", "currency.uom.id.default", "USD", delegator);
}
// create the cart
ShoppingCart cart = ShoppingCartFactory.createShoppingCart(delegator, productStoreId, locale, currency); // SCIPIO: use factory
try {
cart.setUserLogin(userLogin, dispatcher);
} catch (CartItemModifyException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// set the role information
if (UtilValidate.isNotEmpty(orderPartyId)) {
cart.setOrderPartyId(orderPartyId);
} else {
cart.setOrderPartyId(shoppingList.getString("partyId"));
}
List<GenericValue>shoppingListItems = null;
try {
shoppingListItems = shoppingList.getRelated("ShoppingListItem", null, null, false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
long nextItemSeq = 0;
if (UtilValidate.isNotEmpty(shoppingListItems)) {
Pattern pattern = Pattern.compile("\\P{Digit}");
for (GenericValue shoppingListItem : shoppingListItems) {
// get the next item sequence id
String orderItemSeqId = shoppingListItem.getString("shoppingListItemSeqId");
Matcher pmatcher = pattern.matcher(orderItemSeqId);
orderItemSeqId = pmatcher.replaceAll("");
try {
long seq = Long.parseLong(orderItemSeqId);
if (seq > nextItemSeq) {
nextItemSeq = seq;
}
} catch (NumberFormatException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
BigDecimal modifiedPrice = shoppingListItem.getBigDecimal("modifiedPrice");
BigDecimal quantity = shoppingListItem.getBigDecimal("quantity");
if (quantity == null) {
quantity = BigDecimal.ZERO;
}
int itemIndex = -1;
if (shoppingListItem.get("productId") != null) {
// product item
String productId = shoppingListItem.getString("productId");
ProductConfigWrapper configWrapper = null;
if (UtilValidate.isNotEmpty(shoppingListItem.getString("configId"))) {
configWrapper = ProductConfigWorker.loadProductConfigWrapper(delegator, dispatcher, shoppingListItem.getString("configId"), productId, productStoreId, null, null, currency, locale, userLogin);
}
try {
itemIndex = cart.addItemToEnd(productId, null, quantity, null, null, null, null, null, configWrapper, dispatcher, Boolean.TRUE, Boolean.TRUE);
} catch (ItemNotFoundException | CartItemModifyException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// set the modified price
if (modifiedPrice != null && modifiedPrice.doubleValue() != 0) {
ShoppingCartItem item = cart.findCartItem(itemIndex);
if (item != null) {
item.setIsModifiedPrice(true);
item.setBasePrice(modifiedPrice);
}
}
}
// flag the item w/ the orderItemSeqId so we can reference it
ShoppingCartItem cartItem = cart.findCartItem(itemIndex);
cartItem.setOrderItemSeqId(orderItemSeqId);
// attach additional item information
cartItem.setShoppingList(shoppingListItem.getString("shoppingListId"), shoppingListItem.getString("shoppingListItemSeqId"));
}
}
// set the item seq in the cart
if (nextItemSeq > 0) {
try {
cart.setNextItemSeq(nextItemSeq+1);
} catch (GeneralException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
}
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("shoppingCart", cart);
return result;
}
public static Map<String, Object>getShoppingCartData(DispatchContext dctx, Map<String, Object> context) {
Map<String, Object> result = ServiceUtil.returnSuccess();
Locale locale = (Locale) context.get("locale");
ShoppingCart shoppingCart = (ShoppingCart) context.get("shoppingCart");
if (shoppingCart != null) {
String isoCode = shoppingCart.getCurrency();
result.put("totalQuantity", shoppingCart.getTotalQuantity());
result.put("currencyIsoCode",isoCode);
result.put("subTotal", shoppingCart.getSubTotal());
result.put("subTotalCurrencyFormatted",org.ofbiz.base.util.UtilFormatOut.formatCurrency(shoppingCart.getSubTotal(), isoCode, locale));
result.put("totalShipping", shoppingCart.getTotalShipping());
result.put("totalShippingCurrencyFormatted",org.ofbiz.base.util.UtilFormatOut.formatCurrency(shoppingCart.getTotalShipping(), isoCode, locale));
result.put("totalSalesTax",shoppingCart.getTotalSalesTax());
result.put("totalSalesTaxCurrencyFormatted",org.ofbiz.base.util.UtilFormatOut.formatCurrency(shoppingCart.getTotalSalesTax(), isoCode, locale));
result.put("displayGrandTotal", shoppingCart.getDisplayGrandTotal());
result.put("displayGrandTotalCurrencyFormatted",org.ofbiz.base.util.UtilFormatOut.formatCurrency(shoppingCart.getDisplayGrandTotal(), isoCode, locale));
BigDecimal orderAdjustmentsTotal = OrderReadHelper.calcOrderAdjustments(OrderReadHelper.getOrderHeaderAdjustments(shoppingCart.getAdjustments(), null), shoppingCart.getSubTotal(), true, true, true);
result.put("displayOrderAdjustmentsTotalCurrencyFormatted", org.ofbiz.base.util.UtilFormatOut.formatCurrency(orderAdjustmentsTotal, isoCode, locale));
Map<String, Object> cartItemData = new HashMap<>();
for (ShoppingCartItem cartLine : shoppingCart) {
int cartLineIndex = shoppingCart.getItemIndex(cartLine);
cartItemData.put("displayItemQty_" + cartLineIndex, cartLine.getQuantity());
cartItemData.put("displayItemPrice_" + cartLineIndex, org.ofbiz.base.util.UtilFormatOut.formatCurrency(cartLine.getDisplayPrice(), isoCode, locale));
cartItemData.put("displayItemSubTotal_" + cartLineIndex, cartLine.getDisplayItemSubTotal());
cartItemData.put("displayItemSubTotalCurrencyFormatted_" + cartLineIndex ,org.ofbiz.base.util.UtilFormatOut.formatCurrency(cartLine.getDisplayItemSubTotal(), isoCode, locale));
cartItemData.put("displayItemAdjustment_" + cartLineIndex ,org.ofbiz.base.util.UtilFormatOut.formatCurrency(cartLine.getOtherAdjustments(), isoCode, locale));
}
result.put("cartItemData",cartItemData);
}
return result;
}
public static Map<String, Object>getShoppingCartItemIndex(DispatchContext dctx, Map<String, Object> context) {
Map<String, Object> result = ServiceUtil.returnSuccess();
ShoppingCart shoppingCart = (ShoppingCart) context.get("shoppingCart");
String productId = (String) context.get("productId");
if (shoppingCart != null && UtilValidate.isNotEmpty(shoppingCart.items())) {
List<ShoppingCartItem> items = shoppingCart.findAllCartItems(productId);
if (items.size() > 0) {
ShoppingCartItem item = items.get(0);
int itemIndex = shoppingCart.getItemIndex(item);
result.put("itemIndex", String.valueOf(itemIndex));
}
}
return result;
}
public static Map<String, Object>resetShipGroupItems(DispatchContext dctx, Map<String, Object> context) {
Map<String, Object> result = ServiceUtil.returnSuccess();
ShoppingCart cart = (ShoppingCart) context.get("shoppingCart");
for (ShoppingCartItem item : cart) {
cart.clearItemShipInfo(item);
cart.setItemShipGroupQty(item, item.getQuantity(), 0);
}
return result;
}
public static Map<String, Object>prepareVendorShipGroups(DispatchContext dctx, Map<String, Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
Delegator delegator = dctx.getDelegator();
ShoppingCart cart = (ShoppingCart) context.get("shoppingCart");
Map<String, Object> result = ServiceUtil.returnSuccess();
try {
Map<String, Object> resp = dispatcher.runSync("resetShipGroupItems", context);
if (ServiceUtil.isError(resp)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(resp));
}
} catch (GenericServiceException e) {
Debug.logError(e.toString(), module);
return ServiceUtil.returnError(e.toString());
}
Map<String, Object> vendorMap = new HashMap<>();
for (ShoppingCartItem item : cart) {
GenericValue vendorProduct = null;
String productId = item.getParentProductId();
if (productId == null) {
productId = item.getProductId();
}
int index = 0;
try {
vendorProduct = EntityQuery.use(delegator).from("VendorProduct").where("productId", productId, "productStoreGroupId", "_NA_").queryFirst();
} catch (GenericEntityException e) {
Debug.logError(e.toString(), module);
}
if (UtilValidate.isEmpty(vendorProduct)) {
if (vendorMap.containsKey("_NA_")) {
index = (Integer) vendorMap.get("_NA_");
cart.positionItemToGroup(item, item.getQuantity(), 0, index, true);
} else {
index = cart.addShipInfo();
vendorMap.put("_NA_", index);
ShoppingCart.CartShipInfo info = cart.getShipInfo(index);
info.setVendorPartyId("_NA_");
info.setShipGroupSeqId(UtilFormatOut.formatPaddedNumber(index, 5));
cart.positionItemToGroup(item, item.getQuantity(), 0, index, true);
}
}
if (vendorProduct != null) {
String vendorPartyId = vendorProduct.getString("vendorPartyId");
if (vendorMap.containsKey(vendorPartyId)) {
index = (Integer) vendorMap.get(vendorPartyId);
cart.positionItemToGroup(item, item.getQuantity(), 0, index, true);
} else {
index = cart.addShipInfo();
vendorMap.put(vendorPartyId, index);
ShoppingCart.CartShipInfo info = cart.getShipInfo(index);
info.setVendorPartyId(vendorPartyId);
info.setShipGroupSeqId(UtilFormatOut.formatPaddedNumber(index, 5));
cart.positionItemToGroup(item, item.getQuantity(), 0, index, true);
}
}
}
return result;
}
/**
* SCIPIO: 2.1.0: Finds abandoned carts
*
* @param ctx
* @return Map with the result of the service, the output parameters.
*/
public static Map<String, Object> findAbandonedCarts(ServiceContext ctx) {
Map<String, Object> result = ServiceUtil.returnSuccess();
Delegator delegator = ctx.delegator();
Locale locale = ctx.locale();
GenericValue userLogin = ctx.userLogin();
Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
Timestamp fromDate = (Timestamp) ctx.get("fromDate");
Long daysOffset = (Long) ctx.get("daysOffset");
String productStoreId = (String) ctx.get("productStoreId");
DynamicViewEntity dve = new DynamicViewEntity();
dve.addMemberEntity("CA", "CartAbandoned");
dve.addMemberEntity("CAS", "CartAbandonedStatus");
dve.addMemberEntity("V", "Visit");
dve.addMemberEntity("P", "Party");
dve.addMemberEntity("UL", "UserLogin");
// Get the latest for any given party visit
dve.addAlias("CA", "visitId", null, null, null, false, "max");
dve.addAlias("CA", "productStoreId", null, null, null, true, null);
dve.addAlias("CA", "webSiteId", null, null, null, true, null);
dve.addAlias("CA", "locale", null, null, null, true, null);
dve.addAlias("CA", "currencyUomId", null, null, null, true, null);
dve.addAlias("CA", "fromDate", null, null, null, true, null);
dve.addAlias("CA", "thruDate", null, null, null, true, null);
dve.addAlias("CAS", "statusId", null, null, null, true, null);
dve.addAlias("CAS", "reminderRetrySeq", null, null, null, true, null);
dve.addAlias("V", "partyId", null, null, null, true, null);
dve.addAlias("V", "userLoginId", null, null, null, true, null);
dve.addViewLink("CA", "V", false, UtilMisc.toList(ModelKeyMap.makeKeyMapList("visitId")));
dve.addViewLink("CA", "CAS", false, UtilMisc.toList(ModelKeyMap.makeKeyMapList("visitId")));
dve.addViewLink("V", "P", true, UtilMisc.toList(ModelKeyMap.makeKeyMapList("partyId")));
dve.addViewLink("V", "UL", true, UtilMisc.toList(ModelKeyMap.makeKeyMapList("userLoginId")));
dve.addRelation("one", null, "Party", ModelKeyMap.makeKeyMapList("partyId"));
dve.addRelation("many", null, "CartAbandonedLine", ModelKeyMap.makeKeyMapList("visitId"));
dve.addRelation("one", null, "CartAbandonedStatus", ModelKeyMap.makeKeyMapList("visitId"));
dve.addRelation("one", null, "Visit", ModelKeyMap.makeKeyMapList("visitId"));
dve.addRelation("one", null, "UserLogin", ModelKeyMap.makeKeyMapList("userLoginId"));
EntityCondition condition = EntityCondition.makeCondition(UtilMisc.toList(
EntityCondition.makeCondition(UtilMisc.toList(
EntityCondition.makeCondition("partyId", EntityOperator.NOT_EQUAL, null),
EntityCondition.makeCondition("userLoginId", EntityOperator.NOT_EQUAL, null)
), EntityOperator.OR),
EntityCondition.makeCondition("statusId", EntityOperator.IN, UtilMisc.toList("AB_PENDING", "AB_IN_PROGRESS")),
EntityCondition.makeCondition("productStoreId", productStoreId)
), EntityOperator.AND);
GenericValue productStore = ProductStoreWorker.getProductStore(productStoreId, delegator);
if (UtilValidate.isEmpty(daysOffset)) {
daysOffset = productStore.getLong("abandonedCartReminderDayOffset");
}
if (UtilValidate.isEmpty(daysOffset)) {
daysOffset = 0L;
}
// If fromDate present, apply filterByDate manually
if (UtilValidate.isNotEmpty(fromDate)) {
condition = EntityCondition.makeCondition(
condition,
EntityCondition.makeCondition(
EntityCondition.makeCondition(
EntityCondition.makeCondition("thruDate", EntityOperator.EQUALS, null),
EntityOperator.OR,
EntityCondition.makeCondition("thruDate", EntityOperator.GREATER_THAN, nowTimestamp)
),
EntityOperator.AND,
EntityCondition.makeCondition(
EntityCondition.makeCondition("fromDate", EntityOperator.EQUALS, null),
EntityOperator.OR,
EntityCondition.makeCondition("fromDate", EntityOperator.LESS_THAN_EQUAL_TO, fromDate)
)
)
);
}
Long maxAbandonedCartReminderRetry = productStore.getLong("maxAbandonedCartReminderRetry");
if (UtilValidate.isNotEmpty(maxAbandonedCartReminderRetry)) {
condition = EntityCondition.makeCondition(
condition,
EntityCondition.makeCondition("reminderRetrySeq", EntityOperator.LESS_THAN_EQUAL_TO, maxAbandonedCartReminderRetry)
);
}
try {
List<GenericValue> abandonedCarts = EntityQuery.use(delegator).from(dve).where(condition).queryList();
result.put("abandonedCarts", abandonedCarts);
// Loop and filter abandoned carts applying daysOffset
List<GenericValue> filteredAbandonedCarts = UtilMisc.newList();
for (GenericValue abandonedCart : abandonedCarts) {
Timestamp abandonedCartFromDate = abandonedCart.getTimestamp("fromDate");
Timestamp abandonedCartThruDate = abandonedCart.getTimestamp("thruDate");
Timestamp abandonedCartFromDateWithDaysOffset = UtilDateTime.addDaysToTimestamp(abandonedCartFromDate, daysOffset.intValue());
Debug.log("abandonedCartFromDate: " + abandonedCartFromDate, module);
Debug.log("abandonedCartThruDate: " + abandonedCartThruDate, module);
Debug.log("abandonedCartFromDateWithDaysOffset: " + abandonedCartFromDateWithDaysOffset, module);
Debug.log("nowTimestamp greater than abandonedCartFromDate: " + (nowTimestamp.compareTo(abandonedCartFromDateWithDaysOffset) >= 0), module);
if ((UtilValidate.isEmpty(abandonedCartFromDate) || (UtilValidate.isNotEmpty(abandonedCartFromDate) && nowTimestamp.compareTo(abandonedCartFromDateWithDaysOffset) >= 0))
&& (UtilValidate.isEmpty(abandonedCartThruDate) || (UtilValidate.isNotEmpty(abandonedCartThruDate) && abandonedCartThruDate.compareTo(nowTimestamp) < 0))) {
filteredAbandonedCarts.add(abandonedCart);
}
}
result.put("abandonedCarts", filteredAbandonedCarts);
} catch (GenericEntityException e) {
Debug.logError(e.getMessage(), module);
return ServiceUtil.returnError(e.getMessage());
}
return result;
}
/**
* SCIPIO: 2.1.0: Send abandoned cart email reminders
*
* @param ctx
* @return
*/
public static Map<String, Object> sendAbandonedCartEmailReminder(ServiceContext ctx) {
Map<String, Object> result = ServiceUtil.returnSuccess();
LocalDispatcher dispatcher = ctx.dispatcher();
Delegator delegator = ctx.delegator();
Locale locale = ctx.locale();
String productStoreId = ctx.getString("productStoreId");
GenericValue userLogin = ctx.userLogin();
List<GenericValue> abandonedCarts = (List<GenericValue>) ctx.get("abandonedCarts");
String emailType = "PRDS_RCVR_ABNDND_CRT";
for (GenericValue abandonedCart : abandonedCarts) {
// get the email setting and send the mail
Map<String, Object> sendMap = new HashMap<>();
GenericValue productStoreEmail = null;
try {
String abandonedCartProductStoreId = productStoreId;
if (UtilValidate.isEmpty(abandonedCartProductStoreId)) {
abandonedCartProductStoreId = abandonedCart.getString("productStoreId");
}
Locale resolvedLocale = locale;
String abandonedCartLocale = abandonedCart.getString("locale");
if (UtilValidate.isNotEmpty(abandonedCartLocale)) {
resolvedLocale = new Locale(abandonedCartLocale);
}
String webSiteId = abandonedCart.getString("webSiteId");
if (UtilValidate.isEmpty(webSiteId)) {
webSiteId = ProductStoreWorker.getStoreWebSiteIdForEmail(delegator, abandonedCartProductStoreId, webSiteId, true);
}
if (webSiteId != null) {
sendMap.put("webSiteId", webSiteId);
} else {
// This is only technically an error if the email contains links back to a website.
Debug.logWarning("sendAbandonedCartEmailReminder: No webSiteId determined for store '" + abandonedCartProductStoreId + "' email", module);
}
GenericValue productStore = ProductStoreWorker.getProductStore(productStoreId, delegator);
List<GenericValue> abandonedCartLines = abandonedCart.getRelatedCache("CartAbandonedLine");
GenericValue abandonedCartStatus = abandonedCart.getRelatedOneCache("CartAbandonedStatus");
if (UtilValidate.isNotEmpty(abandonedCartStatus)) {
Long reminderRetrySeq = abandonedCartStatus.getLong("reminderRetrySeq");
if ((abandonedCartStatus.getString("statusId").equals("AB_PENDING") || abandonedCartStatus.getString("statusId").equals("AB_IN_PROGRESS"))
&& reminderRetrySeq <= productStore.getLong("maxAbandonedCartReminderRetry")) {
abandonedCartStatus.put("reminderRetrySeq", reminderRetrySeq + 1);
if (reminderRetrySeq == productStore.getLong("maxAbandonedCartReminderRetry")) {
abandonedCartStatus.put("statusId", "AB_COMPLETED");
} else {
abandonedCartStatus.put("statusId", "AB_IN_PROGRESS");
}
abandonedCartStatus.store();
productStoreEmail = EntityQuery.use(delegator).from("ProductStoreEmailSetting").where("productStoreId", abandonedCartProductStoreId, "emailType", emailType).cache().queryOne();
GenericValue customerParty = abandonedCart.getRelatedOne("Party");
GenericValue customerEmailAddress =
EntityUtil.getFirst(UtilMisc.toList(ContactHelper.getContactMechByType(customerParty, "EMAIL_ADDRESS", false)));
if (productStoreEmail != null && customerEmailAddress != null) {
String bodyScreenLocation = productStoreEmail.getString("bodyScreenLocation");
if (UtilValidate.isEmpty(bodyScreenLocation)) {
bodyScreenLocation = ProductStoreWorker.getDefaultProductStoreEmailScreenLocation(emailType);
}
sendMap.put("bodyScreenUri", bodyScreenLocation);
Map<String, Object> bodyParameters = UtilMisc.<String, Object>toMap("customerParty", customerParty,
"abandonedCart", abandonedCart, "abandonedCartStatus", abandonedCartStatus, "abandonedCartLines", abandonedCartLines,
"locale", resolvedLocale, "userLogin", userLogin);
bodyParameters.put("productStoreId", abandonedCartProductStoreId); // SCIPIO
sendMap.put("bodyParameters", bodyParameters);
sendMap.put("subject", productStoreEmail.getString("subject"));
sendMap.put("contentType", productStoreEmail.get("contentType"));
sendMap.put("sendFrom", productStoreEmail.get("fromAddress"));
sendMap.put("sendCc", productStoreEmail.get("ccAddress"));
sendMap.put("sendBcc", productStoreEmail.get("bccAddress"));
sendMap.put("sendTo", customerEmailAddress.getString("infoString"));
sendMap.put("sendAs", productStoreEmail.get("sendAs"));
sendMap.put("partyId", customerParty.getString("partyId"));
sendMap.put("userLogin", userLogin);
sendMap.put("locale", resolvedLocale);
Map<String, Object> sendResp = null;
try {
sendResp = dispatcher.runSync("sendMailFromScreen", sendMap);
if (ServiceUtil.isError(sendResp)) {
sendResp.put("emailType", emailType);
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,
"OrderProblemSendingEmail", locale), null, null, sendResp);
}
} catch (GenericServiceException e) {
Debug.logError(e, "Problem sending mail", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource_error,
"OrderProblemSendingEmail", locale));
}
}
}
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
}
return result;
}
/**
* SCIPIO: 2.1.0: Load cart from abandoned cart
*
* @param ctx
* @return Map with the result of the service, the output parameters.
*/
public static Map<String, Object> loadCartFromAbandonedCart(ServiceContext ctx) {
LocalDispatcher dispatcher = ctx.dispatcher();
Delegator delegator = ctx.delegator();
Map<String, Object> context = ctx.context();
GenericValue userLogin = (GenericValue) context.get("userLogin");
GenericValue abandonedCart = (GenericValue) context.get("abandonedCart");
List<GenericValue> abandonedCartLines = (List<GenericValue>) context.get("abandonedCartLines");
Boolean isUserInSession = (Boolean) context.get("isUserInSession");
String visitId = (String) context.get("visitId");
String cartPartyId = (String) context.get("cartPartyId");
Locale locale = (Locale) context.get("locale");
// get abandoned cart
if (UtilValidate.isEmpty(abandonedCart) && UtilValidate.isNotEmpty(visitId)) {
try {
abandonedCart = EntityQuery.use(delegator).from("CartAbandoned").where("visitId", visitId).queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
}
if (UtilValidate.isEmpty(abandonedCart)) {
return ServiceUtil.returnError("Can't find a valid abandoned cart nor a visitId");
}
GenericValue visit = null;
GenericValue abandonedCartUserLogin = null;
try {
visit = abandonedCart.getRelatedOneCache("Visit");
if (UtilValidate.isEmpty(userLogin)) {
abandonedCartUserLogin = EntityQuery.use(delegator).from("UserLogin").where(UtilMisc.toMap("userLoginId", visit.getString("userLoginId"))).cache().queryOne();
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// initial required cart info
String productStoreId = abandonedCart.getString("productStoreId");
String currency = abandonedCart.getString("currencyUomId");
// If no currency has been set in the ShoppingList, use the ProductStore default currency
if (currency == null) {
try {
GenericValue productStore = abandonedCart.getRelatedOne("ProductStore", false);
if (productStore != null) {
currency = productStore.getString("defaultCurrencyUomId");
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
}
// If we still have no currency, use the default from general.properties. Failing that, use USD
if (currency == null) {
currency = EntityUtilProperties.getPropertyValue("general", "currency.uom.id.default", "USD", delegator);
}
// create the cart
ShoppingCart cart = ShoppingCartFactory.createShoppingCart(delegator, productStoreId, locale, currency); // SCIPIO: use factory
if (isUserInSession) {
try {
cart.setUserLogin(abandonedCartUserLogin, dispatcher);
} catch (CartItemModifyException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
}
// set the role information
if (UtilValidate.isNotEmpty(cartPartyId)) {
cart.setOrderPartyId(cartPartyId);
} else {
cart.setOrderPartyId(visit.getString("partyId"));
}
if (UtilValidate.isEmpty(abandonedCartLines)) {
try {
abandonedCartLines = abandonedCart.getRelated("CartAbandonedLine", null, null, false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
}
long nextItemSeq = 0;
if (UtilValidate.isNotEmpty(abandonedCartLines)) {
Pattern pattern = Pattern.compile("\\P{Digit}");
for (GenericValue abandonedCartLine : abandonedCartLines) {
// get the next item sequence id
String cartItemSeqId = abandonedCartLine.getString("cartAbandonedLineSeqId");
Matcher pmatcher = pattern.matcher(cartItemSeqId);
cartItemSeqId = pmatcher.replaceAll("");
try {
long seq = Long.parseLong(cartItemSeqId);
if (seq > nextItemSeq) {
nextItemSeq = seq;
}
} catch (NumberFormatException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
BigDecimal modifiedPrice = abandonedCartLine.getBigDecimal("totalWithAdjustments");
BigDecimal quantity = abandonedCartLine.getBigDecimal("quantity");
if (quantity == null) {
quantity = BigDecimal.ZERO;
}
int itemIndex = -1;
if (abandonedCartLine.get("productId") != null) {
// product item
String productId = abandonedCartLine.getString("productId");
ProductConfigWrapper configWrapper = null;
if (UtilValidate.isNotEmpty(abandonedCartLine.getString("configId"))) {
configWrapper = ProductConfigWorker.loadProductConfigWrapper(delegator, dispatcher, abandonedCartLine.getString("configId"), productId, productStoreId, null, null, currency, locale, userLogin);
}
try {
itemIndex = cart.addItemToEnd(productId, null, quantity, null, null, null, null, null, configWrapper, dispatcher, Boolean.TRUE, Boolean.TRUE);
} catch (ItemNotFoundException | CartItemModifyException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
// set the modified price
if (modifiedPrice != null && modifiedPrice.doubleValue() != 0) {
ShoppingCartItem item = cart.findCartItem(itemIndex);
if (item != null) {
item.setIsModifiedPrice(true);
item.setBasePrice(modifiedPrice);
}
}
}
// flag the item w/ the orderItemSeqId so we can reference it
ShoppingCartItem cartItem = cart.findCartItem(itemIndex);
cartItem.setOrderItemSeqId(cartItemSeqId);
}
}
// set the item seq in the cart
if (nextItemSeq > 0) {
try {
cart.setNextItemSeq(nextItemSeq + 1);
} catch (GeneralException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
}
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("shoppingCart", cart);
return result;
}
}
|
Communio-Templorum/libris-sanctis | src/pages/metamorphoses/Book7/ctrl.js | yodasws.page('pageMetamorphosesBook7').setRoute({
title: 'Metamorphoses, Book 7',
template: 'pages/metamorphoses/Book7/Book7.html',
canonicalRoute: '/metamorphoses/book7/',
route: '/metamorphoses/book7/?',
});
|
madanagopaltcomcast/pxCore | examples/pxScene2d/external/libnode-v6.9.0/test/fixtures/module-require/child/node_modules/target.js | <reponame>madanagopaltcomcast/pxCore
exports.loaded = 'from child';
|
odenyirechristopher/instagramapp | venv/lib/python3.6/site-packages/csvimport/tests/views.py | from django.http import HttpResponse
def index(request, template="README.txt", **kwargs):
return HttpResponse(
"""<html><body><h1>django-csvimport Test app</h1>
<p>You have installed the test django-csvimport
application. Click on the <a href="/admin/">admin</a>
to try it</p>
<p>NB: you must run<br />
django-admin.py migrate --settings=csvimport.settings <br />
first to create the test models.
<p>Click on csvimport in the admin</p>
<p>Try importing data via the test csv files in
django-csvimport/csvimport/tests/fixtures folder</p>
<p>Click on Add csvimport</p>
<p>For example select Models name: tests.Country and upload the countries.csv file</p>
</body></html>"""
)
|
k-hatano/HyperZebra | src/hyperzebra/TTalk.java | package hyperzebra;
import java.awt.AWTException;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Graphics2D;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.PointerInfo;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;
import hyperzebra.gui.ButtonGUI;
import hyperzebra.gui.FieldGUI;
import hyperzebra.gui.GUI;
import hyperzebra.gui.PCARD;
import hyperzebra.gui.PCARDFrame;
import hyperzebra.gui.button.MyButton;
import hyperzebra.gui.button.MyCheck;
import hyperzebra.gui.button.MyPopup;
import hyperzebra.gui.button.MyRadio;
import hyperzebra.gui.button.RectButton;
import hyperzebra.gui.button.RoundButton;
import hyperzebra.gui.button.RoundedCornerButton;
import hyperzebra.gui.button.TBButtonListener;
import hyperzebra.gui.dialog.GDialog;
import hyperzebra.gui.dialog.GMsg;
import hyperzebra.gui.field.MyScrollPane;
import hyperzebra.gui.field.MyTextArea;
import hyperzebra.gui.menu.GMenu;
import hyperzebra.gui.menu.GMenuBrowse;
import hyperzebra.object.OBackground;
import hyperzebra.object.OBgFieldData;
import hyperzebra.object.OButton;
import hyperzebra.object.OCard;
import hyperzebra.object.OCardBase;
import hyperzebra.object.OField;
import hyperzebra.object.OHyperCard;
import hyperzebra.object.OMenu;
import hyperzebra.object.OMenubar;
import hyperzebra.object.OMsg;
import hyperzebra.object.OObject;
import hyperzebra.object.OStack;
import hyperzebra.object.OTitlebar;
import hyperzebra.object.OToolWindow;
import hyperzebra.object.OWindow;
import hyperzebra.subsystem.debugger.MessageWatcher;
import hyperzebra.subsystem.debugger.VariableWatcher;
import hyperzebra.subsystem.resedit.ResEdit;
import hyperzebra.subsystem.scripteditor.ScriptArea;
import hyperzebra.subsystem.scripteditor.ScriptEditor;
import hyperzebra.tool.AuthTool;
import hyperzebra.tool.ButtonTool;
import hyperzebra.tool.FieldTool;
import hyperzebra.tool.PaintTool;
import hyperzebra.type.xTalkException;
import hyperzebra.type.ttalktype.MemoryData;
import hyperzebra.type.ttalktype.Message;
import hyperzebra.type.ttalktype.ObjResult;
import hyperzebra.type.ttalktype.Result;
interface TalkObject {
// ----getter-----
public String getStr();
public StringBuilder getStrBldr();
public double getNum();
public int getInt();
// ----setter-----
public void setStr(String str);
public void setStrBldr(StringBuilder bldr);
public void setNum(Double num);
public void setNum(int in);
}
/*
* class BasicTalkObject implements TalkObject { //Stringしか持たない基本オブジェクト private
* String str;
*
* //----getter----- public String getStr(){ if(str!=null) return str; else
* return ""; } public double getNum(){ if(str!=null) return
* Double.valueOf(str); else return 0; } public int getInt(){ if(str!=null)
* return Integer.valueOf(str); else return 0; }
*
* //----setter----- public void setStr(String str){ this.str = str; } public
* void setNum(Double num){ this.str = Double.toString(num); } public void
* setNum(int in){ this.str = Integer.toString(in); } }
*/
final class VariableObj implements TalkObject {
// 数値型も持つ変数オブジェクト
private StringBuilder str;
private double num;
private boolean num_flag;
// ----getter-----
public String getStr() {
if (num_flag)
return Double.toString(num);
else
return str.toString();
}
public StringBuilder getStrBldr() {
if (num_flag)
return new StringBuilder(Double.toString(num));
else
return str;
}
public double getNum() {
if (num_flag)
return num;
else
return Double.valueOf(num);
}
public int getInt() {
if (num_flag)
return (int) num;
else
return (int) num;
}
// ----setter-----
public void setStr(String str) {
this.str = new StringBuilder(str);
this.num_flag = false;
}
public void setStrBldr(StringBuilder bldr) {
this.str = bldr;
this.num_flag = false;
}
public void setNum(Double num) {
this.num = num;
this.num_flag = true;
}
public void setNum(int in) {
this.num = (double) in;
this.num_flag = true;
}
}
enum chunkType {
BYTE, CHAR, ITEM, WORD, LINE
};
/*
* final class ChunkObj implements TalkObject { //チャンク指定を持ったままで読み書きできるオブジェクト
* //多重チャンク指定の場合はChunkObjをネストする private TalkObject tobj; private int[]
* splitSets; //number of chunks +1個の配列。 //各delimiterまでのoffsetが入る。
* //[0]にはかならず0が、[splitSet.length]には全体の長さが入ることになる。 private int chunk_s; private
* int chunk_e; private chunkType chunktype;
*
* ChunkObj(TalkObject t, chunkType ct, int s, int e){ tobj = t; chunktype = ct;
* chunk_s = s; chunk_e = e; }
*
* public void setChunk(chunkType ct, int s, int e){ if(chunktype != ct){
* chunktype = ct; splitSets = null; } chunk_s = s; chunk_e = e; }
*
* private void makeCache(){ if(chunktype == chunkType.BYTE || chunktype ==
* chunkType.CHAR){ return; //キャッシュ不要 }
*
* if(chunktype == chunkType.ITEM || chunktype == chunkType.LINE){ String
* splitChar = "\n"; if(chunktype == chunkType.ITEM){ splitChar =
* TTalk.itemDelimiter; } String[] data = tobj.getStr().split(splitChar);
* splitSets = new int[data.length+1]; splitSets[0] = 0; for(int i=0;
* i<data.length; i++){ splitSets[i+1] = splitSets[i] + data[i].length()+1; } }
* else if(chunktype == chunkType.WORD ){ char[] data =
* tobj.getStr().toCharArray(); boolean in_quote = false; int cnt = 1;
* //配列の数を調べる for(int i=0; i<data.length; i++){ if(data[i] == '\"'){ in_quote =
* !in_quote; } else if((data[i] == ' ' || data[i] == '\n') && !in_quote){
* cnt++; } } //配列に作成 splitSets = new int[cnt+1]; //配列に代入 cnt = 1; splitSets[0]
* = 0; int i=0; for(; i<data.length; i++){ if(data[i] == '\"'){ in_quote =
* !in_quote; } else if((data[i] == ' ' || data[i] == '\n') && !in_quote){
* splitSets[cnt] = i; cnt++; } } splitSets[cnt] = i; } }
*
* //----getter----- public String getStr(){ if(chunktype == chunkType.BYTE){
* return Integer.toString(tobj.getStr().getBytes()[chunk_s]); } else
* if(chunktype == chunkType.CHAR){ return
* tobj.getStr().substring(chunk_s,chunk_e); } else{ if(splitSets==null)
* makeCache(); return
* tobj.getStr().substring(splitSets[chunk_s],splitSets[chunk_e]); } } public
* StringBuilder getStrBldr(){ return new StringBuilder(getStr()); } public
* double getNum(){ return Double.valueOf(getStr()); } public int getInt(){
* return Integer.valueOf(getStr()); }
*
* //----setter----- public void setStr(String str){ if(chunktype ==
* chunkType.BYTE){ Integer.toString(tobj.setStr().getBytes()[chunk_s]); } else
* if(chunktype == chunkType.CHAR){ return
* tobj.setStr().substring(chunk_s,chunk_e); } else{ return
* tobj.setStr().substring(splitSets[chunk_s],splitSets[chunk_e]); splitSets =
* null; } } public void setStrBldr(StringBuilder bldr) { this.str = bldr; }
* public void setNum(Double num){ setStr(Double.toString(num)); } public void
* setNum(int in){ setStr(Integer.toString(in)); }
*
* }
*/
//byte[]を持つBytObjなんかも欲しい
// byte ofで参照させるか、char ofでbyte単位で扱うか。
//混乱してきた。整理しよう。
// 最初はStringを持つ
// 数値として参照されると、そのつど数値に変換する
// 数値を代入される場合は新たに数値型が作られる。
// 数値と文字の代入を繰り返すと使わないオブジェクトが増えていくのでGCがんばれ
//
// line ofで 変数が 参照されるとデータを配列で作成して保持し、配列のどれかを返す
// item of line ofとか大変。offset を持つ子を作成したほうが良い?
// そのときStringBuilder型はnullのままにするか、結合情報を持つかは実装次第。
// 配列データはStringBuilderのほうを変更されると破棄する
// line ofで パーツが 参照されるとデータを配列で作成だけして返し、データは破棄する。
// パーツも配列データを持っていてもいいかもしれないが、どうせフィールドは表示するときに全データいるし、容量無駄
// ローカル変数はすぐ消えるから容量無駄にならないはず
// line ofで 変数に 代入されると変数はStringBuilder型をnullにしてデータを配列で持つ
// line ofで パーツに 代入されると配列を作って代入処理をし、そこからさらに結合処理をしてStringBuilderに代入する。
// line ofで代入された変数から全データを参照すると、配列に入ったデータを結合して返す。
// そのときStringBuilder型はnullのままにするか、結合情報を持つかは実装次第。
// word ofだったらsplit文字がいろいろあって復帰が大変なので、split文字だけの配列も持つ。
class OpenFile {
FileInputStream istream;
FileOutputStream ostream;
String path;
}
public class TTalk extends Thread {
public static TTalk talk;
public static DecimalFormat numFormat = new DecimalFormat("0.######");
public static boolean idle = true;
public static String itemDelimiter = ",";
public static ArrayList<Message> messageList = new ArrayList<Message>();
public static TSound tsound = new TSound();
public static boolean stop = false;
public static int tracemode = 0;
public static boolean stepflag;
public static MemoryData globalData = new MemoryData();
static ArrayList<String> pushCardList = new ArrayList<String>();
static Result lastResult;
static int fastLockScreen = 0;
static boolean lockErrorDialogs = false;
static long lastErrorTime;
static boolean lockMessages = false;
static int dragspeed = 0;
public static int wait = 1; // 2.xで昔の速度にするためのウェイト
static ArrayList<OpenFile> openFileList = new ArrayList<OpenFile>();
public enum wordType {
X, VARIABLE, GLOBAL, OBJECT, STRING, CONST, CHUNK, PROPERTY, CMD, CMD_SUB, USER_CMD, XCMD, FUNC, USER_FUNC,
XFCN, OPERATOR, QUOTE, LBRACKET, RBRACKET, LFUNC, RFUNC, COMMA, COMMA_FUNC, OF_FUNC, OF_PROP, OF_OBJ, OF_CHUNK,
ON_HAND, END_HAND, ON_FUNC/* , END_FUNC */, EXIT, PASS, RETURN, IF, ELSE, THEN, ENDIF, REPEAT, END_REPEAT,
EXIT_REP, NEXT_REP, THE_FUNC, COMMENT, NOP, OPERATOR_SUB
}
public static TreeSet<String> operatorSet; // 高速化のためのツリー
public static TreeSet<String> constantSet; // 高速化のためのツリー
public static TreeSet<String> commandSet; // スクリプトエディタで使用
public static TreeSet<String> funcSet; // スクリプトエディタで使用
public static TreeSet<String> propertySet; // スクリプトエディタで使用
private void init() {
operatorSet = new TreeSet<String>();
operatorSet.add("div");
operatorSet.add("mod");
operatorSet.add("not");
operatorSet.add("and");
operatorSet.add("or");
operatorSet.add("contains");
operatorSet.add("within");
operatorSet.add("there");
operatorSet.add("is");
operatorSet.add("<");
operatorSet.add(">");
constantSet = new TreeSet<String>();
constantSet.add("down");
constantSet.add("empty");
constantSet.add("false");
constantSet.add("formfeed");
constantSet.add("linefeed");
constantSet.add("pi");
constantSet.add("quote");
constantSet.add("comma");
constantSet.add("return");
constantSet.add("space");
constantSet.add("tab");
constantSet.add("true");
constantSet.add("up");
constantSet.add("zero");
constantSet.add("one");
constantSet.add("two");
constantSet.add("three");
constantSet.add("four");
constantSet.add("five");
constantSet.add("six");
constantSet.add("seven");
constantSet.add("eight");
constantSet.add("nine");
commandSet = new TreeSet<String>();
commandSet.add("add");
commandSet.add("answer");
commandSet.add("arrowkey");
commandSet.add("ask");
commandSet.add("beep");
commandSet.add("choose");
commandSet.add("click");
commandSet.add("close");
commandSet.add("commandkeydown");
commandSet.add("controlkey");
commandSet.add("convert");
commandSet.add("copy");
commandSet.add("create");
commandSet.add("debug");
commandSet.add("delete");
commandSet.add("dial");
commandSet.add("disable");
commandSet.add("divide");
commandSet.add("do");
commandSet.add("domenu");
commandSet.add("drag");
commandSet.add("edit");
commandSet.add("enable");
commandSet.add("enterinfield");
commandSet.add("enterkey");
commandSet.add("export");
commandSet.add("find");
commandSet.add("get");
commandSet.add("global");// 特別扱い
commandSet.add("go");
commandSet.add("help");
commandSet.add("hide");
commandSet.add("import");
commandSet.add("keydown");
commandSet.add("lock");
commandSet.add("mark");
commandSet.add("multiply");
commandSet.add("open");
commandSet.add("play");
commandSet.add("pop");
commandSet.add("print");
commandSet.add("push");
commandSet.add("put");
commandSet.add("read");
commandSet.add("reply");
commandSet.add("request");
commandSet.add("reset");
commandSet.add("returninfield");
commandSet.add("returnkey");
commandSet.add("save");
commandSet.add("select");
commandSet.add("send");
commandSet.add("set");
commandSet.add("show");
commandSet.add("sort");
commandSet.add("start");
commandSet.add("stop");
commandSet.add("subtract");
commandSet.add("tabkey");
commandSet.add("type");
commandSet.add("unlock");
commandSet.add("unmark");
commandSet.add("visual");
commandSet.add("wait");
commandSet.add("write");
commandSet.add("flash");// add
commandSet.add("about");// add
funcSet = new TreeSet<String>();
funcSet.add("abs");//
funcSet.add("annuity");//
funcSet.add("atan");//
funcSet.add("average");//
funcSet.add("chartonum");//
funcSet.add("clickchunk");
funcSet.add("clickh");//
funcSet.add("clickline");//
funcSet.add("clickloc");//
funcSet.add("clicktext");
funcSet.add("clickv");//
funcSet.add("cmdkey");//
funcSet.add("commandkey");//
funcSet.add("compound");//
funcSet.add("cos");//
funcSet.add("date");//
funcSet.add("diskspace");//
funcSet.add("exp");//
funcSet.add("exp1");//
funcSet.add("exp2");//
funcSet.add("foundchunk");//
funcSet.add("foundfield");//
funcSet.add("foundline");//
funcSet.add("foundtext");//
funcSet.add("heapspace");//
funcSet.add("length");//
funcSet.add("ln");//
funcSet.add("ln1");//
funcSet.add("log2");//
funcSet.add("max");//
funcSet.add("menus");//
funcSet.add("min");//
funcSet.add("mouse");//
funcSet.add("mouseclick");//
funcSet.add("mouseh");//
funcSet.add("mouseloc");//
funcSet.add("mousev");//
funcSet.add("number");
funcSet.add("numtochar");//
funcSet.add("offset");//
funcSet.add("optionkey");//
funcSet.add("param");//
funcSet.add("paramcount");//
funcSet.add("params");//
funcSet.add("programs");
funcSet.add("random");//
funcSet.add("result");//
funcSet.add("round");//
funcSet.add("screenrect");//
funcSet.add("seconds");//
funcSet.add("selectedbutton");
funcSet.add("selectedchunk");
funcSet.add("selectedfield");//
funcSet.add("selectedline");//
funcSet.add("selectedloc");
funcSet.add("selectedtext");//
funcSet.add("selection");
funcSet.add("shiftkey");//
funcSet.add("sin");//
funcSet.add("sound");//
funcSet.add("sqrt");//
funcSet.add("stacks");//
funcSet.add("stackspace");//
funcSet.add("sum");//
funcSet.add("systemversion");//
funcSet.add("tan");//
funcSet.add("target");//
funcSet.add("ticks");//
funcSet.add("time");//
funcSet.add("tool");//
funcSet.add("trunc");//
funcSet.add("value");//
funcSet.add("windows");//
funcSet.add("systemname");// add
funcSet.add("javaversion");// add
funcSet.add("javavmversion");// add
funcSet.add("controlkey");// add
propertySet = new TreeSet<String>();
propertySet.add("address");
propertySet.add("autohilite");
propertySet.add("autoselect");
propertySet.add("autotab");
propertySet.add("blindtyping");
propertySet.add("botright");
propertySet.add("bottom");// set
propertySet.add("bottomright");
propertySet.add("brush");
propertySet.add("cantabort");// set
propertySet.add("cantdelete");// set
propertySet.add("cantmodify");// set
propertySet.add("cantpeek");// set
propertySet.add("centered");
propertySet.add("checkmark");
propertySet.add("cmdchar");
propertySet.add("commandchar");
propertySet.add("cursor");// set
propertySet.add("debugger");
propertySet.add("dialingtime");
propertySet.add("dialingvolume");
propertySet.add("dontsearch");
propertySet.add("dontwrap");
propertySet.add("dragspeed");
propertySet.add("editbkgnd");
propertySet.add("enabled");// set
propertySet.add("environment");
propertySet.add("family");
propertySet.add("filled");
propertySet.add("fixedlineheight");
propertySet.add("freesize");
propertySet.add("grid");
propertySet.add("height");// set
propertySet.add("highlight");// set
propertySet.add("hilight");// set
propertySet.add("hilite");// set
propertySet.add("highlite");// set
propertySet.add("icon");// set
propertySet.add("id");
propertySet.add("itemdelimiter");// set
propertySet.add("language");
propertySet.add("left");// set
propertySet.add("linesize");
propertySet.add("loc");// set
propertySet.add("location");// set
propertySet.add("lockerrordialogs");// set
propertySet.add("lockmessages");// set
propertySet.add("lockrecent");// set
propertySet.add("lockscreen");// set
propertySet.add("locktext");
propertySet.add("longwindowtitles");
propertySet.add("markchar");
propertySet.add("marked");
propertySet.add("menumessage");
propertySet.add("menumsg");
propertySet.add("messagewatcher");
propertySet.add("multiple");
propertySet.add("multiplelines");
propertySet.add("multispace");
propertySet.add("name");// set
propertySet.add("numberformat");
propertySet.add("owner");
propertySet.add("partnumber");
propertySet.add("pattern");
propertySet.add("polysides");
propertySet.add("powerkeys");
propertySet.add("printmargins");
propertySet.add("printtextalign");
propertySet.add("printtextfont");
propertySet.add("printtextheight");
propertySet.add("printtextsize");
propertySet.add("printtextstyle");
propertySet.add("rect");// set
propertySet.add("rectangle");// set
propertySet.add("reporttemplates");
propertySet.add("right");// set
propertySet.add("script");// set
propertySet.add("scripteditor");
propertySet.add("scriptinglanguage");
propertySet.add("scripttextfont");// get,set
propertySet.add("scripttextsize");// get,set
propertySet.add("scroll");// set
propertySet.add("sharedhilite");
propertySet.add("sharedtext");
propertySet.add("showlines");
propertySet.add("showname");
propertySet.add("showpict");// set
propertySet.add("size");
propertySet.add("stacksinuse");
propertySet.add("style");
propertySet.add("suspended");
propertySet.add("textalign");
propertySet.add("textarrows");
propertySet.add("textfont");// set
propertySet.add("textheight");// set
propertySet.add("textsize");// set
propertySet.add("textstyle");// set
propertySet.add("titelwidth");
propertySet.add("top");// set
propertySet.add("topleft");// set
propertySet.add("tracedelay");
propertySet.add("userlevel");// set
propertySet.add("usermodify");
propertySet.add("variablewatcher");
propertySet.add("version");
propertySet.add("visible");// set
propertySet.add("widemargins");
propertySet.add("width");// set
propertySet.add("zoomed");// set
propertySet.add("text");// (add) set
propertySet.add("systemlang");// add get
propertySet.add("blendingmode");// add set
propertySet.add("blendinglevel");// add set
propertySet.add("color");// add set
propertySet.add("backColor");// add set
propertySet.add("selectedfield");//
propertySet.add("selectedline");//
propertySet.add("selectedtext");//
propertySet.add("audiolevel");// xcmd set
propertySet.add("currtime");// xcmd set
propertySet.add("scale");// xcmd set
globalData.treeset = new TreeSet<String>();
globalData.nameList = new ArrayList<String>();
globalData.valueList = new ArrayList<String>();
}
// 受け取ったメッセージを実行するスレッド
public void run() {
talk = this;
init();
this.setName("scriptEngine");
// setPriority(MAX_PRIORITY);
while (true) {
Message msg = null;
synchronized (messageList) {
if (messageList.size() > 0) {
msg = messageList.get(0);
messageList.remove(0);
}
}
if (msg != null) {
try {
if (msg.do_script) {
doScriptforMenu(msg.message);
continue;
} else
ReceiveMessage(msg.message, msg.param, msg.object, null, msg.idle);
} catch (Exception e) {
e.printStackTrace();
}
} else {
/* if(idle==false) */
if (PCARD.pc.tool == null && AuthTool.tool == null) {
returnToIdle();
}
this.TalkSleep(50);
}
}
}
private void TalkSleep(int time) {
if (TXcmd.terazzaAry != null) {
long startTime = (int) new Date().getTime();
while (true) {
// sleepしてる間にアニメーション実施
TXcmd.TerazzaAnime();
// 残り時間を調べる
int left = time - (int) ((new Date().getTime()) - startTime);
if (left <= 0) {
break;
}
// 30ずつsleep
int t = left;
if (left > 30)
t = 30;
try {
Thread.sleep(t);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
if (Thread.currentThread().isInterrupted()) {
break;
}
}
} else if (time > 0) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
}
}
}
// メニューを実行するときに内部スクリプトを実行する
public static String doScriptforMenu(String script) throws xTalkException {
if (Thread.currentThread() != talk) {
CallMessage(script, "", null, false, true);
return "";
}
stop = false;
Result result = null;
MemoryData memData = new MemoryData();
memData.treeset = new TreeSet<String>();
memData.nameList = new ArrayList<String>();
memData.valueList = new ArrayList<String>();
result = talk.doScriptLine(script, /* PCARD.pc.stack.curCard */null, null, memData, 0);
if (result == null)
return "";
return result.theResult;
}
// メッセージをスクリプトスレッドに投げる
public static void CallMessage(String message, OObject object) {
// System.out.println("CallMessage "+message+" "+object.getShortName());
CallMessage(message, "", object, false, false);
}
public static void CallMessage(String message, String param, OObject object, boolean idle, boolean do_script) {
Message msg = new Message();
msg.message = message;
msg.object = object;
msg.param = param;
msg.idle = idle;
msg.do_script = do_script;
synchronized (messageList) {
messageList.add(msg);
}
}
private void ReceiveMessage(String message, String param, OObject object, MemoryData memData, boolean idlenow)
throws xTalkException {
boolean changeIdle = false;
if (idlenow == false && idle == true) {
// ビジー状態にする
idle = false;
changeIdle = true;
GUI.mouseClicked = false;
}
String[] params;
if (param != "") {
params = new String[1];
params[0] = param;
} else
params = new String[0];
lastResult = ReceiveMessage(message, params, object, object, memData);
if (changeIdle) {
// idle状態に戻す
returnToIdle();
}
}
private static void returnToIdle() {
if (!idle && !GUI.mouseDown) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
java.lang.System.gc();// GCをなるべく呼ぶ
}
});
}
idle = true;
TTalk.stop = false;
TTalk.tracemode = 0;
if (PCARD.pc.stack == null)
return;
if (PCARD.lockedScreen) {
OCard.reloadCurrentCard();
PCARD.lockedScreen = false;
}
fastLockScreen = 0;
PCARD.visual = 0;
numFormat = new DecimalFormat("0.######");
itemDelimiter = ",";
dragspeed = 0;
Cursor cr = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
PCARD.pc.setCursor(cr);
PCARD.pc.stack.mouseWithinCheck();
if (VariableWatcher.watcherWindow.isVisible() && TTalk.globalData.nameList.size() != VariableWatcher.rowSize) {
VariableWatcher.watcherWindow.setTable(TTalk.globalData, null);
}
// ファイルクローズ
for (int i = 0; i < openFileList.size(); i++) {
try {
if (openFileList.get(i).istream != null) {
openFileList.get(i).istream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (openFileList.get(i).ostream != null) {
openFileList.get(i).ostream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
openFileList.clear();
}
private Result ReceiveMessage(String message, String[] params, OObject object, OObject target, MemoryData memData)
throws xTalkException {
// System.out.println("ReceiveMessage "+message+" "+object.getShortName());
Result result = new Result();
return ReceiveMessage(message, params, object, target, memData, result, false, false, false, 0);
}
String[] messageRingArray = new String[128];
OObject[] objectRingArray = new OObject[128];
int ringCnt;
// メッセージを受け取る
private final Result ReceiveMessage(String message, String[] params, OObject object, OObject target,
MemoryData memData, Result result, boolean isFunc, boolean isDynamic, boolean isBgroot, int usingCnt)
throws xTalkException {
// long timestart = System.currentTimeMillis();
result.ret = 1;
if (object == null) {
object = PCARD.pc.stack.curCard;
}
if (object == null || object.scriptList == null)
return result;
// ハンドラ行のみをピックアップしてリストに保存する
if (object.handlerLineList == null) {
object.handlerList = new TreeSet<String>();
object.handlerLineList = new ArrayList<Integer>();
for (int line = 0; line < object.scriptList.size(); line++) {
String str = object.scriptList.get(line);
while (str.substring(0, 0).equals(" ")) {
str = str.substring(1);
}
String[] words = str.split(" ");
if (words.length <= 1) {
continue;
}
if (0 == words[0].compareToIgnoreCase("on") || 0 == words[0].compareToIgnoreCase("function")
|| 0 == words[0].compareToIgnoreCase("end")) {
if (0 == words[0].compareToIgnoreCase("on") || 0 == words[0].compareToIgnoreCase("function")) {
if (words[1].indexOf("--") >= 0) {
words[1] = words[1].substring(0, words[1].indexOf("--"));
}
object.handlerList.add(words[1].toLowerCase().intern());
}
object.handlerLineList.add(line);
}
}
}
// ハンドラを探す
if (object.handlerList.contains(message.toLowerCase().intern())) {
// messageWatcher用
messageRingArray[ringCnt % 128] = message;
objectRingArray[ringCnt % 128] = object;
ringCnt++;
if (MessageWatcher.watcherWindow != null && MessageWatcher.watcherWindow.isVisible()) {
MessageWatcher.watcherWindow.setTable(messageRingArray, objectRingArray, ringCnt);
}
int start = 0;
for (int i = 0; object.handlerLineList != null && i < object.handlerLineList.size(); i++) {
int line = object.handlerLineList.get(i);
String str = object.scriptList.get(line);
while (str.substring(0, 0).equals(" ")) {
str = str.substring(1);
}
String[] words = str.split(" ");
if (words.length <= 1) {
line++;
continue;
}
if (words[1].indexOf("--") >= 0) {
words[1] = words[1].substring(0, words[1].indexOf("--"));
}
if (0 == words[1].compareToIgnoreCase(message)) {
if (!isFunc && 0 == words[0].compareToIgnoreCase("on")) {
start = line + 1;
}
if (isFunc && 0 == words[0].compareToIgnoreCase("function")) {
start = line + 1;
}
if (start > 0 && 0 == words[0].compareToIgnoreCase("end")) {
MemoryData memData2 = new MemoryData();
memData2.treeset = new TreeSet<String>();
memData2.nameList = new ArrayList<String>();
memData2.valueList = new ArrayList<String>();
// 引数
String[] handlerWords = object.scriptList.get(start - 1).split(" ");
if (handlerWords.length >= 3) { // on handler param
String paramStr = "";
for (int k = 2; k < handlerWords.length; k++)
paramStr += handlerWords[k];
String[] paramNames = paramStr.split(",");
for (int j = 0; j < paramNames.length; j++) {
if (paramNames[j].startsWith("--"))
break;
if (paramNames[j].indexOf("--") >= 0) {
paramNames[j] = paramNames[j].substring(0, paramNames[j].indexOf("--"));
}
if (j >= params.length)
setVariable(memData2, paramNames[j], "");
else
setVariable(memData2, paramNames[j], params[j]);
}
}
// memDataにメッセージ名とparamsをセット(param(i)とthe paramsのため)
memData2.message = message;
memData2.params = params;
// timeIsMoney("ReceiveMessage2-1:",timestart,14);
try {
result = doScript(object, target, message, object.scriptList, start, line - 1, memData2,
params, 0);
} catch (Exception err) {
if (object.name.length() > 0)
System.out.println(object.objectType + " '" + object.name + "' " + err);
else
System.out.println(object.objectType + " id " + object.id + " " + err);
err.printStackTrace();
result.ret = -1;
break;
}
}
}
line++;
}
}
// timeIsMoney("ReceiveMessage2-2:",timestart,15);
if (result.ret == 1) {
if (object.parent != null) {
// 通常パス:親に送信
/*
* if(object.objectType.equals("background")&&isBgroot==false){
* //バックグラウンドは一度カードを通ってから System.out.println("!1");
* result=ReceiveMessage(message, params, ((OBackground)object).viewCard,
* target, isFunc, isDynamic, true); } else
*/ if (object.parent.objectType.equals("background") && !object.objectType.equals("card")) {
// バックグラウンドのパーツは一度カードを通ってから
result = ReceiveMessage(message, params, ((OBackground) object.parent).viewCard, target, memData,
result, isFunc, isDynamic, isBgroot, usingCnt);
} else {
result = ReceiveMessage(message, params, object.parent, target/* object.parent */, memData, result,
isFunc, isDynamic, isBgroot, usingCnt);
}
} else if (!isDynamic && target != null
&& (target.parent != null && target.parent.objectType == "background"
|| target.objectType == "background" || target.objectType == "stack"
|| target.objectType == "card" && target != PCARD.pc.stack.curCard)) {
// ダイナミックパス:現在のカードに送信
result = ReceiveMessage(message, params, PCARD.pc.stack.curCard, target, memData, result, isFunc, true,
isBgroot, usingCnt);
} else if (!isDynamic && target != null && target.parent != null && target.parent.objectType == "card"
&& target.parent != PCARD.pc.stack.curCard) {
// ダイナミックパス:現在のカードに送信
result = ReceiveMessage(message, params, PCARD.pc.stack.curCard, target, memData, result, isFunc, true,
isBgroot, usingCnt);
} else {
OStack stack = null;
if (object.objectType.equals("stack"))
stack = (OStack) object;
else if (object.parent.objectType.equals("stack"))
stack = (OStack) object.parent;
else if (object.parent.parent.equals("stack"))
stack = (OStack) object.parent.parent;
if (stack != null && stack.usingStacks != null && usingCnt < stack.usingStacks.size()
&& stack.usingStacks.get(usingCnt) != null
&& stack.usingStacks.get(usingCnt).scriptList != null) {
usingCnt++;
result = ReceiveMessage(message, params, stack.usingStacks.get(usingCnt - 1), target, memData,
result, isFunc, true, isBgroot, usingCnt);
} else if (!commandSet.contains(message)) {
result = TUtil.CallSystemMessage(message, params, target, memData, isFunc);
}
}
}
return result;// 0なら見つかった、1なら見つからなかったので次のオブジェクトを探す
}
// mode=0 通常 mode=1 内部呼び出しなのでエラー出さない
private Result doScript(OObject object, OObject target, String message, String script, MemoryData memData,
String[] parentparams, int mode) throws xTalkException {
ArrayList<String> scriptList = new ArrayList<String>();
while (script.indexOf("\r") >= 0) { // return(CR)を(LF)に変える
script = script.substring(0, script.indexOf("\r")) + "\n"
+ script.substring(script.indexOf("\r") + 1, script.length());
}
String[] scrAry = script.split("\n");
for (int i = 0; i < scrAry.length; i++) {
scriptList.add(scrAry[i]);
}
return doScript(object, target, message, scriptList, 0, scriptList.size() - 1, memData, parentparams, mode);
}
// ハンドラの中身を実行
// objectがnullの場合もある
// messageがnullの場合もある
// -1 . error/exit to HyperCard
// 0 .. normal end
// 1 .. pass message
// 2 .. exit repeat
// 3 .. exit handle
private Result doScript(OObject object, OObject target, String message, ArrayList<String> scriptList, int start,
int end, MemoryData memData, String[] parentparams, int mode) throws xTalkException {
if (TTalk.stop) {
throw new xTalkException("user abort.");
}
if (TTalk.tracemode >= 1) {
ScriptEditor.openScriptEditor(PCARD.pc, object, start);
boolean watcher = false;
if (VariableWatcher.watcherWindow.isVisible()) {
watcher = true;
VariableWatcher.watcherWindow.setTable(TTalk.globalData, memData);
}
if (TTalk.tracemode == 2) {
while (stepflag == false) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
}
if (watcher == false && VariableWatcher.watcherWindow.isVisible()) {
watcher = true;
VariableWatcher.watcherWindow.setTable(TTalk.globalData, memData);
}
}
stepflag = false;
}
}
int line = start;
Result result = new Result();
/*
* StringBuilder scr = new StringBuilder(128); scr.append("+ "); for(int
* i=start; i<=end; i++){ scr.append(scriptList.get(i)); scr.append(" "); }
* System.out.println(scr.toString());
*/
result.ret = 0;
if (object != null && object.wrapFlag == false && object.scriptList == scriptList) {
for (int i = 0; i < scriptList.size(); i++) {
String str = scriptList.get(i);
while (str.length() > 0
&& (str.charAt(str.length() - 1) == 'ツ' || str.charAt(str.length() - 1) == '~')) {
i++;
if (i > scriptList.size())
break;
str = str.substring(0, str.length() - 1) + " " + scriptList.get(i);
scriptList.set(i - 1, "");
scriptList.set(i, str);
}
}
object.wrapFlag = true;
}
try { //
while (line <= end) {
/*
* String str=scriptList.get(line); while(str.length()>0 &&
* (str.charAt(str.length()-1)=='ツ' || str.charAt(str.length()-1)=='~') ) {
* line++; if(line>end) break; str =
* str.substring(0,str.length()-1)+" "+scriptList.get(line); } int spacing1=0;
* while(spacing1<str.length() && (str.charAt(spacing1)==' ' ||
* str.charAt(spacing1)==' ')) spacing1++; String[] words =
* str.substring(spacing1).split(" "); if(words.length==0) continue;
*/
ArrayList<String> sList;
ArrayList<wordType> tList;
if (object == null || scriptList != object.scriptList || object.stringList == null
|| object.stringList[line] == null) {
String str = scriptList.get(line);
/*
* while(str.length()>0 && (str.charAt(str.length()-1)=='ツ' ||
* str.charAt(str.length()-1)=='~') ) { line++; if(line>end) break; str =
* str.substring(0,str.length()-1)+" "+scriptList.get(line); }
*/
// 分解
sList = new ArrayList<String>();
tList = new ArrayList<wordType>();
fullresolution(str, sList, tList, memData.treeset, true);
if (object != null) {
object.stringList[line] = sList;
object.typeList[line] = tList;
}
} else {
sList = object.stringList[line];
tList = object.typeList[line];
}
if (sList.size() == 0) {
line++;
continue;
}
String str0 = sList.get(0);
if (str0 == "repeat") {
start = line;
line++;
int nest = 0;
while (line <= end) {
String str2 = scriptList.get(line);
int spacing = 0;
while (spacing < str2.length() && (str2.charAt(spacing) == ' ' || str2.charAt(spacing) == ' '))
spacing++;
String[] words2 = str2.substring(spacing).split(" ");
if (words2.length == 0) {
line++;
continue;
}
if (0 == words2[0].compareToIgnoreCase("repeat")) {
nest++;
}
if (0 == words2[0].compareToIgnoreCase("end") && 0 == words2[1].compareToIgnoreCase("repeat")) {
if (nest == 0)
break;
nest--;
}
line++;
}
if (line > end + 1)
throw new xTalkException("end repeatが見つかりません");
if (sList.size() <= 1 || sList.get(1).startsWith("--")
|| 0 == sList.get(1).compareToIgnoreCase("forever")) {
// repeat [forever]
while (true) {
result = doScript(object, target, message, object.scriptList, start + 1, line - 1, memData,
parentparams, 0);
if (result.ret != 0)
break;
}
} else if (0 == sList.get(1).compareToIgnoreCase("with")) {
// repeat with xxxx=x to xx / down to
int next;
boolean down = false;
String mem;
String rstart = "";
String rend = "";
if (sList.size() >= 3 && sList.get(2).contains("=")) {
String[] words2 = sList.get(2).split("=");
mem = words2[0];
if (words2.length >= 2)
rstart = words2[1];
next = 3;
} else if (sList.size() >= 4 && sList.get(3).contains("=")) {
mem = sList.get(2);
String[] words2 = sList.get(3).split("=");
if (words2.length >= 1)
rstart = words2[1];
next = 4;
} else {
throw new xTalkException("repeat withの引数が分かりません");
}
while (true) {
if (next >= sList.size() || 0 == sList.get(next).compareToIgnoreCase("to"))
break;
if (0 == sList.get(next).compareToIgnoreCase("down")) {
next++;
if (next < sList.size() && 0 == sList.get(next).compareToIgnoreCase("to")) {
down = true;
break;
} else {
throw new xTalkException("downの後にはtoが必要です");
}
}
rstart += " " + sList.get(next);
next++;
}
next++;
while (true) {
if (next >= sList.size() || sList.get(next).startsWith("--"))
break;
if (sList.get(next).contains(" ")) {
rend += " \"" + sList.get(next) + "\"";
} else {
rend += " " + sList.get(next);
}
next++;
}
String startStr = Evalution(rstart, memData, object, target);
setVariable(memData, mem, startStr);
int cnt = 0;
if (down == false) {
while (0 == Evalution(mem + "<=" + rend, memData, object, target).compareTo("true")) {
result = doScript(object, target, message, scriptList, start + 1, line - 1, memData,
parentparams, 0);
if (result.ret != 0)
break;
cnt++;
// System.out.println("cnt="+cnt);
setVariable(memData, mem, Integer.toString(Integer.valueOf(startStr) + cnt));
}
} else {
while (0 == Evalution(mem + ">=" + rend, memData, object, target).compareTo("true")) {
result = doScript(object, target, message, scriptList, start + 1, line - 1, memData,
parentparams, 0);
if (result.ret != 0)
break;
cnt++;
setVariable(memData, mem, Integer.toString(Integer.valueOf(startStr) - cnt));
}
}
} else if (0 == sList.get(1).compareToIgnoreCase("while")) {
// repeat while
String prm = "";
int next = 2;
while (true) {
if (next >= sList.size() || sList.get(next).startsWith("--"))
break;
prm += " " + sList.get(next);
next++;
}
while (0 == Evalution(prm, memData, object, target).compareTo("true")) {
result = doScript(object, target, message, scriptList, start + 1, line - 1, memData,
parentparams, 0);
if (result.ret != 0)
break;
}
} else if (0 == sList.get(1).compareToIgnoreCase("until")) {
// repeat until
String prm = "";
int next = 2;
while (true) {
if (next >= sList.size() || sList.get(next).startsWith("--"))
break;
prm += " " + sList.get(next);
next++;
}
while (0 == Evalution(prm, memData, object, target).compareTo("false")) {
result = doScript(object, target, message, scriptList, start + 1, line - 1, memData,
parentparams, 0);
if (result.ret != 0)
break;
}
} else {
// repeat [for] x [times]
// repeat until
String prm = "";
int next = 1;
if (next < sList.size() && 0 == sList.get(next).compareToIgnoreCase("for"))
next++;
while (true) {
if (next >= sList.size() || sList.get(next).startsWith("--")
|| 0 == sList.get(next).compareToIgnoreCase("times"))
break;
prm += " " + sList.get(next);
next++;
}
int cnt = 0;
while (0 == Evalution(cnt + "<" + prm, memData, object, target).compareTo("true")) {
result = doScript(object, target, message, scriptList, start + 1, line - 1, memData,
parentparams, 0);
if (result.ret != 0)
break;
cnt++;
}
}
if (result.ret == -1 || result.ret == 1 || result.ret == 3)
break;
result.ret = 0;
} // repeat終わり
else if (str0 == "if") {
// if構文
// ArrayList<String> stringList = new ArrayList<String>();
// ArrayList<wordType> typeList = new ArrayList<wordType>();
String nstr = "";
// 分解
// resolution(str, stringList, typeList,false);
int next = -1;
String prm = "";// ifの条件のString
int iftype = 0;
int iftype2 = 0;
int endi = 0;
for (int i = 1; i < sList.size(); i++, endi = i) {
if (0 == sList.get(i).compareToIgnoreCase("then")) {
if (i == sList.size() - 1) { // 行末にthen
iftype = 1;
next = 0;
break; // 複数行のthen
} else {
iftype = 2;
next = i;
break; // 1行のthen
}
}
}
prm = combine(1, endi, sList, tList);
ArrayList<String> nstringList = new ArrayList<String>();
ArrayList<wordType> ntypeList = new ArrayList<wordType>();
if (iftype == 0) {
iftype2 = 1;
// 2行目のthenを探す
if (line + 1 <= end) {
line++;
nstr = scriptList.get(line);
}
resolution(nstr, nstringList, ntypeList, false);
if (nstringList.size() >= 1 && 0 == nstringList.get(0).compareToIgnoreCase("then")) {
if (1 == nstringList.size()) { // 行末にthen
iftype = 1;
next = 0; // 複数行のthen(2行目にある場合)
} else {
iftype = 2;
next = 0; // 1行のthen(2行目にある場合)
}
} else
throw new xTalkException("if文にはthenが必要です");
}
if (iftype2 == 1 && iftype == 2) {
sList = nstringList;
tList = ntypeList;
}
/*
* if(iftype2==2){ stringList = nstringList; typeList = ntypeList; line++; }
*/
// ifの条件を満たすかどうか
boolean doif = false;
if (0 == Evalution(prm, memData, object, target).compareTo("true")) {
doif = true;
}
String doStr = "";
boolean thenthen = false;
int elseiftype = 0;
boolean doifever = false;
// elseが連続する処理のためにここからループする
while (true) {
// then(else)実行
boolean else_works = false;
if (iftype == 2) {
// thenが行末でない
// ->この行を(elseまで)実行
next++;
int nstart = next;
while (true) {
if (next >= sList.size()) { // 行末まで来た
String n2str = "";
ArrayList<String> n2stringList = new ArrayList<String>();
ArrayList<wordType> n2typeList = new ArrayList<wordType>();
int n2next = 0;
if (line + 1 <= end) {
n2str = scriptList.get(line + 1);
}
resolution(n2str, n2stringList, n2typeList, false);
if (n2stringList.size() > n2next
&& 0 == n2stringList.get(n2next).compareToIgnoreCase("else")) {
// 次の行の先頭がelse
if (sList.get(nstart).equalsIgnoreCase("if")) {
int next2 = nstart;
for (; next2 < sList.size(); next2++) {
if (sList.get(next2).equalsIgnoreCase("then"))
break;
}
prm = combine(nstart + 1, next2, sList, tList);
if (0 == Evalution(prm, memData, object, target).compareTo("true")) {
doif = true;
} else
doif = false;
doStr += combine(next2 + 1, next, sList, tList);
} else {
doStr += combine(nstart, next, sList, tList);
}
nstart = -1;
line++;
next = n2next;
sList = n2stringList;
tList = n2typeList;
else_works = true;
break;
} else if (0 == sList.get(sList.size() - 1).compareToIgnoreCase("else")
|| 0 == sList.get(sList.size() - 1).compareToIgnoreCase("then")) {
// この行の行末がelseかthen
iftype = 1;
thenthen = true;
break;
} else {
// 行末で、次の行がelseでないので終了
break;
}
} else if (0 == sList.get(next).compareToIgnoreCase("else")) {
// 文中にelse
else_works = true;
if (sList.get(nstart).equalsIgnoreCase("if")) {
int next2 = nstart + 1;
while (next2 < sList.size() && !sList.get(next2).equalsIgnoreCase("then")) {
next2++;
}
prm = combine(nstart + 1, next2, sList, tList);
if (0 == Evalution(prm, memData, object, target).compareTo("true")) {
doif = true;
} else
doif = false;
}
break;
}
// doStr += " "+stringList.get(next);
next++;
}
if (thenthen)
continue;
if (nstart != -1) {
doStr += combine(nstart, next, sList, tList);
}
if (doif && doifever == false) {
result = doScript(object, target, message, doStr, memData, parentparams, 1);
if (result.ret != 0) {
return result;
}
doifever = true;
}
} else if (iftype == 1) {
// thenが行末
// ->次の行からend if/elseまで実行
if (iftype2 == 1) {
// line++;
}
line++;
int nest = 0;
int ifdostart = line;
// System.out.println("===="+elseiftype);
while (line <= end) {
String str2 = scriptList.get(line);
int spacing = 0;
while (spacing < str2.length()
&& (str2.charAt(spacing) == ' ' || str2.charAt(spacing) == ' '))
spacing++;
if (str2.lastIndexOf("\"") >= 0 && str2.lastIndexOf("\"") + 2 < str2.length()) {
str2 = str2.substring(0, str2.lastIndexOf("\"") + 1) + " "
+ str2.substring(str2.lastIndexOf("\"") + 1);
}
String[] words2 = str2.substring(spacing).split(" ");
if (words2.length < 1) {
line++;
continue;
}
if (words2[0].startsWith("--")) {
line++;
continue;
}
for (int k = 1; k < words2.length; k++) {
if (words2[k].startsWith("--")) {
words2[words2.length - 1] = words2[k - 1];
break;
}
}
if (0 == words2[0].compareToIgnoreCase("else") && elseiftype == 0) {
String str3 = scriptList.get(line - 1);
String[] words3 = str3.substring(0).split(" ");
for (int k = 1; k < words3.length; k++) {
if (words3[k].startsWith("--")) {
words3[words3.length - 1] = words3[k - 1];
break;
}
}
if (words3.length > 0 && 0 != words3[words3.length - 1].compareToIgnoreCase("then")
&& scriptList.get(line - 1).contains(" then ")) {
//
// System.out.println(nest+"*"+str2);
if (0 == words2[words2.length - 1].compareToIgnoreCase("else")
|| 0 == words2[words2.length - 1].compareToIgnoreCase("then")) {
// System.out.println(nest+">"+str2);
nest++;
}
} else if (nest == 0) {
// System.out.println("elseで続く:"+str2);
// elseで続く
// next = 0;
/*
* String n2str = ""; ArrayList<String> n2stringList = new ArrayList<String>();
* ArrayList<wordType> n2typeList = new ArrayList<wordType>();
* if(ifdostart+1<=end){ n2str=scriptList.get(ifdostart); } resolution(n2str,
* n2stringList, n2typeList,false); { if(n2stringList.size()>0 &&
* n2stringList.get(0).equalsIgnoreCase("if")){ int next2 = 1;
* for(;next2<n2stringList.size();next2++){
* if(n2stringList.get(next2).equalsIgnoreCase("then")) break; } prm =
* combine(1, next2, n2stringList, n2typeList); if(0==Evalution(prm,memData,
* object, target).compareTo("true")){ doif=true; }else doif = false; } }
*/
/*
* sList.clear(); tList.clear();
*/
sList = new ArrayList<String>();
tList = new ArrayList<wordType>();
resolution(str2, sList, tList, false);
else_works = true;
break;
}
}
if (0 == words2[words2.length - 1].compareToIgnoreCase("then")
|| (0 != words2.length - 1)
&& 0 == words2[words2.length - 1].compareToIgnoreCase("else")) {
if (0 == words2[0].compareToIgnoreCase("else")
&& 0 == words2[words2.length - 1].compareToIgnoreCase("then")) {
// System.out.println(nest+" "+str2);
} else {
// System.out.println(nest+">"+str2);
nest++;
}
} else if (0 == words2[0].compareToIgnoreCase("else") && (0 != words2.length - 1)
&& 0 != words2[words2.length - 1].compareToIgnoreCase("then")) {
if (scriptList.get(line - 1).contains(" then ")) {
//
// System.out.println(nest+"#"+str2);
} else {
if (nest == 0) {
// System.out.println("elseで終了"+str2);
// elseで終了
/*
* sList.clear(); tList.clear();
*/
sList = new ArrayList<String>();
tList = new ArrayList<wordType>();
resolution(str2, sList, tList, false);
else_works = true;
break;
}
nest--;
// System.out.println(nest+"<"+str2);
}
} else if (0 == words2[0].compareToIgnoreCase("end")
&& 0 == words2[1].compareToIgnoreCase("if")) {
if (nest == 0) {
// end ifで終了
// System.out.println("end ifで終了"+str2);
break;
}
nest--;
// System.out.println(nest+"<"+str2);
}
// else System.out.println(nest+" "+str2);
//// doStr += "\n"+str2;
line++;
elseiftype = 0;
}
if (doif && doifever == false) {
if (doStr.length() > 0) {
result = doScript(object, target, message, doStr, memData, parentparams, 1);
if (result.ret != 0) {
return result;
}
}
result = doScript(object, target, message, object.scriptList, ifdostart, line - 1,
memData, parentparams, 0);
if (result.ret != 0) {
return result;
}
doifever = true;
}
}
if (else_works == false || line > end) {
break;
} else {
doStr = "";
// elseの判定
if (next + 1 == sList.size()) { // 行末にelse
iftype = 1;
next = 0;
// System.out.println("iftype=1;next=0;");
if (line + 1 <= end) {
// line++;
// str=scriptList.get(line);
}
/*
* sList.clear(); tList.clear();
*/
sList = new ArrayList<String>();
tList = new ArrayList<wordType>();
resolution(scriptList.get(line), sList, tList, false);
doif = true;
} else if (sList.get(next + 1).equalsIgnoreCase("if")
&& sList.get(sList.size() - 1).equalsIgnoreCase("then")) { // else if 〜 then
iftype = 1;
// System.out.println("iftype=1;");
elseiftype = 1;
prm = combine(next + 2, sList.size() - 1, sList, tList);
doif = false;
if (0 == Evalution(prm, memData, object, target).compareTo("true")) {
doif = true;
}
} else {
iftype = 2;
// System.out.println("iftype=2;");
doif = true;
// ####next++;
}
// doif = !doifever;
}
}
} else if (str0 == "exit") {
if (sList.size() >= 2 && 0 == sList.get(1).compareToIgnoreCase("repeat")) {
result.ret = 2;
return result;
}
if (sList.size() >= 2 && 0 == sList.get(1).compareToIgnoreCase(message)) {
result.ret = 3;
return result;
}
if (sList.size() >= 2 && 0 == sList.get(1).compareToIgnoreCase("to")) {
if (sList.size() >= 3 && 0 == sList.get(2).compareToIgnoreCase("hypercard")) {
result.ret = -1;
return result;
}
}
throw new xTalkException("exitが分かりません");
} else if (str0 == "next") {
if (sList.size() >= 2 && 0 == sList.get(1).compareToIgnoreCase("repeat")) {
result.ret = 0;
return result;
}
throw new xTalkException("nextが分かりません");
} else if (str0 == "pass") {
if (sList.size() >= 2 && 0 == sList.get(1).compareToIgnoreCase(message)) {
result.ret = 1;
return result;
}
throw new xTalkException("passが分かりません");
} else if (str0 == "return") {
result.theResult = "";
if (sList.size() >= 2) {
String retstr = "";
for (int j = 1; j < sList.size(); j++) {
retstr += sList.get(j) + " ";
}
result.theResult = Evalution(retstr, memData, object, target);
}
result.ret = 0;
return result;
} else if (str0 == "end") {
throw new xTalkException("endが不正な位置にあります");
} else {
// 通常文の実行
if (TTalk.stop == true) {
throw new xTalkException("user abort.");
}
if (TTalk.tracemode == 1 && object != null) {
ScriptEditor.openScriptEditor(PCARD.pc, object, line);
}
/*
* if(object==null || scriptList != object.scriptList){
* //System.out.println(">> "+str); result = doScriptLine(str, object, target,
* memData); }else{ if( object.stringList==null || object.stringList[line] ==
* null){ //分解 //object.stringList[line] = new ArrayList<String>();
* //object.typeList[line] = new ArrayList<wordType>(); //fullresolution(str,
* object.stringList[line], object.typeList[line], true); }
* //System.out.println(">> "+str);
*
* ArrayList<String> stringList = new
* ArrayList<String>(object.stringList[line]);
*
* wordType[] typeAry = new wordType[object.typeList[line].size()]; for(int i=0;
* i<object.typeList[line].size(); i++){ //リストより配列に移す typeAry[i] =
* object.typeList[line].get(i); }
*
* //実行 result = CommandExec(stringList, typeAry, object, target, memData); }
*/
ArrayList<String> stringList = new ArrayList<String>(sList);
wordType[] typeAry = new wordType[tList.size()];
tList.toArray(typeAry);
/*
* wordType[] typeAry = new wordType[tList.size()]; for(int i=0; i<tList.size();
* i++){ //リストより配列に移す typeAry[i] = tList.get(i); }
*/
// 実行
result = CommandExec(stringList, typeAry, object, target, memData, line);
lastResult = result;
}
line++;
}
} catch (xTalkException e) {
// スクリプトエラー発生時の処理
String str = "";
if (line < scriptList.size())
str = scriptList.get(line);
while (str.length() > 1 && str.substring(0, 1).equals(" "))
str = str.substring(1);
System.out.println("Error occurred at:" + str);
if (mode == 1) { // 内部呼び出しなので、ここではダイアログを出さず上位の呼び出し元に投げる
e.printStackTrace();
throw new xTalkException(e.getMessage());
}
if (object != null && mode == 0)
System.out.println("line " + line + " of " + object.getShortName());
messageList.clear();
lastErrorTime = System.currentTimeMillis();
if (TTalk.stop == true) { // cmd+.による強制停止 または エラーによる停止
throw new xTalkException(e.getMessage());
}
e.printStackTrace();
if (lockErrorDialogs) {
throw new xTalkException(e.getMessage());
}
java.awt.Toolkit.getDefaultToolkit().beep();
if (object != null && object.scriptList != null && object.scriptList.size() > 0) {
Object[] options = { "OK", "Open Script" };
String msg = e.getMessage();
if (!PCARD.pc.lang.equals("Japanese")) {
msg = "";
}
int retValue = JOptionPane.showOptionDialog(PCARD.pc,
"Script Error: " + msg + "\n\n" + "line " + line + " of " + object.getShortName(),
"Script Error", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options,
options[0]);
if (retValue == JOptionPane.YES_OPTION) {
} else if (retValue == JOptionPane.NO_OPTION) {
ScriptEditor.openScriptEditor(PCARD.pc, object, line);
}
} else {
Object[] options = { "OK" };
JOptionPane.showOptionDialog(PCARD.pc, "Script Error: ", "Exit Options", JOptionPane.YES_OPTION,
JOptionPane.WARNING_MESSAGE, null, options, options[0]);
}
TTalk.stop = true;// 無駄なダイアログを発生させない
throw new xTalkException(e.getMessage());
}
return result;
}
private static String combine(int start, int end, ArrayList<String> stringList, ArrayList<wordType> typeList) {
StringBuilder str = new StringBuilder(32);
for (int i = start; i < end; i++) {
if (typeList.get(i) == wordType.STRING) {
str.append("\"");
str.append(stringList.get(i));
str.append("\" ");
} else {
str.append(stringList.get(i));
str.append(" ");
}
}
return str.toString();
}
private static void resolution(String script, ArrayList<String> stringList, ArrayList<wordType> typeList,
boolean isCmd) {
ScriptArea.checkWordsLine(script, stringList, typeList, isCmd, false);
for (int j = 0; j < typeList.size(); j++) {
if (typeList.get(j) == TTalk.wordType.COMMENT) {
typeList.remove(j);
stringList.remove(j);
break;
}
}
}
private static void fullresolution(String script, ArrayList<String> stringList, ArrayList<wordType> typeList,
TreeSet<String> treeSet, boolean isCmd) {
resolution(script, stringList, typeList, isCmd);
StringBuilder handler = new StringBuilder("");
TreeSet<String> varSet;
if (treeSet != null)
varSet = treeSet;
else
varSet = new TreeSet<String>();
ScriptArea.checkWordsLine2(script, stringList, typeList, isCmd, handler, varSet);
}
// スクリプトを単語単位に分解
/*
* private static void resolution(String script, ArrayList<String> stringList,
* ArrayList<wordType> typeList, boolean isCmd) { //long timestart =
* System.currentTimeMillis(); StringBuilder str=new StringBuilder(16);
*
* for(int i=0; i<script.length(); i++) { char code = script.charAt(i);
* if(code=='+' || code=='-' || code=='*' || code=='/' || code=='^' || code=='&'
* || code=='=' || code=='<' || code=='>' || code=='≠' || code=='≤' ||
* code=='≥') { if(code=='-' && i>0 && script.codePointAt(i-1)=='-') {
* typeList.remove(typeList.size()-1); stringList.remove(stringList.size()-1);
* break; } if(str.length()>0) { if(Character.isDigit(str.charAt(0)))
* typeList.add(wordType.STRING); else typeList.add(wordType.X);
* stringList.add(str.toString().toLowerCase().intern()); str.setLength(0); }
* typeList.add(wordType.OPERATOR);
* stringList.add(String.valueOf((char)code).intern()); } else if(code=='(') {
* if(str.length()>0 || typeList.size()>0 && typeList.get(typeList.size()-1) ==
* wordType.X) { if(str.length()>0){ if(Character.isDigit(str.charAt(0)))
* typeList.add(wordType.STRING); else typeList.add(wordType.X);
* stringList.add(str.toString().toLowerCase().intern()); str.setLength(0); }
* String funcstr = stringList.get(stringList.size()-1); if(funcstr=="cd" ||
* funcstr=="card" || funcstr=="bg" || funcstr=="bkgnd" ||funcstr=="background"
* || funcstr=="btn" || funcstr=="button" || funcstr=="fld" || funcstr=="field"
* || funcstr=="stack"|| funcstr=="char" || funcstr=="character"||
* funcstr=="item" || funcstr=="word" || funcstr=="line" || funcstr=="window" ||
* funcstr=="id") { typeList.add(wordType.LBRACKET); } else if(funcstr=="of" &&
* stringList.size() >= 2 && (
* stringList.get(stringList.size()-2).matches("^[0-9]*$") ||
* stringList.get(stringList.size()-2)=="char" ||
* stringList.get(stringList.size()-2)=="character" ||
* stringList.get(stringList.size()-2)=="item" ||
* stringList.get(stringList.size()-2)=="word" ||
* stringList.get(stringList.size()-2)=="line") ) {
* typeList.add(wordType.LBRACKET); } else if(isCmd && typeList.size()==1) {
* //左側がコマンドとして認識される場合 typeList.add(wordType.LBRACKET); } else {
* typeList.add(wordType.LFUNC); } stringList.add("("); } else {
* typeList.add(wordType.LBRACKET); stringList.add("("); } } else if(code==')')
* { if(str.length()>0) { if(Character.isDigit(str.charAt(0)))
* typeList.add(wordType.STRING); else typeList.add(wordType.X);
* stringList.add(str.toString().toLowerCase().intern()); str.setLength(0); }
* typeList.add(wordType.RBRACKET); stringList.add(")"); } else if(code==',') {
* if(str.length()>0) { if(Character.isDigit(str.charAt(0)))
* typeList.add(wordType.STRING); else typeList.add(wordType.X);
* stringList.add(str.toString().toLowerCase().intern()); str.setLength(0); }
* typeList.add(wordType.COMMA); stringList.add(","); } else if(code=='"') {
* if(str.length()>0) { typeList.add(wordType.X);
* stringList.add(str.toString().toLowerCase().intern()); str.setLength(0); }
* i++; while(i<script.length()) { code = script.charAt(i); if(code=='"') break;
* str.append(code); i++; } typeList.add(wordType.STRING);
* stringList.add(str.toString()); str.setLength(0); } else if (code==' ' ||
* code=='\t') { if(str.length()>0) { if(Character.isDigit(str.charAt(0)))
* typeList.add(wordType.STRING); else typeList.add(wordType.X);
* stringList.add(str.toString().toLowerCase().intern()); str.setLength(0); } }
* else if(i==script.length()-1) { str.append(code); if(str.length()>0) {
* if(Character.isDigit(str.charAt(0))) typeList.add(wordType.STRING); else
* typeList.add(wordType.X);
* stringList.add(str.toString().toLowerCase().intern()); str.setLength(0); } }
* else { str.append(code); } } //timeIsMoney("resolution:",timestart,18); }
*/
private Result doScriptLines(String script, OObject object, OObject target, MemoryData memData)
throws xTalkException {
Result ret = null;
String[] scripts = script.split("\n");
for (int i = 0; i < scripts.length; i++) {
ret = doScriptLine(scripts[i], object, target, memData, 0);
}
return ret;
}
private Result doScriptLine(String script, OObject object, OObject target, MemoryData memData, int startline)
throws xTalkException {
// long timestart = System.currentTimeMillis();
ArrayList<String> stringList = new ArrayList<String>();
ArrayList<wordType> typeList = new ArrayList<wordType>();
// 1.分解
fullresolution(script, stringList, typeList, memData.treeset, true);
wordType[] typeAry = new wordType[typeList.size()];
for (int i = 0; i < typeList.size(); i++) {
typeAry[i] = typeList.get(i);
}
// timeIsMoney("CommandExec:",timestart,19);
// 2.実行
return CommandExec(stringList, typeAry, object, target, memData, startline);
}
@SuppressWarnings("unchecked")
final private Result CommandExec(ArrayList<String> stringList, wordType[] typeAry, OObject object, OObject target,
MemoryData memData, int startline) throws xTalkException {
// long timestart = System.currentTimeMillis();
Result result = new Result();
if (stringList.size() == 0)
return result;
String str = stringList.get(0)/* .toLowerCase().intern() */;
if (stringList.size() == 1) {
// System.out.println("do-"+str);
} else {
// System.out.println("do-"+str+stringList.get(1));
}
if (TTalk.stop) {
throw new xTalkException("user abort.");
}
if (TTalk.tracemode >= 1 && startline > 0) {
ScriptEditor.openScriptEditor(PCARD.pc, object, startline);
boolean watcher = false;
if (VariableWatcher.watcherWindow.isVisible()) {
watcher = true;
VariableWatcher.watcherWindow.setTable(TTalk.globalData, memData);
}
if (TTalk.tracemode == 2) {
while (stepflag == false) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
}
if (watcher == false && VariableWatcher.watcherWindow.isVisible()) {
watcher = true;
VariableWatcher.watcherWindow.setTable(TTalk.globalData, memData);
}
if (!PCARD.pc.stack.scriptEditor.isVisible()) {
break;
}
}
stepflag = false;
}
}
boolean inScript = true;
if (commandSet.contains(str)) {
// オブジェクトからその親にハンドラは含まれているか
inScript = false;
OObject obj = object;
while (obj != null && obj.handlerList != null) {
if (obj.handlerList.contains(str)) {
inScript = true;
break;
}
obj = obj.parent;
}
}
if (inScript) {
// スクリプトに含まれるハンドラ
int o = 0;
for (int i = 1; i < stringList.size(); i++) {
if (typeAry[i] == wordType.COMMA || i == stringList.size() - 1) {
o++;
}
}
String[] paramAry = new String[o];
o = 0;
int j = 1;
boolean flag = false;
if (stringList.size() == 1)
j = 0;
else {
int nest = 0;
for (int i = 1; i <= stringList.size(); i++) {
if (i < stringList.size() && (typeAry[i] == wordType.LFUNC || typeAry[i] == wordType.LBRACKET)) {
nest++;
}
if (i < stringList.size() && (typeAry[i] == wordType.RBRACKET || typeAry[i] == wordType.RFUNC)) {
nest--;
}
if (i == stringList.size() || (typeAry[i] == wordType.COMMA && nest == 0)) {
if (j < typeAry.length && typeAry[j] == wordType.OPERATOR
&& 0 != stringList.get(j).compareTo("-")) {
// msg boxに式を入れた場合には、コマンドとして実行はしない
flag = true;
result.ret = 1;
break;
}
/*
* if(stringList.get(0).equals("Movie")){
* System.out.println("param "+stringList.get(j)+" :"+j+" "+i); }
*/
paramAry[o] = Evalution(stringList, typeAry, j, i - 1, memData, object, target);
j = i + 1;
o++;
}
}
}
// 基本は自分自身にメッセージ送信する
// バックグラウンドとスタックの場合は自分の子供のカードにメッセージ送信する
OObject sendObject = object;
if (object != null && object.objectType.equals("background")) {
sendObject = ((OBackground) object).viewCard;
if (sendObject == null && ((OStack) ((OBackground) object).parent).curCard.bg == object) {
sendObject = ((OStack) ((OBackground) object).parent).curCard;
}
} else if (object != null && object.objectType.equals("stack")) {
sendObject = ((OStack) object).curCard;
}
if (sendObject == null)
sendObject = object;
if (!flag)
result = ReceiveMessage(stringList.get(0), paramAry, sendObject, target, memData);
if (result.ret == 1) {
// 値を評価する(msg box用)
result.theResult = Evalution(stringList, typeAry, 0, stringList.size() - 1, memData, object, target);
result.ret = 0;
}
}
if (str == "global") {
for (int i = 1; i < stringList.size(); i++) {
if (stringList.get(i).equals(","))
continue;
setGlobalVariable(stringList.get(i), null);
}
} else if (str == "put") {
if (0 == stringList.get(stringList.size() - 2).compareToIgnoreCase("into")
&& (0 == stringList.get(stringList.size() - 1).compareToIgnoreCase("message")
|| 0 == stringList.get(stringList.size() - 1).compareToIgnoreCase("msg"))) {
String value = Evalution(stringList, typeAry, 1, stringList.size() - 3, memData, object, target);
GMsg.msg.setText(value);
} else if (stringList.size() >= 2) {
int next = 2;
String dirStr = "";
while (next < stringList.size()) {
dirStr = stringList.get(next);
if (0 == dirStr.compareToIgnoreCase("into") || 0 == dirStr.compareToIgnoreCase("before")
|| 0 == dirStr.compareToIgnoreCase("after")) {
break;
}
next++;
}
if (next + 1 >= stringList.size()) {
// put xx
String value = Evalution(stringList, typeAry, 1, stringList.size() - 1, memData, object, target);
GMsg.msg.setText(value);
} else if (0 == dirStr.compareToIgnoreCase("after")) {
String doStr = "";
for (int k = 1; k < next; k++) {
if (typeAry[k] == wordType.STRING)
doStr += " \"" + stringList.get(k) + "\"";
else
doStr += " " + stringList.get(k);
}
String toStr = "";
for (int k = next + 1; k < stringList.size(); k++) {
if (typeAry[k] == wordType.STRING)
toStr += " \"" + stringList.get(k) + "\"";
else
toStr += " " + stringList.get(k);
}
doStr = "put " + toStr + " & " + doStr + " into" + toStr;
doScript(object, target, "", doStr, memData, null, 1);
} else if (0 == dirStr.compareToIgnoreCase("before")) {
String doStr = "";
for (int k = 1; k < next; k++) {
if (typeAry[k] == wordType.STRING)
doStr += " \"" + stringList.get(k) + "\"";
else
doStr += " " + stringList.get(k);
}
String toStr = "";
for (int k = next + 1; k < stringList.size(); k++) {
if (typeAry[k] == wordType.STRING)
toStr += " \"" + stringList.get(k) + "\"";
else
toStr += " " + stringList.get(k);
}
doStr = "put " + doStr + " & " + toStr + " into" + toStr;
doScript(object, target, "", doStr, memData, null, 1);
} else { // put into
if (next + 2 < stringList.size() && (0 == stringList.get(next + 1).compareToIgnoreCase("char")
|| 0 == stringList.get(next + 1).compareToIgnoreCase("character")
|| 0 == stringList.get(next + 1).compareToIgnoreCase("item")
|| 0 == stringList.get(next + 1).compareToIgnoreCase("word")
|| 0 == stringList.get(next + 1).compareToIgnoreCase("line")
|| 0 == stringList.get(next + 1).compareToIgnoreCase("last")
|| 0 == stringList.get(next + 1).compareToIgnoreCase("first"))) {
String value = Evalution(stringList, typeAry, 1, next - 1, memData, object, target);
if (0 == stringList.get(next + 1).compareToIgnoreCase("last")
|| 0 == stringList.get(next + 1).compareToIgnoreCase("first")) {
stringList.set(next + 1, stringList.get(next + 2));
// 上書きされるのでコピーする
ArrayList<String> cpstringList = (ArrayList<String>) stringList.clone();
wordType[] cptypeAry = (wordType[]) typeAry.clone();
String value1 = Evalution(cpstringList, cptypeAry, next + 4, cpstringList.size() - 1,
memData, object, target);
stringList.set(next + 2,
Integer.toString(getNumberOfChunk(cpstringList.get(next + 2) + "s", value1)));
}
int next2 = next + 1;
int nest = 0;
while (next2 < stringList.size()) {
if (nest == 0 && 0 == stringList.get(next2).compareToIgnoreCase("of")) {
break;
}
if (typeAry[next2] == wordType.LBRACKET || typeAry[next2] == wordType.LFUNC) {
nest++;
}
if (typeAry[next2] == wordType.RBRACKET || typeAry[next2] == wordType.RFUNC) {
nest--;
}
next2++;
}
String chunkStart = "";
String chunkEnd = null;
int next3 = next;
while (next3 < next2) {
if (0 == stringList.get(next3).compareToIgnoreCase("to")) {
chunkEnd = Evalution(stringList, typeAry, next3 + 1, next2 - 1, memData, object,
target);
break;
}
next3++;
}
chunkStart = Evalution(stringList, typeAry, next + 2, next3 - 1, memData, object, target);
if (next2 + 1 < stringList.size() && (0 == stringList.get(next2 + 1).compareToIgnoreCase("item")
|| 0 == stringList.get(next2 + 1).compareToIgnoreCase("word")
|| 0 == stringList.get(next2 + 1).compareToIgnoreCase("line"))) {
int next4 = next2 + 1;
while (next4 < stringList.size()) {
if (0 == stringList.get(next4).compareToIgnoreCase("of"))
break;
next4++;
}
String chunkStart2 = "";
String chunkEnd2 = null;
int next5 = next2;
while (next5 < next4) {
if (0 == stringList.get(next5).compareToIgnoreCase("to")) {
chunkEnd2 = Evalution(stringList, typeAry, next5 + 1, next4 - 1, memData, object,
target);
break;
}
next5++;
}
chunkStart2 = Evalution(stringList, typeAry, next2 + 2, next5 - 1, memData, object, target);
OObject obj = null;
try {
obj = getObject(stringList, typeAry, next4 + 1, stringList.size() - 1, memData, object,
target);
} catch (Exception e) {
}
if (obj != null) {
setChunkObject2(stringList.get(next + 1), chunkStart, chunkEnd,
stringList.get(next2 + 1), chunkStart2, chunkEnd2, value, obj);
} else {
setChunkVariable2(stringList.get(next + 1), chunkStart, chunkEnd,
stringList.get(next2 + 1), chunkStart2, chunkEnd2, value,
stringList.get(next4 + 1), memData);
}
} else {
OObject obj = null;
try {
obj = getObject(stringList, typeAry, next2 + 1, stringList.size() - 1, memData, object,
target);
} catch (Exception e) {
}
if (obj != null) {
setChunkObject(stringList.get(next + 1), chunkStart, chunkEnd, value, obj);
} else {
setChunkVariable(stringList.get(next + 1), chunkStart, chunkEnd, value,
stringList.get(next2 + 1), memData);
}
}
} else {
ArrayList<String> stL = new ArrayList<String>(stringList);
wordType[] tyA = new wordType[typeAry.length];
System.arraycopy(typeAry, 0, tyA, 0, typeAry.length);
OObject obj;
if (stringList.get(next + 1).equalsIgnoreCase("the") && next + 2 < stringList.size()) {
String str1 = "the " + stringList.get(next + 2);
String res = Evalution(str1, memData, object, target);
/*
* ArrayList<String> tmpStrList = new ArrayList<String>(); ArrayList<wordType>
* newTypeList = new ArrayList<wordType>(); resolution(res, tmpStrList,
* newTypeList, false); wordType[] tmpTypeAry = new
* wordType[newTypeList.size()]; for(int i=0; i<tmpTypeAry.length; i++){
* tmpTypeAry[i] = newTypeList.get(i); }
*/
String newStr = "put empty into " + res;
return doScriptLine(newStr, object, target, memData, 0);
} else {
obj = getObject(stL, tyA, next + 1, stringList.size() - 1, memData, object, target);
}
if (obj != null) {
String value = Evalution(stringList, typeAry, 1, next - 1, memData, object, target);
TUtil.SetProperty(obj, "text", value);
} else {
// 変数
String value = Evalution(stringList, typeAry, 1, stringList.size() - 3, memData, object,
target);
setVariable(memData, stringList.get(stringList.size() - 1), value);
}
}
}
} else {
//
}
} else if (str == "set") {
// set [the] xx [of xx xx] to xx xx
String property = "";
OObject obj = null;
int next = 1;
if (next >= stringList.size())
throw new xTalkException("setが分かりません");
if (0 == stringList.get(next).compareToIgnoreCase("the"))
next++;
if (next >= stringList.size())
throw new xTalkException("setが分かりません");
property = stringList.get(next);
next++;
if (next >= stringList.size())
throw new xTalkException("setが分かりません");
if (0 == stringList.get(next).compareToIgnoreCase("of")) {
next++;
if (next >= stringList.size())
throw new xTalkException("setが分かりません");
int end = next;
while (end < stringList.size()) {
if (0 == stringList.get(end).compareToIgnoreCase("to"))
break;
end++;
}
obj = getObject(stringList, typeAry, next, end - 1, memData, object, target);
if (obj == null) {
throw new xTalkException("setで変更するオブジェクトが分かりません");
}
next = end;
}
if (0 == stringList.get(next).compareToIgnoreCase("to")) {
String value = "";
String param = "";
next++;
while (next < stringList.size()) {
if (stringList.get(next).equals(",") && typeAry[next] == wordType.COMMA) {
if (property.equalsIgnoreCase("topleft") || property.equalsIgnoreCase("scroll")
|| property.equalsIgnoreCase("loc") || property.equalsIgnoreCase("location")
|| property.equalsIgnoreCase("rect") || property.equalsIgnoreCase("rectangle")) {
// loc,rectの場合はコンマで分割
param += Evalution(value, memData, object, target) + ",";
value = "";
next++;
continue;
}
}
if (typeAry[next] == wordType.STRING) {
value += "\"" + stringList.get(next) + "\" ";
} else {
value += stringList.get(next) + " ";
}
next++;
}
param += Evalution(value, memData, object, target);
TUtil.SetProperty(obj, property, param);
}
} else if (str == "go") {
int next = 1;
if (next >= stringList.size())
throw new xTalkException("goが分かりません");
if (0 == stringList.get(next).compareToIgnoreCase("to"))
next++;
int id = 0;
if (0 == stringList.get(next).compareToIgnoreCase("next")) {
int i;
for (i = 0; i < PCARD.pc.stack.cardIdList.size(); i++) {
if (PCARD.pc.stack.curCard != null && PCARD.pc.stack.curCard.id == PCARD.pc.stack.cardIdList.get(i))
break;
}
if (i == PCARD.pc.stack.cardIdList.size())
i = 0;
else {
i++;
if (i >= PCARD.pc.stack.cardIdList.size())
i = 0;
}
id = PCARD.pc.stack.cardIdList.get(i);
} else if (0 == stringList.get(next).compareToIgnoreCase("prev")
|| 0 == stringList.get(next).compareToIgnoreCase("previous")) {
int i;
for (i = 0; i < PCARD.pc.stack.cardIdList.size(); i++) {
if (PCARD.pc.stack.curCard.id == PCARD.pc.stack.cardIdList.get(i))
break;
}
if (i == 0)
i = PCARD.pc.stack.cardIdList.size() - 1;
else
i--;
id = PCARD.pc.stack.cardIdList.get(i);
} else if (0 == stringList.get(next).compareToIgnoreCase("first")) {
id = PCARD.pc.stack.cardIdList.get(0);
} else if (0 == stringList.get(next).compareToIgnoreCase("last")) {
id = PCARD.pc.stack.cardIdList.get(PCARD.pc.stack.cardIdList.size() - 1);
} else if (0 == stringList.get(next).compareToIgnoreCase("home")) {
if (PCARD.pc.tool != null) {
PCARD.pc.tool.end();
PCARD.pc.tool = null;
PaintTool.saveCdPictures();
{
// ペイント用バッファ
PCARD.pc.mainImg = null;
PCARD.pc.bgImg = null;
PCARD.pc.undoBuf = null;
PCARD.pc.redoBuf = null;
}
lockMessages = true;
}
if (!lockMessages) {
talk.ReceiveMessage("closeCard", "", PCARD.pc.stack.curCard, null, false);
if (PCARD.pc.stack != null && PCARD.pc.stack.curCard != null && PCARD.pc.stack.curCard.bg != null) {
talk.ReceiveMessage("closeBackground", "", PCARD.pc.stack.curCard.bg, null, false);
}
talk.ReceiveMessage("closeStack", "", PCARD.pc.stack, null, false);
}
if (PCARD.pc.stack.curCard != null) {
PCARD.pc.stack.curCard.removeData();
if (PCARD.pc.stack.curCard.bg != null)
PCARD.pc.stack.curCard.bg.removeData();
}
PCARD.pc.stack.clean();
PCARD.pc.emptyWindow();
result.ret = -1;
return result;
} else if (0 == stringList.get(next).compareToIgnoreCase("cd")
|| 0 == stringList.get(next).compareToIgnoreCase("card")
|| next + 1 < stringList.size() && (0 == stringList.get(next + 1).compareToIgnoreCase("cd")
|| 0 == stringList.get(next + 1).compareToIgnoreCase("card"))) {
OObject obj = getObject(stringList, typeAry, next, stringList.size() - 1, memData, object, target);
if (obj != null)
id = obj.id;
}
if (id == 0) {
result.theResult = "card not found";
return result;
}
// #####こんなことして大丈夫?
messageList.clear();
// ペイントの後片付け
if (PCARD.pc.tool != null) {
PCARD.pc.tool.end();
PaintTool.saveCdPictures();
{
// ペイント用バッファ
PCARD.pc.mainImg = null;
PCARD.pc.bgImg = null;
PCARD.pc.undoBuf = null;
PCARD.pc.redoBuf = null;
}
lockMessages = true;
}
if (!lockMessages) {
talk.ReceiveMessage("closeCard", new String[0], PCARD.pc.stack.curCard, PCARD.pc.stack.curCard, null);
}
OCard cd = OCard.getOCard(PCARD.pc.stack, id, true);// データのみ読み込む
if (!lockMessages) {
if (cd.bgid != PCARD.pc.stack.curCard.bgid) {
talk.ReceiveMessage("closeBackground", new String[0], PCARD.pc.stack.curCard,
PCARD.pc.stack.curCard, null);
}
}
boolean saveLockedScreen = PCARD.lockedScreen;
if (!PCARD.lockedScreen) {
if (PCARD.visual > 0)
VEffect.setOldOff();
// メインスレッドで画面を書き換えられてしまうのを防ぐ
PCARD.lockedScreen = true;
fastLockScreen = 0;
}
PCARD.pc.stack.curCard.removeData();
if (PCARD.pc.stack.curCard.bg != null)
PCARD.pc.stack.curCard.bg.removeData();
PCARD.pc.stack.curCard.bg = null;
for (int i = PCARD.pc.mainPane.getComponentCount() - 1; i >= 0; i--) {
// PCARD.pc.mainPane.remove(PCARD.pc.mainPane.getComponent(i));
}
cd = OCard.getOCard(PCARD.pc.stack, id, false);// 部品もピクチャも読み込む
cd.bg = OBackground.getOBackground(PCARD.pc.stack, cd, cd.bgid, false);// new OBackground(PCARD.pc.stack,
// cd, cd.bgid, false);
cd.parent = cd.bg;
if (PCARD.pc.stack.curCard.label != null) {
PCARD.pc.mainPane.remove(PCARD.pc.stack.curCard.label);
PCARD.pc.stack.curCard.label = null;
PCARD.pc.stack.curCard.pict = null;
}
PCARD.pc.stack.curCard = cd;
if (!saveLockedScreen) {
VEffect.visualEffect(PCARD.visual, PCARD.toVisual, PCARD.visSpd);
PCARD.visual = 0;
PCARD.toVisual = 0;
PCARD.visSpd = 3;
}
if (!lockMessages) {
if (cd.bgid != PCARD.pc.stack.curCard.bgid) {
talk.ReceiveMessage("openBackground", new String[0], PCARD.pc.stack.curCard, PCARD.pc.stack.curCard,
null);
}
talk.ReceiveMessage("openCard", new String[0], PCARD.pc.stack.curCard, PCARD.pc.stack.curCard, null);
}
if (PCARD.pc.tool != null) {
// ペイントの開始
String toolName = PCARD.pc.tool.getName();
PCARD.pc.tool = null;
TBButtonListener.ChangeTool(toolName, null);
} else if (AuthTool.tool != null) {
// オーサリングの開始
if (AuthTool.tool.getClass() == ButtonTool.class) {
TBButtonListener.ChangeTool("button", null);
} else if (AuthTool.tool.getClass() == FieldTool.class) {
TBButtonListener.ChangeTool("field", null);
}
}
// System.out.println("curCard:"+PCARD.pc.stack.curCard.getShortName());
} else if (str == "visual") {
int next = 1;
if (next >= stringList.size())
throw new xTalkException("visualが分かりません");
if (0 == stringList.get(next).compareToIgnoreCase("effect"))
next++;
int mode;
mode = TUtil.getVisualMode(stringList, next, stringList.size() - 1);
PCARD.visual = mode & 0xFF;
PCARD.toVisual = (mode >> 8) & 0xFF;
PCARD.visSpd = (mode >> 16) & 0xFF;
} else if (str == "lock") {
int next = 1;
if (next >= stringList.size())
throw new xTalkException("lockが分かりません");
if (0 == stringList.get(next).compareToIgnoreCase("screen")) {
if (fastLockScreen != object.id) {
VEffect.setOldOff();
}
PCARD.lockedScreen = true;
} else if (0 == stringList.get(next).compareToIgnoreCase("messages")) {
lockMessages = true;
}
} else if (str == "unlock") {
int next = 1;
if (next >= stringList.size())
throw new xTalkException("unlockが分かりません");
if (0 == stringList.get(next).compareToIgnoreCase("screen")) {
int vis = 0, tovis = 0, spd = 3;
next++;
if (next < stringList.size() && 0 == stringList.get(next).compareToIgnoreCase("with")) {
next++;
if (next < stringList.size() && 0 == stringList.get(next).compareToIgnoreCase("visual")) {
next++;
if (next < stringList.size() && 0 == stringList.get(next).compareToIgnoreCase("effect"))
next++;
}
if (next < stringList.size()) {
int mode = TUtil.getVisualMode(stringList, next, stringList.size() - 1);
vis = mode & 0xFF;
tovis = (mode >> 8) & 0xFF;
spd = (mode >> 16) & 0xFF;
}
}
PCARD.lockedScreen = false;
if (vis == 0)
fastLockScreen = object.id;
VEffect.visualEffect(vis, tovis, spd);
} else if (0 == stringList.get(next).compareToIgnoreCase("messages")) {
lockMessages = false;
}
} else if (str == "answer") {
// answer
int next = 1;
if (next >= stringList.size())
throw new xTalkException("answerが分かりません");
if (stringList.get(next).equals("file")) {
// ファイルオープンダイアログ
next++;
int j;
for (j = next; next < stringList.size() - 1; j++) {
if (stringList.get(j).equals("of") && stringList.get(j + 1).equals("type")) {
break;
}
}
String answerStr = Evalution(stringList, typeAry, next, j - 1, memData, object, target);
String type = null;
if (j + 2 < stringList.size()) {
type = Evalution(stringList, typeAry, j + 2, stringList.size() - 1, memData, object, target);
}
JFileChooser chooser = new JFileChooser();
if (type != null) {
class AnswerFileFilter extends FileFilter {
String type;
String type2;
AnswerFileFilter(String type) {
this.type = type;
if (type.equals("TEXT"))
type2 = "txt";
if (type.equals("PICT"))
type2 = "png";
if (type.equals("STAK"))
type2 = "xml";
}
public boolean accept(File f) {
if (f.isDirectory()) {
return false;
}
String ext = getExtension(f);
if (ext == null || ext.equalsIgnoreCase(type) || ext.equalsIgnoreCase(type2)) {
return true;
}
return false;
}
public String getDescription() {
return type + "ファイル";
}
private String getExtension(File f) {
String ext = null;
String filename = f.getName();
int dotIndex = filename.lastIndexOf('.');
if ((dotIndex > 0) && (dotIndex < filename.length() - 1)) {
ext = filename.substring(dotIndex + 1).toLowerCase();
}
return ext;
}
}
chooser.addChoosableFileFilter(new AnswerFileFilter(type));
}
if (PCARD.pc.stack != null && PCARD.pc.stack.file != null) {
chooser.setCurrentDirectory(new File(new File(PCARD.pc.stack.file.getParent()).getParent()));
}
chooser.setDialogTitle(answerStr);
chooser.setDialogType(JFileChooser.OPEN_DIALOG);
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int selected = chooser.showOpenDialog(PCARD.pc);
if (selected == JFileChooser.APPROVE_OPTION) {
String path = chooser.getSelectedFile().getPath();
setVariable(memData, "it", path);
}
} else {
// answerダイアログボックスの表示
String answerStr = "";
String btn1 = "OK";
String btn2 = null;
String btn3 = null;
int i;
for (i = next + 1; i < stringList.size(); i++) {
if (0 == stringList.get(i).compareToIgnoreCase("with"))
break;
}
answerStr = Evalution(stringList, typeAry, next, i - 1, memData, object, target);
next = i;
if (next < stringList.size() && 0 == stringList.get(next).compareToIgnoreCase("with")) {
next++;
if (next < stringList.size())
btn1 = stringList.get(next);
next++;
if (next + 1 < stringList.size() && 0 == stringList.get(next).compareToIgnoreCase("or")) {
btn2 = btn1;
next++;
btn1 = stringList.get(next);
next++;
}
if (next + 1 < stringList.size() && 0 == stringList.get(next).compareToIgnoreCase("or")) {
btn3 = btn2;
btn2 = btn1;
next++;
btn1 = stringList.get(next);
}
}
new GDialog(PCARD.pc, answerStr, null, btn3, btn2, btn1);
setVariable(memData, "it", GDialog.clicked);
}
} else if (str == "add") {
int next = 1;
while (next < stringList.size()) {
if (0 == stringList.get(next).compareToIgnoreCase("to"))
break;
next++;
}
if (next >= stringList.size())
throw new xTalkException("addが分かりません");
String newStr = "";
newStr += "put";
for (int i = next + 1; i < stringList.size(); i++) {
if (typeAry[i] == wordType.STRING) {
newStr += " \"" + stringList.get(i) + "\"";
} else {
newStr += " " + stringList.get(i);
}
}
newStr += " +";
for (int i = 1; i < next; i++) {
if (typeAry[i] == wordType.STRING) {
newStr += " \"" + stringList.get(i) + "\"";
} else {
newStr += " " + stringList.get(i);
}
}
newStr += " into";
for (int i = next + 1; i < stringList.size(); i++) {
if (typeAry[i] == wordType.STRING) {
newStr += " \"" + stringList.get(i) + "\"";
} else {
newStr += " " + stringList.get(i);
}
}
// doScript(object, target, "", newStr, memData,1);
doScriptLine(newStr, object, target, memData, 0);
} else if (str == "subtract") {
int next = 1;
while (next < stringList.size()) {
if (0 == stringList.get(next).compareToIgnoreCase("from"))
break;
next++;
}
if (next >= stringList.size())
throw new xTalkException("subtractが分かりません");
String newStr = "";
newStr += "put";
for (int i = next + 1; i < stringList.size(); i++) {
if (typeAry[i] == wordType.STRING) {
newStr += " \"" + stringList.get(i) + "\"";
} else {
newStr += " " + stringList.get(i);
}
}
newStr += " -";
for (int i = 1; i < next; i++) {
if (typeAry[i] == wordType.STRING) {
newStr += " \"" + stringList.get(i) + "\"";
} else {
newStr += " " + stringList.get(i);
}
}
newStr += " into";
for (int i = next + 1; i < stringList.size(); i++) {
if (typeAry[i] == wordType.STRING) {
newStr += " \"" + stringList.get(i) + "\"";
} else {
newStr += " " + stringList.get(i);
}
}
// doScript(object, target, "", newStr, memData,1);
doScriptLine(newStr, object, target, memData, 0);
} else if (str == "multiply") {
int next = 1;
while (next < stringList.size()) {
if (0 == stringList.get(next).compareToIgnoreCase("by"))
break;
next++;
}
if (next >= stringList.size())
throw new xTalkException("multiplyが分かりません");
String newStr = "";
newStr += "put";
for (int i = next + 1; i < stringList.size(); i++) {
if (typeAry[i] == wordType.STRING) {
newStr += " \"" + stringList.get(i) + "\"";
} else {
newStr += " " + stringList.get(i);
}
}
newStr += " *";
for (int i = 1; i < next; i++) {
if (typeAry[i] == wordType.STRING) {
newStr += " \"" + stringList.get(i) + "\"";
} else {
newStr += " " + stringList.get(i);
}
}
newStr += " into";
for (int i = 1; i < next; i++) {
if (typeAry[i] == wordType.STRING) {
newStr += " \"" + stringList.get(i) + "\"";
} else {
newStr += " " + stringList.get(i);
}
}
// doScript(object, target, "", newStr, memData,1);
doScriptLine(newStr, object, target, memData, 0);
} else if (str == "divide") {
int next = 1;
while (next < stringList.size()) {
if (0 == stringList.get(next).compareToIgnoreCase("by"))
break;
next++;
}
if (next >= stringList.size())
throw new xTalkException("divideが分かりません");
String newStr = "";
newStr += "put";
for (int i = next + 1; i < stringList.size(); i++) {
if (typeAry[i] == wordType.STRING) {
newStr += " \"" + stringList.get(i) + "\"";
} else {
newStr += " " + stringList.get(i);
}
}
newStr += " /";
for (int i = 1; i < next; i++) {
if (typeAry[i] == wordType.STRING) {
newStr += " \"" + stringList.get(i) + "\"";
} else {
newStr += " " + stringList.get(i);
}
}
newStr += " into";
for (int i = 1; i < next; i++) {
if (typeAry[i] == wordType.STRING) {
newStr += " \"" + stringList.get(i) + "\"";
} else {
newStr += " " + stringList.get(i);
}
}
// doScript(object, target, "", newStr, memData,1);
doScriptLine(newStr, object, target, memData, 0);
} else if (str == "get") {
int next = 1;
if (next >= stringList.size())
throw new xTalkException("getが分かりません");
// 変数it
String value = Evalution(stringList, typeAry, next, stringList.size() - 1, memData, object, target);
setVariable(memData, "it", value);
/*
* String newStr=""; newStr += "put"; for(int i=next; i<stringList.size(); i++){
* newStr += " "+stringList.get(i); } newStr += " into it"; doScript(object,
* target, "", newStr, memData);
*/
} else if (str == "show") {
String objStr = "";
int next = 1;
if (next >= stringList.size())
throw new xTalkException("showが分かりません");
if (stringList.get(next).equalsIgnoreCase("all") && next + 1 < stringList.size()
&& (stringList.get(next + 1).equalsIgnoreCase("cds")
|| stringList.get(next + 1).equalsIgnoreCase("cards"))) {
// show all cds
String innerScript = "";
if (!lockMessages) {
innerScript += "lock messages\n";
}
for (int i = 0; i < PCARD.pc.stack.cardIdList.size(); i++) {
innerScript += "go cd " + (i + 1) + "\n";
if (!PCARD.lockedScreen)
innerScript += "wait 1 tick\n";
}
innerScript += "go cd 1\n";
innerScript += "unlock messages\n";
// if(!lockMessages){
// doScript(object, target, "", innerScript, memData,1);
doScriptLines(innerScript, object, target, memData);
// }
} else if (stringList.get(next).equalsIgnoreCase("groups")) {
// フィールドのグループ指定スタイルに下線を付ける
// TODO:
} else {
while (next < stringList.size()) {
if (0 == stringList.get(next).compareToIgnoreCase("at")) {
String newStr = "";
newStr += "set loc of";
for (int i = 1; i < next; i++) {
objStr += " " + stringList.get(i);
}
newStr += objStr + " to ";
for (int i = next + 1; i < stringList.size(); i++) {
if (typeAry[i] == wordType.STRING) {
newStr += " \"" + stringList.get(i) + "\"";
} else {
newStr += " " + stringList.get(i);
}
}
// doScript(object, target, "", newStr, memData,1);
doScriptLine(newStr, object, target, memData, 0);
break;
}
next++;
}
String newStr = "";
newStr += "set visible of";
if (next < stringList.size()) {
newStr += " " + objStr;
} else {
next = 1;
for (int i = next; i < stringList.size(); i++) {
if (typeAry[i] == wordType.STRING) {
newStr += " \"" + stringList.get(i) + "\"";
} else {
newStr += " " + stringList.get(i);
}
}
}
newStr += " to true";
// doScript(object, target, "", newStr, memData,1);
doScriptLine(newStr, object, target, memData, 0);
}
} else if (str == "hide") {
int next = 1;
if (next >= stringList.size())
throw new xTalkException("hideが分かりません");
String newStr = "";
newStr += "set visible of";
for (int i = next; i < stringList.size(); i++) {
if (typeAry[i] == wordType.STRING) {
newStr += " \"" + stringList.get(i) + "\"";
} else {
newStr += " " + stringList.get(i);
}
}
newStr += " to false";
// doScript(object, target, "", newStr, memData,1);
doScriptLine(newStr, object, target, memData, 0);
} else if (str == "enable") {
int next = 1;
if (next >= stringList.size())
throw new xTalkException("enableが分かりません");
String newStr = "";
newStr += "set enabled of";
for (int i = next; i < stringList.size(); i++) {
if (typeAry[i] == wordType.STRING) {
newStr += " \"" + stringList.get(i) + "\"";
} else {
newStr += " " + stringList.get(i);
}
}
newStr += " to true";
// doScript(object, target, "", newStr, memData,1);
doScriptLine(newStr, object, target, memData, 0);
} else if (str == "disable") {
int next = 1;
if (next >= stringList.size())
throw new xTalkException("disableが分かりません");
String newStr = "";
newStr += "set enabled of";
for (int i = next; i < stringList.size(); i++) {
if (typeAry[i] == wordType.STRING) {
newStr += " \"" + stringList.get(i) + "\"";
} else {
newStr += " " + stringList.get(i);
}
}
newStr += " to false";
// doScript(object, target, "", newStr, memData,1);
doScriptLine(newStr, object, target, memData, 0);
} else if (str == "wait") {
int next = 1;
if (next >= stringList.size())
throw new xTalkException("waitが分かりません");
if (0 == stringList.get(next).compareToIgnoreCase("until")) {
while (true) {
ArrayList<String> stL = new ArrayList<String>(stringList);
wordType[] tyA = new wordType[typeAry.length];
System.arraycopy(typeAry, 0, tyA, 0, typeAry.length);
String cond = Evalution(stL, tyA, next + 1, stringList.size() - 1, memData, object, target);
if (0 == cond.compareToIgnoreCase("true"))
break;
this.TalkSleep(10);
if (TTalk.stop == true) {
throw new xTalkException("user abort.");
}
}
} else if (0 == stringList.get(next).compareToIgnoreCase("while")) {
while (true) {
ArrayList<String> stL = new ArrayList<String>(stringList);
wordType[] tyA = new wordType[typeAry.length];
System.arraycopy(typeAry, 0, tyA, 0, typeAry.length);
String cond = Evalution(stL, tyA, next + 1, stringList.size() - 1, memData, object, target);
if (0 == cond.compareToIgnoreCase("false"))
break;
this.TalkSleep(10);
if (TTalk.stop == true) {
throw new xTalkException("user abort.");
}
}
} else if (0 == stringList.get(stringList.size() - 1).compareToIgnoreCase("seconds")
|| 0 == stringList.get(stringList.size() - 1).compareToIgnoreCase("second")) {
if (stringList.get(next).equalsIgnoreCase("for"))
next++;
String secs = Evalution(stringList, typeAry, next, stringList.size() - 2, memData, object, target);
this.TalkSleep(Integer.valueOf(secs) * 1000);
} else if (0 == stringList.get(stringList.size() - 1).compareToIgnoreCase("ticks")
|| 0 == stringList.get(stringList.size() - 1).compareToIgnoreCase("tick")) {
if (stringList.get(next).equalsIgnoreCase("for"))
next++;
String ticks = Evalution(stringList, typeAry, next, stringList.size() - 2, memData, object, target);
this.TalkSleep(Integer.valueOf(ticks) * 1000 / 60);
} else {
if (stringList.get(next).equalsIgnoreCase("for"))
next++;
String ticks = Evalution(stringList, typeAry, next, stringList.size() - 1, memData, object, target);
if (ticks.length() > 0) {
this.TalkSleep(Integer.valueOf(ticks) * 1000 / 60);
}
}
} else if (str == "do") {
int next = 1;
if (next >= stringList.size())
throw new xTalkException("doが分かりません");
String newStr = "";
newStr = Evalution(stringList, typeAry, next, stringList.size() - 1, memData, object, target);
doScript(object, target, "", newStr, memData, null, 0);
} else if (str == "send") {
// String newStr="";
OObject obj = null;
int next = 1;
if (next >= stringList.size())
throw new xTalkException("sendが分かりません");
while (0 != stringList.get(next).compareToIgnoreCase("to")) {
// newStr += stringList.get(next)+" ";
next++;
if (next >= stringList.size()) {
// throw new xTalkException("sendにはtoが必要です");
break;
}
}
if (next < stringList.size()) {
String newStr2 = Evalution(stringList, typeAry, 1, next - 1, memData, object, target);
next++;
if (next >= stringList.size())
throw new xTalkException("send toが分かりません");
obj = getObject(stringList, typeAry, next, stringList.size() - 1, memData, object, target);
if (obj == null) {
// 変数の値を解析して送信する
String v = Evalution(stringList, typeAry, next, stringList.size() - 1, memData, object, target);
ArrayList<String> vList = new ArrayList<String>();
ArrayList<wordType> tList = new ArrayList<wordType>();
resolution(v, vList, tList, false);
wordType[] typeAry2 = new wordType[tList.size()];
for (int i = 0; i < tList.size(); i++) {
typeAry2[i] = tList.get(i);
}
obj = getObject(vList, typeAry2, 0, vList.size() - 1, memData, object, target);
if (obj == null) {
throw new xTalkException("sendでメッセージを送信するオブジェクトが分かりません");
}
}
if (obj.objectType.equals("window")) {
((OWindow) obj).Command(newStr2);
} else {
doScript(obj, obj, "", newStr2, memData, null, 0);
}
} else {
String newStr2 = Evalution(stringList, typeAry, 1, next - 1, memData, object, target);
doScript(object, object, "", newStr2, memData, null, 0);
}
} else if (str == "edit") {
String newStr = "";
OObject obj = null;
int next = 1;
if (next >= stringList.size())
throw new xTalkException("editが分かりません");
if (stringList.get(next).equalsIgnoreCase("picture")) {
// picture
if (ResEdit.nulleditor == null || ResEdit.nulleditor.child.pcard == null) {
ResEdit.nulleditor = new ResEdit((PCARD) null, "icon", (OObject) null);
}
ResEdit.nulleditor.child.pcard.stack.rsrc.addResource(ResEdit.nulleditor.child.rsrcAry.length + 1,
"icon", new File(stringList.get(2)).getName(), stringList.get(2));
ResEdit.nulleditor.child.open(ResEdit.nulleditor.child.pcard, 0);
/*
* Rsrc.rsrcClass[] newAry = new
* Rsrc.rsrcClass[ResEdit.nulleditor.child.rsrcAry.length+1]; for(int i=0;
* i<newAry.length-1; i++){ newAry[i] = ResEdit.nulleditor.child.rsrcAry[i]; }
* newAry[newAry.length-1] = ResEdit.nulleditor.child.pcard.stack.rsrc. new
* rsrcClass(newAry.length, "icon", stringList.get(2), stringList.get(2), "0",
* "0", null); ResEdit.nulleditor.child.rsrcAry = newAry;
*/
} else {
// script
while (0 != stringList.get(next).compareToIgnoreCase("of")) {
if (!newStr.equals(""))
newStr += " ";
newStr += stringList.get(next);
next++;
if (next >= stringList.size())
throw new xTalkException("editにはofが必要です");
}
next++;
if (next >= stringList.size())
throw new xTalkException("edit ofが分かりません");
obj = getObject(stringList, typeAry, next, stringList.size() - 1, memData, object, target);
if (obj == null)
throw new xTalkException("editで編集するオブジェクトが分かりません");
if (newStr.equalsIgnoreCase("script")) {
ScriptEditor.openScriptEditor(PCARD.pc, obj);
} else {
throw new xTalkException(newStr + "は編集できません");
}
}
} else if (str == "play") {
int next = 1;
if (next >= stringList.size())
throw new xTalkException("playが分かりません");
if (0 == stringList.get(next).compareToIgnoreCase("stop")) {
// play stop
tsound.PlayStop();
} else {
Pattern p = Pattern.compile(
"([a-grA-GR]{0,1})([#b]{0,1})([0-7]{0,1})([whqestx]{0,1})([3]{0,1}[\\.]*)([pf]{0,2})[ ]*");
String neiro[] = new String[7];
for (int i = 0; i < 7; i++) {
neiro[i] = "";
}
String soundRsrc = "";
int tempo = 120;
int vol = 100;
while (next < stringList.size()) {
if (next > 1 && 0 == stringList.get(next).compareToIgnoreCase("tempo")) {
if (soundRsrc.equals(""))
soundRsrc = Evalution(stringList, typeAry, 1, next - 1, memData, object, target);
tempo = Integer.valueOf(stringList.get(next + 1));
next++;
// System.out.println("soundRsrc"+soundRsrc);
} else if (next > 1) {
Matcher m = p.matcher(stringList.get(next));
boolean flag = false;
while (m.find()) {
int allLength = 0;
for (int i = 0; i < 7; i++) {
neiro[i] = m.group(i);
allLength += neiro[i].length();
}
if (allLength == 0)
break;
if (soundRsrc.equals(""))
soundRsrc = Evalution(stringList, typeAry, 1, next - 1, memData, object, target);
if (neiro[6].contains("p"))
vol /= 2;
if (neiro[6].contains("f")) {
vol *= 2;
if (vol > 100)
vol = 100;
}
tsound.Play(PCARD.pc.stack, soundRsrc, neiro, tempo, vol);
flag = true;
}
if (flag == false && !soundRsrc.equals("")) {
throw new xTalkException("playの" + stringList.get(next) + "が分かりません");
}
}
next++;
}
if (soundRsrc.equals("")) {
soundRsrc = Evalution(stringList, typeAry, 1, next - 1, memData, object, target);
boolean playres = tsound.Play(PCARD.pc.stack, soundRsrc, neiro, tempo, vol);
if (!playres) {
result.theResult = "play sound error";
result.ret = 0;
}
}
}
} else if (str == "push") {
int next = 1;
if (next >= stringList.size())
throw new xTalkException("pushが分かりません");
if (stringList.get(next).equalsIgnoreCase("cd") || stringList.get(next).equalsIgnoreCase("card")) {
pushCardList.add(PCARD.pc.stack.curCard.getShortName());
} else {
if (next >= stringList.size())
throw new xTalkException("push " + stringList.get(next) + "が分かりません");
}
} else if (str == "pop") {
int next = 1;
if (next >= stringList.size())
throw new xTalkException("popが分かりません");
if (stringList.get(next).equalsIgnoreCase("cd") || stringList.get(next).equalsIgnoreCase("card")) {
if (pushCardList.size() > 0) {
String doStr = "go " + pushCardList.get(pushCardList.size() - 1);
pushCardList.remove(pushCardList.size() - 1);
doScript(object, target, "", doStr, memData, null, 1);
}
} else {
if (next >= stringList.size())
throw new xTalkException("push " + stringList.get(next) + "が分かりません");
}
} else if (str == "click") {
int next = 1;
if (next < stringList.size() && stringList.get(next).equalsIgnoreCase("at")) {
next++;
if (next >= stringList.size())
throw new xTalkException("click atの座標がありません");
String value = "";
String param = "";
while (next < stringList.size() && !stringList.get(next).equalsIgnoreCase("with")) {
if (stringList.get(next).equals(",")) {
// コンマで分割
param += Evalution(value, memData, object, target) + ",";
value = "";
next++;
continue;
}
value += stringList.get(next) + " ";
next++;
}
param += Evalution(value, memData, object, target);
String[] params = param.split(",");
if (2 != params.length)
throw new xTalkException("click atの座標がわかりません");
int x = 0, y = 0;
try {
x = Integer.valueOf(params[0]);
y = Integer.valueOf(params[1]);
} catch (Exception e) {
throw new xTalkException("click atの座標がわかりません");
}
if (PCARD.pc.tool == null && AuthTool.tool == null) {
// browse tool
OObject obj = null;
for (int i = 0; i < PCARD.pc.mainPane.getComponentCount(); i++) {
Component c = PCARD.pc.mainPane.getComponent(i);
if (c.isVisible() && x >= c.getX() && y >= c.getY() && x < c.getX() + c.getWidth()
&& y < c.getY() + c.getHeight() && // containsを使うと透明ボタンで反応しない
c.isEnabled()) {
if (c.getClass() == MyPopup.class)
obj = ((MyPopup) c).btnData;
if (c.getClass() == MyCheck.class)
obj = ((MyCheck) c).btnData;
if (c.getClass() == MyRadio.class)
obj = ((MyRadio) c).btnData;
if (c.getClass() == RoundButton.class)
obj = ((RoundButton) c).btnData;
if (c.getClass() == RectButton.class)
obj = ((RectButton) c).btnData;
if (c.getClass() == RoundedCornerButton.class)
obj = ((RoundedCornerButton) c).btnData;
if (c.getClass() == MyButton.class)
obj = ((MyButton) c).btnData;
if (c.getClass() == MyTextArea.class)
obj = ((MyTextArea) c).fldData;
if (c.getClass() == MyScrollPane.class)
obj = ((MyScrollPane) c).fldData;
// if(c.getClass()==MyLabel.class) obj = ((MyLabel)c).cd;
if (obj != null) {
GUI.clickH = x;
GUI.clickV = y;
GUI.mouseClicked = true;
talk.ReceiveMessage("mouseDown", "", obj, null, false);
talk.ReceiveMessage("mouseUp", "", obj, null, false);
break;
}
}
}
if (obj == null && x >= 0 && y >= 0 && x < PCARD.pc.stack.width && y < PCARD.pc.stack.height) {
GUI.clickH = x;
GUI.clickV = y;
GUI.mouseClicked = true;
talk.ReceiveMessage("mouseDown", "", PCARD.pc.stack.curCard, null, false);
talk.ReceiveMessage("mouseUp", "", PCARD.pc.stack.curCard, null, false);
}
} else {
// auth or paint tool
if (x < 0 || x > PCARD.pc.getWidth() || y < 0 || y > PCARD.pc.getHeight()) {
result.theResult = "Error: out of card window";
return result;
}
int j;
for (j = 2; j < stringList.size(); j++) {
if (stringList.get(j).equalsIgnoreCase("with")) {
break;
}
}
String withKey = "";
if (j + 1 < stringList.size()) {
withKey = stringList.get(j + 1).toLowerCase();
}
Robot rb = null;
try {
rb = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
x += PCARD.pc.getX();
y += PCARD.pc.getY() + PCARD.pc.getInsets().top;
if (rb != null) {
/*
* BufferedImage bi = new BufferedImage(16,16, BufferedImage.TYPE_INT_ARGB);
* Toolkit kit = Toolkit.getDefaultToolkit(); Cursor cr =
* kit.createCustomCursor(bi, new Point(0, 0), "none-cursor");
* PCARD.pc.setCursor(cr);
*/
if (withKey.contains("control"))
rb.keyPress(KeyEvent.VK_CONTROL);
if (withKey.contains("shift"))
rb.keyPress(KeyEvent.VK_SHIFT);
if (withKey.contains("option") || withKey.contains("alt"))
rb.keyPress(KeyEvent.VK_ALT);
if (withKey.contains("command") || withKey.contains("cmd"))
rb.keyPress(KeyEvent.VK_META);
if (withKey.length() > 0)
rb.delay(100);
{
PointerInfo pointerInfo = MouseInfo.getPointerInfo();
int savex = pointerInfo.getLocation().x;
int savey = pointerInfo.getLocation().y;
rb.mouseMove(x, y);
rb.delay(10);
rb.mousePress(InputEvent.BUTTON1_MASK);
rb.delay(20);
rb.mouseRelease(InputEvent.BUTTON1_MASK);
rb.delay(20);
rb.mouseMove(savex, savey);
}
if (withKey.contains("control"))
rb.keyRelease(KeyEvent.VK_CONTROL);
if (withKey.contains("shift"))
rb.keyRelease(KeyEvent.VK_SHIFT);
if (withKey.contains("option") || withKey.contains("alt"))
rb.keyRelease(KeyEvent.VK_ALT);
if (withKey.contains("command") || withKey.contains("cmd"))
rb.keyRelease(KeyEvent.VK_META);
/* PCARD.pc.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); */
}
}
} else
throw new xTalkException("clickが分かりません");
} else if (str == "drag") {
int next = 1;
int sx = 0, sy = 0;
int ex = 0, ey = 0;
if (next < stringList.size() && stringList.get(next).equalsIgnoreCase("from")) {
next++;
if (next >= stringList.size())
throw new xTalkException("drag fromの座標がありません");
String value = "";
String param = "";
while (next < stringList.size() && !stringList.get(next).equalsIgnoreCase("to")) {
if (stringList.get(next).equals(",")) {
// コンマで分割
param += Evalution(value, memData, object, target) + ",";
value = "";
next++;
continue;
}
value += stringList.get(next) + " ";
next++;
}
param += Evalution(value, memData, object, target);
String[] params = param.split(",");
if (2 != params.length)
throw new xTalkException("drag fromの座標がわかりません");
try {
sx = Integer.valueOf(params[0]);
sy = Integer.valueOf(params[1]);
} catch (Exception e) {
throw new xTalkException("drag fromの座標がわかりません");
}
} else
throw new xTalkException("fromがありません");
if (next < stringList.size() && stringList.get(next).equalsIgnoreCase("to")) {
next++;
if (next >= stringList.size())
throw new xTalkException("drag toの座標がありません");
String value = "";
String param = "";
while (next < stringList.size()) {
if (stringList.get(next).equals(",")) {
// コンマで分割
param += Evalution(value, memData, object, target) + ",";
value = "";
next++;
continue;
}
value += stringList.get(next) + " ";
next++;
}
param += Evalution(value, memData, object, target);
String[] params = param.split(",");
if (2 != params.length)
throw new xTalkException("drag toの座標がわかりません");
try {
ex = Integer.valueOf(params[0]);
ey = Integer.valueOf(params[1]);
} catch (Exception e) {
throw new xTalkException("drag toの座標がわかりません");
}
} else
throw new xTalkException("toがありません");
{
int j;
for (j = next; j < stringList.size(); j++) {
if (stringList.get(j).equalsIgnoreCase("with")) {
break;
}
}
String withKey = "";
if (j + 1 < stringList.size()) {
withKey = stringList.get(j + 1).toLowerCase();
}
Robot rb = null;
try {
rb = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
sx += PCARD.pc.getX();
sy += PCARD.pc.getY() + PCARD.pc.getInsets().top;
ex += PCARD.pc.getX();
ey += PCARD.pc.getY() + PCARD.pc.getInsets().top;
if (rb != null) {
/*
* BufferedImage bi = new BufferedImage(16,16, BufferedImage.TYPE_INT_ARGB);
* Toolkit kit = Toolkit.getDefaultToolkit(); Cursor cr =
* kit.createCustomCursor(bi, new Point(0, 0), "none-cursor");
* PCARD.pc.setCursor(cr);
*/
if (withKey.contains("control"))
rb.keyPress(KeyEvent.VK_CONTROL);
if (withKey.contains("shift"))
rb.keyPress(KeyEvent.VK_SHIFT);
if (withKey.contains("option") || withKey.contains("alt"))
rb.keyPress(KeyEvent.VK_ALT);
if (withKey.contains("command") || withKey.contains("cmd"))
rb.keyPress(KeyEvent.VK_META);
if (withKey.length() > 0)
rb.delay(100);
{
PointerInfo pointerInfo = MouseInfo.getPointerInfo();
int savex = pointerInfo.getLocation().x;
int savey = pointerInfo.getLocation().y;
rb.mouseMove(sx, sy);
rb.delay(10);
rb.mousePress(InputEvent.BUTTON1_MASK);
rb.delay(20);
if (dragspeed > 0) {
double start = new Date().getTime();
double d = Math.sqrt((ex - sx) * (ex - sx) + (ey - sy) * (ey - sy));
while (true) {
double sec = (new Date().getTime() - start) / 10.0 * 3 / 5 / 60;
double per = sec * dragspeed / (d + 0.4);
if (per >= 1)
break;
rb.mouseMove((int) (sx * (1 - per) + ex * per), (int) (sy * (1 - per) + ey * per));
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
}
rb.mouseMove(ex, ey);
rb.delay(20);
rb.mouseRelease(InputEvent.BUTTON1_MASK);
rb.delay(20);
rb.mouseMove(savex, savey);
}
if (withKey.contains("control"))
rb.keyRelease(KeyEvent.VK_CONTROL);
if (withKey.contains("shift"))
rb.keyRelease(KeyEvent.VK_SHIFT);
if (withKey.contains("option") || withKey.contains("alt"))
rb.keyRelease(KeyEvent.VK_ALT);
if (withKey.contains("command") || withKey.contains("cmd"))
rb.keyRelease(KeyEvent.VK_META);
/* PCARD.pc.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); */
}
}
} else if (str == "reset") {
int next = 1;
if (next < stringList.size()) {
if (stringList.get(next).equalsIgnoreCase("menuBar")) {
// メニューバーを初期状態に戻す
PCARD.pc.menu = new GMenu(PCARD.pc, 0);
GMenu.menuUpdate(PCARD.pc.menu.mb);
} else
throw new xTalkException("resetが分かりません");
}
} else if (str == "delete") {
int next = 1;
if (next >= stringList.size())
throw new xTalkException("deleteが分かりません");
if (stringList.get(next).equalsIgnoreCase("menu")) {
// メニュー削除
for (int i = 0; i < PCARDFrame.pc.menu.mb.getComponentCount(); i++) {
Component c = PCARDFrame.pc.menu.mb.getComponent(i);
if (c.getClass() == JMenu.class) {
JMenu menu = (JMenu) c;
String v = Evalution(stringList, typeAry, next + 1, stringList.size() - 1, memData, object,
target);
if (menu.getText().equalsIgnoreCase(v)) {
PCARDFrame.pc.menu.mb.remove(menu);
// メニュー反映
GMenu.menuUpdate(PCARD.pc.menu.mb);
break;
}
}
}
} else if (stringList.get(next).equalsIgnoreCase("menuItem")) {
// メニューアイテム削除
for (int i = 0; i < PCARDFrame.pc.menu.mb.getComponentCount(); i++) {
Component c = PCARDFrame.pc.menu.mb.getComponent(i);
if (c.getClass() == JMenu.class) {
JMenu menu = (JMenu) c;
for (int j = 0; j < menu.getPopupMenu().getComponentCount(); j++) {
Component c2 = menu.getPopupMenu().getComponent(j);
if (c2.getClass() == JMenuItem.class) {
JMenuItem mi = (JMenuItem) c2;
if (mi.getText().equalsIgnoreCase(stringList.get(next))) {
menu.remove(mi);
// メニュー反映
GMenu.menuUpdate(PCARD.pc.menu.mb);
break;
}
}
}
}
}
} else {
String doStr = "put empty into";
for (; next < stringList.size(); next++) {
doStr += " " + stringList.get(next);
}
doScriptLine(doStr, object, target, memData, 0);
// doScript(object, target, "", doStr, memData,1);
}
} else if (str == "sort") {
int next = 1;
if (next >= stringList.size())
throw new xTalkException("sortが分かりません");
String splitStr = "\n";
if (next + 1 <= stringList.size() && stringList.get(next).equalsIgnoreCase("items")
&& stringList.get(next + 1).equalsIgnoreCase("of")) {
splitStr = ",";
next += 2;
} else if (next + 1 <= stringList.size() && stringList.get(next).equalsIgnoreCase("lines")
&& stringList.get(next + 1).equalsIgnoreCase("of")) {
next += 2;
}
int j = next;
boolean isAscending = true; // ソート方向
for (; j < stringList.size(); j++) {
if (stringList.get(j).equalsIgnoreCase("descending")) {
isAscending = false;
break;
} else if (stringList.get(j).equalsIgnoreCase("ascending")) {
break;
}
}
OObject obj = getObject(stringList, typeAry, next, j - 1, memData, object, target);
String oldValue = "";
if (obj != null) {
oldValue = obj.getText();
} else {
oldValue = getVariable(memData, stringList.get(next));
}
StringBuffer newValue = new StringBuffer();
{
String[] valAry = oldValue.split(splitStr);
for (int i = 0; i < valAry.length - 1; i++) {
for (int k = i + 1; k < valAry.length; k++) {
if (valAry[i].compareTo(valAry[k]) > 0 == isAscending) {
String v = valAry[i];
valAry[i] = valAry[k];
valAry[k] = v;
}
}
}
for (int i = 0; i < valAry.length; i++) {
newValue.append(valAry[i]);
if (i + 1 < valAry.length)
newValue.append(splitStr);
}
}
if (obj != null) {
TUtil.SetProperty(obj, "text", newValue.toString());
} else {
setVariable(memData, stringList.get(next), newValue.toString());
}
} else if (str == "ask") {
// ask
int next = 1;
if (stringList.get(next).equals("file")) {
// ファイルセーブダイアログ
next++;
int j;
for (j = next; next < stringList.size() - 1; j++) {
if (stringList.get(j).equals("with")) {
break;
}
}
String answerStr = Evalution(stringList, typeAry, next, j - 1, memData, object, target);
String filename = "";
if (j + 1 < stringList.size()) {
filename = Evalution(stringList, typeAry, j + 1, stringList.size() - 1, memData, object, target);
}
JFileChooser chooser;
if (PCARD.pc.stack.file != null) {
String filePath = PCARD.pc.stack.path;
chooser = new JFileChooser();
File parent = new File(new File(filePath).getParent());
chooser.setCurrentDirectory(parent);
chooser.setSelectedFile(new File(parent.getPath() + File.separatorChar + filename));
} else {
chooser = new JFileChooser(new File(filename));
}
chooser.setDialogTitle(answerStr);
int ret = chooser.showSaveDialog(PCARD.pc);
if (ret != JFileChooser.APPROVE_OPTION) {
// 保存しない
result.theResult = "canceled";
return result;
}
String path = chooser.getSelectedFile().getPath();
setVariable(memData, "it", path);
} else {
// テキスト入力付きダイアログボックスの表示
String answerStr = "";
if (next >= stringList.size())
throw new xTalkException("askが分かりません");
if (stringList.get(next).equalsIgnoreCase("file"))
throw new xTalkException("ask file未対応");
if (stringList.get(next).equalsIgnoreCase("password"))
throw new xTalkException("ask password未対応");
int i;
for (i = next + 1; i < stringList.size(); i++) {
if (0 == stringList.get(i).compareToIgnoreCase("with"))
break;
}
answerStr = Evalution(stringList, typeAry, next, i - 1, memData, object, target);
next = i;
String defaultText = "";
if (next + 1 < stringList.size()) {
defaultText = Evalution(stringList, typeAry, next + 1, stringList.size() - 1, memData, object,
target);
}
new GDialog(PCARD.pc, answerStr, defaultText, "Cancel", "OK", null);
setVariable(memData, "it", GDialog.inputText);
}
} else if (str == "domenu") {
int next = 1;
if (next >= stringList.size())
throw new xTalkException("domenuが分かりません");
// TODO enabledか、そもそもメニューにあるのかも調べたい
GMenuBrowse.doMenu(stringList.get(next));
} else if (str == "select") {
OObject obj = null;
String chunkType = "";
String chunkStart = "";
String chunkEnd = null;
int next = 1;
if (next >= stringList.size())
throw new xTalkException("selectが分かりません");
if (typeAry[next] == wordType.FUNC) {
String newStr = Evalution(stringList, typeAry, next, stringList.size() - 1, memData, object, target);
if (newStr.length() > 0) {
for (int j = stringList.size() - 1; j >= next; j--) {
stringList.remove(1);
}
ArrayList<wordType> typeList = new ArrayList<wordType>();
typeList.add(wordType.X);
resolution(newStr, stringList, typeList, true);
typeAry = new wordType[typeList.size()];
typeList.toArray(typeAry);
} else {
result.theResult = "";
result.ret = 0;
return result;
}
}
if (stringList.get(next).equalsIgnoreCase("char") || stringList.get(next).equalsIgnoreCase("character")
|| stringList.get(next).equalsIgnoreCase("item") || stringList.get(next).equalsIgnoreCase("word")
|| stringList.get(next).equalsIgnoreCase("line")) {
chunkType = stringList.get(next);
int nest = 0;
while (nest != 0 || (0 != stringList.get(next).compareToIgnoreCase("to")
&& 0 != stringList.get(next).compareToIgnoreCase("of"))) {
next++;
if (next >= stringList.size())
break;
if (typeAry[next] == wordType.LFUNC || typeAry[next] == wordType.LBRACKET) {
nest++;
}
if (typeAry[next] == wordType.RFUNC || typeAry[next] == wordType.RBRACKET) {
nest--;
}
}
if (next < stringList.size()) {
chunkStart = Evalution(stringList, typeAry, 2, next - 1, memData, object, target);
}
if (next < stringList.size() && 0 == stringList.get(next).compareToIgnoreCase("to")) {
int next2 = next;
while (0 != stringList.get(next).compareToIgnoreCase("of")) {
next++;
if (next >= stringList.size())
break;
}
if (next < stringList.size()) {
chunkEnd = Evalution(stringList, typeAry, next2 + 1, next - 1, memData, object, target);
}
}
} else if (stringList.get(next).equalsIgnoreCase("empty")) {
if (target != null && target.getClass() == OField.class) {
OField fld = (OField) target;
fld.setSelectedLine(0);
} else {
// throw new xTalkException("ターゲットをselect emptyできません");
}
result.theResult = "";
result.ret = 0;
return result;
} else {
throw new xTalkException("select オブジェクト コマンドは未サポートです");
}
while (0 != stringList.get(next).compareToIgnoreCase("of")) {
next++;
if (next >= stringList.size()) {
throw new xTalkException("selectが分かりません");
}
}
obj = getObject(stringList, typeAry, next + 1, stringList.size() - 1, memData, object, target);
if (obj.objectType.equals("button")) {
if (chunkType.equalsIgnoreCase("line")) {
if (chunkEnd == null) {
if (chunkStart.equals(""))
chunkStart = "0";
((OButton) obj).setSelectedLine(Integer.valueOf(chunkStart));
} else
throw new xTalkException("ボタンはひとつのlineでのみ選択できます");
} else
throw new xTalkException("ボタンはlineでのみ選択できます");
} else if (obj.objectType.equals("field")) {
if (chunkType.equalsIgnoreCase("line") && chunkEnd == null) {
OField fld = (OField) obj;
fld.setSelectedLine(Integer.valueOf(chunkStart));
if (fld.autoSelect == false) {
String[] texts = fld.getText().split("\n");
int start = Integer.valueOf(chunkStart);
int chars = 0;
for (int j = 0; j < start && j < texts.length; j++) {
chars += texts[j].length() + 1;
}
fld.fld.setSelectionStart(chars);
if (start < texts.length) {
fld.fld.setSelectionEnd(chars + texts[start].length());
}
fld.fld.repaint();
}
} else {
throw new xTalkException("selectでの複雑な選択範囲は未サポートです");
}
} else
throw new xTalkException("フィールドとポップアップボタン以外のテキストは選択できません");
} else if (str == "choose") {
int next = 2;
if (next >= stringList.size())
throw new xTalkException("chooseが分かりません");
if (stringList.get(next).equalsIgnoreCase("tool")) {
next = 1;
boolean ret = TBButtonListener.ChangeTool(stringList.get(next), null);
if (!ret) {
throw new xTalkException("ツール\"" + stringList.get(next) + "\"はありません");
}
PCARD.pc.mainPane.repaint();
} else {
throw new xTalkException("chooseが分かりません");
}
} else if (str == "create") {
int next = 1;
if (next >= stringList.size())
throw new xTalkException("createが分かりません");
if (stringList.get(next).equalsIgnoreCase("menu")) {
next++;
if (next >= stringList.size())
throw new xTalkException("create menuが分かりません");
JMenu m = new JMenu(stringList.get(next));
PCARD.pc.menu.mb.add(m);
PCARD.pc.getJMenuBar().add(m);
} else if (stringList.get(next).equalsIgnoreCase("button")
|| stringList.get(next).equalsIgnoreCase("btn")) {
OCardBase cdbase = PCARD.pc.stack.curCard;
if (PaintTool.editBackground) {
cdbase = PCARD.pc.stack.curCard.bg;
}
int newid = 1;
for (; newid < 32767; newid++) {
if (cdbase.GetPartbyId(newid) == null) {
break;
}
}
OButton obtn = null;
obtn = new OButton(cdbase, newid);
if (obtn != null) {
obtn.btn = new MyButton(obtn, "");
((OCardBase) obtn.parent).partsList.add(obtn);
((OCardBase) obtn.parent).btnList.add(obtn);
int left = PCARD.pc.stack.width / 2 - 128 / 2;
int top = PCARD.pc.stack.height / 2 - 32 / 2;
obtn.setRect(left, top, left + 128, top + 32);
obtn.style = 0;
obtn.setName(PCARD.pc.intl.getDialogText("New Button"));
OCard.reloadCurrentCard();
if (AuthTool.tool != null && AuthTool.tool.getClass() == ButtonTool.class) {
ButtonGUI.gui.tgtOBtn = obtn;
ButtonGUI.gui.target = obtn.getComponent();
}
}
} else if (stringList.get(next).equalsIgnoreCase("field") || stringList.get(next).equalsIgnoreCase("fld")) {
OCardBase cdbase = PCARD.pc.stack.curCard;
if (PaintTool.editBackground) {
cdbase = PCARD.pc.stack.curCard.bg;
}
int newid = 1;
for (; newid < 32767; newid++) {
if (cdbase.GetPartbyId(newid) == null) {
break;
}
}
OField ofld = null;
ofld = new OField(cdbase, newid);
if (ofld != null) {
ofld.fld = new MyTextArea("");
((OCardBase) ofld.parent).partsList.add(ofld);
((OCardBase) ofld.parent).fldList.add(ofld);
int left = PCARD.pc.stack.width / 2 - 128 / 2;
int top = PCARD.pc.stack.height / 2 - 128 / 2;
ofld.setRect(left, top, left + 128, top + 128);
ofld.style = 3;
ofld.enabled = false;
OCard.reloadCurrentCard();
if (AuthTool.tool != null && AuthTool.tool.getClass() == FieldTool.class) {
FieldGUI.gui.tgtOFld = ofld;
FieldGUI.gui.target = ofld.getComponent();
}
}
}
} else if (str == "open") {
int next = 1;
if (next >= stringList.size())
throw new xTalkException("openが分かりません");
if (stringList.get(next).equalsIgnoreCase("stack")) {
next = 2;
OStack saveStack = PCARD.pc.stack;
PCARD.pc.stack = new OStack(PCARD.pc);
String path = stringList.get(next);
if (!new File(path).exists()) {
path = convertFromMacPath(path);
}
boolean res = PCARD.pc.stack.openStackFileInThread(path, false);
if (res) {
saveStack.clean();
} else {
PCARD.pc.stack = saveStack;
}
result.theResult = res ? "true" : "false";
result.ret = 0;
} else if (stringList.get(next).equals("file")) {
next++;
if (next >= stringList.size())
throw new xTalkException("open fileが分かりません");
String path = stringList.get(next);
if (!new File(path).exists()) {
path = convertFromMacPath(path);
}
if (!new File(path).getName().equals(path)) {
if (!new File(new File(path).getParent()).exists()) {
throw new xTalkException("不明なディレクトリです。ファイルをopenできません");
}
}
if (!new File(stringList.get(next)).exists()) {
// 新規作成
try {
if (!new File(stringList.get(next)).createNewFile()) {
throw new xTalkException("ファイルを作成できませんでした");
}
} catch (IOException e) {
e.printStackTrace();
}
} else if (new File(stringList.get(next)).isDirectory()) {
// ディレクトリ
throw new xTalkException("ディレクトリはopenできません");
}
for (int i = 0; i < openFileList.size(); i++) {
if (openFileList.get(i).path.equals(path)) {
throw new xTalkException("すでにopenしています");
}
}
OpenFile ofile = new OpenFile();
ofile.path = path;
openFileList.add(ofile);
} else {
throw new xTalkException("openが分かりません");
}
} else if (str == "close") {
int next = 1;
if (next >= stringList.size())
throw new xTalkException("closeが分かりません");
if (stringList.get(next).equalsIgnoreCase("window")) {
next++;
if (next >= stringList.size())
throw new xTalkException("close windowが分かりません");
OObject obj = getObject(stringList, typeAry, next, stringList.size() - 1, memData, object, target);
if (obj != null) {
((OWindow) obj).Close();
}
} else if (stringList.get(next).equals("file")) {
next++;
if (next >= stringList.size())
throw new xTalkException("close fileが分かりません");
String path = stringList.get(next);
if (!new File(path).exists()) {
path = convertFromMacPath(path);
}
if (!new File(path).getName().equals(path)) {
if (!new File(new File(path).getParent()).exists()) {
throw new xTalkException("不明なディレクトリです。ファイルをcloseできません");
}
}
if (!new File(stringList.get(next)).exists()) {
throw new xTalkException("ファイルがありません");
} else if (new File(stringList.get(next)).isDirectory()) {
// ディレクトリ
throw new xTalkException("ディレクトリはcloseできません");
}
OpenFile ofile = null;
for (int i = 0; i < openFileList.size(); i++) {
if (openFileList.get(i).path.equals(path)) {
ofile = openFileList.get(i);
}
}
if (ofile == null)
throw new xTalkException("openしていません");
if (ofile.istream != null) {
try {
ofile.istream.close();
} catch (IOException e) {
}
}
if (ofile.ostream != null) {
try {
ofile.ostream.close();
} catch (IOException e) {
}
}
ofile.path = null;
openFileList.remove(ofile);
} else {
throw new xTalkException("closeが分かりません");
}
} else if (str == "read") {
int next = 1;
if (next >= stringList.size())
throw new xTalkException("readが分かりません");
if (!stringList.get(next).equals("from"))
throw new xTalkException("readが分かりません");
next++;
if (next >= stringList.size())
throw new xTalkException("read fromが分かりません");
if (stringList.get(next).equals("file")) {
next++;
if (next >= stringList.size())
throw new xTalkException("read from fileが分かりません");
String path = stringList.get(next);
if (!new File(path).exists()) {
path = convertFromMacPath(path);
}
int offset = -1;
int forchars = -1;
int endChar = -1;
next++;
if (next < stringList.size()) {
if (stringList.get(next).equals("at")) {
next++;
if (next >= stringList.size())
throw new xTalkException("read from file atが分かりません");
try {
offset = Integer.valueOf(stringList.get(next));
} catch (Exception e) {
throw new xTalkException("ここには数値が必要です");
}
next++;
}
if (next < stringList.size()) {
if (stringList.get(next).equals("until")) {
next++;
if (next >= stringList.size())
throw new xTalkException("read from file untilが分かりません");
String tmp = Evalution(stringList, typeAry, next, stringList.size() - 1, memData, object,
target);
if (tmp.length() == 1) {
endChar = (int) tmp.charAt(0);
} else if (tmp.equalsIgnoreCase("eof")) {
endChar = -1;
} else {
throw new xTalkException("ここには文字を指定してください");
}
} else if (stringList.get(next).equals("for")) {
next++;
if (next >= stringList.size())
throw new xTalkException("read from file forが分かりません");
try {
forchars = Integer.valueOf(stringList.get(next));
} catch (Exception e) {
throw new xTalkException("ここには数値が必要です");
}
}
}
}
OpenFile ofile = null;
for (int i = 0; i < openFileList.size(); i++) {
if (openFileList.get(i).path.equals(path)) {
ofile = openFileList.get(i);
break;
}
}
if (ofile == null) {
throw new xTalkException("ファイルが開かれていません");
}
if (ofile.istream == null) {
try {
ofile.istream = new FileInputStream(new File(path));
} catch (FileNotFoundException e) {
throw new xTalkException("ファイルから読み込みできません");
}
}
try {
if (offset != -1) {
ofile.istream.reset();
}
offset = Math.min(ofile.istream.available(), offset);
for (int i = 0; i < offset; i++) {
ofile.istream.read();
}
forchars = Math.min(ofile.istream.available(), forchars);
if (forchars == -1) {
forchars = ofile.istream.available();
}
byte[] b = new byte[forchars];
int i;
for (i = 0; i < forchars; i++) {
ofile.istream.read(b, i, 1);
if (b[i] == endChar) {
// b[i] = 0;
break;
}
}
setVariable(memData, "it", new String(b));
} catch (IOException e) {
throw new xTalkException("ファイルから読み込み中にエラーが発生しました");
}
} else {
throw new xTalkException("read fromが分かりません");
}
} else if (str == "write") {
int next = 1;
if (next >= stringList.size())
throw new xTalkException("writeが分かりません");
while (next < stringList.size() && !stringList.get(next).equals("to")) {
next++;
}
if (next >= stringList.size())
throw new xTalkException("writeにはto fileが必要です");
String text = Evalution(stringList, typeAry, 1, next - 1, memData, object, target);
next++;
if (next >= stringList.size())
throw new xTalkException("writeにはto fileが必要です");
if (stringList.get(next).equals("file")) {
next++;
if (next >= stringList.size())
throw new xTalkException("write to fileが分かりません");
int j = next;
while (j < stringList.size() && !stringList.get(j).equals("at")) {
next++;
}
String path = Evalution(stringList, typeAry, next, j - 1, memData, object, target);
if (!new File(path).exists()) {
path = convertFromMacPath(path);
}
int offset = -1;
next = j;
if (next < stringList.size() && stringList.get(next).equals("at")) {
next++;
if (next >= stringList.size())
throw new xTalkException("write to file atが分かりません");
try {
offset = Integer.valueOf(stringList.get(next));
} catch (Exception e) {
throw new xTalkException("ここには数値が必要です");
}
next++;
}
OpenFile ofile = null;
for (int i = 0; i < openFileList.size(); i++) {
if (openFileList.get(i).path.equals(path)) {
ofile = openFileList.get(i);
break;
}
}
if (ofile == null) {
throw new xTalkException("ファイルが開かれていません");
}
if (ofile.ostream == null && offset == -1) {
try {
ofile.ostream = new FileOutputStream(new File(path));
} catch (FileNotFoundException e) {
throw new xTalkException("ファイルに書き込みできません");
}
}
try {
if (offset != -1) {
ofile.ostream = new FileOutputStream(new File(path));
}
if (offset > 0) {
byte[] b = new byte[offset];
int i;
FileInputStream istream = new FileInputStream(new File(path));
offset = Math.min(istream.available(), offset);
for (i = 0; i < offset; i++) {
istream.read(b, i, 1);
}
istream.close();
text = new String(b) + text;
}
} catch (IOException e) {
throw new xTalkException("ファイルへの書き込みの準備中にエラーが発生しました");
}
try {
ofile.ostream.write(text.getBytes());
} catch (IOException e) {
throw new xTalkException("ファイルへの書き込み中にエラーが発生しました");
}
} else {
throw new xTalkException("writeが分かりません");
}
} else if (str == "convert") {
int next = 2;
if (next >= stringList.size())
throw new xTalkException("convertが分かりません");
for (next = 2; next < stringList.size(); next++) {
if (stringList.get(next).equalsIgnoreCase("to")) {
break;
}
}
if (next >= stringList.size())
throw new xTalkException("convertにtoがありません");
String convStr = Evalution(stringList, typeAry, 1, next - 1, memData, object, target);
Calendar calender = Calendar.getInstance();
calender.set(Calendar.HOUR_OF_DAY, 0);
calender.set(Calendar.MINUTE, 0);
calender.set(Calendar.SECOND, 0);
while (true) { // breakで抜けるためのダミーループ
Pattern p = Pattern.compile("^([0-9]{1,4})\\.([0-9]{2})([0-9]{2})$");
Matcher m = p.matcher(convStr);
if (m.find()) {
calender.set(Calendar.YEAR, Integer.valueOf(m.group(0)));
calender.set(Calendar.MONTH, Integer.valueOf(m.group(1)) - 1);
calender.set(Calendar.DAY_OF_MONTH, Integer.valueOf(m.group(2)));
break;
}
p = Pattern.compile("^(.*), (.*) ([0-9]{1,2}). ([0-9]){1,4}$");
m = p.matcher(convStr);
if (m.find()) {
calender.set(Calendar.YEAR, Integer.valueOf(m.group(3)));
int month = 0;
String[] month_ary = { "January", "February", "March", "April", "May", "June", "July", "August",
"September", "October", "November", "December" };
for (int i = 0; i < month_ary.length; i++) {
if (month_ary[i].equals(m.group(1))) {
month = i + 1;
calender.set(Calendar.MONTH, month - 1);
break;
}
}
calender.set(Calendar.DAY_OF_MONTH, Integer.valueOf(m.group(2)));
int dow = 0;
String[] youbi_ary = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday" };
for (int i = 0; i < youbi_ary.length; i++) {
if (youbi_ary[i].equals(m.group(0))) {
dow = i + 1;
calender.set(Calendar.DAY_OF_WEEK, dow);
break;
}
}
break;
}
if (PCARD.pc.lang.equals("Japanese")) {
p = Pattern.compile("^([0-9]{1,4})年 ([0-9]{1,2})月 ([0-9]{1,2})日 (.*){3}$");
m = p.matcher(convStr);
if (m.find()) {
calender.set(Calendar.YEAR, Integer.valueOf(m.group(1)));
calender.set(Calendar.MONTH, Integer.valueOf(m.group(2)) - 1);
calender.set(Calendar.DAY_OF_MONTH, Integer.valueOf(m.group(3)));
int dow = 0;
String[] youbi_ary = { "日曜日", "月曜日", "火曜日", "水曜日", "木曜日", "金曜日", "土曜日" };
for (int i = 0; i < youbi_ary.length; i++) {
if (youbi_ary[i].equals(m.group(4))) {
dow = i + 1;
calender.set(Calendar.DAY_OF_WEEK, dow);
break;
}
}
break;
}
}
p = Pattern.compile("^([0-9]{1,2}):([0-9]{1,2}) (AM|PM)$");
m = p.matcher(convStr);
if (m.find()) {
calender.set(Calendar.HOUR, Integer.valueOf(m.group(1)));
calender.set(Calendar.MINUTE, Integer.valueOf(m.group(2)));
calender.set(Calendar.SECOND, 0);
calender.set(Calendar.AM_PM, m.group(3).equals("AM") ? Calendar.AM : Calendar.PM);
break;
}
p = Pattern.compile("^([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}) (AM|PM)$");
m = p.matcher(convStr);
if (m.find()) {
calender.set(Calendar.HOUR, Integer.valueOf(m.group(1)));
calender.set(Calendar.MINUTE, Integer.valueOf(m.group(2)));
calender.set(Calendar.SECOND, Integer.valueOf(m.group(3)));
calender.set(Calendar.AM_PM, m.group(4).equals("AM") ? Calendar.AM : Calendar.PM);
break;
}
throw new xTalkException("convertでこの日付を解析できません");
}
if (next + 1 < stringList.size() && stringList.get(next + 1).equalsIgnoreCase("dateItems")) {
// dateitems
// 年 月 日 時間 分 秒 曜日
String dateItemStr = "";
dateItemStr += calender.get(Calendar.YEAR) + ",";
dateItemStr += calender.get(Calendar.MONTH) + 1 + ",";
dateItemStr += calender.get(Calendar.DAY_OF_MONTH) + ",";
dateItemStr += calender.get(Calendar.HOUR_OF_DAY) + ",";
dateItemStr += calender.get(Calendar.MINUTE) + ",";
dateItemStr += calender.get(Calendar.SECOND) + ",";
dateItemStr += calender.get(Calendar.DAY_OF_WEEK);
result.theResult = dateItemStr;
result.ret = 0;
} else {
throw new xTalkException("convert toでの変換が分かりません");
}
} else if (str == "find") {
int next = 1;
if (next >= stringList.size())
throw new xTalkException("findが分かりません");
OField fld = null;
int j = 2;
for (; j < stringList.size(); j++) {
if (stringList.get(j).equalsIgnoreCase("in") && j + 1 < stringList.size()) {
OObject obj = getObject(stringList, typeAry, j + 1, stringList.size() - 1, memData, object, target);
if (obj != null && obj.objectType.equals("field")) {
fld = (OField) obj;
} else {
throw new xTalkException("findで検索するフィールドが分かりません");
}
break;
}
}
next = 1;
if (stringList.get(next).equalsIgnoreCase("string")) {
// TODO:
next++;
} else if (stringList.get(next).equalsIgnoreCase("chars")) {
// TODO:
next++;
} else if (stringList.get(next).equalsIgnoreCase("word")) {
// TODO:
next++;
} else if (stringList.get(next).equalsIgnoreCase("whole")) {
// TODO:
next++;
} else {
}
String findStr = Evalution(stringList, typeAry, next, j - 1, memData, object, target);
findStr = findStr.toLowerCase();
if (fld != null) {
String text = fld.getText().toLowerCase();
int offset = text.indexOf(findStr);
if (offset == -1) {
result.theResult = "not found";
result.ret = 0;
} else {
PCARD.pc.foundObject = fld.getShortName() + " of " + fld.parent.getShortName();
PCARD.pc.foundIndex = offset;
PCARD.pc.foundText = fld.getText().substring(offset, offset + findStr.length());
fld.fld.setSelectionStart(PCARD.pc.foundIndex);
fld.fld.setSelectionEnd(PCARD.pc.foundIndex + findStr.length());
}
} else {
boolean isFound = false;
for (int i = 0; i < PCARD.pc.stack.cdCacheList.size(); i++) {
OCard card = PCARD.pc.stack.cdCacheList.get(i);
for (int k = 0; k < card.fldList.size(); k++) {
OField fld2 = card.fldList.get(k);
String text = fld2.getText().toLowerCase();
int offset = text.indexOf(findStr);
if (offset != -1) {
PCARD.pc.foundObject = fld2.getShortName() + " of " + card.getShortName();
PCARD.pc.foundIndex = offset;
PCARD.pc.foundText = fld2.getText().substring(offset, offset + findStr.length());
doScriptLine("go " + card.getShortName(), object, target, memData, 0);
fld2.fld.setSelectionStart(PCARD.pc.foundIndex);
fld2.fld.setSelectionEnd(PCARD.pc.foundIndex + findStr.length());
isFound = true;
break;
}
}
if (isFound)
break;
for (int k = 0; k < card.bgfldList.size(); k++) {
OBgFieldData bgfld = card.bgfldList.get(k);
String text = bgfld.text.toLowerCase();
int offset = text.indexOf(findStr);
if (offset != -1) {
PCARD.pc.foundObject = "bg fld id " + bgfld.id + " of " + card.getShortName();
PCARD.pc.foundIndex = offset;
PCARD.pc.foundText = bgfld.text.substring(offset, offset + findStr.length());
doScriptLine("go " + card.getShortName(), object, target, memData, 0);
OField fld2 = card.GetBgFldbyId(bgfld.id);
fld2.fld.setSelectionStart(PCARD.pc.foundIndex);
fld2.fld.setSelectionEnd(PCARD.pc.foundIndex + findStr.length());
isFound = true;
break;
}
}
if (isFound)
break;
}
if (!isFound) {
for (int i = 0; i < PCARD.pc.stack.bgCacheList.size(); i++) {
OBackground bg = PCARD.pc.stack.bgCacheList.get(i);
for (int k = 0; k < bg.fldList.size(); k++) {
OField fld2 = bg.fldList.get(k);
String text = fld2.getText().toLowerCase();
int offset = text.indexOf(findStr);
if (offset != -1) {
PCARD.pc.foundObject = fld2.getShortName() + " of " + bg.getShortName();
PCARD.pc.foundIndex = offset;
PCARD.pc.foundText = fld2.getText().substring(offset, offset + findStr.length());
for (int m = 0; m < PCARD.pc.stack.cdCacheList.size(); m++) {
OCard card = PCARD.pc.stack.cdCacheList.get(m);
if (card.bgid == bg.id) {
doScriptLine("go " + card.getShortName(), object, target, memData, 0);
break;
}
}
fld2.fld.setSelectionStart(PCARD.pc.foundIndex);
fld2.fld.setSelectionEnd(PCARD.pc.foundIndex + findStr.length());
isFound = true;
break;
}
}
if (isFound)
break;
}
}
if (!isFound) {
result.theResult = "not found";
result.ret = 0;
}
}
} else if (str == "type") {
int next = 1;
if (next >= stringList.size())
throw new xTalkException("typeが分かりません");
int j;
for (j = next + 1; j < stringList.size(); j++) {
if (stringList.get(j).equalsIgnoreCase("with")) {
break;
}
}
String withKey = "";
if (j + 1 < stringList.size()) {
withKey = stringList.get(j + 1).toLowerCase();
}
String tmpstr = stringList.get(next).toUpperCase();
Robot rb = null;
try {
rb = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
if (rb != null) {
if (withKey.contains("control"))
rb.keyPress(KeyEvent.VK_CONTROL);
if (withKey.contains("shift"))
rb.keyPress(KeyEvent.VK_SHIFT);
if (withKey.contains("option") || withKey.contains("alt"))
rb.keyPress(KeyEvent.VK_ALT);
if (withKey.contains("command") || withKey.contains("cmd"))
rb.keyPress(KeyEvent.VK_META);
if (withKey.length() > 0)
rb.delay(200);
for (int i = 0; i < tmpstr.length(); i++) {
rb.keyPress(tmpstr.charAt(i));
rb.delay(40);
rb.keyRelease(tmpstr.charAt(i));
}
if (withKey.contains("control"))
rb.keyRelease(KeyEvent.VK_CONTROL);
if (withKey.contains("shift"))
rb.keyRelease(KeyEvent.VK_SHIFT);
if (withKey.contains("option") || withKey.contains("alt"))
rb.keyRelease(KeyEvent.VK_ALT);
if (withKey.contains("command") || withKey.contains("cmd"))
rb.keyRelease(KeyEvent.VK_META);
}
} else if (str == "start") {
int next = 1;
if (next >= stringList.size())
throw new xTalkException("startが分かりません");
if (stringList.get(next) != "using")
throw new xTalkException("startが分かりません");
next++;
if (next >= stringList.size())
throw new xTalkException("start usingが分かりません");
if (stringList.get(next) != "stack")
throw new xTalkException("start usingではスタックを指定してください");
next++;
if (next >= stringList.size())
throw new xTalkException("start using stackが分かりません");
String pathStr = Evalution(stringList, typeAry, next, stringList.size() - 1, memData, object, target);
// 二重using禁止
if (PCARD.pc.stack.usingStacks != null) {
for (int i = 0; i < PCARD.pc.stack.usingStacks.size(); i++) {
if (pathStr.equals(PCARD.pc.stack.usingStacks.get(i).path)) {
PCARD.pc.stack.usingStacks.remove(i);
break;
}
}
}
OStack ostack = new OStack(PCARD.pc);
ostack.openStackFile(pathStr, true);
if (PCARD.pc.stack.usingStacks != null && PCARD.pc.stack.usingStacks.size() <= 8) {
PCARD.pc.stack.usingStacks.add(ostack);
}
} else if (str == "stop") {
int next = 1;
if (next >= stringList.size())
throw new xTalkException("stopが分かりません");
if (stringList.get(next) != "using")
throw new xTalkException("stopが分かりません");
next++;
if (next >= stringList.size())
throw new xTalkException("stop usingが分かりません");
if (stringList.get(next) != "stack")
throw new xTalkException("stop usingではスタックを指定してください");
next++;
if (next >= stringList.size())
throw new xTalkException("stop using stackが分かりません");
String pathStr = Evalution(stringList, typeAry, next, stringList.size() - 1, memData, object, target);
for (int i = 0; i < PCARD.pc.stack.usingStacks.size(); i++) {
if (pathStr.equals(PCARD.pc.stack.usingStacks.get(i).path)) {
PCARD.pc.stack.usingStacks.remove(i);
break;
}
}
} else if (str == "debug") {
int next = 1;
if (next < stringList.size()) {
if (stringList.get(next).equalsIgnoreCase("sound")) {
next++;
if (next < stringList.size()) {
if (stringList.get(next).equalsIgnoreCase("on")) {
TSound.use = true;
} else if (stringList.get(next).equalsIgnoreCase("off")) {
TSound.use = false;
}
}
} else if (stringList.get(next).equalsIgnoreCase("checkpoint")) {
TTalk.tracemode = 2;
ScriptEditor.setTracemode();
} else if (stringList.get(next).equalsIgnoreCase("wait")) {
next++;
if (next < stringList.size()) {
TTalk.wait = Integer.valueOf(stringList.get(next));
}
}
}
} else if (str == "about") {
int next = 1;
if (next < stringList.size()) {
if (stringList.get(next).equalsIgnoreCase("this")) {
new GDialog(null, PCARD.AppName + " " + PCARD.longVersion, null, "OK", null, null);
}
}
} else if (str == "beep") {
java.awt.Toolkit.getDefaultToolkit().beep();
} else if (str == "flash") {
int next = 1;
int cnt;
if (next >= stringList.size())
cnt = 3;
else
cnt = Integer.valueOf(stringList.get(next));
// 反転画像を用意
BufferedImage off = new BufferedImage(PCARD.pc.stack.width, PCARD.pc.stack.height,
BufferedImage.TYPE_INT_BGR);
Graphics2D offg = (Graphics2D) off.createGraphics();
for (int i = 0; i < cnt * 2; i++) {
PCARD.pc.mainPane.paint(offg);
offg.setXORMode(Color.white);
offg.fillRect(0, 0, PCARD.pc.stack.width, PCARD.pc.stack.height);
PCARD.pc.mainPane.getGraphics().drawImage(off, 0, 0, PCARD.pc.stack.width, PCARD.pc.stack.height,
PCARD.pc);
try {
sleep(50);
} catch (InterruptedException e) {
}
}
PCARD.pc.mainPane.repaint();
}
/*
* --add to --answer [with] --answer file [of type] arrowkey --ask [with] ask
* password --ask file [with] --beep --choose x tool choose tool i --click at
* [with] --close file close printing --close window controlKey --convert [date]
* to dateitems convert [date] to dateitems以外 create menu create stack --create
* btn/fld (debug) --debug checkpoint --debug sound on/off --**debug wait <time>
* --delete (dial) --disable --divide --do --doMenu --drag from --edit script of
* --** edit picture <filepath> --enable enterKey --find in functionKey --get
* --go [to] help (hide menubar) hide titlebar --hide --lock screen --lock
* messages mark card mark cards --multiply --open --open file open printing
* open report printing --palette --picture --play --play stop --pop card print
* --push card --put --put into --put after --put before put //menu --read from
* file until/at/for --reset menubar reset paint returnKey save stack x as
* --select --select chunk of field (lineのみ) select text of field --select empty
* --send to --set to show groups --show [at] show marked cards show number
* cards show menubar --show all cards --sort コンテナ sort card --start using stack
* --stop using stack --subtract from tabkey --type [with] --unlock messages
* --unlock screen unmark --visual [effect][to] --wait [for] [seconds] --wait
* until/while --write to file [at]
*/
// timeIsMoney("CommandExec:",timestart,20);
return result;
}
private String convertFromMacPath(String path) {
// : を separetorCharに変換
while (path.indexOf(":") != -1) {
int index = path.indexOf(":");
path = path.substring(0, index) + File.separatorChar + path.substring(index + 1);
}
return path;
}
static String Evalution(String string, MemoryData memData, OObject object, OObject target) throws xTalkException {
// long timestart = System.currentTimeMillis();
if (string.length() == 0) {
return "";
}
ArrayList<String> stringList = new ArrayList<String>();
ArrayList<wordType> typeList = new ArrayList<wordType>();
fullresolution(string, stringList, typeList, memData.treeset, false);
wordType[] typeAry = new wordType[typeList.size()];
for (int i = 0; i < typeList.size(); i++) {
typeAry[i] = typeList.get(i);
}
// timeIsMoney("Evalution1:",timestart,21);
return Evalution(stringList, typeAry, 0, stringList.size() - 1, memData, object, target);
}
final private static String Evalution(ArrayList<String> stringList, wordType[] typeAry, int start, int end,
MemoryData memData, OObject object, OObject target) throws xTalkException {
// リストに入った単語を解釈/演算していく
// 単語数が減るときは左側を残して右側をwordType.NOPにする
/*
* String hintstr=""; for(int i=start; i<=end; i++) { hintstr +=
* stringList.get(i) +" "; } System.out.println(" "+hintstr); String
* hintstr2=""; for(int i=start; i<=end; i++) { if(typeList.get(i)==wordType.X)
* hintstr2 += "value "; if(typeList.get(i)==wordType.STRING) hintstr2 +=
* "STRING "; if(typeList.get(i)==wordType.LFUNC) hintstr2 += "LFUNC ";
* if(typeList.get(i)==wordType.LBRACKET) hintstr2 += "LBRACKET ";
* if(typeList.get(i)==wordType.RBRACKET) hintstr2 += "RBRACKET ";
* if(typeList.get(i)==wordType.OPERATOR) hintstr2 += "OP "; }
* System.out.println(hintstr2);
*/
// long timestart = System.currentTimeMillis();
for (int i = end; i >= start; i--) {
if (typeAry[i] == wordType.NOP) {
end--;
} else
break;
}
if (start == end) {
if (typeAry[start] == wordType.STRING /*
* || stringList.get(start).length()>=1 &&
* Character.isDigit(stringList.get(start).charAt(0))
*/) {
return stringList.get(start);
}
}
// あらかじめtoLowerCaseとinternをしているため、==で比較できる
// 1.括弧
for (int i = start; i <= end; i++) {
if (typeAry[i] == wordType.LBRACKET) {
// 対応する閉じ括弧を探す
int depth = 0;
int j = i + 1;
for (; j <= end; j++) {
if (typeAry[j] == wordType.LBRACKET)
depth++;
else if (typeAry[j] == wordType.LFUNC)
depth++;
else if (typeAry[j] == wordType.RBRACKET || typeAry[j] == wordType.RFUNC) {
if (depth > 0)
depth--;
else {
String value = Evalution(stringList, typeAry, i + 1, j - 1, memData, object, target);
stringList.set(i, value);
typeAry[i] = wordType.STRING;
for (int k = i + 1; k <= j; k++) {
typeAry[k] = wordType.NOP;
}
i = j;
break;
}
}
}
if (j > end)
throw new xTalkException("対応する括弧がありません");
}
/*
* else if(typeAry[i]==wordType.RBRACKET) { //関数の場合にここに入ってしまうので暫定対応 int j;
* for(j=start; j<=end; j++){ if(typeAry[j]==wordType.LFUNC) break; } if(j>end)
* throw new xTalkException("対応する括弧がありません"); }
*/
}
// 括弧付きでの関数コール
for (int i = start; i <= end; i++) {
if (typeAry[i] == wordType.LFUNC) {
if (i > start /* && typeAry[i-1]==wordType.X */) {
int j = i + 1;
int nest = 1;
for (; j <= end; j++) {
if (typeAry[j] == wordType.LBRACKET)
nest++;
if (typeAry[j] == wordType.LFUNC)
nest++;
if (typeAry[j] == wordType.RBRACKET || typeAry[j] == wordType.RFUNC) {
nest--;
if (nest == 0) {
int o = 0;
for (int m = i + 1; m <= j; m++) {
if ((typeAry[m] == wordType.COMMA_FUNC || typeAry[m] == wordType.COMMA) || m == j) {
o++;
}
}
String[] paramAry = new String[o];
int n = i + 1;
o = 0;
for (int m = i + 1; m <= j; m++) {
if ((typeAry[m] == wordType.COMMA_FUNC || typeAry[m] == wordType.COMMA) || m == j) {
paramAry[o] = Evalution(stringList, typeAry, n, m - 1, memData, object, target);
o++;
n = m + 1;
}
}
int offset = 0;
String funcName = stringList.get(i - 1);
if (funcName.equalsIgnoreCase("of")) {
offset = -1;
funcName = stringList.get(i - 2);
if (i - 3 >= start && stringList.get(i - 3).equals("the")) {
offset = -2;
}
}
Result funcres = talk.ReceiveMessage(funcName, paramAry, object, target, memData,
new Result(), true, false, false, 0);
if (funcres != null && funcres.theResult != null) {
stringList.set(i - 1 + offset, funcres.theResult);
typeAry[i - 1 + offset] = wordType.STRING;
} else {
stringList.set(i - 1 + offset, "");
typeAry[i - 1 + offset] = wordType.STRING;
}
for (int k = i + offset; k <= j; k++) {
typeAry[k] = wordType.NOP;
}
break;
}
}
}
if (j > end)
throw new xTalkException("(が不正です");
}
}
}
// HyperTalk定数
for (int i = start; i <= end; i++) {
if (typeAry[i] == wordType.CONST) {
String str = stringList.get(i)/* .toLowerCase() */;
/* if(constantSet.contains(str)) */ {
if (0 == str.compareTo("down")) {
stringList.set(i, "down");
typeAry[i] = wordType.STRING;
} else if (0 == str.compareTo("empty")) {
stringList.set(i, "");
typeAry[i] = wordType.STRING;
} else if (0 == str.compareTo("false")) {
stringList.set(i, "false");
typeAry[i] = wordType.STRING;
} else if (0 == str.compareTo("formfeed")) {
stringList.set(i, "\f");
typeAry[i] = wordType.STRING;
} else if (0 == str.compareTo("carriagereturn")) { // 追加
stringList.set(i, "\r");
typeAry[i] = wordType.STRING;
} else if (0 == str.compareTo("linefeed")) {
stringList.set(i, "\n");
typeAry[i] = wordType.STRING;
} else if (0 == str.compareTo("pi")) {
stringList.set(i, "3.14159265358979323846");
typeAry[i] = wordType.STRING;
} else if (0 == str.compareTo("quote")) {
stringList.set(i, "\"");
typeAry[i] = wordType.STRING;
} else if (0 == str.compareTo("return")) { // 改行コードを変更
// stringList.set(i,"\r");
stringList.set(i, "\n");
typeAry[i] = wordType.STRING;
} else if (0 == str.compareTo("space")) {
stringList.set(i, " ");
typeAry[i] = wordType.STRING;
} else if (0 == str.compareTo("tab")) {
stringList.set(i, "\t");
typeAry[i] = wordType.STRING;
} else if (0 == str.compareTo("comma")) {
stringList.set(i, ",");
typeAry[i] = wordType.STRING;
} else if (0 == str.compareTo("true")) {
stringList.set(i, "true");
typeAry[i] = wordType.STRING;
} else if (0 == str.compareTo("up")) {
stringList.set(i, "up");
typeAry[i] = wordType.STRING;
} else if (0 == str.compareTo("zero")) {
stringList.set(i, "0");
typeAry[i] = wordType.STRING;
} else if (0 == str.compareTo("one")) {
stringList.set(i, "1");
typeAry[i] = wordType.STRING;
} else if (0 == str.compareTo("two")) {
stringList.set(i, "2");
typeAry[i] = wordType.STRING;
} else if (0 == str.compareTo("three")) {
stringList.set(i, "3");
typeAry[i] = wordType.STRING;
} else if (0 == str.compareTo("four")) {
stringList.set(i, "4");
typeAry[i] = wordType.STRING;
} else if (0 == str.compareTo("five")) {
stringList.set(i, "5");
typeAry[i] = wordType.STRING;
} else if (0 == str.compareTo("six")) {
stringList.set(i, "6");
typeAry[i] = wordType.STRING;
} else if (0 == str.compareTo("seven")) {
stringList.set(i, "7");
typeAry[i] = wordType.STRING;
} else if (0 == str.compareTo("eight")) {
stringList.set(i, "8");
typeAry[i] = wordType.STRING;
} else if (0 == str.compareTo("nine")) {
stringList.set(i, "9");
typeAry[i] = wordType.STRING;
}
}
}
}
// 変数
for (int i = start; i <= end; i++) {
if (typeAry[i] == wordType.VARIABLE
|| typeAry[i] == wordType.X && ((i - 1 < start) || (stringList.get(i - 1) != "the"))) {
String str = getVariable(memData, stringList.get(i));
if (str != null) {
stringList.set(i, str);
typeAry[i] = wordType.STRING;
}
}
}
// プロパティ
for (int i = end; i >= start; i--) {
// for(int i=start; i<=end; i++) { // a of the x とかがあるので後ろから見る
if (typeAry[i] == wordType.PROPERTY) {
if (stringList.get(i) == "the" && ((i + 1 <= end
&& 0 != stringList.get(i + 1).compareToIgnoreCase("target"))
&& (i + 2 > end || 0 != stringList.get(i + 2).compareToIgnoreCase("of"))
&& (((0 == stringList.get(i + 1).compareToIgnoreCase("short")
|| 0 == stringList.get(i + 1).compareToIgnoreCase("long"))
&& (i + 3 > end || 0 != stringList.get(i + 3).compareToIgnoreCase("of")))
|| ((0 != stringList.get(i + 1).compareToIgnoreCase("short")
&& 0 != stringList.get(i + 1).compareToIgnoreCase("long"))
&& (i + 3 > end || 0 != stringList.get(i + 3).compareToIgnoreCase("of")))))) {
if (i > end - 1)
throw new xTalkException("theの後にプロパティ名がありません");
String str = stringList.get(i + 1);
if (str.equalsIgnoreCase("short") || str.equalsIgnoreCase("long")) {
str += " " + stringList.get(i + 2);
typeAry[i + 2] = wordType.NOP;
}
stringList.set(i, TUtil.CallSystemFunction(str, null, target, memData, true).theResult);
typeAry[i] = wordType.STRING;
typeAry[i + 1] = wordType.NOP;
} else if (i <= end - 1 && stringList.get(i + 1) == "of"
&& (typeAry[i + 1] == wordType.X || typeAry[i + 1] == wordType.CHUNK
|| typeAry[i + 1] == wordType.OBJECT || typeAry[i + 1] == wordType.OF_PROP)
&&
/* stringList.get(i)!="number" && */ stringList.get(i) != "chars"
&& stringList.get(i) != "characters" && stringList.get(i) != "items"
&& stringList.get(i) != "words" && stringList.get(i) != "lines" && stringList.get(i) != "cds"
&& stringList.get(i) != "cards" && stringList.get(i) != "btns" && stringList.get(i) != "buttons"
&& stringList.get(i) != "flds" && stringList.get(i) != "fields" && stringList.get(i) != "char"
&& stringList.get(i) != "character" && stringList.get(i) != "item"
&& stringList.get(i) != "word" && stringList.get(i) != "line") {
if (i + 1 > end - 1)
throw new xTalkException("ofの後にオブジェクト名がありません");
String str = stringList.get(i);
ObjResult objres = null;
try {
objres = getObjectfromList(stringList, typeAry, i + 2, object, target);
} catch (xTalkException e) {
}
if (objres != null && objres.obj != null) {
//
// String objstr="";
// for(int k=i+2;k<i+2+objres.cnt;k++) objstr += stringList.get(k);
//
int offset = 0;
if (i > start && (0 == stringList.get(i - 1).compareToIgnoreCase("short")
|| 0 == stringList.get(i - 1).compareToIgnoreCase("long"))) {
str = stringList.get(i - 1) + " " + str;
i--;
offset++;
}
if (i > start && 0 == stringList.get(i - 1).compareToIgnoreCase("the")) {
i--;
offset++;
}
stringList.set(i, TUtil.getProperty(str, objres.obj, target, memData));
typeAry[i] = wordType.STRING;
// for(int j=i+1; j<i+2+objres.cnt && j<=end; j++){
for (int j = i + 1; j <= i + 1 + offset + objres.cnt && j <= end; j++) {
typeAry[j] = wordType.NOP;
}
}
}
}
}
// theでコールする関数
for (int i = start; i <= end; i++) {
if (typeAry[i] == wordType.THE_FUNC) {
if (i > end - 1)
throw new xTalkException("theの後に関数名がありません");
String str = stringList.get(i + 1);
stringList.set(i, TUtil.CallSystemFunction(str, new String[0], target, memData, true).theResult);
typeAry[i] = wordType.STRING;
typeAry[i + 1] = wordType.NOP;
}
}
// チャンク式
for (int i = end; i >= start; i--) {
if (typeAry[i] == wordType.CHUNK) {
String str = stringList.get(i)/* .toLowerCase() */;
if (str == "char" || str == "character" || str == "item" || str == "word" || str == "line") {
if (i > start && (stringList.get(i - 1).equals("any") || stringList.get(i - 1).equals("last")
|| stringList.get(i - 1).equals("first"))) {
continue;
}
String chunkStart = "";
String chunkEnd = null;
int j;
for (j = i + 2; j < end; j++) {
if (typeAry[j] == wordType.NOP)
continue;
String str2 = stringList.get(j);
if (0 == str2.compareToIgnoreCase("to")) {
chunkStart = Evalution(stringList, typeAry, i + 1, j - 1, memData, object, target);
for (int k = j + 1; k < end; k++) {
str2 = stringList.get(k);
if (0 == str2.compareToIgnoreCase("of") && typeAry[k] != wordType.NOP) {
chunkEnd = Evalution(stringList, typeAry, j + 1, k - 1, memData, object, target);
j = k;
break;
}
}
break;
} else if (0 == str2.compareToIgnoreCase("of")) {
chunkStart = Evalution(stringList, typeAry, i + 1, j - 1, memData, object, target);
break;
}
}
int k;
for (k = j + 2; k <= end; k++) {
if (typeAry[k] != wordType.NOP && typeAry[k] != wordType.STRING && typeAry[k] != wordType.X
&& typeAry[k] != wordType.OBJECT && typeAry[k] != wordType.OF_OBJ) {
break;
}
}
if (k - 1 > end)
k = end + 1;
if (j + 1 > end)
j = end - 1;
if (j <= i)
break;// ####
String value = Evalution(stringList, typeAry, j + 1, k - 1, memData, object, target);
stringList.set(i, getChunk(str, chunkStart, chunkEnd, value));
typeAry[i] = wordType.STRING;
for (int m = i + 1; m <= k - 1; m++) {
// stringList.set(m,"");
typeAry[m] = wordType.NOP;
}
}
}
}
// チャンク式2(any,last)
for (int i = end; i >= start + 1; i--) {
if (typeAry[i] == wordType.CHUNK) {
String str = stringList.get(i)/* .toLowerCase() */;
if (str == "char" || str == "character" || str == "item" || str == "word" || str == "line") {
if (0 == stringList.get(i - 1).compareToIgnoreCase("any")
|| 0 == stringList.get(i - 1).compareToIgnoreCase("last")
|| 0 == stringList.get(i - 1).compareToIgnoreCase("first")) {
int k;
for (k = i + 2; k <= end; k++) {
if (typeAry[k] != wordType.NOP && typeAry[k] != wordType.STRING
&& typeAry[k] != wordType.OBJECT && typeAry[k] != wordType.X) {
k--;
break;
}
}
if (k > end)
k = end;
String value = Evalution(stringList, typeAry, i + 2, k, memData, object, target);
if (0 == stringList.get(i - 1).compareToIgnoreCase("last")) {
int chunk = getNumberOfChunk(str + "s", value);
if (chunk <= 0)
stringList.set(i - 1, "");
else
stringList.set(i - 1, getChunk(str, Integer.toString(chunk), "", value));
} else if (0 == stringList.get(i - 1).compareToIgnoreCase("first")) {
stringList.set(i - 1, getChunk(str, "1", "", value));
} else if (0 == stringList.get(i - 1).compareToIgnoreCase("any")) {
int number = getNumberOfChunk(str + "s", value);
if (number <= 0)
stringList.set(i - 1, "");
else
stringList.set(i - 1,
getChunk(str, Integer.toString((int) (number * Math.random()) + 1), "", value));
}
typeAry[i - 1] = wordType.STRING;
for (int m = i; m <= k; m++) {
typeAry[m] = wordType.NOP;
}
}
}
}
}
// チャンク式3(number of xxxs)
for (int i = end; i >= start + 2; i--) {
if (typeAry[i] == wordType.X) {
String str = stringList.get(i)/* .toLowerCase() */;
if (str == "chars" || str == "characters" || str == "items" || str == "words" || str == "lines") {
if (0 == stringList.get(i - 1).compareToIgnoreCase("of")
&& 0 == stringList.get(i - 2).compareToIgnoreCase("number") && i + 1 <= end
&& (0 == stringList.get(i + 1).compareToIgnoreCase("of")
|| 0 == stringList.get(i + 1).compareToIgnoreCase("in"))) {
int k;
for (k = i + 2; k <= end; k++) {
if (typeAry[k] != wordType.NOP && typeAry[k] != wordType.STRING && typeAry[k] != wordType.X
&& typeAry[k] != wordType.OBJECT) {
k--;
break;
}
}
if (k > end)
k = end;
String value = Evalution(stringList, typeAry, i + 2, k, memData, object, target);
if (i - 3 >= start && stringList.get(i - 3).equalsIgnoreCase("the")) {
i--;
}
stringList.set(i - 2, Integer.toString(getNumberOfChunk(str, value)));
typeAry[i - 2] = wordType.STRING;
for (int m = i - 1; m <= k; m++) {
typeAry[m] = wordType.NOP;
}
}
} else if (str == "btns" || str == "buttons" || str == "flds" || str == "fields" || str == "cds"
|| str == "cards" || str == "bgs" || str == "bkgnds" || str == "backgrounds") {
int offset = 0;
boolean bg_flag = false;
if (0 == stringList.get(i - 1).compareToIgnoreCase("cd")
|| 0 == stringList.get(i - 1).compareToIgnoreCase("card")) {
offset = 1;
} else if (0 == stringList.get(i - 1).compareToIgnoreCase("bg")
|| 0 == stringList.get(i - 1).compareToIgnoreCase("bkgnd")
|| 0 == stringList.get(i - 1).compareToIgnoreCase("background")) {
bg_flag = true;
offset = 1;
}
if (i - 2 - offset >= start && 0 == stringList.get(i - 1 - offset).compareToIgnoreCase("of")
&& 0 == stringList.get(i - 2 - offset).compareToIgnoreCase("number")) {
// parent
OObject parent = PCARD.pc.stack.curCard;
int endoff = 0;
// if(object.objectType.equals("card")) parent = object;
// else if(object.parent!=null && object.parent.objectType.equals("card"))
// parent = object.parent;
// else if(object.objectType.equals("background")) parent =
// ((OBackground)object).viewCard;
if (0 == stringList.get(i + 1 - offset).compareToIgnoreCase("of")
|| 0 == stringList.get(i + 1 - offset).compareToIgnoreCase("in")) {
ObjResult oResult = getObjectfromList(stringList, typeAry, (i + 1 - offset) + 1, object,
target);
parent = oResult.obj;
endoff = oResult.cnt + 1;
}
System.out.println("number of 's parent:" + parent.getShortName());
if (parent != null) {
// search
int number = -1;
if (0 == str.compareTo("btns") || 0 == str.compareTo("buttons")) {
if (bg_flag) {
if (!parent.objectType.equals("background"))
parent = ((OCard) parent).bg;
}
number = ((OCardBase) parent).btnList.size();
} else if (0 == str.compareTo("flds") || 0 == str.compareTo("fields")) {
if (bg_flag) {
if (!parent.objectType.equals("background"))
parent = ((OCard) parent).bg;
}
number = ((OCardBase) parent).fldList.size();
} else if (0 == str.compareTo("cds") || 0 == str.compareTo("cards")) {
if (bg_flag) {
if (!parent.objectType.equals("background"))
parent = ((OCard) parent).bg;
number = 0;
for (int k = 0; k < ((OStack) parent).cardIdList.size(); k++) {
OCard cd = ((OStack) parent).GetCardbyId(((OStack) parent).cardIdList.get(k));
if (cd.bgid == parent.id) {
number++;
}
}
} else {
number = ((OStack) parent).cardIdList.size();
}
} else if (0 == str.compareTo("bgs") || 0 == str.compareTo("bkgnds")
|| 0 == str.compareTo("backgrounds")) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int k = 0; k < ((OStack) parent).cardIdList.size(); k++) {
OCard cd = ((OStack) parent).GetCardbyId(((OStack) parent).cardIdList.get(k));
int j;
for (j = 0; j < list.size(); j++) {
if (cd.bgid == list.get(j)) {
break;
}
}
if (j >= list.size())
continue;
list.add(cd.bgid);
}
number = list.size();
}
if (number == -1)
throw new xTalkException("number ofで数えられません");
stringList.set(i - 2 - offset, Integer.toString(number));
typeAry[i - 2 - offset] = wordType.STRING;
for (int m = i - 2 - offset + 1; m <= i + endoff; m++) {
typeAry[m] = wordType.NOP;
}
}
}
}
}
}
// ofでコールする関数
for (int i = end; i >= start; i--) {
if (typeAry[i] == wordType.FUNC) {
// ofを使用したnumber of/関数呼び出し
char c = ' ';
if (i + 2 <= end) {
c = stringList.get(i + 2).charAt(stringList.get(i + 2).length() - 1);
}
if (stringList.get(i) == "number" && stringList.get(i + 1) == "of" && (c == 's' || c == 'S')
&& (i + 2 > end || stringList.get(i + 2) != "chars" && stringList.get(i + 2) != "characters"
&& stringList.get(i + 2) != "items" && stringList.get(i + 2) != "words"
&& stringList.get(i + 2) != "lines")) {
// number of xxxs
ObjResult objres2 = null;
int next = i + 2;
if (i + 4 > end - 1) {
} else {
next = i + 3;
if (0 != stringList.get(next).compareToIgnoreCase("of")
&& 0 != stringList.get(next).compareToIgnoreCase("in"))
next++;
objres2 = getObjectfromList(stringList, typeAry, next + 1, object, target);
if (objres2.obj == null) {
objres2.obj = PCARD.pc.stack.curCard;
objres2.cnt = 0;
next = i + 2;
}
}
if (0 == stringList.get(i + 2).compareToIgnoreCase("cds")
|| 0 == stringList.get(i + 2).compareToIgnoreCase("cards")) {
if (objres2 != null && objres2.obj.objectType == "stack") {
OStack st = (OStack) objres2.obj;
stringList.set(i, Integer.toString(st.cardIdList.size()));
typeAry[i] = wordType.STRING;
} else if (objres2 != null && objres2.obj.objectType == "background") {
OBackground bg = (OBackground) objres2.obj;
int cnt = 0;
for (int j = 0; j < bg.stack.cardIdList.size(); j++) {
if (OCard.getOCard(bg.stack, bg.stack.cardIdList.get(j), true).bgid == bg.id) {
cnt++;
}
}
stringList.set(i, Integer.toString(cnt));
typeAry[i] = wordType.STRING;
} else
throw new xTalkException("ここにはバックグラウンドかスタックを指定してください");
} else if (0 == stringList.get(i + 2).compareToIgnoreCase("btns")
|| 0 == stringList.get(i + 2).compareToIgnoreCase("buttons")
|| 0 == stringList.get(i + 3).compareToIgnoreCase("btns")
|| 0 == stringList.get(i + 3).compareToIgnoreCase("buttons")) {
if (objres2 == null || objres2.obj.objectType.equals("card")
|| objres2.obj.objectType.equals("background")) {
OCardBase cdbs;
if (objres2 == null)
cdbs = (OCardBase) PCARD.pc.stack.curCard;
else
cdbs = (OCardBase) objres2.obj;
stringList.set(i, Integer.toString(cdbs.btnList.size()));
typeAry[i] = wordType.STRING;
if (0 == stringList.get(i + 3).compareToIgnoreCase("btns")
|| 0 == stringList.get(i + 3).compareToIgnoreCase("buttons")) {
next++;
}
} else
throw new xTalkException("ここにはカードかバックグラウンドを指定してください");
} else if (0 == stringList.get(i + 2).compareToIgnoreCase("flds")
|| 0 == stringList.get(i + 2).compareToIgnoreCase("fields")
|| 0 == stringList.get(i + 3).compareToIgnoreCase("flds")
|| 0 == stringList.get(i + 3).compareToIgnoreCase("fields")) {
if (objres2 == null || objres2.obj.objectType.equals("card")
|| objres2.obj.objectType.equals("background")) {
OCardBase cdbs;
if (objres2 == null)
cdbs = (OCardBase) PCARD.pc.stack.curCard;
else
cdbs = (OCardBase) objres2.obj;
stringList.set(i, Integer.toString(cdbs.fldList.size()));
typeAry[i] = wordType.STRING;
if (0 == stringList.get(i + 3).compareToIgnoreCase("flds")
|| 0 == stringList.get(i + 3).compareToIgnoreCase("fields")) {
next++;
}
} else
throw new xTalkException("ここにはカードかバックグラウンドを指定してください");
} else if (0 == stringList.get(i + 2).compareToIgnoreCase("parts")
|| 0 == stringList.get(i + 3).compareToIgnoreCase("parts")) {
if (objres2 == null || objres2.obj.objectType.equals("card")
|| objres2.obj.objectType.equals("background")) {
OCardBase cdbs;
if (objres2 == null)
cdbs = (OCardBase) PCARD.pc.stack.curCard;
else
cdbs = (OCardBase) objres2.obj;
stringList.set(i, Integer.toString(cdbs.btnList.size() + cdbs.fldList.size()));
typeAry[i] = wordType.STRING;
} else
throw new xTalkException("ここにはカードかバックグラウンドを指定してください");
}
int cnt = 0;
if (objres2 != null)
cnt += objres2.cnt;
for (int j = i + 1; j <= next + cnt && j <= end; j++) {
typeAry[j] = wordType.NOP;
}
} else if (stringList.get(i) != "number" && stringList.get(i) != "char"
&& stringList.get(i) != "character" && stringList.get(i) != "item"
&& stringList.get(i) != "word" && stringList.get(i) != "line" && stringList.get(i) != "short"
&& stringList.get(i) != "long") {
// 関数呼び出し
String[] paramAry = new String[1];
paramAry[0] = stringList.get(i + 2);
Result funcres = TUtil.CallSystemFunction(stringList.get(i), paramAry, target, memData, true);
int offset = 0;
if (funcres != null && funcres.theResult != null) {
if (i - 1 >= start && stringList.get(i - 1).equalsIgnoreCase("the")) {
i--;
offset++;
}
stringList.set(i, funcres.theResult);
typeAry[i] = wordType.STRING;
} else
throw new xTalkException("この関数が分かりません");
for (int j = i + 1; j <= i + 2 + offset && j <= end; j++) {
typeAry[j] = wordType.NOP;
}
}
}
}
/*
* item random of 2 of x がいけるようにするために前に移動させてみた //プロパティ(or関数) for(int i=start;
* i<=end; i++) { if(typeAry[i]==wordType.X) {
* if(0==stringList.get(i).compareToIgnoreCase("the") && (
* (0!=stringList.get(i+1).compareToIgnoreCase("target")) && (i+2>end ||
* 0!=stringList.get(i+2).compareToIgnoreCase("of")) || (
* (0==stringList.get(i+1).compareToIgnoreCase("short") ||
* 0==stringList.get(i+1).compareToIgnoreCase("long")) && (i+3>end ||
* 0!=stringList.get(i+3).compareToIgnoreCase("of")) ) )) { if(i>end-1) throw
* new xTalkException("theの後にプロパティ名がありません"); String str=stringList.get(i+1);
* if(str.equalsIgnoreCase("short") || str.equalsIgnoreCase("long")){ str +=
* " "+stringList.get(i+2); typeAry[i+2] = wordType.NOP; }
* stringList.set(i,TUtil.getProperty(str,null)); typeAry[i] = wordType.STRING;
* typeAry[i+1] = wordType.NOP; } else if(i<=end-1 &&
* 0==stringList.get(i+1).compareToIgnoreCase("of") && typeAry[i+1]==wordType.X)
* { if(i+1>end-1) throw new xTalkException("ofの後にオブジェクト名がありません"); String
* str=stringList.get(i); ObjResult objres=null; objres =
* getObjectfromList(stringList, typeAry, i+2, object, target); if(objres!=null
* && objres.obj!=null){ // String objstr=""; for(int
* k=i+2;k<i+2+objres.cnt;k++) objstr += stringList.get(k); // int offset = 0;
* if(i>start && (0==stringList.get(i-1).compareToIgnoreCase("short") ||
* 0==stringList.get(i-1).compareToIgnoreCase("long"))){ str =
* stringList.get(i-1)+" "+str; i--; offset++; } if(i>start &&
* 0==stringList.get(i-1).compareToIgnoreCase("the")){ i--; offset++; }
* stringList.set(i,TUtil.getProperty(str,objres.obj)); typeAry[i] =
* wordType.STRING; //for(int j=i+1; j<i+2+objres.cnt && j<=end; j++){ for(int
* j=i+1; j<=i+1+offset+objres.cnt && j<=end; j++){ typeAry[j] = wordType.NOP; }
* } else { // ofを使用したnumber of/関数呼び出し if(0==str.compareToIgnoreCase("number")){
* //number of ObjResult objres2=null; int next=i+2; if(i+4>end-1){
*
* } else { next=i+3; if(0!=stringList.get(next).compareToIgnoreCase("of"))
* next++; objres2 = getObjectfromList(stringList, typeAry, next+1, object,
* target); if(objres2.obj==null){ objres2.obj = PCARD.pc.stack.curCard;
* objres2.cnt = 0; next = i+2; } }
* if(0==stringList.get(i+2).compareToIgnoreCase("cds") ||
* 0==stringList.get(i+2).compareToIgnoreCase("cards")) { if(objres2!=null &&
* objres2.obj.objectType == "stack"){ OStack st = (OStack)objres2.obj;
* stringList.set(i,Integer.toString(st.cardIdList.size())); typeAry[i] =
* wordType.STRING; } else if(objres2!=null && objres2.obj.objectType ==
* "background"){ OBackground bg = (OBackground)objres2.obj; int cnt=0; for(int
* j=0; j<bg.stack.cardIdList.size(); j++){ if(OCard.getOCard(bg.stack,
* bg.stack.cardIdList.get(j), true).bgid == bg.id){ cnt++; } }
* stringList.set(i,Integer.toString(cnt)); typeAry[i] = wordType.STRING; } else
* throw new xTalkException("ここにはバックグラウンドかスタックを指定してください"); } else
* if(0==stringList.get(i+2).compareToIgnoreCase("btns") ||
* 0==stringList.get(i+2).compareToIgnoreCase("buttons") ||
* 0==stringList.get(i+3).compareToIgnoreCase("btns") ||
* 0==stringList.get(i+3).compareToIgnoreCase("buttons")) { if(objres2==null ||
* objres2.obj.objectType.equals("card") ||
* objres2.obj.objectType.equals("background")){ OCardBase cdbs;
* if(objres2==null) cdbs = (OCardBase)PCARD.pc.stack.curCard; else cdbs =
* (OCardBase)objres2.obj;
* stringList.set(i,Integer.toString(cdbs.btnList.size())); typeAry[i] =
* wordType.STRING; } else throw new
* xTalkException("ここにはカードかバックグラウンドを指定してください"); } else
* if(0==stringList.get(i+2).compareToIgnoreCase("flds") ||
* 0==stringList.get(i+2).compareToIgnoreCase("fields") ||
* 0==stringList.get(i+3).compareToIgnoreCase("flds") ||
* 0==stringList.get(i+3).compareToIgnoreCase("fields")) { if(objres2==null ||
* objres2.obj.objectType.equals("card") ||
* objres2.obj.objectType.equals("background")){ OCardBase cdbs;
* if(objres2==null) cdbs = (OCardBase)PCARD.pc.stack.curCard; else cdbs =
* (OCardBase)objres2.obj;
* stringList.set(i,Integer.toString(cdbs.fldList.size())); typeAry[i] =
* wordType.STRING; } else throw new
* xTalkException("ここにはカードかバックグラウンドを指定してください"); } else
* if(0==stringList.get(i+2).compareToIgnoreCase("parts") ||
* 0==stringList.get(i+3).compareToIgnoreCase("parts") ) { if(objres2==null ||
* objres2.obj.objectType.equals("card") ||
* objres2.obj.objectType.equals("background")){ OCardBase cdbs;
* if(objres2==null) cdbs = (OCardBase)PCARD.pc.stack.curCard; else cdbs =
* (OCardBase)objres2.obj;
* stringList.set(i,Integer.toString(cdbs.btnList.size()+cdbs.fldList.size()));
* typeAry[i] = wordType.STRING; } else throw new
* xTalkException("ここにはカードかバックグラウンドを指定してください"); } int cnt=0; if(objres2!=null)
* cnt += objres2.cnt; for(int j=i+1; j<=next+cnt && j<=end; j++){ typeAry[j] =
* wordType.NOP; } } else { //関数呼び出し String[] paramAry = new String[1];
* paramAry[0] = stringList.get(i+2); Result funcres =
* TUtil.CallSystemMessage(str, paramAry, memData, true); int offset=0;
* if(funcres!=null && funcres.theResult!=null) { if(i-1 >= start &&
* stringList.get(i-1).equalsIgnoreCase("the")){ i--; offset++; }
* stringList.set(i,funcres.theResult); typeAry[i] = wordType.STRING; } else
* throw new xTalkException("この関数が分かりません"); for(int j=i+1; j<=i+2+offset &&
* j<=end; j++){ typeAry[j] = wordType.NOP; } } } } } }
*/
// 2a.there is a
for (int i = start; i <= end; i++) {
if (typeAry[i] == wordType.OPERATOR) {
if (stringList.get(i) == "there" && i + 1 <= end && typeAry[i + 1] == wordType.OPERATOR_SUB
&& 0 == stringList.get(i + 1).compareToIgnoreCase("is") && i + 2 <= end
&& typeAry[i + 2] == wordType.OPERATOR_SUB
&& 0 == stringList.get(i + 2).compareToIgnoreCase("a")) {
int j = i;
ObjResult objres = null;
try {
objres = getObjectfromList(stringList, typeAry, i + 3, object, target);
} catch (xTalkException e) {
}
if (objres != null && objres.obj != null) {
stringList.set(j, "true");
typeAry[j] = wordType.STRING;
for (int k = j + 1; k < j + 3 + objres.cnt; k++) {
typeAry[k] = wordType.NOP;
}
} else {
stringList.set(j, "false");
typeAry[j] = wordType.STRING;
for (int k = j + 1; k <= end; k++) {
if (typeAry[k] == wordType.OPERATOR)
break;
typeAry[k] = wordType.NOP;
}
}
} else if (stringList.get(i) == "there" && i + 1 <= end && typeAry[i + 1] == wordType.OPERATOR_SUB
&& 0 == stringList.get(i + 1).compareToIgnoreCase("is") && i + 2 <= end
&& typeAry[i + 2] == wordType.OPERATOR_SUB
&& 0 == stringList.get(i + 2).compareToIgnoreCase("not") && i + 3 <= end
&& typeAry[i + 3] == wordType.OPERATOR_SUB
&& 0 == stringList.get(i + 3).compareToIgnoreCase("a")) {
int j = i;
ObjResult objres = null;
try {
objres = getObjectfromList(stringList, typeAry, i + 4, object, target);
} catch (xTalkException e) {
}
if (objres != null && objres.obj != null) {
stringList.set(j, "false");
typeAry[j] = wordType.STRING;
for (int k = j + 1; k < j + 4 + objres.cnt; k++) {
typeAry[k] = wordType.NOP;
}
} else {
stringList.set(j, "true");
typeAry[j] = wordType.STRING;
for (int k = j + 1; k <= end; k++) {
if (typeAry[k] == wordType.OPERATOR)
break;
typeAry[k] = wordType.NOP;
}
}
}
}
}
// コンテナ
for (int i = start; i <= end; i++) {
if (typeAry[i] == wordType.OBJECT && (i <= end - 1
&& (typeAry[i + 1] == wordType.X || typeAry[i + 1] == wordType.STRING
|| typeAry[i + 1] == wordType.OBJECT || typeAry[i + 1] == wordType.OF_OBJ)
|| stringList.get(i) == "me" || stringList.get(i) == "target" || stringList.get(i) == "msg"
|| stringList.get(i) == "message")) {
ObjResult objres = null;
objres = getObjectfromList(stringList, typeAry, i, object, target);
if (objres != null && objres.obj != null) {
if (i + 1 <= end && stringList.get(i).equalsIgnoreCase("the")
&& stringList.get(i + 1).equalsIgnoreCase("target")) {
// targetの場合はオブジェクト名
stringList.set(i, objres.obj.getShortName());
typeAry[i] = wordType.STRING;
for (int j = i + 1; j < i + objres.cnt && j <= end; j++) {
typeAry[j] = wordType.NOP;
}
} else if (0 == objres.obj.objectType.compareTo("button")
|| 0 == objres.obj.objectType.compareTo("field")) {
stringList.set(i, objres.obj.getText());
typeAry[i] = wordType.STRING;
for (int j = i + 1; j < i + objres.cnt && j <= end; j++) {
typeAry[j] = wordType.NOP;
}
} else if (0 == objres.obj.objectType.compareTo("card"))
throw new xTalkException("カードはコンテナとして使えません");
else if (0 == objres.obj.objectType.compareTo("background"))
throw new xTalkException("バックグラウンドはコンテナとして使えません");
else if (0 == objres.obj.objectType.compareTo("stack"))
throw new xTalkException("スタックはコンテナとして使えません");
}
}
}
// 2b.負の記号(withinはここじゃない?)
for (int i = start; i <= end; i++) {
if (typeAry[i] == wordType.OPERATOR) {
if (stringList.get(i) == "-") {
if (i == start || typeAry[i - 1] == wordType.OPERATOR || typeAry[i - 1] == wordType.OPERATOR_SUB) {
if (i > end - 1)
throw new xTalkException("-の後に値がありません");
String str = Evalution(stringList, typeAry, i + 1, i + 1, memData, object, target);
try {
double value = -1.0 * (Double.valueOf(str));
typeAry[i] = wordType.STRING;
stringList.set(i, numFormat.format(value));
typeAry[i + 1] = wordType.NOP;
} catch (Exception err) {
throw new xTalkException("-の後の値が不正です。" + err);
}
}
} else if (stringList.get(i) == "not") {
if (i == start || (typeAry[i - 1] != wordType.OPERATOR && typeAry[i - 1] != wordType.OPERATOR_SUB)
|| (0 == stringList.get(i - 1).compareToIgnoreCase("and")
|| 0 == stringList.get(i - 1).compareToIgnoreCase("or")
|| 0 == stringList.get(i - 1).compareToIgnoreCase("&"))) {
if (i > end - 1) {
throw new xTalkException("notの後に値がありません");
}
String value = Evalution(stringList, typeAry, i + 1, i + 1, memData, object, target);
if (value.compareToIgnoreCase("true") == 0)
value = "false";
else if (value.compareToIgnoreCase("false") == 0)
value = "true";
else
throw new xTalkException("notの後に真偽値(true/false)がありません");
typeAry[i] = wordType.STRING;
stringList.set(i, value);
typeAry[i + 1] = wordType.NOP;
}
}
/*
* else if(stringList.get(i)=="is" && i+1 <= end &&
* typeAry[i+1]==wordType.OPERATOR && stringList.get(i+1)=="within" ) { String
* str1 = ""; int j=i-1; for(;j>=start;j--){ if(typeAry[j]==wordType.STRING ||
* typeAry[j]==wordType.X){ str1 = Evalution(stringList, typeAry, j, j, memData,
* object, target); break; } } Point p = null; try{ String[] strAry =
* str1.split(","); p = new Point(Integer.valueOf(strAry[0]),
* Integer.valueOf(strAry[1])); } catch (Exception err){ throw new
* xTalkException("within演算子のポイントの指定が不正です。"+err); }
*
* Rectangle r = null; try{ String[] strAry = stringList.get(i+2).split(","); r
* = new Rectangle(Integer.valueOf(strAry[0]), Integer.valueOf(strAry[1]),
* Integer.valueOf(strAry[2]), Integer.valueOf(strAry[3])); } catch (Exception
* err){ throw new xTalkException("within演算子の矩形領域の指定が不正です。"+err); }
*
* typeAry[j] = wordType.STRING; if(r.contains(p)){stringList.set(j,"true");}
* else {stringList.set(j,"false");}
*
* typeAry[i] = wordType.NOP; typeAry[i+1] = wordType.NOP; typeAry[i+2] =
* wordType.NOP; } else if(stringList.get(i)=="is" && i+1 <= end &&
* typeAry[i+1]==wordType.OPERATOR_SUB &&
* 0==stringList.get(i+1).compareToIgnoreCase("not")&& i+2 <= end &&
* typeAry[i+2]==wordType.OPERATOR &&
* 0==stringList.get(i+2).compareToIgnoreCase("within") ) { String str1 = "";
* int j=i-1; for(;j>=start;j--){ if(typeAry[j]==wordType.STRING ||
* typeAry[j]==wordType.X){ str1 = Evalution(stringList, typeAry, j, j, memData,
* object, target); break; } } Point p = null; try{ String[] strAry =
* str1.split(","); p = new Point(Integer.valueOf(strAry[0]),
* Integer.valueOf(strAry[1])); } catch (Exception err){ throw new
* xTalkException("within演算子のポイントの指定が不正です。"+err); }
*
* Rectangle r = null; try{ String[] strAry = stringList.get(i+3).split(","); r
* = new Rectangle(Integer.valueOf(strAry[0]), Integer.valueOf(strAry[1]),
* Integer.valueOf(strAry[2]), Integer.valueOf(strAry[3])); } catch (Exception
* err){ throw new xTalkException("within演算子の矩形領域の指定が不正です。"+err); }
*
* typeAry[j] = wordType.STRING; if( !r.contains(p) ){stringList.set(j,"true");}
* else {stringList.set(j,"false");}
*
* typeAry[i] = wordType.NOP; typeAry[i+1] = wordType.NOP; typeAry[i+2] =
* wordType.NOP; typeAry[i+3] = wordType.NOP; }
*/
}
}
// 3.べき乗
for (int i = end; i >= start; i--) {
if (typeAry[i] == wordType.OPERATOR) {
if (stringList.get(i) == "^") {
if (i > end - 1)
throw new xTalkException("^演算子が不正です");
try {
String str1 = "";
int j = i - 1;
for (; j >= start; j--) {
if (typeAry[j] == wordType.STRING || typeAry[j] == wordType.X) {
str1 = Evalution(stringList, typeAry, j, j, memData, object, target);
break;
}
}
String str2 = Evalution(stringList, typeAry, i + 1, i + 1, memData, object, target);
if (str1.equals(""))
str1 = "0";
if (str2.equals(""))
str2 = "0";
if (str2.equals("∞"))
str1 = "Infinity";
if (str2.equals("∞"))
str2 = "Infinity";
double value = Math.pow(Double.valueOf(str1), Double.valueOf(str2));
typeAry[j] = wordType.STRING;
stringList.set(j, numFormat.format(value));
typeAry[i] = wordType.NOP;
typeAry[i + 1] = wordType.NOP;
} catch (Exception err) {
throw new xTalkException("^演算子が不正です。" + err);
}
}
}
}
// 4.数の乗除
for (int i = start; i <= end; i++) {
if (typeAry[i] == wordType.OPERATOR) {
if (stringList.get(i) == "*" || stringList.get(i) == "/" || stringList.get(i) == "div"
|| stringList.get(i) == "mod") {
if (i > end - 1)
throw new xTalkException(stringList.get(i) + "演算子が不正です");
String str1 = "";
String str2 = "";
try {
int j = i - 1;
for (; j >= start; j--) {
if (typeAry[j] == wordType.STRING || typeAry[j] == wordType.X) {
str1 = Evalution(stringList, typeAry, j, j, memData, object, target);
break;
}
}
str2 = Evalution(stringList, typeAry, i + 1, i + 1, memData, object, target);
double value = 0.0;
if (str1.equals(""))
str1 = "0";
if (str2.equals(""))
str2 = "0";
if (str1.equals("∞") || str2.equals("∞")) {
stringList.set(j, "Infinity");
} else if (str1.equals("�") || str2.equals("�")) {
stringList.set(j, "Infinity");
} else {
if (0 == stringList.get(i).compareTo("*"))
value = Double.valueOf(str1) * Double.valueOf(str2);
else if (0 == stringList.get(i).compareTo("/"))
value = Double.valueOf(str1) / Double.valueOf(str2);
else if (0 == stringList.get(i).compareToIgnoreCase("div"))
value = (int) (Double.valueOf(str1) / Double.valueOf(str2));
else if (0 == stringList.get(i).compareToIgnoreCase("mod"))
value = Double.valueOf(str1) % Double.valueOf(str2);
if (numFormat.format(value) == "∞")
stringList.set(j, "Infinity");
if (numFormat.format(value) == "-∞")
stringList.set(j, "-Infinity");
stringList.set(j, numFormat.format(value));
}
typeAry[j] = wordType.STRING;
typeAry[i] = wordType.NOP;
typeAry[i + 1] = wordType.NOP;
} catch (Exception err) {
throw new xTalkException(stringList.get(i) + "演算子が不正です。" + err);
}
}
}
}
// 5.数の加減
for (int i = start; i <= end; i++) {
if (typeAry[i] == wordType.OPERATOR) {
if (stringList.get(i) == "+" || stringList.get(i) == "-") {
if (i > end - 1)
throw new xTalkException(stringList.get(i) + "演算子が不正です");
try {
String str1 = "";
int j = i - 1;
for (; j >= start; j--) {
if (typeAry[j] == wordType.STRING || typeAry[j] == wordType.X) {
str1 = Evalution(stringList, typeAry, j, j, memData, object, target);
break;
}
}
String str2 = Evalution(stringList, typeAry, i + 1, i + 1, memData, object, target);
double value = 0.0;
if (str1.equals(""))
str1 = "0";
if (str2.equals(""))
str2 = "0";
if (str1.equals("∞") || str2.equals("∞")) {
stringList.set(j, "Infinity");
} else if (str1.equals("�") || str2.equals("�")) {
stringList.set(j, "Infinity");
} else {
if (0 == stringList.get(i).compareTo("+"))
value = Double.valueOf(str1) + Double.valueOf(str2);
else if (0 == stringList.get(i).compareTo("-"))
value = Double.valueOf(str1) - Double.valueOf(str2);
stringList.set(j, numFormat.format(value));
}
typeAry[j] = wordType.STRING;
typeAry[i] = wordType.NOP;
typeAry[i + 1] = wordType.NOP;
} catch (Exception err) {
throw new xTalkException(stringList.get(i) + "演算子が不正です。" + err);
}
}
}
}
// 6..テキストの連結
for (int i = start; i <= end; i++) {
if (typeAry[i] == wordType.OPERATOR) {
if (stringList.get(i) == "&") {
if (i > end - 1) {
throw new xTalkException(stringList.get(i) + "演算子が不正です");
}
String str1 = "";
int j = i - 1;
for (; j >= start; j--) {
if (typeAry[j] == wordType.STRING || typeAry[j] == wordType.X) {
str1 = Evalution(stringList, typeAry, j, j, memData, object, target);
break;
}
}
String str2 = "";
if (stringList.get(i + 1) == "&") {
try {
str2 = Evalution(stringList, typeAry, i + 2, i + 2, memData, object, target);
} catch (Exception err) {
throw new xTalkException(stringList.get(i) + "演算子が不正です。" + err);
}
typeAry[i + 2] = wordType.NOP;
typeAry[j] = wordType.STRING;
stringList.set(j, str1 + " " + str2);
} else {
try {
str2 = Evalution(stringList, typeAry, i + 1, i + 1, memData, object, target);
} catch (Exception err) {
throw new xTalkException(stringList.get(i) + "演算子が不正です。" + err);
}
typeAry[j] = wordType.STRING;
stringList.set(j, str1 + str2);
}
typeAry[i] = wordType.NOP;
typeAry[i + 1] = wordType.NOP;
}
}
}
// within
for (int i = start; i <= end; i++) {
if (typeAry[i] == wordType.OPERATOR) {
if (stringList.get(i) == "is" && i + 1 <= end && typeAry[i + 1] == wordType.OPERATOR
&& stringList.get(i + 1) == "within") {
String str1 = "";
int j = i - 1;
for (; j >= start; j--) {
if (typeAry[j] == wordType.STRING || typeAry[j] == wordType.X) {
str1 = Evalution(stringList, typeAry, j, j, memData, object, target);
break;
}
}
Point p = null;
try {
String[] strAry = str1.split(",");
p = new Point(Integer.valueOf(strAry[0]), Integer.valueOf(strAry[1]));
} catch (Exception err) {
throw new xTalkException("within演算子のポイントの指定が不正です。" + err);
}
Rectangle r = null;
try {
String[] strAry = stringList.get(i + 2).split(",");
r = new Rectangle(Integer.valueOf(strAry[0]), Integer.valueOf(strAry[1]),
Integer.valueOf(strAry[2]), Integer.valueOf(strAry[3]));
} catch (Exception err) {
throw new xTalkException("within演算子の矩形領域の指定が不正です。" + err);
}
typeAry[j] = wordType.STRING;
if (r.contains(p)) {
stringList.set(j, "true");
} else {
stringList.set(j, "false");
}
typeAry[i] = wordType.NOP;
typeAry[i + 1] = wordType.NOP;
typeAry[i + 2] = wordType.NOP;
} else if (stringList.get(i) == "is" && i + 1 <= end && typeAry[i + 1] == wordType.OPERATOR_SUB
&& 0 == stringList.get(i + 1).compareToIgnoreCase("not") && i + 2 <= end
&& typeAry[i + 2] == wordType.OPERATOR
&& 0 == stringList.get(i + 2).compareToIgnoreCase("within")) {
String str1 = "";
int j = i - 1;
for (; j >= start; j--) {
if (typeAry[j] == wordType.STRING || typeAry[j] == wordType.X) {
str1 = Evalution(stringList, typeAry, j, j, memData, object, target);
break;
}
}
Point p = null;
try {
String[] strAry = str1.split(",");
p = new Point(Integer.valueOf(strAry[0]), Integer.valueOf(strAry[1]));
} catch (Exception err) {
throw new xTalkException("within演算子のポイントの指定が不正です。" + err);
}
Rectangle r = null;
try {
String[] strAry = stringList.get(i + 3).split(",");
r = new Rectangle(Integer.valueOf(strAry[0]), Integer.valueOf(strAry[1]),
Integer.valueOf(strAry[2]), Integer.valueOf(strAry[3]));
} catch (Exception err) {
throw new xTalkException("within演算子の矩形領域の指定が不正です。" + err);
}
typeAry[j] = wordType.STRING;
if (!r.contains(p)) {
stringList.set(j, "true");
} else {
stringList.set(j, "false");
}
typeAry[i] = wordType.NOP;
typeAry[i + 1] = wordType.NOP;
typeAry[i + 2] = wordType.NOP;
typeAry[i + 3] = wordType.NOP;
}
}
}
// 7.数またはテキストの比較
for (int i = start; i <= end; i++) {
if (typeAry[i] == wordType.OPERATOR) {
String opr = stringList.get(i);
if (opr == "<" || opr == ">" || opr == "≤" || opr == "≥") {
if (i > end - 1) {
throw new xTalkException("比較演算子が不正です");
}
String str1 = "";
int j = i - 1;
for (; j >= start; j--) {
if (typeAry[j] == wordType.STRING || typeAry[j] == wordType.X) {
str1 = Evalution(stringList, typeAry, j, j, memData, object, target);
break;
}
}
if (typeAry[i + 1] == wordType.OPERATOR_SUB) {
if (i + 1 > end - 1)
throw new xTalkException("比較演算子が不正です");
if (opr == "<" && stringList.get(i + 1) == ">")
continue;
opr = opr + stringList.get(i + 1);
typeAry[i] = wordType.NOP;
i++;
}
String str2 = Evalution(stringList, typeAry, i + 1, i + 1, memData, object, target);
try {
if (str1.equals(""))
str1 = "0";
if (str2.equals(""))
str2 = "0";
Boolean value = false;
if (0 == opr.compareTo("<"))
value = Double.valueOf(str1) < Double.valueOf(str2);
else if (0 == opr.compareTo("<=") || 0 == opr.compareTo("≤"))
value = Double.valueOf(str1) <= Double.valueOf(str2);
// else if(0==opr.compareTo("<>") || 0==opr.compareTo("≠"))
// value=Double.valueOf(str1) != Double.valueOf(str2);
else if (0 == opr.compareTo(">"))
value = Double.valueOf(str1) > Double.valueOf(str2);
else if (0 == opr.compareTo(">=") || 0 == opr.compareTo("≥"))
value = Double.valueOf(str1) >= Double.valueOf(str2);
typeAry[j] = wordType.STRING;
stringList.set(j, value ? "true" : "false");
typeAry[i] = wordType.NOP;
typeAry[i + 1] = wordType.NOP;
} catch (Exception err) {
Boolean value = false;
/*
* if(0==opr.compareTo("<")) value=str1.compareTo(str2)<0; else
* if(0==opr.compareTo("<=") || 0==opr.compareTo("≤"))
* value=str1.compareTo(str2)<=0; else
*/ if (0 == opr.compareTo("<>") || 0 == opr.compareTo("≠"))
value = str1.compareTo(str2) != 0;
/*
* else if(0==opr.compareTo(">")) value=str1.compareTo(str2)>0; else
* if(0==opr.compareTo(">=") || 0==opr.compareTo("≥"))
* value=str1.compareTo(str2)>=0;
*/
else
throw new xTalkException("数字以外を比較できません:" + str1 + "と" + str2);
typeAry[j] = wordType.STRING;
stringList.set(j, value ? "true" : "false");
typeAry[i] = wordType.NOP;
typeAry[i + 1] = wordType.NOP;
}
} else if (opr == "is") {
if (i > end - 1)
continue;
if (0 == stringList.get(i + 1).compareToIgnoreCase("in")) {
if (i + 1 > end - 1)
throw new xTalkException("is in演算子が不正です");
String str1 = "";
int j = i - 1;
for (; j >= start; j--) {
if (typeAry[j] == wordType.STRING || typeAry[j] == wordType.X) {
str1 = Evalution(stringList, typeAry, j, j, memData, object, target);
break;
}
}
String str2 = Evalution(stringList, typeAry, i + 2, i + 2, memData, object, target);
Boolean value = false;
value = str2.toLowerCase().contains(str1.toLowerCase());
typeAry[j] = wordType.STRING;
stringList.set(j, value ? "true" : "false");
typeAry[i] = wordType.NOP;
typeAry[i + 1] = wordType.NOP;
typeAry[i + 2] = wordType.NOP;
} else if (typeAry[i + 1] != wordType.STRING && (0 == stringList.get(i + 1).compareToIgnoreCase("a")
|| 0 == stringList.get(i + 1).compareToIgnoreCase("an"))) {
// is a
if (i + 2 > end)
throw new xTalkException("is a演算子が不正です");
String str1 = "";
int j = i - 1;
for (; j >= start; j--) {
if (typeAry[j] == wordType.STRING || typeAry[j] == wordType.X) {
str1 = Evalution(stringList, typeAry, j, j, memData, object, target);
break;
}
}
boolean value = false;
if (stringList.get(i + 2).equalsIgnoreCase("number")) {
value = str1.matches("^[-]{0,1}[0-9]{1,99}[\\.]{0,1}[0-9]{0,99}$");
} else if (stringList.get(i + 2).equalsIgnoreCase("integer")) {
value = str1.matches("^[-]{0,1}[0-9]{1,99}$");
} else if (stringList.get(i + 2).equalsIgnoreCase("point")) {
value = str1.matches("^[-]{0,1}[0-9]{1,99},[-]{0,1}[0-9]{1,99}$");
} else if (stringList.get(i + 2).equalsIgnoreCase("rect")
|| stringList.get(i + 2).equalsIgnoreCase("rectangle")) {
value = str1.matches(
"^[-]{0,1}[0-9]{1,99},[-]{0,1}[0-9]{1,99},[-]{0,1}[0-9]{1,99},[-]{0,1}[0-9]{1,99}$");
} else if (stringList.get(i + 2).equalsIgnoreCase("date")) {
value = true;// **
} else if (stringList.get(i + 2).equalsIgnoreCase("logical")) {
value = (str1.equalsIgnoreCase("true") || str1.equalsIgnoreCase("false"));
} else
throw new xTalkException(stringList.get(i + 2) + "をis a演算子に使えません");
typeAry[j] = wordType.STRING;
stringList.set(j, value ? "true" : "false");
typeAry[i] = wordType.NOP;
typeAry[i + 1] = wordType.NOP;
typeAry[i + 2] = wordType.NOP;
} else if (0 == stringList.get(i + 1).compareToIgnoreCase("not")) {
if (i > end - 2)
continue;
if (0 == stringList.get(i + 2).compareToIgnoreCase("in")) {
if (i + 2 > end - 1)
throw new xTalkException("is not in演算子が不正です");
String str1 = "";
int j = i - 1;
for (; j >= start; j--) {
if (typeAry[j] == wordType.STRING || typeAry[j] == wordType.X) {
str1 = Evalution(stringList, typeAry, j, j, memData, object, target);
break;
}
}
String str2 = Evalution(stringList, typeAry, i + 3, i + 3, memData, object, target);
Boolean value = false;
value = !str2.toLowerCase().contains(str1.toLowerCase());
typeAry[j] = wordType.STRING;
stringList.set(j, value ? "true" : "false");
typeAry[i] = wordType.NOP;
typeAry[i + 1] = wordType.NOP;
typeAry[i + 2] = wordType.NOP;
typeAry[i + 3] = wordType.NOP;
} else {
if (i > end - 2)
continue;
if (0 == stringList.get(i + 2).compareToIgnoreCase("a")
|| 0 == stringList.get(i + 2).compareToIgnoreCase("an")) {
// is not a/an
if (i + 2 > end)
throw new xTalkException("is not a演算子が不正です");
String str1 = "";
int j = i - 1;
for (; j >= start; j--) {
if (typeAry[j] == wordType.STRING || typeAry[j] == wordType.X) {
str1 = Evalution(stringList, typeAry, j, j, memData, object, target);
break;
}
}
boolean value = false;
if (stringList.get(i + 3).equalsIgnoreCase("number")) {
value = str1.matches("^[-]{0,1}[0-9]{1,99}[\\.]{0,1}[0-9]{0,99}$");
} else if (stringList.get(i + 3).equalsIgnoreCase("integer")) {
value = str1.matches("^[-]{0,1}[0-9]{1,99}$");
} else if (stringList.get(i + 3).equalsIgnoreCase("point")) {
value = str1.matches("^[-]{0,1}[0-9]{1,99},[-]{0,1}[0-9]{1,99}$");
} else if (stringList.get(i + 3).equalsIgnoreCase("rect")
|| stringList.get(i + 3).equalsIgnoreCase("rectangle")) {
value = str1.matches(
"^[-]{0,1}[0-9]{1,99},[-]{0,1}[0-9]{1,99},[-]{0,1}[0-9]{1,99},[-]{0,1}[0-9]{1,99}$");
} else if (stringList.get(i + 3).equalsIgnoreCase("date")) {
value = true;// **
} else if (stringList.get(i + 3).equalsIgnoreCase("logical")) {
value = (str1.equalsIgnoreCase("true") || str1.equalsIgnoreCase("false"));
} else
throw new xTalkException(stringList.get(i + 3) + "をis not a演算子に使えません");
typeAry[j] = wordType.STRING;
stringList.set(j, !value ? "true" : "false");
typeAry[i] = wordType.NOP;
typeAry[i + 1] = wordType.NOP;
typeAry[i + 2] = wordType.NOP;
typeAry[i + 3] = wordType.NOP;
}
}
}
} else if (opr == "contains") {
if (i + 1 > end)
throw new xTalkException("contains演算子が不正です");
String str1 = "";
int j = i - 1;
for (; j >= start; j--) {
if (typeAry[j] == wordType.STRING || typeAry[j] == wordType.X) {
str1 = Evalution(stringList, typeAry, j, j, memData, object, target);
break;
}
}
String str2 = Evalution(stringList, typeAry, i + 1, i + 1, memData, object, target);
Boolean value = false;
value = str1.toLowerCase().contains(str2.toLowerCase());
typeAry[j] = wordType.STRING;
stringList.set(j, value ? "true" : "false");
typeAry[i] = wordType.NOP;
typeAry[i + 1] = wordType.NOP;
}
}
}
// 8.数またはテキストの比較
for (int i = start; i <= end; i++) {
if (typeAry[i] == wordType.OPERATOR) {
String opr = stringList.get(i);
if (opr == "≠") {
if (i > end - 1)
throw new xTalkException("比較演算子が不正です");
String str1 = "";
int j = i - 1;
for (; j >= start; j--) {
if (typeAry[j] == wordType.STRING || typeAry[j] == wordType.X) {
str1 = Evalution(stringList, typeAry, j, j, memData, object, target);
break;
}
}
String str2 = Evalution(stringList, typeAry, i + 1, i + 1, memData, object, target);
Boolean value = false;
try {
value = Double.valueOf(str1) != Double.valueOf(str2);
} catch (Exception err) {
value = (0 != str1.compareToIgnoreCase(str2));
}
value = (0 != str1.compareToIgnoreCase(str2));
typeAry[j] = wordType.STRING;
stringList.set(j, value ? "true" : "false");
typeAry[i] = wordType.NOP;
typeAry[i + 1] = wordType.NOP;
} else if (opr == "is" && stringList.get(i + 1) == "not"
|| opr == "<" && stringList.get(i + 1) == ">") {
if (i + 1 > end - 1)
throw new xTalkException("比較演算子が不正です");
String str1 = "";
int j = i - 1;
for (; j >= start; j--) {
if (typeAry[j] == wordType.STRING || typeAry[j] == wordType.X) {
str1 = Evalution(stringList, typeAry, j, j, memData, object, target);
break;
}
}
String str2 = Evalution(stringList, typeAry, i + 2, i + 2, memData, object, target);
Boolean value = false;
try {
value = (0 != Double.compare(Double.valueOf(str1), Double.valueOf(str2)));
} catch (Exception err) {
value = (0 != str1.compareToIgnoreCase(str2));
}
typeAry[j] = wordType.STRING;
stringList.set(j, value ? "true" : "false");
typeAry[i] = wordType.NOP;
typeAry[i + 1] = wordType.NOP;
typeAry[i + 2] = wordType.NOP;
} else if (opr == "=" || opr == "is") {
if (i > end - 1)
throw new xTalkException("比較演算子が不正です");
String str1 = "";
int j = i - 1;
for (; j >= start; j--) {
if (typeAry[j] == wordType.STRING || typeAry[j] == wordType.X
|| typeAry[j] == wordType.VARIABLE) {
str1 = Evalution(stringList, typeAry, j, j, memData, object, target);
break;
}
}
String str2 = Evalution(stringList, typeAry, i + 1, i + 1, memData, object, target);
{
Boolean value = false;
try {
value = (0 == Double.compare(Double.valueOf(str1), Double.valueOf(str2)));
} catch (Exception err) {
value = (0 == str1.compareToIgnoreCase(str2));
}
typeAry[j] = wordType.STRING;
stringList.set(j, value ? "true" : "false");
typeAry[i] = wordType.NOP;
typeAry[i + 1] = wordType.NOP;
}
}
}
}
// 9.and演算子
for (int i = start; i <= end; i++) {
if (typeAry[i] == wordType.OPERATOR) {
if (stringList.get(i) == "and") {
if (i > end - 1)
throw new xTalkException("and演算子が不正です");
String str1 = "";
int j = i - 1;
for (; j >= start; j--) {
if (typeAry[j] == wordType.STRING || typeAry[j] == wordType.X) {
str1 = Evalution(stringList, typeAry, j, j, memData, object, target);
break;
}
}
String str2 = Evalution(stringList, typeAry, i + 1, i + 1, memData, object, target);
{
Boolean value1 = false;
Boolean value2 = false;
if (0 == str1.compareToIgnoreCase("true"))
value1 = true;
else if (0 == str1.compareToIgnoreCase("false"))
value1 = false;
else
throw new xTalkException("and演算には真偽値(true/false)が必要です");
if (0 == str2.compareToIgnoreCase("true"))
value2 = true;
else if (0 == str2.compareToIgnoreCase("false"))
value2 = false;
else
throw new xTalkException("and演算には真偽値(true/false)が必要です");
typeAry[j] = wordType.STRING;
stringList.set(j, (value1 && value2) ? "true" : "false");
typeAry[i] = wordType.NOP;
typeAry[i + 1] = wordType.NOP;
}
}
}
}
// 10.or演算子
for (int i = start; i <= end; i++) {
if (typeAry[i] == wordType.OPERATOR) {
if (stringList.get(i) == "or") {
if (i > end - 1)
throw new xTalkException("or演算子が不正です");
String str1 = "";
int j = i - 1;
for (; j >= start; j--) {
if (typeAry[j] == wordType.STRING || typeAry[j] == wordType.X) {
str1 = Evalution(stringList, typeAry, j, j, memData, object, target);
break;
}
}
String str2 = Evalution(stringList, typeAry, i + 1, i + 1, memData, object, target);
{
Boolean value1 = false;
Boolean value2 = false;
if (0 == str1.compareToIgnoreCase("true"))
value1 = true;
else if (0 == str1.compareToIgnoreCase("false"))
value1 = false;
else
throw new xTalkException("or演算には真偽値(true/false)が必要です");
if (0 == str2.compareToIgnoreCase("true"))
value2 = true;
else if (0 == str2.compareToIgnoreCase("false"))
value2 = false;
else
throw new xTalkException("or演算には真偽値(true/false)が必要です");
typeAry[j] = wordType.STRING;
stringList.set(j, (value1 || value2) ? "true" : "false");
typeAry[i] = wordType.NOP;
typeAry[i + 1] = wordType.NOP;
}
}
}
}
// 演算子無しで値を繋げていないか?
for (int i = start + 1; i <= end; i++) {
/*
* if(typeAry[i-1]==wordType.X && typeAry[i]==wordType.X) { throw new
* xTalkException(stringList.get(i-1)+" "+stringList.get(i)+"がわかりません"); }
*/
if (typeAry[i] != wordType.NOP) {
throw new xTalkException(stringList.get(i) + "がわかりません");
}
}
// timeIsMoney("Evalution2:",timestart,22);
if (start < typeAry.length && (typeAry[start] == wordType.STRING || typeAry[start] == wordType.X)) {
return stringList.get(start);
} else
return "";
}
static void setVariable(MemoryData memData, String name, String value) throws xTalkException {
// long timestart = System.currentTimeMillis();
/*
* if(name.equalsIgnoreCase("TIMEX")){
* System.out.println("setVariable:"+name+"="+value); }
*/
// System.out.println("setVariable:"+name+"="+value);
String str = name.toLowerCase();
if (memData.treeset.contains(str)) {
// ローカル変数に代入
for (int i = 0; i < memData.nameList.size(); i++) {
if (0 == str.compareTo(memData.nameList.get(i))) {
memData.valueList.set(i, value);
// timeIsMoney("setVariable:",timestart,23);
return;
}
}
}
if (globalData.treeset.contains(str)) {
// グローバル変数に代入
for (int i = 0; i < globalData.nameList.size(); i++) {
if (0 == str.compareTo(globalData.nameList.get(i))) {
globalData.valueList.set(i, value);
// timeIsMoney("setVariable:",timestart,23);
return;
}
}
}
// ローカル変数を宣言して代入
if (true == Character.isLetter(name.charAt(0))) {
if (true == name.matches("^[A-Za-z0-9_]*$")) {
memData.nameList.add(str);
memData.valueList.add(value);
memData.treeset.add(str);
} else
throw new xTalkException("変数名がアルファベットと数字ではありません:" + name);
} else
throw new xTalkException("変数名の頭がアルファベットではありません:" + name);
// timeIsMoney("setVariable:",timestart,23);
}
// 変数の値の取得
private static final String getVariable(MemoryData memData, String str) {
// long timestart = System.currentTimeMillis();
if (memData == null)
return null;
// String str=name.toLowerCase();
if (!memData.treeset.contains(str) && !globalData.treeset.contains(str)) {
if (str == "it") {
return "";
}
return null;
}
for (int i = 0; i < memData.nameList.size(); i++) {
if (0 == str.compareTo(memData.nameList.get(i))) {
// timeIsMoney("getVariable:",timestart,24);
return memData.valueList.get(i);
}
}
for (int i = 0; i < globalData.nameList.size(); i++) {
if (0 == str.compareTo(globalData.nameList.get(i))) {
// timeIsMoney("getVariable:",timestart,24);
return globalData.valueList.get(i);
}
}
// timeIsMoney("getVariable:",timestart,24);
return null;
}
// グローバル変数の宣言、代入
private static void setGlobalVariable(String name, String value) throws xTalkException {
String str = name.toLowerCase();
// グローバル変数に代入
if (globalData.treeset.contains(str)) {
for (int i = 0; i < globalData.nameList.size(); i++) {
if (0 == str.compareTo(globalData.nameList.get(i))) {
if (value != null)
globalData.valueList.set(i, value);
return;
}
}
}
// グローバル変数を宣言して代入
if (true == Character.isLetter(name.charAt(0))) {
if (true == name.matches("^[A-Za-z0-9_]*$")) {
globalData.nameList.add(str);
if (value != null)
globalData.valueList.add(value);
else
globalData.valueList.add("");
globalData.treeset.add(str);
} else
throw new xTalkException("変数名がアルファベットと数字ではありません:" + name);
} else
throw new xTalkException("変数名の頭がアルファベットではありません:" + name);
}
private static ObjResult getObjectfromList(ArrayList<String> stringList, wordType[] typeAry, int start,
OObject object, OObject target) throws xTalkException {
// long timestart = System.currentTimeMillis();
ObjResult objres = new ObjResult();
objres.cnt = 0;
objres.obj = null;
int next = start;
if (next >= stringList.size())
return null;// throw new xTalkException("オブジェクトが分かりません");
String str = stringList.get(next);
if (0 == str.compareToIgnoreCase("HyperCard")) {
objres.cnt = 1;
objres.obj = OHyperCard.hc;
return objres;
}
if (0 == str.compareToIgnoreCase("me")) {
objres.cnt = 1;
objres.obj = object;
return objres;
}
if (0 == str.compareToIgnoreCase("target")) {
objres.cnt = 1;
objres.obj = target;
return objres;
}
if (0 == str.compareToIgnoreCase("menubar")) {
objres.cnt = 1;
objres.obj = OMenubar.menubar;
return objres;
}
if (0 == str.compareToIgnoreCase("msg")) {
objres.cnt = 1;
objres.obj = OMsg.msg;
return objres;
}
next++;
if (next >= stringList.size())
return null;// throw new xTalkException("オブジェクトが分かりません");
String str2 = stringList.get(next);
if (0 == str.compareToIgnoreCase("the") && 0 == str2.compareToIgnoreCase("target")) {
objres.cnt = 2;
objres.obj = target;
return objres;
}
if (0 == str.compareToIgnoreCase("this")) {
if (0 == str2.compareToIgnoreCase("cd") || 0 == str2.compareToIgnoreCase("card")) {
objres.cnt = 2;
objres.obj = PCARD.pc.stack.curCard;
return objres;
}
if (0 == str2.compareToIgnoreCase("bg") || 0 == str2.compareToIgnoreCase("bkgnd")
|| 0 == str2.compareToIgnoreCase("background")) {
objres.cnt = 2;
objres.obj = PCARD.pc.stack.curCard.bg;
return objres;
}
if (0 == str2.compareToIgnoreCase("stack")) {
objres.cnt = 2;
objres.obj = PCARD.pc.stack;
return objres;
}
}
if (0 == str.compareToIgnoreCase("next")) {
if (0 == str2.compareToIgnoreCase("cd") || 0 == str2.compareToIgnoreCase("card")) {
objres.cnt = 2;
int id;
int i;
for (i = 0; i < PCARD.pc.stack.cardIdList.size(); i++) {
if (PCARD.pc.stack.curCard != null && PCARD.pc.stack.curCard.id == PCARD.pc.stack.cardIdList.get(i))
break;
}
if (i == PCARD.pc.stack.cardIdList.size())
i = 0;
else {
i++;
if (i >= PCARD.pc.stack.cardIdList.size())
i = 0;
}
id = PCARD.pc.stack.cardIdList.get(i);
objres.obj = PCARD.pc.stack.GetCardbyId(id);
return objres;
}
}
if (0 == str.compareToIgnoreCase("prev") || 0 == str.compareToIgnoreCase("previous")) {
if (0 == str2.compareToIgnoreCase("cd") || 0 == str2.compareToIgnoreCase("card")) {
objres.cnt = 2;
int id;
int i;
for (i = 0; i < PCARD.pc.stack.cardIdList.size(); i++) {
if (PCARD.pc.stack.curCard != null && PCARD.pc.stack.curCard.id == PCARD.pc.stack.cardIdList.get(i))
break;
}
if (i == 0)
i = PCARD.pc.stack.cardIdList.size() - 1;
else {
i--;
}
id = PCARD.pc.stack.cardIdList.get(i);
objres.obj = PCARD.pc.stack.GetCardbyId(id);
return objres;
}
}
if (0 == str.compareToIgnoreCase("window")) {
for (int i = 0; i < OWindow.list.size(); i++) {
if (!str2.equals("") && OWindow.list.get(i).name != null
&& OWindow.list.get(i).name.equalsIgnoreCase(str2)) {
objres.cnt = 2;
objres.obj = OWindow.list.get(i);
break;
}
}
if (str2.equalsIgnoreCase("message") || str2.equalsIgnoreCase("msg")) {
objres.cnt = 2;
objres.obj = OMsg.msg;
}
return objres;
} else if (0 == str2.compareToIgnoreCase("window")) {
if (0 == str.compareToIgnoreCase("cd") || 0 == str.compareToIgnoreCase("card")) {
objres.cnt = 2;
objres.obj = OWindow.cdwindow;
} else if (0 == str.compareToIgnoreCase("msg") || 0 == str.compareToIgnoreCase("message")) {
objres.cnt = 2;
objres.obj = OWindow.msgwindow;
}
return objres;
} else if (0 == str.compareToIgnoreCase("menu")) {
if (str2.matches("[0-9]*")) {
int i = Integer.valueOf(str2);
if (i <= PCARD.pc.getJMenuBar().getComponentCount()) {
objres.cnt = 2;
objres.obj = new OMenu((JMenu) PCARD.pc.getJMenuBar().getComponent(i));
}
return objres;
} else {
for (int i = 0; i < PCARD.pc.getJMenuBar().getComponentCount(); i++) {
JMenu menu = (JMenu) PCARD.pc.getJMenuBar().getComponent(i);
if (menu.getText().equalsIgnoreCase(str2)) {
objres.cnt = 2;
objres.obj = new OMenu(menu);
}
}
return objres;
}
} else if (0 == str.compareToIgnoreCase("folder")) {
String path = "";
path = str2.replace(':', File.separatorChar);
objres.cnt = 2;
if (new File(path).isDirectory()) {
objres.obj = new OObject();
}
return objres;
}
for (int i = start; i < stringList.size() - 1; i++) {
if (stringList.get(i).equalsIgnoreCase("first")) {
if (stringList.get(i + 1).equalsIgnoreCase("card")
|| stringList.get(i + 1).equalsIgnoreCase("background")
|| stringList.get(i + 1).equalsIgnoreCase("button")
|| stringList.get(i + 1).equalsIgnoreCase("field")) {
String s = "";
if (stringList.get(i).equalsIgnoreCase("first"))
s = "1";
stringList.set(i, stringList.get(i + 1));
stringList.set(i + 1, s);
}
}
}
// button
if (0 == str.compareToIgnoreCase("btn") || 0 == str.compareToIgnoreCase("button")
|| 0 == str2.compareToIgnoreCase("btn") || 0 == str2.compareToIgnoreCase("button")) {
boolean bg = false;
// 今いるカードではなく、オブジェクトの存在するカードが必要な場合もあるが基準が分からんpart1
OCardBase cdbase;
/*
* if(object.objectType.equals("card")) cdbase=(OCardBase)object; else
* if(object.objectType.equals("background"))
* cdbase=((OBackground)object).viewCard; else
* if(object.objectType.equals("button")) cdbase=((OButton)object).card; else
* if(object.objectType.equals("field")) cdbase=((OField)object).card; else
*/ cdbase = PCARD.pc.stack.curCard;
if (0 == str.compareToIgnoreCase("cd") || 0 == str.compareToIgnoreCase("card")) {
// cdbase=PCARD.pc.stack.curCard;
next++;
} else if (0 == str.compareToIgnoreCase("bg") || 0 == str.compareToIgnoreCase("bkgnd")
|| 0 == str.compareToIgnoreCase("background")) {
bg = true;
cdbase = PCARD.pc.stack.curCard.bg;
// cdbase=PCARD.pc.stack.curCard;
next++;
}
if (next >= stringList.size())
throw new xTalkException("ボタンが分かりません");
String str3 = stringList.get(next);
int id = 0;
int number = 0;
String name = "";
if (0 == str3.compareToIgnoreCase("id")) {
next++;
String str4 = stringList.get(next);
id = Integer.valueOf(str4);
} else {
try {
number = Integer.valueOf(str3);
} catch (Exception e) {
name = str3;
}
}
// 他のカードのオブジェクト指定
next++;
while (next < stringList.size() && typeAry[next] == wordType.NOP) {
next++;
}
if (next < stringList.size()) {
String str5 = stringList.get(next);
if (0 == str5.compareToIgnoreCase("of")) {
next++;
if (next >= stringList.size())
throw new xTalkException("オブジェクトが分かりません");
ObjResult objres2;
objres2 = getObjectfromList(stringList, typeAry, next, object, target);
next += objres2.cnt/*-1*/;
if (objres2.obj == null)
throw new xTalkException("オブジェクトが分かりません");
if (0 != objres2.obj.objectType.compareTo("card")
&& 0 != objres2.obj.objectType.compareTo("background"))
throw new xTalkException("ここにはカードまたはバックグラウンドを指定してください");
cdbase = (OCardBase) objres2.obj;
if (bg == true && 0 == cdbase.objectType.compareTo("card")) {
if (((OCard) cdbase).bg != null) {
cdbase = (OCardBase) ((OCard) cdbase).bg;
} else {
cdbase = (OCardBase) new OBackground(cdbase.stack, (OCard) cdbase, ((OCard) cdbase).bgid,
true);
}
if (cdbase == null)
throw new xTalkException("バックグラウンドがありません");
}
}
}
// cdbase.btnListからid/number/nameでさがす
if (id != 0) {
for (int i = 0; i < cdbase.btnList.size(); i++) {
if (id == cdbase.btnList.get(i).id) {
objres.cnt = next - start/* +1 */;
objres.obj = cdbase.btnList.get(i);
// System.out.println("getObjectFromList:"+(System.currentTimeMillis()-timestart));
return objres;
}
}
throw new xTalkException("id " + id + " のボタンはありません");
} else if (number != 0) {
if (number < 0)
throw new xTalkException("" + number + "番目のボタンはありません");
if (number > cdbase.btnList.size())
throw new xTalkException("" + number + "番目のボタンはありません");
objres.cnt = next - start/* +1 */;
objres.obj = cdbase.btnList.get(number - 1);
/// System.out.println("getObjectFromList:"+(System.currentTimeMillis()-timestart));
return objres;
} else {
for (int i = 0; i < cdbase.btnList.size(); i++) {
if (id == cdbase.btnList.get(i).name.compareToIgnoreCase(name)) {
objres.cnt = next - start/* +1 */;
objres.obj = cdbase.btnList.get(i);
// System.out.println("getObjectFromList:"+(System.currentTimeMillis()-timestart));
return objres;
}
}
// 例外として、カード移動した後でもmeのオブジェクトは名前で参照できる
if (object != null && object.objectType.equals("button")) {
if (bg && object.parent.objectType.equals("background")
|| !bg && object.parent.objectType.equals("card")) {
if (object.name.equalsIgnoreCase(name)) {
objres.cnt = next - start/* +1 */;
objres.obj = object;
// System.out.println("getObjectFromList:"+(System.currentTimeMillis()-timestart));
return objres;
}
}
}
if (target != null && target.objectType.equals("button")) {
if (bg && target.parent.objectType.equals("background")
|| !bg && target.parent.objectType.equals("card")) {
if (target.name.equalsIgnoreCase(name)) {
objres.cnt = next - start/* +1 */;
objres.obj = target;
// System.out.println("getObjectFromList:"+(System.currentTimeMillis()-timestart));
return objres;
}
}
}
throw new xTalkException("名前が\"" + name + "\"のボタンはありません");
}
}
// field
if (0 == str.compareToIgnoreCase("fld") || 0 == str.compareToIgnoreCase("field")
|| 0 == str2.compareToIgnoreCase("fld") || 0 == str2.compareToIgnoreCase("field")) {
boolean bg = false;
OCardBase cdbase = PCARD.pc.stack.curCard.bg;
if (0 == str.compareToIgnoreCase("cd") || 0 == str.compareToIgnoreCase("card")) {
cdbase = PCARD.pc.stack.curCard;
next++;
} else if (0 == str.compareToIgnoreCase("bg") || 0 == str.compareToIgnoreCase("bkgnd")
|| 0 == str.compareToIgnoreCase("background")) {
bg = true;
// cdbase=PCARD.pc.stack.curCard.bg;
cdbase = PCARD.pc.stack.curCard;
next++;
}
if (next >= stringList.size())
throw new xTalkException("フィールドが分かりません");
String str3 = stringList.get(next);
int id = 0;
int number = 0;
String name = "";
if (0 == str3.compareToIgnoreCase("id")) {
next++;
String str4 = stringList.get(next);
id = Integer.valueOf(str4);
} else {
try {
number = Integer.valueOf(str3);
} catch (Exception e) {
name = str3;
}
}
// 他のカードのオブジェクト指定
next++;
while (next < stringList.size() && typeAry[next] == wordType.NOP) {
next++;
}
if (next < stringList.size()) {
String str5 = stringList.get(next);
if (0 == str5.compareToIgnoreCase("of")) {
next++;
if (next >= stringList.size())
throw new xTalkException("オブジェクトが分かりません");
ObjResult objres2;
objres2 = getObjectfromList(stringList, typeAry, next, object, target);
next += objres2.cnt/*-1*/;
if (objres2.obj == null)
throw new xTalkException("オブジェクトが分かりません");
if (0 != objres2.obj.objectType.compareTo("card")
&& 0 != objres2.obj.objectType.compareTo("background"))
throw new xTalkException("ここにはカードまたはバックグラウンドを指定してください");
cdbase = (OCardBase) objres2.obj;
}
}
// cdからbgを得る(こうしないとカードごとに内容の違うフィールドの内容が取れない)
// メモリにbgを展開していなかった時代の方法
/*
* if(bg == true && 0==cdbase.objectType.compareTo("card")) {
* if(((OCard)cdbase).bg != null) { cdbase = (OCardBase) ((OCard)cdbase).bg; }
* else { cdbase = (OCardBase) new OBackground(cdbase.stack, (OCard)cdbase,
* ((OCard)cdbase).bgid, true); } if(cdbase == null) throw new
* xTalkException("バックグラウンドがありません"); }
*/
// cdからbgを得る(こうしないとカードごとに内容の違うフィールドの内容が取れない)
if (bg == true && 0 == cdbase.objectType.compareTo("card")) {
OCard ocd = (OCard) cdbase;
cdbase = ocd.getBg();
}
// cdbase.fldListからid/number/nameでさがす
if (id != 0) {
for (int i = 0; i < cdbase.fldList.size(); i++) {
if (id == cdbase.fldList.get(i).id) {
objres.cnt = next - start/* +1 */;
objres.obj = cdbase.fldList.get(i);
// System.out.println("getObjectFromList:"+(System.currentTimeMillis()-timestart));
return objres;
}
}
throw new xTalkException("id " + id + " のフィールドはありません");
} else if (number != 0) {
if (number < 0)
throw new xTalkException("" + number + "番目のフィールドはありません");
if (number > cdbase.fldList.size())
throw new xTalkException("" + number + "番目のフィールドはありません");
objres.cnt = next - start/* +1 */;
objres.obj = cdbase.fldList.get(number - 1);
// System.out.println("getObjectFromList:"+(System.currentTimeMillis()-timestart));
return objres;
} else {
for (int i = 0; i < cdbase.fldList.size(); i++) {
if (0 == cdbase.fldList.get(i).name.compareToIgnoreCase(name)) {
objres.cnt = next - start/* +1 */;
objres.obj = cdbase.fldList.get(i);
// System.out.println("getObjectFromList:"+(System.currentTimeMillis()-timestart));
return objres;
}
}
// 例外として、カード移動した後でもmeのオブジェクトは名前で参照できる
if (object != null && object.objectType.equals("field")) {
if (bg && object.parent.objectType.equals("background")
|| !bg && object.parent.objectType.equals("card")) {
if (object.name.equalsIgnoreCase(name)) {
objres.cnt = next - start/* +1 */;
objres.obj = object;
// System.out.println("getObjectFromList:"+(System.currentTimeMillis()-timestart));
return objres;
}
}
}
throw new xTalkException("名前が\"" + name + "\"のフィールドはありません");
}
}
// cd
if (0 == str.compareToIgnoreCase("cd") || 0 == str.compareToIgnoreCase("card")) {
String str3 = stringList.get(next);
int id = 0;
int number = 0;
String name = "";
if (0 == str3.compareToIgnoreCase("id")) {
next++;
String str4 = stringList.get(next);
id = Integer.valueOf(str4);
} else {
try {
number = Integer.valueOf(str3);
} catch (Exception e) {
name = str3;
}
}
// id/number/nameでさがす
if (id != 0) {
objres.cnt = next - start + 1;
objres.obj = PCARD.pc.stack.GetCardbyId(id);
if (objres.obj == null)
throw new xTalkException("idが" + id + "のカードはありません");
// System.out.println("getObjectFromList:"+(System.currentTimeMillis()-timestart));
return objres;
} else if (number != 0) {
objres.cnt = next - start + 1;
objres.obj = PCARD.pc.stack.GetCardbyNum(number);
if (objres.obj == null)
throw new xTalkException(number + "番目のカードはありません");
// System.out.println("getObjectFromList:"+(System.currentTimeMillis()-timestart));
return objres;
} else {
objres.cnt = next - start + 1;
objres.obj = PCARD.pc.stack.GetCard(name);
if (objres.obj == null)
throw new xTalkException("名前が" + name + "のカードはありません");
// System.out.println("getObjectFromList:"+(System.currentTimeMillis()-timestart));
return objres;
}
}
// String errstr="";
// for(int i=start; i<start+objres.cnt; i++){
// errstr+=stringList.get(i);
// }
// timeIsMoney("getObjectFromList:",timestart,25);
// System.out.println("objstr;"+errstr+" cnt="+objres.cnt);
return objres;
}
private static int getNumberOfChunk(String mode, String source) {
if (0 == mode.compareTo("chars") || 0 == mode.compareTo("characters")) {
return source.length();
}
if (0 == mode.compareTo("items")) {
String[] strAry = source.split(itemDelimiter);
return strAry.length;
}
if (0 == mode.compareTo("words")) { // 改行と""の括りにも対応必要
String[] strAry = source.split(" ");
return strAry.length;
}
if (0 == mode.compareTo("lines")) {
while (source.indexOf("\r") >= 0) {
int offset = 0;
if (source.length() > source.indexOf("\r") + 1 && source.charAt(source.indexOf("\r") + 1) == '\n')
offset = 1;
source = source.substring(0, source.indexOf("\r")) + "\n"
+ source.substring(source.indexOf("\r") + 1 + offset, source.length());
}
String[] strAry = source.split("\n");
return strAry.length;
}
return 0;
}
private static String getChunk(String mode, String chunkStart, String chunkEnd, String source) {
// long timestart = System.currentTimeMillis();
int start = 0;
try {
start = Integer.valueOf(chunkStart);
} catch (Exception e) {
}
int end = start;
if (chunkEnd != null)
try {
end = Integer.valueOf(chunkEnd);
} catch (Exception e) {
}
if (end < start)
return "";
if (0 == mode.compareTo("char") || 0 == mode.compareTo("character")) {
String value = "";
for (int i = start - 1; i <= end - 1; i++) {
if (i >= source.length())
break;
if (i < 0)
continue;
value += String.valueOf(source.charAt(i));
}
// System.out.println("getChunk:"+(System.currentTimeMillis()-timestart));
return value;
}
if (0 == mode.compareTo("item")) {
String value = "";
String[] strAry = source.split(itemDelimiter);
if (start - 1 < strAry.length && start >= 1)
value = strAry[start - 1];
else
return "";
for (int i = start; i <= end - 1; i++) {
if (i >= strAry.length)
break;
value += itemDelimiter + strAry[i];
}
// System.out.println("getChunk:"+(System.currentTimeMillis()-timestart));
return value;
}
if (0 == mode.compareTo("word")) { // 改行と""の括りにも対応必要
String value = "";
String[] strAry = source.split(" ");
if (start - 1 < strAry.length && start >= 1)
value = strAry[start - 1];
else
return "";
for (int i = start; i <= end - 1; i++) {
if (i >= strAry.length)
break;
value += " " + strAry[i];
}
// System.out.println("getChunk:"+(System.currentTimeMillis()-timestart));
return value;
}
if (0 == mode.compareTo("line")) {
String value = "";
while (source.indexOf("\r") >= 0) {
int offset = 0;
if (source.length() > source.indexOf("\r") + 1 && source.charAt(source.indexOf("\r") + 1) == '\n')
offset = 1;
source = source.substring(0, source.indexOf("\r")) + "\n"
+ source.substring(source.indexOf("\r") + 1 + offset, source.length());
}
String[] strAry = source.split("\n");
if (start - 1 < strAry.length && start >= 1)
value = strAry[start - 1];
else
return "";
for (int i = start; i <= end - 1; i++) {
if (i >= strAry.length)
break;
value += "\n" + strAry[i];
}
int indexof = value.indexOf("\r");
if (indexof >= 0) {
String value2 = value.substring(0, indexof);
if (value.length() > indexof)
value2 += value.substring(indexof + 1, value.length());
// System.out.println("getChunk:"+(System.currentTimeMillis()-timestart));
return value2;
} else {
// System.out.println("getChunk:"+(System.currentTimeMillis()-timestart));
return value;
}
}
// timeIsMoney("getChunk:",timestart,26);
return "";
}
private static void setChunkVariable(String mode, String chunkStart, String chunkEnd, String setstr, String name,
MemoryData memData) throws xTalkException {
// long timestart = System.currentTimeMillis();
int start = 0;
try {
start = Integer.valueOf(chunkStart);
} catch (Exception e) {
}
int end = start;
if (chunkEnd != null)
try {
end = Integer.valueOf(chunkEnd);
} catch (Exception e) {
}
String oldvalue = getVariable(memData, name);
if (oldvalue == null)
oldvalue = "";
if (end <= 0) {
// System.out.println("!");
end = 1;
}
String value = "";
if (0 == mode.compareTo("char") || 0 == mode.compareTo("character")) {
if (oldvalue.length() > 0)
value = oldvalue.substring(0, start - 1);
value += setstr;
if (oldvalue.length() > end)
value += oldvalue.substring(end);
} else {
String delimiter = " ";
if (0 == mode.compareTo("item")) {
delimiter = itemDelimiter;
}
if (0 == mode.compareTo("word")) { // 改行と""の括りにも対応必要
delimiter = " ";
}
if (0 == mode.compareTo("line")) {
while (oldvalue.indexOf("\r") >= 0) {
int offset = 0;
if (oldvalue.length() > oldvalue.indexOf("\r") + 1
&& oldvalue.charAt(oldvalue.indexOf("\r") + 1) == '\n')
offset = 1;
oldvalue = oldvalue.substring(0, oldvalue.indexOf("\r")) + "\n"
+ oldvalue.substring(oldvalue.indexOf("\r") + 1 + offset, oldvalue.length());
}
delimiter = "\n";
}
String[] strAry = oldvalue.split(delimiter);
for (int i = 0; i < start - 1; i++) {
if (i < strAry.length)
value += strAry[i] + delimiter;
else
value += delimiter;
}
value += setstr;
for (int i = end; i < strAry.length; i++) {
value += delimiter + strAry[i];
}
}
setVariable(memData, name, value);
// timeIsMoney("setChunkVariable:",timestart,27);
}
private static void setChunkVariable2(String mode, String chunkStart, String chunkEnd, String mode2,
String chunkStart2, String chunkEnd2, String setstr, String name, MemoryData memData)
throws xTalkException {
// long timestart = System.currentTimeMillis();
int start = 0;
try {
start = Integer.valueOf(chunkStart);
} catch (Exception e) {
}
int end = start;
if (chunkEnd != null)
try {
end = Integer.valueOf(chunkEnd);
} catch (Exception e) {
}
int start2 = 0;
try {
start2 = Integer.valueOf(chunkStart2);
} catch (Exception e) {
}
int end2 = start2;
if (chunkEnd != null)
try {
end2 = Integer.valueOf(chunkEnd);
} catch (Exception e) {
}
String oldvalue = getVariable(memData, name);
if (oldvalue == null)
oldvalue = "";
String delimiter2 = " ";
if (0 == mode2.compareTo("item")) {
delimiter2 = itemDelimiter;
}
if (0 == mode2.compareTo("word")) { // 改行と""の括りにも対応必要
delimiter2 = " ";
}
if (0 == mode2.compareTo("line")) {
while (oldvalue.indexOf("\r") >= 0) {
int offset = 0;
if (oldvalue.length() > oldvalue.indexOf("\r") + 1
&& oldvalue.charAt(oldvalue.indexOf("\r") + 1) == '\n')
offset = 1;
oldvalue = oldvalue.substring(0, oldvalue.indexOf("\r")) + "\n"
+ oldvalue.substring(oldvalue.indexOf("\r") + 1 + offset, oldvalue.length());
}
delimiter2 = "\n";
}
String[] strAry2 = oldvalue.split(delimiter2);
String value = "";
for (int i = 0; i < start2 - 1; i++) {
if (i < strAry2.length)
value += strAry2[i] + delimiter2;
else
value += delimiter2;
}
String text2 = "";
if (start2 - 1 >= 0 && start2 - 1 < strAry2.length)
text2 = strAry2[start2 - 1];
if (0 == mode.compareTo("char") || 0 == mode.compareTo("character")) {
if (start - 1 > 0 && end >= 0)
value += text2.substring(0, start - 1) + setstr + text2.substring(end);
else
value += text2.substring(0, 0) + setstr + text2.substring(0);
} else {
String delimiter = " ";
if (0 == mode.compareTo("item")) {
delimiter = itemDelimiter;
}
if (0 == mode.compareTo("word")) { // 改行と""の括りにも対応必要
delimiter = " ";
}
if (0 == mode.compareTo("line")) {
delimiter = "\n";
}
String[] strAry = text2.split(delimiter);
for (int i = 0; i < start - 1; i++) {
if (i < strAry.length)
value += strAry[i] + delimiter;
else
value += delimiter;
}
value += setstr;
for (int i = end; i < strAry.length; i++) {
value += delimiter + strAry[i];
}
}
for (int i = end2; i < strAry2.length; i++) {
value += delimiter2 + strAry2[i];
}
setVariable(memData, name, value);
// timeIsMoney("setChunkVariable2:",timestart,28);
}
private static void setChunkObject(String mode, String chunkStart, String chunkEnd, String setstr, OObject obj) {
int start = 0;
// long timestart = System.currentTimeMillis();
try {
start = Integer.valueOf(chunkStart);
} catch (Exception e) {
}
int end = start;
if (chunkEnd != null)
try {
end = Integer.valueOf(chunkEnd);
} catch (Exception e) {
}
OButton btn = null;
OField fld = null;
String text = "";
if (0 == obj.objectType.compareTo("button")) {
btn = (OButton) obj;
text = btn.getText();
} else if (0 == obj.objectType.compareTo("field")) {
fld = (OField) obj;
text = fld.getText();
} else
return;
String value = "";
if (0 == mode.compareTo("char") || 0 == mode.compareTo("character")) {
value = text.substring(0, start - 1) + setstr + text.substring(end);
} else {
String delimiter = " ";
if (0 == mode.compareTo("item")) {
delimiter = itemDelimiter;
}
if (0 == mode.compareTo("word")) { // 改行と""の括りにも対応必要
delimiter = " ";
}
if (0 == mode.compareTo("line")) {
while (text.indexOf("\r") >= 0) {
int offset = 0;
if (text.length() > text.indexOf("\r") + 1 && text.charAt(text.indexOf("\r") + 1) == '\n')
offset = 1;
text = text.substring(0, text.indexOf("\r")) + "\n"
+ text.substring(text.indexOf("\r") + 1 + offset, text.length());
}
delimiter = "\n";
}
String[] strAry = text.split(delimiter);
for (int i = 0; i < start - 1; i++) {
if (i < strAry.length)
value += strAry[i] + delimiter;
else
value += delimiter;
}
value += setstr;
for (int i = end; i < strAry.length; i++) {
value += delimiter + strAry[i];
}
}
if (btn != null) {
btn.setText(value);
} else if (fld != null) {
fld.setText(value);
}
// timeIsMoney("setChunkVariable2:",timestart,29);
}
private static void setChunkObject2(String mode, String chunkStart, String chunkEnd, String mode2,
String chunkStart2, String chunkEnd2, String setstr, OObject obj) {
int start = 0;
// long timestart = System.currentTimeMillis();
try {
start = Integer.valueOf(chunkStart);
} catch (Exception e) {
}
int end = start;
if (chunkEnd != null)
try {
end = Integer.valueOf(chunkEnd);
} catch (Exception e) {
}
int start2 = 0;
try {
start2 = Integer.valueOf(chunkStart2);
} catch (Exception e) {
}
int end2 = start2;
if (chunkEnd != null)
try {
end2 = Integer.valueOf(chunkEnd);
} catch (Exception e) {
}
OButton btn = null;
OField fld = null;
String text = "";
if (0 == obj.objectType.compareTo("button")) {
btn = (OButton) obj;
text = btn.getText();
} else if (0 == obj.objectType.compareTo("field")) {
fld = (OField) obj;
text = fld.getText();
} else
return;
String delimiter2 = " ";
if (0 == mode2.compareTo("item")) {
delimiter2 = itemDelimiter;
}
if (0 == mode2.compareTo("word")) { // 改行と""の括りにも対応必要
delimiter2 = " ";
}
if (0 == mode2.compareTo("line")) {
while (text.indexOf("\r") >= 0) {
int offset = 0;
if (text.length() > text.indexOf("\r") + 1 && text.charAt(text.indexOf("\r") + 1) == '\n')
offset = 1;
text = text.substring(0, text.indexOf("\r")) + "\n"
+ text.substring(text.indexOf("\r") + 1 + offset, text.length());
}
delimiter2 = "\n";
}
String[] strAry2 = text.split(delimiter2);
String value = "";
for (int i = 0; i < start2 - 1; i++) {
if (i < strAry2.length)
value += strAry2[i] + delimiter2;
else
value += delimiter2;
}
String text2 = "";
if (start2 - 1 >= 0 && start2 - 1 < strAry2.length)
text2 = strAry2[start2 - 1];
if (0 == mode.compareTo("char") || 0 == mode.compareTo("character")) {
value += text2.substring(0, start - 1) + setstr + text2.substring(end);
} else {
String delimiter = " ";
if (0 == mode.compareTo("item")) {
delimiter = itemDelimiter;
}
if (0 == mode.compareTo("word")) { // 改行と""の括りにも対応必要
delimiter = " ";
}
if (0 == mode.compareTo("line")) {
delimiter = "\n";
}
String[] strAry = text2.split(delimiter);
for (int i = 0; i < start - 1; i++) {
if (i < strAry.length)
value += strAry[i] + delimiter;
else
value += delimiter;
}
value += setstr;
for (int i = end; i < strAry.length; i++) {
value += delimiter + strAry[i];
}
}
for (int i = end2; i < strAry2.length; i++) {
value += delimiter2 + strAry2[i];
}
if (btn != null) {
btn.setText(value);
} else if (fld != null) {
fld.setText(value);
}
// timeIsMoney("setChunkObject2:",timestart,30);
}
private static OObject getObject(ArrayList<String> stringList, wordType[] typeAry, int start, int end,
MemoryData memData, OObject object, OObject target) throws xTalkException {
// long timestart = System.currentTimeMillis();
OObject obj = null;
StringBuilder errStr = new StringBuilder(48);
for (int i = start; i <= end; i++) {
if (typeAry[i] == wordType.STRING)
errStr.append("\"");
errStr.append(stringList.get(i));
if (typeAry[i] == wordType.STRING)
errStr.append("\"");
errStr.append(" ");
}
// System.out.println("getObject"+errStr);
int next = start;
if (next >= stringList.size())
return null;
if (0 == stringList.get(next).compareToIgnoreCase("me")) {
obj = object;
// next++;
} else if (0 == stringList.get(next).compareToIgnoreCase("target")) {
obj = target;
// next++;
} else if (0 == stringList.get(next).compareToIgnoreCase("titlebar")) {
obj = OTitlebar.titlebar;
// next++;
} else if (0 == stringList.get(next).compareToIgnoreCase("menubar")) {
obj = OMenubar.menubar;
// next++;
} else if (0 == stringList.get(next).compareToIgnoreCase("tool") && next + 1 <= end
&& 0 == stringList.get(next + 1).compareToIgnoreCase("window")) {
obj = OToolWindow.toolwindow;
// next++;
} else if ((0 == stringList.get(next).compareToIgnoreCase("cd")
|| 0 == stringList.get(next).compareToIgnoreCase("card")) && next + 1 <= end
&& 0 == stringList.get(next + 1).compareToIgnoreCase("window")) {
obj = OWindow.cdwindow;
// next++;
} else if (0 == stringList.get(next).compareToIgnoreCase("msg")
|| 0 == stringList.get(next).compareToIgnoreCase("message")) {
obj = OMsg.msg;
// next++;
} else if (0 == stringList.get(next).compareToIgnoreCase("the") && next + 1 <= end
&& 0 == stringList.get(next + 1).compareToIgnoreCase("target")) {
obj = target;
next++;// next+=2;
} else if (0 == stringList.get(next).compareToIgnoreCase("window")) {
String str = Evalution(stringList, typeAry, next + 1, end, memData, object, target);
for (int i = 0; i < OWindow.list.size(); i++) {
if (!str.equals("") && str.equalsIgnoreCase(OWindow.list.get(i).name)) {
obj = OWindow.list.get(i);
next++;
}
}
if (obj == null && str.equalsIgnoreCase("message")) {
obj = OMsg.msg;
}
} else if (0 == stringList.get(next).compareToIgnoreCase("menu")) {
int j;
for (j = next + 1; j <= end; j++) {
if (stringList.get(j).equalsIgnoreCase("with")) {
break;
}
}
j--;
String str = Evalution(stringList, typeAry, next + 1, j, memData, object, target);
for (int i = 0; i < PCARD.pc.menu.mb.getComponentCount(); i++) {
Component c = PCARD.pc.menu.mb.getComponent(i);
if (c.getClass() == JMenu.class) {
JMenu menu = (JMenu) c;
if (str.equalsIgnoreCase(menu.getText())
|| str.equalsIgnoreCase(PCARD.pc.intl.getEngText(menu.getText()))) {
obj = new OMenu(menu);
break;
}
}
}
} else if ((0 == stringList.get(next).compareToIgnoreCase("cd")
|| 0 == stringList.get(next).compareToIgnoreCase("card")) && next + 1 <= end
&& 0 == stringList.get(next + 1).compareToIgnoreCase("picture")) {
obj = PCARD.pc.stack.curCard.picture;
next++;// next+=2;
} else if ((0 == stringList.get(next).compareToIgnoreCase("bg")
|| 0 == stringList.get(next).compareToIgnoreCase("bkgnd")
|| 0 == stringList.get(next).compareToIgnoreCase("background")) && next + 1 <= end
&& 0 == stringList.get(next + 1).compareToIgnoreCase("picture")) {
obj = PCARD.pc.stack.curCard.bg.picture;
next++;// next+=2;
} else if (0 == stringList.get(next).compareToIgnoreCase("picture") && next + 1 <= end
&& 0 == stringList.get(next + 1).compareToIgnoreCase("of") && next + 2 <= end) {
ObjResult result = getObjectfromList(stringList, typeAry, next + 2, object, target);
if (result != null) {
if (result.obj.objectType.equals("card") || result.obj.objectType.equals("background")) {
obj = ((OCardBase) result.obj).picture;
next++;// next+=2;
next += result.cnt;
}
}
} else if (0 == stringList.get(next).compareToIgnoreCase("this")) {
next++;
if (next > end)
throw new xTalkException("オブジェクト" + errStr + " が分かりません");
if (0 == stringList.get(next).compareToIgnoreCase("card")
|| 0 == stringList.get(next).compareToIgnoreCase("cd")) {
obj = PCARD.pc.stack.curCard;
next++;
} else if (0 == stringList.get(next).compareToIgnoreCase("background")
|| 0 == stringList.get(next).compareToIgnoreCase("bkgnd")
|| 0 == stringList.get(next).compareToIgnoreCase("bg")) {
obj = PCARD.pc.stack.curCard.bg;
next++;
} else if (0 == stringList.get(next).compareToIgnoreCase("stack")) {
obj = PCARD.pc.stack;
next++;
}
} else if (0 == stringList.get(next).compareToIgnoreCase("next")) {
next++;
if (next > end)
throw new xTalkException("オブジェクト" + errStr + " が分かりません");
if (0 == stringList.get(next).compareToIgnoreCase("card")
|| 0 == stringList.get(next).compareToIgnoreCase("cd")) {
int id;
int i;
for (i = 0; i < PCARD.pc.stack.cardIdList.size(); i++) {
if (PCARD.pc.stack.curCard != null && PCARD.pc.stack.curCard.id == PCARD.pc.stack.cardIdList.get(i))
break;
}
if (i == PCARD.pc.stack.cardIdList.size())
i = 0;
else {
i++;
if (i >= PCARD.pc.stack.cardIdList.size())
i = 0;
}
id = PCARD.pc.stack.cardIdList.get(i);
obj = PCARD.pc.stack.GetCardbyId(id);
next++;
}
} else if (0 == stringList.get(next).compareToIgnoreCase("last")) {
next++;
if (next > end)
throw new xTalkException("オブジェクト" + errStr + " が分かりません");
if (0 == stringList.get(next).compareToIgnoreCase("card")
|| 0 == stringList.get(next).compareToIgnoreCase("cd")) {
obj = PCARD.pc.stack.GetCardbyNum(PCARD.pc.stack.cardIdList.size());
next++;
}
} else if (stringList.size() - start >= 2) {
// 今いるカードではなく、オブジェクトの存在するカードが必要な場合もあるが基準は?見つからないとき?
OCardBase cdbase;
/*
* if(object.objectType.equals("card")) cdbase=(OCardBase)object; else
* if(object.objectType.equals("background"))
* cdbase=((OBackground)object).viewCard; else
* if(object.objectType.equals("button")) cdbase=((OButton)object).card; else
* if(object.objectType.equals("field")) cdbase=((OField)object).card; else
*/ cdbase = PCARD.pc.stack.curCard;
boolean bg_flag = false;
// boolean cdbg_flag = false;//カードとBGの両方を探す
int flag = 0; // 1がボタン、2がフィールド
for (int i = next; i <= end; i++) {
// 括弧
if (typeAry[i] == wordType.LBRACKET) {
int nest = 0;
for (int j = i + 1; j <= end; j++) {
if (typeAry[j] == wordType.RBRACKET || typeAry[j] == wordType.RFUNC) {
if (nest == 0) {
Evalution(stringList, typeAry, i, j, memData, object, target);
for (int k = i; k <= j; k++) {
if (typeAry[k] == wordType.NOP)
stringList.set(k, "");
}
break;
}
nest--;
}
if (typeAry[j] == wordType.LBRACKET || typeAry[j] == wordType.LFUNC) {
nest++;
}
}
}
}
for (int i = next; i <= end; i++) {
// 他のカードの場合
if (0 == stringList.get(i).compareToIgnoreCase("of") && (!stringList.get(i - 1).matches("[0-9]*")
|| i - 2 >= start && !stringList.get(i - 2).equalsIgnoreCase("char")
&& !stringList.get(i - 2).equalsIgnoreCase("item")
&& !stringList.get(i - 2).equalsIgnoreCase("line")
&& !stringList.get(i - 2).equalsIgnoreCase("word")
&& !stringList.get(i - 2).equalsIgnoreCase("character"))) {
if (i + 1 > end) {
throw new xTalkException("オブジェクト" + errStr + " が分かりません");
}
// if(0==stringList.get(i+1).compareToIgnoreCase("this")){
// if(i+2>end) throw new xTalkException("オブジェクト"+errStr+" が分かりません");
if (0 == stringList.get(i + 1).compareToIgnoreCase("card")
|| 0 == stringList.get(i + 1).compareToIgnoreCase("cd")) {
if (i + 2 <= end && 0 == stringList.get(i + 2).compareToIgnoreCase("id")) {
if (i + 3 > end)
throw new xTalkException("オブジェクト" + errStr + " が分かりません");
int j;
for (j = i + 3; j < end; j++) {
if (0 == stringList.get(j).compareToIgnoreCase("of")) {
j--;
break;
}
}
String str = Evalution(stringList, typeAry, i + 3, j, memData, object, target);
try {
cdbase = PCARD.pc.stack.GetCardbyId(Integer.valueOf(str));
} catch (Exception err) {
throw new xTalkException("オブジェクト" + errStr + " が分かりません");
}
;
} else {
int j;
for (j = i + 2; j < end; j++) {
if (0 == stringList.get(j).compareToIgnoreCase("of")) {
j--;
break;
}
}
String str = Evalution(stringList, typeAry, i + 2, j, memData, object, target);
try {
cdbase = PCARD.pc.stack.GetCardbyNum(Integer.valueOf(str));
} catch (Exception err) {
cdbase = PCARD.pc.stack.GetCard(str);
}
}
if (cdbase != null) {
end = i - 1;
break;
} else
throw new xTalkException("オブジェクト" + errStr + " が分かりません");
} else if (0 == stringList.get(i + 1).compareToIgnoreCase("background")
|| 0 == stringList.get(i + 1).compareToIgnoreCase("bkgnd")
|| 0 == stringList.get(i + 1).compareToIgnoreCase("bg")) {
if (i + 2 <= end && 0 == stringList.get(i + 2).compareToIgnoreCase("id")) {
if (i + 3 > end)
throw new xTalkException("オブジェクト" + errStr + " が分かりません");
int j;
for (j = i + 3; j < end; j++) {
if (0 == stringList.get(j).compareToIgnoreCase("of")) {
j--;
break;
}
}
String str = Evalution(stringList, typeAry, i + 3, j, memData, object, target);
try {
cdbase = PCARD.pc.stack.GetBackgroundbyId(Integer.valueOf(str));
} catch (Exception err) {
throw new xTalkException("オブジェクト" + errStr + " が分かりません");
}
;
} else {
int j;
for (j = i + 2; j < end; j++) {
if (0 == stringList.get(j).compareToIgnoreCase("of")) {
j--;
break;
}
}
String str = Evalution(stringList, typeAry, i + 2, j, memData, object, target);
try {
cdbase = PCARD.pc.stack.GetBackgroundbyNum(Integer.valueOf(str));
} catch (Exception err) {
cdbase = PCARD.pc.stack.GetBackground(str);
}
}
if (cdbase != null) {
end = i - 1;
break;
} else
throw new xTalkException("オブジェクト" + errStr + " が分かりません");
} else
throw new xTalkException("オブジェクト" + errStr + " が分かりません");
// }
}
}
// Cardにあるオブジェクト
if (0 == stringList.get(next).compareToIgnoreCase("cd")
|| 0 == stringList.get(next).compareToIgnoreCase("card")
|| (0 != stringList.get(next).compareToIgnoreCase("bg")
&& 0 != stringList.get(next).compareToIgnoreCase("bkgnd")
&& 0 != stringList.get(next).compareToIgnoreCase("background"))) {
if (0 == stringList.get(next).compareToIgnoreCase("cd")
|| 0 == stringList.get(next).compareToIgnoreCase("card")) {
next++;
} else if (0 == stringList.get(next).compareToIgnoreCase("btn")
|| 0 == stringList.get(next).compareToIgnoreCase("button")) {
// cdbg_flag = true;
} else if (0 == stringList.get(next).compareToIgnoreCase("fld")
|| 0 == stringList.get(next).compareToIgnoreCase("field")) {
// cdbg_flag = true;
bg_flag = true;
} else {
return null;// オブジェクトではない
}
if (next > end)
throw new xTalkException("オブジェクト" + errStr + " が分かりません");
if (typeAry[next] != wordType.STRING && (0 == stringList.get(next).compareToIgnoreCase("button")
|| 0 == stringList.get(next).compareToIgnoreCase("btn"))) {
flag = 1;
next++;
} else if (typeAry[next] != wordType.STRING && (0 == stringList.get(next).compareToIgnoreCase("field")
|| 0 == stringList.get(next).compareToIgnoreCase("fld"))) {
flag = 2;
next++;
} else {
// Cardそのもの
if (0 == stringList.get(next).compareToIgnoreCase("id")) {
next++;
if (next > end)
throw new xTalkException("オブジェクト" + errStr + " が分かりません");
int j;
for (j = next; j < end; j++) {
if (0 == stringList.get(j).compareToIgnoreCase("of")
&& (!stringList.get(j - 1).matches("[0-9]*")))
break;
}
String str = Evalution(stringList, typeAry, next, j, memData, object, target);
try {
obj = PCARD.pc.stack.GetCardbyId(Integer.valueOf(str));
} catch (Exception err) {
throw new xTalkException("オブジェクト" + errStr + " が分かりません");
}
;
} else {
int j;
for (j = next; j < end; j++) {
if (0 == stringList.get(j).compareToIgnoreCase("of")
&& (!stringList.get(j - 1).matches("[0-9]{1,99}"))) {
j--;
break;
}
}
String str = Evalution(stringList, typeAry, next, j, memData, object, target);
if (cdbase != null && cdbase.objectType.equals("background"))
obj = PCARD.pc.stack.GetCardofBg(cdbase, str);
else
obj = PCARD.pc.stack.GetCard(str);
if (obj == null) {
try {
if (cdbase != null && cdbase.objectType.equals("background"))
obj = PCARD.pc.stack.GetCardofBgbyNum(cdbase, Integer.valueOf(str));
else
obj = PCARD.pc.stack.GetCardbyNum(Integer.valueOf(str));
} catch (Exception err) {
}
}
}
}
}
// Bgにあるオブジェクト
if (next <= end && (0 == stringList.get(next).compareToIgnoreCase("bg")
|| 0 == stringList.get(next).compareToIgnoreCase("bkgnd")
|| 0 == stringList.get(next).compareToIgnoreCase("background"))) {
bg_flag = true;
next++;
if (next > end)
throw new xTalkException("オブジェクト" + errStr + " が分かりません");
if (0 == stringList.get(next).compareToIgnoreCase("button")
|| 0 == stringList.get(next).compareToIgnoreCase("btn")) {
flag = 1;
// cdbase = PCARD.pc.stack.curCard.bg;
next++;
} else if (0 == stringList.get(next).compareToIgnoreCase("field")
|| 0 == stringList.get(next).compareToIgnoreCase("fld")) {
flag = 2;
// cdbase = PCARD.pc.stack.curCard.bg;
next++;
} else {
// Bgそのもの
if (0 == stringList.get(next).compareToIgnoreCase("id")) {
next++;
if (next > end)
throw new xTalkException("オブジェクト" + errStr + " が分かりません");
int j;
for (j = next; j < end; j++) {
if (0 == stringList.get(j).compareToIgnoreCase("of")
&& (!stringList.get(j - 1).matches("[0-9]*")))
break;
}
String str = Evalution(stringList, typeAry, next, j, memData, object, target);
try {
obj = PCARD.pc.stack.GetBackgroundbyId(Integer.valueOf(str));
} catch (Exception err) {
throw new xTalkException("オブジェクト" + errStr + " が分かりません");
}
;
} else {
int j;
for (j = next; j < end; j++) {
if (0 == stringList.get(j).compareToIgnoreCase("of")
&& (!stringList.get(j - 1).matches("[0-9]*")))
break;
}
String str = Evalution(stringList, typeAry, next, j, memData, object, target);
try {
obj = PCARD.pc.stack.GetBackgroundbyNum(Integer.valueOf(str));
} catch (Exception err) {
obj = PCARD.pc.stack.GetBackground(str);
}
}
}
}
if (obj == null && flag == 1) {
// btn
if (next > end)
throw new xTalkException("オブジェクト" + errStr + " が分かりません");
if (0 == stringList.get(next).compareToIgnoreCase("id")) {
next++;
if (next > end)
throw new xTalkException("オブジェクト" + errStr + " が分かりません");
int j;
for (j = next; j < end; j++) {
if (0 == stringList.get(j).compareToIgnoreCase("of")
&& (!stringList.get(j - 1).matches("[0-9]*"))) {
j--;
break;
}
}
String str = Evalution(stringList, typeAry, next, j, memData, object, target);
// System.out.println("* "+str);
try {
if (!bg_flag)
obj = cdbase.GetBtnbyId(Integer.valueOf(str));
else
obj = cdbase.GetBgBtnbyId(Integer.valueOf(str));
} catch (Exception err) {
throw new xTalkException("オブジェクト" + errStr + " が分かりません");
}
;
} else {
int j;
for (j = next; j < end; j++) {
if (0 == stringList.get(j).compareToIgnoreCase("of")
&& (!stringList.get(j - 1).matches("[0-9]*"))) {
j--;
break;
}
}
String str = Evalution(stringList, typeAry, next, j, memData, object, target);
try {
if (!bg_flag)
obj = cdbase.GetBtnbyNum(Integer.valueOf(str));
else
obj = cdbase.GetBgBtnbyNum(Integer.valueOf(str));
} catch (Exception err) {
if (!bg_flag) {
obj = cdbase.GetBtn(str);
/*
* if(obj==null && cdbg_flag){
* cdbase=PCARD.pc.stack.GetBackgroundbyId(((OCard)cdbase).bgid);
* obj=cdbase.GetBtn(str); }
*/
} else
obj = cdbase.GetBgBtn(str);
}
if (obj == null) {
if (object.objectType.equals("button")
&& (bg_flag && object.parent.objectType.equals("background"))
|| (!bg_flag && object.parent.objectType.equals("card"))) {
if (object.name.equalsIgnoreCase(str)) {
obj = object;
}
}
}
if (obj == null && target != null) {
if (target.objectType.equals("button")
&& (bg_flag && target.parent.objectType.equals("background"))
|| (!bg_flag && target.parent.objectType.equals("card"))) {
if (target.name.equalsIgnoreCase(str)) {
obj = target;
}
}
}
}
}
if (obj == null && flag == 2) {
// fld
if (next > end)
throw new xTalkException("オブジェクト" + errStr + " が分かりません");
if (0 == stringList.get(next).compareToIgnoreCase("id")) {
next++;
if (next > end)
throw new xTalkException("オブジェクト" + errStr + " が分かりません");
int j;
for (j = next; j < end; j++) {
if (0 == stringList.get(j).compareToIgnoreCase("of")
&& (!stringList.get(j - 1).matches("[0-9]*"))) {
j--;
break;
}
}
String str = Evalution(stringList, typeAry, next, j, memData, object, target);
try {
if (!bg_flag)
obj = cdbase.GetFldbyId(Integer.valueOf(str));
else
obj = cdbase.GetBgFldbyId(Integer.valueOf(str));
} catch (Exception err) {
throw new xTalkException("オブジェクト" + errStr + " が分かりません");
}
;
} else {
int j;
for (j = next; j < end; j++) {
if (0 == stringList.get(j).compareToIgnoreCase("of")
&& ((!stringList.get(j - 1).matches("[0-9]*")) || j - 1 == next)) {
j--;
break;
}
}
String str = Evalution(stringList, typeAry, next, j, memData, object, target);
try {
if (!bg_flag)
obj = cdbase.GetFldbyNum(Integer.valueOf(str));
else
obj = cdbase.GetBgFldbyNum(Integer.valueOf(str));
} catch (Exception err) {
if (!bg_flag)
obj = cdbase.GetFld(str);
else
obj = cdbase.GetBgFld(str);
}
}
}
}
// timeIsMoney("getObject:",timestart,31);
if (next != end && obj == null) {
throw new xTalkException("オブジェクト" + errStr + "が分かりません");
}
return obj;
}
static timeClass[] timeList = new timeClass[32];
final static void timeIsMoney(String name, long start, int index) {
long time = System.currentTimeMillis() - start;
if (timeList[index] == null) {
timeList[index] = new timeClass();
timeList[index].name = "";
timeList[index].time = 0;
}
if (timeList[index].name.equals(name) || timeList[index].name.length() == 0) {
timeList[index].time += time;
return;
}
}
}
class timeClass {
long time;
String name;
}
|
snaerth/article-keeper | shared/components/logger/actions.js | <reponame>snaerth/article-keeper<filename>shared/components/logger/actions.js
import axios from 'axios';
import {
GET_LOGS_SUCCESS,
GET_LOGS_ERROR,
DELETE_LOGS_SUCCESS,
DELETE_LOGS_ERROR,
IS_FETCHING,
IS_NOT_FETCHING,
} from './types';
import { authError } from '../../common/actions';
/**
* Is fetching data state
*
* @params {String} orientation vertical or horizontal
* @returns {Object}
*/
export function isFetchingData() {
return { type: IS_FETCHING };
}
/**
* Is not fetching data state
*
* @returns {Object}
*/
export function isNotFetchingData() {
return { type: IS_NOT_FETCHING };
}
/**
* Gets logs from api
*
* @param {Object} obj - An object
* @param {String} obj.token - Token string for authentication
* @param {String} obj.queryString - Query string
*/
export function getLogs({ token, queryString }) {
return async (dispatch) => {
try {
const url = `/api/logs?${queryString}`;
const config = {
headers: {
authorization: token,
},
};
const res = await axios.get(url, config);
// Dispatch GET_LOGS_SUCCESS action to logReducer
dispatch({ type: GET_LOGS_SUCCESS, payload: res.data });
} catch (error) {
dispatch(authError(GET_LOGS_ERROR, error));
}
};
}
/**
* Gets logs from api by search query
*
* @param {Object} obj - An object
* @param {String} obj.token - Token string for authentication
* @param {String} obj.queryString - Query string
*/
export function getLogsBySearchQuery({ token, queryString }) {
return async (dispatch) => {
try {
const url = `/api/logs/${queryString}`;
const config = {
headers: {
authorization: token,
},
};
const res = await axios.get(url, config);
// Dispatch GET_LOGS_SUCCESS action to logReducer
dispatch({ type: GET_LOGS_SUCCESS, payload: res.data });
} catch (error) {
dispatch(authError(GET_LOGS_ERROR, error));
}
};
}
/**
* Delete single log by id
*
* @param {String} token
* @param {String} id
*/
export function deleteLogById(token, id) {
return async (dispatch) => {
try {
const url = `/api/logs/${id}`;
const config = {
headers: {
authorization: token,
},
};
const res = await axios.delete(url, config);
// Dispatch GET_LOGS_SUCCESS action to logReducer
dispatch({ type: DELETE_LOGS_SUCCESS, payload: res.data });
} catch (error) {
dispatch(authError(DELETE_LOGS_ERROR, error));
}
};
}
|
phil65/PrettyQt | prettyqt/location/placeeditorial.py | <gh_stars>1-10
from __future__ import annotations
from prettyqt import location
from prettyqt.qt import QtLocation
QtLocation.QPlaceEditorial.__bases__ = (location.PlaceContent,)
class PlaceEditorial(QtLocation.QPlaceEditorial):
def __str__(self):
return f"{self.title()}: {self.text()}"
if __name__ == "__main__":
editorial = PlaceEditorial()
|
Pi-Laboratory/akademik-frontend | src/pages/Lecturer.PresensiNilai/index.js | import PresensiNilaiDetail from "pages/Lecturer.PresensiNilai.Detail";
import PresensiNilaiList from "pages/Lecturer.PresensiNilai.List";
import { Navigation } from "pages/Root/hoc";
import { Helmet } from "react-helmet";
import { useRouteMatch } from "react-router";
import { Layout } from "./Layout";
const navigation = [
{
"component": PresensiNilaiList,
"path": "/",
"hide": true,
"exact": true,
},
{
"component": PresensiNilaiDetail,
"path": "/jadwal/:subject_lecturer_id",
"hide": true,
"exact": true,
}
]
const PresensiNilai = () => {
const { path } = useRouteMatch();
return (
<Navigation base={path} navigation={navigation}>
<Helmet>
<title>Presensi - Nilai</title>
</Helmet>
<Layout />
</Navigation>
)
}
export default PresensiNilai; |
thexa4/Spades | max2/gamestate.py | import random
import numpy as np
import tensorflow as tf
class GameState:
def __init__(self, model, training=False, temperature=1):
self.bid_state = {'bids': {}, 'hand': [], 'bags': []}
self.chosen_bid = None
self.seen = [0] * 52
self.rounds = [None] * 13
self.chosen_cards = [None] * 13
self.tricks = [0] * 4
self.hand = [0] * 52
self.orig_bids = None
self.samples = []
self.model = model
self.training = training
self.temperature = temperature
def thermometer(self, size, n):
result = [0] * size
for i in range(n):
result[i] = 1
return result
def sample(self, options):
if not self.training:
return np.argmax(options)
positive_options = (np.array(options) + 200.0) / 400.0
exponentized = np.exp(positive_options / self.temperature)
exp_sum = np.sum(exponentized)
probabilities = exponentized / exp_sum
return np.random.choice(len(probabilities), p=probabilities)
def bid(self, hand, bids, score):
bidcount = [15,15,15,15]
for i in range(4):
if i in bids:
b = bids[i]
if b == 'N':
bidcount[i] = 0
elif b == 'B':
bidcount[i] = 14
else:
bidcount[i] = b
self.bid_state['bids'] = [self.thermometer(15, bidcount[i]) for i in range(4)]
self.bid_state['bags'] = [[0] * 10 for i in range(2)]
self.bid_state['bags'][0][score[0] % 10] = 1
self.bid_state['bags'][1][score[1] % 10] = 1
self.bid_state['hand'] = [0] * 52
for card in hand:
self.bid_state['hand'][int(card)] = 1
self.seen[int(card)] = 1
self.hand[int(card)] = 1
prediction = self.compute()
max_bid = 13
if 2 in bids:
if bids[2] != 'N' and bids[2] != 'B':
max_bid = 13 - bids[2]
allowed_bids = prediction['bids'][:(max_bid + 1)]
self.chosen_bid = self.sample(allowed_bids)
return self.chosen_bid
def store_bids(self, bids):
self.orig_bids = [0,0,0,0]
bidcount = [15,15,15,15]
for i in range(4):
if i in bids:
b = bids[i]
if b == 'N':
bidcount[i] = 0
elif b == 'B':
bidcount[i] = 14
else:
bidcount[i] = b
self.orig_bids[i] = b
self.bid_state['bids'] = [self.thermometer(15, bidcount[i]) for i in range(4)]
def play(self, round, trick, valid_cards):
played_cards = [[0] * 52 for i in range(3)]
for player in trick.cards:
self.seen[int(trick.cards[player])] = 1
played_cards[player - 1][int(trick.cards[player])] = 1
todo = [[0] * 26 for i in range(4)]
for i in range(4):
delta = self.orig_bids[i] - self.tricks[i]
if delta < 0:
for j in range(-delta + 1):
todo[i][25 - j] = 1
elif delta > 0:
for j in range(delta + 1):
todo[i][j] = 1
r = {
'seen': [0] * 52,
'hand': self.hand.copy(),
'played': played_cards,
'todo': todo,
}
self.rounds[round] = r
if len(valid_cards) == 1:
self.chosen_cards[round] = int(valid_cards[0])
return valid_cards[0]
prediction = self.compute()
allowed_preds = [prediction['round' + str(round)][int(card)] for card in valid_cards]
chosen = valid_cards[self.sample(allowed_preds)]
self.chosen_cards[round] = int(chosen)
return chosen
def store_trick(self, trick):
for player in trick.cards:
self.seen[int(trick.cards[player])] = 1
self.tricks[trick.get_winner()] += 1
def empty_round(self):
return {
'seen': [0] * 52,
'hand': [0] * 52,
'played': [[0] * 52 for i in range(3)],
'todo': [[0] * 26 for i in range(4)],
}
def input(self):
rounds = [None] * 13
for i in range(13):
if self.rounds[i] == None:
rounds[i] = self.empty_round()
else:
rounds[i] = self.rounds[i]
result = {
'bid_state_bids': np.array(self.bid_state['bids']).flatten(),
'bid_state_hand': self.bid_state['hand'],
'bid_state_bags': np.array(self.bid_state['bags']).flatten(),
}
for i in range(13):
roundname = 'round' + str(i) + '_'
result[roundname + 'seen'] = rounds[i]['seen']
result[roundname + 'hand'] = rounds[i]['hand']
result[roundname + 'played'] = np.array(rounds[i]['played']).flatten()
result[roundname + 'todo'] = np.array(rounds[i]['todo']).flatten()
return result
def compute(self):
if self.model == None:
return {
'bids': [random.uniform(0, 100) for i in range(14)],
'round0': [random.uniform(0, 100) for i in range(52)],
'round1': [random.uniform(0, 100) for i in range(52)],
'round2': [random.uniform(0, 100) for i in range(52)],
'round3': [random.uniform(0, 100) for i in range(52)],
'round4': [random.uniform(0, 100) for i in range(52)],
'round5': [random.uniform(0, 100) for i in range(52)],
'round6': [random.uniform(0, 100) for i in range(52)],
'round7': [random.uniform(0, 100) for i in range(52)],
'round8': [random.uniform(0, 100) for i in range(52)],
'round9': [random.uniform(0, 100) for i in range(52)],
'round10': [random.uniform(0, 100) for i in range(52)],
'round11': [random.uniform(0, 100) for i in range(52)],
'round12': [random.uniform(0, 100) for i in range(52)],
}
inputs = self.input()
params = {}
for k in inputs.keys():
v = inputs[k]
params[k] = np.expand_dims(v, 0).astype(np.float32)
prediction = self.model(**params)
return {
'bids': prediction['lambda'][0, :],
'round0': prediction['lambda_1'][0,0,:],
'round1': prediction['lambda_1'][0,1,:],
'round2': prediction['lambda_1'][0,2,:],
'round3': prediction['lambda_1'][0,3,:],
'round4': prediction['lambda_1'][0,4,:],
'round5': prediction['lambda_1'][0,5,:],
'round6': prediction['lambda_1'][0,6,:],
'round7': prediction['lambda_1'][0,7,:],
'round8': prediction['lambda_1'][0,8,:],
'round9': prediction['lambda_1'][0,9,:],
'round10': prediction['lambda_1'][0,10,:],
'round11': prediction['lambda_1'][0,11,:],
'round12': prediction['lambda_1'][0,12,:]
}
def training_data(self):
result = self.input()
result['chosen_bid'] = [self.chosen_bid]
for i in range(13):
roundname = 'round' + str(i) + '_'
result[roundname + 'card'] = np.array([self.chosen_cards[i]])
return result
def store_game(self, score):
return {
'training': self.training_data(),
'score': {
'bid_result': np.array([score]),
'rounds_result': [score] * 13,
}
} |
neverware-mirrors/tast-tests | src/chromiumos/tast/local/bundles/cros/camera/decode_accel_jpeg_perf.go | // Copyright 2018 The Chromium OS 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 camera
import (
"bufio"
"context"
"fmt"
"os"
"path/filepath"
"regexp"
"strconv"
"time"
"chromiumos/tast/common/perf"
"chromiumos/tast/ctxutil"
"chromiumos/tast/errors"
"chromiumos/tast/local/chrome"
"chromiumos/tast/local/gtest"
"chromiumos/tast/local/media/caps"
"chromiumos/tast/local/media/cpu"
"chromiumos/tast/local/sysutil"
"chromiumos/tast/local/upstart"
"chromiumos/tast/testing"
)
func init() {
testing.AddTest(&testing.Test{
Func: DecodeAccelJPEGPerf,
Desc: "Measures jpeg_decode_accelerator_unittest performance",
Contacts: []string{"<EMAIL>", "<EMAIL>"},
Attr: []string{"group:crosbolt", "crosbolt_perbuild"},
SoftwareDeps: []string{"chrome", caps.HWDecodeJPEG},
Data: []string{decodeAccelJpegPerfTestFile},
// The default timeout is not long enough for the unittest to finish. Set the
// timeout to 8m so the decode latency could be up to 20ms:
// 20 ms * 10000 times * 2 runs (SW,HW) + 1 min (CPU idle time) < 8 min.
Timeout: 8 * time.Minute,
})
}
const decodeAccelJpegPerfTestFile = "peach_pi-1280x720.jpg"
// DecodeAccelJPEGPerf measures SW/HW jpeg decode performance by running the
// PerfSW and PerfJDA tests in the jpeg_decode_accelerator_unittest.
// TODO(dstaessens@) Currently the performance tests decode JPEGs as fast as
// possible. But this means a performant HW decoder might actually increase
// CPU usage, as the CPU becomes the bottleneck.
func DecodeAccelJPEGPerf(ctx context.Context, s *testing.State) {
const (
// Duration of the interval during which CPU usage will be measured.
measureDuration = 10 * time.Second
// GTest filter used to run SW JPEG decode tests.
swFilter = "MjpegDecodeAcceleratorTest.PerfSW"
// GTest filter used to run HW JPEG decode tests.
hwFilter = "All/MjpegDecodeAcceleratorTest.PerfJDA/DMABUF"
// Number of JPEG decodes, needs to be high enough to run for measurement duration.
perfJPEGDecodeTimes = 10000
// time reserved for cleanup.
cleanupTime = 5 * time.Second
)
testDir := filepath.Dir(s.DataPath(decodeAccelJpegPerfTestFile))
// Stop the UI job. While this isn't required to run the test binary, it's
// possible a previous tests left tabs open or an animation is playing,
// influencing our performance results.
if err := upstart.StopJob(ctx, "ui"); err != nil {
s.Fatal("Failed to stop ui: ", err)
}
defer upstart.EnsureJobRunning(ctx, "ui")
cleanUpBenchmark, err := cpu.SetUpBenchmark(ctx)
if err != nil {
s.Fatal("Failed to set up benchmark mode: ", err)
}
defer cleanUpBenchmark(ctx)
// Reserve time for cleanup and restarting the ui job at the end of the test.
ctx, cancel := ctxutil.Shorten(ctx, cleanupTime)
defer cancel()
if err := cpu.WaitUntilIdle(ctx); err != nil {
s.Fatal("Failed to wait for CPU to become idle: ", err)
}
s.Log("Measuring SW JPEG decode performance")
cpuUsageSW, decodeLatencySW := runJPEGPerfBenchmark(ctx, s, testDir,
measureDuration, perfJPEGDecodeTimes, swFilter)
s.Log("Measuring HW JPEG decode performance")
cpuUsageHW, decodeLatencyHW := runJPEGPerfBenchmark(ctx, s, testDir,
measureDuration, perfJPEGDecodeTimes, hwFilter)
p := perf.NewValues()
p.Set(perf.Metric{
Name: "sw_jpeg_decode_cpu",
Unit: "percent",
Direction: perf.SmallerIsBetter,
}, cpuUsageSW)
p.Set(perf.Metric{
Name: "hw_jpeg_decode_cpu",
Unit: "percent",
Direction: perf.SmallerIsBetter,
}, cpuUsageHW)
p.Set(perf.Metric{
Name: "sw_jpeg_decode_latency",
Unit: "milliseconds",
Direction: perf.SmallerIsBetter,
}, decodeLatencySW.Seconds()*1000)
p.Set(perf.Metric{
Name: "hw_jpeg_decode_latency",
Unit: "milliseconds",
Direction: perf.SmallerIsBetter,
}, decodeLatencyHW.Seconds()*1000)
p.Save(s.OutDir())
}
// runJPEGPerfBenchmark runs the JPEG decode accelerator unittest binary, and
// returns the measured CPU usage percentage and decode latency.
func runJPEGPerfBenchmark(ctx context.Context, s *testing.State, testDir string,
measureDuration time.Duration, perfJPEGDecodeTimes int, filter string) (float64, time.Duration) {
// Measures CPU usage while running the unittest, and waits for the unittest
// process to finish for the complete logs.
const exec = "jpeg_decode_accelerator_unittest"
logPath := fmt.Sprintf("%s/%s.%s.log", s.OutDir(), exec, filter)
measurements, err := cpu.MeasureProcessUsage(ctx, measureDuration, cpu.WaitProcess,
gtest.New(
filepath.Join(chrome.BinTestDir, exec),
gtest.Logfile(logPath),
gtest.Filter(filter),
gtest.ExtraArgs(
"--perf_decode_times="+strconv.Itoa(perfJPEGDecodeTimes),
"--test_data_path="+testDir+"/",
"--jpeg_filenames="+decodeAccelJpegPerfTestFile),
gtest.UID(int(sysutil.ChronosUID)),
))
if err != nil {
s.Fatalf("Failed to measure CPU usage %v: %v", exec, err)
}
cpuUsage := measurements["cpu"]
// Parse the log file for the decode latency measured by the unittest.
decodeLatency, err := parseJPEGDecodeLog(logPath, s.OutDir())
if err != nil {
s.Fatal("Failed to parse test log: ", err)
}
// Check the total decoding time is longer than the measure duration. If not,
// the measured CPU usage is inaccurate and we should fail this test.
if decodeLatency*time.Duration(perfJPEGDecodeTimes) < measureDuration {
s.Fatal("Decoder did not run long enough for measuring CPU usage")
}
return cpuUsage, decodeLatency
}
// parseJPEGDecodeLog parses the log file created by the JPEG decode accelerator
// unitttest and returns the averaged decode latency.
func parseJPEGDecodeLog(logPath, outputDir string) (time.Duration, error) {
file, err := os.Open(logPath)
if err != nil {
return 0.0, errors.Wrap(err, "couldn't open log file")
}
defer file.Close()
// The log format printed from unittest looks like:
// [...] 27.5416 s for 10000 iterations (avg: 0.002754 s) ...
pattern := regexp.MustCompile(`\(avg: (\d+(?:\.\d*)?) s\)`)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
match := pattern.FindStringSubmatch(scanner.Text())
if len(match) != 2 {
continue
}
decodeLatency, err := strconv.ParseFloat(match[1], 64)
if err != nil {
return 0.0, errors.Wrapf(err, "failed to parse decode latency: %v", match[1])
}
return time.Duration(decodeLatency * float64(time.Second)), nil
}
return 0.0, errors.New("couldn't find decode latency in log file")
}
|
FastNinja/seek-style-guide | react/CriticalIcon/CriticalIcon.js | <reponame>FastNinja/seek-style-guide<gh_stars>100-1000
import svgMarkup from './CriticalIcon.svg';
import React from 'react';
import Icon from '../private/Icon/Icon';
export default function CriticalIcon(props) {
return <Icon markup={svgMarkup} {...props} />;
}
CriticalIcon.displayName = 'CriticalIcon';
|
obtusebanana/upfire | app/containers/Wallet/components/PromptCreateWallet/index.js | <reponame>obtusebanana/upfire<gh_stars>1-10
import React from 'react';
import trans from '../../../../translations';
import { PopAction, Row, RowCenter } from '../../../../components/prompt/style';
import UInput from '../../../../components/InputText';
import SecondaryButton from '../../../../components/Buttons/SecondaryBtn';
export class PromptCreateWallet extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
showConfirmation: false,
password: '',
valid: true,
validationText: '',
passwordValid: true,
passwordErrorText: ''
};
this.handlerResult = this.handlerResult.bind(this);
this.handlerInputPassword = this.handlerInputPassword.bind(this);
}
componentWillMount() {
const {show, passwordValid} = this.props;
this.setState({
showConfirmation: show,
passwordValid
});
}
componentWillReceiveProps(newProps) {
const {
show,
validationText = '',
valid = true,
passwordValid = true
} = newProps;
this.setState({
showConfirmation: show,
valid,
validationText,
passwordValid
});
}
handlerInputPassword(e) {
if (e.target.validity.valid) {
this.setState({invalid: true, password: e.target.value});
}
}
handlerResult() {
const {onClick} = this.props;
const {password} = this.state;
let errors = false;
if (password === '') {
this.setState({
passwordValid: false,
passwordErrorText: trans('Prompt.value.PasswordNotCorrect')
});
errors = true;
} else if (password.length < 6) {
this.setState({
passwordValid: false,
passwordErrorText: trans('Prompt.value.PasswordIsShort')
});
errors = true;
}
if (!errors) {
onClick(password);
}
}
render() {
const {password, passwordValid, passwordErrorText} = this.state;
return (
<div>
<RowCenter>
<UInput
value={password}
onChange={(e) => this.handlerInputPassword(e)}
label={trans('Prompt.value.createPassword')}
type="password"
name="password"
error={!passwordValid ? passwordErrorText : null}
centerContent
/>
</RowCenter>
<Row>
<PopAction>
<SecondaryButton
onClick={() => this.handlerResult()}
title={trans('wallet.createNewWallet')}
/>
</PopAction>
</Row>
</div>
);
}
}
|
jaredmichaelwilliams/homebrew-cask | Casks/fishapp.rb | <filename>Casks/fishapp.rb
cask 'fishapp' do
version '2.2.0'
sha256 'e07d30687eff3a66f17384e3d870f42e4eea722f24f8e742c69b2d5f4f3ce61d'
url "http://fishshell.com/files/#{version}/fish.app.zip"
name 'Fish App'
homepage 'http://fishshell.com'
license :gpl
app 'fish.app'
end
|
CharaD7/azure-sdk-for-python | azure-batch/azure/batch/models/pool_evaluate_auto_scale_parameter.py | <reponame>CharaD7/azure-sdk-for-python
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class PoolEvaluateAutoScaleParameter(Model):
"""Parameters for a CloudJobOperations.EvaluateAutoScale request.
:param auto_scale_formula: A formula for the desired number of compute
nodes in the pool.
:type auto_scale_formula: str
"""
_validation = {
'auto_scale_formula': {'required': True},
}
_attribute_map = {
'auto_scale_formula': {'key': 'autoScaleFormula', 'type': 'str'},
}
def __init__(self, auto_scale_formula):
self.auto_scale_formula = auto_scale_formula
|
jstokes/secure-data-service | sli/acceptance-tests/test/features/security/step_definitions/write_validation_steps.rb | <filename>sli/acceptance-tests/test/features/security/step_definitions/write_validation_steps.rb
=begin
Copyright 2012-2013 inBloom, Inc. and its affiliates.
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.
=end
require 'rest-client'
require 'json'
require 'builder'
require 'rexml/document'
require 'uri'
include REXML
require_relative '../../utils/sli_utils.rb'
require_relative '../../apiV1/utils/api_utils.rb'
###############################################################################
# GIVEN GIVEN GIVEN GIVEN GIVEN GIVEN GIVEN GIVEN GIVEN GIVEN GIVEN GIVEN GIVEN
###############################################################################
Given /^a valid entity json document for a "([^"]*)"$/ do |arg1|
@entityData = {
"gradingPeriod" => {
"gradingPeriodIdentity" => {
"educationalOrgIdentity" => [{
"stateOrganizationId" => "Daybreak Elementary School",
}],
"stateOrganizationId" => "Daybreak Elementary School",
"gradingPeriod" => "First Six Weeks",
"schoolYear" => "2011-2012"
},
"beginDate" => "2012-07-01",
"endDate" => "2012-07-31",
"totalInstructionalDays" => 20
},
"userAccount" => {
"userName" => "<EMAIL>",
"firstName" => "Bob",
"lastName" => "Roberts",
"validated" => false,
"environment" => "Sandbox"
},
"attendance" => {
"entityType" => "attendance",
"studentId" => "0c2756fd-6a30-4010-af79-488d6ef2735a_id",
"schoolId" => "6756e2b9-aba1-4336-80b8-4a5dde3c63fe",
"schoolYearAttendance" => [{
"schoolYear" => "2010-2011",
"attendanceEvent" => [{
"date" => "2010-09-16",
"event" => "Tardy"
}]
}]
},
"studentAcademicRecord" => {
"studentId" => "61161008-2560-480d-aadf-4b0264dc2ae3_id",
"sessionId" => "d23ebfc4-5192-4e6c-a52b-81cee2319072"
},
"student" => {
"birthData" => {
"birthDate" => "1994-04-04"
},
"sex" => "Male",
"studentUniqueStateId" => "123456",
"economicDisadvantaged" => false,
"name" => {
"firstName" => "Mister",
"middleName" => "John",
"lastSurname" => "Doe"
}
},
"cohort" => {
"cohortIdentifier" => "ACC-TEST-COH-4",
"cohortDescription" => "ultimate frisbee team",
"cohortType" => "Extracurricular Activity",
"cohortScope" => "Statewide",
"academicSubject" => "Physical, Health, and Safety Education",
"educationOrgId" => "92d6d5a0-852c-45f4-907a-912752831772"
},
"course" => {
"courseTitle" => "Chinese 1",
"numberOfParts" => 1,
"courseCode" => [{
"ID" => "C1",
"identificationSystem" => "School course code",
"assigningOrganizationCode" => "Bob's Code Generator"
}],
"courseLevel" => "Basic or remedial",
"courseLevelCharacteristics" => ["Advanced Placement"],
"gradesOffered" => ["Eighth grade"],
"subjectArea" => "Foreign Language and Literature",
"courseDescription" => "Intro to Chinese",
"dateCourseAdopted" => "2001-01-01",
"highSchoolCourseRequirement" => false,
"courseDefinedBy" => "LEA",
"minimumAvailableCredit" => {
"credit" => 1.0
},
"maximumAvailableCredit" => {
"credit" => 1.0
},
"careerPathway" => "Hospitality and Tourism",
"schoolId" => "6756e2b9-aba1-4336-80b8-4a5dde3c63fe",
"uniqueCourseId" => "Chinese-1-10"
},
"courseOffering" => {
"schoolId" => "92d6d5a0-852c-45f4-907a-912752831772",
"localCourseCode" => "LCCMA1",
"sessionId" => "4d796afd-b1ac-4f16-9e0d-6db47d445b55",
"localCourseTitle" => "Math 1 - Intro to Mathematics",
"courseId" => "9bd92e8e-df8e-4af9-95e7-2efed847d03d"
},
"disciplineAction" => {
"disciplineActionIdentifier" => "Discipline act XXX",
"disciplines" => [[
{"codeValue" => "Discp Act 3"},
{"shortDescription" => "Disciplinary Action 3"},
{"description" => "Long disciplinary Action 3"}
]],
"disciplineDate" => "2012-01-28",
"disciplineIncidentId" => ["0e26de79-7efa-5e67-9201-5113ad50a03b"],
"studentId" => ["61161008-2560-480d-aadf-4b0264dc2ae3_id"],
"responsibilitySchoolId" => "6756e2b9-aba1-4336-80b8-4a5dde3c63fe",
"assignmentSchoolId" => "6756e2b9-aba1-4336-80b8-4a5dde3c63fe"
},
"disciplineIncident" => {
"incidentIdentifier" => "Incident ID XXX",
"incidentDate" => "2012-02-14",
"incidentTime" => "01:00:00",
"incidentLocation" => "On School",
"behaviors" => [[
{"shortDescription" => "Behavior 012 description"},
{"codeValue" => "BEHAVIOR 012"}
]],
"schoolId" => "6756e2b9-aba1-4336-80b8-4a5dde3c63fe"
},
"educationOrganization" => {
"organizationCategories" => ["State Education Agency"],
"stateOrganizationId" => "SomeUniqueSchoolDistrict-2422883",
"nameOfInstitution" => "Gotham City School District",
"address" => [
"streetNumberName" => "111 Ave C",
"city" => "Chicago",
"stateAbbreviation" => "IL",
"postalCode" => "10098",
"nameOfCounty" => "Wake"
]
},
"gradebookEntry" => {
"gradebookEntryType" => "Quiz",
"dateAssigned" => "2012-02-14",
"sectionId" => "15ab6363-5509-470c-8b59-4f289c224107_id"
},
"learningObjective" => {
"academicSubject" => "Mathematics",
"objective" => "Learn Mathematics",
"objectiveGradeLevel" => "Fifth grade"
},
"learningStandard" => {
"learningStandardId" => {
"identificationCode" => "apiTestLearningStandard"},
"description" => "a description",
"gradeLevel" => "Ninth grade",
"contentStandard"=>"State Standard",
"subjectArea" => "English"
},
"program" => {
"programId" => "ACC-TEST-PROG-3",
"programType" => "Remedial Education",
"programSponsor" => "Local Education Agency",
"services" => [[
{"codeValue" => "codeValue3"},
{"shortDescription" => "Short description for acceptance test program 3"},
{"description" => "This is a longer description of the services provided by acceptance test program 3. More detail could be provided here."}]]
},
"section" => {
"uniqueSectionCode" => "SpanishB09",
"sequenceOfCourse" => 1,
"educationalEnvironment" => "Off-school center",
"mediumOfInstruction" => "Independent study",
"populationServed" => "Regular Students",
"schoolId" => "6756e2b9-aba1-4336-80b8-4a5dde3c63fe",
"sessionId" => "d23ebfc4-5192-4e6c-a52b-81cee2319072",
"courseOfferingId" => "00291269-33e0-415e-a0a4-833f0ef38189",
"assessmentReferences" => ["c757f9f2dc788924ce0715334c7e86735c5e1327_id"]
},
"session" => {
"sessionName" => "<NAME>",
"schoolYear" => "2011-2012",
"term" => "Spring Semester",
"beginDate" => "2012-01-01",
"endDate" => "2012-06-30",
"totalInstructionalDays" => 80,
"gradingPeriodReference" => ["b40a7eb5-dd74-4666-a5b9-5c3f4425f130"],
"schoolId" => "6756e2b9-aba1-4336-80b8-4a5dde3c63fe"
},
"staff" => {
"staffUniqueStateId" => "EMPLOYEE123456789",
"sex" => "Male",
"hispanicLatinoEthnicity" => false,
"highestLevelOfEducationCompleted" => "Bachelor's",
"name" => {
"firstName" => "Teaches",
"middleName" => "D.",
"lastSurname" => "Students"
}
},
"studentGradebookEntry" => {
"gradebookEntryId" => "15ab6363-5509-470c-8b59-4f289c224107_id483354633760fa56c9da15510e36ba79691743e4_id",
"studentId" => "bf88acdb-71f9-4c19-8de8-2cdc698936fe_id",
"sectionId" => "15ab6363-5509-470c-8b59-4f289c224107_id",
"dateFulfilled" => "2012-01-31",
"letterGradeEarned" => "A",
"numericGradeEarned" => 98,
"diagnosticStatement" => "Finished the quiz in 5 minutes",
"studentSectionAssociationId" => "15ab6363-5509-470c-8b59-4f289c224107_id066345e8-2633-474d-9088-7b3828bf873a_id"
},
"assessment" => {
"assessmentTitle" => "Writing Advanced Placement Test",
"assessmentIdentificationCode" => [{
"identificationSystem" => "School",
"ID" => "01234B"
}],
"academicSubject" => "Mathematics",
"assessmentCategory" => "Achievement test",
"gradeLevelAssessed" => "Adult Education",
"contentStandard" => "LEA Standard",
"version" => 2
},
"parent" => {
"parentUniqueStateId" => "ParentID101",
"name" =>
{ "firstName" => "John",
"lastSurname" => "Doe",
}
},
"school" => {
"shortNameOfInstitution" => "SCTS",
"nameOfInstitution" => "School Crud Test School",
"webSite" => "www.scts.edu",
"stateOrganizationId" => "SomeUniqueSchool-24242342",
"organizationCategories" => ["School"],
"address" => [
"addressType" => "Physical",
"streetNumberName" => "123 Main Street",
"city" => "Lebanon",
"stateAbbreviation" => "KS",
"postalCode" => "66952",
"nameOfCounty" => "Smith County"
],
"gradesOffered" => [
"Kindergarten",
"First grade",
"Second grade",
"Third grade",
"Fourth grade",
"Fifth grade"
]
},
"teacher" => {
"birthDate" => "1954-08-31",
"sex" => "Male",
"yearsOfPriorTeachingExperience" => 32,
"staffUniqueStateId" => "12345678",
"highlyQualifiedTeacher" => true,
"highestLevelOfEducationCompleted" => "Master's",
"name" => {
"firstName" => "Rafe",
"middleName" => "Hairfire",
"lastSurname" => "Esquith"
}
},
"grade" => {
"studentSectionAssociationId" => "9b02fbd2-0892-4399-a4ea-e048b3315f25_id00cbf81b-41df-4bda-99ad-a5717d3e81a1_id",
"letterGradeEarned" => "B+",
"gradeType" => "Final"
},
"studentCompetency" => {
"competencyLevel" => {
"description" => "really hard competency"
},
"objectiveId" => {
"learningObjectiveId" => "dd9165f2-65be-6d27-a8ac-bdc5f46757b6"
},
"diagnosticStatement" => "passed with flying colors",
"studentSectionAssociationId" => "9b02fbd2-0892-4399-a4ea-e048b3315f25_id00cbf81b-41df-4bda-99ad-a5717d3e81a1_id"
},
"reportCard" => {
"grades" => ["ef42e2a2-9942-11e1-a8a9-68a86d21d918"],
"studentCompetencyId" => ["3a2ea9f8-9acf-11e1-add5-68a86d83461b"],
"gpaGivenGradingPeriod" => 3.14,
"gpaCumulative" => 2.9,
"numberOfDaysAbsent" => 15,
"numberOfDaysInAttendance" => 150,
"numberOfDaysTardy" => 10,
"studentId" => "0f0d9bac-0081-4900-af7c-d17915e02378_id",
"gradingPeriodId" => "ef72b883-90fa-40fa-afc2-4cb1ae17623b"
},
"graduationPlan" => {
"creditsBySubject" => [{
"subjectArea" => "English",
"credits" => {
"creditConversion" => 0,
"creditType" => "Semester hour credit",
"credit" => 6
}
}],
"individualPlan" => false,
"graduationPlanType" => "Minimum",
"educationOrganizationId" => "6756e2b9-aba1-4336-80b8-4a5dde3c63fe",
"totalCreditsRequired" => {
"creditConversion" => 0,
"creditType" => "Semester hour credit",
"credit" => 32
}
},
"competencyLevelDescriptor" => {
"description" => "Herman tends to throw tantrums",
"codeValue" => "Temper Tantrum",
"performanceBaseConversion" => "Basic"
},
"studentCompetencyObjective" => {
"objectiveGradeLevel" => "Kindergarten",
"objective" => "Phonemic Awareness",
"studentCompetencyObjectiveId" => "SCO-K-1",
"educationOrganizationId" => "ec2e4218-6483-4e9c-8954-0aecccfd4731"
},
"studentProgramAssociation" => {
"studentId" => "0f0d9bac-0081-4900-af7c-d17915e02378_id",
"programId" => "9b8cafdc-8fd5-11e1-86ec-0021701f543f_id",
"beginDate" => "2011-05-01",
"educationOrganizationId" => "6756e2b9-aba1-4336-80b8-4a5dde3c63fe"
},
"studentSectionAssociation" => {
"studentId" => "0f0d9bac-0081-4900-af7c-d17915e02378_id",
"sectionId" => "15ab6363-5509-470c-8b59-4f289c224107_id",
"beginDate" => "2012-05-01"
},
"studentSchoolAssociation" => {
"studentId" => "0f0d9bac-0081-4900-af7c-d17915e02378_id",
"schoolId" => "6756e2b9-aba1-4336-80b8-4a5dde3c63fe",
"entryDate" => "2012-01-01",
"entryGradeLevel" => "Kindergarten"
},
"courseTranscript" => {
"courseAttemptResult" => "Pass",
"creditsEarned" => {"credit" => 3.0},
"courseId" => "9bd92e8e-df8e-4af9-95e7-2efed847d03d",
"gradeType" => "Final",
"studentAcademicRecordId" => "7a70c01bf8d93d9b1f53ab45080777b0b49794fa_id56afc8d4-6c91-48f9-8a11-de527c1131b7",
"educationOrganizationReference" => ["92d6d5a0-852c-45f4-907a-912752831772"]
}
}
@fields = @entityData[arg1]
@type = arg1
end
#line 342, graduationplan
#invalid- "educationOrganizationId" => "b1bd3db6-d020-4651-b1b8-a8dba688d9e1",
#valid+ "educationOrganizationId" => "6756e2b9-aba1-4336-80b8-4a5dde3c63fe",
Then /^I should receive a new entity URI$/ do
step "I should receive an ID for the newly created entity"
assert(@newId != nil, "After POST, URI is nil")
end
When /^the entities referenced or associated edorg is out of my context$/ do
case @type
when "attendance" then @fields["schoolId"] = "b1bd3db6-d020-4651-b1b8-a8dba688d9e1"
when "cohort" then @fields["educationOrgId"] = "eb3b8c35-f582-df23-e406-6947249a19f2"
when "course" then @fields["schoolId"] = "eb3b8c35-f582-df23-e406-6947249a19f2"
when "courseOffering" then @fields["schoolId"] = "67ce204b-9999-4a11-aaab-000000000008"
when "disciplineAction" then @fields["responsibilitySchoolId"] = "67ce204b-9999-4a11-aaab-000000000008"
when "disciplineIncident" then @fields["schoolId"] = "67ce204b-9999-4a11-aaab-000000000008"
when "gradebookEntry" then @fields["sectionId"] = "17a8658c-6fcb-4ece-99d1-b2dea1afd987_id"
when "graduationPlan" then @fields["educationOrganizationId"] = "b1bd3db6-d020-4651-b1b8-a8dba688d9e1"
when "section" then @fields["schoolId"] = "eb3b8c35-f582-df23-e406-6947249a19f2"
when "session" then @fields["schoolId"] = "17a8658c-6fcb-4ece-99d1-b2dea1afd987_id"
when "studentGradebookEntry" then @fields["sectionId"] = "17a8658c-6fcb-4ece-99d1-b2dea1afd987_id"
when "studentProgramAssociation" then @fields["educationOrganizationId"] = "eb3b8c35-f582-df23-e406-6947249a19f2"
when "studentSectionAssociation" then @fields["sectionId"] = "17a8658c-6fcb-4ece-99d1-b2dea1afd987_id"
when "studentSchoolAssociation" then @fields["schoolId"] = "67ce204b-9999-4a11-aaab-000000000008"
when "courseTranscript" then @fields["courseId"] = "5c7aa39b-3193-4865-a10f-5e1e3c7dc7ea"
end
end
When /^I try to update the previously created entity with an invalid reference$/ do
step "the entities referenced or associated edorg is out of my context"
step "I navigate to PUT \"/v1/#@entityUri/#@newId\""
end
When /^I post the entity$/ do
step "I navigate to POST \"/v1/#@entityUri\""
end
When /^I try to delete an entity that is out of my write context$/ do
nop = false
case @type
when "attendance" then id = "4beb72d4-0f76-4071-92b4-61982dba7b7a"
when "cohort" then id = "7e9915ed-ea6f-4e6b-b8b0-aeae20a25826_id"
when "course" then id = "5c7aa39b-3193-4865-a10f-5e1e3c7dc7ea"
when "courseOffering" then id = "119ecc01-d1ea-473d-bafd-51382158800e"
when "courseTranscript" then id = "09eced61-edd9-4826-a7bc-137ffecda877"
when "disciplineAction" then id = "db7f1d4b-9689-b2f4-9281-d88d65999423"
when "disciplineIncident" then id = "0e26de79-22ea-5d67-9201-5113ad50a03b"
when "gradebookEntry" then nop = true
when "graduationPlan" then id = "04e3a07a-a95f-4ac8-88f3-gradplan1115"
when "section" then id = "8ed12459-eae5-49bc-8b6b-6ebe1a56384f_id"
when "session" then id = "c2b11399-1519-44b7-848d-085f268170d2"
when "studentGradebookEntry" then id = "7f05ef51-c974-4071-b91b-f644f9b087cf"
when "studentProgramAssociation" then nop = true
when "studentSectionAssociation" then id = "8ed12459-eae5-49bc-8b6b-6ebe1a56384f_ide4bbd30f-6e98-4798-a200-5a71fd658fe6_id"
when "studentSchoolAssociation" then id = "7c6f61e8-3716-4648-8860-170b62a8f460"
end
step "I navigate to DELETE \"/v1/#@entityUri/#{id}\"" unless nop
end
|
fouadsan/ims-soft | ims_soft/purchases/views.py | from django.forms import models
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse, HttpResponse
from django.views import View
from xhtml2pdf import context
from django.urls import reverse_lazy
from .models import Purchase
from .forms import PurchaseForm, CreatePurchaseForm, ProductFormSet
from .resources import PurchaseResource
from products.models import Product
from purchases.models import ProductAttribute
from .utils import render_to_pdf, get_status
from stock.utils import get_barcode
def new_purchase(request):
purchases = Purchase.objects.all()
form = CreatePurchaseForm(request.POST or None)
formset = ProductFormSet(request.POST or None)
if request.method == 'POST':
formset = ProductFormSet(request.POST)
if form.is_valid() & formset.is_valid():
instance = form.save(commit=False)
instance.created_by = request.user
instance.save()
products = formset.cleaned_data
for product in products:
qs = Product.objects.get(name=product['products'])
prodattr = ProductAttribute.objects.filter(pk=qs.id)
if prodattr:
prodattr.update(quantity=prodattr.first().quantity + int(product['quantity']))
return redirect(reverse_lazy("purchases:pdf-view"))
context = {
'purchases': purchases,
'section_title': 'Purchases',
'title': 'New-Purchase',
'formset': formset,
'form': form
}
return render(request, 'purchases/new_purchase.html', context)
# class PurchaseAddView(TemplateView):
# template_name = "purchases/new_purchase.html"
# # Define method to handle GET request
# def get(self, *args, **kwargs):
# # Create an instance of the formset
# formset = PurchaseFormSet(queryset=Purchase.objects.none())
# return self.render_to_response({'purchase_formset': formset})
# # Define method to handle POST request
# def post(self, request, *args, **kwargs):
# user = request.user
# formset = PurchaseFormSet(data=self.request.POST)
# # Check if submitted forms are valid
# if formset.is_valid():
# instance = formset.save(commit=False)
# instance.created_by = user
# print(instance)
# formset.save()
# return redirect(reverse_lazy("purchases:purchase-history"))
# return self.render_to_response({'purchase_formset': formset})
def purchases_list(request):
form = PurchaseForm(request.POST or None)
context = {
'section_title': 'Purchases',
'title': 'Purchase History',
'form': form
}
return render(request, 'purchases/purchase_history.html', context)
@login_required
def load_purchases(request, num):
if request.is_ajax():
visible = 5
upper = num
lower = upper - visible
size = Purchase.objects.all().count()
qs = Purchase.objects.all()
data = []
for obj in qs:
get_status(obj)
item = {
'id': obj.id,
'supplier': obj.supplier.name,
'created_at': obj.created_at,
'status': obj.status,
'grand_total': obj.grand_total,
'payment': obj.payment,
'created_by': obj.created_by.username,
}
data.append(item)
return JsonResponse({'data': data[lower:upper], 'size': size})
@login_required
def update_purchase(request, pk):
if request.is_ajax():
obj = Purchase.objects.get(pk=pk)
new_payment = request.POST.get('payment')
obj.payment = new_payment
get_status(obj)
obj.save()
return JsonResponse({
'payment': obj.payment,
'status': obj.status
})
return redirect('purchases:purchase-history')
@login_required
def purchase_data(request, pk):
if request.is_ajax():
obj = Purchase.objects.get(pk=pk)
data = {
'id': obj.id,
'supplier': obj.supplier.name,
'created_at': obj.created_at,
'status': obj.status,
'grand_total': obj.grand_total,
'payment': obj.payment,
'created_by': obj.created_by.username,
}
return JsonResponse({'data': data})
return redirect('purchases:purchase-history')
@login_required
def delete_purchase(request, pk):
if request.is_ajax():
obj = Purchase.objects.get(pk=pk)
obj.delete()
return JsonResponse({'msg': 'Object has been deleted'})
return redirect('purchases:purchase-history')
def delete_selected_purchases(request):
if request.is_ajax():
object_ids = request.POST.getlist(('id_list[]'))
for id in object_ids:
obj = Purchase.objects.get(pk=id)
obj.delete()
return JsonResponse({'msg': 'Objects have been deleted'})
return redirect('purchases:purchase-history')
data = {
"company": "Dennnis Ivanov Company",
"address": "123 Street name",
"city": "Vancouver",
"state": "WA",
"zipcode": "98663",
"phone": "555-555-2345",
"email": "<EMAIL>",
"website": "dennisivy.com",
}
class ViewPDF(View):
# data = data.update(get_barcode())
def get(self, request, *args, **kwargs):
pdf = render_to_pdf('purchases/pdf_template.html', data)
return HttpResponse(pdf, content_type='application/pdf')
def auto_complete(request):
if request.is_ajax():
qs = Product.objects.all()
data = []
for obj in qs:
item = {
'name': obj.name,
}
data.append(item)
return JsonResponse({'data': data})
return redirect('purchases:purchase-history')
def export_csv(request):
product_resource = PurchaseResource()
dataset = product_resource.export()
response = HttpResponse(dataset.csv, content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="purchase_history.csv"'
return response
|
NIRALUser/BatchMake | Code/bmSplashScreenControls.cxx | /*=========================================================================
Program: BatchMake
Module: bmSplashScreenControls.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2005 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "bmSplashScreenControls.h"
namespace bm {
SplashScreenControls::SplashScreenControls()
:SplashScreen()
{
make_window();
}
SplashScreenControls::~SplashScreenControls()
{
}
void SplashScreenControls::Show()
{
if(!g_Splashscreen->shown())
g_Splashscreen->show();
}
} // end namespace bm
|
cdriehuys/ray-tracer | render.go | <reponame>cdriehuys/ray-tracer<filename>render.go
package main
import "log"
// Render a world using the view of a specific camera.
func Render(camera Camera, world World) Canvas {
image := MakeCanvas(camera.Width, camera.Height)
for y := 0; y < camera.Height; y++ {
for x := 0; x < camera.Width; x++ {
ray := camera.MakeRayForPixel(x, y)
color := world.ColorAt(ray)
image.SetPixel(x, y, color)
}
log.Printf("Rendered row %d of %d\n", y+1, camera.Height)
}
return image
}
|
dotph/epp-client-fred | test/commands/test_poll_command.rb | require 'helper'
class TestEppPollCommand < Test::Unit::TestCase
context 'EPP::Commands::Poll' do
context 'poll' do
setup do
@poll = EPP::Commands::Poll.new
@command = EPP::Requests::Command.new('ABC-123', @poll)
@request = EPP::Request.new(@command)
@xml = @request.to_xml
namespaces_from_request
end
should 'validate against schema' do
assert @xml.validate_schema(schema)
end
should 'set clTRID' do
assert_equal 'ABC-123', xpath_find('//epp:clTRID')
end
should 'set op mode req' do
assert_equal 'req', xpath_find('//epp:poll/@op')
end
end
context 'ack' do
setup do
@poll = EPP::Commands::Poll.new('234629834')
@command = EPP::Requests::Command.new('ABC-123', @poll)
@request = EPP::Request.new(@command)
@xml = @request.to_xml
namespaces_from_request
end
should 'validate against schema' do
assert @xml.validate_schema(schema)
end
should 'set clTRID' do
assert_equal 'ABC-123', xpath_find('//epp:clTRID')
end
should 'set op mode ack' do
assert_equal 'ack', xpath_find('//epp:poll/@op')
end
should 'set msgID' do
assert_equal '234629834', xpath_find('//epp:poll/@msgID')
end
end
end
end
|
1egoman/slime | state.go | package main
import (
"github.com/1egoman/slick/gateway" // The thing to interface with slack
"github.com/1egoman/slick/modal"
"github.com/1egoman/slick/status"
)
// This struct contains the main application state. I have fluxy intentions.
type State struct {
Mode string
Command []rune
CommandCursorPosition int
// Is the current session of the client offline?
Offline bool
// A list of all keys that have been pressed to make up the current command.
KeyStack []rune
// All the connections that are currently made to outside services.
Connections []gateway.Connection
activeConnection int
connectionSynced bool
// Interacting with messages
SelectedMessageIndex int
BottomDisplayedItem int
RenderedMessageNumber int
RenderedAllMessages bool
// Fuzzy picker
SelectionInput SelectionInput
SelectionInputSelectedItem int
SelectionInputBottomDisplayedItem int
// Status message
Status status.Status
// Modal
Modal modal.Modal
// Handlers to bind to specific actions. For example, when the user presses some keys, when we
// switch connections, etc...
EventActions []EventAction
// A map of configuration options for the editor.
Configuration map[string]string
}
func NewInitialState() *State {
return NewInitialStateMode("chat")
}
func NewInitialStateMode(mode string) *State {
return &State{
// The mode the client is in
Mode: mode,
// Starts online
Offline: false,
// The command the user is typing
Command: []rune{},
CommandCursorPosition: 0,
// Connection to the server
Connections: []gateway.Connection{},
// Which connection in the connections object is active
activeConnection: 0,
connectionSynced: false,
// Interacting with messages
SelectedMessageIndex: 0,
BottomDisplayedItem: 0,
RenderedMessageNumber: -1, // A render loop hasn't run yet.
RenderedAllMessages: false,
// Selection Input data
SelectionInput: SelectionInput{},
// Status message
Status: status.Status{},
// Modal
Modal: modal.Modal{},
// Configuration options
Configuration: map[string]string{
// Disable connection caching
"Connection.Cache": "true",
// Should relative line numbers be shown for each message?
// "Message.RelativeLine": "true",
// Disable auto-updates
// "AutoUpdate": "true",
// The format for the tiemstamp in front of each message.
// Reference date: `Mon Jan 2 15:04:05 MST 2006`
"Message.TimestampFormat": " Jan 2 15:04:05",
// How many messages should Ctrl-U / Ctrl-D page by?
"Message.PageAmount": "12",
// User online status settings
"Message.Sender.OnlinePrefix": "*",
"Message.Sender.OnlinePrefixColor": "green::",
"Message.Sender.OfflinePrefix": "*",
"Message.Sender.OfflinePrefixColor": "silver::",
"Message.ReactionColor": "::",
"Message.FileColor": "::",
"Message.SelectedColor": ":teal:",
"Message.Action.Color": "::",
"Message.Action.HighlightColor": "red::",
"Message.Attachment.TitleColor": "green::",
"Message.Attachment.FieldTitleColor": "::B",
"Message.Attachment.FieldValueColor": "::",
"Message.Part.AtMentionUserColor": "red::B",
"Message.Part.AtMentionGroupColor": "yellow::B",
"Message.Part.ChannelColor": "blue::B",
"Message.Part.LinkColor": "cyan::BU",
"Message.LineNumber.Color": "white::",
"Message.LineNumber.ActiveColor": "teal::",
"Message.UnconfirmedColor": "gray::",
"CommandBar.PrefixColor": "::",
"CommandBar.TextColor": "::",
"CommandBar.NewLineColor": "gray::B",
"StatusBar.Color": "::",
"StatusBar.ModeColor": "::",
"StatusBar.ActiveConnectionColor": "white:blue:",
"StatusBar.GatewayConnectedColor": "white::",
"StatusBar.GatewayConnectingColor": ":darkmagenta:",
"StatusBar.GatewayFailedColor": ":red:",
"StatusBar.LogColor": "white::",
"StatusBar.ErrorColor": "darkmagenta::B",
"StatusBar.TopBorderColor": ":gray:",
"FuzzyPicker.TopBorderColor": ":gray:",
"FuzzyPicker.ActiveItemColor": "::B",
},
}
}
func (s *State) ActiveConnection() gateway.Connection {
if len(s.Connections) > 0 {
return s.Connections[s.activeConnection]
} else {
return nil
}
}
// Methods to manage the active connection
// When the user changes the active connection,
func (s *State) SetActiveConnection(index int) {
s.activeConnection = index
s.connectionSynced = false
}
func (s *State) SetNextActiveConnection() {
s.activeConnection += 1
s.connectionSynced = false
// Make sure connectino can never get larger than the amount of conenctions
if s.activeConnection > len(s.Connections)-1 {
s.activeConnection = len(s.Connections) - 1
}
}
func (s *State) SetPrevActiveConnection() {
s.activeConnection -= 1
s.connectionSynced = false
// Make sure connectino can never get below 0
if s.activeConnection < 0 {
s.activeConnection = 0
}
}
func (s *State) ConnectionIsStale() bool {
return !s.connectionSynced
}
func (s *State) SyncActiveConnection() {
s.connectionSynced = true
}
func (s *State) ActiveConnectionIndex() int {
return s.activeConnection
}
|
LZKDreamer/MouShiMouKe | app/src/main/java/com/lzk/moushimouke/View/Activity/HomePageActivity.java | package com.lzk.moushimouke.View.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.lzk.moushimouke.Model.Adapter.HomePageFragmentAdapter;
import com.lzk.moushimouke.Model.Bean.MyUser;
import com.lzk.moushimouke.Model.Bean.Post;
import com.lzk.moushimouke.Presenter.HomePageActivityPresenter;
import com.lzk.moushimouke.R;
import com.lzk.moushimouke.View.Fragment.HomePageGalleryFragment;
import com.lzk.moushimouke.View.Fragment.HomePagePostFragment;
import com.lzk.moushimouke.View.Fragment.ViewPortraitDialogFragment;
import com.lzk.moushimouke.View.Interface.IHomePageActivityDataCallBack;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jzvd.JZVideoPlayerStandard;
import de.hdodenhof.circleimageview.CircleImageView;
public class HomePageActivity extends AppCompatActivity implements IHomePageActivityDataCallBack {
@BindView(R.id.home_page_background)
ImageView mHomePageBackground;
@BindView(R.id.home_page_portrait)
CircleImageView mHomePagePortrait;
@BindView(R.id.home_page_user_name)
TextView mHomePageUserName;
@BindView(R.id.home_page_post_num)
TextView mHomePagePostNum;
@BindView(R.id.home_page_follower_num)
TextView mHomePageFollowerNum;
@BindView(R.id.home_page_profile)
TextView mHomePageProfile;
@BindView(R.id.home_page_toolbar)
Toolbar mHomePageToolbar;
@BindView(R.id.home_page_tab_layout)
TabLayout mHomePageTabLayout;
@BindView(R.id.home_page_view_pager)
ViewPager mHomePageViewPager;
@BindView(R.id.home_page_appbar)
AppBarLayout mHomePageAppbar;
@BindView(R.id.home_page_toolbar_title)
TextView mHomePageToolbarTitle;
@BindView(R.id.home_page_post)
TextView mHomePagePost;
@BindView(R.id.home_page_follower)
TextView mHomePageFollower;
@BindView(R.id.home_page_toolbar_back)
ImageView mHomePageToolbarBack;
@BindView(R.id.home_page_ll_divider)
View mHomePageLlDivider;
private List<Fragment> mFragmentList;
private String[] mTabTitles;
private HomePageFragmentAdapter mFragmentAdapter;
public static final String tag = "HOME_PAGE_DATA";
private MyUser mUser;
private String portraitUrl, userName, profile;
private int postNum, followerNum;
private List<Post> mPosts;
private HomePageActivityPresenter mActivityPresenter;
private ActionBar actionBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
ButterKnife.bind(this);
initToolbar();
Glide.with(this).load(R.drawable.ic_user_portrait_default).into(mHomePagePortrait);
initUserInfo();
mHomePageAppbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
/*折叠状态*/
if (getSupportActionBar().getHeight() - mHomePageAppbar.getHeight() == verticalOffset) {
mHomePageToolbarTitle.setText(userName);
mHomePageToolbarBack.setImageResource(R.drawable.ic_home_page_back_dark);
mHomePageToolbar.setBackgroundColor(getResources().getColor(R.color.colorWhite));
} else {
mHomePageToolbarTitle.setText("");
mHomePageToolbarBack.setImageResource(R.drawable.ic_home_page_back_white);
mHomePageToolbar.setBackgroundColor(getResources().getColor(R.color.colorTransparent));
}
}
});
}
public static Intent newIntent(Context context, MyUser user) {
Intent intent = new Intent(context, HomePageActivity.class);
intent.putExtra(tag, user);
return intent;
}
private void initUserInfo() {
Intent intent = getIntent();
mUser = (MyUser) intent.getSerializableExtra(tag);
mActivityPresenter = new HomePageActivityPresenter();
mActivityPresenter.requestPostData(mUser, this);
}
private void initFragmentList() {
mFragmentList = new ArrayList<>();
mFragmentList.add(HomePagePostFragment.newInstance(mUser));
mFragmentList.add(HomePageGalleryFragment.newInstance(mUser));
}
private void initToolbar() {
Toolbar toolbar = findViewById(R.id.home_page_toolbar);
toolbar.setTitle("");
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(false);
}
private void initTabAndViewPager() {
mTabTitles = new String[]{getString(R.string.post1), getString(R.string.gallery)};
mFragmentAdapter = new HomePageFragmentAdapter(getSupportFragmentManager(), mFragmentList, mTabTitles);
mHomePageViewPager.setAdapter(mFragmentAdapter);
mHomePageTabLayout.setupWithViewPager(mHomePageViewPager);
mHomePageTabLayout.getTabAt(0).select();
mHomePageTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
JZVideoPlayerStandard.releaseAllVideos();
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
@Override
public void getPostAndFollowerResult(List<Post> postList, int followerNum) {
mHomePagePost.setVisibility(View.VISIBLE);
mHomePageFollower.setVisibility(View.VISIBLE);
mHomePageLlDivider.setVisibility(View.VISIBLE);
if (postList != null) {
postNum = postList.size();
this.followerNum = followerNum;
mPosts = postList;
mHomePagePostNum.setText(postNum + "");
mHomePageFollowerNum.setText(this.followerNum + "");
} else {
mHomePagePostNum.setText(0 + "");
mHomePageFollowerNum.setText(0 + "");
}
portraitUrl = mUser.getPortrait();
if (portraitUrl != null) {
Glide.with(this).load(portraitUrl).into(mHomePagePortrait);
}
userName = mUser.getUsername();
mHomePageUserName.setText(userName);
profile = mUser.getProfile();
if (profile != null) {
mHomePageProfile.setText(profile);
} else {
mHomePageProfile.setText(getString(R.string.empty_profile));
}
initFragmentList();
initTabAndViewPager();
}
@OnClick(R.id.home_page_toolbar_back)
public void onViewClicked() {
finish();
}
@OnClick(R.id.home_page_portrait)
public void onPortraitClicked() {
if (mUser.getPortrait()!=null){
FragmentManager manager=getSupportFragmentManager();
ViewPortraitDialogFragment portraitDialogFragment=ViewPortraitDialogFragment.newInstance(mUser.getPortrait());
portraitDialogFragment.show(manager,"");
}
}
}
|
apisandipas/bssckit | src/theme/breadcrumbItem.js | import palette from '../theme/palette';
import globals from '../theme/globals';
const breadcrumbItem = {
colors: {
default: {
color: palette.secondary,
},
},
padding: {
right: '0.5rem',
left: '0.5rem',
},
margin: {
bottom: '1rem',
},
borderRadius: globals.borderRadius,
};
export default breadcrumbItem;
|
jomof/CppBuildCacheWorkInProgress | agp-7.1.0-alpha01/tools/base/deploy/deployer/src/main/java/com/android/tools/deployer/D8DexSplitter.java | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.deployer;
import com.android.tools.deploy.proto.Deploy;
import com.android.tools.deployer.model.ApkEntry;
import com.android.tools.deployer.model.DexClass;
import com.android.tools.r8.ByteDataView;
import com.android.tools.r8.CompilationFailedException;
import com.android.tools.r8.D8;
import com.android.tools.r8.D8Command;
import com.android.tools.r8.DexFilePerClassFileConsumer;
import com.android.tools.r8.DiagnosticsHandler;
import com.android.tools.r8.inspector.ClassInspector;
import com.android.tools.r8.inspector.FieldInspector;
import com.android.tools.r8.inspector.Inspector;
import com.android.tools.r8.inspector.ValueInspector;
import com.android.tools.r8.origin.Origin;
import com.android.tools.r8.references.FieldReference;
import com.android.tools.tracer.Trace;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Multimap;
import com.google.common.io.ByteStreams;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class D8DexSplitter implements DexSplitter {
/** @param keepCode Needs to be threadsafe. */
@Override
public Collection<DexClass> split(ApkEntry dex, Predicate<DexClass> keepCode) {
try (Trace ignored = Trace.begin("split " + dex.getName())) {
D8Command.Builder newBuilder = D8Command.builder();
DexConsumer consumer = new DexConsumer(dex, keepCode);
newBuilder.addDexProgramData(readDex(dex), Origin.unknown());
newBuilder.setDexClassChecksumFilter(consumer::parseFilter);
newBuilder.addOutputInspection(consumer);
newBuilder.setProgramConsumer(consumer);
D8.run(newBuilder.build());
consumer.join();
return consumer.classes.values().stream()
.map(
dexClass -> {
Collection<Deploy.ClassDef.FieldReInitState> states =
consumer.variableStates.get(dexClass.name);
if (states == null) {
return dexClass;
} else {
return new DexClass(dexClass, ImmutableList.copyOf(states));
}
})
.collect(Collectors.toList());
} catch (InterruptedException | CompilationFailedException e) {
throw new RuntimeException(e);
}
}
protected byte[] readDex(ApkEntry dex) {
// TODO Check if opening the file several times matters
try (ZipFile file = new ZipFile(dex.getApk().path)) {
ZipEntry entry = file.getEntry(dex.getName());
return ByteStreams.toByteArray(file.getInputStream(entry));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static class DexConsumer implements DexFilePerClassFileConsumer, Consumer<Inspector> {
private final Map<String, DexClass> classes = new HashMap<>();
// Note D8 does NOT guarantee any thread / ordering / duplicates of the inspection API.
// We must compute both the classes (filtering out what we don't need) and the variables
// separately and reduce them at the end after the compilation is done.
private final Multimap<String, Deploy.ClassDef.FieldReInitState> variableStates =
ArrayListMultimap.create();
private final CountDownLatch finished = new CountDownLatch(1);
private final Predicate<DexClass> keepCode;
private final ApkEntry dex;
private DexConsumer(ApkEntry dex, Predicate<DexClass> keepCode) {
this.dex = dex;
this.keepCode = keepCode;
}
@Override
public void finished(DiagnosticsHandler handler) {
finished.countDown();
}
public void join() throws InterruptedException {
finished.await();
}
/**
* Performs a filter of Java classes during parse time. If we can already decide if we are
* not keeping the code of this class, we tell the compiler to skip parsing the rest of the
* class body.
*/
public boolean parseFilter(String classDescriptor, Long checksum) {
DexClass c =
new DexClass(
typeNameToClassName(classDescriptor),
checksum == null ? 0 : checksum,
null,
dex);
// D8 is free to use multiple thread to parse (although it mostly do it base on number of dex input). We can
// potentially have multiple parsing calling us back.
synchronized (this) {
classes.put(classDescriptor, c);
}
if (keepCode != null) {
return keepCode.test(c);
} else {
return false;
}
}
@Override
public synchronized void accept(
String name,
ByteDataView data,
Set<String> descriptors,
DiagnosticsHandler handler) {
DexClass clazz = classes.get(name);
String className = typeNameToClassName(name);
// It is possible that some classes has no checksum information. They would not appear on the previous filter step.
if (clazz == null) {
CRC32 crc = new CRC32();
crc.update(data.getBuffer(), data.getOffset(), data.getLength());
long newChecksum = crc.getValue();
clazz = new DexClass(className, newChecksum, null, dex);
classes.put(name, clazz);
}
if (keepCode != null && keepCode.test(clazz)) {
classes.put(
name, new DexClass(className, clazz.checksum, data.copyByteData(), dex));
}
}
@Override
public void accept(Inspector inspector) {
inspector.forEachClass(
classInspector -> {
classInspector.forEachField(
fieldInspector -> {
inspectField(classInspector, fieldInspector);
});
});
}
private void inspectField(ClassInspector classInspector, FieldInspector fieldInspector) {
Deploy.ClassDef.FieldReInitState.Builder state =
Deploy.ClassDef.FieldReInitState.newBuilder();
FieldReference field = fieldInspector.getFieldReference();
state.setName(field.getFieldName());
state.setType(field.getFieldType().getDescriptor());
state.setStaticVar(fieldInspector.isStatic());
Optional<ValueInspector> value = fieldInspector.getInitialValue();
if (fieldInspector.isStatic() && fieldInspector.isFinal() && value.isPresent()) {
state.setState(Deploy.ClassDef.FieldReInitState.VariableState.CONSTANT);
ValueInspector valueInspector = value.get();
if (valueInspector.isByteValue()) {
state.setValue(Byte.toString(value.get().asByteValue().getByteValue()));
} else if (valueInspector.isCharValue()) {
state.setValue(Character.toString(value.get().asCharValue().getCharValue()));
} else if (valueInspector.isIntValue()) {
state.setValue(Integer.toString(value.get().asIntValue().getIntValue()));
} else if (valueInspector.isLongValue()) {
state.setValue(Long.toString(value.get().asLongValue().getLongValue()));
} else if (valueInspector.isShortValue()) {
state.setValue(Short.toString(value.get().asShortValue().getShortValue()));
} else if (valueInspector.isDoubleValue()) {
state.setValue(Double.toString(value.get().asDoubleValue().getDoubleValue()));
} else if (valueInspector.isFloatValue()) {
state.setValue(Float.toString(value.get().asFloatValue().getFloatValue()));
} else if (valueInspector.isBooleanValue()) {
state.setValue(
Boolean.toString(value.get().asBooleanValue().getBooleanValue()));
}
} else {
state.setState(Deploy.ClassDef.FieldReInitState.VariableState.UNKNOWN);
}
// D8 can call this in any threads.
synchronized (this) {
variableStates.put(
typeNameToClassName(classInspector.getClassReference().getDescriptor()),
state.build());
}
}
}
/** VM type names to the more readable class names. */
private static String typeNameToClassName(String typeName) {
assert typeName.startsWith("L");
assert typeName.endsWith(";");
return typeName.substring(1, typeName.length() - 1).replace('/', '.');
}
}
|
samary-xia/magento2.3.3 | app/code/Amasty/Conditions/view/frontend/web/js/model/conditions-subscribe.js | <filename>app/code/Amasty/Conditions/view/frontend/web/js/model/conditions-subscribe.js
define([
'jquery',
'underscore',
'uiComponent',
'Magento_Checkout/js/model/quote',
'Amasty_Conditions/js/action/recollect-totals',
'Amasty_Conditions/js/model/subscriber',
'Magento_Checkout/js/model/shipping-service',
'Magento_Checkout/js/model/shipping-rate-processor/new-address',
'Magento_Checkout/js/model/totals',
'Magento_SalesRule/js/view/payment/discount',
'rjsResolver'
], function ($, _, Component, quote, recollect, subscriber, shippingService, shippingProcessor, totals, discount, resolver) {
'use strict';
return Component.extend({
previousShippingMethodData: {},
previousItemsData: [],
billingAddressCountry: null,
city: null,
street: null,
isPageLoaded: false,
initialize: function () {
this._insertPolyfills();
this._super();
resolver(function() {
this.isPageLoaded = true;
totals.getItems().subscribe(this.storeOldItems, this, "beforeChange");
totals.getItems().subscribe(this.recollectOnItems, this);
}.bind(this));
discount().isApplied.subscribe(function () {
recollect(true);
});
quote.shippingAddress.subscribe(function (newShippingAddress) {
// while page is loading do not recollect, should be recollected after shipping rates
// for avoid extra requests to server
if (this.isPageLoaded && this._isNeededRecollectShipping(newShippingAddress, this.city, this.street)) {
this.city = newShippingAddress.city;
this.street = newShippingAddress.street;
if (newShippingAddress) {
recollect();
}
}
}.bind(this));
quote.billingAddress.subscribe(function (newBillAddress) {
if (this._isNeededRecollectBilling(newBillAddress, this.billingAddressCountry)) {
this.billingAddressCountry = newBillAddress.countryId;
if (!this._isVirtualQuote()
&& (quote.shippingAddress() && newBillAddress.countryId !== quote.shippingAddress().countryId)
) {
shippingProcessor.getRates(quote.shippingAddress());
}
recollect();
}
}.bind(this));
//for invalid shipping address update
shippingService.getShippingRates().subscribe(function (rates) {
if (!this._isVirtualQuote()) {
recollect();
}
}.bind(this));
quote.paymentMethod.subscribe(function (newMethodData) {
recollect();
}, this);
quote.shippingMethod.subscribe(this.storeOldMethod, this, "beforeChange");
quote.shippingMethod.subscribe(this.recollectOnShippingMethod, this);
return this;
},
/**
* Store before change shipping method, because sometimes shipping methods updates always (not by change)
*
* @param {Object} oldMethod
*/
storeOldMethod: function (oldMethod) {
this.previousShippingMethodData = oldMethod;
},
recollectOnShippingMethod: function (newMethodData) {
if (!_.isEqual(this.previousShippingMethodData, newMethodData)) {
recollect();
}
},
/**
* Store before change cart items
*
* @param {Array} oldItems
* @since 1.3.13
*/
storeOldItems: function (oldItems) {
this.previousItemsData = this._prepareArrayForCompare(oldItems);
},
/**
* Recollect totals on cart items update
*
* @param {Array} newItems
* @since 1.3.13 improve compatibility with modules which allow update cart items on checkout page
* and ajax update cart items
*/
recollectOnItems: function (newItems) {
if (!_.isEqual(this.previousItemsData, this._prepareArrayForCompare(newItems))) {
// totals should be already collected, trigger subscribers
// for more stability but less performance can be replaced with recollect(true);
subscriber.isLoading.valueHasMutated();
}
},
/**
* Remove all not simple types from array items
*
* @param {Array} data
* @returns {Array}
* @private
* @since 1.3.13
*/
_prepareArrayForCompare: function (data) {
var result = [],
itemData = {};
_.each(data, function(item) {
itemData = _.pick(item, function (value) {
return !_.isObject(value);
});
result.push(itemData);
}.bind(this));
return result;
},
_isVirtualQuote: function () {
return quote.isVirtual()
|| window.checkoutConfig.activeCarriers && window.checkoutConfig.activeCarriers.length === 0;
},
_isNeededRecollectShipping: function (newShippingAddress, city, street) {
return !this._isVirtualQuote()
&& (
newShippingAddress
&& (newShippingAddress.city || newShippingAddress.street)
&& (newShippingAddress.city != city || !_.isEqual(newShippingAddress.street, street)));
},
_isNeededRecollectBilling: function (newBillAddress, billingAddressCountry) {
return this.isPageLoaded
&& newBillAddress
&& newBillAddress.countryId
&& newBillAddress.countryId != billingAddressCountry
},
_insertPolyfills: function () {
if (typeof Object.assign != 'function') {
// Must be writable: true, enumerable: false, configurable: true
Object.defineProperty(Object, "assign", {
value: function assign(target, varArgs) { // .length of function is 2
'use strict';
if (target == null) { // TypeError if undefined or null
throw new TypeError('Cannot convert undefined or null to object');
}
var to = Object(target);
for (var index = 1; index < arguments.length; index++) {
var nextSource = arguments[index];
if (nextSource != null) { // Skip over if undefined or null
for (var nextKey in nextSource) {
// Avoid bugs when hasOwnProperty is shadowed
if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
to[nextKey] = nextSource[nextKey];
}
}
}
}
return to;
},
writable: true,
configurable: true
});
}
}
});
});
|
ArtemFM/JavaJunior | lesson02/tracker/src/main/java/apavlov/input/Input.java | <filename>lesson02/tracker/src/main/java/apavlov/input/Input.java
package apavlov.input;
/**
* The interface input for work with console.
*
* @author <NAME>
* @since 22.08.2017
*/
public interface Input {
/**
* The method for work to console.
*
* @param question - question for user in console;
* @return value inpeted with console;
*/
String ask(String question);
/**
* The method for work to console.
*
* @param question - question for user in console;
* @param startRange - min possible number;
* @param endRange - max possible number;
* @return value inpeted with console;
*/
int ask(String question, int startRange, int endRange);
}
|
kuro2a/kiku | lib/database/Specification.py | <gh_stars>1-10
#!/usr/bin/python3
from sqlalchemy import UniqueConstraint, Column, Integer, BigInteger, String, TIMESTAMP
from lib.database.DatabaseCore import Base
from datetime import datetime
class Specification(Base):
__tablename__ = 'ma_specification'
id = Column(Integer, nullable=False, primary_key=True, autoincrement=True)
server_id = Column(Integer, nullable=False, unique=True)
os_id = Column(Integer, nullable=False)
cpu_core = Column(Integer, nullable=False)
memory = Column(BigInteger, nullable=False)
swap = Column(BigInteger, nullable=False)
system_storage = Column(BigInteger, nullable=False)
created_time = Column(TIMESTAMP, default=datetime.now, nullable=False)
modified_time = Column(TIMESTAMP, default=datetime.now, nullable=False)
def __repr__(self):
return "<Specification(server_id='%s', cpu_core='%s', memory='%s', swap='%s', system_storage='%s', created_time='%s', modified_time='%s')>" % (
self.server_id,
self.cpu_core,
self.memory,
self.swap,
self.system_storage,
self.created_time,
self.modified_time
)
|
stahta01/mingw-org-wsl | mingwrt/mingwex/math/modff.c | <filename>mingwrt/mingwex/math/modff.c
#include <fenv.h>
#include <math.h>
#include <errno.h>
#define FE_ROUNDING_MASK \
(FE_TONEAREST | FE_DOWNWARD | FE_UPWARD | FE_TOWARDZERO)
float
modff (float value, float* iptr)
{
float int_part;
unsigned short saved_cw;
unsigned short tmp_cw;
/* truncate */
asm ("fnstcw %0;" : "=m" (saved_cw)); /* save control word */
tmp_cw = (saved_cw & ~FE_ROUNDING_MASK) | FE_TOWARDZERO;
asm ("fldcw %0;" : : "m" (tmp_cw));
asm ("frndint;" : "=t" (int_part) : "0" (value)); /* round */
asm ("fldcw %0;" : : "m" (saved_cw)); /* restore saved cw */
if (iptr)
*iptr = int_part;
return (isinf (value) ? 0.0F : value - int_part);
}
|
youqingxiaozhua/OpenSelfSup | openselfsup/datasets/contrastive.py | <reponame>youqingxiaozhua/OpenSelfSup
import torch
from PIL import Image
from .registry import DATASETS
from .base import BaseDataset
from .utils import to_numpy
@DATASETS.register_module
class ContrastiveDataset(BaseDataset):
"""Dataset for contrastive learning methods that forward
two views of the image at a time (MoCo, SimCLR).
"""
def __init__(self, data_source, pipeline, prefetch=False):
data_source['return_label'] = False
super(ContrastiveDataset, self).__init__(data_source, pipeline, prefetch)
def __getitem__(self, idx):
img = self.data_source.get_sample(idx)
assert isinstance(img, Image.Image), \
'The output from the data source must be an Image, got: {}. \
Please ensure that the list file does not contain labels.'.format(
type(img))
img1 = self.pipeline(img)
img2 = self.pipeline(img)
if self.prefetch:
img1 = torch.from_numpy(to_numpy(img1))
img2 = torch.from_numpy(to_numpy(img2))
img_cat = torch.cat((img1.unsqueeze(0), img2.unsqueeze(0)), dim=0)
return dict(img=img_cat)
def evaluate(self, scores, keyword, logger=None, **kwargs):
raise NotImplemented
|
ricortiz/OpenTissue | demos/glut/multibody/src/scenes/setup_falling_cows.cpp | //
// OpenTissue Template Library Demo
// - A specific demonstration of the flexibility of OTTL.
// Copyright (C) 2008 Department of Computer Science, University of Copenhagen.
//
// OTTL and OTTL Demos are licensed under zlib.
//
#include "setup_falling_cows.h"
#include <OpenTissue/core/geometry/geometry_compute_box_mass_properties.h>
#include <OpenTissue/core/geometry/geometry_compute_sphere_mass_properties.h>
#include <OpenTissue/core/math/math_random.h>
#include <OpenTissue/utility/utility_get_environment_variable.h>
void setup_falling_cows(Data & data)
{
data.m_configuration.clear();
data.m_library.clear();
data.m_simulator.clear();
data.m_bodies.resize(250);
if(data.m_cow_mesh.size_vertices()==0)
{
real_type const edge_resolution = 0.01;
bool const face_sampling = true;
std::string data_path = OpenTissue::utility::get_environment_variable("OPENTISSUE");
OpenTissue::mesh::obj_read(data_path + "/demos/data/obj/cow.obj", data.m_cow_mesh);
OpenTissue::mesh::obj_read(data_path + "/demos/data/obj/support_box.obj", data.m_support_box_mesh);
OpenTissue::mesh::scale(data.m_support_box_mesh, 10.0, 10.0, 10.0);
OpenTissue::mesh::compute_angle_weighted_vertex_normals(data.m_cow_mesh);
OpenTissue::mesh::compute_angle_weighted_vertex_normals(data.m_support_box_mesh);
OpenTissue::sdf::semiauto_init_geometry(data.m_cow_mesh, edge_resolution, face_sampling, data.m_cow_geo,128);
OpenTissue::sdf::semiauto_init_geometry(data.m_support_box_mesh, edge_resolution, face_sampling, data.m_support_box_geo,128);
}
data.m_bodies[0].set_fixed(true);
data.m_bodies[0].set_geometry(&data.m_support_box_geo);
data.m_configuration.add(&data.m_bodies[0]);
for(int i=1;i<250;++i)
{
data.m_bodies[i].attach(&data.m_gravity);
data.m_bodies[i].set_geometry(&data.m_cow_geo);
data.m_configuration.add(&data.m_bodies[i]);
}
data.m_bodies[0].set_position( vector3_type(value_traits::zero(),value_traits::zero(),value_traits::zero()) );
data.m_bodies[0].set_orientation( quaternion_type(1,0,0,0) );
data.m_bodies[1].set_position( vector3_type(1.18839,-3.76415,3.75) );
data.m_bodies[1].set_orientation( quaternion_type(0.716584,0.152243,-0.482221,0.480408) );
data.m_bodies[2].set_position( vector3_type(0.396619,-0.184698,5) );
data.m_bodies[2].set_orientation( quaternion_type(0.665121,0.0590083,-0.0274791,0.743893) );
data.m_bodies[3].set_position( vector3_type(0.455702,-3.28147,6.25) );
data.m_bodies[3].set_orientation( quaternion_type(0.0846058,0.0641904,-0.46223,0.880378) );
data.m_bodies[4].set_position( vector3_type(-3.78686,-2.42012,7.5) );
data.m_bodies[4].set_orientation( quaternion_type(0.0993081,-0.430969,-0.275425,0.853548) );
data.m_bodies[5].set_position( vector3_type(3.31468,-3.29832,8.75) );
data.m_bodies[5].set_orientation( quaternion_type(0.916559,0.133608,-0.132948,0.352694) );
data.m_bodies[6].set_position( vector3_type(3.28538,-2.19306,10) );
data.m_bodies[6].set_orientation( quaternion_type(-0.853452,0.159251,-0.106303,0.484725) );
data.m_bodies[7].set_position( vector3_type(3.25657,-0.133671,11.25) );
data.m_bodies[7].set_orientation( quaternion_type(-0.617701,0.218654,-0.00897499,0.755351) );
data.m_bodies[8].set_position( vector3_type(-2.4228,-2.74239,2.5) );
data.m_bodies[8].set_orientation( quaternion_type(0.856188,-0.282454,-0.319712,0.291454) );
data.m_bodies[9].set_position( vector3_type(-1.42912,-3.50047,3.75) );
data.m_bodies[9].set_orientation( quaternion_type(-0.941411,-0.0905098,-0.221694,0.237497) );
data.m_bodies[10].set_position( vector3_type(3.68017,-0.184454,5) );
data.m_bodies[10].set_orientation( quaternion_type(-0.32609,0.560128,-0.0280742,0.761009) );
data.m_bodies[11].set_position( vector3_type(2.25239,-2.22407,6.25) );
data.m_bodies[11].set_orientation( quaternion_type(0.960401,0.0895764,-0.08845,0.248559) );
data.m_bodies[12].set_position( vector3_type(1.2172,1.26701,7.5) );
data.m_bodies[12].set_orientation( quaternion_type(0.42388,0.143118,0.148974,0.881845) );
data.m_bodies[13].set_position( vector3_type(-3.09568,3.03952,8.75) );
data.m_bodies[13].set_orientation( quaternion_type(-0.518346,-0.271063,0.266146,0.766165) );
data.m_bodies[14].set_position( vector3_type(0.250374,3.08347,10) );
data.m_bodies[14].set_orientation( quaternion_type(0.537561,0.0201691,0.248391,0.805558) );
data.m_bodies[15].set_position( vector3_type(2.64791,-3.91626,11.25) );
data.m_bodies[15].set_orientation( quaternion_type(-0.731071,0.148053,-0.21897,0.629022) );
data.m_bodies[16].set_position( vector3_type(-2.3144,-0.798242,2.5) );
data.m_bodies[16].set_orientation( quaternion_type(0.908122,-0.276945,-0.0955188,0.299154) );
data.m_bodies[17].set_position( vector3_type(2.0268,2.43501,3.75) );
data.m_bodies[17].set_orientation( quaternion_type(-0.509298,0.355304,0.426866,0.657388) );
data.m_bodies[18].set_position( vector3_type(-1.3195,-0.193731,5) );
data.m_bodies[18].set_orientation( quaternion_type(-0.999994,-0.000904542,-0.000132807,0.0034276) );
data.m_bodies[19].set_position( vector3_type(1.91327,-0.369274,6.25) );
data.m_bodies[19].set_orientation( quaternion_type(-0.998538,0.0157955,-0.00304864,0.0515985) );
data.m_bodies[20].set_position( vector3_type(-0.950346,-3.89087,7.5) );
data.m_bodies[20].set_orientation( quaternion_type(-0.999818,-0.00213244,-0.00873054,0.0168289) );
data.m_bodies[21].set_position( vector3_type(0.415662,0.503067,8.75) );
data.m_bodies[21].set_orientation( quaternion_type(0.736153,0.0320626,0.0388046,0.674941) );
data.m_bodies[22].set_position( vector3_type(0.671285,2.13276,10) );
data.m_bodies[22].set_orientation( quaternion_type(0.925081,0.0248791,0.0790438,0.370618) );
data.m_bodies[23].set_position( vector3_type(2.7839,-2.54073,11.25) );
data.m_bodies[23].set_orientation( quaternion_type(0.725882,0.16139,-0.147293,0.652192) );
data.m_bodies[24].set_position( vector3_type(3.89306,-2.51045,2.5) );
data.m_bodies[24].set_orientation( quaternion_type(-0.975994,0.161079,-0.103873,0.10344) );
data.m_bodies[25].set_position( vector3_type(-1.68499,-0.236946,3.75) );
data.m_bodies[25].set_orientation( quaternion_type(0.997956,-0.026149,-0.00367711,0.0581955) );
data.m_bodies[26].set_position( vector3_type(0.938627,3.16477,5) );
data.m_bodies[26].set_orientation( quaternion_type(-0.700004,0.111879,0.377222,0.595971) );
data.m_bodies[27].set_position( vector3_type(2.26093,3.81616,6.25) );
data.m_bodies[27].set_orientation( quaternion_type(0.378217,0.273092,0.460943,0.75492) );
data.m_bodies[28].set_position( vector3_type(2.31416,2.29609,7.5) );
data.m_bodies[28].set_orientation( quaternion_type(-0.252323,0.273822,0.271684,0.887436) );
data.m_bodies[29].set_position( vector3_type(2.73336,0.438368,8.75) );
data.m_bodies[29].set_orientation( quaternion_type(0.964991,0.0781166,0.0125281,0.250066) );
data.m_bodies[30].set_position( vector3_type(0.21424,1.95697,10) );
data.m_bodies[30].set_orientation( quaternion_type(-0.35825,0.0196253,0.179267,0.916043) );
data.m_bodies[31].set_position( vector3_type(-3.3889,3.15061,11.25) );
data.m_bodies[31].set_orientation( quaternion_type(-0.603656,-0.222105,0.206488,0.737314) );
data.m_bodies[32].set_position( vector3_type(-3.07224,3.93554,2.5) );
data.m_bodies[32].set_orientation( quaternion_type(0.476518,-0.483734,0.619665,0.393634) );
data.m_bodies[33].set_position( vector3_type(2.44575,1.45476,3.75) );
data.m_bodies[33].set_orientation( quaternion_type(0.994534,0.0542461,0.0322661,0.0831739) );
data.m_bodies[34].set_position( vector3_type(2.24531,-3.48265,5) );
data.m_bodies[34].set_orientation( quaternion_type(0.575079,0.282864,-0.438745,0.629901) );
data.m_bodies[35].set_position( vector3_type(2.36738,-0.884671,6.25) );
data.m_bodies[35].set_orientation( quaternion_type(0.887721,0.161667,-0.0604135,0.426808) );
data.m_bodies[36].set_position( vector3_type(-0.135868,-0.733055,7.5) );
data.m_bodies[36].set_orientation( quaternion_type(0.0255484,-0.0180211,-0.0972295,0.994771) );
data.m_bodies[37].set_position( vector3_type(-3.00803,1.44108,8.75) );
data.m_bodies[37].set_orientation( quaternion_type(0.908683,-0.134108,0.0642486,0.390106) );
data.m_bodies[38].set_position( vector3_type(2.79513,0.80752,10) );
data.m_bodies[38].set_orientation( quaternion_type(0.507234,0.231296,0.066822,0.827497) );
data.m_bodies[39].set_position( vector3_type(-2.67281,-0.433973,11.25) );
data.m_bodies[39].set_orientation( quaternion_type(0.412122,-0.210458,-0.0341712,0.88583) );
data.m_bodies[40].set_position( vector3_type(-2.23139,-2.39644,2.5) );
data.m_bodies[40].set_orientation( quaternion_type(0.534729,-0.457697,-0.49155,0.512793) );
data.m_bodies[41].set_position( vector3_type(1.67864,-0.269906,3.75) );
data.m_bodies[41].set_orientation( quaternion_type(0.134062,0.404012,-0.0649603,0.902542) );
data.m_bodies[42].set_position( vector3_type(2.6418,-2.25849,5) );
data.m_bodies[42].set_orientation( quaternion_type(0.625586,0.338464,-0.289354,0.640592) );
data.m_bodies[43].set_position( vector3_type(-2.44502,1.56169,6.25) );
data.m_bodies[43].set_orientation( quaternion_type(-0.887279,-0.163663,0.104535,0.418357) );
data.m_bodies[44].set_position( vector3_type(-3.197,-2.28877,7.5) );
data.m_bodies[44].set_orientation( quaternion_type(0.703487,-0.268315,-0.19209,0.629455) );
data.m_bodies[45].set_position( vector3_type(-3.42357,-2.64302,8.75) );
data.m_bodies[45].set_orientation( quaternion_type(-0.995837,-0.0319706,-0.0246816,0.0817108) );
data.m_bodies[46].set_position( vector3_type(-3.42015,-3.81323,10) );
data.m_bodies[46].set_orientation( quaternion_type(-0.990418,-0.0420379,-0.0468693,0.122912) );
data.m_bodies[47].set_position( vector3_type(-1.62029,0.363903,11.25) );
data.m_bodies[47].set_orientation( quaternion_type(0.966705,-0.0364601,0.00818861,0.25315) );
data.m_bodies[48].set_position( vector3_type(3.64428,-3.19138,2.5) );
data.m_bodies[48].set_orientation( quaternion_type(-0.99538,0.0641894,-0.0562122,0.0440344) );
data.m_bodies[49].set_position( vector3_type(3.52342,-1.93963,3.75) );
data.m_bodies[49].set_orientation( quaternion_type(-0.579228,0.522306,-0.287528,0.555894) );
data.m_bodies[50].set_position( vector3_type(2.41914,-0.0357677,5) );
data.m_bodies[50].set_orientation( quaternion_type(0.142988,0.431046,-0.00637313,0.890906) );
data.m_bodies[51].set_position( vector3_type(3.39622,-1.56194,6.25) );
data.m_bodies[51].set_orientation( quaternion_type(-0.469168,0.411835,-0.189405,0.757892) );
data.m_bodies[52].set_position( vector3_type(-1.51531,-0.431532,7.5) );
data.m_bodies[52].set_orientation( quaternion_type(-0.132542,-0.19598,-0.0558117,0.970005) );
data.m_bodies[53].set_position( vector3_type(3.1218,1.2819,8.75) );
data.m_bodies[53].set_orientation( quaternion_type(-0.842063,0.179547,0.073727,0.503246) );
data.m_bodies[54].set_position( vector3_type(1.9848,0.846828,10) );
data.m_bodies[54].set_orientation( quaternion_type(0.486936,0.169459,0.0723009,0.853785) );
data.m_bodies[55].set_position( vector3_type(-2.53487,-1.54778,11.25) );
data.m_bodies[55].set_orientation( quaternion_type(0.365757,-0.202762,-0.123805,0.899878) );
data.m_bodies[56].set_position( vector3_type(-3.96728,3.11545,2.5) );
data.m_bodies[56].set_orientation( quaternion_type(-0.152754,-0.696415,0.546885,0.438849) );
data.m_bodies[57].set_position( vector3_type(3.73998,3.16623,3.75) );
data.m_bodies[57].set_orientation( quaternion_type(-0.831246,0.336938,0.285248,0.33784) );
data.m_bodies[58].set_position( vector3_type(2.11811,3.562,5) );
data.m_bodies[58].set_orientation( quaternion_type(-0.678684,0.239538,0.402829,0.565454) );
data.m_bodies[59].set_position( vector3_type(-0.286996,-3.72192,6.25) );
data.m_bodies[59].set_orientation( quaternion_type(0.229619,-0.0383695,-0.497596,0.835584) );
data.m_bodies[60].set_position( vector3_type(2.51241,-1.97211,7.5) );
data.m_bodies[60].set_orientation( quaternion_type(0.80519,0.18277,-0.143465,0.545602) );
data.m_bodies[61].set_position( vector3_type(-1.48796,-2.43867,8.75) );
data.m_bodies[61].set_orientation( quaternion_type(-0.215598,-0.157853,-0.258711,0.928261) );
data.m_bodies[62].set_position( vector3_type(-0.324351,2.78951,10) );
data.m_bodies[62].set_orientation( quaternion_type(0.0638584,-0.0311633,0.268014,0.960791) );
data.m_bodies[63].set_position( vector3_type(-3.46873,-2.01044,11.25) );
data.m_bodies[63].set_orientation( quaternion_type(0.193356,-0.284959,-0.165159,0.924194) );
data.m_bodies[64].set_position( vector3_type(-3.33714,1.33781,2.5) );
data.m_bodies[64].set_orientation( quaternion_type(0.0784902,-0.759715,0.304559,0.569137) );
data.m_bodies[65].set_position( vector3_type(2.33808,1.01822,3.75) );
data.m_bodies[65].set_orientation( quaternion_type(-0.0673981,0.514396,0.224016,0.825028) );
data.m_bodies[66].set_position( vector3_type(2.52998,0.162236,5) );
data.m_bodies[66].set_orientation( quaternion_type(0.781383,0.281635,0.0180599,0.556594) );
data.m_bodies[67].set_position( vector3_type(2.57808,-3.13547,6.25) );
data.m_bodies[67].set_orientation( quaternion_type(-0.498117,0.299963,-0.364816,0.727194) );
data.m_bodies[68].set_position( vector3_type(-1.26041,1.52947,7.5) );
data.m_bodies[68].set_orientation( quaternion_type(0.759819,-0.105633,0.128181,0.628559) );
data.m_bodies[69].set_position( vector3_type(0.882717,-2.20917,8.75) );
data.m_bodies[69].set_orientation( quaternion_type(-0.745235,0.0649119,-0.162455,0.643444) );
data.m_bodies[70].set_position( vector3_type(2.5688,-2.7336,10) );
data.m_bodies[70].set_orientation( quaternion_type(-0.121986,0.238719,-0.254034,0.9293) );
data.m_bodies[71].set_position( vector3_type(1.77557,-1.61614,11.25) );
data.m_bodies[71].set_orientation( quaternion_type(0.961752,0.0422802,-0.0384839,0.267888) );
data.m_bodies[72].set_position( vector3_type(3.51341,-0.459365,2.5) );
data.m_bodies[72].set_orientation( quaternion_type(0.534729,0.684637,-0.0895136,0.48716) );
data.m_bodies[73].set_position( vector3_type(3.57738,-3.16306,3.75) );
data.m_bodies[73].set_orientation( quaternion_type(0.814192,0.342082,-0.302464,0.358589) );
data.m_bodies[74].set_position( vector3_type(-3.30467,-3.35862,5) );
data.m_bodies[74].set_orientation( quaternion_type(0.927322,-0.180023,-0.182963,0.272378) );
data.m_bodies[75].set_position( vector3_type(0.31312,-2.76876,6.25) );
data.m_bodies[75].set_orientation( quaternion_type(-0.115798,0.0454499,-0.401891,0.907198) );
data.m_bodies[76].set_position( vector3_type(1.27018,1.76214,7.5) );
data.m_bodies[76].set_orientation( quaternion_type(-0.734528,0.110386,0.153139,0.651791) );
data.m_bodies[77].set_position( vector3_type(0.618305,0.816553,8.75) );
data.m_bodies[77].set_orientation( quaternion_type(-0.354936,0.0656146,0.0866527,0.928551) );
data.m_bodies[78].set_position( vector3_type(-0.170293,2.77999,10) );
data.m_bodies[78].set_orientation( quaternion_type(-0.861687,-0.00832452,0.135896,0.488834) );
data.m_bodies[79].set_position( vector3_type(-0.355113,2.29365,11.25) );
data.m_bodies[79].set_orientation( quaternion_type(-0.847959,-0.0163866,0.10584,0.519129) );
data.m_bodies[80].set_position( vector3_type(-1.1879,-2.96213,2.5) );
data.m_bodies[80].set_orientation( quaternion_type(-0.833796,-0.161766,-0.403377,0.340445) );
data.m_bodies[81].set_position( vector3_type(-0.0323496,-0.906644,3.75) );
data.m_bodies[81].set_orientation( quaternion_type(-0.916636,-0.00335156,-0.0939321,0.388516) );
data.m_bodies[82].set_position( vector3_type(1.90594,-0.872951,5) );
data.m_bodies[82].set_orientation( quaternion_type(-0.895363,0.156554,-0.0717042,0.4107) );
data.m_bodies[83].set_position( vector3_type(1.49089,-2.3393,6.25) );
data.m_bodies[83].set_orientation( quaternion_type(-0.901841,0.0942047,-0.147813,0.394918) );
data.m_bodies[84].set_position( vector3_type(0.457167,-2.33442,7.5) );
data.m_bodies[84].set_orientation( quaternion_type(0.928751,0.0215391,-0.109985,0.353357) );
data.m_bodies[85].set_position( vector3_type(0.353404,0.734031,8.75) );
data.m_bodies[85].set_orientation( quaternion_type(-0.995687,0.0037308,0.00774897,0.0923715) );
data.m_bodies[86].set_position( vector3_type(-3.12546,-2.91842,10) );
data.m_bodies[86].set_orientation( quaternion_type(-0.853652,-0.149677,-0.139762,0.478897) );
data.m_bodies[87].set_position( vector3_type(-3.16355,-0.373669,11.25) );
data.m_bodies[87].set_orientation( quaternion_type(-0.782817,-0.168361,-0.0198862,0.598713) );
data.m_bodies[88].set_position( vector3_type(-2.96188,0.394665,2.5) );
data.m_bodies[88].set_orientation( quaternion_type(-0.876755,-0.36563,0.0487195,0.308612) );
data.m_bodies[89].set_position( vector3_type(-3.73144,3.50829,3.75) );
data.m_bodies[89].set_orientation( quaternion_type(0.764598,-0.378864,0.356207,0.380749) );
data.m_bodies[90].set_position( vector3_type(3.70238,-3.00436,5) );
data.m_bodies[90].set_orientation( quaternion_type(-0.990668,0.0730377,-0.0592677,0.098636) );
data.m_bodies[91].set_position( vector3_type(2.93332,1.6867,6.25) );
data.m_bodies[91].set_orientation( quaternion_type(0.947797,0.131608,0.0756766,0.280417) );
data.m_bodies[92].set_position( vector3_type(2.90426,3.42918,7.5) );
data.m_bodies[92].set_orientation( quaternion_type(-0.736023,0.224867,0.265509,0.580698) );
data.m_bodies[93].set_position( vector3_type(-1.02725,2.88888,8.75) );
data.m_bodies[93].set_orientation( quaternion_type(0.464419,-0.0981219,0.275942,0.835789) );
data.m_bodies[94].set_position( vector3_type(-0.630024,-2.82614,10) );
data.m_bodies[94].set_orientation( quaternion_type(0.889305,-0.0276751,-0.124144,0.439271) );
data.m_bodies[95].set_position( vector3_type(-3.70238,-0.45912,11.25) );
data.m_bodies[95].set_orientation( quaternion_type(-0.777479,-0.196454,-0.0243616,0.596942) );
data.m_bodies[96].set_position( vector3_type(-3.08029,-0.574847,2.5) );
data.m_bodies[96].set_orientation( quaternion_type(0.184318,-0.755261,-0.140947,0.612978) );
data.m_bodies[97].set_position( vector3_type(1.4904,1.05167,3.75) );
data.m_bodies[97].set_orientation( quaternion_type(-0.311551,0.339613,0.23964,0.854501) );
data.m_bodies[98].set_position( vector3_type(3.87548,2.87448,5) );
data.m_bodies[98].set_orientation( quaternion_type(0.908001,0.233676,0.173319,0.30148) );
data.m_bodies[99].set_position( vector3_type(-2.2873,0.0919218,6.25) );
data.m_bodies[99].set_orientation( quaternion_type(0.295106,-0.328339,0.0131953,0.89718) );
data.m_bodies[100].set_position( vector3_type(-0.535051,0.492325,7.5) );
data.m_bodies[100].set_orientation( quaternion_type(0.564204,-0.058626,0.0539445,0.821782) );
data.m_bodies[101].set_position( vector3_type(-0.388318,-0.123417,8.75) );
data.m_bodies[101].set_orientation( quaternion_type(-0.963106,-0.0119305,-0.0037918,0.268831) );
data.m_bodies[102].set_position( vector3_type(-2.76876,3.30857,10) );
data.m_bodies[102].set_orientation( quaternion_type(-0.281427,-0.243951,0.291513,0.881083) );
data.m_bodies[103].set_position( vector3_type(-2.77413,-1.55461,11.25) );
data.m_bodies[103].set_orientation( quaternion_type(0.653661,-0.179579,-0.100636,0.728252) );
data.m_bodies[104].set_position( vector3_type(-2.56441,-0.806543,2.5) );
data.m_bodies[104].set_orientation( quaternion_type(-0.833213,-0.386263,-0.121485,0.376561) );
data.m_bodies[105].set_position( vector3_type(-3.10764,1.94525,3.75) );
data.m_bodies[105].set_orientation( quaternion_type(0.999995,-0.00187482,0.00117356,0.00226235) );
data.m_bodies[106].set_position( vector3_type(-3.53392,-3.35984,5) );
data.m_bodies[106].set_orientation( quaternion_type(0.688897,-0.366777,-0.34871,0.518938) );
data.m_bodies[107].set_position( vector3_type(-0.848537,2.91012,6.25) );
data.m_bodies[107].set_orientation( quaternion_type(-0.153797,-0.120703,0.41396,0.889052) );
data.m_bodies[108].set_position( vector3_type(-2.75704,1.54485,7.5) );
data.m_bodies[108].set_orientation( quaternion_type(-0.107319,-0.336802,0.18872,0.916205) );
data.m_bodies[109].set_position( vector3_type(1.65423,3.5432,8.75) );
data.m_bodies[109].set_orientation( quaternion_type(0.00704688,0.172598,0.36969,0.912956) );
data.m_bodies[110].set_position( vector3_type(-3.37547,-1.0126,10) );
data.m_bodies[110].set_orientation( quaternion_type(0.965292,-0.0831459,-0.0249429,0.246324) );
data.m_bodies[111].set_position( vector3_type(3.06858,3.9978,11.25) );
data.m_bodies[111].set_orientation( quaternion_type(0.394576,0.228729,0.297993,0.838566) );
data.m_bodies[112].set_position( vector3_type(-2.18598,-3.9856,2.5) );
data.m_bodies[112].set_orientation( quaternion_type(0.558094,-0.349642,-0.637485,0.399868) );
data.m_bodies[113].set_position( vector3_type(-0.0155034,3.65893,3.75) );
data.m_bodies[113].set_orientation( quaternion_type(0.970099,-0.000718186,0.169498,0.173717) );
data.m_bodies[114].set_position( vector3_type(-0.234016,-2.58003,5) );
data.m_bodies[114].set_orientation( quaternion_type(0.493454,-0.0361446,-0.398496,0.772268) );
data.m_bodies[115].set_position( vector3_type(0.821924,-0.576312,6.25) );
data.m_bodies[115].set_orientation( quaternion_type(-0.998118,0.00796236,-0.00558299,0.0605466) );
data.m_bodies[116].set_position( vector3_type(3.59178,2.52559,7.5) );
data.m_bodies[116].set_orientation( quaternion_type(0.396337,0.379441,0.266807,0.79231) );
data.m_bodies[117].set_position( vector3_type(0.73574,-3.01608,8.75) );
data.m_bodies[117].set_orientation( quaternion_type(-0.25631,0.0765974,-0.314002,0.910956) );
data.m_bodies[118].set_position( vector3_type(3.96631,-1.03775,10) );
data.m_bodies[118].set_orientation( quaternion_type(-0.654386,0.2775,-0.0726056,0.699643) );
data.m_bodies[119].set_position( vector3_type(-2.47774,3.10642,11.25) );
data.m_bodies[119].set_orientation( quaternion_type(-0.888514,-0.0952892,0.119467,0.432654) );
data.m_bodies[120].set_position( vector3_type(-2.46602,1.4528,2.5) );
data.m_bodies[120].set_orientation( quaternion_type(0.171487,-0.639297,0.376629,0.648107) );
data.m_bodies[121].set_position( vector3_type(0.526261,-1.08634,3.75) );
data.m_bodies[121].set_orientation( quaternion_type(0.901177,0.0579031,-0.119527,0.412603) );
data.m_bodies[122].set_position( vector3_type(0.315806,-0.40907,5) );
data.m_bodies[122].set_orientation( quaternion_type(-0.139571,0.0622115,-0.0805839,0.984965) );
data.m_bodies[123].set_position( vector3_type(0.546037,-1.83319,6.25) );
data.m_bodies[123].set_orientation( quaternion_type(-0.805929,0.0494574,-0.166041,0.566094) );
data.m_bodies[124].set_position( vector3_type(2.11469,-1.37565,7.5) );
data.m_bodies[124].set_orientation( quaternion_type(-0.956267,0.0781677,-0.0508498,0.277231) );
data.m_bodies[125].set_position( vector3_type(-3.2595,-1.45476,8.75) );
data.m_bodies[125].set_orientation( quaternion_type(0.571544,-0.283031,-0.12632,0.759786) );
data.m_bodies[126].set_position( vector3_type(1.92181,1.23551,10) );
data.m_bodies[126].set_orientation( quaternion_type(-0.753992,0.12307,0.07912,0.640383) );
data.m_bodies[127].set_position( vector3_type(0.535051,1.92938,11.25) );
data.m_bodies[127].set_orientation( quaternion_type(0.913699,0.019029,0.0686182,0.400105) );
data.m_bodies[128].set_position( vector3_type(-3.67675,2.32221,2.5) );
data.m_bodies[128].set_orientation( quaternion_type(-0.930412,-0.268653,0.16968,0.18267) );
data.m_bodies[129].set_position( vector3_type(0.527726,-0.319712,3.75) );
data.m_bodies[129].set_orientation( quaternion_type(0.873181,0.0676798,-0.0410024,0.48093) );
data.m_bodies[130].set_position( vector3_type(0.9064,-3.22068,5) );
data.m_bodies[130].set_orientation( quaternion_type(0.780545,0.0941779,-0.334639,0.519516) );
data.m_bodies[131].set_position( vector3_type(0.396374,2.92209,6.25) );
data.m_bodies[131].set_orientation( quaternion_type(-0.726739,0.0393989,0.29045,0.621239) );
data.m_bodies[132].set_position( vector3_type(0.665426,0.280648,7.5) );
data.m_bodies[132].set_orientation( quaternion_type(0.355742,0.0825377,0.0348109,0.930281) );
data.m_bodies[133].set_position( vector3_type(1.80364,-2.17743,8.75) );
data.m_bodies[133].set_orientation( quaternion_type(0.111321,0.194925,-0.235322,0.94564) );
data.m_bodies[134].set_position( vector3_type(-2.59249,3.05905,10) );
data.m_bodies[134].set_orientation( quaternion_type(-0.388489,-0.221724,0.261628,0.855258) );
data.m_bodies[135].set_position( vector3_type(-3.69652,1.87518,11.25) );
data.m_bodies[135].set_orientation( quaternion_type(0.561907,-0.255042,0.129378,0.776193) );
data.m_bodies[136].set_position( vector3_type(2.16108,0.687643,2.5) );
data.m_bodies[136].set_orientation( quaternion_type(0.186579,0.629007,0.200147,0.727654) );
data.m_bodies[137].set_position( vector3_type(-1.7514,-2.82076,3.75) );
data.m_bodies[137].set_orientation( quaternion_type(-0.727594,-0.239879,-0.386345,0.513617) );
data.m_bodies[138].set_position( vector3_type(-3.42112,-2.13715,5) );
data.m_bodies[138].set_orientation( quaternion_type(-0.866225,-0.266081,-0.166218,0.388879) );
data.m_bodies[139].set_position( vector3_type(-1.30485,-3.27732,6.25) );
data.m_bodies[139].set_orientation( quaternion_type(0.650244,-0.13813,-0.346934,0.661619) );
data.m_bodies[140].set_position( vector3_type(-0.65273,1.184,7.5) );
data.m_bodies[140].set_orientation( quaternion_type(0.795651,-0.0518831,0.0941114,0.596147) );
data.m_bodies[141].set_position( vector3_type(0.309702,3.66137,8.75) );
data.m_bodies[141].set_orientation( quaternion_type(-0.0262193,0.0326226,0.385672,0.921686) );
data.m_bodies[142].set_position( vector3_type(-2.41035,0.934233,10) );
data.m_bodies[142].set_orientation( quaternion_type(-0.900886,-0.101293,0.0392604,0.420242) );
data.m_bodies[143].set_position( vector3_type(-2.72457,-0.398328,11.25) );
data.m_bodies[143].set_orientation( quaternion_type(0.930622,-0.0860934,-0.0125867,0.355487) );
data.m_bodies[144].set_position( vector3_type(-0.724509,-2.13642,2.5) );
data.m_bodies[144].set_orientation( quaternion_type(0.948041,-0.0684514,-0.201848,0.236199) );
data.m_bodies[145].set_position( vector3_type(-3.80151,1.88177,3.75) );
data.m_bodies[145].set_orientation( quaternion_type(0.782041,-0.41846,0.207141,0.412791) );
data.m_bodies[146].set_position( vector3_type(-1.37541,2.96847,5) );
data.m_bodies[146].set_orientation( quaternion_type(0.990941,-0.0309137,0.0667195,0.11238) );
data.m_bodies[147].set_position( vector3_type(-1.98553,-2.14789,6.25) );
data.m_bodies[147].set_orientation( quaternion_type(0.266767,-0.277306,-0.299982,0.872896) );
data.m_bodies[148].set_position( vector3_type(-1.48625,2.27363,7.5) );
data.m_bodies[148].set_orientation( quaternion_type(-0.976678,-0.0400053,0.061199,0.201877) );
data.m_bodies[149].set_position( vector3_type(-3.10666,-3.84277,8.75) );
data.m_bodies[149].set_orientation( quaternion_type(-0.142703,-0.30599,-0.378493,0.861829) );
data.m_bodies[150].set_position( vector3_type(1.88397,-1.38639,10) );
data.m_bodies[150].set_orientation( quaternion_type(0.839051,0.0998039,-0.0734448,0.529754) );
data.m_bodies[151].set_position( vector3_type(-3.85229,3.0173,11.25) );
data.m_bodies[151].set_orientation( quaternion_type(-0.991133,-0.0417237,0.0326801,0.121847) );
data.m_bodies[152].set_position( vector3_type(-3.85498,2.41426,2.5) );
data.m_bodies[152].set_orientation( quaternion_type(0.999922,-0.00925704,0.00579742,0.00600331) );
data.m_bodies[153].set_position( vector3_type(1.13761,3.50804,3.75) );
data.m_bodies[153].set_orientation( quaternion_type(0.118179,0.214778,0.662309,0.707991) );
data.m_bodies[154].set_position( vector3_type(2.58419,3.4724,5) );
data.m_bodies[154].set_orientation( quaternion_type(-0.432371,0.352344,0.473448,0.68173) );
data.m_bodies[155].set_position( vector3_type(-2.82321,3.8435,6.25) );
data.m_bodies[155].set_orientation( quaternion_type(-0.952955,-0.108851,0.148189,0.240973) );
data.m_bodies[156].set_position( vector3_type(-1.23136,3.73901,7.5) );
data.m_bodies[156].set_orientation( quaternion_type(0.663043,-0.108824,0.330442,0.662827) );
data.m_bodies[157].set_position( vector3_type(0.440077,-1.34367,8.75) );
data.m_bodies[157].set_orientation( quaternion_type(0.481483,0.0435164,-0.132867,0.865232) );
data.m_bodies[158].set_position( vector3_type(1.95648,-0.900784,10) );
data.m_bodies[158].set_orientation( quaternion_type(0.055532,0.190967,-0.0879231,0.976072) );
data.m_bodies[159].set_position( vector3_type(-2.13202,-0.719871,11.25) );
data.m_bodies[159].set_orientation( quaternion_type(-0.927322,-0.0695502,-0.0234834,0.366994) );
data.m_bodies[160].set_position( vector3_type(1.4987,-1.84588,2.5) );
data.m_bodies[160].set_orientation( quaternion_type(0.205101,0.425156,-0.523644,0.709206) );
data.m_bodies[161].set_position( vector3_type(0.0753197,3.02878,3.75) );
data.m_bodies[161].set_orientation( quaternion_type(0.95511,0.00462844,0.18612,0.23044) );
data.m_bodies[162].set_position( vector3_type(-3.7517,-1.99799,5) );
data.m_bodies[162].set_orientation( quaternion_type(-0.270276,-0.550406,-0.293121,0.733542) );
data.m_bodies[163].set_position( vector3_type(-0.74575,-0.520157,6.25) );
data.m_bodies[163].set_orientation( quaternion_type(0.930342,-0.0432982,-0.0302003,0.362874) );
data.m_bodies[164].set_position( vector3_type(0.965484,-2.98044,7.5) );
data.m_bodies[164].set_orientation( quaternion_type(0.959434,0.0334892,-0.103381,0.260148) );
data.m_bodies[165].set_position( vector3_type(0.0836207,-2.2458,8.75) );
data.m_bodies[165].set_orientation( quaternion_type(0.556741,0.00768902,-0.206504,0.804573) );
data.m_bodies[166].set_position( vector3_type(-2.27705,-3.35765,10) );
data.m_bodies[166].set_orientation( quaternion_type(-0.786443,-0.130328,-0.192177,0.572355) );
data.m_bodies[167].set_position( vector3_type(3.63353,2.7983,11.25) );
data.m_bodies[167].set_orientation( quaternion_type(-0.277561,0.287332,0.221284,0.889626) );
data.m_bodies[168].set_position( vector3_type(0.314585,0.147832,2.5) );
data.m_bodies[168].set_orientation( quaternion_type(-0.878364,0.0595745,0.0279956,0.473438) );
data.m_bodies[169].set_position( vector3_type(0.271371,-3.33518,3.75) );
data.m_bodies[169].set_orientation( quaternion_type(0.417705,0.0490585,-0.602936,0.677926) );
data.m_bodies[170].set_position( vector3_type(-0.341197,0.434462,5) );
data.m_bodies[170].set_orientation( quaternion_type(-0.999381,-0.00238611,0.00303834,0.0349667) );
data.m_bodies[171].set_position( vector3_type(3.56932,-3.20554,6.25) );
data.m_bodies[171].set_orientation( quaternion_type(0.94703,0.145485,-0.130658,0.25475) );
data.m_bodies[172].set_position( vector3_type(-1.79266,-3.19529,7.5) );
data.m_bodies[172].set_orientation( quaternion_type(0.242755,-0.208341,-0.371353,0.871643) );
data.m_bodies[173].set_position( vector3_type(-2.79049,-0.703757,8.75) );
data.m_bodies[173].set_orientation( quaternion_type(-0.11875,-0.300805,-0.0758624,0.943218) );
data.m_bodies[174].set_position( vector3_type(-2.65011,0.74575,10) );
data.m_bodies[174].set_orientation( quaternion_type(0.612637,-0.201942,0.0568273,0.762015) );
data.m_bodies[175].set_position( vector3_type(2.89108,-0.769677,11.25) );
data.m_bodies[175].set_orientation( quaternion_type(0.131877,0.246184,-0.0655402,0.95797) );
data.m_bodies[176].set_position( vector3_type(1.82122,-1.2902,2.5) );
data.m_bodies[176].set_orientation( quaternion_type(-0.859342,0.277911,-0.196879,0.38149) );
data.m_bodies[177].set_position( vector3_type(-2.76461,-0.112918,3.75) );
data.m_bodies[177].set_orientation( quaternion_type(0.86382,-0.298868,-0.0122071,0.405394) );
data.m_bodies[178].set_position( vector3_type(1.10636,-0.103397,5) );
data.m_bodies[178].set_orientation( quaternion_type(0.935247,0.0764634,-0.00714603,0.345564) );
data.m_bodies[179].set_position( vector3_type(-2.30634,3.07077,6.25) );
data.m_bodies[179].set_orientation( quaternion_type(-0.153986,-0.310653,0.413618,0.841845) );
data.m_bodies[180].set_position( vector3_type(-0.151738,1.03458,7.5) );
data.m_bodies[180].set_orientation( quaternion_type(0.175075,-0.0197284,0.134512,0.975124) );
data.m_bodies[181].set_position( vector3_type(-2.54805,-3.62133,8.75) );
data.m_bodies[181].set_orientation( quaternion_type(-0.7077,-0.183574,-0.260898,0.630392) );
data.m_bodies[182].set_position( vector3_type(1.25333,-3.83935,10) );
data.m_bodies[182].set_orientation( quaternion_type(0.497119,0.100836,-0.308892,0.804544) );
data.m_bodies[183].set_position( vector3_type(-2.66182,1.48405,11.25) );
data.m_bodies[183].set_orientation( quaternion_type(-0.0150041,-0.22835,0.127312,0.965103) );
data.m_bodies[184].set_position( vector3_type(-0.503067,-0.595843,2.5) );
data.m_bodies[184].set_orientation( quaternion_type(0.8801,-0.0912062,-0.108027,0.45325) );
data.m_bodies[185].set_position( vector3_type(-1.27238,-0.584124,3.75) );
data.m_bodies[185].set_orientation( quaternion_type(0.974316,-0.0715792,-0.0328606,0.210961) );
data.m_bodies[186].set_position( vector3_type(-2.86837,0.765282,5) );
data.m_bodies[186].set_orientation( quaternion_type(0.337577,-0.464322,0.123881,0.809383) );
data.m_bodies[187].set_position( vector3_type(-2.54976,-3.15842,6.25) );
data.m_bodies[187].set_orientation( quaternion_type(-0.81785,-0.196876,-0.243873,0.482584) );
data.m_bodies[188].set_position( vector3_type(-0.508683,-1.10245,7.5) );
data.m_bodies[188].set_orientation( quaternion_type(0.0149083,-0.0669452,-0.145088,0.987039) );
data.m_bodies[189].set_position( vector3_type(2.69649,1.34684,8.75) );
data.m_bodies[189].set_orientation( quaternion_type(0.48702,0.254478,0.127107,0.82577) );
data.m_bodies[190].set_position( vector3_type(2.09882,-1.11026,10) );
data.m_bodies[190].set_orientation( quaternion_type(0.239219,0.198276,-0.104887,0.944701) );
data.m_bodies[191].set_position( vector3_type(0.922269,1.71795,11.25) );
data.m_bodies[191].set_orientation( quaternion_type(0.284646,0.0774338,0.144239,0.944551) );
data.m_bodies[192].set_position( vector3_type(3.07077,-0.954253,2.5) );
data.m_bodies[192].set_orientation( quaternion_type(-0.690841,0.545084,-0.169387,0.443768) );
data.m_bodies[193].set_position( vector3_type(0.757714,1.22233,3.75) );
data.m_bodies[193].set_orientation( quaternion_type(0.606633,0.149981,0.241946,0.74227) );
data.m_bodies[194].set_position( vector3_type(0.526261,-1.33268,5) );
data.m_bodies[194].set_orientation( quaternion_type(0.32473,0.0956965,-0.242338,0.909211) );
data.m_bodies[195].set_position( vector3_type(-1.08878,-0.109745,6.25) );
data.m_bodies[195].set_orientation( quaternion_type(-0.926242,-0.0646789,-0.00651938,0.371282) );
data.m_bodies[196].set_position( vector3_type(-1.00967,2.83395,7.5) );
data.m_bodies[196].set_orientation( quaternion_type(0.975827,-0.0273065,0.0766438,0.202837) );
data.m_bodies[197].set_position( vector3_type(3.07712,-2.20356,8.75) );
data.m_bodies[197].set_orientation( quaternion_type(0.463655,0.28598,-0.204793,0.813203) );
data.m_bodies[198].set_position( vector3_type(0.802393,0.184454,10) );
data.m_bodies[198].set_orientation( quaternion_type(0.781084,0.0499346,0.0114789,0.622321) );
data.m_bodies[199].set_position( vector3_type(-0.159551,3.34007,11.25) );
data.m_bodies[199].set_orientation( quaternion_type(-0.00675926,-0.0135942,0.284583,0.958531) );
data.m_bodies[200].set_position( vector3_type(-1.47917,1.69915,2.5) );
data.m_bodies[200].set_orientation( quaternion_type(-0.474662,-0.386869,0.444403,0.653861) );
data.m_bodies[201].set_position( vector3_type(3.58519,-1.47331,3.75) );
data.m_bodies[201].set_orientation( quaternion_type(-0.592978,0.535277,-0.219969,0.559883) );
data.m_bodies[202].set_position( vector3_type(0.330699,-3.52,5) );
data.m_bodies[202].set_orientation( quaternion_type(-0.911069,0.0222629,-0.23697,0.336604) );
data.m_bodies[203].set_position( vector3_type(2.39863,-2.74972,6.25) );
data.m_bodies[203].set_orientation( quaternion_type(0.224203,0.322994,-0.37027,0.84161) );
data.m_bodies[204].set_position( vector3_type(0.448866,0.532609,7.5) );
data.m_bodies[204].set_orientation( quaternion_type(-0.843147,0.0320418,0.0380197,0.535379) );
data.m_bodies[205].set_position( vector3_type(0.978668,-3.42674,8.75) );
data.m_bodies[205].set_orientation( quaternion_type(0.0721803,0.103316,-0.361753,0.923716) );
data.m_bodies[206].set_position( vector3_type(-1.46965,-1.45329,10) );
data.m_bodies[206].set_orientation( quaternion_type(-0.0748576,-0.143519,-0.141922,0.976554) );
data.m_bodies[207].set_position( vector3_type(0.539933,-2.99167,11.25) );
data.m_bodies[207].set_orientation( quaternion_type(-0.765277,0.0298242,-0.16525,0.621413) );
data.m_bodies[208].set_position( vector3_type(-3.92431,2.67843,2.5) );
data.m_bodies[208].set_orientation( quaternion_type(0.917477,-0.290762,0.198451,0.185231) );
data.m_bodies[209].set_position( vector3_type(3.71996,3.80004,3.75) );
data.m_bodies[209].set_orientation( quaternion_type(-0.861395,0.29038,0.296631,0.292725) );
data.m_bodies[210].set_position( vector3_type(1.83636,-3.67016,5) );
data.m_bodies[210].set_orientation( quaternion_type(-0.57052,0.233154,-0.465983,0.634827) );
data.m_bodies[211].set_position( vector3_type(-3.51537,1.2045,6.25) );
data.m_bodies[211].set_orientation( quaternion_type(-0.76367,-0.312126,0.106947,0.554931) );
data.m_bodies[212].set_position( vector3_type(-1.77996,2.93332,7.5) );
data.m_bodies[212].set_orientation( quaternion_type(-0.155028,-0.213207,0.351358,0.898363) );
data.m_bodies[213].set_position( vector3_type(3.03635,3.77319,8.75) );
data.m_bodies[213].set_orientation( quaternion_type(0.962744,0.0820996,0.102023,0.236591) );
data.m_bodies[214].set_position( vector3_type(-3.30125,-0.271371,10) );
data.m_bodies[214].set_orientation( quaternion_type(0.531809,-0.265391,-0.0218158,0.80391) );
data.m_bodies[215].set_position( vector3_type(-2.28193,0.631733,11.25) );
data.m_bodies[215].set_orientation( quaternion_type(-0.930377,-0.0727673,0.020145,0.358746) );
data.m_bodies[216].set_position( vector3_type(-1.78582,-3.45213,2.5) );
data.m_bodies[216].set_orientation( quaternion_type(-0.14479,-0.382361,-0.739134,0.535273) );
data.m_bodies[217].set_position( vector3_type(1.92157,0.762597,3.75) );
data.m_bodies[217].set_orientation( quaternion_type(-0.909322,0.186719,0.0741015,0.364388) );
data.m_bodies[218].set_position( vector3_type(2.58419,-0.405652,5) );
data.m_bodies[218].set_orientation( quaternion_type(-0.97549,0.100769,-0.0158182,0.194973) );
data.m_bodies[219].set_position( vector3_type(-2.00824,3.28636,6.25) );
data.m_bodies[219].set_orientation( quaternion_type(-0.948619,-0.0865573,0.141645,0.269382) );
data.m_bodies[220].set_position( vector3_type(2.90768,-3.77465,7.5) );
data.m_bodies[220].set_orientation( quaternion_type(0.762307,0.211794,-0.274943,0.546295) );
data.m_bodies[221].set_position( vector3_type(-3.86547,-3.25852,8.75) );
data.m_bodies[221].set_orientation( quaternion_type(0.825338,-0.21598,-0.182067,0.488899) );
data.m_bodies[222].set_position( vector3_type(-3.02658,0.732322,10) );
data.m_bodies[222].set_orientation( quaternion_type(-0.672818,-0.213784,0.0517279,0.706355) );
data.m_bodies[223].set_position( vector3_type(-1.67766,3.3679,11.25) );
data.m_bodies[223].set_orientation( quaternion_type(0.935992,-0.0497847,0.0999425,0.333844) );
data.m_bodies[224].set_position( vector3_type(-0.335337,1.12247,2.5) );
data.m_bodies[224].set_orientation( quaternion_type(0.166762,-0.11976,0.400871,0.892833) );
data.m_bodies[225].set_position( vector3_type(3.20017,0.385632,3.75) );
data.m_bodies[225].set_orientation( quaternion_type(-0.434359,0.582925,0.0702445,0.683079) );
data.m_bodies[226].set_position( vector3_type(0.364879,-1.09977,5) );
data.m_bodies[226].set_orientation( quaternion_type(-0.76731,0.0455895,-0.137409,0.624721) );
data.m_bodies[227].set_position( vector3_type(3.99243,-1.72137,6.25) );
data.m_bodies[227].set_orientation( quaternion_type(0.242848,0.508692,-0.219326,0.796338) );
data.m_bodies[228].set_position( vector3_type(1.36515,-2.15155,7.5) );
data.m_bodies[228].set_orientation( quaternion_type(-0.992998,0.0203594,-0.0320875,0.111852) );
data.m_bodies[229].set_position( vector3_type(3.40843,-3.92578,8.75) );
data.m_bodies[229].set_orientation( quaternion_type(0.129881,0.332046,-0.382445,0.852416) );
data.m_bodies[230].set_position( vector3_type(1.27067,-2.19062,10) );
data.m_bodies[230].set_orientation( quaternion_type(0.988907,0.0182965,-0.0315429,0.143991) );
data.m_bodies[231].set_position( vector3_type(-2.45039,-2.37519,11.25) );
data.m_bodies[231].set_orientation( quaternion_type(0.191569,-0.204573,-0.198296,0.939218) );
data.m_bodies[232].set_position( vector3_type(3.4055,1.46648,2.5) );
data.m_bodies[232].set_orientation( quaternion_type(-0.0911002,0.758365,0.326567,0.556721) );
data.m_bodies[233].set_position( vector3_type(0.815088,0.889554,3.75) );
data.m_bodies[233].set_orientation( quaternion_type(-0.502599,0.178879,0.195221,0.822973) );
data.m_bodies[234].set_position( vector3_type(1.21964,2.12445,5) );
data.m_bodies[234].set_orientation( quaternion_type(-0.314738,0.207919,0.362167,0.852376) );
data.m_bodies[235].set_position( vector3_type(-0.191778,0.215217,6.25) );
data.m_bodies[235].set_orientation( quaternion_type(-0.417618,-0.0278511,0.0312549,0.907658) );
data.m_bodies[236].set_position( vector3_type(-3.30393,0.491836,7.5) );
data.m_bodies[236].set_orientation( quaternion_type(0.992219,-0.0501039,0.00745866,0.113737) );
data.m_bodies[237].set_position( vector3_type(-3.75781,1.61711,8.75) );
data.m_bodies[237].set_orientation( quaternion_type(0.77784,-0.244498,0.105216,0.569311) );
data.m_bodies[238].set_position( vector3_type(3.7561,2.46236,10) );
data.m_bodies[238].set_orientation( quaternion_type(-0.584919,0.277911,0.182188,0.739893) );
data.m_bodies[239].set_position( vector3_type(2.84738,3.06149,11.25) );
data.m_bodies[239].set_orientation( quaternion_type(0.0992127,0.236076,0.253828,0.932736) );
data.m_bodies[240].set_position( vector3_type(-3.33518,-2.1059,2.5) );
data.m_bodies[240].set_orientation( quaternion_type(-0.445895,-0.639254,-0.403637,0.479175) );
data.m_bodies[241].set_position( vector3_type(0.276498,3.74535,3.75) );
data.m_bodies[241].set_orientation( quaternion_type(0.958755,0.014808,0.200585,0.200834) );
data.m_bodies[242].set_position( vector3_type(3.43968,0.393689,5) );
data.m_bodies[242].set_orientation( quaternion_type(-0.966803,0.144519,0.016541,0.210077) );
data.m_bodies[243].set_position( vector3_type(-0.987945,2.37886,6.25) );
data.m_bodies[243].set_orientation( quaternion_type(0.0415506,-0.14602,0.351598,0.923759) );
data.m_bodies[244].set_position( vector3_type(0.254036,-3.90503,7.5) );
data.m_bodies[244].set_orientation( quaternion_type(-0.939192,0.0103119,-0.158514,0.304442) );
data.m_bodies[245].set_position( vector3_type(-1.72893,0.465712,8.75) );
data.m_bodies[245].set_orientation( quaternion_type(0.165816,-0.190901,0.0514219,0.966135) );
data.m_bodies[246].set_position( vector3_type(-1.15421,1.4423,10) );
data.m_bodies[246].set_orientation( quaternion_type(0.624988,-0.0886025,0.110718,0.767647) );
data.m_bodies[247].set_position( vector3_type(1.91278,2.58541,11.25) );
data.m_bodies[247].set_orientation( quaternion_type(0.0772475,0.162988,0.220302,0.958611) );
data.m_bodies[248].set_position( vector3_type(-1.07804,-2.02997,2.5) );
data.m_bodies[248].set_orientation( quaternion_type(-0.828626,-0.177705,-0.334622,0.412103) );
data.m_bodies[249].set_position( vector3_type(3.34422,-2.32685,3.75) );
data.m_bodies[249].set_orientation( quaternion_type(-0.652136,0.45786,-0.318571,0.513416) );
real_type e_n = 0.1;
data.m_gravity.set_acceleration(vector3_type(0,0,-9.81));
data.m_simulator.init(data.m_configuration);
material_type * default_material = data.m_library.default_material();
default_material->set_friction_coefficient(.4);
default_material->normal_restitution() = e_n;
data.m_configuration.set_material_library(data.m_library);
data.m_simulator.get_stepper()->get_solver()->set_max_iterations(10);
data.m_simulator.get_stepper()->warm_starting() = false;
data.m_simulator.get_stepper()->use_stabilization() = true;
data.m_simulator.get_stepper()->use_friction() = true;
data.m_simulator.get_stepper()->use_bounce() = true;
}
|
hnthh/foodgram-project-react | backend/recipes/models/recipe_ingredient.py | from config.models import DefaultModel, models
from config.validators import GteMinValueValidator
from django.core.validators import MaxValueValidator
class RecipeIngredient(DefaultModel):
ingredient = models.ForeignKey(
'ingredients.Ingredient',
on_delete=models.CASCADE,
verbose_name='ингредиент',
)
recipe = models.ForeignKey(
'recipes.Recipe',
on_delete=models.CASCADE,
verbose_name='рецепт',
)
amount = models.DecimalField(
'количество',
decimal_places=1,
max_digits=5,
validators=[
GteMinValueValidator(
0,
'Введите число больше нуля или удалите ингредиент.',
),
MaxValueValidator(5000, 'Это ну оооочень много!'),
],
)
class Meta:
verbose_name = 'ингредиент'
verbose_name_plural = 'ингредиенты'
default_related_name = 'recipeingredients'
constraints = (
models.CheckConstraint(
name='amount_gt_0',
check=models.Q(amount__gt=0),
),
models.CheckConstraint(
name='amount_lt_5000',
check=models.Q(amount__lt=5000),
),
models.UniqueConstraint(
fields=('recipe', 'ingredient'),
name='unique_recipe_ingredient',
),
)
def __str__(self):
return f'{self.amount} / {self.ingredient}'
|
Group4-ProjectCourse/MySport-mobile | app/src/main/java/com/mysport/mysport_mobile/MainActivity.java | <filename>app/src/main/java/com/mysport/mysport_mobile/MainActivity.java
package com.mysport.mysport_mobile;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import com.bumptech.glide.Glide;
import com.facebook.login.LoginManager;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.mysport.mysport_mobile.activities.authentication.LoginActivity;
import com.mysport.mysport_mobile.enums.TransactionAction;
import com.mysport.mysport_mobile.events.OnFragmentSendDataListener;
import com.mysport.mysport_mobile.forum.ForumList;
import com.mysport.mysport_mobile.fragments.ProfileFragment;
import com.mysport.mysport_mobile.fragments.calendar.DayViewFragment;
import com.mysport.mysport_mobile.fragments.calendar.MonthViewFragment;
import com.mysport.mysport_mobile.fragments.chat.ChatFragment;
import com.mysport.mysport_mobile.fragments.settings.SettingsFragment;
import com.mysport.mysport_mobile.language.LanguageManager;
import com.mysport.mysport_mobile.models.MongoActivity;
import com.mysport.mysport_mobile.utils.CalendarUtils;
import java.util.Calendar;
import de.hdodenhof.circleimageview.CircleImageView;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener,
OnFragmentSendDataListener<MongoActivity> {
private DayViewFragment dayViewFragment;
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private Toolbar toolbar;
private Button viewOption;
private int currentId;
private FirebaseAuth mAuth;
private LanguageManager languageManager;
private TextView name;
private CircleImageView circleImageView;
private final String TAG = "Chat";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//getTheme().applyStyle(R.style.ThemePurple, true);
setContentView(R.layout.activity_main);
// AppSettings appSettings=new AppSettings.AppSettingsBuilder().subscribePresenceForAllUsers().setRegion(AppConfig.REGION).build();
//
// CometChat.init(this, AppConfig.APP_ID,appSettings, new CometChat.CallbackListener<String>() {
// @Override
// public void onSuccess(String successMessage) {
// Log.d(TAG, "Initialization completed successfully");
// }
// @Override
// public void onError(CometChatException e) {
// Log.d(TAG, "Initialization failed with exception: " + e.getMessage());
// }
// });
//android notification
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//NotificationChannel channel = new NotificationChannel("My notification", "My notification", IMPORTANCE_DEFAULT)
NotificationChannel channel = new NotificationChannel("MS_Notification", "MySport Notification", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
//hooks
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
viewOption = findViewById(R.id.nav_overflow_menu_item);
toolbar = findViewById(R.id.toolbar);
//tool bar
setSupportActionBar(toolbar);
//nav drawer menu
//Hide or show items
Menu menu = navigationView.getMenu();
menu.findItem(R.id.nav_login).setVisible(false);
//menu.findItem(R.id.nav_logout).setVisible(false);
//menu.findItem(R.id.nav_profile).setVisible(false); //If unlogged
//find header view
View headerView = navigationView.getHeaderView(0);
name = headerView.findViewById(R.id.textViewName);
circleImageView = headerView.findViewById(R.id.profileImage);
menu.findItem(R.id.nav_logout).setOnMenuItemClickListener(view -> {
App.setSession(null);
startActivity(new Intent(this, LoginActivity.class));
return false;
});
// menu.findItem(R.id.nav_profile).setOnMenuItemClickListener(view -> {
// handleFragment(TransactionAction.REPLACE, R.id.main_place_for_fragments, new ProfileFragment());
// return false;
// });
navigationView.bringToFront();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this,
drawerLayout,
toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
//user photo update
try {
if (App.getSession().getUser().getPhoto() != null) {
Glide.with(this).load(App.getSession().getUser().getPhoto()).into(circleImageView);
} else {
circleImageView.setImageDrawable(getResources().getDrawable(R.drawable.ronaldo));
}
} catch (NullPointerException nullPointerException) {
Log.e("MyLog", "Photo Uri is null!");
}
//load name from session
name.setText(App.getSession().getUser().getFirstname() + " " + App.getSession().getUser().getSurname());
System.out.println("Name: " + App.getSession().getUser().getFirstname());
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.nav_home);
//fragment transaction
handleFragment(TransactionAction.REPLACE, R.id.main_place_for_fragments, (dayViewFragment = new DayViewFragment(Calendar.getInstance())), "DAY_VIEW");
toolbar.setTitle(CalendarUtils.toSimpleString(Calendar.getInstance()));
//handleFragment(new MonthViewFragment(), "MONTH_VIEW");
viewOption.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Fragment fragment = getSupportFragmentManager().findFragmentByTag("DAY_VIEW");
// if(fragment != null && fragment.isVisible()) {
// handleFragment(TransactionAction.REPLACE, R.id.main_place_for_fragments, new MonthViewFragment(), "MONTH_VIEW");
// toolbar.setTitle("Calendar View");
// viewOption.setVisibility(View.INVISIBLE);
// viewOption.setClickable(false);
// }
handleFragment(TransactionAction.REPLACE, R.id.main_place_for_fragments, new MonthViewFragment(), "MONTH_VIEW");
toolbar.setTitle("Calendar View");
viewOption.setVisibility(View.INVISIBLE);
viewOption.setClickable(false);
}
});
}
public void handleFragment(int containerViewId, Fragment fragment) {
handleFragment(TransactionAction.REPLACE, containerViewId, fragment, null);
}
public void handleFragment(TransactionAction action, int containerViewId, Fragment fragment) {
handleFragment(action, containerViewId, fragment, null);
}
public void handleFragment(TransactionAction action, int containerViewId, Fragment fragment, String tag) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
switch (action) {
case ADD:
transaction.add(containerViewId, fragment, tag == null ? "" : tag);
break;
case REMOVE:
transaction.remove(fragment);
break;
case ATTACH:
transaction.attach(fragment);
break;
case DETACH:
transaction.detach(fragment);
break;
case HIDE:
transaction.hide(fragment);
break;
default:
transaction.replace(containerViewId, fragment, tag == null ? "" : tag);
}
transaction.commit();
}
@Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
int id = menuItem.getItemId();
if (id == navigationView.getCheckedItem().getItemId())
Toast.makeText(this, getString(R.string.menu_item_selected_again) + " - " + navigationView.getCheckedItem().getTitle(), Toast.LENGTH_SHORT).show();
else if (id == R.id.nav_home)
handleFragment(TransactionAction.REPLACE, R.id.main_place_for_fragments, new MonthViewFragment(), "MONTH_VIEW");
else if (id == R.id.nav_calendar)
handleFragment(TransactionAction.REPLACE, R.id.main_place_for_fragments, (dayViewFragment = new DayViewFragment(Calendar.getInstance())), "DAY_VIEW");
else if (id == R.id.nav_settings)
handleFragment(R.id.main_place_for_fragments, new SettingsFragment());
else if (id == R.id.nav_forum){
//handleFragment(R.id.main_place_for_fragments, new ForumFragment());
Intent intent = new Intent(MainActivity.this, ForumList.class);
intent.putExtra("username", "<EMAIL>");//current session
startActivity(intent);
}
else if (id == R.id.nav_profile)
handleFragment(R.id.main_place_for_fragments, new ProfileFragment());
else if (id == R.id.nav_share)
Toast.makeText(this, R.string.message_share_example, Toast.LENGTH_SHORT).show();
else if(id == R.id.nav_chat)
handleFragment(R.id.main_place_for_fragments, new ChatFragment());
// else if (id == R.id.nav_logout)
// FirebaseAuth.getInstance().signOut();
toolbar.setTitle(navigationView.getCheckedItem().getTitle());
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_logout) {
mAuth.signOut();
LoginManager.getInstance().logOut();
finish();
return true;
} else if (id == R.id.nav_overflow_menu_item) {
Toast.makeText(this, "Overflow menu item selected", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
public Toolbar getToolbar() {
return toolbar;
}
public Button getViewOption() {
return viewOption;
}
@Override
public void onSendData(MongoActivity sport) {
dayViewFragment.receiveItem(sport);
}
public DayViewFragment setDayViewFragment(DayViewFragment dayViewFragment) {
this.dayViewFragment = dayViewFragment;
return dayViewFragment;
}
public DayViewFragment getDayViewFragment() {
return dayViewFragment;
}
public void makeNotice(String title, String content) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "MS_Notification");
builder.setContentTitle(title);
builder.setContentText(content);
builder.setSmallIcon(R.drawable.ic_sports);
builder.setAutoCancel(true);
NotificationManagerCompat managerCompat = NotificationManagerCompat.from(this);
managerCompat.notify(1, builder.build());
}
// protected void attachBaseContext(Context base) {
// super.attachBaseContext(languageManager.setLocale(base));
// }
// @Override
// public void onConfigurationChanged(@NonNull @NotNull Configuration newConfig) {
// super.onConfigurationChanged(newConfig);
// languageManager.setLocale(this);
// }
//
// @Override
// protected void attachBaseContext(Context newBase) {
// super.attachBaseContext(LanguageManager.onAttach(newBase));
// }
} |
openshift/meta-cluster-api-operator | pkg/controllers/kubeconfig/generate.go | package kubeconfig
import (
"errors"
"k8s.io/client-go/tools/clientcmd/api"
"github.com/openshift/cluster-capi-operator/pkg/controllers"
)
type kubeconfigOptions struct {
token []byte
caCert []byte
apiServerEnpoint string
clusterName string
}
func generateKubeconfig(options kubeconfigOptions) (*api.Config, error) {
if len(options.token) == 0 {
return nil, errors.New("token can't be empty")
}
if len(options.caCert) == 0 {
return nil, errors.New("ca cert can't be empty")
}
if options.apiServerEnpoint == "" {
return nil, errors.New("api server endpoint can't be empty")
}
if options.clusterName == "" {
return nil, errors.New("cluster name can't be empty")
}
userName := "cluster-capi-operator"
kubeconfig := &api.Config{
Clusters: map[string]*api.Cluster{
options.clusterName: {
Server: options.apiServerEnpoint,
CertificateAuthorityData: options.caCert,
},
},
Contexts: map[string]*api.Context{
options.clusterName: {
Cluster: options.clusterName,
AuthInfo: userName,
Namespace: controllers.DefaultManagedNamespace,
},
},
AuthInfos: map[string]*api.AuthInfo{
userName: {
Token: string(options.token),
},
},
CurrentContext: options.clusterName,
}
return kubeconfig, nil
}
|
G10DRAS/kalliope | kalliope/core/Models/Resources.py |
class Resources(object):
"""
"""
def __init__(self, neuron_folder=None, stt_folder=None, tts_folder=None, trigger_folder=None):
self.neuron_folder = neuron_folder
self.stt_folder = stt_folder
self.tts_folder = tts_folder
self.trigger_folder = trigger_folder
def __str__(self):
return "%s: neuron_folder: %s, stt_folder: %s, tts_folder: %s, trigger_folder: %s" % (self.__class__.__name__,
self.neuron_folder,
self.stt_folder,
self.tts_folder,
self.trigger_folder)
def serialize(self):
"""
This method allows to serialize in a proper way this object
:return: A dict of order
:rtype: Dict
"""
return {
'neuron_folder': self.neuron_folder,
'stt_folder': self.stt_folder,
'tts_folder': self.tts_folder,
'trigger_folder': self.trigger_folder
}
def __eq__(self, other):
"""
This is used to compare 2 objects
:param other:
:return:
"""
return self.__dict__ == other.__dict__
|
Crymlll/darma-bangsa-app | src/components/Konseling/KonselingIcon.js | import React from 'react'
import { View, Text } from 'react-native'
import SimpleLineIcons from 'react-native-vector-icons/SimpleLineIcons'
import {konselingIconStyle} from '../Styles/konselingStyle'
function KonselingIcon() {
return (
<View style={ konselingIconStyle.box }>
<SimpleLineIcons name="graduation" style={konselingIconStyle.Icon}/>
<Text style={konselingIconStyle.text}>Konseling</Text>
</View>
)
}
export default KonselingIcon |
souzamonteiro/maialexa | node_modules/maiascript-cli/src/MaiaCompiler.js | <gh_stars>0
/**
* @license
* Copyright 2020 <NAME>,
* <NAME>,
* <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.
*/
/**
* MaiaScript compiler class.
* @class
*/
function MaiaCompiler() {
init();
/**
* Creates the attributes of the class.
*/
function init() {
binaryExpression = ['operation',
'variableAssignment',
'logicalORExpression',
'logicalXORExpression',
'logicalANDExpression',
'bitwiseORExpression',
'bitwiseXORExpression',
'bitwiseANDExpression',
'equalityExpression',
'relationalExpression',
'shiftExpression',
'additiveExpression',
'powerExpression',
'multiplicativeExpression'];
statementCodeBlock = ['maiascript',
'namespace',
'function',
'local',
'if',
'do',
'while',
'for',
'foreach',
'try',
'catch',
'test'];
conditionalExpression = ['if',
'do',
'while',
'for',
'foreach',
'catch',
'test'];
operators = {'||': 'core.logicalOR',
'||||': 'core.logicalXOR',
'&&': 'core.logicalAND',
'|': 'core.bitwiseOR',
'|||': 'core.bitwiseXOR',
'&': 'core.bitwiseAND',
'==': 'core.equal',
'!=': 'core.different',
'<': 'core.LT',
'<=': 'core.LE',
'>=': 'core.GE',
'>': 'core.GT',
'<<': 'core.leftShift',
'>>': 'core.rightShift',
'+': 'core.add',
'-': 'core.sub',
'^': 'core.power',
'*': 'core.mul',
'/': 'core.div',
'%': 'core.mod',
'~': 'core.bitwiseNot',
'!': 'core.logicalNot'
};
}
/**
* Convert XML to JSON.
* @param {xml} xml - The XML data.
* @return {json} XML data converted to a JSON object.
*/
this.xmlToJson = function(xml)
{
try {
var obj = {};
if (xml.children.length > 0) {
for (var i = 0; i < xml.children.length; i++) {
var item = xml.children.item(i);
nodeName = item.nodeName;
if (typeof(obj[nodeName]) == 'undefined') {
obj[nodeName] = this.xmlToJson(item);
} else {
if (typeof(obj[nodeName].push) == 'undefined') {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(this.xmlToJson(item));
}
}
} else {
obj = xml.textContent;
}
return obj;
} catch (e) {
system.log(e.message);
}
}
/**
* Compiles the MaiaScript XML tree for Maia Internal Code (MIL).
* @param {xml} xml - The XML data.
* @param {string} itemName - Name of the item being analyzed.
* @return {json} XML data converted to a MIL object.
*/
this.xmlToMil = function(xml, itemName = '')
{
try {
var obj = {};
if (itemName == '') {
if (xml.children.length > 0) {
for (var i = 0; i < xml.children.length; i++) {
var item = xml.children.item(i);
nodeName = item.nodeName;
if (typeof(obj[nodeName]) == 'undefined') {
obj[nodeName] = this.xmlToMil(item, nodeName);
} else {
if (typeof(obj[nodeName].push) == 'undefined') {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(this.xmlToMil(item, nodeName));
}
}
} else {
obj = xml.textContent;
}
} else {
if (binaryExpression.includes(itemName)) {
if (xml.children.length > 1) {
for (var i = 0; i < xml.children.length; i++) {
var item = xml.children.item(i);
nodeName = item.nodeName;
if (nodeName != 'TOKEN') {
opName = 'op';
} else {
opName = nodeName;
}
if (typeof(obj[opName]) == 'undefined') {
obj[opName] = this.xmlToMil(item, nodeName);
} else {
if (typeof(obj[opName].push) == 'undefined') {
var old = obj[opName];
obj[opName] = [];
obj[opName].push(old);
}
obj[opName].push(this.xmlToMil(item, nodeName));
}
}
} else if (xml.children.length == 1) {
var item = xml.children.item(0);
nodeName = item.nodeName;
obj = this.xmlToMil(item, nodeName);
} else {
obj = xml.textContent;
}
} else {
if (xml.children.length > 0) {
for (var i = 0; i < xml.children.length; i++) {
var item = xml.children.item(i);
nodeName = item.nodeName;
if (typeof(obj[nodeName]) == 'undefined') {
obj[nodeName] = this.xmlToMil(item, nodeName);
} else {
if (typeof(obj[nodeName].push) == 'undefined') {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(this.xmlToMil(item, nodeName));
}
}
} else {
obj = xml.textContent;
}
}
}
return obj;
} catch (e) {
system.log(e.message);
}
}
/**
* Compiles a complex number to JSON.
* @param {string} text - The expression representing the complex number.
* @return {string} Number converted to JSON.
*/
this.parseComplexNumber = function(text) {
var complexNumber = {
'xml': '',
'text': ''
}
maiaScriptComplexNumber = {
'real': 0,
'imaginary': 0
}
function getXml (data) {
complexNumber.xml += data;
}
var s = new ComplexNumber.XmlSerializer(getXml, true);
var complexNumberParser = new ComplexNumber(text, s);
try {
complexNumberParser.parse_number();
} catch (pe) {
if (!(pe instanceof complexNumberParser.ParseException)) {
throw pe;
} else {
var parserError = complexNumberParser.getErrorMessage(pe);
alert(parserError);
throw parserError;
}
}
var parser = new DOMParser();
var xml = parser.parseFromString(complexNumber.xml,"text/xml");
var json = this.xmlToJson(xml);
if ('number' in json) {
var number = json['number'];
if ('complex' in number) {
var complex = number['complex'];
if ('imaginary' in complex) {
var imaginary = complex['imaginary'];
json.number.complex.imaginary = json.number.complex.imaginary.substring(0, json.number.complex.imaginary.length - 2);
}
}
if (typeof json.number.complex.real == 'undefined') {
json.number.complex.real = 0;
}
maiaScriptComplexNumber = {
'real': core.toNumber(json.number.complex.real),
'imaginary': core.toNumber(json.number.complex.imaginary)
}
}
complexNumber.text = JSON.stringify(maiaScriptComplexNumber);
return complexNumber.text;
}
/**
* Compiles the code in Maia Internal Language (MIL) for JavaScript.
* @param {json} mil - Code in Maia Internal Language (MIL).
* @param {string} parentNodeInfo - Parent node data.
* @param {boolean} isKernelFunction - Parent node is a kernel function.
* @return {string} MIL code converted to JavaScript.
*/
this.parse = function(mil, parentNodeInfo, isKernelFunction) {
var node = {};
var js = '';
if (typeof isKernelFunction == 'undefined') {
var isKernelFunction = false;
}
if ('maiascript' in mil) {
node = mil['maiascript'];
var nodeInfo = {
'parentNode': 'maiascript',
'childNode': '',
'terminalNode' : ''
};
parentNodeInfo.childNode = 'maiascript';
if (typeof node != 'undefined') {
js = this.parse(node, nodeInfo, isKernelFunction);
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
}
} else if ('expression' in mil) {
node = mil['expression'];
var nodeInfo = {
'parentNode': 'expression',
'childNode': '',
'terminalNode' : ''
};
parentNodeInfo.childNode = 'expression';
if (typeof node != 'undefined') {
if (Array.isArray(node)) {
for (var i = 0; i < node.length; i++) {
text = this.parse(node[i], nodeInfo, isKernelFunction);
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
if (statementCodeBlock.includes(parentNodeInfo.parentNode) && (nodeInfo.childNode != 'comment') && (nodeInfo.childNode != 'condition')) {
if (parentNodeInfo.parentNode == 'namespace') {
js += 'this.' + text + ';';
} else {
if (conditionalExpression.includes(parentNodeInfo.parentNode)) {
js += text;
} else {
js += text + ';';
}
}
} else {
js += text;
}
}
} else {
text = this.parse(node, nodeInfo, isKernelFunction);
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
if (statementCodeBlock.includes(parentNodeInfo.parentNode) && (nodeInfo.childNode != 'comment') && (nodeInfo.childNode != 'condition')) {
if (parentNodeInfo.parentNode == 'namespace') {
js += 'this.' + text + ';';
} else {
if (conditionalExpression.includes(parentNodeInfo.parentNode)) {
js += text;
} else {
js += text + ';';
}
}
} else {
js += text;
}
}
}
} else if ('statement' in mil) {
node = mil['statement'];
var nodeInfo = {
'parentNode': 'statement',
'childNode': '',
'terminalNode' : ''
};
parentNodeInfo.childNode = 'statement';
if (typeof node != 'undefined') {
js = this.parse(node, nodeInfo, isKernelFunction);
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
}
} else if ('namespace' in mil) {
node = mil['namespace'];
var nodeInfo = {
'parentNode': 'namespace',
'childNode': '',
'terminalNode' : ''
};
parentNodeInfo.childNode = 'namespace';
if (typeof node != 'undefined') {
if ('identifier' in node) {
var nodeIdentifier = {
'identifier': node['identifier']
};
var name = this.parse(nodeIdentifier, nodeInfo, isKernelFunction);
if ('expression' in node) {
var nodeExpression = {
'expression': node['expression']
};
var body = this.parse(nodeExpression, nodeInfo, isKernelFunction);
}
js = 'function ' + name + '_' + '() {' + body + '};' + name + ' = new ' + name + '_()' ;
}
}
} else if ('function' in mil) {
node = mil['function'];
var nodeInfo = {
'parentNode': 'function',
'childNode': '',
'terminalNode' : 'function'
};
parentNodeInfo.childNode = 'function';
if (typeof node != 'undefined') {
if ('identifier' in node) {
var nodeIdentifier = {
'identifier': node['identifier']
};
var name = this.parse(nodeIdentifier, nodeInfo, isKernelFunction);
if ('TOKEN' in node) {
var statement = node['TOKEN'][0];
if (statement == 'async') {
js += name + ' = async function ';
} else if (statement == 'constructor') {
nodeInfo.parentNode = 'namespace';
js += name + ' = function ';
} else {
js += name + ' = function ';
}
} else {
var statement = 'function';
js += name + ' = function ';
}
if ('arguments' in node) {
var nodeArguments = {
'arguments': node['arguments']
};
var args = this.parse(nodeArguments, nodeInfo, isKernelFunction);
js += '(' + args + ')';
} else {
js += '()';
}
if ('expression' in node) {
var nodeExpression = {
'expression': node['expression']
};
if (statement == 'kernel') {
var body = this.parse(nodeExpression, nodeInfo, true);
} else {
var body = this.parse(nodeExpression, nodeInfo, isKernelFunction);
}
js += ' {' + body + '}';
} else {
js += ' {}';
}
}
}
} else if ('local' in mil) {
node = mil['local'];
var nodeInfo = {
'parentNode': parentNodeInfo.parentNode,
'childNode': '',
'terminalNode' : ''
};
parentNodeInfo.childNode = 'local';
if (typeof node != 'undefined') {
if ('expression' in node) {
var expressionValue = this.parse(node, nodeInfo, isKernelFunction);
js += 'let ' + expressionValue;
}
}
} else if ('if' in mil) {
node = mil['if'];
var nodeInfo = {
'parentNode': 'if',
'childNode': '',
'terminalNode' : 'if'
};
parentNodeInfo.childNode = 'if';
if (typeof node != 'undefined') {
if ('expression' in node) {
var body = '';
var nodeExpression = node['expression'];
if (Array.isArray(nodeExpression)) {
var nodeCondition = {
'expression': nodeExpression[0]
};
var condition = this.parse(nodeCondition, nodeInfo, isKernelFunction);
for (var i = 1; i < nodeExpression.length; i++) {
var commandLine = nodeExpression[i];
var bodyExpression = {
'expression': commandLine
};
body += this.parse(bodyExpression, nodeInfo, isKernelFunction) + ';';
}
js += 'if (' + condition + ') {' + body + '}';
}
}
if ('elseif' in node) {
var body = '';
var nodeElseIf = node['elseif'];
if (Array.isArray(nodeElseIf)) {
for (var i = 0; i < nodeElseIf.length; i++) {
if ('expression' in nodeElseIf[i]) {
var nodeElseIfExpression = nodeElseIf[i]['expression'];
if (Array.isArray(nodeElseIfExpression)) {
var body = '';
var nodeExpression = nodeElseIfExpression[0];
var nodeCondition = {
'expression': nodeExpression
};
var condition = this.parse(nodeCondition, nodeInfo, isKernelFunction);
for (var j = 1; j < nodeElseIfExpression.length; j++) {
var commandLine = nodeElseIfExpression[j];
var bodyExpression = {
'expression': commandLine
};
body += this.parse(bodyExpression, nodeInfo, isKernelFunction) + ';';
}
}
js += ' else if (' + condition + ') {' + body + '}';
}
}
} else {
if ('expression' in nodeElseIf) {
var nodeElseIfExpression = nodeElseIf['expression'];
if (Array.isArray(nodeElseIfExpression)) {
var body = '';
var nodeExpression = nodeElseIfExpression[0];
var nodeCondition = {
'expression': nodeExpression
};
var condition = this.parse(nodeCondition, nodeInfo, isKernelFunction);
for (var j = 1; j < nodeElseIfExpression.length; j++) {
var commandLine = nodeElseIfExpression[j];
var bodyExpression = {
'expression': commandLine
};
body += this.parse(bodyExpression, nodeInfo, isKernelFunction) + ';';
}
}
js += ' else if (' + condition + ') {' + body + '}';
}
}
}
if ('else' in node) {
var body = '';
var nodeElse = node['else'];
if ('expression' in nodeElse) {
var nodeExpression = nodeElse['expression'];
if (Array.isArray(nodeExpression)) {
for (var i = 0; i < nodeExpression.length; i++) {
var commandLine = nodeExpression[i];
var bodyExpression = {
'expression': commandLine
};
body += this.parse(bodyExpression, nodeInfo, isKernelFunction) + ';';
}
} else {
var bodyExpression = {
'expression': nodeExpression
};
body += this.parse(bodyExpression, nodeInfo, isKernelFunction) + ';';
}
js += ' else {' + body + '}';
}
}
}
} else if ('do' in mil) {
node = mil['do'];
var nodeInfo = {
'parentNode': 'do',
'childNode': '',
'terminalNode' : ''
};
parentNodeInfo.childNode = 'do';
if (typeof node != 'undefined') {
if ('expression' in node) {
var body = '';
var nodeExpression = node['expression'];
if (Array.isArray(nodeExpression)) {
for (var i = 0; i < nodeExpression.length - 1; i++) {
var commandLine = nodeExpression[i];
var bodyExpression = {
'expression': commandLine
};
body += this.parse(bodyExpression, nodeInfo, isKernelFunction) + ';';
}
var nodeCondition = {
'expression': nodeExpression[nodeExpression.length - 1]
};
var condition = this.parse(nodeCondition, nodeInfo, isKernelFunction);
}
js += 'do {' + body + '} while (' + condition + ')';
}
}
} else if ('while' in mil) {
node = mil['while'];
var nodeInfo = {
'parentNode': 'while',
'childNode': '',
'terminalNode' : ''
};
parentNodeInfo.childNode = 'while';
if (typeof node != 'undefined') {
if ('expression' in node) {
var body = '';
var nodeExpression = node['expression'];
if (Array.isArray(nodeExpression)) {
var nodeCondition = {
'expression': nodeExpression[0]
};
var condition = this.parse(nodeCondition, nodeInfo, isKernelFunction);
for (var i = 1; i < nodeExpression.length; i++) {
var commandLine = nodeExpression[i];
var bodyExpression = {
'expression': commandLine
};
body += this.parse(bodyExpression, nodeInfo, isKernelFunction) + ';';
}
}
js += 'while (' + condition + ') {' + body + '}';
}
}
} else if ('for' in mil) {
node = mil['for'];
var nodeInfo = {
'parentNode': 'for',
'childNode': '',
'terminalNode' : 'for'
};
parentNodeInfo.childNode = 'for';
if (typeof node != 'undefined') {
if ('expression' in node) {
var body = '';
var nodeExpression = node['expression'];
if (Array.isArray(nodeExpression)) {
var nodeExpression = node['expression'];
var nodeBefore = {
'expression': nodeExpression[0]
};
var before = this.parse(nodeBefore, nodeInfo, isKernelFunction);
var nodeCondition = {
'expression': nodeExpression[1]
};
var condition = this.parse(nodeCondition, nodeInfo, isKernelFunction);
var nodeAfter = {
'expression': nodeExpression[2]
};
var after = this.parse(nodeAfter, nodeInfo, isKernelFunction);
for (var i = 3; i < nodeExpression.length; i++) {
var commandLine = nodeExpression[i];
var bodyExpression = {
'expression': commandLine
};
body += this.parse(bodyExpression, nodeInfo, isKernelFunction) + ';';
}
}
js += 'for (' + before + ';' + condition + ';' + after + ') {' + body + '}';
}
}
} else if ('foreach' in mil) {
node = mil['foreach'];
var nodeInfo = {
'parentNode': 'foreach',
'childNode': '',
'terminalNode' : 'foreach'
};
parentNodeInfo.childNode = 'foreach';
if (typeof node != 'undefined') {
if ('expression' in node) {
var body = '';
var nodeExpression = node['expression'];
if (Array.isArray(nodeExpression)) {
var nodeArray = {
'expression': nodeExpression[0]
};
var arrayName = this.parse(nodeArray, nodeInfo, isKernelFunction);
var nodeKeyVar = {
'expression': nodeExpression[1]
};
var keyVarName = this.parse(nodeKeyVar, nodeInfo, isKernelFunction);
var nodeValueVar = {
'expression': nodeExpression[2]
};
var valueVarName = this.parse(nodeValueVar, nodeInfo, isKernelFunction);
for (var i = 3; i < nodeExpression.length; i++) {
var commandLine = nodeExpression[i];
var bodyExpression = {
'expression': commandLine
};
body += this.parse(bodyExpression, nodeInfo, isKernelFunction) + ';';
}
}
js += 'for (' + keyVarName + ' in ' + arrayName + ') {var ' + valueVarName + ' = ' + arrayName + '[' + keyVarName + '];' + body + '}';
}
}
} else if ('try' in mil) {
node = mil['try'];
var nodeInfo = {
'parentNode': 'try',
'childNode': '',
'terminalNode' : 'try'
};
parentNodeInfo.childNode = 'try';
if (typeof node != 'undefined') {
if ('expression' in node) {
var nodeExpression = node['expression'];
var nodeBody = {
'expression': nodeExpression
};
var body = this.parse(nodeBody, nodeInfo, isKernelFunction);
js += 'try {' + body + '}';
}
if ('catch' in node) {
nodeInfo.parentNode = 'catch';
var nodeCatch = node['catch'];
if ('expression' in nodeCatch) {
var nodeExpression = nodeCatch['expression'];
if (Array.isArray(nodeExpression)) {
var _catch = '';
var nodeVar = {
'expression': nodeExpression[0]
};
var catchVar = this.parse(nodeVar, nodeInfo, isKernelFunction);
for (var i = 1; i < nodeExpression.length; i++) {
var commandLine = nodeExpression[i];
var bodyExpression = {
'expression': commandLine
};
_catch += this.parse(bodyExpression, nodeInfo, isKernelFunction) + ';';
}
}
js += ' catch (' + catchVar + ') {' + _catch + '}';
}
}
}
} else if ('test' in mil) {
node = mil['test'];
var nodeInfo = {
'parentNode': 'test',
'childNode': '',
'terminalNode' : 'test'
};
parentNodeInfo.childNode = 'test';
if (typeof node != 'undefined') {
if ('expression' in node) {
var nodeExpression = node['expression'];
if (Array.isArray(nodeExpression)) {
var _script = '';
var nodeTimes = {
'expression': nodeExpression[0]
};
var _times = this.parse(nodeTimes, nodeInfo, isKernelFunction);
var nodeValue = {
'expression': nodeExpression[1]
};
var _value = this.parse(nodeValue, nodeInfo, isKernelFunction);
var nodeTolerance = {
'expression': nodeExpression[2]
};
var _tolerance = this.parse(nodeTolerance, nodeInfo, isKernelFunction);
for (var i = 3; i < nodeExpression.length; i++) {
var commandLine = nodeExpression[i];
var bodyExpression = {
'expression': commandLine
};
_script += this.parse(bodyExpression, nodeInfo, isKernelFunction) + ';';
}
}
}
if ('catch' in node) {
nodeInfo.parentNode = 'catch';
var nodeCatch = node['catch'];
if ('expression' in nodeCatch) {
var nodeExpression = nodeCatch['expression'];
if (Array.isArray(nodeExpression)) {
var _catch = '';
var nodeVar = {
'expression': nodeExpression[0]
};
var catchVar = this.parse(nodeVar, nodeInfo, isKernelFunction);
for (var i = 1; i < nodeExpression.length; i++) {
var commandLine = nodeExpression[i];
var bodyExpression = {
'expression': commandLine
};
_catch += this.parse(bodyExpression, nodeInfo, isKernelFunction) + ';';
}
}
js += 'core.testScript(' + '\'' + _script + '\',' + _times + ',' + _value + ',' + _tolerance + ',\'' + 'var ' + catchVar + ' = core.testResult.obtained;' + _catch + '\');';
}
}
}
} else if ('break' in mil) {
node = mil['break'];
var nodeInfo = {
'parentNode': 'break',
'childNode': '',
'terminalNode' : 'break'
};
parentNodeInfo.childNode = 'break';
if (typeof node != 'undefined') {
js += 'break';
}
} else if ('continue' in mil) {
node = mil['continue'];
var nodeInfo = {
'parentNode': 'continue',
'childNode': '',
'terminalNode' : 'continue'
};
parentNodeInfo.childNode = 'continue';
if (typeof node != 'undefined') {
js += 'continue';
}
} else if ('return' in mil) {
node = mil['return'];
var nodeInfo = {
'parentNode': 'return',
'childNode': '',
'terminalNode' : 'return'
};
parentNodeInfo.childNode = 'return';
if (typeof node != 'undefined') {
if ('expression' in node) {
var returnValue = this.parse(node, nodeInfo, isKernelFunction);
js += 'return (' + returnValue + ')';
} else {
js += 'return';
}
}
} else if ('throw' in mil) {
node = mil['throw'];
var nodeInfo = {
'parentNode': 'throw',
'childNode': '',
'terminalNode' : 'throw'
};
parentNodeInfo.childNode = 'throw';
if (typeof node != 'undefined') {
if ('expression' in node) {
var returnValue = this.parse(node, nodeInfo, isKernelFunction);
js += 'throw (' + returnValue + ')';
} else {
js += 'throw ()';
}
}
} else if ('operation' in mil) {
node = mil['operation'];
var nodeInfo = {
'parentNode': 'operation',
'childNode': '',
'terminalNode' : ''
};
parentNodeInfo.childNode = 'operation';
if (typeof node != 'undefined') {
if ('op' in node) {
js += this.parse(node, nodeInfo, isKernelFunction);
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
} else {
if ('TOKEN' in node) {
var primary = node['primary'];
var right = this.parse(primary, nodeInfo, isKernelFunction);
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
var operator = node['TOKEN'];
if (isKernelFunction) {
js += operator + right;
} else {
js += operators[operator] + '(' + right + ')';
}
} else {
js += this.parse(node, nodeInfo, isKernelFunction);
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
}
}
}
} else if ('op' in mil) {
node = mil['op'];
var nodeInfo = {
'parentNode': 'op',
'childNode': '',
'terminalNode' : ''
};
parentNodeInfo.childNode = 'op';
if (typeof node != 'undefined') {
if (Array.isArray(node)) {
var nodeInfo = {
'parentNode': 'op',
'childNode': '',
'terminalNode' : ''
};
var left = this.parse(node[0], nodeInfo, isKernelFunction);
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
var nodeInfo = {
'parentNode': 'op',
'childNode': '',
'terminalNode' : ''
};
if ('TOKEN' in node[1]) {
var operator = node[1]['TOKEN'];
if ((operator == '!') || (operator == '~')) {
if (isKernelFunction) {
var right = operator + this.parse(node[1], nodeInfo, isKernelFunction);
} else {
var right = operators[operator] + '(' + this.parse(node[1], nodeInfo, isKernelFunction) + ')';
}
} else {
var right = this.parse(node[1], nodeInfo, isKernelFunction);
}
} else {
var right = this.parse(node[1], nodeInfo, isKernelFunction);
}
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
if ('TOKEN' in mil) {
var operator = mil['TOKEN'];
var j = 0;
if (Array.isArray(operator)) {
if (operator[j] == '=') {
parentNodeInfo.terminalNode = 'assignment';
js += left + '=' + right;
} else if (operator[j] == ':=') {
parentNodeInfo.terminalNode = 'assignment';
js += left + '= new ' + right;
} else if (operator[j] == '?=') {
parentNodeInfo.terminalNode = 'assignment';
js += left + '= await ' + right;
} else {
if (isKernelFunction) {
js += left + operator[j] + right;
} else {
js += operators[operator[j]] + '(' + left + ',' + right + ')';
}
}
j++;
for (var i = 2; i < node.length; i++) {
var right = this.parse(node[i], nodeInfo, isKernelFunction);
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
if (operator[j] == '=') {
parentNodeInfo.terminalNode = 'assignment';
js += '=' + right;
} else if (operator[j] == ':=') {
parentNodeInfo.terminalNode = 'assignment';
js += '= new ' + right;
} else if (operator[j] == '?=') {
parentNodeInfo.terminalNode = 'assignment';
js += '= await ' + right;
} else {
if (isKernelFunction) {
js = js + operator[j] + right;
} else {
js = operators[operator[j]] + '(' + js + ',' + right + ')';
}
}
j++;
}
} else {
if (operator == '=') {
parentNodeInfo.terminalNode = 'assignment';
js += left + '=' + right;
} else if (operator == ':=') {
parentNodeInfo.terminalNode = 'assignment';
js += left + '= new ' + right;
} else if (operator == '?=') {
parentNodeInfo.terminalNode = 'assignment';
js += left + '= await ' + right;
} else {
if (isKernelFunction) {
js += left + operator + right;
} else {
js += operators[operator] + '(' + left + ',' + right + ')';
}
}
}
}
} else {
var nodeInfo = {
'parentNode': 'op',
'childNode': '',
'terminalNode' : ''
};
js += this.parse(node, nodeInfo, isKernelFunction);
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
}
}
} else if ('primary' in mil) {
node = mil['primary'];
var nodeInfo = {
'parentNode': parentNodeInfo.childNode,
'childNode': '',
'terminalNode' : ''
};
parentNodeInfo.childNode = 'primary';
if (typeof node != 'undefined') {
if ('value' in node) {
var value = node['value'];
if ('TOKEN' in value) {
js = value['TOKEN'];
} else {
js = this.parse(node, nodeInfo, isKernelFunction);
}
} else {
js = this.parse(node, nodeInfo, isKernelFunction);
}
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
}
} else if ('member' in mil) {
node = mil['member'];
var nodeInfo = {
'parentNode': 'member',
'childNode': '',
'terminalNode' : ''
};
parentNodeInfo.childNode = 'member';
if (typeof node != 'undefined') {
if ('identifier' in node) {
js += this.parse(node, nodeInfo, isKernelFunction);
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
}
if ('arguments' in node) {
var nodeArguments = {
'matrixIndexes': node['arguments']
};
var args = this.parse(nodeArguments, nodeInfo, isKernelFunction);
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
var tokenType = node['TOKEN'];
if (typeof tokenType != 'undefined') {
if (tokenType.indexOf('(') != -1) {
js += '(' + args.replace(/;/g,',') + ')';
} else if (tokenType.indexOf('[') != -1) {
var arrayOfArgs = args.split(';');
if (Array.isArray(arrayOfArgs)) {
for (var i = 0; i < arrayOfArgs.length; i++) {
js += '[' + arrayOfArgs[i] + ']';
}
} else {
js += '[' + arrayOfArgs + ']';
}
}
}
} else {
var tokenType = node['TOKEN'];
if (typeof tokenType != 'undefined') {
if (tokenType.indexOf('(') != -1) {
js += '()';
} else if (tokenType.indexOf('[') != -1) {
js += '[]';
}
}
}
}
} else if ('identifier' in mil) {
node = mil['identifier'];
var nodeInfo = {
'parentNode': 'identifier',
'childNode': '',
'terminalNode' : ''
};
parentNodeInfo.childNode = 'identifier';
parentNodeInfo.terminalNode = 'identifier';
if (typeof node != 'undefined') {
if (Array.isArray(node)) {
for (var i = 0; i < node.length; i++) {
if (i < (node.length - 1)) {
js += node[i] + '.';
} else {
js += node[i];
}
}
} else {
js = node;
}
}
} else if ('arguments' in mil) {
node = mil['arguments'];
var nodeInfo = {
'parentNode': 'arguments',
'childNode': '',
'terminalNode' : ''
};
parentNodeInfo.childNode = 'arguments';
if (typeof node != 'undefined') {
if ('expression' in node) {
var nodeExpression = node['expression'];
if (Array.isArray(nodeExpression)) {
for (var i = 0; i < nodeExpression.length; i++) {
if (i < (nodeExpression.length - 1)) {
js += this.parse(nodeExpression[i], nodeInfo, isKernelFunction) + ',';
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
} else {
js += this.parse(nodeExpression[i], nodeInfo, isKernelFunction);
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
}
}
} else {
js += this.parse(nodeExpression, nodeInfo, isKernelFunction);
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
}
}
} else {
js = node;
}
} else if ('matrixIndexes' in mil) {
node = mil['matrixIndexes'];
var nodeInfo = {
'parentNode': 'arguments',
'childNode': '',
'terminalNode' : ''
};
parentNodeInfo.childNode = 'arguments';
if (typeof node != 'undefined') {
if ('expression' in node) {
var nodeExpression = node['expression'];
if (Array.isArray(nodeExpression)) {
for (var i = 0; i < nodeExpression.length; i++) {
if (i < (nodeExpression.length - 1)) {
js += this.parse(nodeExpression[i], nodeInfo, isKernelFunction) + ';';
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
} else {
js += this.parse(nodeExpression[i], nodeInfo, isKernelFunction);
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
}
}
} else {
js += this.parse(nodeExpression, nodeInfo, isKernelFunction);
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
}
}
} else {
js = node;
}
} else if ('value' in mil) {
node = mil['value'];
var nodeInfo = {
'parentNode': 'value',
'childNode': '',
'terminalNode' : ''
};
parentNodeInfo.childNode = 'value';
if (typeof node != 'undefined') {
js = this.parse(node, nodeInfo, isKernelFunction);
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
}
} else if ('real' in mil) {
node = mil['real'];
var nodeInfo = {
'parentNode': 'real',
'childNode': '',
'terminalNode' : ''
};
parentNodeInfo.childNode = 'real';
parentNodeInfo.terminalNode = 'real';
if (typeof node == 'string') {
js = node;
}
} else if ('complex' in mil) {
node = mil['complex'];
var nodeInfo = {
'parentNode': 'complex',
'childNode': '',
'terminalNode' : ''
};
parentNodeInfo.childNode = 'complex';
parentNodeInfo.terminalNode = 'complex';
if (typeof node == 'string') {
js = this.parseComplexNumber(node);
}
} else if ('string' in mil) {
node = mil['string'];
var nodeInfo = {
'parentNode': 'string',
'childNode': '',
'terminalNode' : ''
};
parentNodeInfo.childNode = 'string';
parentNodeInfo.terminalNode = 'string';
if (typeof node == 'string') {
js += node;
}
} else if ('array' in mil) {
node = mil['array'];
var nodeInfo = {
'parentNode': 'array',
'childNode': '',
'terminalNode' : ''
};
parentNodeInfo.childNode = 'array';
if (typeof node != 'undefined') {
if ('element' in node) {
var nodeElements = node['element'];
js += '{';
if (Array.isArray(nodeElements)) {
for (var i = 0; i < nodeElements.length; i++) {
var nodeElement = {
'element': nodeElements[i]
};
if (i < (nodeElements.length - 1)) {
js += this.parse(nodeElement, nodeInfo, isKernelFunction) + ',';
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
} else {
js += this.parse(nodeElement, nodeInfo, isKernelFunction);
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
}
}
} else {
var nodeElement = {
'element': nodeElements
};
js += this.parse(nodeElement, nodeInfo, isKernelFunction);
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
}
}
js += '}';
parentNodeInfo.terminalNode = 'array';
}
} else if ('element' in mil) {
node = mil['element'];
var nodeInfo = {
'parentNode': 'element',
'childNode': '',
'terminalNode' : ''
};
parentNodeInfo.childNode = 'element';
if (typeof node != 'undefined') {
if ('key' in node) {
var key = node['key'];
js += key['string'] + ': ';
}
if ('expression' in node) {
var nodeExpression = {
'expression': node['expression']
};
var expression = this.parse(nodeExpression, nodeInfo, isKernelFunction);
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
js += expression;
}
}
} else if ('matrix' in mil) {
node = mil['matrix'];
var nodeInfo = {
'parentNode': 'matrix',
'childNode': '',
'terminalNode' : ''
};
parentNodeInfo.childNode = 'matrix';
if (typeof node != 'undefined') {
if ('row' in node) {
var nodeRows = node['row'];
if (Array.isArray(nodeRows)) {
js += '[';
for (var i = 0; i < nodeRows.length; i++) {
var nodeRow = {
'row': nodeRows[i]
}
if (i < (nodeRows.length - 1)) {
js += this.parse(nodeRow, nodeInfo, isKernelFunction) + ',';
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
} else {
js += this.parse(nodeRow, nodeInfo, isKernelFunction);
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
}
}
js += ']';
} else {
var nodeRow = {
'row': nodeRows
}
js += this.parse(nodeRow, nodeInfo, isKernelFunction);
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
}
} else {
js += '[]';
}
}
} else if ('row' in mil) {
node = mil['row'];
var nodeInfo = {
'parentNode': 'row',
'childNode': '',
'terminalNode' : ''
};
parentNodeInfo.childNode = 'row';
if (typeof node != 'undefined') {
js += '[';
if (Array.isArray(node)) {
for (var i = 0; i < node.length; i++) {
if (i < (node.length - 1)) {
js += this.parse(node[i], nodeInfo, isKernelFunction) + ',';
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
} else {
js += this.parse(node[i], nodeInfo, isKernelFunction);
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
}
}
} else {
js += this.parse(node, nodeInfo, isKernelFunction);
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
}
js += ']';
}
} else if ('column' in mil) {
node = mil['column'];
var nodeInfo = {
'parentNode': 'column',
'childNode': '',
'terminalNode' : ''
};
parentNodeInfo.childNode = 'column';
if (typeof node != 'undefined') {
if (Array.isArray(node)) {
for (var i = 0; i < node.length; i++) {
if (i < (node.length - 1)) {
js += this.parse(node[i], nodeInfo, isKernelFunction) + ',';
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
} else {
js += this.parse(node[i], nodeInfo, isKernelFunction);
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
}
}
} else {
js += this.parse(node, nodeInfo, isKernelFunction);
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
}
}
} else if ('parenthesizedExpression' in mil) {
node = mil['parenthesizedExpression'];
var nodeInfo = {
'parentNode': 'parenthesizedExpression',
'childNode': '',
'terminalNode' : ''
};
parentNodeInfo.childNode = 'parenthesizedExpression';
if (typeof node != 'undefined') {
js = '(' + this.parse(node, nodeInfo, isKernelFunction) + ')';
parentNodeInfo.terminalNode = nodeInfo.terminalNode;
};
} else if ('comment' in mil) {
node = mil['comment'];
parentNodeInfo.childNode = 'comment';
parentNodeInfo.terminalNode = 'comment';
js = '';
} else if ('TOKEN' in mil) {
js = '';
}
return js;
}
/**
* Compiles the MaiaScript XML tree for JavaScript.
* @param {xml} xml - The XML data.
* @return {string} XML data converted to JavaScript.
*/
this.compile = function(xml) {
var nodeInfo = {
'parentNode': '',
'childNode': 'maiascript',
'terminalNode' : ''
};
var mil = {};
var js = "";
mil = this.xmlToMil(xml);
js = this.parse(mil, nodeInfo);
return js;
}
}
|
luxius-luminus/pai | deployment/paiLibrary/common/kubernetes_handler.py | <filename>deployment/paiLibrary/common/kubernetes_handler.py
# Copyright (c) Microsoft Corporation
# All rights reserved.
#
# MIT License
#
# 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.
import sys
import logging
import logging.config
import kubernetes.client
from kubernetes.client.rest import ApiException
from kubernetes import client, config, watch
logger = logging.getLogger(__name__)
def get_kubernetes_corev1api(PAI_KUBE_CONFIG_PATH, **kwargs):
config.load_kube_config(config_file=PAI_KUBE_CONFIG_PATH)
api_instance = kubernetes.client.CoreV1Api()
return api_instance
def list_all_nodes(PAI_KUBE_CONFIG_PATH, include_uninitialized = True):
api_instance = get_kubernetes_corev1api(PAI_KUBE_CONFIG_PATH = PAI_KUBE_CONFIG_PATH)
try:
api_response = api_instance.list_node(
include_uninitialized = include_uninitialized
)
node_list = api_response.items
except ApiException as e:
logger.error("Exception when calling kubernetes CoreV1Api->list_node: {0}".format(e))
sys.exit(1)
except Exception as e:
logger.error("Error happened when calling kubernetes CoreV1Api->list_node: {0}".format(e))
sys.exit(1)
if len(node_list) == 0:
return None
resp = dict()
for node in node_list:
node_name = node.metadata.name
"""
Example of address
[
{'address': '10.240.0.10', 'type': 'InternalIP'},
{'address': '10.240.0.10', 'type': 'Hostname'},
{'address': 'x.x.x.x', 'type': 'ExternalIP'}
]
before using this list, please check whether it exists or not.
"""
node_addresses = list()
for node_address_instance in node.status.addresses:
node_addresses.append(
{
"type": node_address_instance.type,
"address": node_address_instance.address
}
)
node_conditions = list()
for node_conditions_instance in node.status.conditions:
node_conditions.append(
{
"type": node_conditions_instance.type,
# type str, value True, False, Unknown
"status": node_conditions_instance.status
}
)
resp[node_name] = dict()
resp[node_name]["address"] = node_addresses
resp[node_name]["condition"] = node_conditions
return resp
def get_configmap(PAI_KUBE_CONFIG_DEFAULT_LOCATION, name, namespace = "default"):
api_instance = get_kubernetes_corev1api(PAI_KUBE_CONFIG_PATH=PAI_KUBE_CONFIG_DEFAULT_LOCATION)
exact = True
export = True
target_configmap_data = None
target_configmap_metadata = None
try:
api_response = api_instance.read_namespaced_config_map(name, namespace, exact=exact, export=export)
target_configmap_data = api_response.data
target_configmap_metadata = api_response.metadata
except ApiException as e:
if e.status == 404:
logger.info("Couldn't find configmap named {0}".format(name))
return None
else:
logger.error("Exception when calling CoreV1Api->read_namespaced_config_map: {0}".format(str(e)))
sys.exit(1)
ret = {
"metadata" : target_configmap_metadata,
"data" : target_configmap_data
}
return ret
def update_configmap(PAI_KUBE_CONFIG_DEFAULT_LOCATION, name, data_dict, namespace = "default"):
api_instance = get_kubernetes_corev1api(PAI_KUBE_CONFIG_PATH=PAI_KUBE_CONFIG_DEFAULT_LOCATION)
meta_data = kubernetes.client.V1ObjectMeta()
meta_data.namespace = namespace
meta_data.name = name
body = kubernetes.client.V1ConfigMap(
metadata = meta_data,
data = data_dict)
try:
api_response = api_instance.replace_namespaced_config_map(name, namespace, body)
logger.info("configmap named {0} is updated.".format(name))
except ApiException as e:
if e.status == 404:
try:
logger.info("Couldn't find configmap named {0}. Create a new configmap".format(name))
api_response = api_instance.create_namespaced_config_map(namespace, body)
logger.info("Configmap named {0} is created".format(name))
except ApiException as ie:
logger.error("Exception when calling CoreV1Api->create_namespaced_config_map: {0}".format(str(e)))
sys.exit(1)
else:
logger.error("Exception when calling CoreV1Api->replace_namespaced_config_map: {0}".format(str(e)))
sys.exit(1) |
tobiasleibner/dune-gdt | dune/gdt/operators/fv/rhs.hh | // This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// <NAME> (2017)
#ifndef DUNE_GDT_OPERATORS_FV_RHS_HH
#define DUNE_GDT_OPERATORS_FV_RHS_HH
#include <type_traits>
#include <dune/xt/grid/walker/functors.hh>
#include <dune/xt/la/container/interfaces.hh>
#include <dune/gdt/functionals/base.hh>
#include <dune/gdt/local/functionals/integrals.hh>
#include <dune/gdt/local/integrands/fv.hh>
#include <dune/gdt/operators/base.hh>
#include <dune/gdt/local/operators/integrals.hh>
namespace Dune {
namespace GDT {
// forward
template <class RhsEvaluationImp>
class AdvectionRhsOperator;
namespace internal {
template <class RhsEvaluationImp>
class AdvectionRhsOperatorTraits
{
public:
typedef AdvectionRhsOperator<RhsEvaluationImp> derived_type;
typedef RhsEvaluationImp RhsEvaluationType;
typedef typename RhsEvaluationImp::DomainFieldType FieldType;
typedef typename RhsEvaluationImp::PartialURangeType JacobianType;
}; // class AdvectionRhsOperatorTraits
} // namespace internal
template <class GridLayerType, class MatrixType, class DiscreteFunctionType>
class MatrixSolveFunctor : public XT::Grid::Functor::Codim0<GridLayerType>
{
typedef typename XT::Grid::Functor::Codim0<GridLayerType> BaseType;
public:
using typename BaseType::EntityType;
MatrixSolveFunctor(const std::vector<MatrixType>& matrices,
const DiscreteFunctionType& rhs,
DiscreteFunctionType& solution)
: matrices_(matrices)
, rhs_(rhs)
, solution_(solution)
{
}
virtual void apply_local(const EntityType& entity)
{
// get mapper
const auto& mapper = rhs_.space().mapper();
// copy rhs to DynamicVector
DynamicVector<typename MatrixType::value_type> local_solution(mapper.numDofs(entity), 0.);
DynamicVector<typename MatrixType::value_type> local_rhs(local_solution.size(), 0.);
const auto& rhs_vector = rhs_.vector();
auto& solution_vector = solution_.vector();
const auto global_indices = mapper.globalIndices(entity);
for (size_t ii = 0; ii < local_rhs.size(); ++ii)
local_rhs[ii] = rhs_vector.get_entry(global_indices[ii]);
// solve
matrices_[rhs_.space().grid_layer().indexSet().index(entity)].solve(local_solution, local_rhs);
// write solution
for (size_t ii = 0; ii < local_rhs.size(); ++ii)
solution_vector.set_entry(global_indices[ii], local_solution[ii]);
}
private:
const std::vector<MatrixType>& matrices_;
const DiscreteFunctionType& rhs_;
DiscreteFunctionType& solution_;
};
template <class GridLayerType, class MatrixType, class DiscreteFunctionType>
class MatrixApplyFunctor : public XT::Grid::Functor::Codim0<GridLayerType>
{
typedef typename XT::Grid::Functor::Codim0<GridLayerType> BaseType;
public:
using typename BaseType::EntityType;
MatrixApplyFunctor(const std::vector<MatrixType>& matrices,
const DiscreteFunctionType& vector,
DiscreteFunctionType& result)
: matrices_(matrices)
, vector_(vector)
, result_(result)
{
}
virtual void apply_local(const EntityType& entity)
{
// get mapper
const auto& mapper = vector_.space().mapper();
// copy rhs to DynamicVector
DynamicVector<typename MatrixType::value_type> local_vector(mapper.numDofs(entity), 0.);
DynamicVector<typename MatrixType::value_type> local_result(local_vector.size(), 0.);
const auto& vector_vector = vector_.vector();
auto& result_vector = result_.vector();
const auto global_indices = mapper.globalIndices(entity);
for (size_t ii = 0; ii < local_vector.size(); ++ii)
local_vector[ii] = vector_vector.get_entry(global_indices[ii]);
// solve
matrices_[vector_.space().grid_layer().indexSet().index(entity)].mv(local_vector, local_result);
// write solution
for (size_t ii = 0; ii < local_vector.size(); ++ii)
result_vector.set_entry(global_indices[ii], local_result[ii]);
}
private:
const std::vector<MatrixType>& matrices_;
const DiscreteFunctionType& vector_;
DiscreteFunctionType& result_;
};
template <class RhsEvaluationImp>
class AdvectionRhsOperator : public Dune::GDT::OperatorInterface<internal::AdvectionRhsOperatorTraits<RhsEvaluationImp>>
{
// static_assert(is_rhs_evaluation<RhsEvaluationImp>::value, "RhsEvaluationImp has to be derived from
// RhsInterface!");
public:
typedef internal::AdvectionRhsOperatorTraits<RhsEvaluationImp> Traits;
typedef typename Traits::RhsEvaluationType RhsEvaluationType;
using BaseType = typename Dune::GDT::OperatorInterface<internal::AdvectionRhsOperatorTraits<RhsEvaluationImp>>;
AdvectionRhsOperator(const RhsEvaluationType& rhs_evaluation)
: rhs_evaluation_(rhs_evaluation)
{
}
template <class SourceType, class RangeType>
void apply(const SourceType& source, RangeType& range, const XT::Common::Parameter& /*param*/) const
{
std::fill(range.vector().begin(), range.vector().end(), 0);
LocalVolumeIntegralFunctional<LocalFvRhsIntegrand<RhsEvaluationType, SourceType>,
typename RangeType::SpaceType::BaseFunctionSetType>
local_functional(rhs_evaluation_, source);
VectorFunctionalBase<typename RangeType::VectorType,
typename RangeType::SpaceType,
typename RangeType::SpaceType::GridLayerType,
typename RangeType::DomainFieldType>
functional_assembler(range.vector(), range.space());
functional_assembler.append(local_functional);
functional_assembler.assemble(true);
}
const RhsEvaluationType& evaluation() const
{
return rhs_evaluation_;
}
// assembles jacobian (jacobian is assumed to be zero initially)
template <class SourceType, class MatrixTraits>
void assemble_jacobian(XT::LA::MatrixInterface<MatrixTraits, typename SourceType::RangeFieldType>& jac,
const SourceType& source,
const XT::Common::Parameter& /*param*/ = {}) const
{
typedef typename SourceType::SpaceType SpaceImp;
typedef typename SpaceImp::BaseFunctionSetType BasisType;
typedef LocalVolumeIntegralOperator<LocalFvRhsJacobianIntegrand<RhsEvaluationType, SourceType>, BasisType>
LocalOperatorType;
LocalOperatorType local_operator(rhs_evaluation_, source);
SystemAssembler<SpaceImp> assembler(source.space());
assembler.append(local_operator, jac);
assembler.assemble(true);
}
// // assembles jacobian (jacobian is assumed to be zero initially)
// template <class SourceType, class MatrixType>
// void assemble_newton_matrix(std::vector<MatrixType>& newton_matrices,
// const SourceType& source,
// const XT::Common::Parameter& param) const
// {
// typedef LocalVolumeIntegralOperator<LocalFvRhsNewtonIntegrand<RhsEvaluationType, SourceType>> LocalOperatorType;
// LocalOperatorType local_operator(rhs_evaluation_, source, param);
// LocalVolumeTwoFormAssembler<LocalOperatorType> local_assembler(local_operator);
// SystemAssembler<typename SourceType::SpaceType> assembler(source.space());
// assembler.append(local_assembler, newton_matrices);
// assembler.assemble(false);
// }
// // solves with local jacobian on each entity
// template <class SourceType, class RangeType, class MatrixType>
// void solve(const std::vector<MatrixType>& newton_matrices,
// const SourceType& rhs,
// RangeType& solution,
// const XT::Common::Parameter& /*param*/ = {}) const
// {
// MatrixSolveFunctor<typename SourceType::SpaceType::GridLayerType, MatrixType, SourceType> functor(
// newton_matrices, rhs, solution);
// SystemAssembler<typename SourceType::SpaceType> assembler(rhs.space());
// assembler.append(functor);
// assembler.assemble(false);
// }
// // applies local jacobian on each entity
// template <class SourceType, class RangeType, class MatrixType>
// void mv(const std::vector<MatrixType>& newton_matrices,
// const SourceType& vector,
// RangeType& result,
// const XT::Common::Parameter& /*param*/ = {}) const
// {
// MatrixApplyFunctor<typename SourceType::SpaceType::GridLayerType, MatrixType, SourceType> functor(
// newton_matrices, vector, result);
// SystemAssembler<typename SourceType::SpaceType> assembler(vector.space());
// assembler.append(functor);
// assembler.assemble(false);
// }
private:
const RhsEvaluationType& rhs_evaluation_;
}; // class AdvectionRhsOperator
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_OPERATORS_FV_RHS_HH
|
mrgreentech/react-pam | src/Components/Form/Message.js | import React from 'react';
import PropTypes from 'prop-types';
const Message = ({ component, inline, ...rest }) => {
const props = [];
if (inline) {
props.push('inline');
}
const Component = component ? component : 'aside';
return <Component pam-form-message={props.join(' ')} {...rest} />;
};
Message.propTypes = {
component: PropTypes.node,
inline: PropTypes.bool
};
Message.defaultProps = {
inline: false
};
export default Message;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.