code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
import smtplib
from email.mime.text import MIMEText
from django.core.mail import EmailMultiAlternatives
from django.conf import settings
def send_message(message):
"""
* desc 快捷发送邮件
* input 要发送的邮件信息
* output None
"""
mail_handler = SendMail()
mail_handler.send_mail(settings.REPORT_USER, 'Error info', message)
class SendMail(object):
"""docstring for SendMail"""
def __init__(self):
self.mail_host = settings.MAIL_HOST
self.mail_host_user = settings.MAIL_HOST_USER
self.mail_host_pwd = settings.MAIL_HOST_PWD
self.smtp = smtplib.SMTP()
self.smtp_login()
def smtp_login(self):
# login the host
self.smtp.connect(self.mail_host)
self.smtp.login(self.mail_host_user, self.mail_host_pwd)
def send_file_mail(self, receiver_list, subject, file_info, file_name):
# 发送附件的方法
part = MIMEApplication(file_info)
part.add_header('Content-Disposition',
'attachment', filename=file_name)
msg.attach(part)
sender = self.mail_host_user
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = ";".join(receiver_list)
self.smtp.sendmail(sender, receiver_list, msg.as_string())
def send_mail(self, receiver_list, subject, context, mail_type="plain"):
"""
* desc 发送邮件的接口
* input receiver_list 收件人的地址列表 subject 主题 context 发送的内容 mail_type 邮件的格式 目前测试成功 plain 和 html
* output 发送成功与否
"""
sender = self.mail_host_user
msg = MIMEText(context, mail_type)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = ";".join(receiver_list)
self.smtp.sendmail(sender, receiver_list, msg.as_string())
def close(self):
# 关闭建立的链接
self.smtp.close()
class MailHandler(object):
def __init__(self):
pass
def send_mail_message(self, to_user, msg, error=0):
"""
* desc 发送错误邮件
* input 要发送的人 发送的消息 错误还是告警
* output 0 发送成功 1 发送失败
"""
subject = settings.MSUBMAIL
if error:
text_content = 'Virtual Manager Error'
else:
text_content = 'Virtual Manager Warning'
from_email = settings.FMAIL
try:
to = [str(user) + "@hujiang.com" for user in to_user.split(',')]
print(to)
content_msg = EmailMultiAlternatives(
subject, text_content, from_email, to)
html_content = u'<b>' + msg + '</b>'
content_msg.attach_alternative(html_content, 'text/html')
content_msg.send()
return 0
except:
return 1
| hanleilei/note | python/vir_manager/utils/mail_utils.py | Python | cc0-1.0 | 2,926 |
/********************************************************************** <BR>
This file is part of Crack dot Com's free source code release of
Golgotha. <a href="http://www.crack.com/golgotha_release"> <BR> for
information about compiling & licensing issues visit this URL</a>
<PRE> If that doesn't help, contact Jonathan Clark at
golgotha_source@usa.net (Subject should have "GOLG" in it)
***********************************************************************/
#include "pch.h"
//very fast, but very bad random number generator.
//I think this is done so badly, because we want to get shure that the "random" sequence
//is reproduceable. But we should better save the seed in the save-file, so we can use a
//real random seed if appropriate.
enum {
TSIZE=1024
};
static w32 w32_rtable[TSIZE];
static float f_rtable[TSIZE];
static int seed=0;
static int initialized=0;
void next_seed()
{
if (!initialized)
{
w32 inc=0xacd2d391, mul=0xf34f9201, x=0;
for (int i=0; i<TSIZE; i++)
{
w32_rtable[i]=x;
f_rtable[i]=(float)((double)x/(double)0xffffffff);
x=(x+inc)*mul;
}
initialized=1;
}
seed=(seed +1)%TSIZE ;
}
w32 i4_rand()
{
next_seed();
return w32_rtable[seed];
}
float i4_float_rand()
{
next_seed();
return f_rtable[seed];
}
void i4_rand_reset(w32 _seed)
{
seed=_seed % TSIZE;
}
| pgrawehr/golgotha | math__random.cpp | C++ | cc0-1.0 | 1,383 |
#include <bits/stdc++.h>
using namespace std;
long long unsigned v[63], a, b;
long long unsigned S(long long unsigned n){
if(!n) return 0;
if((1LL<<((sizeof(long long)<<3) - __builtin_clzll(n)))-1 == n)
return v[(sizeof(long long)<<3) - __builtin_clzll(n)];
return v[(sizeof(long long)<<3) - __builtin_clzll(n)-1] + S(n^(1LL<<((sizeof(long long))<<3) - __builtin_clzll(n)-1)) + n - ((1LL << ((sizeof(long long)<<3) - __builtin_clzll(n)-1))-1);
}
int main(){
v[0] = 0;
for(int i=1; i<63; i++)
v[i] = (v[i-1]<<1) + (1LL<<(i-1));
while(scanf("%llu %llu", &a, &b) != EOF)
printf("%llu\n", S(b)-S(a-1));
return 0;
}
| luizreis/programming-contest-notebook | code/latin-2013/countingones.cpp | C++ | cc0-1.0 | 628 |
# frozen_string_literal: true
class FeedbacksController < ApplicationController
before_action :authenticate_user!, except: [:create]
before_action :set_feedback, only: [:show, :edit, :update, :destroy]
before_action :check_if_smokedetector, only: :create
protect_from_forgery except: [:create]
def clear
@post = Post.find(params[:id])
@feedbacks = Feedback.unscoped.where(post_id: params[:id])
unless verify_access(@feedbacks)
redirect_to missing_privileges_path(required: :admin)
return
end
@sites = [@post.site]
raise ActionController::RoutingError, 'Not Found' if @post.nil?
end
def delete
f = Feedback.find params[:id]
raise ActionController::RoutingError, 'Not Found' unless verify_access(f)
f.post.reasons.each do |reason|
expire_fragment(reason)
end
f.is_invalidated = true
f.invalidated_by = current_user.id
f.invalidated_at = DateTime.now
f.save!
redirect_to clear_post_feedback_path(f.post_id)
end
# POST /feedbacks
# POST /feedbacks.json
def create
# puts Feedback.where(post_id: params[:feedback][:post_id], user_name: params[:feedback][:user_name]).present?
post_link = feedback_params[:post_link]
post = Post.where(link: post_link).order(:created_at).last
render(plain: 'Error: No post found for link') && return if post.nil?
# Ignore identical feedback from the same user
if Feedback.where(post: post, user_name: feedback_params[:user_name], feedback_type: feedback_params[:feedback_type]).present?
render(plain: 'Identical feedback from user already exists on post') && return
end
@feedback = Feedback.new(feedback_params)
post.reasons.each do |reason|
expire_fragment(reason)
end
expire_fragment('post' + post.id.to_s)
@feedback.post = post
if Feedback.where(chat_user_id: @feedback.chat_user_id).count == 0
feedback_intro = 'It seems this is your first time sending feedback to SmokeDetector. ' \
'Make sure you\'ve read the guidance on [your privileges](https://git.io/voC8N), ' \
'the [available commands](https://git.io/voC4m), and [what feedback to use in different situations](https://git.io/voC4s).'
ActionCable.server.broadcast 'smokedetector_messages', message: "@#{@feedback.user_name.delete(' ')}: #{feedback_intro}"
end
respond_to do |format|
if @feedback.save
format.json { render :show, status: :created, body: 'OK' }
else
format.json { render json: @feedback.errors, status: :unprocessable_entity }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_feedback
@feedback = Feedback.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def feedback_params
params.require(:feedback).permit(:message_link, :user_name, :user_link, :feedback_type, :post_link, :chat_user_id, :chat_host)
end
def verify_access(feedbacks)
return true if current_user.has_role? :admin
if feedbacks.respond_to? :where
return false unless feedbacks.where(user_id: current_user.id).exists?
else
return false unless feedbacks.user_id == current_user.id
end
true
end
end
| angussidney/metasmoke | app/controllers/feedbacks_controller.rb | Ruby | cc0-1.0 | 3,291 |
jsonp({"cep":"36784000","cidade":"Dona Euz\u00e9bia","uf":"MG","estado":"Minas Gerais"});
| lfreneda/cepdb | api/v1/36784000.jsonp.js | JavaScript | cc0-1.0 | 90 |
<?php
/**
* Class Autoloader
*/
class Autoloader{
/**
* Enregistre notre autoloader
*/
static function register(){
spl_autoload_register(array(__CLASS__, 'autoload'));
}
/**
* Inclue le fichier correspondant à notre classe
* @param $class string Le nom de la classe à charger
*/
static function autoload($class){
require 'class/' . $class . '.php';
}
}
?>
| ntrancha/crypto_php | autoloader.php | PHP | cc0-1.0 | 383 |
#!/usr/bin/env node
/*
The Cedric's Swiss Knife (CSK) - CSK terminal toolbox test suite
Copyright (c) 2009 - 2015 Cédric Ronvel
The MIT License (MIT)
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.
*/
"use strict" ;
/* jshint unused:false */
var fs = require( 'fs' ) ;
var termkit = require( '../lib/termkit.js' ) ;
termkit.getDetectedTerminal( function( error , term ) {
var autoCompleter = function autoCompleter( inputString , callback )
{
fs.readdir( __dirname , function( error , files ) {
//console.log( files ) ;
callback( undefined , termkit.autoComplete( files , inputString , true ) ) ;
} ) ;
} ;
function question()
{
term( 'Choose a file: ' ) ;
term.inputField( { autoComplete: autoCompleter , autoCompleteMenu: true } , function( error , input ) {
if ( error )
{
term.red.bold( "\nAn error occurs: " + error + "\n" ) ;
question() ;
}
else
{
term.green( "\nYour file is '%s'\n" , input ) ;
terminate() ;
}
} ) ;
}
function terminate()
{
term.grabInput( false ) ;
// Add a 100ms delay, so the terminal will be ready when the process effectively exit, preventing bad escape sequences drop
setTimeout( function() { process.exit() ; } , 100 ) ;
}
term.bold.cyan( 'Async auto-completer, type something and hit the ENTER key...\n' ) ;
question() ;
} ) ;
| hamizmz/Junk-Draw | typescript/TestApplication/node_modules/terminal-kit/sample/async-auto-completer-test.js | JavaScript | cc0-1.0 | 2,362 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DungeonCrwlMain
{
/// <summary>
/// You have proficiency in the
/// Perception skill.
/// </summary>
public class KeenSensesAttribute : AttributeComponent
{
public KeenSensesAttribute()
: base("Keen Senses")
{ }
}
}
| ptrick/DungeonCrwl | DungeonCrwl/DungeonCrwlMain/KeenSensesAttribute.cs | C# | cc0-1.0 | 402 |
describe("twitter plugin", function () {
xit("works", function () {
expect(function () {
var plugins = require("../index.js").convert,
assert = require("assert");
var goodURLs = [
"https://twitter.com/davidmerfieId/status/500323409218117633",
"http://twitter.com/davidmerfieId/status/500323409218117633",
"https://twitter.com/davidmerfieId/status/500323409218117633/",
"https://twitter.com/davidmerfieId/status/500323409218117633?foo=bar",
"https://twitter.com/davidmerfieId/STATUS/500323409218117633?foo=bar",
];
var badURLs = [
"http://twatter.com/davidmerfieId/status/500323409218117633",
"http://twitter.foo.com/davidmerfieId/status/500323409218117633",
"https://twitter.com/davidmerfieId/500323409218117633",
"https://twitter.com/davidmerfieId/status",
"https://twitter.com/davidmerfieId/ST/500323409218117633",
"",
"ABC",
];
for (var i in goodURLs) goodURLs[i] = linkify(goodURLs[i]);
for (var j in badURLs) badURLs[j] = linkify(badURLs[j]);
goodURLs.forEach(function (html) {
plugins(
{ plugins: { twitter: { enabled: true } } },
"/path.txt",
html,
function (err, newHTML) {
assert(newHTML !== html);
}
);
});
badURLs.forEach(function (html) {
plugins(
{ plugins: { twitter: { enabled: true } } },
"/path.txt",
html,
function (err, newHTML) {
assert(newHTML === html);
}
);
});
console.log("All tests complete?");
function linkify(url) {
return '<p><a href="' + url + '">' + url + "</a></p>";
}
}).not.toThrow();
});
});
| davidmerfield/Blot | app/build/plugins/twitter/tests.js | JavaScript | cc0-1.0 | 1,799 |
from django.db import models
# Create your models here.
class Pizza(models.Model):
name = models.CharField(max_length=128)
price = models.DecimalField(decimal_places=2, max_digits=5)
ingredients = models.TextField()
picture = models.ImageField(blank=True, null=True)
def __unicode__(self):
return u'Pizza: {}'.format(self.name)
def __repr__(self):
return unicode(self)
| caioherrera/django-pizza | pizzaria/pizza/models.py | Python | cc0-1.0 | 412 |
jsonp({"cep":"59855000","cidade":"Ita\u00fa","uf":"RN","estado":"Rio Grande do Norte"});
| lfreneda/cepdb | api/v1/59855000.jsonp.js | JavaScript | cc0-1.0 | 89 |
package de.homelab.madgaksha.lotsofbs.entityengine.entitysystem;
import com.badlogic.ashley.core.Entity;
import com.badlogic.ashley.core.Family;
import com.badlogic.ashley.systems.IteratingSystem;
import com.badlogic.gdx.math.MathUtils;
import de.homelab.madgaksha.lotsofbs.entityengine.DefaultPriority;
import de.homelab.madgaksha.lotsofbs.entityengine.Mapper;
import de.homelab.madgaksha.lotsofbs.entityengine.component.DamageQueueComponent;
import de.homelab.madgaksha.lotsofbs.entityengine.component.DeathComponent;
import de.homelab.madgaksha.lotsofbs.entityengine.component.InactiveComponent;
import de.homelab.madgaksha.lotsofbs.entityengine.component.PainPointsComponent;
import de.homelab.madgaksha.lotsofbs.entityengine.component.VoiceComponent;
import de.homelab.madgaksha.lotsofbs.logging.Logger;
/**
* Updates an object's position its velocity over a small time step dt.
*
* @author madgaksha
*/
public class DamageSystem extends IteratingSystem {
@SuppressWarnings("unused")
private final static Logger LOG = Logger.getLogger(DamageQueueComponent.class);
public static final long MAX_PAIN_POINTS = 999999999999L; // 10^12-1
public static final int NUMBER_OF_DIGITS = 12;
/**
* In per-mille (0.001). If damage/maxHP is greater than this theshold,
* other voices will be played etc.
*/
public static final long THRESHOLD_LIGHT_HEAVY_DAMAGE = 10L;
public DamageSystem() {
this(DefaultPriority.damageSystem);
}
public DamageSystem(final int priority) {
super(Family.all(PainPointsComponent.class, DamageQueueComponent.class).exclude(InactiveComponent.class).get(),
priority);
}
@Override
protected void processEntity(final Entity entity, final float deltaTime) {
final PainPointsComponent ppc = Mapper.painPointsComponent.get(entity);
final DamageQueueComponent dqc = Mapper.damageQueueComponent.get(entity);
// Change pain points accordingly.
if (dqc.queuedDamage != 0L) {
// take damage
final VoiceComponent vc = Mapper.voiceComponent.get(entity);
ppc.painPoints = MathUtils.clamp(ppc.painPoints + dqc.queuedDamage, 0L, ppc.maxPainPoints);
if (dqc.keepOneHp) {
ppc.painPoints = Math.min(ppc.maxPainPoints - 1, ppc.painPoints);
dqc.keepOneHp = false;
}
ppc.updatePainPoints();
// Check if entity just died :(
if (ppc.painPoints == ppc.maxPainPoints) {
final DeathComponent dc = Mapper.deathComponent.get(entity);
if (dc != null && !dc.dead) {
if (vc != null && vc.voicePlayer != null)
vc.voicePlayer.playUnconditionally(vc.onDeath);
dc.reaper.kill(entity);
dc.dead = true;
}
}
// Otherwise, play sound on taking damage
else if (vc != null && vc.voicePlayer != null) {
if (dqc.queuedDamage > 0L) {
vc.voicePlayer.play((dqc.queuedDamage * 1000L < THRESHOLD_LIGHT_HEAVY_DAMAGE * ppc.maxPainPoints)
? vc.onLightDamage : vc.onHeavyDamage);
}
else {
vc.voicePlayer.play((-dqc.queuedDamage * 1000L < THRESHOLD_LIGHT_HEAVY_DAMAGE * ppc.maxPainPoints)
? vc.onLightHeal : vc.onHeavyHeal);
}
}
}
dqc.queuedDamage = 0L;
}
}
| blutorange/lotsOfBSGdx | core/src/de/homelab/madgaksha/lotsofbs/entityengine/entitysystem/DamageSystem.java | Java | cc0-1.0 | 3,092 |
import json
from django.core.urlresolvers import reverse
from django.http import HttpResponseNotFound
from django.test import TestCase
from mock import Mock
from utils import use_GET_in
from api.views import msas, tables
class ConversionTest(TestCase):
def test_use_GET_in(self):
fn, request = Mock(), Mock()
request.GET.lists.return_value = [('param1', [0]), ('param2', [-1])]
# Dictionaries become JSON
fn.return_value = {'a': 1, 'b': 2}
response = use_GET_in(fn, request)
self.assertEqual(json.loads(response.content), {'a': 1, 'b': 2})
self.assertEqual(fn.call_args[0][0], {'param1': [0], 'param2': [-1]})
# Everything else is unaltered
fn.return_value = HttpResponseNotFound('Oh noes')
response = use_GET_in(fn, request)
self.assertEqual(response.status_code, 404)
self.assertEqual(response.content, 'Oh noes')
class ViewsTests(TestCase):
fixtures = ['agency.json', 'fake_msa.json', 'api_tracts.json', 'test_counties.json', 'fake_respondents.json']
def test_api_all_user_errors(self):
resp = self.client.get(reverse('all'), {'neLat':'42.048794',
'neLon':'-87.430698',
'swLat':'',
'swLon':'-88.225583',
'year':'2013',
'action_taken':'1,2,3,4,5',
'lender':'736-4045996'})
self.assertEqual(resp.status_code, 404)
resp = self.client.get(reverse('all'), {'neLat':'42.048794',
'neLon':'-87.430698',
'swLat':'41.597775',
'swLon':'',
'year':'2013',
'action_taken':'1,2,3,4,5',
'lender':'736-4045996'})
self.assertEqual(resp.status_code, 404)
def test_api_msas_user_errors(self):
resp = self.client.get(reverse('msas'))
self.assertEqual(resp.status_code, 404)
resp = self.client.get(reverse('msas'), {'neLat':'42.048794',
'neLon':'-87.430698',
'swLat':'',
'swLon':'-88.225583',
'year':'2013',
'action_taken':'1,2,3,4,5',
'lender':'736-4045996'})
self.assertEqual(resp.status_code, 404)
resp = self.client.get(reverse('msas'), {'neLat':'42.048794',
'neLon':'-87.430698',
'swLat':'41.597775',
'swLon':'',
'year':'2013',
'action_taken':'1,2,3,4,5',
'lender':'736-4045996'})
self.assertEqual(resp.status_code, 404)
def test_api_msas_endpoint(self):
"""should return a list of MSA ids in view"""
coords = {'neLat': '36.551569', 'neLon':'-78.961487', 'swLat':'35.824494', 'swLon':'-81.828918'}
url = reverse(msas)
resp = self.client.get(url, coords)
result_list = json.loads(resp.content)
self.assertTrue(isinstance(result_list, list))
self.assertContains(resp, '49180')
def test_api_tables_endpoint(self):
"""should return table_data json for a lender/MSA pair"""
params = {'lender': '90000451965', 'metro': '49180'}
url = reverse(tables)
resp = self.client.get(url, params)
result_dict = json.loads(resp.content)
self.assertTrue(isinstance(result_dict, dict))
keys = ['counties', 'msa']
lender_keys = ['hma_pct', 'lma_pct', 'mma_pct', 'lma', 'mma', 'hma', 'lar_total', 'peer_hma_pct', 'peer_lma_pct', 'peer_mma_pct', 'peer_lma', 'peer_mma', 'peer_hma', 'peer_lar_total', 'odds_lma', 'odds_mma', 'odds_hma']
for key in keys:
self.assertTrue(key in result_dict.keys())
for key in lender_keys:
self.assertTrue(key in result_dict['msa'].keys())
self.assertTrue(len(result_dict['msa']) > 0)
| mehtadev17/mapusaurus | mapusaurus/api/tests.py | Python | cc0-1.0 | 4,338 |
"""
The most important object in the Gratipay object model is Participant, and the
second most important one is Ccommunity. There are a few others, but those are
the most important two. Participant, in particular, is at the center of
everything on Gratipay.
"""
from contextlib import contextmanager
from postgres import Postgres
import psycopg2.extras
@contextmanager
def just_yield(obj):
yield obj
class GratipayDB(Postgres):
def get_cursor(self, cursor=None, **kw):
if cursor:
if kw:
raise ValueError('cannot change options when reusing a cursor')
return just_yield(cursor)
return super(GratipayDB, self).get_cursor(**kw)
def self_check(self):
with self.get_cursor() as cursor:
check_db(cursor)
def check_db(cursor):
"""Runs all available self checks on the given cursor.
"""
_check_balances(cursor)
_check_no_team_balances(cursor)
_check_tips(cursor)
_check_orphans(cursor)
_check_orphans_no_tips(cursor)
_check_paydays_volumes(cursor)
def _check_tips(cursor):
"""
Checks that there are no rows in tips with duplicate (tipper, tippee, mtime).
https://github.com/gratipay/gratipay.com/issues/1704
"""
conflicting_tips = cursor.one("""
SELECT count(*)
FROM
(
SELECT * FROM tips
EXCEPT
SELECT DISTINCT ON(tipper, tippee, mtime) *
FROM tips
ORDER BY tipper, tippee, mtime
) AS foo
""")
assert conflicting_tips == 0
def _check_balances(cursor):
"""
Recalculates balances for all participants from transfers and exchanges.
https://github.com/gratipay/gratipay.com/issues/1118
"""
b = cursor.all("""
select p.username, expected, balance as actual
from (
select username, sum(a) as expected
from (
select participant as username, sum(amount) as a
from exchanges
where amount > 0
and (status is null or status = 'succeeded')
group by participant
union all
select participant as username, sum(amount-fee) as a
from exchanges
where amount < 0
and (status is null or status <> 'failed')
group by participant
union all
select tipper as username, sum(-amount) as a
from transfers
group by tipper
union all
select participant as username, sum(amount) as a
from payments
where direction='to-participant'
group by participant
union all
select participant as username, sum(-amount) as a
from payments
where direction='to-team'
group by participant
union all
select tippee as username, sum(amount) as a
from transfers
group by tippee
) as foo
group by username
) as foo2
join participants p on p.username = foo2.username
where expected <> p.balance
""")
assert len(b) == 0, "conflicting balances: {}".format(b)
def _check_no_team_balances(cursor):
if cursor.one("select exists (select * from paydays where ts_end < ts_start) as running"):
# payday is running
return
teams = cursor.all("""
SELECT t.slug, balance
FROM (
SELECT team, sum(delta) as balance
FROM (
SELECT team, sum(-amount) AS delta
FROM payments
WHERE direction='to-participant'
GROUP BY team
UNION ALL
SELECT team, sum(amount) AS delta
FROM payments
WHERE direction='to-team'
GROUP BY team
) AS foo
GROUP BY team
) AS foo2
JOIN teams t ON t.slug = foo2.team
WHERE balance <> 0
""")
assert len(teams) == 0, "teams with non-zero balance: {}".format(teams)
def _check_orphans(cursor):
"""
Finds participants that
* does not have corresponding elsewhere account
* have not been absorbed by other participant
These are broken because new participants arise from elsewhere
and elsewhere is detached only by take over which makes a note
in absorptions if it removes the last elsewhere account.
Especially bad case is when also claimed_time is set because
there must have been elsewhere account attached and used to sign in.
https://github.com/gratipay/gratipay.com/issues/617
"""
orphans = cursor.all("""
select username
from participants
where not exists (select * from elsewhere where elsewhere.participant=username)
and not exists (select * from absorptions where archived_as=username)
""")
assert len(orphans) == 0, "missing elsewheres: {}".format(list(orphans))
def _check_orphans_no_tips(cursor):
"""
Finds participants
* without elsewhere account attached
* having non zero outstanding tip
This should not happen because when we remove the last elsewhere account
in take_over we also zero out all tips.
"""
orphans_with_tips = cursor.all("""
WITH valid_tips AS (SELECT * FROM current_tips WHERE amount > 0)
SELECT username
FROM (SELECT tipper AS username FROM valid_tips
UNION
SELECT tippee AS username FROM valid_tips) foo
WHERE NOT EXISTS (SELECT 1 FROM elsewhere WHERE participant=username)
""")
assert len(orphans_with_tips) == 0, orphans_with_tips
def _check_paydays_volumes(cursor):
"""
Recalculate *_volume fields in paydays table using exchanges table.
"""
if cursor.one("select exists (select * from paydays where ts_end < ts_start) as running"):
# payday is running
return
charge_volume = cursor.all("""
select * from (
select id, ts_start, charge_volume, (
select coalesce(sum(amount+fee), 0)
from exchanges
where timestamp > ts_start
and timestamp < ts_end
and amount > 0
and recorder is null
and (status is null or status <> 'failed')
) as ref
from paydays
order by id
) as foo
where charge_volume != ref
""")
assert len(charge_volume) == 0
charge_fees_volume = cursor.all("""
select * from (
select id, ts_start, charge_fees_volume, (
select coalesce(sum(fee), 0)
from exchanges
where timestamp > ts_start
and timestamp < ts_end
and amount > 0
and recorder is null
and (status is null or status <> 'failed')
) as ref
from paydays
order by id
) as foo
where charge_fees_volume != ref
""")
assert len(charge_fees_volume) == 0
ach_volume = cursor.all("""
select * from (
select id, ts_start, ach_volume, (
select coalesce(sum(amount), 0)
from exchanges
where timestamp > ts_start
and timestamp < ts_end
and amount < 0
and recorder is null
) as ref
from paydays
order by id
) as foo
where ach_volume != ref
""")
assert len(ach_volume) == 0
ach_fees_volume = cursor.all("""
select * from (
select id, ts_start, ach_fees_volume, (
select coalesce(sum(fee), 0)
from exchanges
where timestamp > ts_start
and timestamp < ts_end
and amount < 0
and recorder is null
) as ref
from paydays
order by id
) as foo
where ach_fees_volume != ref
""")
assert len(ach_fees_volume) == 0
def add_event(c, type, payload):
SQL = """
INSERT INTO events (type, payload)
VALUES (%s, %s)
"""
c.run(SQL, (type, psycopg2.extras.Json(payload)))
| mccolgst/www.gittip.com | gratipay/models/__init__.py | Python | cc0-1.0 | 8,904 |
using UnityEngine;
using System.Collections;
using UnityEditor;
[CustomEditor(typeof(ColorFilter) ),CanEditMultipleObjects]
public class ColorFilterEditor : Editor {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public override void OnInspectorGUI () {
serializedObject.Update();
ColorFilter myScript =(ColorFilter) target;
DrawDefaultInspector();
if (GUILayout.Button("SetColor")){
myScript.SetColor(GameManager.Instance().GetColor(myScript.color));
}
}
}
| yibojiang/Ritual | Assets/Editor/ColorFilterEditor.cs | C# | cc0-1.0 | 546 |
/**
*/
package uk.ac.york.cs.cs2as.cs2as_dsl;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Contributions Def</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link uk.ac.york.cs.cs2as.cs2as_dsl.ContributionsDef#getContributions <em>Contributions</em>}</li>
* </ul>
*
* @see uk.ac.york.cs.cs2as.cs2as_dsl.Cs2as_dslPackage#getContributionsDef()
* @model
* @generated
*/
public interface ContributionsDef extends EObject
{
/**
* Returns the value of the '<em><b>Contributions</b></em>' containment reference list.
* The list contents are of type {@link uk.ac.york.cs.cs2as.cs2as_dsl.Contribution}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Contributions</em>' containment reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Contributions</em>' containment reference list.
* @see uk.ac.york.cs.cs2as.cs2as_dsl.Cs2as_dslPackage#getContributionsDef_Contributions()
* @model containment="true"
* @generated
*/
EList<Contribution> getContributions();
} // ContributionsDef
| adolfosbh/cs2as | uk.ac.york.cs.cs2as.dsl/src-gen/uk/ac/york/cs/cs2as/cs2as_dsl/ContributionsDef.java | Java | epl-1.0 | 1,310 |
/*
* AutoRefactor - Eclipse plugin to automatically refactor Java code bases.
*
* Copyright (C) 2019 Fabrice Tiercelin - initial API and implementation
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* 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 under LICENSE-GNUGPL. If not, see
* <http://www.gnu.org/licenses/>.
*
*
* 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 under LICENSE-ECLIPSE, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.autorefactor.jdt.internal.ui.fix;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.autorefactor.jdt.core.dom.ASTRewrite;
import org.autorefactor.jdt.internal.corext.dom.InterruptibleVisitor;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ImportDeclaration;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.SimpleType;
import org.eclipse.jdt.core.dom.TypeDeclaration;
/**
* Handle the need to add an import for a class.
*/
public abstract class NewClassImportCleanUp extends AbstractCleanUpRule {
/**
* The class that does the cleanup when an import needs to be added.
*/
public abstract static class CleanUpWithNewClassImport extends ASTVisitor {
private Set<String> classesToUseWithImport= new HashSet<>();
private Set<String> importsToAdd= new HashSet<>();
/**
* The imports that need to be added.
*
* @return the importsToBeAdd
*/
public Set<String> getImportsToAdd() {
return importsToAdd;
}
/**
* The imports already existing.
*
* @return the already imported classes
*/
public Set<String> getClassesToUseWithImport() {
return classesToUseWithImport;
}
}
private static class LocalClassVisitor extends InterruptibleVisitor {
private Set<String> classnamesNeverUsedLocally= new HashSet<>();
/**
* LocalClassVisitor.
*
* @param classnamesNeverUsedLocally Classnames never used locally
*/
public LocalClassVisitor(final Set<String> classnamesNeverUsedLocally) {
this.classnamesNeverUsedLocally= classnamesNeverUsedLocally;
}
@Override
public boolean visit(final TypeDeclaration nestedClass) {
classnamesNeverUsedLocally.remove(nestedClass.getName().getIdentifier());
return !classnamesNeverUsedLocally.isEmpty() || interruptVisit();
}
@Override
public boolean visit(final SimpleType simpleName) {
if (simpleName.getName().isSimpleName()) {
classnamesNeverUsedLocally.remove(((SimpleName) simpleName.getName()).getIdentifier());
if (classnamesNeverUsedLocally.isEmpty()) {
return interruptVisit();
}
}
return true;
}
/**
* @return the classnamesNeverUsedLocally
*/
public Set<String> getClassnamesNeverUsedLocally() {
return classnamesNeverUsedLocally;
}
}
/**
* True if an import already exists for a class.
*
* @param node One node in the class file
* @return True if an import already exists for a class.
*/
public Set<String> getAlreadyImportedClasses(final ASTNode node) {
Set<String> alreadyImportedClasses= new HashSet<>();
CompilationUnit cu= (CompilationUnit) node.getRoot();
Set<String> classesToUse= getClassesToImport();
Map<String, String> importsByPackage= new HashMap<>();
for (String clazz : classesToUse) {
importsByPackage.put(getPackageName(clazz), clazz);
}
for (Object anObject : cu.imports()) {
ImportDeclaration anImport= (ImportDeclaration) anObject;
if (anImport.isOnDemand()) {
String fullName= importsByPackage.get(anImport.getName().getFullyQualifiedName());
if (fullName != null) {
alreadyImportedClasses.add(fullName);
}
} else if (classesToUse.contains(anImport.getName().getFullyQualifiedName())) {
alreadyImportedClasses.add(anImport.getName().getFullyQualifiedName());
}
}
return alreadyImportedClasses;
}
@Override
public boolean visit(final CompilationUnit node) {
if (!super.visit(node)) {
return false;
}
Set<String> classesToUse= getClassesToImport();
if (classesToUse.isEmpty()) {
return true;
}
Map<String, String> importsByClassname= new HashMap<>();
Map<String, String> importsByPackage= new HashMap<>();
for (String clazz : classesToUse) {
importsByClassname.put(getSimpleName(clazz), clazz);
importsByPackage.put(getPackageName(clazz), clazz);
}
Set<String> alreadyImportedClasses= new HashSet<>();
Set<String> classesToImport= new HashSet<>(classesToUse);
for (Object anObject : node.imports()) {
ImportDeclaration anImport= (ImportDeclaration) anObject;
if (!anImport.isStatic()) {
if (anImport.isOnDemand()) {
String fullName= importsByPackage.get(anImport.getName().getFullyQualifiedName());
if (fullName != null) {
alreadyImportedClasses.add(fullName);
}
} else if (classesToUse.contains(anImport.getName().getFullyQualifiedName())) {
alreadyImportedClasses.add(anImport.getName().getFullyQualifiedName());
classesToImport.remove(anImport.getName().getFullyQualifiedName());
} else if (importsByClassname.containsKey(getSimpleName(anImport.getName().getFullyQualifiedName()))) {
classesToImport
.remove(importsByClassname.get(getSimpleName(anImport.getName().getFullyQualifiedName())));
}
}
}
filterLocallyUsedNames(node, importsByClassname, classesToImport);
if (alreadyImportedClasses.size() < classesToUse.size() && !classesToImport.isEmpty()) {
CleanUpWithNewClassImport refactoringClass= getRefactoringClassInstance();
refactoringClass.getClassesToUseWithImport().addAll(alreadyImportedClasses);
refactoringClass.getClassesToUseWithImport().addAll(classesToImport);
node.accept(refactoringClass);
if (!refactoringClass.getImportsToAdd().isEmpty()) {
ASTRewrite rewrite= cuRewrite.getASTRewrite();
for (String importToAdd : refactoringClass.getImportsToAdd()) {
rewrite.getImportRewrite().addImport(importToAdd);
}
return false;
}
}
return true;
}
/**
* Add the class to the list of classes to import and return the name of the class.
*
* @param classToUse The class to use
* @param classesToUseWithImport The classes to use with import
* @param importsToAdd The imports to add
*
* @return the name of the class.
*/
public static String addImport(final Class<?> classToUse, final Set<String> classesToUseWithImport,
final Set<String> importsToAdd) {
if (classesToUseWithImport.contains(classToUse.getCanonicalName())) {
importsToAdd.add(classToUse.getCanonicalName());
return classToUse.getSimpleName();
}
return classToUse.getCanonicalName();
}
/**
* The simple name of the class.
*
* @param fullyQualifiedName The name of the class with packages.
* @return The simple name of the class.
*/
public String getSimpleName(final String fullyQualifiedName) {
return fullyQualifiedName.replaceFirst("^(?:.*\\.)?([^.]*)$", "$1"); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* The package of the class.
*
* @param fullyQualifiedName The name of the class with packages.
* @return The package of the class.
*/
public String getPackageName(final String fullyQualifiedName) {
return fullyQualifiedName.replaceFirst("^(.*)\\.[^.]+$", "$1"); //$NON-NLS-1$ //$NON-NLS-2$
}
private void filterLocallyUsedNames(final CompilationUnit node, final Map<String, String> importsByClassname,
final Set<String> classesToImport) {
LocalClassVisitor nestedClassVisitor= new LocalClassVisitor(importsByClassname.keySet());
nestedClassVisitor.visitNode(node);
Set<String> classnamesNeverUsedLocally= nestedClassVisitor.getClassnamesNeverUsedLocally();
Iterator<String> iterator= classesToImport.iterator();
while (iterator.hasNext()) {
String classToImport= iterator.next();
if (!classnamesNeverUsedLocally.contains(getSimpleName(classToImport))) {
iterator.remove();
}
}
}
/**
* The class that does the cleanup when an import needs to be added.
*
* @return The class that does the cleanup when an import needs to be added.
*/
public abstract CleanUpWithNewClassImport getRefactoringClassInstance();
/**
* The class names to import.
*
* @return The class names to import
*/
public abstract Set<String> getClassesToImport();
}
| rpau/AutoRefactor | plugin/src/main/java/org/autorefactor/jdt/internal/ui/fix/NewClassImportCleanUp.java | Java | epl-1.0 | 9,275 |
// $Id$
# ifndef CPPAD_CPPAD_IPOPT_NLP_HPP
# define CPPAD_CPPAD_IPOPT_NLP_HPP
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-15 Bradley M. Bell
CppAD is distributed under multiple licenses. This distribution is under
the terms of the
Eclipse Public License Version 1.0.
A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */
/*
$begin cppad_ipopt_nlp$$
$dollar @$$
$spell
libipopt
namespace
dir
cppad
bool
doesn't
nan
inf
naninf
std
maxiter
infeasibility
obj
const
optimizer
cppad_ipopt_nlp.hpp
fg_info.eval
retape
CppAD
$$
$section Nonlinear Programming Using the CppAD Interface to Ipopt$$
$mindex AD$$
$head Deprecated 2012-11-28$$
This interface to Ipopt is deprecated, use $cref ipopt_solve$$ instead.
$head Syntax$$
$codei%# include "cppad_ipopt_nlp.hpp"
%$$
$codei%cppad_ipopt_solution %solution%;
%$$
$codei%cppad_ipopt_nlp %cppad_nlp%(
%n%, %m%, %x_i%, %x_l%, %x_u%, %g_l%, %g_u%, &%fg_info%, &%solution%
)%$$
$codei%
export LD_LIBRARY_PATH=@LD_LIBRARY_PATH:%ipopt_library_paths%$$
$head Purpose$$
The class $code cppad_ipopt_nlp$$ is used to solve nonlinear programming
problems of the form
$latex \[
\begin{array}{rll}
{\rm minimize} & f(x)
\\
{\rm subject \; to} & g^l \leq g(x) \leq g^u
\\
& x^l \leq x \leq x^u
\end{array}
\] $$
This is done using
$href%
http://www.coin-or.org/projects/Ipopt.xml%
Ipopt
%$$
optimizer and
$href%
http://www.coin-or.org/CppAD/%
CppAD
%$$
Algorithmic Differentiation package.
$head cppad_ipopt namespace$$
All of the declarations for these routines
are in the $code cppad_ipopt$$ namespace
(not the $code CppAD$$ namespace).
For example; $cref/SizeVector/cppad_ipopt_nlp/SizeVector/$$ below
actually denotes the type $code cppad_ipopt::SizeVector$$.
$head ipopt_library_paths$$
If you are linking to a shared version of the Ipopt library,
you may have to add some paths the $code LD_LIBRARY_PATH$$
shell variable using the $code export$$ command in the syntax above.
For example, if the file the ipopt library is
$codei%
%ipopt_prefix%/lib64/libipopt.a
%$$
you will need to add the corresponding directory; e.g.,
$codei%
export LD_LIBRARY_PATH="%ipopt_prefix%/lib64%:@LD_LIBRARY_PATH"
%$$
see $cref ipopt_prefix$$.
$head fg(x)$$
The function $latex fg : \B{R}^n \rightarrow \B{R}^{m+1}$$ is defined by
$latex \[
\begin{array}{rcl}
fg_0 (x) & = & f(x) \\
fg_1 (x) & = & g_0 (x) \\
& \vdots & \\
fg_m (x) & = & g_{m-1} (x)
\end{array}
\] $$
$subhead Index Vector$$
We define an $icode index vector$$ as a vector of non-negative integers
for which none of the values are equal; i.e.,
it is both a vector and a set.
If $latex I$$ is an index vector $latex |I|$$ is used to denote the
number of elements in $latex I$$ and $latex \| I \|$$ is used
to denote the value of the maximum element in $latex I$$.
$subhead Projection$$
Given an index vector $latex J$$ and a positive integer $latex n$$
where $latex n > \| J \|$$, we use $latex J \otimes n $$ for
the mapping $latex ( J \otimes n ) : \B{R}^n \rightarrow \B{R}^{|J|}$$ defined by
$latex \[
[ J \otimes n ] (x)_j = x_{J(j)}
\] $$
for $latex j = 0 , \ldots |J| - 1$$.
$subhead Injection$$
Given an index vector $latex I$$ and a positive integer $latex m$$
where $latex m > \| I \|$$, we use $latex m \otimes I$$ for
the mapping $latex ( m \otimes I ): \B{R}^{|I|} \rightarrow \B{R}^m$$ defined by
$latex \[
[ m \otimes I ] (y)_i = \left\{ \begin{array}{ll}
y_k & {\rm if} \; i = I(k) \; {\rm for \; some} \;
k \in \{ 0 , \cdots, |I|-1 \}
\\
0 & {\rm otherwise}
\end{array} \right.
\] $$
$subhead Representation$$
In many applications, each of the component functions of $latex fg(x)$$
only depend on a few of the components of $latex x$$.
In this case, expressing $latex fg(x)$$ in terms of simpler functions
with fewer arguments can greatly reduce the amount of work required
to compute its derivatives.
$pre
$$
We use the functions
$latex r_k : \B{R}^{q(k)} \rightarrow \B{R}^{p(k)}$$
for $latex k = 0 , \ldots , K$$ to express our
representation of $latex fg(x)$$ in terms of simpler functions
as follows
$latex \[
fg(x) = \sum_{k=0}^{K-1} \; \sum_{\ell=0}^{L(k) - 1}
[ (m+1) \otimes I_{k,\ell} ] \; \circ
\; r_k \; \circ \; [ J_{k,\ell} \otimes n ] \; (x)
\] $$
where $latex \circ$$ represents function composition,
for $latex k = 0 , \ldots , K - 1$$, and $latex \ell = 0 , \ldots , L(k)$$,
$latex I_{k,\ell}$$ and $latex J_{k,\ell}$$ are index vectors with
$latex | J_{k,\ell} | = q(k)$$,
$latex \| J_{k,\ell} \| < n$$,
$latex | I_{k,\ell} | = p(k)$$, and
$latex \| I_{k,\ell} \| \leq m$$.
$head Simple Representation$$
In the simple representation,
$latex r_0 (x) = fg(x)$$,
$latex K = 1$$,
$latex q(0) = n$$,
$latex p(0) = m+1$$,
$latex L(0) = 1$$,
$latex I_{0,0} = (0 , \ldots , m)$$,
and $latex J_{0,0} = (0 , \ldots , n-1)$$.
$head SizeVector$$
The type $codei SizeVector$$ is defined by the
$codei cppad_ipopt_nlp.hpp$$ include file to be a
$cref SimpleVector$$ class with elements of type
$code size_t$$.
$head NumberVector$$
The type $codei NumberVector$$ is defined by the
$codei cppad_ipopt_nlp.hpp$$ include file to be a
$cref SimpleVector$$ class with elements of type
$code Ipopt::Number$$.
$head ADNumber$$
The type $codei ADNumber$$ is defined by the
$codei cppad_ipopt_nlp.hpp$$ include file to be a
an AD type that can be used to compute derivatives.
$head ADVector$$
The type $codei ADVector$$ is defined by the
$codei cppad_ipopt_nlp.hpp$$ include file to be a
$cref SimpleVector$$ class with elements of type
$code ADNumber$$.
$head n$$
The argument $icode n$$ has prototype
$codei%
size_t %n%
%$$
It specifies the dimension of the argument space;
i.e., $latex x \in \B{R}^n$$.
$head m$$
The argument $icode m$$ has prototype
$codei%
size_t %m%
%$$
It specifies the dimension of the range space for $latex g$$;
i.e., $latex g : \B{R}^n \rightarrow \B{R}^m$$.
$head x_i$$
The argument $icode x_i$$ has prototype
$codei%
const NumberVector& %x_i%
%$$
and its size is equal to $latex n$$.
It specifies the initial point where Ipopt starts the optimization process.
$head x_l$$
The argument $icode x_l$$ has prototype
$codei%
const NumberVector& %x_l%
%$$
and its size is equal to $latex n$$.
It specifies the lower limits for the argument in the optimization problem;
i.e., $latex x^l$$.
$head x_u$$
The argument $icode x_u$$ has prototype
$codei%
const NumberVector& %x_u%
%$$
and its size is equal to $latex n$$.
It specifies the upper limits for the argument in the optimization problem;
i.e., $latex x^u$$.
$head g_l$$
The argument $icode g_l$$ has prototype
$codei%
const NumberVector& %g_l%
%$$
and its size is equal to $latex m$$.
It specifies the lower limits for the constraints in the optimization problem;
i.e., $latex g^l$$.
$head g_u$$
The argument $icode g_u$$ has prototype
$codei%
const NumberVector& %g_u%
%$$
and its size is equal to $latex n$$.
It specifies the upper limits for the constraints in the optimization problem;
i.e., $latex g^u$$.
$head fg_info$$
The argument $icode fg_info$$ has prototype
$codei%
%FG_info fg_info%
%$$
where the class $icode FG_info$$ is derived from the
base class $code cppad_ipopt_fg_info$$.
Certain virtual member functions of $icode fg_info$$ are used to
compute the value of $latex fg(x)$$.
The specifications for these member functions are given below:
$subhead fg_info.number_functions$$
This member function has prototype
$codei%
virtual size_t cppad_ipopt_fg_info::number_functions(void)
%$$
If $icode K$$ has type $code size_t$$, the syntax
$codei%
%K% = %fg_info%.number_functions()
%$$
sets $icode K$$ to the number of functions used in the
representation of $latex fg(x)$$; i.e., $latex K$$ in
the $cref/representation/cppad_ipopt_nlp/fg(x)/Representation/$$ above.
$pre
$$
The $code cppad_ipopt_fg_info$$ implementation of this function
corresponds to the simple representation mentioned above; i.e.
$icode%K% = 1%$$.
$subhead fg_info.eval_r$$
This member function has the prototype
$codei%
virtual ADVector cppad_ipopt_fg_info::eval_r(size_t %k%, const ADVector& %u%) = 0;
%$$
Thus it is a pure virtual function and must be defined in the
derived class $icode FG_info$$.
$pre
$$
This function computes the value of $latex r_k (u)$$
used in the $cref/representation/cppad_ipopt_nlp/fg(x)/Representation/$$
for $latex fg(x)$$.
If $icode k$$ in $latex \{0 , \ldots , K-1 \}$$ has type $code size_t$$,
$icode u$$ is an $code ADVector$$ of size $icode q(k)$$
and $icode r$$ is an $code ADVector$$ of size $icode p(k)$$
the syntax
$codei%
%r% = %fg_info%.eval_r(%k%, %u%)
%$$
set $icode r$$ to the vector $latex r_k (u)$$.
$subhead fg_info.retape$$
This member function has the prototype
$codei%
virtual bool cppad_ipopt_fg_info::retape(size_t %k%)
%$$
If $icode k$$ in $latex \{0 , \ldots , K-1 \}$$ has type $code size_t$$,
and $icode retape$$ has type $code bool$$,
the syntax
$codei%
%retape% = %fg_info%.retape(%k%)
%$$
sets $icode retape$$ to true or false.
If $icode retape$$ is true,
$code cppad_ipopt_nlp$$ will retape the operation sequence
corresponding to $latex r_k (u)$$ for
every value of $icode u$$.
An $code cppad_ipopt_nlp$$ object
should use much less memory and run faster if $icode retape$$ is false.
You can test both the true and false cases to make sure
the operation sequence does not depend on $icode u$$.
$pre
$$
The $code cppad_ipopt_fg_info$$ implementation of this function
sets $icode retape$$ to true
(while slower it is also safer to always retape).
$subhead fg_info.domain_size$$
This member function has prototype
$codei%
virtual size_t cppad_ipopt_fg_info::domain_size(size_t %k%)
%$$
If $icode k$$ in $latex \{0 , \ldots , K-1 \}$$ has type $code size_t$$,
and $icode q$$ has type $code size_t$$, the syntax
$codei%
%q% = %fg_info%.domain_size(%k%)
%$$
sets $icode q$$ to the dimension of the domain space for $latex r_k (u)$$;
i.e., $latex q(k)$$ in
the $cref/representation/cppad_ipopt_nlp/fg(x)/Representation/$$ above.
$pre
$$
The $code cppad_ipopt_h_base$$ implementation of this function
corresponds to the simple representation mentioned above; i.e.,
$latex q = n$$.
$subhead fg_info.range_size$$
This member function has prototype
$codei%
virtual size_t cppad_ipopt_fg_info::range_size(size_t %k%)
%$$
If $icode k$$ in $latex \{0 , \ldots , K-1 \}$$ has type $code size_t$$,
and $icode p$$ has type $code size_t$$, the syntax
$codei%
%p% = %fg_info%.range_size(%k%)
%$$
sets $icode p$$ to the dimension of the range space for $latex r_k (u)$$;
i.e., $latex p(k)$$ in
the $cref/representation/cppad_ipopt_nlp/fg(x)/Representation/$$ above.
$pre
$$
The $code cppad_ipopt_h_base$$ implementation of this function
corresponds to the simple representation mentioned above; i.e.,
$latex p = m+1$$.
$subhead fg_info.number_terms$$
This member function has prototype
$codei%
virtual size_t cppad_ipopt_fg_info::number_terms(size_t %k%)
%$$
If $icode k$$ in $latex \{0 , \ldots , K-1 \}$$ has type $code size_t$$,
and $icode L$$ has type $code size_t$$, the syntax
$codei%
%L% = %fg_info%.number_terms(%k%)
%$$
sets $icode L$$ to the number of terms in representation
for this value of $icode k$$;
i.e., $latex L(k)$$ in
the $cref/representation/cppad_ipopt_nlp/fg(x)/Representation/$$ above.
$pre
$$
The $code cppad_ipopt_h_base$$ implementation of this function
corresponds to the simple representation mentioned above; i.e.,
$latex L = 1$$.
$subhead fg_info.index$$
This member function has prototype
$codei%
virtual void cppad_ipopt_fg_info::index(
size_t %k%, size_t %ell%, SizeVector& %I%, SizeVector& %J%
)
%$$
The argument
$icode%
k
%$$
has type $codei size_t$$
and is a value between zero and $latex K-1$$ inclusive.
The argument
$icode%
ell
%$$
has type $codei size_t$$
and is a value between zero and $latex L(k)-1$$ inclusive.
The argument
$icode%
I
%$$ is a $cref SimpleVector$$ with elements
of type $code size_t$$ and size greater than or equal to $latex p(k)$$.
The input value of the elements of $icode I$$ does not matter.
The output value of
the first $latex p(k)$$ elements of $icode I$$
must be the corresponding elements of $latex I_{k,ell}$$
in the $cref/representation/cppad_ipopt_nlp/fg(x)/Representation/$$ above.
The argument
$icode%
J
%$$ is a $cref SimpleVector$$ with elements
of type $code size_t$$ and size greater than or equal to $latex q(k)$$.
The input value of the elements of $icode J$$ does not matter.
The output value of
the first $latex q(k)$$ elements of $icode J$$
must be the corresponding elements of $latex J_{k,ell}$$
in the $cref/representation/cppad_ipopt_nlp/fg(x)/Representation/$$ above.
$pre
$$
The $code cppad_ipopt_h_base$$ implementation of this function
corresponds to the simple representation mentioned above; i.e.,
for $latex i = 0 , \ldots , m$$,
$icode%I%[%i%] = %i%$$,
and for $latex j = 0 , \ldots , n-1$$,
$icode%J%[%j%] = %j%$$.
$head solution$$
After the optimization process is completed, $icode solution$$ contains
the following information:
$subhead status$$
The $icode status$$ field of $icode solution$$ has prototype
$codei%
cppad_ipopt_solution::solution_status %solution%.status
%$$
It is the final Ipopt status for the optimizer.
Here is a list of the possible values for the status:
$table
$icode status$$ $cnext Meaning
$rnext
not_defined $cnext
The optimizer did not return a final status to this $code cppad_ipopt_nlp$$
object.
$rnext
unknown $cnext
The status returned by the optimizer is not defined in the Ipopt
documentation for $code finalize_solution$$.
$rnext
success $cnext
Algorithm terminated successfully at a point satisfying the convergence
tolerances (see Ipopt options).
$rnext
maxiter_exceeded $cnext
The maximum number of iterations was exceeded (see Ipopt options).
$rnext
stop_at_tiny_step $cnext
Algorithm terminated because progress was very slow.
$rnext
stop_at_acceptable_point $cnext
Algorithm stopped at a point that was converged,
not to the 'desired' tolerances, but to 'acceptable' tolerances
(see Ipopt options).
$rnext
local_infeasibility $cnext
Algorithm converged to a non-feasible point
(problem may have no solution).
$rnext
user_requested_stop $cnext
This return value should not happen.
$rnext
diverging_iterates $cnext
It the iterates are diverging.
$rnext
restoration_failure $cnext
Restoration phase failed, algorithm doesn't know how to proceed.
$rnext
error_in_step_computation $cnext
An unrecoverable error occurred while Ipopt tried to
compute the search direction.
$rnext
invalid_number_detected $cnext
Algorithm received an invalid number (such as $code nan$$ or $code inf$$)
from the users function $icode%fg_info%.eval%$$ or from the CppAD evaluations
of its derivatives
(see the Ipopt option $code check_derivatives_for_naninf$$).
$rnext
internal_error $cnext
An unknown Ipopt internal error occurred.
Contact the Ipopt authors through the mailing list.
$tend
$subhead x$$
The $code x$$ field of $icode solution$$ has prototype
$codei%
NumberVector %solution%.x
%$$
and its size is equal to $latex n$$.
It is the final $latex x$$ value for the optimizer.
$subhead z_l$$
The $code z_l$$ field of $icode solution$$ has prototype
$codei%
NumberVector %solution%.z_l
%$$
and its size is equal to $latex n$$.
It is the final Lagrange multipliers for the
lower bounds on $latex x$$.
$subhead z_u$$
The $code z_u$$ field of $icode solution$$ has prototype
$codei%
NumberVector %solution%.z_u
%$$
and its size is equal to $latex n$$.
It is the final Lagrange multipliers for the
upper bounds on $latex x$$.
$subhead g$$
The $code g$$ field of $icode solution$$ has prototype
$codei%
NumberVector %solution%.g
%$$
and its size is equal to $latex m$$.
It is the final value for the constraint function $latex g(x)$$.
$subhead lambda$$
The $code lambda$$ field of $icode solution$$ has prototype
$codei%
NumberVector %solution%.lambda
%$$
and its size is equal to $latex m$$.
It is the final value for the
Lagrange multipliers corresponding to the constraint function.
$subhead obj_value$$
The $code obj_value$$ field of $icode solution$$ has prototype
$codei%
Number %solution%.obj_value
%$$
It is the final value of the objective function $latex f(x)$$.
$children%
cppad_ipopt/example/get_started.cpp%
cppad_ipopt/example/ode1.omh%
cppad_ipopt/speed/ode_speed.cpp
%$$
$head Example$$
The file
$cref ipopt_nlp_get_started.cpp$$ is an example and test of
$code cppad_ipopt_nlp$$ that uses the
$cref/simple representation/cppad_ipopt_nlp/Simple Representation/$$.
It returns true if it succeeds and false otherwise.
The section $cref ipopt_nlp_ode$$ discusses an example that
uses a more complex representation.
$head Wish List$$
This is a list of possible future improvements to
$code cppad_ipopt_nlp$$ that would require changed to the user interface:
$list number$$
The routine $codei%fg_info.eval_r(%k%, %u%)%$$ should also support
$codei NumberVector$$ for the type of the argument $code u$$
(this would certainly be more efficient when
$codei%fg_info.retape(%k%)%$$ is true and $latex L(k) > 1$$).
It could be an option for the user to provide this as well as
the necessary $code ADVector$$ definition.
$lnext
There should a $cref Discrete$$ routine that the user can call
to determine the value of $latex \ell$$ during the evaluation of
$codei%fg_info.eval_r(%k%, %u%)%$$.
This way data, which does not affect the derivative values,
can be included in the function recording and evaluation.
$lend
$end
-----------------------------------------------------------------------------
*/
# include <cppad/cppad.hpp>
# include <coin/IpIpoptApplication.hpp>
# include <coin/IpTNLP.hpp>
/*!
\file cppad_ipopt_nlp.hpp
\brief CppAD interface to Ipopt
\ingroup cppad_ipopt_nlp_cpp
*/
// ---------------------------------------------------------------------------
namespace cppad_ipopt {
// ---------------------------------------------------------------------------
/// A scalar value used to record operation sequence.
typedef CppAD::AD<Ipopt::Number> ADNumber;
/// A simple vector of values used to record operation sequence
typedef CppAD::vector<ADNumber> ADVector;
/// A simple vector of size_t values.
typedef CppAD::vector<size_t> SizeVector;
/// A simple vector of values used by Ipopt
typedef CppAD::vector<Ipopt::Number> NumberVector;
/*!
Abstract base class user derives from to define the funcitons in the problem.
*/
class cppad_ipopt_fg_info
{
/// allow cppad_ipopt_nlp class complete access to this class
friend class cppad_ipopt_nlp;
private:
/// domain space dimension for the functions f(x), g(x)
size_t n_;
/// range space dimension for the function g(x)
size_t m_;
/// the cppad_ipopt_nlp constructor uses this method to set n_
void set_n(size_t n)
{ n_ = n; }
/// the cppad_ipopt_nlp constructor uses this method to set m_
void set_m(size_t m)
{ m_ = m; }
public:
/// destructor virtual so user derived class destructor gets called
virtual ~cppad_ipopt_fg_info(void)
{ }
/// number_functions; i.e. K (simple representation uses 1)
virtual size_t number_functions(void)
{ return 1; }
/// function that evaluates the users representation for f(x) and
/// and g(x) is pure virtual so user must define it in derived class
virtual ADVector eval_r(size_t k, const ADVector& u) = 0;
/// should the function r_k (u) be retaped when ever the arguemnt
/// u changes (default is true which is safe but slow)
virtual bool retape(size_t k)
{ return true; }
/// domain_size q[k] for r_k (u) (simple representation uses n)
virtual size_t domain_size(size_t k)
{ return n_; }
/// range_size p[k] for r_k (u) (simple representation uses m+1)
virtual size_t range_size(size_t k)
{ return m_ + 1; }
/// number_terms that use r_k (u) (simple represenation uses 1)
virtual size_t number_terms(size_t k)
{ return 1; }
/// return the index vectors I_{k,ell} and J_{k,ell}
/// (simple representation uses I[i] = i and J[j] = j)
virtual void index(size_t k, size_t ell, SizeVector& I, SizeVector& J)
{ assert( I.size() >= m_ + 1 );
assert( J.size() >= n_ );
for(size_t i = 0; i <= m_; i++)
I[i] = i;
for(size_t j = 0; j < n_; j++)
J[j] = j;
}
};
/*!
Class that contains information about the problem solution
\section Nonlinear_Programming_Problem Nonlinear Programming Problem
We are give smooth functions
\f$ f : {\bf R}^n \rightarrow {\bf R} \f$
and
\f$ g : {\bf R}^n \rightarrow {\bf R}^m \f$
and wish to solve the problem
\f[
\begin{array}{rcl}
{\rm minimize} & f(x) & {\rm w.r.t.} \; x \in {\bf R}^n
\\
{\rm subject \; to} & g^l \leq g(x) \leq g^u
\\
& x^l \leq x \leq x^u
\end{array}
\f]
\section Users_Representation Users Representation
The functions
\f$ f : {\bf R}^n \rightarrow {\bf R} \f$ and
\f$ g : {\bf R}^n \rightarrow {\bf R}^m \f$ are defined by
\f[
\left( \begin{array}{c} f(x) \\ g(x) \end{array} \right)
=
\sum_{k=0}^{K-1} \; \sum_{\ell=0}^{L(k) - 1}
[ (m+1) \otimes I_{k,\ell} ] \; \circ
\; r_k \; \circ \; [ J_{k,\ell} \otimes n ] \; (x)
\f]
where for \f$ k = 0 , \ldots , K-1\f$,
\f$ r_k : {\bf R}^{q(k)} \rightarrow {\bf R}^{p(k)} \f$.
\section Deprecated_Evaluation_Methods Evaluation Methods
The set of evaluation methods for this class is
\verbatim
{ eval_f, eval_grad_f, eval_g, eval_jac_g, eval_h }
\endverbatim
Note that the \c bool return flag for the evaluations methods
does not appear in the Ipopt documentation.
Looking at the code, it seems to be a flag telling Ipopt to abort
when the flag is false.
*/
class cppad_ipopt_solution
{
public:
/// possible values for he solution status
enum solution_status {
not_defined,
success,
maxiter_exceeded,
stop_at_tiny_step,
stop_at_acceptable_point,
local_infeasibility,
user_requested_stop,
feasible_point_found,
diverging_iterates,
restoration_failure,
error_in_step_computation,
invalid_number_detected,
too_few_degrees_of_freedom,
internal_error,
unknown
} status;
/// the approximation solution
NumberVector x;
/// Lagrange multipliers corresponding to lower bounds on x
NumberVector z_l;
/// Lagrange multipliers corresponding to upper bounds on x
NumberVector z_u;
/// value of g(x)
NumberVector g;
/// Lagrange multipliers correspondiing constraints on g(x)
NumberVector lambda;
/// value of f(x)
Ipopt::Number obj_value;
/// constructor initializes solution status as not yet defined
cppad_ipopt_solution(void)
{ status = not_defined; }
};
/*!
Class connects Ipopt to CppAD for derivative and sparsity pattern calculations.
*/
class cppad_ipopt_nlp : public Ipopt::TNLP
{
private:
/// A Scalar value used by Ipopt
typedef Ipopt::Number Number;
/// An index value used by Ipopt
typedef Ipopt::Index Index;
/// Indexing style used in Ipopt sparsity structure
typedef Ipopt::TNLP::IndexStyleEnum IndexStyleEnum;
/// A simple vector of boolean values
typedef CppAD::vectorBool BoolVector;
/// A simple vector of AD function objects
typedef CppAD::vector< CppAD::ADFun<Number> > ADFunVector;
/// A simple vector of simple vectors of boolean values
typedef CppAD::vector<BoolVector> BoolVectorVector;
/// A mapping that is dense in i, sparse in j, and maps (i, j)
/// to the corresponding sparsity index in Ipopt.
typedef CppAD::vector< std::map<size_t,size_t> > IndexMap;
// ------------------------------------------------------------------
// Values directly passed in to constuctor
// ------------------------------------------------------------------
/// dimension of the domain space for f(x) and g(x)
/// (passed to ctor)
const size_t n_;
/// dimension of the range space for g(x)
/// (passed to ctor)
const size_t m_;
/// dimension of the range space for g(x)
/// (passed to ctor)
const NumberVector x_i_;
/// lower limit for x
/// (size n_), (passed to ctor)
const NumberVector x_l_;
/// upper limit for x
/// (size n_) (passed to ctor)
const NumberVector x_u_;
/// lower limit for g(x)
/// (size m_) (passed to ctor)
const NumberVector g_l_;
/// upper limit for g(x)
/// (size m_) (passed to ctor)
const NumberVector g_u_;
/// pointer to base class version of derived class object used to get
/// information about the user's representation for f(x) and g(x)
/// (passed to ctor)
cppad_ipopt_fg_info* const fg_info_;
/// pointer to object where final results are stored
/// (passed to ctor)
cppad_ipopt_solution* const solution_;
/// plus infinity as a value of type Number
const Number infinity_;
// ------------------------------------------------------------------
// Effectively const values determined during constructor using calls
// to fg_info:
// ------------------------------------------------------------------
/// The value of \f$ K \f$ in the representation.
/// (effectively const)
size_t K_;
/// Does operation sequence for \f$ r_k (u) \f$ depend on \f$ u \f$.
/// (size K_) (effectively const)
BoolVector retape_;
/// <tt>q_[k]</tt> is the domain space dimension for \f$ r_k (u) \f$
/// (size K_) (effectively const)
SizeVector q_;
/// <tt>p_[k]</tt> is the range space dimension for \f$ r_k (u) \f$
/// (size K_) (effectively const)
SizeVector p_;
/// <tt>L_[k]</tt> is number of times \f$ r_k (u) \f$ appears in
/// the representation summation
/// (size K_) (effectively const)
SizeVector L_;
// -------------------------------------------------------------------
// Other effectively const values determined by the constructor:
// -------------------------------------------------------------------
/*!
CppAD sparsity patterns for \f$ \{ r_k^{(1)} (u) \} \f$ (set by ctor).
For <tt>k = 0 , ... , K_-1, pattern_jac_r_[k]</tt>
is a CppAD sparsity pattern for the Jacobian of \f$ r_k (u) \f$
and as such it has size <tt>p_[k]*q_[k]</tt>.
(effectively const)
*/
BoolVectorVector pattern_jac_r_;
/*!
CppAD sparsity patterns for \f$ \{ r_k^{(2)} (u) \} \f$ (set by ctor).
For <tt>k = 0 , ... , K_-1, pattern_jac_r_[k]</tt>
is a CppAD sparsity pattern for the Hessian of
\f[
R(u) = \sum_{i=0}^{p[k]-1} r_k (u)_i
\f]
and as such it has size <tt>q_[k]*q_[k]</tt>.
(effectively const)
*/
BoolVectorVector pattern_hes_r_;
/// number non-zero is Ipopt sparsity structor for Jacobian of g(x)
/// (effectively const)
size_t nnz_jac_g_;
/// row indices in Ipopt sparsity structor for Jacobian of g(x)
/// (effectively const)
SizeVector iRow_jac_g_;
/// column indices in Ipopt sparsity structor for Jacobian of g(x)
/// (effectively const)
SizeVector jCol_jac_g_;
/// number non-zero is Ipopt sparsity structor for Hessian of Lagragian
/// (effectively const)
size_t nnz_h_lag_;
/// row indices in Ipopt sparsity structor for Hessian of Lagragian
/// (effectively const)
SizeVector iRow_h_lag_;
/// column indices in Ipopt sparsity structor for Hessian of Lagragian
/// (effectively const)
SizeVector jCol_h_lag_;
/*!
Mapping from (i, j) in Jacobian of g(x) to Ipopt sparsity structure
For <tt>i = 0 , ... , m_-1, index_jac_g_[i]</tt>
is a standard map from column index values \c j to the corresponding
index in the Ipopt sparsity structure for the Jacobian of g(x).
*/
IndexMap index_jac_g_;
/*!
Mapping from (i, j) in Hessian of fg(x) to Ipopt sparsity structure
For <tt>i = 0 , ... , n_-1, index_hes_fg_[i]</tt>
is a standard map from column index values \c j to the corresponding
index in the Ipopt sparsity structure for the Hessian of the Lagragian.
*/
IndexMap index_hes_fg_;
// -----------------------------------------------------------------
// Values that are changed by routine other than the constructor:
// -----------------------------------------------------------------
/// For <tt>k = 0 , ... , K_-1, r_fun_[k]</tt>
/// is a the CppAD function object corresponding to \f$ r_k (u) \f$.
ADFunVector r_fun_;
/*!
Is r_fun[k] OK for current x.
For <tt>k = 0 , ... , K_-1, tape_ok_[k]</tt>
is true if current operations sequence in <tt>r_fun_[k]</tt>
OK for this value of \f$ x \f$.
Note that \f$ u = [ J_{k,\ell} \otimes n ] (x) \f$ may depend on the
value of \f$ \ell \f$.
*/
BoolVector tape_ok_;
/// work space of size equal maximum of <tt>q[k]</tt> w.r.t \c k.
SizeVector J_;
/// work space of size equal maximum of <tt>p[k]</tt> w.r.t \c k.
SizeVector I_;
// ------------------------------------------------------------
// Private Methods
// ------------------------------------------------------------
/// block the default constructor from use
cppad_ipopt_nlp(const cppad_ipopt_nlp&);
/// blocks the assignment operator from use
cppad_ipopt_nlp& operator=(const cppad_ipopt_nlp&);
public:
// ----------------------------------------------------------------
// See cppad_ipopt_nlp.cpp for doxygen documentation of these methods
// ----------------------------------------------------------------
/// only constructor for cppad_ipopot_nlp
cppad_ipopt_nlp(
size_t n ,
size_t m ,
const NumberVector &x_i ,
const NumberVector &x_l ,
const NumberVector &x_u ,
const NumberVector &g_l ,
const NumberVector &g_u ,
cppad_ipopt_fg_info* fg_info ,
cppad_ipopt_solution* solution
);
// use virtual so that derived class destructor gets called.
virtual ~cppad_ipopt_nlp();
// return info about the nlp
virtual bool get_nlp_info(
Index& n ,
Index& m ,
Index& nnz_jac_g ,
Index& nnz_h_lag ,
IndexStyleEnum& index_style
);
// return bounds for my problem
virtual bool get_bounds_info(
Index n ,
Number* x_l ,
Number* x_u ,
Index m ,
Number* g_l ,
Number* g_u
);
// return the starting point for the algorithm
virtual bool get_starting_point(
Index n ,
bool init_x ,
Number* x ,
bool init_z ,
Number* z_L ,
Number* z_U ,
Index m ,
bool init_lambda ,
Number* lambda
);
// return the objective value
virtual bool eval_f(
Index n ,
const Number* x ,
bool new_x ,
Number& obj_value
);
// Method to return the gradient of the objective
virtual bool eval_grad_f(
Index n ,
const Number* x ,
bool new_x ,
Number* grad_f
);
// return the constraint residuals
virtual bool eval_g(
Index n ,
const Number* x ,
bool new_x ,
Index m ,
Number* g
);
// Method to return:
// 1) The structure of the jacobian (if "values" is NULL)
// 2) The values of the jacobian (if "values" is not NULL)
virtual bool eval_jac_g(
Index n ,
const Number* x ,
bool new_x ,
Index m ,
Index nele_jac ,
Index* iRow ,
Index* jCol ,
Number* values
);
// Method to return:
// 1) structure of hessian of the lagrangian (if "values" is NULL)
// 2) values of hessian of the lagrangian (if "values" is not NULL)
virtual bool eval_h(
Index n ,
const Number* x ,
bool new_x ,
Number obj_factor ,
Index m ,
const Number* lambda ,
bool new_lambda ,
Index nele_hess ,
Index* iRow ,
Index* jCol ,
Number* values
);
// called when the algorithm is completed so the TNLP can
// store/write the solution
virtual void finalize_solution(
Ipopt::SolverReturn status ,
Index n ,
const Number* x ,
const Number* z_L ,
const Number* z_U ,
Index m ,
const Number* g ,
const Number* lambda ,
Number obj_value ,
const Ipopt::IpoptData* ip_data ,
Ipopt::IpoptCalculatedQuantities* ip_cq
);
virtual bool intermediate_callback(
Ipopt::AlgorithmMode mode,
Index iter,
Number obj_value,
Number inf_pr,
Number inf_du,
Number mu,
Number d_norm,
Number regularization_size,
Number alpha_du,
Number alpha_pr,
Index ls_trials,
const Ipopt::IpoptData* ip_data,
Ipopt::IpoptCalculatedQuantities* ip_cq
);
};
// ---------------------------------------------------------------------------
} // end namespace cppad_ipopt
// ---------------------------------------------------------------------------
# endif
| wegamekinglc/CppAD | cppad_ipopt/src/cppad_ipopt_nlp.hpp | C++ | epl-1.0 | 33,872 |
/*******************************************************************************
* Copyright (c) 2014 BSI Business Systems Integration AG.
* 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:
* BSI Business Systems Integration AG - initial API and implementation
******************************************************************************/
package org.eclipsescout.rt.ui.fx.basic.chart.factory;
import java.util.Collection;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.HPos;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.geometry.Side;
import javafx.scene.Node;
import javafx.scene.chart.Chart;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.Separator;
import javafx.scene.control.TextField;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import org.eclipse.scout.rt.shared.TEXTS;
import org.eclipsescout.rt.ui.fx.FxStyleUtility;
import org.eclipsescout.rt.ui.fx.IFxEnvironment;
import org.eclipsescout.rt.ui.fx.basic.chart.FxScoutChartRowData;
/**
*
*/
public abstract class AbstractFxScoutChartFactory implements IFxScoutChartFactory {
private Chart m_chart;
private GridPane m_controlPanel;
private int m_controlRowCount;
private ObservableList<FxScoutChartRowData> m_data;
private ObservableList<String> m_columnTitles;
private ObservableList<String> m_categoryTitles;
private IFxEnvironment m_fxEnvironment;
private ChartProperties m_chartProperties;
private boolean m_isInverse = false;
public AbstractFxScoutChartFactory(ObservableList<FxScoutChartRowData> data, Collection<String> columns, ChartProperties chartProperties, IFxEnvironment fxEnvironment) {
m_controlPanel = new GridPane();
m_data = FXCollections.observableArrayList();
m_data.addAll(data);
m_columnTitles = FXCollections.observableArrayList(columns);
m_categoryTitles = FXCollections.observableArrayList();
for (FxScoutChartRowData row : data) {
m_categoryTitles.add(row.getRowName());
}
m_chartProperties = chartProperties;
m_fxEnvironment = fxEnvironment;
}
@Override
public Chart getChart() {
return m_chart;
}
public void setChart(Chart chart) {
m_chart = chart;
}
@Override
public Pane getControlPanel() {
return m_controlPanel;
}
public ObservableList<FxScoutChartRowData> getData() {
return m_data;
}
public ObservableList<String> getColumnTitles() {
return m_columnTitles;
}
public ObservableList<String> getCategoryTitles() {
return m_categoryTitles;
}
/**
* Should be implemented by overwritten charts to build the appropriate chart.
*/
protected abstract void buildChart();
protected abstract void buildData();
@Override
public void rebuildFromData(ObservableList<FxScoutChartRowData> data, Collection<String> columnTitles) {
m_columnTitles.setAll(columnTitles);
m_data.setAll(data);
m_categoryTitles.clear();
for (FxScoutChartRowData row : data) {
m_categoryTitles.add(row.getRowName());
}
buildData();
}
/**
* Should be overwritten if additional functionality will be provided. A super call as the first operation is
* mandatory.
*/
protected void buildControlPanel() {
m_controlPanel = new GridPane();
m_controlPanel.setHgap(10);
m_controlPanel.setVgap(5);
FxStyleUtility.setPadding(m_controlPanel, 5);
ColumnConstraints c1 = new ColumnConstraints();
c1.setHalignment(HPos.RIGHT);
ColumnConstraints c2 = new ColumnConstraints();
c2.setHalignment(HPos.LEFT);
m_controlPanel.getColumnConstraints().addAll(c1, c2);
m_controlRowCount = 0;
addSeparatorElement(TEXTS.get("GeneralControls"));
// legend side
ObservableList<Side> side = FXCollections.observableArrayList(Side.values());
ChoiceBox<Side> legendSide = new ChoiceBox<Side>(side);
// legend visible
CheckBox legendVisible = new CheckBox();
// title
TextField title = new TextField(getChart().getTitle());
title.setPromptText("title");
// title side
ChoiceBox<Side> titleSide = new ChoiceBox<Side>(side);
if (getChartProperties() != null) {
getChartProperties().bindToSettings(getChartProperties().legendSideProperty, getChart().legendSideProperty(), legendSide.valueProperty());
getChartProperties().bindToSettings(getChartProperties().legendVisibleProperty, getChart().legendVisibleProperty(), legendVisible.selectedProperty());
getChartProperties().bindToSettings(getChartProperties().titleSideProperty, getChart().titleSideProperty(), titleSide.valueProperty());
getChartProperties().bindToSettings(getChartProperties().titleProperty, getChart().titleProperty(), title.textProperty());
}
else {
legendSide.setValue(getChart().getLegendSide());
getChart().legendSideProperty().bind(legendSide.valueProperty());
legendVisible.setSelected(getChart().isLegendVisible());
getChart().legendVisibleProperty().bind(legendVisible.selectedProperty());
titleSide.setValue(getChart().getTitleSide());
getChart().titleSideProperty().bind(titleSide.valueProperty());
title.setText(getChart().getTitle());
getChart().titleProperty().bind(title.textProperty());
}
addControlElement(new Label(TEXTS.get("LegendSide")), legendSide);
addControlElement(new Label(TEXTS.get("LegendVisible")), legendVisible);
addControlElement(new Label(TEXTS.get("Title")), title);
addControlElement(new Label(TEXTS.get("TitleSide")), titleSide);
}
protected void addControlElement(Node... n) {
m_controlPanel.addRow(m_controlRowCount++, n);
}
protected void addSeparatorElement(String name) {
Label label = new Label(" " + name + " ");
Separator left = new Separator(Orientation.HORIZONTAL);
HBox.setHgrow(left, Priority.ALWAYS);
Separator right = new Separator(Orientation.HORIZONTAL);
HBox.setHgrow(right, Priority.ALWAYS);
HBox separator = new HBox(left, label, right);
separator.setAlignment(Pos.CENTER);
m_controlPanel.add(separator, 0, m_controlRowCount++, 3, 1);
}
@Override
public ChartProperties getChartProperties() {
return m_chartProperties;
}
public void inverseChart() {
m_isInverse = !m_isInverse;
}
public boolean isInverse() {
return m_isInverse;
}
}
| jmini/org.eclipsescout.rt.ui.fx | org.eclipsescout.rt.ui.fx/src/org/eclipsescout/rt/ui/fx/basic/chart/factory/AbstractFxScoutChartFactory.java | Java | epl-1.0 | 6,789 |
package io.renren.common.aspect;
import com.google.gson.Gson;
import io.renren.common.annotation.SysLog;
import io.renren.common.utils.HttpContextUtils;
import io.renren.common.utils.IPUtils;
import io.renren.modules.sys.entity.SysLogEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysLogService;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
/**
* 系统日志,切面处理类
*
*/
@Aspect
@Component
public class SysLogAspect {
@Autowired
private SysLogService sysLogService;
@Pointcut("@annotation(io.renren.common.annotation.SysLog)")
public void logPointCut() {
}
@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
long beginTime = System.currentTimeMillis();
//执行方法
Object result = point.proceed();
//执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
//保存日志
saveSysLog(point, time);
return result;
}
private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
SysLogEntity sysLog = new SysLogEntity();
SysLog syslog = method.getAnnotation(SysLog.class);
if(syslog != null){
//注解上的描述
sysLog.setOperation(syslog.value());
}
//请求的方法名
String className = joinPoint.getTarget().getClass().getName();
String methodName = signature.getName();
sysLog.setMethod(className + "." + methodName + "()");
//请求的参数
Object[] args = joinPoint.getArgs();
try{
String params = new Gson().toJson(args[0]);
sysLog.setParams(params);
}catch (Exception e){
}
//获取request
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
//设置IP地址
sysLog.setIp(IPUtils.getIpAddr(request));
//用户名
String username = ((SysUserEntity) SecurityUtils.getSubject().getPrincipal()).getUsername();
sysLog.setUsername(username);
sysLog.setTime(time);
sysLog.setCreateDate(new Date());
//保存系统日志
sysLogService.save(sysLog);
}
}
| LittleNoobLol/renren-crawler | renren-crawler/src/main/java/io/renren/common/aspect/SysLogAspect.java | Java | epl-1.0 | 2,563 |
/*******************************************************************************
"FreePastry" Peer-to-Peer Application Development Substrate
Copyright 2002-2007, Rice University. Copyright 2006-2007, Max Planck Institute
for Software Systems. 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 Rice University (RICE), Max Planck Institute for Software
Systems (MPI-SWS) 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 RICE, MPI-SWS and the contributors on an "as is"
basis, without any representations or warranties of any kind, express or implied
including, but not limited to, representations or warranties of
non-infringement, merchantability or fitness for a particular purpose. In no
event shall RICE, MPI-SWS or contributors be liable for any direct, indirect,
incidental, special, exemplary, or consequential damages (including, but not
limited to, procurement of substitute goods or services; loss of use, data, or
profits; or business interruption) however caused and on any theory of
liability, whether in contract, strict liability, or tort (including negligence
or otherwise) arising in any way out of the use of this software, even if
advised of the possibility of such damage.
*******************************************************************************/
package org.mpisws.p2p.transport.util;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Map;
import org.mpisws.p2p.transport.ErrorHandler;
import org.mpisws.p2p.transport.P2PSocket;
import org.mpisws.p2p.transport.P2PSocketReceiver;
import rice.environment.logging.Logger;
/**
* Just maps a socket from one form into another.
*
* @author Jeff Hoye
*
* @param <Identifier>
* @param <SubIdentifier>
*/
public class SocketWrapperSocket<Identifier, SubIdentifier> implements P2PSocket<Identifier>, P2PSocketReceiver<SubIdentifier> {
protected Identifier identifier;
protected P2PSocket<SubIdentifier> socket;
protected Logger logger;
protected Map<String, Object> options;
// TODO: make getters
protected P2PSocketReceiver<Identifier> reader, writer;
protected ErrorHandler<Identifier> errorHandler;
public SocketWrapperSocket(Identifier identifier, P2PSocket<SubIdentifier> socket, Logger logger, ErrorHandler<Identifier> errorHandler, Map<String, Object> options) {
this.identifier = identifier;
this.socket = socket;
this.logger = logger;
this.options = options;
this.errorHandler = errorHandler;
}
@Override
public Identifier getIdentifier() {
return identifier;
}
@Override
public void close() {
if (logger.level <= Logger.FINER) {
logger.logException("Closing "+this, new Exception("Stack Trace"));
} else if (logger.level <= Logger.FINE) logger.log("Closing "+this);
socket.close();
}
@Override
public long read(ByteBuffer dsts) throws IOException {
long ret = socket.read(dsts);
if (logger.level <= Logger.FINEST) logger.log(this+"read():"+ret);
return ret;
}
@Override
public void register(boolean wantToRead, boolean wantToWrite,
final P2PSocketReceiver<Identifier> receiver) {
// logger.log(this+"register("+wantToRead+","+wantToWrite+","+receiver+")");
if (logger.level <= Logger.FINEST) logger.log(this+"register("+wantToRead+","+wantToWrite+","+receiver+")");
if (wantToRead) {
if (reader != null && reader != receiver) throw new IllegalStateException("Already registered "+reader+" for reading. Can't register "+receiver);
reader = receiver;
}
if (wantToWrite) {
if (writer != null && writer != receiver) throw new IllegalStateException("Already registered "+reader+" for writing. Can't register "+receiver);
writer = receiver;
}
socket.register(wantToRead, wantToWrite, this);
// new P2PSocketReceiver<SubIdentifier>() {
// public void receiveSelectResult(P2PSocket<SubIdentifier> socket, boolean canRead,
// boolean canWrite) throws IOException {
// if (logger.level <= Logger.FINEST) logger.log(SocketWrapperSocket.this+"rsr("+socket+","+canRead+","+canWrite+")");
// receiver.receiveSelectResult(SocketWrapperSocket.this, canRead, canWrite);
// }
//
// public void receiveException(P2PSocket<SubIdentifier> socket, IOException e) {
// receiver.receiveException(SocketWrapperSocket.this, e);
// }
//
// public String toString() {
// return SocketWrapperSocket.this+"$1";
// }
// });
}
@Override
public void receiveSelectResult(P2PSocket<SubIdentifier> socket, boolean canRead,
boolean canWrite) throws IOException {
// logger.log(this+"rsr("+socket+","+canRead+","+canWrite+")");
if (logger.level <= Logger.FINEST) logger.log(this+"rsr("+socket+","+canRead+","+canWrite+")");
if (canRead && canWrite && (reader == writer)) {
P2PSocketReceiver<Identifier> temp = reader;
reader = null;
writer = null;
temp.receiveSelectResult(this, canRead, canWrite);
return;
}
if (canRead) {
P2PSocketReceiver<Identifier> temp = reader;
if (temp== null) {
if (logger.level <= Logger.WARNING) logger.log("no reader in "+this+".rsr("+socket+","+canRead+","+canWrite+")");
} else {
reader = null;
temp.receiveSelectResult(this, true, false);
}
}
if (canWrite) {
P2PSocketReceiver<Identifier> temp = writer;
if (temp == null) {
if (logger.level <= Logger.WARNING) logger.log("no writer in "+this+".rsr("+socket+","+canRead+","+canWrite+")");
} else {
writer = null;
temp.receiveSelectResult(this, false, true);
}
}
// receiver.receiveSelectResult(SocketWrapperSocket.this, canRead, canWrite);
}
@Override
public void receiveException(P2PSocket<SubIdentifier> socket, Exception e) {
// logger.log(this+".receiveException("+e+")");
if (writer != null) {
if (writer == reader) {
P2PSocketReceiver<Identifier> temp = writer;
writer = null;
reader = null;
temp.receiveException(this, e);
} else {
P2PSocketReceiver<Identifier> temp = writer;
writer = null;
temp.receiveException(this, e);
}
}
if (reader != null) {
P2PSocketReceiver<Identifier> temp = reader;
reader = null;
temp.receiveException(this, e);
}
if (reader == null && writer == null && errorHandler != null) errorHandler.receivedException(getIdentifier(), e);
// receiver.receiveException(SocketWrapperSocket.this, e);
}
@Override
public void shutdownOutput() {
socket.shutdownOutput();
}
@Override
public long write(ByteBuffer srcs) throws IOException {
long ret = socket.write(srcs);
if (logger.level <= Logger.FINEST) logger.log(this+"write():"+ret);
return ret;
}
@Override
public String toString() {
if (getIdentifier() == socket.getIdentifier()) return socket.toString();
return identifier+"-"+socket;
}
@Override
public Map<String, Object> getOptions() {
return options;
}
}
| michele-loreti/jResp | core/org.cmg.jresp.pastry/pastry-2.1/src/org/mpisws/p2p/transport/util/SocketWrapperSocket.java | Java | epl-1.0 | 7,716 |
/**
* Copyright (c) 2007 Borland Software 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:
* bblajer - initial API and implementation
*/
package org.eclipse.gmf.runtime.gwt.ui.actions;
import java.util.List;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.commands.Command;
import org.eclipse.gmf.runtime.gwt.requests.RequestConstants;
import org.eclipse.ui.IWorkbenchPart;
/**
* Action that deletes view only for shortcuts and children of non-canonical parents,
* and both the view and the model for children of canonical parents.
*/
public class DeleteViewAction extends DeleteAction {
public DeleteViewAction(IWorkbenchPart part) {
super(part);
}
@Override
protected void init() {
super.init();
setId(ActionIds.DELETE_VIEW);
setText("Delete From Diagram");
setToolTipText("Delete From Diagram");
}
@Override
public Command createDeleteCommand(List objects) {
if (objects.isEmpty()) {
return null;
}
if (!(objects.get(0) instanceof EditPart)) {
return null;
}
return createDeleteCommand(objects, RequestConstants.REQ_DELETE_VIEW);
}
}
| ghillairet/gmf-tooling-gwt-runtime | org.eclipse.gmf.runtime.lite.gwt/src/org/eclipse/gmf/runtime/gwt/ui/actions/DeleteViewAction.java | Java | epl-1.0 | 1,327 |
package magic;
import magic.type.Intersection;
import magic.type.JavaType;
import magic.type.Union;
/**
* Abstract base class for Kiss types
*
* @author Mike
*
*/
public abstract class Type {
public static final Type[] EMPTY_TYPE_ARRAY = new Type[0];
/**
* Performs a runtime check if an object is an instance of this type
*
* @param o
* @return
*/
public abstract boolean checkInstance(Object o);
/**
* Returns the most specific Java class or interface that can represent all instances of this type
* @return
*/
public abstract Class<?> getJavaClass();
/**
* Returns true if this is a JVM primitive type
* @return
*/
public boolean isPrimitive() {
return false;
}
/**
* Return true if this type provably contains the null value
* @return
*/
public boolean canBeNull() {
return checkInstance(null);
}
/**
* Returns true if this type provably contains at least one truthy value
* @return
*/
public abstract boolean canBeTruthy();
/**
* Returns true if this type provably contains at least one falsey value
* @return
*/
public abstract boolean canBeFalsey();
/**
* Returns true if another type t is provably contained within this type.
*
* Equivalently this means:
* - t is a subtype of this type
* - every instance of t is an instance of this type
*
* If contains returns false, t may still be a subtype - it just can't be proven
*
* @param t
* @return
*/
public abstract boolean contains(Type t);
/**
* Returns the intersection of this type with another type
* @param t
* @return
*/
public Type intersection(Type t) {
return Intersection.create(this,t);
}
/**
* Returns the union of this type with another type
* @param t
* @return
*/
public Type union(Type t) {
return Union.create(this,t);
}
/**
* Returns true if this type can be proven to equal another type.
*
*/
@Override
public final boolean equals(Object o) {
if (o==this) return true;
if (!(o instanceof Type)) return false;
return equals((Type)o);
}
public boolean equals(Type t) {
return t.contains(this)&&this.contains(t);
}
public boolean equiv(Type t) {
// performance: check for immediate equality first
if (t.equals(this)) return true;
return t.contains(this)&&this.contains(t);
}
@Override
public int hashCode() {
return super.hashCode();
}
public Object cast(Object a) {
if (!checkInstance(a)) throw new ClassCastException("Can't cast value to type "+this.toString());
return a;
}
public abstract void validate();
public abstract Type inverse();
public boolean cannotBeNull() {
return !checkInstance(null);
}
public boolean cannotBeFalsey() {
return !(checkInstance(null)||checkInstance(Boolean.FALSE));
}
/**
* Returns true if the type provably cannot be a true value (i.e. must be null or Boolean.FALSE)
* @return
*/
public boolean cannotBeTruthy() {
return false;
}
@SuppressWarnings("unchecked")
public <T> JavaType<T> toJavaType() {
return (JavaType<T>) JavaType.create(this.getJavaClass());
}
/**
* Gets the return type of instances of this type
* Returns None if the Type does not represent a function
* @return
*/
public Type getReturnType() {
return Types.NONE;
}
/**
* Gets the variadic parameter type of instances of this type
* Returns None if the Type does not represent a function
* @return
*/
public Type getVariadicType() {
return Types.NONE;
}
/**
* Gets the variadic parameter type of instances of this type
* Returns None if the Type does not represent a function
* @return
*/
public Type getParamType(int i) {
return Types.NONE;
}
/**
* Returns true if this type potentially intersects another type
* @param type
* @return
*/
public boolean intersects(Type type) {
return !intersection(type).equals(Types.NONE);
}
}
| mikera/magic | src/main/java/magic/Type.java | Java | epl-1.0 | 3,891 |
/*******************************************************************************
* Copyright (c) 2011 Nokia 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:
* Comarch team - initial API and implementation
*******************************************************************************/
package org.ned.client.view.style;
public class NEDStyleToolbox {
public static final int BACKGROUND_START_COLOR = 0x9fd056;
public static final int BACKGROUND_END_COLOR = 0x69b510;
public static final int MAIN_FONT_COLOR = 0x7b7b7b;
public static final int BLUE = 0x0000FF;
public static final int MAIN_BG_COLOR = 0xe1e1e1;
public static final int DARK_GREY = 0x7b7b7b;
public static final int WHITE = 0xffffff;
public static final int TRANSPARENT = 0x0;
}
| nokiaeducationdelivery/ned-mobile-client | java/src/org/ned/client/view/style/NEDStyleToolbox.java | Java | epl-1.0 | 1,032 |
package br.com.projetoloja.uicontroller;
import br.com.projetoloja.cliente.Cliente;
import br.com.projetoloja.conta.Conta;
import br.com.projetoloja.fachada.Fachada;
import br.com.projetoloja.ui.StartApp;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import javax.swing.*;
/**
* Created by João Henrique on 18/01/2016.
*/
public class ControllerPagamentoParcela {
@FXML
private Label codBanco;
@FXML
private Label nomeBanco;
@FXML
private Label parcelaBanco;
@FXML
private Label valorBanco;
public static Cliente clienteParcela = null;
@FXML
private void initialize(){
try {
if(clienteParcela != null) {
Conta conta = Fachada.getInstance().recuperarConta(clienteParcela.getConta().getId());
codBanco.setText(String.valueOf(clienteParcela.getId()));
nomeBanco.setText(clienteParcela.getNome());
parcelaBanco.setText(String.valueOf(conta.getParcelaAtual()));
valorBanco.setText("R$: " + clienteParcela.getConta().getValorParcela());
}
} catch (Exception e) {
e.printStackTrace();
}
}
@FXML
private void cancelar() throws Exception {
clienteParcela = null;
StartApp.getInstance().telaCliente(new Stage());
StartApp.stagePagamentoParcela.close();
}
@FXML
private void finalizar(){
try {
Fachada.getInstance().pagamento(clienteParcela.getConta().getId());
if(clienteParcela.getConta().getQuantidadeParcelas() > clienteParcela.getConta().getParcelaAtual()){
JOptionPane.showMessageDialog(null,"Parcela Paga com sucesso...");
initialize();
}else{
JOptionPane.showMessageDialog(null,"Fim de conta...");
clienteParcela = null;
StartApp.getInstance().telaCliente(new Stage());
StartApp.stagePagamentoParcela.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| JoaoHenrique60/Projeto-loja | Projeto-loja/src/br/com/projetoloja/uicontroller/ControllerPagamentoParcela.java | Java | epl-1.0 | 2,282 |
package mesfavoris.java.editor;
import static mesfavoris.bookmarktype.BookmarkPropertiesProviderUtil.getSelection;
import static mesfavoris.bookmarktype.BookmarkPropertiesProviderUtil.getTextEditor;
import static mesfavoris.java.JavaBookmarkProperties.PROP_LINE_NUMBER_INSIDE_ELEMENT;
import static mesfavoris.texteditor.TextEditorBookmarkProperties.PROP_LINE_CONTENT;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.ITypeRoot;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.texteditor.ITextEditor;
import mesfavoris.java.element.JavaTypeMemberBookmarkPropertiesProvider;
import mesfavoris.texteditor.TextEditorUtils;
public class JavaEditorBookmarkPropertiesProvider extends JavaTypeMemberBookmarkPropertiesProvider {
@Override
public void addBookmarkProperties(Map<String, String> bookmarkProperties, IWorkbenchPart part, ISelection selection,
IProgressMonitor monitor) {
ITextEditor editor = getTextEditor(part);
if (editor == null) {
return;
}
if (editor != part) {
selection = getSelection(editor);
}
if (!(selection instanceof ITextSelection)) {
return;
}
ITextSelection textSelection = (ITextSelection) selection;
int lineNumber = textSelection.getStartLine();
int offset = getOffset(editor, textSelection);
IJavaElement editorJavaElement = JavaUI.getEditorInputJavaElement(editor.getEditorInput());
if (editorJavaElement == null) {
return;
}
IJavaElement containingJavaElement = getContainingJavaElement(editorJavaElement, offset);
if (!(containingJavaElement instanceof IMember)) {
return;
}
IMember member = (IMember) containingJavaElement;
super.addMemberBookmarkProperties(bookmarkProperties, member);
addLineNumberInsideMemberProperty(bookmarkProperties, member, lineNumber);
addJavadocComment(bookmarkProperties, member, lineNumber);
addLineContent(bookmarkProperties, editor, lineNumber);
}
private int getOffset(ITextEditor textEditor, ITextSelection textSelection) {
try {
int offset = TextEditorUtils.getOffsetOfFirstNonWhitespaceCharAtLine(textEditor, textSelection.getStartLine());
return offset > textSelection.getOffset() ? offset : textSelection.getOffset();
} catch (BadLocationException e) {
return textSelection.getOffset();
}
}
private void addLineNumberInsideMemberProperty(Map<String, String> bookmarkProperties, IMember member,
int lineNumber) {
try {
int methodLineNumber = JavaEditorUtils.getLineNumber(member);
int lineNumberInsideMethod = lineNumber - methodLineNumber;
putIfAbsent(bookmarkProperties, PROP_LINE_NUMBER_INSIDE_ELEMENT, Integer.toString(lineNumberInsideMethod));
} catch (JavaModelException e) {
return;
}
}
private void addJavadocComment(Map<String, String> bookmarkProperties, IMember member,
int lineNumber) {
try {
if (JavaEditorUtils.getLineNumber(member) != lineNumber) {
return;
}
super.addJavadocComment(bookmarkProperties, member);
} catch (JavaModelException e) {
return;
}
}
private IJavaElement getContainingJavaElement(IJavaElement editorJavaElement, int offset) {
if (!(editorJavaElement instanceof ITypeRoot)) {
return null;
}
ITypeRoot compilationUnit = (ITypeRoot) editorJavaElement;
try {
IJavaElement selectedJavaElement = compilationUnit.getElementAt(offset);
return selectedJavaElement;
} catch (JavaModelException e) {
return null;
}
}
private void addLineContent(Map<String, String> properties, ITextEditor textEditor, int lineNumber) {
putIfAbsent(properties, PROP_LINE_CONTENT, () -> {
String content = TextEditorUtils.getLineContent(textEditor, lineNumber);
return content == null ? null : content.trim();
});
}
}
| cchabanois/mesfavoris | bundles/mesfavoris.java/src/mesfavoris/java/editor/JavaEditorBookmarkPropertiesProvider.java | Java | epl-1.0 | 4,045 |
package com.forgeessentials.commands.item;
import java.util.ArrayList;
import java.util.List;
import com.forgeessentials.util.events.FEModuleEvent.FEModuleServerPostInitEvent;
import com.forgeessentials.util.events.FEPlayerEvent.NoPlayerInfoEvent;
import com.forgeessentials.util.questioner.Questioner;
import com.forgeessentials.util.questioner.QuestionerCallback;
import com.forgeessentials.util.questioner.QuestionerStillActiveException;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.permissions.PermissionsManager;
import net.minecraftforge.permissions.PermissionsManager.RegisteredPermValue;
import com.forgeessentials.api.APIRegistry;
import com.forgeessentials.commands.util.CommandDataManager;
import com.forgeessentials.commands.util.FEcmdModuleCommands;
import com.forgeessentials.commands.util.Kit;
import com.forgeessentials.core.misc.FECommandManager.ConfigurableCommand;
import com.forgeessentials.core.misc.TranslatedCommandException;
import com.forgeessentials.core.misc.Translator;
import com.forgeessentials.util.FunctionHelper;
import com.forgeessentials.util.OutputHandler;
/**
* Kit command with cooldown. Should also put armor in armor slots.
*
* @author Dries007
*/
public class CommandKit extends FEcmdModuleCommands implements ConfigurableCommand
{
public static final String PERM = COMMANDS_PERM + ".kit";
public static final String PERM_ADMIN = COMMANDS_PERM + ".admin";
public static final String PERM_BYPASS_COOLDOWN = PERM + ".bypasscooldown";
public static final String[] tabCompletionArg2 = new String[] { "set", "del" };
protected String kitForNewPlayers;
public CommandKit()
{
APIRegistry.getFEEventBus().register(this);
}
@Override
public String getCommandName()
{
return "kit";
}
@Override
public void processCommandPlayer(EntityPlayerMP sender, String[] args)
{
/*
* Print kits
*/
if (args.length == 0)
{
OutputHandler.chatNotification(sender, "Available kits:");
String msg = "";
for (Kit kit : CommandDataManager.kits.values())
{
if (PermissionsManager.checkPermission(sender, getPermissionNode() + "." + kit.getName()))
{
msg = kit.getName() + ", " + msg;
}
}
OutputHandler.chatNotification(sender, msg);
return;
}
/*
* Give kit
*/
if (args.length == 1)
{
if (!CommandDataManager.kits.containsKey(args[0].toLowerCase()))
throw new TranslatedCommandException("Kit %s does not exist.", args[0]);
if (!PermissionsManager.checkPermission(sender, getPermissionNode() + "." + args[0].toLowerCase()))
throw new TranslatedCommandException(
"You have insufficient permissions to do that. If you believe you received this message in error, please talk to a server admin.");
CommandDataManager.kits.get(args[0].toLowerCase()).giveKit(sender);
return;
}
/*
* Make kit
*/
if (args.length >= 2 && args[1].equalsIgnoreCase("set") && PermissionsManager.checkPermission(sender, getPermissionNode() + ".admin"))
{
if (!CommandDataManager.kits.containsKey(args[0].toLowerCase()))
{
int cooldown = -1;
if (args.length == 3)
{
cooldown = parseIntWithMin(sender, args[2], -1);
}
new Kit(sender, args[0].toLowerCase(), cooldown);
OutputHandler.chatConfirmation(sender,
Translator.format("Kit created successfully. %s cooldown.", FunctionHelper.formatDateTimeReadable(cooldown, true)));
}
else
{
try
{
Questioner.add(sender, Translator.format("Kit %s already exists. overwrite?", args[0].toLowerCase()), new HandleKitOverrides(sender, args));
}
catch (QuestionerStillActiveException e)
{
throw new QuestionerStillActiveException.CommandException();
}
}
return;
}
/*
* Delete kit
*/
if (args.length == 2 && args[1].equalsIgnoreCase("del") && PermissionsManager.checkPermission(sender, getPermissionNode() + ".admin"))
{
if (args.length == 2)
{
if (!CommandDataManager.kits.containsKey(args[0].toLowerCase()))
throw new TranslatedCommandException("Kit %s does not exist.", args[0]);
CommandDataManager.removeKit(CommandDataManager.kits.get(args[0].toLowerCase()));
OutputHandler.chatConfirmation(sender, "Kit removed.");
}
}
/*
* You're doing it wrong!
*/
throw new TranslatedCommandException(getCommandUsage(sender));
}
@Override
public boolean canConsoleUseCommand()
{
return false;
}
@Override
public void registerExtraPermissions()
{
APIRegistry.perms.registerPermission(PERM_ADMIN, RegisteredPermValue.OP);
APIRegistry.perms.registerPermission(PERM_BYPASS_COOLDOWN, RegisteredPermValue.OP);
}
@Override
public List<String> addTabCompletionOptions(ICommandSender sender, String[] args)
{
if (args.length == 0)
{
List<String> kits = new ArrayList<String>();
for (Kit kit : CommandDataManager.kits.values())
kits.add(kit.getName());
return getListOfStringsMatchingLastWord(args, kits);
}
else if (args.length == 1)
return getListOfStringsMatchingLastWord(args, tabCompletionArg2);
return null;
}
@Override
public RegisteredPermValue getDefaultPermission()
{
return RegisteredPermValue.TRUE;
}
@Override
public String getCommandUsage(ICommandSender sender)
{
return "/kit [name] OR [name] [set|del] <cooldown> Allows you to receive free kits which are pre-defined by the server owner.";
}
@Override
public void loadConfig(Configuration config, String category)
{
kitForNewPlayers = config.get(category, "kitForNewPlayers", "", "Name of kit to issue to new players. If this is left blank, it will be ignored.")
.getString();
}
@SubscribeEvent
public void checkKitExistence(FEModuleServerPostInitEvent e)
{
if (!CommandDataManager.kits.containsKey(kitForNewPlayers))
kitForNewPlayers = null;
}
@SubscribeEvent
public void issueWelcomeKit(NoPlayerInfoEvent e)
{
Kit kit = CommandDataManager.kits.get(kitForNewPlayers);
if (kit != null)
{
kit.giveKit(e.entityPlayer);
}
}
static class HandleKitOverrides implements QuestionerCallback
{
private String[] args;
private EntityPlayerMP sender;
private HandleKitOverrides(EntityPlayerMP sender, String[] args)
{
this.args = args;
this.sender = sender;
}
@Override
public void respond(Boolean response)
{
if (response != null && response == true)
{
int cooldown = -1;
if (args.length == 3)
{
cooldown = parseIntWithMin(sender, args[2], -1);
}
new Kit(sender, args[0].toLowerCase(), cooldown);
OutputHandler.chatConfirmation(sender,
Translator.format("Kit created successfully. %s cooldown.", FunctionHelper.formatDateTimeReadable(cooldown, true)));
}
}
}
}
| aschmois/ForgeEssentialsMain | src/main/java/com/forgeessentials/commands/item/CommandKit.java | Java | epl-1.0 | 8,111 |
/**
* Eclipse Public License - v 1.0
*
* THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION
* OF THE
* PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
*
* 1. DEFINITIONS
*
* "Contribution" means:
*
* a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and
* b) in the case of each subsequent Contributor:
* i) changes to the Program, and
* ii) additions to the Program;
* where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution
* 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf.
* Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program
* under their own license agreement, and (ii) are not derivative works of the Program.
* "Contributor" means any person or entity that distributes the Program.
*
* "Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone
* or when combined with the Program.
*
* "Program" means the Contributions distributed in accordance with this Agreement.
*
* "Recipient" means anyone who receives the Program under this Agreement, including all Contributors.
*
* 2. GRANT OF RIGHTS
*
* a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license
* to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor,
* if any, and such derivative works, in source code and object code form.
* b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license
* under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source
* code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the
* Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The
* patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.
* c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided
* by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor
* disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise.
* As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other
* intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the
* Program, it is Recipient's responsibility to acquire that license before distributing the Program.
* d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright
* license set forth in this Agreement.
* 3. REQUIREMENTS
*
* A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that:
*
* a) it complies with the terms and conditions of this Agreement; and
* b) its license agreement:
* i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions
* of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;
* ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and
* consequential damages, such as lost profits;
* iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and
* iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner
* on or through a medium customarily used for software exchange.
* When the Program is made available in source code form:
*
* a) it must be made available under this Agreement; and
* b) a copy of this Agreement must be included with each copy of the Program.
* Contributors may not remove or alter any copyright notices contained within the Program.
*
* Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients
* to identify the originator of the Contribution.
*
* 4. COMMERCIAL DISTRIBUTION
*
* Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this
* license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering
* should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in
* a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor
* ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions
* brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in
* connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or
* Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly
* notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the
* Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim
* at its own expense.
*
* For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial
* Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims
* and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend
* claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay
* any damages as a result, the Commercial Contributor must pay those damages.
*
* 5. NO WARRANTY
*
* EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS
* FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and
* assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program
* errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.
*
* 6. DISCLAIMER OF LIABILITY
*
* EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), 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 OR DISTRIBUTION
* OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* 7. GENERAL
*
* If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the
* remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum
* extent necessary to make such provision valid and enforceable.
*
* If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program
* itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's
* rights granted under Section 2(b) shall terminate as of the date such litigation is filed.
*
* All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this
* Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights
* under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However,
* Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.
*
* Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may
* only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this
* Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the
* initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate
* entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be
* distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is
* published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in
* Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement,
* whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved.
*
* This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to
* this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights
* to a jury trial in any resulting litigation.
*/
package com.runescape.server.revised.content.dialogue.impl;
import com.runescape.server.revised.content.dialogue.AbstractDialogue;
import com.runescape.server.revised.content.dialogue.DialogueEvent;
import com.runescape.server.revised.content.dialogue.DialogueType;
public class HansDialogue extends AbstractDialogue<DialogueType> {
@Override
public DialogueEvent executeDialogueEvent() {
return null;
}
}
| RodriguesJ/Atem | src/com/runescape/server/revised/content/dialogue/impl/HansDialogue.java | Java | epl-1.0 | 12,043 |
/*
* Copyright 2004-2009 unitarou <boss@unitarou.org>.
* All rights reserved.
*
* This program and the accompanying materials are made available under the terms of
* the Common Public License v1.0 which accompanies this distribution,
* and is available at http://opensource.org/licenses/cpl.php
*
* Contributors:
* unitarou - initial API and implementation
*/
package org.unitarou.yukinoshita.model.cmd;
import org.unitarou.lang.ArgumentChecker;
import org.unitarou.lang.Strings;
import org.unitarou.sgf.CardinalityType;
import org.unitarou.sgf.Property;
import org.unitarou.sgf.SgfId;
import org.unitarou.yukinoshita.model.NodeView;
/**
* @author unitarou <boss@unitarou.org>
*/
public class CommandFactory {
/**
* {@link UpdateProperty}ð쬵ÄԵܷB<br>
* ±±ÅnewDatumªóÌêÍnodeView©çsgfTypeðí·éR}hÉÈèÜ·B<br>
* ܽnodeViewÌlÆnewDatumÉ·ª³¢êÍnullðԵܷB
*
* @param newDatum {@link Property#Property(SgfId, String)}ɼÚn³êé¶ñAó¶ÌêÍíðÓ¡µÜ·B
* <b>GXP[vÍÖ~Å·B</b>
* @param sgfId XVÎÛÆÈévpeBÌ^
* @param nodeView
* @param bindSameType trueÉÝè·éÆ{@link SgfId#propertyType()}ðÂNodeÜÅkÁÄA
* (øÌnodeViewÅÍÈ)»Ìm[hðXVµÜ·B
* @return 쬳ê½vpeBBNOT NULL
* @throws org.unitarou.lang.NullArgumentException øª<code>null</code>ÌêB
* @throws IllegalArgumentException sgfType ª{@link CardinalityType#SINGLE}ÈOÌlðÂB
*/
static public UpdateProperty createUpdateProperty(
String newDatum, SgfId sgfId, NodeView nodeView, boolean bindSameType)
{
ArgumentChecker.throwIfNull(newDatum, sgfId, nodeView);
if (!sgfId.cardinalityType().equals(CardinalityType.SINGLE)) {
throw new IllegalArgumentException("Bad carinality, property must be single: " + sgfId); //$NON-NLS-1$
}
Property property = bindSameType
? nodeView.findProperty(sgfId)
: nodeView.getProperty(sgfId);
String lastDatum = Strings.EMPTY;
if (property != null) {
lastDatum = property.getString();
}
if (newDatum.equals(lastDatum)) {
return null;
}
if (newDatum.equals(Strings.EMPTY)) { // í
// øÅGameInfoª éã¬ÌNodeÉXV·éæ¤Éwè
property = new Property(sgfId, lastDatum);
return new UpdateProperty(
(bindSameType) ? sgfId.propertyType() : null,
null,
property);
}
// øÅGameInfoª éã¬ÌNodeÉXV·éæ¤Éwè
property = new Property(sgfId, newDatum);
return new UpdateProperty(
(bindSameType) ? sgfId.propertyType() : null,
property);
}
/**
*
*/
protected CommandFactory() {
super();
}
}
| comutt/yukinoshita2 | src/org/unitarou/yukinoshita/model/cmd/CommandFactory.java | Java | epl-1.0 | 2,978 |
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) braces deadcode
package net.minecraft.src;
import java.util.*;
// Referenced classes of package net.minecraft.src:
// Slot, ItemStack, ICrafting, EntityPlayer,
// InventoryPlayer, IInventory
public abstract class Container
{
public Container()
{
field_20123_d = new ArrayList();
slots = new ArrayList();
windowId = 0;
field_20917_a = 0;
field_20121_g = new ArrayList();
field_20918_b = new HashSet();
}
protected void addSlot(Slot slot)
{
slot.slotNumber = slots.size();
slots.add(slot);
field_20123_d.add(null);
}
public void updateCraftingResults()
{
for(int i = 0; i < slots.size(); i++)
{
ItemStack itemstack = ((Slot)slots.get(i)).getStack();
ItemStack itemstack1 = (ItemStack)field_20123_d.get(i);
if(ItemStack.areItemStacksEqual(itemstack1, itemstack))
{
continue;
}
itemstack1 = itemstack != null ? itemstack.copy() : null;
field_20123_d.set(i, itemstack1);
for(int j = 0; j < field_20121_g.size(); j++)
{
((ICrafting)field_20121_g.get(j)).func_20159_a(this, i, itemstack1);
}
}
}
public Slot getSlot(int i)
{
return (Slot)slots.get(i);
}
public ItemStack getStackInSlot(int i)
{
Slot slot = (Slot)slots.get(i);
if(slot != null)
{
return slot.getStack();
} else
{
return null;
}
}
public ItemStack func_27280_a(int i, int j, boolean flag, EntityPlayer entityplayer)
{
ItemStack itemstack = null;
if(j == 0 || j == 1)
{
InventoryPlayer inventoryplayer = entityplayer.inventory;
if(i == -999)
{
if(inventoryplayer.getItemStack() != null && i == -999)
{
if(j == 0)
{
entityplayer.dropPlayerItem(inventoryplayer.getItemStack());
inventoryplayer.setItemStack(null);
}
if(j == 1)
{
entityplayer.dropPlayerItem(inventoryplayer.getItemStack().splitStack(1));
if(inventoryplayer.getItemStack().stackSize == 0)
{
inventoryplayer.setItemStack(null);
}
}
}
} else
if(flag)
{
ItemStack itemstack1 = getStackInSlot(i);
if(itemstack1 != null)
{
int k = itemstack1.stackSize;
itemstack = itemstack1.copy();
Slot slot1 = (Slot)slots.get(i);
if(slot1 != null && slot1.getStack() != null)
{
int l = slot1.getStack().stackSize;
if(l < k)
{
func_27280_a(i, j, flag, entityplayer);
}
}
}
} else
{
Slot slot = (Slot)slots.get(i);
if(slot != null)
{
slot.onSlotChanged();
ItemStack itemstack2 = slot.getStack();
ItemStack itemstack3 = inventoryplayer.getItemStack();
if(itemstack2 != null)
{
itemstack = itemstack2.copy();
}
if(itemstack2 == null)
{
if(itemstack3 != null && slot.isItemValid(itemstack3))
{
int i1 = j != 0 ? 1 : itemstack3.stackSize;
if(i1 > slot.getSlotStackLimit())
{
i1 = slot.getSlotStackLimit();
}
slot.putStack(itemstack3.splitStack(i1));
if(itemstack3.stackSize == 0)
{
inventoryplayer.setItemStack(null);
}
}
} else
if(itemstack3 == null)
{
int j1 = j != 0 ? (itemstack2.stackSize + 1) / 2 : itemstack2.stackSize;
ItemStack itemstack5 = slot.decrStackSize(j1);
inventoryplayer.setItemStack(itemstack5);
if(itemstack2.stackSize == 0)
{
slot.putStack(null);
}
slot.onPickupFromSlot(inventoryplayer.getItemStack());
} else
if(slot.isItemValid(itemstack3))
{
if(itemstack2.itemID != itemstack3.itemID || itemstack2.getHasSubtypes() && itemstack2.getItemDamage() != itemstack3.getItemDamage())
{
if(itemstack3.stackSize <= slot.getSlotStackLimit())
{
ItemStack itemstack4 = itemstack2;
slot.putStack(itemstack3);
inventoryplayer.setItemStack(itemstack4);
}
} else
{
int k1 = j != 0 ? 1 : itemstack3.stackSize;
if(k1 > slot.getSlotStackLimit() - itemstack2.stackSize)
{
k1 = slot.getSlotStackLimit() - itemstack2.stackSize;
}
if(k1 > itemstack3.getMaxStackSize() - itemstack2.stackSize)
{
k1 = itemstack3.getMaxStackSize() - itemstack2.stackSize;
}
itemstack3.splitStack(k1);
if(itemstack3.stackSize == 0)
{
inventoryplayer.setItemStack(null);
}
itemstack2.stackSize += k1;
}
} else
if(itemstack2.itemID == itemstack3.itemID && itemstack3.getMaxStackSize() > 1 && (!itemstack2.getHasSubtypes() || itemstack2.getItemDamage() == itemstack3.getItemDamage()))
{
int l1 = itemstack2.stackSize;
if(l1 > 0 && l1 + itemstack3.stackSize <= itemstack3.getMaxStackSize())
{
itemstack3.stackSize += l1;
itemstack2.splitStack(l1);
if(itemstack2.stackSize == 0)
{
slot.putStack(null);
}
slot.onPickupFromSlot(inventoryplayer.getItemStack());
}
}
}
}
}
return itemstack;
}
public void onCraftGuiClosed(EntityPlayer entityplayer)
{
InventoryPlayer inventoryplayer = entityplayer.inventory;
if(inventoryplayer.getItemStack() != null)
{
entityplayer.dropPlayerItem(inventoryplayer.getItemStack());
inventoryplayer.setItemStack(null);
}
}
public void onCraftMatrixChanged(IInventory iinventory)
{
updateCraftingResults();
}
public void putStackInSlot(int i, ItemStack itemstack)
{
getSlot(i).putStack(itemstack);
}
public void putStacksInSlots(ItemStack aitemstack[])
{
for(int i = 0; i < aitemstack.length; i++)
{
getSlot(i).putStack(aitemstack[i]);
}
}
public void func_20112_a(int i, int j)
{
}
public short func_20111_a(InventoryPlayer inventoryplayer)
{
field_20917_a++;
return field_20917_a;
}
public void func_20113_a(short word0)
{
}
public void func_20110_b(short word0)
{
}
public abstract boolean isUsableByPlayer(EntityPlayer entityplayer);
protected void func_28125_a(ItemStack itemstack, int i, int j, boolean flag)
{
int k = i;
if(flag)
{
k = j - 1;
}
if(itemstack.isStackable())
{
while(itemstack.stackSize > 0 && (!flag && k < j || flag && k >= i))
{
Slot slot = (Slot)slots.get(k);
ItemStack itemstack1 = slot.getStack();
if(itemstack1 != null && itemstack1.itemID == itemstack.itemID && (!itemstack.getHasSubtypes() || itemstack.getItemDamage() == itemstack1.getItemDamage()))
{
int i1 = itemstack1.stackSize + itemstack.stackSize;
if(i1 <= itemstack.getMaxStackSize())
{
itemstack.stackSize = 0;
itemstack1.stackSize = i1;
slot.onSlotChanged();
} else
if(itemstack1.stackSize < itemstack.getMaxStackSize())
{
itemstack.stackSize -= itemstack.getMaxStackSize() - itemstack1.stackSize;
itemstack1.stackSize = itemstack.getMaxStackSize();
slot.onSlotChanged();
}
}
if(flag)
{
k--;
} else
{
k++;
}
}
}
if(itemstack.stackSize > 0)
{
int l;
if(flag)
{
l = j - 1;
} else
{
l = i;
}
do
{
if((flag || l >= j) && (!flag || l < i))
{
break;
}
Slot slot1 = (Slot)slots.get(l);
ItemStack itemstack2 = slot1.getStack();
if(itemstack2 == null)
{
slot1.putStack(itemstack.copy());
slot1.onSlotChanged();
itemstack.stackSize = 0;
break;
}
if(flag)
{
l--;
} else
{
l++;
}
} while(true);
}
}
public List field_20123_d;
public List slots;
public int windowId;
private short field_20917_a;
protected List field_20121_g;
private Set field_20918_b;
}
| sehrgut/minecraft-smp-mocreatures | moCreatures/client/core/sources/net/minecraft/src/Container.java | Java | epl-1.0 | 11,548 |
package org.birenheide.bf.debug.core;
import org.birenheide.bf.InterpreterState;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.model.IMemoryBlock;
public class BfMemoryBlock extends BfDebugElement implements IMemoryBlock {
private final InterpreterState state;
private final long start;
private final long length;
private boolean createdbyUser = true;
BfMemoryBlock(BfDebugTarget parent, InterpreterState state, long start, long length) {
super(parent);
this.state = state;
long st = start;
long l = length;
if (st >= state.getDataSize()) {
st = state.getDataSize();
l = 0;
}
else if (st + l > state.getDataSize()) {
l = state.getDataSize() - st;
}
this.start = st;
this.length = l;
}
public boolean isUserCreated() {
return this.createdbyUser;
}
public void setUserCreated(boolean isUserCreated) {
this.createdbyUser = isUserCreated;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (this.createdbyUser ? 1231 : 1237);
result = prime * result + (int) (this.length ^ (this.length >>> 32));
result = prime * result + (int) (this.start ^ (this.start >>> 32));
result = prime * result + this.getDebugTarget().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;
}
BfMemoryBlock other = (BfMemoryBlock) obj;
if (!this.getDebugTarget().equals(other.getDebugTarget())) {
return false;
}
if (this.createdbyUser != other.createdbyUser) {
return false;
}
if (this.length != other.length) {
return false;
}
if (this.start != other.start) {
return false;
}
return true;
}
@Override
public long getStartAddress() {
return this.start;
}
public int getMemoryPointer() {
return this.getDebugTarget().getProcess().getProcessListener().getSuspendedState().dataPointer();
}
@Override
public long getLength() {
return this.length;
}
@Override
public byte[] getBytes() throws DebugException {
return this.state.dataSnapShot((int) this.start, (int) (this.start + this.length));
}
@Override
public boolean supportsValueModification() {
return false;
}
@Override
public void setValue(long offset, byte[] bytes) throws DebugException {
}
} | RichardBirenheide/brainfuck | org.birenheide.bf.debug/src/org/birenheide/bf/debug/core/BfMemoryBlock.java | Java | epl-1.0 | 2,404 |
/**
* Copyright (c) 2015 FENECON GmbH & Co. KG.
* 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
*/
package org.openhab.binding.fems.internal.types;
import org.bulldog.core.gpio.DigitalInput;
import org.eclipse.smarthome.core.library.types.OpenClosedType;
import org.eclipse.smarthome.core.types.State;
/**
*
* @author Stefan Feilmeier
*/
public class IODigitalInput implements IO {
private DigitalInput pin;
public IODigitalInput(DigitalInput pin) {
this.pin = pin;
pin.setTeardownOnShutdown(true);
}
@Override
public State getState() {
if (pin.read().getBooleanValue()) {
return OpenClosedType.OPEN;
} else {
return OpenClosedType.CLOSED;
}
}
@Override
public void dispose() {
// nothing to do here
}
}
| fenecon/fenecon-openhab | addons/binding/org.openhab.binding.fems/src/main/java/org/openhab/binding/fems/internal/types/IODigitalInput.java | Java | epl-1.0 | 1,021 |
package com.odcgroup.page.ui.edit;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.DragTracker;
import org.eclipse.gef.Request;
import org.eclipse.gef.requests.SelectionRequest;
import com.odcgroup.page.ui.figure.scroll.ScrollableWidgetFigure;
import com.odcgroup.page.ui.figure.scroll.XScrollBar;
import com.odcgroup.page.ui.figure.scroll.XScrollBarDragTracker;
import com.odcgroup.page.ui.figure.scroll.YScrollBar;
import com.odcgroup.page.ui.figure.scroll.YScrollBarDragTracker;
/**
* An EditPart for Widgets which are not the root element of the diagram and contain ScrollBars.
* Note that we assume that the different containers use local coordinates.
*
* @author Gary Hayes
*/
public class ScrollableWidgetEditPart extends WidgetEditPart {
/**
* Overrides the base-class version to determine if we are selecting the Figure or the ScrollBar associated with it.
*
* @param request
* The request
* @return DragTracker The DragTracker
*/
public DragTracker getDragTracker(Request request) {
SelectionRequest sr = (SelectionRequest) request;
Point mp = sr.getLocation();
ScrollableWidgetFigure swf = (ScrollableWidgetFigure) getFigure();
if (hasClickedXThumb(swf, mp)) {
return new XScrollBarDragTracker(swf);
}
if (hasClickedYThumb(swf, mp)) {
return new YScrollBarDragTracker(swf);
}
return super.getDragTracker(request);
}
/**
* Returns true if the mouse was clicked over the X-ScrollBar's thumb.
*
* @param scrollableFigure The ScrollableWidgetFigure
* @param p The Point to test
* @return boolean True if the mouse was clicked over the X-ScrollBar's thumb
*/
private boolean hasClickedXThumb(ScrollableWidgetFigure scrollableFigure, Point p) {
XScrollBar xsb = scrollableFigure.getXScrollBar();
if (xsb == null) {
// No ScrollBar. The result is obviously false
return false;
}
return contains(scrollableFigure, xsb.getThumb().getBounds(), p);
}
/**
* Returns true if the mouse was clicked over the Y-ScrollBar's thumb.
*
* @param scrollableFigure The ScrollableWidgetFigure
* @param p The Point to test
* @return boolean True if the mouse was clicked over the Y-ScrollBar's thumb
*/
private boolean hasClickedYThumb(ScrollableWidgetFigure scrollableFigure, Point p) {
YScrollBar ysb = scrollableFigure.getYScrollBar();
if (ysb == null) {
// No ScrollBar. The result is obviously false
return false;
}
return contains(scrollableFigure, ysb.getThumb().getBounds(), p);
}
/**
* Returns true if the Rectanglwe contains the Point. This test
* is relative to the figure passed as an argument. The Rectangle
* is displaced relative to the absolute position of the Figure
* before performing the test.
*
* @param scrollableFigure The figure
* @param r The Rectangle
* @param p The Point to test
* @return boolean True if the Rectangle contains the Point
*/
private boolean contains(ScrollableWidgetFigure scrollableFigure, Rectangle r, Point p) {
Rectangle sb = r.getCopy();
Point sp = translatePointToAbsolute(scrollableFigure);
sb.x = sb.x + sp.x;
sb.y = sb.y + sp.y;
if (sb.contains(p)) {
return true;
}
return false;
}
/**
* Translates the point to absolute coordinates.
* Note that we assume that each container is using
* local coordinates.
*
* @param figure The figure containing the Point
* @return Point The translated Point
*/
private Point translatePointToAbsolute(IFigure figure) {
int x = 0;
int y = 0;
IFigure f = figure;
while (f.getParent() != null) {
Rectangle fb = f.getBounds();
x = x + fb.x;
y = y + fb.y;
f = f.getParent();
}
return new Point(x, y);
}
} | debabratahazra/DS | designstudio/components/page/ui/com.odcgroup.page.ui/src/main/java/com/odcgroup/page/ui/edit/ScrollableWidgetEditPart.java | Java | epl-1.0 | 3,822 |
/*******************************************************************************
* Copyright (c) 2004, 2005 IBM Corporation and others.
* 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:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.html.core.internal.contentmodel.chtml;
import java.util.Arrays;
import org.eclipse.wst.xml.core.internal.contentmodel.CMAttributeDeclaration;
import org.eclipse.wst.xml.core.internal.contentmodel.CMDataType;
import org.eclipse.wst.xml.core.internal.contentmodel.CMNamedNodeMap;
/**
* IMG.
*/
final class HedIMG extends HedEmpty {
/**
*/
public HedIMG(ElementCollection collection) {
super(CHTMLNamespace.ElementName.IMG, collection);
layoutType = LAYOUT_OBJECT;
}
/**
* IMG.
* %attrs;
* (src %URI; #REQUIRED): should be defined locally.
* (alt %Text; #REQUIRED)
* (longdesc %URI; #IMPLIED)
* (name CDATA #IMPLIED)
* (height %Length; #IMPLIED)
* (width %Length; #IMPLIED)
* (usemap %URI; #IMPLIED)
* (ismap (ismap) #IMPLIED)
* (align %IAlign; #IMPLIED): should be defined locally.
* (border %Pixels; #IMPLIED)
* (hspace %Pixels; #IMPLIED)
* (vspace %Pixels; #IMPLIED)
* (mapfile %URI; #IMPLIED)
*/
protected void createAttributeDeclarations() {
if (attributes != null)
return; // already created.
if (attributeCollection == null)
return; // fatal
attributes = new CMNamedNodeMapImpl();
// %attrs;
attributeCollection.getAttrs(attributes);
// (src %URI; #REQUIRED): should be defined locally.
HTMLCMDataTypeImpl atype = null;
HTMLAttrDeclImpl attr = null;
atype = new HTMLCMDataTypeImpl(CMDataType.URI);
attr = new HTMLAttrDeclImpl(CHTMLNamespace.ATTR_NAME_SRC, atype, CMAttributeDeclaration.REQUIRED);
attributes.putNamedItem(CHTMLNamespace.ATTR_NAME_SRC, attr);
String[] names = {CHTMLNamespace.ATTR_NAME_ALT, CHTMLNamespace.ATTR_NAME_NAME, CHTMLNamespace.ATTR_NAME_HEIGHT, CHTMLNamespace.ATTR_NAME_WIDTH, CHTMLNamespace.ATTR_NAME_BORDER, CHTMLNamespace.ATTR_NAME_HSPACE, CHTMLNamespace.ATTR_NAME_VSPACE,};
attributeCollection.getDeclarations(attributes, Arrays.asList(names).iterator());
// align (local); should be defined locally.
attr = AttributeCollection.createAlignForImage();
attributes.putNamedItem(CHTMLNamespace.ATTR_NAME_ALIGN, attr);
}
/**
*/
public CMNamedNodeMap getProhibitedAncestors() {
if (prohibitedAncestors != null)
return prohibitedAncestors;
String[] names = {CHTMLNamespace.ElementName.PRE};
prohibitedAncestors = elementCollection.getDeclarations(names);
return prohibitedAncestors;
}
}
| ttimbul/eclipse.wst | bundles/org.eclipse.wst.html.core/src/org/eclipse/wst/html/core/internal/contentmodel/chtml/HedIMG.java | Java | epl-1.0 | 2,893 |
package gov.nih.nlm.uts.webservice.metadata;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for getAllSourceRelationLabels complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="getAllSourceRelationLabels">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ticket" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="version" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "getAllSourceRelationLabels", propOrder = {
"ticket",
"version"
})
public class GetAllSourceRelationLabels {
protected String ticket;
protected String version;
/**
* Gets the value of the ticket property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTicket() {
return ticket;
}
/**
* Sets the value of the ticket property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTicket(String value) {
this.ticket = value;
}
/**
* Gets the value of the version property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVersion() {
return version;
}
/**
* Sets the value of the version property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVersion(String value) {
this.version = value;
}
}
| dkincaid/clumcl | src/generated/java/gov/nih/nlm/uts/webservice/metadata/GetAllSourceRelationLabels.java | Java | epl-1.0 | 2,008 |
# vi: ts=4 expandtab syntax=python
##############################################################################
# Copyright (c) 2008 IBM 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:
# Dave Leskovec (IBM) - initial implementation
##############################################################################
"""
This module contains functions dealing with platform information.
"""
import OvfLibvirt
from locale import getlocale, getdefaultlocale
from time import timezone
def virtTypeIsAvailable(virtType):
"""
Check if the given virt type is available on this system
@type node: String
@param node: Platform type to check
@rtype: Boolean
@return: Indication if type is available or not
"""
if virtType:
return True
return False
def getVsSystemType(vs):
"""
This function gets the list of system types for the virtual system and
selects one based on the libvirt capabilities. It will select the
first type in the list that is present on the system.
@type node: DOM node
@param node: Virtual System node
@rtype: String
@return: Platform type for Virtual System
"""
virtTypes = OvfLibvirt.getOvfSystemType(vs)
for virtType in virtTypes:
# check if this virtType is available
if virtTypeIsAvailable(virtType):
return virtType
return None
def getPlatformDict(vs, virtPlatform=None):
"""
Get the platform information
@type node: DOM node
@param node: Virtual System node
@type virtPlatform: String
@param node: Virtual Platform type. If None, will be taken from vs
@rtype: String
@return: Dictionary containing platform information for the virtual
system the contents are defined by the ovf specification for
the environment.
"""
retDict = {}
if not virtPlatform:
virtPlatform = getVsSystemType(vs)
retDict['Kind'] = virtPlatform
# We could possibly look up the version and vendor here
# gather the details of the platform
(langCode, encoding) = getlocale()
if langCode == None:
(langCode, encoding) = getdefaultlocale()
retDict['Locale'] = langCode
retDict['Timezone'] = timezone
return retDict
| Awingu/open-ovf | py/ovf/OvfPlatform.py | Python | epl-1.0 | 2,476 |
/*******************************************************************************
* Copyright (c) 2005, 2006 IBM Corporation and others.
* 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:
* IBM Corporation - initial API and implementation
*
*******************************************************************************/
package org.eclipse.wst.xsd.ui.internal.refactor;
public interface IReferenceUpdating {
/**
* Checks if this refactoring object is capable of updating references to the renamed element.
*/
public boolean canEnableUpdateReferences();
/**
* If <code>canUpdateReferences</code> returns <code>true</code>, then this method is used to
* inform the refactoring object whether references should be updated.
* This call can be ignored if <code>canUpdateReferences</code> returns <code>false</code>.
*/
public void setUpdateReferences(boolean update);
/**
* If <code>canUpdateReferences</code> returns <code>true</code>, then this method is used to
* ask the refactoring object whether references should be updated.
* This call can be ignored if <code>canUpdateReferences</code> returns <code>false</code>.
*/
public boolean getUpdateReferences();
} | ttimbul/eclipse.wst | bundles/org.eclipse.wst.xsd.ui/src-refactor/org/eclipse/wst/xsd/ui/internal/refactor/IReferenceUpdating.java | Java | epl-1.0 | 1,426 |
/*
* Copyright 2012 PRODYNA AG
*
* Licensed under the Eclipse Public License (EPL), Version 1.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.opensource.org/licenses/eclipse-1.0.php or
* http://www.nabucco.org/License.html
*
* 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.nabucco.framework.generator.compiler.transformation.java.view;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration;
import org.eclipse.jdt.internal.compiler.ast.ImportReference;
import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration;
import org.eclipse.jdt.internal.compiler.ast.QualifiedNameReference;
import org.eclipse.jdt.internal.compiler.ast.ReturnStatement;
import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
import org.nabucco.framework.generator.compiler.constants.NabuccoJavaTemplateConstants;
import org.nabucco.framework.generator.compiler.transformation.common.annotation.NabuccoAnnotation;
import org.nabucco.framework.generator.compiler.transformation.common.annotation.NabuccoAnnotationMapper;
import org.nabucco.framework.generator.compiler.transformation.common.annotation.NabuccoAnnotationType;
import org.nabucco.framework.generator.compiler.transformation.java.common.ast.container.JavaAstContainter;
import org.nabucco.framework.generator.compiler.transformation.java.common.ast.container.JavaAstType;
import org.nabucco.framework.generator.compiler.transformation.java.constants.ViewConstants;
import org.nabucco.framework.generator.compiler.transformation.java.visitor.NabuccoToJavaVisitorContext;
import org.nabucco.framework.generator.compiler.transformation.util.NabuccoTransformationUtility;
import org.nabucco.framework.generator.compiler.visitor.NabuccoVisitorException;
import org.nabucco.framework.generator.parser.syntaxtree.AnnotationDeclaration;
import org.nabucco.framework.generator.parser.syntaxtree.SearchViewStatement;
import org.nabucco.framework.mda.logger.MdaLogger;
import org.nabucco.framework.mda.logger.MdaLoggingFactory;
import org.nabucco.framework.mda.model.java.JavaModelException;
import org.nabucco.framework.mda.model.java.ast.element.JavaAstElementFactory;
import org.nabucco.framework.mda.model.java.ast.element.discriminator.LiteralType;
import org.nabucco.framework.mda.model.java.ast.element.method.JavaAstMethodSignature;
import org.nabucco.framework.mda.model.java.ast.produce.JavaAstModelProducer;
/**
* NabuccoToJavaRcpViewVisitorSupportUtil
*
* @author Silas Schwarz PRODYNA AG
*/
public final class NabuccoToJavaRcpViewVisitorSupportUtil implements ViewConstants {
private static MdaLogger logger = MdaLoggingFactory.getInstance().getLogger(
NabuccoToJavaRcpViewVisitorSupportUtil.class);
private NabuccoToJavaRcpViewVisitorSupportUtil() {
}
public static final ImportReference getModelTypeImport(NabuccoToJavaVisitorContext visitorContext,
SearchViewStatement searchViewStatement) throws JavaModelException {
String pkg = visitorContext.getPackage().replace(UI, UI_RCP) + PKG_SEPARATOR + MODEL_PACKAGE;
String name = searchViewStatement.nodeToken2.tokenImage.replace(NabuccoJavaTemplateConstants.VIEW,
NabuccoJavaTemplateConstants.MODEL);
return JavaAstModelProducer.getInstance().createImportReference(pkg + PKG_SEPARATOR + name);
}
/**
* Swaps the field order so that the title field is defined after the id field since it depends
* on it
*
*/
public static void swapFieldOrder(TypeDeclaration type) {
int idPos = -1;
for (int i = 0; i < type.fields.length; i++) {
if (Arrays.equals(type.fields[i].name, ID.toCharArray())) {
idPos = i;
}
}
if (idPos != 0) {
FieldDeclaration currentFirst = type.fields[0];
type.fields[0] = type.fields[idPos];
type.fields[idPos] = currentFirst;
}
}
public static List<JavaAstContainter<? extends ASTNode>> getUiCommonElements(TypeDeclaration uIType,
TypeDeclaration type, AnnotationDeclaration annotations) throws JavaModelException {
List<JavaAstContainter<? extends ASTNode>> result = new ArrayList<JavaAstContainter<? extends ASTNode>>();
NabuccoAnnotation elementId = NabuccoAnnotationMapper.getInstance().mapToAnnotation(annotations,
NabuccoAnnotationType.CLIENT_ELEMENT_ID);
// Add the static final id field if we find a Id client element
// annotation (@id)
if (elementId != null && elementId.getValue() != null && !elementId.getValue().isEmpty()) {
JavaAstElementFactory javaFactory = JavaAstElementFactory.getInstance();
// create static field id
FieldDeclaration fieldID = javaFactory.getJavaAstType().getField(uIType, ID);
fieldID.initialization = JavaAstModelProducer.getInstance().createLiteral(elementId.getValue(),
LiteralType.STRING_LITERAL);
JavaAstContainter<FieldDeclaration> fieldContainer = new JavaAstContainter<FieldDeclaration>(fieldID,
JavaAstType.FIELD);
result.add(fieldContainer);
// select the method "getId()"
JavaAstMethodSignature signature = new JavaAstMethodSignature(GET_ID);
MethodDeclaration getIdMethod = (MethodDeclaration) javaFactory.getJavaAstType().getMethod(uIType,
signature);
JavaAstContainter<MethodDeclaration> methodContainer = new JavaAstContainter<MethodDeclaration>(
getIdMethod, JavaAstType.METHOD);
// set the returnStatement
((QualifiedNameReference) ((ReturnStatement) getIdMethod.statements[0]).expression).tokens[0] = type.name;
result.add(methodContainer);
} else {
logger.warning("@Id annotation is missing or could not be analized");
}
return result;
}
public static JavaAstContainter<FieldDeclaration> createStaticFinalField(String mappedFieldName)
throws JavaModelException {
JavaAstElementFactory javaFactory = JavaAstElementFactory.getInstance();
String mappedField = PROPERTY + UNDERSCORE + mappedFieldName.toUpperCase().replace(PKG_SEPARATOR, UNDERSCORE);
FieldDeclaration resultingField = JavaAstModelProducer.getInstance().createFieldDeclaration(mappedField);
javaFactory.getJavaAstField().setFieldType(resultingField,
JavaAstModelProducer.getInstance().createTypeReference(STRING, false));
String[] mappedFieldInit = mappedFieldName.split(FIELD_SEPARATOR);
// only if mapped field is a Basetype or Enumeration
if (mappedFieldName.split(FIELD_SEPARATOR).length <= 2) {
resultingField.initialization = JavaAstModelProducer.getInstance().createLiteral(
mappedFieldInit[0] + NabuccoTransformationUtility.firstToUpper(mappedFieldInit[1]),
LiteralType.STRING_LITERAL);
} else {
resultingField.initialization = JavaAstModelProducer.getInstance()
.createLiteral(
mappedFieldInit[0]
+ NabuccoTransformationUtility.firstToUpper(mappedFieldInit[1])
+ NabuccoTransformationUtility.firstToUpper(mappedFieldInit[2]),
LiteralType.STRING_LITERAL);
}
// make static final
javaFactory.getJavaAstField().addModifier(resultingField,
ClassFileConstants.AccStatic | ClassFileConstants.AccFinal);
// remove private
javaFactory.getJavaAstField().removeModifier(resultingField, ClassFileConstants.AccPrivate);
// add public
javaFactory.getJavaAstField().addModifier(resultingField, ClassFileConstants.AccPublic);
JavaAstContainter<FieldDeclaration> result = new JavaAstContainter<FieldDeclaration>(resultingField,
JavaAstType.FIELD);
return result;
}
public static JavaAstContainter<FieldDeclaration> createConstant(String name, String value) {
try {
name = name.toUpperCase();
JavaAstModelProducer producer = JavaAstModelProducer.getInstance();
int modifier = ClassFileConstants.AccStatic | ClassFileConstants.AccFinal | ClassFileConstants.AccPublic;
FieldDeclaration constant = producer.createFieldDeclaration(name, modifier);
constant.type = producer.createTypeReference(STRING, false);
constant.initialization = producer.createLiteral(value, LiteralType.STRING_LITERAL);
return new JavaAstContainter<FieldDeclaration>(constant, JavaAstType.FIELD);
} catch (JavaModelException e) {
throw new NabuccoVisitorException("Cannot create constant [" + name + "].", e);
}
}
}
| NABUCCO/org.nabucco.framework.generator | org.nabucco.framework.generator.compiler/src/main/org/nabucco/framework/generator/compiler/transformation/java/view/NabuccoToJavaRcpViewVisitorSupportUtil.java | Java | epl-1.0 | 9,473 |
<?php
/* Member Page */
/* Include Class */
include("class/database.class.php");
include("class/member.class.php");
include("include/hash.inc.php");
/* Start an instance of the Database Class */
$database = new database("127.0.0.1", "cryptbin", "root", "root");
/* Create an instance of the Member Class */
$member = new member();
?> | DrWhatNoName/cryptbin | src/include/member.inc.php | PHP | epl-1.0 | 333 |
package com.ge.research.sadl.ui.preferences;
import org.eclipse.jface.preference.BooleanFieldEditor;
import org.eclipse.jface.preference.RadioGroupFieldEditor;
import org.eclipse.jface.preference.StringFieldEditor;
import org.eclipse.xtext.ui.editor.preferences.LanguageRootPreferencePage;
import org.eclipse.xtext.ui.editor.preferences.fields.LabelFieldEditor;
import com.ge.research.sadl.preferences.SadlPreferences;
public class SadlRootPreferencePage extends LanguageRootPreferencePage {
@SuppressWarnings("restriction")
@Override
protected void createFieldEditors() {
addField(new LabelFieldEditor("General SADL Settings", getFieldEditorParent()));
addField(new StringFieldEditor(SadlPreferences.SADL_BASE_URI.getId(), "Base URI", getFieldEditorParent()));
addField(new RadioGroupFieldEditor("OWL_Format", "Saved OWL model format :", 5,
new String[][] {
{SadlPreferences.RDF_XML_ABBREV_FORMAT.getId(), SadlPreferences.RDF_XML_ABBREV_FORMAT.getId()},
{SadlPreferences.RDF_XML_FORMAT.getId(), SadlPreferences.RDF_XML_FORMAT.getId()},
{SadlPreferences.N3_FORMAT.getId(), SadlPreferences.N3_FORMAT.getId()},
{SadlPreferences.N_TRIPLE_FORMAT.getId(), SadlPreferences.N_TRIPLE_FORMAT.getId()},
{SadlPreferences.JENA_TDB.getId(), SadlPreferences.JENA_TDB.getId()},
},
getFieldEditorParent()));
addField(new RadioGroupFieldEditor("importBy", "Show import model list as:", 2,
new String[][] {{"Model Namespaces", SadlPreferences.MODEL_NAMESPACES.getId()}, {"SADL File Names", SadlPreferences.SADL_FILE_NAMES.getId()}}, getFieldEditorParent()));
addField(new BooleanFieldEditor(SadlPreferences.PREFIXES_ONLY_AS_NEEDED.getId(), "Show prefixes for imported concepts only when needed for disambiguation", getFieldEditorParent()));
addField(new BooleanFieldEditor(SadlPreferences.VALIDATE_BEFORE_TEST.getId(), "Validate before Testing", getFieldEditorParent()));
addField(new BooleanFieldEditor(SadlPreferences.NAMESPACE_IN_QUERY_RESULTS.getId(), "Show Namespaces in Query Results", getFieldEditorParent()));
addField(new BooleanFieldEditor(SadlPreferences.SHOW_TIMING_INFORMATION.getId(), "Show Timing Informaton (Build, Reasoning)", getFieldEditorParent()));
addField(new RadioGroupFieldEditor("dmyOrder", "Interpret Date 10/11/2012 as:", 2,
new String[][] {{"MM/DD/YYYY", SadlPreferences.DMY_ORDER_MDY.getId()},
{"DD/MM/YYYY", SadlPreferences.DMY_ORDER_DMY.getId()}}, getFieldEditorParent()));
addField(new BooleanFieldEditor(SadlPreferences.DEEP_VALIDATION_OFF.getId(), "Disable Deep Validation of Model", getFieldEditorParent()));
addField(new StringFieldEditor(SadlPreferences.GRAPH_VIZ_PATH.getId(), "GraphViz bin folder", getFieldEditorParent()));
}
}
| brfeddersen/sadlos2 | sadl3/com.ge.research.sadl.parent/com.ge.research.sadl.ui/src/com/ge/research/sadl/ui/preferences/SadlRootPreferencePage.java | Java | epl-1.0 | 2,875 |
package edu.rice.habanero.benchmarks.knapsack;
import edu.rice.habanero.benchmarks.BenchmarkRunner;
import edu.rice.habanero.concurrent.executors.GenericTaskExecutor;
import edu.rice.habanero.concurrent.executors.TaskExecutor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu)
*/
public class ThreadPoolBenchmark extends AbstractBenchmark {
public static void main(final String[] args) {
BenchmarkRunner.runBenchmark(args, new ThreadPoolBenchmark());
}
@Override
protected TaskExecutor createTaskExecutor() {
final ExecutorService executorService = Executors.newFixedThreadPool(BenchmarkRunner.numThreads());
final int minPriorityInc = BenchmarkRunner.minPriority();
final int maxPriorityInc = BenchmarkRunner.maxPriority();
return new GenericTaskExecutor(minPriorityInc, maxPriorityInc, executorService);
}
}
| shamsmahmood/priorityworkstealing | src/main/java/edu/rice/habanero/benchmarks/knapsack/ThreadPoolBenchmark.java | Java | epl-1.0 | 994 |
/**
*/
package org.asup.db.server.store;
import org.eclipse.emf.ecore.EFactory;
/**
* <!-- begin-user-doc -->
* The <b>Factory</b> for the model.
* It provides a create method for each non-abstract class of the model.
* <!-- end-user-doc -->
* @see org.asup.db.server.store.QStorePackage
* @generated
*/
public interface QStoreFactory extends EFactory {
/**
* The singleton instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
QStoreFactory eINSTANCE = org.asup.db.server.store.impl.StoreFactoryImpl.init();
/**
* Returns a new object of class '<em>User</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>User</em>'.
* @generated
*/
QUser createUser();
/**
* Returns a new object of class '<em>Workstation</em>'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return a new object of class '<em>Workstation</em>'.
* @generated
*/
QWorkstation createWorkstation();
/**
* Returns the package supported by this factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the package supported by this factory.
* @generated
*/
QStorePackage getStorePackage();
} //QStoreFactory
| asupdev/asup | org.asup.db.server.test/src/org/asup/db/server/store/QStoreFactory.java | Java | epl-1.0 | 1,237 |
/**
* Copyright (c) 2014-2017 by the respective copyright holders.
* 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
*/
package org.eclipse.smarthome.core.voice.text;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.ResourceBundle;
/**
* Expression that successfully parses, if a sequence of given expressions is matching. This class is immutable.
*
* @author Tilman Kamp - Initial contribution and API
*
*/
public final class ExpressionSequence extends Expression {
private List<Expression> subExpressions;
/**
* Constructs a new instance.
*
* @param subExpressions the sub expressions that are parsed in the given order
*/
public ExpressionSequence(Expression... subExpressions) {
super();
this.subExpressions = Collections
.unmodifiableList(Arrays.asList(Arrays.copyOf(subExpressions, subExpressions.length)));
}
@Override
ASTNode parse(ResourceBundle language, TokenList tokenList) {
TokenList list = tokenList;
int l = subExpressions.size();
ASTNode node = new ASTNode(), cr;
ASTNode[] children = new ASTNode[l];
Object[] values = new Object[l];
for (int i = 0; i < l; i++) {
cr = children[i] = subExpressions.get(i).parse(language, list);
if (!cr.isSuccess()) {
return node;
}
values[i] = cr.getValue();
list = cr.getRemainingTokens();
}
node.setChildren(children);
node.setRemainingTokens(list);
node.setSuccess(true);
node.setValue(values);
generateValue(node);
return node;
}
@Override
List<Expression> getChildExpressions() {
return subExpressions;
}
@Override
boolean collectFirsts(ResourceBundle language, HashSet<String> firsts) {
boolean blocking = false;
for (Expression e : subExpressions) {
if ((blocking = e.collectFirsts(language, firsts)) == true) {
break;
}
}
return blocking;
}
@Override
public String toString() {
String s = null;
for (Expression e : subExpressions) {
s = s == null ? e.toString() : (s + ", " + e.toString());
}
return "seq(" + s + ")";
}
} | AchimHentschel/smarthome | bundles/core/org.eclipse.smarthome.core.voice/src/main/java/org/eclipse/smarthome/core/voice/text/ExpressionSequence.java | Java | epl-1.0 | 2,583 |
/*
* Sonatype Nexus (TM) Open Source Version
* Copyright (c) 2008-present Sonatype, Inc.
* All rights reserved. Includes the third-party code listed at http://links.sonatype.com/products/nexus/oss/attributions.
*
* This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0,
* which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html.
*
* Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks
* of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the
* Eclipse Foundation. All other trademarks are the property of their respective owners.
*/
package org.sonatype.nexus.orient;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import javax.inject.Provider;
import org.sonatype.goodies.common.ComponentSupport;
import org.sonatype.nexus.common.app.ApplicationDirectories;
import org.sonatype.nexus.common.upgrade.Checkpoint;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
/**
* Support for upgrade checkpoint of OrientDB databases.
*
* @since 3.1
*/
public abstract class DatabaseCheckpointSupport
extends ComponentSupport
implements Checkpoint
{
private final String databaseName;
private final Provider<DatabaseInstance> databaseInstance;
private final ApplicationDirectories appDirectories;
private File upgradeDir;
private File backupZip;
private File failedZip;
protected DatabaseCheckpointSupport(final String databaseName,
final Provider<DatabaseInstance> databaseInstance,
final ApplicationDirectories appDirectories)
{
this.databaseName = checkNotNull(databaseName);
this.databaseInstance = checkNotNull(databaseInstance);
this.appDirectories = checkNotNull(appDirectories);
}
@Override
public void begin(String version) throws Exception {
upgradeDir = appDirectories.getWorkDirectory("upgrades/" + databaseName);
String timestampSuffix = String.format("-%1$tY%1$tm%1$td-%1$tH%1$tM%1$tS", System.currentTimeMillis());
backupZip = new File(upgradeDir, databaseName + "-" + version + timestampSuffix + "-backup.zip");
failedZip = new File(upgradeDir, databaseName + "-failed.zip");
log.debug("Backing up database to {}", backupZip);
try (OutputStream out = new FileOutputStream(backupZip)) {
databaseInstance.get().externalizer().backup(out);
}
}
@Override
public void commit() throws Exception {
// no-op
}
@Override
public void rollback() throws Exception {
checkState(failedZip != null);
checkState(backupZip != null);
log.debug("Exporting failed database to {}", failedZip);
try (OutputStream out = new FileOutputStream(failedZip)) {
databaseInstance.get().externalizer().backup(out);
}
finally {
log.debug("Restoring original database from {}", backupZip);
try (InputStream in = new FileInputStream(backupZip)) {
databaseInstance.get().externalizer().restore(in, true);
}
}
}
@Override
public void end() {
checkState(upgradeDir != null);
checkState(backupZip != null);
log.debug("Deleting backup from {}", upgradeDir);
try {
Files.delete(backupZip.toPath());
Files.delete(upgradeDir.toPath());
}
catch (IOException e) { // NOSONAR
log.warn("Could not delete backup of {} database, please delete {} manually. Error: {}", databaseName, upgradeDir,
e.toString());
}
backupZip = null;
failedZip = null;
upgradeDir = null;
}
}
| sonatype/nexus-public | components/nexus-orient/src/main/java/org/sonatype/nexus/orient/DatabaseCheckpointSupport.java | Java | epl-1.0 | 3,928 |
/**
* Copyright (c) 2015 SK holdings Co., Ltd. All rights reserved.
* This software is the confidential and proprietary information of SK holdings.
* 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 SK holdings.
* (http://www.eclipse.org/legal/epl-v10.html)
*/
package nexcore.tool.uml.model.umldiagram;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc --> A representation of the model object '
* <em><b>Map</b></em>'. <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link nexcore.tool.uml.model.umldiagram.Map#getKey <em>Key</em>}</li>
* <li>{@link nexcore.tool.uml.model.umldiagram.Map#getValue <em>Value</em>}</li>
* </ul>
* </p>
*
* @see nexcore.tool.uml.model.umldiagram.UMLDiagramPackage#getMap()
* @model
* @generated
*/
/**
* <ul>
* <li>업무 그룹명 : nexcore.tool.uml.model</li>
* <li>서브 업무명 : nexcore.tool.uml.model.umldiagram</li>
* <li>설 명 : Map</li>
* <li>작성일 : 2015. 10. 6.</li>
* <li>작성자 : 탁희수 </li>
* </ul>
*/
public interface Map extends EObject {
/**
* Returns the value of the '<em><b>Key</b></em>' attribute. <!--
* begin-user-doc -->
* <p>
* If the meaning of the '<em>Key</em>' attribute isn't clear, there really
* should be more of a description here...
* </p>
* <!-- end-user-doc -->
*
* @return the value of the '<em>Key</em>' attribute.
* @see #setKey(String)
* @see nexcore.tool.uml.model.umldiagram.UMLDiagramPackage#getMap_Key()
* @model dataType="org.eclipse.emf.ecore.xml.type.String" required="true"
* @generated
*/
String getKey();
/**
* Sets the value of the '{@link nexcore.tool.uml.model.umldiagram.Map#getKey <em>Key</em>}' attribute.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @param value the new value of the '<em>Key</em>' attribute.
* @see #getKey()
* @generated
*/
void setKey(String value);
/**
* Returns the value of the '<em><b>Value</b></em>' attribute. <!--
* begin-user-doc -->
* <p>
* If the meaning of the '<em>Value</em>' attribute isn't clear, there
* really should be more of a description here...
* </p>
* <!-- end-user-doc -->
*
* @return the value of the '<em>Value</em>' attribute.
* @see #setValue(String)
* @see nexcore.tool.uml.model.umldiagram.UMLDiagramPackage#getMap_Value()
* @model dataType="org.eclipse.emf.ecore.xml.type.String" required="true"
* @generated
*/
String getValue();
/**
* Sets the value of the '{@link nexcore.tool.uml.model.umldiagram.Map#getValue <em>Value</em>}' attribute.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @param value the new value of the '<em>Value</em>' attribute.
* @see #getValue()
* @generated
*/
void setValue(String value);
} // Map
| SK-HOLDINGS-CC/NEXCORE-UML-Modeler | nexcore.tool.uml.model/src/java/nexcore/tool/uml/model/umldiagram/Map.java | Java | epl-1.0 | 3,108 |
#region CPL License
/*
Nuclex Framework
Copyright (C) 2002-2009 Nuclex Development Labs
This library is free software; you can redistribute it and/or
modify it under the terms of the IBM Common Public License as
published by the IBM Corporation; either version 1.0 of the
License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
IBM Common Public License for more details.
You should have received a copy of the IBM Common Public
License along with this library
*/
#endregion
using System;
using System.Runtime.Serialization;
using Microsoft.Xna.Framework;
namespace Nuclectic.Geometry.Lines {
/// <summary>A Ray from some origin to infinity</summary>
[DataContract]
public class Ray2 : ILine2 {
/// <summary>Initializes a new ray</summary>
[System.Diagnostics.DebuggerStepThrough]
public Ray2() {
Origin = Vector2.Zero;
Direction = Vector2.UnitX;
}
/// <summary>Constructs a new line as copy of an existing instance</summary>
/// <param name="other">Existing instance to copy</param>
[System.Diagnostics.DebuggerStepThrough]
public Ray2(Ray2 other) {
Origin = other.Origin;
Direction = other.Direction;
}
/// <summary>Initializes a new ray</summary>
/// <param name="origin">Location from which the ray originates</param>
/// <param name="direction">Direction into which the ray goes</param>
[System.Diagnostics.DebuggerStepThrough]
public Ray2(Vector2 origin, Vector2 direction) {
Origin = origin;
Direction = direction;
// Make sure the direction is normalized
Direction = Vector2.Normalize(Direction);
}
/// <summary>Determines the closest point on the ray to the specified location</summary>
/// <param name="location">Random loation to which the closest point is determined</param>
/// <returns>The closest point within the ray</returns>
public Vector2 ClosestPointTo(Vector2 location) {
// Calculate the position of an orthogonal vector on the ray pointing
// towards the location the caller specified
float position = Vector2.Dot(location - Origin, Direction);
// Clip the position in the negative direction so it can't go before the ray's origin
return Origin + Direction * Math.Max(position, 0.0f);
}
/// <summary>Checks two ray instances for inequality</summary>
/// <param name="first">First instance to be compared</param>
/// <param name="second">Second instance fo tbe compared</param>
/// <returns>True if the instances differ or exactly one reference is set to null</returns>
public static bool operator !=(Ray2 first, Ray2 second) {
return !(first == second);
}
/// <summary>Checks two ray instances for equality</summary>
/// <param name="first">First instance to be compared</param>
/// <param name="second">Second instance fo tbe compared</param>
/// <returns>True if both instances are equal or both references are null</returns>
public static bool operator ==(Ray2 first, Ray2 second) {
if(ReferenceEquals(first, null))
return ReferenceEquals(second, null);
return first.Equals(second);
}
/// <summary>Checks whether another instance is equal to this instance</summary>
/// <param name="other">Other instance to compare to this instance</param>
/// <returns>True if the other instance is equal to this instance</returns>
public override bool Equals(object other) {
return Equals(other as Ray2);
}
/// <summary>Checks whether another instance is equal to this instance</summary>
/// <param name="other">Other instance to compare to this instance</param>
/// <returns>True if the other instance is equal to this instance</returns>
public virtual bool Equals(Ray2 other) {
if(other == null)
return false;
else
return (this.Origin == other.Origin) && (this.Direction == other.Direction);
}
/// <summary>Obtains a hash code of this instance</summary>
/// <returns>The hash code of the instance</returns>
public override int GetHashCode() {
unchecked { return Origin.GetHashCode() + Direction.GetHashCode(); }
}
/// <summary>Origin of the ray</summary>
[DataMember]
public Vector2 Origin;
/// <summary>Normalized direction into which the ray goes</summary>
[DataMember]
public Vector2 Direction;
}
} // namespace Nuclex.Geometry.Ranges
| illuminus86/NuclecticFramework | src/Nuclectic.Geometry/Lines/Ray2.cs | C# | epl-1.0 | 4,613 |
// The MIT License (MIT)
//
// Copyright (c) 2015, 2018 Arian Fornaris
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions: The above copyright notice and this permission
// notice shall be included in all copies or substantial portions of the
// Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
package phasereditor.scene.core.codedom;
/**
* @author arian
*
*/
public class FieldDeclDom extends MemberDeclDom {
private String _type;
public FieldDeclDom(String name, String type) {
super(name);
_type = type;
}
public String getType() {
return _type;
}
public void setType(String type) {
_type = type;
}
}
| boniatillo-com/PhaserEditor | source/v2/phasereditor/phasereditor.scene.core/src/phasereditor/scene/core/codedom/FieldDeclDom.java | Java | epl-1.0 | 1,481 |
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) braces deadcode
package net.minecraft.src;
import java.util.List;
import java.util.Random;
// Referenced classes of package net.minecraft.src:
// Entity, Vec3D, AxisAlignedBB, World,
// Item, EntityPlayer, EntityItem, MathHelper,
// InventoryPlayer, ItemStack, EntityLiving, IInventory,
// NBTTagCompound, BlockRail, NBTTagList, Block
public class EntityMinecart extends Entity
implements IInventory
{
public EntityMinecart(World world)
{
super(world);
cargoItems = new ItemStack[36];
damageTaken = 0;
field_9167_b = 0;
forwardDirection = 1;
field_469_aj = false;
preventEntitySpawning = true;
setSize(0.98F, 0.7F);
yOffset = height / 2.0F;
}
protected boolean func_25017_l()
{
return false;
}
protected void entityInit()
{
}
public AxisAlignedBB func_89_d(Entity entity)
{
return entity.boundingBox;
}
public AxisAlignedBB getBoundingBox()
{
return null;
}
public boolean canBePushed()
{
return true;
}
public EntityMinecart(World world, double d, double d1, double d2,
int i)
{
this(world);
setPosition(d, d1 + (double)yOffset, d2);
motionX = 0.0D;
motionY = 0.0D;
motionZ = 0.0D;
prevPosX = d;
prevPosY = d1;
prevPosZ = d2;
minecartType = i;
}
public double getMountedYOffset()
{
return (double)height * 0.0D - 0.30000001192092896D;
}
public boolean attackEntityFrom(Entity entity, int i)
{
if(worldObj.singleplayerWorld || isDead)
{
return true;
}
forwardDirection = -forwardDirection;
field_9167_b = 10;
setBeenAttacked();
damageTaken += i * 10;
if(damageTaken > 40)
{
dropItemWithOffset(Item.minecartEmpty.shiftedIndex, 1, 0.0F);
if(minecartType == 1)
{
dropItemWithOffset(Block.crate.blockID, 1, 0.0F);
} else
if(minecartType == 2)
{
dropItemWithOffset(Block.stoneOvenIdle.blockID, 1, 0.0F);
}
setEntityDead();
}
return true;
}
public boolean canBeCollidedWith()
{
return !isDead;
}
public void setEntityDead()
{
label0:
for(int i = 0; i < getSizeInventory(); i++)
{
ItemStack itemstack = getStackInSlot(i);
if(itemstack == null)
{
continue;
}
float f = rand.nextFloat() * 0.8F + 0.1F;
float f1 = rand.nextFloat() * 0.8F + 0.1F;
float f2 = rand.nextFloat() * 0.8F + 0.1F;
do
{
if(itemstack.stackSize <= 0)
{
continue label0;
}
int j = rand.nextInt(21) + 10;
if(j > itemstack.stackSize)
{
j = itemstack.stackSize;
}
itemstack.stackSize -= j;
EntityItem entityitem = new EntityItem(worldObj, posX + (double)f, posY + (double)f1, posZ + (double)f2, new ItemStack(itemstack.itemID, j, itemstack.getItemDamage()));
float f3 = 0.05F;
entityitem.motionX = (float)rand.nextGaussian() * f3;
entityitem.motionY = (float)rand.nextGaussian() * f3 + 0.2F;
entityitem.motionZ = (float)rand.nextGaussian() * f3;
worldObj.entityJoinedWorld(entityitem);
} while(true);
}
super.setEntityDead();
}
public void onUpdate()
{
if(field_9167_b > 0)
{
field_9167_b--;
}
if(damageTaken > 0)
{
damageTaken--;
}
if(worldObj.singleplayerWorld && field_9163_an > 0)
{
if(field_9163_an > 0)
{
double d = posX + (field_9162_ao - posX) / (double)field_9163_an;
double d1 = posY + (field_9161_ap - posY) / (double)field_9163_an;
double d3 = posZ + (field_9160_aq - posZ) / (double)field_9163_an;
double d4;
for(d4 = field_9159_ar - (double)rotationYaw; d4 < -180D; d4 += 360D) { }
for(; d4 >= 180D; d4 -= 360D) { }
rotationYaw += d4 / (double)field_9163_an;
rotationPitch += (field_9158_as - (double)rotationPitch) / (double)field_9163_an;
field_9163_an--;
setPosition(d, d1, d3);
setRotation(rotationYaw, rotationPitch);
} else
{
setPosition(posX, posY, posZ);
setRotation(rotationYaw, rotationPitch);
}
return;
}
prevPosX = posX;
prevPosY = posY;
prevPosZ = posZ;
motionY -= 0.039999999105930328D;
int i = MathHelper.floor_double(posX);
int j = MathHelper.floor_double(posY);
int k = MathHelper.floor_double(posZ);
if(BlockRail.func_27029_g(worldObj, i, j - 1, k))
{
j--;
}
double d2 = 0.40000000000000002D;
boolean flag = false;
double d5 = 0.0078125D;
int l = worldObj.getBlockId(i, j, k);
if(BlockRail.func_27030_c(l))
{
Vec3D vec3d = func_182_g(posX, posY, posZ);
int i1 = worldObj.getBlockMetadata(i, j, k);
posY = j;
boolean flag1 = false;
boolean flag2 = false;
if(l == Block.railPowered.blockID)
{
flag1 = (i1 & 8) != 0;
flag2 = !flag1;
}
if(((BlockRail)Block.blocksList[l]).func_27028_d())
{
i1 &= 7;
}
if(i1 >= 2 && i1 <= 5)
{
posY = j + 1;
}
if(i1 == 2)
{
motionX -= d5;
}
if(i1 == 3)
{
motionX += d5;
}
if(i1 == 4)
{
motionZ += d5;
}
if(i1 == 5)
{
motionZ -= d5;
}
int ai[][] = field_468_ak[i1];
double d9 = ai[1][0] - ai[0][0];
double d10 = ai[1][2] - ai[0][2];
double d11 = Math.sqrt(d9 * d9 + d10 * d10);
double d12 = motionX * d9 + motionZ * d10;
if(d12 < 0.0D)
{
d9 = -d9;
d10 = -d10;
}
double d13 = Math.sqrt(motionX * motionX + motionZ * motionZ);
motionX = (d13 * d9) / d11;
motionZ = (d13 * d10) / d11;
if(flag2)
{
double d16 = Math.sqrt(motionX * motionX + motionZ * motionZ);
if(d16 < 0.029999999999999999D)
{
motionX *= 0.0D;
motionY *= 0.0D;
motionZ *= 0.0D;
} else
{
motionX *= 0.5D;
motionY *= 0.0D;
motionZ *= 0.5D;
}
}
double d17 = 0.0D;
double d18 = (double)i + 0.5D + (double)ai[0][0] * 0.5D;
double d19 = (double)k + 0.5D + (double)ai[0][2] * 0.5D;
double d20 = (double)i + 0.5D + (double)ai[1][0] * 0.5D;
double d21 = (double)k + 0.5D + (double)ai[1][2] * 0.5D;
d9 = d20 - d18;
d10 = d21 - d19;
if(d9 == 0.0D)
{
posX = (double)i + 0.5D;
d17 = posZ - (double)k;
} else
if(d10 == 0.0D)
{
posZ = (double)k + 0.5D;
d17 = posX - (double)i;
} else
{
double d22 = posX - d18;
double d24 = posZ - d19;
double d26 = (d22 * d9 + d24 * d10) * 2D;
d17 = d26;
}
posX = d18 + d9 * d17;
posZ = d19 + d10 * d17;
setPosition(posX, posY + (double)yOffset, posZ);
double d23 = motionX;
double d25 = motionZ;
if(riddenByEntity != null)
{
d23 *= 0.75D;
d25 *= 0.75D;
}
if(d23 < -d2)
{
d23 = -d2;
}
if(d23 > d2)
{
d23 = d2;
}
if(d25 < -d2)
{
d25 = -d2;
}
if(d25 > d2)
{
d25 = d2;
}
moveEntity(d23, 0.0D, d25);
if(ai[0][1] != 0 && MathHelper.floor_double(posX) - i == ai[0][0] && MathHelper.floor_double(posZ) - k == ai[0][2])
{
setPosition(posX, posY + (double)ai[0][1], posZ);
} else
if(ai[1][1] != 0 && MathHelper.floor_double(posX) - i == ai[1][0] && MathHelper.floor_double(posZ) - k == ai[1][2])
{
setPosition(posX, posY + (double)ai[1][1], posZ);
}
if(riddenByEntity != null)
{
motionX *= 0.99699997901916504D;
motionY *= 0.0D;
motionZ *= 0.99699997901916504D;
} else
{
if(minecartType == 2)
{
double d27 = MathHelper.sqrt_double(pushX * pushX + pushZ * pushZ);
if(d27 > 0.01D)
{
flag = true;
pushX /= d27;
pushZ /= d27;
double d29 = 0.040000000000000001D;
motionX *= 0.80000001192092896D;
motionY *= 0.0D;
motionZ *= 0.80000001192092896D;
motionX += pushX * d29;
motionZ += pushZ * d29;
} else
{
motionX *= 0.89999997615814209D;
motionY *= 0.0D;
motionZ *= 0.89999997615814209D;
}
}
motionX *= 0.95999997854232788D;
motionY *= 0.0D;
motionZ *= 0.95999997854232788D;
}
Vec3D vec3d1 = func_182_g(posX, posY, posZ);
if(vec3d1 != null && vec3d != null)
{
double d28 = (vec3d.yCoord - vec3d1.yCoord) * 0.050000000000000003D;
double d14 = Math.sqrt(motionX * motionX + motionZ * motionZ);
if(d14 > 0.0D)
{
motionX = (motionX / d14) * (d14 + d28);
motionZ = (motionZ / d14) * (d14 + d28);
}
setPosition(posX, vec3d1.yCoord, posZ);
}
int k1 = MathHelper.floor_double(posX);
int l1 = MathHelper.floor_double(posZ);
if(k1 != i || l1 != k)
{
double d15 = Math.sqrt(motionX * motionX + motionZ * motionZ);
motionX = d15 * (double)(k1 - i);
motionZ = d15 * (double)(l1 - k);
}
if(minecartType == 2)
{
double d30 = MathHelper.sqrt_double(pushX * pushX + pushZ * pushZ);
if(d30 > 0.01D && motionX * motionX + motionZ * motionZ > 0.001D)
{
pushX /= d30;
pushZ /= d30;
if(pushX * motionX + pushZ * motionZ < 0.0D)
{
pushX = 0.0D;
pushZ = 0.0D;
} else
{
pushX = motionX;
pushZ = motionZ;
}
}
}
if(flag1)
{
double d31 = Math.sqrt(motionX * motionX + motionZ * motionZ);
if(d31 > 0.01D)
{
double d32 = 0.040000000000000001D;
motionX += (motionX / d31) * d32;
motionZ += (motionZ / d31) * d32;
} else
if(i1 == 1)
{
if(worldObj.isBlockOpaqueCube(i - 1, j, k))
{
motionX = 0.02D;
} else
if(worldObj.isBlockOpaqueCube(i + 1, j, k))
{
motionX = -0.02D;
}
} else
if(i1 == 0)
{
if(worldObj.isBlockOpaqueCube(i, j, k - 1))
{
motionZ = 0.02D;
} else
if(worldObj.isBlockOpaqueCube(i, j, k + 1))
{
motionZ = -0.02D;
}
}
}
} else
{
if(motionX < -d2)
{
motionX = -d2;
}
if(motionX > d2)
{
motionX = d2;
}
if(motionZ < -d2)
{
motionZ = -d2;
}
if(motionZ > d2)
{
motionZ = d2;
}
if(onGround)
{
motionX *= 0.5D;
motionY *= 0.5D;
motionZ *= 0.5D;
}
moveEntity(motionX, motionY, motionZ);
if(!onGround)
{
motionX *= 0.94999998807907104D;
motionY *= 0.94999998807907104D;
motionZ *= 0.94999998807907104D;
}
}
rotationPitch = 0.0F;
double d6 = prevPosX - posX;
double d7 = prevPosZ - posZ;
if(d6 * d6 + d7 * d7 > 0.001D)
{
rotationYaw = (float)((Math.atan2(d7, d6) * 180D) / 3.1415926535897931D);
if(field_469_aj)
{
rotationYaw += 180F;
}
}
double d8;
for(d8 = rotationYaw - prevRotationYaw; d8 >= 180D; d8 -= 360D) { }
for(; d8 < -180D; d8 += 360D) { }
if(d8 < -170D || d8 >= 170D)
{
rotationYaw += 180F;
field_469_aj = !field_469_aj;
}
setRotation(rotationYaw, rotationPitch);
List list = worldObj.getEntitiesWithinAABBExcludingEntity(this, boundingBox.expand(0.20000000298023224D, 0.0D, 0.20000000298023224D));
if(list != null && list.size() > 0)
{
for(int j1 = 0; j1 < list.size(); j1++)
{
Entity entity = (Entity)list.get(j1);
if(entity != riddenByEntity && entity.canBePushed() && (entity instanceof EntityMinecart))
{
entity.applyEntityCollision(this);
}
}
}
if(riddenByEntity != null && riddenByEntity.isDead)
{
riddenByEntity = null;
}
if(flag && rand.nextInt(4) == 0)
{
fuel--;
if(fuel < 0)
{
pushX = pushZ = 0.0D;
}
worldObj.spawnParticle("largesmoke", posX, posY + 0.80000000000000004D, posZ, 0.0D, 0.0D, 0.0D);
}
}
public Vec3D func_182_g(double d, double d1, double d2)
{
int i = MathHelper.floor_double(d);
int j = MathHelper.floor_double(d1);
int k = MathHelper.floor_double(d2);
if(BlockRail.func_27029_g(worldObj, i, j - 1, k))
{
j--;
}
int l = worldObj.getBlockId(i, j, k);
if(BlockRail.func_27030_c(l))
{
int i1 = worldObj.getBlockMetadata(i, j, k);
d1 = j;
if(((BlockRail)Block.blocksList[l]).func_27028_d())
{
i1 &= 7;
}
if(i1 >= 2 && i1 <= 5)
{
d1 = j + 1;
}
int ai[][] = field_468_ak[i1];
double d3 = 0.0D;
double d4 = (double)i + 0.5D + (double)ai[0][0] * 0.5D;
double d5 = (double)j + 0.5D + (double)ai[0][1] * 0.5D;
double d6 = (double)k + 0.5D + (double)ai[0][2] * 0.5D;
double d7 = (double)i + 0.5D + (double)ai[1][0] * 0.5D;
double d8 = (double)j + 0.5D + (double)ai[1][1] * 0.5D;
double d9 = (double)k + 0.5D + (double)ai[1][2] * 0.5D;
double d10 = d7 - d4;
double d11 = (d8 - d5) * 2D;
double d12 = d9 - d6;
if(d10 == 0.0D)
{
d = (double)i + 0.5D;
d3 = d2 - (double)k;
} else
if(d12 == 0.0D)
{
d2 = (double)k + 0.5D;
d3 = d - (double)i;
} else
{
double d13 = d - d4;
double d14 = d2 - d6;
double d15 = (d13 * d10 + d14 * d12) * 2D;
d3 = d15;
}
d = d4 + d10 * d3;
d1 = d5 + d11 * d3;
d2 = d6 + d12 * d3;
if(d11 < 0.0D)
{
d1++;
}
if(d11 > 0.0D)
{
d1 += 0.5D;
}
return Vec3D.createVector(d, d1, d2);
} else
{
return null;
}
}
protected void writeEntityToNBT(NBTTagCompound nbttagcompound)
{
nbttagcompound.setInteger("Type", minecartType);
if(minecartType == 2)
{
nbttagcompound.setDouble("PushX", pushX);
nbttagcompound.setDouble("PushZ", pushZ);
nbttagcompound.setShort("Fuel", (short)fuel);
} else
if(minecartType == 1)
{
NBTTagList nbttaglist = new NBTTagList();
for(int i = 0; i < cargoItems.length; i++)
{
if(cargoItems[i] != null)
{
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
nbttagcompound1.setByte("Slot", (byte)i);
cargoItems[i].writeToNBT(nbttagcompound1);
nbttaglist.setTag(nbttagcompound1);
}
}
nbttagcompound.setTag("Items", nbttaglist);
}
}
protected void readEntityFromNBT(NBTTagCompound nbttagcompound)
{
minecartType = nbttagcompound.getInteger("Type");
if(minecartType == 2)
{
pushX = nbttagcompound.getDouble("PushX");
pushZ = nbttagcompound.getDouble("PushZ");
fuel = nbttagcompound.getShort("Fuel");
} else
if(minecartType == 1)
{
NBTTagList nbttaglist = nbttagcompound.getTagList("Items");
cargoItems = new ItemStack[getSizeInventory()];
for(int i = 0; i < nbttaglist.tagCount(); i++)
{
NBTTagCompound nbttagcompound1 = (NBTTagCompound)nbttaglist.tagAt(i);
int j = nbttagcompound1.getByte("Slot") & 0xff;
if(j >= 0 && j < cargoItems.length)
{
cargoItems[j] = new ItemStack(nbttagcompound1);
}
}
}
}
public void applyEntityCollision(Entity entity)
{
if(worldObj.singleplayerWorld)
{
return;
}
if(entity == riddenByEntity)
{
return;
}
if((entity instanceof EntityLiving) && !(entity instanceof EntityPlayer) && minecartType == 0 && motionX * motionX + motionZ * motionZ > 0.01D && riddenByEntity == null && entity.ridingEntity == null)
{
entity.mountEntity(this);
}
double d = entity.posX - posX;
double d1 = entity.posZ - posZ;
double d2 = d * d + d1 * d1;
if(d2 >= 9.9999997473787516E-005D)
{
d2 = MathHelper.sqrt_double(d2);
d /= d2;
d1 /= d2;
double d3 = 1.0D / d2;
if(d3 > 1.0D)
{
d3 = 1.0D;
}
d *= d3;
d1 *= d3;
d *= 0.10000000149011612D;
d1 *= 0.10000000149011612D;
d *= 1.0F - entityCollisionReduction;
d1 *= 1.0F - entityCollisionReduction;
d *= 0.5D;
d1 *= 0.5D;
if(entity instanceof EntityMinecart)
{
double d4 = entity.motionX + motionX;
double d5 = entity.motionZ + motionZ;
if(((EntityMinecart)entity).minecartType == 2 && minecartType != 2)
{
motionX *= 0.20000000298023224D;
motionZ *= 0.20000000298023224D;
addVelocity(entity.motionX - d, 0.0D, entity.motionZ - d1);
entity.motionX *= 0.69999998807907104D;
entity.motionZ *= 0.69999998807907104D;
} else
if(((EntityMinecart)entity).minecartType != 2 && minecartType == 2)
{
entity.motionX *= 0.20000000298023224D;
entity.motionZ *= 0.20000000298023224D;
entity.addVelocity(motionX + d, 0.0D, motionZ + d1);
motionX *= 0.69999998807907104D;
motionZ *= 0.69999998807907104D;
} else
{
d4 /= 2D;
d5 /= 2D;
motionX *= 0.20000000298023224D;
motionZ *= 0.20000000298023224D;
addVelocity(d4 - d, 0.0D, d5 - d1);
entity.motionX *= 0.20000000298023224D;
entity.motionZ *= 0.20000000298023224D;
entity.addVelocity(d4 + d, 0.0D, d5 + d1);
}
} else
{
addVelocity(-d, 0.0D, -d1);
entity.addVelocity(d / 4D, 0.0D, d1 / 4D);
}
}
}
public int getSizeInventory()
{
return 27;
}
public ItemStack getStackInSlot(int i)
{
return cargoItems[i];
}
public ItemStack decrStackSize(int i, int j)
{
if(cargoItems[i] != null)
{
if(cargoItems[i].stackSize <= j)
{
ItemStack itemstack = cargoItems[i];
cargoItems[i] = null;
return itemstack;
}
ItemStack itemstack1 = cargoItems[i].splitStack(j);
if(cargoItems[i].stackSize == 0)
{
cargoItems[i] = null;
}
return itemstack1;
} else
{
return null;
}
}
public void setInventorySlotContents(int i, ItemStack itemstack)
{
cargoItems[i] = itemstack;
if(itemstack != null && itemstack.stackSize > getInventoryStackLimit())
{
itemstack.stackSize = getInventoryStackLimit();
}
}
public String getInvName()
{
return "Minecart";
}
public int getInventoryStackLimit()
{
return 64;
}
public void onInventoryChanged()
{
}
public boolean interact(EntityPlayer entityplayer)
{
if(minecartType == 0)
{
if(riddenByEntity != null && (riddenByEntity instanceof EntityPlayer) && riddenByEntity != entityplayer)
{
return true;
}
if(!worldObj.singleplayerWorld)
{
entityplayer.mountEntity(this);
}
} else
if(minecartType == 1)
{
if(!worldObj.singleplayerWorld)
{
entityplayer.displayGUIChest(this);
}
} else
if(minecartType == 2)
{
ItemStack itemstack = entityplayer.inventory.getCurrentItem();
if(itemstack != null && itemstack.itemID == Item.coal.shiftedIndex)
{
if(--itemstack.stackSize == 0)
{
entityplayer.inventory.setInventorySlotContents(entityplayer.inventory.currentItem, null);
}
fuel += 1200;
}
pushX = posX - entityplayer.posX;
pushZ = posZ - entityplayer.posZ;
}
return true;
}
public boolean canInteractWith(EntityPlayer entityplayer)
{
if(isDead)
{
return false;
}
return entityplayer.getDistanceSqToEntity(this) <= 64D;
}
private ItemStack cargoItems[];
public int damageTaken;
public int field_9167_b;
public int forwardDirection;
private boolean field_469_aj;
public int minecartType;
public int fuel;
public double pushX;
public double pushZ;
private static final int field_468_ak[][][] = {
{
{
0, 0, -1
}, {
0, 0, 1
}
}, {
{
-1, 0, 0
}, {
1, 0, 0
}
}, {
{
-1, -1, 0
}, {
1, 0, 0
}
}, {
{
-1, 0, 0
}, {
1, -1, 0
}
}, {
{
0, 0, -1
}, {
0, -1, 1
}
}, {
{
0, -1, -1
}, {
0, 0, 1
}
}, {
{
0, 0, 1
}, {
1, 0, 0
}
}, {
{
0, 0, 1
}, {
-1, 0, 0
}
}, {
{
0, 0, -1
}, {
-1, 0, 0
}
}, {
{
0, 0, -1
}, {
1, 0, 0
}
}
};
private int field_9163_an;
private double field_9162_ao;
private double field_9161_ap;
private double field_9160_aq;
private double field_9159_ar;
private double field_9158_as;
}
| sehrgut/minecraft-smp-mocreatures | moCreatures/server/core/sources/net/minecraft/src/EntityMinecart.java | Java | epl-1.0 | 27,522 |
/*******************************************************************************
* Copyright (c) 2014 Codenvy, S.A.
* 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:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package com.codenvy.flux.watcher.core;
/**
* Type of events sent by a {@link com.codenvy.flux.watcher.core.Repository}.
*
* @author Kevin Pollet
*/
public enum RepositoryEventType {
PROJECT_RESOURCE_CREATED,
PROJECT_RESOURCE_MODIFIED,
PROJECT_RESOURCE_DELETED
}
| Serli/flux-file-watcher | flux-file-watcher-core/src/main/java/com/codenvy/flux/watcher/core/RepositoryEventType.java | Java | epl-1.0 | 796 |
/**
*/
package hu.bme.mit.inf.dslreasoner.alloyLanguage;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>ALS Override</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link hu.bme.mit.inf.dslreasoner.alloyLanguage.ALSOverride#getLeftOperand <em>Left Operand</em>}</li>
* <li>{@link hu.bme.mit.inf.dslreasoner.alloyLanguage.ALSOverride#getRightOperand <em>Right Operand</em>}</li>
* </ul>
*
* @see hu.bme.mit.inf.dslreasoner.alloyLanguage.AlloyLanguagePackage#getALSOverride()
* @model
* @generated
*/
public interface ALSOverride extends ALSTerm
{
/**
* Returns the value of the '<em><b>Left Operand</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Left Operand</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Left Operand</em>' containment reference.
* @see #setLeftOperand(ALSTerm)
* @see hu.bme.mit.inf.dslreasoner.alloyLanguage.AlloyLanguagePackage#getALSOverride_LeftOperand()
* @model containment="true"
* @generated
*/
ALSTerm getLeftOperand();
/**
* Sets the value of the '{@link hu.bme.mit.inf.dslreasoner.alloyLanguage.ALSOverride#getLeftOperand <em>Left Operand</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Left Operand</em>' containment reference.
* @see #getLeftOperand()
* @generated
*/
void setLeftOperand(ALSTerm value);
/**
* Returns the value of the '<em><b>Right Operand</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Right Operand</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Right Operand</em>' containment reference.
* @see #setRightOperand(ALSTerm)
* @see hu.bme.mit.inf.dslreasoner.alloyLanguage.AlloyLanguagePackage#getALSOverride_RightOperand()
* @model containment="true"
* @generated
*/
ALSTerm getRightOperand();
/**
* Sets the value of the '{@link hu.bme.mit.inf.dslreasoner.alloyLanguage.ALSOverride#getRightOperand <em>Right Operand</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Right Operand</em>' containment reference.
* @see #getRightOperand()
* @generated
*/
void setRightOperand(ALSTerm value);
} // ALSOverride
| viatra/VIATRA-Generator | Solvers/Alloy-Solver/hu.bme.mit.inf.dslreasoner.alloy.language/src-gen/hu/bme/mit/inf/dslreasoner/alloyLanguage/ALSOverride.java | Java | epl-1.0 | 2,742 |
/*
* Copyright (c) 2014 Cisco Systems, Inc. and others. 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
*/
package org.opendaylight.controller.md.sal.dom.store.impl.tree.data;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.opendaylight.controller.md.sal.dom.store.impl.TestModel.ID_QNAME;
import static org.opendaylight.controller.md.sal.dom.store.impl.TestModel.INNER_LIST_QNAME;
import static org.opendaylight.controller.md.sal.dom.store.impl.TestModel.NAME_QNAME;
import static org.opendaylight.controller.md.sal.dom.store.impl.TestModel.OUTER_LIST_PATH;
import static org.opendaylight.controller.md.sal.dom.store.impl.TestModel.OUTER_LIST_QNAME;
import static org.opendaylight.controller.md.sal.dom.store.impl.TestModel.TEST_PATH;
import static org.opendaylight.controller.md.sal.dom.store.impl.TestModel.TEST_QNAME;
import static org.opendaylight.controller.md.sal.dom.store.impl.TestModel.VALUE_QNAME;
import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapEntry;
import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapEntryBuilder;
import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapNodeBuilder;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.md.sal.dom.store.impl.TestModel;
import org.opendaylight.controller.md.sal.dom.store.impl.tree.DataTree;
import org.opendaylight.controller.md.sal.dom.store.impl.tree.DataTreeModification;
import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import com.google.common.base.Optional;
import com.google.common.primitives.UnsignedLong;
/**
*
* Schema structure of document is
*
* <pre>
* container root {
* list list-a {
* key leaf-a;
* leaf leaf-a;
* choice choice-a {
* case one {
* leaf one;
* }
* case two-three {
* leaf two;
* leaf three;
* }
* }
* list list-b {
* key leaf-b;
* leaf leaf-b;
* }
* }
* }
* </pre>
*
*/
public class ModificationMetadataTreeTest {
private static final Short ONE_ID = 1;
private static final Short TWO_ID = 2;
private static final String TWO_ONE_NAME = "one";
private static final String TWO_TWO_NAME = "two";
private static final InstanceIdentifier OUTER_LIST_1_PATH = InstanceIdentifier.builder(OUTER_LIST_PATH)
.nodeWithKey(OUTER_LIST_QNAME, ID_QNAME, ONE_ID) //
.build();
private static final InstanceIdentifier OUTER_LIST_2_PATH = InstanceIdentifier.builder(OUTER_LIST_PATH)
.nodeWithKey(OUTER_LIST_QNAME, ID_QNAME, TWO_ID) //
.build();
private static final InstanceIdentifier TWO_TWO_PATH = InstanceIdentifier.builder(OUTER_LIST_2_PATH)
.node(INNER_LIST_QNAME) //
.nodeWithKey(INNER_LIST_QNAME, NAME_QNAME, TWO_TWO_NAME) //
.build();
private static final InstanceIdentifier TWO_TWO_VALUE_PATH = InstanceIdentifier.builder(TWO_TWO_PATH)
.node(VALUE_QNAME) //
.build();
private static final MapEntryNode BAR_NODE = mapEntryBuilder(OUTER_LIST_QNAME, ID_QNAME, TWO_ID) //
.withChild(mapNodeBuilder(INNER_LIST_QNAME) //
.withChild(mapEntry(INNER_LIST_QNAME, NAME_QNAME, TWO_ONE_NAME)) //
.withChild(mapEntry(INNER_LIST_QNAME, NAME_QNAME, TWO_TWO_NAME)) //
.build()) //
.build();
private SchemaContext schemaContext;
private ModificationApplyOperation applyOper;
@Before
public void prepare() {
schemaContext = TestModel.createTestContext();
assertNotNull("Schema context must not be null.", schemaContext);
applyOper = SchemaAwareApplyOperation.from(schemaContext);
}
/**
* Returns a test document
*
* <pre>
* test
* outer-list
* id 1
* outer-list
* id 2
* inner-list
* name "one"
* inner-list
* name "two"
*
* </pre>
*
* @return
*/
public NormalizedNode<?, ?> createDocumentOne() {
return ImmutableContainerNodeBuilder
.create()
.withNodeIdentifier(new NodeIdentifier(schemaContext.getQName()))
.withChild(createTestContainer()).build();
}
private ContainerNode createTestContainer() {
return ImmutableContainerNodeBuilder
.create()
.withNodeIdentifier(new NodeIdentifier(TEST_QNAME))
.withChild(
mapNodeBuilder(OUTER_LIST_QNAME)
.withChild(mapEntry(OUTER_LIST_QNAME, ID_QNAME, ONE_ID))
.withChild(BAR_NODE).build()).build();
}
@Test
public void basicReadWrites() {
DataTreeModification modificationTree = new InMemoryDataTreeModification(new InMemoryDataTreeSnapshot(schemaContext,
StoreMetadataNode.createRecursively(createDocumentOne(), UnsignedLong.valueOf(5)), applyOper),
new SchemaAwareApplyOperationRoot(schemaContext));
Optional<NormalizedNode<?, ?>> originalBarNode = modificationTree.readNode(OUTER_LIST_2_PATH);
assertTrue(originalBarNode.isPresent());
assertSame(BAR_NODE, originalBarNode.get());
// writes node to /outer-list/1/inner_list/two/value
modificationTree.write(TWO_TWO_VALUE_PATH, ImmutableNodes.leafNode(VALUE_QNAME, "test"));
// reads node to /outer-list/1/inner_list/two/value
// and checks if node is already present
Optional<NormalizedNode<?, ?>> barTwoCModified = modificationTree.readNode(TWO_TWO_VALUE_PATH);
assertTrue(barTwoCModified.isPresent());
assertEquals(ImmutableNodes.leafNode(VALUE_QNAME, "test"), barTwoCModified.get());
// delete node to /outer-list/1/inner_list/two/value
modificationTree.delete(TWO_TWO_VALUE_PATH);
Optional<NormalizedNode<?, ?>> barTwoCAfterDelete = modificationTree.readNode(TWO_TWO_VALUE_PATH);
assertFalse(barTwoCAfterDelete.isPresent());
}
public DataTreeModification createEmptyModificationTree() {
/**
* Creates empty Snapshot with associated schema context.
*/
DataTree t = InMemoryDataTreeFactory.getInstance().create();
t.setSchemaContext(schemaContext);
/**
*
* Creates Mutable Data Tree based on provided snapshot and schema
* context.
*
*/
return t.takeSnapshot().newModification();
}
@Test
public void createFromEmptyState() {
DataTreeModification modificationTree = createEmptyModificationTree();
/**
* Writes empty container node to /test
*
*/
modificationTree.write(TEST_PATH, ImmutableNodes.containerNode(TEST_QNAME));
/**
* Writes empty list node to /test/outer-list
*/
modificationTree.write(OUTER_LIST_PATH, ImmutableNodes.mapNodeBuilder(OUTER_LIST_QNAME).build());
/**
* Reads list node from /test/outer-list
*/
Optional<NormalizedNode<?, ?>> potentialOuterList = modificationTree.readNode(OUTER_LIST_PATH);
assertTrue(potentialOuterList.isPresent());
/**
* Reads container node from /test and verifies that it contains test
* node
*/
Optional<NormalizedNode<?, ?>> potentialTest = modificationTree.readNode(TEST_PATH);
ContainerNode containerTest = assertPresentAndType(potentialTest, ContainerNode.class);
/**
*
* Gets list from returned snapshot of /test and verifies it contains
* outer-list
*
*/
assertPresentAndType(containerTest.getChild(new NodeIdentifier(OUTER_LIST_QNAME)), MapNode.class);
}
@Test
public void writeSubtreeReadChildren() {
DataTreeModification modificationTree = createEmptyModificationTree();
modificationTree.write(TEST_PATH, createTestContainer());
Optional<NormalizedNode<?, ?>> potential = modificationTree.readNode(TWO_TWO_PATH);
assertPresentAndType(potential, MapEntryNode.class);
}
@Test
public void writeSubtreeDeleteChildren() {
DataTreeModification modificationTree = createEmptyModificationTree();
modificationTree.write(TEST_PATH, createTestContainer());
// We verify data are present
Optional<NormalizedNode<?, ?>> potentialBeforeDelete = modificationTree.readNode(TWO_TWO_PATH);
assertPresentAndType(potentialBeforeDelete, MapEntryNode.class);
modificationTree.delete(TWO_TWO_PATH);
Optional<NormalizedNode<?, ?>> potentialAfterDelete = modificationTree.readNode(TWO_TWO_PATH);
assertFalse(potentialAfterDelete.isPresent());
}
private static <T> T assertPresentAndType(final Optional<?> potential, final Class<T> type) {
assertNotNull(potential);
assertTrue(potential.isPresent());
assertTrue(type.isInstance(potential.get()));
return type.cast(potential.get());
}
}
| niuqg/controller | opendaylight/md-sal/sal-dom-broker/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/data/ModificationMetadataTreeTest.java | Java | epl-1.0 | 10,396 |
package net.trajano.ms.engine.test;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.dns.AddressResolverOptions;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import net.trajano.ms.engine.internal.resteasy.VertxClientEngine;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.junit.Test;
import javax.ws.rs.client.Client;
import javax.ws.rs.core.Response;
import static org.junit.Assert.assertEquals;
public class VertxClientTest {
@Test
public void testWellKnown() {
final Vertx vertx = Vertx.vertx(new VertxOptions().setAddressResolverOptions(new AddressResolverOptions().setMaxQueries(10)));
final HttpClientOptions options = new HttpClientOptions()
.setPipelining(true);
final HttpClient httpClient = vertx.createHttpClient(options);
final Client client = new ResteasyClientBuilder().httpEngine(new VertxClientEngine(httpClient)).build();
String entity;
{
final Response response = client.target("https://accounts.google.com/.well-known/openid-configuration").request().get();
entity = response.readEntity(String.class);
response.close();
}
{
final Response response = client.target("https://accounts.google.com/.well-known/openid-configuration").request().get();
assertEquals(entity, response.readEntity(String.class));
response.close();
}
{
final Response response = client.target("https://accounts.google.com/.well-known/openid-configuration").request().get();
assertEquals(entity, response.readEntity(String.class));
response.close();
}
client.close();
httpClient.close();
}
}
| trajano/app-ms | ms-engine/src/test/java/net/trajano/ms/engine/test/VertxClientTest.java | Java | epl-1.0 | 1,822 |
using System;
using UnityCMF.ECore;
namespace UnityCMF.CCore
{
public interface CPackage
{
CFactory FactoryInstance { get; }
EClassifier getClassifier(string name);
}
}
| markus1978/UnityCMF | Assets/Scripts/UnityCMF/CCore/CPackage.cs | C# | epl-1.0 | 179 |
/*******************************************************************************
* Copyright (c) 2014 Bruno Medeiros and other Contributors.
* 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:
* Bruno Medeiros - initial API and implementation
*******************************************************************************/
package melnorme.util.swt.components;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import melnorme.util.swt.SWTLayoutUtil;
/**
* Common class for UI components, or composite widgets, using SWT.
* Can be created in two ways:
* the standard way - only one child control is created under parent.
* inlined - many child controls created under parent control. This allows more flexibility for more complex layouts.
*/
public abstract class AbstractComponent implements IWidgetComponent {
public AbstractComponent() {
_verifyContract();
}
protected void _verifyContract() {
}
@Override
public Composite createComponent(Composite parent) {
Composite topControl = createTopLevelControl(parent);
createContents(topControl);
updateComponentFromInput();
return topControl;
}
@Override
public void createComponentInlined(Composite parent) {
createContents(parent);
updateComponentFromInput();
}
protected final Composite createTopLevelControl(Composite parent) {
Composite topControl = doCreateTopLevelControl(parent);
topControl.setLayout(createTopLevelLayout().create());
return topControl;
}
protected Composite doCreateTopLevelControl(Composite parent) {
return new Composite(parent, SWT.NONE);
}
protected GridLayoutFactory createTopLevelLayout() {
return GridLayoutFactory.fillDefaults().numColumns(getPreferredLayoutColumns());
}
public abstract int getPreferredLayoutColumns();
protected abstract void createContents(Composite topControl);
/* ----------------- util ----------------- */
/** Do {@link #createComponent(Composite)}, and also set the layout data of created Control. */
public final Composite createComponent(Composite parent, Object layoutData) {
Composite control = createComponent(parent);
return SWTLayoutUtil.setLayoutData(control, layoutData);
}
/* ----------------- ----------------- */
/**
* Update the controls of the components from whatever is considerd the input, or source, of the control.
*/
protected abstract void updateComponentFromInput();
/* ----------------- Shortcut utils ----------------- */
protected static GridDataFactory gdSwtDefaults() {
return GridDataFactory.swtDefaults();
}
protected static GridDataFactory gdFillDefaults() {
return GridDataFactory.fillDefaults();
}
protected static GridLayoutFactory glSwtDefaults() {
return GridLayoutFactory.swtDefaults();
}
protected static GridLayoutFactory glFillDefaults() {
return GridLayoutFactory.fillDefaults();
}
} | happyspace/goclipse | plugin_ide.ui/src-lang/melnorme/util/swt/components/AbstractComponent.java | Java | epl-1.0 | 3,307 |
/*
* 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.tomcat.util.http.fileupload.util;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* An input stream, which limits its data size. This stream is
* used, if the content length is unknown.
*
* @version $Id: LimitedInputStream.java 1456935 2013-03-15 12:47:29Z markt $
*/
public abstract class LimitedInputStream extends FilterInputStream implements Closeable {
/**
* The maximum size of an item, in bytes.
*/
private final long sizeMax;
/**
* The current number of bytes.
*/
private long count;
/**
* Whether this stream is already closed.
*/
private boolean closed;
/**
* Creates a new instance.
*
* @param pIn The input stream, which shall be limited.
* @param pSizeMax The limit; no more than this number of bytes
* shall be returned by the source stream.
*/
public LimitedInputStream(InputStream pIn, long pSizeMax) {
super(pIn);
sizeMax = pSizeMax;
}
/**
* Called to indicate, that the input streams limit has
* been exceeded.
*
* @param pSizeMax The input streams limit, in bytes.
* @param pCount The actual number of bytes.
* @throws IOException The called method is expected
* to raise an IOException.
*/
protected abstract void raiseError(long pSizeMax, long pCount)
throws IOException;
/**
* Called to check, whether the input streams
* limit is reached.
*
* @throws IOException The given limit is exceeded.
*/
private void checkLimit() throws IOException {
if (count > sizeMax) {
raiseError(sizeMax, count);
}
}
/**
* Reads the next byte of data from this input stream. The value
* byte is returned as an <code>int</code> in the range
* <code>0</code> to <code>255</code>. If no byte is available
* because the end of the stream has been reached, the value
* <code>-1</code> is returned. This method blocks until input data
* is available, the end of the stream is detected, or an exception
* is thrown.
* <p>
* This method
* simply performs <code>in.read()</code> and returns the result.
*
* @return the next byte of data, or <code>-1</code> if the end of the
* stream is reached.
* @exception IOException if an I/O error occurs.
* @see java.io.FilterInputStream#in
*/
@Override
public int read() throws IOException {
int res = super.read();
if (res != -1) {
count++;
checkLimit();
}
return res;
}
/**
* Reads up to <code>len</code> bytes of data from this input stream
* into an array of bytes. If <code>len</code> is not zero, the method
* blocks until some input is available; otherwise, no
* bytes are read and <code>0</code> is returned.
* <p>
* This method simply performs <code>in.read(b, off, len)</code>
* and returns the result.
*
* @param b the buffer into which the data is read.
* @param off The start offset in the destination array
* <code>b</code>.
* @param len the maximum number of bytes read.
* @return the total number of bytes read into the buffer, or
* <code>-1</code> if there is no more data because the end of
* the stream has been reached.
* @exception NullPointerException If <code>b</code> is <code>null</code>.
* @exception IndexOutOfBoundsException If <code>off</code> is negative,
* <code>len</code> is negative, or <code>len</code> is greater than
* <code>b.length - off</code>
* @exception IOException if an I/O error occurs.
* @see java.io.FilterInputStream#in
*/
@Override
public int read(byte[] b, int off, int len) throws IOException {
int res = super.read(b, off, len);
if (res > 0) {
count += res;
checkLimit();
}
return res;
}
/**
* Returns, whether this stream is already closed.
*
* @return True, if the stream is closed, otherwise false.
* @throws IOException An I/O error occurred.
*/
@Override
public boolean isClosed() throws IOException {
return closed;
}
/**
* Closes this input stream and releases any system resources
* associated with the stream.
* This
* method simply performs <code>in.close()</code>.
*
* @exception IOException if an I/O error occurs.
* @see java.io.FilterInputStream#in
*/
@Override
public void close() throws IOException {
closed = true;
super.close();
}
}
| GazeboHub/ghub-portal-doc | doc/modelio/GHub Portal/mda/JavaDesigner/res/java/tomcat/java/org/apache/tomcat/util/http/fileupload/util/LimitedInputStream.java | Java | epl-1.0 | 5,635 |
/* ******************************************************************************
* Copyright (c) 2014 - 2015 Fabian Prasser.
* 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:
* Fabian Prasser - initial API and implementation
******************************************************************************/
package de.linearbits.jhc;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Transform;
/**
* This class implements graphics operations for SWT
*
* @author Fabian Prasser
*/
class GraphicsSWT implements Graphics<Image, Color> {
/** The antialias. */
private int antialias;
/** The canvas. */
private CanvasSWT canvas;
/** The gc. */
private GC gc;
/** The interpolation. */
private int interpolation;
/**
* Creates a new instance
*
* @param canvas the canvas
* @param gc the gc
*/
protected GraphicsSWT(CanvasSWT canvas, GC gc) {
this.canvas = canvas;
this.gc = gc;
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#disableAntialiasing()
*/
@Override
public void disableAntialiasing() {
gc.setAntialias(SWT.OFF);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#disableInterpolation()
*/
@Override
public void disableInterpolation() {
gc.setInterpolation(SWT.NONE);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#drawImage(java.lang.Object, int, int, int, int)
*/
@Override
public void drawImage(Image image, int x, int y, int width, int height) {
org.eclipse.swt.graphics.Rectangle bounds = image.getBounds();
gc.drawImage(image, 0, 0, bounds.width, bounds.height, x, y, width, height);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#drawLegend(de.linearbits.jhc.Gradient)
*/
@Override
public Image drawLegend(JHCGradient gradient) {
PixelsSWT pixels = new PixelsSWT(new Dimension(1, gradient.getSteps()), canvas.getDisplay(), gradient.getColor(0));
for (int i = 0; i < gradient.getSteps(); i++) {
pixels.set(0, i, gradient.getColor(i));
}
pixels.update();
return pixels.getImage();
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#drawLine(int, int, int, int)
*/
@Override
public void drawLine(int x1, int y1, int x2, int y2) {
gc.drawLine(x1, y1, x2, y2);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#drawRectangle(int, int, int, int)
*/
@Override
public void drawRectangle(int x, int y, int width, int height) {
gc.drawRectangle(x, y, width, height);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#drawRectangleFilled(int, int, int, int)
*/
@Override
public void drawRectangleFilled(int x, int y, int width, int height) {
gc.fillRectangle(x, y, width, height);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#drawStringAboveHorizontallyCentered(java.lang.String, int, int, int)
*/
@Override
public void drawStringAboveHorizontallyCentered(String string, int x, int y, int width) {
Point extent = gc.textExtent(string);
int yy = y - extent.y;
if (width >= extent.x) {
gc.setClipping(x, yy, width, extent.y);
int xx = x + (width - extent.x) / 2;
gc.drawText(string, xx, yy, true);
} else {
int postfixWidth = gc.textExtent(POSTFIX).x;
gc.setClipping(x, yy, width - postfixWidth, extent.y);
gc.drawText(string, x, yy, true);
gc.setClipping(x + width - postfixWidth, yy, postfixWidth, extent.y);
gc.drawText(POSTFIX, x + width - postfixWidth, yy, true);
}
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#drawStringBelowHorizontallyCentered(java.lang.String, int, int, int)
*/
@Override
public void drawStringBelowHorizontallyCentered(String string, int x, int y, int width) {
Point extent = gc.textExtent(string);
int descent = gc.getFontMetrics().getDescent();
if (width >= extent.x) {
gc.setClipping(x, y + descent, width, extent.y);
int xx = x + (width - extent.x) / 2;
gc.drawText(string, xx, y + descent, true);
} else {
int postfixWidth = gc.textExtent(POSTFIX).x;
gc.setClipping(x, y + descent, width - postfixWidth, extent.y);
gc.drawText(string, x, y + descent, true);
gc.setClipping(x + width - postfixWidth, y + descent, postfixWidth, extent.y);
gc.drawText(POSTFIX, x + width - postfixWidth, y + descent, true);
}
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#drawStringVerticallyCenteredLeftAligned(java.lang.String, int, int, int, int)
*/
@Override
public void drawStringVerticallyCenteredLeftAligned(String string, int x, int y, int width, int height) {
Point extent = gc.textExtent(string);
int yy = y + height / 2 - extent.y / 2;
if (width >= extent.x) {
gc.setClipping(x, yy, width, extent.y);
gc.drawText(string, x, yy, true);
} else {
int postfixWidth = gc.textExtent(POSTFIX).x;
gc.setClipping(x, yy, width - postfixWidth, extent.y);
gc.drawText(string, x, yy, true);
gc.setClipping(x + width - postfixWidth, yy, postfixWidth, extent.y);
gc.drawText(POSTFIX, x + width - postfixWidth, yy, true);
}
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#enableAntialiasing()
*/
@Override
public void enableAntialiasing() {
gc.setAntialias(SWT.ON);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#enableInterpolation()
*/
@Override
public void enableInterpolation() {
gc.setInterpolation(SWT.HIGH);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#getTextHeight(java.lang.String)
*/
@Override
public int getTextHeight(String string) {
return gc.textExtent(string).y;
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#getTextWidth(java.lang.String)
*/
@Override
public int getTextWidth(String string) {
return gc.textExtent(string).x;
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#init()
*/
@Override
public void init() {
gc.setFont(canvas.getFont());
antialias = gc.getAntialias();
interpolation = gc.getInterpolation();
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#resetAntialiasing()
*/
@Override
public void resetAntialiasing() {
gc.setAntialias(antialias);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#resetClipping()
*/
@Override
public void resetClipping() {
org.eclipse.swt.graphics.Rectangle bounds = canvas.getBounds();
gc.setClipping(0, 0, bounds.width, bounds.height);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#resetInterpolation()
*/
@Override
public void resetInterpolation() {
gc.setInterpolation(interpolation);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#resetRotation()
*/
@Override
public void resetRotation() {
gc.setTransform(null);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#setBackground(java.lang.Object)
*/
@Override
public void setBackground(Color color) {
gc.setBackground(color);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#setForeground(java.lang.Object)
*/
@Override
public void setForeground(Color color) {
gc.setForeground(color);
}
/*
* (non-Javadoc)
*
* @see de.linearbits.jhc.Graphics#setRotation(int)
*/
@Override
public void setRotation(int degrees) {
Transform tr = new Transform(canvas.getDisplay());
tr.rotate(degrees);
gc.setTransform(tr);
}
@Override
public void drawStringCentered(String string, int x, int y, int width, int height) {
Point extent = gc.textExtent(string);
int yy = y + (height - extent.y) / 2;
int xx = x + (width - extent.x) / 2;
gc.setClipping(xx, yy, extent.x, extent.y);
gc.drawText(string, xx, yy, true);
}
}
| prasser/jhc | src/swt/de/linearbits/jhc/GraphicsSWT.java | Java | epl-1.0 | 9,146 |
var library = require('./library.js');
var check_cond = function(num, div, start)
{
var n = '';
for(var i = start; i < start + 3; i++)
{
n = n + num.toString().charAt(i - 1);
}
if(parseInt(n) % div === 0)
{
return true;
}
return false;
}
var check_all = function(num)
{
var all = [2, 3, 5, 7, 11, 13, 17];
for(var i = 0; i < all.length; i += 1)
{
if(!check_cond(num, all[i], i + 2))
{
return false;
}
}
return true;
}
var solve = function ()
{
var sum = 0;
var start = 1234567890;
var end = 9876543210;
for(var i = start, count = 0; i <= end; i += 1, count += 1)
{
if(count % 1000000 == 0)
{
console.log("\$i : " + i);
}
if(!library.is_pandigital(i, 0))
{
continue;
}
if(!check_all(i))
{
continue;
}
console.log("OK : " + i);
sum += i;
}
};
var check_all_2 = function(num)
{
var y = num.toString();
var n = [0];
for(var i = 0; i < y.length; i += 1)
{
n.push(parseInt(y[i]));
}
if(n[4] % 2 != 0)
{
return false;
}
var a = n[3] + n[4] + n[5];
if(a % 3 != 0)
{
return false;
}
if(n[6] % 5 != 0)
{
return false;
}
var b = n[5] * 10 + n[6] - 2 * n[7];
if(b % 7 != 0)
{
return false;
}
var c = n[6] * 10 + n[7] - n[8];
if(c % 11 != 0)
{
return false;
}
var d = n[7] * 10 + n[8] + 4 * n[9];
if(d % 13 != 0)
{
return false;
}
var e = n[8] * 10 + n[9] - 5 * n[10];
if(e % 17 != 0)
{
return false;
}
return true;
}
var solve_2 = function ()
{
var sum = 0;
var start = 1234567890;
var end = 9876543210;
for(var i = start, count = 0; i <= end; i += 1, count += 1)
{
if(count % 1000000 == 0)
{
console.log("\$i : " + i);
}
if(!check_all_2(i))
{
continue;
}
if(!library.is_pandigital_v2(i, 0))
{
continue;
}
console.log("OK : " + i);
sum += i;
}
};
var sum = solve_2();
console.log(sum);
//var num = process.argv[2];
//console.log(check_all_2(num));
| xitkov/projecteuler | other-lang/js/solve0043.js | JavaScript | epl-1.0 | 2,372 |
package org.productivity.java.syslog4j.impl;
import java.util.List;
import org.productivity.java.syslog4j.SyslogConfigIF;
/**
* AbstractSyslogConfigIF provides an interface for all Abstract Syslog
* configuration implementations.
*
* <p>Syslog4j is licensed under the Lesser GNU Public License v2.1. A copy
* of the LGPL license is available in the META-INF folder in all
* distributions of Syslog4j and in the base directory of the "doc" ZIP.</p>
*
* @author <syslog4j@productivity.org>
* @version $Id: AbstractSyslogConfigIF.java,v 1.7 2010/10/29 03:14:20 cvs Exp $
*/
public interface AbstractSyslogConfigIF extends SyslogConfigIF {
public Class getSyslogWriterClass();
public List getBackLogHandlers();
public List getMessageModifiers();
public byte[] getSplitMessageBeginText();
public void setSplitMessageBeginText(byte[] beginText);
public byte[] getSplitMessageEndText();
public void setSplitMessageEndText(byte[] endText);
public boolean isThreaded();
public void setThreaded(boolean threaded);
public boolean isUseDaemonThread();
public void setUseDaemonThread(boolean useDaemonThread);
public int getThreadPriority();
public void setThreadPriority(int threadPriority);
public long getThreadLoopInterval();
public void setThreadLoopInterval(long threadLoopInterval);
public long getMaxShutdownWait();
public void setMaxShutdownWait(long maxShutdownWait);
public int getWriteRetries();
public void setWriteRetries(int writeRetries);
public int getMaxQueueSize();
/**
* Use the (default) value of -1 to allow for a queue of indefinite depth (size).
*
* @param maxQueueSize
*/
public void setMaxQueueSize(int maxQueueSize);
}
| kerbyfc/slag | src/slag/java/org/productivity/java/syslog4j/impl/AbstractSyslogConfigIF.java | Java | epl-1.0 | 1,753 |
/*
* AutoRefactor - Eclipse plugin to automatically refactor Java code bases.
*
* Copyright (C) 2013 Jean-Noël Rouvignac - initial API and implementation
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* 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 under LICENSE-GNUGPL. If not, see
* <http://www.gnu.org/licenses/>.
*
*
* 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 under LICENSE-ECLIPSE, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.autorefactor.jdt.internal.ui.fix.samples_out;
import java.util.List;
public class ReduceVariableScopeSample {
public static void main(String[] args) {
// Push variable into for loops initializers
int i;
{
i = 0;
}
for (i = 0; i < args.length; i++) {
i = 0;
}
for (i = 0; i < args.length; i++)
i = 0;
for (Object obj : (List) null) {
i = 0;
}
for (Object obj : (List) null)
i = 0;
if (isOk()) {
i = 0;
}
if (isOk())
i = 0;
while (isOk()) {
i = 0;
}
while (isOk())
i = 0;
}
private static boolean isOk() {
return false;
}
private static void doIt() {
}
}
| rpau/AutoRefactor | samples/src/test/java/org/autorefactor/jdt/internal/ui/fix/samples_out/ReduceVariableScopeSample.java | Java | epl-1.0 | 1,996 |
/**
* Copyright (c) 2016-2019 by the respective copyright holders.
* 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
*/
package com.zsmartsystems.zigbee.dongle.telegesis.internal.protocol;
/**
* Class to implement the Telegesis command <b>Nack Message</b>.
* <p>
* Acknowledgement for message XX was not received
* <p>
* This class provides methods for processing Telegesis AT API commands.
* <p>
* Note that this code is autogenerated. Manual changes may be overwritten.
*
* @author Chris Jackson - Initial contribution of Java code generator
*/
public class TelegesisNackMessageEvent extends TelegesisFrame implements TelegesisEvent {
/**
* NACK response field
*/
private Integer messageId;
/**
*
* @return the messageId as {@link Integer}
*/
public Integer getMessageId() {
return messageId;
}
@Override
public void deserialize(int[] data) {
initialiseDeserializer(data);
// Deserialize the fields for the "NACK" response
if (testPrompt(data, "NACK:")) {
setDeserializer(5);
// Deserialize field "message ID"
messageId = deserializeInt8();
}
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder(205);
builder.append("TelegesisNackMessageEvent [messageId=");
builder.append(messageId);
builder.append(']');
return builder.toString();
}
}
| cschwer/com.zsmartsystems.zigbee | com.zsmartsystems.zigbee.dongle.telegesis/src/main/java/com/zsmartsystems/zigbee/dongle/telegesis/internal/protocol/TelegesisNackMessageEvent.java | Java | epl-1.0 | 1,675 |
/*******************************************************************************
* Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.models.jpa.inheritance;
import java.io.*;
import org.eclipse.persistence.tools.schemaframework.*;
import javax.persistence.*;
import static javax.persistence.GenerationType.*;
import static javax.persistence.CascadeType.*;
import static javax.persistence.FetchType.*;
import static javax.persistence.InheritanceType.*;
@Entity
@EntityListeners(org.eclipse.persistence.testing.models.jpa.inheritance.listeners.VehicleListener.class)
@Table(name="CMP3_VEHICLE")
@Inheritance(strategy=JOINED)
@DiscriminatorColumn(name="VEH_TYPE")
@DiscriminatorValue("V")
public abstract class Vehicle implements Serializable {
private Number id;
private Company owner;
private Integer passengerCapacity;
private VehicleDirectory directory;
public Vehicle() {}
public void change() {
return;
}
public abstract String getColor();
@Id
@GeneratedValue(strategy=TABLE, generator="VEHICLE_TABLE_GENERATOR")
@TableGenerator(
name="VEHICLE_TABLE_GENERATOR",
table="CMP3_INHERITANCE_SEQ",
pkColumnName="SEQ_NAME",
valueColumnName="SEQ_COUNT",
pkColumnValue="VEHICLE_SEQ")
@Column(name="ID")
public Number getId() {
return id;
}
@ManyToOne(cascade=PERSIST, fetch=LAZY)
@JoinColumn(name="OWNER_ID", referencedColumnName="ID")
public Company getOwner() {
return owner;
}
@Column(name="CAPACITY")
public Integer getPassengerCapacity() {
return passengerCapacity;
}
/**
* Return the view for Sybase.
*/
public static ViewDefinition oracleView() {
ViewDefinition definition = new ViewDefinition();
definition.setName("AllVehicles");
definition.setSelectClause("Select V.*, F.FUEL_CAP, F.FUEL_TYP, B.DESCRIP, B.DRIVER_ID, C.CDESCRIP" + " from VEHICLE V, FUEL_VEH F, BUS B, CAR C" + " where V.ID = F.ID (+) AND V.ID = B.ID (+) AND V.ID = C.ID (+)");
return definition;
}
public abstract void setColor(String color);
public void setId(Number id) {
this.id = id;
}
public void setOwner(Company ownerCompany) {
owner = ownerCompany;
}
public void setPassengerCapacity(Integer capacity) {
passengerCapacity = capacity;
}
@ManyToOne(cascade=PERSIST, fetch=LAZY)
@JoinColumn(name="DIRECTORY_ID", referencedColumnName="ID")
public VehicleDirectory getDirectory() {
return directory;
}
public void setDirectory(VehicleDirectory directory) {
this.directory = directory;
}
/**
* Return the view for Sybase.
*/
public static ViewDefinition sybaseView() {
ViewDefinition definition = new ViewDefinition();
definition.setName("AllVehicles");
definition.setSelectClause("Select V.*, F.FUEL_CAP, F.FUEL_TYP, B.DESCRIP, B.DRIVER_ID, C.CDESCRIP" + " from VEHICLE V, FUEL_VEH F, BUS B, CAR C" + " where V.ID *= F.ID AND V.ID *= B.ID AND V.ID *= C.ID");
return definition;
}
public String toString() {
return org.eclipse.persistence.internal.helper.Helper.getShortClassName(getClass()) + "(" + id + ")";
}
}
| bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | jpa/eclipselink.jpa.test/src/org/eclipse/persistence/testing/models/jpa/inheritance/Vehicle.java | Java | epl-1.0 | 4,050 |
/*******************************************************************************
* Copyright (c) 2012-2015 Codenvy, S.A.
* 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:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.ide.ext.git.server.rest;
import org.eclipse.che.ide.ext.git.shared.Tag;
import javax.inject.Singleton;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/**
* Writer to serialize list of git tags to plain text in form as command line git does.
*
* @author <a href="mailto:andrew00x@gmail.com">Andrey Parfonov</a>
* @version $Id: $
*/
@Singleton
@Provider
@Produces(MediaType.TEXT_PLAIN)
public final class TagListWriter implements MessageBodyWriter<Iterable<Tag>> {
/**
* @see MessageBodyWriter#isWriteable(Class, java.lang.reflect.Type, java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType)
*/
@Override
public boolean isWriteable(Class< ? > type, Type genericType, Annotation[] annotations, MediaType mediaType) {
if (Iterable.class.isAssignableFrom(type) && (genericType instanceof ParameterizedType)) {
Type[] types = ((ParameterizedType)genericType).getActualTypeArguments();
return types.length == 1 && types[0] == Tag.class;
}
return false;
}
/**
* @see MessageBodyWriter#getSize(Object, Class, java.lang.reflect.Type, java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType)
*/
@Override
public long getSize(Iterable<Tag> tags,
Class< ? > type,
Type genericType,
Annotation[] annotations,
MediaType mediaType) {
return -1;
}
/**
* @see MessageBodyWriter#writeTo(Object, Class, java.lang.reflect.Type, java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType,
* javax.ws.rs.core.MultivaluedMap, java.io.OutputStream)
*/
@Override
public void writeTo(Iterable<Tag> tags,
Class< ? > type,
Type genericType,
Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream) throws IOException, WebApplicationException {
Writer writer = new OutputStreamWriter(entityStream);
for (Tag tag : tags) {
writer.write(tag.getName());
writer.write('\n');
}
writer.flush();
}
}
| sunix/che-plugins | plugin-git/che-plugin-git-ext-git/src/main/java/org/eclipse/che/ide/ext/git/server/rest/TagListWriter.java | Java | epl-1.0 | 3,244 |
/*******************************************************************************
* Copyright (c) 2012-2017 Codenvy, S.A.
* 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:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.plugin.docker.machine;
import com.google.inject.assistedinject.Assisted;
import org.eclipse.che.api.core.ConflictException;
import org.eclipse.che.api.core.NotFoundException;
import org.eclipse.che.api.core.model.workspace.config.Command;
import org.eclipse.che.api.core.util.LineConsumer;
import org.eclipse.che.api.core.util.ListLineConsumer;
import org.eclipse.che.api.core.util.ValueHolder;
import org.eclipse.che.api.machine.server.exception.MachineException;
import org.eclipse.che.api.machine.server.spi.InstanceProcess;
import org.eclipse.che.api.machine.server.spi.impl.AbstractMachineProcess;
import org.eclipse.che.commons.annotation.Nullable;
import org.eclipse.che.plugin.docker.client.DockerConnector;
import org.eclipse.che.plugin.docker.client.Exec;
import org.eclipse.che.plugin.docker.client.LogMessage;
import org.eclipse.che.plugin.docker.client.MessageProcessor;
import org.eclipse.che.plugin.docker.client.params.CreateExecParams;
import org.eclipse.che.plugin.docker.client.params.StartExecParams;
import javax.inject.Inject;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.Arrays;
import static com.google.common.base.MoreObjects.firstNonNull;
import static java.lang.String.format;
/**
* Docker implementation of {@link InstanceProcess}
*
* @author andrew00x
* @author Alexander Garagatyi
*/
public class DockerProcess extends AbstractMachineProcess implements InstanceProcess {
private final DockerConnector docker;
private final String container;
private final String pidFilePath;
private final String commandLine;
private final String shellInvoker;
private volatile boolean started;
@Inject
public DockerProcess(DockerConnector docker,
@Assisted Command command,
@Assisted("container") String container,
@Nullable @Assisted("outputChannel") String outputChannel,
@Assisted("pid_file_path") String pidFilePath,
@Assisted int pid) {
super(command, pid, outputChannel);
this.docker = docker;
this.container = container;
this.commandLine = command.getCommandLine();
this.shellInvoker = firstNonNull(command.getAttributes().get("shell"), "/bin/sh");
this.pidFilePath = pidFilePath;
this.started = false;
}
@Override
public boolean isAlive() {
if (!started) {
return false;
}
try {
checkAlive();
return true;
} catch (MachineException | NotFoundException e) {
// when process is not found (may be finished or killed)
// when process is not running yet
// when docker is not accessible or responds in an unexpected way - should never happen
return false;
}
}
@Override
public void start() throws ConflictException, MachineException {
start(null);
}
@Override
public void start(LineConsumer output) throws ConflictException, MachineException {
if (started) {
throw new ConflictException("Process already started.");
}
started = true;
// Trap is invoked when bash session ends. Here we kill all sub-processes of shell and remove pid-file.
final String trap = format("trap '[ -z \"$(jobs -p)\" ] || kill $(jobs -p); [ -e %1$s ] && rm %1$s' EXIT", pidFilePath);
// 'echo' saves shell pid in file, then run command
final String shellCommand = trap + "; echo $$>" + pidFilePath + "; " + commandLine;
final String[] command = {shellInvoker, "-c", shellCommand};
Exec exec;
try {
exec = docker.createExec(CreateExecParams.create(container, command).withDetach(output == null));
} catch (IOException e) {
throw new MachineException(format("Error occurs while initializing command %s in docker container %s: %s",
Arrays.toString(command), container, e.getMessage()), e);
}
try {
docker.startExec(StartExecParams.create(exec.getId()), output == null ? null : new LogMessagePrinter(output));
} catch (IOException e) {
if (output != null && e instanceof SocketTimeoutException) {
throw new MachineException(getErrorMessage());
} else {
throw new MachineException(format("Error occurs while executing command %s: %s",
Arrays.toString(exec.getCommand()), e.getMessage()), e);
}
}
}
@Override
public void checkAlive() throws MachineException, NotFoundException {
// Read pid from file and run 'kill -0 [pid]' command.
final String isAliveCmd = format("[ -r %1$s ] && kill -0 $(cat %1$s) || echo 'Unable read PID file'", pidFilePath);
final ListLineConsumer output = new ListLineConsumer();
final String[] command = {"/bin/sh", "-c", isAliveCmd};
Exec exec;
try {
exec = docker.createExec(CreateExecParams.create(container, command).withDetach(false));
} catch (IOException e) {
throw new MachineException(format("Error occurs while initializing command %s in docker container %s: %s",
Arrays.toString(command), container, e.getMessage()), e);
}
try {
docker.startExec(StartExecParams.create(exec.getId()), new LogMessagePrinter(output));
} catch (IOException e) {
throw new MachineException(format("Error occurs while executing command %s in docker container %s: %s",
Arrays.toString(exec.getCommand()), container, e.getMessage()), e);
}
// 'kill -0 [pid]' is silent if process is running or print "No such process" message otherwise
if (!output.getText().isEmpty()) {
throw new NotFoundException(format("Process with pid %s not found", getPid()));
}
}
@Override
public void kill() throws MachineException {
if (started) {
// Read pid from file and run 'kill [pid]' command.
final String killCmd = format("[ -r %1$s ] && kill $(cat %1$s)", pidFilePath);
final String[] command = {"/bin/sh", "-c", killCmd};
Exec exec;
try {
exec = docker.createExec(CreateExecParams.create(container, command).withDetach(true));
} catch (IOException e) {
throw new MachineException(format("Error occurs while initializing command %s in docker container %s: %s",
Arrays.toString(command), container, e.getMessage()), e);
}
try {
docker.startExec(StartExecParams.create(exec.getId()), MessageProcessor.DEV_NULL);
} catch (IOException e) {
throw new MachineException(format("Error occurs while executing command %s in docker container %s: %s",
Arrays.toString(exec.getCommand()), container, e.getMessage()), e);
}
}
}
private String getErrorMessage() {
final StringBuilder errorMessage = new StringBuilder("Command output read timeout is reached.");
try {
// check if process is alive
final Exec checkProcessExec = docker.createExec(
CreateExecParams.create(container,
new String[] {"/bin/sh",
"-c",
format("if kill -0 $(cat %1$s 2>/dev/null) 2>/dev/null; then cat %1$s; fi",
pidFilePath)})
.withDetach(false));
ValueHolder<String> pidHolder = new ValueHolder<>();
docker.startExec(StartExecParams.create(checkProcessExec.getId()), message -> {
if (message.getType() == LogMessage.Type.STDOUT) {
pidHolder.set(message.getContent());
}
});
if (pidHolder.get() != null) {
errorMessage.append(" Process is still running and has id ").append(pidHolder.get()).append(" inside machine");
}
} catch (IOException ignore) {
}
return errorMessage.toString();
}
}
| gazarenkov/che-sketch | plugins/plugin-docker/che-plugin-docker-machine/src/main/java/org/eclipse/che/plugin/docker/machine/DockerProcess.java | Java | epl-1.0 | 9,181 |
/**
*/
package WTSpec.provider;
import WTSpec.CtrlUnit115;
import WTSpec.WTSpecPackage;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
/**
* This is the item provider adapter for a {@link WTSpec.CtrlUnit115} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class CtrlUnit115ItemProvider extends wtcItemProvider {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public CtrlUnit115ItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
addInput__iWindSpeedRawPropertyDescriptor(object);
addOutput__oWindSpeedPropertyDescriptor(object);
addOutput__oWindSpeedAveragePropertyDescriptor(object);
addParameter__pNacelleSlopePropertyDescriptor(object);
addParameter__pNacelleOffsetPropertyDescriptor(object);
addParameter__pWindSpeedAveragePeriodPropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the Input iWind Speed Raw feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addInput__iWindSpeedRawPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit115_Input__iWindSpeedRaw_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit115_Input__iWindSpeedRaw_feature", "_UI_CtrlUnit115_type"),
WTSpecPackage.Literals.CTRL_UNIT115__INPUT_IWIND_SPEED_RAW,
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Output oWind Speed feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addOutput__oWindSpeedPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit115_Output__oWindSpeed_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit115_Output__oWindSpeed_feature", "_UI_CtrlUnit115_type"),
WTSpecPackage.Literals.CTRL_UNIT115__OUTPUT_OWIND_SPEED,
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Output oWind Speed Average feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addOutput__oWindSpeedAveragePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit115_Output__oWindSpeedAverage_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit115_Output__oWindSpeedAverage_feature", "_UI_CtrlUnit115_type"),
WTSpecPackage.Literals.CTRL_UNIT115__OUTPUT_OWIND_SPEED_AVERAGE,
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Parameter pNacelle Slope feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addParameter__pNacelleSlopePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit115_Parameter__pNacelleSlope_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit115_Parameter__pNacelleSlope_feature", "_UI_CtrlUnit115_type"),
WTSpecPackage.Literals.CTRL_UNIT115__PARAMETER_PNACELLE_SLOPE,
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Parameter pNacelle Offset feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addParameter__pNacelleOffsetPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit115_Parameter__pNacelleOffset_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit115_Parameter__pNacelleOffset_feature", "_UI_CtrlUnit115_type"),
WTSpecPackage.Literals.CTRL_UNIT115__PARAMETER_PNACELLE_OFFSET,
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Parameter pWind Speed Average Period feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addParameter__pWindSpeedAveragePeriodPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_CtrlUnit115_Parameter__pWindSpeedAveragePeriod_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_CtrlUnit115_Parameter__pWindSpeedAveragePeriod_feature", "_UI_CtrlUnit115_type"),
WTSpecPackage.Literals.CTRL_UNIT115__PARAMETER_PWIND_SPEED_AVERAGE_PERIOD,
true,
false,
true,
null,
null,
null));
}
/**
* This returns CtrlUnit115.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/CtrlUnit115"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
String label = ((CtrlUnit115)object).getSysId();
return label == null || label.length() == 0 ?
getString("_UI_CtrlUnit115_type") :
getString("_UI_CtrlUnit115_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
}
}
| FTSRG/mondo-collab-framework | archive/mondo-access-control/CollaborationIncQuery/WTSpec.edit/src/WTSpec/provider/CtrlUnit115ItemProvider.java | Java | epl-1.0 | 7,434 |
package javamm.ui.launch;
import org.eclipse.jdt.launching.JavaLaunchDelegate;
public class JavammLaunchDelegate extends JavaLaunchDelegate {
}
| LorenzoBettini/javamm | javamm.ui/src/javamm/ui/launch/JavammLaunchDelegate.java | Java | epl-1.0 | 146 |
package edu.upenn.cis455.storage.entity;
public interface WebPageEntity {
}
| arpitpanwar/Crawler | src/edu/upenn/cis455/storage/entity/WebPageEntity.java | Java | epl-1.0 | 78 |
/*******************************************************************************
* Copyright (c) 2011, 2016 Eurotech and/or its affiliates and others
*
* 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:
* Eurotech - initial API and implementation
*
*******************************************************************************/
package org.eclipse.kapua.app.console.client.ui.button;
import org.eclipse.kapua.app.console.client.resources.icons.KapuaIcon;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
public class Button extends com.extjs.gxt.ui.client.widget.button.Button {
private String originalText;
private KapuaIcon icon;
public Button(String text, KapuaIcon icon, SelectionListener<ButtonEvent> listener) {
super();
setText(text);
setIcon(icon);
addSelectionListener(listener);
}
@Override
public String getText() {
return originalText;
}
@Override
public void setText(String text) {
super.setText((icon != null ? icon.getInlineHTML() + " " : "") + text);
this.originalText = text;
}
public void setIcon(KapuaIcon icon) {
super.setText(icon.getInlineHTML() + " " + originalText);
this.icon = icon;
}
}
| cbaerikebc/kapua | console/src/main/java/org/eclipse/kapua/app/console/client/ui/button/Button.java | Java | epl-1.0 | 1,547 |
/* This file was generated by SableCC (http://www.sablecc.org/). */
package com.abstratt.mdd.frontend.textuml.grammar.node;
import com.abstratt.mdd.frontend.textuml.grammar.analysis.*;
@SuppressWarnings("nls")
public final class APackageVisibilityModifier extends PVisibilityModifier
{
private TPackage _package_;
public APackageVisibilityModifier()
{
// Constructor
}
public APackageVisibilityModifier(
@SuppressWarnings("hiding") TPackage _package_)
{
// Constructor
setPackage(_package_);
}
@Override
public Object clone()
{
return new APackageVisibilityModifier(
cloneNode(this._package_));
}
public void apply(Switch sw)
{
((Analysis) sw).caseAPackageVisibilityModifier(this);
}
public TPackage getPackage()
{
return this._package_;
}
public void setPackage(TPackage node)
{
if(this._package_ != null)
{
this._package_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._package_ = node;
}
@Override
public String toString()
{
return ""
+ toString(this._package_);
}
@Override
void removeChild(@SuppressWarnings("unused") Node child)
{
// Remove child
if(this._package_ == child)
{
this._package_ = null;
return;
}
throw new RuntimeException("Not a child.");
}
@Override
void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild)
{
// Replace child
if(this._package_ == oldChild)
{
setPackage((TPackage) newChild);
return;
}
throw new RuntimeException("Not a child.");
}
}
| abstratt/textuml | plugins/com.abstratt.mdd.frontend.textuml.grammar/src-gen/com/abstratt/mdd/frontend/textuml/grammar/node/APackageVisibilityModifier.java | Java | epl-1.0 | 1,990 |
/*
Start of Program
*/
import javax.swing.*;
import java.awt.event.*;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
public class RacerStart extends JFrame
{
public static boolean gameFreaky = false;
public static boolean buttonState = false;
private boolean gameInProgress;
public static void main(String[] args)
{
RacerStart rs = new RacerStart();
}
/*
* Sound that is played only when the user crashes their car
*/
public void playSoundCrash()
{
try
{
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(this.getClass().getResource("boo.wav"));
Clip mp3Clip = AudioSystem.getClip();
mp3Clip.open(audioInputStream);
mp3Clip.start();
}
catch(Exception e)
{
System.out.println("ERROR" + e);
}
}
/*
* Creates the interface for the game
*/
public RacerStart()
{
int startCordX = 4;
int stopCordX = startCordX;
int stopCordY = Racer.SCREEN_HEIGHT - 81;
int startCordY = stopCordY - 34;
int freakyCordX = Racer.SCREEN_WIDTH - 142;
int freakyCordY = stopCordY;
LeaderBoard l = new LeaderBoard();
JFrame window = new JFrame();
Racer r = new Racer();
window.setTitle("Totally not a racing game");
window.setSize(Racer.SCREEN_WIDTH, Racer.SCREEN_HEIGHT);
window.setContentPane(r.getPanel());
window.setVisible(true);
window.setLayout(null);
window.setResizable(false);
window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JButton butStop = new JButton("STOP");
JButton butStart = new JButton("START");
JButton butFreaky = new JButton("FREAKY");
JLabel lblScoreDisplay = new JLabel(Integer.toString(r.getScore()));
lblScoreDisplay.setBounds(12, 12, 30, 10);
butStop.setBounds(stopCordX, stopCordY, 120, 30);
butStart.setBounds(startCordX, startCordY, 120, 30);
butFreaky.setBounds(freakyCordX, freakyCordY, 120, 30);
window.add(butStop);
window.add(butStart);
window.add(butFreaky);
window.add(lblScoreDisplay);
/*
* Action listeners for buttons
*/
butFreaky.addActionListener(e -> {
if(buttonState == false) // button looks normal
{
gameFreaky = true;
butFreaky.setBorder(BorderFactory.createLoweredBevelBorder());
buttonState = true;
}
else // button looks pressed
{
gameFreaky = false;
butFreaky.setBorder(null);
buttonState = false;
}
});
// Start and stop buttons
butStart.addActionListener(e -> {
r.start();
});
butStop.addActionListener(e -> {
r.stop();
});
gameInProgress = true;
r.start();
while(true)
{
if (r.hasCrashed() && gameInProgress)
{
r.stop();
l.showBoard();
playSoundCrash();
gameInProgress = false;
}
else if(!r.hasCrashed())
{
gameInProgress = true;
}
// Update the score as the game progresses
lblScoreDisplay.setText(Integer.toString(r.getScore()));
LeaderBoard.newScore = Integer.parseInt (lblScoreDisplay.getText());
r.update();
}
}
} | boyneg/GitLabLession | RacerStart.java | Java | epl-1.0 | 3,698 |
package me.chaopeng.chaosblog.utils.cli_utils;
import org.apache.commons.cli.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
/**
* 命令行参数类
*
* @author chao
*/
public class CliUtils {
private static final Logger logger = LoggerFactory.getLogger(CliUtils.class);
private static Options opts = new Options();
private static HashMap<String, CliOptionHandler> handlers = new HashMap<String, CliOptionHandler>();
public static void setOption(String opt, Boolean hasArg, String description, CliOptionHandler handler) {
opts.addOption(opt, hasArg, description);
handlers.put(opt, handler);
}
public static void parser(String[] args) {
CommandLineParser parser = new DefaultParser();
try {
CommandLine cl = parser.parse(opts, args);
Option[] options = cl.getOptions();
for (Option option : options) {
CliOptionHandler handler = handlers.get(option.getOpt());
if (handler != null) {
try {
handler.call(option.getValues());
} catch (CliException e) {
logger.error("!!!", e);
}
}
}
} catch (ParseException e) {
logger.error("!!!", e);
}
}
public static void help() {
HelpFormatter hf = new HelpFormatter();
hf.printHelp("Options", opts);
}
}
| chaopeng/chaosblog | src/main/java/me/chaopeng/chaosblog/utils/cli_utils/CliUtils.java | Java | epl-1.0 | 1,508 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on Jul 1, 2014
@author: anroco
I have a list in python and I want to invest the elements, ie the latter is the
first, how I can do?
Tengo una lista en python y quiero invertir los elementos de la lista, es
decir que el último sea el primero, ¿como puedo hacerlo?
'''
#create a list
lista = [9, 2, 5, 10, 9, 1, 3]
print (lista)
#reverses the order of the list
lista.reverse()
print (lista)
#create a list
lista = ['abc', 'a', 'bcd', 'c', 'bb', 'abcd']
print (lista)
#reverses the order of the list
lista.reverse()
print (lista)
| OxPython/Python_lists_reverse | src/reverse_lists.py | Python | epl-1.0 | 594 |
/*
* Note: this file is mostly a wrapper for the sun.net.ftp.FtpClient class.
*/
/*
* Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package net.ftp;
import java.net.*;
import java.io.*;
import java.util.Date;
import java.util.List;
import utils.ClassUtils;
import java.util.Iterator;
/**
* A class that implements the FTP protocol according to
* RFCs <A href="http://www.ietf.org/rfc/rfc0959.txt">959</A>,
* <A href="http://www.ietf.org/rfc/rfc2228.txt">2228</A>,
* <A href="http://www.ietf.org/rfc/rfc2389.txt">2389</A>,
* <A href="http://www.ietf.org/rfc/rfc2428.txt">2428</A>,
* <A href="http://www.ietf.org/rfc/rfc3659.txt">3659</A>,
* <A href="http://www.ietf.org/rfc/rfc4217.txt">4217</A>.
* Which includes support for FTP over SSL/TLS (aka ftps).
*
* {@code FtpClient} provides all the functionalities of a typical FTP
* client, like storing or retrieving files, listing or creating directories.
* A typical usage would consist of connecting the client to the server,
* log in, issue a few commands then logout.
* Here is a code example:
*
* <pre>
* FtpClient cl = FtpClient.create();
* cl.connect("ftp.gnu.org").login("anonymous", "john.doe@mydomain.com".toCharArray())).changeDirectory("pub/gnu");
* Iterator<FtpDirEntry> dir = cl.listFiles();
* while (dir.hasNext()) {
* FtpDirEntry f = dir.next();
* System.err.println(f.getName());
* }
* cl.close();
* }
* </pre>
* <p>
* <b>Error reporting:</b> There are, mostly, two families of errors that
* can occur during an FTP session. The first kind are the network related
* issues
* like a connection reset, and they are usually fatal to the session, meaning,
* in all likelyhood the connection to the server has been lost and the session
* should be restarted from scratch. These errors are reported by throwing an
* {@link IOException}. The second kind are the errors reported by the FTP
* server,
* like when trying to download a non-existing file for example. These errors
* are usually non fatal to the session, meaning more commands can be sent to
* the
* server. In these cases, a {@link FtpProtocolException} is thrown.
* </p>
* <p>
* It should be noted that this is not a thread-safe API, as it wouldn't make
* too much sense, due to the very sequential nature of FTP, to provide a
* client able to be manipulated from multiple threads.
*
* @since 1.7
*/
public class FtpClient
{
private static final String ftpClientClassName = "sun.net.ftp.impl.FtpClient";
private static final Class<?> ftpClientClass;
private static final String ftpDirEntryClassName = "sun.net.ftp.FtpDirEntry";
static final Class<?> ftpDirEntryClass;
static {
try{
ftpClientClass = Class.forName(ftpClientClassName);
ftpDirEntryClass = Class.forName(ftpDirEntryClassName);
}
catch(ClassNotFoundException e){
throw new InternalError(e);
}
}
private static final int FTP_PORT = 21;
// /**
// * Returns the default FTP port number.
// *
// * @return the port number.
// */
// public static final int defaultPort(){
// return FTP_PORT;
// }
/**
* Creates an instance of FtpClient and connects it to the specified
* address.
*
* @param dest the {@code InetSocketAddress} to connect to.
* @return The created {@code FtpClient}
* @throws IOException if the connection fails
* @see #connect(java.net.SocketAddress)
*/
public static FtpClient create(InetSocketAddress dest)
throws FtpProtocolException, IOException{
FtpClient client = create();
if(dest != null){
client.connect(dest);
}
return client;
}
/**
* Creates an instance of {@code FtpClient} and connects it to the
* specified host on the default FTP port.
*
* @param dest the {@code String} containing the name of the host
* to connect to.
* @return The created {@code FtpClient}
* @throws IOException if the connection fails.
* @throws FtpProtocolException if the server rejected the connection
*/
public static FtpClient create(String dest)
throws FtpProtocolException, IOException{
return create(new InetSocketAddress(dest, FTP_PORT));
}
/**
* Creates an instance of FtpClient. The client is not connected to any
* server yet.
*
*/
public static FtpClient create(){
return new FtpClient();
}
/**
* Creates an instance of FtpClient. The client is not connected to any
* server yet.
*
*/
protected FtpClient(){
try{
client = ClassUtils.invokeStaticMethod(ftpClientClass, "create");
}
catch(Exception e){
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Object client;
@SuppressWarnings("unchecked")
private <T,X extends Throwable> T invokeQualifiedMethod(String name, Object... refpairs) throws X{
return (T)normalize(ClassUtils.invokeMethod(ftpClientClass, this.client, name, refpairs));
}
private Object normalize(Object obj){
if(obj==null)
return null;
Class<?> cls = obj.getClass();
if(ftpClientClass.isAssignableFrom(cls)){
client = ftpClientClass.cast(obj);
return this;
}
else if(cls.getSimpleName().equals("FtpReplyCode")){
return ClassUtils.castEnumConstant(obj, FtpReplyCode.class);
}
else if(Iterator.class.isAssignableFrom(cls)){
try{
if(cls.getMethod("next").getReturnType().isAssignableFrom(ftpDirEntryClass)){
return new FtpFileIterator(Iterator.class.cast(obj));
}
}
catch(NoSuchMethodException | SecurityException e){
throw new InternalError(e);
}
}
return obj;
}
/**
* Transfers a file from the client to the server (aka a <I>put</I>)
* by sending the STOR command, and returns the {@code OutputStream}
* from the established data connection.
*
* A new file is created at the server site if the file specified does
* not already exist.
*
* {@link #completePending()} <b>has</b> to be called once the application
* is finished writing to the returned stream.
*
* @param name the name of the remote file to write.
* @return the {@link java.io.OutputStream} from the data connection or
* {@code null} if the command was unsuccessful.
* @throws IOException if an error occurred during the transmission.
* @throws FtpProtocolException if the command was rejected by the server
*/
public OutputStream putFileStream(String name)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("putFileStream", String.class, name);
}
/**
* Transfers a file from the client to the server (aka a <I>put</I>)
* by sending the STOR or STOU command, depending on the
* {@code unique} argument. The content of the {@code InputStream}
* passed in argument is written into the remote file, overwriting any
* existing data.
*
* A new file is created at the server site if the file specified does
* not already exist.
*
* If {@code unique} is set to {@code true}, the resultant file
* is to be created under a name unique to that directory, meaning
* it will not overwrite an existing file, instead the server will
* generate a new, unique, file name.
* The name of the remote file can be retrieved, after completion of the
* transfer, by calling {@link #getLastFileName()}.
*
* <p>
* This method will block until the transfer is complete or an exception
* is thrown.
* </p>
*
* @param name the name of the remote file to write.
* @param local the {@code InputStream} that points to the data to
* transfer.
* @return this FtpClient
* @throws IOException if an error occurred during the transmission.
* @throws FtpProtocolException if the command was rejected by the server
*/
public FtpClient putFile(String name, InputStream local)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("putFile", String.class, name, InputStream.class, local);
}
/**
* Changes the current transfer type to binary.
*
* @return This FtpClient
* @throws IOException if an error occurs during the transmission.
* @throws FtpProtocolException if the command was rejected by the server
*/
public FtpClient setBinaryType() throws FtpProtocolException, IOException{
return invokeQualifiedMethod("setBinaryType");
}
/**
* Changes the current transfer type to ascii.
*
* @return This FtpClient
* @throws IOException if an error occurs during the transmission.
* @throws FtpProtocolException if the command was rejected by the server
*/
public FtpClient setAsciiType() throws FtpProtocolException, IOException{
return invokeQualifiedMethod("setAsciiType");
}
/**
* Set the transfer mode to <I>passive</I>. In that mode, data connections
* are established by having the client connect to the server.
* This is the recommended default mode as it will work best through
* firewalls and NATs.
*
* @return This FtpClient
* @see #setActiveMode()
*/
public FtpClient enablePassiveMode(boolean passive){
return invokeQualifiedMethod("enablePassiveMode", boolean.class, passive);
}
/**
* Gets the current transfer mode.
*
* @return the current <code>FtpTransferMode</code>
*/
public boolean isPassiveModeEnabled(){
return invokeQualifiedMethod("isPassiveModeEnabled");
}
/**
* Sets the timeout value to use when connecting to the server,
*
* @param timeout the timeout value, in milliseconds, to use for the connect
* operation. A value of zero or less, means use the default timeout.
*
* @return This FtpClient
*/
public FtpClient setConnectTimeout(int timeout){
return invokeQualifiedMethod("setConnectTimeout", int.class, timeout);
}
/**
* Returns the current connection timeout value.
*
* @return the value, in milliseconds, of the current connect timeout.
* @see #setConnectTimeout(int)
*/
public int getConnectTimeout(){
return invokeQualifiedMethod("getConnectTimeout");
}
/**
* Sets the timeout value to use when reading from the server,
*
* @param timeout the timeout value, in milliseconds, to use for the read
* operation. A value of zero or less, means use the default timeout.
* @return This FtpClient
*/
public FtpClient setReadTimeout(int timeout){
return invokeQualifiedMethod("setReadTimeout", int.class, timeout);
}
/**
* Returns the current read timeout value.
*
* @return the value, in milliseconds, of the current read timeout.
* @see #setReadTimeout(int)
*/
public int getReadTimeout(){
return invokeQualifiedMethod("getReadTimeout");
}
/**
* Set the {@code Proxy} to be used for the next connection.
* If the client is already connected, it doesn't affect the current
* connection. However it is not recommended to change this during a
* session.
*
* @param p the {@code Proxy} to use, or {@code null} for no proxy.
* @return This FtpClient
*/
public FtpClient setProxy(Proxy p){
return invokeQualifiedMethod("setProxy", Proxy.class, p);
}
/**
* Get the proxy of this FtpClient
*
* @return the <code>Proxy</code>, this client is using, or
* <code>null</code>
* if none is used.
* @see #setProxy(Proxy)
*/
public Proxy getProxy(){
return invokeQualifiedMethod("getProxy");
}
/**
* Tests whether this client is connected or not to a server.
*
* @return <code>true</code> if the client is connected.
*/
public boolean isConnected(){
return invokeQualifiedMethod("isConnected");
}
/**
* Retrieves the address of the FTP server this client is connected to.
*
* @return the {@link SocketAddress} of the server, or {@code null} if this
* client is not connected yet.
*/
public SocketAddress getServerAddress(){
return invokeQualifiedMethod("getServerAddress");
}
/**
* Connects the {@code FtpClient} to the specified destination server.
*
* @param dest the address of the destination server
* @return this FtpClient
* @throws IOException if connection failed.
* @throws SecurityException if there is a SecurityManager installed and it
* denied the authorization to connect to the destination.
* @throws FtpProtocolException
*/
public FtpClient connect(SocketAddress dest)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("connect", SocketAddress.class, dest);
}
/**
* Connects the FtpClient to the specified destination.
*
* @param dest the address of the destination server
* @throws IOException if connection failed.
*/
public FtpClient connect(SocketAddress dest, int timeout)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("connect", SocketAddress.class, dest, int.class, timeout);
}
/**
* Attempts to log on the server with the specified user name and password.
*
* @param user The user name
* @param password The password for that user
* @return <code>true</code> if the login was successful.
* @throws IOException if an error occurred during the transmission
*/
public FtpClient login(String user, char[] password)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("login", String.class, user, char[].class, password);
}
/**
* Attempts to log on the server with the specified user name, password and
* account name.
*
* @param user The user name
* @param password The password for that user.
* @param account The account name for that user.
* @return <code>true</code> if the login was successful.
* @throws IOException if an error occurs during the transmission.
*/
public FtpClient login(String user, char[] password, String account)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("login", String.class, user, char[].class, password, String.class, account);
}
/**
* Logs out the current user. This is in effect terminates the current
* session and the connection to the server will be closed.
*
*/
public void close() throws IOException{
invokeQualifiedMethod("close");
}
/**
* Checks whether the client is logged in to the server or not.
*
* @return <code>true</code> if the client has already completed a login.
*/
public boolean isLoggedIn(){
return invokeQualifiedMethod("isLoggedIn");
}
/**
* Changes to a specific directory on a remote FTP server
*
* @param remoteDirectory path of the directory to CD to.
* @return <code>true</code> if the operation was successful.
* @exception <code>FtpProtocolException</code>
*/
public FtpClient changeDirectory(String remoteDirectory)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("changeDirectory", String.class, remoteDirectory);
}
/**
* Changes to the parent directory, sending the CDUP command to the server.
*
* @return <code>true</code> if the command was successful.
* @throws IOException
*/
public FtpClient changeToParentDirectory()
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("changeToParentDirectory");
}
/**
* Returns the server current working directory, or <code>null</code> if
* the PWD command failed.
*
* @return a <code>String</code> containing the current working directory,
* or <code>null</code>
* @throws IOException
*/
public String getWorkingDirectory()
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("getWorkingDirectory");
}
/**
* Sets the restart offset to the specified value. That value will be
* sent through a <code>REST</code> command to server before a file
* transfer and has the effect of resuming a file transfer from the
* specified point. After a transfer the restart offset is set back to
* zero.
*
* @param offset the offset in the remote file at which to start the next
* transfer. This must be a value greater than or equal to zero.
* @throws IllegalArgumentException if the offset is negative.
*/
public FtpClient setRestartOffset(long offset){
return invokeQualifiedMethod("setRestartOffset", long.class, offset);
}
/**
* Retrieves a file from the ftp server and writes it to the specified
* <code>OutputStream</code>.
* If the restart offset was set, then a <code>REST</code> command will be
* sent before the RETR in order to restart the tranfer from the specified
* offset.
* The <code>OutputStream</code> is not closed by this method at the end
* of the transfer.
*
* @param name a <code>String<code> containing the name of the file to
* retreive from the server.
* @param local the <code>OutputStream</code> the file should be written to.
* @throws IOException if the transfer fails.
*/
public FtpClient getFile(String name, OutputStream local)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("getFile", String.class, name, OutputStream.class, local);
}
/**
* Retrieves a file from the ftp server, using the RETR command, and
* returns the InputStream from* the established data connection.
* {@link #completePending()} <b>has</b> to be called once the application
* is done reading from the returned stream.
*
* @param name the name of the remote file
* @return the {@link java.io.InputStream} from the data connection, or
* <code>null</code> if the command was unsuccessful.
* @throws IOException if an error occurred during the transmission.
*/
public InputStream getFileStream(String name)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("getFileStream", String.class, name);
}
/**
* Transfers a file from the client to the server (aka a <I>put</I>)
* by sending the STOR or STOU command, depending on the
* <code>unique</code> argument, and returns the <code>OutputStream</code>
* from the established data connection.
* {@link #completePending()} <b>has</b> to be called once the application
* is finished writing to the stream.
*
* A new file is created at the server site if the file specified does
* not already exist.
*
* If <code>unique</code> is set to <code>true</code>, the resultant file
* is to be created under a name unique to that directory, meaning
* it will not overwrite an existing file, instead the server will
* generate a new, unique, file name.
* The name of the remote file can be retrieved, after completion of the
* transfer, by calling {@link #getLastFileName()}.
*
* @param name the name of the remote file to write.
* @param unique <code>true</code> if the remote files should be unique,
* in which case the STOU command will be used.
* @return the {@link java.io.OutputStream} from the data connection or
* <code>null</code> if the command was unsuccessful.
* @throws IOException if an error occurred during the transmission.
*/
public OutputStream putFileStream(String name, boolean unique)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("putFileStream", String.class, name, boolean.class, unique);
}
/**
* Transfers a file from the client to the server (aka a <I>put</I>)
* by sending the STOR command. The content of the <code>InputStream</code>
* passed in argument is written into the remote file, overwriting any
* existing data.
*
* A new file is created at the server site if the file specified does
* not already exist.
*
* @param name the name of the remote file to write.
* @param local the <code>InputStream</code> that points to the data to
* transfer.
* @param unique <code>true</code> if the remote file should be unique
* (i.e. not already existing), <code>false</code> otherwise.
* @return <code>true</code> if the transfer was successful.
* @throws IOException if an error occurred during the transmission.
* @see #getLastFileName()
*/
public FtpClient putFile(String name, InputStream local, boolean unique)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("putFile", String.class, name, InputStream.class, local, boolean.class, unique);
}
/**
* Sends the APPE command to the server in order to transfer a data stream
* passed in argument and append it to the content of the specified remote
* file.
*
* @param name A <code>String</code> containing the name of the remote file
* to append to.
* @param local The <code>InputStream</code> providing access to the data
* to be appended.
* @return <code>true</code> if the transfer was successful.
* @throws IOException if an error occurred during the transmission.
*/
public FtpClient appendFile(String name, InputStream local)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("appendFile", String.class, name, InputStream.class, local);
}
/**
* Renames a file on the server.
*
* @param from the name of the file being renamed
* @param to the new name for the file
* @throws IOException if the command fails
*/
public FtpClient rename(String from, String to)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("rename", String.class, from, String.class, to);
}
/**
* Deletes a file on the server.
*
* @param name a <code>String</code> containing the name of the file
* to delete.
* @return <code>true</code> if the command was successful
* @throws IOException if an error occurred during the exchange
*/
public FtpClient deleteFile(String name)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("deleteFile", String.class, name);
}
/**
* Creates a new directory on the server.
*
* @param name a <code>String</code> containing the name of the directory
* to create.
* @return <code>true</code> if the operation was successful.
* @throws IOException if an error occurred during the exchange
*/
public FtpClient makeDirectory(String name)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("makeDirectory", String.class, name);
}
/**
* Removes a directory on the server.
*
* @param name a <code>String</code> containing the name of the directory
* to remove.
*
* @return <code>true</code> if the operation was successful.
* @throws IOException if an error occurred during the exchange.
*/
public FtpClient removeDirectory(String name)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("removeDirectory", String.class, name);
}
/**
* Sends a No-operation command. It's useful for testing the connection
* status or as a <I>keep alive</I> mechanism.
*
* @throws FtpProtocolException if the command fails
*/
public FtpClient noop()
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("noop");
}
/**
* Sends the STAT command to the server.
* This can be used while a data connection is open to get a status
* on the current transfer, in that case the parameter should be
* <code>null</code>.
* If used between file transfers, it may have a pathname as argument
* in which case it will work as the LIST command except no data
* connection will be created.
*
* @param name an optional <code>String</code> containing the pathname
* the STAT command should apply to.
* @return the response from the server or <code>null</code> if the
* command failed.
* @throws IOException if an error occurred during the transmission.
*/
public String getStatus(String name)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("getStatus", String.class, name);
}
/**
* Sends the FEAT command to the server and returns the list of supported
* features in the form of strings.
*
* The features are the supported commands, like AUTH TLS, PROT or PASV.
* See the RFCs for a complete list.
*
* Note that not all FTP servers support that command, in which case
* the method will return <code>null</code>
*
* @return a <code>List</code> of <code>Strings</code> describing the
* supported additional features, or <code>null</code>
* if the command is not supported.
* @throws IOException if an error occurs during the transmission.
*/
public List<String> getFeatures()
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("getFeatures");
}
/**
* sends the ABOR command to the server.
* It tells the server to stop the previous command or transfer.
*
* @return <code>true</code> if the command was successful.
* @throws IOException if an error occurred during the transmission.
*/
public FtpClient abort()
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("abort");
}
/**
* Some methods do not wait until completion before returning, so this
* method can be called to wait until completion. This is typically the case
* with commands that trigger a transfer like {@link #getFileStream(String)}
* .
* So this method should be called before accessing information related to
* such a command.
* <p>
* This method will actually block reading on the command channel for a
* notification from the server that the command is finished. Such a
* notification often carries extra information concerning the completion
* of the pending action (e.g. number of bytes transfered).
* </p>
* <p>
* Note that this will return true immediately if no command or action
* is pending
* </p>
* <p>
* It should be also noted that most methods issuing commands to the ftp
* server will call this method if a previous command is pending.
* <p>
* Example of use:
*
* <pre>
* InputStream in = cl.getFileStream("file");
* ...
* cl.completePending();
* long size = cl.getLastTransferSize();
* </pre>
*
* On the other hand, it's not necessary in a case like:
*
* <pre>
* InputStream in = cl.getFileStream("file");
* // read content
* ...
* cl.logout();
* </pre>
* <p>
* Since {@link #logout()} will call completePending() if necessary.
* </p>
*
* @return <code>true</code> if the completion was successful or if no
* action was pending.
* @throws IOException
*/
public FtpClient completePending()
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("completePending");
}
/**
* Reinitializes the USER parameters on the FTP server
*
* @throws FtpProtocolException if the command fails
*/
public FtpClient reInit()
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("reInit");
}
/**
* Issues a LIST command to the server to get the current directory
* listing, and returns the InputStream from the data connection.
* {@link #completePending()} <b>has</b> to be called once the application
* is finished writing to the stream.
*
* @param path the pathname of the directory to list, or <code>null</code>
* for the current working directory.
* @return the <code>InputStream</code> from the resulting data connection
* @throws IOException if an error occurs during the transmission.
* @see #changeDirectory(String)
* @see #listFiles(String)
*/
public InputStream list(String path)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("list", String.class, path);
}
/**
* Issues a NLST path command to server to get the specified directory
* content. It differs from {@link #list(String)} method by the fact that
* it will only list the file names which would make the parsing of the
* somewhat easier.
*
* {@link #completePending()} <b>has</b> to be called once the application
* is finished writing to the stream.
*
* @param path a <code>String</code> containing the pathname of the
* directory to list or <code>null</code> for the current working
* directory.
* @return the <code>InputStream</code> from the resulting data connection
* @throws IOException if an error occurs during the transmission.
*/
public InputStream nameList(String path)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("nameList", String.class, path);
}
/**
* Issues the SIZE [path] command to the server to get the size of a
* specific file on the server.
* Note that this command may not be supported by the server. In which
* case -1 will be returned.
*
* @param path a <code>String</code> containing the pathname of the
* file.
* @return a <code>long</code> containing the size of the file or -1 if
* the server returned an error, which can be checked with
* {@link #getLastReplyCode()}.
* @throws IOException if an error occurs during the transmission.
*/
public long getSize(String path)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("getSize", String.class, path);
}
/**
* Issues the MDTM [path] command to the server to get the modification
* time of a specific file on the server.
* Note that this command may not be supported by the server, in which
* case <code>null</code> will be returned.
*
* @param path a <code>String</code> containing the pathname of the file.
* @return a <code>Date</code> representing the last modification time
* or <code>null</code> if the server returned an error, which
* can be checked with {@link #getLastReplyCode()}.
* @throws IOException if an error occurs during the transmission.
*/
public Date getLastModified(String path)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("getLastModified", String.class, path);
}
/**
* Issues a MLSD command to the server to get the specified directory
* listing and applies the current parser to create an Iterator of
* {@link java.net.ftp.FtpDirEntry}. Note that the Iterator returned is also
* a
* {@link java.io.Closeable}.
* If the server doesn't support the MLSD command, the LIST command is used
* instead.
*
* {@link #completePending()} <b>has</b> to be called once the application
* is finished iterating through the files.
*
* @param path the pathname of the directory to list or <code>null</code>
* for the current working directoty.
* @return a <code>Iterator</code> of files or <code>null</code> if the
* command failed.
* @throws IOException if an error occurred during the transmission
* @see #setDirParser(FtpDirParser)
* @see #changeDirectory(String)
*/
public Iterator<FtpDirEntry> listFiles(String path)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("listFiles", String.class, path);
}
/**
* Attempts to use Kerberos GSSAPI as an authentication mechanism with the
* ftp server. This will issue an <code>AUTH GSSAPI</code> command, and if
* it is accepted by the server, will followup with <code>ADAT</code>
* command to exchange the various tokens until authentification is
* successful. This conforms to Appendix I of RFC 2228.
*
* @return <code>true</code> if authentication was successful.
* @throws IOException if an error occurs during the transmission.
*/
public FtpClient useKerberos()
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("useKerberos");
}
/**
* Returns the Welcome string the server sent during initial connection.
*
* @return a <code>String</code> containing the message the server
* returned during connection or <code>null</code>.
*/
public String getWelcomeMsg(){
return invokeQualifiedMethod("getWelcomeMsg");
}
/**
* Returns the last reply code sent by the server.
*
* @return the lastReplyCode
*/
public FtpReplyCode getLastReplyCode(){
return invokeQualifiedMethod("getLastReplyCode");
}
/**
* Returns the last response string sent by the server.
*
* @return the message string, which can be quite long, last returned
* by the server.
*/
public String getLastResponseString(){
return invokeQualifiedMethod("getLastResponseString");
}
/**
* Returns, when available, the size of the latest started transfer.
* This is retreived by parsing the response string received as an initial
* response to a RETR or similar request.
*
* @return the size of the latest transfer or -1 if either there was no
* transfer or the information was unavailable.
*/
public long getLastTransferSize(){
return invokeQualifiedMethod("getLastTransferSize");
}
/**
* Returns, when available, the remote name of the last transfered file.
* This is mainly useful for "put" operation when the unique flag was
* set since it allows to recover the unique file name created on the
* server which may be different from the one submitted with the command.
*
* @return the name the latest transfered file remote name, or
* <code>null</code> if that information is unavailable.
*/
public String getLastFileName(){
return invokeQualifiedMethod("getLastFileName");
}
/**
* Attempts to switch to a secure, encrypted connection. This is done by
* sending the "AUTH TLS" command.
* <p>
* See <a href="http://www.ietf.org/rfc/rfc4217.txt">RFC 4217</a>
* </p>
* If successful this will establish a secure command channel with the
* server, it will also make it so that all other transfers (e.g. a RETR
* command) will be done over an encrypted channel as well unless a
* {@link #reInit()} command or a {@link #endSecureSession()} command is
* issued.
*
* @return <code>true</code> if the operation was successful.
* @throws IOException if an error occurred during the transmission.
* @see #endSecureSession()
*/
public FtpClient startSecureSession()
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("startSecureSession");
}
/**
* Sends a <code>CCC</code> command followed by a <code>PROT C</code>
* command to the server terminating an encrypted session and reverting
* back to a non crypted transmission.
*
* @return <code>true</code> if the operation was successful.
* @throws IOException if an error occurred during transmission.
* @see #startSecureSession()
*/
public FtpClient endSecureSession()
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("endSecureSession");
}
/**
* Sends the "Allocate" (ALLO) command to the server telling it to
* pre-allocate the specified number of bytes for the next transfer.
*
* @param size The number of bytes to allocate.
* @return <code>true</code> if the operation was successful.
* @throws IOException if an error occurred during the transmission.
*/
public FtpClient allocate(long size)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("allocate", long.class, size);
}
/**
* Sends the "Structure Mount" (SMNT) command to the server. This let the
* user mount a different file system data structure without altering his
* login or accounting information.
*
* @param struct a <code>String</code> containing the name of the
* structure to mount.
* @return <code>true</code> if the operation was successful.
* @throws IOException if an error occurred during the transmission.
*/
public FtpClient structureMount(String struct)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("structureMount", String.class, struct);
}
/**
* Sends a SYST (System) command to the server and returns the String
* sent back by the server describing the operating system at the
* server.
*
* @return a <code>String</code> describing the OS, or <code>null</code>
* if the operation was not successful.
* @throws IOException if an error occurred during the transmission.
*/
public String getSystem()
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("getSystem");
}
/**
* Sends the HELP command to the server, with an optional command, like
* SITE, and returns the text sent back by the server.
*
* @param cmd the command for which the help is requested or
* <code>null</code> for the general help
* @return a <code>String</code> containing the text sent back by the
* server, or <code>null</code> if the command failed.
* @throws IOException if an error occurred during transmission
*/
public String getHelp(String cmd)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("getHelp", String.class, cmd);
}
/**
* Sends the SITE command to the server. This is used by the server
* to provide services specific to his system that are essential
* to file transfer.
*
* @param cmd the command to be sent.
* @return <code>true</code> if the command was successful.
* @throws IOException if an error occurred during transmission
*/
public FtpClient siteCmd(String cmd)
throws FtpProtocolException, IOException{
return invokeQualifiedMethod("siteCmd", String.class, cmd);
}
private class FtpFileIterator implements Iterator<FtpDirEntry>, Closeable{
private final Iterator<?> it;
FtpFileIterator(Iterator<?> it){
if(!Closeable.class.isAssignableFrom(it.getClass()))
throw new InternalError("Argument \"it\" does not implement Closeable!");
this.it=it;
}
public void close() throws IOException{
Closeable.class.cast(it).close();
}
public boolean hasNext(){
return it.hasNext();
}
public FtpDirEntry next(){
return new FtpDirEntry(it.next());
}
public void remove(){
it.remove();
}
}
}
| JonahSloan/Advanced-Java-Tools | src/net/ftp/FtpClient.java | Java | epl-1.0 | 38,154 |
/*******************************************************************************
* Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.models.weaving;
// J2SE imports
import java.io.Serializable;
// Persistence imports
import javax.persistence.*;
import static javax.persistence.GenerationType.*;
@Entity
@Table(name="SIMPLE")
public class SimpleObject implements Serializable {
// ensure we have at least one of each type of primitive
private int version;
private boolean booleanAttribute;
private char charAttribute;
private byte byteAttribute;
private short shortAttribute;
private long longAttribute;
private float floatAttribute;
private double doubleAttribute;
// have some objects, too
private Integer id; // PK
private String name;
private SimpleAggregate simpleAggregate;
public SimpleObject () {
}
@Id
@GeneratedValue(strategy=TABLE, generator="SIMPLE_TABLE_GENERATOR")
@TableGenerator(
name="SIMPLE_TABLE_GENERATOR",
table="SIMPLE_SEQ",
pkColumnName="SEQ_NAME",
valueColumnName="SEQ_COUNT",
pkColumnValue="SIMPLE_SEQ"
)
@Column(name="ID")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Version
@Column(name="VERSION")
public int getVersion() {
return version;
}
protected void setVersion(int version) {
this.version = version;
}
@Column(name="NAME", length=80)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isBooleanAttribute() {
return booleanAttribute;
}
public void setBooleanAttribute(boolean booleanAttribute) {
this.booleanAttribute = booleanAttribute;
}
public byte getByteAttribute() {
return byteAttribute;
}
public void setByteAttribute(byte byteAttribute) {
this.byteAttribute = byteAttribute;
}
public char getCharAttribute() {
return charAttribute;
}
public void setCharAttribute(char charAttribute) {
this.charAttribute = charAttribute;
}
public double getDoubleAttribute() {
return doubleAttribute;
}
public void setDoubleAttribute(double doubleAttribute) {
this.doubleAttribute = doubleAttribute;
}
public float getFloatAttribute() {
return floatAttribute;
}
public void setFloatAttribute(float floatAttribute) {
this.floatAttribute = floatAttribute;
}
public long getLongAttribute() {
return longAttribute;
}
public void setLongAttribute(long longAttribute) {
this.longAttribute = longAttribute;
}
public short getShortAttribute() {
return shortAttribute;
}
public void setShortAttribute(short shortAttribute) {
this.shortAttribute = shortAttribute;
}
@Embedded()
public SimpleAggregate getSimpleAggregate() {
return simpleAggregate;
}
public void setSimpleAggregate(SimpleAggregate simpleAggregate) {
this.simpleAggregate = simpleAggregate;
}
}
| bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | jpa/eclipselink.jpa.test/src/org/eclipse/persistence/testing/models/weaving/SimpleObject.java | Java | epl-1.0 | 3,716 |
/**
* Copyright (c) 2015 SK holdings Co., Ltd. All rights reserved.
* This software is the confidential and proprietary information of SK holdings.
* 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 SK holdings.
* (http://www.eclipse.org/legal/epl-v10.html)
*/
package nexcore.tool.uml.ui.analysis.activitydiagram.command;
import java.util.ArrayList;
import java.util.List;
import nexcore.tool.uml.manager.UMLManager;
import nexcore.tool.uml.model.umldiagram.AbstractConnection;
import nexcore.tool.uml.model.umldiagram.AbstractNode;
import nexcore.tool.uml.model.umldiagram.ContainerNode;
import nexcore.tool.uml.model.umldiagram.Diagram;
import nexcore.tool.uml.model.umldiagram.NodeType;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.commands.Command;
/**
* <ul>
* <li>업무 그룹명 : nexcore.tool.uml.ui.analysis</li>
* <li>서브 업무명 : nexcore.tool.uml.ui.analysis.activitydiagram.command</li>
* <li>설 명 : DeleteActivityPartitionNodeCommand</li>
* <li>작성일 : 2011. 7. 12.</li>
* <li>작성자 : Kang</li>
* </ul>
*/
public class DeleteActivityPartitionNodeCommand extends Command {
/**
* parent
*/
private AbstractNode parent;
/**
* 삭제할 노드
*/
private ContainerNode node;
/**
* @see org.eclipse.gef.commands.Command#execute()
*/
public void execute() {
Diagram diagram = null;
if( parent instanceof Diagram ) {
diagram = (Diagram) parent;
}
if( null == diagram ) {
return;
}
List<AbstractNode> nodeList = new ArrayList<AbstractNode>();
nodeList = node.getNodeList();
List<AbstractConnection> incomingList = new ArrayList<AbstractConnection>();
List<AbstractConnection> outgoingList = new ArrayList<AbstractConnection>();
List<ContainerNode> partitionList = new ArrayList<ContainerNode>();
for( AbstractNode abstractNode : nodeList ) {
incomingList.addAll( abstractNode.getIncomingConnectionList() );
outgoingList.addAll( abstractNode.getOutgoingConnectionList() );
}
for( AbstractConnection connection : incomingList ) {
diagram.getConnectionList().remove(connection);
node.getConnectionList().remove(connection);
UMLManager.deleteElement(connection.getUmlModel());
UMLManager.deleteElement(connection);
AbstractNode sourceNode = (AbstractNode) connection.getSource();
sourceNode.getOutgoingConnectionList().remove(connection);
}
for( AbstractConnection connection : outgoingList ) {
diagram.getConnectionList().remove(connection);
node.getConnectionList().remove(connection);
UMLManager.deleteElement(connection.getUmlModel());
UMLManager.deleteElement(connection);
AbstractNode targetNode = (AbstractNode) connection.getTarget();
targetNode.getIncomingConnectionList().remove(connection);
}
for( int i = nodeList.size() - 1; i >= 0; i-- ) {
AbstractNode abstractNode = nodeList.get(i);
diagram.getNodeList().remove(abstractNode);
node.getNodeList().remove(abstractNode);
UMLManager.deleteElement(abstractNode.getUmlModel());
UMLManager.deleteElement(abstractNode);
}
for( AbstractNode abstractNode : diagram.getNodeList() ) {
if( abstractNode instanceof ContainerNode ) {
ContainerNode containerNode = (ContainerNode) abstractNode;
if( NodeType.ACTIVITY_PARTITION.equals(containerNode.getNodeType()) ) {
partitionList.add(containerNode);
}
}
}
Rectangle bounds = new Rectangle();
bounds.setLocation( node.getX(), node.getY() );
bounds.setSize( node.getWidth(), node.getHeight() );
int indexOfCurrentNode = partitionList.indexOf(node);
UMLManager.deleteElement(node.getUmlModel());
UMLManager.deleteElement(node);
if( partitionList.size() - 1 != indexOfCurrentNode ) {
ContainerNode nextContainerNode = partitionList.get( indexOfCurrentNode + 1 );
nextContainerNode.setX(bounds.x);
nextContainerNode.setWidth( nextContainerNode.getWidth() + bounds.width );
}
}
/**
* @return the parent
*/
public AbstractNode getParent() {
return parent;
}
/**
* 삭제 액션 Diagram 설정
*
* @param model
* void
*/
public void setParent(Object model) {
if (model instanceof AbstractNode) {
parent = (AbstractNode) model;
} else {
parent = null;
}
}
/**
* 삭제할 node 반환
*
* @return the node
*/
public AbstractNode getNode() {
return node;
}
/**
* 삭제될 node 저장.
*
* @param model
* void
*/
public void setNode(Object model) {
if (model instanceof AbstractNode) {
node = (ContainerNode) model;
} else {
node = null;
}
}
}
| SK-HOLDINGS-CC/NEXCORE-UML-Modeler | nexcore.tool.uml.ui.analysis/src/java/nexcore/tool/uml/ui/analysis/activitydiagram/command/DeleteActivityPartitionNodeCommand.java | Java | epl-1.0 | 5,600 |
/*
* Copyright (C) 2010, Google Inc.
* and other copyright owners as documented in the project's IP log.
*
* This program and the accompanying materials are made available
* under the terms of the Eclipse Distribution License v1.0 which
* accompanies this distribution, is reproduced below, and is
* available at http://www.eclipse.org/org/documents/edl-v10.php
*
* 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 Eclipse Foundation, 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.
*/
package org.jboss.forge.jgit.util;
/**
* Utility class for character functions on raw bytes
* <p>
* Characters are assumed to be 8-bit US-ASCII.
*/
public class RawCharUtil {
private static final boolean[] WHITESPACE = new boolean[256];
static {
WHITESPACE['\r'] = true;
WHITESPACE['\n'] = true;
WHITESPACE['\t'] = true;
WHITESPACE[' '] = true;
}
/**
* Determine if an 8-bit US-ASCII encoded character is represents whitespace
*
* @param c
* the 8-bit US-ASCII encoded character
* @return true if c represents a whitespace character in 8-bit US-ASCII
*/
public static boolean isWhitespace(byte c) {
return WHITESPACE[c & 0xff];
}
/**
* Returns the new end point for the byte array passed in after trimming any
* trailing whitespace characters, as determined by the isWhitespace()
* function. start and end are assumed to be within the bounds of raw.
*
* @param raw
* the byte array containing the portion to trim whitespace for
* @param start
* the start of the section of bytes
* @param end
* the end of the section of bytes
* @return the new end point
*/
public static int trimTrailingWhitespace(byte[] raw, int start, int end) {
int ptr = end - 1;
while (start <= ptr && isWhitespace(raw[ptr]))
ptr--;
return ptr + 1;
}
/**
* Returns the new start point for the byte array passed in after trimming
* any leading whitespace characters, as determined by the isWhitespace()
* function. start and end are assumed to be within the bounds of raw.
*
* @param raw
* the byte array containing the portion to trim whitespace for
* @param start
* the start of the section of bytes
* @param end
* the end of the section of bytes
* @return the new start point
*/
public static int trimLeadingWhitespace(byte[] raw, int start, int end) {
while (start < end && isWhitespace(raw[start]))
start++;
return start;
}
private RawCharUtil() {
// This will never be called
}
}
| forge/plugin-undo | src/main/jgit/org/jboss/forge/jgit/util/RawCharUtil.java | Java | epl-1.0 | 3,984 |
/**
* Copyright (c) 2017 Inria
*
* 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:
* - Faiez Zalila <faiez.zalila@inria.fr>
*/
package org.eclipse.cmf.occi.core.presentation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.StringTokenizer;
import org.eclipse.emf.common.CommonPlugin;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.edit.ui.provider.ExtendedImageRegistry;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.dialogs.WizardNewFileCreationPage;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.part.ISetSelectionTarget;
import org.eclipse.cmf.occi.core.OCCIFactory;
import org.eclipse.cmf.occi.core.OCCIPackage;
import org.eclipse.cmf.occi.core.provider.OCCIEditPlugin;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
/**
* This is a simple wizard for creating a new model file.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class OCCIModelWizard extends Wizard implements INewWizard {
/**
* The supported extensions for created files.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final List<String> FILE_EXTENSIONS =
Collections.unmodifiableList(Arrays.asList(OCCIEditorPlugin.INSTANCE.getString("_UI_OCCIEditorFilenameExtensions").split("\\s*,\\s*")));
/**
* A formatted list of supported file extensions, suitable for display.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final String FORMATTED_FILE_EXTENSIONS =
OCCIEditorPlugin.INSTANCE.getString("_UI_OCCIEditorFilenameExtensions").replaceAll("\\s*,\\s*", ", ");
/**
* This caches an instance of the model package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected OCCIPackage occiPackage = OCCIPackage.eINSTANCE;
/**
* This caches an instance of the model factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected OCCIFactory occiFactory = occiPackage.getOCCIFactory();
/**
* This is the file creation page.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected OCCIModelWizardNewFileCreationPage newFileCreationPage;
/**
* This is the initial object creation page.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected OCCIModelWizardInitialObjectCreationPage initialObjectCreationPage;
/**
* Remember the selection during initialization for populating the default container.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IStructuredSelection selection;
/**
* Remember the workbench during initialization.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IWorkbench workbench;
/**
* Caches the names of the types that can be created as the root object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected List<String> initialObjectNames;
/**
* This just records the information.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void init(IWorkbench workbench, IStructuredSelection selection) {
this.workbench = workbench;
this.selection = selection;
setWindowTitle(OCCIEditorPlugin.INSTANCE.getString("_UI_Wizard_label"));
setDefaultPageImageDescriptor(ExtendedImageRegistry.INSTANCE.getImageDescriptor(OCCIEditorPlugin.INSTANCE.getImage("full/wizban/NewOCCI")));
}
/**
* Returns the names of the types that can be created as the root object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Collection<String> getInitialObjectNames() {
if (initialObjectNames == null) {
initialObjectNames = new ArrayList<String>();
for (EClassifier eClassifier : occiPackage.getEClassifiers()) {
if (eClassifier instanceof EClass) {
EClass eClass = (EClass)eClassifier;
if (!eClass.isAbstract()) {
initialObjectNames.add(eClass.getName());
}
}
}
Collections.sort(initialObjectNames, CommonPlugin.INSTANCE.getComparator());
}
return initialObjectNames;
}
/**
* Create a new model.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected EObject createInitialModel() {
EClass eClass = (EClass)occiPackage.getEClassifier(initialObjectCreationPage.getInitialObjectName());
EObject rootObject = occiFactory.create(eClass);
return rootObject;
}
/**
* Do the work after everything is specified.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean performFinish() {
try {
// Remember the file.
//
final IFile modelFile = getModelFile();
// Do the work within an operation.
//
WorkspaceModifyOperation operation =
new WorkspaceModifyOperation() {
@Override
protected void execute(IProgressMonitor progressMonitor) {
try {
// Create a resource set
//
ResourceSet resourceSet = new ResourceSetImpl();
// Get the URI of the model file.
//
URI fileURI = URI.createPlatformResourceURI(modelFile.getFullPath().toString(), true);
// Create a resource for this file.
//
Resource resource = resourceSet.createResource(fileURI);
// Add the initial model object to the contents.
//
EObject rootObject = createInitialModel();
if (rootObject != null) {
resource.getContents().add(rootObject);
}
// Save the contents of the resource to the file system.
//
Map<Object, Object> options = new HashMap<Object, Object>();
options.put(XMLResource.OPTION_ENCODING, initialObjectCreationPage.getEncoding());
resource.save(options);
}
catch (Exception exception) {
OCCIEditorPlugin.INSTANCE.log(exception);
}
finally {
progressMonitor.done();
}
}
};
getContainer().run(false, false, operation);
// Select the new file resource in the current view.
//
IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
IWorkbenchPage page = workbenchWindow.getActivePage();
final IWorkbenchPart activePart = page.getActivePart();
if (activePart instanceof ISetSelectionTarget) {
final ISelection targetSelection = new StructuredSelection(modelFile);
getShell().getDisplay().asyncExec
(new Runnable() {
public void run() {
((ISetSelectionTarget)activePart).selectReveal(targetSelection);
}
});
}
// Open an editor on the new file.
//
try {
page.openEditor
(new FileEditorInput(modelFile),
workbench.getEditorRegistry().getDefaultEditor(modelFile.getFullPath().toString()).getId());
}
catch (PartInitException exception) {
MessageDialog.openError(workbenchWindow.getShell(), OCCIEditorPlugin.INSTANCE.getString("_UI_OpenEditorError_label"), exception.getMessage());
return false;
}
return true;
}
catch (Exception exception) {
OCCIEditorPlugin.INSTANCE.log(exception);
return false;
}
}
/**
* This is the one page of the wizard.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class OCCIModelWizardNewFileCreationPage extends WizardNewFileCreationPage {
/**
* Pass in the selection.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public OCCIModelWizardNewFileCreationPage(String pageId, IStructuredSelection selection) {
super(pageId, selection);
}
/**
* The framework calls this to see if the file is correct.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected boolean validatePage() {
if (super.validatePage()) {
String extension = new Path(getFileName()).getFileExtension();
if (extension == null || !FILE_EXTENSIONS.contains(extension)) {
String key = FILE_EXTENSIONS.size() > 1 ? "_WARN_FilenameExtensions" : "_WARN_FilenameExtension";
setErrorMessage(OCCIEditorPlugin.INSTANCE.getString(key, new Object [] { FORMATTED_FILE_EXTENSIONS }));
return false;
}
return true;
}
return false;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public IFile getModelFile() {
return ResourcesPlugin.getWorkspace().getRoot().getFile(getContainerFullPath().append(getFileName()));
}
}
/**
* This is the page where the type of object to create is selected.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class OCCIModelWizardInitialObjectCreationPage extends WizardPage {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Combo initialObjectField;
/**
* @generated
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*/
protected List<String> encodings;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Combo encodingField;
/**
* Pass in the selection.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public OCCIModelWizardInitialObjectCreationPage(String pageId) {
super(pageId);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE); {
GridLayout layout = new GridLayout();
layout.numColumns = 1;
layout.verticalSpacing = 12;
composite.setLayout(layout);
GridData data = new GridData();
data.verticalAlignment = GridData.FILL;
data.grabExcessVerticalSpace = true;
data.horizontalAlignment = GridData.FILL;
composite.setLayoutData(data);
}
Label containerLabel = new Label(composite, SWT.LEFT);
{
containerLabel.setText(OCCIEditorPlugin.INSTANCE.getString("_UI_ModelObject"));
GridData data = new GridData();
data.horizontalAlignment = GridData.FILL;
containerLabel.setLayoutData(data);
}
initialObjectField = new Combo(composite, SWT.BORDER);
{
GridData data = new GridData();
data.horizontalAlignment = GridData.FILL;
data.grabExcessHorizontalSpace = true;
initialObjectField.setLayoutData(data);
}
for (String objectName : getInitialObjectNames()) {
initialObjectField.add(getLabel(objectName));
}
if (initialObjectField.getItemCount() == 1) {
initialObjectField.select(0);
}
initialObjectField.addModifyListener(validator);
Label encodingLabel = new Label(composite, SWT.LEFT);
{
encodingLabel.setText(OCCIEditorPlugin.INSTANCE.getString("_UI_XMLEncoding"));
GridData data = new GridData();
data.horizontalAlignment = GridData.FILL;
encodingLabel.setLayoutData(data);
}
encodingField = new Combo(composite, SWT.BORDER);
{
GridData data = new GridData();
data.horizontalAlignment = GridData.FILL;
data.grabExcessHorizontalSpace = true;
encodingField.setLayoutData(data);
}
for (String encoding : getEncodings()) {
encodingField.add(encoding);
}
encodingField.select(0);
encodingField.addModifyListener(validator);
setPageComplete(validatePage());
setControl(composite);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ModifyListener validator =
new ModifyListener() {
public void modifyText(ModifyEvent e) {
setPageComplete(validatePage());
}
};
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected boolean validatePage() {
return getInitialObjectName() != null && getEncodings().contains(encodingField.getText());
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setVisible(boolean visible) {
super.setVisible(visible);
if (visible) {
if (initialObjectField.getItemCount() == 1) {
initialObjectField.clearSelection();
encodingField.setFocus();
}
else {
encodingField.clearSelection();
initialObjectField.setFocus();
}
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getInitialObjectName() {
String label = initialObjectField.getText();
for (String name : getInitialObjectNames()) {
if (getLabel(name).equals(label)) {
return name;
}
}
return null;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getEncoding() {
return encodingField.getText();
}
/**
* Returns the label for the specified type name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected String getLabel(String typeName) {
try {
return OCCIEditPlugin.INSTANCE.getString("_UI_" + typeName + "_type");
}
catch(MissingResourceException mre) {
OCCIEditorPlugin.INSTANCE.log(mre);
}
return typeName;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected Collection<String> getEncodings() {
if (encodings == null) {
encodings = new ArrayList<String>();
for (StringTokenizer stringTokenizer = new StringTokenizer(OCCIEditorPlugin.INSTANCE.getString("_UI_XMLEncodingChoices")); stringTokenizer.hasMoreTokens(); ) {
encodings.add(stringTokenizer.nextToken());
}
}
return encodings;
}
}
/**
* The framework calls this to create the contents of the wizard.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void addPages() {
// Create a page, set the title, and the initial model file name.
//
newFileCreationPage = new OCCIModelWizardNewFileCreationPage("Whatever", selection);
newFileCreationPage.setTitle(OCCIEditorPlugin.INSTANCE.getString("_UI_OCCIModelWizard_label"));
newFileCreationPage.setDescription(OCCIEditorPlugin.INSTANCE.getString("_UI_OCCIModelWizard_description"));
newFileCreationPage.setFileName(OCCIEditorPlugin.INSTANCE.getString("_UI_OCCIEditorFilenameDefaultBase") + "." + FILE_EXTENSIONS.get(0));
addPage(newFileCreationPage);
// Try and get the resource selection to determine a current directory for the file dialog.
//
if (selection != null && !selection.isEmpty()) {
// Get the resource...
//
Object selectedElement = selection.iterator().next();
if (selectedElement instanceof IResource) {
// Get the resource parent, if its a file.
//
IResource selectedResource = (IResource)selectedElement;
if (selectedResource.getType() == IResource.FILE) {
selectedResource = selectedResource.getParent();
}
// This gives us a directory...
//
if (selectedResource instanceof IFolder || selectedResource instanceof IProject) {
// Set this for the container.
//
newFileCreationPage.setContainerFullPath(selectedResource.getFullPath());
// Make up a unique new name here.
//
String defaultModelBaseFilename = OCCIEditorPlugin.INSTANCE.getString("_UI_OCCIEditorFilenameDefaultBase");
String defaultModelFilenameExtension = FILE_EXTENSIONS.get(0);
String modelFilename = defaultModelBaseFilename + "." + defaultModelFilenameExtension;
for (int i = 1; ((IContainer)selectedResource).findMember(modelFilename) != null; ++i) {
modelFilename = defaultModelBaseFilename + i + "." + defaultModelFilenameExtension;
}
newFileCreationPage.setFileName(modelFilename);
}
}
}
initialObjectCreationPage = new OCCIModelWizardInitialObjectCreationPage("Whatever2");
initialObjectCreationPage.setTitle(OCCIEditorPlugin.INSTANCE.getString("_UI_OCCIModelWizard_label"));
initialObjectCreationPage.setDescription(OCCIEditorPlugin.INSTANCE.getString("_UI_Wizard_initial_object_description"));
addPage(initialObjectCreationPage);
}
/**
* Get the file from the page.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public IFile getModelFile() {
return newFileCreationPage.getModelFile();
}
}
| occiware/OCCI-Studio | plugins/org.eclipse.cmf.occi.core.editor/src-gen/org/eclipse/cmf/occi/core/presentation/OCCIModelWizard.java | Java | epl-1.0 | 17,927 |
/**
* Copyright (c) 2015 SK holdings Co., Ltd. All rights reserved.
* This software is the confidential and proprietary information of SK holdings.
* 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 SK holdings.
* (http://www.eclipse.org/legal/epl-v10.html)
*/
package nexcore.tool.mda.model.developer.operationbody;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>IMDA Operation</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link nexcore.tool.mda.model.developer.operationbody.IMDAOperation#getId <em>Id</em>}</li>
* <li>{@link nexcore.tool.mda.model.developer.operationbody.IMDAOperation#getName <em>Name</em>}</li>
* </ul>
* </p>
*
* @see nexcore.tool.mda.model.developer.operationbody.OperationbodyPackage#getIMDAOperation()
* @model interface="true" abstract="true"
* @generated
*/
public interface IMDAOperation extends EObject {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
String copyright = "";
/**
* Returns the value of the '<em><b>Id</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Id</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Id</em>' attribute.
* @see #setId(String)
* @see nexcore.tool.mda.model.developer.operationbody.OperationbodyPackage#getIMDAOperation_Id()
* @model required="true"
* @generated
*/
String getId();
/**
* Sets the value of the '{@link nexcore.tool.mda.model.developer.operationbody.IMDAOperation#getId <em>Id</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Id</em>' attribute.
* @see #getId()
* @generated
*/
void setId(String value);
/**
* Returns the value of the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Name</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Name</em>' attribute.
* @see #setName(String)
* @see nexcore.tool.mda.model.developer.operationbody.OperationbodyPackage#getIMDAOperation_Name()
* @model required="true"
* @generated
*/
String getName();
/**
* Sets the value of the '{@link nexcore.tool.mda.model.developer.operationbody.IMDAOperation#getName <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Name</em>' attribute.
* @see #getName()
* @generated
*/
void setName(String value);
} // IMDAOperation
| SK-HOLDINGS-CC/NEXCORE-UML-Modeler | nexcore.tool.mda.model/src/java/nexcore/tool/mda/model/developer/operationbody/IMDAOperation.java | Java | epl-1.0 | 3,042 |
/*
* Copyright (c) 2014, 2015 Eike Stepper (Berlin, Germany) and others.
* 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:
* Eike Stepper - initial API and implementation
*/
package org.eclipse.oomph.setup.provider;
import org.eclipse.oomph.setup.InstallationTask;
import org.eclipse.oomph.setup.SetupPackage;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ViewerNotification;
import java.util.Collection;
import java.util.List;
/**
* This is the item provider adapter for a {@link org.eclipse.oomph.setup.InstallationTask} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class InstallationTaskItemProvider extends SetupTaskItemProvider
{
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public InstallationTaskItemProvider(AdapterFactory adapterFactory)
{
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object)
{
if (itemPropertyDescriptors == null)
{
super.getPropertyDescriptors(object);
addLocationPropertyDescriptor(object);
addRelativeProductFolderPropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the Location feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addLocationPropertyDescriptor(Object object)
{
itemPropertyDescriptors.add(createItemPropertyDescriptor(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(),
getString("_UI_InstallationTask_location_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_InstallationTask_location_feature", "_UI_InstallationTask_type"),
SetupPackage.Literals.INSTALLATION_TASK__LOCATION, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null));
}
/**
* This adds a property descriptor for the Relative Product Folder feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addRelativeProductFolderPropertyDescriptor(Object object)
{
itemPropertyDescriptors.add(createItemPropertyDescriptor(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(),
getString("_UI_InstallationTask_relativeProductFolder_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_InstallationTask_relativeProductFolder_feature", "_UI_InstallationTask_type"),
SetupPackage.Literals.INSTALLATION_TASK__RELATIVE_PRODUCT_FOLDER, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null));
}
/**
* This returns InstallationTask.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object)
{
return overlayImage(object, getResourceLocator().getImage("full/obj16/InstallationTask"));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected boolean shouldComposeCreationImage()
{
return true;
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object)
{
String label = ((InstallationTask)object).getLocation();
return label == null || label.length() == 0 ? getString("_UI_InstallationTask_type") : getString("_UI_InstallationTask_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification)
{
updateChildren(notification);
switch (notification.getFeatureID(InstallationTask.class))
{
case SetupPackage.INSTALLATION_TASK__LOCATION:
case SetupPackage.INSTALLATION_TASK__RELATIVE_PRODUCT_FOLDER:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true));
return;
}
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object)
{
super.collectNewChildDescriptors(newChildDescriptors, object);
}
}
| peterkir/org.eclipse.oomph | plugins/org.eclipse.oomph.setup.edit/src/org/eclipse/oomph/setup/provider/InstallationTaskItemProvider.java | Java | epl-1.0 | 5,393 |
package org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case;
import java.util.Map;
import org.opendaylight.yangtools.yang.binding.Augmentation;
import java.util.HashMap;
import java.util.List;
import com.google.common.collect.Range;
import java.util.ArrayList;
import java.util.Collections;
public class PopMplsActionBuilder {
private Integer _ethernetType;
private final Map<Class<? extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction>>, Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction>> augmentation = new HashMap<>();
public PopMplsActionBuilder() {
}
public Integer getEthernetType() {
return _ethernetType;
}
@SuppressWarnings("unchecked")
public <E extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction>> E getAugmentation(Class<E> augmentationType) {
if (augmentationType == null) {
throw new IllegalArgumentException("Augmentation Type reference cannot be NULL!");
}
return (E) augmentation.get(augmentationType);
}
public PopMplsActionBuilder setEthernetType(Integer value) {
if (value != null) {
boolean isValidRange = false;
List<Range<Integer>> rangeConstraints = new ArrayList<>();
rangeConstraints.add(Range.closed(new Integer("0"), new Integer("65535")));
for (Range<Integer> r : rangeConstraints) {
if (r.contains(value)) {
isValidRange = true;
}
}
if (!isValidRange) {
throw new IllegalArgumentException(String.format("Invalid range: %s, expected: %s.", value, rangeConstraints));
}
}
this._ethernetType = value;
return this;
}
public PopMplsActionBuilder addAugmentation(Class<? extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction>> augmentationType, Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction> augmentation) {
this.augmentation.put(augmentationType, augmentation);
return this;
}
public PopMplsAction build() {
return new PopMplsActionImpl(this);
}
private static final class PopMplsActionImpl implements PopMplsAction {
public Class<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction> getImplementedInterface() {
return org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction.class;
}
private final Integer _ethernetType;
private final Map<Class<? extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction>>, Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction>> augmentation;
private PopMplsActionImpl(PopMplsActionBuilder builder) {
this._ethernetType = builder.getEthernetType();
switch (builder.augmentation.size()) {
case 0:
this.augmentation = Collections.emptyMap();
break;
case 1:
final Map.Entry<Class<? extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction>>, Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction>> e = builder.augmentation.entrySet().iterator().next();
this.augmentation = Collections.<Class<? extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction>>, Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction>>singletonMap(e.getKey(), e.getValue());
break;
default :
this.augmentation = new HashMap<>(builder.augmentation);
}
}
@Override
public Integer getEthernetType() {
return _ethernetType;
}
@SuppressWarnings("unchecked")
@Override
public <E extends Augmentation<org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.pop.mpls.action._case.PopMplsAction>> E getAugmentation(Class<E> augmentationType) {
if (augmentationType == null) {
throw new IllegalArgumentException("Augmentation Type reference cannot be NULL!");
}
return (E) augmentation.get(augmentationType);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((_ethernetType == null) ? 0 : _ethernetType.hashCode());
result = prime * result + ((augmentation == null) ? 0 : augmentation.hashCode());
return result;
}
@Override
public boolean equals(java.lang.Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
PopMplsActionImpl other = (PopMplsActionImpl) obj;
if (_ethernetType == null) {
if (other._ethernetType != null) {
return false;
}
} else if(!_ethernetType.equals(other._ethernetType)) {
return false;
}
if (augmentation == null) {
if (other.augmentation != null) {
return false;
}
} else if(!augmentation.equals(other.augmentation)) {
return false;
}
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("PopMplsAction [");
boolean first = true;
if (_ethernetType != null) {
if (first) {
first = false;
} else {
builder.append(", ");
}
builder.append("_ethernetType=");
builder.append(_ethernetType);
}
if (first) {
first = false;
} else {
builder.append(", ");
}
builder.append("augmentation=");
builder.append(augmentation.values());
return builder.append(']').toString();
}
}
}
| niuqg/controller | opendaylight/md-sal/model/model-flow-base/src/main/yang-gen-sal/org/opendaylight/yang/gen/v1/urn/opendaylight/action/types/rev131112/action/action/pop/mpls/action/_case/PopMplsActionBuilder.java | Java | epl-1.0 | 7,204 |
package at.medevit.ch.artikelstamm.ui.internal;
import org.eclipse.core.databinding.conversion.Converter;
public class IntToStringConverterSelbstbehalt extends Converter {
public IntToStringConverterSelbstbehalt(){
super(Integer.class, String.class);
}
@Override
public Object convert(Object fromObject){
if (fromObject instanceof Integer) {
int value = (Integer) fromObject;
if (value >= 0)
return value + "";
}
return null;
}
}
| DavidGutknecht/elexis-3-base | bundles/at.medevit.ch.artikelstamm.ui/src/at/medevit/ch/artikelstamm/ui/internal/IntToStringConverterSelbstbehalt.java | Java | epl-1.0 | 461 |
/*
* Copyright (c) 2015-2017 Red Hat, Inc.
* 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:
* Red Hat, Inc. - initial API and implementation
*/
'use strict';
import {EnvironmentManager} from './environment-manager';
import {IEnvironmentManagerMachine} from './environment-manager-machine';
import {ComposeParser, IComposeRecipe} from './compose-parser';
/**
* This is the implementation of environment manager that handles the docker compose format.
*
* Format sample and specific description:
* <code>
* services:
* devmachine:
* image: codenvy/ubuntu_jdk8
* depends_on:
* - anotherMachine
* mem_limit: 2147483648
* anotherMachine:
* image: codenvy/ubuntu_jdk8
* depends_on:
* - thirdMachine
* mem_limit: 1073741824
* thirdMachine:
* image: codenvy/ubuntu_jdk8
* mem_limit: 512741824
* labels:
* com.example.description: "Accounting webapp"
* com.example.department: "Finance"
* com.example.label-with-empty-value: ""
* environment:
* SOME_ENV: development
* SHOW: 'true'
* SESSION_SECRET:
* </code>
*
*
* The recipe type is <code>compose</code>.
* Machines are described both in recipe and in machines attribute of the environment (machine configs).
* The machine configs contain memoryLimitBytes in attributes, servers and agent.
* Environment variables can be set only in recipe content.
*
* @author Ann Shumilova
*/
export class ComposeEnvironmentManager extends EnvironmentManager {
parser: ComposeParser;
constructor($log: ng.ILogService) {
super($log);
this.parser = new ComposeParser();
}
get editorMode(): string {
return 'text/x-yaml';
}
/**
* Parses recipe content
*
* @param content {string} recipe content
* @returns {IComposeRecipe} recipe object
*/
_parseRecipe(content: string): IComposeRecipe {
let recipe = null;
try {
recipe = this.parser.parse(content);
} catch (e) {
this.$log.error(e);
}
return recipe;
}
/**
* Dumps recipe object
*
* @param recipe {IComposeRecipe} recipe object
* @returns {string} recipe content
*/
_stringifyRecipe(recipe: IComposeRecipe): string {
let content = '';
try {
content = this.parser.dump(recipe);
} catch (e) {
this.$log.error(e);
}
return content;
}
/**
* Retrieves the list of machines.
*
* @param {che.IWorkspaceEnvironment} environment environment's configuration
* @param {any=} runtime runtime of active environment
* @returns {IEnvironmentManagerMachine[]} list of machines defined in environment
*/
getMachines(environment: che.IWorkspaceEnvironment, runtime?: any): IEnvironmentManagerMachine[] {
let recipe: any = null,
machines: IEnvironmentManagerMachine[] = super.getMachines(environment, runtime),
machineNames: string[] = [];
if (environment.recipe.content) {
recipe = this._parseRecipe(environment.recipe.content);
if (recipe) {
machineNames = Object.keys(recipe.services);
} else if (environment.machines) {
machineNames = Object.keys(environment.machines);
}
} else if (environment.recipe.location) {
machineNames = Object.keys(environment.machines);
}
machineNames.forEach((machineName: string) => {
let machine: IEnvironmentManagerMachine = machines.find((_machine: IEnvironmentManagerMachine) => {
return _machine.name === machineName;
});
if (!machine) {
machine = { name: machineName };
machines.push(machine);
}
machine.recipe = recipe ? recipe.services[machineName] : recipe;
if (environment.machines && environment.machines[machineName]) {
angular.merge(machine, environment.machines[machineName]);
}
// memory
let memoryLimitBytes = this.getMemoryLimit(machine);
if (memoryLimitBytes === -1 && recipe) {
this.setMemoryLimit(machine, recipe.services[machineName].mem_limit);
}
});
return machines;
}
/**
* Provides the environment configuration based on machines format.
*
* @param {che.IWorkspaceEnvironment} environment origin of the environment to be edited
* @param {IEnvironmentManagerMachine} machines the list of machines
* @returns {che.IWorkspaceEnvironment} environment's configuration
*/
getEnvironment(environment: che.IWorkspaceEnvironment, machines: IEnvironmentManagerMachine[]): che.IWorkspaceEnvironment {
let newEnvironment = super.getEnvironment(environment, machines);
if (newEnvironment.recipe.content) {
let recipe: IComposeRecipe = this._parseRecipe(newEnvironment.recipe.content);
if (recipe) {
machines.forEach((machine: IEnvironmentManagerMachine) => {
let machineName = machine.name;
if (!recipe.services[machineName]) {
return;
}
if (machine.recipe.environment && Object.keys(machine.recipe.environment).length) {
recipe.services[machineName].environment = angular.copy(machine.recipe.environment);
} else {
delete recipe.services[machineName].environment;
}
if (machine.recipe.image) {
recipe.services[machineName].image = machine.recipe.image;
}
});
try {
newEnvironment.recipe.content = this._stringifyRecipe(recipe);
} catch (e) {
this.$log.error('Cannot retrieve environment\'s recipe, error: ', e);
}
}
}
return newEnvironment;
}
/**
* Returns object which contains docker image or link to docker file and build context.
*
* @param {IEnvironmentManagerMachine} machine
* @returns {*}
*/
getSource(machine: IEnvironmentManagerMachine): any {
if (!machine.recipe) {
return null;
}
if (machine.recipe.image) {
return {image: machine.recipe.image};
} else if (machine.recipe.build) {
return machine.recipe.build;
}
}
/**
* Updates machine's image
*
* @param {IEnvironmentManagerMachine} machine
* @param {String} image
*/
setSource(machine: IEnvironmentManagerMachine, image: string) {
if (!machine.recipe) {
return;
}
machine.recipe.image = image;
}
/**
* Returns true if environment recipe content is present.
*
* @param {IEnvironmentManagerMachine} machine
* @returns {boolean}
*/
canEditEnvVariables(machine: IEnvironmentManagerMachine): boolean {
return !!machine.recipe;
}
/**
* Returns object with environment variables.
*
* @param {IEnvironmentManagerMachine} machine
* @returns {*}
*/
getEnvVariables(machine: IEnvironmentManagerMachine): any {
if (!machine.recipe) {
return null;
}
return machine.recipe.environment || {};
}
/**
* Updates machine with new environment variables.
*
* @param {IEnvironmentManagerMachine} machine
* @param {any} envVariables
*/
setEnvVariables(machine: IEnvironmentManagerMachine, envVariables: any): void {
if (!machine.recipe) {
return;
}
if (Object.keys(envVariables).length) {
machine.recipe.environment = angular.copy(envVariables);
} else {
delete machine.recipe.environment;
}
}
/**
* Renames machine.
*
* @param {che.IWorkspaceEnvironment} environment
* @param {string} oldName
* @param {string} newName
* @returns {che.IWorkspaceEnvironment} new environment
*/
renameMachine(environment: che.IWorkspaceEnvironment, oldName: string, newName: string): che.IWorkspaceEnvironment {
try {
let recipe: IComposeRecipe = this._parseRecipe(environment.recipe.content);
// fix relations to other machines in recipe
Object.keys(recipe.services).forEach((serviceName: string) => {
if (serviceName === oldName) {
return;
}
// fix 'depends_on'
let dependsOn = recipe.services[serviceName].depends_on || [],
index = dependsOn.indexOf(oldName);
if (index > -1) {
dependsOn.splice(index, 1);
dependsOn.push(newName);
}
// fix 'links'
let links = recipe.services[serviceName].links || [],
re = new RegExp('^' + oldName + '(?:$|:(.+))');
for (let i = 0; i < links.length; i++) {
if (re.test(links[i])) {
let match = links[i].match(re),
alias = match[1] || '',
newLink = alias ? newName + ':' + alias : newName;
links.splice(i, 1);
links.push(newLink);
break;
}
}
});
// rename machine in recipe
recipe.services[newName] = recipe.services[oldName];
delete recipe.services[oldName];
// try to update recipe
environment.recipe.content = this._stringifyRecipe(recipe);
// and then update config
environment.machines[newName] = environment.machines[oldName];
delete environment.machines[oldName];
} catch (e) {
this.$log.error('Cannot rename machine, error: ', e);
}
return environment;
}
/**
* Removes machine.
*
* @param {che.IWorkspaceEnvironment} environment
* @param {string} name name of machine
* @returns {che.IWorkspaceEnvironment} new environment
*/
deleteMachine(environment: che.IWorkspaceEnvironment, name: string): che.IWorkspaceEnvironment {
try {
let recipe: IComposeRecipe = this._parseRecipe(environment.recipe.content);
// fix relations to other machines in recipe
Object.keys(recipe.services).forEach((serviceName: string) => {
if (serviceName === name) {
return;
}
// fix 'depends_on'
let dependsOn = recipe.services[serviceName].depends_on || [],
index = dependsOn.indexOf(name);
if (index > -1) {
dependsOn.splice(index, 1);
if (dependsOn.length === 0) {
delete recipe.services[serviceName].depends_on;
}
}
// fix 'links'
let links = recipe.services[serviceName].links || [],
re = new RegExp('^' + name + '(?:$|:(.+))');
for (let i = 0; i < links.length; i++) {
if (re.test(links[i])) {
links.splice(i, 1);
break;
}
}
if (links.length === 0) {
delete recipe.services[serviceName].links;
}
});
// delete machine from recipe
delete recipe.services[name];
// try to update recipe
environment.recipe.content = this._stringifyRecipe(recipe);
// and then update config
delete environment.machines[name];
} catch (e) {
this.$log.error('Cannot delete machine, error: ', e);
}
return environment;
}
}
| sudaraka94/che | dashboard/src/components/api/environment/compose-environment-manager.ts | TypeScript | epl-1.0 | 11,054 |
package org.hamcrest.collection;
import java.util.Arrays;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
/**
* Matcher for array whose elements satisfy a sequence of matchers.
* The array size must equal the number of element matchers.
*/
public class IsArray<T> extends TypeSafeMatcher<T[]> {
private final Matcher<? super T>[] elementMatchers;
public IsArray(Matcher<? super T>[] elementMatchers) {
this.elementMatchers = elementMatchers.clone();
}
@Override
public boolean matchesSafely(T[] array) {
if (array.length != elementMatchers.length) return false;
for (int i = 0; i < array.length; i++) {
if (!elementMatchers[i].matches(array[i])) return false;
}
return true;
}
@Override
public void describeMismatchSafely(T[] actual, Description mismatchDescription) {
if (actual.length != elementMatchers.length) {
mismatchDescription.appendText("array length was " + actual.length);
return;
}
for (int i = 0; i < actual.length; i++) {
if (!elementMatchers[i].matches(actual[i])) {
mismatchDescription.appendText("element " + i + " was ").appendValue(actual[i]);
return;
}
}
}
@Override
public void describeTo(Description description) {
description.appendList(descriptionStart(), descriptionSeparator(), descriptionEnd(),
Arrays.asList(elementMatchers));
}
/**
* Returns the string that starts the description.
*
* Can be overridden in subclasses to customise how the matcher is
* described.
*/
protected String descriptionStart() {
return "[";
}
/**
* Returns the string that separates the elements in the description.
*
* Can be overridden in subclasses to customise how the matcher is
* described.
*/
protected String descriptionSeparator() {
return ", ";
}
/**
* Returns the string that ends the description.
*
* Can be overridden in subclasses to customise how the matcher is
* described.
*/
protected String descriptionEnd() {
return "]";
}
/**
* Creates a matcher that matches arrays whose elements are satisfied by the specified matchers. Matches
* positively only if the number of matchers specified is equal to the length of the examined array and
* each matcher[i] is satisfied by array[i].
* <p/>
* For example:
* <pre>assertThat(new Integer[]{1,2,3}, is(array(equalTo(1), equalTo(2), equalTo(3))))</pre>
*
* @param elementMatchers
* the matchers that the elements of examined arrays should satisfy
*/
@Factory
public static <T> IsArray<T> array(Matcher<? super T>... elementMatchers) {
return new IsArray<T>(elementMatchers);
}
}
| jasonCarNormal0101/StockAdviser | lib/hamcrest-1.3/hamcrest-library/src/main/java/org/hamcrest/collection/IsArray.java | Java | epl-1.0 | 3,007 |
/*******************************************************************************
"FreePastry" Peer-to-Peer Application Development Substrate
Copyright 2002-2007, Rice University. Copyright 2006-2007, Max Planck Institute
for Software Systems. 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 Rice University (RICE), Max Planck Institute for Software
Systems (MPI-SWS) 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 RICE, MPI-SWS and the contributors on an "as is"
basis, without any representations or warranties of any kind, express or implied
including, but not limited to, representations or warranties of
non-infringement, merchantability or fitness for a particular purpose. In no
event shall RICE, MPI-SWS or contributors be liable for any direct, indirect,
incidental, special, exemplary, or consequential damages (including, but not
limited to, procurement of substitute goods or services; loss of use, data, or
profits; or business interruption) however caused and on any theory of
liability, whether in contract, strict liability, or tort (including negligence
or otherwise) arising in any way out of the use of this software, even if
advised of the possibility of such damage.
*******************************************************************************/
package org.mpisws.p2p.transport.peerreview.replay.playback;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Map;
import org.mpisws.p2p.transport.ClosedChannelException;
import org.mpisws.p2p.transport.P2PSocket;
import org.mpisws.p2p.transport.P2PSocketReceiver;
import org.mpisws.p2p.transport.SocketCallback;
import org.mpisws.p2p.transport.SocketRequestHandle;
public class ReplaySocket<Identifier> implements P2PSocket<Identifier>, SocketRequestHandle<Identifier> {
protected Identifier identifier;
protected int socketId;
protected ReplayVerifier<Identifier> verifier;
boolean closed = false;
boolean outputShutdown = false;
Map<String, Object> options;
/**
* TODO: Make extensible by putting into a factory.
*
* @param identifier
* @param socketId
* @param verifier
*/
public ReplaySocket(Identifier identifier, int socketId, ReplayVerifier<Identifier> verifier, Map<String, Object> options) {
this.identifier = identifier;
this.socketId = socketId;
this.verifier = verifier;
this.options = options;
}
@Override
public Identifier getIdentifier() {
return identifier;
}
@Override
public Map<String, Object> getOptions() {
return options;
}
@Override
public long read(ByteBuffer dst) throws IOException {
// if (closed) throw new ClosedChannelException("Socket already closed.");
return verifier.readSocket(socketId, dst);
}
@Override
public long write(ByteBuffer src) throws IOException {
// if (closed || outputClosed) throw new ClosedChannelException("Socket already closed.");
return verifier.writeSocket(socketId, src);
}
P2PSocketReceiver<Identifier> reader;
P2PSocketReceiver<Identifier> writer;
@Override
public void register(boolean wantToRead, boolean wantToWrite, P2PSocketReceiver<Identifier> receiver) {
if (closed) {
receiver.receiveException(this, new ClosedChannelException("Socket "+this+" already closed."));
return;
}
if (wantToWrite && outputShutdown) {
receiver.receiveException(this, new ClosedChannelException("Socket "+this+" already shutdown output."));
return;
}
if (wantToWrite) {
if (writer != null) {
if (writer != receiver) throw new IllegalStateException("Already registered "+writer+" for writing, you can't register "+receiver+" for writing as well!");
}
}
if (wantToRead) {
if (reader != null) {
if (reader != receiver) throw new IllegalStateException("Already registered "+reader+" for reading, you can't register "+receiver+" for reading as well!");
}
reader = receiver;
}
if (wantToWrite) {
writer = receiver;
}
}
public void notifyIO(boolean canRead, boolean canWrite) throws IOException {
if (!canRead && !canWrite) {
throw new IOException("I can't read or write. canRead:"+canRead+" canWrite:"+canWrite);
}
if (canRead && canWrite) {
if (writer != reader) throw new IllegalStateException("weader != writer canRead:"+canRead+" canWrite:"+canWrite);
P2PSocketReceiver<Identifier> temp = writer;
writer = null;
reader = null;
temp.receiveSelectResult(this, canRead, canWrite);
return;
}
if (canRead) {
if (reader == null) throw new IllegalStateException("reader:"+reader+" canRead:"+canRead);
P2PSocketReceiver<Identifier> temp = reader;
reader = null;
temp.receiveSelectResult(this, canRead, canWrite);
return;
}
if (canWrite) {
if (writer == null) throw new IllegalStateException("writer:"+writer+" canWrite:"+canWrite);
P2PSocketReceiver<Identifier> temp = writer;
writer = null;
temp.receiveSelectResult(this, canRead, canWrite);
return;
}
}
@Override
public void close() {
closed = true;
verifier.close(socketId);
}
SocketCallback<Identifier> deliverSocketToMe;
public void setDeliverSocketToMe(SocketCallback<Identifier> deliverSocketToMe) {
this.deliverSocketToMe = deliverSocketToMe;
}
public void socketOpened() {
deliverSocketToMe.receiveResult(this, this);
deliverSocketToMe = null;
}
@Override
public void shutdownOutput() {
outputShutdown = true;
verifier.shutdownOutput(socketId);
// throw new RuntimeException("Not implemented.");
}
public void receiveException(IOException ioe) {
if (deliverSocketToMe != null) {
deliverSocketToMe.receiveException(this, ioe);
return;
}
if (writer != null) {
if (writer == reader) {
writer.receiveException(this, ioe);
writer = null;
reader = null;
} else {
writer.receiveException(this, ioe);
writer = null;
}
}
if (reader != null) {
reader.receiveException(this, ioe);
reader = null;
}
}
@Override
public boolean cancel() {
throw new RuntimeException("Not implemented.");
}
}
| michele-loreti/jResp | core/org.cmg.jresp.pastry/pastry-2.1/src/org/mpisws/p2p/transport/peerreview/replay/playback/ReplaySocket.java | Java | epl-1.0 | 6,880 |
/**
* Copyright (c) 2016-2019 by the respective copyright holders.
* 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
*/
package com.zsmartsystems.zigbee.zcl.clusters.general;
import javax.annotation.Generated;
import com.zsmartsystems.zigbee.zcl.ZclCommand;
import com.zsmartsystems.zigbee.zcl.ZclFieldSerializer;
import com.zsmartsystems.zigbee.zcl.ZclFieldDeserializer;
import com.zsmartsystems.zigbee.zcl.protocol.ZclDataType;
import com.zsmartsystems.zigbee.zcl.protocol.ZclCommandDirection;
import java.util.List;
import com.zsmartsystems.zigbee.zcl.ZclStatus;
import com.zsmartsystems.zigbee.zcl.field.AttributeStatusRecord;
/**
* Configure Reporting Response value object class.
* <p>
* Cluster: <b>General</b>. Command is sent <b>TO</b> the server.
* This command is a <b>generic</b> command used across the profile.
* <p>
* The Configure Reporting Response command is generated in response to a
* Configure Reporting command.
* <p>
* Code is auto-generated. Modifications may be overwritten!
*/
@Generated(value = "com.zsmartsystems.zigbee.autocode.ZclProtocolCodeGenerator", date = "2018-04-26T19:23:24Z")
public class ConfigureReportingResponse extends ZclCommand {
/**
* Status command message field.
* <p>
* Status is only provided if the command was successful, and the
* attribute status records are not included for successfully
* written attributes, in order to save bandwidth.
*/
private ZclStatus status;
/**
* Records command message field.
* <p>
* Note that attribute status records are not included for successfully
* configured attributes in order to save bandwidth. In the case of successful
* configuration of all attributes, only a single attribute status record SHALL
* be included in the command, with the status field set to SUCCESS and the direction and
* attribute identifier fields omitted.
*/
private List<AttributeStatusRecord> records;
/**
* Default constructor.
*/
public ConfigureReportingResponse() {
genericCommand = true;
commandId = 7;
commandDirection = ZclCommandDirection.CLIENT_TO_SERVER;
}
/**
* Sets the cluster ID for <i>generic</i> commands. {@link ConfigureReportingResponse} is a <i>generic</i> command.
* <p>
* For commands that are not <i>generic</i>, this method will do nothing as the cluster ID is fixed.
* To test if a command is <i>generic</i>, use the {@link #isGenericCommand} method.
*
* @param clusterId the cluster ID used for <i>generic</i> commands as an {@link Integer}
*/
@Override
public void setClusterId(Integer clusterId) {
this.clusterId = clusterId;
}
/**
* Gets Status.
*
* Status is only provided if the command was successful, and the
* attribute status records are not included for successfully
* written attributes, in order to save bandwidth.
*
* @return the Status
*/
public ZclStatus getStatus() {
return status;
}
/**
* Sets Status.
*
* Status is only provided if the command was successful, and the
* attribute status records are not included for successfully
* written attributes, in order to save bandwidth.
*
* @param status the Status
*/
public void setStatus(final ZclStatus status) {
this.status = status;
}
/**
* Gets Records.
*
* Note that attribute status records are not included for successfully
* configured attributes in order to save bandwidth. In the case of successful
* configuration of all attributes, only a single attribute status record SHALL
* be included in the command, with the status field set to SUCCESS and the direction and
* attribute identifier fields omitted.
*
* @return the Records
*/
public List<AttributeStatusRecord> getRecords() {
return records;
}
/**
* Sets Records.
*
* Note that attribute status records are not included for successfully
* configured attributes in order to save bandwidth. In the case of successful
* configuration of all attributes, only a single attribute status record SHALL
* be included in the command, with the status field set to SUCCESS and the direction and
* attribute identifier fields omitted.
*
* @param records the Records
*/
public void setRecords(final List<AttributeStatusRecord> records) {
this.records = records;
}
@Override
public void serialize(final ZclFieldSerializer serializer) {
if (status == ZclStatus.SUCCESS) {
serializer.serialize(status, ZclDataType.ZCL_STATUS);
return;
}
serializer.serialize(records, ZclDataType.N_X_ATTRIBUTE_STATUS_RECORD);
}
@Override
public void deserialize(final ZclFieldDeserializer deserializer) {
if (deserializer.getRemainingLength() == 1) {
status = (ZclStatus) deserializer.deserialize(ZclDataType.ZCL_STATUS);
return;
}
records = (List<AttributeStatusRecord>) deserializer.deserialize(ZclDataType.N_X_ATTRIBUTE_STATUS_RECORD);
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder(82);
builder.append("ConfigureReportingResponse [");
builder.append(super.toString());
builder.append(", status=");
builder.append(status);
builder.append(", records=");
builder.append(records);
builder.append(']');
return builder.toString();
}
}
| cschwer/com.zsmartsystems.zigbee | com.zsmartsystems.zigbee/src/main/java/com/zsmartsystems/zigbee/zcl/clusters/general/ConfigureReportingResponse.java | Java | epl-1.0 | 5,846 |
/*
* Licensed Materials - Property of Cirrus Link Solutions
* Copyright (c) 2016 Cirrus Link Solutions LLC - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
*/
package com.cirruslink.sparkplug.message.model;
import java.util.Objects;
import com.cirruslink.sparkplug.SparkplugInvalidTypeException;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSetter;
/**
* A class to represent a parameter associated with a template.
*/
public class Parameter {
/**
* The name of the parameter
*/
@JsonProperty("name")
private String name;
/**
* The data type of the parameter
*/
@JsonProperty("type")
private ParameterDataType type;
/**
* The value of the parameter
*/
@JsonProperty("value")
private Object value;
/**
* Constructs a Parameter instance.
*
* @param name The name of the parameter.
* @param type The type of the parameter.
* @param value The value of the parameter.
* @throws SparkplugInvalidTypeException
*/
public Parameter(String name, ParameterDataType type, Object value) throws SparkplugInvalidTypeException {
this.name = name;
this.type = type;
this.value = value;
this.type.checkType(value);
}
@JsonGetter("name")
public String getName() {
return name;
}
@JsonSetter("name")
public void setName(String name) {
this.name = name;
}
public ParameterDataType getType() {
return type;
}
public void setType(ParameterDataType type) {
this.type = type;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object == null || this.getClass() != object.getClass()) {
return false;
}
Parameter param = (Parameter) object;
return Objects.equals(name, param.getName())
&& Objects.equals(type, param.getType())
&& Objects.equals(value, param.getValue());
}
@Override
public String toString() {
return "Parameter [name=" + name + ", type=" + type + ", value=" + value + "]";
}
}
| Cirrus-Link/Sparkplug | client_libraries/java/src/main/java/com/cirruslink/sparkplug/message/model/Parameter.java | Java | epl-1.0 | 2,232 |
/* This file was generated by SableCC (http://www.sablecc.org/). */
package com.abstratt.mdd.frontend.textuml.grammar.node;
import com.abstratt.mdd.frontend.textuml.grammar.analysis.*;
@SuppressWarnings("nls")
public final class ATransitionEffect extends PTransitionEffect
{
private TDo _do_;
private PSimpleBlock _simpleBlock_;
public ATransitionEffect()
{
// Constructor
}
public ATransitionEffect(
@SuppressWarnings("hiding") TDo _do_,
@SuppressWarnings("hiding") PSimpleBlock _simpleBlock_)
{
// Constructor
setDo(_do_);
setSimpleBlock(_simpleBlock_);
}
@Override
public Object clone()
{
return new ATransitionEffect(
cloneNode(this._do_),
cloneNode(this._simpleBlock_));
}
public void apply(Switch sw)
{
((Analysis) sw).caseATransitionEffect(this);
}
public TDo getDo()
{
return this._do_;
}
public void setDo(TDo node)
{
if(this._do_ != null)
{
this._do_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._do_ = node;
}
public PSimpleBlock getSimpleBlock()
{
return this._simpleBlock_;
}
public void setSimpleBlock(PSimpleBlock node)
{
if(this._simpleBlock_ != null)
{
this._simpleBlock_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._simpleBlock_ = node;
}
@Override
public String toString()
{
return ""
+ toString(this._do_)
+ toString(this._simpleBlock_);
}
@Override
void removeChild(@SuppressWarnings("unused") Node child)
{
// Remove child
if(this._do_ == child)
{
this._do_ = null;
return;
}
if(this._simpleBlock_ == child)
{
this._simpleBlock_ = null;
return;
}
throw new RuntimeException("Not a child.");
}
@Override
void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild)
{
// Replace child
if(this._do_ == oldChild)
{
setDo((TDo) newChild);
return;
}
if(this._simpleBlock_ == oldChild)
{
setSimpleBlock((PSimpleBlock) newChild);
return;
}
throw new RuntimeException("Not a child.");
}
}
| abstratt/textuml | plugins/com.abstratt.mdd.frontend.textuml.grammar/src-gen/com/abstratt/mdd/frontend/textuml/grammar/node/ATransitionEffect.java | Java | epl-1.0 | 2,810 |
package uk.ac.lancs.comp.khatchad.rejuvenatepc.ui.views;
import org.eclipse.contribution.xref.internal.ui.utils.XRefUIUtils;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.widgets.Shell;
import uk.ac.lancs.comp.khatchad.rejuvenatepc.core.model.Suggestion;
public class DoubleClickAction extends Action {
private Shell shell;
private TableViewer viewer;
public DoubleClickAction(Shell shell, TableViewer viewer) {
this.shell = shell;
this.viewer = viewer;
}
@SuppressWarnings({ "restriction", "unchecked" })
@Override
public void run() {
ISelection selection = viewer.getSelection();
if (selection instanceof IStructuredSelection) {
Object sel =
((IStructuredSelection) selection).getFirstElement();
if ( sel instanceof Suggestion ) {
Suggestion<IJavaElement> suggestion = (Suggestion<IJavaElement>)sel;
XRefUIUtils.revealInEditor(suggestion.getSuggestion());
}
}
}
}
| khatchad/Rejuvenate-Pointcut | uk.ac.lancs.comp.khatchad.rejuvenatepc.ui/src/uk/ac/lancs/comp/khatchad/rejuvenatepc/ui/views/DoubleClickAction.java | Java | epl-1.0 | 1,120 |
/**
*/
package org.omg.CVLMetamodelMaster.cvl.provider;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ViewerNotification;
import org.omg.CVLMetamodelMaster.cvl.CvlPackage;
import org.omg.CVLMetamodelMaster.cvl.ObjectHandle;
/**
* This is the item provider adapter for a {@link org.omg.CVLMetamodelMaster.cvl.ObjectHandle} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class ObjectHandleItemProvider extends BaseModelHandleItemProvider {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ObjectHandleItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
addMOFRefPropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the MOF Ref feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addMOFRefPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_ObjectHandle_MOFRef_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_ObjectHandle_MOFRef_feature", "_UI_ObjectHandle_type"),
CvlPackage.Literals.OBJECT_HANDLE__MOF_REF,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This returns ObjectHandle.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/ObjectHandle"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
String label = ((ObjectHandle)object).getReferenceString();
return label == null || label.length() == 0 ?
getString("_UI_ObjectHandle_type") :
getString("_UI_ObjectHandle_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
switch (notification.getFeatureID(ObjectHandle.class)) {
case CvlPackage.OBJECT_HANDLE__MOF_REF:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true));
return;
}
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
}
}
| diverse-project/kcvl | fr.inria.diverse.kcvl.metamodel.edit/src/main/java/org/omg/CVLMetamodelMaster/cvl/provider/ObjectHandleItemProvider.java | Java | epl-1.0 | 3,826 |
var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var browserify = require('browserify');
var watchify = require('watchify');
var babel = require('babelify');
var jade = require('gulp-jade');
var connect = require('gulp-connect');
var uglify = require('gulp-uglify');
var envify = require('envify/custom');
var file = require('gulp-file');
var buildDir = 'build';
var devBuildDir = 'dev_build';
function handleError(err) {
console.error(err); // eslint-disable-line no-console
this.emit('end');
}
function templates(outDir) {
return function() {
return gulp.src('public/*.jade')
.pipe(jade())
.pipe(gulp.dest(outDir));
};
}
function styles(outDir) {
return function() {
return gulp.src('public/*.css')
.pipe(gulp.dest(outDir))
.pipe(connect.reload());
};
}
function vendor(outDir) {
return function() {
return gulp.src('public/vendor/**')
.pipe(gulp.dest(outDir + '/vendor'));
};
}
function icons(outDir) {
return function() {
return gulp.src('public/icons/**')
.pipe(gulp.dest(outDir + '/icons'));
};
}
gulp.task('templates', templates(devBuildDir));
gulp.task('styles', styles(devBuildDir));
gulp.task('vendor', vendor(devBuildDir));
gulp.task('icons', icons(devBuildDir));
function compile(opts) {
var bundler = watchify(
browserify('./public/main.js', { debug: true })
.transform(babel)
.transform(envify({
NODE_ENV: 'development'
}), {global: true})
);
function rebundle() {
return bundler.bundle()
.on('error', handleError)
.pipe(source('main.js'))
.pipe(buffer())
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(devBuildDir))
.pipe(connect.reload());
}
if (opts.watch) {
bundler.on('update', function() {
console.log('-> bundling...'); // eslint-disable-line no-console
return rebundle();
});
}
return rebundle();
}
gulp.task('connect', function() {
return connect.server({
root: devBuildDir,
livereload: true
});
});
gulp.task('watch', function() {
gulp.watch('public/*.css', ['styles']);
return compile({watch: true});
});
gulp.task('build', function() {
templates(buildDir)();
styles(buildDir)();
vendor(buildDir)();
icons(buildDir)();
file('CNAME', 'circuits.im', { src: true })
.pipe(gulp.dest(buildDir));
return browserify('./public/main.js')
.transform(envify({
NODE_ENV: 'production'
}), {global: true})
.transform(babel.configure({
optional: [
'optimisation.react.constantElements',
'optimisation.react.inlineElements'
]
}))
.bundle().on('error', handleError)
.pipe(source('main.js'))
.pipe(buffer())
.pipe(uglify())
.pipe(gulp.dest(buildDir));
});
gulp.task('default', ['templates', 'vendor', 'styles', 'icons', 'connect', 'watch']);
| circuitsim/circuit-simulator | gulpfile.js | JavaScript | epl-1.0 | 2,998 |
/**
* Copyright (c) 2014-2015 by Wen Yu.
* 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
*
* Any modifications to this file must keep this entire header intact.
*/
package cafe.image.jpeg;
/**
* JPEG COM segment builder
*
* @author Wen Yu, yuwen_66@yahoo.com
* @version 1.0 10/11/2013
*/
public class COMBuilder extends SegmentBuilder {
private String comment;
public COMBuilder() {
super(Marker.COM);
}
public COMBuilder comment(String comment) {
this.comment = comment;
return this;
}
@Override
protected byte[] buildData() {
return comment.getBytes();
}
}
| nagyistoce/icafe | src/cafe/image/jpeg/COMBuilder.java | Java | epl-1.0 | 796 |
/*******************************************************************************
* Copyright (c) 2014 UT-Battelle, LLC.
* 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:
* Initial API and implementation and/or initial documentation - Jay Jay Billings,
* Jordan H. Deyton, Dasha Gorin, Alexander J. McCaskey, Taylor Patterson,
* Claire Saunders, Matthew Wang, Anna Wojtowicz
*******************************************************************************/
package org.eclipse.ice.reactor.perspective;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;
/**
* This class implements IPerspectiveFactory to create the Visualization
* Perspective.
*
* @author Taylor Patterson
*
*/
public class ReactorsPerspective implements IPerspectiveFactory {
/**
* The ID of this perspective.
*/
public static final String ID = "org.eclipse.ice.reactors.perspective.ReactorsPerspective";
/*
* (non-Javadoc)
* @see org.eclipse.ui.IPerspectiveFactory#createInitialLayout(org.eclipse.ui.IPageLayout)
*/
@Override
public void createInitialLayout(IPageLayout layout) {
// Add the perspective to the layout
layout.addPerspectiveShortcut(ReactorsPerspective.ID);
return;
}
}
| wo-amlangwang/ice | org.eclipse.ice.reactor.perspective/src/org/eclipse/ice/reactor/perspective/ReactorsPerspective.java | Java | epl-1.0 | 1,442 |
package net.trajano.doxdb.rest;
import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.Provider;
import net.trajano.doxdb.DoxID;
@Provider
public class DoxIDMapper implements
ParamConverter<DoxID> {
@Override
public DoxID fromString(final String s) {
return new DoxID(s);
}
@Override
public String toString(final DoxID doxid) {
return doxid.toString();
}
}
| trajano/doxdb | doxdb-rest/src/main/java/net/trajano/doxdb/rest/DoxIDMapper.java | Java | epl-1.0 | 416 |
#include <iostream>
#include <vector>
#include <iterator>
#include <queue>
#include <functional>
#include <algorithm>
using std::cin;
using std::cout;
using std::vector;
using std::swap;
using std::less;
using std::endl;
using std::cerr;
struct TNode
{
int key;
int index[2];
TNode()
{
index[0] = -1;
index[1] = -1;
}
explicit TNode(int _key)
{
key = _key;
index[0] = -1;
index[1] = -1;
}
bool operator>(const TNode& tn) const
{
return this->key > tn.key;
}
bool operator<(const TNode& tn) const
{
return this->key < tn.key;
}
bool inMinHeap()
{
return index[0] != -1;
}
bool inMaxHeap()
{
return index[1] != -1;
}
};
typedef TNode* tp;
TNode a;
template<class BDIT, int ind = 0>
class IndexGetter
{
public:
IndexGetter()
{}
int& operator()(BDIT it)
{
int index = ind;
if (0 <= ind && ind <= 1) {
index = ind;
}
return it->index[index];
}
private:
};
TNode invalid;
template <class T
, class IndexGetter
, class Compare
= std::less <typename std::iterator_traits <T>::value_type> >
class IndexHeap
{
public:
IndexHeap()
{}
bool empty()
{
return heap.empty();
}
void remove(T it)
{
if (!empty()) {
int tind = ig(it);
if (tind == size() - 1) {
ig(heap.back()) = -1;
heap.pop_back();
return;
}
swp(tind, size() - 1);
ig(heap.back()) = -1;
heap.pop_back();
if (!empty()) {
update_heap(heap[tind]);
}
}
}
size_t size()
{
return heap.size();
}
T top()
{
if (!empty())
return heap[0];
return &invalid;
}
T pop()
{
if (!empty()) {
T ret = top();
remove(ret);
return ret;
}
return &invalid;
}
void insert(T elem)
{
if (elem == &invalid)
return;
if (ig(elem) != -1)
return;
ig(elem) = size();
heap.push_back(elem);
update_heap(elem);
}
void swp(int ftind, int sdind)
{
swap(ig(heap[ftind]), ig(heap[sdind]));
swap(heap[ftind], heap[sdind]);
}
void print()
{
std::cerr << "****************" << endl;
for (int i = 0; i < size(); ++i) {
std::cerr << "heap[" << i << "] : " << heap[i]->key << ", "
<< ig(heap[i]) << std::endl;
}
std::cerr << "****************" << endl << endl;
}
void update_heap(T it)
{
while (shiftUp(it)) {}
while (shiftDown(it)) {}
}
bool shiftUp(T it)
{
int tind, pind;
tind = ig(it);
pind = (tind - 1) / 2;
// cerr << tind << " : " << pind << endl;
if (comp(*(heap[tind]), *(heap[pind]))) {
swp(tind, pind);
return true;
}
return false;
}
bool shiftDown(T it)
{
int leftChild, rightChild, largestChild;
int index = ig(it);
leftChild = index * 2 + 1;
rightChild = index * 2 + 2;
largestChild = index;
if (leftChild < size()
&& comp(*(heap[leftChild]), *(heap[largestChild]))) {
largestChild = leftChild;
}
if (rightChild < size()
&& comp(*(heap[rightChild]), *(heap[largestChild]))) {
largestChild = rightChild;
}
if (largestChild != index) {
swp(index, largestChild);
return true;
}
return false;
}
private:
IndexGetter ig;
vector<T> heap;
Compare comp;
};
int main(int argc, char *argv[])
{
int elemNum, comNum, statNum;
invalid.key = -1;
vector<TNode> nodes;
IndexHeap<tp, IndexGetter<tp, 0>, std::less<TNode> > min_heap;
IndexHeap<tp, IndexGetter<tp, 1>, std::greater<TNode> > max_heap;
cin >> elemNum >> comNum >> statNum;
for (int i = 0; i < elemNum; ++i) {
int telem;
cin >> telem;
nodes.push_back(TNode(telem));
}
int left = 0, right = 0;
max_heap.insert(&nodes[0]);
for (int ind = 0; ind < comNum; ++ind) {
char com;
cin >> com;
if (com == 'R') {
++right;
min_heap.insert(&nodes[right]);
}
/*
* if (ind == 3) {
* cerr << "debug: " << endl;
* cerr << left << " " << right << endl;
* cerr << nodes[left].index[1] << endl;
* max_heap.print();
* }
*/
if (com == 'L') {
if (nodes[left].inMaxHeap()) {
max_heap.remove(&nodes[left]);
} else {
min_heap.remove(&nodes[left]);
}
++left;
}
// cerr << max_heap.size() << " : " << min_heap.size() << endl;
while (max_heap.size() < statNum && !min_heap.empty()) {
tp it = min_heap.pop();
// cerr << it->key << endl;
max_heap.insert(it);
}
while (!max_heap.empty()
&& !min_heap.empty()
&& *max_heap.top() > *min_heap.top()) {
min_heap.insert(max_heap.pop());
max_heap.insert(min_heap.pop());
}
if (max_heap.size() < statNum) {
cout << -1 << endl;
} else {
cout << max_heap.top()->key << endl;
}
}
return 0;
}
| abcdw/shad | homework/alg/3/floating_k_statisctic.cpp | C++ | gpl-2.0 | 5,671 |
/*
* Password Management Servlets (PWM)
* http://www.pwm-project.org
*
* Copyright (c) 2006-2009 Novell, Inc.
* Copyright (c) 2009-2016 The PWM Project
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package password.pwm.util;
import com.novell.ldapchai.ChaiUser;
import com.novell.ldapchai.exception.ChaiOperationException;
import com.novell.ldapchai.exception.ChaiUnavailableException;
import org.apache.commons.csv.CSVPrinter;
import password.pwm.PwmApplication;
import password.pwm.PwmApplicationMode;
import password.pwm.PwmConstants;
import password.pwm.bean.FormNonce;
import password.pwm.bean.SessionLabel;
import password.pwm.config.FormConfiguration;
import password.pwm.config.PwmSetting;
import password.pwm.error.ErrorInformation;
import password.pwm.error.PwmError;
import password.pwm.error.PwmOperationalException;
import password.pwm.error.PwmUnrecoverableException;
import password.pwm.http.PwmRequest;
import password.pwm.http.PwmSession;
import password.pwm.util.logging.PwmLogger;
import password.pwm.util.macro.MacroMachine;
import java.io.*;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.text.NumberFormat;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.regex.Pattern;
/**
* A collection of static methods used throughout PWM
*
* @author Jason D. Rivard
*/
public class
Helper {
// ------------------------------ FIELDS ------------------------------
private static final PwmLogger LOGGER = PwmLogger.forClass(Helper.class);
// -------------------------- STATIC METHODS --------------------------
private Helper() {
}
/**
* Convert a byte[] array to readable string format. This makes the "hex" readable
*
* @param in byte[] buffer to convert to string format
* @return result String buffer in String format
*/
public static String byteArrayToHexString(final byte in[]) {
final String pseudo[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};
if (in == null || in.length <= 0) {
return "";
}
final StringBuilder out = new StringBuilder(in.length * 2);
for (final byte b : in) {
byte ch = (byte) (b & 0xF0); // strip off high nibble
ch = (byte) (ch >>> 4); // shift the bits down
ch = (byte) (ch & 0x0F); // must do this is high order bit is on!
out.append(pseudo[(int) ch]); // convert the nibble to a String Character
ch = (byte) (b & 0x0F); // strip off low nibble
out.append(pseudo[(int) ch]); // convert the nibble to a String Character
}
return out.toString();
}
/**
* Pause the calling thread the specified amount of time.
*
* @param sleepTimeMS - a time duration in milliseconds
* @return time actually spent sleeping
*/
public static long pause(final long sleepTimeMS) {
final long startTime = System.currentTimeMillis();
do {
try {
final long sleepTime = sleepTimeMS - (System.currentTimeMillis() - startTime);
Thread.sleep(sleepTime > 0 ? sleepTime : 5);
} catch (InterruptedException e) {
//who cares
}
} while ((System.currentTimeMillis() - startTime) < sleepTimeMS);
return System.currentTimeMillis() - startTime;
}
/**
* Writes a Map of form values to ldap onto the supplied user object.
* The map key must be a string of attribute names.
* <p/>
* Any ldap operation exceptions are not reported (but logged).
*
* @param pwmSession for looking up session info
* @param theUser User to write to
* @param formValues A map with {@link password.pwm.config.FormConfiguration} keys and String values.
* @throws ChaiUnavailableException if the directory is unavailable
* @throws PwmOperationalException if their is an unexpected ldap problem
*/
public static void writeFormValuesToLdap(
final PwmApplication pwmApplication,
final PwmSession pwmSession,
final ChaiUser theUser,
final Map<FormConfiguration,String> formValues,
final boolean expandMacros
)
throws ChaiUnavailableException, PwmOperationalException, PwmUnrecoverableException
{
final Map<String,String> tempMap = new HashMap<>();
for (final FormConfiguration formItem : formValues.keySet()) {
if (!formItem.isReadonly()) {
tempMap.put(formItem.getName(),formValues.get(formItem));
}
}
final MacroMachine macroMachine = pwmSession.getSessionManager().getMacroMachine(pwmApplication);
writeMapToLdap(theUser, tempMap, macroMachine, expandMacros);
}
/**
* Writes a Map of values to ldap onto the supplied user object.
* The map key must be a string of attribute names.
* <p/>
* Any ldap operation exceptions are not reported (but logged).
*
* @param theUser User to write to
* @param valueMap A map with String keys and String values.
* @throws ChaiUnavailableException if the directory is unavailable
* @throws PwmOperationalException if their is an unexpected ldap problem
*/
public static void writeMapToLdap(
final ChaiUser theUser,
final Map<String,String> valueMap,
final MacroMachine macroMachine,
final boolean expandMacros
)
throws PwmOperationalException, ChaiUnavailableException
{
final Map<String,String> currentValues;
try {
currentValues = theUser.readStringAttributes(valueMap.keySet());
} catch (ChaiOperationException e) {
final String errorMsg = "error reading existing values on user " + theUser.getEntryDN() + " prior to replacing values, error: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg);
final PwmOperationalException newException = new PwmOperationalException(errorInformation);
newException.initCause(e);
throw newException;
}
for (final String attrName : valueMap.keySet()) {
String attrValue = valueMap.get(attrName) != null ? valueMap.get(attrName) : "";
if (expandMacros) {
attrValue = macroMachine.expandMacros(attrValue);
}
if (!attrValue.equals(currentValues.get(attrName))) {
if (attrValue.length() > 0) {
try {
theUser.writeStringAttribute(attrName, attrValue);
LOGGER.info("set attribute on user " + theUser.getEntryDN() + " (" + attrName + "=" + attrValue + ")");
} catch (ChaiOperationException e) {
final String errorMsg = "error setting '" + attrName + "' attribute on user " + theUser.getEntryDN() + ", error: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg);
final PwmOperationalException newException = new PwmOperationalException(errorInformation);
newException.initCause(e);
throw newException;
}
} else {
if (currentValues.get(attrName) != null && currentValues.get(attrName).length() > 0) {
try {
theUser.deleteAttribute(attrName, null);
LOGGER.info("deleted attribute value on user " + theUser.getEntryDN() + " (" + attrName + ")");
} catch (ChaiOperationException e) {
final String errorMsg = "error removing '" + attrName + "' attribute value on user " + theUser.getEntryDN() + ", error: " + e.getMessage();
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg);
final PwmOperationalException newException = new PwmOperationalException(errorInformation);
newException.initCause(e);
throw newException;
}
}
}
} else {
LOGGER.debug("skipping attribute modify for attribute '" + attrName + "', no change in value");
}
}
}
public static String binaryArrayToHex(final byte[] buf) {
final char[] HEX_CHARS = "0123456789ABCDEF".toCharArray();
final char[] chars = new char[2 * buf.length];
for (int i = 0; i < buf.length; ++i) {
chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
}
return new String(chars);
}
public static String formatDiskSize(final long diskSize) {
final float COUNT = 1000;
if (diskSize < 1) {
return "n/a";
}
if (diskSize == 0) {
return "0";
}
final NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
if (diskSize > COUNT * COUNT * COUNT) {
final StringBuilder sb = new StringBuilder();
sb.append(nf.format(diskSize / COUNT / COUNT / COUNT));
sb.append(" GB");
return sb.toString();
}
if (diskSize > COUNT * COUNT) {
final StringBuilder sb = new StringBuilder();
sb.append(nf.format(diskSize / COUNT / COUNT));
sb.append(" MB");
return sb.toString();
}
return NumberFormat.getInstance().format(diskSize) + " bytes";
}
static public String buildPwmFormID(final PwmRequest pwmRequest) throws PwmUnrecoverableException {
final FormNonce formID = new FormNonce(
pwmRequest.getPwmSession().getLoginInfoBean().getGuid(),
new Date(),
pwmRequest.getPwmSession().getLoginInfoBean().getReqCounter()
);
return pwmRequest.getPwmApplication().getSecureService().encryptObjectToString(formID);
}
public static void rotateBackups(final File inputFile, final int maxRotate) {
if (maxRotate < 1) {
return;
}
for (int i = maxRotate; i >= 0; i--) {
final File thisFile = (i == 0) ? inputFile : new File(inputFile.getAbsolutePath() + "-" + i);
final File youngerFile = (i <= 1) ? inputFile : new File(inputFile.getAbsolutePath() + "-" + (i - 1));
if (i == maxRotate) {
if (thisFile.exists()) {
LOGGER.debug("deleting old backup file: " + thisFile.getAbsolutePath());
if (!thisFile.delete()) {
LOGGER.error("unable to delete old backup file: " + thisFile.getAbsolutePath());
}
}
} else if (i == 0 || youngerFile.exists()) {
final File destFile = new File(inputFile.getAbsolutePath() + "-" + (i + 1));
LOGGER.debug("backup file " + thisFile.getAbsolutePath() + " renamed to " + destFile.getAbsolutePath());
if (!thisFile.renameTo(destFile)) {
LOGGER.debug("unable to rename file " + thisFile.getAbsolutePath() + " to " + destFile.getAbsolutePath());
}
}
}
}
public static Date nextZuluZeroTime() {
final Calendar nextZuluMidnight = GregorianCalendar.getInstance(TimeZone.getTimeZone("Zulu"));
nextZuluMidnight.set(Calendar.HOUR_OF_DAY,0);
nextZuluMidnight.set(Calendar.MINUTE,0);
nextZuluMidnight.set(Calendar.SECOND, 0);
nextZuluMidnight.add(Calendar.HOUR, 24);
return nextZuluMidnight.getTime();
}
public static String makeThreadName(final PwmApplication pwmApplication, final Class theClass) {
String instanceName = "-";
if (pwmApplication != null && pwmApplication.getInstanceID() != null) {
instanceName = pwmApplication.getInstanceID();
}
return PwmConstants.PWM_APP_NAME + "-" + instanceName + "-" + theClass.getSimpleName();
}
public static void checkUrlAgainstWhitelist(
final PwmApplication pwmApplication,
final SessionLabel sessionLabel,
final String inputURL
)
throws PwmOperationalException
{
LOGGER.trace(sessionLabel, "beginning test of requested redirect URL: " + inputURL);
if (inputURL == null || inputURL.isEmpty()) {
return;
}
final URI inputURI;
try {
inputURI = URI.create(inputURL);
} catch (IllegalArgumentException e) {
LOGGER.error(sessionLabel, "unable to parse requested redirect url '" + inputURL + "', error: " + e.getMessage());
// dont put input uri in error response
final String errorMsg = "unable to parse url: " + e.getMessage();
throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_REDIRECT_ILLEGAL,errorMsg));
}
{ // check to make sure we werent handed a non-http uri.
final String scheme = inputURI.getScheme();
if (scheme != null && !scheme.isEmpty() && !scheme.equalsIgnoreCase("http") && !scheme.equals("https")) {
final String errorMsg = "unsupported url scheme";
throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_REDIRECT_ILLEGAL,errorMsg));
}
}
if (inputURI.getHost() != null && !inputURI.getHost().isEmpty()) { // disallow localhost uri
try {
InetAddress inetAddress = InetAddress.getByName(inputURI.getHost());
if (inetAddress.isLoopbackAddress()) {
final String errorMsg = "redirect to loopback host is not permitted";
throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_REDIRECT_ILLEGAL,errorMsg));
}
} catch (UnknownHostException e) {
/* noop */
}
}
final StringBuilder sb = new StringBuilder();
if (inputURI.getScheme() != null) {
sb.append(inputURI.getScheme());
sb.append("://");
}
if (inputURI.getHost() != null) {
sb.append(inputURI.getHost());
}
if (inputURI.getPort() != -1) {
sb.append(":");
sb.append(inputURI.getPort());
}
if (inputURI.getPath() != null) {
sb.append(inputURI.getPath());
}
final String testURI = sb.toString();
LOGGER.trace(sessionLabel, "preparing to whitelist test parsed and decoded URL: " + testURI);
final String REGEX_PREFIX = "regex:";
final List<String> whiteList = pwmApplication.getConfig().readSettingAsStringArray(PwmSetting.SECURITY_REDIRECT_WHITELIST);
for (final String loopFragment : whiteList) {
if (loopFragment.startsWith(REGEX_PREFIX)) {
try {
final String strPattern = loopFragment.substring(REGEX_PREFIX.length(), loopFragment.length());
final Pattern pattern = Pattern.compile(strPattern);
if (pattern.matcher(testURI).matches()) {
LOGGER.debug(sessionLabel, "positive URL match for regex pattern: " + strPattern);
return;
} else {
LOGGER.trace(sessionLabel, "negative URL match for regex pattern: " + strPattern);
}
} catch (Exception e) {
LOGGER.error(sessionLabel, "error while testing URL match for regex pattern: '" + loopFragment + "', error: " + e.getMessage());;
}
} else {
if (testURI.startsWith(loopFragment)) {
LOGGER.debug(sessionLabel, "positive URL match for pattern: " + loopFragment);
return;
} else {
LOGGER.trace(sessionLabel, "negative URL match for pattern: " + loopFragment);
}
}
}
final String errorMsg = testURI + " is not a match for any configured redirect whitelist, see setting: " + PwmSetting.SECURITY_REDIRECT_WHITELIST.toMenuLocationDebug(null,PwmConstants.DEFAULT_LOCALE);
throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_REDIRECT_ILLEGAL,errorMsg));
}
public static boolean determineIfDetailErrorMsgShown(final PwmApplication pwmApplication) {
if (pwmApplication == null) {
return false;
}
PwmApplicationMode mode = pwmApplication.getApplicationMode();
if (mode == PwmApplicationMode.CONFIGURATION || mode == PwmApplicationMode.NEW) {
return true;
}
if (mode == PwmApplicationMode.RUNNING) {
if (pwmApplication.getConfig() != null) {
if (pwmApplication.getConfig().readSettingAsBoolean(PwmSetting.DISPLAY_SHOW_DETAILED_ERRORS)) {
return true;
}
}
}
return false;
}
public static CSVPrinter makeCsvPrinter(final OutputStream outputStream)
throws IOException
{
return new CSVPrinter(new OutputStreamWriter(outputStream,PwmConstants.DEFAULT_CHARSET), PwmConstants.DEFAULT_CSV_FORMAT);
}
public static <E extends Enum<E>> E readEnumFromString(Class<E> enumClass, E defaultValue, String input) {
if (input == null) {
return defaultValue;
}
try {
Method valueOfMethod = enumClass.getMethod("valueOf", String.class);
Object result = valueOfMethod.invoke(null, input);
return (E) result;
} catch (IllegalArgumentException e) {
LOGGER.trace("input=" + input + " does not exist in enumClass=" + enumClass.getSimpleName());
} catch (Exception e) {
LOGGER.warn("unexpected error translating input=" + input + " to enumClass=" + enumClass.getSimpleName());
}
return defaultValue;
}
public static Properties newSortedProperties() {
return new Properties() {
public synchronized Enumeration<Object> keys() {
return Collections.enumeration(new TreeSet<>(super.keySet()));
}
};
}
public static ThreadFactory makePwmThreadFactory(final String namePrefix, final boolean daemon) {
return new ThreadFactory() {
private final ThreadFactory realThreadFactory = Executors.defaultThreadFactory();
@Override
public Thread newThread(final Runnable r) {
final Thread t = realThreadFactory.newThread(r);
t.setDaemon(daemon);
if (namePrefix != null) {
final String newName = namePrefix + t.getName();
t.setName(newName);
}
return t;
}
};
}
public static String throwableToString(final Throwable throwable) {
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw);
throwable.printStackTrace(pw);
pw.flush();
return sw.toString();
}
/**
* Converts an exception to a string message. Handles cases where the message in the exception is null
* and/or there are multiple nested cause exceptions.
* @param e The exception to convert to a string
* @return A string containing any meaningful extractable cause information, suitable for debugging.
*/
public static String readHostileExceptionMessage(Throwable e) {
String errorMsg = e.getClass().getName();
if (e.getMessage() != null) {
errorMsg += ": " + e.getMessage();
}
Throwable cause = e.getCause();
int safetyCounter = 0;
while (cause != null && safetyCounter < 10) {
safetyCounter++;
errorMsg += ", cause:" + cause.getClass().getName();
if (cause.getMessage() != null) {
errorMsg += ": " + cause.getMessage();
}
cause = cause.getCause();
}
return errorMsg;
}
public static <E extends Enum<E>> boolean enumArrayContainsValue(final E[] enumArray, final E enumValue) {
return !(enumArray == null || enumArray.length == 0) && Arrays.asList(enumArray).contains(enumValue);
}
}
| bonhamcm/pwm | src/main/java/password/pwm/util/Helper.java | Java | gpl-2.0 | 21,609 |
/********************************************\
*
* Sire - Molecular Simulation Framework
*
* Copyright (C) 2008 Christopher Woods
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* For full details of the license please see the COPYING file
* that should have come with this distribution.
*
* You can contact the authors via the developer's mailing list
* at http://siremol.org
*
\*********************************************/
#include "SireStream/streamdata.hpp"
using namespace SireStream;
static const RegisterLibrary *registry = new RegisterLibrary( QString("SireIO"), 1, 1 );
| chryswoods/Sire | corelib/src/libs/SireIO/register_sireio.cpp | C++ | gpl-2.0 | 1,308 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.myapp.struts;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class LoginAction extends org.apache.struts.action.Action {
/* forward name="success" path="" */
private static final String SUCCESS = "success";
private static final String FAILURE = "failure";
/**
* This is the action called from the Struts framework.
* @param mapping The ActionMapping used to select this instance.
* @param form The optional ActionForm bean for this request.
* @param request The HTTP Request we are processing.
* @param response The HTTP Response we are processing.
* @throws java.lang.Exception
* @return
*/
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
LoginActionForm data = (LoginActionForm)form;
String username = data.getUsername();
String pass = data.getPass();
if ((username.equals("admin")) && (pass.equals("admin")))
{ HttpSession session = request.getSession(true);
session.setAttribute("user", "admin");
return mapping.findForward(SUCCESS);
} else {
return mapping.findForward(FAILURE);
}
}
}
| kawzar/tdp | src/java/com/myapp/struts/LoginAction.java | Java | gpl-2.0 | 1,684 |
<?php
/*The supplier transaction uses the SuppTrans class to hold the information about the invoice or credit note
the SuppTrans class contains an array of GRNs objects - containing details of GRNs for invoicing/crediting and also
an array of GLCodes objects - only used if the AP - GL link is effective */
include('includes/DefineSuppTransClass.php');
/* Session started in header.inc for password checking and authorisation level check */
include('includes/session.inc');
$Title = _('Supplier Transaction General Ledger Analysis');
$ViewTopic = 'AccountsPayable';
$BookMark = 'SuppTransGLAnalysis';
include('includes/header.inc');
if (!isset($_SESSION['SuppTrans'])) {
prnMsg(_('To enter a supplier invoice or credit note the supplier must first be selected from the supplier selection screen') . ', ' . _('then the link to enter a supplier invoice or supplier credit note must be clicked on'), 'info');
echo '<br /><a href="' . $RootPath . '/SelectSupplier.php">' . _('Select A Supplier') . '</a>';
include('includes/footer.inc');
exit;
/*It all stops here if there aint no supplier selected and transaction initiated ie $_SESSION['SuppTrans'] started off*/
}
/*If the user hit the Add to transaction button then process this first before showing all GL codes on the transaction otherwise it wouldnt show the latest addition*/
if (isset($_POST['AddGLCodeToTrans']) and $_POST['AddGLCodeToTrans'] == _('Enter GL Line')) {
$InputError = False;
if ($_POST['GLCode'] == '') {
$_POST['GLCode'] = $_POST['AcctSelection'];
}
if ($_POST['GLCode'] == '') {
prnMsg(_('You must select a general ledger code from the list below'), 'warn');
$InputError = True;
}
$SQL = "SELECT accountcode,
accountname
FROM chartmaster
WHERE accountcode='" . $_POST['GLCode'] . "'
AND chartmaster.language='" . $_SESSION['ChartLanguage'] . "'";
$Result = DB_query($SQL);
if (DB_num_rows($Result) == 0 and $_POST['GLCode'] != '') {
prnMsg(_('The account code entered is not a valid code') . '. ' . _('This line cannot be added to the transaction') . '.<br />' . _('You can use the selection box to select the account you want'), 'error');
$InputError = True;
} else if ($_POST['GLCode'] != '') {
$MyRow = DB_fetch_row($Result);
$GLActName = $MyRow[1];
if (!is_numeric(filter_number_format($_POST['Amount']))) {
prnMsg(_('The amount entered is not numeric') . '. ' . _('This line cannot be added to the transaction'), 'error');
$InputError = True;
} elseif ($_POST['JobRef'] != '') {
$SQL = "SELECT contractref FROM contracts WHERE contractref='" . $_POST['JobRef'] . "'";
$Result = DB_query($SQL);
if (DB_num_rows($Result) == 0) {
prnMsg(_('The contract reference entered is not a valid contract, this line cannot be added to the transaction'), 'error');
$InputError = True;
}
}
}
if ($InputError == False) {
$_SESSION['SuppTrans']->Add_GLCodes_To_Trans($_POST['GLCode'], $GLActName, filter_number_format($_POST['Amount']), $_POST['Narrative'], $_POST['Tag']);
unset($_POST['GLCode']);
unset($_POST['Amount']);
unset($_POST['JobRef']);
unset($_POST['Narrative']);
unset($_POST['AcctSelection']);
unset($_POST['Tag']);
}
}
if (isset($_GET['Delete'])) {
$_SESSION['SuppTrans']->Remove_GLCodes_From_Trans($_GET['Delete']);
}
if (isset($_GET['Edit'])) {
$_POST['GLCode'] = $_SESSION['SuppTrans']->GLCodes[$_GET['Edit']]->GLCode;
$_POST['AcctSelection'] = $_SESSION['SuppTrans']->GLCodes[$_GET['Edit']]->GLCode;
$_POST['Amount'] = $_SESSION['SuppTrans']->GLCodes[$_GET['Edit']]->Amount;
$_POST['JobRef'] = $_SESSION['SuppTrans']->GLCodes[$_GET['Edit']]->JobRef;
$_POST['Narrative'] = $_SESSION['SuppTrans']->GLCodes[$_GET['Edit']]->Narrative;
$_POST['Tag'] = $_SESSION['SuppTrans']->GLCodes[$_GET['Edit']]->Tag;
$_SESSION['SuppTrans']->Remove_GLCodes_From_Trans($_GET['Edit']);
}
/*Show all the selected GLCodes so far from the SESSION['SuppInv']->GLCodes array */
if ($_SESSION['SuppTrans']->InvoiceOrCredit == 'Invoice') {
echo '<p class="page_title_text" >
<img src="' . $RootPath . '/css/' . $_SESSION['Theme'] . '/images/transactions.png" title="' . _('General Ledger') . '" alt="" />' . ' ' . _('General Ledger Analysis of Invoice From') . ' ' . $_SESSION['SuppTrans']->SupplierName;
} else {
echo '<p class="page_title_text" >
<img src="' . $RootPath . '/css/' . $_SESSION['Theme'] . '/images/transactions.png" title="' . _('General Ledger') . '" alt="" />' . ' ' . _('General Ledger Analysis of Credit Note From') . ' ' . $_SESSION['SuppTrans']->SupplierName;
}
echo '</p>
<table class="selection">
<thead>
<tr>
<th class="SortedColumn">' . _('Account') . '</th>
<th class="SortedColumn">' . _('Name') . '</th>
<th class="SortedColumn">' . _('Amount') . '<br />(' . $_SESSION['SuppTrans']->CurrCode . ')</th>
<th>' . _('Narrative') . '</th>
<th>' . _('Tag') . '</th>
<th colspan="2"> </th>
</tr>
</thead>';
$TotalGLValue = 0;
$i = 0;
echo '<tbody>';
foreach ($_SESSION['SuppTrans']->GLCodes as $EnteredGLCode) {
echo '<tr>
<td class="text">' . $EnteredGLCode->GLCode . '</td>
<td class="text">' . $EnteredGLCode->GLActName . '</td>
<td class="number">' . locale_number_format($EnteredGLCode->Amount, $_SESSION['SuppTrans']->CurrDecimalPlaces) . '</td>
<td class="text">' . $EnteredGLCode->Narrative . '</td>
<td class="text">' . $EnteredGLCode->Tag . ' - ' . $EnteredGLCode->TagName . '</td>
<td><a href="' . htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '?Edit=' . $EnteredGLCode->Counter . '">' . _('Edit') . '</a></td>
<td><a href="' . htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '?Delete=' . $EnteredGLCode->Counter . '">' . _('Delete') . '</a></td>
</tr>';
$TotalGLValue += $EnteredGLCode->Amount;
}
echo '</tbody>';
echo '<tr>
<td colspan="2" class="number">' . _('Total') . ':</td>
<td class="number">' . locale_number_format($TotalGLValue, $_SESSION['SuppTrans']->CurrDecimalPlaces) . '</td>
<td colspan="4"> </td>
</tr>
</table>';
if ($_SESSION['SuppTrans']->InvoiceOrCredit == 'Invoice') {
echo '<br />
<div class="centre">
<a href="' . $RootPath . '/SupplierInvoice.php">' . _('Back to Invoice Entry') . '</a>
</div>';
} else {
echo '<br />
<div class="centre">
<a href="' . $RootPath . '/SupplierCredit.php">' . _('Back to Credit Note Entry') . '</a>
</div>';
}
/*Set up a form to allow input of new GL entries */
echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '" method="post">';
echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';
echo '<br />
<table class="selection">';
if (!isset($_POST['GLCode'])) {
$_POST['GLCode'] = '';
}
echo '<tr>
<td>' . _('Select Tag') . ':</td>
<td><select name="Tag">';
$SQL = "SELECT tagref,
tagdescription
FROM tags
ORDER BY tagref";
$Result = DB_query($SQL);
echo '<option value="0"></option>';
while ($MyRow = DB_fetch_array($Result)) {
if (isset($_POST['Tag']) and $_POST['Tag'] == $MyRow['tagref']) {
echo '<option selected="selected" value="' . $MyRow['tagref'] . '">' . $MyRow['tagref'] . ' - ' . $MyRow['tagdescription'] . '</option>';
} else {
echo '<option value="' . $MyRow['tagref'] . '">' . $MyRow['tagref'] . ' - ' . $MyRow['tagdescription'] . '</option>';
}
}
echo '</select></td>
</tr>';
echo '<tr>
<td>' . _('Account Code') . ':</td>
<td><input type="text" name="GLCode" size="12" required="required" maxlength="11" value="' . $_POST['GLCode'] . '" />
<input type="hidden" name="JobRef" value="" /></td>
</tr>';
echo '<tr>
<td>' . _('Account Selection') . ':
<br />(' . _('If you know the code enter it above') . '
<br />' . _('otherwise select the account from the list') . ')</td>
<td><select name="AcctSelection" onchange="return assignComboToInput(this,' . 'GLCode' . ')">';
$SQL = "SELECT accountcode,
accountname
FROM chartmaster
WHERE language='" . $_SESSION['ChartLanguage'] . "'
ORDER BY accountcode";
$Result = DB_query($SQL);
echo '<option value=""></option>';
while ($MyRow = DB_fetch_array($Result)) {
if (isset($_POST['AcctSelection']) and $MyRow['accountcode'] == $_POST['AcctSelection']) {
echo '<option selected="selected" value="';
} else {
echo '<option value="';
}
echo $MyRow['accountcode'] . '">' . $MyRow['accountcode'] . ' - ' . htmlspecialchars($MyRow['accountname'], ENT_QUOTES, 'UTF-8', false) . '</option>';
}
echo '</select>
</td>
</tr>';
if (!isset($_POST['Amount'])) {
$_POST['Amount'] = 0;
}
echo '<tr>
<td>', _('Amount'), ' (', $_SESSION['SuppTrans']->CurrCode, '):</td>
<td><input type="text" class="number" name="Amount" size="12" required="required" maxlength="11" value="' . locale_number_format($_POST['Amount'], $_SESSION['SuppTrans']->CurrDecimalPlaces) . '" /></td>
</tr>';
if (!isset($_POST['Narrative'])) {
$_POST['Narrative'] = '';
}
echo '<tr>
<td>' . _('Narrative') . ':</td>
<td><textarea name="Narrative" cols="40" rows="2">' . $_POST['Narrative'] . '</textarea></td>
</tr>
</table>
<br />';
echo '<div class="centre">
<input type="submit" name="AddGLCodeToTrans" value="' . _('Enter GL Line') . '" />
</div>';
echo '</form>';
include('includes/footer.inc');
?> | fahadhatib/KwaMoja | SuppTransGLAnalysis.php | PHP | gpl-2.0 | 9,263 |
/*
* Project Danielle (v.1)
* Daniel Tixier
* Started 3/8/2013.
*
* Major shell work completed 3/19.
* Major GUI work completed 3/29.
* Major initial bid/play logic completed 3/31.
* Major debugging started 3/31, break took from 4/2 - 4/16.
* Worked on displaying card pics, completed 4/21.
* Running prototype 4/21
* Master background with exit button and scores 4/22
* Major renovations (bidding nil, redealing, catching wrong input exception, slimming main method)completed 4/23
*
*
* Danielle is a heuristic-based, pseudo AI (with GUI implementation) that plays a hand of the 4-player
* card game Spades. It considers itself as sitting in the West position.
*/
package danielle_1;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.BevelBorder;
public class Danielle_1 {
static final int TWO_SPADES = 0;
static final int THREE_SPADES = 1;
static final int FOUR_SPADES = 2;
static final int FIVE_SPADES = 3;
static final int SIX_SPADES = 4;
static final int SEVEN_SPADES = 5;
static final int EIGHT_SPADES = 6;
static final int NINE_SPADES = 7;
static final int TEN_SPADES = 8;
static final int JACK_SPADES = 9;
static final int QUEEN_SPADES = 10;
static final int KING_SPADES = 11;
static final int ACE_SPADES = 12;
static final int TWO_HEARTS = 13;
static final int THREE_HEARTS = 14;
static final int FOUR_HEARTS = 15;
static final int FIVE_HEARTS = 16;
static final int SIX_HEARTS = 17;
static final int SEVEN_HEARTS = 18;
static final int EIGHT_HEARTS = 19;
static final int NINE_HEARTS = 20;
static final int TEN_HEARTS = 21;
static final int JACK_HEARTS = 22;
static final int QUEEN_HEARTS = 23;
static final int KING_HEARTS = 24;
static final int ACE_HEARTS = 25;
static final int TWO_CLUBS = 26;
static final int THREE_CLUBS = 27;
static final int FOUR_CLUBS = 28;
static final int FIVE_CLUBS = 29;
static final int SIX_CLUBS = 30;
static final int SEVEN_CLUBS = 31;
static final int EIGHT_CLUBS = 32;
static final int NINE_CLUBS = 33;
static final int TEN_CLUBS = 34;
static final int JACK_CLUBS = 35;
static final int QUEEN_CLUBS = 36;
static final int KING_CLUBS = 37;
static final int ACE_CLUBS = 38;
static final int TWO_DIAMONDS = 39;
static final int THREE_DIAMONDS = 40;
static final int FOUR_DIAMONDS = 41;
static final int FIVE_DIAMONDS = 42;
static final int SIX_DIAMONDS = 43;
static final int SEVEN_DIAMONDS = 44;
static final int EIGHT_DIAMONDS = 45;
static final int NINE_DIAMONDS = 46;
static final int TEN_DIAMONDS = 47;
static final int JACK_DIAMONDS = 48;
static final int QUEEN_DIAMONDS = 49;
static final int KING_DIAMONDS = 50;
static final int ACE_DIAMONDS = 51;
static char[] dd = new char[52];
static ImageIcon[] cardPictureIcon = new ImageIcon[52];
static ArrayList<JLabel> cardPictureLabel = new ArrayList<>();
static JFrame background = new JFrame();
static JPanel statusPanel = new JPanel();
static JLabel scoresLabel = new JLabel();
static JLabel bidsLabel = new JLabel();
static JLabel tricksLabel = new JLabel();
static final int W = 0, N = 1, E = 2, S = 3;
static boolean isWnil, isNnil, isEnil, isSnil, isWsetnil, isNsetnil, isEsetnil, isSsetnil;
static int bidW, bidN, bidE, bidS, ourBid, theirBid, ourTricks, theirTricks;
// Leader Constant, Bidding Constant, and High Card
static int lc, bc, hc;
static int[] currentTrick = new int[4];// represents a trick
// Names of players
static String partner = "", opponentN = "", opponentS = "";
static int we = 0, they = 0, ourBags = 0, theirBags = 0;
static int winningPointValue;
//@SuppressWarnings("empty-statement")
public static void main(String[] args) {
// Add a try-catch structure to let the user know that something went wrong when running external to netbeans.
try{
// Initialize the 52 card pictures
for (int i = 0; i < 52; i++) {
cardPictureIcon[i] = new ImageIcon(Danielle_1.class.getResource("cardPictures/"+(i)+".png"));
}
// Initialize the 52 card labels
for (int i = 0; i < 52; i++) {
cardPictureLabel.add(new JLabel(cardPictureIcon[i]));
}
// Other variables
String winningTeam = "Danielle and "+partner;
// Set properties of the main frame for the program
background.setTitle("Danielle_1.1");
background.setSize(660, 600);
background.setLocationRelativeTo(null);
background.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
background.setVisible(true);
background.setLayout(new BorderLayout());
// Make a button to close the program.
JButton closeButton = new JButton("Close Danielle_1.1");
closeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
int option = JOptionPane.showConfirmDialog(background, "Exit the program?");
if(option == JOptionPane.YES_OPTION)
System.exit(0);
}
});
background.add(closeButton,BorderLayout.SOUTH);
statusPanel.setLayout(new BorderLayout());
statusPanel.add(scoresLabel, BorderLayout.NORTH);
statusPanel.add(bidsLabel, BorderLayout.CENTER);
statusPanel.add(tricksLabel, BorderLayout.SOUTH);
background.add(statusPanel, BorderLayout.NORTH);
// Get names
partner = JOptionPane.showInputDialog(null, "Enter name of partner.");
opponentN = JOptionPane.showInputDialog(null, "Enter name of opponent North.");
opponentS = JOptionPane.showInputDialog(null, "Enter name of opponent South.");
// Who bids first switches every deal, vs. who leads switches every trick.
String bcAsString = JOptionPane.showInputDialog(null, "Who bids first?\nEnter name as entered previously.");
bc = W;// Default Danielle bids
if(bcAsString.equalsIgnoreCase("Danielle"))
bc = W;
else if(bcAsString.equalsIgnoreCase(opponentN))
bc = N;
else if(bcAsString.equalsIgnoreCase(partner))
bc = E;
else if(bcAsString.equalsIgnoreCase(opponentS))
bc = S;
else{
JOptionPane.showMessageDialog(null, "You entered \"Who bids first?\" wrong. Now I have to start over.", "Fail Box", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
// What are we playing to?
String wpvAsString = JOptionPane.showInputDialog(null, "What are we playing to? (Ex: 500)");
winningPointValue = Integer.parseInt(wpvAsString);
int highestScore = 0;
while(highestScore < winningPointValue){
// Reset everything to 0 for the new hand.
// Reset tricks taken to 0.
ourTricks = 0; theirTricks = 0;
// Set leader constant equal to whoever bid first, since we are starting a new hand
lc = bc;
hc = 0;// The ever-changing high card
// int[] currentTrick = new int[4];// represents a trick
isWnil = false; isNnil = false; isEnil = false; isSnil = false; isWsetnil = false; isNsetnil = false; isEsetnil = false; isSsetnil = false;
ourBid = 0;
theirBid = 0;
// Loop in case Danielle calls a redeal
while(true){
// Reset all the cards to no information
for (int i = 0; i < 52; i++) {
dd[i] = '\u0000';
}
HandInputFrame hif = new HandInputFrame('W');
hif.setTitle("Input Danielle's Hand");
hif.setLocationRelativeTo(null);
hif.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
hif.setVisible(true);
// Give time to enter values into frame
while(hif.isVisible()){
System.out.print("");
}
bidW = bidding();
// Call a redeal now if you are going to call it.
if(bidW != -2)
break;
else
JOptionPane.showMessageDialog(null, "Danielle calls redeal. New hand!! Yes!!");
}
DisplayCardsFrame dcf = new DisplayCardsFrame();
// Bidding can't be exported to a method easily because of the continue aspect of a redeal.
String s; // To use in getting values from inputdialogs
// Other bids, switching on order of dealer, so input in the right order.
switch(bc){
case W:
// Danielle bids
if(bidW == -1){
JOptionPane.showMessageDialog(null, "Danielle bids nil");
ourBid += 1;// To get back to 0 when added up later.
isWnil = true;
}
else
JOptionPane.showMessageDialog(null, "Danielle bids "+bidW);
s = JOptionPane.showInputDialog(null, "What does "+opponentN+" bid?", "Input "+opponentN+"'s bid.", JOptionPane.QUESTION_MESSAGE);
bidN = Integer.parseInt(s);
if(bidN == -2){
dcf.dispose();
JOptionPane.showMessageDialog(null, "Redeal!");
continue;//redeal
}
else if(bidN == -1){
isNnil = true;
theirBid += 1;
}
s = JOptionPane.showInputDialog(null, "What does "+partner+" bid?", "Input "+partner+"'s bid.", JOptionPane.QUESTION_MESSAGE);
bidE = Integer.parseInt(s);
if(bidE == -2){
dcf.dispose();
JOptionPane.showMessageDialog(null, "Redeal!");
continue;//redeal
}
else if(bidE == -1){
isEnil = true;
ourBid +=1;
}
s = JOptionPane.showInputDialog(null, "What does "+opponentS+" bid?", "Input "+opponentS+"'s bid.", JOptionPane.QUESTION_MESSAGE);
bidS = Integer.parseInt(s);
if(bidS == -2){
dcf.dispose();
JOptionPane.showMessageDialog(null, "Redeal!");
continue;//redeal
}
else if(bidS == -1){
isSnil = true;
theirBid +=1;
}
break;
case N:
s = JOptionPane.showInputDialog(null, "What does "+opponentN+" bid?", "Input "+opponentN+"'s bid.", JOptionPane.QUESTION_MESSAGE);
bidN = Integer.parseInt(s);
if(bidN == -2){
dcf.dispose();
JOptionPane.showMessageDialog(null, "Redeal!");
continue;//redeal
}
else if(bidN == -1){
isNnil = true;
theirBid += 1;
}
s = JOptionPane.showInputDialog(null, "What does "+partner+" bid?", "Input "+partner+"'s bid.", JOptionPane.QUESTION_MESSAGE);
bidE = Integer.parseInt(s);
if(bidE == -2){
dcf.dispose();
JOptionPane.showMessageDialog(null, "Redeal!");
continue;//redeal
}
else if(bidE == -1){
isEnil = true;
ourBid +=1;
}
s = JOptionPane.showInputDialog(null, "What does "+opponentS+" bid?", "Input "+opponentS+"'s bid.", JOptionPane.QUESTION_MESSAGE);
bidS = Integer.parseInt(s);
if(bidS == -2){
dcf.dispose();
JOptionPane.showMessageDialog(null, "Redeal!");
continue;//redeal
}
else if(bidS == -1){
isSnil = true;
theirBid +=1;
}
// Danielle bids
if(bidW == -1){
JOptionPane.showMessageDialog(null, "Danielle bids nil");
ourBid += 1;// To get back to 0 when added up later.
isWnil = true;
}
else
JOptionPane.showMessageDialog(null, "Danielle bids "+bidW);
break;
case E:
s = JOptionPane.showInputDialog(null, "What does "+partner+" bid?", "Input "+partner+"'s bid.", JOptionPane.QUESTION_MESSAGE);
bidE = Integer.parseInt(s);
if(bidE == -2){
dcf.dispose();
JOptionPane.showMessageDialog(null, "Redeal!");
continue;//redeal
}
else if(bidE == -1){
isEnil = true;
ourBid += 1;
}
s = JOptionPane.showInputDialog(null, "What does "+opponentS+" bid?", "Input "+opponentS+"'s bid.", JOptionPane.QUESTION_MESSAGE);
bidS = Integer.parseInt(s);
if(bidS == -2){
dcf.dispose();
JOptionPane.showMessageDialog(null, "Redeal!");
continue;//redeal
}
else if(bidS == -1){
isSnil = true;
theirBid += 1;
}
// Danielle bids
if(bidW == -1){
JOptionPane.showMessageDialog(null, "Danielle bids nil");
ourBid += 1;// To get back to 0 when added up later.
isWnil = true;
}
else
JOptionPane.showMessageDialog(null, "Danielle bids "+bidW);
s = JOptionPane.showInputDialog(null, "What does "+opponentN+" bid?", "Input "+opponentN+"'s bid.", JOptionPane.QUESTION_MESSAGE);
bidN = Integer.parseInt(s);
if(bidN == -2){
dcf.dispose();
JOptionPane.showMessageDialog(null, "Redeal!");
continue;//redeal
}
else if(bidN == -1){
isNnil = true;
theirBid += 1;
}
break;
case S:
s = JOptionPane.showInputDialog(null, "What does "+opponentS+" bid?", "Input "+opponentS+"'s bid.", JOptionPane.QUESTION_MESSAGE);
bidS = Integer.parseInt(s);
if(bidS == -2){
dcf.dispose();
JOptionPane.showMessageDialog(null, "Redeal!");
continue;//redeal
}
else if(bidS == -1){
isSnil = true;
theirBid += 1;
}
// Danielle bids
if(bidW == -1){
JOptionPane.showMessageDialog(null, "Danielle bids nil");
ourBid += 1;// To get back to 0 when added up later.
isWnil = true;
}
else
JOptionPane.showMessageDialog(null, "Danielle bids "+bidW);
s = JOptionPane.showInputDialog(null, "What does "+opponentN+" bid?", "Input "+opponentN+"'s bid.", JOptionPane.QUESTION_MESSAGE);
bidN = Integer.parseInt(s);
if(bidN == -2){
dcf.dispose();
JOptionPane.showMessageDialog(null, "Redeal!");
continue;//redeal
}
else if(bidN == -1){
isNnil = true;
theirBid += 1;
}
s = JOptionPane.showInputDialog(null, "What does "+partner+" bid?", "Input "+partner+"'s bid.", JOptionPane.QUESTION_MESSAGE);
bidE = Integer.parseInt(s);
if(bidE == -2){
dcf.dispose();
JOptionPane.showMessageDialog(null, "Redeal!");
continue;//redeal
}
else if(bidE == -1){
isEnil = true;
ourBid += 1;
}
break;
default:
System.out.println("Order of bidding is wrong somewhow.");
bidS = 0;bidE = 0; bidN = 0;// Make the compiler happy
break;
}// End bids!
// Refresh status lines
scoresLabel.setText(scoreLine());
bidsLabel.setText(bidLine());
tricksLabel.setText(trickLine());
// Combine bidding to simplify things later.
ourBid += bidW + bidE;
theirBid += bidS + bidN;
// For loop represents each trick
for (int i = 0; i < 13; i++) {
// Set all the cards played in the currentTrick to "not played" value of -1
for (int j = 0; j < currentTrick.length; j++) {
currentTrick[j] = -1;
}
// Get cards played, switching on leader so order is correct
switch(lc){
case W:
currentTrick[W] = daniellePlays(/*lc, isWnil, isNnil, isEnil, isSnil, isWsetnil, isNsetnil, isEsetnil, isSsetnil,currentTrick, ourTricks, theirTricks, ourBid, theirBid*/);
// Always refresh the hand view before showing which card played, for aesthetics
dcf.dispose();
dcf = new DisplayCardsFrame();
JOptionPane.showMessageDialog(null, cardPictureIcon[currentTrick[W]],"Danielle plays card #"+currentTrick[W], JOptionPane.PLAIN_MESSAGE);
hc = currentTrick[W];
currentTrick[N] = humanPlays('N');
currentTrick[E] = humanPlays('E');
currentTrick[S] = humanPlays('S');
break;
case N:
currentTrick[N] = humanPlays('N');
hc = currentTrick[N];
currentTrick[E] = humanPlays('E');
currentTrick[S] = humanPlays('S');
currentTrick[W] = daniellePlays(/*lc, isWnil, isNnil, isEnil, isSnil, isWsetnil, isNsetnil, isEsetnil, isSsetnil, currentTrick, ourTricks, theirTricks, ourBid, theirBid*/);
dcf.dispose();
dcf = new DisplayCardsFrame();
JOptionPane.showMessageDialog(null, cardPictureIcon[currentTrick[W]],"Danielle plays card #"+currentTrick[W], JOptionPane.PLAIN_MESSAGE);
break;
case E:
currentTrick[E] = humanPlays('E');
hc = currentTrick[E];
currentTrick[S] = humanPlays('S');
currentTrick[W] = daniellePlays(/*lc, isWnil, isNnil, isEnil, isSnil, isWsetnil, isNsetnil, isEsetnil, isSsetnil, currentTrick, ourTricks, theirTricks, ourBid, theirBid*/);
dcf.dispose();
dcf = new DisplayCardsFrame();
JOptionPane.showMessageDialog(null, cardPictureIcon[currentTrick[W]],"Danielle plays card #"+currentTrick[W], JOptionPane.PLAIN_MESSAGE);
currentTrick[N] = humanPlays('N');
break;
case S:
currentTrick[S] = humanPlays('S');
hc = currentTrick[S];
currentTrick[W] = daniellePlays(/*lc, isWnil, isNnil, isEnil, isSnil, isWsetnil, isNsetnil, isEsetnil, isSsetnil, currentTrick, ourTricks, theirTricks, ourBid, theirBid*/);
dcf.dispose();
dcf = new DisplayCardsFrame();
JOptionPane.showMessageDialog(null, cardPictureIcon[currentTrick[W]],"Danielle plays card #"+currentTrick[W], JOptionPane.PLAIN_MESSAGE);
currentTrick[N] = humanPlays('N');
currentTrick[E] = humanPlays('E');
break;
default:
System.out.println("Order of playing logic isnt working");
break;
}
//Danielle assesses situation, changes how playing?
determineTrickResult(i);
// For troubleshooting...
for (int j = 0; j < dd.length; j++) {
System.out.println("dd["+j+"] = "+dd[j]);
}
// Refresh status lines
scoresLabel.setText(scoreLine());
bidsLabel.setText(bidLine());
tricksLabel.setText(trickLine());
}
// Output scores
updateScore();
JOptionPane.showMessageDialog(null, "Scores:\nDanielle and "+partner+": "+(we + ourBags)+"\n"+opponentN+" and "+opponentS+": "+(they + theirBags));
// Determine if the game is over
if(we + ourBags > they + theirBags){
highestScore = we + ourBags;
winningTeam = "Danielle and "+partner;
}
else{
highestScore = they + theirBags;
winningTeam = opponentN+" and "+opponentS;
}
// Have the next person deal
bc = (bc + 1) % 4;
// Refresh status lines
scoresLabel.setText(scoreLine());
bidsLabel.setText(bidLine());
tricksLabel.setText(trickLine());
}
//Output the winning team
JOptionPane.showMessageDialog(null, "Winning team: "+ winningTeam);
System.exit(0);
}catch(NumberFormatException e){
background.add(new JLabel("Exception Thrown. Since something went wrong, probably user error, exit and start over."), BorderLayout.CENTER);
// Re-size so it displays the new label.
background.setSize(661, 600);
}
}
/** Update all scoring variables.
* Scoring can't handle: *2 nils on same team,
* two-for more than 10,
* nil and 24T on same team*/
private static void updateScore() {
//Scoring E & W
// Neither is nil, no 24T
if(bidW != -1 && bidE != -1 && bidW + bidE < 10){
if(ourTricks == bidW + bidE)
we += (bidW + bidE) * 10;
else if(ourTricks < bidW + bidE)
we -= (bidW + bidE) * 10;
else{// ourTricks > bidW + bidE
we += (bidW + bidE) * 10;
ourBags += ourTricks - (bidW + bidE);
if(ourBags >= 10){
we -= 100;
ourBags -= 10;
}
}
}
// They go 24T
else if(bidW + bidE >= 10){
if(ourTricks >= bidW + bidE){
we += 200;
ourBags += ourTricks - (bidW + bidE);
}
else // don't make it
we -= 200;
}
// W is nil
else if(bidW == -1){
if(isWsetnil)
we -= 100;
else // W makes nil
we += 100;
if(ourTricks == bidE)
we += bidE * 10;
else if(ourTricks < bidE)
we -= bidE * 10;
else{// ourTricks > bidE
we += bidE * 10;
ourBags += ourTricks - bidE;
if(ourBags >= 10){
we -= 100;
ourBags -= 10;
}
}
}
// E is nil
else if(bidE == -1){
if(isEsetnil)
we -= 100;
else // E makes nil
we += 100;
if(ourTricks == bidW)
we += bidW * 10;
else if(ourTricks < bidW)
we -= bidW * 10;
else{// ourTricks > bidW
we += bidW * 10;
ourBags += ourTricks - bidW;
if(ourBags >= 10){
we -= 100;
ourBags -= 10;
}
}
}
// error message if none of above fit the situation
else
System.out.println("Scoring with E & W isn't working.");
//Scoring N & S
// Neither is nil, no 24T
if(bidN != -1 && bidS != -1 && bidN + bidS < 10){
if(theirTricks == bidN + bidS)
they += (bidN + bidS) * 10;
else if(theirTricks < bidN + bidS)
they -= (bidN + bidS) * 10;
else{// theirTricks > bidN + bidS
they += (bidN + bidS) * 10;
theirBags += theirTricks - (bidN + bidS);
if(theirBags >= 10){
they -= 100;
theirBags -= 10;
}
}
}
// They go 24T
else if(bidN + bidS >= 10){
if(theirTricks >= bidN + bidS){
they += 200;
theirBags += theirTricks - (bidN + bidS);
}
else // don't make it
they -= 200;
}
// N is nil
else if(bidN == -1){
if(isNsetnil)
they -= 100;
else // N makes nil
they += 100;
if(theirTricks == bidS)
they += bidS * 10;
else if(theirTricks < bidS)
they -= bidS * 10;
else{// theirTricks > bidS
they += bidS * 10;
theirBags += theirTricks - bidS;
if(theirBags >= 10){
they -= 100;
theirBags -= 10;
}
}
}
// S is nil
else if(bidS == -1){
if(isSsetnil)
they -= 100;
else // S makes nil
they += 100;
if(theirTricks == bidN)
they += bidN * 10;
else if(theirTricks < bidN)
they -= bidN * 10;
else{// theirTricks > bidN
they += bidN * 10;
theirBags += theirTricks - bidN;
if(theirBags >= 10){
they -= 100;
theirBags -= 10;
}
}
}
// error message if none of above fit the situation
else
System.out.println("Scoring with N & S isn't working.");
}
/** Determines who won and dishes out the consequences.
* int passed is the current trick, just to display it.*/
private static void determineTrickResult(int i) {
// Determine who won
for (int j = 0; j < 4; j++) {
if(hc >= 13 && hc < 26 /* a heart is led */ && ((currentTrick[j] > hc && currentTrick[j] < 26) || currentTrick[j] < 13))/* a bigger heart or a spade */
hc = currentTrick[j];
else if(hc >= 26 && hc < 39 /* a club is led */ && ((currentTrick[j] > hc && currentTrick[j] < 39) || currentTrick[j] < 13))/* a bigger club or a spade */
hc = currentTrick[j];
else if(hc >= 39 /* a diamond is led */ && (currentTrick[j] > hc || currentTrick[j] < 13))/* a bigger diamond or a spade */
hc = currentTrick[j];
else if(currentTrick[j] > hc && currentTrick[j] < 13)// a bigger spade
hc = currentTrick[j];
}
// Define consequenses for winning: leading next trick, increment tricks won, determine if set nil or not, output a dialog box
if(hc == currentTrick[W]){
lc = W;
ourTricks++;
if(isWnil){
isWnil = false;
isWsetnil = true;
}
JOptionPane.showMessageDialog(null, "Danielle won trick "+(i+1)+"!\nTake it please..." , "Trick over", JOptionPane.INFORMATION_MESSAGE);
}
else if(hc == currentTrick[N]){
lc = N;
theirTricks++;
if(isNnil){
isNnil = false;
isNsetnil = true;
}
JOptionPane.showMessageDialog(null, opponentN+" won trick "+(i+1)+"!\nTake it please..." , "Trick over", JOptionPane.INFORMATION_MESSAGE);
}
else if(hc == currentTrick[E]){
lc = E;
ourTricks++;
if(isEnil){
isEnil = false;
isEsetnil = true;
}
JOptionPane.showMessageDialog(null, partner+" won trick "+(i+1)+"!\nTake it please..." , "Trick over", JOptionPane.INFORMATION_MESSAGE);
}
else if(hc == currentTrick[S]){
lc = S;
theirTricks++;
if(isSnil){
isSnil = false;
isSsetnil = true;
}
JOptionPane.showMessageDialog(null, opponentS+" won trick "+(i+1)+"!\nTake it please..." , "Trick over", JOptionPane.INFORMATION_MESSAGE);
}
else
System.out.println("something is wrong in setting the winning trick");
}
// Class to view cards
public static class DisplayCardsFrame extends JFrame{
final int widthOfFrame;
DisplayCardsPanel dcpanel = new DisplayCardsPanel();
public DisplayCardsFrame(){
widthOfFrame = 350;
add(dcpanel);
setTitle("Danielle's Hand");
setSize(widthOfFrame, cardPictureIcon[1].getIconHeight()+50);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
setVisible(true);
// setResizable(false); Not using this command because it messes it up
// It does not like repainting at all.
}
}
public static class DisplayCardsPanel extends JPanel{
final int widthOfFrame;
int x;
public DisplayCardsPanel() {
widthOfFrame = 350;
setLayout(null);
setSize(widthOfFrame, cardPictureIcon[1].getIconHeight()+50);
x = widthOfFrame - cardPictureIcon[1].getIconWidth()*2;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 51; i >= 0; i--) {
// If the card is held by 'W', add it to the frame
if(dd[i] == 'W'){
cardPictureLabel.get(i).setBounds(x,0,cardPictureLabel.get(i).getPreferredSize().width,cardPictureLabel.get(i).getPreferredSize().height);
add(cardPictureLabel.get(i));
x-=15;
}
}
}
}
/** Class to create a frame to input the cards with GUI instead of using a Scanner.
* Used for entering 13 card hand, as well as each played card. */
public static class HandInputFrame extends JFrame{
// Make button for each number
JCheckBox[] cbAll = new JCheckBox[52];
JButton ok = new JButton("OK");
JPanel colorPanel = new JPanel();
char player;
// Frame Constructor
public HandInputFrame(char player){
cbAll[0] = new JCheckBox("2 Spades");
cbAll[1] = new JCheckBox("3 Spades");
cbAll[2] = new JCheckBox("4 Spades");
cbAll[3] = new JCheckBox("5 Spades");
cbAll[4] = new JCheckBox("6 Spades");
cbAll[5] = new JCheckBox("7 Spades");
cbAll[6] = new JCheckBox("8 Spades");
cbAll[7] = new JCheckBox("9 Spades");
cbAll[8] = new JCheckBox("10 Spades");
cbAll[9] = new JCheckBox("Jack Spades");
cbAll[10] = new JCheckBox("Queen Spades");
cbAll[11] = new JCheckBox("King Spades");
cbAll[12] = new JCheckBox("Ace Spades");
cbAll[13] = new JCheckBox("2 Hearts");
cbAll[14] = new JCheckBox("3 Hearts");
cbAll[15] = new JCheckBox("4 Hearts");
cbAll[16] = new JCheckBox("5 Hearts");
cbAll[17] = new JCheckBox("6 Hearts");
cbAll[18] = new JCheckBox("7 Hearts");
cbAll[19] = new JCheckBox("8 Hearts");
cbAll[20] = new JCheckBox("9 Hearts");
cbAll[21] = new JCheckBox("10 Hearts");
cbAll[22] = new JCheckBox("Jack Hearts");
cbAll[23] = new JCheckBox("Queen Hearts");
cbAll[24] = new JCheckBox("King Hearts");
cbAll[25] = new JCheckBox("Ace Hearts");
cbAll[26] = new JCheckBox("2 Clubs");
cbAll[27] = new JCheckBox("3 Clubs");
cbAll[28] = new JCheckBox("4 Clubs");
cbAll[29] = new JCheckBox("5 Clubs");
cbAll[30] = new JCheckBox("6 Clubs");
cbAll[31] = new JCheckBox("7 Clubs");
cbAll[32] = new JCheckBox("8 Clubs");
cbAll[33] = new JCheckBox("9 Clubs");
cbAll[34] = new JCheckBox("10 Clubs");
cbAll[35] = new JCheckBox("Jack Clubs");
cbAll[36] = new JCheckBox("Queen Clubs");
cbAll[37] = new JCheckBox("King Clubs");
cbAll[38] = new JCheckBox("Ace Clubs");
cbAll[39] = new JCheckBox("2 Diamonds");
cbAll[40] = new JCheckBox("3 Diamonds");
cbAll[41] = new JCheckBox("4 Diamonds");
cbAll[42] = new JCheckBox("5 Diamonds");
cbAll[43] = new JCheckBox("6 Diamonds");
cbAll[44] = new JCheckBox("7 Diamonds");
cbAll[45] = new JCheckBox("8 Diamonds");
cbAll[46] = new JCheckBox("9 Diamonds");
cbAll[47] = new JCheckBox("10 Diamonds");
cbAll[48] = new JCheckBox("Jack Diamonds");
cbAll[49] = new JCheckBox("Queen Diamonds");
cbAll[50] = new JCheckBox("King Diamonds");
cbAll[51] = new JCheckBox("Ace Diamonds");
StatusListener colorListener = new StatusListener(colorPanel, player);
// If playing a card, only let one box be checked.
boolean ensureOnlyOneBoxChecked = (player == 'W') ? false : true;
if(ensureOnlyOneBoxChecked){
ButtonGroup group = new ButtonGroup();
// Since only one card can be played, don't let more than one box be checked
for (int i = 0; i < cbAll.length; i++) {
group.add(cbAll[i]);
}
}
// Set a display label that changes color with status.
// Yellow = not enough selected (inputing Danielle's hand only)
// Red = Too many selected, or singleton card selected has already been played
// Green = The right amount of cards selected, or that the singleton card has not been played by anyone and is not held by Danielle.
for (int i = 0; i < cbAll.length; i++) {
cbAll[i].addItemListener(colorListener);
}
setLayout(new FlowLayout());
JPanel pSpades = new JPanel(new GridLayout(13,1));
JPanel pHearts = new JPanel(new GridLayout(13,1));
JPanel pClubs = new JPanel(new GridLayout(13,1));
JPanel pDiamonds = new JPanel(new GridLayout(13,1));
JPanel rightPanel = new JPanel(new GridLayout(2, 1));
PlayCardListener listener = new PlayCardListener(player, this);
ok.addActionListener(listener);
// Add spade boxes to the 1st column panel
for (int i = 0; i < 13; i++) {
pSpades.add(cbAll[i]);
}
// Add heart boxes to the 2nd column panel
for (int i = 13; i < 26; i++) {
pHearts.add(cbAll[i]);
}
// Add club boxes to the 3rd column panel
for (int i = 26; i < 39; i++) {
pClubs.add(cbAll[i]);
}
// Add diamond boxes to the 4th column panel
for (int i = 39; i < 52; i++) {
pDiamonds.add(cbAll[i]);
}
colorPanel.setPreferredSize(new Dimension(35, 150));
ok.setBorder(new BevelBorder(BevelBorder.RAISED, Color.black, Color.black));
rightPanel.add(colorPanel);
rightPanel.add(ok);
//p1.setVisible(true);
add(pSpades);
add(pHearts);
add(pClubs);
add(pDiamonds);
add(rightPanel);
pack();
}
private class StatusListener implements ItemListener{
int numChecked = 0;
JPanel jpn;
char player;
public StatusListener(JPanel jpn, char player) {
this.jpn = jpn;
this.player = player;
}
@Override
public void itemStateChanged(ItemEvent ie) {
if(ie.getStateChange() == ItemEvent.SELECTED)
numChecked++;
else
numChecked--;
// Color the panel
if(player != 'W'){
jpn.setBackground(Color.green);
// For checkboxes 0-51, if it is selected, and the card slot it represents has something in it, paint the side red because the card can't be played.
for (int i = 0; i < 52; i++) {
if(ie.getStateChange() == ItemEvent.SELECTED && ie.getItem().equals(cbAll[i]) && dd[i] != '\u0000')
jpn.setBackground(Color.red);
}
}
else{
if(numChecked == 0)
jpn.setBackground(Color.lightGray);
else if(numChecked < 13)
jpn.setBackground(Color.yellow);
else if(numChecked > 13)
jpn.setBackground(Color.red);
else
jpn.setBackground(Color.green);
}
}
}
private class PlayCardListener implements ActionListener {
char x;
HandInputFrame f;
// Variable to make sure they don't accidently skip a play
boolean canClose = false;
public PlayCardListener(char x, HandInputFrame f) {
this.x = x;
this.f = f;
}
public PlayCardListener(HandInputFrame f) {
x = 'W';
this.f = f;
}
@Override
public void actionPerformed(ActionEvent ae) {
// Get the selected card
for (int i = 0; i < 52; i++) {
if(cbAll[i].isSelected()){
dd[i] = x;
canClose = true;
}
}
// Close the window that the listener's button is in
if(canClose)
f.dispose();
else
JOptionPane.showMessageDialog(rootPane, "A card must be played.");
}
}
}// End HandInputFrame
/**Bidding characteristics:
-Only takes its own hand into consideration - simply takes what it thinks it can take (effectively it is West, bidding first, as if score is not a factor)
-Bid nil as often as possible.
-If bidding 4 or more, consider (go into more decisions to decide) bidding one extra.?
*Define winners: the tricks it is bidding on. Base these off of covers/length of spades
*Aces, kings, and all spades have a chance to be winners.*/
public static int bidding() {
int bid = 0;
// First determine whether or not to bid nil
if(canGoNil())
return -1;// Option #1
// For a normal hand, bid on the high cards
// Bid on Aces and kings
if(dd[ACE_HEARTS] == 'W'){
bid++;
if(dd[KING_HEARTS] == 'W')
bid++;
}
else if(dd[KING_HEARTS] == 'W' && numberOfSuit('W', "Hearts") > 2)
bid++;
if(dd[ACE_CLUBS] == 'W'){
bid++;
if(dd[KING_CLUBS] == 'W')
bid++;
}
else if(dd[KING_CLUBS] == 'W' && numberOfSuit('W', "Clubs") > 2)
bid++;
if(dd[ACE_DIAMONDS] == 'W'){
bid++;
if(dd[KING_DIAMONDS] == 'W')
bid++;
}
else if(dd[KING_DIAMONDS] == 'W' && numberOfSuit('W', "Diamonds") > 2)
bid++;
// Bid on spades...
if(dd[ACE_SPADES] == 'W' && dd[KING_SPADES] == 'W' &&
dd[QUEEN_SPADES] == 'W' && dd[JACK_SPADES] == 'W')
bid += (numberOfSuit('W', "Spades"));
else if(dd[ACE_SPADES] == 'W' && dd[KING_SPADES] == 'W' &&
dd[QUEEN_SPADES] == 'W' && numberOfSuit('W', "Spades") > 3)
bid += (numberOfSuit('W', "Spades") - 1);
else if(dd[ACE_SPADES] == 'W' && dd[KING_SPADES] == 'W' &&
dd[QUEEN_SPADES] == 'W')
bid += 3;
else if((dd[ACE_SPADES] == 'W' || dd[KING_SPADES] == 'W') &&
numberOfSuit('W', "Spades") > 2)
bid += numberOfSuit('W', "Spades") - 2;
else if(dd[ACE_SPADES] == 'W' || dd[KING_SPADES] == 'W')
bid++;
else if(numberOfSuit('W', "Spades") > 3)
bid += (numberOfSuit('W', "Spades") - 3);
else if(numberOfSuit('W', "Spades") > 0 && (numberOfSuit('W', "Hearts") < 2 || numberOfSuit('W', "Clubs") < 2 || numberOfSuit('W', "Diamonds") < 2))
bid += 1;
// If can't bid nil or bid 4 or more or go nil(decided above), redeal
if(bid < 4 && (numberOfSuit('W',"Diamonds") >= 7 || numberOfSuit('W', "Hearts") >= 7
|| numberOfSuit('W', "Clubs") >= 7 || numberOfSuit('W', "Spades") == 0)){
System.out.println("$$$$");return -2; // Option #redeal
}
return bid;// Option normal
}
/** Determines if Danielle can go nil or not.*/
public static boolean canGoNil() {
//exception, too good of a hand to go nil
boolean a_k_spades = false;
boolean nilableSpades = false;
boolean badEnoughForNil = true;
boolean nilableHearts = false;
boolean nilableClubs = false;
boolean nilableDiamonds = false;
// Get the cards Danielle has in each suit
int[] hearts = inSuit("Hearts");
int[] spades = inSuit("Spades");
int[] clubs = inSuit("Clubs");
int[] diamonds = inSuit("Diamonds");
// Determine nilable spades.
// If has Ace or King, no chance at nil.
if(dd[ACE_SPADES] == 'W' || dd[KING_SPADES] == 'W')//no A or K of spades
a_k_spades = true;
if(!a_k_spades && numberOfSuit('W', "Spades") < 5){//&& 4 spades or less,
if(numberOfSuit('W', "Spades") == 4 && getHigh('W', QUEEN_SPADES) <= NINE_SPADES &&
getHigh('W', NINE_SPADES) <= FIVE_SPADES)//including Q-9-5-x or less
nilableSpades = true;
else if(numberOfSuit('W', "Spades") == 3 && getHigh('W', QUEEN_SPADES)
<= NINE_SPADES && getHigh('W', NINE_SPADES) <= FIVE_SPADES)//including Q-9-5 or less, this line of code is redundant
nilableSpades = true;
else if(numberOfSuit('W', "Spades") == 2 && getHigh('W', QUEEN_SPADES) <= NINE_SPADES)
nilableSpades = true;//including Q-9 or less
else // holds 1 or 0 spades
nilableSpades = true;
}
// Nilable suit criteria, must be equal to or lower than these values
//>5 x-x-9-6-5-3
//5 x-x-8-5-3
//4 x-J-7-4
//3 Q-7-4
//2 10-5
//1 9
// Check whichever length of HEARTS Danielle has for the nilable suit criteria.
if(hearts.length > 5 && hearts[0] <= THREE_HEARTS && hearts[1] <= FIVE_HEARTS && hearts[2] <= SIX_HEARTS && hearts[3] <= NINE_HEARTS)
nilableHearts = true;
else if (hearts.length == 5 && hearts[0] <= THREE_HEARTS && hearts[1] <= FIVE_HEARTS && hearts[2] <= EIGHT_HEARTS)
nilableHearts = true;
else if (hearts.length == 4 && hearts[0] <= FOUR_HEARTS && hearts[1] <= SEVEN_HEARTS && hearts[2] <= JACK_HEARTS)
nilableHearts = true;
else if (hearts.length == 3 && hearts[0] <= FOUR_HEARTS && hearts[1] <= SEVEN_HEARTS && hearts[2] <= QUEEN_HEARTS)
nilableHearts = true;
else if (hearts.length == 2 && hearts[0] <= FIVE_HEARTS && hearts[1] <= TEN_HEARTS)
nilableHearts = true;
else if (hearts.length == 1 && hearts[0] <= NINE_HEARTS)
nilableHearts = true;
else if (hearts.length == 0)
nilableHearts = true;
// Check whichever length of CLUBS Danielle has for the nilable suit criteria.
if(clubs.length > 5 && clubs[0] <= THREE_CLUBS && clubs[1] <= FIVE_CLUBS && clubs[2] <= SIX_CLUBS && clubs[3] <= NINE_CLUBS)
nilableClubs = true;
else if (clubs.length == 5 && clubs[0] <= THREE_CLUBS && clubs[1] <= FIVE_CLUBS && clubs[2] <= EIGHT_CLUBS)
nilableClubs = true;
else if (clubs.length == 4 && clubs[0] <= FOUR_CLUBS && clubs[1] <= SEVEN_CLUBS && clubs[2] <= JACK_CLUBS)
nilableClubs = true;
else if (clubs.length == 3 && clubs[0] <= FOUR_CLUBS && clubs[1] <= SEVEN_CLUBS && clubs[2] <= QUEEN_CLUBS)
nilableClubs = true;
else if (clubs.length == 2 && clubs[0] <= FIVE_CLUBS && clubs[1] <= TEN_CLUBS)
nilableClubs = true;
else if (clubs.length == 1 && clubs[0] <= NINE_CLUBS)
nilableClubs = true;
else if (clubs.length == 0)
nilableClubs = true;
// Check whichever length of DIAMONDS Danielle has for the nilable suit criteria.
if(diamonds.length > 5 && diamonds[0] <= THREE_DIAMONDS && diamonds[1] <= FIVE_DIAMONDS && diamonds[2] <= SIX_DIAMONDS && diamonds[3] <= NINE_DIAMONDS)
nilableDiamonds = true;
else if (diamonds.length == 5 && diamonds[0] <= THREE_DIAMONDS && diamonds[1] <= FIVE_DIAMONDS && diamonds[2] <= EIGHT_DIAMONDS)
nilableDiamonds = true;
else if (diamonds.length == 4 && diamonds[0] <= FOUR_DIAMONDS && diamonds[1] <= SEVEN_DIAMONDS && diamonds[2] <= JACK_DIAMONDS)
nilableDiamonds = true;
else if (diamonds.length == 3 && diamonds[0] <= FOUR_DIAMONDS && diamonds[1] <= SEVEN_DIAMONDS && diamonds[2] <= QUEEN_DIAMONDS)
nilableDiamonds = true;
else if (diamonds.length == 2 && diamonds[0] <= FIVE_DIAMONDS && diamonds[1] <= TEN_DIAMONDS)
nilableDiamonds = true;
else if (diamonds.length == 1 && diamonds[0] <= NINE_DIAMONDS)
nilableDiamonds = true;
else if (diamonds.length == 0)
nilableDiamonds = true;
// Don't go nil with more than 2 Aces/Kings
if(numberOfAcesAndKings() > 2)
badEnoughForNil = false;
// Return
if(nilableSpades && nilableHearts && nilableClubs && nilableDiamonds && badEnoughForNil)
return true;
else
return false;
}
/** Returns highest in a suit. Works the same way as numberOfSuit.*/
public static int getHigh(char player, String suit){
int num = -1;
switch (suit) {
case "Spades":
for (int i = 0; i < 13; i++) {
if(dd[i] == player)
num = i;
}
break;
case "Hearts":
for (int i = 13; i < 26; i++) {
if(dd[i] == player)
num = i;
}
break;
case "Clubs":
for (int i = 26; i < 39; i++) {
if(dd[i] == player)
num = i;
}
break;
case "Diamonds":
for (int i = 39; i < 52; i++) {
if(dd[i] == player)
num = i;
}
break;
default:
System.out.println("getHigh isnt working");
break;
}
return num;
}
/** Returns highest in a suit below or equal to a specified card.
If no cards held are below or equal to the specified card, returns -1.*/
public static int getHigh(char player, int card){
int num = -1;
if(card < 13){
for (int i = 0; i <= card; i++) {
if(dd[i] == player)
num = i;
}
}
else if(card < 26){
for (int i = 13; i <= card; i++) {
if(dd[i] == player)
num = i;
}
}
else if(card < 39){
for (int i = 26; i <= card; i++) {
if(dd[i] == player)
num = i;
}
}
else if(card < 52){
for (int i = 39; i <= card; i++) {
if(dd[i] == player)
num = i;
}
}
else
System.out.println("getHigh isnt working");
System.out.println("getHigh is returning: "+num);
return num;
}
/** Returns lowest in a suit above or equal to a specified card.*/
public static int getLow(char player, int card){
int num = -1;
if(card < 13){
for (int i = 12; i >= card; i--) {
if(dd[i] == player)
num = i;
}
}
else if(card < 26){
for (int i = 25; i >= card; i--) {
if(dd[i] == player)
num = i;
}
}
else if(card < 39){
for (int i = 38; i >= card; i--) {
if(dd[i] == player)
num = i;
}
}
else if(card < 52){
for (int i = 51; i >= card; i--) {
if(dd[i] == player)
num = i;
}
}
else
System.out.println("getLow isnt working");
System.out.println("getLow is returning: "+num);
return num;
}
/** Returns the number of cards or a given suit in a given hand, that Danielle knows.
// *For example, if asking for hearts of North, it returns the number of hearts that North has played.
// Used in bidding. Returns 0 if no cards held.*/
public static int numberOfSuit(char player, String suit){
int num = 0;
switch (suit) {
case "Spades":
for (int i = 0; i < 13; i++) {
if(dd[i] == player)
num++;
}
break;
case "Hearts":
for (int i = 13; i < 26; i++) {
if(dd[i] == player)
num++;
}
break;
case "Clubs":
for (int i = 26; i < 39; i++) {
if(dd[i] == player)
num++;
}
break;
case "Diamonds":
for (int i = 39; i < 52; i++) {
if(dd[i] == player)
num++;
}
break;
default:
System.out.println("numberOfSuit isnt working");
break;
}
return num;
}
// North makes a play
public static int humanPlays(char x){
String name = "";
if(x == 'E')
name = partner;
else if(x == 'N')
name = opponentN;
else if(x == 'S')
name = opponentS;
else
name = "Janky, lol";
char[] tempdd = dd.clone();
HandInputFrame hif = new HandInputFrame(x);
hif.setTitle(name+": Input "+name+"'s Play. Single Card Only!");
hif.setLocationRelativeTo(null);
hif.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
hif.setVisible(true);
// Wait for button to be pressed on the frame
while(hif.isVisible()){
System.out.print("");
}
for (int i = 0; i < tempdd.length; i++)
if(tempdd[i] != dd[i]){
System.out.println(name+" plays dd["+i+"], so this slot now equals: "+dd[i]);
return i;
}
// If it didn't return anything, something is wrong
System.out.println("Something is wrong in humanPlays. Had to terminate. Oops.");
System.exit(x);
return -10;
}
/** method with all the logic for how Danielle plays!*/
public static int daniellePlays(/*int lc, boolean isWnil, boolean isNnil,
boolean isEnil, boolean isSnil, boolean isWsetnil,boolean isNsetnil,
boolean isEsetnil, boolean isSsetnil, int[] currentTrick,
int ourTricks, int theirTricks, int ourBid, int theirBid*/) {
int x;
if(isWnil && !isWsetnil){
x = sluff(lc, currentTrick);
dd[x] = 'P';
return x;
}
else if(isNnil && !isNsetnil || isSnil && !isSsetnil){
x = sluff(lc, currentTrick);
dd[x] = 'P';
return x;
}
else if(ourTricks >= ourBid){
x = sluff(lc, currentTrick);
dd[x] = 'P';
return x;
}
else{//no need to sluff
x = win(lc, currentTrick);
dd[x] = 'P';
return x;
}
}
/** Play to sluff*/
public static int sluff(int lc, int[] currentTrick){
int x = -10;
switch(lc){
case W:// Danielle plays first
if(numberOfSuit('W', "Hearts") > 0 || numberOfSuit('W', "Clubs") > 0 || numberOfSuit('W', "Diamonds") > 0)
return absoluteLowest();
else
return getLow('W', TWO_SPADES);
case N:// Danielle plays last
// Find highest card in suit played
for (int i = 0; i < currentTrick.length; i++) {
if(currentTrick[i] > x && currentTrick[i] <= highInSuitConst(currentTrick[lc]))
x = currentTrick[i];
}
x = getHigh('W', x);
if(x != -1)// sluff in suit
return x;
else// does not have anything in the suit lower than x
if(getHigh('W', highInSuitConst(currentTrick[lc])) == -1)// has no card in suit
return absoluteHighest();
else// has a card in suit, so has to play it
return getLow('W', lowInSuitConst(currentTrick[lc]));
case E:// Danielle plays 3rd
// Find highest card played so far
if(currentTrick[S] > currentTrick[E] && currentTrick[S] <= highInSuitConst(currentTrick[E]))
x = currentTrick[S];
else
x = currentTrick[E];
x = getHigh('W', x);
if(x != -1)// can play under in suit
return x;
else// has nothing lower than what has been played
x = getHigh('W', highInSuitConst(currentTrick[lc]));
if(x != -1)// play the lowest it can anyway
return getLow('W', currentTrick[lc]);// 2nd parameter is the only thing that represents suit, and it doesn't matter because W has nothing lower in the hand anyway.
else// nothing in the suit
if(numberOfSuit('W', "Hearts") > 0 || numberOfSuit('W', "Clubs") > 0 || numberOfSuit('W', "Diamonds") > 0)
return absoluteHighest();
else
return getLow('W', TWO_SPADES);// if you have to play a spade, play a low one
case S:// Danielle plays 2nd
x = getHigh('W', currentTrick[S]);
if(x != -1)// can play under in suit
return x;
else// has nothing lower than what has been played
x = getHigh('W', highInSuitConst(currentTrick[lc]));
if(x != -1)// play the lowest it can anyway
return getLow('W', currentTrick[S]);// 2nd parameter is the only thing that represents suit, and it doesn't matter because W has nothing lower in the hand anyway.
else// nothing in the suit
if(numberOfSuit('W', "Hearts") > 0 || numberOfSuit('W', "Clubs") > 0 || numberOfSuit('W', "Diamonds") > 0)
return absoluteHighest();
else
return getLow('W', TWO_SPADES);// if you have to play a spade, play a low one
default:
System.out.println("daniellePlays method getting to default. Check it out.");
break;
}
return x;// Shouldn't ever get to this point.
}
/** Play to win */
public static int win(int lc, int[] currentTrick){
boolean canWinInSuit = true;
boolean alreadyRuffedThisTrick = false;
boolean spadesBroken = false;
int extra;
if(lc == W){
for (int i = 0; i < 13; i++) {
if(dd[i] != '\u0000' && dd[i] != 'W'){
spadesBroken = true;
break;
}
}
if(spadesBroken){
if(numberOfSuit('W', "Spades") > 0)
return getHigh('W', highInSuitConst(0));
else
return absoluteHighest();
}
else{
if(numberOfSuit('W', "Hearts") > 0 || numberOfSuit('W', "Clubs") > 0 || numberOfSuit('W', "Diamonds") > 0)
return absoluteHighest();
else// has to break spades
return getHigh('W', highInSuitConst(0));
}
}// End lc == 'W'
else{
int x = getHigh('W', highInSuitConst(currentTrick[lc]));
if(x != -1){// has a card in the suit led
for (int i = 0; i < currentTrick.length; i++) {
if(x < currentTrick[i])
canWinInSuit = false;
}
if(canWinInSuit)
return x;
else// have to play something lower, so go all the way low
return getLow('W', lowInSuitConst(currentTrick[lc]));
}
else{// has no card in the suit led; x == -1
for (int i = 0; i < currentTrick.length; i++) {
if(currentTrick[i] >= 0 && currentTrick[i] < 13){
extra = currentTrick[i];
if(extra > x)
x = extra;// x represents the highest spade played
alreadyRuffedThisTrick = true;
}
}
if(alreadyRuffedThisTrick)// select the lowest spade that will win
x = getLow('W', x);
else// nobody has spaded in
x = getLow('W', lowInSuitConst(TWO_SPADES));
if(x != -1)// W has a spade
return x;
else// has not spades
return absoluteLowest();
}
}
}
/** Returns the high card in the suit of the given card.*/
public static int highInSuitConst(int lc){
if(lc < 13)
return 12;
else if(lc < 26)
return 25;
else if(lc < 39)
return 38;
else
return 51;
}
/** Returns the low card in the suit of the given card.*/
public static int lowInSuitConst(int lc){
if(lc < 13)
return 0;
else if(lc < 26)
return 13;
else if(lc < 39)
return 26;
else
return 39;
}
/**Return the lowest card by number in W's hand, does not return a spade.*/
public static int absoluteLowest(){
int x = 52;
for (int i = dd.length - 1; i >= dd.length - 13; i--) // check each decreasing number
for (int j = i; j >= 13; j = j-13) //check each suit
if(dd[j] == 'W')
x = j;
if(x == 52)
System.out.println("absoluteLowest did not go lower than 52.");
System.out.println("absoluteLowest returning: "+x);
return x;
}
/** return the highest card by number in W's hand, does not return a spade*/
public static int absoluteHighest(){
int x = -10;
for (int i = 13; i < 26; i++) // check each increasing number
for (int j = i; j <= 51; j = j+13) //check each suit
if(dd[j] == 'W')
x = j;
if(x == 52)
System.out.println("absoluteHighest did not go higher than -10.");
System.out.println("absoluteHighest is returning: "+x);
return x;
}
/** Returns a string that represents the current scores.*/
public static String scoreLine(){
return "Scores - Danielle & "+partner+": "+(we + ourBags)+" "+opponentN+" & "+opponentS+": "+(they + theirBags)+" Game to: "+winningPointValue;
}
/** Returns a string that represents the current bids.*/
public static String bidLine(){
return "Bids - Danielle: "+bidW+" "+partner+": "+bidE+" "+opponentN+": "+bidN+" "+opponentS+": "+bidS;
}
/** Returns a string that represents the current tricks taken.*/
public static String trickLine(){
return "Taken - Danielle & "+partner+": "+ourTricks+" "+opponentN+" & "+opponentS+": "+theirTricks;
}
/** Returns an int array with all the cards in specified suit held by Danielle.
* [0] contains the lowest card, [length -1] contains the highest card.*/
public static int[] inSuit(String suit){
int[] nums = new int[numberOfSuit('W', suit)];
int count = 0;
switch (suit) {
case "Spades":
for (int i = 0; i < 13; i++) {
if(dd[i] == 'W'){
nums[count] = i;
count++;
}
}
break;
case "Hearts":
for (int i = 13; i < 26; i++) {
if(dd[i] == 'W'){
nums[count] = i;
count++;
}
}
break;
case "Clubs":
for (int i = 26; i < 39; i++) {
if(dd[i] == 'W'){
nums[count] = i;
count++;
}
}
break;
case "Diamonds":
for (int i = 39; i < 52; i++) {
if(dd[i] == 'W'){
nums[count] = i;
count++;
}
}
break;
default:
System.out.println("inSuit is getting to default");
break;
}
return nums;
}
/** Returns how many Aces and Kings Danielle has.*/
public static int numberOfAcesAndKings(){
int num = 0;
if(dd[ACE_CLUBS] == 'W')
num++;
if(dd[ACE_DIAMONDS] == 'W')
num++;
if(dd[ACE_HEARTS] == 'W')
num++;
if(dd[ACE_SPADES] == 'W')
num++;
if(dd[KING_CLUBS] == 'W')
num++;
if(dd[KING_DIAMONDS] == 'W')
num++;
if(dd[KING_HEARTS] == 'W')
num++;
if(dd[KING_SPADES] == 'W')
num++;
return num;
}
}
| digitgopher/danielle | Danielle_1.java | Java | gpl-2.0 | 68,662 |
/*
* Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.graal.lir.sparc;
import static com.oracle.graal.api.code.ValueUtil.*;
import static com.oracle.graal.asm.sparc.SPARCAssembler.*;
import static com.oracle.graal.lir.LIRInstruction.OperandFlag.*;
import static com.oracle.graal.sparc.SPARC.*;
import com.oracle.graal.api.code.*;
import com.oracle.graal.api.meta.*;
import com.oracle.graal.asm.sparc.*;
import com.oracle.graal.compiler.common.*;
import com.oracle.graal.lir.*;
import com.oracle.graal.lir.asm.*;
import com.oracle.graal.lir.gen.*;
public final class SPARCBitManipulationOp extends SPARCLIRInstruction {
public static final LIRInstructionClass<SPARCBitManipulationOp> TYPE = LIRInstructionClass.create(SPARCBitManipulationOp.class);
public enum IntrinsicOpcode {
IPOPCNT,
LPOPCNT,
IBSR,
LBSR,
BSF;
}
@Opcode private final IntrinsicOpcode opcode;
@Def protected AllocatableValue result;
@Alive({REG}) protected AllocatableValue input;
@Temp({REG}) protected Value scratch;
public SPARCBitManipulationOp(IntrinsicOpcode opcode, AllocatableValue result, AllocatableValue input, LIRGeneratorTool gen) {
super(TYPE);
this.opcode = opcode;
this.result = result;
this.input = input;
scratch = gen.newVariable(LIRKind.derive(input));
}
@Override
public void emitCode(CompilationResultBuilder crb, SPARCMacroAssembler masm) {
Register dst = asIntReg(result);
if (isRegister(input)) {
Register src = asRegister(input);
switch (opcode) {
case IPOPCNT:
// clear upper word for 64 bit POPC
masm.srl(src, g0, dst);
masm.popc(dst, dst);
break;
case LPOPCNT:
masm.popc(src, dst);
break;
case BSF:
Kind tkind = input.getKind();
if (tkind == Kind.Int) {
masm.sub(src, 1, dst);
masm.andn(dst, src, dst);
masm.srl(dst, g0, dst);
masm.popc(dst, dst);
} else if (tkind == Kind.Long) {
masm.sub(src, 1, dst);
masm.andn(dst, src, dst);
masm.popc(dst, dst);
} else {
throw GraalInternalError.shouldNotReachHere("missing: " + tkind);
}
break;
case IBSR: {
Kind ikind = input.getKind();
assert ikind == Kind.Int;
Register tmp = asRegister(scratch);
assert !tmp.equals(dst);
masm.srl(src, 1, tmp);
masm.srl(src, 0, dst);
masm.or(dst, tmp, dst);
masm.srl(dst, 2, tmp);
masm.or(dst, tmp, dst);
masm.srl(dst, 4, tmp);
masm.or(dst, tmp, dst);
masm.srl(dst, 8, tmp);
masm.or(dst, tmp, dst);
masm.srl(dst, 16, tmp);
masm.or(dst, tmp, dst);
masm.popc(dst, dst);
masm.sub(dst, 1, dst);
break;
}
case LBSR: {
Kind lkind = input.getKind();
assert lkind == Kind.Long;
Register tmp = asRegister(scratch);
assert !tmp.equals(dst);
masm.srlx(src, 1, tmp);
masm.or(src, tmp, dst);
masm.srlx(dst, 2, tmp);
masm.or(dst, tmp, dst);
masm.srlx(dst, 4, tmp);
masm.or(dst, tmp, dst);
masm.srlx(dst, 8, tmp);
masm.or(dst, tmp, dst);
masm.srlx(dst, 16, tmp);
masm.or(dst, tmp, dst);
masm.srlx(dst, 32, tmp);
masm.or(dst, tmp, dst);
masm.popc(dst, dst);
masm.sub(dst, 1, dst); // This is required to fit the given structure.
break;
}
default:
throw GraalInternalError.shouldNotReachHere();
}
} else if (isConstant(input) && isSimm13(crb.asIntConst(input))) {
switch (opcode) {
case IPOPCNT:
masm.popc(crb.asIntConst(input), dst);
break;
case LPOPCNT:
masm.popc(crb.asIntConst(input), dst);
break;
default:
throw GraalInternalError.shouldNotReachHere();
}
} else {
throw GraalInternalError.shouldNotReachHere();
}
}
}
| BunnyWei/truffle-llvmir | graal/com.oracle.graal.lir.sparc/src/com/oracle/graal/lir/sparc/SPARCBitManipulationOp.java | Java | gpl-2.0 | 6,018 |
<?php
/*
* Copyright 2004 $ThePhpWikiProgrammingTeam
* Copyright 2009-2010 Marc-Etienne Vargenau, Alcatel-Lucent
*
* This file is part of PhpWiki.
*
* PhpWiki is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* PhpWiki 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 PhpWiki; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/**
* Set simple individual PagePermissions
*
* Usage: <<WikiAdminSetAclSimple >> or called via WikiAdminSelect
* Author: Marc-Etienne Vargenau, Alcatel-Lucent
*
*/
require_once 'lib/plugin/WikiAdminSetAcl.php';
class WikiPlugin_WikiAdminSetAclSimple
extends WikiPlugin_WikiAdminSetAcl
{
function getDescription()
{
return _("Set simple individual page permissions.");
}
/**
* @param WikiDB $dbi
* @param string $argstr
* @param WikiRequest $request
* @param string $basepage
* @return mixed
*/
function run($dbi, $argstr, &$request, $basepage)
{
if ($request->getArg('action') != 'browse') {
if ($request->getArg('action') != __("PhpWikiAdministration")."/".__("SetAclSimple")) {
return $this->disabled(_("Plugin not run: not in browse mode"));
}
}
if (!ENABLE_PAGEPERM) {
return $this->disabled("ENABLE_PAGEPERM = false");
}
$args = $this->getArgs($argstr, $request);
$this->_args = $args;
$this->preSelectS($args, $request);
$p = $request->getArg('p');
$post_args = $request->getArg('admin_setacl');
$pages = array();
if ($p && !$request->isPost())
$pages = $p;
elseif ($this->_list)
$pages = $this->_list;
$header = HTML::fieldset();
if ($p && $request->isPost() &&
(!empty($post_args['aclliberal']) || !empty($post_args['aclrestricted']))
) {
// without individual PagePermissions:
if (!ENABLE_PAGEPERM and !$request->_user->isAdmin()) {
$request->_notAuthorized(WIKIAUTH_ADMIN);
$this->disabled("! user->isAdmin");
}
if (!empty($post_args['aclliberal'])) {
return $this->setaclPages($request, array_keys($p), $this->liberalPerms());
} elseif (!empty($post_args['aclrestricted'])) {
return $this->setaclPages($request, array_keys($p), $this->restrictedPerms());
}
}
if (empty($pages)) {
// List all pages to select from.
$pages = $this->collectPages($pages, $dbi, $args['sortby'], $args['limit'], $args['exclude']);
}
$pagelist = new PageList_Selectable($args['info'],
$args['exclude'],
array('types' => array(
'acl'
=> new _PageList_Column_acl('acl', _("ACL")))));
$pagelist->addPageList($pages);
$button_label_liberal = _("Set Liberal Access Rights");
$button_label_restrictive = _("Set Restrictive Access Rights");
$header = $this->setaclForm($header, $pages);
$header->pushContent(HTML::legend(_("Select the pages where to change access rights")));
$buttons = HTML::p(Button('submit:admin_setacl[aclliberal]', $button_label_liberal, 'wikiadmin'),
Button('submit:admin_setacl[aclrestricted]', $button_label_restrictive, 'wikiadmin'));
$header->pushContent($buttons);
return HTML::form(array('action' => $request->getPostURL(),
'method' => 'post'),
$header,
$pagelist->getContent(),
HiddenInputs($request->getArgs(),
false,
array('admin_setacl')),
ENABLE_PAGEPERM
? ''
: HiddenInputs(array('require_authority_for_post' => WIKIAUTH_ADMIN)));
}
/*
* acces rights where everyone can edit
* _EVERY: view edit list create;
* _ADMIN: remove purge dump change;
* _OWNER: remove purge dump change;
*/
private function liberalPerms()
{
$perm = array('view' => array(ACL_EVERY => true),
'edit' => array(ACL_EVERY => true),
'create' => array(ACL_EVERY => true),
'list' => array(ACL_EVERY => true),
'remove' => array(ACL_ADMIN => true,
ACL_OWNER => true),
'purge' => array(ACL_ADMIN => true,
ACL_OWNER => true),
'dump' => array(ACL_ADMIN => true,
ACL_OWNER => true),
'change' => array(ACL_ADMIN => true,
ACL_OWNER => true));
return $perm;
}
/*
* acces rights where only authenticated users can see pages
* _AUTHENTICATED: view edit list create;
* _ADMIN: remove purge dump change;
* _OWNER: remove purge dump change;
* _EVERY: -view -edit -list -create;
*/
private function restrictedPerms()
{
$perm = array('view' => array(ACL_AUTHENTICATED => true,
ACL_EVERY => false),
'edit' => array(ACL_AUTHENTICATED => true,
ACL_EVERY => false),
'create' => array(ACL_AUTHENTICATED => true,
ACL_EVERY => false),
'list' => array(ACL_AUTHENTICATED => true,
ACL_EVERY => false),
'remove' => array(ACL_ADMIN => true,
ACL_OWNER => true),
'purge' => array(ACL_ADMIN => true,
ACL_OWNER => true),
'dump' => array(ACL_ADMIN => true,
ACL_OWNER => true),
'change' => array(ACL_ADMIN => true,
ACL_OWNER => true));
return $perm;
}
function setaclForm(&$header, $pagehash)
{
$pages = array();
foreach ($pagehash as $name => $checked) {
if ($checked) $pages[] = $name;
}
$header->pushContent(HTML::strong(_("Selected Pages: ")), HTML::samp(join(', ', $pages)), HTML::br());
return $header;
}
}
// Local Variables:
// mode: php
// tab-width: 8
// c-basic-offset: 4
// c-hanging-comment-ender-p: nil
// indent-tabs-mode: nil
// End:
| bclementcsp/wiki | lib/plugin/WikiAdminSetAclSimple.php | PHP | gpl-2.0 | 6,659 |