repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
liyong03/YLCleaner | YLCleaner/Xcode-RuntimeHeaders/SpriteKit/SKEffectNode.h | <reponame>liyong03/YLCleaner
/*
* Generated by class-dump 3.3.4 (64 bit).
*
* class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by <NAME>.
*/
#import <SpriteKit/SKNode.h>
@class CIFilter;
@interface SKEffectNode : SKNode
{
}
- (void)dealloc;
@property BOOL shouldCenterFilter;
- (void)_flippedChangedFrom:(BOOL)arg1 to:(BOOL)arg2;
- (void)_scaleFactorChangedFrom:(float)arg1 to:(float)arg2;
@property long long blendMode;
@property BOOL shouldRasterize;
@property BOOL shouldEnableEffects;
@property(retain) CIFilter *filter;
- (id)description;
- (void)encodeWithCoder:(id)arg1;
- (id)initWithCoder:(id)arg1;
- (id)init;
@end
|
3dhater/Racer | src/libs/qlib/qtimer.cpp | <reponame>3dhater/Racer<filename>src/libs/qlib/qtimer.cpp
/*
* QTimer - Simple timing things
* 11-08-94: Created! (from the Amiga!)
* 01-04-99: Using VTraces for finer granularity
* 10-05-99: Using UST for even more granularity (nanoseconds)
* 03-03-01: Modified to use timeGetTime() on Win32; better resolution.
* 15-04-01: Support for gettimeofday() (on Linux)
* FUTURE:
* - Optionally select (at construction time) what timing method to use
* (for VTraces for example)
* BUGS:
* - GetTime() does not work
* NOTES:
* - Timer may be stopped intermittently, like a stopwatch
* - USE_GETTIMEOFDAY uses usecs (microseconds)
* - USE_TIME uses seconds
* - USE_UST uses nanoseconds (although resolution is often far less)
* - USE_OS_TICKS uses OS ticks (depending)
* (C) MarketGraph/RvG
*/
#include <qlib/timer.h>
#include <qlib/app.h>
#include <time.h>
#ifdef linux
#include <sys/time.h>
#endif
#include <qlib/debug.h>
DEBUG_ENABLE
// Screen Hertz; for Quizes, PAL should do the trick
#define TRACES_PER_SECOND 50
QTimer::QTimer()
{ Reset();
}
QTimer::~QTimer()
{
}
void QTimer::ResetBase()
// Reset 0-base for time counting
{
#ifdef USE_VTRACE
baseVCount=app->GetVTraceCount();
#endif
#ifdef USE_UST
dmGetUST(&baseUST);
#endif
#ifdef USE_TIME
time(&base_secs);
#endif
#ifdef USE_GETTIMEOFDAY
struct timezone tz;
gettimeofday(&tvBase,&tz);
// Calculate time in usecs
base_usecs=tvBase.tv_sec*1000000+tvBase.tv_usec;
#endif
#ifdef USE_OS_TICK
//baseTicks=(int)GetTickCount();
baseTicks=(int)timeGetTime();
#endif
}
/**********************
* STOPWATCH EMULATION *
**********************/
void QTimer::UpdateTicks()
// Updates 'ticks' to the last available time instant (NOW)
{
if(!isRunning)
{ //qerr("QTimer::UpdateTicks() called without running timer");
return;
}
#ifdef USE_VTRACE
int vc;
vc=app->GetVTraceCount();
ticks+=vc-baseVCount;
baseVCount=vc;
#endif
#ifdef USE_UST
uint64 vc;
dmGetUST(&vc);
ticks+=vc-baseUST;
baseUST=vc;
#endif
#ifdef USE_OS_TICK
// Looks a lot like UST
int t;
//t=(int)GetTickCount();
t=(int)timeGetTime();
ticks+=t-baseTicks;
baseTicks=t;
#endif
#ifdef USE_GETTIMEOFDAY
int t;
struct timezone tz;
gettimeofday(&tv,&tz);
t=tv.tv_sec*1000000+tv.tv_usec;
ticks+=t-base_usecs;
base_usecs=t;
#endif
}
void QTimer::Reset()
{ /** Starts timer at current time **/
ResetBase();
ticks=0;
isRunning=FALSE;
}
void QTimer::Start()
// Turn timer on
{
if(isRunning)return;
ResetBase();
isRunning=TRUE;
}
void QTimer::Stop()
// Stop time recording
{
if(!isRunning)return;
UpdateTicks();
isRunning=FALSE;
}
/****************
* RETRIEVE TIME *
****************/
void QTimer::GetTime(ulong *secs,ulong *micros)
/** Get passed time since last reset **/
{
qerr("QTimer::GetTime() called; is OBSOLETE");
}
ulong QTimer::GetSeconds()
/** Get passed seconds since last Start() **/
{
#ifdef USE_VTRACE
long s;
int vc;
//vc=app->GetVTraceCount();
//return (ulong)((vc-baseVCount)/TRACES_PER_SECOND);
UpdateTicks();
return ticks/TRACES_PER_SECOND;
#endif
#ifdef USE_UST
UpdateTicks();
return ticks/1000000000; // 10^9 = nanoseconds
#endif
#ifdef USE_TIME
time_t t;
time(&t);
return (ulong)(t-base_secs);
#endif
#ifdef USE_OS_TICK
UpdateTicks();
return ticks/1000;
#endif
#ifdef USE_GETTIMEOFDAY
UpdateTicks();
return ticks/1000000;
#endif
}
#ifdef USE_UST
uint64 QTimer::GetTicks()
#else
int QTimer::GetTicks()
#endif
// Get #ticks, 1 tick is 1 vertical blank interval, or nanosecond, or WHATEVER!
// Don't use this function in application code; too many variant
{
UpdateTicks();
return ticks;
//int vc;
//vc=app->GetVTraceCount();
//return (int)(vc-baseVCount);
}
int QTimer::GetMilliSeconds()
{
#ifdef USE_UST
//uint64 div;
//div=1000000;
UpdateTicks();
//qdbg("ticks=%lld\n",ticks);
return (int)(ticks/1000000);
#endif
#ifdef USE_TIME
UpdateTicks();
return (int)(ticks*1000);
#endif
#ifdef USE_OS_TICK
UpdateTicks();
return (int)ticks;
#endif
#ifdef USE_GETTIMEOFDAY
UpdateTicks();
return ticks/1000;
#endif
}
int QTimer::GetMicroSeconds()
// Returns time in microseconds
{
#ifdef USE_UST
UpdateTicks();
return (int)(ticks/1000);
#endif
#ifdef USE_TIME
UpdateTicks();
return (int)(ticks*1000000);
#endif
#ifdef USE_OS_TICK
// Not really microseconds!
UpdateTicks();
return (int)ticks;
#endif
#ifdef USE_GETTIMEOFDAY
UpdateTicks();
return ticks;
#endif
}
void QTimer::WaitForTime(int secs,int msecs)
// Reasonably multitasking-friendly wait for the timer to pass the given
// time and return.
// On O2's and most low level SGI's, the accurary is ~10ms (scheduler slice)
// Starts the timer if it is not running (instead of just returning)
// On Win32, we might just use Sleep()
{ int n;
secs=secs*1000+msecs;
// Make sure timer is running
if(!IsRunning())Start();
while(1)
{ n=GetMilliSeconds();
if(n>=secs)break;
QNap(1);
}
}
/*****************
* TIME ADJUSTING *
*****************/
void QTimer::AdjustMilliSeconds(int delta)
// Adjust time in milliseconds
// 'delta' may be negative or positive. Note that this may underflow the
// timer, meaning it will be negative.
{
#ifdef USE_UST
uint64 delta64;
delta64=(uint64)delta;
// Get time in nanoseconds
delta64*=1000000;
ticks+=delta64;
#endif
#ifdef USE_OS_TICK
// Adjust msecs
ticks+=delta;
#endif
#ifdef USE_GETTIMEOFDAY
ticks+=delta*1000;
#endif
}
/** TEST **/
//#define NOTDEF_TEST
#ifdef NOTDEF_TEST
#include <stdio.h>
void main(void)
{ QTimer *qt;
ulong s,m;
QAppSetup();
qt=new QTimer();
while(!RMB())
{ qt->GetTime(&s,&m);
printf("S=%d, M=%4d\n",s,m);
}
//delete qt;
QAppQuit();
}
#endif
|
viktorpts/FlyJS | js/components/PlayerControl.js | import Component from './Component.js';
import ServiceLocator from '../utility/ServiceLocator.js';
export default class PlayerControl extends Component {
constructor(owner, input) {
super(owner);
this.input = input;
ServiceLocator.Remote.registerControls(input);
}
update() {
// TODO poll input and post events to owner
if(this.input.keysPressed["ArrowLeft"]) {
this.owner.direction -= Math.PI / 32;
}
if(this.input.keysPressed["ArrowRight"]) {
this.owner.direction += Math.PI / 32;
}
if(this.input.keysPressed["ArrowUp"]) {
this.owner.post('accelerate', 0.2);
}
if(this.input.keysPressed["ArrowDown"]) {
this.owner.post('accelerate', -0.05);
}
/*
if(this.input.keysPressed["Space"]) {
this.owner.shoot();
}
*/
ServiceLocator.Renderer.debug[0] = 'Local player position: ' + this.owner.x.toFixed(0) + ':' + this.owner.y.toFixed(0);
}
} |
MenSeb/react-cubes-galaxy | src/components/System/types.js | import { arrayOf, object } from 'prop-types'
export default {
elements: arrayOf( object ).isRequired
} |
wonderfulm3/stepper-form | library/src/main/java/io/tammen/stepper/widget/mobile/exception/StepperElementException.java | <filename>library/src/main/java/io/tammen/stepper/widget/mobile/exception/StepperElementException.java
package io.tammen.stepper.widget.mobile.exception;
/**
* Created by <NAME> on 3/26/2018.
*/
public class StepperElementException extends Exception {
private final AnnotationErrorCode annotationErrorCode;
public StepperElementException(AnnotationErrorCode annotationErrorCode) {
super();
this.annotationErrorCode = annotationErrorCode;
}
public StepperElementException(String message, AnnotationErrorCode annotationErrorCode) {
super(message);
this.annotationErrorCode = annotationErrorCode;
}
public StepperElementException(String message, Throwable throwable, AnnotationErrorCode annotationErrorCode) {
super(message, throwable);
this.annotationErrorCode = annotationErrorCode;
}
}
|
Klotzi111/nmuk | src/main/java/de/siphalor/nmuk/impl/duck/IKeyBinding.java | <reponame>Klotzi111/nmuk
/*
* Copyright 2021 Siphalor
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied.
* See the License for the specific language governing
* permissions and limitations under the License.
*/
package de.siphalor.nmuk.impl.duck;
import java.util.List;
import org.jetbrains.annotations.ApiStatus;
import net.minecraft.client.option.KeyBinding;
@ApiStatus.Internal
public interface IKeyBinding {
// only required because mc verions 1.14 does not have this
void nmuk$setPressed(boolean pressed);
int nmuk$getNextChildId();
void nmuk$setNextChildId(int nextChildId);
boolean nmuk$isAlternative();
KeyBinding nmuk$getParent();
void nmuk$setParent(KeyBinding binding);
List<KeyBinding> nmuk$getAlternatives();
int nmuk$getAlternativesCount();
/**
*
* @param binding
* @return the index at which the binding was found in the parent's alternatives
*/
int nmuk$removeAlternative(KeyBinding binding);
void nmuk$addAlternative(KeyBinding binding);
/**
* This method should only be used for the controls gui to determine the entry position
*
* @return the index in the parent's children list
*/
int nmuk$getIndexInParent();
int nmuk$getAlternativeId();
void nmuk$setAlternativeId(int alternativeId);
}
|
Git-liuxiaoyu/cloud-hospital-parent | cloud-hospital-parent/cloud-hospital-nacos-parent/worker-service/src/main/java/com/example/workerservice/service/api/division/IAddDivisionCommandHandler.java | <gh_stars>0
package com.example.workerservice.service.api.division;
import com.example.workerservice.service.command.division.add.AddDivisionCommand;
/**
* 接口 - IAddDivisionCommandHandler
*
* @author Alnwick11AtoZ 松
* @date 2021/6/28
*/
public interface IAddDivisionCommandHandler {
void action(AddDivisionCommand command);
}
|
Geomatys/constellation | modules/library/api/src/main/java/org/constellation/process/converter/MapToCRSProcessReferenceConverter.java | package org.constellation.process.converter;
import org.apache.sis.util.UnconvertibleObjectException;
import org.constellation.process.CRSProcessReference;
import java.util.LinkedHashMap;
import org.geotoolkit.feature.util.converter.SimpleConverter;
/**
* @author <NAME> (Geomatys).
*/
public class MapToCRSProcessReferenceConverter extends SimpleConverter<LinkedHashMap, CRSProcessReference> {
@Override
public Class<LinkedHashMap> getSourceClass() {
return LinkedHashMap.class;
}
@Override
public Class<CRSProcessReference> getTargetClass() {
return CRSProcessReference.class;
}
@Override
public CRSProcessReference apply(LinkedHashMap map) throws UnconvertibleObjectException {
CRSProcessReference reference = new CRSProcessReference();
reference.setCode((String) map.get("code"));
return reference;
}
}
|
Gratzi/Telescope | packages/pegg-cards/package.js | <filename>packages/pegg-cards/package.js
Package.describe({
name: 'pegg-cards',
version: '0.0.1',
// Brief, one-line summary of the package.
summary: '',
// URL to the Git repository containing the source code for this package.
git: '',
// By default, Meteor will default to using README.md for documentation.
// To avoid submitting documentation, set this field to null.
documentation: 'README.md'
});
Package.onUse(function(api) {
api.versionsFrom('1.3.2.4');
api.use([
'ecmascript',
'nova:core@0.26.0-nova',
'nova:posts@0.26.0-nova',
'nova:users@0.26.0-nova'
]);
api.mainModule('pegg-cards.js');
api.addFiles(['PeggCardPostsPage.jsx', 'filterPosts.js'], 'client');
api.addFiles(['pegg-parse.js'], 'server');
// api.addFiles('filterPosts.js', ['client', 'server']);
});
Package.onTest(function(api) {
api.use('ecmascript');
api.use('tinytest');
api.use('pegg-cards');
api.mainModule('pegg-cards-tests.js');
});
|
jan2000/curl | src/tool_writeout.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2021, <NAME>, <<EMAIL>>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
#define ENABLE_CURLX_PRINTF
/* use our own printf() functions */
#include "curlx.h"
#include "tool_cfgable.h"
#include "tool_writeout.h"
#include "tool_writeout_json.h"
#include "memdebug.h" /* keep this as LAST include */
static int writeTime(FILE *stream, const struct writeoutvar *wovar,
struct per_transfer *per, CURLcode per_result,
bool use_json);
static int writeString(FILE *stream, const struct writeoutvar *wovar,
struct per_transfer *per, CURLcode per_result,
bool use_json);
static int writeLong(FILE *stream, const struct writeoutvar *wovar,
struct per_transfer *per, CURLcode per_result,
bool use_json);
static int writeOffset(FILE *stream, const struct writeoutvar *wovar,
struct per_transfer *per, CURLcode per_result,
bool use_json);
struct httpmap {
const char *str;
int num;
};
static const struct httpmap http_version[] = {
{ "0", CURL_HTTP_VERSION_NONE},
{ "1", CURL_HTTP_VERSION_1_0},
{ "1.1", CURL_HTTP_VERSION_1_1},
{ "2", CURL_HTTP_VERSION_2},
{ "3", CURL_HTTP_VERSION_3},
{ NULL, 0} /* end of list */
};
/* The designated write function should be the same as the CURLINFO return type
with exceptions special cased in the respective function. For example,
http_version uses CURLINFO_HTTP_VERSION which returns the version as a long,
however it is output as a string and therefore is handled in writeString.
Yes: "http_version": "1.1"
No: "http_version": 1.1
Variable names should be in alphabetical order.
*/
static const struct writeoutvar variables[] = {
{"content_type", VAR_CONTENT_TYPE, CURLINFO_CONTENT_TYPE, writeString},
{"errormsg", VAR_ERRORMSG, 0, writeString},
{"exitcode", VAR_EXITCODE, 0, writeLong},
{"filename_effective", VAR_EFFECTIVE_FILENAME, 0, writeString},
{"ftp_entry_path", VAR_FTP_ENTRY_PATH, CURLINFO_FTP_ENTRY_PATH, writeString},
{"http_code", VAR_HTTP_CODE, CURLINFO_RESPONSE_CODE, writeLong},
{"http_connect", VAR_HTTP_CODE_PROXY, CURLINFO_HTTP_CONNECTCODE, writeLong},
{"http_version", VAR_HTTP_VERSION, CURLINFO_HTTP_VERSION, writeString},
{"json", VAR_JSON, 0, NULL},
{"local_ip", VAR_LOCAL_IP, CURLINFO_LOCAL_IP, writeString},
{"local_port", VAR_LOCAL_PORT, CURLINFO_LOCAL_PORT, writeLong},
{"method", VAR_EFFECTIVE_METHOD, CURLINFO_EFFECTIVE_METHOD, writeString},
{"num_connects", VAR_NUM_CONNECTS, CURLINFO_NUM_CONNECTS, writeLong},
{"num_headers", VAR_NUM_HEADERS, 0, writeLong},
{"num_redirects", VAR_REDIRECT_COUNT, CURLINFO_REDIRECT_COUNT, writeLong},
{"onerror", VAR_ONERROR, 0, NULL},
{"proxy_ssl_verify_result", VAR_PROXY_SSL_VERIFY_RESULT,
CURLINFO_PROXY_SSL_VERIFYRESULT, writeLong},
{"redirect_url", VAR_REDIRECT_URL, CURLINFO_REDIRECT_URL, writeString},
{"referer", VAR_REFERER, CURLINFO_REFERER, writeString},
{"remote_ip", VAR_PRIMARY_IP, CURLINFO_PRIMARY_IP, writeString},
{"remote_port", VAR_PRIMARY_PORT, CURLINFO_PRIMARY_PORT, writeLong},
{"response_code", VAR_HTTP_CODE, CURLINFO_RESPONSE_CODE, writeLong},
{"scheme", VAR_SCHEME, CURLINFO_SCHEME, writeString},
{"size_download", VAR_SIZE_DOWNLOAD, CURLINFO_SIZE_DOWNLOAD_T, writeOffset},
{"size_header", VAR_HEADER_SIZE, CURLINFO_HEADER_SIZE, writeLong},
{"size_request", VAR_REQUEST_SIZE, CURLINFO_REQUEST_SIZE, writeLong},
{"size_upload", VAR_SIZE_UPLOAD, CURLINFO_SIZE_UPLOAD_T, writeOffset},
{"speed_download", VAR_SPEED_DOWNLOAD, CURLINFO_SPEED_DOWNLOAD_T,
writeOffset},
{"speed_upload", VAR_SPEED_UPLOAD, CURLINFO_SPEED_UPLOAD_T, writeOffset},
{"ssl_verify_result", VAR_SSL_VERIFY_RESULT, CURLINFO_SSL_VERIFYRESULT,
writeLong},
{"stderr", VAR_STDERR, 0, NULL},
{"stdout", VAR_STDOUT, 0, NULL},
{"time_appconnect", VAR_APPCONNECT_TIME, CURLINFO_APPCONNECT_TIME_T,
writeTime},
{"time_connect", VAR_CONNECT_TIME, CURLINFO_CONNECT_TIME_T, writeTime},
{"time_namelookup", VAR_NAMELOOKUP_TIME, CURLINFO_NAMELOOKUP_TIME_T,
writeTime},
{"time_pretransfer", VAR_PRETRANSFER_TIME, CURLINFO_PRETRANSFER_TIME_T,
writeTime},
{"time_redirect", VAR_REDIRECT_TIME, CURLINFO_REDIRECT_TIME_T, writeTime},
{"time_starttransfer", VAR_STARTTRANSFER_TIME, CURLINFO_STARTTRANSFER_TIME_T,
writeTime},
{"time_total", VAR_TOTAL_TIME, CURLINFO_TOTAL_TIME_T, writeTime},
{"url", VAR_INPUT_URL, 0, writeString},
{"url_effective", VAR_EFFECTIVE_URL, CURLINFO_EFFECTIVE_URL, writeString},
{"urlnum", VAR_URLNUM, 0, writeLong},
{NULL, VAR_NONE, 0, NULL}
};
static int writeTime(FILE *stream, const struct writeoutvar *wovar,
struct per_transfer *per, CURLcode per_result,
bool use_json)
{
bool valid = false;
curl_off_t us = 0;
(void)per;
(void)per_result;
DEBUGASSERT(wovar->writefunc == writeTime);
if(wovar->ci) {
if(!curl_easy_getinfo(per->curl, wovar->ci, &us))
valid = true;
}
else {
DEBUGASSERT(0);
}
if(valid) {
curl_off_t secs = us / 1000000;
us %= 1000000;
if(use_json)
fprintf(stream, "\"%s\":", wovar->name);
fprintf(stream, "%" CURL_FORMAT_CURL_OFF_TU
".%06" CURL_FORMAT_CURL_OFF_TU, secs, us);
}
else {
if(use_json)
fprintf(stream, "\"%s\":null", wovar->name);
}
return 1; /* return 1 if anything was written */
}
static int writeString(FILE *stream, const struct writeoutvar *wovar,
struct per_transfer *per, CURLcode per_result,
bool use_json)
{
bool valid = false;
const char *strinfo = NULL;
DEBUGASSERT(wovar->writefunc == writeString);
if(wovar->ci) {
if(wovar->ci == CURLINFO_HTTP_VERSION) {
long version = 0;
if(!curl_easy_getinfo(per->curl, CURLINFO_HTTP_VERSION, &version)) {
const struct httpmap *m = &http_version[0];
while(m->str) {
if(m->num == version) {
strinfo = m->str;
valid = true;
break;
}
m++;
}
}
}
else {
if(!curl_easy_getinfo(per->curl, wovar->ci, &strinfo) && strinfo)
valid = true;
}
}
else {
switch(wovar->id) {
case VAR_ERRORMSG:
if(per_result) {
strinfo = per->errorbuffer[0] ? per->errorbuffer :
curl_easy_strerror(per_result);
valid = true;
}
break;
case VAR_EFFECTIVE_FILENAME:
if(per->outs.filename) {
strinfo = per->outs.filename;
valid = true;
}
break;
case VAR_INPUT_URL:
if(per->this_url) {
strinfo = per->this_url;
valid = true;
}
break;
default:
DEBUGASSERT(0);
break;
}
}
if(valid) {
DEBUGASSERT(strinfo);
if(use_json) {
fprintf(stream, "\"%s\":\"", wovar->name);
jsonWriteString(stream, strinfo);
fputs("\"", stream);
}
else
fputs(strinfo, stream);
}
else {
if(use_json)
fprintf(stream, "\"%s\":null", wovar->name);
}
return 1; /* return 1 if anything was written */
}
static int writeLong(FILE *stream, const struct writeoutvar *wovar,
struct per_transfer *per, CURLcode per_result,
bool use_json)
{
bool valid = false;
long longinfo = 0;
DEBUGASSERT(wovar->writefunc == writeLong);
if(wovar->ci) {
if(!curl_easy_getinfo(per->curl, wovar->ci, &longinfo))
valid = true;
}
else {
switch(wovar->id) {
case VAR_NUM_HEADERS:
longinfo = per->num_headers;
valid = true;
break;
case VAR_EXITCODE:
longinfo = per_result;
valid = true;
break;
case VAR_URLNUM:
if(per->urlnum <= INT_MAX) {
longinfo = (long)per->urlnum;
valid = true;
}
break;
default:
DEBUGASSERT(0);
break;
}
}
if(valid) {
if(use_json)
fprintf(stream, "\"%s\":%ld", wovar->name, longinfo);
else {
if(wovar->id == VAR_HTTP_CODE || wovar->id == VAR_HTTP_CODE_PROXY)
fprintf(stream, "%03ld", longinfo);
else
fprintf(stream, "%ld", longinfo);
}
}
else {
if(use_json)
fprintf(stream, "\"%s\":null", wovar->name);
}
return 1; /* return 1 if anything was written */
}
static int writeOffset(FILE *stream, const struct writeoutvar *wovar,
struct per_transfer *per, CURLcode per_result,
bool use_json)
{
bool valid = false;
curl_off_t offinfo = 0;
(void)per;
(void)per_result;
DEBUGASSERT(wovar->writefunc == writeOffset);
if(wovar->ci) {
if(!curl_easy_getinfo(per->curl, wovar->ci, &offinfo))
valid = true;
}
else {
DEBUGASSERT(0);
}
if(valid) {
if(use_json)
fprintf(stream, "\"%s\":", wovar->name);
fprintf(stream, "%" CURL_FORMAT_CURL_OFF_T, offinfo);
}
else {
if(use_json)
fprintf(stream, "\"%s\":null", wovar->name);
}
return 1; /* return 1 if anything was written */
}
void ourWriteOut(const char *writeinfo, struct per_transfer *per,
CURLcode per_result)
{
FILE *stream = stdout;
const char *ptr = writeinfo;
bool done = FALSE;
while(ptr && *ptr && !done) {
if('%' == *ptr && ptr[1]) {
if('%' == ptr[1]) {
/* an escaped %-letter */
fputc('%', stream);
ptr += 2;
}
else {
/* this is meant as a variable to output */
char *end;
if('{' == ptr[1]) {
char keepit;
int i;
bool match = FALSE;
end = strchr(ptr, '}');
ptr += 2; /* pass the % and the { */
if(!end) {
fputs("%{", stream);
continue;
}
keepit = *end;
*end = 0; /* null-terminate */
for(i = 0; variables[i].name; i++) {
if(curl_strequal(ptr, variables[i].name)) {
match = TRUE;
switch(variables[i].id) {
case VAR_ONERROR:
if(per_result == CURLE_OK)
/* this isn't error so skip the rest */
done = TRUE;
break;
case VAR_STDOUT:
stream = stdout;
break;
case VAR_STDERR:
stream = stderr;
break;
case VAR_JSON:
ourWriteOutJSON(stream, variables, per, per_result);
break;
default:
(void)variables[i].writefunc(stream, &variables[i],
per, per_result, false);
break;
}
break;
}
}
if(!match) {
fprintf(stderr, "curl: unknown --write-out variable: '%s'\n", ptr);
}
ptr = end + 1; /* pass the end */
*end = keepit;
}
else {
/* illegal syntax, then just output the characters that are used */
fputc('%', stream);
fputc(ptr[1], stream);
ptr += 2;
}
}
}
else if('\\' == *ptr && ptr[1]) {
switch(ptr[1]) {
case 'r':
fputc('\r', stream);
break;
case 'n':
fputc('\n', stream);
break;
case 't':
fputc('\t', stream);
break;
default:
/* unknown, just output this */
fputc(*ptr, stream);
fputc(ptr[1], stream);
break;
}
ptr += 2;
}
else {
fputc(*ptr, stream);
ptr++;
}
}
}
|
math715/arts | leetcode/236.lowest-common-ancestor-of-a-binary-tree.cpp | <reponame>math715/arts
/*
* @lc app=leetcode id=236 lang=cpp
*
* [236] Lowest Common Ancestor of a Binary Tree
*/
// @lc code=start
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
unordered_map<TreeNode*,TreeNode*> fa;
unordered_set<TreeNode*> vis;
queue<TreeNode*> que;
if(root) que.push(root);
fa[root] = nullptr;
while(que.size()){
TreeNode* par = que.front();
que.pop();
if(par->left){
que.push(par->left);
fa[par->left] = par;
}
if(par->right){
que.push(par->right);
fa[par->right] = par;
}
}
while(p){
vis.insert(p);
p = fa[p];
}
while(q){
if(vis.count(q)){
return q;
}
q = fa[q];
}
return nullptr;
}
};
// @lc code=end
|
donkeycart/ralasafe | src/main/java/org/ralasafe/db/DBPower.java | /**
* Copyright (c) 2004-2011 <NAME>(<NAME>), http://www.ralasafe.com
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*/
package org.ralasafe.db;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ralasafe.RalasafeException;
import org.ralasafe.util.DBUtil;
import org.ralasafe.util.IOUtil;
import org.ralasafe.util.StringUtil;
public class DBPower {
private static Log log=LogFactory.getLog( DBPower.class );
private static final String DATASOURCES_CONFIG_FILE = "ralasafe/datasources.xml";
public static final String BASE_CONFIG_DIR_MAP_KEY = "baseConfigDir";
public static final String DATASOURCES_CONFIG_FILE_MAP_KEY = "datasourcesConfigFile";
private static final int DEFAULT_MAX_BATCH_SIZE = 50;
private static int maxBatchSize = DEFAULT_MAX_BATCH_SIZE;
// private static DataSourceProviderDbcpImpl defaultDs=null;
private static String defaultDsName = "ralasafe";
private static String defaultAppDsName;
/** key/value=datasourceName<String>/ds<DataSource> */
private static Map dsnameMap = new HashMap();
/** key/value=tableId<Integer>/DataSource */
private static Map tableIdDsMap = new HashMap();
/**
* key/value=datasourceName<String>/Map[key/value=tableName<String>/tableId<
* Integer>]
*/
private static Map dsTableNameMap = new HashMap();
private static int tableIdIndex = 1;
private static boolean started;
public static boolean isStarted() {
return started;
}
public static void on(Map map) {
if (started) {
return;
}
started = true;
if (map == null) {
map = new HashMap();
}
String configFile = (String) map.get(DATASOURCES_CONFIG_FILE_MAP_KEY);
String baseDir = (String) map.get(BASE_CONFIG_DIR_MAP_KEY);
if (baseDir == null) {
baseDir = "";
}
if (configFile == null) {
configFile = DATASOURCES_CONFIG_FILE;
}
configFile = baseDir + configFile;
String line = System.getProperty("line.separator");
System.out.println("**** Starting Ralasafe datasource ......");
System.out.println("\t\tDirectory: " + baseDir);
// startup datasource and regist into dsnameMap
DataSourceHelper helper = new DataSourceHelper(configFile);
List configs = helper.parseConfig();
int count = configs.size();
for (int i = 0; i < count; i++) {
DataSourceConfig config = (DataSourceConfig) configs.get(i);
Properties props = new Properties();
FileInputStream fis = null;
try {
fis = new FileInputStream(baseDir + config.getConfigFile());
props.load(fis);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
IOUtil.close(fis);
}
DataSource ds = null;
String implType = props.getProperty("type", "ralasafe");
if (implType.equalsIgnoreCase("ralasafe")) {
DataSourceProviderDbcpImpl impl = new DataSourceProviderDbcpImpl();
String validInfo = impl.getValidInfo(props);
StringBuffer buff = new StringBuffer();
buff.append(config.toString()).append(line);
if (validInfo == null) {
impl.setup(props);
impl.setName(config.getName());
ds = impl;
} else {
buff.append("Error: " + validInfo).append(line);
}
buff.append(impl).append(line);
System.out.println(buff.toString());
} else if (implType.equalsIgnoreCase("jndi")) {
DataSourceProviderJndiImpl impl = new DataSourceProviderJndiImpl();
String validInfo = impl.getValidInfo(props);
StringBuffer buff = new StringBuffer();
buff.append(config.toString()).append(line);
if (validInfo == null) {
impl.setup(props);
impl.setName(config.getName());
ds = impl;
} else {
buff.append("Error: " + validInfo).append(line);
}
buff.append(impl).append(line);
System.out.println(buff.toString());
} else if (implType.equalsIgnoreCase("method")) {
DataSourceProviderMethodImpl impl = new DataSourceProviderMethodImpl();
String validInfo = impl.getValidInfo(props);
StringBuffer buff = new StringBuffer();
buff.append(config.toString()).append(line);
if (validInfo == null) {
impl.setup(props);
impl.setName(config.getName());
ds = impl;
} else {
buff.append("Error: " + validInfo).append(line);
}
buff.append(impl).append(line);
System.out.println(buff.toString());
} else {
String msg="Can't setup data source! Unknown data source type:" + implType;
log.error( msg );
throw new RuntimeException( msg );
}
if (ds != null) {
ds.setShowAllSchemas(config.isShowAllSchemas());
ds.setSchemas(config.getSchemas());
dsnameMap.put(config.getName(), ds);
}
}
// find default app ds name (business ds name)
for (int i = 0; i < count; i++) {
DataSourceConfig config = (DataSourceConfig) configs.get(i);
String name = config.getName();
if (!name.equals("ralasafe")) {
defaultAppDsName = name;
break;
}
}
if (!dsnameMap.containsKey("ralasafe")) {
String str = "Error: no datasource with name=\"ralasafe\" found!";
System.out.println(str);
System.out.println("**** Ralasafe datasource failed!");
throw new RuntimeException();
}
System.out.println("**** Ralasafe datasource started successfully!");
}
public static int getTableId(String dsName, String tableName) {
if (StringUtil.isEmpty(dsName)) {
dsName = defaultDsName;
}
Map tableNameMap = (Map) dsTableNameMap.get(dsName);
if (tableNameMap == null) {
tableNameMap = new HashMap();
dsTableNameMap.put(dsName, tableNameMap);
}
Integer tableId = (Integer) tableNameMap.get(tableName);
if (tableId == null) {
tableId = new Integer(tableIdIndex);
tableIdIndex++;
tableNameMap.put(tableName, tableId);
DataSource ds = (DataSource) dsnameMap.get(dsName);
tableIdDsMap.put(tableId, ds);
}
return tableId.intValue();
}
/**
*
* @param entityName
* @return
* @throws SQLException
*/
public static Connection getConnection(int tableId) throws DBLevelException {
try {
DataSource ds = (DataSource) tableIdDsMap.get(new Integer(tableId));
if (ds == null) {
String msg = "No datasource found in table with tableId="
+ tableId + "";
throw new RalasafeException(msg);
// ds = (DataSource)dsnameMap.get( defaultDsName);
}
return ds.getDataSource().getConnection();
} catch (SQLException e) {
log.error( "", e );
throw new DBLevelException(e);
}
}
public static String getDatasourceName(int tableId) {
DataSource ds = (DataSource) tableIdDsMap.get(new Integer(tableId));
return ds.getName();
}
public static Connection[] getConnections(int[] tableIds)
throws DBLevelException {
Connection[] conns = new Connection[tableIds.length];
Map dsNameConnIndexMap = new HashMap();
try {
for (int i = 0; i < tableIds.length; i++) {
int tableId = tableIds[i];
DataSource ds = (DataSource) tableIdDsMap.get(new Integer(
tableId));
String name = ds.getName();
if (dsNameConnIndexMap.containsKey(name)) {
int previousIndex = ((Integer) dsNameConnIndexMap.get(name))
.intValue();
conns[i] = conns[previousIndex];
} else {
conns[i] = ds.getDataSource().getConnection();
dsNameConnIndexMap.put(name, new Integer(i));
}
}
} catch (SQLException e) {
dsNameConnIndexMap.clear();
for (int i = 0; i < conns.length; i++) {
Connection conn = conns[i];
DBUtil.close(conn);
}
throw new DBLevelException(e);
}
return conns;
}
public static Connection[] getUniqueConnections(int[] tableIds)
throws DBLevelException {
Connection[] conns = new Connection[tableIds.length];
try {
for (int i = 0; i < tableIds.length; i++) {
int tableId = tableIds[i];
DataSource ds = (DataSource) tableIdDsMap.get(new Integer(
tableId));
String name = ds.getName();
conns[i] = ds.getDataSource().getConnection();
}
} catch (SQLException e) {
for (int i = 0; i < conns.length; i++) {
Connection conn = conns[i];
DBUtil.close(conn);
}
throw new DBLevelException(e);
}
return conns;
}
public static void setMaxBatchSize(int maxBatchSize) {
DBPower.maxBatchSize = maxBatchSize;
}
public static int getMaxBatchSize() {
return maxBatchSize;
}
public static Connection getConnection(String dsName) {
if (dsName == null) {
dsName = defaultDsName;
}
DataSource ds = (DataSource) dsnameMap.get(dsName);
if (ds == null) {
String msg = "Can't get connection. Cause: datasource with name=" + dsName + " not found.";
log.error( msg );
throw new RalasafeException(msg);
}
try {
return ds.getDataSource().getConnection();
} catch (SQLException e) {
log.error( "", e );
throw new DBLevelException(e);
}
}
public static Collection getDsNames() {
return dsnameMap.keySet();
}
/**
* Return default application datasource name. If many application datasource exist, return the first one
* which it not named with 'ralasafe'.
* If no application datasource exist, return 'ralasafe'.
*
* @return
*/
public static String getDefaultAppDsName() {
return defaultAppDsName == null ? defaultDsName : defaultAppDsName;
}
public static String getDefaultDsName() {
return defaultDsName;
}
public static DataSource getDataSource(String dsName) {
return (DataSource) dsnameMap.get(dsName);
}
}
|
lazyxu/kfs | warpper/grpcweb/rootdirectory/socket.go | package rootdirectory
import (
"bufio"
"encoding/binary"
"fmt"
"io"
"net"
"os"
"strconv"
"github.com/golang/protobuf/proto"
"github.com/lazyxu/kfs/kfscore/object"
"github.com/lazyxu/kfs/warpper/grpcweb/pb"
"github.com/lazyxu/kfs/kfscore/storage"
"github.com/sirupsen/logrus"
)
const (
MethodInvalid int32 = iota
MethodUploadBlob
MethodUploadTree
MethodUpdateBranch
)
const (
CompressNone int32 = iota
CompressZlib
)
func process(conn net.Conn, s storage.Storage) {
defer conn.Close()
reader := bufio.NewReader(conn)
var headerLen uint64
err := binary.Read(reader, binary.LittleEndian, &headerLen)
if err == io.EOF {
return
}
if err != nil {
logrus.WithError(err).Error("method")
return
}
logrus.Infoln("headerLen", headerLen)
rawHeader := make([]byte, headerLen)
n, err := reader.Read(rawHeader)
if err != nil {
logrus.WithError(err).Error("branch")
return
}
if uint64(n) != headerLen {
logrus.WithField("n", n).Error("header len not enough")
return
}
var header pb.Header
err = proto.Unmarshal(rawHeader, &header)
if err != nil {
logrus.WithError(err).Error("branch")
return
}
logrus.Infoln("header", header.String())
if header.Method == MethodUploadBlob {
obj := object.Init(s)
if len(header.Hash) != 0 {
exist, err := obj.S.Exist(storage.TypBlob, header.Hash)
if err != nil {
logrus.WithError(err).Error("Exist")
return
}
if exist {
_, err = conn.Write([]byte{1})
} else {
_, err = conn.Write([]byte{0})
}
if err != nil {
logrus.WithError(err).Error("Write")
return
}
}
r := io.LimitReader(reader, int64(header.RawSize))
hash, err := obj.WriteBlob(r)
if err != nil {
logrus.WithError(err).Error("WriteBlob")
return
}
logrus.Infoln("hash", hash)
hashLen := uint8(len(hash))
err = binary.Write(conn, binary.LittleEndian, hashLen)
if err != nil {
logrus.WithError(err).Error("Write hashLen")
return
}
_, err = conn.Write([]byte(hash))
if err != nil {
logrus.WithError(err).Error("Write")
return
}
} else if header.Method == MethodUploadTree {
obj := object.Init(s)
r := io.LimitReader(reader, int64(header.RawSize))
buf := make([]byte, header.RawSize)
_, err = r.Read(buf)
if err != nil {
logrus.WithError(err).Error("Read")
return
}
infos := &pb.FileInfos{}
err = proto.Unmarshal(buf, infos)
if err != nil {
logrus.WithError(err).Error("Unmarshal")
return
}
t := obj.NewTree()
for _, info := range infos.Info {
if info == nil || info.Type == "" {
continue
}
var item *object.Metadata
if info.Type == "file" {
item = obj.NewFileMetadata(info.Name, os.FileMode(info.Mode)).Builder().
Hash(info.Hash).Size(info.Size).ChangeTime(info.CtimeNs).ModifyTime(info.MtimeNs).Build()
} else if info.Type == "dir" {
item = obj.NewDirMetadata(info.Name, os.FileMode(info.Mode)).Builder().
Hash(info.Hash).ChangeTime(info.CtimeNs).ModifyTime(info.MtimeNs).Build()
}
t.Items = append(t.Items, item)
}
hash, err := obj.WriteTree(t)
if err != nil {
logrus.WithError(err).Error("WriteTree")
return
}
logrus.Infoln("hash", hash)
hashLen := uint8(len(hash))
err = binary.Write(conn, binary.LittleEndian, hashLen)
if err != nil {
logrus.WithError(err).Error("Write hashLen")
return
}
_, err = conn.Write([]byte(hash))
if err != nil {
logrus.WithError(err).Error("Write")
return
}
}
}
func Socket(s storage.Storage, port int) {
listen, err := net.Listen("tcp", "127.0.0.1:"+strconv.Itoa(port))
if err != nil {
fmt.Printf("listen failed, err:%v\n", err)
return
}
logrus.WithField("port", port).Info("Listening socket")
for {
conn, err := listen.Accept()
if err != nil {
fmt.Printf("accept failed, err:%v\n", err)
continue
}
go process(conn, s)
}
}
|
MrSylar59/Planning-des-coursiers | src/modele/Solution.java | <reponame>MrSylar59/Planning-des-coursiers<filename>src/modele/Solution.java
package modele;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
/**
* Classe qui représente une solution à une instance donnée.
* @author thomas
*/
@Entity
public class Solution implements Serializable {
/* PARAMETRES */
private static final long serialVersionUID = 1L;
/**
* Id pour la table de la base de données
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/**
* Le cout de mise en place de la solution en fonction du nombre de shifts
*/
@Column(name = "PRIX")
private double prix;
/**
* Nom de l'algorithme utilisé pour générer la solution
*/
@Column(name = "ALGO")
private String algo;
/**
* L'instance pour laquelle la solution s'applique
*/
@JoinColumn(name = "INST_ID")
private Instance inst;
/**
* L'ensemble des shifts devant être réalisés dans la solution
*/
@OneToMany(mappedBy="solution", cascade = CascadeType.PERSIST)
private List<Shift> shifts;
/* CONSTRUCTEURS */
/**
* Constructeur par default
*/
public Solution() {
this.prix = 0;
this.shifts = new LinkedList<>();
}
/**
* Constructeur par data Instance et code algorithme
* @param inst
* @param algo
*/
public Solution(Instance inst, String algo){
this();
if (inst != null)
this.inst = inst;
if (algo != null && !algo.isBlank())
this.algo = algo;
}
/**
* Constructeur par data identifiant, prix totale, code de l'algorithme
* @param id
* @param prix
* @param algo
*/
public Solution(long id,double prix, String algo){
this();
this.id = id;
this.prix = prix;
if (algo != null && !algo.isBlank())
this.algo = algo;
}
/**
* GETTEURS
*/
public Instance getInstance(){
return this.inst;
}
public List<Shift> getShifts() {
return shifts;
}
public double getPrix() {
return prix;
}
public long getId(){
return id;
}
/**
* METHODES
*/
/**
* Fonction qui ajoute un shift à la liste des solution. Ajouter un shift
* modifie le prix de la solution.
*
* @param s le shift à ajouter à une solution
* @return renvoie true si l'ajout a été fait et false sinon
*/
public boolean AjouterShift(Shift s){
this.prix += s.getPrix();
return this.shifts.add(s);
}
/**
* Fonction permettant d'ajouter la solution en base
* @param em
*/
public void ajouterEnBase(EntityManager em){
final EntityTransaction et = em.getTransaction();
et.begin();
em.persist(this);
et.commit();
}
@Override
public int hashCode() {
int hash = 3;
hash = 41 * hash + (int) (Double.doubleToLongBits(this.prix) ^ (Double.doubleToLongBits(this.prix) >>> 32));
hash = 41 * hash + Objects.hashCode(this.algo);
hash = 41 * hash + Objects.hashCode(this.inst);
hash = 41 * hash + Objects.hashCode(this.shifts);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Solution other = (Solution) obj;
if (Double.doubleToLongBits(this.prix) != Double.doubleToLongBits(other.prix)) {
return false;
}
if (!Objects.equals(this.algo, other.algo)) {
return false;
}
if (!Objects.equals(this.inst, other.inst)) {
return false;
}
if (!Objects.equals(this.shifts, other.shifts)) {
return false;
}
return true;
}
@Override
public String toString() {
String str = "";
for (Shift s : this.shifts){
str += s;
str += "\n";
}
return "Solution{" + "prix=" + prix + ", algo=" + algo + ", shifts=\n" + str + '}';
}
}
|
putrafirman/SimpleGame-JavaWalking | lib/lwjgl-2.9.1/lwjgl-source-2.9.1/src/native/macosx/context.h | /*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* $Id$
*
* Base Win32 display
*
* @author cix_foo <<EMAIL>>
* @author mojang
* @author kappaOne <<EMAIL>>
* @version $Revision$
*/
#ifndef __LWJGL_CONTEXT_H
#define __LWJGL_CONTEXT_H
#include <Cocoa/Cocoa.h>
#include <OpenGL/gl.h>
#include <OpenGL/glext.h>
#include "common_tools.h"
#include <jawt_md.h>
enum {
NSControlLeftKeyMask = 0x0001,
NSControlRightKeyMask = 0x2000,
NSShiftLeftKeyMask = 0x0002,
NSShiftRightKeyMask = 0x0004,
NSCommandLeftKeyMask = 0x0008,
NSCommandRightKeyMask = 0x0010,
NSAlternateLeftKeyMask = 0x0020,
NSAlternateRightKeyMask = 0x0040
};
@class NSOpenGLContext, NSOpenGLPixelFormat, MacOSXOpenGLView, MacOSXKeyableWindow;
typedef struct {
MacOSXKeyableWindow *window;
NSRect display_rect;
MacOSXOpenGLView *view;
NSOpenGLContext *context;
// Native objects for Java callbacks
jobject jdisplay;
jobject jmouse;
jobject jkeyboard;
jboolean fullscreen;
jboolean undecorated;
jboolean resizable;
jboolean parented;
jboolean enableFullscreenModeAPI;
jboolean enableHighDPI;
jboolean resized;
} MacOSXWindowInfo;
@interface MacOSXOpenGLView : NSView
{
@public
MacOSXWindowInfo* _parent;
@private
NSOpenGLContext* _openGLContext;
NSOpenGLPixelFormat* _pixelFormat;
NSTrackingArea * _trackingArea;
}
+ (NSOpenGLPixelFormat*)defaultPixelFormat;
- (BOOL)windowShouldClose:(id)sender;
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender;
- (id)initWithFrame:(NSRect)frameRect pixelFormat:(NSOpenGLPixelFormat*)format;
- (void)setOpenGLContext:(NSOpenGLContext*)context;
- (NSOpenGLContext*)openGLContext;
- (void)clearGLContext;
- (void)prepareOpenGL;
- (void)update;
- (void)lockFocus;
- (void)setPixelFormat:(NSOpenGLPixelFormat*)pixelFormat;
- (NSOpenGLPixelFormat*)pixelFormat;
- (void)setParent:(MacOSXWindowInfo*)parent;
- (BOOL)acceptsFirstResponder;
@end
@interface GLLayer : CAOpenGLLayer {
@public
JAWT_MacOSXDrawingSurfaceInfo *macosx_dsi;
JAWT_Rectangle canvasBounds;
MacOSXWindowInfo *window_info;
bool setViewport;
bool autoResizable;
@private
CGLContextObj contextObject;
int fboID;
int imageRenderBufferID;
int depthRenderBufferID;
int fboWidth;
int fboHeight;
}
- (void) attachLayer;
- (void) removeLayer;
- (void) blitFrameBuffer;
- (int) getWidth;
- (int) getHeight;
@end
typedef struct {
bool isCALayer;
bool isWindowed;
MacOSXWindowInfo *window_info;
NSOpenGLPixelFormat *pixel_format;
NSOpenGLPixelBuffer *pbuffer;
NSView *parent;
GLLayer *glLayer;
} MacOSXPeerInfo;
@interface MacOSXKeyableWindow : NSWindow
+ (void)createWindow;
+ (void)destroyWindow;
- (BOOL)canBecomeKeyWindow;
@end
NSOpenGLPixelFormat *choosePixelFormat(JNIEnv *env, jobject pixel_format, bool gl32, bool use_display_bpp, bool support_window, bool support_pbuffer, bool double_buffered);
#endif
|
numberen/apollo-platform | ros/actionlib/src/actionlib/action_server.py | <reponame>numberen/apollo-platform
#! /usr/bin/env python
# Copyright (c) 2009, <NAME>, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Author: <NAME>.
# Based on C++ action_server.h by <NAME>
import rospy
import threading
from actionlib_msgs.msg import *
from actionlib.goal_id_generator import GoalIDGenerator
from actionlib.status_tracker import StatusTracker
from actionlib.handle_tracker_deleter import HandleTrackerDeleter
from actionlib.server_goal_handle import ServerGoalHandle
from actionlib.exceptions import *
def nop_cb(goal_handle):
pass
def ros_timer(callable,frequency):
rate = rospy.Rate(frequency)
rospy.logdebug("Starting timer");
while not rospy.is_shutdown():
try:
rate.sleep()
callable()
except rospy.exceptions.ROSInterruptException:
rospy.logdebug("Sleep interrupted");
## @class ActionServer
## @brief The ActionServer is a helpful tool for managing goal requests to a
## node. It allows the user to specify callbacks that are invoked when goal
## or cancel requests come over the wire, and passes back GoalHandles that
## can be used to track the state of a given goal request. The ActionServer
## makes no assumptions about the policy used to service these goals, and
## sends status for each goal over the wire until the last GoalHandle
## associated with a goal request is destroyed.
class ActionServer:
## @brief Constructor for an ActionServer
## @param ns/name A namespace for the action server
## @param actionspec An explicit specification of the action
## @param goal_cb A goal callback to be called when the ActionServer receives a new goal over the wire
## @param cancel_cb A cancel callback to be called when the ActionServer receives a new cancel request over the wire
## @param auto_start A boolean value that tells the ActionServer wheteher or not to start publishing as soon as it comes up. THIS SHOULD ALWAYS BE SET TO FALSE TO AVOID RACE CONDITIONS and start() should be called after construction of the server.
def __init__(self, ns, ActionSpec, goal_cb, cancel_cb = nop_cb, auto_start = True):
self.ns=ns;
try:
a = ActionSpec()
self.ActionSpec = ActionSpec
self.ActionGoal = type(a.action_goal)
self.ActionResult = type(a.action_result)
self.ActionResultType = type(a.action_result.result)
self.ActionFeedback = type(a.action_feedback)
except AttributeError:
raise ActionException("Type is not an action spec: %s" % str(ActionSpec))
self.goal_sub = None
self.cancel_sub = None
self.status_pub = None
self.result_pub = None
self.feedback_pub = None
self.lock = threading.RLock()
self.status_timer = None;
self.status_list = [];
self.last_cancel = rospy.Time();
self.status_list_timeout = rospy.Duration();
self.id_generator = GoalIDGenerator();
self.goal_callback = goal_cb;
assert(self.goal_callback);
self.cancel_callback = cancel_cb;
self.auto_start = auto_start;
self.started = False;
if self.auto_start:
rospy.logwarn("You've passed in true for auto_start to the python action server, you should always pass in false to avoid race conditions.")
self.start()
## @brief Register a callback to be invoked when a new goal is received, this will replace any previously registered callback
## @param cb The callback to invoke
def register_goal_callback(self, cb):
self.goal_callback = cb
## @brief Register a callback to be invoked when a new cancel is received, this will replace any previously registered callback
## @param cb The callback to invoke
def register_cancel_callback(self,cancel_cb):
self.cancel_callback = cancel_cb
## @brief Start the action server
def start(self):
with self.lock:
self.initialize();
self.started = True;
self.publish_status();
## @brief Initialize all ROS connections and setup timers
def initialize(self):
self.status_pub = rospy.Publisher(rospy.remap_name(self.ns)+"/status", GoalStatusArray, latch=True, queue_size=50);
self.result_pub = rospy.Publisher(rospy.remap_name(self.ns)+"/result", self.ActionResult, queue_size=50);
self.feedback_pub = rospy.Publisher(rospy.remap_name(self.ns)+"/feedback", self.ActionFeedback, queue_size=50);
self.goal_sub = rospy.Subscriber(rospy.remap_name(self.ns)+"/goal", self.ActionGoal,self.internal_goal_callback);
self.cancel_sub = rospy.Subscriber(rospy.remap_name(self.ns)+"/cancel", GoalID,self.internal_cancel_callback);
#read the frequency with which to publish status from the parameter server
#if not specified locally explicitly, use search param to find actionlib_status_frequency
resolved_status_frequency_name = rospy.remap_name(self.ns)+"/status_frequency"
if rospy.has_param(resolved_status_frequency_name):
self.status_frequency = rospy.get_param(resolved_status_frequency_name, 5.0);
rospy.logwarn("You're using the deprecated status_frequency parameter, please switch to actionlib_status_frequency.")
else:
search_status_frequency_name = rospy.search_param("actionlib_status_frequency")
if search_status_frequency_name is None:
self.status_frequency = 5.0
else:
self.status_frequency = rospy.get_param(search_status_frequency_name, 5.0)
status_list_timeout = rospy.get_param(rospy.remap_name(self.ns)+"/status_list_timeout", 5.0);
self.status_list_timeout = rospy.Duration(status_list_timeout);
self.status_timer = threading.Thread( None, ros_timer, None, (self.publish_status_async,self.status_frequency) );
self.status_timer.start();
## @brief Publishes a result for a given goal
## @param status The status of the goal with which the result is associated
## @param result The result to publish
def publish_result(self, status, result):
with self.lock:
ar = self.ActionResult();
ar.header.stamp = rospy.Time.now();
ar.status = status;
ar.result = result;
self.result_pub.publish(ar);
self.publish_status()
## @brief Publishes feedback for a given goal
## @param status The status of the goal with which the feedback is associated
## @param feedback The feedback to publish
def publish_feedback(self, status, feedback):
with self.lock:
af=self.ActionFeedback();
af.header.stamp = rospy.Time.now();
af.status = status;
af.feedback = feedback;
self.feedback_pub.publish(af);
## @brief The ROS callback for cancel requests coming into the ActionServer
def internal_cancel_callback(self, goal_id):
with self.lock:
#if we're not started... then we're not actually going to do anything
if not self.started:
return;
#we need to handle a cancel for the user
rospy.logdebug("The action server has received a new cancel request");
goal_id_found = False;
for st in self.status_list[:]:
#check if the goal id is zero or if it is equal to the goal id of
#the iterator or if the time of the iterator warrants a cancel
cancel_everything = (goal_id.id == "" and goal_id.stamp == rospy.Time() ) #rospy::Time()) #id and stamp 0 --> cancel everything
cancel_this_one = ( goal_id.id == st.status.goal_id.id) #ids match... cancel that goal
cancel_before_stamp = (goal_id.stamp != rospy.Time() and st.status.goal_id.stamp <= goal_id.stamp) #//stamp != 0 --> cancel everything before stamp
if cancel_everything or cancel_this_one or cancel_before_stamp:
#we need to check if we need to store this cancel request for later
if goal_id.id == st.status.goal_id.id:
goal_id_found = True;
#attempt to get the handle_tracker for the list item if it exists
handle_tracker = st.handle_tracker;
if handle_tracker is None:
#if the handle tracker is expired, then we need to create a new one
handle_tracker = HandleTrackerDeleter(self, st);
st.handle_tracker = handle_tracker;
#we also need to reset the time that the status is supposed to be removed from the list
st.handle_destruction_time = rospy.Time.now()
#set the status of the goal to PREEMPTING or RECALLING as approriate
#and check if the request should be passed on to the user
gh = ServerGoalHandle(st, self, handle_tracker);
if gh.set_cancel_requested():
#call the user's cancel callback on the relevant goal
self.cancel_callback(gh);
#if the requested goal_id was not found, and it is non-zero, then we need to store the cancel request
if goal_id.id != "" and not goal_id_found:
tracker= StatusTracker(goal_id, actionlib_msgs.msg.GoalStatus.RECALLING);
self.status_list.append(tracker)
#start the timer for how long the status will live in the list without a goal handle to it
tracker.handle_destruction_time = rospy.Time.now()
#make sure to set last_cancel_ based on the stamp associated with this cancel request
if goal_id.stamp > self.last_cancel:
self.last_cancel = goal_id.stamp;
## @brief The ROS callback for goals coming into the ActionServer
def internal_goal_callback(self, goal):
with self.lock:
#if we're not started... then we're not actually going to do anything
if not self.started:
return;
rospy.logdebug("The action server has received a new goal request");
#we need to check if this goal already lives in the status list
for st in self.status_list[:]:
if goal.goal_id.id == st.status.goal_id.id:
rospy.logdebug("Goal %s was already in the status list with status %i" % (goal.goal_id.id, st.status.status))
# Goal could already be in recalling state if a cancel came in before the goal
if st.status.status == actionlib_msgs.msg.GoalStatus.RECALLING:
st.status.status = actionlib_msgs.msg.GoalStatus.RECALLED
self.publish_result(st.status, self.ActionResultType())
#if this is a request for a goal that has no active handles left,
#we'll bump how long it stays in the list
if st.handle_tracker is None:
st.handle_destruction_time = rospy.Time.now()
#make sure not to call any user callbacks or add duplicate status onto the list
return;
#if the goal is not in our list, we need to create a StatusTracker associated with this goal and push it on
st = StatusTracker(None,None,goal)
self.status_list.append(st);
#we need to create a handle tracker for the incoming goal and update the StatusTracker
handle_tracker = HandleTrackerDeleter(self, st);
st.handle_tracker = handle_tracker;
#check if this goal has already been canceled based on its timestamp
gh= ServerGoalHandle(st, self, handle_tracker);
if goal.goal_id.stamp != rospy.Time() and goal.goal_id.stamp <= self.last_cancel:
#if it has... just create a GoalHandle for it and setCanceled
gh.set_canceled(None, "This goal handle was canceled by the action server because its timestamp is before the timestamp of the last cancel request");
else:
#now, we need to create a goal handle and call the user's callback
self.goal_callback(gh);
## @brief Publish status for all goals on a timer event
def publish_status_async(self):
rospy.logdebug("Status async");
with self.lock:
#we won't publish status unless we've been started
if not self.started:
return
self.publish_status();
## @brief Explicitly publish status
def publish_status(self):
with self.lock:
#build a status array
status_array = actionlib_msgs.msg.GoalStatusArray()
#status_array.set_status_list_size(len(self.status_list));
i=0;
while i<len(self.status_list):
st = self.status_list[i]
#check if the item is due for deletion from the status list
if st.handle_destruction_time != rospy.Time() and st.handle_destruction_time + self.status_list_timeout < rospy.Time.now():
rospy.logdebug("Item %s with destruction time of %.3f being removed from list. Now = %.3f" % \
(st.status.goal_id, st.handle_destruction_time.to_sec(), rospy.Time.now().to_sec()))
del self.status_list[i]
else:
status_array.status_list.append(st.status);
i+=1
status_array.header.stamp = rospy.Time.now()
self.status_pub.publish(status_array)
|
org-papaja/adminfly-project | adminfly/modules/mongodb-viewer/src/main/java/org/papaja/adminfly/module/mdbv/mysql/mapper/RowMapper.java | <reponame>org-papaja/adminfly-project
package org.papaja.adminfly.module.mdbv.mysql.mapper;
import org.papaja.adminfly.commons.dao.mapper.AbstractMapper;
import org.papaja.adminfly.module.mdbv.mysql.dto.RowDto;
import org.papaja.converter.Format;
import org.papaja.adminfly.module.mdbv.mysql.entity.Row;
import org.springframework.stereotype.Component;
@Component
public class RowMapper extends AbstractMapper<RowDto, Row> {
@Override
public void accept(RowDto source, Row target) {
target.setName(source.getName());
target.setPath(source.getPath());
target.setPosition(source.getPosition());
target.setType(Format.valueOf(source.getType()));
}
@Override
public Row get() {
return new Row();
}
}
|
kukkalli/oai-cn5g-fed | component/oai-amf/src/ngap/ngapIEs/RanNodeName.hpp | <reponame>kukkalli/oai-cn5g-fed
/*
* Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenAirInterface Software Alliance licenses this file to You under
* the OAI Public License, Version 1.1 (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.openairinterface.org/?page_id=698
*
* 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.
*-------------------------------------------------------------------------------
* For more information about the OpenAirInterface (OAI) Software Alliance:
* <EMAIL>
*/
/*! \file
\brief
\author <NAME>, BUPT
\date 2020
\email: <EMAIL>
*/
#ifndef _RANNODENAME_H_
#define _RANNODENAME_H_
extern "C" {
#include "Ngap_RANNodeName.h"
}
#include <string>
namespace ngap {
class RanNodeName {
public:
RanNodeName();
virtual ~RanNodeName();
void setValue(const std::string ranName);
bool encode2RanNodeName(Ngap_RANNodeName_t*);
bool decodefromRanNodeName(Ngap_RANNodeName_t*);
bool getValue(std::string& ranName);
private:
char* ranNodeName;
};
} // namespace ngap
#endif
|
jovido-projects/jovido-webseed | src/main/java/biz/jovido/seed/content/LinkAttribute.java | package biz.jovido.seed.content;
/**
* @author <NAME>
*/
public class LinkAttribute extends Attribute {
@Override
public Payload createPayload() {
return new LinkPayload();
}
}
|
npocmaka/Windows-Server-2003 | ds/adsi/router/cdso.cxx | <reponame>npocmaka/Windows-Server-2003<gh_stars>10-100
//---------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1992 - 1995
//
// File: cdso.cxx
//
// Contents: Microsoft OleDB/OleDS Data Source Object for ADSI
//
//
// History: 08-01-96 shanksh Created.
//
//------------------------------------------------------------------------------
#include "oleds.hxx"
#pragma hdrstop
extern LONG glnOledbObjCnt;
//+---------------------------------------------------------------------------
//
// Function: CDSOObject::CreateDSOObject
//
// Synopsis: Creates a new DB Session object from the DSO, and returns the
// requested interface on the newly created object.
//
// Arguments: pUnkOuter Controlling IUnknown if being aggregated
// riid The ID of the interface
// ppDBSession A pointer to memory in which to return the
// interface pointer
//
// Returns:
// S_OK The method succeeded.
// E_INVALIDARG ppDBSession was NULL
// DB_E_NOAGGREGATION pUnkOuter was not NULL (this object
// does not support being aggregated)
// E_FAIL Provider-specific error. This
// E_OUTOFMEMORY Out of memory
// E_NOINTERFACE Could not obtain requested interface on
// DBSession object
//
// Modifies:
//
// History: 08-28-96 ShankSh Created.
//
//----------------------------------------------------------------------------
HRESULT
CDSOObject::CreateDSOObject(
IUnknown * pUnkOuter,
REFIID riid,
void ** ppvObj
)
{
CDSOObject* pDSO = NULL;
HRESULT hr;
//
// check in-params and NULL out-params in case of error
//
if( ppvObj )
*ppvObj = NULL;
else
RRETURN( E_INVALIDARG );
if( pUnkOuter )// && !InlineIsEqualGUID(riid, IID_IUnknown) )
RRETURN( DB_E_NOAGGREGATION );
//
// open a DBSession object
//
pDSO = new CDSOObject(pUnkOuter);
if( !pDSO )
RRETURN( E_OUTOFMEMORY );
//
// initialize the object
//
if( !pDSO->FInit() ) {
delete pDSO;
RRETURN( E_OUTOFMEMORY );
}
//
// get requested interface pointer on DSO Object
//
hr = pDSO->QueryInterface( riid, (void **)ppvObj);
if( FAILED( hr ) ) {
delete pDSO;
RRETURN( hr );
}
pDSO->Release();
RRETURN( S_OK );
}
//+---------------------------------------------------------------------------
//
// Function: CDSOObject::Initialize
//
// Synopsis: Initializes the DataSource object.
//
// Arguments:
//
//
// Returns: HRESULT
// S_OK
// E_FAIL
//
// Modifies:
//
// History: 08-28-96 ShankSh Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP
CDSOObject::Initialize(
void
)
{
HRESULT hr = S_OK;
if( _fDSOInitialized )
RRETURN( DB_E_ALREADYINITIALIZED);
if(IsIntegratedSecurity())
{
//
// If using integrated security, we need to save the calling thread's
// security context here. Reason is that when we actually connect to
// the directory, we could be running on a different context, and we
// need to impersonate this context to work correctly.
//
if (!OpenThreadToken(
GetCurrentThread(),
TOKEN_ALL_ACCESS,
TRUE,
&_ThreadToken))
{
//
// If thread doesn't have a token, use process token
//
if (GetLastError() != ERROR_NO_TOKEN ||
!OpenProcessToken(
GetCurrentProcess(),
TOKEN_ALL_ACCESS,
&_ThreadToken))
{
GetLastError();
BAIL_ON_FAILURE(hr = E_FAIL);
}
}
}
_fDSOInitialized = TRUE;
error:
RRETURN (hr);
}
//+---------------------------------------------------------------------------
//
// Function: CDSOObject::Uninitialize
//
// Synopsis: Returns the Data Source Object to an uninitialized state
//
// Arguments:
//
//
// Returns: HRESULT
// S_OK | The method succeeded
// DB_E_OBJECTOPEN | A DBSession object was already created
//
// Modifies:
//
// History: 08-28-96 ShankSh Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP
CDSOObject::Uninitialize(
void
)
{
//
// data source object is not initialized; do nothing
//
if( !_fDSOInitialized ) {
RRETURN( S_OK );
}
else {
if( !IsSessionOpen() ) {
//
// DSO initialized, but no DBSession is open.
// So, reset DSO to uninitialized state
//
if (_ThreadToken)
{
CloseHandle(_ThreadToken);
_ThreadToken = NULL;
}
_fDSOInitialized = FALSE;
RRETURN( S_OK );
}
else {
//
// DBSession has already been created; trying to uninit
// the DSO now is an error
//
RRETURN( DB_E_OBJECTOPEN );
}
}
}
//+---------------------------------------------------------------------------
//
// Function: CDSOObject::GetProperties
//
// Synopsis: Returns current settings of all properties in the
// DBPROPFLAGS_DATASOURCE property group
//
// Arguments:
// cPropertySets count of restiction guids
// rgPropertySets restriction guids
// pcProperties count of properties returned
// pprgProperties property information returned
//
// Returns: HRESULT
// S_OK | The method succeeded
// E_FAIL | Provider specific error
// E_INVALIDARG | pcPropertyInfo or prgPropertyInfo was NULL
// E_OUTOFMEMORY | Out of memory
//
// Modifies:
//
// History: 08-28-96 ShankSh Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP
CDSOObject::GetProperties(
ULONG cPropIDSets,
const DBPROPIDSET rgPropIDSets[],
ULONG * pcPropSets,
DBPROPSET ** pprgPropSets
)
{
//
// Asserts
//
ADsAssert(_pUtilProp);
//
// If the Data Source object is initialized.
//
DWORD dwBitMask = PROPSET_DSO;
if( _fDSOInitialized )
dwBitMask |= PROPSET_INIT;
//
// Validate the GetProperties Arguments
//
HRESULT hr = _pUtilProp->GetPropertiesArgChk(
cPropIDSets,
rgPropIDSets,
pcPropSets,
pprgPropSets,
dwBitMask);
if( FAILED(hr) )
RRETURN( hr );
//
// Just pass this call on to the utility object that manages our properties
//
RRETURN( _pUtilProp->GetProperties(
cPropIDSets,
rgPropIDSets,
pcPropSets,
pprgPropSets,
dwBitMask ) );
}
//+---------------------------------------------------------------------------
//
// Function: CDSOObject::GetPropertyInfo
//
// Synopsis: Returns information about rowset and data source properties supported
// by the provider
//
// Arguments:
// cPropertySets Number of properties being asked about
// rgPropertySets Array of cPropertySets properties about
// which to return information
// pcPropertyInfoSets Number of properties for which information
// is being returned
// prgPropertyInfoSets Buffer containing default values returned
// ppDescBuffer Buffer containing property descriptions
//
// Returns: HRESULT
// S_OK | The method succeeded
// E_FAIL | Provider specific error
// E_INVALIDARG | pcPropertyInfo or prgPropertyInfo was NULL
// E_OUTOFMEMORY | Out of memory
//
// Modifies:
//
// History: 08-28-96 ShankSh Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP
CDSOObject::GetPropertyInfo(
ULONG cPropertyIDSets,
const DBPROPIDSET rgPropertyIDSets[],
ULONG * pcPropertyInfoSets,
DBPROPINFOSET ** pprgPropertyInfoSets,
WCHAR ** ppDescBuffer)
{
//
// Asserts
//
ADsAssert(_pUtilProp);
//
// Just pass this call on to the utility object that manages our properties
//
RRETURN( _pUtilProp->GetPropertyInfo(
cPropertyIDSets,
rgPropertyIDSets,
pcPropertyInfoSets,
pprgPropertyInfoSets,
ppDescBuffer,
_fDSOInitialized) );
}
//+---------------------------------------------------------------------------
//
// Function: CDSOObject::SetProperties
//
// Synopsis: Set properties in the DBPROPFLAGS_DATASOURCE property group
//
// Arguments:
// cPropertySets
// rgPropertySets
//
// Returns: HRESULT
// E_INVALIDARG | cProperties was not equal to 0 and
// rgProperties was NULL
// E_FAIL | Provider specific error
//
// Modifies:
//
// History: 08-28-96 ShankSh Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP
CDSOObject::SetProperties(
ULONG cPropertySets,
DBPROPSET rgPropertySets[]
)
{
//
// Asserts
//
ADsAssert(_pUtilProp);
//
// If the Data Source object is initialized.
//
DWORD dwBitMask = PROPSET_DSO;
if( _fDSOInitialized )
dwBitMask |= PROPSET_INIT;
//
// Just pass this call on to the utility object that manages our properties
//
RRETURN( _pUtilProp->SetProperties(
cPropertySets,
rgPropertySets,
dwBitMask) );
}
//+---------------------------------------------------------------------------
//
// Function: CDSOObject::GetClassID
//
// Synopsis:
//
// Arguments:
//
//
//
// Returns:
//
//
//
//
// Modifies:
//
// History: 08-28-96 ShankSh Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP
CDSOObject::GetClassID(
CLSID * pClassID
)
{
if( pClassID )
{
memcpy(pClassID, &CLSID_ADsDSOObject, sizeof(CLSID));
RRETURN( S_OK );
}
RRETURN( E_FAIL );
}
//+---------------------------------------------------------------------------
//
// Function: CDSOObject::CreateSession
//
// Synopsis: Creates a new DB Session object from the DSO, and returns the
// requested interface on the newly created object.
//
// Arguments:
// pUnkOuter, Controlling IUnknown if being aggregated
// riid, The ID of the interface
// ppDBSession A pointer to memory in which to return the
// interface pointer
//
// Returns: HRESULT
// S_OK The method succeeded.
// E_INVALIDARG ppDBSession was NULL
// DB_E_NOAGGREGATION pUnkOuter was not NULL (this object
// does not support being aggregated)
// E_FAIL Provider-specific error. This
// provider can only create one DBSession
// E_OUTOFMEMORY Out of memory
// E_NOINTERFACE Could not obtain requested interface
// on DBSession object
//
// Modifies:
//
// History: 08-28-96 ShankSh Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP
CDSOObject::CreateSession(
IUnknown * pUnkOuter,
REFIID riid,
IUnknown ** ppDBSession
)
{
CSessionObject* pDBSession = NULL;
HRESULT hr;
BOOL fSuccess;
//
// check in-params and NULL out-params in case of error
//
if( ppDBSession )
*ppDBSession = NULL;
else
RRETURN( E_INVALIDARG );
if( pUnkOuter )//&& !InlineIsEqualGUID(riid, IID_IUnknown) )
RRETURN( DB_E_NOAGGREGATION );
if( !_fDSOInitialized ) {
RRETURN(E_UNEXPECTED);
}
//
// open a DBSession object
//
pDBSession = new CSessionObject(pUnkOuter);
if( !pDBSession )
RRETURN( E_OUTOFMEMORY );
//
// initialize the object
//
if( _pUtilProp->IsIntegratedSecurity() )
{
CCredentials tempCreds;
tempCreds.SetUserName(NULL);
tempCreds.SetPassword(<PASSWORD>);
tempCreds.SetAuthFlags(_Credentials.GetAuthFlags());
fSuccess = pDBSession->FInit(this, tempCreds);
}
else
{
fSuccess = pDBSession->FInit(this, _Credentials);
}
if (!fSuccess) {
delete pDBSession;
RRETURN( E_OUTOFMEMORY );
}
//
// get requested interface pointer on DBSession
//
hr = pDBSession->QueryInterface( riid, (void **) ppDBSession );
if( FAILED( hr ) ) {
delete pDBSession;
RRETURN( hr );
}
pDBSession->Release();
RRETURN( S_OK );
}
//+-----------------------------------------------------------------------------
//
// Function: CDSOObject::CDSOObject
//
// Synopsis: Constructor
//
// Arguments:
// pUnkOuter Outer Unkown Pointer
//
// Returns:
//
// Modifies:
//
// History: 08-28-96 ShankSh Created.
//
//----------------------------------------------------------------------------
CDSOObject::CDSOObject(
LPUNKNOWN pUnkOuter
)
{
// Initialize simple member vars
_pUnkOuter = pUnkOuter ? pUnkOuter : (IDBInitialize FAR *) this;
_fDSOInitialized = FALSE;
_cSessionsOpen = FALSE;
_pUtilProp = NULL;
_ThreadToken = NULL;
// Set defaults
_Credentials.SetUserName(NULL);
_Credentials.SetPassword(<PASSWORD>);
_Credentials.SetAuthFlags(0);
ENLIST_TRACKING(CDSOObject);
// make sure DLL isn't unloaded until all data source objects are destroyed
InterlockedIncrement(&glnOledbObjCnt);
}
//+---------------------------------------------------------------------------
//
// Function: CDSOObject::~CDSOObject
//
// Synopsis: Destructor
//
// Arguments:
//
// Returns:
//
// Modifies:
//
// History: 08-28-96 ShankSh Created.
//
//----------------------------------------------------------------------------
CDSOObject::~CDSOObject( )
{
//
// Free properties management object
//
delete _pUtilProp;
if (_ThreadToken)
CloseHandle(_ThreadToken);
InterlockedDecrement(&glnOledbObjCnt);
}
//+---------------------------------------------------------------------------
//
// Function: CDSOObject::FInit
//
// Synopsis: Initialize the data source Object
//
// Arguments:
//
// Returns:
// Did the Initialization Succeed
// TRUE Initialization succeeded
// FALSE Initialization failed
//
// Modifies:
//
// History: 08-28-96 ShankSh Created.
//
//----------------------------------------------------------------------------
BOOL CDSOObject::FInit(
void
)
{
HRESULT hr;
//
// Allocate properties management object
//
_pUtilProp = new CUtilProp();
if( !_pUtilProp )
return FALSE;
hr = _pUtilProp->FInit(&_Credentials);
BAIL_ON_FAILURE( hr );
return TRUE;
error:
return FALSE;
}
//+---------------------------------------------------------------------------
//
// Function: CDSOObject::QueryInterface
//
// Synopsis: Returns a pointer to a specified interface. Callers use
// QueryInterface to determine which interfaces the called object
// supports.
//
// Arguments:
// riid Interface ID of the interface being queried for
// ppv Pointer to interface that was instantiated
//
// Returns:
// S_OK Interface is supported and ppvObject is set.
// E_NOINTERFACE Interface is not supported by the object
// E_INVALIDARG One or more arguments are invalid.
//
// Modifies:
//
// History: 08-28-96 ShankSh Created.
//
//----------------------------------------------------------------------------
STDMETHODIMP
CDSOObject::QueryInterface(REFIID iid, LPVOID FAR* ppv)
{
if( ppv == NULL )
RRETURN( E_INVALIDARG );
if( IsEqualIID(iid, IID_IUnknown) ) {
*ppv = (IDBInitialize FAR *) this;
}
else if( IsEqualIID(iid, IID_IDBInitialize) ) {
*ppv = (IDBInitialize FAR *) this;
}
else if( IsEqualIID(iid, IID_IDBProperties) ) {
*ppv = (IDBProperties FAR *) this;
}
else if( _fDSOInitialized &&
IsEqualIID(iid, IID_IDBCreateSession) ) {
*ppv = (IDBCreateSession FAR *) this;
}
else if( IsEqualIID(iid, IID_IPersist) ) {
*ppv = (IPersist FAR *) this;
}
else {
*ppv = NULL;
return E_NOINTERFACE;
}
AddRef();
return NOERROR;
}
|
hwxiasn/archetypes | ygb/ygb-cms/src/main/java/com/qingbo/ginkgo/ygb/cms/repository/ArticlePublishTaskRepository.java | package com.qingbo.ginkgo.ygb.cms.repository;
import com.qingbo.ginkgo.ygb.base.repository.BaseRepository;
import com.qingbo.ginkgo.ygb.cms.entity.ArticlePublishTask;
public interface ArticlePublishTaskRepository extends BaseRepository<ArticlePublishTask> {
}
|
idorom/Library-Project | src/Model/Review.java | package Model;
import java.io.Serializable;
public class Review implements Serializable {
private static final long serialVersionUID = 6000L;
/** the review Paragraph.**/
private String readerFirstName;
/** the review Paragraph.**/
private String readerLastName;
/** the review Paragraph.**/
private String bookName;
/** the review Paragraph.**/
private String reviewSentence;
/*** the Item review score.*/
private int rate;
/**
* Full constructor.
*
* @param reviewParagraph review Paragraph.
* @param score the Item review score.
* @param reviewerId the reviewer Id.
*/
public Review(String readerFirstName, String readerLastName, String bookName, String reviewSentence, int rate) {
this.readerFirstName=readerFirstName;
this.readerLastName=readerLastName;
this.bookName=bookName;
this.reviewSentence = reviewSentence;
this.rate = rate;
}
/**
* return the score review
*/
public int getRate() {
return this.rate;
}
/**
* return the review Paragraph
*/
public String getSentence() {
return this.reviewSentence;
}
/**
* return the reviewer Id
*/
public String getReaderFirstName() {
return this.readerFirstName;
}
/**
* return the reviewer Id
*/
public String getReaderLaststName() {
return this.readerLastName;
}
/**
* return the reviewer Id
*/
public String BookName() {
return this.bookName;
}
@Override
public String toString() {
return "review - item name: " + bookName + ", reader name: "+ readerFirstName +" " + readerLastName + ", rate: " + rate;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((bookName == null) ? 0 : bookName.hashCode());
result = prime * result + ((readerFirstName == null) ? 0 : readerFirstName.hashCode());
result = prime * result + ((readerLastName == null) ? 0 : readerLastName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Review other = (Review) obj;
if (bookName == null) {
if (other.bookName != null)
return false;
} else if (!bookName.equals(other.bookName))
return false;
if (readerFirstName == null) {
if (other.readerFirstName != null)
return false;
} else if (!readerFirstName.equals(other.readerFirstName))
return false;
if (readerLastName == null) {
if (other.readerLastName != null)
return false;
} else if (!readerLastName.equals(other.readerLastName))
return false;
return true;
}
}
|
letmeupgradeya/kibana | x-pack/plugins/maps/public/components/widget_overlay/layer_control/layer_toc/view.js | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import _ from 'lodash';
import React from 'react';
import {
EuiDragDropContext,
EuiDroppable,
EuiDraggable,
} from '@elastic/eui';
import { TOCEntry } from './toc_entry';
export class LayerTOC extends React.Component {
componentWillUnmount() {
this._updateDebounced.cancel();
}
shouldComponentUpdate() {
this._updateDebounced();
return false;
}
_updateDebounced = _.debounce(this.forceUpdate, 100);
_onDragEnd = ({ source, destination }) => {
// Dragging item out of EuiDroppable results in destination of null
if (!destination) {
return;
}
// Layer list is displayed in reverse order so index needs to reversed to get back to original reference.
const reverseIndex = (index) => {
return this.props.layerList.length - index - 1;
};
const prevIndex = reverseIndex(source.index);
const newIndex = reverseIndex(destination.index);
const newOrder = [];
for(let i = 0; i < this.props.layerList.length; i++) {
newOrder.push(i);
}
newOrder.splice(prevIndex, 1);
newOrder.splice(newIndex, 0, prevIndex);
this.props.updateLayerOrder(newOrder);
};
_renderLayers() {
// Reverse layer list so first layer drawn on map is at the bottom and
// last layer drawn on map is at the top.
const reverseLayerList = [...this.props.layerList].reverse();
if (this.props.isReadOnly) {
return reverseLayerList
.map((layer) => {
return (
<TOCEntry
key={layer.getId()}
layer={layer}
/>
);
});
}
return (
<EuiDragDropContext onDragEnd={this._onDragEnd}>
<EuiDroppable droppableId="mapLayerTOC" spacing="none">
{(provided, snapshot) => (
reverseLayerList.map((layer, idx) => (
<EuiDraggable
spacing="none"
key={layer.getId()}
index={idx}
draggableId={layer.getId()}
customDragHandle={true}
disableInteractiveElementBlocking // Allows button to be drag handle
>
{(provided, state) => (
<TOCEntry
layer={layer}
dragHandleProps={provided.dragHandleProps}
isDragging={state.isDragging}
isDraggingOver={snapshot.isDraggingOver}
/>
)}
</EuiDraggable>
))
)}
</EuiDroppable>
</EuiDragDropContext>
);
}
render() {
return (
<div data-test-subj="mapLayerTOC">
{this._renderLayers()}
</div>
);
}
}
|
gengwg/leetcode | 101_symmetric_tree.py | <gh_stars>1-10
"""
101 Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def isSymmetric(self, root):
"""
http://www.cnblogs.com/zuoyuan/p/3747174.html
check if root.left==root.right.
if equal, check root.left.left==root.right.right && root.left.right==root.right.left
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
return self.helper(root.left, root.right)
def helper(self, p, q):
if p is None and q is None:
return True
if p and q and p.val == q.val:
return self.helper(p.left, q.right) and self.helper(p.right, q.left)
return False
# ref 100
def helper(self, p, q):
if p is None and q is None:
return True
if p is None or q is None:
return False
if p.val != q.val:
return False
return self.helper(p.left, q.right) and self.helper(p.right, q.left)
|
ska-telescope/lmc-base-classes | setup.py | #!/usr/bin/env python
import os
import sys
import setuptools
setup_dir = os.path.dirname(os.path.abspath(__file__))
release_filename = os.path.join(setup_dir, "src", "ska_tango_base", "release.py")
exec(open(release_filename).read())
# prevent unnecessary installation of pytest-runner
needs_pytest = {"pytest", "test", "ptr"}.intersection(sys.argv)
pytest_runner = ["pytest-runner"] if needs_pytest else []
setuptools.setup(
name=name,
description=description,
version=version,
author=author,
author_email=author_email,
license=license,
packages=setuptools.find_packages("src"),
package_dir={"": "src"},
include_package_data=True,
url="https://www.skatelescope.org/",
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: Other/Proprietary License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Scientific/Engineering :: Astronomy",
],
platforms=["OS Independent"],
setup_requires=[] + pytest_runner,
install_requires=[
"debugpy",
"numpy",
"pytango",
"ska_ser_logging",
"transitions",
],
tests_require=["pytest", "coverage", "pytest-json-report", "pytest-forked"],
entry_points={
"console_scripts": [
"SKAAlarmHandler=ska_tango_base.alarm_handler_device:main",
"SKABaseDevice=ska_tango_base.base.base_device:main",
"SKACapability=ska_tango_base.capability_device:main",
"SKAExampleDevice=ska_tango_base.example_device:main",
"SKALogger=ska_tango_base.logger_device:main",
"SKAController=ska_tango_base.controller_device:main",
"SKAObsDevice=ska_tango_base.obs.obs_device:main",
"SKASubarray=ska_tango_base.subarray.subarray_device:main",
"SKATelState=ska_tango_base.tel_state_device:main",
"CspSubelementController=ska_tango_base.csp_subelement_controller:main",
"CspSubelementObsDevice=ska_tango_base.csp_subelement_obsdevice:main",
"CspSubelementSubarray=ska_tango_base.csp_subelement_subarray:main",
]
},
keywords="tango lmc base classes ska",
zip_safe=False,
)
|
KaiSta/SpeedyGo | traceReplay/detector/preciseTsanee/ptsanee.go | <reponame>KaiSta/SpeedyGo<gh_stars>1-10
package ptsanee
import (
"fmt"
"github.com/xojoc/bitset"
"../../util"
algos "../analysis"
"../report"
"../traceReplay"
)
type ListenerAsyncSnd struct{}
type ListenerAsyncRcv struct{}
type ListenerDataAccess struct{}
type ListenerGoFork struct{}
type ListenerGoWait struct{}
type ListenerNT struct{}
type ListenerNTWT struct{}
type ListenerPostProcess struct{}
type EventCollector struct {
listeners []traceReplay.EventListener
}
var phase = 1
var lockClues map[uint32]bitset.BitSet
var minimalThread map[uint32]thread
var minimalVar map[uint32]*minVar
var minimalLock map[uint32]minLock
type minVar struct {
lwlocks map[uint32]struct{}
lwVC vcepoch
}
func newMinVar() *minVar {
return &minVar{lwlocks: make(map[uint32]struct{}), lwVC: newvc2()}
}
type minLock struct {
rel vcepoch
count int
acq epoch
nextacq epoch
end epoch
}
func (l *EventCollector) Put(p *util.SyncPair) {
if phase == 2 {
for _, l := range l.listeners {
l.Put(p)
}
} else {
t1, ok := minimalThread[p.T1]
if !ok {
t1 = newT(p.T1)
}
if p.Lock {
t1.ls[p.T2] = struct{}{}
lock, ok := minimalLock[p.T2]
if !ok {
lock = minLock{rel: newvc2()}
}
lock.count++
lock.nextacq = newEpoch(p.T1, t1.vc.get(p.T1))
t1.vc = t1.vc.ssync(lock.rel)
minimalLock[p.T2] = lock
} else if p.Unlock {
delete(t1.ls, p.T2)
lock := minimalLock[p.T2]
lock.acq = lock.nextacq
lock.end = newEpoch(p.T1, t1.vc.get(p.T1))
minimalLock[p.T2] = lock
} else if p.Write {
varstate, ok := minimalVar[p.T2]
if !ok {
varstate = newMinVar()
}
varstate.lwVC = t1.vc.clone()
varstate.lwlocks = make(map[uint32]struct{})
for k := range t1.ls {
varstate.lwlocks[k] = struct{}{}
}
minimalVar[p.T2] = varstate
} else if p.Read {
varstate, ok := minimalVar[p.T2]
if !ok {
varstate = newMinVar()
}
t1.vc = t1.vc.ssync(varstate.lwVC)
for k := range t1.ls {
lock, ok := minimalLock[k]
//fmt.Println(lock)
if !ok {
fmt.Println("FOOOO???")
}
lock.rel = lock.rel.ssync(varstate.lwVC)
lastOwner := lock.acq.t
localTimeForLastOwner := t1.vc.get(lastOwner)
relTimeForLastOwner := lock.end.v
//fmt.Println(lastOwner, localTimeForLastOwner, relTimeForLastOwner)
if lock.acq.v < localTimeForLastOwner && localTimeForLastOwner < relTimeForLastOwner {
lockclue := lockClues[k]
lockclue.Set(lock.count)
lockClues[k] = lockclue
//fmt.Println(">>>>>>>>>>>>>", k, lock.count)
}
minimalLock[k] = lock
if _, ok := varstate.lwlocks[k]; ok {
lcount := minimalLock[k]
lockclue := lockClues[k]
lockclue.Set(lcount.count)
lockClues[k] = lockclue
}
}
} else if p.PostProcess {
phase++
locks = make(map[uint32]lock)
threads = make(map[uint32]thread)
signalList = make(map[uint32]vcepoch)
variables = make(map[uint32]*variable)
volatiles = make(map[uint32]vcepoch)
notifies = make(map[uint32]vcepoch)
minimalThread = nil
minimalVar = nil
minimalLock = nil
return
}
t1.vc = t1.vc.add(p.T1, 1)
minimalThread[p.T1] = t1
}
}
func Init() {
locks = make(map[uint32]lock)
threads = make(map[uint32]thread)
signalList = make(map[uint32]vcepoch)
variables = make(map[uint32]*variable)
volatiles = make(map[uint32]vcepoch)
notifies = make(map[uint32]vcepoch)
phase = 1
lockClues = make(map[uint32]bitset.BitSet)
minimalThread = make(map[uint32]thread)
minimalVar = make(map[uint32]*minVar)
minimalLock = make(map[uint32]minLock)
listeners := []traceReplay.EventListener{
&ListenerAsyncSnd{},
&ListenerAsyncRcv{},
&ListenerDataAccess{},
&ListenerGoFork{},
&ListenerGoWait{},
&ListenerNT{},
&ListenerNTWT{},
&ListenerPostProcess{},
}
algos.RegisterDetector("ptsanee", &EventCollector{listeners})
}
var threads map[uint32]thread
var locks map[uint32]lock
var signalList map[uint32]vcepoch
var variables map[uint32]*variable
var volatiles map[uint32]vcepoch
var notifies map[uint32]vcepoch
type thread struct {
vc vcepoch
hb vcepoch
ls map[uint32]struct{}
lsVC map[uint32]vcepoch
lsboo map[uint32]bool
strongSync uint32
}
type lock struct {
rel vcepoch
hb vcepoch
acqRel []vcPair
count int
acq epoch
nextAcq epoch
}
func newT(id uint32) thread {
return thread{vc: newvc2().set(id, 1), hb: newvc2().set(id, 1), ls: make(map[uint32]struct{}),
lsVC: make(map[uint32]vcepoch), lsboo: make(map[uint32]bool)}
}
func newL() lock {
return lock{rel: newvc2(), hb: newvc2(), acqRel: make([]vcPair, 0)}
}
type vcPair struct {
owner uint32
acq epoch
rel vcepoch
}
type pair struct {
*dot
a bool
}
type read struct {
File uint32
Line uint32
T uint32
}
type variable struct {
races []datarace
history []variableHistory
frontier []*dot
graph *fsGraph
lastWrite vcepoch
lwLocks map[uint32]struct{}
lwDot *dot
current int
}
func newVar() *variable {
return &variable{lastWrite: newvc2(), lwDot: nil, frontier: make([]*dot, 0),
current: 0, graph: newGraph(), races: make([]datarace, 0),
history: make([]variableHistory, 0), lwLocks: make(map[uint32]struct{})}
}
type dataRace struct {
raceAcc int
prevAcc int
}
type variableHistory struct {
sourceRef uint32
t uint32
c uint32
line uint16
isWrite bool
}
type dot struct {
int
v vcepoch
ls map[uint32]struct{}
sourceRef uint32
pos int
line uint16
t uint16
write bool
}
type datarace struct {
d1 *dot
d2 *dot
}
const maxsize = 25
type node struct {
neighbors []int
d *dot
}
type fsGraph struct {
ds []node
}
func newGraph() *fsGraph {
return &fsGraph{ds: make([]node, 0)}
}
func (g *fsGraph) add(nd *dot, dots []*dot) {
if len(g.ds) >= maxsize {
g.ds = g.ds[1:] //remove first element by shifting the array one to the left
}
newNode := node{d: nd}
for _, d := range dots {
newNode.neighbors = append(newNode.neighbors, d.int) //only the ints, not the dots otherwise the dots would live on in the memory
}
g.ds = append(g.ds, newNode)
}
func (v *variable) updateGraph3(nf *dot, of []*dot) {
v.graph.add(nf, of)
}
func (g *fsGraph) get(dID int) ([]*dot, bool) {
left, right := 0, len(g.ds)-1
for left <= right {
mid := left + ((right - left) / 2)
if g.ds[mid].d.int == dID {
dots := make([]*dot, 0, len(g.ds[mid].neighbors))
for _, n := range g.ds[mid].neighbors {
if d := g.find_internal(n); d != nil {
//neighbour dot still in graph
dots = append(dots, d)
}
}
return dots, true
}
if g.ds[mid].d.int > dID {
right = mid - 1
} else {
left = mid + 1
}
}
return nil, false
}
func (g *fsGraph) find_internal(dID int) *dot {
left, right := 0, len(g.ds)-1
for left <= right {
mid := left + ((right - left) / 2)
if g.ds[mid].d.int == dID {
return g.ds[mid].d
}
if g.ds[mid].d.int > dID {
right = mid - 1
} else {
left = mid + 1
}
}
return nil
}
func (l *ListenerAsyncRcv) Put(p *util.SyncPair) {
if !p.AsyncRcv {
return
}
if !p.Unlock {
return
}
lock, ok := locks[p.T2]
if !ok {
lock = newL()
}
t1, ok := threads[p.T1]
if !ok {
t1 = newT(p.T1)
}
//fmt.Println(t1.vc)
lock.acq = lock.nextAcq
lock.hb = lock.hb.ssync(t1.vc)
lock.acqRel = append(lock.acqRel, vcPair{p.T1, newEpoch(lock.acq.t, lock.acq.v), lock.hb.clone()})
// for _, v := range t1.lsVC {
// lock.rel = lock.rel.ssync(v)
// }
for _, v := range t1.lsboo {
if v {
lock.rel = lock.rel.ssync(t1.vc)
break
}
}
delete(t1.ls, p.T2)
delete(t1.lsVC, p.T2)
delete(t1.lsboo, p.T2)
t1.vc = t1.vc.add(p.T1, 1)
threads[p.T1] = t1
locks[p.T2] = lock
}
func (l *ListenerAsyncRcv) PutOld(p *util.SyncPair) {
if !p.AsyncRcv {
return
}
if !p.Unlock {
return
}
lock, ok := locks[p.T2]
if !ok {
lock = newL()
}
t1, ok := threads[p.T1]
if !ok {
t1 = newT(p.T1)
}
lock.hb = lock.hb.ssync(t1.vc)
delete(t1.ls, p.T2)
t1.vc = t1.vc.add(p.T1, 1) //inc(Th(i),i)
t1.hb = t1.hb.add(p.T1, 1)
if t1.strongSync == p.T2 {
t1.strongSync = 0
} else if t1.strongSync > 0 {
lock.rel = lock.rel.ssync(t1.vc)
}
threads[p.T1] = t1
locks[p.T2] = lock
}
func (l *ListenerAsyncSnd) Put(p *util.SyncPair) {
if !p.AsyncSend {
return
}
if !p.Lock {
return
}
lock, ok := locks[p.T2]
if !ok {
lock = newL()
}
t1, ok := threads[p.T1]
if !ok {
t1 = newT(p.T1)
}
// fmt.Println(t1.vc)
lock.nextAcq = newEpoch(p.T1, t1.vc.get(p.T1))
lock.count++
t1.vc = t1.vc.ssync(lock.rel) //sync only wrds
t1.ls[p.T2] = struct{}{} //inlcude lock to lockset
clue := lockClues[p.T2]
if clue.Get(lock.count) {
t1.lsVC[p.T2] = lock.hb
t1.lsboo[p.T2] = true
} else {
t1.lsVC[p.T2] = newvc2()
t1.lsboo[p.T2] = false
}
t1.vc = t1.vc.add(p.T1, 1)
threads[p.T1] = t1
locks[p.T2] = lock
}
func (l *ListenerAsyncSnd) PutOld(p *util.SyncPair) {
if !p.AsyncSend {
return
}
if !p.Lock {
return
}
lock, ok := locks[p.T2]
if !ok {
lock = newL()
}
t1, ok := threads[p.T1]
if !ok {
t1 = newT(p.T1)
}
lock.count++
t1.vc = t1.vc.ssync(lock.rel) //Th(i) = Th(i) U Rel(x)
t1.hb = t1.hb.ssync(lock.hb) // Th(i)_hb = Th(i)_hb U Rel(x)_hb (hb synchro)
t1.ls[p.T2] = struct{}{}
clue := lockClues[p.T2]
if clue.Get(lock.count) && t1.strongSync == 0 { //check for 0 if outer lock already claimed strongSync, so we do not overwrite it
// t1.vc = t1.vc.ssync(lock.hb)
t1.strongSync = p.T2
}
t1.vc = t1.vc.add(p.T1, 1)
t1.hb = t1.hb.add(p.T1, 1)
threads[p.T1] = t1
locks[p.T2] = lock
}
var startDot = dot{int: 0}
//intersect returns true if the two sets have at least one element in common
func intersect(a, b map[uint32]struct{}) bool {
for k := range a {
if _, ok := b[k]; ok {
return true
}
}
return false
}
func (l *ListenerDataAccess) Put(p *util.SyncPair) {
if !p.DataAccess {
return
}
t1, ok := threads[p.T1]
if !ok {
t1 = newT(p.T1)
}
varstate, ok := variables[p.T2]
if !ok {
varstate = newVar()
}
varstate.current++
newFE := &dot{v: t1.vc.clone(), int: varstate.current, t: uint16(p.T1),
sourceRef: p.Ev.Ops[0].SourceRef, line: uint16(p.Ev.Ops[0].Line),
write: p.Write, ls: make(map[uint32]struct{}), pos: p.Ev.LocalIdx}
for k := range t1.ls { //copy lockset
newFE.ls[k] = struct{}{}
}
if p.Write {
//fmt.Println(t1.vc)
newFrontier := make([]*dot, 0, len(varstate.frontier))
connectTo := make([]*dot, 0)
for _, f := range varstate.frontier {
k := f.v.get(uint32(f.t))
thi_at_j := t1.vc.get(uint32(f.t))
if k > thi_at_j {
newFrontier = append(newFrontier, f) // RW(x) = {j#k | j#k ∈ RW(x) ∧ k > Th(i)[j]}
if !intersect(newFE.ls, f.ls) {
report.ReportRace(report.Location{File: uint32(f.sourceRef), Line: uint32(f.line), W: f.write},
report.Location{File: p.Ev.Ops[0].SourceRef, Line: p.Ev.Ops[0].Line, W: newFE.write}, false, 0)
}
visited := &bitset.BitSet{}
varstate.findRaces(newFE, f, visited, 0)
} else if k < thi_at_j {
connectTo = append(connectTo, f)
}
}
varstate.updateGraph3(newFE, connectTo)
newFrontier = append(newFrontier, newFE) // ∪{i#Th(i)[i]}
varstate.frontier = newFrontier
varstate.lastWrite = t1.vc.clone()
for _, v := range t1.lsVC {
varstate.lastWrite = varstate.lastWrite.ssync(v)
}
varstate.lwLocks = make(map[uint32]struct{})
for k := range t1.ls {
varstate.lwLocks[k] = struct{}{}
}
varstate.lwDot = newFE
//t1.vc = t1.vc.add(p.T1, 1)
list, ok := varstate.graph.get(newFE.int)
if ok && len(list) == 0 {
list = append(list, &startDot)
varstate.graph.add(newFE, list)
}
} else if p.Read {
newFE.v = newFE.v.ssync(varstate.lastWrite) //sync with last write in advance, necessary for the graph analysis in the following loop!
// fmt.Println(newFE.v)
newFrontier := make([]*dot, 0, len(varstate.frontier))
connectTo := make([]*dot, 0)
for _, f := range varstate.frontier {
k := f.v.get(uint32(f.t)) //j#k
thi_at_j := t1.vc.get(uint32(f.t)) //Th(i)[j]
if k > thi_at_j {
newFrontier = append(newFrontier, f) // RW(x) = {j]k | j]k ∈ RW(x) ∧ k > Th(i)[j]}
if f.write {
if !intersect(newFE.ls, f.ls) {
report.ReportRace(report.Location{File: uint32(f.sourceRef), Line: uint32(f.line), W: f.write},
report.Location{File: p.Ev.Ops[0].SourceRef, Line: p.Ev.Ops[0].Line, W: newFE.write}, false, 0)
}
visited := &bitset.BitSet{}
varstate.findRaces(newFE, f, visited, 0)
}
} else {
if f.int > 0 {
connectTo = append(connectTo, f)
}
if f.write {
newFrontier = append(newFrontier, f)
}
}
}
//write-read sync
t1.vc = t1.vc.ssync(varstate.lastWrite) //Th(i) = max(Th(i),L W (x))
newFE.v = t1.vc.clone()
varstate.updateGraph3(newFE, connectTo)
newFrontier = append(newFrontier, newFE) // ∪{i#Th(i)[i]}
varstate.frontier = newFrontier
//connect to artifical start dot if no connection exists
list, ok := varstate.graph.get(newFE.int)
if ok && len(list) == 0 {
list = append(list, &startDot)
varstate.graph.add(newFE, list)
}
for k := range t1.ls {
lk := locks[k]
lk.rel = lk.rel.ssync(varstate.lastWrite) // collect lastwrite vcs in rel for each owned lock
locks[k] = lk
for _, p := range lk.acqRel {
localTimeForLastOwner := t1.vc.get(p.owner)
relTimeForLastOwner := p.rel.get(p.owner)
if p.acq.v < localTimeForLastOwner && localTimeForLastOwner < relTimeForLastOwner {
t1.vc = t1.vc.ssync(p.rel)
}
}
// lastOwner := lk.acq.t
// localTimeForLastOwner := t1.vc.get(lastOwner)
// relTimeForLastOwner := lk.hb.get(lastOwner)
// if lk.acq.v < localTimeForLastOwner && localTimeForLastOwner < relTimeForLastOwner {
// t1.vc = t1.vc.ssync(lk.hb)
// }
}
} else { //volatile synchronize
vol, ok := volatiles[p.T2]
if !ok {
vol = newvc2()
}
t1.vc = t1.vc.ssync(vol)
vol = t1.vc.clone()
for _, v := range t1.lsVC {
vol = vol.ssync(v)
}
volatiles[p.T2] = vol
}
t1.vc = t1.vc.add(p.T1, 1)
threads[p.T1] = t1
variables[p.T2] = varstate
}
func (l *ListenerDataAccess) PutOld(p *util.SyncPair) {
if !p.DataAccess {
return
}
t1, ok := threads[p.T1]
if !ok {
t1 = newT(p.T1)
}
varstate, ok := variables[p.T2]
if !ok {
varstate = newVar()
}
if p.Write {
varstate.current++
newFE := &dot{v: t1.vc.clone(), int: varstate.current, t: uint16(p.T1),
sourceRef: p.Ev.Ops[0].SourceRef, line: uint16(p.Ev.Ops[0].Line),
write: true, ls: make(map[uint32]struct{}), pos: p.Ev.LocalIdx}
for k := range t1.ls { //copy lockset
newFE.ls[k] = struct{}{}
}
newFrontier := make([]*dot, 0, len(varstate.frontier))
connectTo := make([]*dot, 0)
for _, f := range varstate.frontier {
k := f.v.get(uint32(f.t))
thi_at_j := t1.vc.get(uint32(f.t))
if k > thi_at_j {
newFrontier = append(newFrontier, f) // RW(x) = {j#k | j#k ∈ RW(x) ∧ k > Th(i)[j]}
if !intersect(newFE.ls, f.ls) {
report.ReportRace(report.Location{File: uint32(f.sourceRef), Line: uint32(f.line), W: f.write},
report.Location{File: p.Ev.Ops[0].SourceRef, Line: p.Ev.Ops[0].Line, W: newFE.write}, false, 0)
}
visited := &bitset.BitSet{}
varstate.findRaces(newFE, f, visited, 0)
} else if k < thi_at_j {
connectTo = append(connectTo, f)
}
}
varstate.updateGraph3(newFE, connectTo)
newFrontier = append(newFrontier, newFE) // ∪{i#Th(i)[i]}
varstate.frontier = newFrontier
varstate.lastWrite = t1.vc.clone()
varstate.lwLocks = make(map[uint32]struct{})
for k := range t1.ls {
varstate.lwLocks[k] = struct{}{}
}
varstate.lwDot = newFE
//t1.vc = t1.vc.add(p.T1, 1)
list, ok := varstate.graph.get(newFE.int)
if ok && len(list) == 0 {
list = append(list, &startDot)
varstate.graph.add(newFE, list)
}
} else if p.Read {
varstate.current++
newFE := &dot{v: t1.vc.clone(), int: varstate.current, t: uint16(p.T1),
sourceRef: uint32(p.Ev.Ops[0].SourceRef), line: uint16(p.Ev.Ops[0].Line),
write: false, ls: make(map[uint32]struct{}), pos: p.Ev.LocalIdx}
for k := range t1.ls { //copy lockset
newFE.ls[k] = struct{}{}
}
//locks accumulate lastWrite vcs for lockset of t
if varstate.lwDot != nil {
for k := range t1.ls {
lk := locks[k]
lk.rel = lk.rel.ssync(varstate.lastWrite)
// //order critical sections if the last write is inside the same lock as the current read
// if _, ok := varstate.lwLocks[k]; ok {
// t1.vc = t1.vc.ssync(lk.hb)
// }
locks[k] = lk
}
}
//write read dependency race
if varstate.lwDot != nil {
curVal := t1.vc.get(uint32(varstate.lwDot.t))
lwVal := varstate.lastWrite.get(uint32(varstate.lwDot.t))
if lwVal > curVal {
if !intersect(newFE.ls, varstate.lwDot.ls) {
report.ReportRace(report.Location{File: uint32(varstate.lwDot.sourceRef), Line: uint32(varstate.lwDot.line), W: true},
report.Location{File: p.Ev.Ops[0].SourceRef, Line: p.Ev.Ops[0].Line, W: false}, true, 0)
}
}
}
//write-read sync
t1.vc = t1.vc.ssync(varstate.lastWrite) //Th(i) = max(Th(i),L W (x))
newFE.v = t1.vc.clone()
newFrontier := make([]*dot, 0, len(varstate.frontier))
connectTo := make([]*dot, 0)
for _, f := range varstate.frontier {
k := f.v.get(uint32(f.t)) //j#k
thi_at_j := t1.vc.get(uint32(f.t)) //Th(i)[j]
if k > thi_at_j {
newFrontier = append(newFrontier, f) // RW(x) = {j]k | j]k ∈ RW(x) ∧ k > Th(i)[j]}
if f.write {
if !intersect(newFE.ls, f.ls) {
report.ReportRace(report.Location{File: uint32(f.sourceRef), Line: uint32(f.line), W: f.write},
report.Location{File: p.Ev.Ops[0].SourceRef, Line: p.Ev.Ops[0].Line, W: newFE.write}, false, 0)
}
visited := &bitset.BitSet{}
varstate.findRaces(newFE, f, visited, 0)
}
} else {
if f.int > 0 {
connectTo = append(connectTo, f)
}
if f.write {
newFrontier = append(newFrontier, f)
}
}
}
varstate.updateGraph3(newFE, connectTo)
newFrontier = append(newFrontier, newFE) // ∪{i#Th(i)[i]}
varstate.frontier = newFrontier
//connect to artifical start dot if no connection exists
list, ok := varstate.graph.get(newFE.int)
if ok && len(list) == 0 {
list = append(list, &startDot)
varstate.graph.add(newFE, list)
}
} else { //volatile synchronize
vol, ok := volatiles[p.T2]
if !ok {
vol = newvc2()
}
t1.vc = t1.vc.ssync(vol)
vol = t1.vc.clone()
volatiles[p.T2] = vol
}
t1.vc = t1.vc.add(p.T1, 1) //inc(Th(i),i)
t1.hb = t1.hb.add(p.T1, 1)
//update states
threads[p.T1] = t1
variables[p.T2] = varstate
}
func (l *ListenerGoFork) Put(p *util.SyncPair) {
if !p.IsFork {
return
}
t1, ok := threads[p.T1]
if !ok {
t1 = newT(p.T1)
}
signalList[p.T2] = t1.vc.clone()
if t1.strongSync > 0 {
signalList[p.T2] = t1.vc.clone().ssync(t1.hb)
}
t1.vc = t1.vc.add(p.T1, 1)
t1.hb = t1.hb.add(p.T1, 1)
threads[p.T1] = t1
}
func (l *ListenerGoWait) Put(p *util.SyncPair) {
if !p.IsWait {
return
}
t2, ok := signalList[p.T2]
if ok {
t1, ok := threads[p.T1]
if !ok {
t1 = newT(p.T1)
}
t1.vc = t1.vc.ssync(t2)
t1.vc = t1.vc.add(p.T1, 1)
t1.hb = t1.hb.add(p.T1, 1)
threads[p.T1] = t1
}
}
func (l *ListenerNT) Put(p *util.SyncPair) {
if !p.IsNT {
return
}
t1, ok := threads[p.T1]
if !ok {
t1 = newT(p.T1)
}
vc, ok := notifies[p.T2]
if !ok {
vc = newvc2()
}
if t1.strongSync == 0 {
vc = vc.ssync(t1.vc)
} else {
vc = vc.ssync(t1.vc.clone().ssync(t1.hb))
}
t1.vc = t1.vc.add(p.T1, 1)
t1.hb = t1.hb.add(p.T1, 1)
notifies[p.T2] = vc
threads[p.T1] = t1
}
func (l *ListenerNTWT) Put(p *util.SyncPair) {
if !p.IsNTWT {
return
}
//post wait event, so notify is already synchronized
if vc, ok := notifies[p.T2]; ok {
t1, ok := threads[p.T1]
if !ok {
t1 = newT(p.T1)
}
t1.vc = t1.vc.ssync(vc)
t1.vc = t1.vc.add(p.T1, 1)
t1.hb = t1.hb.add(p.T1, 1)
// vc = t1.vc.clone()
if t1.strongSync == 0 {
vc = t1.vc.clone()
} else {
vc = vc.ssync(t1.vc.clone().ssync(t1.hb))
}
threads[p.T1] = t1
notifies[p.T2] = vc
}
}
func (l *ListenerPostProcess) Put(p *util.SyncPair) {
if !p.PostProcess {
return
}
phase++
// set to nil so gc collects it
minimalLock = nil
minimalThread = nil
minimalVar = nil
}
func (v *variable) findRaces(raceAcc, prevAcc *dot, visited *bitset.BitSet, level uint64) {
if visited.Get(prevAcc.int) {
return
}
visited.Set(prevAcc.int)
list, ok := v.graph.get(prevAcc.int)
if !ok {
return
}
for _, d := range list {
if d.int == 0 {
continue
}
dVal := d.v.get(uint32(d.t))
raVal := raceAcc.v.get(uint32(d.t))
if dVal > raVal && (d.write || raceAcc.write) { // at least one must be a write!
if !intersect(raceAcc.ls, d.ls) {
report.ReportRace(report.Location{File: uint32(d.sourceRef), Line: uint32(d.line), W: d.write},
report.Location{File: uint32(raceAcc.sourceRef), Line: uint32(raceAcc.line), W: raceAcc.write}, false, 1)
// if b {
// fmt.Println("LS's", raceAcc.ls, d.ls, intersect(raceAcc.ls, d.ls))
// }
}
v.findRaces(raceAcc, d, visited, level+1)
}
}
}
|
dennissoftman/CleanEngine | include/uimanager.hpp | <gh_stars>0
#ifndef UIMANAGER_HPP
#define UIMANAGER_HPP
#include "renderer.hpp"
struct ButtonData
{
int id; // button identifier
};
typedef void(*OnButtonPressedCallback)(const ButtonData &);
class UIManager
{
friend class Renderer;
public:
virtual ~UIManager() {}
virtual void init() = 0;
virtual void update(double dt) = 0;
virtual void draw(Renderer *rend) = 0;
virtual void setOnButtonPressedCallback(OnButtonPressedCallback callb) = 0;
static UIManager *create();
};
#endif // UIMANAGER_HPP
|
matias-gonz/AlgoBlocks | src/main/java/edu/fiuba/algo3/interfaz/controladores/BotonABGAHandler.java | <reponame>matias-gonz/AlgoBlocks<filename>src/main/java/edu/fiuba/algo3/interfaz/controladores/BotonABGAHandler.java<gh_stars>0
package edu.fiuba.algo3.interfaz.controladores;
import edu.fiuba.algo3.interfaz.vista.SectorBloquesDisponibles;
import edu.fiuba.algo3.interfaz.vista.botoneras.BotonGAPersonalizado;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class BotonABGAHandler extends Stage implements EventHandler<ActionEvent> {
VBox contenendorAlgoritmo;
SectorBloquesDisponibles botoneraSectorBloquesDisponibles;
public BotonABGAHandler(VBox contenendorAlgoritmo, SectorBloquesDisponibles botoneraSectorBloquesDisponibles) {
this.contenendorAlgoritmo = contenendorAlgoritmo;
this.botoneraSectorBloquesDisponibles = botoneraSectorBloquesDisponibles;
}
@Override
public void handle(ActionEvent actionEvent) {
Label informacion = new Label("Ingrese un nombre al algoritmo a guardar");
TextField texto = new TextField();
Button aceptar = new Button("Aceptar");
Button cancelar = new Button( "Cancelar" );
VBox menu = new VBox(informacion, texto);
menu.setAlignment(Pos.BASELINE_CENTER);
HBox opciones = new HBox(aceptar, cancelar);
opciones.setAlignment( Pos.BASELINE_CENTER );
menu.getChildren().addAll(opciones);
Scene escena = new Scene(menu, 390, 80);
this.resizableProperty().set(false);
cancelar.setOnAction( e-> {
this.hide();
this.requestFocus();
});
aceptar.setOnAction( e-> {
if( texto.getText().trim().equals("") )
{
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("[ALGOBLOCKS] Alerta!");
alert.setHeaderText("ERROR");
alert.setContentText("NOMBRE ERRONEO!");
alert.showAndWait();
return;
}
// este boton debería tener la info de los hijos de this.contenedorAlgoritmo (es pasada por parámetro).
// y bueno, el nombre escrito en el texto.
BotonGAPersonalizado botonPersonalizado = new BotonGAPersonalizado( texto, this.contenendorAlgoritmo, botoneraSectorBloquesDisponibles);
this.botoneraSectorBloquesDisponibles.getChildren().add(botonPersonalizado);
this.botoneraSectorBloquesDisponibles.notificarObservador(this.contenendorAlgoritmo);
// this.contenendorAlgoritmo.getChildren() tiene los Bloques que hay que ejecutarse!
this.hide();
});
this.setTitle("Guardar algoritmo");
escena.setOnKeyPressed( e ->
{
switch( e.getCode() )
{
case ENTER:
aceptar.fire();
break;
case ESCAPE:
cancelar.fire();
break;
}
});
this.setScene(escena);
this.show();
}
}
|
SudoHead/atlas | Atlas/src/atlas/view/SimEvent.java | <filename>Atlas/src/atlas/view/SimEvent.java
package atlas.view;
/**
* This enum represents all the events that from the view.
*/
public enum SimEvent {
START,
STOP,
EXIT,
ADD,
EDIT,
STOP_EDIT,
CENTER,
LOCK,
SPEED_CHANGED,
NEW_SIM,
SAVE_SIM,
SAVE_BODY,
UPDATE_BODY,
LOAD,
MOUSE_CLICKED,
MOUSE_MULTI_CLICKED,
MOUSE_PRESSED,
MOUSE_DRAGGED,
MOUSE_RELEASED,
MOUSE_WHEEL_UP,
MOUSE_WHEEL_DOWN,
ESC,
W, A, S, D,
SPACEBAR_PRESSED,
KEYBOARD_1, KEYBOARD_2, KEYBOARD_3, KEYBOARD_4, KEYBOARD_5,
KEYBOARD_6, KEYBOARD_7, KEYBOARD_8, KEYBOARD_9,
COLLISION_ONE, COLLISION_TWO,
NBODY_ONE, NBODY_TWO, NBODY_THREE,
TOGGLE_TRAILS
}
|
frank-dong-ms/sccl | sccl/language/collectives.py | <reponame>frank-dong-ms/sccl<gh_stars>0
from dataclasses import dataclass, field
from sccl.language.ir import Buffer
from sccl.language import *
class Collective():
def __init__(self, num_ranks, chunk_factor, inplace):
self.num_ranks = num_ranks
self.chunk_factor = chunk_factor
self.inplace = inplace
self.name = "custom"
def init_buffers(self):
pass
def check(self, prog):
pass
def get_buffer_index(self, rank, buffer, index):
return buffer, index
class AllToAll(Collective):
def __init__(self, num_ranks, chunk_factor, inplace):
Collective.__init__(self, num_ranks, chunk_factor, inplace)
self.name = 'alltoall'
def init_buffers(self):
chunks_per_node = self.num_ranks * self.chunk_factor
rank_buffers = []
for r in range(self.num_ranks):
input_buffer = [None] * chunks_per_node
output_buffer = [None] * chunks_per_node
for index in range(chunks_per_node):
chunk = Chunk(r, index, index//self.chunk_factor, index % self.chunk_factor + r*self.chunk_factor)
input_buffer[index] = chunk
buffers = {Buffer.input : input_buffer,
Buffer.output : output_buffer}
rank_buffers.append(buffers)
return rank_buffers
# Expected output buffer for alltoall
def check(self, prog):
chunks_per_node = self.num_ranks * self.chunk_factor
correct = True
for r in range(self.num_ranks):
output = prog.buffers[r][Buffer.output]
for i in range(self.num_ranks):
for ch in range(self.chunk_factor):
index = ch + i * self.chunk_factor
chunk = output[index]
expected_origin_index = ch + r * self.chunk_factor
if chunk is None or chunk.origin_rank != i or chunk.origin_index != expected_origin_index:
print(f'Rank {r} chunk {index} is incorrect should be chunk({i},{expected_origin_index}) given {chunk}')
correct = False
return correct
class AllGather(Collective):
def __init__(self, num_ranks, chunk_factor, inplace):
Collective.__init__(self, num_ranks, chunk_factor, inplace)
self.name = 'allgather'
# Initializes input buffer for an allgather
def init_buffers(self):
rank_buffers = []
if self.inplace:
# Inplace AllGather only uses the output buffer
for r in range(self.num_ranks):
output_buffer = [None] * (self.num_ranks * self.chunk_factor)
for ch in range(self.chunk_factor):
output_buffer[r*self.chunk_factor+ch] = Chunk(r, ch, -1, r*self.chunk_factor+ch)
buffers = {Buffer.input : output_buffer[r*self.chunk_factor:(r+1)*self.chunk_factor],
Buffer.output : output_buffer}
rank_buffers.append(buffers)
else:
for r in range(self.num_ranks):
input_buffer = [None] * self.chunk_factor
output_buffer = [None] * (self.num_ranks * self.chunk_factor)
for ch in range(self.chunk_factor):
input_buffer[ch] = Chunk(r, ch, -1, r*self.chunk_factor+ch)
buffers = {Buffer.input : input_buffer,
Buffer.output : output_buffer}
rank_buffers.append(buffers)
return rank_buffers
# Expected output buffer for allgather
def check(self, prog):
correct = True
buf = Buffer.output
for r in range(self.num_ranks):
output = prog.buffers[r][buf]
for i in range(self.num_ranks):
for ch in range(self.chunk_factor):
index = i*self.chunk_factor + ch
chunk = output[index]
if chunk is None:
print(f'Rank {r} chunk {index} is incorrect should be ({i}, {ch}) given None')
correct = False
elif chunk.origin_rank != i or chunk.origin_index != ch:
print(f'Rank {r} chunk {index} is incorrect should be ({i}, {ch}) given ({chunk.origin_rank}, {chunk.origin_index})')
correct = False
return correct
def get_buffer_index(self, rank, buffer, index):
# For inplace AllGathers, the input buffer points into the output buffer
if self.inplace and buffer == Buffer.input:
return Buffer.output, index + rank * self.chunk_factor
else:
return buffer, index
class AllReduce(Collective):
def __init__(self, num_ranks, chunk_factor, inplace):
Collective.__init__(self, num_ranks, chunk_factor, inplace)
self.name = 'allreduce'
def init_buffers(self):
chunks_per_node = self.chunk_factor
rank_buffers = []
for r in range(self.num_ranks):
input_buffer = []
output_buffer = [None] * chunks_per_node
for c in range(chunks_per_node):
# Chunks start at rank r index c, and ends on all ranks (-1) at index r
input_buffer.append(Chunk(r, c, -1, c))
# Input and output buffer are the same.
if self.inplace:
buffers = {Buffer.input : input_buffer,
Buffer.output : input_buffer}
else:
buffers = {Buffer.input : input_buffer,
Buffer.output : output_buffer}
rank_buffers.append(buffers)
return rank_buffers
def check(self, prog):
chunks_per_node = self.chunk_factor
expected_chunks = []
buf = Buffer.input if self.inplace else Buffer.output
for c in range(chunks_per_node):
chunk = ReduceChunk([])
for r in range(self.num_ranks):
chunk = chunk.reduce(Chunk(r, c))
expected_chunks.append(chunk)
correct = True
for r in range(self.num_ranks):
output = prog.buffers[r][buf]
for c in range(chunks_per_node):
chunk = output[c]
if chunk is None or chunk != expected_chunks[c]:
print(f'Rank {r} chunk {c} is incorrect should be ReduceChunk index {c} from all ranks, given {chunk}')
correct = False
return correct
def get_buffer_index(self, rank, buffer, index):
if self.inplace and buffer == Buffer.output:
return Buffer.input, index
else:
return buffer, index
class ReduceScatter(Collective):
def __init__(self, num_ranks, chunk_factor, inplace):
Collective.__init__(self, num_ranks, chunk_factor, inplace)
self.name = 'reduce_scatter'
def init_buffers(self):
rank_buffers = []
for r in range(self.num_ranks):
if self.inplace:
input_buffer = []
for i in range(self.num_ranks):
for c in range(self.chunk_factor):
input_buffer.append(Chunk(r, i*self.chunk_factor + c, i, c))
buffers = {Buffer.input : input_buffer}
rank_buffers.append(buffers)
else:
input_buffer = []
output_buffer = [None] * self.chunk_factor
for i in range(self.num_ranks):
for c in range(self.chunk_factor):
input_buffer.append(Chunk(r, i*self.chunk_factor + c, i, c))
buffers = {Buffer.input : input_buffer,
Buffer.output : output_buffer}
rank_buffers.append(buffers)
return rank_buffers
def check(self, prog):
expected_chunks = []
buf = Buffer.input if self.inplace else Buffer.output
for c in range(self.num_ranks * self.chunk_factor):
chunk = ReduceChunk([])
for r in range(self.num_ranks):
chunk = chunk.reduce(Chunk(r, c))
expected_chunks.append(chunk)
correct = True
for r in range(self.num_ranks):
output = prog.buffers[r][buf]
for c in range(self.chunk_factor):
correct_idx = r * self.chunk_factor + c
if self.inplace:
c = correct_idx
chunk = output[c]
if chunk is None or chunk != expected_chunks[correct_idx]:
print(f'Rank {r} chunk {c} is incorrect should be index {correct_idx} from all ranks given {chunk}')
correct = False
return correct
def get_buffer_index(self, rank, buffer, index):
# For inplace ReduceScatter the output buffer is a pointer into the input buffer
if self.inplace and buffer == Buffer.output:
return Buffer.input, index + rank * self.chunk_factor
else:
return buffer, index
|
usenixatc2021/SoftRefresh_Scheduling | linsched-linsched-alpha/arch/parisc/math-emu/dbl_float.h | /*
* Linux/PA-RISC Project (http://www.parisc-linux.org/)
*
* Floating-point emulation code
* Copyright (C) 2001 Hewlett-Packard (<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, 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
*/
#ifdef __NO_PA_HDRS
PA header file -- do not include this header file for non-PA builds.
#endif
/* 32-bit word grabbing functions */
#define Dbl_firstword(value) Dallp1(value)
#define Dbl_secondword(value) Dallp2(value)
#define Dbl_thirdword(value) dummy_location
#define Dbl_fourthword(value) dummy_location
#define Dbl_sign(object) Dsign(object)
#define Dbl_exponent(object) Dexponent(object)
#define Dbl_signexponent(object) Dsignexponent(object)
#define Dbl_mantissap1(object) Dmantissap1(object)
#define Dbl_mantissap2(object) Dmantissap2(object)
#define Dbl_exponentmantissap1(object) Dexponentmantissap1(object)
#define Dbl_allp1(object) Dallp1(object)
#define Dbl_allp2(object) Dallp2(object)
/* dbl_and_signs ANDs the sign bits of each argument and puts the result
* into the first argument. dbl_or_signs ors those same sign bits */
#define Dbl_and_signs( src1dst, src2) \
Dallp1(src1dst) = (Dallp1(src2)|~((unsigned int)1<<31)) & Dallp1(src1dst)
#define Dbl_or_signs( src1dst, src2) \
Dallp1(src1dst) = (Dallp1(src2)&((unsigned int)1<<31)) | Dallp1(src1dst)
/* The hidden bit is always the low bit of the exponent */
#define Dbl_clear_exponent_set_hidden(srcdst) Deposit_dexponent(srcdst,1)
#define Dbl_clear_signexponent_set_hidden(srcdst) \
Deposit_dsignexponent(srcdst,1)
#define Dbl_clear_sign(srcdst) Dallp1(srcdst) &= ~((unsigned int)1<<31)
#define Dbl_clear_signexponent(srcdst) \
Dallp1(srcdst) &= Dmantissap1((unsigned int)-1)
/* Exponent field for doubles has already been cleared and may be
* included in the shift. Here we need to generate two double width
* variable shifts. The insignificant bits can be ignored.
* MTSAR f(varamount)
* VSHD srcdst.high,srcdst.low => srcdst.low
* VSHD 0,srcdst.high => srcdst.high
* This is very difficult to model with C expressions since the shift amount
* could exceed 32. */
/* varamount must be less than 64 */
#define Dbl_rightshift(srcdstA, srcdstB, varamount) \
{if((varamount) >= 32) { \
Dallp2(srcdstB) = Dallp1(srcdstA) >> (varamount-32); \
Dallp1(srcdstA)=0; \
} \
else if(varamount > 0) { \
Variable_shift_double(Dallp1(srcdstA), Dallp2(srcdstB), \
(varamount), Dallp2(srcdstB)); \
Dallp1(srcdstA) >>= varamount; \
} }
/* varamount must be less than 64 */
#define Dbl_rightshift_exponentmantissa(srcdstA, srcdstB, varamount) \
{if((varamount) >= 32) { \
Dallp2(srcdstB) = Dexponentmantissap1(srcdstA) >> (varamount-32); \
Dallp1(srcdstA) &= ((unsigned int)1<<31); /* clear expmant field */ \
} \
else if(varamount > 0) { \
Variable_shift_double(Dexponentmantissap1(srcdstA), Dallp2(srcdstB), \
(varamount), Dallp2(srcdstB)); \
Deposit_dexponentmantissap1(srcdstA, \
(Dexponentmantissap1(srcdstA)>>varamount)); \
} }
/* varamount must be less than 64 */
#define Dbl_leftshift(srcdstA, srcdstB, varamount) \
{if((varamount) >= 32) { \
Dallp1(srcdstA) = Dallp2(srcdstB) << (varamount-32); \
Dallp2(srcdstB)=0; \
} \
else { \
if ((varamount) > 0) { \
Dallp1(srcdstA) = (Dallp1(srcdstA) << (varamount)) | \
(Dallp2(srcdstB) >> (32-(varamount))); \
Dallp2(srcdstB) <<= varamount; \
} \
} }
#define Dbl_leftshiftby1_withextent(lefta,leftb,right,resulta,resultb) \
Shiftdouble(Dallp1(lefta), Dallp2(leftb), 31, Dallp1(resulta)); \
Shiftdouble(Dallp2(leftb), Extall(right), 31, Dallp2(resultb))
#define Dbl_rightshiftby1_withextent(leftb,right,dst) \
Extall(dst) = (Dallp2(leftb) << 31) | ((unsigned int)Extall(right) >> 1) | \
Extlow(right)
#define Dbl_arithrightshiftby1(srcdstA,srcdstB) \
Shiftdouble(Dallp1(srcdstA),Dallp2(srcdstB),1,Dallp2(srcdstB));\
Dallp1(srcdstA) = (int)Dallp1(srcdstA) >> 1
/* Sign extend the sign bit with an integer destination */
#define Dbl_signextendedsign(value) Dsignedsign(value)
#define Dbl_isone_hidden(dbl_value) (Is_dhidden(dbl_value)!=0)
/* Singles and doubles may include the sign and exponent fields. The
* hidden bit and the hidden overflow must be included. */
#define Dbl_increment(dbl_valueA,dbl_valueB) \
if( (Dallp2(dbl_valueB) += 1) == 0 ) Dallp1(dbl_valueA) += 1
#define Dbl_increment_mantissa(dbl_valueA,dbl_valueB) \
if( (Dmantissap2(dbl_valueB) += 1) == 0 ) \
Deposit_dmantissap1(dbl_valueA,dbl_valueA+1)
#define Dbl_decrement(dbl_valueA,dbl_valueB) \
if( Dallp2(dbl_valueB) == 0 ) Dallp1(dbl_valueA) -= 1; \
Dallp2(dbl_valueB) -= 1
#define Dbl_isone_sign(dbl_value) (Is_dsign(dbl_value)!=0)
#define Dbl_isone_hiddenoverflow(dbl_value) (Is_dhiddenoverflow(dbl_value)!=0)
#define Dbl_isone_lowmantissap1(dbl_valueA) (Is_dlowp1(dbl_valueA)!=0)
#define Dbl_isone_lowmantissap2(dbl_valueB) (Is_dlowp2(dbl_valueB)!=0)
#define Dbl_isone_signaling(dbl_value) (Is_dsignaling(dbl_value)!=0)
#define Dbl_is_signalingnan(dbl_value) (Dsignalingnan(dbl_value)==0xfff)
#define Dbl_isnotzero(dbl_valueA,dbl_valueB) \
(Dallp1(dbl_valueA) || Dallp2(dbl_valueB))
#define Dbl_isnotzero_hiddenhigh7mantissa(dbl_value) \
(Dhiddenhigh7mantissa(dbl_value)!=0)
#define Dbl_isnotzero_exponent(dbl_value) (Dexponent(dbl_value)!=0)
#define Dbl_isnotzero_mantissa(dbl_valueA,dbl_valueB) \
(Dmantissap1(dbl_valueA) || Dmantissap2(dbl_valueB))
#define Dbl_isnotzero_mantissap1(dbl_valueA) (Dmantissap1(dbl_valueA)!=0)
#define Dbl_isnotzero_mantissap2(dbl_valueB) (Dmantissap2(dbl_valueB)!=0)
#define Dbl_isnotzero_exponentmantissa(dbl_valueA,dbl_valueB) \
(Dexponentmantissap1(dbl_valueA) || Dmantissap2(dbl_valueB))
#define Dbl_isnotzero_low4p2(dbl_value) (Dlow4p2(dbl_value)!=0)
#define Dbl_iszero(dbl_valueA,dbl_valueB) (Dallp1(dbl_valueA)==0 && \
Dallp2(dbl_valueB)==0)
#define Dbl_iszero_allp1(dbl_value) (Dallp1(dbl_value)==0)
#define Dbl_iszero_allp2(dbl_value) (Dallp2(dbl_value)==0)
#define Dbl_iszero_hidden(dbl_value) (Is_dhidden(dbl_value)==0)
#define Dbl_iszero_hiddenoverflow(dbl_value) (Is_dhiddenoverflow(dbl_value)==0)
#define Dbl_iszero_hiddenhigh3mantissa(dbl_value) \
(Dhiddenhigh3mantissa(dbl_value)==0)
#define Dbl_iszero_hiddenhigh7mantissa(dbl_value) \
(Dhiddenhigh7mantissa(dbl_value)==0)
#define Dbl_iszero_sign(dbl_value) (Is_dsign(dbl_value)==0)
#define Dbl_iszero_exponent(dbl_value) (Dexponent(dbl_value)==0)
#define Dbl_iszero_mantissa(dbl_valueA,dbl_valueB) \
(Dmantissap1(dbl_valueA)==0 && Dmantissap2(dbl_valueB)==0)
#define Dbl_iszero_exponentmantissa(dbl_valueA,dbl_valueB) \
(Dexponentmantissap1(dbl_valueA)==0 && Dmantissap2(dbl_valueB)==0)
#define Dbl_isinfinity_exponent(dbl_value) \
(Dexponent(dbl_value)==DBL_INFINITY_EXPONENT)
#define Dbl_isnotinfinity_exponent(dbl_value) \
(Dexponent(dbl_value)!=DBL_INFINITY_EXPONENT)
#define Dbl_isinfinity(dbl_valueA,dbl_valueB) \
(Dexponent(dbl_valueA)==DBL_INFINITY_EXPONENT && \
Dmantissap1(dbl_valueA)==0 && Dmantissap2(dbl_valueB)==0)
#define Dbl_isnan(dbl_valueA,dbl_valueB) \
(Dexponent(dbl_valueA)==DBL_INFINITY_EXPONENT && \
(Dmantissap1(dbl_valueA)!=0 || Dmantissap2(dbl_valueB)!=0))
#define Dbl_isnotnan(dbl_valueA,dbl_valueB) \
(Dexponent(dbl_valueA)!=DBL_INFINITY_EXPONENT || \
(Dmantissap1(dbl_valueA)==0 && Dmantissap2(dbl_valueB)==0))
#define Dbl_islessthan(dbl_op1a,dbl_op1b,dbl_op2a,dbl_op2b) \
(Dallp1(dbl_op1a) < Dallp1(dbl_op2a) || \
(Dallp1(dbl_op1a) == Dallp1(dbl_op2a) && \
Dallp2(dbl_op1b) < Dallp2(dbl_op2b)))
#define Dbl_isgreaterthan(dbl_op1a,dbl_op1b,dbl_op2a,dbl_op2b) \
(Dallp1(dbl_op1a) > Dallp1(dbl_op2a) || \
(Dallp1(dbl_op1a) == Dallp1(dbl_op2a) && \
Dallp2(dbl_op1b) > Dallp2(dbl_op2b)))
#define Dbl_isnotlessthan(dbl_op1a,dbl_op1b,dbl_op2a,dbl_op2b) \
(Dallp1(dbl_op1a) > Dallp1(dbl_op2a) || \
(Dallp1(dbl_op1a) == Dallp1(dbl_op2a) && \
Dallp2(dbl_op1b) >= Dallp2(dbl_op2b)))
#define Dbl_isnotgreaterthan(dbl_op1a,dbl_op1b,dbl_op2a,dbl_op2b) \
(Dallp1(dbl_op1a) < Dallp1(dbl_op2a) || \
(Dallp1(dbl_op1a) == Dallp1(dbl_op2a) && \
Dallp2(dbl_op1b) <= Dallp2(dbl_op2b)))
#define Dbl_isequal(dbl_op1a,dbl_op1b,dbl_op2a,dbl_op2b) \
((Dallp1(dbl_op1a) == Dallp1(dbl_op2a)) && \
(Dallp2(dbl_op1b) == Dallp2(dbl_op2b)))
#define Dbl_leftshiftby8(dbl_valueA,dbl_valueB) \
Shiftdouble(Dallp1(dbl_valueA),Dallp2(dbl_valueB),24,Dallp1(dbl_valueA)); \
Dallp2(dbl_valueB) <<= 8
#define Dbl_leftshiftby7(dbl_valueA,dbl_valueB) \
Shiftdouble(Dallp1(dbl_valueA),Dallp2(dbl_valueB),25,Dallp1(dbl_valueA)); \
Dallp2(dbl_valueB) <<= 7
#define Dbl_leftshiftby4(dbl_valueA,dbl_valueB) \
Shiftdouble(Dallp1(dbl_valueA),Dallp2(dbl_valueB),28,Dallp1(dbl_valueA)); \
Dallp2(dbl_valueB) <<= 4
#define Dbl_leftshiftby3(dbl_valueA,dbl_valueB) \
Shiftdouble(Dallp1(dbl_valueA),Dallp2(dbl_valueB),29,Dallp1(dbl_valueA)); \
Dallp2(dbl_valueB) <<= 3
#define Dbl_leftshiftby2(dbl_valueA,dbl_valueB) \
Shiftdouble(Dallp1(dbl_valueA),Dallp2(dbl_valueB),30,Dallp1(dbl_valueA)); \
Dallp2(dbl_valueB) <<= 2
#define Dbl_leftshiftby1(dbl_valueA,dbl_valueB) \
Shiftdouble(Dallp1(dbl_valueA),Dallp2(dbl_valueB),31,Dallp1(dbl_valueA)); \
Dallp2(dbl_valueB) <<= 1
#define Dbl_rightshiftby8(dbl_valueA,dbl_valueB) \
Shiftdouble(Dallp1(dbl_valueA),Dallp2(dbl_valueB),8,Dallp2(dbl_valueB)); \
Dallp1(dbl_valueA) >>= 8
#define Dbl_rightshiftby4(dbl_valueA,dbl_valueB) \
Shiftdouble(Dallp1(dbl_valueA),Dallp2(dbl_valueB),4,Dallp2(dbl_valueB)); \
Dallp1(dbl_valueA) >>= 4
#define Dbl_rightshiftby2(dbl_valueA,dbl_valueB) \
Shiftdouble(Dallp1(dbl_valueA),Dallp2(dbl_valueB),2,Dallp2(dbl_valueB)); \
Dallp1(dbl_valueA) >>= 2
#define Dbl_rightshiftby1(dbl_valueA,dbl_valueB) \
Shiftdouble(Dallp1(dbl_valueA),Dallp2(dbl_valueB),1,Dallp2(dbl_valueB)); \
Dallp1(dbl_valueA) >>= 1
/* This magnitude comparison uses the signless first words and
* the regular part2 words. The comparison is graphically:
*
* 1st greater? -------------
* |
* 1st less?-----------------+---------
* | |
* 2nd greater or equal----->| |
* False True
*/
#define Dbl_ismagnitudeless(leftB,rightB,signlessleft,signlessright) \
((signlessleft <= signlessright) && \
( (signlessleft < signlessright) || (Dallp2(leftB)<Dallp2(rightB)) ))
#define Dbl_copytoint_exponentmantissap1(src,dest) \
dest = Dexponentmantissap1(src)
/* A quiet NaN has the high mantissa bit clear and at least on other (in this
* case the adjacent bit) bit set. */
#define Dbl_set_quiet(dbl_value) Deposit_dhigh2mantissa(dbl_value,1)
#define Dbl_set_exponent(dbl_value, exp) Deposit_dexponent(dbl_value,exp)
#define Dbl_set_mantissa(desta,destb,valuea,valueb) \
Deposit_dmantissap1(desta,valuea); \
Dmantissap2(destb) = Dmantissap2(valueb)
#define Dbl_set_mantissap1(desta,valuea) \
Deposit_dmantissap1(desta,valuea)
#define Dbl_set_mantissap2(destb,valueb) \
Dmantissap2(destb) = Dmantissap2(valueb)
#define Dbl_set_exponentmantissa(desta,destb,valuea,valueb) \
Deposit_dexponentmantissap1(desta,valuea); \
Dmantissap2(destb) = Dmantissap2(valueb)
#define Dbl_set_exponentmantissap1(dest,value) \
Deposit_dexponentmantissap1(dest,value)
#define Dbl_copyfromptr(src,desta,destb) \
Dallp1(desta) = src->wd0; \
Dallp2(destb) = src->wd1
#define Dbl_copytoptr(srca,srcb,dest) \
dest->wd0 = Dallp1(srca); \
dest->wd1 = Dallp2(srcb)
/* An infinity is represented with the max exponent and a zero mantissa */
#define Dbl_setinfinity_exponent(dbl_value) \
Deposit_dexponent(dbl_value,DBL_INFINITY_EXPONENT)
#define Dbl_setinfinity_exponentmantissa(dbl_valueA,dbl_valueB) \
Deposit_dexponentmantissap1(dbl_valueA, \
(DBL_INFINITY_EXPONENT << (32-(1+DBL_EXP_LENGTH)))); \
Dmantissap2(dbl_valueB) = 0
#define Dbl_setinfinitypositive(dbl_valueA,dbl_valueB) \
Dallp1(dbl_valueA) \
= (DBL_INFINITY_EXPONENT << (32-(1+DBL_EXP_LENGTH))); \
Dmantissap2(dbl_valueB) = 0
#define Dbl_setinfinitynegative(dbl_valueA,dbl_valueB) \
Dallp1(dbl_valueA) = ((unsigned int)1<<31) | \
(DBL_INFINITY_EXPONENT << (32-(1+DBL_EXP_LENGTH))); \
Dmantissap2(dbl_valueB) = 0
#define Dbl_setinfinity(dbl_valueA,dbl_valueB,sign) \
Dallp1(dbl_valueA) = ((unsigned int)sign << 31) | \
(DBL_INFINITY_EXPONENT << (32-(1+DBL_EXP_LENGTH))); \
Dmantissap2(dbl_valueB) = 0
#define Dbl_sethigh4bits(dbl_value, extsign) Deposit_dhigh4p1(dbl_value,extsign)
#define Dbl_set_sign(dbl_value,sign) Deposit_dsign(dbl_value,sign)
#define Dbl_invert_sign(dbl_value) Deposit_dsign(dbl_value,~Dsign(dbl_value))
#define Dbl_setone_sign(dbl_value) Deposit_dsign(dbl_value,1)
#define Dbl_setone_lowmantissap2(dbl_value) Deposit_dlowp2(dbl_value,1)
#define Dbl_setzero_sign(dbl_value) Dallp1(dbl_value) &= 0x7fffffff
#define Dbl_setzero_exponent(dbl_value) \
Dallp1(dbl_value) &= 0x800fffff
#define Dbl_setzero_mantissa(dbl_valueA,dbl_valueB) \
Dallp1(dbl_valueA) &= 0xfff00000; \
Dallp2(dbl_valueB) = 0
#define Dbl_setzero_mantissap1(dbl_value) Dallp1(dbl_value) &= 0xfff00000
#define Dbl_setzero_mantissap2(dbl_value) Dallp2(dbl_value) = 0
#define Dbl_setzero_exponentmantissa(dbl_valueA,dbl_valueB) \
Dallp1(dbl_valueA) &= 0x80000000; \
Dallp2(dbl_valueB) = 0
#define Dbl_setzero_exponentmantissap1(dbl_valueA) \
Dallp1(dbl_valueA) &= 0x80000000
#define Dbl_setzero(dbl_valueA,dbl_valueB) \
Dallp1(dbl_valueA) = 0; Dallp2(dbl_valueB) = 0
#define Dbl_setzerop1(dbl_value) Dallp1(dbl_value) = 0
#define Dbl_setzerop2(dbl_value) Dallp2(dbl_value) = 0
#define Dbl_setnegativezero(dbl_value) \
Dallp1(dbl_value) = (unsigned int)1 << 31; Dallp2(dbl_value) = 0
#define Dbl_setnegativezerop1(dbl_value) Dallp1(dbl_value) = (unsigned int)1<<31
/* Use the following macro for both overflow & underflow conditions */
#define ovfl -
#define unfl +
#define Dbl_setwrapped_exponent(dbl_value,exponent,op) \
Deposit_dexponent(dbl_value,(exponent op DBL_WRAP))
#define Dbl_setlargestpositive(dbl_valueA,dbl_valueB) \
Dallp1(dbl_valueA) = ((DBL_EMAX+DBL_BIAS) << (32-(1+DBL_EXP_LENGTH))) \
| ((1<<(32-(1+DBL_EXP_LENGTH))) - 1 ); \
Dallp2(dbl_valueB) = 0xFFFFFFFF
#define Dbl_setlargestnegative(dbl_valueA,dbl_valueB) \
Dallp1(dbl_valueA) = ((DBL_EMAX+DBL_BIAS) << (32-(1+DBL_EXP_LENGTH))) \
| ((1<<(32-(1+DBL_EXP_LENGTH))) - 1 ) \
| ((unsigned int)1<<31); \
Dallp2(dbl_valueB) = 0xFFFFFFFF
#define Dbl_setlargest_exponentmantissa(dbl_valueA,dbl_valueB) \
Deposit_dexponentmantissap1(dbl_valueA, \
(((DBL_EMAX+DBL_BIAS) << (32-(1+DBL_EXP_LENGTH))) \
| ((1<<(32-(1+DBL_EXP_LENGTH))) - 1 ))); \
Dallp2(dbl_valueB) = 0xFFFFFFFF
#define Dbl_setnegativeinfinity(dbl_valueA,dbl_valueB) \
Dallp1(dbl_valueA) = ((1<<DBL_EXP_LENGTH) | DBL_INFINITY_EXPONENT) \
<< (32-(1+DBL_EXP_LENGTH)) ; \
Dallp2(dbl_valueB) = 0
#define Dbl_setlargest(dbl_valueA,dbl_valueB,sign) \
Dallp1(dbl_valueA) = ((unsigned int)sign << 31) | \
((DBL_EMAX+DBL_BIAS) << (32-(1+DBL_EXP_LENGTH))) | \
((1 << (32-(1+DBL_EXP_LENGTH))) - 1 ); \
Dallp2(dbl_valueB) = 0xFFFFFFFF
/* The high bit is always zero so arithmetic or logical shifts will work. */
#define Dbl_right_align(srcdstA,srcdstB,shift,extent) \
if( shift >= 32 ) \
{ \
/* Big shift requires examining the portion shift off \
the end to properly set inexact. */ \
if(shift < 64) \
{ \
if(shift > 32) \
{ \
Variable_shift_double(Dallp1(srcdstA),Dallp2(srcdstB), \
shift-32, Extall(extent)); \
if(Dallp2(srcdstB) << 64 - (shift)) Ext_setone_low(extent); \
} \
else Extall(extent) = Dallp2(srcdstB); \
Dallp2(srcdstB) = Dallp1(srcdstA) >> (shift - 32); \
} \
else \
{ \
Extall(extent) = Dallp1(srcdstA); \
if(Dallp2(srcdstB)) Ext_setone_low(extent); \
Dallp2(srcdstB) = 0; \
} \
Dallp1(srcdstA) = 0; \
} \
else \
{ \
/* Small alignment is simpler. Extension is easily set. */ \
if (shift > 0) \
{ \
Extall(extent) = Dallp2(srcdstB) << 32 - (shift); \
Variable_shift_double(Dallp1(srcdstA),Dallp2(srcdstB),shift, \
Dallp2(srcdstB)); \
Dallp1(srcdstA) >>= shift; \
} \
else Extall(extent) = 0; \
}
/*
* Here we need to shift the result right to correct for an overshift
* (due to the exponent becoming negative) during normalization.
*/
#define Dbl_fix_overshift(srcdstA,srcdstB,shift,extent) \
Extall(extent) = Dallp2(srcdstB) << 32 - (shift); \
Dallp2(srcdstB) = (Dallp1(srcdstA) << 32 - (shift)) | \
(Dallp2(srcdstB) >> (shift)); \
Dallp1(srcdstA) = Dallp1(srcdstA) >> shift
#define Dbl_hiddenhigh3mantissa(dbl_value) Dhiddenhigh3mantissa(dbl_value)
#define Dbl_hidden(dbl_value) Dhidden(dbl_value)
#define Dbl_lowmantissap2(dbl_value) Dlowp2(dbl_value)
/* The left argument is never smaller than the right argument */
#define Dbl_subtract(lefta,leftb,righta,rightb,resulta,resultb) \
if( Dallp2(rightb) > Dallp2(leftb) ) Dallp1(lefta)--; \
Dallp2(resultb) = Dallp2(leftb) - Dallp2(rightb); \
Dallp1(resulta) = Dallp1(lefta) - Dallp1(righta)
/* Subtract right augmented with extension from left augmented with zeros and
* store into result and extension. */
#define Dbl_subtract_withextension(lefta,leftb,righta,rightb,extent,resulta,resultb) \
Dbl_subtract(lefta,leftb,righta,rightb,resulta,resultb); \
if( (Extall(extent) = 0-Extall(extent)) ) \
{ \
if((Dallp2(resultb)--) == 0) Dallp1(resulta)--; \
}
#define Dbl_addition(lefta,leftb,righta,rightb,resulta,resultb) \
/* If the sum of the low words is less than either source, then \
* an overflow into the next word occurred. */ \
Dallp1(resulta) = Dallp1(lefta) + Dallp1(righta); \
if((Dallp2(resultb) = Dallp2(leftb) + Dallp2(rightb)) < Dallp2(rightb)) \
Dallp1(resulta)++
#define Dbl_xortointp1(left,right,result) \
result = Dallp1(left) XOR Dallp1(right)
#define Dbl_xorfromintp1(left,right,result) \
Dallp1(result) = left XOR Dallp1(right)
#define Dbl_swap_lower(left,right) \
Dallp2(left) = Dallp2(left) XOR Dallp2(right); \
Dallp2(right) = Dallp2(left) XOR Dallp2(right); \
Dallp2(left) = Dallp2(left) XOR Dallp2(right)
/* Need to Initialize */
#define Dbl_makequietnan(desta,destb) \
Dallp1(desta) = ((DBL_EMAX+DBL_BIAS)+1)<< (32-(1+DBL_EXP_LENGTH)) \
| (1<<(32-(1+DBL_EXP_LENGTH+2))); \
Dallp2(destb) = 0
#define Dbl_makesignalingnan(desta,destb) \
Dallp1(desta) = ((DBL_EMAX+DBL_BIAS)+1)<< (32-(1+DBL_EXP_LENGTH)) \
| (1<<(32-(1+DBL_EXP_LENGTH+1))); \
Dallp2(destb) = 0
#define Dbl_normalize(dbl_opndA,dbl_opndB,exponent) \
while(Dbl_iszero_hiddenhigh7mantissa(dbl_opndA)) { \
Dbl_leftshiftby8(dbl_opndA,dbl_opndB); \
exponent -= 8; \
} \
if(Dbl_iszero_hiddenhigh3mantissa(dbl_opndA)) { \
Dbl_leftshiftby4(dbl_opndA,dbl_opndB); \
exponent -= 4; \
} \
while(Dbl_iszero_hidden(dbl_opndA)) { \
Dbl_leftshiftby1(dbl_opndA,dbl_opndB); \
exponent -= 1; \
}
#define Twoword_add(src1dstA,src1dstB,src2A,src2B) \
/* \
* want this macro to generate: \
* ADD src1dstB,src2B,src1dstB; \
* ADDC src1dstA,src2A,src1dstA; \
*/ \
if ((src1dstB) + (src2B) < (src1dstB)) Dallp1(src1dstA)++; \
Dallp1(src1dstA) += (src2A); \
Dallp2(src1dstB) += (src2B)
#define Twoword_subtract(src1dstA,src1dstB,src2A,src2B) \
/* \
* want this macro to generate: \
* SUB src1dstB,src2B,src1dstB; \
* SUBB src1dstA,src2A,src1dstA; \
*/ \
if ((src1dstB) < (src2B)) Dallp1(src1dstA)--; \
Dallp1(src1dstA) -= (src2A); \
Dallp2(src1dstB) -= (src2B)
#define Dbl_setoverflow(resultA,resultB) \
/* set result to infinity or largest number */ \
switch (Rounding_mode()) { \
case ROUNDPLUS: \
if (Dbl_isone_sign(resultA)) { \
Dbl_setlargestnegative(resultA,resultB); \
} \
else { \
Dbl_setinfinitypositive(resultA,resultB); \
} \
break; \
case ROUNDMINUS: \
if (Dbl_iszero_sign(resultA)) { \
Dbl_setlargestpositive(resultA,resultB); \
} \
else { \
Dbl_setinfinitynegative(resultA,resultB); \
} \
break; \
case ROUNDNEAREST: \
Dbl_setinfinity_exponentmantissa(resultA,resultB); \
break; \
case ROUNDZERO: \
Dbl_setlargest_exponentmantissa(resultA,resultB); \
}
#define Dbl_denormalize(opndp1,opndp2,exponent,guard,sticky,inexact) \
Dbl_clear_signexponent_set_hidden(opndp1); \
if (exponent >= (1-DBL_P)) { \
if (exponent >= -31) { \
guard = (Dallp2(opndp2) >> -exponent) & 1; \
if (exponent < 0) sticky |= Dallp2(opndp2) << (32+exponent); \
if (exponent > -31) { \
Variable_shift_double(opndp1,opndp2,1-exponent,opndp2); \
Dallp1(opndp1) >>= 1-exponent; \
} \
else { \
Dallp2(opndp2) = Dallp1(opndp1); \
Dbl_setzerop1(opndp1); \
} \
} \
else { \
guard = (Dallp1(opndp1) >> -32-exponent) & 1; \
if (exponent == -32) sticky |= Dallp2(opndp2); \
else sticky |= (Dallp2(opndp2) | Dallp1(opndp1) << 64+exponent); \
Dallp2(opndp2) = Dallp1(opndp1) >> -31-exponent; \
Dbl_setzerop1(opndp1); \
} \
inexact = guard | sticky; \
} \
else { \
guard = 0; \
sticky |= (Dallp1(opndp1) | Dallp2(opndp2)); \
Dbl_setzero(opndp1,opndp2); \
inexact = sticky; \
}
/*
* The fused multiply add instructions requires a double extended format,
* with 106 bits of mantissa.
*/
#define DBLEXT_THRESHOLD 106
#define Dblext_setzero(valA,valB,valC,valD) \
Dextallp1(valA) = 0; Dextallp2(valB) = 0; \
Dextallp3(valC) = 0; Dextallp4(valD) = 0
#define Dblext_isnotzero_mantissap3(valC) (Dextallp3(valC)!=0)
#define Dblext_isnotzero_mantissap4(valD) (Dextallp3(valD)!=0)
#define Dblext_isone_lowp2(val) (Dextlowp2(val)!=0)
#define Dblext_isone_highp3(val) (Dexthighp3(val)!=0)
#define Dblext_isnotzero_low31p3(val) (Dextlow31p3(val)!=0)
#define Dblext_iszero(valA,valB,valC,valD) (Dextallp1(valA)==0 && \
Dextallp2(valB)==0 && Dextallp3(valC)==0 && Dextallp4(valD)==0)
#define Dblext_copy(srca,srcb,srcc,srcd,desta,destb,destc,destd) \
Dextallp1(desta) = Dextallp4(srca); \
Dextallp2(destb) = Dextallp4(srcb); \
Dextallp3(destc) = Dextallp4(srcc); \
Dextallp4(destd) = Dextallp4(srcd)
#define Dblext_swap_lower(leftp2,leftp3,leftp4,rightp2,rightp3,rightp4) \
Dextallp2(leftp2) = Dextallp2(leftp2) XOR Dextallp2(rightp2); \
Dextallp2(rightp2) = Dextallp2(leftp2) XOR Dextallp2(rightp2); \
Dextallp2(leftp2) = Dextallp2(leftp2) XOR Dextallp2(rightp2); \
Dextallp3(leftp3) = Dextallp3(leftp3) XOR Dextallp3(rightp3); \
Dextallp3(rightp3) = Dextallp3(leftp3) XOR Dextallp3(rightp3); \
Dextallp3(leftp3) = Dextallp3(leftp3) XOR Dextallp3(rightp3); \
Dextallp4(leftp4) = Dextallp4(leftp4) XOR Dextallp4(rightp4); \
Dextallp4(rightp4) = Dextallp4(leftp4) XOR Dextallp4(rightp4); \
Dextallp4(leftp4) = Dextallp4(leftp4) XOR Dextallp4(rightp4)
#define Dblext_setone_lowmantissap4(dbl_value) Deposit_dextlowp4(dbl_value,1)
/* The high bit is always zero so arithmetic or logical shifts will work. */
#define Dblext_right_align(srcdstA,srcdstB,srcdstC,srcdstD,shift) \
{int shiftamt, sticky; \
shiftamt = shift % 32; \
sticky = 0; \
switch (shift/32) { \
case 0: if (shiftamt > 0) { \
sticky = Dextallp4(srcdstD) << 32 - (shiftamt); \
Variable_shift_double(Dextallp3(srcdstC), \
Dextallp4(srcdstD),shiftamt,Dextallp4(srcdstD)); \
Variable_shift_double(Dextallp2(srcdstB), \
Dextallp3(srcdstC),shiftamt,Dextallp3(srcdstC)); \
Variable_shift_double(Dextallp1(srcdstA), \
Dextallp2(srcdstB),shiftamt,Dextallp2(srcdstB)); \
Dextallp1(srcdstA) >>= shiftamt; \
} \
break; \
case 1: if (shiftamt > 0) { \
sticky = (Dextallp3(srcdstC) << 31 - shiftamt) | \
Dextallp4(srcdstD); \
Variable_shift_double(Dextallp2(srcdstB), \
Dextallp3(srcdstC),shiftamt,Dextallp4(srcdstD)); \
Variable_shift_double(Dextallp1(srcdstA), \
Dextallp2(srcdstB),shiftamt,Dextallp3(srcdstC)); \
} \
else { \
sticky = Dextallp4(srcdstD); \
Dextallp4(srcdstD) = Dextallp3(srcdstC); \
Dextallp3(srcdstC) = Dextallp2(srcdstB); \
} \
Dextallp2(srcdstB) = Dextallp1(srcdstA) >> shiftamt; \
Dextallp1(srcdstA) = 0; \
break; \
case 2: if (shiftamt > 0) { \
sticky = (Dextallp2(srcdstB) << 31 - shiftamt) | \
Dextallp3(srcdstC) | Dextallp4(srcdstD); \
Variable_shift_double(Dextallp1(srcdstA), \
Dextallp2(srcdstB),shiftamt,Dextallp4(srcdstD)); \
} \
else { \
sticky = Dextallp3(srcdstC) | Dextallp4(srcdstD); \
Dextallp4(srcdstD) = Dextallp2(srcdstB); \
} \
Dextallp3(srcdstC) = Dextallp1(srcdstA) >> shiftamt; \
Dextallp1(srcdstA) = Dextallp2(srcdstB) = 0; \
break; \
case 3: if (shiftamt > 0) { \
sticky = (Dextallp1(srcdstA) << 31 - shiftamt) | \
Dextallp2(srcdstB) | Dextallp3(srcdstC) | \
Dextallp4(srcdstD); \
} \
else { \
sticky = Dextallp2(srcdstB) | Dextallp3(srcdstC) | \
Dextallp4(srcdstD); \
} \
Dextallp4(srcdstD) = Dextallp1(srcdstA) >> shiftamt; \
Dextallp1(srcdstA) = Dextallp2(srcdstB) = 0; \
Dextallp3(srcdstC) = 0; \
break; \
} \
if (sticky) Dblext_setone_lowmantissap4(srcdstD); \
}
/* The left argument is never smaller than the right argument */
#define Dblext_subtract(lefta,leftb,leftc,leftd,righta,rightb,rightc,rightd,resulta,resultb,resultc,resultd) \
if( Dextallp4(rightd) > Dextallp4(leftd) ) \
if( (Dextallp3(leftc)--) == 0) \
if( (Dextallp2(leftb)--) == 0) Dextallp1(lefta)--; \
Dextallp4(resultd) = Dextallp4(leftd) - Dextallp4(rightd); \
if( Dextallp3(rightc) > Dextallp3(leftc) ) \
if( (Dextallp2(leftb)--) == 0) Dextallp1(lefta)--; \
Dextallp3(resultc) = Dextallp3(leftc) - Dextallp3(rightc); \
if( Dextallp2(rightb) > Dextallp2(leftb) ) Dextallp1(lefta)--; \
Dextallp2(resultb) = Dextallp2(leftb) - Dextallp2(rightb); \
Dextallp1(resulta) = Dextallp1(lefta) - Dextallp1(righta)
#define Dblext_addition(lefta,leftb,leftc,leftd,righta,rightb,rightc,rightd,resulta,resultb,resultc,resultd) \
/* If the sum of the low words is less than either source, then \
* an overflow into the next word occurred. */ \
if ((Dextallp4(resultd) = Dextallp4(leftd)+Dextallp4(rightd)) < \
Dextallp4(rightd)) \
if((Dextallp3(resultc) = Dextallp3(leftc)+Dextallp3(rightc)+1) <= \
Dextallp3(rightc)) \
if((Dextallp2(resultb) = Dextallp2(leftb)+Dextallp2(rightb)+1) \
<= Dextallp2(rightb)) \
Dextallp1(resulta) = Dextallp1(lefta)+Dextallp1(righta)+1; \
else Dextallp1(resulta) = Dextallp1(lefta)+Dextallp1(righta); \
else \
if ((Dextallp2(resultb) = Dextallp2(leftb)+Dextallp2(rightb)) < \
Dextallp2(rightb)) \
Dextallp1(resulta) = Dextallp1(lefta)+Dextallp1(righta)+1; \
else Dextallp1(resulta) = Dextallp1(lefta)+Dextallp1(righta); \
else \
if ((Dextallp3(resultc) = Dextallp3(leftc)+Dextallp3(rightc)) < \
Dextallp3(rightc)) \
if ((Dextallp2(resultb) = Dextallp2(leftb)+Dextallp2(rightb)+1) \
<= Dextallp2(rightb)) \
Dextallp1(resulta) = Dextallp1(lefta)+Dextallp1(righta)+1; \
else Dextallp1(resulta) = Dextallp1(lefta)+Dextallp1(righta); \
else \
if ((Dextallp2(resultb) = Dextallp2(leftb)+Dextallp2(rightb)) < \
Dextallp2(rightb)) \
Dextallp1(resulta) = Dextallp1(lefta)+Dextallp1(righta)+1; \
else Dextallp1(resulta) = Dextallp1(lefta)+Dextallp1(righta)
#define Dblext_arithrightshiftby1(srcdstA,srcdstB,srcdstC,srcdstD) \
Shiftdouble(Dextallp3(srcdstC),Dextallp4(srcdstD),1,Dextallp4(srcdstD)); \
Shiftdouble(Dextallp2(srcdstB),Dextallp3(srcdstC),1,Dextallp3(srcdstC)); \
Shiftdouble(Dextallp1(srcdstA),Dextallp2(srcdstB),1,Dextallp2(srcdstB)); \
Dextallp1(srcdstA) = (int)Dextallp1(srcdstA) >> 1
#define Dblext_leftshiftby8(valA,valB,valC,valD) \
Shiftdouble(Dextallp1(valA),Dextallp2(valB),24,Dextallp1(valA)); \
Shiftdouble(Dextallp2(valB),Dextallp3(valC),24,Dextallp2(valB)); \
Shiftdouble(Dextallp3(valC),Dextallp4(valD),24,Dextallp3(valC)); \
Dextallp4(valD) <<= 8
#define Dblext_leftshiftby4(valA,valB,valC,valD) \
Shiftdouble(Dextallp1(valA),Dextallp2(valB),28,Dextallp1(valA)); \
Shiftdouble(Dextallp2(valB),Dextallp3(valC),28,Dextallp2(valB)); \
Shiftdouble(Dextallp3(valC),Dextallp4(valD),28,Dextallp3(valC)); \
Dextallp4(valD) <<= 4
#define Dblext_leftshiftby3(valA,valB,valC,valD) \
Shiftdouble(Dextallp1(valA),Dextallp2(valB),29,Dextallp1(valA)); \
Shiftdouble(Dextallp2(valB),Dextallp3(valC),29,Dextallp2(valB)); \
Shiftdouble(Dextallp3(valC),Dextallp4(valD),29,Dextallp3(valC)); \
Dextallp4(valD) <<= 3
#define Dblext_leftshiftby2(valA,valB,valC,valD) \
Shiftdouble(Dextallp1(valA),Dextallp2(valB),30,Dextallp1(valA)); \
Shiftdouble(Dextallp2(valB),Dextallp3(valC),30,Dextallp2(valB)); \
Shiftdouble(Dextallp3(valC),Dextallp4(valD),30,Dextallp3(valC)); \
Dextallp4(valD) <<= 2
#define Dblext_leftshiftby1(valA,valB,valC,valD) \
Shiftdouble(Dextallp1(valA),Dextallp2(valB),31,Dextallp1(valA)); \
Shiftdouble(Dextallp2(valB),Dextallp3(valC),31,Dextallp2(valB)); \
Shiftdouble(Dextallp3(valC),Dextallp4(valD),31,Dextallp3(valC)); \
Dextallp4(valD) <<= 1
#define Dblext_rightshiftby4(valueA,valueB,valueC,valueD) \
Shiftdouble(Dextallp3(valueC),Dextallp4(valueD),4,Dextallp4(valueD)); \
Shiftdouble(Dextallp2(valueB),Dextallp3(valueC),4,Dextallp3(valueC)); \
Shiftdouble(Dextallp1(valueA),Dextallp2(valueB),4,Dextallp2(valueB)); \
Dextallp1(valueA) >>= 4
#define Dblext_rightshiftby1(valueA,valueB,valueC,valueD) \
Shiftdouble(Dextallp3(valueC),Dextallp4(valueD),1,Dextallp4(valueD)); \
Shiftdouble(Dextallp2(valueB),Dextallp3(valueC),1,Dextallp3(valueC)); \
Shiftdouble(Dextallp1(valueA),Dextallp2(valueB),1,Dextallp2(valueB)); \
Dextallp1(valueA) >>= 1
#define Dblext_xortointp1(left,right,result) Dbl_xortointp1(left,right,result)
#define Dblext_xorfromintp1(left,right,result) \
Dbl_xorfromintp1(left,right,result)
#define Dblext_copytoint_exponentmantissap1(src,dest) \
Dbl_copytoint_exponentmantissap1(src,dest)
#define Dblext_ismagnitudeless(leftB,rightB,signlessleft,signlessright) \
Dbl_ismagnitudeless(leftB,rightB,signlessleft,signlessright)
#define Dbl_copyto_dblext(src1,src2,dest1,dest2,dest3,dest4) \
Dextallp1(dest1) = Dallp1(src1); Dextallp2(dest2) = Dallp2(src2); \
Dextallp3(dest3) = 0; Dextallp4(dest4) = 0
#define Dblext_set_sign(dbl_value,sign) Dbl_set_sign(dbl_value,sign)
#define Dblext_clear_signexponent_set_hidden(srcdst) \
Dbl_clear_signexponent_set_hidden(srcdst)
#define Dblext_clear_signexponent(srcdst) Dbl_clear_signexponent(srcdst)
#define Dblext_clear_sign(srcdst) Dbl_clear_sign(srcdst)
#define Dblext_isone_hidden(dbl_value) Dbl_isone_hidden(dbl_value)
/*
* The Fourword_add() macro assumes that integers are 4 bytes in size.
* It will break if this is not the case.
*/
#define Fourword_add(src1dstA,src1dstB,src1dstC,src1dstD,src2A,src2B,src2C,src2D) \
/* \
* want this macro to generate: \
* ADD src1dstD,src2D,src1dstD; \
* ADDC src1dstC,src2C,src1dstC; \
* ADDC src1dstB,src2B,src1dstB; \
* ADDC src1dstA,src2A,src1dstA; \
*/ \
if ((unsigned int)(src1dstD += (src2D)) < (unsigned int)(src2D)) { \
if ((unsigned int)(src1dstC += (src2C) + 1) <= \
(unsigned int)(src2C)) { \
if ((unsigned int)(src1dstB += (src2B) + 1) <= \
(unsigned int)(src2B)) src1dstA++; \
} \
else if ((unsigned int)(src1dstB += (src2B)) < \
(unsigned int)(src2B)) src1dstA++; \
} \
else { \
if ((unsigned int)(src1dstC += (src2C)) < \
(unsigned int)(src2C)) { \
if ((unsigned int)(src1dstB += (src2B) + 1) <= \
(unsigned int)(src2B)) src1dstA++; \
} \
else if ((unsigned int)(src1dstB += (src2B)) < \
(unsigned int)(src2B)) src1dstA++; \
} \
src1dstA += (src2A)
#define Dblext_denormalize(opndp1,opndp2,opndp3,opndp4,exponent,is_tiny) \
{int shiftamt, sticky; \
is_tiny = TRUE; \
if (exponent == 0 && (Dextallp3(opndp3) || Dextallp4(opndp4))) { \
switch (Rounding_mode()) { \
case ROUNDPLUS: \
if (Dbl_iszero_sign(opndp1)) { \
Dbl_increment(opndp1,opndp2); \
if (Dbl_isone_hiddenoverflow(opndp1)) \
is_tiny = FALSE; \
Dbl_decrement(opndp1,opndp2); \
} \
break; \
case ROUNDMINUS: \
if (Dbl_isone_sign(opndp1)) { \
Dbl_increment(opndp1,opndp2); \
if (Dbl_isone_hiddenoverflow(opndp1)) \
is_tiny = FALSE; \
Dbl_decrement(opndp1,opndp2); \
} \
break; \
case ROUNDNEAREST: \
if (Dblext_isone_highp3(opndp3) && \
(Dblext_isone_lowp2(opndp2) || \
Dblext_isnotzero_low31p3(opndp3))) { \
Dbl_increment(opndp1,opndp2); \
if (Dbl_isone_hiddenoverflow(opndp1)) \
is_tiny = FALSE; \
Dbl_decrement(opndp1,opndp2); \
} \
break; \
} \
} \
Dblext_clear_signexponent_set_hidden(opndp1); \
if (exponent >= (1-QUAD_P)) { \
shiftamt = (1-exponent) % 32; \
switch((1-exponent)/32) { \
case 0: sticky = Dextallp4(opndp4) << 32-(shiftamt); \
Variableshiftdouble(opndp3,opndp4,shiftamt,opndp4); \
Variableshiftdouble(opndp2,opndp3,shiftamt,opndp3); \
Variableshiftdouble(opndp1,opndp2,shiftamt,opndp2); \
Dextallp1(opndp1) >>= shiftamt; \
break; \
case 1: sticky = (Dextallp3(opndp3) << 32-(shiftamt)) | \
Dextallp4(opndp4); \
Variableshiftdouble(opndp2,opndp3,shiftamt,opndp4); \
Variableshiftdouble(opndp1,opndp2,shiftamt,opndp3); \
Dextallp2(opndp2) = Dextallp1(opndp1) >> shiftamt; \
Dextallp1(opndp1) = 0; \
break; \
case 2: sticky = (Dextallp2(opndp2) << 32-(shiftamt)) | \
Dextallp3(opndp3) | Dextallp4(opndp4); \
Variableshiftdouble(opndp1,opndp2,shiftamt,opndp4); \
Dextallp3(opndp3) = Dextallp1(opndp1) >> shiftamt; \
Dextallp1(opndp1) = Dextallp2(opndp2) = 0; \
break; \
case 3: sticky = (Dextallp1(opndp1) << 32-(shiftamt)) | \
Dextallp2(opndp2) | Dextallp3(opndp3) | \
Dextallp4(opndp4); \
Dextallp4(opndp4) = Dextallp1(opndp1) >> shiftamt; \
Dextallp1(opndp1) = Dextallp2(opndp2) = 0; \
Dextallp3(opndp3) = 0; \
break; \
} \
} \
else { \
sticky = Dextallp1(opndp1) | Dextallp2(opndp2) | \
Dextallp3(opndp3) | Dextallp4(opndp4); \
Dblext_setzero(opndp1,opndp2,opndp3,opndp4); \
} \
if (sticky) Dblext_setone_lowmantissap4(opndp4); \
exponent = 0; \
}
|
seven332/rhino-android | src/org/mozilla/javascript/xml/XMLObject.java | /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.javascript.xml;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.IdScriptableObject;
import org.mozilla.javascript.NativeWith;
import org.mozilla.javascript.Ref;
import org.mozilla.javascript.Scriptable;
/**
* This Interface describes what all XML objects (XML, XMLList) should have in common.
*
*/
public abstract class XMLObject extends IdScriptableObject
{
private static final long serialVersionUID = 8455156490438576500L;
public XMLObject()
{
}
public XMLObject(Scriptable scope, Scriptable prototype)
{
super(scope, prototype);
}
/**
* Implementation of ECMAScript [[Has]].
*/
public abstract boolean has(Context cx, Object id);
/**
* Implementation of ECMAScript [[Get]].
*/
public abstract Object get(Context cx, Object id);
/**
* Implementation of ECMAScript [[Put]].
*/
public abstract void put(Context cx, Object id, Object value);
/**
* Implementation of ECMAScript [[Delete]].
*/
public abstract boolean delete(Context cx, Object id);
public abstract Object getFunctionProperty(Context cx, String name);
public abstract Object getFunctionProperty(Context cx, int id);
/**
* Return an additional object to look for methods that runtime should
* consider during method search. Return null if no such object available.
*/
public abstract Scriptable getExtraMethodSource(Context cx);
/**
* Generic reference to implement x.@y, x..y etc.
*/
public abstract Ref memberRef(Context cx, Object elem,
int memberTypeFlags);
/**
* Generic reference to implement x::ns, x.@ns::y, x..@ns::y etc.
*/
public abstract Ref memberRef(Context cx, Object namespace, Object elem,
int memberTypeFlags);
/**
* Wrap this object into NativeWith to implement the with statement.
*/
public abstract NativeWith enterWith(Scriptable scope);
/**
* Wrap this object into NativeWith to implement the .() query.
*/
public abstract NativeWith enterDotQuery(Scriptable scope);
/**
* Custom <tt>+</tt> operator.
* Should return {@link Scriptable#NOT_FOUND} if this object does not have
* custom addition operator for the given value,
* or the result of the addition operation.
* <p>
* The default implementation returns {@link Scriptable#NOT_FOUND}
* to indicate no custom addition operation.
*
* @param cx the Context object associated with the current thread.
* @param thisIsLeft if true, the object should calculate this + value
* if false, the object should calculate value + this.
* @param value the second argument for addition operation.
*/
public Object addValues(Context cx, boolean thisIsLeft, Object value)
{
return Scriptable.NOT_FOUND;
}
/**
* Gets the value returned by calling the typeof operator on this object.
* @see org.mozilla.javascript.ScriptableObject#getTypeOf()
* @return "xml" or "undefined" if {@link #avoidObjectDetection()} returns <code>true</code>
*/
@Override
public String getTypeOf()
{
return avoidObjectDetection() ? "undefined" : "xml";
}
}
|
volunL/Matterwiki4j | matterwiki-4j-boot/src/main/java/com/brainboom/matterwiki4jboot/security/service/TokenUserDetailsService.java | package com.brainboom.matterwiki4jboot.security.service;
import com.brainboom.matterwiki4jboot.entity.Users;
import com.brainboom.matterwiki4jboot.repository.UsersRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@Service
public class TokenUserDetailsService implements UserDetailsService {
@Autowired
UsersRepository usersRepository;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
List<SimpleGrantedAuthority> roles = new ArrayList<>();
Users users = usersRepository.findUsersByEmail(s);
if (users == null) {
throw new UsernameNotFoundException("user " + s + " not found");
}
if (users.getId() == 1) {
roles.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
return new User(users.getName(), users.getPassword(), roles);
} else {
roles.add(new SimpleGrantedAuthority("ROLE_USER"));
return new User(users.getName(), users.getPassword(), roles);
}
}
}
|
lalaguozhe/Taurus | taurus-restlet/src/main/java/com/dp/bigdata/taurus/restlet/utils/DeployOptions.java | <filename>taurus-restlet/src/main/java/com/dp/bigdata/taurus/restlet/utils/DeployOptions.java
package com.dp.bigdata.taurus.restlet.utils;
/**
*
* DeployOptions
* @author damon.zhu
*
*/
public enum DeployOptions {
DEPLOY,
UNDEPLOY,
}
|
romainfroidevaux/RealTimeEmbeddedConsole | doc/html/search/variables_b.js | var searchData=
[
['name',['name',['../a00035.html#a4ddd389d5fc1d96becd50015ee4c97ff',1,'shell_interpreter_cmd']]],
['next',['next',['../a00035.html#a4fcd250edcf6e7b55c4767686b3babaf',1,'shell_interpreter_cmd']]],
['nimask',['nimask',['../a00001.html#a8a1c8828c1a0f8dc03eb097d826caf4d',1,'aitc_ctrl']]],
['nipnd',['nipnd',['../a00001.html#ad7d90d77ccfe32f96618711bfa303e07',1,'aitc_ctrl']]],
['nipriority',['nipriority',['../a00001.html#ae5128351c0c97092655ea90a7a76b181',1,'aitc_ctrl']]],
['nivecsr',['nivecsr',['../a00001.html#a4136ec610468d6bdc4fd063c5f0bd058',1,'aitc_ctrl']]]
];
|
gromgit/homebrew-oldcore | Formula/liblqr.rb | class Liblqr < Formula
desc "C/C++ seam carving library"
homepage "https://liblqr.wikidot.com/"
license "LGPL-3.0"
revision 1
head "https://github.com/carlobaldassi/liblqr.git", branch: "master"
stable do
url "https://github.com/carlobaldassi/liblqr/archive/v0.4.2.tar.gz"
sha256 "1019a2d91f3935f1f817eb204a51ec977a060d39704c6dafa183b110fd6280b0"
# Fix -flat_namespace being used on Big Sur and later.
patch do
url "https://raw.githubusercontent.com/Homebrew/formula-patches/03cf8088210822aa2c1ab544ed58ea04c897d9c4/libtool/configure-pre-0.4.2.418-big_sur.diff"
sha256 "83af02f2aa2b746bb7225872cab29a253264be49db0ecebb12f841562d9a2923"
end
end
bottle do
root_url "https://github.com/gromgit/homebrew-core-mojave/releases/download/liblqr"
rebuild 2
sha256 cellar: :any, mojave: "3d69ddb1234403f986452994601e016a71713feabf03361e15a5b22e24e63f26"
end
depends_on "pkg-config" => :build
depends_on "glib"
def install
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make", "install"
end
end
|
coreplane/expo | ios/Pods/Headers/Private/ABI40_0_0Yoga/ABI40_0_0yoga/ABI40_0_0YGConfig.h | <reponame>coreplane/expo<gh_stars>1-10
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include "ABI40_0_0Yoga-internal.h"
#include "ABI40_0_0Yoga.h"
struct YOGA_EXPORT ABI40_0_0YGConfig {
using LogWithContextFn = int (*)(
ABI40_0_0YGConfigRef config,
ABI40_0_0YGNodeRef node,
ABI40_0_0YGLogLevel level,
void* context,
const char* format,
va_list args);
using CloneWithContextFn = ABI40_0_0YGNodeRef (*)(
ABI40_0_0YGNodeRef node,
ABI40_0_0YGNodeRef owner,
int childIndex,
void* cloneContext);
private:
union {
CloneWithContextFn withContext;
ABI40_0_0YGCloneNodeFunc noContext;
} cloneNodeCallback_;
union {
LogWithContextFn withContext;
ABI40_0_0YGLogger noContext;
} logger_;
bool cloneNodeUsesContext_;
bool loggerUsesContext_;
public:
bool useWebDefaults = false;
bool useLegacyStretchBehaviour = false;
bool shouldDiffLayoutWithoutLegacyStretchBehaviour = false;
bool printTree = false;
float pointScaleFactor = 1.0f;
std::array<bool, ABI40_0_0facebook::yoga::enums::count<ABI40_0_0YGExperimentalFeature>()>
experimentalFeatures = {};
void* context = nullptr;
ABI40_0_0YGConfig(ABI40_0_0YGLogger logger);
void log(ABI40_0_0YGConfig*, ABI40_0_0YGNode*, ABI40_0_0YGLogLevel, void*, const char*, va_list);
void setLogger(ABI40_0_0YGLogger logger) {
logger_.noContext = logger;
loggerUsesContext_ = false;
}
void setLogger(LogWithContextFn logger) {
logger_.withContext = logger;
loggerUsesContext_ = true;
}
void setLogger(std::nullptr_t) { setLogger(ABI40_0_0YGLogger{nullptr}); }
ABI40_0_0YGNodeRef cloneNode(
ABI40_0_0YGNodeRef node,
ABI40_0_0YGNodeRef owner,
int childIndex,
void* cloneContext);
void setCloneNodeCallback(ABI40_0_0YGCloneNodeFunc cloneNode) {
cloneNodeCallback_.noContext = cloneNode;
cloneNodeUsesContext_ = false;
}
void setCloneNodeCallback(CloneWithContextFn cloneNode) {
cloneNodeCallback_.withContext = cloneNode;
cloneNodeUsesContext_ = true;
}
void setCloneNodeCallback(std::nullptr_t) {
setCloneNodeCallback(ABI40_0_0YGCloneNodeFunc{nullptr});
}
};
|
tony810430/ozone | hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/server/events/SingleThreadExecutor.java | <reponame>tony810430/ozone
/*
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdds.server.events;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.hadoop.metrics2.annotation.Metric;
import org.apache.hadoop.metrics2.annotation.Metrics;
import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
import org.apache.hadoop.metrics2.lib.MutableCounterLong;
/**
* Simple EventExecutor to call all the event handler one-by-one.
*
* @param <P> the payload type of events
*/
@Metrics(context = "EventQueue")
public class SingleThreadExecutor<P> implements EventExecutor<P> {
private static final String EVENT_QUEUE = "EventQueue";
private static final Logger LOG =
LoggerFactory.getLogger(SingleThreadExecutor.class);
private final String name;
private final ExecutorService executor;
@Metric
private MutableCounterLong queued;
@Metric
private MutableCounterLong done;
@Metric
private MutableCounterLong failed;
/**
* Create SingleThreadExecutor.
*
* @param name Unique name used in monitoring and metrics.
*/
public SingleThreadExecutor(String name) {
this.name = name;
DefaultMetricsSystem.instance()
.register(EVENT_QUEUE + name, "Event Executor metrics ", this);
executor = Executors.newSingleThreadExecutor(
runnable -> {
Thread thread = new Thread(runnable);
thread.setName(EVENT_QUEUE + "-" + name);
return thread;
});
}
@Override
public void onMessage(EventHandler<P> handler, P message, EventPublisher
publisher) {
queued.incr();
executor.execute(() -> {
try {
handler.onMessage(message, publisher);
done.incr();
} catch (Exception ex) {
LOG.error("Error on execution message {}", message, ex);
failed.incr();
}
});
}
@Override
public long failedEvents() {
return failed.value();
}
@Override
public long successfulEvents() {
return done.value();
}
@Override
public long queuedEvents() {
return queued.value();
}
@Override
public void close() {
executor.shutdown();
}
@Override
public String getName() {
return name;
}
}
|
acisternino/narjillos | src/main/java/org/nusco/narjillos/persistence/serialization/ThingAdapter.java | <reponame>acisternino/narjillos
package org.nusco.narjillos.persistence.serialization;
import org.nusco.narjillos.experiment.environment.FoodPellet;
import org.nusco.narjillos.core.things.Thing;
import org.nusco.narjillos.creature.Egg;
import org.nusco.narjillos.creature.Narjillo;
import com.google.gson.JsonParseException;
class ThingAdapter extends HierarchyAdapter<Thing> {
@Override
protected String getTypeTag(Thing obj) {
return obj.getLabel();
}
@Override
protected Class<?> getClass(String typeTag) throws JsonParseException {
switch (typeTag) {
case FoodPellet.LABEL:
return FoodPellet.class;
case Egg.LABEL:
return Egg.class;
case Narjillo.LABEL:
return Narjillo.class;
}
throw new RuntimeException("Unknown subtype of Thing: " + typeTag);
}
}
|
julian-lai/useragent | lib/user_agent/browsers/amazon_music.rb | # frozen_string_literal: true
class UserAgent
module Browsers
# AmazonMusic/17.7.2 Mozilla/5.0 (Linux; Android 8.1.0; 5059X Build/O11019; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/64.0.3282.137 Mobile Safari/537.36
# AmazonMusic/10.0.0 iPad8,9 CFNetwork/1220.1 Darwin/20.3.0
# AmazonMusic/10.2.0 iPhone11,6 CFNetwork/1237 Darwin/20.4.0
# AmazonMusic/1.0 x86_64 CFNetwork/1121.2.1 Darwin/19.6.0
# AmazonMusic/16.17.1 Dalvik/2.1.0 (Linux; U; Android 7.0; LGL83BL Build/NRD90U)
# AmazonMusic
class AmazonMusic < Base
include DesktopClassifiable
AMAZONMUSIC = 'AmazonMusic'
AMAZON_MUSIC = 'Amazon Music'
IPAD_IPHONE = %w[iPad iPhone].freeze
##
# @param agent [Array]
# Array of useragent product
# @return [Boolean]
# True if the useragent matches this browser
def self.extend?(agent)
agent.detect { |useragent| useragent.product == AMAZONMUSIC }
end
##
# @return [String]
# The browser name
def browser
AMAZON_MUSIC
end
##
# @return [Boolean]
# True if it's a mobile
def mobile?
return true if IPAD_IPHONE.include?(platform)
super
end
# Gets the operating system
#
# @return [String, nil] the os
def os
if IPAD_IPHONE.include?(platform) && app = detect_product(DARWIN)
[IOS, UserAgent::OperatingSystems::Darwin::IOS[app.version.to_s]].compact.join(' ')
elsif platform == MACINTOSH && app = detect_product(DARWIN)
[MAC_OS, UserAgent::OperatingSystems::Darwin::MAC_OS[app.version.to_s]].compact.join(' ')
else
app = app_with_comments
if (app && os_string = app.comment.detect { |c| ANDROID_REGEX.match?(c) })
OperatingSystems.normalize_os(os_string)
end
end
end
# Gets the platform
#
# @return [String, nil] the platform
def platform
ua = self.to_s
return IPAD if IPAD_REGEX.match?(ua)
return IPHONE if IPHONE_REGEX.match?(ua)
return MACINTOSH if DARWIN_REGEX.match?(ua)
app = app_with_comments
ANDROID if app && app.comment.any? { |c| ANDROID_REGEX.match?(c) }
end
end
end
end
|
wangsikai/learn | yoo-master-dc2492330d5d46b48f1ceca891e0f9f7e1593fee/module/core/file/src/main/java/com/lanking/uxb/service/file/cache/FileCacheService.java | package com.lanking.uxb.service.file.cache;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lanking.cloud.domain.base.file.File;
import com.lanking.cloud.sdk.util.CollectionUtils;
import com.lanking.uxb.service.cache.api.impl.AbstractCacheService;
@Service
@SuppressWarnings("unchecked")
public class FileCacheService extends AbstractCacheService {
private ValueOperations<String, File> filesOpt;
private static final String FILE_KEY = "f";
private static final String FILE_MD5_KEY = "md5";
private String getFileKey(long id) {
return assemblyKey(FILE_KEY, id);
}
private List<String> mgetFileKey(List<Long> ids) {
List<String> keys = Lists.newArrayList();
if (CollectionUtils.isNotEmpty(ids)) {
for (Long id : ids) {
keys.add(getFileKey(id));
}
}
return keys;
}
public File getFileById(long id) {
return filesOpt.get(getFileKey(id));
}
public void setFile(long id, File file) {
filesOpt.set(getFileKey(id), file);
}
public void setFile(File file) {
filesOpt.set(getFileKey(file.getId()), file);
}
public void msetFile(List<File> files) {
if (CollectionUtils.isNotEmpty(files)) {
for (File file : files) {
if (file != null) {
setFile(file);
}
}
}
}
public Map<Long, File> mget(List<Long> ids) {
Map<Long, File> fileMap = Maps.newHashMap();
List<String> keys = mgetFileKey(ids);
List<File> files = filesOpt.multiGet(keys);
if (CollectionUtils.isNotEmpty(files)) {
for (File file : files) {
if (file != null) {
fileMap.put(file.getId(), file);
}
}
}
return fileMap;
}
public void delete(long id) {
getRedisTemplate().delete(getFileKey(id));
}
public void delete(Collection<Long> ids) {
List<String> keys = Lists.newArrayList();
for (Long id : ids) {
keys.add(getFileKey(id));
}
getRedisTemplate().delete(keys);
}
private String getFileMd5Key(long spaceId, String md5) {
return assemblyKey(FILE_MD5_KEY, spaceId, md5);
}
public File getFileByMd5(long spaceId, String md5) {
return filesOpt.get(getFileMd5Key(spaceId, md5));
}
public void setFileMd5(File file) {
filesOpt.set(getFileMd5Key(file.getSpaceId(), file.getMd5()), file);
}
@Override
public String getNs() {
return "f";
}
@Override
public String getNsCn() {
return "文件";
}
@Override
public void afterPropertiesSet() {
super.afterPropertiesSet();
filesOpt = getRedisTemplate().opsForValue();
}
}
|
ichitaso/TwitterListEnabler | Twitter-Dumped/7.51.5/t1/_TtC9T1Twitter23LoadingGapTableViewCell.h | //
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>.
//
#import <TFNUI/TFNTableViewCell.h>
__attribute__((visibility("hidden")))
@interface _TtC9T1Twitter23LoadingGapTableViewCell : TFNTableViewCell
{
// Error parsing type: , name: stackView
// Error parsing type: , name: activityIndicator
// Error parsing type: , name: loadingDirectionIndicator
// Error parsing type: , name: titleLabel
// Error parsing type: , name: loadingDisplayState
// Error parsing type: , name: loadingDirection
// Error parsing type: , name: supportsDirectionalLoading
}
- (void).cxx_destruct;
- (void)didDisplayInDataViewController:(id)arg1 atIndexPath:(id)arg2 visibleIntersection:(struct CGRect)arg3;
- (void)willDisplayInDataViewController:(id)arg1 atIndexPath:(id)arg2;
- (void)updateConstraints;
- (void)layoutMetricsDidChange:(id)arg1;
- (id)initWithCoder:(id)arg1;
- (id)initWithStyle:(long long)arg1 reuseIdentifier:(id)arg2;
@end
|
ktsanter/instructor-tips | server/private/welcomeletter/scripts/configuration.js | <gh_stars>0
//-------------------------------------------------------------------
// welcome letter configuration
//-------------------------------------------------------------------
// TODO: use profile pic in letter (option for a different one?)
// TODO: add tiny editor for formatted message
// TODO: finish help
//-------------------------------------------------------------------
const app = function () {
const page = {};
const appInfo = {
appName: 'Welcome letter configuration'
};
const settings = {
hideClass: 'hide-me',
navItemClass: 'use-handler',
currentCourse: null,
logoutURL: '/usermanagement/logout/welcomeV2',
optionsURL: '/welcomeletter/options',
helpURL: '/welcomeletter/help',
previewURL_base: '/welcomeletterV2',
dirtyBit: {
navConfiguration: false,
navPreview: false,
navShare: false,
navProfile: false
}
};
//---------------------------------------
// get things going
//----------------------------------------
async function init (sodium) {
page.body = document.getElementsByTagName('body')[0];
page.errorContainer = page.body.getElementsByClassName('error-container')[0];
page.notice = new StandardNotice(page.errorContainer, page.errorContainer);
page.contents = page.body.getElementsByClassName('contents')[0];
page.contentsConfiguration = page.contents.getElementsByClassName('contents-navConfiguration')[0];
page.contentsPreview = page.contents.getElementsByClassName('contents-navPreview')[0];
page.contentsShare = page.contents.getElementsByClassName('contents-navShare')[0];
page.notice.setNotice('loading...', true);
page.navbar = page.body.getElementsByClassName('navbar')[0];
UtilityKTS.setClass(page.navbar, settings.hideClass, true);
_attachNavbarHandlers(); // do these before making the profile object
await _initProfile(sodium);
page.notice.setNotice('');
UtilityKTS.setClass(page.navbar, settings.hideClass, false);
await _renderContents();
page.navbar.getElementsByClassName(settings.navItemClass)[0].click();
}
async function _initProfile(sodium) {
settings.profile = new ASProfile({
id: "myProfile",
"sodium": sodium,
navbarElements: {
"save": page.navbar.getElementsByClassName('navSave')[0],
"reload": page.navbar.getElementsByClassName('navReload')[0],
"icon": page.navbar.getElementsByClassName('icon-profile')[0],
"pic": page.navbar.getElementsByClassName('pic-profile')[0]
},
hideClass: settings.hideClass
});
await settings.profile.init();
}
//-----------------------------------------------------------------------------
// navbar
//-----------------------------------------------------------------------------
function _attachNavbarHandlers() {
var handler = (e) => { _navDispatch(e); }
var navItems = page.navbar.getElementsByClassName(settings.navItemClass);
for (var i = 0; i < navItems.length; i++) {
navItems[i].addEventListener('click', handler);
}
// hide disallowed nav features
var allowOptions = page.body.getElementsByClassName('allowoptions')[0].innerHTML == 'true';
if (!allowOptions) {
var elemNav = document.getElementById('navEditOptions');
var elemDivider = document.getElementById('dividerNav2');
UtilityKTS.setClass(elemNav, settings.hideClass, true);
UtilityKTS.setClass(elemDivider, settings.hideClass, true);
}
}
//-----------------------------------------------------------------------------
// page rendering
//-----------------------------------------------------------------------------
async function _renderContents() {
page.elemCourseSelection = page.contentsConfiguration.getElementsByClassName('select-course')[0];
page.elemProjectAdd = page.contentsConfiguration.getElementsByClassName('button-add')[0];
page.elemProjectDelete = page.contentsConfiguration.getElementsByClassName('button-delete')[0];
// configuration
page.elemAPCourse = page.contentsConfiguration.getElementsByClassName('check-apcourse')[0];
page.elemHasPasswords = page.contentsConfiguration.getElementsByClassName('check-haspasswords')[0];
page.elemExamsSelection = page.contentsConfiguration.getElementsByClassName('select-exams')[0];
page.elemProctoringSelection = page.contentsConfiguration.getElementsByClassName('select-proctoring')[0];
page.elemRetakesSelection = page.contentsConfiguration.getElementsByClassName('select-retakes')[0];
page.elemResubmissionSelect = page.contentsConfiguration.getElementsByClassName('select-resubmission')[0];
// preview
page.elemAudience = page.contentsPreview.getElementsByClassName('check-audience')[0];
page.elemAudience.leftLabel = page.elemAudience.parentNode.parentNode.getElementsByClassName('checkbox-label-left')[0];
page.elemAudience.rightLabel = page.elemAudience.parentNode.getElementsByClassName('checkbox-label-right')[0];
page.elemPreviewFrame = page.contentsPreview.getElementsByClassName('preview-frame')[0];
// share
page.elemLinkStudent = page.contentsShare.getElementsByClassName('btnLinkStudent')[0];
page.elemMessageStudent = page.contentsShare.getElementsByClassName('btnMessageStudent')[0];
page.elemLinkMentor = page.contentsShare.getElementsByClassName('btnLinkMentor')[0];
page.elemMessageMentor = page.contentsShare.getElementsByClassName('btnMessageMentor')[0];
_attachHandlers();
await _updateCourseSelection();
}
function _attachHandlers() {
// configuration
page.elemCourseSelection.addEventListener('change', (e) => { _handleCourseSelection(e); });
page.elemProjectAdd.addEventListener('click', () => { _addCourse(); });
page.elemProjectDelete.addEventListener('click', (e) => { _deleteCourse(e); });
page.elemAPCourse.addEventListener('click', (e) => { _handleConfigChange(e); });
page.elemHasPasswords.addEventListener('click', (e) => { _handleConfigChange(e); });
page.elemExamsSelection.addEventListener('change', (e) => { _handleConfigChange(e); });
page.elemProctoringSelection.addEventListener('change', (e) => { _handleConfigChange(e); });
page.elemRetakesSelection.addEventListener('change', (e) => { _handleConfigChange(e); });
page.elemResubmissionSelect.addEventListener('change', (e) => { _handleConfigChange(e); });
// preview
page.elemAudience.addEventListener('click', (e) => { _handleAudienceChange(e); });
page.elemAudience.leftLabel.addEventListener('click', () => { _handleDoubleSwitch(page.elemAudience, 'left'); });
page.elemAudience.rightLabel.addEventListener('click', () => { _handleDoubleSwitch(page.elemAudience, 'right'); });
// share
page.elemLinkStudent.addEventListener('click', () => { _handleLink('student'); });
page.elemMessageStudent.addEventListener('click', () => { _handleMessage('student'); });
page.elemLinkMentor.addEventListener('click', () => { _handleLink('mentor'); });
page.elemMessageMentor.addEventListener('click', () => { _handleMessage('mentor'); });
}
//---------------------------------------
// updating
//----------------------------------------
async function _showContents(contentsId) {
settings.currentNavOption = contentsId;
var containers = page.contents.getElementsByClassName('contents-container');
for (var i = 0; i < containers.length; i++) {
var hide = !containers[i].classList.contains('contents-' + contentsId);
UtilityKTS.setClass(containers[i], settings.hideClass, hide);
}
if (contentsId == 'navPreview') await _updatePreview();
if (contentsId == 'navShare') _updateShare();
if (contentsId == 'navProfile') await settings.profile.reload();
_setNavOptions();
}
function _setNavOptions() {
var opt = settings.currentNavOption;
var validCourse = (settings.currentCourse != null);
_enableNavOption('navPreview', true, validCourse);
_enableNavOption('navShare', true, validCourse);
_enableNavOption('navRename', true, false);
_enableNavOption('dividerNav1', true, false);
_enableNavOption('navSave', false);
_enableNavOption('navReload', false);
if (opt == 'navConfiguration') {
_enableNavOption('navRename', true, validCourse);
_enableNavOption('dividerNav1', true, validCourse);
UtilityKTS.setClass(page.elemProjectDelete, 'disabled', !validCourse);
} else if (opt == 'navPreview') {
} else if (opt == 'navShare') {
} else if (opt == 'navProfile') {
var enable = settings.profile.isDirty();
_enableNavOption('navSave', true, enable);
_enableNavOption('navReload', true, enable);
}
}
function _enableNavOption(navOption, visible, enable) {
var elem = document.getElementById(navOption);
UtilityKTS.setClass(elem, settings.hideClass, !visible);
if (elem.classList.contains('btn')) {
elem.disabled = !enable;
} else {
UtilityKTS.setClass(elem, 'disabled', !enable);
}
}
function _setDirtyBit(dirty) {
var opt = settings.currentNavOption;
if (settings.dirtyBit.hasOwnProperty(opt)) {
settings.dirtyBit[settings.currentNavOption] = dirty;
}
_setNavOptions();
}
async function _updateCourseSelection() {
UtilityKTS.removeChildren(page.elemCourseSelection);
if (!(await _queryCourseList())) return;
var indexToSelect = -1;
for (var i = 0; i < settings.courseInfo.length; i++) {
var course = settings.courseInfo[i];
var elem = CreateElement.createOption(null, 'course', course.courseid, course.coursename);
elem.courseInfo = course;
if (settings.currentCourse && course.courseid == settings.currentCourse.courseid) indexToSelect = i;
page.elemCourseSelection.appendChild(elem);
}
page.elemCourseSelection.selectedIndex = indexToSelect;
var courseInfo = null;
if (indexToSelect >= 0) courseInfo = page.elemCourseSelection[indexToSelect].courseInfo;
_loadCourse(courseInfo);
}
function _loadCourse(courseInfo) {
settings.currentCourse = courseInfo;
var elemList = Array.prototype.slice.call(page.contentsConfiguration.getElementsByTagName('select'));
elemList = elemList.concat(Array.prototype.slice.call(page.contentsConfiguration.getElementsByTagName('input')));
elemList = elemList.concat(Array.prototype.slice.call(page.contentsConfiguration.getElementsByTagName('button')));
elemList = elemList.concat(Array.prototype.slice.call(page.contentsConfiguration.getElementsByTagName('label')));
for (var i = 0; i < elemList.length; i++) {
var elem = elemList[i];
if (elem.id != 'selectCourse' && elem.htmlFor != 'selectCourse') {
elem.disabled = !courseInfo;
UtilityKTS.setClass(elem, settings.hideClass, !courseInfo);
}
}
page.elemAPCourse.checked = courseInfo && courseInfo.ap;
page.elemHasPasswords.checked = courseInfo && courseInfo.haspasswords;
page.elemExamsSelection.value = courseInfo ? courseInfo.examid: -1;
page.elemProctoringSelection.value = courseInfo ? courseInfo.proctoringid: -1;
page.elemRetakesSelection.value = courseInfo ? courseInfo.retakeid: -1;
page.elemResubmissionSelect.value = courseInfo ? courseInfo.resubmissionid: -1;
_setDirtyBit(false);
}
async function _updatePreview() {
var audience = 'student';
if (page.elemAudience.checked) audience = 'mentor';
var previewURL = _landingPageURL(audience);
page.elemPreviewFrame.src = previewURL;
}
function _updateShare() {
_showShareCopyMessage('');
}
async function _saveCourseInfo() {
if (!settings.currentCourse) return;
var course = settings.currentCourse;
var configurationInfo = {
courseid: course.courseid,
coursename: course.coursename,
ap: page.elemAPCourse.checked,
haspasswords: page.elemHasPasswords.checked,
examid: page.elemExamsSelection.value,
proctoringid: page.elemProctoringSelection.value,
retakeid: page.elemRetakesSelection.value,
resubmissionid: page.elemResubmissionSelect.value,
};
var result = await _queryUpdateCourse(configurationInfo);
if (!result.success) {
if (result.details.includes('duplicate')) {
alert('failed to rename course\n a configuration for "' + course.coursename + '" already exists');
page.notice.setNotice('');
} else {
page.notice.setNotice(result.details);
}
}
await _updateCourseSelection();
}
async function _renameCourse() {
if (!settings.currentCourse) return;
var courseNameOrig = settings.currentCourse.coursename;
var msg = 'Please enter the new name for the course.';
var newCourseName = prompt(msg, courseNameOrig);
if (!newCourseName || newCourseName == courseNameOrig) return;
if (!_validateCourseName(newCourseName)) {
var msg = "The course name\n" + newCourseName + '\nis not valid.';
msg += '\n\nIt must have length between 1 and 200';
msg += ' and include only letters, digits, spaces, parentheses and commas.';
alert(msg);
return;
}
settings.currentCourse.coursename = newCourseName;
await _saveCourseInfo();
}
async function _addCourse(e) {
var msg = 'Enter the name of the new course';
var courseName = prompt(msg);
if (!courseName) return;
if (!_validateCourseName(courseName)) {
var msg = "The course name\n" + courseName + '\nis not valid.';
msg += '\n\nIt must have length between 1 and 200';
msg += ' and include only letters, digits, spaces, parentheses and commas.';
alert(msg);
return;
}
var result = await _queryInsertCourse({coursename: courseName});
if (result.success) {
settings.currentCourse = {courseid: result.data.courseid};
await _updateCourseSelection();
} else {
if (result.details.includes('duplicate')) {
alert('failed to add course\n A configuration for "' + courseName + '" already exists');
} else {
page.notice.setNotice(result.details);
}
}
}
async function _deleteCourse() {
if (!settings.currentCourse) return;
var msg = 'This course will be deleted:';
msg += '\n' + settings.currentCourse.coursename;
msg += '\n\nThis action cannot be undone. Continue with deletion?';
if (!confirm(msg)) return;
var result = await _queryDeleteCourse(settings.currentCourse);
if (!result.success) {
page.notice.setNotice(result.details);
return;
}
settings.currentCourse = null;
await _updateCourseSelection();
}
function _showShareCopyMessage(msg) {
page.contentsShare.getElementsByClassName('copy-message')[0].innerHTML = msg;
}
//---------------------------------------
// handlers
//----------------------------------------
async function _navDispatch(e) {
var dispatchTarget = e.target.id;
if (dispatchTarget == 'navProfilePic') dispatchTarget = 'navProfile';
if (dispatchTarget == settings.currentNavOption) return;
var dispatchMap = {
"navConfiguration": async function() { await _showContents('navConfiguration'); },
"navPreview": async function() { await _showContents('navPreview'); },
"navShare": async function() { await _showContents('navShare'); },
"navRename": async function() { await _renameCourse(); },
"navEditOptions": function() { _doOptions(); },
"navSave": async function() { await _handleSave(e);},
"navReload": async function() { await _handleReload(e);},
"navProfile": async function() { await _showContents('navProfile'); },
"navHelp": function() { _doHelp(); },
"navSignout": function() { _doLogout(); }
}
dispatchMap[dispatchTarget]();
}
function _handleCourseSelection(e) {
_loadCourse(e.target[e.target.selectedIndex].courseInfo);
}
async function _handleConfigChange(e) {
await _saveCourseInfo();
}
function _handleAudienceChange(e) {
UtilityKTS.setClass(e.target.leftLabel, 'diminished', e.target.checked);
UtilityKTS.setClass(e.target.rightLabel, 'diminished', !e.target.checked);
_updatePreview();
}
function _handleDoubleSwitch(elem, clickedLabel) {
if (clickedLabel == 'left' && elem.checked) {
elem.click();
} else if (clickedLabel == 'right' && !elem.checked) {
elem.click();
}
}
function _handleLink(audience) {
var msg = _landingPageURL(audience);
_copyToClipboard(msg);
_showShareCopyMessage(audience + ' link copied');
}
async function _handleMessage(audience) {
var msg = await _mailMessage(audience);
if (!msg) return;
//--- is this necessary? --------------------
// strip non-body material
msg = msg.replace(/<!DOCTYPE html>/g, '');
msg = msg.replace(/<html>/g, '');
msg = msg.replace(/<html lang=\"en\">/g, '');
msg = msg.replace(/<\/html>/g, '');
msg = msg.replace(/<head>.*<\/head>/g, '');
msg = msg.replace(/<body>/, '');
msg = msg.replace(/<\/body>/, '');
//-------------------------------------------
_copyRenderedToClipboard(msg);
_showShareCopyMessage(audience + ' link copied');
}
async function _handleSave(e) {
if (settings.currentNavOption == 'navProfile') {
settings.profile.save();
}
}
function _handleReload(e) {
if (!confirm('Current changes will be lost.\nContinue with reloading project?')) return;
if (settings.currentNavOption == 'navProfile') {
settings.profile.reload();
}
}
function _doOptions() {
window.open(settings.optionsURL, '_self');
}
function _doHelp() {
window.open(settings.helpURL, '_blank');
}
function _doLogout() {
window.open(settings.logoutURL, '_self');
}
//---------------------------------------
// DB interface
//----------------------------------------
async function _queryCourseList() {
var dbResult = await SQLDBInterface.doGetQuery('welcomeV2/query', 'courselist');
settings.courseInfo = null;
if (dbResult.success) {
settings.courseInfo = dbResult.data;
}
return dbResult.success;
}
async function _queryInsertCourse(courseInfo) {
return await SQLDBInterface.doPostQuery('welcomeV2/insert', 'course', courseInfo);
}
async function _queryUpdateCourse(configurationInfo) {
return await SQLDBInterface.doPostQuery('welcomeV2/update', 'course', configurationInfo);
}
async function _queryDeleteCourse(courseInfo) {
return await SQLDBInterface.doPostQuery('welcomeV2/delete', 'course', courseInfo);
}
async function _queryMailMessage(params) {
return await SQLDBInterface.doPostQuery('welcomeV2/query', 'mailmessage', params);
}
//---------------------------------------
// clipboard functions
//----------------------------------------
function _copyToClipboard(txt) {
if (!page._clipboard) page._clipboard = new ClipboardCopy(page.body, 'plain');
page._clipboard.copyToClipboard(txt);
}
function _copyRenderedToClipboard(txt) {
if (!page._renderedclipboard) page._renderedclipboard = new ClipboardCopy(page.body, 'rendered');
page._renderedclipboard.copyRenderedToClipboard(txt);
}
//---------------------------------------
// utility functions
//----------------------------------------
function _validateCourseName(courseName) {
var valid = courseName.length < 200;
valid = valid && courseName.length > 0;
valid = valid && (courseName.match(/[A-Za-z0-9&:\(\), ]+/) == courseName);
return valid;
}
function _landingPageURL(audience) {
var audienceIndex = '000';
if (audience == 'mentor') audienceIndex = '100';
var previewURL = window.location.origin + settings.previewURL_base;
previewURL += '/' + settings.currentCourse.courseid;
previewURL += '/' + audienceIndex;
return previewURL;
}
async function _mailMessage(audience) {
var result = null;
var params = settings.currentCourse;
params.audience = audience;
params.letterURL = _landingPageURL(audience);
var queryResult = await _queryMailMessage(params);
if (queryResult.success) {
result = queryResult.data;
} else {
page.notice.setNotice('failed to retrieve ' + audience + ' message');
}
return result;
}
//---------------------------------------
// return from wrapper function
//----------------------------------------
return {
init: init
};
}();
|
BuildJet/sat4envi | s4e-backend/src/main/java/pl/cyfronet/s4e/event/OnSendHelpRequestEvent.java | /*
* Copyright 2020 ACC Cyfronet AGH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package pl.cyfronet.s4e.event;
import lombok.Getter;
import org.springframework.context.ApplicationEvent;
import pl.cyfronet.s4e.controller.request.HelpType;
import java.util.Locale;
@Getter
public class OnSendHelpRequestEvent extends ApplicationEvent {
private final String requestingUserEmail;
private final String expertEmail;
private final HelpType helpType;
private final String issueDescription;
private final Locale locale;
public OnSendHelpRequestEvent(String requestingUserEmail, String expertEmail, HelpType helpType, String issueDescription, Locale locale) {
super(requestingUserEmail);
this.requestingUserEmail = requestingUserEmail;
this.expertEmail = expertEmail;
this.helpType = helpType;
this.issueDescription = issueDescription;
this.locale = locale;
}
}
|
kant/iDAAS-EventBuilder | src/main/java/io/connectedhealth_idaas/eventbuilder/pojos/edi/hipaa/E8.java | package io.connectedhealth_idaas.eventbuilder.pojos.edi.hipaa;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
public class E8 {
private String E8_01_BlockIdentifier;
private String E8_02_MovementAuthorityCode;
public String toString() { return ReflectionToStringBuilder.toString(this);}
}
|
nickbabcock/EECS381StyleCheck | clang-tools-extra/clang-tidy/modernize/UseEqualsDeleteCheck.cpp | <reponame>nickbabcock/EECS381StyleCheck
//===--- UseEqualsDeleteCheck.cpp - clang-tidy-----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "UseEqualsDeleteCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Lex/Lexer.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace modernize {
static const char SpecialFunction[] = "SpecialFunction";
static const char DeletedNotPublic[] = "DeletedNotPublic";
void UseEqualsDeleteCheck::registerMatchers(MatchFinder *Finder) {
if (!getLangOpts().CPlusPlus)
return;
auto PrivateSpecialFn = cxxMethodDecl(
isPrivate(),
anyOf(cxxConstructorDecl(anyOf(isDefaultConstructor(),
isCopyConstructor(), isMoveConstructor())),
cxxMethodDecl(
anyOf(isCopyAssignmentOperator(), isMoveAssignmentOperator())),
cxxDestructorDecl()));
Finder->addMatcher(
cxxMethodDecl(
PrivateSpecialFn,
unless(anyOf(hasBody(stmt()), isDefaulted(), isDeleted(),
ast_matchers::isTemplateInstantiation(),
// Ensure that all methods except private special member
// functions are defined.
hasParent(cxxRecordDecl(hasMethod(unless(
anyOf(PrivateSpecialFn, hasBody(stmt()), isPure(),
isDefaulted(), isDeleted()))))))))
.bind(SpecialFunction),
this);
Finder->addMatcher(
cxxMethodDecl(isDeleted(), unless(isPublic())).bind(DeletedNotPublic),
this);
}
void UseEqualsDeleteCheck::check(const MatchFinder::MatchResult &Result) {
if (const auto *Func =
Result.Nodes.getNodeAs<CXXMethodDecl>(SpecialFunction)) {
SourceLocation EndLoc = Lexer::getLocForEndOfToken(
Func->getEndLoc(), 0, *Result.SourceManager, getLangOpts());
// FIXME: Improve FixItHint to make the method public.
diag(Func->getLocation(),
"use '= delete' to prohibit calling of a special member function")
<< FixItHint::CreateInsertion(EndLoc, " = delete");
} else if (const auto *Func =
Result.Nodes.getNodeAs<CXXMethodDecl>(DeletedNotPublic)) {
// Ignore this warning in macros, since it's extremely noisy in code using
// DISALLOW_COPY_AND_ASSIGN-style macros and there's no easy way to
// automatically fix the warning when macros are in play.
if (Func->getLocation().isMacroID())
return;
// FIXME: Add FixItHint to make the method public.
diag(Func->getLocation(), "deleted member function should be public");
}
}
} // namespace modernize
} // namespace tidy
} // namespace clang
|
shaojiankui/iOS10-Runtime-Headers | protocols/MusicUpNextSectionHeaderDelegate.h | <reponame>shaojiankui/iOS10-Runtime-Headers
/* Generated by RuntimeBrowser.
*/
@protocol MusicUpNextSectionHeaderDelegate <NSObject>
@optional
- (void)addButtonPressedForSectionHeader:(MusicUpNextSectionHeaderView *)arg1;
- (void)clearButtonPressedForSectionHeader:(MusicUpNextSectionHeaderView *)arg1;
@end
|
KoJunHee/jeonju | node_modules/lab/lib/transform.js | <reponame>KoJunHee/jeonju
// Load modules
var Fs = require('fs');
// Declare internals
var internals = {
fileCache: {},
transforms: [{ ext: '.js', transform: null }]
};
internals.prime = function (extension) {
require.extensions[extension] = function (localModule, filename) {
var src = Fs.readFileSync(filename, 'utf8');
return localModule._compile(exports.transform(filename, src), filename);
};
};
exports.install = function (settings, primeFn) {
if (Array.isArray(settings.transform)) {
settings.transform.forEach(function (element) {
if (element.ext === '.js') {
internals.transforms[0].transform = element.transform;
}
else {
internals.transforms.push(element);
}
});
}
if (typeof primeFn !== 'function') {
primeFn = internals.prime;
}
internals.transforms.forEach(function (transform) {
primeFn(transform.ext);
});
};
exports.transform = function (filename, content) {
var ext = '';
var transform = null;
internals.transforms.forEach(function (element) {
ext = element.ext;
if (filename.indexOf(ext, filename.length - ext.length) !== -1) {
transform = element.transform;
}
});
var relativeFilename = filename.substr(process.cwd().length + 1);
internals.fileCache[relativeFilename] = (typeof transform === 'function') ? transform(content, relativeFilename) : content;
return internals.fileCache[relativeFilename];
};
exports.retrieveFile = function (path) {
var cwd = process.cwd();
var cacheKey = path.indexOf(cwd) === 0 ? path.substr(cwd.length + 1) : path;
if (internals.fileCache[cacheKey]) {
return internals.fileCache[cacheKey];
}
var contents = null;
try {
contents = Fs.readFileSync(path, 'utf8');
}
catch (e) {
contents = null;
}
internals.fileCache[path] = contents;
return contents;
};
|
bobmcwhirter/drools | drools-verifier/src/main/java/org/drools/verifier/components/FieldObjectTypeLink.java | <filename>drools-verifier/src/main/java/org/drools/verifier/components/FieldObjectTypeLink.java
package org.drools.verifier.components;
/**
*
* @author <NAME>
*/
public class FieldObjectTypeLink extends VerifierComponent {
private static int index = 0;
private int fieldId;
private int objectTypeId;
public FieldObjectTypeLink() {
super(index++);
}
@Override
public VerifierComponentType getComponentType() {
return VerifierComponentType.FIELD_CLASS_LINK;
}
public int getObjectTypeId() {
return objectTypeId;
}
public void setClassId(int classId) {
this.objectTypeId = classId;
}
public int getFieldId() {
return fieldId;
}
public void setFieldId(int fieldId) {
this.fieldId = fieldId;
}
}
|
nobu/ruby-1.0 | range.c | /************************************************
range.c -
$Author: matz $
$Date: 1996/12/25 09:30:12 $
created at: Thu Aug 19 17:46:47 JST 1993
Copyright (C) 1993-1996 <NAME>
************************************************/
#include "ruby.h"
VALUE mComparable;
static VALUE cRange;
extern VALUE cNumeric;
static ID upto;
static VALUE
range_s_new(class, first, last)
VALUE class, first, last;
{
VALUE obj;
if (!(FIXNUM_P(first) && FIXNUM_P(last))
&& (TYPE(first) != TYPE(last)
|| CLASS_OF(first) != CLASS_OF(last)
|| !rb_respond_to(first, upto))
&& !(obj_is_kind_of(first, cNumeric)
&& obj_is_kind_of(last, cNumeric))) {
ArgError("bad value for range");
}
obj = obj_alloc(class);
rb_iv_set(obj, "first", first);
rb_iv_set(obj, "last", last);
return obj;
}
VALUE
range_new(first, last)
VALUE first, last;
{
return range_s_new(cRange, first, last);
}
static VALUE
range_eqq(rng, obj)
VALUE rng, obj;
{
VALUE first, last;
first = rb_iv_get(rng, "first");
last = rb_iv_get(rng, "last");
if (FIXNUM_P(first) && FIXNUM_P(obj) && FIXNUM_P(last)) {
if (FIX2INT(first) <= FIX2INT(obj) && FIX2INT(obj) <= FIX2INT(last)) {
return TRUE;
}
return FALSE;
}
else {
if (RTEST(rb_funcall(first, rb_intern("<="), 1, obj)) &&
RTEST(rb_funcall(last, rb_intern(">="), 1, obj))) {
return TRUE;
}
return FALSE;
}
}
struct upto_data {
VALUE first;
VALUE last;
};
static VALUE
range_upto(data)
struct upto_data *data;
{
return rb_funcall(data->first, upto, 1, data->last);
}
static VALUE
range_each(obj)
VALUE obj;
{
VALUE b, e;
b = rb_iv_get(obj, "first");
e = rb_iv_get(obj, "last");
if (FIXNUM_P(b)) { /* fixnum is a special case(for performance) */
num_upto(b, e);
}
else {
struct upto_data data;
data.first = b;
data.last = e;
rb_iterate(range_upto, &data, rb_yield, 0);
}
return Qnil;
}
static VALUE
range_first(obj)
VALUE obj;
{
VALUE b;
b = rb_iv_get(obj, "first");
return b;
}
static VALUE
range_last(obj)
VALUE obj;
{
VALUE e;
e = rb_iv_get(obj, "last");
return e;
}
VALUE
range_beg_end(range, begp, endp)
VALUE range;
int *begp, *endp;
{
VALUE first, last;
if (!obj_is_kind_of(range, cRange)) return FALSE;
first = rb_iv_get(range, "first"); *begp = NUM2INT(first);
last = rb_iv_get(range, "last"); *endp = NUM2INT(last);
return TRUE;
}
static VALUE
range_to_s(range)
VALUE range;
{
VALUE str, str2;
str = obj_as_string(rb_iv_get(range, "first"));
str2 = obj_as_string(rb_iv_get(range, "last"));
str_cat(str, "..", 2);
str_cat(str, RSTRING(str2)->ptr, RSTRING(str2)->len);
return str;
}
static VALUE
range_inspect(range)
VALUE range;
{
VALUE str, str2;
str = rb_inspect(rb_iv_get(range, "first"));
str2 = rb_inspect(rb_iv_get(range, "last"));
str_cat(str, "..", 2);
str_cat(str, RSTRING(str2)->ptr, RSTRING(str2)->len);
return str;
}
static VALUE
range_length(rng)
VALUE rng;
{
VALUE first, last;
VALUE size;
first = rb_iv_get(rng, "first");
last = rb_iv_get(rng, "last");
if (!obj_is_kind_of(first, cNumeric)) {
return enum_length(rng);
}
size = rb_funcall(last, '-', 1, first);
size = rb_funcall(size, '+', 1, INT2FIX(1));
return size;
}
extern VALUE mEnumerable;
void
Init_Range()
{
cRange = rb_define_class("Range", cObject);
rb_include_module(cRange, mEnumerable);
rb_define_singleton_method(cRange, "new", range_s_new, 2);
rb_define_method(cRange, "===", range_eqq, 1);
rb_define_method(cRange, "each", range_each, 0);
rb_define_method(cRange, "first", range_first, 0);
rb_define_method(cRange, "last", range_last, 0);
rb_define_method(cRange, "to_s", range_to_s, 0);
rb_define_method(cRange, "inspect", range_inspect, 0);
rb_define_method(cRange, "length", range_length, 0);
rb_define_method(cRange, "size", range_length, 0);
upto = rb_intern("upto");
}
|
youyouqiu/hybrid-development | clbs/src/main/java/com/zw/ws/entity/t808/location/LocationAttachOilTank.java | <filename>clbs/src/main/java/com/zw/ws/entity/t808/location/LocationAttachOilTank.java
/**
* Copyright (c) 2016 ZhongWei, Inc. All rights reserved. This software is the confidential and proprietary information of ZhongWei, Inc.
* You shall not disclose such Confidential Information and shall use it only in accordance with the terms of the license agreement you
* entered into with ZhongWei.
*/
package com.zw.ws.entity.t808.location;
import lombok.Data;
import java.io.Serializable;
/**
*
* TODO 油位传感器详细数据
* <p>Title: LocationAttachOilTank.java</p>
* <p>Copyright: Copyright (c) 2016</p>
* <p>Company: ZhongWei</p>
* <p>team: ZhongWeiTeam</p>
* @author: wangying
* @date 2016年11月3日下午5:41:10
* @version 1.0
*/
@Data
public class LocationAttachOilTank implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private Integer len;
/**
* 液位高度AD值
*/
private String ADHeight;
/**
* 燃油温度
*/
private String oilTem;
/**
* 环境温度
*/
private String envTem;
/**
* 加油量
*/
private String add;
/**
* 漏油量
*/
private String del;
/**
* 油箱油量
*/
private String oilMass;
/**
* 液位百分比
*/
private String percentage;
/**
* 油位高度
*/
private String oilHeight;
}
|
SimbaService/Simba | server/simbastore/src/com/necla/simba/server/simbastore/cassandra/CassandraHandler.java | /*******************************************************************************
* Copyright 2015 <NAME>, <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.
*******************************************************************************/
package com.necla.simba.server.simbastore.cassandra;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.ByteBuffer;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.ColumnMetadata;
import com.datastax.driver.core.ConsistencyLevel;
import com.datastax.driver.core.ExecutionInfo;
import com.datastax.driver.core.Host;
import com.datastax.driver.core.KeyspaceMetadata;
import com.datastax.driver.core.Metadata;
import com.datastax.driver.core.Query;
import com.datastax.driver.core.QueryTrace;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.SimpleStatement;
import com.datastax.driver.core.TableMetadata;
import com.datastax.driver.core.exceptions.AlreadyExistsException;
import com.datastax.driver.core.exceptions.NoHostAvailableException;
import com.datastax.driver.core.exceptions.QueryExecutionException;
import com.datastax.driver.core.exceptions.QueryTimeoutException;
import com.datastax.driver.core.exceptions.QueryValidationException;
import com.datastax.driver.core.exceptions.SyntaxError;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.necla.simba.protocol.Common.Column;
import com.necla.simba.protocol.Common.ColumnData;
import com.necla.simba.protocol.Common.SimbaConsistency;
import com.necla.simba.server.simbastore.stats.IOStats;
public class CassandraHandler {
private static final Logger LOG = LoggerFactory
.getLogger(CassandraHandler.class);
private static String seed;
private static String keyspaceName;
private Cluster cluster;
private Session session;
private Properties properties;
public static final String VERSION = "version";
public static final String DELETED = "deleted";
public static final String KEY = "key";
private static final Set<String> meta;
static {
meta = new HashSet<String>();
String[] fields = { VERSION, DELETED, KEY };
for (String f : fields)
meta.add(f);
}
// Cassandra accepts Integer timestamps.
// We can use a local timestamp (technically, a counter) since any
// SimbaTable table belongs to a single SimbaStore node.
private Long counter = System.currentTimeMillis();
private static PrintWriter out;
static String[] excluded = { "system", "system_auth", "system_traces" };
static List<String> exclusions = Arrays.asList(excluded);
private Column.Type toSimbaType(String casType) {
if (casType.equals("text"))
return Column.Type.VARCHAR;
else if (casType.equals("int"))
return Column.Type.INT;
else if (casType.equals("list<uuid>"))
return Column.Type.OBJECT;
else if (casType.equals("uuid"))
return Column.Type.UUID;
else if (casType.equals("boolean"))
return Column.Type.BOOLEAN;
else if (casType.equals("bigint"))
return Column.Type.BIGINT;
else if (casType.equals("blob"))
return Column.Type.BLOB;
else if (casType.equals("double"))
return Column.Type.DOUBLE;
else if (casType.equals("float"))
return Column.Type.FLOAT;
else if (casType.equals("counter"))
return Column.Type.COUNTER;
else if (casType.equals("timestamp"))
return Column.Type.TIMESTAMP;
else if (casType.equals("varint"))
return Column.Type.VARINT;
else if (casType.equals("inet"))
return Column.Type.INET;
throw new RuntimeException("Unsupported type " + casType);
}
private String toCasType(Column.Type simbaType) {
switch (simbaType.getNumber()) {
case Column.Type.VARCHAR_VALUE:
return "text";
case Column.Type.INT_VALUE:
return "int";
case Column.Type.OBJECT_VALUE:
return "list<uuid>";
case Column.Type.UUID_VALUE:
return "uuid";
case Column.Type.BIGINT_VALUE:
return "bigint";
case Column.Type.BOOLEAN_VALUE:
return "boolean";
case Column.Type.BLOB_VALUE:
return "blob";
case Column.Type.DOUBLE_VALUE:
return "double";
case Column.Type.FLOAT_VALUE:
return "float";
case Column.Type.COUNTER_VALUE:
return "counter";
case Column.Type.TIMESTAMP_VALUE:
return "timestamp";
case Column.Type.VARINT_VALUE:
return "varint";
case Column.Type.INET_VALUE:
return "inet";
default:
throw new RuntimeException("Unsupported type " + simbaType);
}
}
public CassandraHandler(Properties props) {
this.properties = props;
seed = props.getProperty("cassandra.seed");
keyspaceName = props.getProperty("cassandra.keyspace");
LOG.info("Started CassandraHandler: seed: " + seed
+ " default keyspace: " + keyspaceName);
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(
"cassandra.log")));
} catch (IOException e) {
e.printStackTrace();
}
// flush the print buffer every N seconds (N = 30)
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
// LOG.debug("Flushing print buffer...");
out.flush();
}
}, 0, 10000);
connect();
}
public void connect() {
cluster = new Cluster.Builder().addContactPoint(seed).build();
// final int core_threads = 1;
// final int max_threads = 4;
//
// PoolingOptions p = cluster.getConfiguration().getPoolingOptions();
// p.setMaxConnectionsPerHost(HostDistance.LOCAL, max_threads);
// p.setCoreConnectionsPerHost(HostDistance.LOCAL, core_threads);
// SocketOptions so = cluster.getConfiguration().getSocketOptions();
// so.setTcpNoDelay(true).setReuseAddress(true).setKeepAlive(true);
Metadata metadata = cluster.getMetadata();
System.out.printf("Connected to cluster: %s\n",
metadata.getClusterName());
for (Host host : metadata.getAllHosts()) {
System.out.printf("Datacenter: %s; Host: %s; Rack: %s\n",
host.getDatacenter(), host.getAddress(), host.getRack());
}
session = cluster.connect();
// restoreTables(cluster);
}
private ResultSet executeQuery(String statement) {
ResultSet result = null;
try {
result = session.execute(statement);
} catch (AlreadyExistsException e) {
System.out.println("Keyspace or table already exists");
} catch (NoHostAvailableException e) {
System.out
.printf("No host in the %s cluster can be contacted to execute the query.\n",
session.getCluster());
e.printStackTrace();
} catch (QueryTimeoutException e) {
System.out
.println("An exception has been thrown by Cassandra because the query execution has timed out.");
e.printStackTrace();
} catch (QueryExecutionException e) {
System.out
.println("An exception was thrown by Cassandra because it cannot "
+ "successfully execute the query with the specified consistency level.");
e.printStackTrace();
} catch (SyntaxError e) {
System.out.printf(
"The query '%s' has a syntax error.\n message=%s",
statement, e.getMessage());
e.printStackTrace();
} catch (QueryValidationException e) {
System.out
.printf("The query '%s' is not valid, for example, incorrect syntax.\n",
statement);
e.printStackTrace();
} catch (IllegalStateException e) {
System.out.println("The BoundStatement is not ready.");
e.printStackTrace();
}
return result;
}
private ResultSet executeQuery(Query query) {
ResultSet result = null;
try {
result = session.execute(query);
} catch (AlreadyExistsException e) {
System.out.println("Keyspace or table already exists");
} catch (NoHostAvailableException e) {
System.out
.printf("No host in the %s cluster can be contacted to execute the query.\n",
session.getCluster());
} catch (QueryExecutionException e) {
System.out
.println("An exception was thrown by Cassandra because it cannot "
+ "successfully execute the query with the specified consistency level.");
} catch (QueryValidationException e) {
System.out
.printf("The query \n%s \nis not valid, for example, incorrect syntax.\n",
query.toString());
} catch (IllegalStateException e) {
System.out.println("The BoundStatement is not ready.");
}
return result;
}
public int getVersion(String keyspace, String table, ConsistencyLevel level) {
int version = -1;
// Build SELECT query
Query query = QueryBuilder.select(VERSION)
.from((keyspace == null) ? keyspaceName : keyspace, table)
.setConsistencyLevel(level);
ResultSet result = executeQuery(query);
if (result.isExhausted()) {
return -1;
}
for (Row row : result) {
int tmp = row.getInt(VERSION);
if (version < tmp) {
version = tmp;
}
}
return version;
}
public void createKeyspace(String keyspaceName, Integer replication) {
try {
session.execute("CREATE KEYSPACE " + keyspaceName
+ " WITH replication " + "= {'class':'SimpleStrategy', "
+ "'replication_factor':" + replication.toString() + "};");
} catch (AlreadyExistsException e) {
System.out.println("Keyspace " + keyspaceName
+ " already exists -- ignoring!");
}
}
public List<Column> getSchema(String keySpace, String tableName) {
Metadata m = session.getCluster().getMetadata();
KeyspaceMetadata km = m.getKeyspace(keySpace);
if (km == null)
return null;
TableMetadata tm = km.getTable(tableName);
if (tm == null)
return null;
// build schema
List<Column> columns = new LinkedList<Column>();
for (ColumnMetadata cm : tm.getColumns()) {
if (!meta.contains(cm.getName()))
columns.add(Column.newBuilder().setName(cm.getName())
.setType(toSimbaType(cm.getType().toString())).build());
}
return columns;
}
public void createTable(String keyspace, String tableName, List<Column> list) {
// Create table
StringBuilder command = new StringBuilder();
command.append("CREATE TABLE ")
.append((keyspace == null) ? keyspaceName : keyspace)
.append(".").append(tableName).append(" (").append(KEY)
.append(" text PRIMARY KEY, ").append(VERSION).append(" int, ")
.append(DELETED).append(" boolean, ");
Column pair = list.get(0);
command.append(pair.getName()).append(" ")
.append(toCasType(pair.getType()));
for (int i = 1; i < list.size(); i++) {
pair = list.get(i);
command.append(", ").append(pair.getName()).append(" ")
.append(toCasType(pair.getType()));
}
command.append(");");
executeQuery(command.toString());
// add some delay (in seconds) to hopefully avoid issue where index is
// not created successfully.
// int delay = 5;
// try {
// Thread.sleep(delay * 1000);
// } catch (InterruptedException e){
// e.printStackTrace();
// }
// Create secondary index on version
command = new StringBuilder();
command.append("CREATE INDEX ON ")
.append((keyspace == null) ? keyspaceName : keyspace)
.append(".").append(tableName).append(" (").append(VERSION)
.append(");");
LOG.debug(command.toString());
executeQuery(command.toString());
}
public void putRow(String keyspace, String tableName, String rowKey,
Integer version, List<ColumnData> values, ConsistencyLevel level) {
Long start = System.nanoTime();
LOG.debug("PUT ROW START\n");
StringBuilder command = new StringBuilder();
StringBuilder vals = new StringBuilder();
command.append("INSERT INTO ")
.append((keyspace == null) ? keyspaceName : keyspace)
.append(".").append(tableName).append(" (").append(KEY)
.append(",").append(VERSION).append(",").append(DELETED)
.append(",");
ColumnData pair = values.get(0);
command.append(pair.getColumn());
vals.append(pair.getValue());
for (int i = 1; i < values.size(); i++) {
pair = values.get(i);
command.append(",").append(pair.getColumn());
vals.append(",").append(pair.getValue());
}
command.append(") VALUES (").append("'" + rowKey + "',")
.append(version + ",").append("false,").append(vals.toString())
.append(") USING TIMESTAMP ").append(++this.counter)
.append(";");
SimpleStatement ss = new SimpleStatement(command.toString());
ss.setConsistencyLevel(level);
LOG.debug(ss.toString());
executeQuery(ss);
LOG.debug("PUT ROW END\n\n");
IOStats.putRow(((double) System.nanoTime() - (double) start) / 1000000);
}
public void putSubscription(String keyspace, String tableName,
String rowKey, ByteBuffer subscription, ConsistencyLevel level) {
Query query = QueryBuilder.update(keyspace, tableName)
.with(QueryBuilder.append("subscriptions", subscription))
.where(QueryBuilder.eq(KEY, UUID.fromString(rowKey)))
.setConsistencyLevel(level);
session.execute(query);
}
public void setTableConsistencyLevel(String rowKey,
SimbaConsistency.Type consistencyLevel) {
Query query = QueryBuilder.insertInto("simbastore", "metadata")
.value(KEY, rowKey).value("consistency", consistencyLevel)
.setConsistencyLevel(ConsistencyLevel.ALL);
session.execute(query);
}
public void putRowWithTracing(String keyspace, String tableName,
String rowKey, Integer version, List<ColumnData> values,
ConsistencyLevel level) {
StringBuilder command = new StringBuilder();
StringBuilder vals = new StringBuilder();
command.append("INSERT INTO ")
.append((keyspace == null) ? keyspaceName : keyspace)
.append(".").append(tableName).append(" (").append(KEY)
.append(",").append(VERSION).append(",").append(DELETED)
.append(",");
ColumnData pair = values.get(0);
command.append(pair.getColumn());
vals.append(pair.getValue());
for (int i = 1; i < values.size(); i++) {
pair = values.get(i);
command.append(",").append(pair.getColumn());
vals.append(",").append(pair.getValue());
}
command.append(") VALUES (").append("'" + rowKey + "',")
.append(version + ",").append("false,").append(vals.toString())
.append(");");
LOG.debug(command.toString());
SimpleStatement ss = new SimpleStatement(command.toString());
Query insert = QueryBuilder.batch(ss).setConsistencyLevel(level)
.enableTracing();
ResultSet results = session.execute(insert);
ExecutionInfo executionInfo = results.getExecutionInfo();
System.out.printf("Host (queried): %s\n", executionInfo
.getQueriedHost().toString());
for (Host host : executionInfo.getTriedHosts()) {
System.out.printf("Host (tried): %s\n", host.toString());
}
QueryTrace queryTrace = executionInfo.getQueryTrace();
System.out.printf("Trace id: %s\n\n", queryTrace.getTraceId());
System.out.printf("%-38s | %-12s | %-10s | %-12s\n", "activity",
"timestamp", "source", "source_elapsed");
System.out
.println("---------------------------------------+--------------+------------+--------------");
for (QueryTrace.Event event : queryTrace.getEvents()) {
System.out.printf("%38s | %12s | %10s | %12s\n",
event.getDescription(), new Date(event.getTimestamp()),
event.getSource(), event.getSourceElapsedMicros());
}
insert.disableTracing();
}
public ResultSet getRowWithTracing(String keyspace, String table,
String key, ConsistencyLevel level) {
Query select = QueryBuilder.select().all().from(keyspace, table)
.where(QueryBuilder.eq(KEY, key)).setConsistencyLevel(level)
.enableTracing();
ResultSet results = session.execute(select);
ExecutionInfo executionInfo = results.getExecutionInfo();
System.out.printf("Host (queried): %s\n", executionInfo
.getQueriedHost().toString());
for (Host host : executionInfo.getTriedHosts()) {
System.out.printf("Host (tried): %s\n", host.toString());
}
QueryTrace queryTrace = executionInfo.getQueryTrace();
System.out.printf("Trace id: %s\n\n", queryTrace.getTraceId());
System.out.printf("%-38s | %-12s | %-10s | %-12s\n", "activity",
"timestamp", "source", "source_elapsed");
System.out
.println("---------------------------------------+--------------+------------+--------------");
for (QueryTrace.Event event : queryTrace.getEvents()) {
System.out.printf("%38s | %12s | %10s | %12s\n",
event.getDescription(), new Date(event.getTimestamp()),
event.getSource(), event.getSourceElapsedMicros());
}
select.disableTracing();
return results;
}
public ResultSet getRow(String keyspace, String table, String key,
ConsistencyLevel level) {
Long start = System.nanoTime();
// LOG.debug("GET ROW START\n");
Query query = QueryBuilder.select().all().from(keyspace, table)
.where(QueryBuilder.eq(KEY, key)).setConsistencyLevel(level);
LOG.debug(query.toString());
ResultSet result = executeQuery(query);
IOStats.getRow(((double) System.nanoTime() - (double) start) / 1000000);
return result;
}
public ResultSet getRows(String keyspace, String table, int limit,
String startKey, ConsistencyLevel level) {
StringBuilder command = new StringBuilder();
command.append("SELECT * from ").append(keyspace).append(".")
.append(table);
if (startKey != null) {
command.append(" WHERE token(key)>token('").append(startKey)
.append("')");
}
if (limit > 0) {
command.append(" LIMIT ").append(Integer.toString(limit));
}
command.append(";");
SimpleStatement ss = new SimpleStatement(command.toString());
ss.setConsistencyLevel(level);
ResultSet result = executeQuery(ss);
return result;
}
public ResultSet getSubscriptions(String deviceId, ConsistencyLevel level) {
LOG.debug("GET SUBSCRIPTIONS START\n");
StringBuilder command = new StringBuilder();
command.append("SELECT * FROM simbastore.subscriptions WHERE ")
.append(KEY).append(" = ").append(deviceId).append(";");
SimpleStatement ss = new SimpleStatement(command.toString());
ss.setConsistencyLevel(level);
ResultSet result = executeQuery(ss);
LOG.debug("GET SUBSCRIPTIONS END\n\n");
return result;
}
public ResultSet getTableConsistencyLevel(String rowKey) {
Query query = QueryBuilder.select().all()
.from("simbastore", "metadata")
.where(QueryBuilder.eq(KEY, rowKey))
.setConsistencyLevel(ConsistencyLevel.ONE);
ResultSet result = executeQuery(query);
return result;
}
public ResultSet getColumnFromRow(String keyspace, String tableName,
String key, String column, ConsistencyLevel level) {
StringBuilder command = new StringBuilder();
// Build SELECT query
command.append("SELECT ").append(column).append(" FROM ")
.append((keyspace == null) ? keyspaceName : keyspace)
.append(".").append(tableName).append(" WHERE ").append(KEY)
.append(" = '").append(key).append("';");
SimpleStatement ss = new SimpleStatement(command.toString());
ss.setConsistencyLevel(level);
ResultSet result = executeQuery(ss);
return result;
}
public ResultSet getColumnsFromRow(String keyspace, String tableName,
String key, ArrayList<String> columns, ConsistencyLevel level) {
StringBuilder command = new StringBuilder();
StringBuilder cols = new StringBuilder();
// Build column list
cols.append(columns.get(0));
for (int i = 1; i < columns.size(); i++) {
cols.append(",").append(columns.get(i));
}
// Build SELECT query
command.append("SELECT ").append(cols.toString()).append(" FROM ")
.append((keyspace == null) ? keyspaceName : keyspace)
.append(".").append(tableName).append(" WHERE ").append(KEY)
.append(" = '").append(key).append("';");
SimpleStatement ss = new SimpleStatement(command.toString());
ss.setConsistencyLevel(level);
ResultSet result = executeQuery(ss);
return result;
}
public ResultSet getRowByVersion(String keyspace, String tableName,
int version, ConsistencyLevel level) {
Long start = System.nanoTime();
StringBuilder command = new StringBuilder();
command.append("SELECT * FROM ")
.append((keyspace == null) ? keyspaceName : keyspace)
.append(".").append(tableName).append(" WHERE ")
.append(VERSION).append(" = ").append(version).append(";");
SimpleStatement ss = new SimpleStatement(command.toString());
ss.setConsistencyLevel(level);
ResultSet result = executeQuery(ss);
IOStats.getRowByVersion(((double) System.nanoTime() - (double) start) / 1000000);
return result;
}
public void markDeleted(String keyspace, String tableName, String key,
int version, ConsistencyLevel level) {
Long start = System.nanoTime();
StringBuilder command = new StringBuilder();
command.append("UPDATE ")
.append((keyspace == null) ? keyspaceName : keyspace)
.append(".").append(tableName).append(" USING TIMESTAMP ")
.append(++this.counter).append(" SET ").append(DELETED)
.append(" = true,").append(VERSION).append(" = ")
.append(version).append(" WHERE ").append(KEY).append(" = '")
.append(key).append("';");
SimpleStatement ss = new SimpleStatement(command.toString());
ss.setConsistencyLevel(level);
executeQuery(ss);
IOStats.markDelRow(((double) System.nanoTime() - (double) start) / 1000000);
}
public void deleteColumnFromRow(String keyspace, String tableName,
String key, String column, ConsistencyLevel level) {
StringBuilder command = new StringBuilder();
command.append("DELETE ").append(column).append(" FROM ")
.append((keyspace == null) ? keyspaceName : keyspace)
.append(".").append(tableName).append(" WHERE ").append(KEY)
.append(" = '").append(key).append("';");
SimpleStatement ss = new SimpleStatement(command.toString());
ss.setConsistencyLevel(level);
executeQuery(ss);
}
public void deleteColumnsFromRow(String keyspace, String tableName,
String key, List<String> columns, ConsistencyLevel level) {
StringBuilder command = new StringBuilder();
command.append("DELETE ");
String col = columns.get(0);
command.append(col);
for (int i = 1; i < columns.size(); i++) {
col = columns.get(i);
command.append(",").append(col);
}
command.append(" FROM ")
.append((keyspace == null) ? keyspaceName : keyspace)
.append(".").append(tableName).append(" WHERE ").append(KEY)
.append(" = '").append(key).append("';");
SimpleStatement ss = new SimpleStatement(command.toString());
ss.setConsistencyLevel(level);
executeQuery(ss);
}
public void deleteRow(String keyspace, String tableName, String key,
ConsistencyLevel level) {
Long start = System.nanoTime();
StringBuilder command = new StringBuilder();
command.append("DELETE FROM ")
.append((keyspace == null) ? keyspaceName : keyspace)
.append(".").append(tableName).append(" WHERE ").append(KEY)
.append(" = '").append(key).append("';");
SimpleStatement ss = new SimpleStatement(command.toString());
ss.setConsistencyLevel(level);
executeQuery(ss);
IOStats.delRow(((double) System.nanoTime() - (double) start) / 1000000);
}
public void dropTable(String id) {
executeQuery("DROP TABLE " + id + ";");
}
public void shutdown() {
cluster.shutdown();
}
public static void getRowsTest(String keyspace, String table,
int start_row, int end_row) {
Properties properties = new Properties();
try {
properties.load(CassandraHandler.class
.getResourceAsStream("/simbastore.properties"));
} catch (IOException e) {
System.err.println("Could not load properties: " + e.getMessage());
System.exit(1);
}
CassandraHandler ch = new CassandraHandler(properties);
LOG.info("connect");
for (int i = start_row; i <= end_row; i++) {
long start = System.nanoTime();
ResultSet resultSet = ch.getRow(keyspace, table, "row" + i,
ConsistencyLevel.ONE);
System.out.println(resultSet.one().getString(KEY));
Double elapsed = ((double) System.nanoTime() - (double) start) / 1000000;
out.println("GET row" + i + " " + elapsed.toString());
}
ch.shutdown();
LOG.info("shutdown");
out.flush();
System.exit(0);
}
public static void putRowsTest(String keyspace, String table,
int start_row, int end_row) {
Properties properties = new Properties();
try {
properties.load(CassandraHandler.class
.getResourceAsStream("/simbastore.properties"));
} catch (IOException e) {
System.err.println("Could not load properties: " + e.getMessage());
System.exit(1);
}
CassandraHandler ch = new CassandraHandler(properties);
LOG.info("connect");
List<Column> columns = new LinkedList<Column>();
for (int i = 0; i < 10; i++) {
columns.add(Column.newBuilder().setName("col" + i)
.setType(Column.Type.VARCHAR).build());
}
ch.createTable(keyspace, table, columns);
for (int i = start_row; i <= end_row; i++) {
List<ColumnData> values = new LinkedList<ColumnData>();
for (int j = 0; j < 10; ++j) {
values.add(ColumnData.newBuilder().setColumn("col" + j)
.setValue("'" + randomString(50) + "'").build());
}
ch.putRow(keyspace, table, "row" + i, i, values,
ConsistencyLevel.ALL);
}
ch.shutdown();
LOG.info("shutdown");
System.exit(0);
}
static final String AB = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
static Random rnd = new Random();
public static String randomString(int len) {
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++)
sb.append(AB.charAt(rnd.nextInt(AB.length())));
return sb.toString();
}
/*
* testing
*/
public static void main(String[] args) {
if (args[0].equals("get")) {
getRowsTest(args[1], args[2], Integer.parseInt(args[3]),
Integer.parseInt(args[4]));
} else if (args[0].equals("put")) {
putRowsTest(args[1], args[2], Integer.parseInt(args[3]),
Integer.parseInt(args[4]));
}
}
}
|
whirvis/you-have-uno | game/game-client/src/main/java/csci4490/uno/client/state/HomeState.java | package csci4490.uno.client.state;
import csci4490.uno.client.UnoGame;
import csci4490.uno.client.UnoGameState;
import csci4490.uno.client.gui.HomePanel;
import csci4490.uno.dealer.UnoAccount;
import csci4490.uno.dealer.UnoLogin;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
public class HomeState extends UnoGameState<HomePanel> {
public HomeState(@NotNull UnoGame game) {
super(game, "Home", new HomePanel());
}
@Override
protected void initState() {
panel.loginButton.addActionListener((event -> {
game.enterState(game.loginStateId);
}));
panel.createAccountButton.addActionListener(event -> {
game.enterState(game.createAccountStateId);
});
panel.playButton.addActionListener(event -> {
game.enterState(game.gameOptionsId);
});
}
@Override
protected void update(long delta) {
UnoLogin login = game.getLogin();
if(game.isVerifyingLogin()) {
panel.currentAccountLabel.setText("Logging in...");
} else if(login == null) {
panel.currentAccountLabel.setText("Not logged in");
} else {
UnoAccount account = login.getAccount();
String text = "Logged in as: " + account.getUsername();
panel.currentAccountLabel.setText(text);
}
}
}
|
jefernathan/Python | ex061.py | # Refaça o DESAFIO 051, lendo o primeiro termo e a razão de uma PA, mostrando os 10 primeiros termos da progressão usando a estrutura while.
termo = int(input('Primeiro termo: '))
razao = int(input('Razão: '))
contador = 0
while contador < 10:
print(termo, end=' ➔ ')
termo += razao
contador += 1
print('FIM')
|
alofrrr/C | somaValoresNaColuna11.c | <reponame>alofrrr/C
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
int main()
{
setlocale(LC_ALL, "Portuguese");
srand(time(NULL));
int m[30][11], i, j;
printf("\t\tMatriz\n");
for(i=0; i<30; i++){
for(j=0; j<11; j++){
m[i][j] = (rand()%10);}}
for(i=0; i<30; i++){
m[i][10] = 0;}
printf("\nSoma dos valores aleatórios da linha na coluna 11:\n\n");
for(i=0; i<30; i++){
m[i][10] = m[i][0] + m[i][1] + m[i][2] + m[i][3] + m[i][4] + m[i][5] + m[i][6]
+ m[i][7] + m[i][8] + m[i][9];}
for(i=0; i<30; i++){
for(j=0; j<11; j++){
printf("[%d]", m[i][j]);}
printf("\n");}
return 0;
} |
weihsiu/scala-dom-types | shared/src/main/scala/com/raquo/domtypes/generic/codecs/package.scala | <reponame>weihsiu/scala-dom-types
package com.raquo.domtypes.generic
package object codecs {
// @TODO[Performance] Which of those methods could benefit from @inline annotation? We typically use those values typed as just `Codec`
// String Codecs
object StringAsIsCodec extends AsIsCodec[String]
// Int Codecs
object IntAsIsCodec extends AsIsCodec[Int]
object IntAsStringCodec extends Codec[Int, String] {
override def decode(domValue: String): Int = domValue.toInt // @TODO this can throw exception. How do we handle this?
override def encode(scalaValue: Int): String = scalaValue.toString
}
// Double Codecs
object DoubleAsIsCodec extends AsIsCodec[Double]
object DoubleAsStringCodec extends Codec[Double, String] {
override def decode(domValue: String): Double = domValue.toDouble// @TODO this can throw exception. How do we handle this?
override def encode(scalaValue: Double): String = scalaValue.toString
}
// Boolean Codecs
object BooleanAsIsCodec extends AsIsCodec[Boolean]
object BooleanAsAttrPresenceCodec extends Codec[Boolean, String] {
override def decode(domValue: String): Boolean = domValue != null
override def encode(scalaValue: Boolean): String = if (scalaValue) "" else null
}
object BooleanAsTrueFalseStringCodec extends Codec[Boolean, String] {
override def decode(domValue: String): Boolean = domValue == "true"
override def encode(scalaValue: Boolean): String = if (scalaValue) "true" else "false"
}
object BooleanAsYesNoStringCodec extends Codec[Boolean, String] {
override def decode(domValue: String): Boolean = domValue == "yes"
override def encode(scalaValue: Boolean): String = if (scalaValue) "yes" else "no"
}
object BooleanAsOnOffStringCodec extends Codec[Boolean, String] {
override def decode(domValue: String): Boolean = domValue == "on"
override def encode(scalaValue: Boolean): String = if (scalaValue) "on" else "off"
}
// Iterable Codecs
object IterableAsSpaceSeparatedStringCodec extends Codec[Iterable[String], String] { // use for e.g. className
override def decode(domValue: String): Iterable[String] = if (domValue == "") Nil else domValue.split(' ')
override def encode(scalaValue: Iterable[String]): String = scalaValue.mkString(" ")
}
object IterableAsCommaSeparatedStringCodec extends Codec[Iterable[String], String] { // use for lists of IDs
override def decode(domValue: String): Iterable[String] = if (domValue == "") Nil else domValue.split(',')
override def encode(scalaValue: Iterable[String]): String = scalaValue.mkString(",")
}
}
|
shawven/security | security-verification/src/main/java/com/github/shawven/security/verification/captcha/CaptchaProcessor.java |
package com.github.shawven.security.verification.captcha;
import com.github.shawven.security.verification.*;
import com.github.shawven.security.verification.repository.VerificationRepositoryFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 图片验证码处理器
*/
public class CaptchaProcessor extends AbstractVerificationProcessor<Captcha> {
private static final Logger logger = LoggerFactory.getLogger(CaptchaProcessor.class);
public CaptchaProcessor(VerificationRepositoryFactory repositoryFactory,
VerificationGenerator<Captcha> verificationGenerator) {
super(repositoryFactory, verificationGenerator);
}
/**
* 发送图形验证码,将其写到响应中
* @param captchaRequest
* @param captcha
*/
@Override
protected void send(VerificationRequest<Captcha> captchaRequest, Captcha captcha) {
try {
HttpServletResponse response = captchaRequest.getResponse();
response.setHeader(VerificationConstants.REQUEST_ID, captchaRequest.getRequestId());
ImageIO.write(captcha.getImage(), "JPEG", response.getOutputStream());
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}
|
gtorvald/gauge3panel | node_modules/@iconscout/react-unicons/icons/uil-stopwatch-slash.js | <gh_stars>100-1000
import React from 'react';
import PropTypes from 'prop-types';
const UilStopwatchSlash = (props) => {
const { color, size, ...otherProps } = props
return React.createElement('svg', {
xmlns: 'http://www.w3.org/2000/svg',
width: size,
height: size,
viewBox: '0 0 24 24',
fill: color,
...otherProps
}, React.createElement('path', {
d: 'M10.6,5.63a1,1,0,0,0,.36,2,6.18,6.18,0,0,1,1-.09,6,6,0,0,1,6,6,6.18,6.18,0,0,1-.09,1,1,1,0,0,0,.8,1.16l.18,0a1,1,0,0,0,1-.82A7.45,7.45,0,0,0,20,13.5a8,8,0,0,0-1.7-4.91l.91-.9a1,1,0,0,0-1.42-1.42l-.9.91A8,8,0,0,0,12,5.5,7.45,7.45,0,0,0,10.6,5.63ZM10,4.5h4a1,1,0,0,0,0-2H10a1,1,0,0,0,0,2Zm3.49,9.08s0-.05,0-.08,0-.05,0-.08l1.34-1.33a1,1,0,1,0-1.42-1.42L12.08,12h-.16L5.71,5.79A1,1,0,0,0,4.29,7.21l.48.48h0l.91.91A8,8,0,0,0,16.9,19.82l1.39,1.39a1,1,0,0,0,1.42,0,1,1,0,0,0,0-1.42ZM12,19.5A6,6,0,0,1,7.11,10l3.4,3.39s0,.05,0,.08A1.5,1.5,0,0,0,12,15h.08l3.39,3.4A6,6,0,0,1,12,19.5Z'
}));
};
UilStopwatchSlash.propTypes = {
color: PropTypes.string,
size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
};
UilStopwatchSlash.defaultProps = {
color: 'currentColor',
size: '24',
};
export default UilStopwatchSlash; |
seemoo-lab/polypyus_pdom | export/model/org/eclipse/cdt/core/settings/model/ICExclusionPatternPathEntry.java | <reponame>seemoo-lab/polypyus_pdom<gh_stars>0
/*******************************************************************************
* Copyright (c) 2005, 2007 Intel Corporation
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Intel Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.core.settings.model;
import org.eclipse.core.runtime.IPath;
public interface ICExclusionPatternPathEntry extends ICPathEntry {
/**
* Returns an array of inclusion paths affecting the
* source folder when looking for files recursively.
* @return IPath
*/
IPath[] getExclusionPatterns();
/**
* Returns a char based representation of the exclusions patterns full path.
*/
public char[][] fullExclusionPatternChars();
}
|
jugglinmike/nanoc | lib/nanoc/cli/commands/watch.rb | <gh_stars>0
# encoding: utf-8
usage 'watch [options]'
summary 'start the watcher'
description <<-EOS
Start the watcher. When a change is detected, the site will be recompiled.
EOS
module Nanoc::CLI::Commands
class Watch < ::Nanoc::CLI::CommandRunner
def run
require 'listen'
require 'pathname'
require_site
watcher_config = self.site.config[:watcher] || {}
@notifier = Notifier.new
# Define rebuilder
rebuilder = lambda do |file_path|
# Determine filename
if file_path.nil?
filename = nil
else
filename = ::Pathname.new(file_path).relative_path_from(::Pathname.new(Dir.getwd)).to_s
end
# Notify
if filename
print "Change detected to #{filename}; recompiling… "
else
print "Watcher started; compiling the entire site… "
end
# Recompile
start = Time.now
site = Nanoc::Site.new('.')
begin
site.compile
# TODO include icon (--image misc/success-icon.png)
notify_on_compilation_success = watcher_config.fetch(:notify_on_compilation_success) { true }
if notify_on_compilation_success
@notifier.notify('Compilation complete')
end
time_spent = ((Time.now - start)*1000.0).round
puts "done in #{format '%is %ims', *(time_spent.divmod(1000))}"
rescue Exception => e
# TODO include icon (--image misc/error-icon.png)
notify_on_compilation_failure = watcher_config.fetch(:notify_on_compilation_failure) { true }
if notify_on_compilation_failure
@notifier.notify('Compilation failed')
end
puts
Nanoc::CLI::ErrorHandler.print_error(e)
puts
end
end
# Rebuild once
rebuilder.call(nil)
# Get directories to watch
dirs_to_watch = watcher_config[:dirs_to_watch] || ['content', 'layouts', 'lib']
files_to_watch = watcher_config[:files_to_watch] || ['config.yaml', 'Rules', 'rules', 'Rules.rb', 'rules.rb']
files_to_watch = Regexp.new(files_to_watch.map { |name| "#{Regexp.quote(name)}$"}.join("|"))
ignore_dir = Regexp.new(Dir.glob("*").map{|dir| dir if File::ftype(dir) == "directory" }.compact.join("|"))
# Watch
puts "Watching for changes…"
callback = Proc.new do |modified, added, removed|
rebuilder.call(modified[0]) if modified[0]
rebuilder.call(added[0]) if added[0]
rebuilder.call(removed[0]) if removed[0]
end
listener = Listen::MultiListener.new(*dirs_to_watch).change(&callback)
listener_root = Listen::MultiListener.new('', :filter => files_to_watch, :ignore => ignore_dir).change(&callback)
begin
listener_root.start(false)
listener.start
rescue Interrupt
listener.stop
listener_root.stop
end
end
# Allows sending user notifications in a cross-platform way.
class Notifier
# A list of commandline tool names that can be used to send notifications
TOOLS = %w( growlnotify notify-send ) unless defined? TOOLS
# The tool to use for discovering binaries' locations
FIND_BINARY_COMMAND = RUBY_PLATFORM =~ /mingw|mswin/ ? "where" : "which" unless defined? FIND_BINARY_COMMAND
# Send a notification. If no notifier is found, no notification will be
# created.
#
# @param [String] message The message to include in the notification
def notify(message)
return if tool.nil?
send(tool.tr('-', '_'), message)
end
private
def tool
@tool ||= begin
require 'terminal-notifier'
'terminal-notify'
rescue LoadError
begin
TOOLS.find { |t| !`#{FIND_BINARY_COMMAND} #{t}`.empty? }
rescue Errno::ENOENT
nil
end
end
end
def terminal_notify(message)
TerminalNotifier.notify(message, :title => "nanoc")
end
def growlnotify(message)
system('growlnotify', '-m', message)
end
def notify_send(message)
system('notify-send', message)
end
end
end
end
runner Nanoc::CLI::Commands::Watch
|
magicbrush/InteractiveMediaP5 | p0-randomWalk/RandomWalk0/sketch.js | var ps;
var psCount = 100;
var stepPerDraw = 10000;
var arrived;
// 函数setup() :准备阶段
function setup()
{
createCanvas(200,200);
ps = new Array();
arrived = new Array();
for(var i = 0;i<psCount;i++)
{
ps[i] = createVector(width/2,height/2);
arrived[i] = false;
}
}
// 函数draw():作画阶段
function draw() {
fill(255,255,255,1);
rect(0,0,2*width,2*height);
for(var i = 0;i<psCount;i++)
{
var pos = ps[i];
for(var k=0;k<stepPerDraw;k++)
{
pos.x += int(random(-1.01,1.01));
pos.y += int(random(-1.01,1.01));
}
ps[i] = pos;
var bArrive = judgeArrived2(pos.x,pos.y);
if(bArrive)
{
arrived[i] = true;
}
drawBall(pos.x,pos.y);
}
var arrivedCount = 0;
for(var i=0;i<psCount;i++)
{
if(arrived[i]==true)
{
arrivedCount ++;
}
}
push();
fill(255);
rect(0,0,100,20);
fill(0);
text(arrivedCount,10,15);
pop();
}
function judgeArrived(x,y)
{
return (x<0||x>width||y<0||y>height);
}
function judgeArrived2(x,y)
{
return (x>width);
}
function drawBall(x,y)
{
var r = 125*(sin(getTime())+1);
var g = 125*(cos(getTime()/9.1234)+1);
var b = 125*(sin(getTime()*0.32347)+1);
//var color = color(r,g,b);
r += x;
r = r%255;
g+= y;
g = g%255;
b += x-y;
b = b%255;
push();
translate(x,y);
fill(r,g,b);
ellipse(0,0,5,5);
pop();
}
function getTime()
{
return millis()/1000;
}
|
gdonald/cpama | ch18/e11/main.c | <filename>ch18/e11/main.c<gh_stars>0
#include <stdio.h>
/*
int f(int)[]; // functions can't return arrays
int g(int)(int); // functions can't return functions
int a[10](int); // array elements can't be functions
*/
int y2 = 13;
int a2[1] = { 7 };
int *f(int x)
{
printf("x: %d\n", x);
return a2;
}
int f2(int r) { return r; }
int (*g(int))(int);
int foo(int bar) { return bar * 2; }
int (*a[10])(int) = { foo };
int main(void)
{
printf("a2[0]: %d\n", f(9)[0]);
printf("r: %d\n", (*(*g))(86)(2));
printf("bar * 2: %d\n", (*a[0])(21));
return 0;
}
int (*g(int y))(int)
{
printf("y: %d\n", y);
return f2;
}
|
keyboardDrummer/Blender | modularLanguages/shared/src/main/scala/miksilo/modularLanguages/deltas/solidity/SolidityIntLiteralDelta.scala | <reponame>keyboardDrummer/Blender
package miksilo.modularLanguages.deltas.solidity
import miksilo.modularLanguages.core.deltas.path.NodePath
import miksilo.modularLanguages.core.deltas.{Contract, Delta}
import miksilo.languageServer.core.language.{Compilation, Language}
import miksilo.languageServer.core.smarts.ConstraintBuilder
import miksilo.languageServer.core.smarts.scopes.objects.Scope
import miksilo.languageServer.core.smarts.types.objects.Type
import miksilo.modularLanguages.deltas.expression.{ExpressionDelta, IntLiteralDelta, IsExpression}
object SolidityIntLiteralDelta extends Delta {
override def inject(language: Language): Unit = {
ExpressionDelta.expressionInstances.add(language, IntLiteralDelta.Shape, new IsExpression {
override def constraints(compilation: Compilation, builder: ConstraintBuilder, expression: NodePath, _type: Type, parentScope: Scope): Unit = {
}
})
super.inject(language)
}
override def dependencies: Set[Contract] = Set(IntLiteralDelta)
override def description = "Overrides the type checking of the int literal"
}
|
aleattene/python-workbook | chap_05/exe_123_pig_latin_improved.py | <filename>chap_05/exe_123_pig_latin_improved.py
"""
The program extends exercise 122 (file 122_PingLatin),
so that CAPITAL LETTERS and PUNCTUATION MARKS
(commas, points, question marks, and exclamation marks) are correctly managed:
- if a word begins with a CAPITAL letter,
its PIG LATIN representation should begin anyway with a capital letter
and the shifted letter to the end of the word
should be changed to lowercase (Computer -> Omputercay)
- if a word ends with a PUNCTUATION MARKS,
the punctuation mark it should remain at the end of the word
after the transformation has been performed (Science! -> Iencescay!)
"""
# START Definition of the FUNCTION
def checkEntry(line_text): # possible evolution -> check entry
pass
# ["s","t","r","i","n","g","a","?","a","y"] -> ["s","t","r","i","n","g","a","a","y","?"]
def punctuationManagement(list_chars):
punctuation_marks = [".", ",", "?", "!"]
marks = 0
# WARNING -> edit the original caller list
for i in range(len(list_chars)):
if list_chars[i] in punctuation_marks:
while list_chars[i] in punctuation_marks:
list_chars.append(list_chars[i])
list_chars.pop(i)
return
def translateToPigLatin(strings_list):
# WOLVELS
wovels_lower = ["a", "e", "i", "o", "u"]
wovels_upper = ["A", "E", "I", "O", "U"]
# CONSONANTS
consonants_lower = ["b", "c", "d", "f", "g", "h", "j", "k", "l",
"m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"]
consonants_upper = ["B", "C", "D", "F", "G", "H", "J", "K", "L",
"M", "N", "P", "Q", "R", "S", "T", "V", "W", "X", "Y", "Z"]
for i in range(len(strings_list)):
# ["stringa"] -> ["a"] or ["A"]
if strings_list[i][0] in wovels_lower or strings_list[i][0] in wovels_upper:
# ["stringa"] -> ["s","t","r","i","n","g","a"]
list_tmp = list(strings_list[i])
if list_tmp[0] in wovels_upper:
# ["a"] -> ["A"]
list_tmp[0] = list_tmp[0].upper()
# ["s","t","r","i","n","g","a","?"] -> ["s","t","r","i","n","g","a","?","w","a","y"] or
# ["S","t","r","i","n","g","a","?"] -> ["S","t","r","i","n","g","a","?","w","a","y"]
list_tmp.append("w")
list_tmp.append("a")
list_tmp.append("y")
# ["s","t","r","i","n","g","a","?","w","a","y"] -> ["s","t","r","i","n","g","a","w","a","y","?"]
punctuationManagement(list_tmp)
# ["s","t","r","i","n","g","a","w","a","y"] -> ["Stringaway"] or
# ["s","t","r","i","n","g","a","w","a","y","?"] -> ["Stringaway?"]
strings_list[i] = "".join(list_tmp)
# ["stringa"] -> ["s"] or ["S"]
elif strings_list[i][0] in consonants_lower or strings_list[i][0] in consonants_upper:
# ["stringa"] -> ["s","t","r","i","n","g","a"]
list_tmp = list(strings_list[i])
capitalize = False # ["s"]
if list_tmp[0] in consonants_upper:
capitalize = True # ["S"]
while list_tmp[0] in consonants_lower or list_tmp[0] in consonants_upper:
list_tmp.append(list_tmp[0].lower())
list_tmp.pop(0)
if capitalize:
# ["s"] -> ["S"]
list_tmp[0] = list_tmp[0].upper()
# ["s","t","r","i","n","g","a","?","a","y"] -> ["s","t","r","i","n","g","a","a","y","?"] or
# ["S","t","r","i","n","g","a","?","a","y"] -> ["S","t","r","i","n","g","a","a","y","?"]
list_tmp.append("a")
list_tmp.append("y")
# ["s","t","r","i","n","g","a","?","a","y"] -> ["s","t","r","i","n","g","a","a","y","?"]
punctuationManagement(list_tmp)
# ["s","t","r","i","n","g","a","a","y"] -> ["stringaay"] or
# ["s","t","r","i","n","g","a","a","y","?"] -> ["stringaay?"]
strings_list[i] = "".join(list_tmp)
return strings_list
# END Definition of FUNCTION
# START MAIN PROGRAM
def main():
# Acquisition of DATA entered by the USER
text = input("Enter the TEXT: ")
# STRING TESTING
# text = "computer, think? algorithm! office."
# ORIGINAL LIST generation -> ["string","string"]
original_strings_list = text.split()
# TRANSLATED (PIG LATIN) LIST
strings_translated = translateToPigLatin(original_strings_list)
# Displaying the RESULTS
print("ORIGINAL TEXT -> {}".format(text))
print("TEXT TRANSLATED (PIG LATIN) -> ", end="")
for string in strings_translated:
print(string, end=" ")
if __name__ == "__main__":
main()
|
specs-feup/matisse | MatlabToCTester/src/org/specs/MatlabToCTester/Auxiliary/MatlabOptions.java | <reponame>specs-feup/matisse<gh_stars>0
/**
* Copyright 2012 SPeCS Research Group.
*
* 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. under the License.
*/
package org.specs.MatlabToCTester.Auxiliary;
/**
* @author <NAME>
*
*/
public class MatlabOptions {
// The absolute and relative error tolerance values used in the
// comparison of the C outputs and Matlab outputs
private final double absEpsilon;
private final double relEpsilon;
private final boolean testWithMatlab;
public MatlabOptions(double absEpsilon, double relEpsilon, boolean testWithMatlab) {
this.absEpsilon = absEpsilon;
this.relEpsilon = relEpsilon;
this.testWithMatlab = testWithMatlab;
}
/**
* @return the absEpsilon
*/
public double getAbsEpsilon() {
return absEpsilon;
}
/**
* @return the relEpsilon
*/
public double getRelEpsilon() {
return relEpsilon;
}
public boolean testWithMatlab() {
return testWithMatlab;
}
}
|
pablokawan/ABx | Include/sa/WeightedSelector.h | /**
* Copyright 2017-2020 <NAME>
*
* 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.
*/
#pragma once
#include <memory>
#include <vector>
#include <random>
#include <sa/Assert.h>
#include <sa/Noncopyable.h>
namespace sa {
// https://github.com/m-ochi/aliasmethod
template <typename T>
class WeightedSelector
{
NON_COPYABLE(WeightedSelector)
private:
bool initialized_;
std::vector<float> weights_;
std::vector<float> probs_;
std::vector<size_t> alias_;
std::vector<T> values_;
size_t GetIndex(float rand1, float rand2) const
{
const size_t count = values_.size();
size_t k = static_cast<size_t>(static_cast<float>(count) * rand1);
return rand2 < probs_[k] ? k : alias_[k];
}
public:
WeightedSelector() :
initialized_(false)
{ }
size_t Count() const { return values_.size(); }
/// Add a value with a weight. After all values have been added call Update() then
/// call Get() to get a value.
void Add(const T& value, float weight)
{
values_.push_back(value);
weights_.push_back(weight);
}
void Update()
{
const size_t count = values_.size();
std::unique_ptr<float[]> norm_probs = std::make_unique<float[]>(count);
std::unique_ptr<size_t[]> large_block = std::make_unique<size_t[]>(count);
std::unique_ptr<size_t[]> small_block = std::make_unique<size_t[]>(count);
probs_.clear();
alias_.clear();
probs_.resize(count);
alias_.resize(count);
float sum = 0;
size_t cur_small_block;
size_t cur_large_block;
size_t num_small_block = 0;
size_t num_large_block = 0;
for (size_t k = 0; k < count; ++k)
sum += weights_[k];
for (size_t k = 0; k < count; ++k)
norm_probs[k] = weights_[k] * count / sum;
for (size_t k = count - 1; k != 0; --k)
{
if (norm_probs[k] < 1)
small_block[num_small_block++] = k;
else
large_block[num_large_block++] = k;
}
while (num_small_block && num_large_block)
{
cur_small_block = small_block[--num_small_block];
cur_large_block = large_block[--num_large_block];
probs_[cur_small_block] = norm_probs[cur_small_block];
alias_[cur_small_block] = cur_large_block;
norm_probs[cur_large_block] = norm_probs[cur_large_block] + norm_probs[cur_small_block] - 1;
if (norm_probs[cur_large_block] < 1)
small_block[num_small_block++] = cur_large_block;
else
large_block[num_large_block++] = cur_large_block;
}
while (num_large_block)
probs_[large_block[--num_large_block]] = 1.0f;
while (num_small_block)
probs_[small_block[--num_small_block]] = 1.0f;
initialized_ = true;
}
bool IsInitialized() const { return initialized_; }
const T& Get(float rand1, float rand2) const
{
ASSERT(initialized_);
auto i = GetIndex(rand1, rand2);
ASSERT(Count() > i);
return values_[i];
}
};
}
|
haesleinhuepf/pyqode.core | pyqode/core/panels/marker.py | # -*- coding: utf-8 -*-
"""
This module contains the marker panel
"""
import logging
from pyqode.core.api import TextDecoration
from pyqode.core.api.panel import Panel
from pyqode.core.api.utils import DelayJobRunner, TextHelper
from qtpy import QtCore, QtWidgets, QtGui
def _logger():
""" Gets module's logger """
return logging.getLogger(__name__)
class Marker(QtCore.QObject):
"""
A marker is an icon draw on a marker panel at a specific line position and
with a possible tooltip.
"""
@property
def position(self):
"""
Gets the marker position (line number)
:type: int
"""
try:
return self.block.blockNumber()
except AttributeError:
return self._position # not added yet
@property
def icon(self):
"""
Gets the icon file name. Read-only.
"""
if isinstance(self._icon, str):
if QtGui.QIcon.hasThemeIcon(self._icon):
return QtGui.QIcon.fromTheme(self._icon)
else:
return QtGui.QIcon(self._icon)
elif isinstance(self._icon, tuple):
return QtGui.QIcon.fromTheme(self._icon[0],
QtGui.QIcon(self._icon[1]))
elif isinstance(self._icon, QtGui.QIcon):
return self._icon
return QtGui.QIcon()
@property
def description(self):
""" Gets the marker description. """
return self._description
def __init__(self, position, icon="", description="", parent=None):
"""
:param position: The marker position/line number.
:type position: int
:param icon: The icon to display
:type icon: QtGui.QIcon
:param parent: The optional parent object.
:type parent: QtCore.QObject or None
"""
QtCore.QObject.__init__(self, parent)
#: The position of the marker (line number)
self._position = position
self._icon = icon
self._description = description
class MarkerPanel(Panel):
"""
General purpose marker panel.
This panels takes care of drawing icons at a specific line number.
Use addMarker, removeMarker and clearMarkers to manage the collection of
displayed makers.
You can create a user editable panel (e.g. a breakpoints panel) by using
the following signals:
- :attr:`pyqode.core.panels.MarkerPanel.add_marker_requested`
- :attr:`pyqode.core.panels.MarkerPanel.remove_marker_requested`
"""
#: Signal emitted when the user clicked in a place where there is no
#: marker.
add_marker_requested = QtCore.Signal(int)
#: Signal emitted when the user right clicked on an existing marker.
edit_marker_requested = QtCore.Signal(int)
#: Signal emitted when the user left clicked on an existing marker.
remove_marker_requested = QtCore.Signal(int)
@property
def background(self):
"""
Marker background color in editor. Use None if no text decoration
should be used.
"""
return self._background
@background.setter
def background(self, value):
self._background = value
def __init__(self):
Panel.__init__(self)
self._background = QtGui.QColor('#FFC8C8')
self._markers = []
self._icons = {}
self._previous_line = -1
self.scrollable = True
self._job_runner = DelayJobRunner(delay=100)
self.setMouseTracking(True)
self._to_remove = []
@property
def markers(self):
"""
Gets all markers.
"""
return self._markers
def add_marker(self, marker):
"""
Adds the marker to the panel.
:param marker: Marker to add
:type marker: pyqode.core.modes.Marker
"""
self._markers.append(marker)
doc = self.editor.document()
assert isinstance(doc, QtGui.QTextDocument)
block = doc.findBlockByLineNumber(marker._position)
marker.block = block
d = TextDecoration(block)
d.set_full_width()
if self._background:
d.set_background(QtGui.QBrush(self._background))
marker.decoration = d
self.editor.decorations.append(d)
self.repaint()
def remove_marker(self, marker):
"""
Removes a marker from the panel
:param marker: Marker to remove
:type marker: pyqode.core.Marker
"""
self._markers.remove(marker)
self._to_remove.append(marker)
if hasattr(marker, 'decoration'):
self.editor.decorations.remove(marker.decoration)
self.repaint()
def clear_markers(self):
""" Clears the markers list """
while len(self._markers):
self.remove_marker(self._markers[0])
def marker_for_line(self, line):
"""
Returns the marker that is displayed at the specified line number if
any.
:param line: The marker line.
:return: Marker of None
:rtype: pyqode.core.Marker
"""
markers = []
for marker in self._markers:
if line == marker.position:
markers.append(marker)
return markers
def sizeHint(self):
"""
Returns the panel size hint. (fixed with of 16px)
"""
metrics = QtGui.QFontMetricsF(self.editor.font())
size_hint = QtCore.QSize(metrics.height(), metrics.height())
if size_hint.width() > 16:
size_hint.setWidth(16)
return size_hint
def paintEvent(self, event):
Panel.paintEvent(self, event)
painter = QtGui.QPainter(self)
for top, block_nbr, block in self.editor.visible_blocks:
for marker in self._markers:
if marker.block == block and marker.icon:
rect = QtCore.QRect()
rect.setX(0)
rect.setY(top)
rect.setWidth(self.sizeHint().width())
rect.setHeight(self.sizeHint().height())
marker.icon.paint(painter, rect)
def mousePressEvent(self, event):
# Handle mouse press:
# - emit add marker signal if there were no marker under the mouse
# cursor
# - emit remove marker signal if there were one or more markers under
# the mouse cursor.
line = TextHelper(self.editor).line_nbr_from_position(event.pos().y())
if self.marker_for_line(line):
if event.button() == QtCore.Qt.LeftButton:
self.remove_marker_requested.emit(line)
else:
self.edit_marker_requested.emit(line)
else:
self.add_marker_requested.emit(line)
def mouseMoveEvent(self, event):
# Requests a tooltip if the cursor is currently over a marker.
line = TextHelper(self.editor).line_nbr_from_position(event.pos().y())
markers = self.marker_for_line(line)
text = '\n'.join([marker.description for marker in markers if
marker.description])
if len(markers):
if self._previous_line != line:
top = TextHelper(self.editor).line_pos_from_number(
markers[0].position)
if top:
self._job_runner.request_job(self._display_tooltip,
text, top)
else:
self._job_runner.cancel_requests()
self._previous_line = line
def leaveEvent(self, *args, **kwargs):
"""
Hide tooltip when leaving the panel region.
"""
QtWidgets.QToolTip.hideText()
self._previous_line = -1
def _display_tooltip(self, tooltip, top):
"""
Display tooltip at the specified top position.
"""
QtWidgets.QToolTip.showText(self.mapToGlobal(QtCore.QPoint(
self.sizeHint().width(), top)), tooltip, self)
|
ivan-kyosev-gs/legend-sdlc | legend-sdlc-server-shared/src/main/java/org/finos/legend/sdlc/server/error/BaseExceptionMapper.java | <filename>legend-sdlc-server-shared/src/main/java/org/finos/legend/sdlc/server/error/BaseExceptionMapper.java
// Copyright 2021 <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 org.finos.legend.sdlc.server.error;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.Response.Status.Family;
import javax.ws.rs.ext.ExceptionMapper;
abstract class BaseExceptionMapper<T extends Throwable> implements ExceptionMapper<T>
{
private static final Logger LOGGER = LoggerFactory.getLogger(BaseExceptionMapper.class);
protected final boolean includeStackTrace;
protected BaseExceptionMapper(boolean includeStackTrace)
{
this.includeStackTrace = includeStackTrace;
}
protected Response buildResponse(Status status, ExtendedErrorMessage errorMessage)
{
if (status.getStatusCode() != errorMessage.getCode())
{
LOGGER.warn("Building response with status code ({}) that does not match error message statue code ({})", status.getStatusCode(), errorMessage.getCode());
}
return Response.status(status)
.entity(errorMessage)
.type(MediaType.APPLICATION_JSON)
.build();
}
protected Response buildDefaultResponse(Throwable t)
{
Status status = Status.INTERNAL_SERVER_ERROR;
ExtendedErrorMessage errorMessage = ExtendedErrorMessage.fromThrowable(t, this.includeStackTrace);
if (errorMessage.getCode() != status.getStatusCode())
{
LOGGER.warn("Building default response for error message with non-default status: {}", errorMessage.getCode());
Status errorMessageStatus = Status.fromStatusCode(errorMessage.getCode());
if (errorMessageStatus == null)
{
LOGGER.warn("Unknown status code in error message: {}", errorMessage.getCode());
}
else
{
Family family = errorMessageStatus.getFamily();
if ((family == Family.CLIENT_ERROR) || (family == Family.SERVER_ERROR))
{
status = errorMessageStatus;
}
}
}
return buildResponse(status, errorMessage);
}
}
|
clchiou/garage | shipyard2/rules/third-party/lxml/build.py | <reponame>clchiou/garage<gh_stars>1-10
import shipyard2.rules.bases
import shipyard2.rules.pythons
shipyard2.rules.bases.define_distro_packages([
'libxml2-dev',
'libxslt1-dev',
])
(shipyard2.rules.pythons.define_pypi_package('lxml', '4.6.3').build\
.depend('install')
)
|
jgowdyelastic/kibana | src/core_plugins/kibana/public/context/api/utils/sorting.js | /*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. 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.
*/
import _ from 'lodash';
/**
* The list of field names that are allowed for sorting, but not included in
* index pattern fields.
*
* @constant
* @type {string[]}
*/
const META_FIELD_NAMES = ['_seq_no', '_doc', '_uid'];
/**
* Returns a field from the intersection of the set of sortable fields in the
* given index pattern and a given set of candidate field names.
*
* @param {IndexPattern} indexPattern - The index pattern to search for
* sortable fields
* @param {string[]} fields - The list of candidate field names
*
* @returns {string[]}
*/
function getFirstSortableField(indexPattern, fieldNames) {
const sortableFields = fieldNames.filter((fieldName) => (
META_FIELD_NAMES.includes(fieldName)
|| (indexPattern.fields.byName[fieldName] || { sortable: false }).sortable
));
return sortableFields[0];
}
/**
* A sort directive in object or string form.
*
* @typedef {(SortDirectiveString|SortDirectiveObject)} SortDirective
*/
/**
* A sort directive in object form.
*
* @typedef {Object.<FieldName, (SortDirection|SortOptions)>} SortDirectiveObject
*/
/**
* A sort order string.
*
* @typedef {('asc'|'desc')} SortDirection
*/
/**
* A field name.
*
* @typedef {string} FieldName
*/
/**
* A sort options object
*
* @typedef {Object} SortOptions
* @property {SortDirection} order
*/
/**
* Return a copy of the directive with the sort direction reversed. If the
* field name is '_score', it inverts the default sort direction in the same
* way as Elasticsearch itself.
*
* @param {SortDirective} sortDirective - The directive to reverse the
* sort direction of
*
* @returns {SortDirective}
*/
function reverseSortDirective(sortDirective) {
if (_.isString(sortDirective)) {
return {
[sortDirective]: (sortDirective === '_score' ? 'asc' : 'desc'),
};
} else if (_.isPlainObject(sortDirective)) {
return _.mapValues(sortDirective, reverseSortDirection);
} else {
return sortDirective;
}
}
/**
* Return the reversed sort direction.
*
* @param {(SortDirection|SortOptions)} sortDirection
*
* @returns {(SortDirection|SortOptions)}
*/
function reverseSortDirection(sortDirection) {
if (_.isPlainObject(sortDirection)) {
return _.assign({}, sortDirection, {
order: reverseSortDirection(sortDirection.order),
});
} else {
return (sortDirection === 'asc' ? 'desc' : 'asc');
}
}
export {
getFirstSortableField,
reverseSortDirection,
reverseSortDirective,
};
|
Vitingwrin/SigninClient | app/src/main/java/com/hellochiu/soap/CourseService.java | package com.hellochiu.soap;
import org.ksoap2.serialization.SoapObject;
public class CourseService {
public static final String NONE = "none";
public static final String ADD_COURSE_SUCCESS = "加入成功";
private ServiceUtil util = new ServiceUtil();
public String getSelectedCourses(String stuId) {
SoapObject result = util.callService("GetSelectedCourses", "stuId", stuId);
return result == null ? null : result.getPropertyAsString(0);
}
public String getCreatedCourses(String tchId) {
SoapObject result = util.callService("GetCreatedCourses", "tchId", tchId);
return result == null ? null : result.getPropertyAsString(0);
}
public String getCourseStuDetails(String courseId) {
SoapObject result = util.callService("GetCourseStuDetails", "courseId", courseId);
return result == null ? null : result.getPropertyAsString(0);
}
public String getAllCourses() {
SoapObject result = util.callService("GetAllCourses");
return result == null ? null : result.getPropertyAsString(0);
}
public String addCourse(String stuId, String courseId) {
SoapObject result = util.callService("AddCourse", "stuId", stuId, "courseId", courseId);
return result == null ? null : result.getPropertyAsString(0);
}
public String createCourse(String tchId, String courseName, String coursePwd, String beginTime, String endTime) {
SoapObject result = util.callService("CreateCourse", "tchId", tchId, "courseName", courseName,
"coursePwd", coursePwd, "beginTime", beginTime, "endTime", endTime);
return result == null ? null : result.getPropertyAsString(0);
}
}
|
Bhaskers-Blu-Org2/pmod | src/foundation_library/Expression.h | /***
* Copyright (C) Microsoft. All rights reserved.
* Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
*
* File:Expression.h
****/
#ifndef _EXPRESSION_DEFINED
#define _EXPRESSION_DEFINED
#include <foundation/interfaces/expression.h>
#include <foundation/ctl/com_library.h>
#include <foundation/library/base_adapter_host.h>
#include <memory>
#include <vector>
#include <foundation/array_wrapper.h>
#include "auto_delete_vector.h"
class CTokenBase;
typedef auto_delete_vector<CTokenBase> _TokenBaseVectorType;
class CExpression:
public foundation::library::_DefaultAdapterHost
<
foundation::IExpression,
foundation::ctl::ImplementsInspectable
<
foundation::IExpression,
&foundation::IID_IExpression
>
>
{
public:
static HRESULT CreateInstance(
_In_ LPCSTR_t expression,
_COM_Outptr_ IExpression **ppExpression);
HRESULT _Initialize(LPCSTR_t expression);
protected:
STDMETHOD(GetReferenceTokens)(UINT32 *size, HSTRING **ppReferenceTokens);
STDMETHOD(Evaluate)(foundation::IResolveTokenDelegate *pResolveDelegate, foundation::IPropertyValue ** ppValue);
private:
_TokenBaseVectorType m_rpn;
foundation::HStringArrayWrapper m_TokenReferences;
};
#endif
|
servicecatalog/oscm | oscm-unittests-base/javasrc/org/oscm/test/data/SupportedCountries.java | <filename>oscm-unittests-base/javasrc/org/oscm/test/data/SupportedCountries.java<gh_stars>10-100
/*******************************************************************************
* Copyright FUJITSU LIMITED 2018
*******************************************************************************/
package org.oscm.test.data;
import java.util.Locale;
import org.oscm.dataservice.local.DataService;
import org.oscm.domobjects.Organization;
import org.oscm.domobjects.SupportedCountry;
import org.oscm.internal.types.exception.NonUniqueBusinessKeyException;
import org.oscm.internal.types.exception.ObjectNotFoundException;
public class SupportedCountries {
/**
* Returns the SupportedCountry for the given country code. The
* SupportedCountry is created in case it does not exist. Normally all
* SupportedCountry objects are created during DB setup.
*/
public static SupportedCountry findOrCreate(DataService mgr,
String countryCode) throws NonUniqueBusinessKeyException {
SupportedCountry result = (SupportedCountry) mgr
.find(new SupportedCountry(countryCode));
if (result == null) {
result = persistCountry(mgr, countryCode);
}
return result;
}
/**
* Creates one supported country. One country is the minimum setup to pass
* validation tests in the business logic.
*
* @param mgr
* @throws NonUniqueBusinessKeyException
*/
public static void createOneSupportedCountry(DataService mgr)
throws NonUniqueBusinessKeyException {
findOrCreate(mgr, Locale.GERMANY.getCountry());
}
/**
* Creates a few supported countries for testing. This method is faster than
* creating all countries.
*
* @param mgr
* @throws NonUniqueBusinessKeyException
*/
public static void createSomeSupportedCountries(DataService mgr)
throws NonUniqueBusinessKeyException {
findOrCreate(mgr, Locale.GERMANY.getCountry());
findOrCreate(mgr, Locale.JAPAN.getCountry());
findOrCreate(mgr, Locale.UK.getCountry());
}
/**
* Creates all SupportedCountry objects. Normally all SupportedCountry
* objects are created during DB setup. Creating all countries is slow and
* should be done only if needed.
*/
public static void createAllSupportedCountries(DataService mgr)
throws NonUniqueBusinessKeyException {
for (String countryCode : Locale.getISOCountries()) {
findOrCreate(mgr, countryCode);
}
}
/*
* Create a supported country for the given country code.
*/
private static SupportedCountry persistCountry(DataService mgr,
String countryCode) throws NonUniqueBusinessKeyException {
SupportedCountry country = new SupportedCountry(countryCode);
mgr.persist(country);
return country;
}
/**
* Setup one country for testing. The platform operator is created with one
* supported country. Only minimum data is created for performance reasons.
*
* @param mgr
* @throws Exception
*/
public static void setupOneCountry(DataService mgr) throws Exception {
createOneSupportedCountry(mgr);
createPlatformOperator(mgr);
}
/**
* Setup a few countries for testing. The platform operator is created. Only
* a few countries are created for performance reasons.
*
* @param mgr
* @throws Exception
*/
public static void setupSomeCountries(DataService mgr) throws Exception {
createSomeSupportedCountries(mgr);
createPlatformOperator(mgr);
}
/**
* Setup all countries for testing. The platform operator is created with
* all supported countries. Creating all countries is slow and should be
* done only when needed.
*
* @param mgr
* @throws Exception
*/
public static void setupAllCountries(DataService mgr) throws Exception {
createAllSupportedCountries(mgr);
createPlatformOperator(mgr);
}
/*
* Create the platform operator. The platform operator defines the supported
* countries for all supplieres.
*/
private static Organization createPlatformOperator(DataService mgr)
throws NonUniqueBusinessKeyException, ObjectNotFoundException {
Organization operator = Organizations.findOrganization(mgr,
"PLATFORM_OPERATOR");
if (operator == null) {
operator = Organizations.createOrganization(mgr);
operator.setOrganizationId("PLATFORM_OPERATOR");
}
Organizations.supportAllCountries(mgr, operator);
return operator;
}
/**
* Searches the SupportedCountry for the given country code.
*
* @param mgr
* @param countryCode
* @return
*/
public static SupportedCountry find(DataService mgr, String countryCode) {
SupportedCountry result = (SupportedCountry) mgr
.find(new SupportedCountry(countryCode));
return result;
}
}
|
TheGenial/Java-Projects | PreJob-Task/RESTfulinPeace/src/main/java/com/arif/restfulinpeace/dao/PatientRepository.java | <filename>PreJob-Task/RESTfulinPeace/src/main/java/com/arif/restfulinpeace/dao/PatientRepository.java
package com.arif.restfulinpeace.dao;
import com.arif.restfulinpeace.model.Patient;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
@Repository
public interface PatientRepository extends JpaRepository<Patient,String> {
@Query("select p from Patient p where p.patientid = ?")
Patient getPatientById(Integer patientId);
}
|
dgarus/asto | src/test/java/com/artipie/asto/KeyTest.java | <gh_stars>0
/*
* The MIT License (MIT) Copyright (c) 2020-2021 art<EMAIL>
* https://github.com/artipie/asto/LICENSE.txt
*/
package com.artipie.asto;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.hamcrest.core.IsEqual;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* Test case for {@link Key}.
*
* @since 0.32
*/
@SuppressWarnings("PMD.TooManyMethods")
final class KeyTest {
@Test
void getPartsOfKey() {
final Key key = new Key.From("1", "2");
MatcherAssert.assertThat(
key.parts(),
Matchers.containsInRelativeOrder("1", "2")
);
}
@Test
void resolvesKeysFromParts() {
MatcherAssert.assertThat(
new Key.From("one1", "two2", "three3/four4").string(),
new IsEqual<>("one1/two2/three3/four4")
);
}
@Test
void resolvesKeyFromParts() {
MatcherAssert.assertThat(
new Key.From("one", "two", "three").string(),
Matchers.equalTo("one/two/three")
);
}
@Test
void resolvesKeyFromBasePath() {
MatcherAssert.assertThat(
new Key.From(new Key.From("black", "red"), "green", "yellow").string(),
Matchers.equalTo("black/red/green/yellow")
);
}
@Test
void keyFromString() {
final String string = "a/b/c";
MatcherAssert.assertThat(
new Key.From(string).string(),
Matchers.equalTo(string)
);
}
@Test
void keyWithEmptyPart() {
Assertions.assertThrows(Exception.class, () -> new Key.From("", "something").string());
}
@Test
void resolvesRootKey() {
MatcherAssert.assertThat(Key.ROOT.string(), Matchers.equalTo(""));
}
@Test
void returnsParent() {
MatcherAssert.assertThat(
new Key.From("a/b").parent().get().string(),
new IsEqual<>("a")
);
}
@Test
void rootParent() {
MatcherAssert.assertThat(
"ROOT parent is not empty",
!Key.ROOT.parent().isPresent()
);
}
@Test
void emptyKeyParent() {
MatcherAssert.assertThat(
"Empty key parent is not empty",
!new Key.From("").parent().isPresent()
);
}
@Test
void comparesKeys() {
final Key frst = new Key.From("1");
final Key scnd = new Key.From("2");
MatcherAssert.assertThat(
Key.CMP_STRING.compare(frst, scnd),
new IsEqual<>(-1)
);
}
}
|
madang01/gitcodda | codda2/project/sample_base/server_build/src/main/java/kr/pe/codda/jooq/SbDb.java | /*
* This file is generated by jOOQ.
*/
package kr.pe.codda.jooq;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Generated;
import kr.pe.codda.jooq.tables.SbAccountSerarchTb;
import kr.pe.codda.jooq.tables.SbBoardFilelistTb;
import kr.pe.codda.jooq.tables.SbBoardHistoryTb;
import kr.pe.codda.jooq.tables.SbBoardInfoTb;
import kr.pe.codda.jooq.tables.SbBoardTb;
import kr.pe.codda.jooq.tables.SbBoardVoteTb;
import kr.pe.codda.jooq.tables.SbDocHistoryTb;
import kr.pe.codda.jooq.tables.SbDocTb;
import kr.pe.codda.jooq.tables.SbMemberActivityHistoryTb;
import kr.pe.codda.jooq.tables.SbMemberTb;
import kr.pe.codda.jooq.tables.SbSeqTb;
import kr.pe.codda.jooq.tables.SbSiteLogTb;
import kr.pe.codda.jooq.tables.SbSitemenuTb;
import kr.pe.codda.jooq.tables.SbUploadImageTb;
import org.jooq.Catalog;
import org.jooq.Table;
import org.jooq.impl.SchemaImpl;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.10.6"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class SbDb extends SchemaImpl {
private static final long serialVersionUID = -1046974919;
/**
* The reference instance of <code>sb_db</code>
*/
public static final SbDb SB_DB = new SbDb();
/**
* 계정 찾기 테이블
*/
public final SbAccountSerarchTb SB_ACCOUNT_SERARCH_TB = kr.pe.codda.jooq.tables.SbAccountSerarchTb.SB_ACCOUNT_SERARCH_TB;
/**
* The table <code>sb_db.sb_board_filelist_tb</code>.
*/
public final SbBoardFilelistTb SB_BOARD_FILELIST_TB = kr.pe.codda.jooq.tables.SbBoardFilelistTb.SB_BOARD_FILELIST_TB;
/**
* The table <code>sb_db.sb_board_history_tb</code>.
*/
public final SbBoardHistoryTb SB_BOARD_HISTORY_TB = kr.pe.codda.jooq.tables.SbBoardHistoryTb.SB_BOARD_HISTORY_TB;
/**
* The table <code>sb_db.sb_board_info_tb</code>.
*/
public final SbBoardInfoTb SB_BOARD_INFO_TB = kr.pe.codda.jooq.tables.SbBoardInfoTb.SB_BOARD_INFO_TB;
/**
* The table <code>sb_db.sb_board_tb</code>.
*/
public final SbBoardTb SB_BOARD_TB = kr.pe.codda.jooq.tables.SbBoardTb.SB_BOARD_TB;
/**
* The table <code>sb_db.sb_board_vote_tb</code>.
*/
public final SbBoardVoteTb SB_BOARD_VOTE_TB = kr.pe.codda.jooq.tables.SbBoardVoteTb.SB_BOARD_VOTE_TB;
/**
* The table <code>sb_db.sb_doc_history_tb</code>.
*/
public final SbDocHistoryTb SB_DOC_HISTORY_TB = kr.pe.codda.jooq.tables.SbDocHistoryTb.SB_DOC_HISTORY_TB;
/**
* The table <code>sb_db.sb_doc_tb</code>.
*/
public final SbDocTb SB_DOC_TB = kr.pe.codda.jooq.tables.SbDocTb.SB_DOC_TB;
/**
* The table <code>sb_db.sb_member_activity_history_tb</code>.
*/
public final SbMemberActivityHistoryTb SB_MEMBER_ACTIVITY_HISTORY_TB = kr.pe.codda.jooq.tables.SbMemberActivityHistoryTb.SB_MEMBER_ACTIVITY_HISTORY_TB;
/**
* The table <code>sb_db.sb_member_tb</code>.
*/
public final SbMemberTb SB_MEMBER_TB = kr.pe.codda.jooq.tables.SbMemberTb.SB_MEMBER_TB;
/**
* The table <code>sb_db.sb_seq_tb</code>.
*/
public final SbSeqTb SB_SEQ_TB = kr.pe.codda.jooq.tables.SbSeqTb.SB_SEQ_TB;
/**
* The table <code>sb_db.sb_sitemenu_tb</code>.
*/
public final SbSitemenuTb SB_SITEMENU_TB = kr.pe.codda.jooq.tables.SbSitemenuTb.SB_SITEMENU_TB;
/**
* The table <code>sb_db.sb_site_log_tb</code>.
*/
public final SbSiteLogTb SB_SITE_LOG_TB = kr.pe.codda.jooq.tables.SbSiteLogTb.SB_SITE_LOG_TB;
/**
* The table <code>sb_db.sb_upload_image_tb</code>.
*/
public final SbUploadImageTb SB_UPLOAD_IMAGE_TB = kr.pe.codda.jooq.tables.SbUploadImageTb.SB_UPLOAD_IMAGE_TB;
/**
* No further instances allowed
*/
private SbDb() {
super("sb_db", null);
}
/**
* {@inheritDoc}
*/
@Override
public Catalog getCatalog() {
return DefaultCatalog.DEFAULT_CATALOG;
}
@Override
public final List<Table<?>> getTables() {
List result = new ArrayList();
result.addAll(getTables0());
return result;
}
private final List<Table<?>> getTables0() {
return Arrays.<Table<?>>asList(
SbAccountSerarchTb.SB_ACCOUNT_SERARCH_TB,
SbBoardFilelistTb.SB_BOARD_FILELIST_TB,
SbBoardHistoryTb.SB_BOARD_HISTORY_TB,
SbBoardInfoTb.SB_BOARD_INFO_TB,
SbBoardTb.SB_BOARD_TB,
SbBoardVoteTb.SB_BOARD_VOTE_TB,
SbDocHistoryTb.SB_DOC_HISTORY_TB,
SbDocTb.SB_DOC_TB,
SbMemberActivityHistoryTb.SB_MEMBER_ACTIVITY_HISTORY_TB,
SbMemberTb.SB_MEMBER_TB,
SbSeqTb.SB_SEQ_TB,
SbSitemenuTb.SB_SITEMENU_TB,
SbSiteLogTb.SB_SITE_LOG_TB,
SbUploadImageTb.SB_UPLOAD_IMAGE_TB);
}
}
|
LyonDon/Spring | test/src/SwordOffer/Solution52.java | <reponame>LyonDon/Spring
package SwordOffer;
/**
* 请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。
* 在本题中,匹配是指字符串的所有字符匹配整个模式。
* 例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配
* @author Administrator
*/
public class Solution52 {
public boolean match(char[] str, char[] pattern){
if (str==null||pattern==null) {
return false;
}
int i=0;
int j=0;
return matchCore(str,pattern,i,j);
}
public boolean matchCore(char[] str,char[] pattern,int i,int j) {
//有效性检验。str到尾,pattern到尾,返回true
//若pattern到尾,str未到尾,返回false
if (i==str.length&&(j==pattern.length)) {
return true;
}
if (i!=str.length&&(j==pattern.length)) {
return false;
}
//如果模式的第二的字符是“*”的话,若pattern的第一位与str的第一位不同,则pattern后移两位,继续匹配
//若pattern的第一位与str的第一位相同,有三种匹配情况:
//pattern后移两位,str不移位,相当于忽略x*
//str后移一位,pattern后移两位,相当于一个x
//str后移一位,pattern不移位,因为还能匹配之后的元素
if (j+1<pattern.length&&pattern[j+1]=='*') {
if (i!=str.length&&str[i]==pattern[j]||(pattern[j]=='.'&&i!=str.length)) {
return matchCore(str, pattern, i, j+2)||matchCore(str, pattern, i+1, j+2)||matchCore(str, pattern, i+1, j);
}else {
return matchCore(str, pattern, i, j+2);
}
}
//如果模式的第二个字符不是“*”的话,有两种情况
//若第一个字符匹配,则判断第二个字符
//若第一个字符不匹配,则返回false;
if ((i!=str.length&&str[i]==pattern[j])||(i!=str.length&&pattern[j]=='.')) {
return matchCore(str, pattern, i+1, j+1);
}
return false;
}
}
|
smolnar82/cloudbreak | mock-infrastructure/src/generated/com/sequenceiq/mock/swagger/model/ApiServiceRef.java | package com.sequenceiq.mock.swagger.model;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.*;
/**
* A serviceRef references a service. It is identified by the \"serviceName\", \"clusterName\" (name of the cluster which the service belongs to) and an optional \"peerName\" (to reference a remote service i.e. services managed by other CM instances). To operate on the service object, use the API with those fields as parameters.
*/
@ApiModel(description = "A serviceRef references a service. It is identified by the \"serviceName\", \"clusterName\" (name of the cluster which the service belongs to) and an optional \"peerName\" (to reference a remote service i.e. services managed by other CM instances). To operate on the service object, use the API with those fields as parameters.")
@Validated
@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2020-10-26T08:01:08.932+01:00")
public class ApiServiceRef {
@JsonProperty("peerName")
private String peerName = null;
@JsonProperty("clusterName")
private String clusterName = null;
@JsonProperty("serviceName")
private String serviceName = null;
@JsonProperty("serviceDisplayName")
private String serviceDisplayName = null;
@JsonProperty("serviceType")
private String serviceType = null;
public ApiServiceRef peerName(String peerName) {
this.peerName = peerName;
return this;
}
/**
* The name of the CM peer corresponding to the remote CM that manages the referenced service. This should only be set when referencing a remote service.
* @return peerName
**/
@ApiModelProperty(value = "The name of the CM peer corresponding to the remote CM that manages the referenced service. This should only be set when referencing a remote service.")
public String getPeerName() {
return peerName;
}
public void setPeerName(String peerName) {
this.peerName = peerName;
}
public ApiServiceRef clusterName(String clusterName) {
this.clusterName = clusterName;
return this;
}
/**
* The enclosing cluster for this service.
* @return clusterName
**/
@ApiModelProperty(value = "The enclosing cluster for this service.")
public String getClusterName() {
return clusterName;
}
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
public ApiServiceRef serviceName(String serviceName) {
this.serviceName = serviceName;
return this;
}
/**
* The service name.
* @return serviceName
**/
@ApiModelProperty(value = "The service name.")
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public ApiServiceRef serviceDisplayName(String serviceDisplayName) {
this.serviceDisplayName = serviceDisplayName;
return this;
}
/**
*
* @return serviceDisplayName
**/
@ApiModelProperty(value = "")
public String getServiceDisplayName() {
return serviceDisplayName;
}
public void setServiceDisplayName(String serviceDisplayName) {
this.serviceDisplayName = serviceDisplayName;
}
public ApiServiceRef serviceType(String serviceType) {
this.serviceType = serviceType;
return this;
}
/**
* The service type. This is available since version 32
* @return serviceType
**/
@ApiModelProperty(value = "The service type. This is available since version 32")
public String getServiceType() {
return serviceType;
}
public void setServiceType(String serviceType) {
this.serviceType = serviceType;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ApiServiceRef apiServiceRef = (ApiServiceRef) o;
return Objects.equals(this.peerName, apiServiceRef.peerName) &&
Objects.equals(this.clusterName, apiServiceRef.clusterName) &&
Objects.equals(this.serviceName, apiServiceRef.serviceName) &&
Objects.equals(this.serviceDisplayName, apiServiceRef.serviceDisplayName) &&
Objects.equals(this.serviceType, apiServiceRef.serviceType);
}
@Override
public int hashCode() {
return Objects.hash(peerName, clusterName, serviceName, serviceDisplayName, serviceType);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ApiServiceRef {\n");
sb.append(" peerName: ").append(toIndentedString(peerName)).append("\n");
sb.append(" clusterName: ").append(toIndentedString(clusterName)).append("\n");
sb.append(" serviceName: ").append(toIndentedString(serviceName)).append("\n");
sb.append(" serviceDisplayName: ").append(toIndentedString(serviceDisplayName)).append("\n");
sb.append(" serviceType: ").append(toIndentedString(serviceType)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
mengyangbai/leetcode | string/reconstructoriginaldigits.py | class Solution:
def originalDigits(self, s):
"""
:type s: str
:rtype: str
"""
res = ""
res += "0"*s.count('z')
res += "1"*(s.count('o')-s.count('z')-s.count('w')-s.count('u'))
res += "2"*s.count('w')
res += "3"*(s.count('h') - s.count('g'))
res += "4"*s.count('u')
res += "5"*(s.count('f') - s.count('u'))
res += "6"*s.count('x')
res += "7"*(s.count('s')-s.count('x'))
res += "8"*s.count("g")
res += "9"*(s.count('i') - s.count('x') - s.count("g") - s.count('f') + s.count('u'))
return res
|
chengmaotao/xiyouShop | src/main/java/com/cms/entity/base/BaseAdminRole.java | <gh_stars>1-10
package com.cms.entity.base;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.IBean;
/**
* Generated by JFinal, do not modify this file.
*/
@SuppressWarnings({"serial", "unchecked"})
public abstract class BaseAdminRole<M extends BaseAdminRole<M>> extends Model<M> implements IBean {
public M setAdminId(java.lang.Long adminId) {
set("adminId", adminId);
return (M)this;
}
public java.lang.Long getAdminId() {
return getLong("adminId");
}
public M setRoleId(java.lang.Long roleId) {
set("roleId", roleId);
return (M)this;
}
public java.lang.Long getRoleId() {
return getLong("roleId");
}
}
|
directionless/google-cloud-ruby | google-cloud-logging/lib/google/cloud/logging/entry.rb | <gh_stars>1-10
# Copyright 2016 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require "google/cloud/logging/convert"
require "google/cloud/logging/resource"
require "google/cloud/logging/entry/http_request"
require "google/cloud/logging/entry/operation"
require "google/cloud/logging/entry/source_location"
require "google/cloud/logging/entry/list"
module Google
module Cloud
module Logging
##
# # Entry
#
# An individual entry in a log.
#
# Each log entry is composed of metadata and a payload. The metadata
# includes standard information used by Stackdriver Logging, such as when
# the entry was created and where it came from. The payload is the event
# record. Traditionally this is a message string, but in Stackdriver
# Logging it can also be a JSON or protocol buffer object. A single log
# can have entries with different payload types.
#
# A log is a named collection of entries. Logs can be produced by Google
# Cloud Platform services, by third-party services, or by your
# applications. For example, the log `compute.googleapis.com/activity_log`
# is produced by Google Compute Engine. Logs are simply referenced by name
# in google-cloud. There is no `Log` type in google-cloud or `Log`
# resource in the Stackdriver Logging API.
#
# @see https://cloud.google.com/logging/docs/view/logs_index List of Log
# Types
#
# @example
# require "google/cloud/logging"
#
# logging = Google::Cloud::Logging.new
#
# entry = logging.entry payload: "Job started.", log_name: "my_app_log"
# entry.resource.type = "gae_app"
# entry.resource.labels[:module_id] = "1"
# entry.resource.labels[:version_id] = "20150925t173233"
#
# logging.write_entries entry
#
# @example Provide a hash to write a JSON payload to the log:
# require "google/cloud/logging"
#
# logging = Google::Cloud::Logging.new
#
# payload = { "stats" => { "a" => 8, "b" => 12.5} }
# entry = logging.entry payload: payload, log_name: "my_app_log"
# entry.resource.type = "gae_app"
# entry.resource.labels[:module_id] = "1"
# entry.resource.labels[:version_id] = "20150925t173233"
#
# logging.write_entries entry
#
class Entry
##
# Generate a pseudo-random, 16-character ID suitable for use as the log
# entry's {#insert_id}.
#
# @return [String]
#
# @example
# require "google/cloud/logging"
#
# insert_id = Google::Cloud::Logging::Entry.insert_id
#
def self.insert_id
rand(36**16).to_s 36
end
##
# Create a new Entry instance. The {#resource} attribute is
# pre-populated with a new {Google::Cloud::Logging::Resource} instance.
# See also {Google::Cloud::Logging::Project#entry}.
def initialize
@labels = {}
@resource = Resource.new
@http_request = HttpRequest.new
@operation = Operation.new
@severity = :DEFAULT
@source_location = SourceLocation.new
@insert_id = Entry.insert_id
end
##
# The resource name of the log to which this log entry belongs. The
# format of the name is `projects/<project-id>/logs/<log-id>`. e.g.
# `projects/my-projectid/logs/my_app_log` and
# `projects/1234567890/logs/library.googleapis.com%2Fbook_log`
#
# The log ID part of resource name must be less than 512 characters long
# and can only include the following characters: upper and lower case
# alphanumeric characters: `[A-Za-z0-9]`; and punctuation characters:
# forward-slash (`/`), underscore (`_`), hyphen (`-`), and period (`.`).
# Forward-slash (`/`) characters in the log ID must be URL-encoded.
attr_accessor :log_name
##
# The monitored resource associated with this log entry. Example: a log
# entry that reports a database error would be associated with the
# monitored resource designating the particular database that reported
# the error.
# @return [Google::Cloud::Logging::Resource]
attr_accessor :resource
##
# The time the event described by the log entry occurred. If omitted,
# Stackdriver Logging will use the time the log entry is written.
# @return [Time]
attr_accessor :timestamp
##
# The severity level of the log entry. The default value is `:DEFAULT`.
# @return [Symbol]
attr_accessor :severity
##
# Returns `true` if the severity level is `:DEFAULT`.
def default?
severity == :DEFAULT
end
##
# Sets the severity level to `:DEFAULT`.
#
# @example
# require "google/cloud/logging"
#
# logging = Google::Cloud::Logging.new
#
# entry = logging.entry
# entry.severity = :DEBUG
# entry.default!
# entry.default? #=> true
# entry.severity #=> :DEFAULT
#
def default!
self.severity = :DEFAULT
end
##
# Returns `true` if the severity level is `:DEBUG`.
def debug?
severity == :DEBUG
end
##
# Sets the severity level to `:DEBUG`.
#
# @example
# require "google/cloud/logging"
#
# logging = Google::Cloud::Logging.new
#
# entry = logging.entry
# entry.severity #=> :DEFAULT
# entry.debug!
# entry.debug? #=> true
# entry.severity #=> :DEBUG
#
def debug!
self.severity = :DEBUG
end
##
# Returns `true` if the severity level is `:INFO`.
def info?
severity == :INFO
end
##
# Sets the severity level to `:INFO`.
#
# @example
# require "google/cloud/logging"
#
# logging = Google::Cloud::Logging.new
#
# entry = logging.entry
# entry.severity #=> :DEFAULT
# entry.info!
# entry.info? #=> true
# entry.severity #=> :INFO
#
def info!
self.severity = :INFO
end
##
# Returns `true` if the severity level is `:NOTICE`.
def notice?
severity == :NOTICE
end
##
# Sets the severity level to `:NOTICE`.
#
# @example
# require "google/cloud/logging"
#
# logging = Google::Cloud::Logging.new
#
# entry = logging.entry
# entry.severity #=> :DEFAULT
# entry.notice!
# entry.notice? #=> true
# entry.severity #=> :NOTICE
#
def notice!
self.severity = :NOTICE
end
##
# Returns `true` if the severity level is `:WARNING`.
def warning?
severity == :WARNING
end
##
# Sets the severity level to `:WARNING`.
#
# @example
# require "google/cloud/logging"
#
# logging = Google::Cloud::Logging.new
#
# entry = logging.entry
# entry.severity #=> :DEFAULT
# entry.warning!
# entry.warning? #=> true
# entry.severity #=> :WARNING
#
def warning!
self.severity = :WARNING
end
##
# Returns `true` if the severity level is `:ERROR`.
def error?
severity == :ERROR
end
##
# Sets the severity level to `:ERROR`.
#
# @example
# require "google/cloud/logging"
#
# logging = Google::Cloud::Logging.new
#
# entry = logging.entry
# entry.severity #=> :DEFAULT
# entry.error!
# entry.error? #=> true
# entry.severity #=> :ERROR
#
def error!
self.severity = :ERROR
end
##
# Returns `true` if the severity level is `:CRITICAL`.
def critical?
severity == :CRITICAL
end
##
# Sets the severity level to `:CRITICAL`.
#
# @example
# require "google/cloud/logging"
#
# logging = Google::Cloud::Logging.new
#
# entry = logging.entry
# entry.severity #=> :DEFAULT
# entry.critical!
# entry.critical? #=> true
# entry.severity #=> :CRITICAL
#
def critical!
self.severity = :CRITICAL
end
##
# Returns `true` if the severity level is `:ALERT`.
def alert?
severity == :ALERT
end
##
# Sets the severity level to `:ALERT`.
#
# @example
# require "google/cloud/logging"
#
# logging = Google::Cloud::Logging.new
#
# entry = logging.entry
# entry.severity #=> :DEFAULT
# entry.alert!
# entry.alert? #=> true
# entry.severity #=> :ALERT
#
def alert!
self.severity = :ALERT
end
##
# Returns `true` if the severity level is `:EMERGENCY`.
def emergency?
severity == :EMERGENCY
end
##
# Sets the severity level to `:EMERGENCY`.
#
# @example
# require "google/cloud/logging"
#
# logging = Google::Cloud::Logging.new
#
# entry = logging.entry
# entry.severity #=> :DEFAULT
# entry.emergency!
# entry.emergency? #=> true
# entry.severity #=> :EMERGENCY
#
def emergency!
self.severity = :EMERGENCY
end
##
# A unique ID for the log entry. If you provide this field, the logging
# service considers other log entries in the same log with the same ID
# as duplicates which can be removed. If omitted, Stackdriver Logging
# will generate a unique ID for this log entry.
# @return [String]
attr_accessor :insert_id
##
# A set of user-defined data that provides additional information about
# the log entry.
# @return [Hash]
attr_accessor :labels
##
# The log entry payload, represented as either a string, a hash (JSON),
# or a hash (protocol buffer).
# @return [String, Hash]
attr_accessor :payload
##
# Information about the HTTP request associated with this log entry, if
# applicable.
# @return [Google::Cloud::Logging::Entry::HttpRequest]
attr_reader :http_request
##
# Information about an operation associated with the log entry, if
# applicable.
# @return [Google::Cloud::Logging::Entry::Operation]
attr_reader :operation
##
# Resource name of the trace associated with the log entry, if any. If
# it contains a relative resource name, the name is assumed to be
# relative to `//tracing.googleapis.com`. Example:
# `projects/my-projectid/traces/06796866738c859f2f19b7cfb3214824`
# Optional.
# @return [String]
attr_accessor :trace
##
# Source code location information associated with the log entry, if
# any.
# @return [Google::Cloud::Logging::Entry::SourceLocation]
attr_reader :source_location
##
# The sampling decision of the trace associated with the log entry.
# Optional. A `true` value means that the trace resource name in the
# `trace` field was sampled for storage in a trace backend. A `false`
# means that the trace was not sampled for storage when this log entry
# was written, or the sampling decision was unknown at the time. A
# non-sampled `trace` value is still useful as a request correlation
# identifier. The default is `false`.
# @return [Boolean]
attr_accessor :trace_sampled
##
# @private Determines if the Entry has any data.
def empty?
log_name.nil? &&
timestamp.nil? &&
(labels.nil? || labels.empty?) &&
payload.nil? &&
resource.empty? &&
http_request.empty? &&
operation.empty? &&
trace.nil? &&
source_location.empty? &&
trace_sampled.nil?
end
##
# @private Exports the Entry to a Google::Logging::V2::LogEntry object.
def to_grpc
grpc = Google::Logging::V2::LogEntry.new(
log_name: log_name.to_s,
timestamp: timestamp_grpc,
# TODO: verify severity is the correct type?
severity: severity,
insert_id: insert_id.to_s,
labels: labels_grpc,
resource: resource.to_grpc,
http_request: http_request.to_grpc,
operation: operation.to_grpc,
trace: trace.to_s,
source_location: source_location.to_grpc,
trace_sampled: !(!trace_sampled)
)
# Add payload
append_payload grpc
grpc
end
##
# @private New Entry from a Google::Logging::V2::LogEntry object.
def self.from_grpc grpc
return new if grpc.nil?
new.tap do |e|
e.log_name = grpc.log_name
e.timestamp = extract_timestamp grpc
e.severity = grpc.severity
e.insert_id = grpc.insert_id
e.labels = Convert.map_to_hash grpc.labels
e.payload = extract_payload grpc
e.instance_variable_set :@resource,
Resource.from_grpc(grpc.resource)
e.instance_variable_set :@http_request,
HttpRequest.from_grpc(grpc.http_request)
e.instance_variable_set :@operation,
Operation.from_grpc(grpc.operation)
e.trace = grpc.trace
e.instance_variable_set :@source_location,
SourceLocation.from_grpc(
grpc.source_location
)
e.trace_sampled = grpc.trace_sampled
end
end
##
# @private Formats the timestamp as a Google::Protobuf::Timestamp
# object.
def timestamp_grpc
return nil if timestamp.nil?
# TODO: ArgumentError if timestamp is not a Time object?
Google::Protobuf::Timestamp.new(
seconds: timestamp.to_i,
nanos: timestamp.nsec
)
end
##
# @private Formats the labels so they can be saved to a
# Google::Logging::V2::LogEntry object.
def labels_grpc
return {} if labels.nil?
# Coerce symbols to strings
Hash[labels.map do |k, v|
v = String(v) if v.is_a? Symbol
[String(k), v]
end]
end
##
# @private Adds the payload data to a Google::Logging::V2::LogEntry
# object.
def append_payload grpc
grpc.proto_payload = nil
grpc.json_payload = nil
grpc.text_payload = nil
if payload.is_a? Google::Protobuf::Any
grpc.proto_payload = payload
elsif payload.respond_to? :to_hash
grpc.json_payload = Convert.hash_to_struct payload.to_hash
else
grpc.text_payload = payload.to_s
end
end
##
# @private Extract payload data from Google API Client object.
def self.extract_payload grpc
grpc.proto_payload || grpc.json_payload || grpc.text_payload
end
##
# @private Get a Time object from a Google::Protobuf::Timestamp object.
def self.extract_timestamp grpc
return nil if grpc.timestamp.nil?
Time.at grpc.timestamp.seconds, Rational(grpc.timestamp.nanos, 1000)
end
end
end
end
end
|
Bingwen-Hu/hackaway | projects/interview/others/change.cpp | <filename>projects/interview/others/change.cpp
#include <vector>
// coins = 1, 5, 10, 20, 50, 100
int change(std::vector<int> num_of_coins, int sum) {
// sum = change(num_of_coins[i]-1, num-Ci)
}
int main() {
return 0;
} |
openregister/openregister-java | src/test/java/uk/gov/register/serialization/RSFCreatorTest.java | package uk.gov.register.serialization;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import org.apache.commons.collections4.IteratorUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import uk.gov.register.core.*;
import uk.gov.register.proofs.ProofGenerator;
import uk.gov.register.serialization.mappers.EntryToCommandMapper;
import uk.gov.register.serialization.mappers.ItemToCommandMapper;
import uk.gov.register.serialization.mappers.RootHashCommandMapper;
import uk.gov.register.util.HashValue;
import uk.gov.register.views.RegisterProof;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class RSFCreatorTest {
private static final JsonNodeFactory jsonFactory = JsonNodeFactory.instance;
private static final String EMPTY_REGISTER_ROOT_HASH = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
private final HashValue emptyRegisterHash = new HashValue(HashingAlgorithm.SHA256, EMPTY_REGISTER_ROOT_HASH);
private RSFCreator sutCreator;
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Mock
private Register register;
@Mock
private ProofGenerator proofGenerator;
private Entry systemEntry;
private Entry entry1;
private Entry entry2;
private Item systemItem;
private Item item1;
private Item item2;
private RegisterCommand assertEmptyRootHashCommand;
private RegisterCommand addSystemItemCommand;
private RegisterCommand addItem1Command;
private RegisterCommand addItem2Command;
private RegisterCommand appendSystemEntryCommand;
private RegisterCommand appendEntry1Command;
private RegisterCommand appendEntry2Command;
@Before
public void setUp() {
sutCreator = new RSFCreator();
sutCreator.register(new RootHashCommandMapper());
sutCreator.register(new EntryToCommandMapper());
sutCreator.register(new ItemToCommandMapper());
systemItem = new Item(jsonFactory.objectNode()
.put("system-field-1", "system-field-1-value")
.put("system-field-2", "system-field-2-value"));
item1 = new Item(jsonFactory.objectNode()
.put("field-1", "entry1-field-1-value")
.put("field-2", "entry1-field-2-value"));
item2 = new Item(jsonFactory.objectNode()
.put("field-1", "entry2-field-1-value")
.put("field-2", "entry2-field-2-value"));
systemEntry = new Entry(1, systemItem.getSha256hex(), systemItem.getBlobHash(), Instant.parse("2016-07-24T16:54:00Z"), "system-key", EntryType.system);
entry1 = new Entry(1, item1.getSha256hex(), item1.getBlobHash(), Instant.parse("2016-07-24T16:55:00Z"), "entry1-field-1-value", EntryType.user);
entry2 = new Entry(2, item2.getSha256hex(), item2.getBlobHash(), Instant.parse("2016-07-24T16:56:00Z"), "entry2-field-1-value", EntryType.user);
assertEmptyRootHashCommand = new RegisterCommand("assert-root-hash", Collections.singletonList(emptyRegisterHash.encode()));
addSystemItemCommand = new RegisterCommand("add-item", Collections.singletonList("{\"system-field-1\":\"system-field-1-value\",\"system-field-2\":\"system-field-2-value\"}"));
addItem1Command = new RegisterCommand("add-item", Collections.singletonList("{\"field-1\":\"entry1-field-1-value\",\"field-2\":\"entry1-field-2-value\"}"));
addItem2Command = new RegisterCommand("add-item", Collections.singletonList("{\"field-1\":\"entry2-field-1-value\",\"field-2\":\"entry2-field-2-value\"}"));
appendSystemEntryCommand = new RegisterCommand("append-entry", Arrays.asList("system", "system-key", "2016-07-24T16:54:00Z", systemItem.getSha256hex().encode()));
appendEntry1Command = new RegisterCommand("append-entry", Arrays.asList("user", "entry1-field-1-value", "2016-07-24T16:55:00Z", item1.getSha256hex().encode()));
appendEntry2Command = new RegisterCommand("append-entry", Arrays.asList("user", "entry2-field-1-value","2016-07-24T16:56:00Z", item2.getSha256hex().encode()));
}
@Test
public void createRegisterSerialisationFormat_returnsRSFFromEntireRegister() {
when(register.getItemIterator(EntryType.user)).thenReturn(Arrays.asList(item1, item2).iterator());
when(register.getItemIterator(EntryType.system)).thenReturn(Arrays.asList(systemItem).iterator());
when(register.getEntryIterator(EntryType.system)).thenReturn(Arrays.asList(systemEntry).iterator());
when(register.getEntryIterator(EntryType.user)).thenReturn(Arrays.asList(entry1, entry2).iterator());
when(proofGenerator.getRootHash()).thenReturn(new HashValue(HashingAlgorithm.SHA256, "1231234"));
RegisterSerialisationFormat actualRSF = sutCreator.create(register, proofGenerator);
List<RegisterCommand> actualCommands = IteratorUtils.toList(actualRSF.getCommands());
assertThat(actualCommands.size(), equalTo(8));
assertThat(actualCommands, contains(
assertEmptyRootHashCommand,
addSystemItemCommand,
addItem1Command,
addItem2Command,
appendSystemEntryCommand,
appendEntry1Command,
appendEntry2Command,
new RegisterCommand("assert-root-hash", Collections.singletonList("sha-256:1231234"))
));
}
@Test
public void createRegisterSerialisationFormat_whenCalledWithBoundary_returnsPartialRSFRegister() {
HashValue oneEntryRootHash = new HashValue(HashingAlgorithm.SHA256, "oneEntryInRegisterHash");
HashValue twoEntriesRootHash = new HashValue(HashingAlgorithm.SHA256, "twoEntriesInRegisterHash");
when(register.getItemIterator(1, 2)).thenReturn(Collections.singletonList(item1).iterator());
when(register.getEntryIterator(1, 2)).thenReturn(Collections.singletonList(entry1).iterator());
when(proofGenerator.getRootHash(1)).thenReturn(oneEntryRootHash);
when(proofGenerator.getRootHash(2)).thenReturn(twoEntriesRootHash);
RegisterSerialisationFormat actualRSF = sutCreator.create(register, proofGenerator, 1, 2);
List<RegisterCommand> actualCommands = IteratorUtils.toList(actualRSF.getCommands());
verify(register, never()).getItemIterator(EntryType.system);
verify(register, never()).getEntryIterator(EntryType.system);
verify(register, times(1)).getItemIterator(1, 2);
verify(register, times(1)).getEntryIterator(1, 2);
assertThat(actualCommands.size(), equalTo(4));
assertThat(actualCommands, contains(
new RegisterCommand("assert-root-hash", Collections.singletonList(oneEntryRootHash.encode())),
addItem1Command,
appendEntry1Command,
new RegisterCommand("assert-root-hash", Collections.singletonList(twoEntriesRootHash.encode()))
));
}
@Test
public void createRegisterSerialisationFormat_whenStartIsZero_returnsSystemEntries() {
HashValue rootHash = new HashValue(HashingAlgorithm.SHA256, "twoEntriesInRegisterHash");
when(register.getItemIterator(EntryType.system)).thenReturn(Arrays.asList(systemItem).iterator());
when(register.getItemIterator(0, 2)).thenReturn(Arrays.asList(item1, item2).iterator());
when(register.getEntryIterator(EntryType.system)).thenReturn(Arrays.asList(systemEntry).iterator());
when(register.getEntryIterator(0, 2)).thenReturn(Arrays.asList(entry1, entry2).iterator());
when(proofGenerator.getRootHash(2)).thenReturn(rootHash);
RegisterSerialisationFormat actualRSF = sutCreator.create(register, proofGenerator, 0, 2);
List<RegisterCommand> actualCommands = IteratorUtils.toList(actualRSF.getCommands());
assertThat(actualCommands.size(), equalTo(8));
assertThat(actualCommands, contains(
assertEmptyRootHashCommand,
addItem1Command,
addItem2Command,
addSystemItemCommand,
appendSystemEntryCommand,
appendEntry1Command,
appendEntry2Command,
new RegisterCommand("assert-root-hash", Collections.singletonList(rootHash.encode()))
));
}
@Test
public void createRegisterSerialisationFormat_throwsAnExceptionForUnknownMapperType() throws Exception {
when(register.getItemIterator(EntryType.user)).thenReturn(Arrays.asList(item1, item2).iterator());
when(register.getEntryIterator(EntryType.system)).thenReturn(Collections.emptyIterator());
when(register.getEntryIterator(EntryType.user)).thenReturn(Arrays.asList(entry1, entry2).iterator());
when(register.getItemIterator(EntryType.system)).thenReturn(Arrays.asList(systemItem).iterator());
when(proofGenerator.getRootHash()).thenReturn(new HashValue(HashingAlgorithm.SHA256, "1231234"));
expectedException.expect(RuntimeException.class);
expectedException.expectMessage("Mapper not registered for class: uk.gov.register.util.HashValue");
RSFCreator creatorWithoutMappers = new RSFCreator();
RegisterSerialisationFormat rsf = creatorWithoutMappers.create(register, proofGenerator);
IteratorUtils.toList(rsf.getCommands());
}
@Test
public void createRegisterSerialisationFormat_whenParametersEqual_returnsOnlyRootHash() {
HashValue rootHash = new HashValue(HashingAlgorithm.SHA256, "twoEntriesInRegisterHash");
when(proofGenerator.getRootHash(2)).thenReturn(rootHash);
RegisterSerialisationFormat actualRSF = sutCreator.create(register, proofGenerator, 2, 2);
List<RegisterCommand> actualCommands = IteratorUtils.toList(actualRSF.getCommands());
assertThat(actualCommands.size(), equalTo(1));
assertThat(actualCommands, contains(
new RegisterCommand("assert-root-hash", Collections.singletonList(rootHash.encode()))
));
}
@Test
public void createRegisterSerialisationFormat_whenParametersEqualAndZero_returnsSystemEntries() {
when(register.getItemIterator(EntryType.system)).thenReturn(Arrays.asList(systemItem).iterator());
when(register.getItemIterator(0, 0)).thenReturn(Collections.emptyIterator());
when(register.getEntryIterator(EntryType.system)).thenReturn(Arrays.asList(systemEntry).iterator());
when(register.getEntryIterator(0, 0)).thenReturn(Collections.emptyIterator());
when(proofGenerator.getRootHash(0)).thenReturn(emptyRegisterHash);
RegisterSerialisationFormat actualRSF = sutCreator.create(register, proofGenerator, 0, 0);
List<RegisterCommand> actualCommands = IteratorUtils.toList(actualRSF.getCommands());
assertThat(actualCommands.size(), equalTo(4));
assertThat(actualCommands, contains(
assertEmptyRootHashCommand,
addSystemItemCommand,
appendSystemEntryCommand,
assertEmptyRootHashCommand
));
}
}
|
origin-finkle/logs | internal/config/castinfight.go | <filename>internal/config/castinfight.go
package config
import (
"context"
"fmt"
"sync"
"github.com/origin-finkle/logs/internal/logger"
"github.com/origin-finkle/logs/internal/models"
"github.com/origin-finkle/logs/internal/models/remark"
"github.com/origin-finkle/logs/internal/wowhead"
)
var cifMutex sync.RWMutex
func GetCastInFight(ctx context.Context, id int64) (*models.CastInFight, error) {
ctx = logger.ContextWithLogger(ctx, logger.FromContext(ctx).WithField("spell_id", id))
cifMutex.RLock()
if v, ok := data.CastInFight[id]; ok {
cifMutex.RUnlock()
return v, nil
}
cifMutex.RUnlock()
spell, err := wowhead.GetSpell(ctx, id)
if err != nil {
logger.FromContext(ctx).WithError(err).Warnf("did not load item %d", id)
return nil, ErrCastInFightNotFound
}
cif := &models.CastInFight{
SpellID: spell.SpellID,
Name: spell.Name,
Rank: spell.Rank,
Display: true,
}
if cif.Rank == 0 {
cif.Rank = 1
}
switch true {
// TODO: differenciate items used
/*case cif.Rank > 0:
cif.Type = "spell"*/
default:
cif.Type = "spell"
}
SetCastInFight(cif)
postAddCIF(cif)
return cif, nil
}
func markCIFAsInvalid(lowerRanked, higherRanked *models.CastInFight) {
if lowerRanked.Invalid {
already := data.CastInFight[lowerRanked.SuggestedSpellID]
if already.Rank > higherRanked.Rank {
// do not update as the suggested spell has a higher rank than the current one
return
}
}
lowerRanked.Invalid = true
lowerRanked.InvalidReason = remark.Type_CastHigherRankAvailable
lowerRanked.SuggestedSpellID = higherRanked.SpellID
}
func postAddCIF(cif *models.CastInFight) {
cifMutex.RLock()
defer cifMutex.RUnlock()
// find similar cif, if rank < current one, then mark as invalid
for _, castInFight := range data.CastInFight {
if castInFight.Name == cif.Name {
if castInFight.Rank < cif.Rank {
markCIFAsInvalid(castInFight, cif)
} else if castInFight.Rank > cif.Rank {
markCIFAsInvalid(cif, castInFight)
}
}
}
}
func SetCastInFight(v *models.CastInFight) {
cifMutex.Lock()
defer cifMutex.Unlock()
v.TextRule = v.CommonConfig.String()
data.CastInFight[v.SpellID] = v
}
var (
ErrCastInFightNotFound = fmt.Errorf("cast in fight not found")
)
|
alinakazi/apache-royale-0.9.8-bin-js-swf | royale-compiler/compiler-jx/src/main/java/org/apache/royale/compiler/internal/codegen/mxml/royale/MXMLRoyaleEmitter.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.apache.royale.compiler.internal.codegen.mxml.royale;
import java.io.File;
import java.io.FilterWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Stack;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.royale.abc.ABCConstants;
import org.apache.royale.abc.instructionlist.InstructionList;
import org.apache.royale.abc.semantics.Instruction;
import org.apache.royale.abc.semantics.MethodInfo;
import org.apache.royale.abc.semantics.Name;
import org.apache.royale.abc.semantics.Namespace;
import org.apache.royale.abc.semantics.OneOperandInstruction;
import org.apache.royale.compiler.codegen.as.IASEmitter;
import org.apache.royale.compiler.codegen.js.IJSEmitter;
import org.apache.royale.compiler.codegen.js.IMappingEmitter;
import org.apache.royale.compiler.codegen.mxml.royale.IMXMLRoyaleEmitter;
import org.apache.royale.compiler.common.ASModifier;
import org.apache.royale.compiler.common.DependencyType;
import org.apache.royale.compiler.common.ISourceLocation;
import org.apache.royale.compiler.constants.IASKeywordConstants;
import org.apache.royale.compiler.constants.IASLanguageConstants;
import org.apache.royale.compiler.definitions.IClassDefinition;
import org.apache.royale.compiler.definitions.IDefinition;
import org.apache.royale.compiler.definitions.IFunctionDefinition;
import org.apache.royale.compiler.definitions.INamespaceDefinition;
import org.apache.royale.compiler.definitions.ITypeDefinition;
import org.apache.royale.compiler.internal.as.codegen.InstructionListNode;
import org.apache.royale.compiler.internal.codegen.as.ASEmitterTokens;
import org.apache.royale.compiler.internal.codegen.databinding.BindingDatabase;
import org.apache.royale.compiler.internal.codegen.databinding.BindingInfo;
import org.apache.royale.compiler.internal.codegen.databinding.FunctionWatcherInfo;
import org.apache.royale.compiler.internal.codegen.databinding.PropertyWatcherInfo;
import org.apache.royale.compiler.internal.codegen.databinding.StaticPropertyWatcherInfo;
import org.apache.royale.compiler.internal.codegen.databinding.WatcherInfoBase;
import org.apache.royale.compiler.internal.codegen.databinding.WatcherInfoBase.WatcherType;
import org.apache.royale.compiler.internal.codegen.databinding.XMLWatcherInfo;
import org.apache.royale.compiler.internal.codegen.js.JSEmitterTokens;
import org.apache.royale.compiler.internal.codegen.js.JSSessionModel.PropertyNodes;
import org.apache.royale.compiler.internal.codegen.js.JSSessionModel.BindableVarInfo;
import org.apache.royale.compiler.internal.codegen.js.royale.JSRoyaleEmitter;
import org.apache.royale.compiler.internal.codegen.js.royale.JSRoyaleEmitterTokens;
import org.apache.royale.compiler.internal.codegen.js.goog.JSGoogDocEmitter;
import org.apache.royale.compiler.internal.codegen.js.goog.JSGoogEmitterTokens;
import org.apache.royale.compiler.internal.codegen.js.jx.BindableEmitter;
import org.apache.royale.compiler.internal.codegen.js.jx.PackageFooterEmitter;
import org.apache.royale.compiler.internal.codegen.js.utils.EmitterUtils;
import org.apache.royale.compiler.internal.codegen.mxml.MXMLEmitter;
import org.apache.royale.compiler.internal.codegen.mxml.MXMLEmitterTokens;
import org.apache.royale.compiler.internal.driver.js.royale.JSCSSCompilationSession;
import org.apache.royale.compiler.internal.projects.RoyaleJSProject;
import org.apache.royale.compiler.internal.projects.RoyaleProject;
import org.apache.royale.compiler.internal.scopes.ASProjectScope;
import org.apache.royale.compiler.internal.targets.ITargetAttributes;
import org.apache.royale.compiler.internal.tree.as.FunctionCallNode;
import org.apache.royale.compiler.internal.tree.as.IdentifierNode;
import org.apache.royale.compiler.internal.tree.as.MemberAccessExpressionNode;
import org.apache.royale.compiler.internal.tree.as.VariableNode;
import org.apache.royale.compiler.internal.tree.mxml.MXMLDocumentNode;
import org.apache.royale.compiler.internal.tree.mxml.MXMLFileNode;
import org.apache.royale.compiler.internal.tree.mxml.MXMLFunctionNode;
import org.apache.royale.compiler.internal.tree.mxml.MXMLBindingNode;
import org.apache.royale.compiler.mxml.IMXMLLanguageConstants;
import org.apache.royale.compiler.problems.FileNotFoundProblem;
import org.apache.royale.compiler.projects.ICompilerProject;
import org.apache.royale.compiler.projects.IRoyaleProject;
import org.apache.royale.compiler.scopes.IDefinitionSet;
import org.apache.royale.compiler.tree.ASTNodeID;
import org.apache.royale.compiler.tree.as.*;
import org.apache.royale.compiler.tree.metadata.IMetaTagNode;
import org.apache.royale.compiler.tree.metadata.IMetaTagsNode;
import org.apache.royale.compiler.tree.mxml.*;
import org.apache.royale.compiler.units.ICompilationUnit;
import org.apache.royale.compiler.utils.DefinitionUtils;
import org.apache.royale.compiler.utils.NativeUtils;
import org.apache.royale.compiler.visitor.mxml.IMXMLBlockWalker;
import org.apache.royale.swc.ISWC;
import com.google.common.base.Joiner;
import com.google.common.io.Files;
import com.google.debugging.sourcemap.FilePosition;
/**
* @author <NAME>
*/
public class MXMLRoyaleEmitter extends MXMLEmitter implements
IMXMLRoyaleEmitter, IMappingEmitter
{
// the instances in a container
private ArrayList<MXMLDescriptorSpecifier> currentInstances;
private ArrayList<MXMLDescriptorSpecifier> currentPropertySpecifiers;
private ArrayList<MXMLDescriptorSpecifier> descriptorTree;
private MXMLDescriptorSpecifier propertiesTree;
private MXMLDescriptorSpecifier currentStateOverrides;
private ArrayList<MXMLEventSpecifier> events;
// all instances in the current document or subdocument
private ArrayList<MXMLDescriptorSpecifier> instances;
// all instances in the document AND its subdocuments
private ArrayList<MXMLDescriptorSpecifier> allInstances = new ArrayList<MXMLDescriptorSpecifier>();
private ArrayList<IMXMLScriptNode> scripts;
//private ArrayList<MXMLStyleSpecifier> styles;
private IClassDefinition classDefinition;
private IClassDefinition documentDefinition;
private ArrayList<String> usedNames = new ArrayList<String>();
private ArrayList<String> staticUsedNames = new ArrayList<String>();
private ArrayList<IMXMLMetadataNode> metadataNodes = new ArrayList<IMXMLMetadataNode>();
// separately track all fx:Declarations that are primitive types (fx:String, fx:Array)
private ArrayList<IMXMLInstanceNode> primitiveDeclarationNodes = new ArrayList<IMXMLInstanceNode>();
private int eventCounter;
private int idCounter;
private int bindingCounter;
private boolean inMXMLContent;
private IMXMLInstanceNode overrideInstanceToEmit;
private Stack<IMXMLStateNode> inStatesOverride = new Stack<IMXMLStateNode>();
private boolean makingSimpleArray;
private boolean inStaticInitializer;
private StringBuilder subDocuments = new StringBuilder();
private ArrayList<String> subDocumentNames = new ArrayList<String>();
private String interfaceList;
private boolean emitExports = true;
/**
* This keeps track of the entries in our temporary array of
* DeferredInstanceFromFunction objects that we CG to help with
* State override CG.
*
* Keys are Instance nodes,
* values are the array index where the deferred instance is:
*
* deferred instance = local3[ nodeToIndexMap.get(an instance) ]
*/
protected Map<IMXMLNode, Integer> nodeToIndexMap;
private SourceMapMapping lastMapping;
private List<SourceMapMapping> sourceMapMappings;
public List<SourceMapMapping> getSourceMapMappings()
{
return sourceMapMappings;
}
public MXMLRoyaleEmitter(FilterWriter out)
{
super(out);
sourceMapMappings = new ArrayList<SourceMapMapping>();
}
@Override
public String postProcess(String output)
{
IASEmitter asEmitter = ((IMXMLBlockWalker) getMXMLWalker()).getASEmitter();
ArrayList<String> asEmitterUsedNames = ((JSRoyaleEmitter)asEmitter).usedNames;
JSRoyaleEmitter fjs = (JSRoyaleEmitter)asEmitter;
String currentClassName = fjs.getModel().getCurrentClass().getQualifiedName();
ArrayList<String> removals = new ArrayList<String>();
for (String usedName : asEmitterUsedNames) {
//remove any internal component that has been registered with the other emitter's usedNames
if (usedName.startsWith(currentClassName+".") && subDocumentNames.contains(usedName.substring(currentClassName.length()+1))) {
removals.add(usedName);
}
}
for (String usedName : removals)
{
asEmitterUsedNames.remove(usedName);
}
RoyaleJSProject fjp = (RoyaleJSProject) getMXMLWalker().getProject();
if (fjp.config == null || fjp.config.isVerbose())
{
System.out.println(currentClassName + " as: " + asEmitterUsedNames.toString());
System.out.println(currentClassName + " mxml: " + usedNames.toString());
}
usedNames.addAll(asEmitterUsedNames);
ArrayList<String> asStaticEmitterUsedNames = ((JSRoyaleEmitter)asEmitter).staticUsedNames;
removals = new ArrayList<String>();
for (String usedName : asStaticEmitterUsedNames) {
//remove any internal component that has been registered with the other emitter's usedNames
if (usedName.startsWith(currentClassName+".") && subDocumentNames.contains(usedName.substring(currentClassName.length()+1))) {
removals.add(usedName);
}
}
for (String usedName : removals)
{
asStaticEmitterUsedNames.remove(usedName);
}
if (fjp.config == null || fjp.config.isVerbose())
{
System.out.println(currentClassName + " as: " + asStaticEmitterUsedNames.toString());
System.out.println(currentClassName + " mxml: " + staticUsedNames.toString());
}
staticUsedNames.addAll(asStaticEmitterUsedNames);
boolean foundXML = false;
String[] lines = output.split("\n");
ArrayList<String> finalLines = new ArrayList<String>();
int endRequires = -1;
boolean sawRequires = false;
boolean stillSearching = true;
int provideIndex = -1;
ArrayList<String> namesToAdd = new ArrayList<String>();
ArrayList<String> foundRequires = new ArrayList<String>();
int len = lines.length;
for (int i = 0; i < len; i++)
{
String line = lines[i];
if (stillSearching)
{
if (provideIndex == -1 || !sawRequires)
{
int c = line.indexOf(JSGoogEmitterTokens.GOOG_PROVIDE.getToken());
if (c != -1)
{
// if zero requires are found, require Language after the
// call to goog.provide
provideIndex = i + 1;
}
}
int c = line.indexOf(JSGoogEmitterTokens.GOOG_REQUIRE.getToken());
if (c > -1)
{
int c2 = line.indexOf(")");
String s = line.substring(c + 14, c2 - 1);
if (s.equals(IASLanguageConstants.XML))
{
foundXML = true;
}
sawRequires = true;
foundRequires.add(s);
if (!usedNames.contains(s))
{
removeLineFromMappings(i);
continue;
}
}
else if (sawRequires)
{
// append info() structure if main CU
ICompilerProject project = getMXMLWalker().getProject();
RoyaleJSProject royaleProject = null;
if (project instanceof RoyaleJSProject)
royaleProject = (RoyaleJSProject) project;
stillSearching = false;
for (String usedName :usedNames) {
if (!foundRequires.contains(usedName)) {
if (usedName.equals(classDefinition.getQualifiedName())) continue;
if (((JSRoyaleEmitter) asEmitter).getModel().isInternalClass(usedName)) continue;
if (subDocumentNames.contains(usedName)) continue;
if (royaleProject != null)
{
if (!isGoogProvided(usedName))
{
continue;
}
ICompilationUnit cu = royaleProject.resolveQNameToCompilationUnit(usedName);
if (cu == null)
{
System.out.println("didn't find CompilationUnit for " + usedName);
}
}
namesToAdd.add(usedName);
}
}
for (String nameToAdd : namesToAdd) {
finalLines.add(createRequireLine(nameToAdd,false));
addLineToMappings(i);
}
endRequires = finalLines.size();
}
}
finalLines.add(line);
}
boolean needXML = ((RoyaleJSProject)(((IMXMLBlockWalker) getMXMLWalker()).getProject())).needXML;
if (needXML && !foundXML)
{
StringBuilder appendString = new StringBuilder();
appendString.append(JSGoogEmitterTokens.GOOG_REQUIRE.getToken());
appendString.append(ASEmitterTokens.PAREN_OPEN.getToken());
appendString.append(ASEmitterTokens.SINGLE_QUOTE.getToken());
appendString.append(IASLanguageConstants.XML);
appendString.append(ASEmitterTokens.SINGLE_QUOTE.getToken());
appendString.append(ASEmitterTokens.PAREN_CLOSE.getToken());
appendString.append(ASEmitterTokens.SEMICOLON.getToken());
finalLines.add(endRequires, appendString.toString());
addLineToMappings(endRequires);
endRequires++;
}
// append info() structure if main CU
ICompilerProject project = getMXMLWalker().getProject();
if (project instanceof RoyaleJSProject)
{
RoyaleJSProject royaleProject = (RoyaleJSProject) project;
if (royaleProject.mainCU != null)
{
String mainDef = null;
try {
mainDef = royaleProject.mainCU.getQualifiedNames().get(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String thisDef = documentDefinition.getQualifiedName();
if (mainDef != null && mainDef.equals(thisDef))
{
String infoInject = "\n\n" + thisDef + ".prototype.info = function() {\n" +
" return { ";
String sep = "";
Set<String> mixins = royaleProject.mixinClassNames;
if (mixins.size() > 0)
{
String mixinInject = "\"mixins\": [";
boolean firstOne = true;
for (String mixin : mixins)
{
if (!isGoogProvided(mixin))
{
continue;
}
if (!firstOne)
{
mixinInject += ", ";
}
mixinInject += mixin;
firstOne = false;
StringBuilder appendString = new StringBuilder();
appendString.append(JSGoogEmitterTokens.GOOG_REQUIRE.getToken());
appendString.append(ASEmitterTokens.PAREN_OPEN.getToken());
appendString.append(ASEmitterTokens.SINGLE_QUOTE.getToken());
appendString.append(mixin);
appendString.append(ASEmitterTokens.SINGLE_QUOTE.getToken());
appendString.append(ASEmitterTokens.PAREN_CLOSE.getToken());
appendString.append(ASEmitterTokens.SEMICOLON.getToken());
finalLines.add(endRequires, appendString.toString());
addLineToMappings(endRequires);
endRequires++;
}
mixinInject += "]";
infoInject += mixinInject;
sep = ",\n";
}
Map<String, String> aliases = royaleProject.remoteClassAliasMap;
if (aliases != null && aliases.size() > 0)
{
String aliasInject = sep + "\"remoteClassAliases\": {";
boolean firstOne = true;
for (String className : aliases.keySet())
{
if (!isGoogProvided(className))
{
continue;
}
if (!firstOne)
{
aliasInject += ", ";
}
aliasInject += "\"" + className + "\": ";
String alias = aliases.get(className);
aliasInject += "\"" + alias + "\"";
firstOne = false;
StringBuilder appendString = new StringBuilder();
appendString.append(JSGoogEmitterTokens.GOOG_REQUIRE.getToken());
appendString.append(ASEmitterTokens.PAREN_OPEN.getToken());
appendString.append(ASEmitterTokens.SINGLE_QUOTE.getToken());
appendString.append(className);
appendString.append(ASEmitterTokens.SINGLE_QUOTE.getToken());
appendString.append(ASEmitterTokens.PAREN_CLOSE.getToken());
appendString.append(ASEmitterTokens.SEMICOLON.getToken());
finalLines.add(endRequires, appendString.toString());
addLineToMappings(endRequires);
endRequires++;
}
aliasInject += "}";
infoInject += aliasInject;
sep = ",\n";
}
Collection<String> locales = royaleProject.getLocales();
if (locales.size() > 0)
{
String localeInject = sep + "\"compiledLocales\": [";
boolean firstOne = true;
String[] localeNames = new String[locales.size()];
locales.toArray(localeNames);
for (String locale : localeNames)
{
if (!firstOne)
{
localeInject += ", ";
}
localeInject += "\"" + locale + "\"";
firstOne = false;
}
localeInject += "]";
infoInject += localeInject;
sep = ",\n";
}
List<String> bundles = royaleProject.compiledResourceBundleNames;
if (bundles.size() > 0)
{
String bundleInject = sep + "\"compiledResourceBundleNames\": [";
boolean firstOne = true;
for (String bundle : bundles)
{
if (!firstOne)
{
bundleInject += ", ";
}
bundleInject += "\"" + bundle + "\"";
firstOne = false;
}
bundleInject += "]";
infoInject += bundleInject;
sep = ",\n";
}
List<String> bundleClasses = royaleProject.compiledResourceBundleClasses;
if (bundles.size() > 0)
{
for (String bundleClass : bundleClasses)
{
StringBuilder appendString = new StringBuilder();
appendString.append(JSGoogEmitterTokens.GOOG_REQUIRE.getToken());
appendString.append(ASEmitterTokens.PAREN_OPEN.getToken());
appendString.append(ASEmitterTokens.SINGLE_QUOTE.getToken());
appendString.append(bundleClass);
appendString.append(ASEmitterTokens.SINGLE_QUOTE.getToken());
appendString.append(ASEmitterTokens.PAREN_CLOSE.getToken());
appendString.append(ASEmitterTokens.SEMICOLON.getToken());
finalLines.add(endRequires, appendString.toString());
addLineToMappings(endRequires);
endRequires++;
}
}
boolean isMX = false;
List<ISWC> swcs = royaleProject.getLibraries();
for (ISWC swc : swcs)
{
if (swc.getSWCFile().getName().equalsIgnoreCase("MX.swc"))
{
isMX = true;
break;
}
}
if (isMX)
{
MXMLDocumentNode mxmlDoc = (MXMLDocumentNode)documentDefinition.getNode();
if (mxmlDoc != null)
{
MXMLFileNode mxmlFile = (MXMLFileNode)mxmlDoc.getParent();
if (mxmlFile != null)
{
ITargetAttributes attrs = mxmlFile.getTargetAttributes(royaleProject);
if (attrs != null && attrs.getUsePreloader() != null)
{
String preloaderInject = sep + IMXMLLanguageConstants.ATTRIBUTE_USE_PRELOADER + ": ";
preloaderInject += attrs.getUsePreloader() == Boolean.TRUE ? "true" : "false";
sep = ",\n";
infoInject += preloaderInject;
}
}
}
}
String contextRoot = royaleProject.getServciesContextRoot();
if (contextRoot != null)
{
String contextInject = sep + "\"contextRoot\"" + ": ";
contextInject += "'" + contextRoot.trim() + "'";
sep = ",\n";
infoInject += contextInject;
}
String servicesPath = royaleProject.getServicesXMLPath();
if (servicesPath != null)
{
File servicesFile = new File(servicesPath);
if (!servicesFile.exists())
{
FileNotFoundProblem prob = new FileNotFoundProblem(servicesPath);
royaleProject.getProblems().add(prob);
}
else
{
// should use XML parser to skip over comments
// but this will work for now
List<String> fileLines = null;
try {
fileLines = Files.readLines(new File(servicesPath), Charset.forName("utf8"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
StringBuffer sb = new StringBuffer();
boolean inComment = false;
boolean inChannels = false;
for (String s : fileLines)
{
s = s.trim();
if (s.contains("<!--"))
{
if (!s.contains("-->"))
inComment = true;
continue;
}
if (inComment)
{
if (s.contains("-->"))
inComment = false;
continue;
}
if (s.contains("service-include"))
{
int c = s.indexOf("file-path");
c = s.indexOf("\"", c);
int c2 = s.indexOf("\"", c + 1);
String filePath = s.substring(c + 1, c2);
File subFile = new File(servicesFile.getParentFile(), filePath);
List<String> subfileLines;
try {
subfileLines = Files.readLines(subFile, Charset.forName("utf8"));
s = getSubFileContent(subfileLines);
sb.append(s);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
sb.append(s + " ");
if (s.contains("<channel-definition"))
inChannels = true;
if (s.contains("<endpoint"))
inChannels = false;
if (inChannels && s.contains("class"))
{
int c = s.indexOf("class");
c = s.indexOf("\"", c);
int c2 = s.indexOf("\"", c + 1);
String className = s.substring(c + 1, c2);
StringBuilder appendString = new StringBuilder();
appendString.append(JSGoogEmitterTokens.GOOG_REQUIRE.getToken());
appendString.append(ASEmitterTokens.PAREN_OPEN.getToken());
appendString.append(ASEmitterTokens.SINGLE_QUOTE.getToken());
appendString.append(className);
appendString.append(ASEmitterTokens.SINGLE_QUOTE.getToken());
appendString.append(ASEmitterTokens.PAREN_CLOSE.getToken());
appendString.append(ASEmitterTokens.SEMICOLON.getToken());
finalLines.add(endRequires, appendString.toString());
addLineToMappings(endRequires);
endRequires++;
}
}
}
String servicesInject = sep + "\"servicesConfig\"" + ": ";
servicesInject += "'" + sb.toString().trim() + "'";
sep = ",\n";
infoInject += servicesInject;
}
}
infoInject += "}};";
finalLines.add(infoInject);
int newLineIndex = 0;
while((newLineIndex = infoInject.indexOf('\n', newLineIndex)) != -1)
{
addLineToMappings(finalLines.size());
newLineIndex++;
}
String cssInject = "\n\n" + thisDef + ".prototype.cssData = [";
JSCSSCompilationSession cssSession = (JSCSSCompilationSession) royaleProject.getCSSCompilationSession();
String s = cssSession.getEncodedCSS();
if (s != null)
{
int reqidx = s.indexOf(JSGoogEmitterTokens.GOOG_REQUIRE.getToken());
if (reqidx != -1)
{
String cssRequires = s.substring(reqidx);
s = s.substring(0, reqidx - 1);
String[] cssRequireLines = cssRequires.split("\n");
for(String require : cssRequireLines)
{
finalLines.add(endRequires, require);
addLineToMappings(endRequires);
endRequires++;
}
}
cssInject += s;
finalLines.add(cssInject);
newLineIndex = 0;
while((newLineIndex = cssInject.indexOf('\n', newLineIndex)) != -1)
{
addLineToMappings(finalLines.size());
newLineIndex++;
}
}
}
}
}
if (staticUsedNames.size() > 0)
{
if (staticUsedNames.size() > 1 ||
!staticUsedNames.get(0).equals(currentClassName))
{
StringBuilder sb = new StringBuilder();
sb.append(JSGoogEmitterTokens.ROYALE_STATIC_DEPENDENCY_LIST.getToken());
boolean firstDependency = true;
for (String staticName : staticUsedNames)
{
if (currentClassName.equals(staticName))
continue;
if (!firstDependency)
sb.append(",");
firstDependency = false;
sb.append(staticName);
}
sb.append("*/");
finalLines.add(provideIndex, sb.toString());
addLineToMappings(provideIndex);
}
}
return Joiner.on("\n").join(finalLines);
}
private String getSubFileContent(List<String> subfileLines) {
StringBuffer sb = new StringBuffer();
for (String s : subfileLines)
{
s = s.trim();
if (s.startsWith("<?xml"))
continue;
else
{
sb.append(s + " ");
}
}
return sb.toString();
}
public void startMapping(ISourceLocation node)
{
startMapping(node, node.getLine(), node.getColumn());
}
public void startMapping(ISourceLocation node, int line, int column)
{
if (isBufferWrite())
{
return;
}
if (lastMapping != null)
{
FilePosition sourceStartPosition = lastMapping.sourceStartPosition;
throw new IllegalStateException("Cannot start new mapping when another mapping is already started. "
+ "Previous mapping at Line " + sourceStartPosition.getLine()
+ " and Column " + sourceStartPosition.getColumn()
+ " in file " + lastMapping.sourcePath);
}
String sourcePath = node.getSourcePath();
if (sourcePath == null)
{
//if the source path is null, this node may have been generated by
//the compiler automatically. for example, an untyped variable will
//have a node for the * type.
if (node instanceof IASNode)
{
IASNode parentNode = ((IASNode) node).getParent();
if (parentNode != null)
{
//try the parent node
startMapping(parentNode, line, column);
return;
}
}
}
SourceMapMapping mapping = new SourceMapMapping();
mapping.sourcePath = sourcePath;
mapping.sourceStartPosition = new FilePosition(line, column);
mapping.destStartPosition = new FilePosition(getCurrentLine(), getCurrentColumn());
lastMapping = mapping;
}
public void startMapping(ISourceLocation node, ISourceLocation afterNode)
{
startMapping(node, afterNode.getEndLine(), afterNode.getEndColumn());
}
public void endMapping(ISourceLocation node)
{
if (isBufferWrite())
{
return;
}
if (lastMapping == null)
{
throw new IllegalStateException("Cannot end mapping when a mapping has not been started");
}
lastMapping.destEndPosition = new FilePosition(getCurrentLine(), getCurrentColumn());
sourceMapMappings.add(lastMapping);
lastMapping = null;
}
/**
* Adjusts the line numbers saved in the source map when a line should be
* added during post processing.
*
* @param lineIndex
*/
protected void addLineToMappings(int lineIndex)
{
for (SourceMapMapping mapping : sourceMapMappings)
{
FilePosition destStartPosition = mapping.destStartPosition;
int startLine = destStartPosition.getLine();
if(startLine > lineIndex)
{
mapping.destStartPosition = new FilePosition(startLine + 1, destStartPosition.getColumn());
FilePosition destEndPosition = mapping.destEndPosition;
mapping.destEndPosition = new FilePosition(destEndPosition.getLine() + 1, destEndPosition.getColumn());
}
}
}
/**
* Adjusts the line numbers saved in the source map when a line should be
* removed during post processing.
*
* @param lineIndex
*/
protected void removeLineFromMappings(int lineIndex)
{
for (SourceMapMapping mapping : sourceMapMappings)
{
FilePosition destStartPosition = mapping.destStartPosition;
int startLine = destStartPosition.getLine();
if(startLine > lineIndex)
{
mapping.destStartPosition = new FilePosition(startLine - 1, destStartPosition.getColumn());
FilePosition destEndPosition = mapping.destEndPosition;
mapping.destEndPosition = new FilePosition(destEndPosition.getLine() - 1, destEndPosition.getColumn());
}
}
}
@Override
protected String getIndent(int numIndent)
{
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < numIndent; i++)
sb.append(JSRoyaleEmitterTokens.INDENT.getToken());
return sb.toString();
}
//--------------------------------------------------------------------------
@Override
public void emitDeclarations(IMXMLDeclarationsNode node)
{
inMXMLContent = true;
boolean reusingDescriptor = false;
MXMLDescriptorSpecifier currentInstance = getCurrentDescriptor("i");
MXMLDescriptorSpecifier currentPropertySpecifier = new MXMLDescriptorSpecifier();
currentPropertySpecifier.isProperty = true;
currentPropertySpecifier.name = "mxmlContent";
currentPropertySpecifier.parent = currentInstance;
if (currentInstance == null)
{
ArrayList<MXMLDescriptorSpecifier> specList =
(currentInstance == null) ? descriptorTree : currentInstance.propertySpecifiers;
for (MXMLDescriptorSpecifier ds : specList)
{
if (ds.name.equals("mxmlContent"))
{
currentPropertySpecifier = ds;
reusingDescriptor = true;
break;
}
}
}
if (!reusingDescriptor)
descriptorTree.add(currentPropertySpecifier);
moveDown(false, currentInstance, currentPropertySpecifier);
super.emitDeclarations(node);
moveUp(false, false);
inMXMLContent = false;
}
@Override
public void emitDocument(IMXMLDocumentNode node)
{
RoyaleJSProject fjp = (RoyaleJSProject) getMXMLWalker().getProject();
if (fjp.config != null)
emitExports = fjp.config.getExportPublicSymbols();
descriptorTree = new ArrayList<MXMLDescriptorSpecifier>();
propertiesTree = new MXMLDescriptorSpecifier();
events = new ArrayList<MXMLEventSpecifier>();
instances = new ArrayList<MXMLDescriptorSpecifier>();
scripts = new ArrayList<IMXMLScriptNode>();
//styles = new ArrayList<MXMLStyleSpecifier>();
currentInstances = new ArrayList<MXMLDescriptorSpecifier>();
currentStateOverrides = new MXMLDescriptorSpecifier();
currentPropertySpecifiers = new ArrayList<MXMLDescriptorSpecifier>();
eventCounter = 0;
idCounter = 0;
bindingCounter = 0;
// visit MXML
IClassDefinition cdef = node.getClassDefinition();
classDefinition = cdef;
documentDefinition = cdef;
// TODO (mschmalle) will remove this cast as more things get abstracted
JSRoyaleEmitter fjs = (JSRoyaleEmitter) ((IMXMLBlockWalker) getMXMLWalker())
.getASEmitter();
fjs.setBuilder(getBuilder());
fjs.getModel().setCurrentClass(cdef);
// visit tags
final int len = node.getChildCount();
for (int i = 0; i < len; i++)
{
getMXMLWalker().walk(node.getChild(i));
}
String cname = node.getFileNode().getName();
emitHeader(node);
emitClassDeclStart(cname, node.getBaseClassName(), false);
emitComplexInitializers(node);
emitPropertyDecls();
emitClassDeclEnd(cname, node.getBaseClassName());
emitDeclarationVariables();
// emitMetaData(cdef);
write(subDocuments.toString());
writeNewline();
emitScripts();
fjs.getBindableEmitter().emit(cdef);
fjs.getAccessorEmitter().emit(cdef);
emitEvents(cname);
emitComplexStaticInitializers(node);
emitPropertyGetterSetters(cname);
emitMXMLDescriptorFuncs(cname);
emitBindingData(cname, cdef);
emitMetaData(cdef);
emitSourceMapDirective(node);
}
public void emitDeclarationVariables()
{
for (IMXMLInstanceNode node : primitiveDeclarationNodes)
{
String id = node.getEffectiveID();
writeNewline();
writeNewline("/**");
writeNewline(" * @export");
writeNewline(" * @type {" + JSGoogDocEmitter.convertASTypeToJSType(formatQualifiedName(node.getName()), "") + "}");
writeNewline(" */");
String cname = node.getFileNode().getName();
write(cname);
write(ASEmitterTokens.MEMBER_ACCESS);
write(JSEmitterTokens.PROTOTYPE);
write(ASEmitterTokens.MEMBER_ACCESS);
write(id);
writeNewline(ASEmitterTokens.SEMICOLON);
}
}
public void emitSubDocument(IMXMLComponentNode node)
{
ArrayList<MXMLDescriptorSpecifier> oldDescriptorTree;
MXMLDescriptorSpecifier oldPropertiesTree;
MXMLDescriptorSpecifier oldStateOverrides;
ArrayList<MXMLEventSpecifier> oldEvents;
ArrayList<IMXMLScriptNode> oldScripts;
ArrayList<MXMLDescriptorSpecifier> oldCurrentInstances;
ArrayList<MXMLDescriptorSpecifier> oldInstances;
ArrayList<MXMLDescriptorSpecifier> oldCurrentPropertySpecifiers;
int oldEventCounter;
int oldIdCounter;
boolean oldInMXMLContent;
oldDescriptorTree = descriptorTree;
descriptorTree = new ArrayList<MXMLDescriptorSpecifier>();
oldPropertiesTree = propertiesTree;
propertiesTree = new MXMLDescriptorSpecifier();
oldInMXMLContent = inMXMLContent;
inMXMLContent = false;
oldEvents = events;
events = new ArrayList<MXMLEventSpecifier>();
oldInstances = instances;
instances = new ArrayList<MXMLDescriptorSpecifier>();
oldScripts = scripts;
scripts = new ArrayList<IMXMLScriptNode>();
//styles = new ArrayList<MXMLStyleSpecifier>();
oldCurrentInstances = currentInstances;
currentInstances = new ArrayList<MXMLDescriptorSpecifier>();
oldCurrentPropertySpecifiers = currentPropertySpecifiers;
currentPropertySpecifiers = new ArrayList<MXMLDescriptorSpecifier>();
oldStateOverrides = currentStateOverrides;
currentStateOverrides = new MXMLDescriptorSpecifier();
oldEventCounter = eventCounter;
eventCounter = 0;
oldIdCounter = idCounter;
idCounter = 0;
// visit MXML
IClassDefinition oldClassDef = classDefinition;
IClassDefinition cdef = node.getContainedClassDefinition();
classDefinition = cdef;
IASEmitter asEmitter = ((IMXMLBlockWalker) getMXMLWalker())
.getASEmitter();
((JSRoyaleEmitter) asEmitter).getModel().pushClass(cdef);
IASNode classNode = node.getContainedClassDefinitionNode();
String cname = cdef.getQualifiedName();
String baseClassName = cdef.getBaseClassAsDisplayString();
subDocumentNames.add(cname);
// visit tags
final int len = classNode.getChildCount();
for (int i = 0; i < len; i++)
{
getMXMLWalker().walk(classNode.getChild(i));
}
((JSRoyaleEmitter) asEmitter).mxmlEmitter = this;
emitClassDeclStart(cname, baseClassName, false);
emitComplexInitializers(classNode);
emitPropertyDecls();
emitClassDeclEnd(cname, baseClassName);
emitMetaData(cdef);
emitScripts();
emitEvents(cname);
emitPropertyGetterSetters(cname);
emitMXMLDescriptorFuncs(cname);
emitBindingData(cname, cdef);
write(((JSRoyaleEmitter) asEmitter).stringifyDefineProperties(cdef));
descriptorTree = oldDescriptorTree;
propertiesTree = oldPropertiesTree;
currentStateOverrides = oldStateOverrides;
events = oldEvents;
scripts = oldScripts;
currentInstances = oldCurrentInstances;
allInstances.addAll(instances);
instances = oldInstances;
currentPropertySpecifiers = oldCurrentPropertySpecifiers;
eventCounter = oldEventCounter;
idCounter = oldIdCounter;
inMXMLContent = oldInMXMLContent;
classDefinition = oldClassDef;
((JSRoyaleEmitter) asEmitter).getModel().popClass();
((JSRoyaleEmitter) asEmitter).mxmlEmitter = null;
}
@Override
public void emitMetadata(IMXMLMetadataNode node)
{
metadataNodes.add(node);
}
public void emitSourceMapDirective(ITypeNode node)
{
IMXMLBlockWalker walker = (IMXMLBlockWalker) getMXMLWalker();
IJSEmitter jsEmitter = (IJSEmitter) walker.getASEmitter();
jsEmitter.emitSourceMapDirective(node);
}
//--------------------------------------------------------------------------
protected void emitClassDeclStart(String cname, String baseClassName,
boolean indent)
{
writeNewline();
writeNewline("/**");
writeNewline(" * @constructor");
writeNewline(" * @extends {" + formatQualifiedName(baseClassName) + "}");
if (interfaceList != null && interfaceList.length() > 0)
{
String[] interfaces = interfaceList.split(",");
for (String iface : interfaces)
{
writeNewline(" * @implements {" + formatQualifiedName(iface.trim()) + "}");
}
}
writeNewline(" */");
writeToken(formatQualifiedName(cname));
writeToken(ASEmitterTokens.EQUAL);
write(ASEmitterTokens.FUNCTION);
write(ASEmitterTokens.PAREN_OPEN);
writeToken(ASEmitterTokens.PAREN_CLOSE);
if (indent)
indentPush();
writeNewline(ASEmitterTokens.BLOCK_OPEN, true);
write(formatQualifiedName(cname));
write(ASEmitterTokens.MEMBER_ACCESS);
write(JSGoogEmitterTokens.GOOG_BASE);
write(ASEmitterTokens.PAREN_OPEN);
write(ASEmitterTokens.THIS);
writeToken(ASEmitterTokens.COMMA);
write(ASEmitterTokens.SINGLE_QUOTE);
write(JSGoogEmitterTokens.GOOG_CONSTRUCTOR);
write(ASEmitterTokens.SINGLE_QUOTE);
write(ASEmitterTokens.PAREN_CLOSE);
writeNewline(ASEmitterTokens.SEMICOLON);
}
//--------------------------------------------------------------------------
protected void emitClassDeclEnd(String cname, String baseClassName)
{
writeNewline();
writeNewline("/**");
writeNewline(" * @private");
writeNewline(" * @type {Array}");
writeNewline(" */");
writeNewline("this.mxmldd;");
// top level is 'mxmlContent', skip it...
if (currentStateOverrides.propertySpecifiers.size() > 0)
{
MXMLDescriptorSpecifier root = currentStateOverrides;
root.isTopNode = true;
collectExportedNames(root);
writeNewline("/**");
if (emitExports)
writeNewline(" * @export");
writeNewline(" * @type {Array}");
writeNewline(" */");
writeNewline("this.mxmlsd = " + ASEmitterTokens.SQUARE_OPEN.getToken());
indentPush();
write(root.outputStateDescriptors(false));
write("null");
write(ASEmitterTokens.SQUARE_CLOSE);
indentPop();
writeNewline(ASEmitterTokens.SEMICOLON);
}
writeNewline();
writeNewline("/**");
writeNewline(" * @private");
writeNewline(" * @type {Array}");
writeNewline(" */");
indentPop();
writeNewline("this.mxmldp;");
if (propertiesTree.propertySpecifiers.size() > 0 ||
propertiesTree.eventSpecifiers.size() > 0)
{
indentPush();
writeNewline();
write("this.generateMXMLAttributes");
write(ASEmitterTokens.PAREN_OPEN);
indentPush();
writeNewline(ASEmitterTokens.SQUARE_OPEN);
MXMLDescriptorSpecifier root = propertiesTree;
root.isTopNode = true;
for(int i = 0; i < getCurrentIndent(); i++)
{
root.indentPush();
}
write(root.output(true));
indentPop();
writeNewline();
collectExportedNames(root);
write(ASEmitterTokens.SQUARE_CLOSE);
write(ASEmitterTokens.PAREN_CLOSE);
writeNewline(ASEmitterTokens.SEMICOLON);
indentPop();
writeNewline();
}
write(ASEmitterTokens.BLOCK_CLOSE);
writeNewline(ASEmitterTokens.SEMICOLON);
write(JSGoogEmitterTokens.GOOG_INHERITS);
write(ASEmitterTokens.PAREN_OPEN);
write(formatQualifiedName(cname));
writeToken(ASEmitterTokens.COMMA);
write(formatQualifiedName(baseClassName));
write(ASEmitterTokens.PAREN_CLOSE);
writeNewline(ASEmitterTokens.SEMICOLON);
writeNewline();
writeNewline();
writeNewline();
}
//--------------------------------------------------------------------------
protected void emitMetaData(IClassDefinition cdef)
{
String cname = cdef.getQualifiedName();
writeNewline("/**");
writeNewline(" * Metadata");
writeNewline(" *");
writeNewline(" * @type {Object.<string, Array.<Object>>}");
writeNewline(" */");
write(formatQualifiedName(cname) + ".prototype.ROYALE_CLASS_INFO = { names: [{ name: '");
write(cdef.getBaseName());
write("', qName: '");
write(formatQualifiedName(cname));
write("'");
writeToken(ASEmitterTokens.COMMA);
write(JSRoyaleEmitterTokens.ROYALE_CLASS_INFO_KIND);
writeToken(ASEmitterTokens.COLON);
write(ASEmitterTokens.SINGLE_QUOTE);
write(JSRoyaleEmitterTokens.ROYALE_CLASS_INFO_CLASS_KIND);
writeToken(ASEmitterTokens.SINGLE_QUOTE);
write(" }]");
if (interfaceList != null)
{
write(", interfaces: [");
write(interfaceList);
write("]");
}
write(" };");
emitReflectionData(cdef);
writeNewline();
writeNewline();
}
private void emitReflectionData(IClassDefinition cdef)
{
JSRoyaleEmitter asEmitter = (JSRoyaleEmitter)((IMXMLBlockWalker) getMXMLWalker()).getASEmitter();
RoyaleJSProject fjs = (RoyaleJSProject) getMXMLWalker().getProject();
ArrayList<String> exportProperties = new ArrayList<String>();
ArrayList<String> exportSymbols = new ArrayList<String>();
Set<String> exportMetadata = Collections.<String> emptySet();
if (fjs.config != null)
exportMetadata = fjs.config.getCompilerKeepCodeWithMetadata();
ArrayList<PackageFooterEmitter.VariableData> varData = new ArrayList<PackageFooterEmitter.VariableData>();
// vars can only come from script blocks and decls?
for (IMXMLInstanceNode declNode : primitiveDeclarationNodes)
{
PackageFooterEmitter.VariableData data = asEmitter.packageFooterEmitter.new VariableData();
varData.add(data);
data.name = declNode.getEffectiveID();
data.isStatic = false;
String qualifiedTypeName = declNode.getName();
data.type = (qualifiedTypeName);
}
List<IVariableNode> vars = asEmitter.getModel().getVars();
for (IVariableNode varNode : vars)
{
String ns = varNode.getNamespace();
if (ns == IASKeywordConstants.PUBLIC && !varNode.isConst())
{
PackageFooterEmitter.VariableData data = asEmitter.packageFooterEmitter.new VariableData();
varData.add(data);
data.name = varNode.getName();
data.isStatic = varNode.hasModifier(ASModifier.STATIC);
String qualifiedTypeName = varNode.getVariableTypeNode().resolveType(getMXMLWalker().getProject()).getQualifiedName();
data.type = (qualifiedTypeName);
IMetaTagsNode metaData = varNode.getMetaTags();
if (metaData != null)
{
IMetaTagNode[] tags = metaData.getAllTags();
if (tags.length > 0)
{
data.metaData = tags;
for (IMetaTagNode tag : tags)
{
String tagName = tag.getTagName();
if (exportMetadata.contains(tagName))
{
if (data.isStatic)
exportSymbols.add(data.name);
else
exportProperties.add(data.name);
}
}
}
}
}
}
ArrayList<PackageFooterEmitter.AccessorData> accessorData = new ArrayList<PackageFooterEmitter.AccessorData>();
HashMap<String, PropertyNodes> accessors = asEmitter.getModel().getPropertyMap();
//instance accessors
collectAccessors(accessors,accessorData,cdef);
accessors = asEmitter.getModel().getStaticPropertyMap();
//static accessors
collectAccessors(accessors,accessorData,cdef);
//additional bindables
HashMap<String, BindableVarInfo> bindableVars = asEmitter.getModel().getBindableVars();
for (String varName : bindableVars.keySet())
{
BindableVarInfo bindableVarInfo = bindableVars.get(varName);
String ns = bindableVarInfo.namespace;
if (ns == IASKeywordConstants.PUBLIC)
{
PackageFooterEmitter.AccessorData data = asEmitter.packageFooterEmitter.new AccessorData();
accessorData.add(data);
data.name = varName;
data.isStatic = bindableVarInfo.isStatic;
data.type = bindableVarInfo.type;
data.declaredBy = cdef.getQualifiedName();
data.access = "readwrite";
if (bindableVarInfo.metaTags != null) {
if (bindableVarInfo.metaTags.length > 0)
data.metaData = bindableVarInfo.metaTags;
}
}
}
for (MXMLDescriptorSpecifier instance : instances)
{
if (instance.id != null)
{
PackageFooterEmitter.AccessorData data = asEmitter.packageFooterEmitter.new AccessorData();
accessorData.add(data);
data.name = instance.id;
data.type = instance.name;
data.access = "readwrite";
data.declaredBy = cdef.getQualifiedName();
}
}
ArrayList<PackageFooterEmitter.MethodData> methodData = new ArrayList<PackageFooterEmitter.MethodData>();
List<IFunctionNode> methods = asEmitter.getModel().getMethods();
for (IFunctionNode methodNode : methods)
{
String ns = methodNode.getNamespace();
if (ns == IASKeywordConstants.PUBLIC)
{
PackageFooterEmitter.MethodData data = asEmitter.packageFooterEmitter.new MethodData();
methodData.add(data);
data.name = methodNode.getName();
String qualifiedTypeName = methodNode.getReturnType();
if (!(qualifiedTypeName.equals("") || qualifiedTypeName.equals("void"))) {
qualifiedTypeName = methodNode.getReturnTypeNode().resolveType(fjs).getQualifiedName();;
}
data.type = qualifiedTypeName;
data.declaredBy = cdef.getQualifiedName();
data.isStatic = methodNode.hasModifier(ASModifier.STATIC);
IParameterNode[] paramNodes = methodNode.getParameterNodes();
if (paramNodes != null && paramNodes.length > 0) {
data.parameters = paramNodes;
}
IMetaTagsNode metaData = methodNode.getMetaTags();
if (metaData != null)
{
IMetaTagNode[] tags = metaData.getAllTags();
if (tags.length > 0)
{
data.metaData = tags;
for (IMetaTagNode tag : tags)
{
String tagName = tag.getTagName();
if (exportMetadata.contains(tagName))
{
if (data.isStatic)
exportSymbols.add(data.name);
else
exportProperties.add(data.name);
}
}
}
}
}
}
if (cdef.getConstructor()==null) {
//add a constructor description for the reflection data
PackageFooterEmitter.MethodData data = asEmitter.packageFooterEmitter.new MethodData();
methodData.add(data);
data.name = cdef.getBaseName();
data.type = "";
data.isStatic = false;
data.declaredBy = cdef.getQualifiedName();
}
ArrayList<IMetaTagNode> metadataTagNodes = new ArrayList<IMetaTagNode>();
for (IMXMLMetadataNode metadataTag : metadataNodes)
{
IMetaTagNode[] tags = metadataTag.getMetaTagNodes();
//tags (MetaTagNodes) can be null if the parent node is empty (or content is commented out)
if (tags != null) {
for (IMetaTagNode tag : tags)
{
metadataTagNodes.add(tag);
}
}
}
IMetaTagNode[] metaDataTags = new IMetaTagNode[metadataTagNodes.size()];
asEmitter.packageFooterEmitter.emitReflectionData(
formatQualifiedName(cdef.getQualifiedName()),
PackageFooterEmitter.ReflectionKind.CLASS,
varData,
accessorData,
methodData,
metadataTagNodes.toArray(metaDataTags));
asEmitter.packageFooterEmitter.emitReflectionRegisterInitialStaticFields(
formatQualifiedName(cdef.getQualifiedName()),
cdef);
asEmitter.packageFooterEmitter.emitExportProperties(
formatQualifiedName(cdef.getQualifiedName()),
exportProperties,
exportSymbols);
}
private void collectAccessors(HashMap<String, PropertyNodes> accessors, ArrayList<PackageFooterEmitter.AccessorData> accessorData,IClassDefinition cdef ) {
JSRoyaleEmitter asEmitter = (JSRoyaleEmitter)((IMXMLBlockWalker) getMXMLWalker()).getASEmitter();
RoyaleJSProject fjs = (RoyaleJSProject) getMXMLWalker().getProject();
for (String propName : accessors.keySet())
{
PropertyNodes p = accessors.get(propName);
IFunctionNode accessorNode = p.getter;
if (accessorNode == null)
accessorNode = p.setter;
String ns = accessorNode.getNamespace();
if (ns == IASKeywordConstants.PUBLIC)
{
PackageFooterEmitter.AccessorData data = asEmitter.packageFooterEmitter.new AccessorData();
accessorData.add(data);
data.name = accessorNode.getName();
data.isStatic = accessorNode.hasModifier(ASModifier.STATIC);
if (p.getter != null)
{
data.type = p.getter.getReturnTypeNode().resolveType(fjs).getQualifiedName();
if (p.setter !=null) {
data.access = "readwrite";
} else data.access = "readonly";
}
else
{
data.type = p.setter.getVariableTypeNode().resolveType(fjs).getQualifiedName();
data.access = "writeonly";
}
data.declaredBy = (cdef.getQualifiedName());
IMetaTagsNode metaData = accessorNode.getMetaTags();
if (metaData != null)
{
IMetaTagNode[] tags = metaData.getAllTags();
if (tags.length > 0)
{
data.metaData = tags;
/* accessors don't need exportProp since they are referenced via the defineProp data structure
for (IMetaTagNode tag : tags)
{
String tagName = tag.getTagName();
if (exportMetadata.contains(tagName))
{
if (data.isStatic)
exportSymbols.add(data.name);
else
exportProperties.add(data.name);
}
}
*/
}
}
}
}
}
//--------------------------------------------------------------------------
protected void emitPropertyDecls()
{
for (MXMLDescriptorSpecifier instance : instances)
{
String id = instance.id != null ? instance.id : instance.effectiveId;
if (id != null) { //it seems id can be null, for example with a generated Object for Operations via RemoteObject
writeNewline();
writeNewline("/**");
writeNewline(" * @private");
writeNewline(" * @type {" + instance.name + "}");
writeNewline(" */");
write(ASEmitterTokens.THIS);
write(ASEmitterTokens.MEMBER_ACCESS);
if (!id.startsWith(MXMLRoyaleEmitterTokens.ID_PREFIX.getToken())) id += "_";
write(id);
writeNewline(ASEmitterTokens.SEMICOLON);
}
}
}
//--------------------------------------------------------------------------
protected void emitBindingData(String cname, IClassDefinition cdef)
{
IRoyaleProject project = (IRoyaleProject)(walker.getProject());
BindingDatabase bd = project.getBindingMap().get(cdef);
if (bd == null)
return;
if (bd.getBindingInfo().isEmpty())
return;
inStaticInitializer = true;
outputBindingInfoAsData(cname, bd);
inStaticInitializer = false;
}
private void outputBindingInfoAsData(String cname, BindingDatabase bindingDataBase)
{
IASEmitter asEmitter = ((IMXMLBlockWalker) getMXMLWalker())
.getASEmitter();
writeNewline("/**");
writeNewline(" * @export"); // must export or else GCC will remove it
writeNewline(" */");
writeNewline(formatQualifiedName(cname)
+ ".prototype._bindings = [");
if (bindingDataBase.getHasAncestorBindings()) {
//reference the ancestor binding data (which may in turn reference its owner's ancestor's bindings etc)
writeNewline(formatQualifiedName(bindingDataBase.getNearestAncestorWithBindings()) +
".prototype._bindings,");
}
Set<BindingInfo> bindingInfo = bindingDataBase.getBindingInfo();
writeNewline(bindingInfo.size() + ","); // number of bindings
boolean hadOutput = false;
for (BindingInfo bi : bindingInfo)
{
if (hadOutput) writeNewline(ASEmitterTokens.COMMA.getToken());
hadOutput = true;
String s;
IMXMLNode node = bi.node;
if (node instanceof IMXMLSingleDataBindingNode)
{
IMXMLSingleDataBindingNode sbdn = (IMXMLSingleDataBindingNode)node;
RoyaleJSProject project = (RoyaleJSProject)getMXMLWalker().getProject();
IDefinition bdef = sbdn.getExpressionNode().resolve(project);
if (bdef != null)
{
//IDefinition cdef = bdef.getParent();
project.addExportedName(/*cdef.getQualifiedName() + "." + */bdef.getBaseName());
}
}
s = bi.getSourceString();
if (s == null && bi.isSourceSimplePublicProperty())
s = getSourceStringFromGetter(bi.getExpressionNodesForGetter());
if (s == null || s.length() == 0)
{
List<IExpressionNode> getterNodes = bi.getExpressionNodesForGetter();
StringBuilder sb = new StringBuilder();
sb.append("function() { return ");
int n = getterNodes.size();
for (int i = 0; i < n; i++)
{
IExpressionNode getterNode = getterNodes.get(i);
sb.append(asEmitter.stringifyNode(getterNode));
if (i < n - 1)
sb.append(ASEmitterTokens.SPACE.getToken() + ASEmitterTokens.PLUS.getToken() + ASEmitterTokens.SPACE.getToken());
}
sb.append("; },");
writeNewline(sb.toString());
}
else if (s.contains("."))
{
if (bi.classDef != null)
{
String[] parts = s.split("\\.");
write(ASEmitterTokens.SQUARE_OPEN.getToken() + ASEmitterTokens.DOUBLE_QUOTE.getToken() +
bi.classDef.getQualifiedName() + ASEmitterTokens.DOUBLE_QUOTE.getToken());
String qname = bi.classDef.getQualifiedName();
if (!usedNames.contains(qname))
usedNames.add(qname);
if (!staticUsedNames.contains(qname))
staticUsedNames.add(qname);
int n = parts.length;
for (int i = 1; i < n; i++)
{
String part = parts[i];
write(", " + ASEmitterTokens.DOUBLE_QUOTE.getToken() + part + ASEmitterTokens.DOUBLE_QUOTE.getToken());
}
writeNewline(ASEmitterTokens.SQUARE_CLOSE.getToken() + ASEmitterTokens.COMMA.getToken());
}
else
{
String[] parts = s.split("\\.");
write(ASEmitterTokens.SQUARE_OPEN.getToken() + ASEmitterTokens.DOUBLE_QUOTE.getToken() +
parts[0] + ASEmitterTokens.DOUBLE_QUOTE.getToken());
int n = parts.length;
for (int i = 1; i < n; i++)
{
String part = parts[i];
write(", " + ASEmitterTokens.DOUBLE_QUOTE.getToken() + part + ASEmitterTokens.DOUBLE_QUOTE.getToken());
}
writeNewline(ASEmitterTokens.SQUARE_CLOSE.getToken() + ASEmitterTokens.COMMA.getToken());
}
}
else
writeNewline(ASEmitterTokens.DOUBLE_QUOTE.getToken() + s +
ASEmitterTokens.DOUBLE_QUOTE.getToken() + ASEmitterTokens.COMMA.getToken());
IExpressionNode destNode = bi.getExpressionNodeForDestination();
s = bi.getDestinationString();
if (destNode != null && s == null)
{
StringBuilder sb = new StringBuilder();
sb.append(generateSetterFunction(bi, destNode));
writeNewline(sb.toString() + ASEmitterTokens.COMMA.getToken());
}
else
writeNewline(ASEmitterTokens.NULL.getToken() + ASEmitterTokens.COMMA.getToken());
if (s == null)
{
write(ASEmitterTokens.NULL.getToken());
}
else if (s.contains("."))
{
String[] parts = s.split("\\.");
write(ASEmitterTokens.SQUARE_OPEN.getToken() + ASEmitterTokens.DOUBLE_QUOTE.getToken() +
parts[0] + ASEmitterTokens.DOUBLE_QUOTE.getToken());
int n = parts.length;
for (int i = 1; i < n; i++)
{
String part = parts[i];
write(", " + ASEmitterTokens.DOUBLE_QUOTE.getToken() + part + ASEmitterTokens.DOUBLE_QUOTE.getToken());
}
write(ASEmitterTokens.SQUARE_CLOSE.getToken());
}
else
write(ASEmitterTokens.DOUBLE_QUOTE.getToken() + s +
ASEmitterTokens.DOUBLE_QUOTE.getToken());
}
Set<Entry<Object, WatcherInfoBase>> watcherChains = bindingDataBase.getWatcherChains();
if (watcherChains != null)
{
int count = watcherChains.size();
if (hadOutput) {
if (count > 0) writeNewline(ASEmitterTokens.COMMA);
else writeNewline();
}
for (Entry<Object, WatcherInfoBase> entry : watcherChains)
{
count--;
WatcherInfoBase watcherInfoBase = entry.getValue();
encodeWatcher(watcherInfoBase);
if (count > 0) writeNewline(ASEmitterTokens.COMMA);
}
} else {
if (hadOutput) writeNewline();
}
writeNewline( ASEmitterTokens.SQUARE_CLOSE.getToken() + ASEmitterTokens.SEMICOLON.getToken());
}
private String generateSetterFunction(BindingInfo bi, IExpressionNode destNode) {
IASEmitter asEmitter = ((IMXMLBlockWalker) getMXMLWalker())
.getASEmitter();
StringBuilder sb = new StringBuilder();
sb.append("function (value) { ");
if (destNode instanceof InstructionListNode)
{
sb.append(generateDestExpression(bi));
}
else
{
String body = asEmitter.stringifyNode(destNode);
sb.append(body);
sb.append(" = value;");
}
sb.append("}");
return sb.toString();
}
String generateDestExpression(BindingInfo bi)
{
StringBuilder sb = new StringBuilder();
MXMLBindingNode node = (MXMLBindingNode)bi.node;
IMXMLBindingAttributeNode destNode = node.getDestinationAttributeNode();
Stack<IASNode> nodeStack = new Stack<IASNode>();
nodeStack.push(node);
IASNode parentNode = node.getParent();
while (!(parentNode instanceof IMXMLInstanceNode))
{
nodeStack.push(parentNode);
parentNode = parentNode.getParent();
}
boolean isXML = parentNode instanceof IMXMLXMLNode;
boolean isXMLList = parentNode instanceof IMXMLXMLListNode;
String effectiveID = ((IMXMLInstanceNode)parentNode).getEffectiveID();
sb.append("this.");
sb.append(effectiveID);
// at least for one XMLList case, we could not trust
// the nodestack as children were only binding nodes
// and not preceding XML nodes
if (isXMLList)
{
// re-interpret the instruction list.
// it would not be a surprise of the non-XMLList cases will
// eventually require this code path
InstructionListNode ilNode = (InstructionListNode)destNode.getExpressionNode();
InstructionList il = ilNode.getInstructions();
ArrayList<Instruction> abcs = il.getInstructions();
// the first indexed access accesses an XMLList, the next ones
// access an XML object
boolean indexedAccess = false;
int n = abcs.size();
for (int i = 0; i < n; i++)
{
Instruction inst = abcs.get(i);
int opCode = inst.getOpcode();
if (opCode == ABCConstants.OP_getlocal0)
{
if (i > 0)
System.out.println("unexpected getLocal0 in binding expression");
}
else if (opCode == ABCConstants.OP_getproperty)
{
OneOperandInstruction getProp = (OneOperandInstruction)inst;
Name propName = (Name)getProp.getOperand(0);
if (i == 0)
System.out.println("unexpected opcode in binding expression");
else if (i == 1 && !propName.getBaseName().contentEquals(effectiveID))
System.out.println("unexpected effectiveID in binding expression");
else if (i > 1)
{
try
{
Integer.parseInt(propName.getBaseName());
if (indexedAccess)
sb.append(".children()");
sb.append("[" + propName.getBaseName() + "]" );
indexedAccess = true;
} catch (NumberFormatException ex)
{
sb.append(".elements(" + propName.getBaseName() + ")" );
}
}
}
else if (opCode == ABCConstants.OP_getlocal1)
{
if (i != n - 3)
System.out.println("unexpected getLocal1 in binding expression");
}
else if (opCode == ABCConstants.OP_setproperty)
{
if (i != n - 2)
System.out.println("unexpected setProperty in binding expression");
OneOperandInstruction setProp = (OneOperandInstruction)inst;
Name propName = (Name)setProp.getOperand(0);
if (!propName.getBaseName().contentEquals(destNode.getName()))
System.out.println("unexpected setProperty name in binding expression");
break; // exit loop
}
}
sb.append(".setAttribute('" + destNode.getName() + "', value);" );
}
else
{
while (nodeStack.size() > 0)
{
IASNode childNode = nodeStack.pop();
int n = parentNode.getChildCount();
int i = 0;
for (; i < n; i++)
{
if (childNode == parentNode.getChild(i))
break;
}
assert i < n;
sb.append("[" + new Integer(i).toString() + "]" );
parentNode = childNode;
}
if (isXML)
sb.append(".setAttribute('" + destNode.getName() + "', value);" );
else
sb.append("." + destNode.getName() + " = value;");
}
return sb.toString();
}
private void encodeWatcher(WatcherInfoBase watcherInfoBase)
{
IASEmitter asEmitter = ((IMXMLBlockWalker) getMXMLWalker())
.getASEmitter();
writeNewline(watcherInfoBase.getIndex() + ASEmitterTokens.COMMA.getToken());
WatcherType type = watcherInfoBase.getType();
if (type == WatcherType.FUNCTION)
{
writeNewline("0" + ASEmitterTokens.COMMA.getToken());
FunctionWatcherInfo functionWatcherInfo = (FunctionWatcherInfo)watcherInfoBase;
writeNewline(ASEmitterTokens.DOUBLE_QUOTE.getToken() + functionWatcherInfo.getFunctionName() +
ASEmitterTokens.DOUBLE_QUOTE.getToken() + ASEmitterTokens.COMMA.getToken());
IExpressionNode params[] = functionWatcherInfo.params;
StringBuilder sb = new StringBuilder();
sb.append("function() { return [");
boolean firstone = true;
for (IExpressionNode param : params)
{
if (!firstone)
{
sb.append(ASEmitterTokens.COMMA.getToken());
}
firstone = false;
sb.append(asEmitter.stringifyNode(param));
}
sb.append("]; },");
writeNewline(sb.toString());
outputEventNames(functionWatcherInfo.getEventNames());
outputBindings(functionWatcherInfo.getBindings());
}
else if ((type == WatcherType.STATIC_PROPERTY) || (type == WatcherType.PROPERTY))
{
writeNewline((type == WatcherType.STATIC_PROPERTY ? "1" : "2") +
ASEmitterTokens.COMMA.getToken());
PropertyWatcherInfo propertyWatcherInfo = (PropertyWatcherInfo)watcherInfoBase;
boolean makeStaticWatcher = (watcherInfoBase.getType() == WatcherType.STATIC_PROPERTY);
// round up the getter function for the watcher, or null if we don't need one
StringBuilder propertyGetterFunction = null;
if (watcherInfoBase.isRoot && !makeStaticWatcher)
{
// TODO: figure out what this looks like
// propertyGetterFunction = this.propertyGetter;
// assert propertyGetterFunction != null;
StringBuilder sb = new StringBuilder();
sb.append("function() { return this.");
RoyaleJSProject fjp = (RoyaleJSProject) getMXMLWalker().getProject();
String propName = propertyWatcherInfo.getPropertyName();
IDefinitionSet defSet = this.classDefinition.getContainedScope().getLocalDefinitionSetByName(propName);
if (defSet != null)
{
IDefinition rootDef = defSet.getDefinition(0);
if (rootDef != null)
{
if (rootDef.isPrivate())
{
sb.append(((JSRoyaleEmitter)asEmitter).formatPrivateName(this.classDefinition.getQualifiedName(),
propName));
sb.append("; }");
propertyGetterFunction = sb;
}
// might need for public as well.
}
}
}
else if (watcherInfoBase.isRoot && makeStaticWatcher)
{
// TODO: implement getter func for static watcher.
}
writeNewline(ASEmitterTokens.DOUBLE_QUOTE.getToken() + propertyWatcherInfo.getPropertyName() +
ASEmitterTokens.DOUBLE_QUOTE.getToken() + ASEmitterTokens.COMMA.getToken());
outputEventNames(propertyWatcherInfo.getEventNames());
outputBindings(propertyWatcherInfo.getBindings());
if (propertyGetterFunction == null)
writeNewline("null" + ASEmitterTokens.COMMA.getToken()); // null is valid
else
writeNewline(propertyGetterFunction.toString() + ASEmitterTokens.COMMA.getToken());
if (type == WatcherType.STATIC_PROPERTY)
{
StaticPropertyWatcherInfo pwinfo = (StaticPropertyWatcherInfo)watcherInfoBase;
Name classMName = pwinfo.getContainingClass(getMXMLWalker().getProject());
writeNewline(nameToString(classMName)+ ASEmitterTokens.COMMA.getToken());
}
}
else if (type == WatcherType.XML)
{
writeNewline("3" + ASEmitterTokens.COMMA.getToken());
XMLWatcherInfo xmlWatcherInfo = (XMLWatcherInfo)watcherInfoBase;
writeNewline(ASEmitterTokens.DOUBLE_QUOTE.getToken() + xmlWatcherInfo.getPropertyName() +
ASEmitterTokens.DOUBLE_QUOTE.getToken() + ASEmitterTokens.COMMA.getToken());
outputBindings(xmlWatcherInfo.getBindings());
}
else assert false;
// then recurse into children
Set<Entry<Object, WatcherInfoBase>> children = watcherInfoBase.getChildren();
if (children != null)
{
writeNewline(ASEmitterTokens.SQUARE_OPEN.getToken());
for ( Entry<Object, WatcherInfoBase> ent : children)
{
encodeWatcher(ent.getValue());
writeNewline(ASEmitterTokens.COMMA);
}
write("null" + ASEmitterTokens.SQUARE_CLOSE.getToken() );
}
else
{
write("null" );
}
}
private String getSourceStringFromMemberAccessExpressionNode(MemberAccessExpressionNode node)
{
String s = "";
IExpressionNode left = node.getLeftOperandNode();
if (left instanceof FunctionCallNode) // probably a cast
{
IASNode child = ((FunctionCallNode)left).getArgumentsNode().getChild(0);
if (child instanceof IdentifierNode)
s = getSourceStringFromIdentifierNode((IdentifierNode)child);
else if (child instanceof MemberAccessExpressionNode)
s = getSourceStringFromMemberAccessExpressionNode((MemberAccessExpressionNode)child);
}
else if (left instanceof MemberAccessExpressionNode)
s = getSourceStringFromMemberAccessExpressionNode((MemberAccessExpressionNode)left);
else if (left instanceof IdentifierNode)
s = getSourceStringFromIdentifierNode((IdentifierNode)left);
else
System.out.println("expected binding member access left node" + node.toString());
s += ".";
IExpressionNode right = node.getRightOperandNode();
if (right instanceof FunctionCallNode) // probably a cast
{
IASNode child = ((FunctionCallNode)right).getArgumentsNode().getChild(0);
if (child instanceof IdentifierNode)
s += getSourceStringFromIdentifierNode((IdentifierNode)child);
else if (child instanceof MemberAccessExpressionNode)
s += getSourceStringFromMemberAccessExpressionNode((MemberAccessExpressionNode)child);
}
else if (right instanceof MemberAccessExpressionNode)
s += getSourceStringFromMemberAccessExpressionNode((MemberAccessExpressionNode)right);
else if (right instanceof IdentifierNode)
s += getSourceStringFromIdentifierNode((IdentifierNode)right);
else
System.out.println("expected binding member access right node" + node.toString());
return s;
}
private String getSourceStringFromIdentifierNode(IdentifierNode node)
{
return node.getName();
}
private String getSourceStringFromGetter(List<IExpressionNode> nodes)
{
String s = "";
IExpressionNode node = nodes.get(0);
if (node instanceof MemberAccessExpressionNode)
{
s = getSourceStringFromMemberAccessExpressionNode((MemberAccessExpressionNode)node);
}
else if (node instanceof IdentifierNode)
{
s = ((IdentifierNode)node).getName();
}
return s;
}
private void outputEventNames(List<String> events)
{
if (events.size() > 1)
{
int n = events.size();
write(ASEmitterTokens.SQUARE_OPEN.getToken() + ASEmitterTokens.DOUBLE_QUOTE.getToken() +
events.get(0) + ASEmitterTokens.DOUBLE_QUOTE.getToken());
for (int i = 1; i < n; i++)
{
String event = events.get(i);
write(ASEmitterTokens.COMMA.getToken() + ASEmitterTokens.DOUBLE_QUOTE.getToken() +
event + ASEmitterTokens.DOUBLE_QUOTE.getToken());
}
writeNewline(ASEmitterTokens.SQUARE_CLOSE.getToken() + ASEmitterTokens.COMMA.getToken());
}
else if (events.size() == 1)
writeNewline(ASEmitterTokens.DOUBLE_QUOTE.getToken() + events.get(0) +
ASEmitterTokens.DOUBLE_QUOTE.getToken() + ASEmitterTokens.COMMA.getToken());
else
writeNewline("null" + ASEmitterTokens.COMMA.getToken());
}
private void outputBindings(List<BindingInfo> bindings)
{
if (bindings.size() > 1)
{
int n = bindings.size();
write(ASEmitterTokens.SQUARE_OPEN.getToken() + bindings.get(0).getIndex());
for (int i = 1; i < n; i++)
{
BindingInfo binding = bindings.get(i);
write(ASEmitterTokens.COMMA.getToken() + binding.getIndex());
}
writeNewline(ASEmitterTokens.SQUARE_CLOSE.getToken() + ASEmitterTokens.COMMA.getToken());
}
else if (bindings.size() == 1)
writeNewline(bindings.get(0).getIndex() + ASEmitterTokens.COMMA.getToken());
else
writeNewline("null" + ASEmitterTokens.COMMA.getToken());
}
//--------------------------------------------------------------------------
protected void emitScripts()
{
for (IMXMLScriptNode node : scripts)
{
IASEmitter asEmitter = ((IMXMLBlockWalker) getMXMLWalker())
.getASEmitter();
int len = node.getChildCount();
if (len > 0)
{
for (int i = 0; i < len; i++)
{
IASNode cnode = node.getChild(i);
if (cnode.getNodeID() == ASTNodeID.VariableID) {
((JSRoyaleEmitter) asEmitter).getModel().getVars().add((IVariableNode) cnode);
} else {
if (cnode.getNodeID() == ASTNodeID.BindableVariableID) {
IVariableNode variableNode = (IVariableNode) cnode;
BindableVarInfo bindableVarInfo = new BindableVarInfo();
bindableVarInfo.isStatic = variableNode.hasModifier(ASModifier.STATIC);;
bindableVarInfo.namespace = variableNode.getNamespace();
IMetaTagsNode metaTags = variableNode.getMetaTags();
if (metaTags != null) {
IMetaTagNode[] tags = metaTags.getAllTags();
if (tags.length > 0)
bindableVarInfo.metaTags = tags;
}
bindableVarInfo.type = variableNode.getVariableTypeNode().resolveType(getMXMLWalker().getProject()).getQualifiedName();
((JSRoyaleEmitter) asEmitter).getModel().getBindableVars().put(variableNode.getName(), bindableVarInfo);
}
}
if (!(cnode instanceof IImportNode))
{
asEmitter.getWalker().walk(cnode);
write(ASEmitterTokens.SEMICOLON.getToken());
if (i == len - 1)
indentPop();
writeNewline();
writeNewline();
writeNewline();
}
}
}
}
}
//--------------------------------------------------------------------------
protected void emitEvents(String cname)
{
for (MXMLEventSpecifier event : events)
{
writeNewline("/**");
if (emitExports)
writeNewline(" * @export");
writeNewline(" * @param {" + formatQualifiedName(event.type) + "} event");
writeNewline(" */");
writeNewline(formatQualifiedName(cname)
+ ".prototype." + event.eventHandler + " = function(event)");
writeNewline(ASEmitterTokens.BLOCK_OPEN, true);
IASEmitter asEmitter = ((IMXMLBlockWalker) getMXMLWalker())
.getASEmitter();
IMXMLEventSpecifierNode node = event.node;
int len = node.getChildCount();
for (int i = 0; i < len; i++)
{
if (i > 0)
{
writeNewline();
}
IASNode cnode = node.getChild(i);
asEmitter.getWalker().walk(cnode);
write(ASEmitterTokens.SEMICOLON);
}
indentPop();
writeNewline();
write(ASEmitterTokens.BLOCK_CLOSE);
writeNewline(ASEmitterTokens.SEMICOLON);
writeNewline();
writeNewline();
}
}
//--------------------------------------------------------------------------
private boolean skippedDefineProps;
protected void emitPropertyGetterSetters(String cname)
{
int n = 0;
for (MXMLDescriptorSpecifier instance : instances)
{
if (instance.id != null || instance.hasLocalId)
{
n++;
}
}
if (n == 0 && (descriptorTree.size() == 0 ||
descriptorTree.size() == 1 && descriptorTree.get(0).propertySpecifiers.size() == 0))
{
skippedDefineProps = true;
return;
}
String formattedCName = formatQualifiedName(cname);
write("Object.defineProperties(");
write(formattedCName);
writeNewline(".prototype, /** @lends {" + formattedCName + ".prototype} */ {");
indentPush();
int i = 0;
for (MXMLDescriptorSpecifier instance : instances)
{
String instanceId = instance.id;
if (instanceId == null && instance.hasLocalId ){
instanceId = instance.effectiveId;
}
if (instanceId != null)
{
indentPush();
writeNewline("/** @export */");
writeNewline(instanceId + ": {");
writeNewline("/** @this {" + formattedCName + "} */");
indentPush();
writeNewline("get: function() {");
indentPop();
writeNewline("return this." + instanceId + "_;");
writeNewline("},");
writeNewline("/** @this {" + formattedCName + "} */");
indentPush();
writeNewline("set: function(value) {");
indentPush();
writeNewline("if (value != this." + instanceId + "_) {");
writeNewline("this." + instanceId + "_ = value;");
write("this.dispatchEvent(org.apache.royale.events.ValueChangeEvent.createUpdateEvent(this, '");
indentPop();
writeNewline(instanceId + "', null, value));");
indentPop();
writeNewline("}");
indentPop();
writeNewline("}");
if (i < n - 1 || descriptorTree.size() > 0)
writeNewline("},");
else
{
indentPop();
writeNewline("}");
}
i++;
}
}
if (descriptorTree.size() == 0)
writeNewline("});");
}
//--------------------------------------------------------------------------
protected void emitMXMLDescriptorFuncs(String cname)
{
// top level is 'mxmlContent', skip it...
if (descriptorTree.size() > 0)
{
RoyaleJSProject project = (RoyaleJSProject) getMXMLWalker().getProject();
project.needLanguage = true;
MXMLDescriptorSpecifier root = descriptorTree.get(0);
if (root.propertySpecifiers.size() == 0 && skippedDefineProps)
return; // all declarations were primitives
root.isTopNode = false;
collectExportedNames(root);
indentPush();
writeNewline("'MXMLDescriptor': {");
writeNewline("/** @this {" + formatQualifiedName(cname) + "} */");
indentPush();
writeNewline("get: function() {");
writeNewline("if (this.mxmldd == undefined)");
indentPush();
writeNewline("{");
writeNewline("/** @type {Array} */");
writeNewline("var arr = " + formatQualifiedName(cname) + ".superClass_.get__MXMLDescriptor.apply(this);");
writeNewline("/** @type {Array} */");
indentPush();
writeNewline("var data = [");
for(int i = 0; i < getCurrentIndent(); i++)
{
root.indentPush();
}
write(root.output(true));
indentPop();
writeNewline();
writeNewline("];");
indentPush();
writeNewline("if (arr)");
indentPop();
writeNewline("this.mxmldd = arr.concat(data);");
indentPush();
writeNewline("else");
indentPop();
indentPop();
writeNewline("this.mxmldd = data;");
writeNewline("}");
indentPop();
writeNewline("return this.mxmldd;");
indentPop();
writeNewline("}");
indentPop();
writeNewline("}");
indentPop();
writeNewline("});");
}
}
private void collectExportedNames(MXMLDescriptorSpecifier descriptor)
{
ICompilerProject project = getMXMLWalker().getProject();
RoyaleJSProject royaleProject = null;
if (project instanceof RoyaleJSProject)
{
royaleProject = (RoyaleJSProject) project;
String name = descriptor.name;
if (name == null)
name = this.classDefinition.getQualifiedName();
for (MXMLDescriptorSpecifier prop : descriptor.propertySpecifiers)
{
String propName = prop.name;
royaleProject.addExportedName(/*name + "." + */propName);
if (prop.propertySpecifiers.size() > 0)
{
collectExportedNames(prop.propertySpecifiers.get(0));
}
}
if (descriptor.childrenSpecifier != null)
{
for (MXMLDescriptorSpecifier prop : descriptor.childrenSpecifier.propertySpecifiers)
{
collectExportedNames(prop);
}
}
}
}
//--------------------------------------------------------------------------
private HashMap<IMXMLEventSpecifierNode, String> eventHandlerNameMap = new HashMap<IMXMLEventSpecifierNode, String>();
@Override
public void emitEventSpecifier(IMXMLEventSpecifierNode node)
{
IMXMLStateNode currentState = null;
if (!inStatesOverride.empty())
currentState = inStatesOverride.peek();
if (isStateDependent(node, currentState, true))
return;
IDefinition cdef = node.getDefinition();
MXMLDescriptorSpecifier currentDescriptor = getCurrentDescriptor("i");
MXMLEventSpecifier eventSpecifier = new MXMLEventSpecifier();
IASEmitter asEmitter = ((IMXMLBlockWalker) getMXMLWalker()).getASEmitter();
JSRoyaleEmitter fjs = (JSRoyaleEmitter)asEmitter;
IClassDefinition currentClass = fjs.getModel().getCurrentClass();
//naming needs to avoid conflicts with ancestors - using delta from object which is
//a) short and b)provides a 'unique' (not zero risk, but very low risk) option
String nameBase = EmitterUtils.getClassDepthNameBase(MXMLRoyaleEmitterTokens.EVENT_PREFIX
.getToken(), currentClass, getMXMLWalker().getProject());
eventSpecifier.eventHandler = nameBase + eventCounter++;
eventSpecifier.name = cdef.getBaseName();
eventSpecifier.type = node.getEventParameterDefinition()
.getTypeAsDisplayString();
eventHandlerNameMap.put(node, eventSpecifier.eventHandler);
//save the node for emitting later in emitEvents()
//previously, we stringified the node and saved that instead of the
//node, but source maps don't work when you stringify a node too early -JT
eventSpecifier.node = node;
if (currentDescriptor != null)
currentDescriptor.eventSpecifiers.add(eventSpecifier);
else if (inStatesOverride.empty()) // in theory, if no currentdescriptor must be top tag event
propertiesTree.eventSpecifiers.add(eventSpecifier);
events.add(eventSpecifier);
}
@Override
public void emitInstance(IMXMLInstanceNode node)
{
IMXMLStateNode currentState = null;
if (!inStatesOverride.empty())
currentState = inStatesOverride.peek();
if (overrideInstanceToEmit != node && isStateDependent(node, currentState, false))
return;
ASTNodeID nodeID = node.getNodeID();
if ((nodeID == ASTNodeID.MXMLXMLID || nodeID == ASTNodeID.MXMLXMLListID) &&
node.getParent().getNodeID() == ASTNodeID.MXMLDeclarationsID)
{
primitiveDeclarationNodes.add(node);
return;
}
IClassDefinition cdef = node
.getClassReference((ICompilerProject) getMXMLWalker()
.getProject());
MXMLDescriptorSpecifier currentPropertySpecifier = getCurrentDescriptor("ps");
if (nodeID == ASTNodeID.MXMLFunctionID)
{
RoyaleJSProject project = (RoyaleJSProject) getMXMLWalker().getProject();
project.needLanguage = true;
MXMLFunctionNode fnode = ((MXMLFunctionNode)node);
IFunctionDefinition fdef = fnode.getValue(project);
IExpressionNode fexpNode = (IExpressionNode)fnode.getExpressionNode();
String fnName = fdef.getBaseName();
IASEmitter asEmitter = ((IMXMLBlockWalker) getMXMLWalker())
.getASEmitter();
if (fdef.isPrivate() && project.getAllowPrivateNameConflicts())
fnName = ((JSRoyaleEmitter)asEmitter).formatPrivateName(fdef.getParent().getQualifiedName(), fdef.getBaseName());
String fNodeString = ((JSRoyaleEmitter)asEmitter).stringifyNode(fexpNode);
currentPropertySpecifier.value = fNodeString;
return;
}
String effectiveId = null;
String id = node.getID();
if (id == null)
{
effectiveId = node.getEffectiveID();
if (effectiveId == null)
effectiveId = node.getClassDefinitionNode().getGeneratedID(node);
}
MXMLDescriptorSpecifier currentInstance = new MXMLDescriptorSpecifier();
currentInstance.isProperty = false;
currentInstance.id = id;
currentInstance.hasLocalId = node.getLocalID() != null;
currentInstance.effectiveId = effectiveId;
currentInstance.name = formatQualifiedName(cdef.getQualifiedName());
currentInstance.parent = currentPropertySpecifier;
if (currentPropertySpecifier != null)
currentPropertySpecifier.propertySpecifiers.add(currentInstance);
else if (inMXMLContent)
descriptorTree.add(currentInstance);
else
{
// we get here if a instance is a child of a top-level tag
// and there is no default property. If there are other
// ways to get here, then the code will need adjusting.
// this code assumes that the children will have an id
// and will just create properties with the children's id
// on the class.
MXMLDescriptorSpecifier prop = new MXMLDescriptorSpecifier();
prop.isProperty = true;
prop.name = id;
prop.parent = propertiesTree;
propertiesTree.propertySpecifiers.add(prop);
currentInstance.parent = prop;
prop.propertySpecifiers.add(currentInstance);
}
addInstanceIfNeeded(instances, currentInstance);
IMXMLPropertySpecifierNode[] pnodes = node.getPropertySpecifierNodes();
if (pnodes != null)
{
moveDown(false, currentInstance, null);
for (IMXMLPropertySpecifierNode pnode : pnodes)
{
getMXMLWalker().walk(pnode); // Property Specifier
}
moveUp(false, true);
}
else if (node instanceof IMXMLStateNode)
{
IMXMLStateNode stateNode = (IMXMLStateNode)node;
String name = stateNode.getStateName();
if (name != null)
{
MXMLDescriptorSpecifier stateName = new MXMLDescriptorSpecifier();
stateName.isProperty = true;
stateName.id = id;
stateName.name = "name";
stateName.value = ASEmitterTokens.SINGLE_QUOTE.getToken() + name + ASEmitterTokens.SINGLE_QUOTE.getToken();
stateName.parent = currentInstance;
currentInstance.propertySpecifiers.add(stateName);
}
MXMLDescriptorSpecifier overrides = new MXMLDescriptorSpecifier();
overrides.isProperty = true;
overrides.hasArray = true;
overrides.id = id;
overrides.name = "overrides";
overrides.parent = currentInstance;
currentInstance.propertySpecifiers.add(overrides);
moveDown(false, null, overrides);
IMXMLClassDefinitionNode classDefinitionNode = stateNode.getClassDefinitionNode();
List<IMXMLNode> snodes = classDefinitionNode.getNodesDependentOnState(stateNode.getStateName());
if (snodes != null)
{
inStatesOverride.push(stateNode);
for (int i=0; i<snodes.size(); i++)
{
IMXMLNode inode = snodes.get(i);
if (inode.getNodeID() == ASTNodeID.MXMLInstanceID)
{
emitInstanceOverride((IMXMLInstanceNode)inode, stateNode);
}
}
// Next process the non-instance overrides dependent on this state.
// Each one will generate code to push an IOverride instance.
for (IMXMLNode anode : snodes)
{
switch (anode.getNodeID())
{
case MXMLPropertySpecifierID:
{
emitPropertyOverride((IMXMLPropertySpecifierNode)anode);
break;
}
case MXMLStyleSpecifierID:
{
emitStyleOverride((IMXMLStyleSpecifierNode)anode);
break;
}
case MXMLEventSpecifierID:
{
emitEventOverride((IMXMLEventSpecifierNode)anode);
break;
}
default:
{
break;
}
}
}
inStatesOverride.pop();
}
moveUp(false, false);
}
IMXMLEventSpecifierNode[] enodes = node.getEventSpecifierNodes();
if (enodes != null)
{
moveDown(false, currentInstance, null);
for (IMXMLEventSpecifierNode enode : enodes)
{
getMXMLWalker().walk(enode); // Event Specifier
}
moveUp(false, true);
}
}
private void addInstanceIfNeeded(
ArrayList<MXMLDescriptorSpecifier> instances2,
MXMLDescriptorSpecifier currentInstance) {
for (MXMLDescriptorSpecifier instance : instances2)
if (instance.id != null && currentInstance.id != null && instance.id.equals(currentInstance.id))
return;
instances.add(currentInstance);
}
public void emitPropertyOverride(IMXMLPropertySpecifierNode propertyNode)
{
RoyaleProject project = (RoyaleProject) getMXMLWalker().getProject();
Name propertyOverride = project.getPropertyOverrideClassName();
emitPropertyOrStyleOverride(propertyOverride, propertyNode);
}
/**
* Generates instructions in the current context
* to create an instance of mx.states.SetStyle
* with its <code>target</code>, <code>name</code>,
* and <code>value</code> properties set.
*/
void emitStyleOverride(IMXMLStyleSpecifierNode styleNode)
{
RoyaleProject project = (RoyaleProject) getMXMLWalker().getProject();
Name styleOverride = project.getStyleOverrideClassName();
emitPropertyOrStyleOverride(styleOverride, styleNode);
}
void emitPropertyOrStyleOverride(Name overrideName, IMXMLPropertySpecifierNode propertyOrStyleNode)
{
MXMLDescriptorSpecifier currentInstance = getCurrentDescriptor("ps");
IASNode parentNode = propertyOrStyleNode.getParent();
String id = parentNode instanceof IMXMLInstanceNode ?
((IMXMLInstanceNode)parentNode).getEffectiveID() :
null;
String name = propertyOrStyleNode.getName();
boolean valueIsDataBound = isDataBindingNode(propertyOrStyleNode.getChild(0));
IMXMLInstanceNode propertyOrStyleValueNode = propertyOrStyleNode.getInstanceNode();
MXMLDescriptorSpecifier setProp = new MXMLDescriptorSpecifier();
setProp.isProperty = false;
setProp.name = formatQualifiedName(nameToString(overrideName));
setProp.parent = currentInstance;
currentInstance.propertySpecifiers.add(setProp);
if (id != null)
{
// Set its 'target' property to the id of the object
// whose property or style this override will set.
MXMLDescriptorSpecifier target = new MXMLDescriptorSpecifier();
target.isProperty = true;
target.name = "target";
target.parent = setProp;
target.value = ASEmitterTokens.SINGLE_QUOTE.getToken() + id + ASEmitterTokens.SINGLE_QUOTE.getToken();
setProp.propertySpecifiers.add(target);
}
// Set its 'name' property to the name of the property or style.
MXMLDescriptorSpecifier pname = new MXMLDescriptorSpecifier();
pname.isProperty = true;
pname.name = "name";
pname.parent = setProp;
pname.value = ASEmitterTokens.SINGLE_QUOTE.getToken() + name + ASEmitterTokens.SINGLE_QUOTE.getToken();
setProp.propertySpecifiers.add(pname);
if (!valueIsDataBound)
{
// Set its 'value' property to the value of the property or style.
MXMLDescriptorSpecifier value = new MXMLDescriptorSpecifier();
value.isProperty = true;
value.name = "value";
value.parent = setProp;
setProp.propertySpecifiers.add(value);
moveDown(false, null, value);
getMXMLWalker().walk(propertyOrStyleValueNode); // instance node
moveUp(false, false);
}
else
{
String overrideID = MXMLRoyaleEmitterTokens.BINDING_PREFIX.getToken() + bindingCounter++;
setProp.id = overrideID;
instances.add(setProp);
IRoyaleProject project = (IRoyaleProject)(walker.getProject());
BindingDatabase bd = project.getBindingMap().get(classDefinition);
Set<BindingInfo> bindingInfo = bd.getBindingInfo();
IMXMLDataBindingNode bindingNode = (IMXMLDataBindingNode)propertyOrStyleNode.getChild(0);
for (BindingInfo bi : bindingInfo)
{
if (bi.node == bindingNode)
{
bi.setDestinationString(overrideID + ".value");
break;
}
}
}
}
/**
* Generates instructions in the current context
* to create an instance of mx.states.SetEventHandler
* with its <code>target</code>, <code>name</code>,
* and <code>handlerFunction</code> properties set.
*/
void emitEventOverride(IMXMLEventSpecifierNode eventNode)
{
MXMLDescriptorSpecifier currentInstance = getCurrentDescriptor("ps");
RoyaleProject project = (RoyaleProject) getMXMLWalker().getProject();
Name eventOverride = project.getEventOverrideClassName();
IASNode parentNode = eventNode.getParent();
String id = parentNode instanceof IMXMLInstanceNode ?
((IMXMLInstanceNode)parentNode).getEffectiveID() :
"";
String name = MXMLEventSpecifier.getJSEventName(eventNode.getName());
String eventHandler = eventHandlerNameMap.get(eventNode);
if (eventHandler == null)
{
emitEventSpecifier(eventNode);
eventHandler = eventHandlerNameMap.get(eventNode);
}
MXMLDescriptorSpecifier setEvent = new MXMLDescriptorSpecifier();
setEvent.isProperty = false;
setEvent.name = formatQualifiedName(nameToString(eventOverride));
setEvent.parent = currentInstance;
currentInstance.propertySpecifiers.add(setEvent);
// Set its 'target' property to the id of the object
// whose event this override will set.
MXMLDescriptorSpecifier target = new MXMLDescriptorSpecifier();
target.isProperty = true;
target.name = "target";
target.parent = setEvent;
target.value = ASEmitterTokens.SINGLE_QUOTE.getToken() + id + ASEmitterTokens.SINGLE_QUOTE.getToken();
setEvent.propertySpecifiers.add(target);
// Set its 'name' property to the name of the event.
MXMLDescriptorSpecifier pname = new MXMLDescriptorSpecifier();
pname.isProperty = true;
pname.name = "name";
pname.parent = setEvent;
pname.value = ASEmitterTokens.SINGLE_QUOTE.getToken() + name + ASEmitterTokens.SINGLE_QUOTE.getToken();
setEvent.propertySpecifiers.add(pname);
// Set its 'handlerFunction' property to the autogenerated event handler.
MXMLDescriptorSpecifier handler = new MXMLDescriptorSpecifier();
handler.isProperty = true;
handler.name = "handlerFunction";
handler.parent = setEvent;
handler.value = JSRoyaleEmitterTokens.CLOSURE_FUNCTION_NAME.getToken() + ASEmitterTokens.PAREN_OPEN.getToken() +
ASEmitterTokens.THIS.getToken() + ASEmitterTokens.MEMBER_ACCESS.getToken() + eventHandler +
ASEmitterTokens.COMMA.getToken() + ASEmitterTokens.SPACE.getToken() + ASEmitterTokens.THIS.getToken() +
ASEmitterTokens.COMMA.getToken() + ASEmitterTokens.SPACE.getToken() + ASEmitterTokens.SINGLE_QUOTE.getToken() +
eventHandler + ASEmitterTokens.SINGLE_QUOTE.getToken() +
ASEmitterTokens.PAREN_CLOSE.getToken();
setEvent.propertySpecifiers.add(handler);
}
public void emitInstanceOverride(IMXMLInstanceNode instanceNode, IMXMLStateNode state)
{
MXMLDescriptorSpecifier currentInstance = getCurrentDescriptor("ps");
RoyaleProject project = (RoyaleProject) getMXMLWalker().getProject();
Name instanceOverrideName = project.getInstanceOverrideClassName();
MXMLDescriptorSpecifier overrideInstances = getCurrentDescriptor("so");
int index = overrideInstances.propertySpecifiers.size();
if (nodeToIndexMap == null)
nodeToIndexMap = new HashMap<IMXMLNode, Integer>();
if (nodeToIndexMap.containsKey(instanceNode))
{
index = nodeToIndexMap.get(instanceNode);
}
else
{
nodeToIndexMap.put(instanceNode, index);
MXMLDescriptorSpecifier itemsDesc = new MXMLDescriptorSpecifier();
itemsDesc.isProperty = true;
itemsDesc.hasArray = true;
itemsDesc.name = "itemsDescriptor";
itemsDesc.parent = overrideInstances;
overrideInstances.propertySpecifiers.add(itemsDesc);
boolean oldInMXMLContent = inMXMLContent;
moveDown(false, null, itemsDesc);
inMXMLContent = true;
overrideInstanceToEmit = instanceNode;
getMXMLWalker().walk(instanceNode); // instance node
overrideInstanceToEmit = null;
inMXMLContent = oldInMXMLContent;
moveUp(false, false);
}
MXMLDescriptorSpecifier addItems = new MXMLDescriptorSpecifier();
addItems.isProperty = false;
addItems.name = formatQualifiedName(nameToString(instanceOverrideName));
addItems.parent = currentInstance;
currentInstance.propertySpecifiers.add(addItems);
MXMLDescriptorSpecifier itemsDescIndex = new MXMLDescriptorSpecifier();
itemsDescIndex.isProperty = true;
itemsDescIndex.hasArray = true;
itemsDescIndex.name = "itemsDescriptorIndex";
itemsDescIndex.parent = addItems;
itemsDescIndex.value = Integer.toString(index);
addItems.propertySpecifiers.add(itemsDescIndex);
//-----------------------------------------------------------------------------
// Second property set: maybe set destination and propertyName
// get the property specifier node for the property the instanceNode represents
IMXMLPropertySpecifierNode propertySpecifier = (IMXMLPropertySpecifierNode)
instanceNode.getAncestorOfType( IMXMLPropertySpecifierNode.class);
if (propertySpecifier == null)
{
assert false; // I think this indicates an invalid tree...
}
else
{
// Check the parent - if it's an instance then we want to use these
// nodes to get our property values from. If not, then it's the root
// and we don't need to specify destination
IASNode parent = propertySpecifier.getParent();
if (parent instanceof IMXMLInstanceNode)
{
IMXMLInstanceNode parentInstance = (IMXMLInstanceNode)parent;
String parentId = parentInstance.getEffectiveID();
assert parentId != null;
String propName = propertySpecifier.getName();
MXMLDescriptorSpecifier dest = new MXMLDescriptorSpecifier();
dest.isProperty = true;
dest.name = "destination";
dest.parent = addItems;
dest.value = ASEmitterTokens.SINGLE_QUOTE.getToken() + parentId + ASEmitterTokens.SINGLE_QUOTE.getToken();
addItems.propertySpecifiers.add(dest);
MXMLDescriptorSpecifier prop = new MXMLDescriptorSpecifier();
prop.isProperty = true;
prop.name = "propertyName";
prop.parent = addItems;
prop.value = ASEmitterTokens.SINGLE_QUOTE.getToken() + propName + ASEmitterTokens.SINGLE_QUOTE.getToken();
addItems.propertySpecifiers.add(prop);
}
}
//---------------------------------------------------------------
// Third property set: position and relativeTo
String positionPropertyValue = null;
String relativeToPropertyValue = null;
// look to see if we have any sibling nodes that are not state dependent
// that come BEFORE us
IASNode instanceParent = instanceNode.getParent();
IASNode prevStatelessSibling=null;
for (int i=0; i< instanceParent.getChildCount(); ++i)
{
IASNode sib = instanceParent.getChild(i);
assert sib instanceof IMXMLInstanceNode; // surely our siblings are also instances?
// stop looking for previous nodes when we find ourself
if (sib == instanceNode)
break;
if (sib instanceof IMXMLInstanceNode && !isStateDependent(sib, state, true))
{
prevStatelessSibling = sib;
}
}
if (prevStatelessSibling == null) {
positionPropertyValue = "first"; // TODO: these should be named constants
}
else {
positionPropertyValue = "after";
relativeToPropertyValue = ((IMXMLInstanceNode)prevStatelessSibling).getEffectiveID();
}
MXMLDescriptorSpecifier pos = new MXMLDescriptorSpecifier();
pos.isProperty = true;
pos.name = "position";
pos.parent = addItems;
pos.value = ASEmitterTokens.SINGLE_QUOTE.getToken() + positionPropertyValue + ASEmitterTokens.SINGLE_QUOTE.getToken();
addItems.propertySpecifiers.add(pos);
if (relativeToPropertyValue != null)
{
MXMLDescriptorSpecifier rel = new MXMLDescriptorSpecifier();
rel.isProperty = true;
rel.name = "relativeTo";
rel.parent = addItems;
rel.value = ASEmitterTokens.SINGLE_QUOTE.getToken() + relativeToPropertyValue + ASEmitterTokens.SINGLE_QUOTE.getToken();
addItems.propertySpecifiers.add(rel);
}
}
private String nameToString(Name name)
{
String s;
Namespace ns = name.getSingleQualifier();
s = ns.getName();
if (s != "") s = s + ASEmitterTokens.MEMBER_ACCESS.getToken() + name.getBaseName();
else s = name.getBaseName();
return s;
}
/**
* Determines whether a string matches a state's name or group name.
*/
protected boolean inStateOrStateGroup(String name, IMXMLStateNode state)
{
if (state == null) return false;
if (name.contentEquals(state.getStateName()))
return true;
String[] groups = state.getStateGroups();
if (groups != null)
{
for (String s : groups)
{
if (name.contentEquals(s))
return true;
}
}
return false;
}
/**
* Determines whether a node is state-dependent.
* TODO: we should move to IMXMLNode
*/
protected boolean isStateDependent(IASNode node, IMXMLStateNode currentState, boolean includeGroups)
{
if (node instanceof IMXMLSpecifierNode)
{
String suffix = ((IMXMLSpecifierNode)node).getSuffix();
return suffix != null && suffix.length() > 0 && !inStateOrStateGroup(suffix, currentState);
}
else if (isStateDependentInstance(node, currentState, includeGroups))
return true;
return false;
}
/**
* Determines whether the geven node is an instance node, as is state dependent
*/
protected boolean isStateDependentInstance(IASNode node, IMXMLStateNode currentState, boolean includeGroups)
{
if (node instanceof IMXMLInstanceNode)
{
String[] includeIn = ((IMXMLInstanceNode)node).getIncludeIn();
String[] excludeFrom = ((IMXMLInstanceNode)node).getExcludeFrom();
if (includeGroups)
{
if (includeIn != null && currentState != null)
for (String s : includeIn)
if (inStateOrStateGroup(s, currentState)) return false;
if (excludeFrom != null && currentState != null)
{
for (String s : excludeFrom)
if (inStateOrStateGroup(s, currentState)) return true;
return false;
}
}
return includeIn != null || excludeFrom != null;
}
return false;
}
/**
* Is a give node a "databinding node"?
*/
public static boolean isDataBindingNode(IASNode node)
{
return node instanceof IMXMLDataBindingNode;
}
protected static boolean isDataboundProp(IMXMLPropertySpecifierNode propertyNode)
{
boolean ret = propertyNode.getChildCount() > 0 && isDataBindingNode(propertyNode.getInstanceNode());
// Sanity check that we based our conclusion about databinding on the correct node.
// (code assumes only one child if databinding)
int n = propertyNode.getChildCount();
for (int i = 0; i < n; i++)
{
boolean db = isDataBindingNode(propertyNode.getChild(i));
assert db == ret;
}
return ret;
}
@Override
public void emitPropertySpecifier(IMXMLPropertySpecifierNode node)
{
if (isDataboundProp(node))
return;
if (isStateDependent(node, null, true))
return;
IDefinition cdef = node.getDefinition();
IASNode cnode = node.getChild(0);
MXMLDescriptorSpecifier currentInstance = getCurrentDescriptor("i");
MXMLDescriptorSpecifier currentPropertySpecifier = new MXMLDescriptorSpecifier();
currentPropertySpecifier.isProperty = true;
currentPropertySpecifier.name = cdef != null ? cdef.getQualifiedName() : node.getName();
currentPropertySpecifier.parent = currentInstance;
boolean oldInMXMLContent = inMXMLContent;
boolean reusingDescriptor = false;
if (currentPropertySpecifier.name.equals("mxmlContent"))
{
inMXMLContent = true;
ArrayList<MXMLDescriptorSpecifier> specList =
(currentInstance == null) ? descriptorTree : currentInstance.propertySpecifiers;
for (MXMLDescriptorSpecifier ds : specList)
{
if (ds.name.equals("mxmlContent"))
{
currentPropertySpecifier = ds;
reusingDescriptor = true;
break;
}
}
}
if (currentInstance != null)
{
// we end up here for children of tags
if (!reusingDescriptor)
currentInstance.propertySpecifiers.add(currentPropertySpecifier);
}
else if (inMXMLContent)
{
// we end up here for top tags?
if (!reusingDescriptor)
descriptorTree.add(currentPropertySpecifier);
}
else
{
currentPropertySpecifier.parent = propertiesTree;
propertiesTree.propertySpecifiers.add(currentPropertySpecifier);
}
boolean valueIsArray = cnode != null && cnode instanceof IMXMLArrayNode;
boolean valueIsObject = cnode != null && cnode instanceof IMXMLObjectNode;
currentPropertySpecifier.hasArray = valueIsArray;
currentPropertySpecifier.hasObject = valueIsObject;
moveDown(false, null, currentPropertySpecifier);
getMXMLWalker().walk(cnode); // Array or Instance
moveUp(false, false);
inMXMLContent = oldInMXMLContent;
}
@Override
public void emitScript(IMXMLScriptNode node)
{
//save the script for emitting later in emitScripts()
//previously, we stringified the node and saved that instead of the
//node, but source maps don't work when you stringify a node too early -JT
scripts.add(node);
}
@Override
public void emitStyleSpecifier(IMXMLStyleSpecifierNode node)
{
}
//--------------------------------------------------------------------------
@Override
public void emitObject(IMXMLObjectNode node)
{
final int len = node.getChildCount();
if (!makingSimpleArray)
{
MXMLDescriptorSpecifier ps = getCurrentDescriptor("ps");
if (ps.hasObject || ps.parent == null) //('ps.parent == null' was added to allow a top level fx:Object definition, they were not being output without that)
{
emitInstance(node);
return;
}
for (int i = 0; i < len; i++)
{
getMXMLWalker().walk(node.getChild(i)); // props in object
}
}
else
{
MXMLDescriptorSpecifier ps = getCurrentDescriptor("ps");
if (ps.value == null)
ps.value = "";
ps.value += "{";
for (int i = 0; i < len; i++)
{
IMXMLPropertySpecifierNode propName = (IMXMLPropertySpecifierNode)node.getChild(i);
ps.value += propName.getName() + ": ";
getMXMLWalker().walk(propName.getChild(0));
if (i < len - 1)
ps.value += ", ";
}
ps.value += "}";
}
}
@Override
public void emitArray(IMXMLArrayNode node)
{
if (node.getParent().getNodeID() == ASTNodeID.MXMLDeclarationsID)
{
primitiveDeclarationNodes.add(node);
return;
}
boolean isSimple = true;
final int len = node.getChildCount();
for (int i = 0; i < len; i++)
{
final IASNode child = node.getChild(i);
ASTNodeID nodeID = child.getNodeID();
if (nodeID == ASTNodeID.MXMLArrayID || nodeID == ASTNodeID.MXMLInstanceID || nodeID == ASTNodeID.MXMLStateID)
{
isSimple = false;
break;
}
}
boolean oldMakingSimpleArray = makingSimpleArray;
MXMLDescriptorSpecifier ps = getCurrentDescriptor("ps");
if (isSimple)
{
makingSimpleArray = true;
ps.value = ASEmitterTokens.SQUARE_OPEN.getToken();
}
for (int i = 0; i < len; i++)
{
getMXMLWalker().walk(node.getChild(i)); // Instance
if (isSimple && i < len - 1)
ps.value += ASEmitterTokens.COMMA.getToken();
}
if (isSimple)
{
ps.value += ASEmitterTokens.SQUARE_CLOSE.getToken();
}
makingSimpleArray = oldMakingSimpleArray;
}
@Override
public void emitString(IMXMLStringNode node)
{
if (node.getParent().getNodeID() == ASTNodeID.MXMLDeclarationsID)
{
primitiveDeclarationNodes.add(node);
return;
}
getCurrentDescriptor("ps").valueNeedsQuotes = true;
emitAttributeValue(node);
}
@Override
public void emitMXMLClass(IMXMLClassNode node)
{
RoyaleJSProject project = (RoyaleJSProject)getMXMLWalker().getProject();
ITypeDefinition cdef = node.getValue(project);
String qname = formatQualifiedName(cdef.getQualifiedName());
ICompilationUnit classCU = project.resolveQNameToCompilationUnit(qname);
ICompilationUnit cu = project.resolveQNameToCompilationUnit(classDefinition.getQualifiedName());
project.addDependency(cu, classCU, DependencyType.EXPRESSION, qname);
MXMLDescriptorSpecifier ps = getCurrentDescriptor("ps");
ps.value = qname;
}
//--------------------------------------------------------------------------
@Override
public void emitLiteral(IMXMLLiteralNode node)
{
MXMLDescriptorSpecifier ps = getCurrentDescriptor("ps");
if (ps.value == null) // might be non-null if makingSimpleArray
ps.value = "";
if (ps.valueNeedsQuotes)
ps.value += ASEmitterTokens.SINGLE_QUOTE.getToken();
String s = node.getValue().toString();
if (ps.valueNeedsQuotes)
{
// escape all single quotes found within the string
s = s.replace(ASEmitterTokens.SINGLE_QUOTE.getToken(),
"\\" + ASEmitterTokens.SINGLE_QUOTE.getToken());
}
s = s.replace("\r\n", "\\n");
s = s.replace("\n", "\\n");
ps.value += s;
if (ps.valueNeedsQuotes)
ps.value += ASEmitterTokens.SINGLE_QUOTE.getToken();
}
//--------------------------------------------------------------------------
@Override
public void emitFactory(IMXMLFactoryNode node)
{
IASNode cnode = node.getChild(0);
ITypeDefinition type = ((IMXMLClassNode)cnode).getValue(getMXMLWalker().getProject());
if (type == null) return;
MXMLDescriptorSpecifier ps = getCurrentDescriptor("ps");
ps.value = "new " + formatQualifiedName("org.apache.royale.core.ClassFactory") + "(";
if (cnode instanceof IMXMLClassNode)
{
ps.value += formatQualifiedName(type.getQualifiedName());
}
ps.value += ")";
}
//--------------------------------------------------------------------------
@Override
public void emitComponent(IMXMLComponentNode node)
{
MXMLDescriptorSpecifier ps = getCurrentDescriptor("ps");
ps.value = "new " + formatQualifiedName("org.apache.royale.core.ClassFactory") + "(";
ps.value += formatQualifiedName(documentDefinition.getQualifiedName()) + ".";
ps.value += formatQualifiedName(node.getName());
ps.value += ")";
setBufferWrite(true);
emitSubDocument(node);
subDocuments.append(getBuilder().toString());
getBuilder().setLength(0);
setBufferWrite(false);
}
@Override
protected void setBufferWrite(boolean value)
{
super.setBufferWrite(value);
IASEmitter asEmitter = ((IMXMLBlockWalker) getMXMLWalker()).getASEmitter();
((JSRoyaleEmitter)asEmitter).setBufferWrite(value);
}
//--------------------------------------------------------------------------
// JS output
//--------------------------------------------------------------------------
private void emitHeader(IMXMLDocumentNode node)
{
String cname = node.getFileNode().getName();
String bcname = node.getBaseClassName();
RoyaleJSProject project = (RoyaleJSProject) getMXMLWalker().getProject();
List<File> sourcePaths = project.getSourcePath();
String sourceName = node.getSourcePath();
for (File sourcePath : sourcePaths)
{
if (sourceName.startsWith(sourcePath.getAbsolutePath()))
{
sourceName = sourceName.substring(sourcePath.getAbsolutePath().length() + 1);
}
}
writeNewline("/**");
writeNewline(" * Generated by Apache Royale Compiler from " + sourceName.replace('\\', '/'));
writeNewline(" * " + cname);
writeNewline(" *");
writeNewline(" * @fileoverview");
writeNewline(" *");
writeNewline(" * @suppress {checkTypes|accessControls}");
writeNewline(" */");
writeNewline();
ArrayList<String> writtenInstances = new ArrayList<String>();
emitHeaderLine(cname, true); // provide
for (String subDocumentName : subDocumentNames)
{
emitHeaderLine(subDocumentName, true);
writtenInstances.add(formatQualifiedName(subDocumentName));
}
writeNewline();
emitHeaderLine(bcname);
writtenInstances.add(formatQualifiedName(cname)); // make sure we don't add ourselves
writtenInstances.add(formatQualifiedName(bcname)); // make sure we don't add the baseclass twice
allInstances.addAll(0, instances);
for (MXMLDescriptorSpecifier instance : allInstances)
{
String name = instance.name;
if (writtenInstances.indexOf(name) == -1)
{
emitHeaderLine(name);
writtenInstances.add(name);
}
}
ASProjectScope projectScope = (ASProjectScope) project.getScope();
IDefinition cdef = node.getDefinition();
ICompilationUnit cu = projectScope
.getCompilationUnitForDefinition(cdef);
ArrayList<String> deps = project.getRequires(cu);
// TODO (mschmalle) will remove this cast as more things get abstracted
JSRoyaleEmitter fjs = (JSRoyaleEmitter) ((IMXMLBlockWalker) getMXMLWalker())
.getASEmitter();
if (fjs.getModel().hasStaticBindableVars()) {
//we need to add EventDispatcher
if (deps.indexOf(BindableEmitter.DISPATCHER_CLASS_QNAME) == -1)
deps.add(BindableEmitter.DISPATCHER_CLASS_QNAME);
if (usedNames.indexOf(BindableEmitter.DISPATCHER_CLASS_QNAME) == -1)
usedNames.add(BindableEmitter.DISPATCHER_CLASS_QNAME);
}
if (interfaceList != null)
{
String[] interfaces = interfaceList.split(", ");
for (String iface : interfaces)
{
deps.add(iface);
usedNames.add(iface);
}
}
if (deps != null)
{
Collections.sort(deps);
for (String imp : deps)
{
if (imp.indexOf(JSGoogEmitterTokens.AS3.getToken()) != -1)
continue;
if (imp.equals(cname))
continue;
if (imp.equals("mx.binding.Binding"))
continue;
if (imp.equals("mx.binding.BindingManager"))
continue;
if (imp.equals("mx.binding.FunctionReturnWatcher"))
continue;
if (imp.equals("mx.binding.PropertyWatcher"))
continue;
if (imp.equals("mx.binding.StaticPropertyWatcher"))
continue;
if (imp.equals("mx.binding.XMLWatcher"))
continue;
if (imp.equals("mx.events.PropertyChangeEvent"))
continue;
if (imp.equals("mx.events.PropertyChangeEventKind"))
continue;
if (imp.equals("mx.core.DeferredInstanceFromFunction"))
continue;
if (NativeUtils.isNative(imp))
continue;
String formatted = formatQualifiedName(imp, false);
if (writtenInstances.indexOf(formatted) == -1)
{
emitHeaderLine(imp);
writtenInstances.add(formatted);
}
}
}
// erikdebruin: Add missing language feature support, like the 'is' and
// 'as' operators. We don't need to worry about requiring
// this in every project: ADVANCED_OPTIMISATIONS will NOT
// include any of the code if it is not used in the project.
if (project.mainCU != null &&
cu.getName().equals(project.mainCU.getName()))
{
if (project instanceof RoyaleJSProject)
{
if (((RoyaleJSProject)project).needLanguage)
emitHeaderLine(JSRoyaleEmitterTokens.LANGUAGE_QNAME.getToken());
}
}
writeNewline();
writeNewline();
}
private void emitHeaderLine(String qname)
{
emitHeaderLine(qname, false);
}
private void emitHeaderLine(String qname, boolean isProvide)
{
write((isProvide) ? JSGoogEmitterTokens.GOOG_PROVIDE
: JSGoogEmitterTokens.GOOG_REQUIRE);
write(ASEmitterTokens.PAREN_OPEN);
write(ASEmitterTokens.SINGLE_QUOTE);
write(formatQualifiedName(qname, false));
write(ASEmitterTokens.SINGLE_QUOTE);
write(ASEmitterTokens.PAREN_CLOSE);
writeNewline(ASEmitterTokens.SEMICOLON);
}
private String createRequireLine(String qname, boolean isProvide) {
StringBuilder createHeader = new StringBuilder();
createHeader.append(isProvide ? JSGoogEmitterTokens.GOOG_PROVIDE.getToken() : JSGoogEmitterTokens.GOOG_REQUIRE.getToken());
createHeader.append(ASEmitterTokens.PAREN_OPEN.getToken());
createHeader.append(ASEmitterTokens.SINGLE_QUOTE.getToken());
createHeader.append(qname);
createHeader.append(ASEmitterTokens.SINGLE_QUOTE.getToken());
createHeader.append(ASEmitterTokens.PAREN_CLOSE.getToken());
createHeader.append(ASEmitterTokens.SEMICOLON.getToken());
return createHeader.toString();
}
//--------------------------------------------------------------------------
// Utils
//--------------------------------------------------------------------------
@Override
protected void emitAttributeValue(IASNode node)
{
IMXMLLiteralNode cnode = (IMXMLLiteralNode) node.getChild(0);
if (cnode.getValue() != null)
getMXMLWalker().walk((IASNode) cnode); // Literal
}
private MXMLDescriptorSpecifier getCurrentDescriptor(String type)
{
MXMLDescriptorSpecifier currentDescriptor = null;
int index;
if (type.equals("i"))
{
index = currentInstances.size() - 1;
if (index > -1)
currentDescriptor = currentInstances.get(index);
}
else if (type.equals("so"))
{
return currentStateOverrides;
}
else
{
index = currentPropertySpecifiers.size() - 1;
if (index > -1)
currentDescriptor = currentPropertySpecifiers.get(index);
}
return currentDescriptor;
}
protected void moveDown(boolean byPass,
MXMLDescriptorSpecifier currentInstance,
MXMLDescriptorSpecifier currentPropertySpecifier)
{
if (!byPass)
{
if (currentInstance != null)
currentInstances.add(currentInstance);
}
if (currentPropertySpecifier != null)
currentPropertySpecifiers.add(currentPropertySpecifier);
}
protected void moveUp(boolean byPass, boolean isInstance)
{
if (!byPass)
{
int index;
if (isInstance)
{
index = currentInstances.size() - 1;
if (index > -1)
currentInstances.remove(index);
}
else
{
index = currentPropertySpecifiers.size() - 1;
if (index > -1)
currentPropertySpecifiers.remove(index);
}
}
}
public String formatQualifiedName(String name)
{
return formatQualifiedName(name, true);
}
protected String formatQualifiedName(String name, boolean useName)
{
/*
if (name.contains("goog.") || name.startsWith("Vector."))
return name;
name = name.replaceAll("\\.", "_");
*/
if (subDocumentNames.contains(name))
return documentDefinition.getQualifiedName() + "." + name;
if (NativeUtils.isJSNative(name)) return name;
if (inStaticInitializer)
{
if (!staticUsedNames.contains(name) && !NativeUtils.isJSNative(name) && isGoogProvided(name))
{
staticUsedNames.add(name);
}
}
if (useName && !usedNames.contains(name) && isGoogProvided(name))
{
usedNames.add(name);
}
return name;
}
@SuppressWarnings("incomplete-switch")
private void emitComplexInitializers(IASNode node)
{
int n = node.getChildCount();
for (int i = 0; i < n; i++)
{
IASNode child = node.getChild(i);
if (child.getNodeID() == ASTNodeID.MXMLScriptID)
{
int m = child.getChildCount();
for (int j = 0; j < m; j++)
{
IASNode schild = child.getChild(j);
ASTNodeID schildID = schild.getNodeID();
if (schildID == ASTNodeID.VariableID ||
schildID == ASTNodeID.BindableVariableID)
{
IVariableNode varnode = (IVariableNode)schild;
IExpressionNode vnode = varnode.getAssignedValueNode();
if (vnode != null && (!EmitterUtils.isScalar(vnode)))
{
IDefinition varDef = varnode.getDefinition();
if (varDef.isStatic())
continue;
writeNewline();
write(ASEmitterTokens.THIS);
write(ASEmitterTokens.MEMBER_ACCESS);
JSRoyaleEmitter fjs = (JSRoyaleEmitter) ((IMXMLBlockWalker) getMXMLWalker())
.getASEmitter();
ICompilerProject project = getMXMLWalker().getProject();
String qname = varnode.getName();
if (varDef != null && varDef.isPrivate() && project.getAllowPrivateNameConflicts())
qname = fjs.formatPrivateName(varDef.getParent().getQualifiedName(), qname);
if (EmitterUtils.isCustomNamespace(varnode.getNamespace())) {
INamespaceDecorationNode ns = ((VariableNode) varnode).getNamespaceNode();
INamespaceDefinition nsDef = (INamespaceDefinition)ns.resolve(project);
fjs.formatQualifiedName(nsDef.getQualifiedName()); // register with used names
String s = nsDef.getURI();
write(JSRoyaleEmitter.formatNamespacedProperty(s, qname, false));
}
else write(qname);
if (schildID == ASTNodeID.BindableVariableID && !varnode.isConst())
write("_"); // use backing variable
write(ASEmitterTokens.SPACE);
writeToken(ASEmitterTokens.EQUAL);
fjs.emitAssignmentCoercion(vnode, varnode.getVariableTypeNode().resolve(getMXMLWalker().getProject()));
write(ASEmitterTokens.SEMICOLON);
}
}
}
}
}
n = primitiveDeclarationNodes.size();
for (int i = 0; i < n; i++)
{
IMXMLInstanceNode declNode = primitiveDeclarationNodes.get(i);
ASTNodeID nodeId = declNode.getNodeID();
String varname;
switch (nodeId)
{
case MXMLStringID:
{
IMXMLStringNode stringNode = (IMXMLStringNode)declNode;
varname = stringNode.getEffectiveID();
writeNewline();
write(ASEmitterTokens.THIS);
write(ASEmitterTokens.MEMBER_ACCESS);
write(varname);
write(ASEmitterTokens.SPACE);
writeToken(ASEmitterTokens.EQUAL);
IMXMLLiteralNode valueNode = (IMXMLLiteralNode)(stringNode.getExpressionNode());
Object value = valueNode.getValue();
write(objectToString(value));
write(ASEmitterTokens.SEMICOLON);
break;
}
case MXMLArrayID:
{
IMXMLArrayNode arrayNode = (IMXMLArrayNode)declNode;
varname = arrayNode.getEffectiveID();
writeNewline();
write(ASEmitterTokens.THIS);
write(ASEmitterTokens.MEMBER_ACCESS);
write(varname);
write(ASEmitterTokens.SPACE);
writeToken(ASEmitterTokens.EQUAL);
write("[");
int m = arrayNode.getChildCount();
boolean firstOne = true;
for (int j = 0; j < m; j++)
{
IMXMLInstanceNode valueNode = (IMXMLInstanceNode)(arrayNode.getChild(j));
if (firstOne)
firstOne = false;
else
writeToken(",");
write(instanceToString(valueNode));
}
write("]");
write(ASEmitterTokens.SEMICOLON);
break;
}
case MXMLXMLID:
{
IMXMLXMLNode xmlNode = (IMXMLXMLNode)declNode;
String valueString = xmlNode.getXMLString();
if (valueString != null)
{
varname = xmlNode.getEffectiveID();
writeNewline();
write(ASEmitterTokens.THIS);
write(ASEmitterTokens.MEMBER_ACCESS);
write(varname);
write(ASEmitterTokens.SPACE);
writeToken(ASEmitterTokens.EQUAL);
write("new XML('");
write(StringEscapeUtils.escapeJavaScript(valueString));
write("')");
write(ASEmitterTokens.SEMICOLON);
}
break;
}
case MXMLXMLListID:
{
IMXMLXMLListNode xmlNode = (IMXMLXMLListNode)declNode;
String valueString = xmlNode.getXMLString();
if (valueString != null)
{
varname = xmlNode.getEffectiveID();
writeNewline();
write(ASEmitterTokens.THIS);
write(ASEmitterTokens.MEMBER_ACCESS);
write(varname);
write(ASEmitterTokens.SPACE);
writeToken(ASEmitterTokens.EQUAL);
write("new XMLList('");
write(StringEscapeUtils.escapeJavaScript(valueString));
write("')");
write(ASEmitterTokens.SEMICOLON);
}
break;
}
}
}
}
private String objectToString(Object value)
{
if (value instanceof String)
{
String s = (String)value;
s = StringEscapeUtils.escapeJavaScript(s);
return "'" + s + "'";
}
return "";
}
private String instanceToString(IMXMLInstanceNode instanceNode)
{
if (instanceNode instanceof IMXMLStringNode)
{
IMXMLStringNode stringNode = (IMXMLStringNode)instanceNode;
IASNode vNode = stringNode.getExpressionNode();
if (vNode instanceof IMXMLLiteralNode)
{
IMXMLLiteralNode valueNode = (IMXMLLiteralNode)vNode;
Object value = valueNode.getValue();
return objectToString(value);
}
else
return "''";
}
return "";
}
public void emitComplexStaticInitializers(IASNode node){
JSRoyaleEmitter fjs = (JSRoyaleEmitter) ((IMXMLBlockWalker) getMXMLWalker())
.getASEmitter();
if (!fjs.getFieldEmitter().hasComplexStaticInitializers) return;
int n = node.getChildCount();
boolean sawOutput = false;
for (int i = 0; i < n; i++)
{
IASNode child = node.getChild(i);
if (child.getNodeID() == ASTNodeID.MXMLScriptID)
{
int m = child.getChildCount();
for (int j = 0; j < m; j++)
{
IASNode schild = child.getChild(j);
ASTNodeID schildID = schild.getNodeID();
if (schildID == ASTNodeID.VariableID ||
schildID == ASTNodeID.BindableVariableID)
{
sawOutput = fjs.getFieldEmitter().emitFieldInitializer((IVariableNode) schild) || sawOutput;
}
}
}
}
if (sawOutput) {
writeNewline();
writeNewline();
}
}
@Override
public void emitImplements(IMXMLImplementsNode node)
{
StringBuilder list = new StringBuilder();
boolean needsComma = false;
IIdentifierNode[] interfaces = node.getInterfaceNodes();
for (IIdentifierNode iface : interfaces)
{
if (needsComma)
list.append(", ");
list.append(iface.getName());
needsComma = true;
}
//System.out.println("mxml implements "+list);
interfaceList = list.toString();
}
boolean isGoogProvided(String className)
{
ICompilerProject project = getMXMLWalker().getProject();
return ((RoyaleJSProject)project).isGoogProvided(className);
}
@Override
public void emitRemoteObjectMethod(IMXMLRemoteObjectMethodNode node) {
MXMLDescriptorSpecifier currentInstance = getCurrentDescriptor("i");
String propName = null;
int l = node.getChildCount();
for (int k = 0; k < l; k++)
{
IASNode child = node.getChild(k);
if (child.getNodeID() == ASTNodeID.MXMLPropertySpecifierID)
{
IMXMLPropertySpecifierNode propNode = (IMXMLPropertySpecifierNode)child;
if (propNode.getName().equals("name"))
{
// assume StringNode with LiteralNode
IMXMLStringNode literalNode = (IMXMLStringNode)propNode.getChild(0);
propName = literalNode.getValue();
break;
}
}
}
MXMLDescriptorSpecifier propertySpecifier = new MXMLDescriptorSpecifier();
propertySpecifier.isProperty = true;
propertySpecifier.name = propName;
propertySpecifier.parent = currentInstance;
currentInstance.propertySpecifiers.add(propertySpecifier);
moveDown(false, null, propertySpecifier);
emitInstance(node);
moveUp(false, false);
// build out the argument list if any
int n = node.getChildCount();
for (int i = 0; i < n; i++)
{
IASNode childNode = node.getChild(i);
if (childNode.getNodeID() == ASTNodeID.MXMLPropertySpecifierID)
{
IMXMLPropertySpecifierNode propNode = (IMXMLPropertySpecifierNode)childNode;
if (propNode.getName().equals("arguments"))
{
ArrayList<String> argList = new ArrayList<String>();
childNode = propNode.getChild(0); // this is an MXMLObjectNode
n = childNode.getChildCount();
for (i = 0; i < n; i++)
{
IASNode argNode = childNode.getChild(i);
propNode = (IMXMLPropertySpecifierNode)argNode;
argList.add(propNode.getName());
}
if (argList.size() > 0)
{
StringBuilder list = new StringBuilder();
list.append("[");
int m = argList.size();
for (int j = 0; j < m; j++)
{
if (j > 0)
list.append(",");
list.append("'" + argList.get(j) + "'");
}
list.append("]");
MXMLDescriptorSpecifier operationInstance = propertySpecifier.propertySpecifiers.get(0);
MXMLDescriptorSpecifier argListSpecifier = new MXMLDescriptorSpecifier();
argListSpecifier.isProperty = true;
argListSpecifier.name = "argumentNames";
argListSpecifier.parent = operationInstance;
argListSpecifier.value = list.toString();
if (operationInstance != null)
operationInstance.propertySpecifiers.add(argListSpecifier);
}
break;
}
}
}
}
@Override
public void emitRemoteObject(IMXMLRemoteObjectNode node) {
emitInstance(node);
// now search for Operations, and add an Object that contains them
int n = node.getChildCount();
MXMLDescriptorSpecifier objectSpecifier = null;
MXMLDescriptorSpecifier propertySpecifier = null;
for (int i = 0; i < n; i++)
{
IASNode child = node.getChild(i);
if (child.getNodeID() == ASTNodeID.MXMLRemoteObjectMethodID)
{
MXMLDescriptorSpecifier currentPropertySpecifier = getCurrentDescriptor("ps");
MXMLDescriptorSpecifier currentInstance =
currentPropertySpecifier.propertySpecifiers.get(currentPropertySpecifier.propertySpecifiers.size() - 1);
if (objectSpecifier == null)
{
propertySpecifier = new MXMLDescriptorSpecifier();
propertySpecifier.isProperty = true;
propertySpecifier.name = "operations";
propertySpecifier.parent = currentInstance;
if (currentInstance != null)
currentInstance.propertySpecifiers.add(propertySpecifier);
objectSpecifier = new MXMLDescriptorSpecifier();
objectSpecifier.isProperty = false;
objectSpecifier.name = formatQualifiedName(IASLanguageConstants.Object);
objectSpecifier.parent = propertySpecifier;
propertySpecifier.propertySpecifiers.add(objectSpecifier);
instances.add(objectSpecifier);
}
moveDown(false, objectSpecifier, null);
getMXMLWalker().walk(child); // RemoteObjectMethod
moveUp(false, true);
}
}
}
@Override
public void emitWebServiceMethod(IMXMLWebServiceOperationNode node) {
MXMLDescriptorSpecifier currentInstance = getCurrentDescriptor("i");
String propName = null;
int l = node.getChildCount();
for (int k = 0; k < l; k++)
{
IASNode child = node.getChild(k);
if (child.getNodeID() == ASTNodeID.MXMLPropertySpecifierID)
{
IMXMLPropertySpecifierNode propNode = (IMXMLPropertySpecifierNode)child;
if (propNode.getName().equals("name"))
{
// assume StringNode with LiteralNode
IMXMLStringNode literalNode = (IMXMLStringNode)propNode.getChild(0);
propName = literalNode.getValue();
break;
}
}
}
MXMLDescriptorSpecifier propertySpecifier = new MXMLDescriptorSpecifier();
propertySpecifier.isProperty = true;
propertySpecifier.name = propName;
propertySpecifier.parent = currentInstance;
currentInstance.propertySpecifiers.add(propertySpecifier);
moveDown(false, null, propertySpecifier);
emitInstance(node);
moveUp(false, false);
// build out the argument list if any
int n = node.getChildCount();
for (int i = 0; i < n; i++)
{
IASNode childNode = node.getChild(i);
if (childNode.getNodeID() == ASTNodeID.MXMLPropertySpecifierID)
{
IMXMLPropertySpecifierNode propNode = (IMXMLPropertySpecifierNode)childNode;
if (propNode.getName().equals("arguments"))
{
ArrayList<String> argList = new ArrayList<String>();
childNode = propNode.getChild(0); // this is an MXMLObjectNode
n = childNode.getChildCount();
for (i = 0; i < n; i++)
{
IASNode argNode = childNode.getChild(i);
propNode = (IMXMLPropertySpecifierNode)argNode;
argList.add(propNode.getName());
}
if (argList.size() > 0)
{
StringBuilder list = new StringBuilder();
list.append("[");
int m = argList.size();
for (int j = 0; j < m; j++)
{
if (j > 0)
list.append(",");
list.append("'" + argList.get(j) + "'");
}
list.append("]");
MXMLDescriptorSpecifier operationInstance = propertySpecifier.propertySpecifiers.get(0);
MXMLDescriptorSpecifier argListSpecifier = new MXMLDescriptorSpecifier();
argListSpecifier.isProperty = true;
argListSpecifier.name = "argumentNames";
argListSpecifier.parent = operationInstance;
argListSpecifier.value = list.toString();
if (operationInstance != null)
operationInstance.propertySpecifiers.add(argListSpecifier);
}
break;
}
}
}
}
@Override
public void emitWebService(IMXMLWebServiceNode node) {
emitInstance(node);
// now search for Operations, and add an Object that contains them
int n = node.getChildCount();
MXMLDescriptorSpecifier objectSpecifier = null;
MXMLDescriptorSpecifier propertySpecifier = null;
for (int i = 0; i < n; i++)
{
IASNode child = node.getChild(i);
if (child.getNodeID() == ASTNodeID.MXMLWebServiceOperationID)
{
MXMLDescriptorSpecifier currentPropertySpecifier = getCurrentDescriptor("ps");
MXMLDescriptorSpecifier currentInstance =
currentPropertySpecifier.propertySpecifiers.get(currentPropertySpecifier.propertySpecifiers.size() - 1);
if (objectSpecifier == null)
{
propertySpecifier = new MXMLDescriptorSpecifier();
propertySpecifier.isProperty = true;
propertySpecifier.name = "operations";
propertySpecifier.parent = currentInstance;
if (currentInstance != null)
currentInstance.propertySpecifiers.add(propertySpecifier);
objectSpecifier = new MXMLDescriptorSpecifier();
objectSpecifier.isProperty = false;
objectSpecifier.name = formatQualifiedName(IASLanguageConstants.Object);
objectSpecifier.parent = propertySpecifier;
propertySpecifier.propertySpecifiers.add(objectSpecifier);
instances.add(objectSpecifier);
}
moveDown(false, objectSpecifier, null);
getMXMLWalker().walk(child); // RemoteObjectMethod
moveUp(false, true);
}
}
}
}
|
jonnyzzz/phd-project | morse/DotNet/calculator/FunctionNodeMin.h | #pragma once
#include "functionnode.h"
class FunctionNodeMin :
public FunctionNode
{
public:
FunctionNodeMin(FunctionNode* left, FunctionNode* right);
virtual ~FunctionNodeMin(void);
public:
virtual double evaluate(FunctionContext* cx);
virtual bool canSimplify(FunctionContext* cx);
virtual FunctionNode* simplify(FunctionContext* cx);
virtual FunctionNode* diff(int variableID);
virtual FunctionNode* clone();
public:
virtual void print(ostream& o, FunctionDictionary* dic);
public:
virtual void appendDependency(FunctionNodeDependency* dependency);
virtual FunctionNodeType type();
virtual void Accept(FunctionNodeVisitor* visitor);
public:
FunctionNode* getLeft();
FunctionNode* getRight();
private:
FunctionNode* left;
FunctionNode* right;
};
|
bioinsilico/3DBIONOTES | lib/tasks/swissvarentries.rake | namespace :swissvarentries do
desc "Seeds SwissVar"
localDB = Settings.GS_LocalDB
localAppDB = Settings.GS_LocalAppDB
#AminoDic = {'CYS'=>'C', 'ASP'=>'D', 'SER'=>'S', 'GLN'=>'Q', 'LYS'=>'K','ILE'=>'I', 'PRO'=>'P', 'THR'=>'T', 'PHE'=>'F', 'ASN'=>'N', 'GLY'=>'G', 'HIS'=>'H', 'LEU'=>'L', 'ARG'=>'R', 'TRP'=>'W','ALA'=>'A', 'VAL'=>'V', 'GLU'=>'E', 'TYR'=>'Y', 'MET'=>'M'}
task seed_swissvar: :environment do
data = `awk -F"\t" '{if(length($3)>0 && length($6)>0)print $0}' #{localDB}/SWISSVAR/swissvar.tsv`
data = data.split(/\n/)
file = File.open(localAppDB+"/mysql/swissvar.tsv",'w')
out = {}
data.each do |l|
r = l.split("\t")
res = r[5]
res.slice!(0,2)
original = AminoDic[res.slice!(0,3).upcase]
variation = AminoDic[res.slice!(-3,3).upcase]
acc = r[0]
acc.gsub!(/\t+|\s+/,'')
dis = r[2]
var = r[4]
x = {start:res.to_i, end:res.to_i, position:res.to_i, original:original, variation:variation, disease:dis, evidence:var}
out[acc] = [] unless out.key? acc
out[acc].push x
end
out.each do |k,v|
file.write("NULL\t"+k+"\t"+v.to_json+"\n")
end
file.close()
end
end
|
cerberus707/lab-python | Conteudo das Aulas/015/Exercicios/Exercicio 2.py | <filename>Conteudo das Aulas/015/Exercicios/Exercicio 2.py
"""
Dados n e uma seqüência de n números inteiros,
determinar a soma dos números pares.
"""
|
spring2go/geekstore | src/test/java/io/geekstore/common/utils/TimeSpanUtilTest.java | <reponame>spring2go/geekstore<filename>src/test/java/io/geekstore/common/utils/TimeSpanUtilTest.java
/*
* Copyright (c) 2020 GeekStore.
* All rights reserved.
*/
package io.geekstore.common.utils;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Created on Nov, 2020 by @author bobo
*/
public class TimeSpanUtilTest {
@Test
public void testTimeSpanUtil() {
long result = TimeSpanUtil.toMs("2 days");
assertThat(result).isEqualTo(172800000);
result = TimeSpanUtil.toMs("2 DAYS");
assertThat(result).isEqualTo(172800000);
result = TimeSpanUtil.toMs("1y");
assertThat(result).isEqualTo(31536001024L);
result = TimeSpanUtil.toMs("100");
assertThat(result).isEqualTo(100);
result = TimeSpanUtil.toMs("1m");
assertThat(result).isEqualTo(60000);
result = TimeSpanUtil.toMs("1h");
assertThat(result).isEqualTo(3600000);
result = TimeSpanUtil.toMs("2.5 hrs");
assertThat(result).isEqualTo(9000000);
result = TimeSpanUtil.toMs("2d");
assertThat(result).isEqualTo(172800000);
result = TimeSpanUtil.toMs("3w");
assertThat(result).isEqualTo(1814400000);
result = TimeSpanUtil.toMs("1s");
assertThat(result).isEqualTo(1000);
result = TimeSpanUtil.toMs("100ms");
assertThat(result).isEqualTo(100);
result = TimeSpanUtil.toMs("1.5h");
assertThat(result).isEqualTo(5400000);
result = TimeSpanUtil.toMs("1 s");
assertThat(result).isEqualTo(1000);
result = TimeSpanUtil.toMs("1.5H");
assertThat(result).isEqualTo(5400000);
result = TimeSpanUtil.toMs(".5ms");
assertThat(result).isEqualTo(0);
result = TimeSpanUtil.toMs("-100ms");
assertThat(result).isEqualTo(-100);
result = TimeSpanUtil.toMs("-1.5h");
assertThat(result).isEqualTo(-5400000);
result = TimeSpanUtil.toMs("-10.5h");
assertThat(result).isEqualTo(-37800000);
result = TimeSpanUtil.toMs("-.5h");
assertThat(result).isEqualTo(-1800000);
}
}
|
stoys-io/stoys-python | tests/utils/scala_compat_test.py | <filename>tests/utils/scala_compat_test.py
from stoys.utils.scala_compat import Map, Option, Seq, Some
def test_option() -> None:
assert Option(None) is None
assert Option("foo") == "foo"
assert Some("foo") == "foo"
def test_seq() -> None:
assert Seq.empty == []
assert Seq() == []
assert Seq(1, 2, 3, 4) == [1, 2, 3, 4]
def test_map() -> None:
assert Map.empty == {}
assert Map() == {}
assert Map(foo="foo", bar="bar") == {"foo": "foo", "bar": "bar"}
assert Map(("foo", "foo")) == {"foo": "foo"}
assert Map(("foo", "foo"), ("bar", "bar")) == {"foo": "foo", "bar": "bar"}
# assert Map('foo' -> 'foo', 'bar' -> 'bar') == {'foo': 'foo', 'bar': 'bar'}
|
andraantariksa/PlasmaEngine | Source/Core/Meta/VariantTypes.inl | <gh_stars>10-100
// MIT Licensed (see LICENSE.md).
DoVariantType(String);
DoVariantType(int);
DoVariantType(uint);
DoVariantType(float);
DoVariantType(double);
DoVariantType(bool);
DoVariantType(Vec2);
DoVariantType(Vec3);
DoVariantType(Vec4);
DoVariantType(Quat);
|
iTondy/gkccash_core | src/qml/build/moc_mnemonicmanager.cpp | /****************************************************************************
** Meta object code from reading C++ file 'mnemonicmanager.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.10.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../qt_native/mnemonicmanager.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'mnemonicmanager.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.10.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_MnemonicManager_t {
QByteArrayData data[15];
char stringdata0[208];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_MnemonicManager_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_MnemonicManager_t qt_meta_stringdata_MnemonicManager = {
{
QT_MOC_LITERAL(0, 0, 15), // "MnemonicManager"
QT_MOC_LITERAL(1, 16, 16), // "mnemonicFinished"
QT_MOC_LITERAL(2, 33, 0), // ""
QT_MOC_LITERAL(3, 34, 10), // "RandomInit"
QT_MOC_LITERAL(4, 45, 14), // "GetRandomIndex"
QT_MOC_LITERAL(5, 60, 5), // "index"
QT_MOC_LITERAL(6, 66, 21), // "GetRandomMnemonicWord"
QT_MOC_LITERAL(7, 88, 18), // "CheckMnemonicWords"
QT_MOC_LITERAL(8, 107, 5), // "words"
QT_MOC_LITERAL(9, 113, 17), // "CheckMnemonicWord"
QT_MOC_LITERAL(10, 131, 4), // "word"
QT_MOC_LITERAL(11, 136, 16), // "SetMnemonicWords"
QT_MOC_LITERAL(12, 153, 16), // "GetMnemonicWords"
QT_MOC_LITERAL(13, 170, 15), // "GetMnemonicWord"
QT_MOC_LITERAL(14, 186, 21) // "CheckMnemonicFinished"
},
"MnemonicManager\0mnemonicFinished\0\0"
"RandomInit\0GetRandomIndex\0index\0"
"GetRandomMnemonicWord\0CheckMnemonicWords\0"
"words\0CheckMnemonicWord\0word\0"
"SetMnemonicWords\0GetMnemonicWords\0"
"GetMnemonicWord\0CheckMnemonicFinished"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_MnemonicManager[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
10, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: name, argc, parameters, tag, flags
1, 0, 64, 2, 0x06 /* Public */,
// methods: name, argc, parameters, tag, flags
3, 0, 65, 2, 0x02 /* Public */,
4, 1, 66, 2, 0x02 /* Public */,
6, 1, 69, 2, 0x02 /* Public */,
7, 1, 72, 2, 0x02 /* Public */,
9, 2, 75, 2, 0x02 /* Public */,
11, 0, 80, 2, 0x02 /* Public */,
12, 0, 81, 2, 0x02 /* Public */,
13, 1, 82, 2, 0x02 /* Public */,
14, 0, 85, 2, 0x02 /* Public */,
// signals: parameters
QMetaType::Void,
// methods: parameters
QMetaType::Void,
QMetaType::QString, QMetaType::Int, 5,
QMetaType::QString, QMetaType::Int, 5,
QMetaType::Bool, QMetaType::QString, 8,
QMetaType::Bool, QMetaType::QString, QMetaType::QString, 5, 10,
QMetaType::Void,
QMetaType::QString,
QMetaType::QString, QMetaType::Int, 5,
QMetaType::Void,
0 // eod
};
void MnemonicManager::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
MnemonicManager *_t = static_cast<MnemonicManager *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->mnemonicFinished(); break;
case 1: _t->RandomInit(); break;
case 2: { QString _r = _t->GetRandomIndex((*reinterpret_cast< int(*)>(_a[1])));
if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = std::move(_r); } break;
case 3: { QString _r = _t->GetRandomMnemonicWord((*reinterpret_cast< int(*)>(_a[1])));
if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = std::move(_r); } break;
case 4: { bool _r = _t->CheckMnemonicWords((*reinterpret_cast< QString(*)>(_a[1])));
if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = std::move(_r); } break;
case 5: { bool _r = _t->CheckMnemonicWord((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2])));
if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = std::move(_r); } break;
case 6: _t->SetMnemonicWords(); break;
case 7: { QString _r = _t->GetMnemonicWords();
if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = std::move(_r); } break;
case 8: { QString _r = _t->GetMnemonicWord((*reinterpret_cast< int(*)>(_a[1])));
if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = std::move(_r); } break;
case 9: _t->CheckMnemonicFinished(); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
{
typedef void (MnemonicManager::*_t)();
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&MnemonicManager::mnemonicFinished)) {
*result = 0;
return;
}
}
}
}
QT_INIT_METAOBJECT const QMetaObject MnemonicManager::staticMetaObject = {
{ &QObject::staticMetaObject, qt_meta_stringdata_MnemonicManager.data,
qt_meta_data_MnemonicManager, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *MnemonicManager::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *MnemonicManager::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_MnemonicManager.stringdata0))
return static_cast<void*>(this);
return QObject::qt_metacast(_clname);
}
int MnemonicManager::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 10)
qt_static_metacall(this, _c, _id, _a);
_id -= 10;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 10)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 10;
}
return _id;
}
// SIGNAL 0
void MnemonicManager::mnemonicFinished()
{
QMetaObject::activate(this, &staticMetaObject, 0, nullptr);
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
|
fancylou/o2oa | x_organization_assemble_control_alpha/jest/department.js | department_parameter = {
root : common_parameter.host + '/x_organization_assemble_control/jaxrs/department',
list_action : null,
list_action_parameter : null,
first : '(0)',
last : '(0)',
count : 20
};
function department_list_reload() {
if (department_parameter.list_action) {
department_parameter.list_action.call(window, department_parameter.list_action_parameter);
} else {
department_list_next('(0)');
}
}
function department_list_next(id) {
var id = ( id ? id : department_parameter.last);
department_parameter.list_action = department_list_next;
department_parameter.list_action_parameter = id;
$.ajax({
type : 'get',
dataType : 'json',
url : department_parameter.root + '/list/' + id + '/next/' + department_parameter.count,
xhrFields : {
'withCredentials' : true
},
crossDomain : true
}).done(function(data) {
if (data.type == 'success') {
if (data.data.length > 0) {
department_parameter.first = data.data[0].id;
department_parameter.last = data.data[data.data.length - 1].id;
} else {
department_parameter.first = '(0)';
}
$('#content').html(department_list_grid(data.data));
$('#total', '#content').html(data.count);
department_list_init();
} else {
failure(data);
}
});
}
function department_list_prev(id) {
var id = ( id ? id : department_parameter.first);
department_parameter.list_action = department_list_prev;
department_parameter.list_action_parameter = id;
$.ajax({
type : 'get',
dataType : 'json',
url : department_parameter.root + '/list/' + id + '/prev/' + department_parameter.count,
xhrFields : {
'withCredentials' : true
},
crossDomain : true
}).done(function(data) {
if (data.type == 'success') {
if (data.data.length > 0) {
department_parameter.first = data.data[0].id;
department_parameter.last = data.data[data.data.length - 1].id;
} else {
department_parameter.last = '(0)';
}
$('#content').html(department_list_grid(data.data));
$('#total', '#content').html(data.count);
department_list_init();
} else {
failure(data);
}
});
}
function department_list_grid(items) {
var str = '<table border="1" width="100%">';
str += '<tr><td colspan="6"> <a href="#" id="prev">prev</a> <a href="#" id="next">next</a> <span id="total">0</span></td></tr>';
str += '<tr><th>rank</th><th>id</th><th>name</th><th>level</th><th>superior</th><th>operate</th></tr>';
$.each(items, function(index, item) {
str += '<tr>';
str += '<td>' + item.rank + '</td>';
str += '<td>' + item.id + '</td>';
str += '<td>' + item.name + '</td>';
str += '<td>' + item.level + '</td>';
str += '<td>' + item.superior + '</td>';
str += '<td>';
str += '<a href="#" onclick="department_edit(\'' + item.id + '\')">edit</a> ';
str += '<a href="#" onclick="department_delete(\'' + item.id + '\')">delete</a>';
str += '</td>';
str += '</tr>';
});
str += '</table>';
return str;
}
function department_list_init() {
$('#next', '#content').click(function() {
department_list_next();
});
$('#prev', '#content').click(function() {
department_list_prev();
});
}
function department_create() {
var str = '<table border="1" width="100%">';
str += '<tr><td colspan="2"><a href="#" id="post">post</a></td></tr>';
str += '<tr><td>name:</td><td><input type="text" id="name" style="width:95%"/></td></tr>';
str += '<tr><td>company:</td><td><input type="text" id="company" style="width:95%"/></td></tr>';
str += '<tr><td>superior:</td><td><input type="text" id="superior" style="width:95%"/></td></tr>';
str += '<tr><td>unique:</td><td><input type="text" id="unique" style="width:95%"/></td></tr>';
str += '</table>';
$('#content').html(str);
$('#post', '#content').click(function() {
department_post();
});
}
function department_post() {
$.ajax({
type : 'post',
dataType : 'json',
url : department_parameter.root,
contentType : 'application/json; charset=utf-8',
data : JSON.stringify({
name : $('#name', '#content').val(),
company : $('#company', '#content').val(),
superior : $('#superior', '#content').val(),
unique : $('#unique', '#content').val()
}),
xhrFields : {
'withCredentials' : true
},
crossDomain : true
}).done(function(data) {
if (data.type == 'success') {
department_list_reload();
} else {
failure(data);
}
});
}
function department_edit(id) {
var str = '<table border="1" width="100%">';
str += '<tr><td colspan="2"><a href="#" id="put">put</a></td></tr>';
str += '<tr><td>id:</td><td id="id"></td></tr>';
str += '<tr><td>sequence:</td><td id="sequence"></td></tr>';
str += '<tr><td>level:</td><td id="level"></td></tr>';
str += '<tr><td>name:</td><td><input type="text" id="name" style="width:95%"/></td></tr>';
str += '<tr><td>company:</td><td><input type="text" id="company" style="width:95%"/></td></tr>';
str += '<tr><td>superior:</td><td><input type="text" id="superior" style="width:95%"/></td></tr>';
str += '<tr><td>unique:</td><td><input type="text" id="unique" style="width:95%"/></td></tr>';
str += '</table>';
$('#content').html(str);
$('#put', '#content').click(function() {
department_put(id);
});
$.ajax({
type : 'get',
dataType : 'json',
url : department_parameter.root + '/' + id,
xhrFields : {
'withCredentials' : true
},
crossDomain : true
}).done(function(data) {
if (data.type == 'success') {
$('#name', '#content').val(data.data.name);
$('#company', '#content').val(data.data.company);
$('#superior', '#content').val(data.data.superior);
$('#unique', '#content').val(data.data.unique);
$('#id', '#content').html(data.data.id);
$('#sequence', '#content').html(data.data.sequence);
$('#level', '#content').html(data.data.level);
} else {
failure(data);
}
});
}
function department_put(id) {
$.ajax({
type : 'put',
dataType : 'json',
url : department_parameter.root + '/' + id,
contentType : 'application/json; charset=utf-8',
data : JSON.stringify({
name : $('#name', '#content').val(),
company : $('#company', '#content').val(),
superior : $('#superior', '#content').val(),
unique : $('#unique', '#content').val()
}),
xhrFields : {
'withCredentials' : true
},
crossDomain : true
}).done(function(data) {
if (data.type == 'success') {
department_list_reload();
} else {
failure(data);
}
});
}
function department_delete(id) {
$.ajax({
type : 'delete',
dataType : 'json',
url : department_parameter.root + '/' + id,
xhrFields : {
'withCredentials' : true
},
crossDomain : true
}).done(function(data) {
if (data.type == 'success') {
department_list_reload();
} else {
failure(data);
}
});
}
function department_query_grid(items) {
var str = '<table border="1" width="100%">';
str += '<tr><th>id</th><th>name</th><th>company</th><th>superior</th><th>level</th><th>operate</th></tr>';
$.each(items, function(index, item) {
str += '<tr>';
str += '<td>' + item.id + '</td>';
str += '<td>' + item.name + '</td>';
str += '<td>' + item.company + '</td>';
str += '<td>' + item.superior + '</td>';
str += '<td>' + item.level + '</td>';
str += '<td>';
str += '<a href="#" onclick="department_edit(\'' + item.id + '\')">edit</a> ';
str += '<a href="#" onclick="department_delete(\'' + item.id + '\')">delete</a>';
str += '</td>';
str += '</tr>';
});
str += '</table>';
return str;
}
function department_query_init() {
str = '<table border="1" width="100%">';
str += '<tr><td>query:</td><td><input type="text" id="query" style="width:95%"/></td></tr>';
str += '<tr><td colspan="2"><a href="#" id="subDirectWithCompany">获取指定公司的直接下级部门.</a></td></tr>';
str += '<tr><td colspan="2"><a href="#" id="subNestedWithCompany">获取指定公司的嵌套下级部门.</a></td></tr>';
str += '<tr><td colspan="2"><a href="#" id="subDirect">获取指定部门的直接下级部门.</a></td></tr>';
str += '<tr><td colspan="2"><a href="#" id="subNested">获取指定部门的嵌套下级部门.</a></td></tr>';
str += '<tr><td colspan="2"><a href="#" id="pinyinInitial">根据首字母查找.</a></td></tr>';
str += '<tr><td colspan="2"><a href="#" id="like">进行模糊查找.</a></td></tr>';
str += '<tr><td colspan="2"><a href="#" id="likePinyin">根据拼音查找.</a></td></tr>';
str += '</table>';
$('#content').html(str);
$('#subDirectWithCompany', '#content').click(function() {
department_query_subDirectWithCompany($('#query', '#content').val());
});
$('#subNestedWithCompany', '#content').click(function() {
department_query_subNestedWithCompany($('#query', '#content').val());
});
$('#subDirect', '#content').click(function() {
department_query_subDirect($('#query', '#content').val());
});
$('#subNested', '#content').click(function() {
department_query_subNested($('#query', '#content').val());
});
$('#pinyinInitial', '#content').click(function() {
department_query_pinyinInitial($('#query', '#content').val());
});
$('#like', '#content').click(function() {
department_query_like($('#query', '#content').val());
});
$('#likePinyin', '#content').click(function() {
department_query_likePinyin($('#query', '#content').val());
});
}
function department_query_subDirectWithCompany(id) {
department_parameter.list_action = department_query_subDirectWithCompany;
department_parameter.list_action_parameter = id;
$.ajax({
type : 'get',
dataType : 'json',
url : department_parameter.root + '/list/company/' + id + '/sub/direct',
xhrFields : {
'withCredentials' : true
},
crossDomain : true
}).done(function(data) {
if (data.type == 'success') {
$('#content').html(department_query_grid(data.data));
} else {
failure(data);
}
});
}
function department_query_subNestedWithCompany(id) {
department_parameter.list_action = department_query_subNestedWithCompany;
department_parameter.list_action_parameter = id;
$.ajax({
type : 'get',
dataType : 'json',
url : department_parameter.root + '/list/company/' + id + '/sub/nested',
xhrFields : {
'withCredentials' : true
},
crossDomain : true
}).done(function(data) {
if (data.type == 'success') {
$('#content').html(department_query_grid(data.data));
} else {
failure(data);
}
});
}
function department_query_subDirect(id) {
department_parameter.list_action = department_query_subDirect;
department_parameter.list_action_parameter = id;
$.ajax({
type : 'get',
dataType : 'json',
url : department_parameter.root + '/list/' + id + '/sub/direct',
xhrFields : {
'withCredentials' : true
},
crossDomain : true
}).done(function(data) {
if (data.type == 'success') {
$('#content').html(department_query_grid(data.data));
} else {
failure(data);
}
});
}
function department_query_subNested(id) {
department_parameter.list_action = department_query_subNested;
department_parameter.list_action_parameter = id;
$.ajax({
type : 'get',
dataType : 'json',
url : department_parameter.root + '/list/' + id + '/sub/nested',
xhrFields : {
'withCredentials' : true
},
crossDomain : true
}).done(function(data) {
if (data.type == 'success') {
$('#content').html(department_query_grid(data.data));
} else {
failure(data);
}
});
}
function department_query_like(key) {
department_parameter.list_action = department_query_like;
department_parameter.list_action_parameter = key;
$.ajax({
type : 'get',
dataType : 'json',
url : department_parameter.root + '/list/like/' + encodeURIComponent(key),
xhrFields : {
'withCredentials' : true
},
crossDomain : true
}).done(function(data) {
if (data.type == 'success') {
$('#content').html(department_query_grid(data.data));
} else {
failure(data);
}
});
}
function department_query_pinyinInitial(key) {
department_parameter.list_action = department_query_pinyinInitial;
department_parameter.list_action_parameter = key;
$.ajax({
type : 'get',
dataType : 'json',
url : department_parameter.root + '/list/pinyininitial/' + encodeURIComponent(key),
xhrFields : {
'withCredentials' : true
},
crossDomain : true
}).done(function(data) {
if (data.type == 'success') {
$('#content').html(department_query_grid(data.data));
} else {
failure(data);
}
});
}
function department_query_likePinyin(key) {
department_parameter.list_action = department_query_likePinyin;
department_parameter.list_action_parameter = key;
$.ajax({
type : 'get',
dataType : 'json',
url : department_parameter.root + '/list/like/pinyin/' + encodeURIComponent(key),
xhrFields : {
'withCredentials' : true
},
crossDomain : true
}).done(function(data) {
if (data.type == 'success') {
$('#content').html(department_query_grid(data.data));
} else {
failure(data);
}
});
} |
rerorero/meshtest | src/repository/discovery_consul_test.go | package repository
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/hashicorp/consul/api"
"github.com/rerorero/meshem/src/model"
"github.com/rerorero/meshem/src/utils"
)
func unregisterAll(t *testing.T, consul *utils.Consul) {
nodes, _, err := consul.Client.Catalog().Nodes(nil)
assert.NoError(t, err)
for _, n := range nodes {
dereg := &api.CatalogDeregistration{
Node: n.Node,
}
_, err = consul.Client.Catalog().Deregister(dereg, nil)
assert.NoError(t, err)
}
}
func TestDiscoveryRegister(t *testing.T) {
consul := utils.NewConsulMock()
unregisterAll(t, consul)
sut := NewDiscoveryConsul(consul, "")
host, err := model.NewHost("reg1", "192.168.10.10:80", "127.0.0.1:8080", "127.0.0.1")
assert.NoError(t, err)
tags := map[string]string{}
tags["aaa"] = "a3"
tags["bbbb"] = "b4"
err = sut.Register(host, tags)
assert.NoError(t, err)
info, ok, err := sut.FindByName("reg1")
assert.NoError(t, err)
assert.True(t, ok)
assert.Equal(t, &DiscoveryInfo{
Name: host.Name,
Address: *host.GetAdminAddr(),
Tags: tags,
}, info)
// overwrite
host2, err := model.NewHost("reg1", "192.168.20.30:9000", "127.0.0.1:9090", "127.0.0.1")
tags["c"] = "c1"
err = sut.Register(host2, tags)
assert.NoError(t, err)
info, ok, err = sut.FindByName("reg1")
assert.NoError(t, err)
assert.True(t, ok)
assert.Equal(t, &DiscoveryInfo{
Name: host2.Name,
Address: *host2.GetAdminAddr(),
Tags: tags,
}, info)
// unregister
err = sut.Unregister("reg1")
assert.NoError(t, err)
// not found
info, ok, err = sut.FindByName("reg1")
assert.NoError(t, err)
assert.False(t, ok)
// unregister unregistered
err = sut.Unregister("reg1")
assert.NoError(t, err)
}
|
jmabry/pyaf | tests/exog/random/random_exog_16_1280.py | import pyaf.tests.exog.test_random_exogenous as testrandexog
testrandexog.test_random_exogenous( 16,1280); |
LLcat1217/arangodb | tests/js/client/shell/api/explain.js | <reponame>LLcat1217/arangodb
/* jshint globalstrict:false, strict:false, maxlen: 200 */
/* global db, fail, arango, assertTrue, assertFalse, assertEqual, assertNotUndefined */
// //////////////////////////////////////////////////////////////////////////////
// / @brief
// /
// /
// / DISCLAIMER
// /
// / Copyright 2018 ArangoDB GmbH, Cologne, Germany
// /
// / Licensed under the Apache License, Version 2.0 (the "License")
// / you may not use this file except in compliance with the License.
// / You may obtain a copy of the License at
// /
// / http://www.apache.org/licenses/LICENSE-2.0
// /
// / Unless required by applicable law or agreed to in writing, software
// / distributed under the License is distributed on an "AS IS" BASIS,
// / WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// / See the License for the specific language governing permissions and
// / limitations under the License.
// /
// / Copyright holder is ArangoDB GmbH, Cologne, Germany
// /
// / @author
// //////////////////////////////////////////////////////////////////////////////
'use strict';
const internal = require('internal');
const sleep = internal.sleep;
const forceJson = internal.options().hasOwnProperty('server.force-json') && internal.options()['server.force-json'];
const contentType = forceJson ? "application/json" : "application/x-velocypack";
const jsunity = require("jsunity");
let api = "/_api/explain";
////////////////////////////////////////////////////////////////////////////////;
// error handling;
////////////////////////////////////////////////////////////////////////////////;
function error_handlingSuite () {
return {
test_returns_an_error_if_body_is_missing: function() {
let cmd = api;
let doc = arango.POST_RAW(cmd, "");
assertEqual(doc.code, internal.errors.ERROR_HTTP_BAD_PARAMETER.code);
assertEqual(doc.headers['content-type'], contentType);
assertTrue(doc.parsedBody['error']);
assertEqual(doc.parsedBody['code'], internal.errors.ERROR_HTTP_BAD_PARAMETER.code);
},
test_returns_an_error_for_an_invalid_path: function() {
let cmd = api + "/foo";
let body = { "query" : "RETURN 1" };
let doc = arango.POST_RAW(cmd, body);
assertEqual(doc.code, internal.errors.ERROR_HTTP_NOT_FOUND.code);
assertEqual(doc.headers['content-type'], contentType);
assertTrue(doc.parsedBody['error']);
assertEqual(doc.parsedBody['code'], internal.errors.ERROR_HTTP_NOT_FOUND.code);
},
test_returns_an_error_if_collection_is_unknown: function() {
let cmd = api;
let body = { "query" : "FOR u IN unknowncollection LIMIT 2 RETURN u.n" };
let doc = arango.POST_RAW(cmd, body);
assertEqual(doc.code, internal.errors.ERROR_HTTP_NOT_FOUND.code);
assertEqual(doc.headers['content-type'], contentType);
assertTrue(doc.parsedBody['error']);
assertEqual(doc.parsedBody['code'], internal.errors.ERROR_HTTP_NOT_FOUND.code);
assertEqual(doc.parsedBody['errorNum'], internal.errors.ERROR_ARANGO_DATA_SOURCE_NOT_FOUND.code);
},
test_returns_an_error_if_bind_variables_are_missing_completely: function() {
let cmd = api;
let body = { "query" : "FOR u IN [1,2] FILTER u.id == @id RETURN 1" };
let doc = arango.POST_RAW(cmd, body);
assertEqual(doc.code, internal.errors.ERROR_HTTP_BAD_PARAMETER.code);
assertEqual(doc.headers['content-type'], contentType);
assertTrue(doc.parsedBody['error']);
assertEqual(doc.parsedBody['code'], internal.errors.ERROR_HTTP_BAD_PARAMETER.code);
assertEqual(doc.parsedBody['errorNum'], internal.errors.ERROR_QUERY_BIND_PARAMETER_MISSING.code);
},
test_returns_an_error_if_bind_variables_are_required_but_empty: function() {
let cmd = api;
let body = { "query" : "FOR u IN [1,2] FILTER u.id == @id RETURN 1", "bindVars" : { } };
let doc = arango.POST_RAW(cmd, body);
assertEqual(doc.code, internal.errors.ERROR_HTTP_BAD_PARAMETER.code);
assertEqual(doc.headers['content-type'], contentType);
assertTrue(doc.parsedBody['error']);
assertEqual(doc.parsedBody['code'], internal.errors.ERROR_HTTP_BAD_PARAMETER.code);
assertEqual(doc.parsedBody['errorNum'], internal.errors.ERROR_QUERY_BIND_PARAMETER_MISSING.code);
},
test_returns_an_error_if_bind_variables_are_missing: function() {
let cmd = api;
let body = { "query" : "FOR u IN [1,2] FILTER u.id == @id RETURN 1", "bindVars" : { "id2" : 1 } };
let doc = arango.POST_RAW(cmd, body);
assertEqual(doc.code, internal.errors.ERROR_HTTP_BAD_PARAMETER.code);
assertEqual(doc.headers['content-type'], contentType);
assertTrue(doc.parsedBody['error']);
assertEqual(doc.parsedBody['code'], internal.errors.ERROR_HTTP_BAD_PARAMETER.code);
assertEqual(doc.parsedBody['errorNum'], internal.errors.ERROR_QUERY_BIND_PARAMETER_MISSING.code);
},
test_returns_an_error_if_query_contains_a_parse_error: function() {
let cmd = api;
let body = { "query" : "FOR u IN " };
let doc = arango.POST_RAW(cmd, body);
assertEqual(doc.code, internal.errors.ERROR_HTTP_BAD_PARAMETER.code);
assertEqual(doc.headers['content-type'], contentType);
assertTrue(doc.parsedBody['error']);
assertEqual(doc.parsedBody['code'], internal.errors.ERROR_HTTP_BAD_PARAMETER.code);
assertEqual(doc.parsedBody['errorNum'], internal.errors.ERROR_QUERY_PARSE.code);
}
};
}
////////////////////////////////////////////////////////////////////////////////;
// explaining;
////////////////////////////////////////////////////////////////////////////////;
function explaining_queriesSuite () {
return {
test_explains_a_simple_query: function() {
let cmd = api;
let body = { "query" : "FOR u IN [1,2] RETURN u" };
let doc = arango.POST_RAW(cmd, body);
assertEqual(doc.code, 200);
assertEqual(doc.headers['content-type'], contentType);
assertFalse(doc.parsedBody['error']);
assertEqual(doc.parsedBody['code'], 200);
}
};
}
jsunity.run(error_handlingSuite);
jsunity.run(explaining_queriesSuite);
return jsunity.done();
|
arhjaye/main | src/main/java/seedu/project/model/util/SampleDataUtil.java | package seedu.project.model.util;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
import seedu.project.model.Name;
import seedu.project.model.ProjectList;
import seedu.project.model.project.Project;
import seedu.project.model.tag.Tag;
import seedu.project.model.task.Deadline;
import seedu.project.model.task.Description;
import seedu.project.model.task.Task;
/**
* Contains utility methods for populating {@code Project} with sample data.
*/
public class SampleDataUtil {
public static Task[] getSampleTasks() {
return new Task[] {
new Task(new Name("Sample task 1"), new Description("This is a sample task"), new Deadline("01-01-2019"),
getTagSet("SAMPLE")),
new Task(new Name("Sample task 2"), new Description("This is a sample task"), new Deadline("01-01-2019"),
getTagSet("SAMPLE"))
};
}
public static Project[] getSampleProjects() {
return new Project[] {
new Project(new Name("Sample project 1")),
new Project(new Name("Sample project 2"))
};
}
public static Project[] getProjectsToImport() {
return new Project[] {
new Project(new Name("Sample project 3")),
new Project(new Name("Sample project 4"))
};
}
public static ProjectList getSampleProjectList() {
ProjectList projectList = new ProjectList();
for (Project project : getSampleProjects()) {
for (Task task : getSampleTasks()) {
project.addTask(task);
}
projectList.addProject(project);
}
return projectList;
}
/**
* Returns a task set containing the list of strings given.
*/
public static Set<Tag> getTagSet(String... strings) {
return Arrays.stream(strings)
.map(Tag::new)
.collect(Collectors.toSet());
}
}
|
codyroux/lean0.1 | src/kernel/context.h | <gh_stars>1-10
/*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: <NAME>
*/
#pragma once
#include <utility>
#include "util/list.h"
#include "util/optional.h"
#include "kernel/expr.h"
namespace lean {
/**
\brief An element of the Lean context.
\see context
*/
class context_entry {
name m_name;
optional<expr> m_domain;
optional<expr> m_body;
public:
context_entry(name const & n, optional<expr> const & d, expr const & b):m_name(n), m_domain(d), m_body(b) {}
context_entry(name const & n, expr const & d, optional<expr> const & b):m_name(n), m_domain(d), m_body(b) {}
context_entry(name const & n, expr const & d, expr const & b):m_name(n), m_domain(d), m_body(b) {}
context_entry(name const & n, expr const & d):m_name(n), m_domain(d) {}
name const & get_name() const { return m_name; }
optional<expr> const & get_domain() const { return m_domain; }
optional<expr> const & get_body() const { return m_body; }
friend bool operator==(context_entry const & e1, context_entry const & e2) { return e1.m_domain == e2.m_domain && e1.m_body == e2.m_body; }
friend bool operator!=(context_entry const & e1, context_entry const & e2) { return !(e1 == e2); }
};
class metavar_env;
/**
\brief A context is essentially a mapping from free-variables to types (and definition/body).
*/
class context {
list<context_entry> m_list;
explicit context(list<context_entry> const & l):m_list(l) {}
public:
context() {}
context(context const & c, name const & n, optional<expr> const & d, expr const & b):m_list(context_entry(n, d, b), c.m_list) {}
context(context const & c, name const & n, expr const & d, optional<expr> const & b):m_list(context_entry(n, d, b), c.m_list) {}
context(context const & c, name const & n, expr const & d, expr const & b):m_list(context_entry(n, d, b), c.m_list) {}
context(context const & c, name const & n, expr const & d):m_list(context_entry(n, d), c.m_list) {}
context(context const & c, context_entry const & e):m_list(e, c.m_list) {}
context(unsigned sz, context_entry const * es):context(to_list(es, es + sz)) {}
context(std::initializer_list<std::pair<char const *, expr const &>> const & l);
context_entry const & lookup(unsigned vidx) const;
std::pair<context_entry const &, context> lookup_ext(unsigned vidx) const;
/** \brief Similar to lookup, but always succeed */
optional<context_entry> find(unsigned vidx) const;
bool empty() const { return is_nil(m_list); }
explicit operator bool() const { return !empty(); }
unsigned size() const { return length(m_list); }
typedef list<context_entry>::iterator iterator;
iterator begin() const { return m_list.begin(); }
iterator end() const { return m_list.end(); }
friend bool is_eqp(context const & c1, context const & c2) { return is_eqp(c1.m_list, c2.m_list); }
/**
\brief Return a new context where entries at positions >= s are removed.
*/
context truncate(unsigned s) const;
/**
\brief Return a new context where the entries at positions [s, s+n) were removed.
The free variables in entries [0, s) are lowered.
That is, if this context is of the form
[ce_m, ..., ce_{s+n}, ce_{s+n-1}, ..., ce_s, ce_{s-1}, ..., ce_0]
Then, the resultant context is of the form
[ce_m, ..., ce_{s+n}, lower(ce_{s-1}, n, n), ..., lower(ce_0, s+n-1, n)]
\pre size() >= s + n
If for some i in [0, s), has_free_var(ce_i, s - 1 - i, s + n - 1 - i), then return none.
That is, the lower operations must be valid.
*/
optional<context> remove(unsigned s, unsigned n, metavar_env const & menv) const;
friend bool operator==(context const & ctx1, context const & ctx2) { return ctx1.m_list == ctx2.m_list; }
friend bool operator!=(context const & ctx1, context const & ctx2) { return !(ctx1 == ctx2); }
};
/**
\brief Return the context entry for the free variable with de
Bruijn index \c i, and the context for this entry.
*/
inline std::pair<context_entry const &, context> lookup_ext(context const & c, unsigned i) { return c.lookup_ext(i); }
/**
\brief Return the context entry for the free variable with de
Bruijn index \c i.
*/
inline context_entry const & lookup(context const & c, unsigned i) { return c.lookup(i); }
inline optional<context_entry> find(context const & c, unsigned i) { return c.find(i); }
inline context extend(context const & c, name const & n, optional<expr> const & d, expr const & b) { return context(c, n, d, b); }
inline context extend(context const & c, name const & n, expr const & d, optional<expr> const & b) { return context(c, n, d, b); }
inline context extend(context const & c, name const & n, expr const & d, expr const & b) { return context(c, n, d, b); }
inline context extend(context const & c, name const & n, expr const & d) { return context(c, n, d); }
inline bool empty(context const & c) { return c.empty(); }
std::ostream & operator<<(std::ostream & out, context const & ctx);
}
|
ClnViewer/ADB-Android-Viewer | src/ADBDriverDLL/src/Dialog/WINAPI/AdbListDialog/AdbListDialog.cpp | /*
MIT License
Android remote Viewer, GUI ADB tools
Android Viewer developed to view and control your android device from a PC.
ADB exchange Android Viewer, support scale view, input tap from mouse,
input swipe from keyboard, save/copy screenshot, etc..
Copyright (c) 2016-2019 PS
GitHub: https://github.com/ClnViewer/ADB-Android-Viewer
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, sub license, 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.
*/
#include "AdbListDialogInternal.h"
namespace GameDev
{
INT_PTR AdbListDialog::__DialogProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_CHAR: return _OnWM_CHAR(hWnd, uMsg, wParam, lParam);
case WM_COMMAND: return _OnWM_COMMAND(hWnd, uMsg, wParam, lParam);
case WM_NOTIFY: return _OnWM_NOTIFY(hWnd, uMsg, wParam, lParam);
case WM_CLOSE: return _OnWM_CLOSE(hWnd, uMsg, wParam, lParam);
case WM_INITDIALOG: return _OnWM_INITDIALOG(hWnd, uMsg, wParam, lParam);
//case WM_CTLCOLORBTN:
case WM_CTLCOLORSCROLLBAR:
case WM_CTLCOLORLISTBOX:
case WM_CTLCOLORSTATIC:
case WM_CTLCOLORDLG: return _OnWM_CTLCOLORSTATIC(hWnd, uMsg, wParam, lParam);
case WM_DRAWITEM: return _OnWM_DRAWITEM(hWnd, uMsg, wParam, lParam);
case WM_NCHITTEST: return _OnWM_NCHITTEST(hWnd, uMsg, wParam, lParam);
default:
break;
}
return false;
}
INT_PTR CALLBACK AdbListDialog::DialogRedirect(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
if (uMsg == WM_INITDIALOG)
SetWindowLongPtr(hWnd, DWLP_USER, lParam);
AdbListDialog *pThis =
reinterpret_cast<AdbListDialog*>(GetWindowLongPtr(hWnd, DWLP_USER));
if (pThis)
return pThis->__DialogProc(hWnd, uMsg, wParam, lParam);
return FALSE;
}
INT_PTR AdbListDialog::Show(SelectedList & dict)
{
return Show(dict, 0);
}
INT_PTR AdbListDialog::Show(SelectedList & dict, int32_t colw, bool isreverse)
{
_isreverse = isreverse;
return Show(dict, colw);
}
INT_PTR AdbListDialog::Show(SelectedList & dict, int32_t colw)
{
if (!_hinst)
_hinst = gethmodule();
_dict = dict;
_p.x = ((colw) ? colw : 100);
_p.y = ((colw) ? (470 - colw) : 370);
return DialogBoxParamW(
_hinst,
MAKEINTRESOURCEW(_rid),
NULL,
&AdbListDialog::DialogRedirect,
reinterpret_cast<LPARAM>(this)
);
}
std::wstring AdbListDialog::SelectedKey() const
{
return _key;
}
std::wstring AdbListDialog::SelectedValue() const
{
return _val;
}
AdbListDialog::AdbListDialog(DWORD rid)
: _p({0,0}), _hwnd(nullptr), _hinst(nullptr), _rid(rid), _sel(-1), _isreverse(false) {}
AdbListDialog::AdbListDialog(HINSTANCE hinst, DWORD rid)
: _p({0,0}), _hwnd(nullptr), _hinst(hinst), _rid(rid), _sel(-1), _isreverse(false) {}
AdbListDialog::AdbListDialog(HINSTANCE hinst, DWORD rid, COLORREF creft, COLORREF crefb)
: _p({0,0}), _hwnd(nullptr), _hinst(hinst), _rid(rid), _sel(-1), _isreverse(false)
{
_style.Set(creft, crefb);
}
AdbListDialog::~AdbListDialog()
{
_style.~StyleDialog();
}
}
|
I-Hudson/InSightEngine | InSight/include/InSight/BaseRenderer.h | <filename>InSight/include/InSight/BaseRenderer.h<gh_stars>1-10
#pragma once
#include "Shader/BaseShader.h"
#include <vector>
#include "Debug.h"
class BaseRenderer
{
public:
//Constructor
BaseRenderer();
//Destructor
~BaseRenderer();
//add entity
template<typename T, typename... TArgs>
T* addShader(TArgs&&... mArgs)
{
T* BaseShader = DEBUG_NEW T(std::forward<TArgs>(mArgs)...);
BaseShader->setBaseRenderer(this);
mShadersToRender.emplace_back(BaseShader);
return BaseShader;
}
//remove entity
void removeShader(BaseShader* a_removeShader);
//draw
void draw();
//destroy
void destroy();
//set the screen size
void setScreenSize(const glm::vec2& aScreenSize);
//get the screen size
glm::vec2 getScreenSize();
private:
//store all the enitity to draw
std::vector<BaseShader*> mShadersToRender;
//when a mesh component is added. Add that to this vector to
//draw
//store screen size
glm::vec2 mScreenSize;
}; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.