repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
datagutten/comics | comics/accounts/urls.py | 4857 | from django.conf import settings
from django.conf.urls import patterns, url
from django.contrib.auth import views as auth_views
from django.views.generic.base import TemplateView
from invitation import views as invitation_views
from registration import views as reg_views
from comics.accounts.forms import (
AuthenticationForm, PasswordResetForm, RegistrationForm)
from comics.accounts import views as account_views
urlpatterns = patterns(
'',
### django-invitation
url(r'^invite/complete/$',
TemplateView.as_view(
template_name='invitation/invitation_complete.html'),
{
'extra_context': {'active': {
'invite': True,
}},
},
name='invitation_complete'),
url(r'^invite/$',
invitation_views.invite,
{
'extra_context': {'active': {
'invite': True,
}},
},
name='invitation_invite'),
url(r'^invited/(?P<invitation_key>\w+)/$',
invitation_views.invited,
{
'extra_context': {'active': {'register': True}},
},
name='invitation_invited'),
url(r'^register/$',
invitation_views.register,
{
'backend': 'comics.accounts.backends.RegistrationBackend',
'form_class': RegistrationForm,
'extra_context': {'active': {'register': True}},
},
name='registration_register'),
### django-registration
#url(r'^register/$',
# reg_views.register,
# {
# 'backend': 'comics.accounts.backends.RegistrationBackend',
# 'extra_context': {'active': {'register': True}},
# },
# name='registration_register'),
url(r'^register/complete/$',
TemplateView.as_view(
template_name='registration/registration_complete.html'),
name='registration_complete'),
url(r'^register/closed/$',
TemplateView.as_view(
template_name='registration/registration_closed.html'),
name='registration_disallowed'),
url(r'^activate/complete/$',
TemplateView.as_view(
template_name='registration/activation_complete.html'),
name='registration_activation_complete'),
url(r'^activate/(?P<activation_key>\w+)/$',
reg_views.activate,
{'backend': 'comics.accounts.backends.RegistrationBackend'},
name='registration_activate'),
### django.contrib.auth
url(r'^login/$',
auth_views.login,
{
'authentication_form': AuthenticationForm,
'extra_context': {'active': {'login': True}},
'template_name': 'auth/login.html',
},
name='login'),
url(r'^logout/$',
auth_views.logout,
{'next_page': '/account/login/'},
name='logout'),
url(r'^password/change/$',
auth_views.password_change,
{
'template_name': 'auth/password_change.html',
'extra_context': {'active': {
'account': True,
'password_change': True,
}},
},
name='password_change'),
url(r'^password/change/done/$',
auth_views.password_change_done,
{'template_name': 'auth/password_change_done.html'},
name='password_change_done'),
url(r'^password/reset/$',
auth_views.password_reset,
{
'template_name': 'auth/password_reset.html',
'email_template_name': 'auth/password_reset_email.txt',
'subject_template_name': 'auth/password_reset_email_subject.txt',
'password_reset_form': PasswordResetForm,
},
name='password_reset'),
url(r'^password/reset/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$',
auth_views.password_reset_confirm,
{'template_name': 'auth/password_reset_confirm.html'},
name='password_reset_confirm'),
url(r'^password/reset/complete/$',
auth_views.password_reset_complete,
{'template_name': 'auth/password_reset_complete.html'},
name='password_reset_complete'),
url(r'^password/reset/done/$',
auth_views.password_reset_done,
{'template_name': 'auth/password_reset_done.html'},
name='password_reset_done'),
### comics.accounts
url(r'^$',
account_views.account_details, name='account'),
url(r'^secret-key/$',
account_views.secret_key, name='secret_key'),
url(r'^toggle-comic/$',
account_views.mycomics_toggle_comic, name='toggle_comic'),
url(r'^edit-comics/$',
account_views.mycomics_edit_comics, name='edit_comics'),
)
if 'comics.sets' in settings.INSTALLED_APPS:
urlpatterns += patterns(
'',
url(r'^import-set/$',
account_views.mycomics_import_named_set, name='import_named_set'),
)
| agpl-3.0 |
ccg/freenote | app/mock/store/NoteListStore.js | 656 | Ext.define('App.mock.store.NoteListStore', {
extend: 'Ext.data.TreeStore',
model: 'App.model.Note',
autoLoad: true,
storeId: 'noteListStore',
root: {
expanded: true,
text: "Root",
children: [
{
"leaf": true,
"id": 1,
"text": "first post!",
"title": "first post!",
"body": "hello world"
},
{
"leaf": true,
"id": 2,
"text": "hello world",
"title": "hello world",
"body": "second post"
}
]
}
}); | agpl-3.0 |
closeio/nylas | inbox/models/mixins.py | 6188 | import abc
from datetime import datetime
from sqlalchemy import Column, DateTime, String, inspect, Boolean, sql, func
from sqlalchemy.ext.hybrid import hybrid_property, Comparator
from inbox.sqlalchemy_ext.util import Base36UID, generate_public_id, ABCMixin
from inbox.models.constants import MAX_INDEXABLE_LENGTH
from inbox.util.addr import canonicalize_address
from inbox.util.encoding import unicode_safe_truncate
class HasRevisions(ABCMixin):
"""Mixin for tables that should be versioned in the transaction log."""
@property
def versioned_relationships(self):
"""
May be overriden by subclasses. This should be the list of
relationship attribute names that should trigger an update revision
when changed. (We want to version changes to some, but not all,
relationship attributes.)
"""
return []
@property
def propagated_attributes(self):
"""
May be overridden by subclasses. This is the list of attribute names
that should trigger an update revision for a /related/ object -
for example, when a message's `is_read` or `categories` is changed,
we want an update revision created for the message's thread as well.
Such manual propagation is required because changes to related objects
are not reflected in the related attribute's history, only additions
and deletions are. For example, thread.messages.history will
not reflect a change made to one of the thread's messages.
"""
return []
@property
def should_suppress_transaction_creation(self):
"""
May be overridden by subclasses. We don't want to version certain
specific objects - for example, Block instances that are just raw
message parts and not real attachments. Use this property to suppress
revisions of such objects. (The need for this is really an artifact of
current deficiencies in our models. We should be able to get rid of it
eventually.)
"""
return False
# Must be defined by subclasses
API_OBJECT_NAME = abc.abstractproperty()
def has_versioned_changes(self):
"""
Return True if the object has changes on any of its column properties
or any relationship attributes named in self.versioned_relationships,
or has been manually marked as dirty (the special 'dirty' instance
attribute is set to True).
"""
obj_state = inspect(self)
versioned_attribute_names = list(self.versioned_relationships)
for mapper in obj_state.mapper.iterate_to_root():
for attr in mapper.column_attrs:
versioned_attribute_names.append(attr.key)
for attr_name in versioned_attribute_names:
if getattr(obj_state.attrs, attr_name).history.has_changes():
return True
return False
class HasPublicID(object):
public_id = Column(Base36UID, nullable=False,
index=True, default=generate_public_id)
class AddressComparator(Comparator):
def __eq__(self, other):
return self.__clause_element__() == canonicalize_address(other)
def like(self, term, escape=None):
return self.__clause_element__().like(term, escape=escape)
def in_(self, addresses):
return self.__clause_element__().in_(map(canonicalize_address, addresses))
class CaseInsensitiveComparator(Comparator):
def __eq__(self, other):
return func.lower(self.__clause_element__()) == func.lower(other)
class HasEmailAddress(object):
"""
Provides an email_address attribute, which returns as value whatever you
set it to, but uses a canonicalized form for comparisons. So e.g.
db_session.query(Account).filter_by(
email_address='[email protected]').all()
and
db_session.query(Account).filter_by(
email_address='[email protected]').all()
will return the same results, because the two Gmail addresses are
equivalent.
"""
_raw_address = Column(String(MAX_INDEXABLE_LENGTH),
nullable=True, index=True)
_canonicalized_address = Column(String(MAX_INDEXABLE_LENGTH),
nullable=True, index=True)
@hybrid_property
def email_address(self):
return self._raw_address
@email_address.comparator
def email_address(cls):
return AddressComparator(cls._canonicalized_address)
@email_address.setter
def email_address(self, value):
# Silently truncate if necessary. In practice, this may be too
# long if somebody put a super-long email into their contacts by
# mistake or something.
if value is not None:
value = unicode_safe_truncate(value, MAX_INDEXABLE_LENGTH)
self._raw_address = value
self._canonicalized_address = canonicalize_address(value)
class CreatedAtMixin(object):
created_at = Column(DateTime, server_default=func.now(),
nullable=False, index=True)
class UpdatedAtMixin(object):
updated_at = Column(DateTime, default=datetime.utcnow,
onupdate=datetime.utcnow, nullable=False, index=True)
class DeletedAtMixin(object):
deleted_at = Column(DateTime, nullable=True, index=True)
class HasRunState(ABCMixin):
# Track whether this object (e.g. folder, account) should be running
# or not. Used to compare against reported data points to see if all is
# well.
# Is sync enabled for this object? The sync_enabled property should be
# a Boolean that reflects whether the object should be reporting
# a heartbeat. For folder-level objects, this property can be used to
# combine local run state with the parent account's state, so we don't
# need to cascade account-level start/stop status updates down to folders.
sync_enabled = abc.abstractproperty()
# Database-level tracking of whether the sync should be running.
sync_should_run = Column(Boolean, default=True, nullable=False,
server_default=sql.expression.true())
| agpl-3.0 |
bietiekay/hacs | tools/hacs-dbtool/GoogleLatitudeDataObject.cs | 1939 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using sones.Storage.Serializer;
namespace xs1_data_logging
{
// TODO: GeoHash!
/// <summary>
/// holds the values
/// </summary>
public class GoogleLatitudeDataObject : IFastSerialize
{
public String AccountName;
public String LatitudeID;
public Int64 Timecode;
public String reverseGeocode;
public Double Latitude;
public Double Longitude;
public Int32 AccuracyInMeters;
public GoogleLatitudeDataObject()
{
}
public GoogleLatitudeDataObject(String _AccountName, String _LatitudeID, Int64 _TimeCode, String _reverseGeocode, Double _Latitude, Double _Longitude, Int32 _AccuracyInMeters)
{
AccountName = _AccountName;
LatitudeID = _LatitudeID;
Timecode = _TimeCode;
reverseGeocode = _reverseGeocode;
Latitude = _Latitude;
Longitude = _Longitude;
AccuracyInMeters = _AccuracyInMeters;
}
#region IFastSerialize Members
public byte[] Serialize()
{
SerializationWriter writer = new SerializationWriter();
writer.WriteObject(AccountName);
writer.WriteObject(LatitudeID);
writer.WriteObject(Timecode);
writer.WriteObject(reverseGeocode);
writer.WriteObject(Latitude);
writer.WriteObject(Longitude);
writer.WriteObject(AccuracyInMeters);
return writer.ToArray();
}
public void Deserialize(byte[] Data)
{
SerializationReader reader = new SerializationReader(Data);
AccountName = (String)reader.ReadObject();
LatitudeID = (String)reader.ReadObject();
Timecode = (Int64)reader.ReadObject();
reverseGeocode = (String)reader.ReadObject();
Latitude = (Double)reader.ReadObject();
Longitude = (Double)reader.ReadObject();
AccuracyInMeters = (Int32)reader.ReadObject();
}
#endregion
}
}
| agpl-3.0 |
jzinedine/CMDBuild | dms/alfresco/src/main/java/org/cmdbuild/dms/alfresco/ftp/AlfrescoFtpService.java | 1326 | package org.cmdbuild.dms.alfresco.ftp;
import javax.activation.DataHandler;
import org.cmdbuild.dms.DmsConfiguration;
import org.cmdbuild.dms.DocumentDelete;
import org.cmdbuild.dms.DocumentDownload;
import org.cmdbuild.dms.DocumentSearch;
import org.cmdbuild.dms.StorableDocument;
import org.cmdbuild.dms.alfresco.AlfrescoInnerService;
import org.cmdbuild.dms.exception.DmsError;
public class AlfrescoFtpService extends AlfrescoInnerService {
public AlfrescoFtpService(final DmsConfiguration configuration) {
super(configuration);
}
@Override
public void delete(final DocumentDelete document) throws DmsError {
ftpClient().delete( //
document.getFileName(), //
document.getPath() //
);
}
@Override
public DataHandler download(final DocumentDownload document) throws DmsError {
return ftpClient().download( //
document.getFileName(), //
document.getPath() //
);
}
@Override
public void upload(final StorableDocument document) throws DmsError {
ftpClient().upload( //
document.getFileName(), //
document.getInputStream(), //
document.getPath() //
);
}
private AlfrescoFtpClient ftpClient() {
return new AlfrescoFtpClient(configuration);
}
public void create(final DocumentSearch document) throws DmsError {
ftpClient().mkdir(document.getPath());
}
}
| agpl-3.0 |
pmitros/x-analytics-scripts | xanalytics/streaming.py | 15280 | '''
This file contains streaming data processors. Why stream
processing? A few reasons:
1. You get immediate results. Development time is much faster. If you
have a bug, you see it almost immediately.
2. The code is more readable.
Downsides:
1. Stack traces are a bit ugly.
See:
http://www.dabeaz.com/generators/Generators.pdf
For best practices.
'''
import argparse
import dateutil.parser
import gzip
import itertools
import md5
import numbers
import os
import string
import struct
import warnings
try:
import simplejson as json
except:
import json
from fs.base import FS
import fs.osfs
from bson import BSON
import xanalytics.settings
######
# Generic functions to stream processing in Python
######
def filter_map(f, *args):
'''
Turn a function into an iterator and apply to each item. Pass on
items which return 'None'
'''
def map_stream(data, *fargs):
for d in data:
if d is not None:
o = f(d, *(args + fargs))
if o:
yield o
return map_stream
def _to_filesystem(filesystem_or_directory):
'''
Take a pyfilesystem or directory.
If a directory, return a pyfilesystem.
This gives backwards-compatibility with code before we moved to pyfs
'''
if isinstance(filesystem_or_directory, FS):
return filesystem_or_directory
elif isinstance(filesystem_or_directory, basestring):
warnings.warn("We're deprecating directory support in favor of pyfs.")
return fs.osfs.OSFS(filesystem_or_directory)
else:
error = "Unrecognized filesystem parameter: " + \
repr(filesystem_or_directory)
raise AttributeError(error)
def get_files(filesystem, directory=".", only_gz=False):
'''
Return an iterator of all the files in a given directory or pyfilesystem.
>>> "__init__.py" in list(get_files("."))
True
>>> import fs.osfs
>>> "__init__.py" in list(get_files(fs.osfs.OSFS(".")))
True
'''
filesystem = _to_filesystem(filesystem)
for f in sorted(filesystem.listdir(directory)):
if only_gz and not f.endswith(".gz"):
continue
yield f
def _read_text_data(filesystem, directory=".", only_gz=False):
'''
Helper: Yield all the lines in all the files in a directory.
The only_gz helps with edX directories which contain a mixture of
useful and useless files.
'''
filesystem = _to_filesystem(filesystem)
for f in filesystem.listdir(directory):
if only_gz and not f.endswith(".gz"):
continue
for line in filesystem.open(directory + "/" + f):
yield line.encode('ascii', 'ignore')
def _read_bson_data(filesystem, directory):
for f in get_files(filesystem, directory, only_gz):
fp = filesystem.open(os.path.join(directory, f))
for line in _read_bson_file(fp):
yield line
@filter_map
def text_to_csv(line, csv_delimiter="\t", csv_header=False):
'''
Untested
'''
if csv_header:
# TODO
raise UnimplementedException("CSVs with headers don't work yet. "
"Sorry. Major hole.")
else:
if line[-1] == '\n':
line = line[:-1]
return line.split(csv_delimiter)
def read_data(filesystem,
directory=".",
only_gz=False,
format="text",
csv_delimiter="\t",
csv_header=False):
'''Takes a pyfs containing log files. Returns an iterator of all
lines in all files.
Optional: Skip non-.gz files.
Optional: Format can be text, JSON, or BSON, in which case, we'll decode.
'''
filesystem = _to_filesystem(filesystem)
if format == "bson":
warnings.warn("Untested code path")
return _read_bson_data(filesystem, directory)
text_data = _read_text_data(filesystem, directory, only_gz)
if format == "text":
return text_data
elif format == "json":
return text_to_json(text_data)
elif format == "csv":
return text_to_csv(text_data, csv_delimiter, csv_header)
else:
raise AttributeError("Unknown format: ", format)
@filter_map
def text_to_json(line, clever=False):
'''Decode lines to JSON. If a line is truncated, this will drop the line.
clever allows us to try to reconstruct long lines. This is not
helpful for most analytics due to performance, but it is in cases
where we need every last bit of data.
>>> data = ("""{"a":"b"}""", """["c", "d"]""", )
>>> list(text_to_json(data))
[{u'a': u'b'}]
'''
line = line.strip()
if "{" not in line:
return None
if len(line) == 0:
return None
if line[0] not in ['{']: # Tracking logs are always dicts
return None
if clever:
endings = ['', '}', '"}', '""}', '"}}', '"}}}',
'"}}}}', '"}}}}}', '"}}}}}}']
for ending in endings:
try:
line = json.loads(line + ending)
return line
except:
pass
print >>sys.stderr, line
print >>sys.stderr, "Warning: We've got a line we couldn't fix up.\n" \
"Please look at it, and add the right logic to streaming.py.\n" \
"It's usually a new ending. Sometimes, it's "\
"detecting a non-JSON line of some form"
os.exit(-1)
# We've truncated lines to random lengths in the past...
if len(line) in range(32000, 33000):
return None
elif len(line) in range(9980, 10001):
return None
elif len(line) in range(2039, 2044):
return None
try:
line = json.loads(line)
return line
except ValueError:
print line, len(line)
return None
def json_to_text(data):
''' Convert JSON back to text, for dumping to processed file
'''
for line in data:
yield json.dumps(line) + '\n'
_data_part = 0
_data_item = 0
def save_data(data, directory):
'''
Write data back to the directory specified. Data is dumped into
individual files, each a maximum of 20,000 events long (by
default, overridable in settings).
'''
global _data_part, _data_item
fout = None
max_file_length = int(settings.settings.get('max-file-size', 20000))
for line in data:
if _data_item % 20000 == 0:
if fout:
fout.close()
filename = "{dir}/part{part}.gz".format(dir=directory,
part=_data_part)
fout = gzip.open(filename, "w")
_data_part = _data_part + 1
fout.write(line)
_data_item = _data_item + 1
def read_bson_file(filename):
'''
Reads a dump of BSON to a file.
Reading BSON is 3-4 times faster than reading JSON with:
import json
Performance between cjson, simplejson, and other libraries is more
mixed.
Untested since move from filename to fp and refactoring
'''
return _read_bson_file(gzip.open(filename))
def encode_to_bson(data):
'''
Encode to BSON. Encoding BSON is about the same speed as encoding
JSON (~25% faster), but decoding is much faster.
'''
for d in data:
yield BSON.encode(d)
_hash_memory = dict()
def short_hash(string, length=3, memoize=False):
'''
Provide a compact hash of a string. Returns a hex string which is
the hash. length is the length of the string.
This is helpful if we want to shard data. This is not helpful if
we want to avoid collisions. The hash is **short**.
>>> short_hash("Alice") != short_hash("Bob")
True
>>> short_hash("Eve") == short_hash("Eve")
True
>>> "Alice" not in _hash_memory
True
>>> short_hash("Eve", memoize=True) == short_hash("Eve", memoize=True)
True
>>> "Eve" in _hash_memory
True
>>> len(short_hash("Mallet")) == 3
True
'''
global _hash_memory
if memoize:
if string in _hash_memory:
return _hash_memory[string]
m = md5.new()
m.update(string)
h = m.hexdigest()[0:length]
if memoize:
_hash_memory[string] = h
return h
def list_short_hashes(length):
'''
A generator of all hashes of length `length` (as would be
generated by short_hash)
Hashes are of the form we expect
>>> "aa" in list(list_short_hashes(2))
True
They take all possible hex values
>>> len(list(list_short_hashes(3))) == 16 ** 3
True
The list is complete/unique
>>> len(list(list_short_hashes(3))) == len(set(list_short_hashes(3)))
True
>>> short_hash("Hello", 3) in list(list_short_hashes(3))
True
'''
generator = ("".join(x)
for x in itertools.product("0123456789abcdef", repeat=length))
return generator
def filter_data(data, filter):
'''
Apply a function 'filter' to all elements in the data
'''
for item in data:
if filter(item):
yield item
######
# Stream operations specific to edX
######
def event_count(data):
'''
Count number of events in data.
'''
count = 0
for event in data:
count = count + 1
return count
def users_count(data):
'''
Count number of unique users in data
'''
return len(field_set(data, "username"))
def field_set(data, field):
'''
Return a set of unique items in field
'''
us = set()
for event in data:
us.add(__select_field(event, field))
return us
def dbic(data, label):
'''
Debug: Print item count
'''
cnt = 0
for d in data:
cnt = cnt + 1
yield d
print label, cnt
def __select_field(event, field):
'''
Takes a field definition and a dictionary. Does a hierarchical query.
__select_field(event, "event:element") is equivalent to:
try:
event['event']['element']
except KeyError:
return None
'''
for key in field.split(":"): # Pick out the hierarchy
if key not in event:
return None
event = event[key]
return event
def sort_events(data, fields):
'''
Sort data. Warning: In-memory. Not iterable. Only works for small datasets
'''
def event_cmp(d1, d2):
for field in fields:
c = cmp(__select_field(d1, field), __select_field(d2, field))
if c != 0:
return c
return 0
return sorted(list(data), cmp=event_cmp)
def select_fields(data, fields):
'''
Filter data down to a subset of fields. Also, flatten (should be a
param in the future whether to do this.
'''
for d in data:
d2 = {}
for field in fields:
d2[field] = __select_field(d, field)
yield d2
def select_in(data, string):
'''
Select data from _text_ (not JSON) where a string appears is in the data
'''
for d in data:
if string in d:
yield d
def memoize(data, directory):
'''
UNTESTED/UNTESTED/UNTESTED
Check if the directory already has data. If so, read it in. Otherwise, dump
data to the directory and return it.
The current version reads/writes redundantly on the save operation, and
JSON decodes redundantly, so it's not very performant. This would be worth
fixing.
UNTESTED/UNTESTED/UNTESTED
'''
for f in os.listdir(directory):
if not f.endswith(".gz"):
continue
return read_data(directory)
save_data(data, directory)
return read_data(directory)
def _read_bson_file(fp):
while True:
l = f.read(4)
if len(l) < 4:
break
length = struct.unpack('<i', l)
o = l + f.read(length[0]-4)
yield BSON.decode(BSON(o))
_tokens = dict()
_token_ct = 0
def token(user):
'''
Generate a token for a username. The tokens are generated in
order, so this is not generically secure. In this context, they
are generate by the order users appear in the log file.
Note that this is limited to courses with 140608 users for now (if
you go over, it will raise an exception).
>>> names = map(str, range(100))
>>> tokenized_once = map(token, names)
>>> tokenized_twice = map(token, names)
Confirm we have the same mapping if we pass a name through twice
>>> print tokenized_once == tokenized_twice
True
Confirm we have a different mapping for different users
>>> len(set(tokenized_once)) == len(tokenized_once)
True
'''
global _tokens, _token_ct
if user in _tokens:
return _tokens[user]
t = string.letters[(_token_ct / (52 * 52)) % 52] + \
string.letters[(_token_ct / 52) % 52] + \
string.letters[_token_ct % 52]
_token_ct = _token_ct + 1
if _token_ct > 140607:
raise "We need to clean up tokenization code to support more users"
_tokens[user] = t
return t
def merge_generators(l, key=lambda x: x):
'''
Perform a merge of generators, keeping order.
If inputs are sorted from greatest to least, output will be sorted
likewise.
Possible uses:
* Hadoop-style merge sort.
* In-order output from multiprocess.py.
This is likely obsoleted for most purposes by megasort.py
>>> import random
>>> a = sorted([random.randint(0, 50) for x in range(10)], reverse=True)
>>> b = sorted([random.randint(0, 50) for x in range(10)], reverse=True)
>>> c = sorted([random.randint(0, 50) for x in range(10)], reverse=True)
>>> list(merge_generators([a, b, c])) == sorted(a + b + c, reverse=True)
True
'''
l = map(iter, l)
def next(g):
'''
Get next iterm from a generator.
If no more items, return None
'''
try:
return g.next()
except StopIteration:
return None
def key_wrapper(a):
if a is None:
return None
else:
return key(a[1])
heads = [(i, l[i].next()) for i in range(len(l))]
while max(heads, key=key_wrapper)[1] is not None:
item = max(heads, key=key_wrapper)
yield item[1]
heads[item[0]] = (item[0], next(l[item[0]]))
def fields(d, separator="."):
'''
Return all of the fields in a JSON object, flattened.
>>> fields({'a':{'b':'c', 'd':{'e':'f','g':'h'},'i':'j'}, 'k':'l'})
set(['k', 'a.d.g', 'a.i', 'a.b', 'a.d.e'])
'''
s = set()
for k in d:
if isinstance(d[k], dict):
s.update(k+separator+x for x in fields(d[k]))
else:
s.add(k)
return s
def flatten(d, separator="."):
'''
Flatten a JSON object, so there is one top-level dictionary, and
keys are flattened.
>>> flatten({'a':{'b':'c', 'd':{'e':'f','g':'h'},'i':'j'}, 'k':'l'})
{'k': 'l', 'a.d.g': 'h', 'a.i': 'j', 'a.b': 'c', 'a.d.e': 'f'}
'''
nd = dict()
for k in d:
if isinstance(d[k], dict):
cd = flatten(d[k])
nd.update((k+separator+x, cd[x]) for x in cd)
else:
nd[k] = d[k]
return nd
def snoop(data):
for item in data:
print item
yield item
if __name__ == '__main__':
import doctest
doctest.testmod()
| agpl-3.0 |
dzc34/Asqatasun | rules/rules-rgaa3.0/src/main/java/org/asqatasun/rules/rgaa30/Rgaa30Rule010401.java | 2576 | /*
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2019 Asqatasun.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.rules.rgaa30;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.asqatasun.entity.audit.TestSolution;
import org.asqatasun.ruleimplementation.AbstractDetectionPageRuleImplementation;
import org.asqatasun.rules.elementselector.CaptchaElementSelector;
import org.asqatasun.rules.elementselector.SimpleElementSelector;
import static org.asqatasun.rules.keystore.AttributeStore.ALT_ATTR;
import static org.asqatasun.rules.keystore.AttributeStore.SRC_ATTR;
import static org.asqatasun.rules.keystore.CssLikeQueryStore.IMG_WITH_ALT_NOT_IN_LINK_CSS_LIKE_QUERY;
import static org.asqatasun.rules.keystore.RemarkMessageStore.CHECK_CAPTCHA_ALTERNATIVE_MSG;
/**
* Implementation of the rule 1.4.1 of the referential Rgaa 3.0.
* <br/>
* For more details about the implementation, refer to <a href="http://doc.asqatasun.org/en/90_Rules/rgaa3.0/01.Images/Rule-1-4-1.html">the rule 1.4.1 design page.</a>
* @see <a href="http://references.modernisation.gouv.fr/referentiel-technique-0#test-1-4-1"> 1.4.1 rule specification</a>
*
*/
public class Rgaa30Rule010401 extends AbstractDetectionPageRuleImplementation {
/**
* Default constructor
*/
public Rgaa30Rule010401 () {
super(
new CaptchaElementSelector(
new SimpleElementSelector(IMG_WITH_ALT_NOT_IN_LINK_CSS_LIKE_QUERY)),
// solution when at least one element is found
new ImmutablePair(TestSolution.NEED_MORE_INFO,CHECK_CAPTCHA_ALTERNATIVE_MSG),
// solution when no element is found
new ImmutablePair(TestSolution.NOT_APPLICABLE,""),
// evidence elements
ALT_ATTR,
SRC_ATTR
);
}
}
| agpl-3.0 |
sgmap/mes-aides-ui | src/main.js | 1620 | import "core-js/stable"
import Vue from "vue"
import App from "./App.vue"
import router from "./router"
import store from "./store"
import moment from "moment"
import ScrollService from "./plugins/ScrollService"
import StateService from "./plugins/StateService"
import AsyncComputed from "vue-async-computed"
import * as Sentry from "@sentry/vue"
import Vuelidate from "vuelidate"
import VueMatomo from "vue-matomo"
import "template.data.gouv.fr/dist/main.css"
import "font-awesome/scss/font-awesome.scss"
import "@/styles/main.scss"
import AnalyticsDirective from "./directives/analytics"
import MailDirective from "./directives/mail"
import SelectOnClickDirective from "./directives/selectOnClick"
import { iframeResizerContentWindow } from "iframe-resizer"
const Resizer = {
install: function () {
iframeResizerContentWindow
},
}
AnalyticsDirective(Vue)
MailDirective(Vue)
SelectOnClickDirective(Vue)
if (process.env.NODE_ENV === "production") {
Sentry.init({
Vue,
dsn: "https://[email protected]/5709078",
})
}
Vue.use(AsyncComputed)
Vue.use(Resizer)
Vue.use(ScrollService)
Vue.use(StateService)
Vue.use(Vuelidate)
Vue.use(VueMatomo, {
host: "https://stats.data.gouv.fr",
trackerFileName: "piwik",
siteId: process.env.VUE_APP_MATOMO_ID,
router: router,
})
Vue.filter("capitalize", function (value) {
if (!value) return ""
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)
})
Vue.config.productionTip = false
moment.locale("fr")
new Vue({
router,
store,
render: (h) => h(App),
}).$mount("#app")
| agpl-3.0 |
ungerik/ephesoft | Ephesoft_Community_Release_4.0.2.0/source/gxt/gxt-admin/src/main/java/com/ephesoft/gxt/admin/client/presenter/document/testextraction/datatable/DataTableGridPresenter.java | 3522 | /*********************************************************************************
* Ephesoft is a Intelligent Document Capture and Mailroom Automation program
* developed by Ephesoft, Inc. Copyright (C) 2015 Ephesoft Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY EPHESOFT, EPHESOFT DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact Ephesoft, Inc. headquarters at 111 Academy Way,
* Irvine, CA 92617, USA. or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Ephesoft" logo.
* If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by Ephesoft".
********************************************************************************/
package com.ephesoft.gxt.admin.client.presenter.document.testextraction.datatable;
import com.ephesoft.dcma.batch.schema.DataTable;
import com.ephesoft.gxt.admin.client.controller.BatchClassManagementController;
import com.ephesoft.gxt.admin.client.event.ClearTestExtractionGridEvent;
import com.ephesoft.gxt.admin.client.presenter.document.testextraction.TestExtractionInlinePresenter;
import com.ephesoft.gxt.admin.client.view.document.testextraction.datatable.DataTableGridView;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.web.bindery.event.shared.binder.EventBinder;
import com.google.web.bindery.event.shared.binder.EventHandler;
public class DataTableGridPresenter extends TestExtractionInlinePresenter<DataTableGridView> {
public DataTableGridPresenter(BatchClassManagementController controller, DataTableGridView view) {
super(controller, view);
}
interface CustomEventBinder extends EventBinder<DataTableGridPresenter> {
}
private static final CustomEventBinder eventBinder = GWT.create(CustomEventBinder.class);
@Override
public void injectEvents(EventBus eventBus) {
eventBinder.bindEventHandlers(this, eventBus);
}
@EventHandler
public void clearVerticalLayoutContainer(ClearTestExtractionGridEvent clearVLC) {
view.clearVerticalLayoutContainer();
controller.clearNoExtractionResultView();
}
@Override
public void bind() {
DataTable selectedDataTable = controller.getSelectedDataTable();
view.initialiseDataTableGrid(selectedDataTable);
}
}
| agpl-3.0 |
natea/Miro-Community | localtv/util.py | 12513 | # Copyright 2009 - Participatory Culture Foundation
#
# This file is part of Miro Community.
#
# Miro Community is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Miro Community is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Miro Community. If not, see <http://www.gnu.org/licenses/>.
import hashlib
import re
import string
import urllib
from django.conf import settings
from django.core.cache import cache
from django.core.mail import EmailMessage
from django.db.models import get_model, Q
from django.utils.encoding import force_unicode
import tagging
import vidscraper
from notification import models as notification
VIDEO_EXTENSIONS = [
'.mov', '.wmv', '.mp4', '.m4v', '.ogg', '.ogv', '.anx',
'.mpg', '.avi', '.flv', '.mpeg', '.divx', '.xvid', '.rmvb',
'.mkv', '.m2v', '.ogm']
def is_video_filename(filename):
"""
Pass a filename to this method and it will return a boolean
saying if the filename represents a video file.
"""
filename = filename.lower()
for ext in VIDEO_EXTENSIONS:
if filename.endswith(ext):
return True
return False
def is_video_type(type):
application_video_mime_types = [
"application/ogg",
"application/x-annodex",
"application/x-bittorrent",
"application/x-shockwave-flash"
]
return (type.startswith('video/') or type.startswith('audio/') or
type in application_video_mime_types)
def get_first_video_enclosure(entry):
"""Find the first video enclosure in a feedparser entry. Returns the
enclosure, or None if no video enclosure is found.
"""
enclosures = entry.get('media_content') or entry.get('enclosures')
if not enclosures:
return None
best_enclosure = None
for enclosure in enclosures:
if is_video_type(enclosure.get('type', '')) or \
is_video_filename(enclosure.get('url', '')):
if enclosure.get('isdefault'):
return enclosure
elif best_enclosure is None:
best_enclosure = enclosure
return best_enclosure
def get_thumbnail_url(entry):
"""Get the URL for a thumbnail from a feedparser entry."""
# Try the video enclosure
def _get(d):
if 'media_thumbnail' in d:
return d.media_thumbnail[0]['url']
if 'blip_thumbnail_src' in d and d.blip_thumbnail_src:
return (u'http://a.images.blip.tv/%s' % (
d['blip_thumbnail_src'])).encode('utf-8')
if 'itunes_image' in d:
return d.itunes_image['href']
if 'image' in d:
return d.image['href']
raise KeyError
video_enclosure = get_first_video_enclosure(entry)
if video_enclosure is not None:
try:
return _get(video_enclosure)
except KeyError:
pass
# Try to get any enclosure thumbnail
for key in 'media_content', 'enclosures':
if key in entry:
for enclosure in entry[key]:
try:
return _get(enclosure)
except KeyError:
pass
# Try to get the thumbnail for our entry
try:
return _get(entry)
except KeyError:
pass
if entry.get('link', '').find(u'youtube.com') != -1:
if 'content' in entry:
content = entry.content[0]['value']
elif 'summary' in entry:
content = entry.summary
else:
return None
match = re.search(r'<img alt="" src="([^"]+)" />',
content)
if match:
return match.group(1)
return None
def get_tag(tag_text):
while True:
try:
tags = tagging.models.Tag.objects.filter(name=tag_text)
if not tags.count():
return tagging.models.Tag.objects.create(name=tag_text)
elif tags.count() == 1:
return tags[0]
else:
for tag in tags:
if tag.name == tag:
# MySQL doesn't do case-sensitive equals on strings
return tag
except Exception:
pass # try again to create the tag
def get_or_create_tags(tag_list):
tag_set = set()
for tag_text in tag_list:
if isinstance(tag_text, basestring):
tag_text = tag_text[:50] # tags can only by 50 chars
if settings.FORCE_LOWERCASE_TAGS:
tag_text = tag_text.lower()
tag = get_tag(tag_text);
tag.name = force_unicode(tag.name)
tag_set.add(tag)
return tagging.utils.edit_string_for_tags(list(tag_set))
def get_scraped_data(url):
cache_key = 'vidscraper_data-' + url
if len(cache_key) >= 250:
# too long, use the hash
cache_key = 'vidscraper_data-hash-' + hashlib.sha1(url).hexdigest()
scraped_data = cache.get(cache_key)
if not scraped_data:
# try and scrape the url
try:
scraped_data = vidscraper.auto_scrape(url)
except vidscraper.errors.Error:
scraped_data = None
cache.add(cache_key, scraped_data)
return scraped_data
def send_notice(notice_label, subject, message, fail_silently=True,
sitelocation=None):
notice_type = notification.NoticeType.objects.get(label=notice_label)
recipient_list = notification.NoticeSetting.objects.filter(
notice_type=notice_type,
medium="1",
send=True).exclude(user__email='').filter(
Q(user__in=sitelocation.admins.all()) |
Q(user__is_superuser=True)).values_list('user__email', flat=True)
EmailMessage(subject, message, settings.DEFAULT_FROM_EMAIL,
bcc=recipient_list).send(fail_silently=fail_silently)
class SortHeaders:
def __init__(self, request, headers, default_order=None):
self.request = request
self.header_defs = headers
if default_order is None:
for header, ordering in headers:
if ordering is not None:
default_order = ordering
break
self.default_order = default_order
if default_order.startswith('-'):
self.desc = True
self.ordering = default_order[1:]
else:
self.desc = False
self.ordering = default_order
# Determine order field and order type for the current request
sort = request.GET.get('sort', '')
desc = False
if sort.startswith('-'):
desc = True
sort = sort[1:]
if sort:
for header, ordering in headers:
if ordering and ordering.startswith('-'):
ordering = ordering[1:]
if sort == ordering:
self.ordering, self.desc = sort, desc
def headers(self):
"""
Generates dicts containing header and sort link details for
all defined headers.
"""
for header, ordering in self.header_defs:
css_class = ''
if ordering == self.ordering or (
ordering and ordering.startswith('-') and
ordering[1:] == self.ordering):
# current sort
if self.desc:
ordering = self.ordering
css_class = 'sortup'
else:
ordering = '-%s' % self.ordering
css_class = 'sortdown'
yield {
'sort': ordering,
'link': self._query_string(ordering),
'label': header,
'class': css_class
}
def __iter__(self):
return iter(self.headers())
def _query_string(self, sort):
"""
Creates a query string from the given dictionary of
parameters, including any additonal parameters which should
always be present.
"""
if sort is None:
return None
params = self.request.GET.copy()
params.pop('sort', None)
params.pop('page', None)
if sort != self.default_order:
params['sort'] = sort
if not params:
return self.request.path
return '?%s' % params.urlencode()
def order_by(self):
"""
Creates an ordering criterion based on the current order
field and order type, for use with the Django ORM's
``order_by`` method.
"""
return '%s%s' % (
self.desc and '-' or '',
self.ordering)
class MockQueryset(object):
"""
Wrap a list of objects in an object which pretends to be a QuerySet.
"""
def __init__(self, objects, model=None, filters=None):
self.objects = objects
self.model = model
self.filters = filters or {}
if self.model:
self.db = model.objects.all().db
elif hasattr(objects, 'db'):
self.db = objects.db
else:
self.db = 'default'
self._count = None
self._iter_index = None
self._result_cache = []
self.ordered = True
def all(self):
return self
def _clone(self):
return self
def __len__(self):
if self._count is None:
if self.model:
self._count = self.model.objects.filter(
pk__in=self.objects).count()
else:
self._count = len(self.objects)
return self._count
def __iter__(self):
if not self.model:
return iter(self.objects)
it = MockQueryset(self.objects, self.model, self.filters)
it._count = self._count
it._result_cache = self._result_cache[:]
it._iter_index = 0
return it
def next(self):
if self._iter_index is None:
raise RuntimeError('Cannot use MockQueryset directly as an '
'iterator, must call iter() first')
if self._iter_index == len(self):
raise StopIteration # don't even bother looking for more results
if self._iter_index >= len(self._result_cache): # not enough data
objs = []
while True:
next = self.objects[self._iter_index:self._iter_index + 20]
if not next:
break
values = self.model.objects.in_bulk(next)
objs = [values[k] for k in next
if k in values and \
self._is_valid(values[k])]
if objs:
break
self._result_cache += objs
if self._iter_index >= len(self._result_cache):
raise StopIteration
result = self._result_cache[self._iter_index]
self._iter_index += 1
return result
def _is_valid(self, obj):
if not self.filters:
return True
for filter_key, filter_value in self.filters.items():
if getattr(obj, filter_key) != filter_value:
return False
return True
def __getitem__(self, k):
if isinstance(k, slice):
mq = MockQueryset(self.objects[k], self.model, self.filters)
return mq
return self.objects[k]
def filter(self, **kwargs):
new_filters = self.filters.copy()
for k, v in kwargs.items():
if '__' in k: # special filter
return self.objects.filter(**kwargs)
new_filters[k] = v
return MockQueryset(self.objects, self.model, new_filters)
def get_profile_model():
app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
Profile = get_model(app_label, model_name)
if Profile is None:
raise RuntimeError("could not find a Profile model at %r" %
settings.AUTH_PROFILE_MODULE)
return Profile
SAFE_URL_CHARACTERS = string.ascii_letters + string.punctuation
def quote_unicode_url(url):
return urllib.quote(url, safe=SAFE_URL_CHARACTERS)
| agpl-3.0 |
open-craft/opencraft | instance/tests/models/test_mixin_utilities.py | 15755 | """
Test model mixin utilities.
"""
import json
from unittest import TestCase
import ddt
from django.test.utils import override_settings
from instance.models.mixins.utilities import SensitiveDataFilter, get_ansible_failure_log_entry
from instance.tests.models.factories.openedx_instance import OpenEdXInstanceFactory
from instance.tests.models.factories.openedx_appserver import make_test_appserver
@ddt.ddt
class SensitiveDataFilterTestCase(TestCase):
"""
Test sensitive data filtering context manager.
"""
@ddt.data([
list(),
["nothing", "to", "filter", "here"],
["nothing", {"to": {"filter", "here"}}],
["nothing", {"to": {"filter": ["here"]}}],
["nothing", ["to", ["filter", ["here"]]]],
dict(),
{"nothing": "to", "filter": "here"},
{"nothing": {"to": {"filter": "here"}}},
{"nothing": {"to": ["filter", ["here"]]}},
{"nothing": {"to": {"filter": ["here"]}}},
{"nothing": ["to", {"filter": "here"}]},
{"nothing": ["to", {"filter": ["here"]}]},
"",
"nothing to filter here",
])
def test_nothing_to_filter(self, data):
"""
Test nothing is sensitive in the given data.
"""
with SensitiveDataFilter(data) as filtered_data:
self.assertEqual(data, filtered_data)
@ddt.data(
("username:password", SensitiveDataFilter.FILTERED_TEXT),
("api-abc", SensitiveDataFilter.FILTERED_TEXT),
("api_abc", SensitiveDataFilter.FILTERED_TEXT),
("token-abc", SensitiveDataFilter.FILTERED_TEXT),
("token_abc", SensitiveDataFilter.FILTERED_TEXT),
("key-abc", SensitiveDataFilter.FILTERED_TEXT),
("key_abc", SensitiveDataFilter.FILTERED_TEXT),
("KeY_AbC_d", SensitiveDataFilter.FILTERED_TEXT),
("UPPERCASE_KEY", SensitiveDataFilter.FILTERED_TEXT),
)
@ddt.unpack
def test_filter_plain_text(self, data, expected):
"""
Test filtering for plain text data.
"""
with SensitiveDataFilter(data) as filtered_data:
self.assertEqual(filtered_data, expected)
@ddt.data(
(
["username:password"],
[SensitiveDataFilter.FILTERED_TEXT]
),
(
[{"username": "test", "password": "topsecret"}],
[{"username": "test", "password": SensitiveDataFilter.FILTERED_TEXT}]
),
(
[{"username": "test", "password": ["this won't be filtered"]}],
[{"username": "test", "password": ["this won't be filtered"]}] # not matching any plain text pattern
),
(
[{"data": {"password": "topsecret"}}],
[{"data": {"password": SensitiveDataFilter.FILTERED_TEXT}}],
),
(
[{"data": {"password": ["this won't be filtered"]}}],
[{"data": {"password": ["this won't be filtered"]}}], # not matching any plain text pattern
),
(
[{"data": {"password": ["api-abc"]}}],
[{"data": {"password": [SensitiveDataFilter.FILTERED_TEXT]}}],
),
(
[{"data": {"password": ["api_abc"]}}],
[{"data": {"password": [SensitiveDataFilter.FILTERED_TEXT]}}],
),
(
[{"data": {"password": ["token-abc"]}}],
[{"data": {"password": [SensitiveDataFilter.FILTERED_TEXT]}}],
),
(
[{"data": {"password": ["token_abc"]}}],
[{"data": {"password": [SensitiveDataFilter.FILTERED_TEXT]}}],
),
(
[{"data": {"password": ["key-abc"]}}],
[{"data": {"password": [SensitiveDataFilter.FILTERED_TEXT]}}],
),
(
[{"data": {"password": ["key_abc"]}}],
[{"data": {"password": [SensitiveDataFilter.FILTERED_TEXT]}}],
),
(
[{"data": {"password": ["user:pass", "some:pattern"]}}],
[{"data": {"password": [SensitiveDataFilter.FILTERED_TEXT, SensitiveDataFilter.FILTERED_TEXT]}}],
),
)
@ddt.unpack
def test_filter_list_data(self, data, expected):
"""
Test filtering for list data.
"""
with SensitiveDataFilter(data) as filtered_data:
self.assertListEqual(filtered_data, expected)
@ddt.data(
(
{"password": "topsecret"},
{"password": SensitiveDataFilter.FILTERED_TEXT}
),
(
{"nested": {"password": "topsecret"}},
{"nested": {"password": SensitiveDataFilter.FILTERED_TEXT}},
),
(
{"nested": {"list": ["of", {"some": [{"password": "topsecret"}]}]}},
{"nested": {"list": ["of", {"some": [{"password": SensitiveDataFilter.FILTERED_TEXT}]}]}},
),
(
{"api-abc": "topsecret"},
{"api-abc": SensitiveDataFilter.FILTERED_TEXT}
),
(
{"api_abc": "topsecret"},
{"api_abc": SensitiveDataFilter.FILTERED_TEXT}
),
(
{"token-abc": "topsecret"},
{"token-abc": SensitiveDataFilter.FILTERED_TEXT}
),
(
{"token_abc": "topsecret"},
{"token_abc": SensitiveDataFilter.FILTERED_TEXT}
),
(
{"key-abc": "topsecret"},
{"key-abc": SensitiveDataFilter.FILTERED_TEXT}
),
(
{"key_abc": "topsecret"},
{"key_abc": SensitiveDataFilter.FILTERED_TEXT}
),
(
{"not_problematic": "topsecret"},
{"not_problematic": SensitiveDataFilter.FILTERED_TEXT}
),
# Complex data which is like an ansible output. Although most of the data is
# filtered out, that's the behaviour what is expected. In case of a real ansible
# output, the error lines will verbose and not contain that much text to filter out.
(
{
"changed": False,
"cmd": "/usr/bin/git checkout --force 1821396aee788eabe2ec4cb00f60879a3fde7d01",
"msg": "Failed to checkout 1821396aee788eabe2ec4cb00f60879a3fde7d01",
"rc": 128,
"stderr": r"fatal: tree: tree\npassword: abc\nmyuser:mypa$$word\naPiKey=123\nnot matching line",
"stderr_lines": [
"fatal: reference is not a tree: tree",
"password: abc",
"myuser:mypa$$word",
"aPiKey=123",
"/edx/app/forum/cs_comments_service/lib/tasks/kpis.rake:7: ",
"warning: already initialized constant ROOT",
"not matching line"
],
"stdout": "",
"stdout_lines": []
},
{
"changed": False,
"cmd": "/usr/bin/git checkout --force 1821396aee788eabe2ec4cb00f60879a3fde7d01",
"msg": "Failed to checkout 1821396aee788eabe2ec4cb00f60879a3fde7d01",
"rc": 128,
# the following line is filtered completely, which is not an issue, since the error lines will
# be listed line-by-line below; there is no better/safer way to keep the sensitive data in safe
"stderr": SensitiveDataFilter.FILTERED_TEXT,
"stderr_lines": [
"fatal: reference is not a tree: tree",
SensitiveDataFilter.FILTERED_TEXT,
SensitiveDataFilter.FILTERED_TEXT,
SensitiveDataFilter.FILTERED_TEXT,
"/edx/app/forum/cs_comments_service/lib/tasks/kpis.rake:7: ",
"warning: already initialized constant ROOT",
"not matching line",
],
"stdout": "",
"stdout_lines": []
},
)
)
@ddt.unpack
def test_filter_dict_data(self, data, expected):
"""
Test filtering for dictionaries for various values and nested dictionaries.
"""
self.maxDiff = None
with SensitiveDataFilter(data) as filtered_data:
self.assertDictEqual(filtered_data, expected)
@ddt.ddt
class AnsibleLogExtractTestCase(TestCase):
"""
Test extracting relevant failure ansible log entry from appserver logs.
"""
def setUp(self):
self.instance = OpenEdXInstanceFactory(name='test instance')
self.appserver = make_test_appserver(
instance=self.instance.appserver_set.first()
)
def test_no_entries_found(self):
"""
Test when no log entries found, we return default values, so processing
result can continue.
"""
self.appserver.logger.info('Usual log message')
self.appserver.logger.warning('A warning message')
self.appserver.logger.error("Some error happened, but that's not Ansible related")
self.appserver.logger.error("Other error message happened")
task_name, log_entry, _ = get_ansible_failure_log_entry(self.appserver.log_entries_queryset)
self.assertEqual(task_name, "")
self.assertDictEqual(log_entry, dict())
def test_entry_found_without_task_name(self):
"""
Test when entry found without task, the entry returned, but task name remains
empty. This behaviour is expected, since the value is in the log entry not in the
ansible task name.
"""
expected_log_entry = {"changed": False, "other": True, "stdout_lines": []}
self.appserver.logger.info('Usual log message')
self.appserver.logger.warning('A warning message')
self.appserver.logger.info('fatal: [1.2.3.4]: FAILED! => {}'.format(
json.dumps(expected_log_entry)
))
self.appserver.logger.error("Some error happened, but that's not Ansible related")
self.appserver.logger.error("Other error message happened")
task_name, log_entry, _ = get_ansible_failure_log_entry(self.appserver.log_entries_queryset)
self.assertEqual(task_name, "")
self.assertDictEqual(log_entry, expected_log_entry)
def test_entry_and_task_name_found(self):
"""
Test if we find both log entry and the belonging ansible task name, we return both.
"""
expected_task_name = "task name"
expected_log_entry = {"changed": False, "other": True, "stdout_lines": []}
self.appserver.logger.info('Usual log message')
self.appserver.logger.warning('A warning message')
self.appserver.logger.info(f'TASK [{expected_task_name}]')
self.appserver.logger.info(f'fatal: [1.2.3.4]: FAILED! => {json.dumps(expected_log_entry)}')
self.appserver.logger.error("Some error happened, but that's not Ansible related")
self.appserver.logger.error("Other error message happened")
task_name, log_entry, _ = get_ansible_failure_log_entry(self.appserver.log_entries_queryset)
self.assertEqual(task_name, expected_task_name)
self.assertDictEqual(log_entry, expected_log_entry)
@ddt.data("fatal", "changed", "skipping", "warning")
def test_complex_entry_and_task_name_found(self, kind):
"""
Test if we find both log entry and the belonging ansible task name, we return both.
"""
expected_task_name = "task name"
expected_log_entry = {"changed": False, "other": True, "stdout_lines": [
"WARN -- : MONGODB | Unsupported client option 'max_retries'. It will be ignored.",
"/edx/app/forum/.gem/ruby/2.5.0/gems/rake-12.0.0/exe/rake:27:in `<top (required)>'"
]}
self.appserver.logger.info('Usual log message')
self.appserver.logger.warning('A warning message')
self.appserver.logger.info(f'TASK [{expected_task_name}]')
self.appserver.logger.info(f'{kind}: [1.2.3.4]: FAILED! => {json.dumps(expected_log_entry)}')
self.appserver.logger.error("Some error happened, but that's not Ansible related")
self.appserver.logger.error("Other error message happened")
task_name, log_entry, _ = get_ansible_failure_log_entry(self.appserver.log_entries_queryset)
self.assertEqual(task_name, expected_task_name)
self.assertDictEqual(log_entry, expected_log_entry)
@ddt.data("fatal", "changed", "skipping", "warning")
def test_complex_entry_and_task_name_found_for_item_change(self, kind):
"""
Test if we find both log entry and the belonging ansible task name, we return both.
"""
expected_task_name = "task name"
expected_log_entry = {"changed": False, "other": True, "stdout_lines": [
"WARN -- : MONGODB | Unsupported client option 'max_retries'. It will be ignored.",
"/edx/app/forum/.gem/ruby/2.5.0/gems/rake-12.0.0/exe/rake:27:in `<top (required)>'"
]}
self.appserver.logger.info('Usual log message')
self.appserver.logger.warning('A warning message')
self.appserver.logger.info(f'TASK [{expected_task_name}]')
self.appserver.logger.info(f'{kind}: [1.2.3.4]: FAILED! => (item={json.dumps(expected_log_entry)})')
self.appserver.logger.error("Some error happened, but that's not Ansible related")
self.appserver.logger.error("Other error message happened")
task_name, log_entry, _ = get_ansible_failure_log_entry(self.appserver.log_entries_queryset)
self.assertEqual(task_name, expected_task_name)
self.assertDictEqual(log_entry, expected_log_entry)
@override_settings(LOG_LIMIT=2)
def test_entry_and_task_name_not_found_within_the_log_limit(self):
"""
Test that the log entries don't contain information past the cutoff point even if those
entries might have matched otherwise, and it would result in the log being empty.
"""
self.appserver.logger.info('TASK [task name]')
self.appserver.logger.info(
'failed: [1.2.3.4] (item={"state": "present", "password": "***", "name": "397bf39ead3d3751"}) => '
'{"ansible_loop_var": "item", "changed": false, "item": {"name": "397bf39ead3d3751", "password": "***",'
'"state": "present"}, "msg": "Failed to import the required Python library (passlib) on '
'edxapp-periodic-buil-appserver-1039\'s Python /usr/bin/python3. Please read module documentation and '
'install in the appropriate location"}',
)
self.appserver.logger.info(
'fatal: [1.2.3.4]: FAILED! => {"changed": true, "stdout_lines": ["out"], "stderr_lines": ["err"]}'
)
self.appserver.logger.error("Some error happened, but that's not Ansible related")
self.appserver.logger.error("Other error message happened")
task_name, log_entry, other_logs = get_ansible_failure_log_entry(self.appserver.log_entries_queryset)
self.assertEqual(task_name, "")
self.assertDictEqual(log_entry, dict())
self.assertListEqual(other_logs, [
{
'ansible_loop_var': 'item',
'changed': False,
'item': {'name': '397bf39ead3d3751', 'password': '***', 'state': 'present'},
'msg': (
'Failed to import the required Python library (passlib) on '
"edxapp-periodic-buil-appserver-1039's Python /usr/bin/python3. "
'Please read module documentation and install in the appropriate '
'location'
)
},
{
'changed': True,
'stderr_lines': ['err'],
'stdout_lines': ['out']
}
])
| agpl-3.0 |
BatedUrGonnaDie/splits-io | config/initializers/cors.rb | 636 | Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '/api/*',
methods: :any,
headers: 'Origin, X-Requested-With, Content-Type, Accept, Authorization',
expose: 'X-Filename',
if: Proc.new { |env|
req = Rack::Request.new(env)
if /\A\/api\/v3\/runs\/\w+\z/.match?(req.path) && req.delete?
false
elsif /\A\/api\/v3\/runs\/\w+\/disown\z/.match?(req.path) && req.post?
false
elsif /\A\/api\/v4\/runs\/\w+\z/.match?(req.path) && req.put?
false
else
true
end
}
end
end
| agpl-3.0 |
automenta/narchy | lab/src/main/java/jurls/reinforcementlearning/domains/grid/Grid1D.java | 5442 | package jurls.reinforcementlearning.domains.grid;
/*
One-dimensional grid task
In this task, the agent steps forward and backward along
a nine-position line. The fourth position is rewarded and
the ninth position is punished. There is also a slight
punishment for effort expended in trying to move,
i.e. taking actions. This is intended to be a simple-as-possible
task for troubleshooting BECCA. See Chapter 4 of the
Users Guide for details.
Optimal performance is a reward of about 90 per time step.
*/
public class Grid1D implements World {
private final int size;
private final double VISUALIZE_PERIOD;
private final double REWARD_MAGNITUDE;
private final double ENERGY_COST;
private final double JUMP_FRACTION;
private double worldState;
private int simpleState;
private double energy;
private double[] action;
private final int totalTime;
private int time;
private final double noise;
private final double cycleSkew;
public Grid1D(int size, int totalTime, double noise, double cycleSkew) {
this.time = 0;
this.size = size;
this.VISUALIZE_PERIOD = Math.pow(10, 4);
this.REWARD_MAGNITUDE = 100.0;
this.ENERGY_COST = this.REWARD_MAGNITUDE / 100.0;
this.JUMP_FRACTION = 0.0;
this.noise = noise;
this.cycleSkew = cycleSkew;
this.worldState = 0.0;
this.simpleState = 0;
this.totalTime = totalTime;
/*
this.display_state = True;
*/
}
@Override public String getName() { return "Grid1D"; }
@Override public int getNumSensors() { return size; }
@Override public int getNumActions() { return size; }
@Override public boolean isActive() { return time < totalTime; }
@Override
public double step(double[] action, double[] sensor) {
time++;
this.action = action;
double stepSize = ( action[0] +
2 * action[1] +
3 * action[2] +
4 * action[3] -
action[4] -
2 * action[5] -
3 * action[6] -
4 * action[7]);
energy=(action[0] +
2 * action[1] +
3 * action[2] +
4 * action[3] +
action[4] +
2 * action[5] +
3 * action[6] +
4 * action[7]);
worldState = worldState + stepSize;
if (Math.random() < JUMP_FRACTION) {
worldState = size * Math.random();
}
else {
worldState += cycleSkew;
}
worldState -= size * Math.floor( worldState / ((double)size) );
simpleState = (int)Math.floor(worldState);
if (simpleState == 9) simpleState = 0;
/*
# Assign basic_feature_input elements as binary.
# Represent the presence or absence of the current position in the bin.
*/
for (int i = 0; i < sensor.length; i++) {
sensor[i] = (Math.random()*noise);
}
sensor[simpleState] = 1 - (Math.random()*noise);
return getReward(sensor);
}
public double getReward(double[] sensor) {
double reward = 0.;
reward -= sensor[8] * REWARD_MAGNITUDE;
reward += sensor[3] * REWARD_MAGNITUDE;
reward -= energy * ENERGY_COST;
reward = Math.max(reward, -REWARD_MAGNITUDE);
return reward;
}
@Override
public String toString() {
String s = "";
for (int i = 0; i < size; i++) {
char c;
if (i == simpleState)
c = 'O';
else
c = '.';
s += c;
}
s += "\n";
for (int i = 0; i < size; i++) {
char c;
if (action[i] > 0)
c = 'X';
else
c = '.';
s += c;
}
s += "\n";
return s;
}
/*
def visualize(self, agent):
""" Show what's going on in the world """
if (this.display_state):
state_image = ['.'] * (this.num_sensors + this.num_actions + 2)
state_image[this.simple_state] = 'O'
state_image[this.num_sensors:this.num_sensors + 2] = '||'
action_index = np.where(this.action > 0.1)[0]
if action_index.size > 0:
for i in range(action_index.size):
state_image[this.num_sensors + 2 + action_index[i]] = 'x'
print(''.join(state_image))
if (this.timestep % this.VISUALIZE_PERIOD) == 0:
print("world age is %s timesteps " % this.timestep)
*/
/*
def set_agent_parameters(self, agent):
""" Turn a few of the knobs to adjust BECCA for this world """
# Prevent the agent from forming any groups
#agent.reward_min = -100.
#agent.reward_max = 100.
pass
*/
public static void main(String[] args) {
}
}
| agpl-3.0 |
icecity96/PAT | PAT1018.cpp | 1170 | #include <iostream>
#include <vector>
using namespace std;
int a_w = 0;
int b_w = 0;
int a_b = 0;
int a_B = 0;
int a_C = 0;
int a_J = 0;
int b_B = 0;
int b_C = 0;
int b_J = 0;
int judge(char A,char B)
{
if(A==B)
{
a_b++;
return 0;
}
else if(A=='B'&&B=='C')
{
a_w++;
a_B++;
return 1;
}
else if(A=='B'&&B=='J')
{
b_w++;
b_J++;
return -1;
}
else if(A=='C'&&B=='B')
{
b_w++;
b_B++;
return -1;
}
else if(A=='C'&&B=='J')
{
a_w++;
a_C++;
return 1;
}
else if(A=='J'&&B=='C')
{
b_w++;
b_C++;
return -1;
}
else if(A=='J'&&B=='B')
{
a_w++;
a_J++;
return 1;
}
else
{
return -2;
}
}
int main(int argc, char **argv) {
int n;
cin >> n;
while(n!=0)
{
char A,B;
cin >> A >> B;
judge(A,B);
cin.clear();
n--;
}
cout << a_w << " "<<a_b <<" "<<b_w<<endl;
cout << b_w << " "<<a_b <<" "<<a_w<<endl;
if(max(max(a_B,a_C),a_J)==a_B)
{
cout << "B ";
}
else if(max(max(a_B,a_C),a_J)==a_C)
{
cout << "C ";
}
else
{
cout << "J ";
}
if(max(max(b_B,b_C),b_J)==b_B)
{
cout << "B";
}
else if(max(max(b_B,b_C),b_J)==b_C)
{
cout << "C";
}
else
{
cout << "J";
}
cout << endl;
return 0;
}
| agpl-3.0 |
anuj-rajput/snipe-it | resources/lang/id/admin/models/general.php | 1177 | <?php
return array(
'about_models_title' => 'Tentang Model Aset',
'about_models_text' => 'Model Aset adalah cara untuk mengelompokkan aset identik. "MBP 2013", "IPhone 6s", dll.',
'deleted' => 'Model ini telah dihapus. <a href="/hardware/models/:model_id/restore">Click di sini untuk memulihkan</a>.',
'bulk_delete' => 'Bulk Delete Asset Models',
'bulk_delete_help' => 'Use the checkboxes below to confirm the deletion of the selected asset models. Asset models that have assets associated with them cannot be deleted until the assets are associated with a different model.',
'bulk_delete_warn' => 'You are about to delete :model_count asset models.',
'restore' => 'Mengembalikan Model',
'requestable' => 'Pengguna dapat meminta model ini',
'show_mac_address' => 'Tampilkan alamat MAC di aset untuk model ini',
'view_deleted' => 'Lihat yang Dihapus',
'view_models' => 'Lihat Model',
'fieldset' => 'Fieldset',
'no_custom_field' => 'Field yang tidak bisa di rubah',
);
| agpl-3.0 |
sgmap/pix | api/tests/unit/infrastructure/adapters/assessment-adapter_test.js | 4164 | const { expect } = require('../../../test-helper');
const assessmentAdapter = require('../../../../lib/infrastructure/adapters/assessment-adapter');
const CatAssessment = require('../../../../lib/cat/assessment');
const CatCourse = require('../../../../lib/cat/course');
const CatSkill = require('../../../../lib/cat/skill');
const CatChallenge = require('../../../../lib/cat/challenge');
const CatAnswer = require('../../../../lib/cat/answer');
const Answer = require('../../../../lib/domain/models/Answer');
describe('Unit | Adapter | Assessment', () => {
describe('#getAdaptedAssessment', () => {
it('should return an Assessment from the Cat repository', () => {
// given
const skills = [];
const challenges = [];
const answers = [];
// when
const adaptedAssessment = assessmentAdapter.getAdaptedAssessment(answers, challenges, skills);
// then
expect(adaptedAssessment).to.be.an.instanceOf(CatAssessment);
});
it('should add a course with a list of skills', () => {
// given
const web3Skill = { name: 'web3' };
const skills = [web3Skill];
const challenges = [];
const answers = [];
// when
const adaptedAssessment = assessmentAdapter.getAdaptedAssessment(answers, challenges, skills);
// then
expect(adaptedAssessment).to.have.property('course').and.to.be.an.instanceOf(CatCourse);
const { course } = adaptedAssessment;
expect(course).to.have.property('competenceSkills').and.to.be.an.instanceOf(Array);
const expectedSetOfSkills = [new CatSkill('web3')];
expect(course.competenceSkills).to.deep.equal(expectedSetOfSkills);
});
describe('the assessment\'s course ', () => {
it('should have an array of challenges', () => {
// given
const skills = [];
const challenges = [{
id: 256,
status: 'validé',
skills: [],
timer: 26
}];
const answers = [];
// when
const adaptedAssessment = assessmentAdapter.getAdaptedAssessment(answers, challenges, skills);
// then
const { course } = adaptedAssessment;
expect(course).to.have.property('challenges');
expect(course.challenges[0]).to.deep.equal(new CatChallenge(256, 'validé', [], 26));
});
it('should not select challenges without skills', () => {
// given
const skills = [];
const challenges = [{
id: 256,
status: 'validé',
timer: 26
}];
const answers = [];
// when
const adaptedAssessment = assessmentAdapter.getAdaptedAssessment(answers, challenges, skills);
// then
const { course } = adaptedAssessment;
expect(course).to.have.property('challenges');
expect(course.challenges).to.have.lengthOf(0);
});
it('should have challenges with skills', () => {
// given
const skills = [];
const challenges = [{
id: 256,
status: 'validé',
skills: [{ name: 'url6' }],
timer: 26
}];
const answers = [];
// when
const adaptedAssessment = assessmentAdapter.getAdaptedAssessment(answers, challenges, skills);
// then
const challenge = adaptedAssessment.course.challenges[0];
expect(challenge.skills).to.deep.equal([new CatSkill('url6')]);
});
});
describe('the assessment\'s answers', () => {
it('should have an array of challenges', () => {
// given
const skills = [];
const challenges = [{
id: 256,
status: 'validé',
skills: [],
timer: 26
}];
const answersGiven = [new Answer({ id: 42, challengeId: 256, result: '#ABAND#' })];
// when
const adaptedAssessment = assessmentAdapter.getAdaptedAssessment(answersGiven, challenges, skills);
// then
const { answers } = adaptedAssessment;
expect(answers).to.deep.equal([new CatAnswer(new CatChallenge(256, 'validé', [], 26), '#ABAND#')]);
});
});
});
});
| agpl-3.0 |
kobotoolbox/kpi | jsapp/js/components/common/audioPlayer.tsx | 3645 | import React from 'react'
import autoBind from 'react-autobind'
import bem, {makeBem} from 'js/bem'
import KoboRange from 'js/components/common/koboRange'
import 'js/components/common/audioPlayer.scss'
bem.AudioPlayer = makeBem(null, 'audio-player')
bem.AudioPlayer__controls = makeBem(bem.AudioPlayer, 'controls', 'div')
bem.AudioPlayer__progress = makeBem(bem.AudioPlayer, 'progress', 'div')
bem.AudioPlayer__time = makeBem(bem.AudioPlayer, 'time', 'div')
bem.AudioPlayer__timeCurrent = makeBem(bem.AudioPlayer, 'time-current', 'span')
bem.AudioPlayer__timeTotal = makeBem(bem.AudioPlayer, 'time-total', 'span')
bem.AudioPlayer__seek = makeBem(bem.AudioPlayer, 'seek', 'div')
type AudioPlayerProps = {
mediaURL: string
}
type AudioPlayerState = {
isLoading: boolean,
isPlaying: boolean,
currentTime: number,
totalTime: number,
}
/**
* Custom audio player for viewing audio submissions in data table
*
* @param {string} mediaURL
*/
class AudioPlayer extends React.Component<AudioPlayerProps, AudioPlayerState> {
audioInterface: HTMLAudioElement
constructor(props: AudioPlayerProps) {
super(props)
this.state = {
isLoading: false,
isPlaying: false,
currentTime: 0,
totalTime: 0,
}
this.audioInterface = new Audio(this.props.mediaURL)
// Set up listeners for audio component
this.audioInterface.onloadedmetadata = () => {
this.setState({
totalTime: this.audioInterface.duration,
})
}
this.audioInterface.ontimeupdate = () => {
// Pause the player when it reaches the end
if (
this.audioInterface.currentTime === this.state.totalTime &&
this.state.isPlaying
) {
this.onPlayStatusChange()
}
this.setState({
currentTime: this.audioInterface.currentTime,
})
}
autoBind(this)
}
componentWillUnmount() {
this.audioInterface.pause()
}
onPlayStatusChange() {
if (!this.state.isPlaying) {
this.audioInterface.play()
} else {
this.audioInterface.pause()
}
this.setState({
isPlaying: !this.state.isPlaying,
})
}
onSeekChange(newTime: string) {
this.audioInterface.currentTime = parseInt(newTime)
this.setState({
currentTime: parseInt(newTime),
})
}
/* We deal internally with un-converted time for easier computing. Only use
* this when it's time to display
*
* @param {float} time - HTMLElementAudio.duration returns a float in seconds
*/
convertToClock(time: number) {
let minutes = Math.floor(time / 60)
// The duration is given in decimal seconds, so we have to do ceiling here
let seconds = Math.ceil(time - minutes * 60)
let finalSeconds: string;
if (seconds < 10) {
finalSeconds = '0' + seconds
} else {
finalSeconds = String(seconds)
}
return minutes + ':' + finalSeconds
}
getControlIcon(isPlaying: boolean) {
const iconClassNames = ['k-icon']
if (isPlaying) {
iconClassNames.push('k-icon-pause')
} else {
iconClassNames.push('k-icon-caret-right')
}
return iconClassNames.join(' ')
}
render() {
return (
<bem.AudioPlayer>
<bem.AudioPlayer__controls>
<i
className={this.getControlIcon(this.state.isPlaying)}
onClick={this.onPlayStatusChange}
/>
</bem.AudioPlayer__controls>
<KoboRange
max={this.state.totalTime}
value={this.state.currentTime}
isTime={true}
onChange={this.onSeekChange}
/>
</bem.AudioPlayer>
)
}
}
export default AudioPlayer
| agpl-3.0 |
PW-Sat2/PWSat2OBC | unit_tests/base/Include/mock/ImtqTelemetryCollectorMock.hpp | 471 | #ifndef MOCK_IMTQ_TELEMETRY_COLLECTOR_MOCK_HPP
#define MOCK_IMTQ_TELEMETRY_COLLECTOR_MOCK_HPP
#pragma once
#include "gmock/gmock.h"
#include "telemetry/IImtqTelemetryCollector.hpp"
#include "telemetry/state.hpp"
struct ImtqTelemetryCollectorMock : public telemetry::IImtqTelemetryCollector
{
ImtqTelemetryCollectorMock();
~ImtqTelemetryCollectorMock();
MOCK_METHOD1(CaptureTelemetry, bool(telemetry::ManagedTelemetry& target));
};
#endif
| agpl-3.0 |
OrganicityEu-Platform/organicity-urban-data-observatory | gulp/build.js | 3559 | 'use strict';
var gulp = require('gulp');
var replace = require('replace');
var gutil = require('gulp-util')
var $ = require('gulp-load-plugins')({
pattern: ['gulp-*', 'main-bower-files', 'uglify-save-license', 'del']
});
module.exports = function(options) {
gulp.task('partials', function () {
return gulp.src([
options.src + '/app/**/*.html',
options.tmp + '/serve/app/**/*.html'
])
.pipe($.minifyHtml({
empty: true,
spare: true,
quotes: true
}))
.pipe($.angularTemplatecache('templateCacheHtml.js', {
module: 'app',
root: 'app'
}))
.pipe(gulp.dest(options.tmp + '/partials/'));
});
gulp.task('html', ['inject', 'partials'], function () {
var partialsInjectFile = gulp.src(options.tmp + '/partials/templateCacheHtml.js', { read: false });
var partialsInjectOptions = {
starttag: '<!-- inject:partials -->',
ignorePath: options.tmp + '/partials',
addRootSlash: false
};
var htmlFilter = $.filter('*.html');
var jsFilter = $.filter('**/*.js', '!'+options.src+'/**/scktool-*.js');
var cssFilter = $.filter('**/*.css');
var assets;
return gulp.src(options.tmp + '/serve/*.html')
.pipe($.inject(partialsInjectFile, partialsInjectOptions))
.pipe(assets = $.useref.assets())
.pipe($.rev())
.pipe(jsFilter)
.pipe($.ngAnnotate())
.pipe($.uglify({ preserveComments: $.uglifySaveLicense })).on('error', options.errorHandler('Uglify'))
.pipe(jsFilter.restore())
.pipe(cssFilter)
.pipe($.csso())
.pipe(cssFilter.restore())
.pipe(assets.restore())
.pipe($.useref())
.pipe($.revReplace())
.pipe(htmlFilter)
.pipe($.minifyHtml({
empty: true,
spare: true,
quotes: true,
conditionals: true
}))
.pipe(htmlFilter.restore())
.pipe(gulp.dest(options.dist + '/'))
.pipe($.size({ title: options.dist + '/', showFiles: true }));
});
// Only applies for fonts from bower dependencies
// Custom fonts are handled by the "other" task
gulp.task('fonts', function () {
return gulp.src($.mainBowerFiles())
.pipe($.filter('**/*.{eot,svg,ttf,woff,woff2}'))
.pipe($.flatten())
.pipe(gulp.dest(options.dist + '/fonts/'));
});
gulp.task('other', function () {
return gulp.src([
options.src + '/**/*',
'!' + options.src + '/**/*.{html,css,js,scss}'
])
.pipe(gulp.dest(options.dist + '/'));
});
gulp.task('version', function(){
var p = require('./../package.json');
var gr = require('git-rev');
gutil.log(' -- The version is now: ' + p.version);
gr.short(function(str){
if (str.length > 1){
gutil.log(str);
replace({
regex: "Hash.*",
replacement: "Hash: " + str,
paths: ['./src/app/components/footer/footer.html'],
recursive: true,
silent: true,
});
}
})
replace({
regex: "Version.*",
replacement: "Version: " + p.version,
paths: ['./src/app/components/footer/footer.html'],
recursive: true,
silent: true,
});
});
gulp.task('clean', function (done) {
$.del([options.dist + '/', options.tmp + '/'], done);
});
gulp.task('external-assets', function() {
return gulp.src(['bower_components/leaflet/dist/images/**'])
.pipe(gulp.dest(options.dist + '/styles/images'));
});
gulp.task('build', ['html', 'fonts', 'other', 'external-assets', 'version']);
};
| agpl-3.0 |
mytechia/UNIDA | unida_library/src/main/java/com/hi3project/unida/library/location/StringLiteralLocation.java | 861 | package com.hi3project.unida.library.location;
/**
* <p><b>Description:</b></p>
*
*
*
*
* <p><b>Creation date:</b> 28-dic-2009</p>
*
* <p><b>Changelog:</b></p>
* <ul>
* <li>1 - 28-dic-2009 Initial release</li>
* </ul>
*
*
* @author Gervasio Varela Fernandez
* @version 1
*/
public class StringLiteralLocation extends Location
{
private String location;
public StringLiteralLocation(Long codId, String location)
{
super(codId);
this.location = location;
}
public StringLiteralLocation(String location)
{
super(null);
this.location = location;
}
public StringLiteralLocation()
{
}
public String getLocation() {
return this.location;
}
@Override
public String toString()
{
return this.location;
}
}
| agpl-3.0 |
juxtalearn/clipit | mod/z04_clipit_activity/views/default/activity/admin/groups/users_list.php | 790 | <?php
/**
* Clipit Web Space
* PHP version: >= 5.2
* Creation date: 25/08/14
* Last update: 25/08/14
* @author Miguel Ángel Gutiérrez <[email protected]>, URJC Clipit Project
* @version $Version$
* @link http://clipit.es
* @license GNU Affero General Public License v3
* @package Clipit
*/
$users = get_input('users');
$users = ClipitUser::get_by_id($users);
?>
<ul>
<?php foreach($users as $user):?>
<li data-user="<?php echo $user->id;?>" style="cursor: pointer">
<?php echo elgg_view('output/img', array(
'src' => get_avatar($user, 'small'),
'class' => 'image-block avatar-tiny',
'alt' => 'avatar-tiny',
));
?>
<?php echo $user->name;?>
</li>
<?php endforeach; ?>
</ul>
| agpl-3.0 |
shaze/genesis | src/admix/AdmixSubject.java | 2879 | /*************************************************************************
* Genesis -- program for creating structure and PCA plots of genotype data
* Copyright (C) 2014. Robert W Buchmann, University of the Witwatersrand, Johannesburg
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package admix;
import java.io.Serializable;
/**This object contains the data about one element on the admixture plot
* <p>
* This includes:
* <li>an array of floats representing the ratios of the ancestors
* <li>the name and phenotype data of the individual
* <li>a pointer to this individual's external population group
* </ul>
*
* @see AdmixGraph
*/
public class AdmixSubject implements Serializable{
private static final long serialVersionUID = 6612552057155898150L;
private float[] ratio;
private AdmixPopulationGroup[] groups;
private String name;
private String[] phenotypeData;
private boolean receivedPheno=false;
private boolean selected,visible=true;
public float[] getRatio(){ //returns the whole ratio array
return ratio;
}
public void setPhenotypeData(String[] phenoData){
this.phenotypeData = phenoData;
setReceivedPheno(true);
}
public String[] getPhenotypeData(){
return phenotypeData;
}
public int getNoAncestors(){
return ratio.length;
}
public float getPercent(int x){ // returns the xth element of the ratio array
return ratio[x];
}
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
AdmixSubject(float[] ratio){
this.ratio = ratio;
}
public AdmixPopulationGroup[] getGroups() {
return groups;
}
public void setGroup(AdmixPopulationGroup[] groups) {
this.groups = groups;
}
public boolean isReceivedPheno() {
return receivedPheno;
}
public void setReceivedPheno(boolean receivedPheno) {
this.receivedPheno = receivedPheno;
}
public boolean getSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public boolean getVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
}
| agpl-3.0 |
tsakas/juju | worker/dependency/util_test.go | 4029 | // Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package dependency_test
import (
"time"
"github.com/juju/testing"
jc "github.com/juju/testing/checkers"
gc "gopkg.in/check.v1"
"launchpad.net/tomb"
coretesting "github.com/juju/juju/testing"
"github.com/juju/juju/worker"
"github.com/juju/juju/worker/dependency"
)
type engineFixture struct {
testing.IsolationSuite
engine dependency.Engine
}
func (s *engineFixture) SetUpTest(c *gc.C) {
s.IsolationSuite.SetUpTest(c)
s.startEngine(c, nothingFatal)
}
func (s *engineFixture) TearDownTest(c *gc.C) {
s.stopEngine(c)
s.IsolationSuite.TearDownTest(c)
}
func (s *engineFixture) startEngine(c *gc.C, isFatal dependency.IsFatalFunc) {
if s.engine != nil {
c.Fatalf("original engine not stopped")
}
config := dependency.EngineConfig{
IsFatal: isFatal,
WorstError: func(err0, err1 error) error { return err0 },
ErrorDelay: coretesting.ShortWait / 2,
BounceDelay: coretesting.ShortWait / 10,
}
e, err := dependency.NewEngine(config)
c.Assert(err, jc.ErrorIsNil)
s.engine = e
}
func (s *engineFixture) stopEngine(c *gc.C) {
if s.engine != nil {
err := worker.Stop(s.engine)
s.engine = nil
c.Check(err, jc.ErrorIsNil)
}
}
type manifoldHarness struct {
inputs []string
errors chan error
starts chan struct{}
ignoreExternalKill bool
}
func newManifoldHarness(inputs ...string) *manifoldHarness {
return &manifoldHarness{
inputs: inputs,
errors: make(chan error, 1000),
starts: make(chan struct{}, 1000),
ignoreExternalKill: false,
}
}
// newErrorIgnoringManifoldHarness starts a minimal worker that ignores
// fatal errors - and will never die.
// This is potentially nasty, but it's useful in tests where we want
// to generate fatal errors but not race on which one the engine see first.
func newErrorIgnoringManifoldHarness(inputs ...string) *manifoldHarness {
return &manifoldHarness{
inputs: inputs,
errors: make(chan error, 1000),
starts: make(chan struct{}, 1000),
ignoreExternalKill: true,
}
}
func (ews *manifoldHarness) Manifold() dependency.Manifold {
return dependency.Manifold{
Inputs: ews.inputs,
Start: ews.start,
}
}
func (ews *manifoldHarness) start(getResource dependency.GetResourceFunc) (worker.Worker, error) {
for _, resourceName := range ews.inputs {
if err := getResource(resourceName, nil); err != nil {
return nil, err
}
}
w := &minimalWorker{tomb.Tomb{}, ews.ignoreExternalKill}
go func() {
defer w.tomb.Done()
ews.starts <- struct{}{}
select {
case <-w.tombDying():
case err := <-ews.errors:
w.tomb.Kill(err)
}
}()
return w, nil
}
func (ews *manifoldHarness) AssertOneStart(c *gc.C) {
ews.AssertStart(c)
ews.AssertNoStart(c)
}
func (ews *manifoldHarness) AssertStart(c *gc.C) {
select {
case <-ews.starts:
case <-time.After(coretesting.LongWait):
c.Fatalf("never started")
}
}
func (ews *manifoldHarness) AssertNoStart(c *gc.C) {
select {
case <-time.After(coretesting.ShortWait):
case <-ews.starts:
c.Fatalf("started unexpectedly")
}
}
func (ews *manifoldHarness) InjectError(c *gc.C, err error) {
select {
case ews.errors <- err:
case <-time.After(coretesting.LongWait):
c.Fatalf("never sent")
}
}
type minimalWorker struct {
tomb tomb.Tomb
ignoreExternalKill bool
}
func (w *minimalWorker) tombDying() <-chan struct{} {
if w.ignoreExternalKill {
return nil
}
return w.tomb.Dying()
}
func (w *minimalWorker) Kill() {
w.tomb.Kill(nil)
}
func (w *minimalWorker) Wait() error {
return w.tomb.Wait()
}
func (w *minimalWorker) Report() map[string]interface{} {
return map[string]interface{}{
"key1": "hello there",
}
}
func startMinimalWorker(_ dependency.GetResourceFunc) (worker.Worker, error) {
w := &minimalWorker{}
go func() {
<-w.tomb.Dying()
w.tomb.Done()
}()
return w, nil
}
func nothingFatal(_ error) bool {
return false
}
| agpl-3.0 |
ymilord/OctoPrint-MrBeam | src/octoprint/plugins/cura/profile.py | 33248 | # coding=utf-8
from __future__ import absolute_import
__author__ = "Gina Häußge <[email protected]>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
from . import s
import re
class SupportLocationTypes(object):
NONE = "none"
TOUCHING_BUILDPLATE = "buildplate"
EVERYWHERE = "everywhere"
class SupportDualTypes(object):
BOTH = "both"
FIRST = "first"
SECOND = "second"
class SupportTypes(object):
GRID = "grid"
LINES = "lines"
class PlatformAdhesionTypes(object):
NONE = "none"
BRIM = "brim"
RAFT = "raft"
class MachineShapeTypes(object):
SQUARE = "square"
CIRCULAR = "circular"
class GcodeFlavors(object):
REPRAP = "reprap"
REPRAP_VOLUME = "reprap_volume"
ULTIGCODE = "ultigcode"
MAKERBOT = "makerbot"
BFB = "bfb"
MACH3 = "mach3"
defaults = dict(
layer_height=0.1,
wall_thickness=0.8,
solid_layer_thickness=0.6,
nozzle_size=0.4,
print_temperature=[220, 0, 0, 0],
print_bed_temperature=70,
platform_adhesion=PlatformAdhesionTypes.NONE,
filament_diameter=[2.85, 0, 0, 0],
filament_flow=100.0,
bottom_thickness=0.3,
first_layer_width_factor=100.0,
object_sink=0.0,
fill_density=20,
solid_top=True,
solid_bottom=True,
fill_overlap=15,
# speeds
print_speed=50.0,
travel_speed=150.0,
bottom_layer_speed=20.0,
infill_speed=0.0,
outer_shell_speed=0.0,
inner_shell_speed=0.0,
# dual extrusion
overlap_dual=0.15,
wipe_tower=False,
wipe_tower_volume=15,
ooze_shield=False,
# retraction
retraction_enable=True,
retraction_speed=40.0,
retraction_amount=4.5,
retraction_dual_amount=16.5,
retraction_min_travel=1.5,
retraction_combing=True,
retraction_minimal_extrusion=0.02,
retraction_hop=0.0,
# cooling
cool_min_layer_time=5,
fan_enabled=True,
fan_full_height=0.5,
fan_speed=100,
fan_speed_max=100,
cool_min_feedrate=10,
cool_head_lift=False,
# support
support=SupportLocationTypes.NONE,
support_type=SupportTypes.GRID,
support_angle=60.0,
support_fill_rate=15,
support_xy_distance=0.7,
support_z_distance=0.15,
support_dual_extrusion=SupportDualTypes.BOTH,
# platform adhesion
skirt_line_count=1,
skirt_gap=3.0,
skirt_minimal_length=150.0,
brim_line_count=20,
raft_margin=5.0,
raft_line_spacing=3.0,
raft_base_thickness=0.3,
raft_base_linewidth=1.0,
raft_interface_thickness=0.27,
raft_interface_linewidth=0.4,
raft_airgap=0.22,
raft_surface_layers=2,
# repairing
fix_horrible_union_all_type_a=True,
fix_horrible_union_all_type_b=False,
fix_horrible_use_open_bits=False,
fix_horrible_extensive_stitching=False,
# extras
spiralize=False,
follow_surface=False,
machine_width=205,
machine_depth=205,
machine_center_is_zero=False,
has_heated_bed=False,
gcode_flavor=GcodeFlavors.REPRAP,
extruder_amount=1,
steps_per_e=0,
start_gcode=[
# 1 extruder
""";Sliced at: {day} {date} {time}
;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line
;M109 S{print_temperature} ;Uncomment to add your own temperature line
G21 ;metric values
G90 ;absolute positioning
M82 ;set extruder to absolute mode
M107 ;start with the fan off
G28 X0 Y0 ;move X/Y to min endstops
G28 Z0 ;move Z to min endstops
G1 Z15.0 F{travel_speed} ;move the platform down 15mm
G92 E0 ;zero the extruded length
G1 F200 E3 ;extrude 3mm of feed stock
G92 E0 ;zero the extruded length again
G1 F{travel_speed}
;Put printing message on LCD screen
M117 Printing...
""",
# 2 extruders
""";Sliced at: {day} {date} {time}
;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line
;M104 S{print_temperature} ;Uncomment to add your own temperature line
;M109 T1 S{print_temperature2} ;Uncomment to add your own temperature line
;M109 T0 S{print_temperature} ;Uncomment to add your own temperature line
G21 ;metric values
G90 ;absolute positioning
M107 ;start with the fan off
G28 X0 Y0 ;move X/Y to min endstops
G28 Z0 ;move Z to min endstops
G1 Z15.0 F{travel_speed} ;move the platform down 15mm
T1 ;Switch to the 2nd extruder
G92 E0 ;zero the extruded length
G1 F200 E10 ;extrude 10mm of feed stock
G92 E0 ;zero the extruded length again
G1 F200 E-{retraction_dual_amount}
T0 ;Switch to the first extruder
G92 E0 ;zero the extruded length
G1 F200 E10 ;extrude 10mm of feed stock
G92 E0 ;zero the extruded length again
G1 F{travel_speed}
;Put printing message on LCD screen
M117 Printing...
""",
# 3 extruders
""";Sliced at: {day} {date} {time}
;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line
;M104 S{print_temperature} ;Uncomment to add your own temperature line
;M109 T1 S{print_temperature2} ;Uncomment to add your own temperature line
;M109 T0 S{print_temperature} ;Uncomment to add your own temperature line
G21 ;metric values
G90 ;absolute positioning
M107 ;start with the fan off
G28 X0 Y0 ;move X/Y to min endstops
G28 Z0 ;move Z to min endstops
G1 Z15.0 F{travel_speed} ;move the platform down 15mm
T2 ;Switch to the 2nd extruder
G92 E0 ;zero the extruded length
G1 F200 E10 ;extrude 10mm of feed stock
G92 E0 ;zero the extruded length again
G1 F200 E-{retraction_dual_amount}
T1 ;Switch to the 2nd extruder
G92 E0 ;zero the extruded length
G1 F200 E10 ;extrude 10mm of feed stock
G92 E0 ;zero the extruded length again
G1 F200 E-{retraction_dual_amount}
T0 ;Switch to the first extruder
G92 E0 ;zero the extruded length
G1 F200 E10 ;extrude 10mm of feed stock
G92 E0 ;zero the extruded length again
G1 F{travel_speed}
;Put printing message on LCD screen
M117 Printing...
""",
# 4 extruders
""";Sliced at: {day} {date} {time}
;Basic settings: Layer height: {layer_height} Walls: {wall_thickness} Fill: {fill_density}
;M190 S{print_bed_temperature} ;Uncomment to add your own bed temperature line
;M104 S{print_temperature} ;Uncomment to add your own temperature line
;M109 T2 S{print_temperature2} ;Uncomment to add your own temperature line
;M109 T1 S{print_temperature2} ;Uncomment to add your own temperature line
;M109 T0 S{print_temperature} ;Uncomment to add your own temperature line
G21 ;metric values
G90 ;absolute positioning
M107 ;start with the fan off
G28 X0 Y0 ;move X/Y to min endstops
G28 Z0 ;move Z to min endstops
G1 Z15.0 F{travel_speed} ;move the platform down 15mm
T3 ;Switch to the 4th extruder
G92 E0 ;zero the extruded length
G1 F200 E10 ;extrude 10mm of feed stock
G92 E0 ;zero the extruded length again
G1 F200 E-{retraction_dual_amount}
T2 ;Switch to the 3th extruder
G92 E0 ;zero the extruded length
G1 F200 E10 ;extrude 10mm of feed stock
G92 E0 ;zero the extruded length again
G1 F200 E-{retraction_dual_amount}
T1 ;Switch to the 2nd extruder
G92 E0 ;zero the extruded length
G1 F200 E10 ;extrude 10mm of feed stock
G92 E0 ;zero the extruded length again
G1 F200 E-{retraction_dual_amount}
T0 ;Switch to the first extruder
G92 E0 ;zero the extruded length
G1 F200 E10 ;extrude 10mm of feed stock
G92 E0 ;zero the extruded length again
G1 F{travel_speed}
;Put printing message on LCD screen
M117 Printing...
"""
],
end_gcode=[
# 1 extruder
""";End GCode
M104 S0 ;extruder heater off
M140 S0 ;heated bed heater off (if you have it)
G91 ;relative positioning
G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way
M84 ;steppers off
G90 ;absolute positioning
;{profile_string}
""",
# 2 extruders
""";End GCode
M104 T0 S0 ;extruder heater off
M104 T1 S0 ;extruder heater off
M140 S0 ;heated bed heater off (if you have it)
G91 ;relative positioning
G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way
M84 ;steppers off
G90 ;absolute positioning
;{profile_string}
""",
# 3 extruders
""";End GCode
M104 T0 S0 ;extruder heater off
M104 T1 S0 ;extruder heater off
M104 T2 S0 ;extruder heater off
M140 S0 ;heated bed heater off (if you have it)
G91 ;relative positioning
G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way
M84 ;steppers off
G90 ;absolute positioning
;{profile_string}
""",
# 4 extruders
""";End GCode
M104 T0 S0 ;extruder heater off
M104 T1 S0 ;extruder heater off
M104 T2 S0 ;extruder heater off
M104 T3 S0 ;extruder heater off
M140 S0 ;heated bed heater off (if you have it)
G91 ;relative positioning
G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way
M84 ;steppers off
G90 ;absolute positioning
;{profile_string}
"""
],
preSwitchExtruder_gcode=""";Switch between the current extruder and the next extruder, when printing with multiple extruders.
;This code is added before the T(n)
""",
postSwitchExtruder_gcode=""";Switch between the current extruder and the next extruder, when printing with multiple extruders.
;This code is added after the T(n)
"""
)
class Profile(object):
regex_extruder_offset = re.compile("extruder_offset_([xy])(\d)")
regex_filament_diameter = re.compile("filament_diameter(\d?)")
regex_print_temperature = re.compile("print_temperature(\d?)")
regex_strip_comments = re.compile(";.*$", flags=re.MULTILINE)
@classmethod
def from_cura_ini(cls, path):
import os
if not os.path.exists(path) or not os.path.isfile(path):
return None
import ConfigParser
config = ConfigParser.ConfigParser()
try:
config.read(path)
except:
return None
arrayified_options = ["print_temperature", "filament_diameter", "start.gcode", "end.gcode"]
translated_options = dict(
inset0_speed="outer_shell_speed",
insetx_speed="inner_shell_speed",
layer0_width_factor="first_layer_width_factor",
simple_mode="follow_surface",
)
translated_options["start.gcode"] = "start_gcode"
translated_options["end.gcode"] = "end_gcode"
value_conversions = dict(
platform_adhesion={
"None": PlatformAdhesionTypes.NONE,
"Brim": PlatformAdhesionTypes.BRIM,
"Raft": PlatformAdhesionTypes.RAFT
},
support={
"None": SupportLocationTypes.NONE,
"Touching buildplate": SupportLocationTypes.TOUCHING_BUILDPLATE,
"Everywhere": SupportLocationTypes.EVERYWHERE
},
support_type={
"Lines": SupportTypes.LINES,
"Grid": SupportTypes.GRID
},
support_dual_extrusion={
"Both": SupportDualTypes.BOTH,
"First extruder": SupportDualTypes.FIRST,
"Second extruder": SupportDualTypes.SECOND
}
)
result = dict()
for section in config.sections():
if not section in ("profile", "alterations"):
continue
for option in config.options(section):
ignored = False
key = option
# try to fetch the value in the correct type
try:
value = config.getboolean(section, option)
except:
# no boolean, try int
try:
value = config.getint(section, option)
except:
# no int, try float
try:
value = config.getfloat(section, option)
except:
# no float, use str
value = config.get(section, option)
index = None
for opt in arrayified_options:
if key.startswith(opt):
if key == opt:
index = 0
else:
try:
# try to convert the target index, e.g. print_temperature2 => print_temperature[1]
index = int(key[len(opt):]) - 1
except ValueError:
# ignore entries for which that fails
ignored = True
key = opt
break
if ignored:
continue
if key in translated_options:
# if the key has to be translated to a new value, do that now
key = translated_options[key]
if key in value_conversions and value in value_conversions[key]:
value = value_conversions[key][value]
if index is not None:
# if we have an array to fill, make sure the target array exists and has the right size
if not key in result:
result[key] = []
if len(result[key]) <= index:
for n in xrange(index - len(result[key]) + 1):
result[key].append(None)
result[key][index] = value
else:
# just set the value if there's no array to fill
result[key] = value
# merge it with our default settings, the imported profile settings taking precedence
return cls.merge_profile(result)
@classmethod
def merge_profile(cls, profile, overrides=None):
result = dict()
for key in defaults.keys():
r = cls.merge_profile_key(key, profile, overrides=overrides)
if r is not None:
result[key] = r
return result
@classmethod
def merge_profile_key(cls, key, profile, overrides=None):
profile_value = None
override_value = None
if not key in defaults:
return None
import copy
result = copy.deepcopy(defaults[key])
if key in profile:
profile_value = profile[key]
if overrides and key in overrides:
override_value = overrides[key]
if profile_value is None and override_value is None:
# neither override nor profile, no need to handle this key further
return None
if key in ("filament_diameter", "print_temperature", "start_gcode", "end_gcode"):
# the array fields need some special treatment. Basically something like this:
#
# override_value: [None, "b"]
# profile_value : ["a" , None, "c"]
# default_value : ["d" , "e" , "f", "g"]
#
# should merge to something like this:
#
# ["a" , "b" , "c", "g"]
#
# So override > profile > default, if neither override nor profile value are available
# the default value should just be left as is
for x in xrange(len(result)):
if override_value is not None and x < len(override_value) and override_value[x] is not None:
# we have an override value for this location, so we use it
result[x] = override_value[x]
elif profile_value is not None and x < len(profile_value) and profile_value[x] is not None:
# we have a profile value for this location, so we use it
result[x] = profile_value[x]
else:
# just change the result value to the override_value if available, otherwise to the profile_value if
# that is given, else just leave as is
if override_value is not None:
result = override_value
elif profile_value is not None:
result = profile_value
return result
def __init__(self, profile, overrides=None):
self._profile = self.__class__.merge_profile(profile, overrides=overrides)
def profile(self):
import copy
return copy.deepcopy(self._profile)
def get(self, key):
if key in ("machine_width", "machine_depth", "machine_center_is_zero"):
bedDimensions = s.globalGet(["printerParameters", "bedDimensions"])
circular = bedDimensions["circular"] if "circular" in bedDimensions else False
radius = bedDimensions["radius"] if "radius" in bedDimensions and bedDimensions["radius"] is not None else 0
if key == "machine_width":
return radius * 2 if circular else bedDimensions["x"]
elif key == "machine_depth":
return radius * 2 if circular else bedDimensions["y"]
elif key == "machine_center_is_zero":
return circular
else:
return None
elif key == "extruder_amount":
return s.globalGetInt(["printerParameters", "numExtruders"])
elif key.startswith("extruder_offset_"):
extruder_offsets = s.globalGet(["printerParameters", "extruderOffsets"])
match = Profile.regex_extruder_offset.match(key)
if not match:
return 0.0
axis, number = match.groups()
axis = axis.lower()
number = int(number)
if not axis in ("x", "y"):
return 0.0
if number >= len(extruder_offsets):
return 0.0
if not axis in extruder_offsets[number]:
return 0.0
return extruder_offsets[number][axis]
elif key.startswith("filament_diameter"):
match = Profile.regex_filament_diameter.match(key)
if not match:
return 0.0
diameters = self._get("filament_diameter")
if not match.group(1):
return diameters[0]
index = int(match.group(1))
if index >= len(diameters):
return 0.0
return diameters[index]
elif key.startswith("print_temperature"):
match = Profile.regex_print_temperature.match(key)
if not match:
return 0.0
temperatures = self._get("print_temperature")
if not match.group(1):
return temperatures[0]
index = int(match.group(1))
if index >= len(temperatures):
return 0.0
return temperatures[index]
else:
return self._get(key)
def _get(self, key):
if key in self._profile:
return self._profile[key]
elif key in defaults:
return defaults[key]
else:
return None
def get_int(self, key, default=None):
value = self.get(key)
if value is None:
return default
try:
return int(value)
except ValueError:
return default
def get_float(self, key, default=None):
value = self.get(key)
if value is None:
return default
if isinstance(value, (str, unicode, basestring)):
value = value.replace(",", ".").strip()
try:
return float(value)
except ValueError:
return default
def get_boolean(self, key, default=None):
value = self.get(key)
if value is None:
return default
if isinstance(value, bool):
return value
elif isinstance(value, (str, unicode, basestring)):
return value.lower() == "true" or value.lower() == "yes" or value.lower() == "on" or value == "1"
elif isinstance(value, (int, float)):
return value > 0
else:
return value == True
def get_microns(self, key, default=None):
value = self.get_float(key, default=None)
if value is None:
return default
return int(value * 1000)
def get_gcode_template(self, key):
extruder_count = s.globalGetInt(["printerParameters", "numExtruders"])
if key in self._profile:
gcode = self._profile[key]
else:
gcode = defaults[key]
if key in ("start_gcode", "end_gcode"):
return gcode[extruder_count-1]
else:
return gcode
def get_machine_extruder_offset(self, extruder, axis):
extruder_offsets = s.globalGet(["printerParameters", "extruderOffsets"])
if extruder >= len(extruder_offsets):
return 0.0
if axis.lower() not in ("x", "y"):
return 0.0
return extruder_offsets[extruder][axis.lower()]
def get_profile_string(self):
import base64
import zlib
import copy
profile = copy.deepcopy(defaults)
profile.update(self._profile)
for key in ("print_temperature", "print_temperature2", "print_temperature3", "print_temperature4",
"filament_diameter", "filament_diameter2", "filament_diameter3", "filament_diameter4"):
profile[key] = self.get(key)
result = []
for k, v in profile.items():
if isinstance(v, (str, unicode)):
result.append("{k}={v}".format(k=k, v=v.encode("utf-8")))
else:
result.append("{k}={v}".format(k=k, v=v))
return base64.b64encode(zlib.compress("\b".join(result), 9))
def replaceTagMatch(self, m):
import time
pre = m.group(1)
tag = m.group(2)
if tag == 'time':
return pre + time.strftime('%H:%M:%S')
if tag == 'date':
return pre + time.strftime('%d-%m-%Y')
if tag == 'day':
return pre + ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][int(time.strftime('%w'))]
if tag == 'profile_string':
return pre + 'CURA_OCTO_PROFILE_STRING:%s' % (self.get_profile_string())
if pre == 'F' and tag == 'max_z_speed':
f = self.get_float("travel_speed") * 60
elif pre == 'F' and tag in ['print_speed', 'retraction_speed', 'travel_speed', 'bottom_layer_speed', 'cool_min_feedrate']:
f = self.get_float(tag) * 60
elif self.get(tag):
f = self.get(tag)
else:
return '%s?%s?' % (pre, tag)
if (f % 1) == 0:
return pre + str(int(f))
return pre + str(f)
def get_gcode(self, key):
extruder_count = s.globalGetInt(["printerParameters", "numExtruders"])
prefix = ""
postfix = ""
if self.get("gcode_flavor") == GcodeFlavors.ULTIGCODE:
if key == "end_gcode":
return "M25 ;Stop reading from this point on.\n;CURA_PROFILE_STRING:%s\n" % (self.get_profile_string())
return ""
if key == "start_gcode":
contents = self.get_gcode_template("start_gcode")
e_steps = self.get_float("steps_per_e")
if e_steps > 0:
prefix += "M92 E{e_steps}\n" % (e_steps)
temp = self.get_float("print_temperature")
bedTemp = 0
if self.get_boolean("has_heated_bed"):
bedTemp = self.get_float("print_bed_temperature")
include_bed_temps = bedTemp > 0 and not "{print_bed_temperature}" in Profile.regex_strip_comments.sub("", contents)
if include_bed_temps:
prefix += "M140 S{print_bed_temperature}\n"
if temp > 0 and not "{print_temperature}" in Profile.regex_strip_comments.sub("", contents):
if extruder_count > 0:
def temp_line(temp, extruder, template):
t = temp
if extruder > 0:
print_temp = self.get_float("print_temperature%d" % (extruder + 1))
if print_temp > 0:
t = print_temp
return template.format(extruder=extruder, temp=t)
for n in xrange(1, extruder_count):
prefix += temp_line(temp, n, "M104 T{extruder} S{temp}\n")
for n in xrange(0, extruder_count):
prefix += temp_line(temp, n, "M109 T{extruder} S{temp}\n")
prefix += "T0\n"
else:
prefix += "M109 S{temp}\n".format(temp=temp)
if include_bed_temps:
prefix += "M190 S{print_bed_temperature}\n".format(bedTemp=bedTemp)
else:
contents = self.get_gcode_template(key)
return unicode(prefix + re.sub("(.)\{([^\}]*)\}", self.replaceTagMatch, contents).rstrip() + '\n' + postfix).strip().encode('utf-8') + '\n'
def calculate_edge_width_and_line_count(self):
wall_thickness = self.get_float("wall_thickness")
nozzle_size = self.get_float("nozzle_size")
if self.get_boolean("spiralize") or self.get_boolean("follow_surface"):
return wall_thickness, 1
if wall_thickness < 0.01:
return nozzle_size, 0
if wall_thickness < nozzle_size:
return wall_thickness, 1
edge_width = None
line_count = int(wall_thickness / (nozzle_size - 0.0001))
if line_count < 1:
edge_width = nozzle_size
line_count = 1
line_width = wall_thickness / line_count
line_width_alt = wall_thickness / (line_count + 1)
if line_width > nozzle_size * 1.5:
return line_width_alt, line_count + 1
if not edge_width:
edge_width = line_width
return edge_width, line_count
def calculate_solid_layer_count(self):
layer_height = self.get_float("layer_height")
solid_thickness = self.get_float("solid_layer_thickness")
if layer_height == 0.0:
return 1
import math
return int(math.ceil(solid_thickness / (layer_height - 0.0001)))
def calculate_minimal_extruder_count(self):
extruder_count = s.globalGetInt(["printerParameters", "numExtruders"])
if extruder_count < 2:
return 1
if self.get("support") == SupportLocationTypes.NONE:
return 1
if self.get("support_dual_extrusion") == SupportDualTypes.SECOND:
return 2
return 1
def convert_to_engine(self):
edge_width, line_count = self.calculate_edge_width_and_line_count()
solid_layer_count = self.calculate_solid_layer_count()
extruder_count = s.globalGetInt(["printerParameters", "numExtruders"])
minimal_extruder_count = self.calculate_minimal_extruder_count()
settings = {
"layerThickness": self.get_microns("layer_height"),
"initialLayerThickness": self.get_microns("bottom_thickness") if self.get_float("bottom_thickness") > 0.0 else self.get_microns("layer_height"),
"filamentDiameter": self.get_microns("filament_diameter"),
"filamentFlow": self.get_int("filament_flow"),
"extrusionWidth": edge_width * 1000,
"layer0extrusionWidth": int(edge_width * self.get_float("first_layer_width_factor") / 100 * 1000),
"insetCount": line_count,
"downSkinCount": solid_layer_count if self.get_boolean("solid_bottom") else 0,
"upSkinCount": solid_layer_count if self.get_boolean("solid_top") else 0,
"infillOverlap": self.get_int("fill_overlap"),
"initialSpeedupLayers": int(4),
"initialLayerSpeed": self.get_int("bottom_layer_speed"),
"printSpeed": self.get_int("print_speed"),
"infillSpeed": self.get_int("infill_speed") if self.get_int("infill_speed") > 0 else self.get_int("print_speed"),
"inset0Speed": self.get_int("outer_shell_speed") if self.get_int("outer_shell_speed") > 0 else self.get_int("print_speed"),
"insetXSpeed": self.get_int("inner_shell_speed") if self.get_int("inner_shell_speed") > 0 else self.get_int("print_speed"),
"moveSpeed": self.get_int("travel_speed"),
"fanSpeedMin": self.get_int("fan_speed") if self.get_boolean("fan_enabled") else 0,
"fanSpeedMax": self.get_int("fan_speed_max") if self.get_boolean("fan_enabled") else 0,
"supportAngle": int(-1) if self.get("support") == SupportLocationTypes.NONE else self.get_int("support_angle"),
"supportEverywhere": int(1) if self.get("support") == SupportLocationTypes.EVERYWHERE else int(0),
"supportLineDistance": int(100 * edge_width * 1000 / self.get_float("support_fill_rate")) if self.get_float("support_fill_rate") > 0 else -1,
"supportXYDistance": int(1000 * self.get_float("support_xy_distance")),
"supportZDistance": int(1000 * self.get_float("support_z_distance")),
"supportExtruder": 0 if self.get("support_dual_extrusion") == SupportDualTypes.FIRST else (1 if self.get("support_dual_extrusion") == SupportDualTypes.SECOND and minimal_extruder_count > 1 else -1),
"retractionAmount": self.get_microns("retraction_amount") if self.get_boolean("retraction_enable") else 0,
"retractionSpeed": self.get_int("retraction_speed"),
"retractionMinimalDistance": self.get_microns("retraction_min_travel"),
"retractionAmountExtruderSwitch": self.get_microns("retraction_dual_amount"),
"retractionZHop": self.get_microns("retraction_hop"),
"minimalExtrusionBeforeRetraction": self.get_microns("retraction_minimal_extrusion"),
"enableCombing": 1 if self.get_boolean("retraction_combing") else 0,
"multiVolumeOverlap": self.get_microns("overlap_dual"),
"objectSink": max(0, self.get_microns("object_sink")),
"minimalLayerTime": self.get_int("cool_min_layer_time"),
"minimalFeedrate": self.get_int("cool_min_feedrate"),
"coolHeadLift": 1 if self.get_boolean("cool_head_lift") else 0,
# model positioning
"posx": int(self.get_float("machine_width") / 2.0 * 1000) if not self.get_boolean("machine_center_is_zero") else 0.0,
"posy": int(self.get_float("machine_depth") / 2.0 * 1000) if not self.get_boolean("machine_center_is_zero") else 0.0,
# gcodes
"startCode": self.get_gcode("start_gcode"),
"endCode": self.get_gcode("end_gcode"),
"preSwitchExtruderCode": self.get_gcode("preSwitchExtruder_gcode"),
"postSwitchExtruderCode": self.get_gcode("postSwitchExtruder_gcode"),
# fixing
"fixHorrible": 0,
}
for extruder in range(1, extruder_count):
for axis in ("x", "y"):
settings["extruderOffset[{extruder}].{axis}".format(extruder=extruder, axis=axis.upper())] = self.get_machine_extruder_offset(extruder, axis)
fanFullHeight = self.get_microns("fan_full_height")
settings["fanFullOnLayerNr"] = (fanFullHeight - settings["initialLayerThickness"] - 1) / settings["layerThickness"] + 1
if settings["fanFullOnLayerNr"] < 0:
settings["fanFullOnLayerNr"] = 0
if self.get("support_type") == SupportTypes.LINES:
settings["supportType"] = 1
# infill
if self.get_float("fill_density") == 0:
settings["sparseInfillLineDistance"] = -1
elif self.get_float("fill_density") == 100:
settings["sparseInfillLineDistance"] = settings["extrusionWidth"]
settings["downSkinCount"] = 10000
settings["upSkinCount"] = 10000
else:
settings["sparseInfillLineDistance"] = int(100 * edge_width * 1000 / self.get_float("fill_density"))
# brim/raft/skirt
if self.get("platform_adhesion") == PlatformAdhesionTypes.BRIM:
settings["skirtDistance"] = 0
settings["skirtLineCount"] = self.get_int("brim_line_count")
elif self.get("platform_adhesion") == PlatformAdhesionTypes.RAFT:
settings["skirtDistance"] = 0
settings["skirtLineCount"] = 0
settings["raftMargin"] = self.get_microns("raft_margin")
settings["raftLineSpacing"] = self.get_microns("raft_line_spacing")
settings["raftBaseThickness"] = self.get_microns("raft_base_thickness")
settings["raftBaseLinewidth"] = self.get_microns("raft_base_linewidth")
settings["raftInterfaceThickness"] = self.get_microns("raft_interface_thickness")
settings["raftInterfaceLinewidth"] = self.get_microns("raft_interface_linewidth")
settings["raftInterfaceLineSpacing"] = self.get_microns("raft_interface_linewidth") * 2
settings["raftAirGapLayer0"] = self.get_microns("raft_airgap")
settings["raftBaseSpeed"] = self.get_int("bottom_layer_speed")
settings["raftFanSpeed"] = 100
settings["raftSurfaceThickness"] = settings["raftInterfaceThickness"]
settings["raftSurfaceLinewidth"] = int(edge_width * 1000)
settings["raftSurfaceLineSpacing"] = int(edge_width * 1000 * 0.9)
settings["raftSurfaceLayers"] = self.get_int("raft_surface_layers")
settings["raftSurfaceSpeed"] = self.get_int("bottom_layer_speed")
else:
settings["skirtDistance"] = self.get_microns("skirt_gap")
settings["skirtLineCount"] = self.get_int("skirt_line_count")
settings["skirtMinLength"] = self.get_microns("skirt_minimal_length")
# fixing
if self.get_boolean("fix_horrible_union_all_type_a"):
settings["fixHorrible"] |= 0x01
if self.get_boolean("fix_horrible_union_all_type_b"):
settings["fixHorrible"] |= 0x02
if self.get_boolean("fix_horrible_use_open_bits"):
settings["fixHorrible"] |= 0x10
if self.get_boolean("fix_horrible_extensive_stitching"):
settings["fixHorrible"] |= 0x04
if settings["layerThickness"] <= 0:
settings["layerThickness"] = 1000
# gcode flavor
if self.get("gcode_flavor") == GcodeFlavors.ULTIGCODE:
settings["gcodeFlavor"] = 1
elif self.get("gcode_flavor") == GcodeFlavors.MAKERBOT:
settings["gcodeFlavor"] = 2
elif self.get("gcode_flavor") == GcodeFlavors.BFB:
settings["gcodeFlavor"] = 3
elif self.get("gcode_flavor") == GcodeFlavors.MACH3:
settings["gcodeFlavor"] = 4
elif self.get("gcode_flavor") == GcodeFlavors.REPRAP_VOLUME:
settings["gcodeFlavor"] = 5
# extras
if self.get_boolean("spiralize"):
settings["spiralizeMode"] = 1
if self.get_boolean("follow_surface"):
settings["simpleMode"] = 1
# dual extrusion
if self.get_boolean("wipe_tower") and extruder_count > 1:
import math
settings["wipeTowerSize"] = int(math.sqrt(self.get_float("wipe_tower_volume") * 1000 * 1000 * 1000 / settings["layerThickness"]))
if self.get_boolean("ooze_shield"):
settings["enableOozeShield"] = 1
return settings
| agpl-3.0 |
casualuser/Qbix | MyApp/views/MyApp/content/about.php | 152 | <div id='content'>
<h1>About MyApp</h1>
Here you can write something about this app or website.<br>
Or if you want, you can remove this page.
</div>
| agpl-3.0 |
acsone/purchase-workflow | purchase_supplier_rounding_method/tests/__init__.py | 78 | # -*- coding: utf-8 -*-
from . import test_purchase_supplier_rounding_method
| agpl-3.0 |
smichel17/pollr | python/db.py | 4600 | import sys, math
import sqlite3 as lite
# Converts Erlang style strings into python style strings
def convert(sentence):
return ''.join(chr(i) for i in sentence)
# Will build both dbs in their initial state, deleting any prior data
def build_db_scratch():
build_word_db()
build_hashtag_db()
build_queue_db()
def readList(filename):
words = []
f = open(filename, 'r')
header = f.readline()
for line in f:
tokens = line.rstrip().split(",")
words.append((tokens[0], tokens[1], tokens[2]))
return tuple(words)
def build_word_db():
con = lite.connect('./db/sentiment.db')
with con:
cur = con.cursor()
cur.execute("DROP TABLE IF EXISTS Words")
cur.execute("CREATE TABLE Words(Word TEXT, Pos INT, Neg INT)")
words = readList("./wordlists/top20000.txt")
cur.executemany("INSERT INTO Words VALUES(?, ?, ?)", words)
def get_word_sentiment(word):
con = lite.connect('./db/sentiment.db')
with con:
cur = con.cursor()
params = {"Word": word}
cur.execute("SELECT Pos, Neg FROM Words WHERE Word=:Word", params)
con.commit()
return cur.fetchone()
def build_hashtag_db():
con = lite.connect('./db/sentiment.db')
with con:
cur = con.cursor()
cur.execute("DROP TABLE IF EXISTS Hashtags")
cur.execute("CREATE TABLE Hashtags(Hashtag TEXT, Pos INT, Neg INT)")
def get_hashtag_sentiment_erl(hashtag):
hashtag = convert(hashtag)
con = lite.connect('./db/sentiment.db')
with con:
cur = con.cursor()
params = {"Hashtag": hashtag}
cur.execute("SELECT Pos FROM Hashtags WHERE Hashtag=:Hashtag", params)
con.commit()
result = cur.fetchone()
if result is None:
return None
return result[0]
def get_hashtag_sentiment_log(hashtag):
con = lite.connect('./db/sentiment.db')
with con:
cur = con.cursor()
params = {"Tag": hashtag}
cur.execute("SELECT Pos, Neg FROM Hashtags WHERE Hashtag=:Tag", params)
con.commit()
result = cur.fetchone()
if result is None:
return None
try:
return math.log(result[0]), math.log(result[1])
except:
return 0.5, 0.5
def set_hashtag_sentiment_erl(hashtag, score):
hashtag = convert(hashtag)
con = lite.connect('./db/sentiment.db')
with con:
# Test if hashtag is already in the db
cur = con.cursor()
params = {"Tag": hashtag}
cur.execute("SELECT Pos, Neg FROM Hashtags WHERE Hashtag=:Tag", params)
con.commit()
# React accordingly -- that is add a new value or update existing one
result = cur.fetchone()
if result is None:
params = (hashtag, score, 1-score)
cur.execute("INSERT INTO Hashtags VALUES(?, ?, ?)", params)
else:
par = (score, 1-score, hashtag)
cur.execute("UPDATE Hashtags SET Pos=?, Neg=? WHERE Hashtag=?", par)
con.commit()
def build_queue_db():
con = lite.connect('./db/sentiment.db')
with con:
cur = con.cursor()
cur.execute("DROP TABLE IF EXISTS Queue")
cur.execute("CREATE TABLE Queue(Hashtag TEXT, Requests INT)")
def most_requested_hashtag_erl():
con = lite.connect('./db/sentiment.db')
with con:
cur = con.cursor()
cur.execute("SELECT Hashtag,Requests FROM Queue ORDER BY Requests DESC")
result = cur.fetchone()
if result is not None:
return result[0]
return None
def update_requested_hashtag_erl(hashtag):
hashtag = convert(hashtag)
con = lite.connect('./db/sentiment.db')
with con:
# Test if hashtag is already in the db
cur = con.cursor()
par = (hashtag,)
cur.execute("SELECT Hashtag, Requests FROM Queue WHERE Hashtag=?", par)
con.commit()
# React accordingly -- that is add a new value or update existing one
result = cur.fetchone()
if result is None:
cur.execute("INSERT INTO Queue VALUES(?, ?)", (hashtag, 1))
else:
params = (result[1]+1, hashtag)
cur.execute("UPDATE Queue SET Requests=? WHERE Hashtag=?", params)
con.commit()
def delete_requested_hashtag_erl(hashtag):
hashtag = convert(hashtag)
con = lite.connect('./db/sentiment.db')
with con:
cur = con.cursor()
cur.execute("DELETE FROM Queue WHERE Hashtag=?", (hashtag,)) | agpl-3.0 |
pgdurand/BeeDeeM | src/bzh/plealog/dbmirror/util/event/DBMirrorListener.java | 882 | /* Copyright (C) 2007-2017 Patrick G. Durand
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/agpl-3.0.txt
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*/
package bzh.plealog.dbmirror.util.event;
import java.util.EventListener;
public interface DBMirrorListener extends EventListener {
public void mirrorChanged(DBMirrorEvent event);
}
| agpl-3.0 |
jakemadison/FeedEater | __init__.py | 132 | # add project root folder to pythonpath
from os.path import dirname
from sys import path
path.append(dirname(dirname(__file__)))
| agpl-3.0 |
juxtalearn/clipit | mod/z02_clipit_api/views/default/forms/useradd.php | 1612 | <?php
/**
* Elgg add user form.
*
* @package Elgg
* @subpackage Core
*
*/
$name = $username = $email = $password = $password2 = $admin = '';
if (elgg_is_sticky_form('useradd')) {
extract(elgg_get_sticky_values('useradd'));
elgg_clear_sticky_form('useradd');
if (is_array($admin)) {
$admin = $admin[0];
}
}
?>
<div>
<label><?php echo elgg_echo('name');?></label><br />
<?php
echo elgg_view('input/text', array(
'name' => 'name',
'value' => $name,
));
?>
</div>
<div>
<label><?php echo elgg_echo('username'); ?></label><br />
<?php
echo elgg_view('input/text', array(
'name' => 'username',
'value' => $username,
));
?>
</div>
<div>
<label><?php echo elgg_echo('email'); ?></label><br />
<?php
echo elgg_view('input/text', array(
'name' => 'email',
'value' => $email,
));
?>
</div>
<div>
<label><?php echo elgg_echo('password'); ?></label><br />
<?php
echo elgg_view('input/password', array(
'name' => 'password',
'value' => $password,
));
?>
</div>
<div>
<label><?php echo elgg_echo('passwordagain'); ?></label><br />
<?php
echo elgg_view('input/password', array(
'name' => 'password2',
'value' => $password2,
));
?>
</div>
<div>
<?php
echo elgg_view('input/radio', array(
'name' => "role",
'options' => array(
elgg_echo('student_option') => "student",
elgg_echo('teacher_option') => "teacher",
elgg_echo('admin_option') => "admin"),
'value' => "student",
));
?>
</div>
<div class="elgg-foot">
<?php echo elgg_view('input/submit', array('value' => elgg_echo('register'))); ?>
</div> | agpl-3.0 |
reuven/modelingcommons | public/extensions/gis/src/org/myworldgis/netlogo/RasterDataset.java | 26469 | //
// Copyright (c) 2007 Eric Russell. All rights reserved.
//
package org.myworldgis.netlogo;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.util.GeometryTransformer;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.image.BandedSampleModel;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferDouble;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.awt.image.WritableRaster;
import java.awt.image.renderable.ParameterBlock;
import java.text.ParseException;
import javax.media.jai.BorderExtender;
import javax.media.jai.BorderExtenderConstant;
import javax.media.jai.Interpolation;
import javax.media.jai.InterpolationBicubic;
import javax.media.jai.InterpolationBicubic2;
import javax.media.jai.InterpolationBilinear;
import javax.media.jai.InterpolationNearest;
import javax.media.jai.JAI;
import javax.media.jai.KernelJAI;
import javax.media.jai.RenderedOp;
import javax.media.jai.TiledImage;
import org.myworldgis.projection.Projection;
import org.myworldgis.util.RasterUtils;
import org.myworldgis.util.ValueColorModel;
import org.nlogo.api.Argument;
import org.nlogo.api.Context;
import org.nlogo.api.Dump;
import org.nlogo.api.ExtensionException;
import org.nlogo.api.LogoException;
import org.nlogo.api.Syntax;
/**
*
*/
public class RasterDataset extends Dataset {
//--------------------------------------------------------------------------
// Inner classes
//--------------------------------------------------------------------------
/** */
public static final strictfp class New extends GISExtension.Reporter {
public String getAgentClassString() {
return "OTPL";
}
public Syntax getSyntax() {
return Syntax.reporterSyntax(new int[] { Syntax.NumberType(),
Syntax.NumberType(),
Syntax.ListType() },
Syntax.WildcardType());
}
public Object reportInternal (Argument args[], Context context)
throws ExtensionException, LogoException, ParseException {
int width = args[0].getIntValue();
int height = args[1].getIntValue();
Envelope envelope = EnvelopeLogoListFormat.getInstance().parse(args[2].getList());
GridDimensions dimensions = new GridDimensions(new Dimension(width, height), envelope);
DataBuffer data = new DataBufferDouble(width * height);
BandedSampleModel sampleModel = new BandedSampleModel(data.getDataType(),width, height, 1);
WritableRaster raster = Raster.createWritableRaster(sampleModel, data, null);
return new RasterDataset(dimensions, raster);
}
}
/** */
public static final strictfp class GetHeight extends GISExtension.Reporter {
public String getAgentClassString() {
return "OTPL";
}
public Syntax getSyntax() {
return Syntax.reporterSyntax(new int[] { Syntax.WildcardType() },
Syntax.NumberType());
}
public Object reportInternal (Argument args[], Context context)
throws ExtensionException, LogoException {
return Double.valueOf(getDataset(args[0]).getDimensions().getGridHeight());
}
}
/** */
public static final strictfp class GetWidth extends GISExtension.Reporter {
public String getAgentClassString() {
return "OTPL";
}
public Syntax getSyntax() {
return Syntax.reporterSyntax(new int[] { Syntax.WildcardType() },
Syntax.NumberType());
}
public Object reportInternal (Argument args[], Context context)
throws ExtensionException, LogoException {
return Double.valueOf(getDataset(args[0]).getDimensions().getGridWidth());
}
}
/** */
public static final strictfp class GetValue extends GISExtension.Reporter {
public String getAgentClassString() {
return "OTPL";
}
public Syntax getSyntax() {
return Syntax.reporterSyntax(new int[] { Syntax.WildcardType(),
Syntax.NumberType(),
Syntax.NumberType() },
Syntax.NumberType());
}
public Object reportInternal (Argument args[], Context context)
throws ExtensionException, LogoException {
RasterDataset dataset = getDataset(args[0]);
int col = args[1].getIntValue();
int row = args[2].getIntValue();
return Double.valueOf(dataset.getRaster().getSampleDouble(col, row, 0));
}
}
/** */
public static final strictfp class SetValue extends GISExtension.Command {
public String getAgentClassString() {
return "OTPL";
}
public Syntax getSyntax() {
return Syntax.commandSyntax(new int[] { Syntax.WildcardType(),
Syntax.NumberType(),
Syntax.NumberType(),
Syntax.NumberType() });
}
public void performInternal (Argument args[], Context context)
throws ExtensionException, LogoException {
RasterDataset dataset = getDataset(args[0]);
int col = args[1].getIntValue();
int row = args[2].getIntValue();
double value = args[3].getDoubleValue();
dataset.getRaster().setSample(col, row, 0, value);
}
}
/** */
public static final strictfp class GetMinimum extends GISExtension.Reporter {
public String getAgentClassString() {
return "OTPL";
}
public Syntax getSyntax() {
return Syntax.reporterSyntax(new int[] { Syntax.WildcardType() },
Syntax.NumberType());
}
public Object reportInternal (Argument args[], Context context)
throws ExtensionException, LogoException {
DataBuffer buffer = getDataset(args[0]).getRaster().getDataBuffer();
double result = Double.MAX_VALUE;
for (int i = 0; i < buffer.getSize(); i += 1) {
double d = buffer.getElemDouble(i);
if ((d < result) && (!Double.isNaN(d))) {
result = d;
}
}
return Double.valueOf(result);
}
}
/** */
public static final strictfp class GetMaximum extends GISExtension.Reporter {
public String getAgentClassString() {
return "OTPL";
}
public Syntax getSyntax() {
return Syntax.reporterSyntax(new int[] { Syntax.WildcardType() },
Syntax.NumberType());
}
public Object reportInternal (Argument args[], Context context)
throws ExtensionException, LogoException {
DataBuffer buffer = getDataset(args[0]).getRaster().getDataBuffer();
double result = -Double.MAX_VALUE;
for (int i = 0; i < buffer.getSize(); i += 1) {
double d = buffer.getElemDouble(i);
if ((d > result) && (!Double.isNaN(d))) {
result = d;
}
}
return Double.valueOf(result);
}
}
/** */
public static final strictfp class GetInterpolation extends GISExtension.Reporter {
public String getAgentClassString() {
return "OTPL";
}
public Syntax getSyntax() {
return Syntax.reporterSyntax(new int[] { Syntax.WildcardType() },
Syntax.StringType());
}
public Object reportInternal (Argument args[], Context context)
throws ExtensionException, LogoException {
Interpolation interp = getDataset(args[0]).getInterpolation();
if (interp instanceof InterpolationNearest) {
return "NEAREST_NEIGHBOR";
} else if (interp instanceof InterpolationBilinear) {
return "BILINEAR";
} else if (interp instanceof InterpolationBicubic) {
return "BICUBIC";
} else if (interp instanceof InterpolationBicubic2) {
return "BICUBIC_2";
} else {
throw new ExtensionException("Unknown interpolation type: " + Dump.logoObject(interp));
}
}
}
/** */
public static final strictfp class SetInterpolation extends GISExtension.Command {
public String getAgentClassString() {
return "OTPL";
}
public Syntax getSyntax() {
return Syntax.commandSyntax(new int[] { Syntax.WildcardType(),
Syntax.StringType() });
}
public void performInternal (Argument args[], Context context)
throws ExtensionException, LogoException {
Object obj = args[0].get();
if (obj instanceof RasterDataset) {
RasterDataset dataset = (RasterDataset)obj;
String newInterpolation = args[1].getString();
if (newInterpolation.equalsIgnoreCase("NEAREST_NEIGHBOR")) {
dataset.setInterpolation(Interpolation.INTERP_NEAREST);
} else if (newInterpolation.equalsIgnoreCase("BILINEAR")) {
dataset.setInterpolation(Interpolation.INTERP_BILINEAR);
} else if (newInterpolation.equalsIgnoreCase("BICUBIC")) {
dataset.setInterpolation(Interpolation.INTERP_BICUBIC);
} else if (newInterpolation.equalsIgnoreCase("BICUBIC_2")) {
dataset.setInterpolation(Interpolation.INTERP_BICUBIC_2);
} else {
throw new ExtensionException("Unknown interpolation type: " + Dump.logoObject(newInterpolation));
}
} else {
throw new ExtensionException("not a RasterDataset: " + obj);
}
}
}
//--------------------------------------------------------------------------
// Class methods
//--------------------------------------------------------------------------
/** */
static RasterDataset getDataset (Argument arg)
throws ExtensionException, LogoException {
Object obj = arg.get();
if (obj instanceof RasterDataset) {
return (RasterDataset)obj;
} else {
throw new ExtensionException("not a RasterDataset: " + obj);
}
}
/** */
static RenderedImage createRendering (RenderedOp op, ColorModel cm) {
WritableRaster wr = op.copyData();
TiledImage ti = new TiledImage(wr.getMinX(), wr.getMinY(),
wr.getWidth(), wr.getHeight(),
0, 0,
cm.createCompatibleSampleModel(wr.getWidth(), wr.getHeight()),
cm);
ti.setData(wr);
return ti;
}
//--------------------------------------------------------------------------
// Instance variables
//--------------------------------------------------------------------------
/** */
private GridDimensions _dimensions;
/** */
private WritableRaster _raster;
/** */
private Interpolation _interpolation;
/** */
private double[][] _interpArray;
//--------------------------------------------------------------------------
// Constructors
//--------------------------------------------------------------------------
/** */
public RasterDataset (GridDimensions dimensions, WritableRaster raster) {
super("RASTER");
_dimensions = dimensions;
_raster = raster;
_interpolation = Interpolation.getInstance(Interpolation.INTERP_NEAREST);
_interpArray = new double[_interpolation.getHeight()][_interpolation.getWidth()];
GISExtension.getState().datasetLoadNotify();
}
/** */
public RasterDataset (WritableRaster raster,
GridDimensions srcDimensions,
Projection srcProj,
Projection dstProj) {
super("RASTER");
GeometryFactory factory = GISExtension.getState().factory();
GeometryTransformer srcToGeog = srcProj.getInverseTransformer();
GeometryTransformer geogToDst = dstProj.getForwardTransformer();
int minCol = Integer.MAX_VALUE;
int maxCol = -1;
int minRow = Integer.MAX_VALUE;
int maxRow = -1;
Envelope newEnvelope = new Envelope();
for (int col = 0; col <= srcDimensions.getGridWidth(); col += 2) {
for (int row = 0; row <= srcDimensions.getGridHeight(); row += 2) {
Point src = factory.createPoint(new Coordinate(srcDimensions.getColumnLeft(col),
srcDimensions.getRowBottom(row)));
Point dest = (Point)geogToDst.transform(srcToGeog.transform(src));
if (!dest.isEmpty()) {
if (col < minCol) {
minCol = col;
}
if (col > maxCol) {
maxCol = col;
}
if (row < minRow) {
minRow = row;
}
if (row > maxRow) {
maxRow = row;
}
newEnvelope.expandToInclude(dest.getCoordinate());
}
}
}
double scale = StrictMath.min((maxCol - minCol) / newEnvelope.getWidth(),
(maxRow - minRow) / newEnvelope.getHeight());
_dimensions = new GridDimensions(new Dimension((int)(scale * newEnvelope.getWidth()),
(int)(scale * newEnvelope.getHeight())),
newEnvelope);
ColorModel srcCM = new ValueColorModel(raster);
BufferedImage img = new BufferedImage(srcCM, raster, false, null);
RenderedImage dstImage = RasterUtils.reproject(img,
srcDimensions,
srcProj,
_dimensions,
dstProj,
factory,
new double[] { Double.NaN });
_raster = (WritableRaster)dstImage.getData();
_interpolation = Interpolation.getInstance(Interpolation.INTERP_NEAREST);
_interpArray = new double[_interpolation.getHeight()][_interpolation.getWidth()];
GISExtension.getState().datasetLoadNotify();
}
//--------------------------------------------------------------------------
// Instance methods
//--------------------------------------------------------------------------
/** */
public GridDimensions getDimensions () {
return _dimensions;
}
/** */
public WritableRaster getRaster () {
return _raster;
}
/** */
public Interpolation getInterpolation () {
return _interpolation;
}
/** */
public void setInterpolation (int interpolationType) {
_interpolation = Interpolation.getInstance(interpolationType);
_interpArray = new double[_interpolation.getHeight()][_interpolation.getWidth()];
}
/** */
public double getValue (Coordinate gisSpLocation) {
Coordinate gridSpLocation = _dimensions.gisToGrid(gisSpLocation, null);
if (Double.isNaN(gridSpLocation.x) || Double.isNaN(gridSpLocation.y)) {
return Double.NaN;
}
int rx = (int)StrictMath.floor(gridSpLocation.x);
int ry = (int)StrictMath.floor(gridSpLocation.y);
float xfrac = (float)(gridSpLocation.x - rx);
float yfrac = (float)(gridSpLocation.y - ry);
for (int iy = 0; iy < _interpArray.length; iy += 1) {
int sy = ry + iy - _interpolation.getTopPadding();
if ((sy >= 0) && (sy < _dimensions.getGridHeight())) {
// NOTE: reverse y axis. I hate raster space!
sy = _dimensions.getGridHeight() - sy - 1;
for (int ix = 0; ix < _interpArray[iy].length; ix += 1) {
int sx = rx + ix - _interpolation.getLeftPadding();
if ((sx >= 0) && (sx < _dimensions.getGridWidth())) {
_interpArray[iy][ix] = _raster.getSampleDouble(sx, sy, 0);
} else {
_interpArray[iy][ix] = Double.NaN;
}
}
} else {
for (int ix = 0; ix < _interpArray[iy].length; ix += 1) {
_interpArray[iy][ix] = Double.NaN;
}
}
}
return _interpolation.interpolate(_interpArray, xfrac, yfrac);
}
/** */
public double getValue (Envelope gisSpEnvelope) {
Coordinate gisBL = new Coordinate(gisSpEnvelope.getMinX(), gisSpEnvelope.getMinY());
Coordinate gridBL = _dimensions.gisToGrid(gisBL, gisBL);
Coordinate gisTR = new Coordinate(gisSpEnvelope.getMaxX(), gisSpEnvelope.getMaxY());
Coordinate gridTR = _dimensions.gisToGrid(gisTR, gisTR);
int minY, maxY;
if (Double.isNaN(gridBL.y) && Double.isNaN(gridTR.y)) {
return GISExtension.MISSING_VALUE;
} else if (Double.isNaN(gridBL.y)) {
minY = 0;
maxY = (int)StrictMath.ceil(gridTR.y);
} else if (Double.isNaN(gridTR.y)) {
minY = (int)StrictMath.floor(gridBL.y);
maxY = _dimensions.getGridHeight();
} else {
minY = (int)StrictMath.floor(gridBL.y);
maxY = (int)StrictMath.ceil(gridTR.y);
}
int minX, maxX;
if (Double.isNaN(gridBL.x) && Double.isNaN(gridTR.x)) {
return GISExtension.MISSING_VALUE;
} else if (Double.isNaN(gridBL.x)) {
minX = 0;
maxX = (int)StrictMath.ceil(gridTR.x);
} else if (Double.isNaN(gridTR.x)) {
minX = (int)StrictMath.floor(gridBL.x);
maxX = _dimensions.getGridWidth();
} else {
minX = (int)StrictMath.floor(gridBL.x);
maxX = (int)StrictMath.ceil(gridTR.x);
}
double sum = 0.0;
int count = 0;
for (int y = minY; y < maxY; y += 1) {
for (int x = minX; x < maxX; x += 1) {
sum += _raster.getSampleDouble(x, _dimensions.getGridHeight() - y - 1, 0);
count += 1;
}
}
if (count > 0) {
return Double.valueOf(sum / count);
} else {
return GISExtension.MISSING_VALUE;
}
}
/** */
public RasterDataset resample (GridDimensions toDimensions) {
// Short circuit if possible
if (toDimensions.equals(_dimensions)) {
return this;
}
// Compute the bounds of the new raster in local raster coordinates.
double targetLeft = (toDimensions.getLeft() - _dimensions.getLeft()) / _dimensions.getCellWidth();
double targetRight = (toDimensions.getRight() - _dimensions.getLeft()) / _dimensions.getCellWidth();
double targetBottom = (toDimensions.getBottom() - _dimensions.getBottom()) / _dimensions.getCellHeight();
double targetTop = (toDimensions.getTop() - _dimensions.getBottom()) / _dimensions.getCellHeight();
ColorModel srcCM = new ValueColorModel(_raster);
RenderedImage srcImg = new BufferedImage(srcCM, _raster, false, null);
// If any of the bounds of the new raster lie outside the bounds
// of the current raster, extend the current raster with NaN's
// to cover all of the requested area
Insets border = new Insets(0, 0, 0, 0);
BorderExtender borderExtender = new BorderExtenderConstant(new double[] { Double.NaN });
if (targetLeft < 0.0) {
border.left = -(int)StrictMath.floor(targetLeft);
}
if (targetRight > _dimensions.getGridWidth()) {
border.right = (int)StrictMath.ceil(targetRight) - _dimensions.getGridWidth();
}
if (targetBottom < 0.0) {
border.bottom = -(int)StrictMath.floor(targetBottom);
}
if (targetTop > _dimensions.getGridHeight()) {
border.top = (int)StrictMath.ceil(targetTop) - _dimensions.getGridHeight();
}
if ((border.left > 0) || (border.right > 0) || (border.bottom > 0) || (border.top > 0)) {
ParameterBlock pb = new ParameterBlock();
pb.addSource(srcImg);
pb.add(Integer.valueOf(border.left));
pb.add(Integer.valueOf(border.right));
pb.add(Integer.valueOf(border.top));
pb.add(Integer.valueOf(border.bottom));
pb.add(borderExtender);
//HACK- work around for bug in JAI
srcImg = createRendering(JAI.create("border", pb), srcCM);
}
double flippedTopY = (_dimensions.getGridHeight() + border.top + border.bottom) - targetTop;
if ((targetLeft > 0.0) ||
(targetRight < _dimensions.getGridWidth()) ||
(targetBottom > 0.0) ||
(targetTop < _dimensions.getGridHeight())) {
float left = Math.max((float)targetLeft, 0f);
float bottom = Math.max((float)flippedTopY, 0f);
float right = Math.min((float)(targetRight - targetLeft), _dimensions.getGridWidth()-1);
float top = Math.min((float)(targetTop - targetBottom), _dimensions.getGridHeight()-1);
ParameterBlock pb = new ParameterBlock();
pb.addSource(srcImg);
pb.add(Float.valueOf(left));
pb.add(Float.valueOf(bottom));
pb.add(Float.valueOf(right));
pb.add(Float.valueOf(top));
pb.add(borderExtender);
//HACK- work around for bug in JAI
srcImg = createRendering(JAI.create("crop", pb), srcCM);
}
double scaleX = toDimensions.getGridWidth() / (double)srcImg.getWidth();
double scaleY = toDimensions.getGridHeight() / (double)srcImg.getHeight();
// Remember, translation values are in the RESAMPLED raster's coordinate
// system,not the current raster's coordinate system.
double transX = (_dimensions.getLeft() - toDimensions.getLeft()) / toDimensions.getCellWidth();
double transY = (_dimensions.getTop() - toDimensions.getBottom()) / toDimensions.getCellHeight();
transY = toDimensions.getGridHeight() - transY;
ParameterBlock pb = new ParameterBlock();
pb.addSource(srcImg);
pb.add(Float.valueOf((float)scaleX));
pb.add(Float.valueOf((float)scaleY));
pb.add(Float.valueOf((float)transX));
pb.add(Float.valueOf((float)transY));
pb.add(_interpolation);
RenderingHints hints = new RenderingHints(JAI.KEY_BORDER_EXTENDER, borderExtender);
RenderedOp dstImg = JAI.create("scale", pb, hints);
WritableRaster wr = srcCM.createCompatibleWritableRaster(dstImg.getWidth(), dstImg.getHeight());
dstImg.copyData(wr);
return new RasterDataset(toDimensions, wr);
}
/** */
public RasterDataset convolve (KernelJAI kernel) {
ColorModel srcCM = new ValueColorModel(_raster);
Object srcImg = new BufferedImage(srcCM, _raster, false, null);
BorderExtender borderExtender = new BorderExtenderConstant(new double[] { Double.NaN });
ParameterBlock pb = new ParameterBlock();
pb.addSource(srcImg);
pb.add(kernel);
RenderingHints hints = new RenderingHints(JAI.KEY_BORDER_EXTENDER, borderExtender);
RenderedOp dstImg = JAI.create("convolve", pb, hints);
WritableRaster wr = srcCM.createCompatibleWritableRaster(dstImg.getWidth(), dstImg.getHeight());
dstImg.copyData(wr);
return new RasterDataset(_dimensions, wr);
}
//--------------------------------------------------------------------------
// Dataset implementation
//--------------------------------------------------------------------------
/** */
public Envelope getEnvelope () {
return _dimensions.getEnvelope();
}
//--------------------------------------------------------------------------
// ExtensionObject implementation
//--------------------------------------------------------------------------
/**
* Returns a string representation of the object. If readable is
* true, it should be possible read it as NL code.
*
**/
public String dump (boolean readable, boolean exporting, boolean reference ) {
return "";
}
/** */
public String getNLTypeName() {
return "RasterDataset";
}
/** */
public boolean recursivelyEqual (Object obj) {
if (obj instanceof VectorDataset) {
RasterDataset rd = (RasterDataset)obj;
return rd == this;
} else {
return false;
}
}
}
| agpl-3.0 |
Seklfreak/Robyul2 | cache/elastic.go | 599 | package cache
import (
"errors"
"sync"
"github.com/olivere/elastic"
)
var (
elasticClient *elastic.Client
elasticClientMutex sync.RWMutex
)
func SetElastic(s *elastic.Client) {
elasticClientMutex.Lock()
elasticClient = s
elasticClientMutex.Unlock()
}
func HasElastic() bool {
if elasticClient == nil {
return false
}
return true
}
func GetElastic() *elastic.Client {
elasticClientMutex.RLock()
defer elasticClientMutex.RUnlock()
if elasticClient == nil {
panic(errors.New("Tried to get elastic client before cache#SetElastic() was called"))
}
return elasticClient
}
| agpl-3.0 |
City-of-Bloomington/civic-legislation | src/Application/Controllers/LegislationStatusesController.php | 2049 | <?php
/**
* @copyright 2017-2020 City of Bloomington, Indiana
* @license http://www.gnu.org/licenses/agpl.txt GNU/AGPL, see LICENSE
*/
declare (strict_types=1);
namespace Application\Controllers;
use Application\Models\Legislation\Status;
use Application\Models\Legislation\StatusesTable;
use Web\Controller;
use Web\Block;
use Web\View;
class LegislationStatusesController extends Controller
{
public function index(): View
{
$table = new StatusesTable();
$list = $table->find();
$this->template->blocks[] = new Block('legislation/statuses.inc', ['statuses'=>$list]);
return $this->template;
}
public function update(): View
{
if (!empty($_REQUEST['id'])) {
try { $status = new Status($_REQUEST['id']); }
catch (\Exception $e) { $_SESSION['errorMessages'][] = $e; }
}
else { $status = new Status(); }
if (isset($status)) {
if (isset($_POST['name'])) {
try {
$status->handleUpdate($_POST);
$status->save();
header('Location: '.View::generateUrl('legislationStatuses.index'));
exit();
}
catch (\Exception $e) { $_SESSION['errorMessages'][] = $e; }
}
$this->template->blocks[] = new Block('legislation/updateStatusForm.inc', ['status'=>$status]);
}
else {
header('HTTP/1.1 404 Not Found', true, 404);
$this->template->blocks[] = new Block('404.inc');
}
return $this->template;
}
public function delete(): View
{
if (!empty($_REQUEST['id'])) {
try { $status = new Status($_REQUEST['id']); }
catch (\Exception $e) { $_SESSION['errorMessages'][] = $e; }
}
if (isset($status)) {
$status->delete();
}
header('Location: '.View::generateUrl('legislationStatuses.index'));
exit();
return $this->template;
}
}
| agpl-3.0 |
firefly-iii/firefly-iii | app/Support/Search/SearchInterface.php | 2157 | <?php
/**
* SearchInterface.php
* Copyright (c) 2019 [email protected]
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace FireflyIII\Support\Search;
use Carbon\Carbon;
use FireflyIII\User;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
/**
* Interface SearchInterface.
*/
interface SearchInterface
{
/**
* @return array
*/
public function getInvalidOperators(): array;
/**
* @return Collection
*/
public function getModifiers(): Collection;
/**
* @return Collection
*/
public function getOperators(): Collection;
/**
* @return string
*/
public function getWordsAsString(): string;
/**
* @return bool
*/
public function hasModifiers(): bool;
/**
* @param string $query
*/
public function parseQuery(string $query);
/**
* @return float
*/
public function searchTime(): float;
/**
* @return LengthAwarePaginator
*/
public function searchTransactions(): LengthAwarePaginator;
/**
* @param Carbon $date
*/
public function setDate(Carbon $date): void;
/**
* @param int $limit
*/
public function setLimit(int $limit): void;
/**
* @param int $page
*/
public function setPage(int $page): void;
/**
* @param User $user
*/
public function setUser(User $user);
}
| agpl-3.0 |
Ramkavanan/SHCRM | app/protected/modules/routes/controllers/DefaultController.php | 39445 | <?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
class RoutesDefaultController extends ZurmoModuleController {
/* * public function filters() {
$modelClassName = $this->getModule()->getPrimaryModelName();
$viewClassName = $modelClassName . 'EditAndDetailsView';
return array_merge(parent::filters(),
array(
array(
ZurmoBaseController::REQUIRED_ATTRIBUTES_FILTER_PATH . ' + create, createFromRelation, edit',
'moduleClassName' => get_class($this->getModule()),
'viewClassName' => $viewClassName,
),
array(
ZurmoModuleController::ZERO_MODELS_CHECK_FILTER_PATH . ' + list, index',
'controller' => $this,
),
)
);
} */
public function actionList() {
$pageSize = Yii::app()->pagination->resolveActiveForCurrentUserByType(
'listPageSize', get_class($this->getModule()));
$route = new Route(false);
$searchForm = new RoutesSearchForm($route);
$dataProvider = $this->resolveSearchDataProvider(
$searchForm, $pageSize, null, 'RoutesSearchView'
);
if (isset($_GET['ajax']) && $_GET['ajax'] == 'list-view') {
$mixedView = $this->makeListView(
$searchForm, $dataProvider
);
$view = new RoutesPageView($mixedView);
} else {
$mixedView = $this->makeActionBarSearchAndListView($searchForm, $dataProvider);
$view = new RoutesPageView(ZurmoDefaultViewUtil::
makeStandardViewForCurrentUser($this, $mixedView));
}
echo $view->render();
}
public function actionEdit($id) {
$isClone = 'edit';
//get boject by id
unset($_SESSION['agreementList']);
$route = Route::getById(intval($id));
//if tracking is available edit not allowed
$isRouteTracking = RouteTracking::getTrackingByRouteId($id);
if(!empty($isRouteTracking)){
Yii::app()->user->setFlash('notification', Zurmo::t('ZurmoModule', 'Route cannot be edited once tracking is started.'));
$this->redirect(Yii::app()->createUrl('routes/default/details?id='.$id));
Yii::app()->end(false);
}
//Security check
ControllerSecurityUtil::resolveAccessCanCurrentUserWriteModel($route);
//create view and render
$this->processEdit($route, $id, $isClone);
}
public function actionCopy($id,$type=''){
$isClone = 'clone';
$copyToRoute = new Route();
$postVariableName = get_class($copyToRoute);
$route = Route::getById((int) $id);
if (!isset($_POST[$postVariableName])) {
ControllerSecurityUtil::resolveAccessCanCurrentUserReadModel($route);
ZurmoCopyModelUtil::copy($route, $copyToRoute);
$this->processEdit($copyToRoute, $id, $isClone, $type);
}
}
protected function processEdit(Route $route, $id, $isClone = null, $type=null, $redirectUrl = null) {
$editAndDetailsView1 = $this->makeEditAndDetailsView($this->attemptToSaveModelFromPost($route), 'Edit');
$editAndDetailsView = new RouteStep1View($id, $isClone, $type);
$view = new RoutesPageView(ZurmoDefaultViewUtil::makeStandardViewForCurrentUser($this, $editAndDetailsView));
echo $view->render();
}
public function actionCreate($id=NULL) {
$isClone = 'create';
unset($_SESSION['agreementList']);
unset($_SESSION['agreementNameList']);
$view = new RouteStep1View($id, $isClone);
$trackingView = new RoutesPageView(ZurmoDefaultViewUtil::makeStandardViewForCurrentUser($this, $view));
echo $trackingView->render();
}
/**
* Check if form is posted. If form is posted attempt to save. If save is complete, confirm the current
* user can still read the model. If not, then redirect the user to the index action for the module.
*/
protected function attemptToSaveModelFromPost($model, $createStep = 1, $redirectUrlParams = null, $redirect = true, $returnOnValidate = false) {
assert('$redirectUrlParams == null || is_array($redirectUrlParams) || is_string($redirectUrlParams)');
$savedSuccessfully = false;
$modelToStringValue = null;
$postVariableName = get_class($model);
if (isset($_POST[$postVariableName])) {
$postData = $_POST[$postVariableName];
$controllerUtil = static::getZurmoControllerUtil();
$model = $controllerUtil->saveModelFromPost($postData, $model, $savedSuccessfully, $modelToStringValue, $returnOnValidate);
}
if ($savedSuccessfully && $redirect) {
if ($createStep = Route::STEP1) {
$this->redirect(array($this->getId() . '/createStep2', 'id' => $model->id));
}
//$this->actionAfterSuccessfulModelSave($model, $modelToStringValue, $redirectUrlParams);
}
return $model;
}
public function actionCreateStep2($id, $ClonedRouteId, $type) {
$view = new RouteStep2View($id, $type, $ClonedRouteId);
$routeView = new RoutesPageView(ZurmoDefaultViewUtil::makeStandardViewForCurrentUser($this, $view));
echo $routeView->render();
}
public function actionDetails($id) {
$route = static::getModelAndCatchNotFoundAndDisplayError('Route', intval($id));
$breadCrumbView = StickySearchUtil::resolveBreadCrumbViewForDetailsControllerAction($this, 'RoutesSearchView', $route);
ControllerSecurityUtil::resolveAccessCanCurrentUserReadModel($route);
AuditEvent::logAuditEvent('ZurmoModule', ZurmoModule::AUDIT_EVENT_ITEM_VIEWED, array(strval($route), 'RoutesModule'), $route);
$detailsAndRelationsView = $this->makeDetailsAndRelationsView($route, 'RoutesModule',
'RoutesDetailsAndRelationsView',
Yii::app()->request->getRequestUri(), $breadCrumbView);
$view = new RoutesPageView(ZurmoDefaultViewUtil::
makeStandardViewForCurrentUser($this, $detailsAndRelationsView));
echo $view->render();
}
//Function for route delete
public function actionDelete($id, $massDelete=null)
{
$route_agmt_prod_id_arr = array();
$route_agmt_id_arr = array();
$route = Route::GetById(intval($id));
if(!empty ($route)){
$route->delete(); //Delete a route
}
$routeAgmnts = RouteAgreement::getAgmtByRouteId(intval($id));
if(!empty ($routeAgmnts)){
foreach ($routeAgmnts as $routeAgmnt) {
$route_agmt_id_arr[] = $routeAgmnt->id;
$routeAgmnt->delete(); //Delete a route agreement for route
}
}
$routeCategorys = RouteCategory::getCatByRouteId(intval($id));
if(!empty ($routeCategorys)){
foreach ($routeCategorys as $routeCategory) {
$routeCategory->delete(); //Delete a route category for route
}
}
$routeProds = RouteProducts::getRouteProductsByRouteId(intval($id));
if(!empty ($routeProds)){
foreach ($routeProds as $routeProd) {
$route_agmt_prod_id_arr[$routeProd->agreement->id][] = $routeProd->id;
$routeProd->delete(); //Delete a route products for route
}
}
$RouteTrackings = RouteTracking::getTrackingByRouteId(intval($id));
if(!empty ($RouteTrackings)){
$RouteTrackingIds = array();
foreach ($RouteTrackings as $RouteTracking) {
$RouteTrackingIds[] = $RouteTracking->id;
$RouteTrackingProds = RouteTrackingProducts::getTrackingProdByRouteTrackingId(intval($RouteTracking->id));
if(!empty ($RouteTrackingProds)){
foreach ($RouteTrackingProds as $RouteTrackingProd) {
$RouteTrackingProd->delete(); //Delete a route tracking products for route
}
}
$RouteTracking->delete(); //Delete a route tracking for route
}
}
else{
$this->redirect(array($this->getId() . '/index'));
}
// To delete in the agmt tracking tables
foreach ($RouteTrackingIds as $value) {
$this->deleteAgmtTracking($value, $route_agmt_prod_id_arr);
}
if($massDelete != 0){
return 1;
}else{
$this->redirect(array($this->getId() . '/index'));
}
}
//Function for route tracking delete
public function actionDeleteTrackingDetails($id){
$route_agmt_prod_id_arr = array();
$RouteTracking = RouteTracking::GetById(intval($id));
$RouteTrackingProds = RouteTrackingProducts::getTrackingProdByRouteTrackingId(intval($id));
if(!empty ($RouteTrackingProds)){
foreach ($RouteTrackingProds as $RouteTrackingProd) {
$route_agmt_prod_id_arr[$RouteTrackingProd->agreement->id][] = $RouteTrackingProd->agreementproduct->id;
$RouteTrackingProd->delete(); //Delete a route tracking products for route
}
}
// To delete in the agmt tracking tables
$this->deleteAgmtTracking($id, $route_agmt_prod_id_arr);
$RouteTracking->delete(); //Delete a route tracking for route
$this->redirect(array($this->getId() . '/details?id='.$RouteTracking->route->id.''));
}
public function actionMassDelete() {
$massDelete = 1;
if(isset($_GET['selectedIds'])){
$selectedIds = explode(',', $_GET['selectedIds']);
foreach ($selectedIds as $value) {
$results[] = $this->actionDelete($value, $massDelete);
}
}elseif (isset($_GET['selectAll'])) {
}
if(!empty($results)){
Yii::app()->user->setFlash('notification', Zurmo::t('ZurmoModule', 'Routes are deleted Successfully.'));
$this->redirect(Yii::app()->createUrl('routes/default'));
Yii::app()->end(false);
}
// $pageSize = Yii::app()->pagination->resolveActiveForCurrentUserByType(
// 'massDeleteProgressPageSize');
// $route = new Route(false);
// $activeAttributes = $this->resolveActiveAttributesFromMassDeletePost();
// $dataProvider = $this->getDataProviderByResolvingSelectAllFromGet(
// new RoutesSearchForm($route), $pageSize, Yii::app()->user->userModel->id, null, 'RoutesSearchView');
// $selectedRecordCount = $this->getSelectedRecordCountByResolvingSelectAllFromGet($dataProvider);
// $route = $this->processMassDelete(
// $pageSize, $activeAttributes, $selectedRecordCount, 'RoutesPageView', $route, RoutesModule::getModuleLabelByTypeAndLanguage('Plural'), $dataProvider
// );
// $massDeleteView = $this->makeMassDeleteView(
// $route, $activeAttributes, $selectedRecordCount, RoutesModule::getModuleLabelByTypeAndLanguage('Plural')
// );
// $view = new RoutesPageView(ZurmoDefaultViewUtil::
// makeStandardViewForCurrentUser($this, $massDeleteView));
// echo $view->render();
}
public function actionExport() {
$this->export('RouteEditAndDetailsView', 'Route');
}
public function actionModalList() {
$modalListLinkProvider = new SelectFromRelatedEditModalListLinkProvider(
$_GET['modalTransferInformation']['sourceIdFieldId'], $_GET['modalTransferInformation']['sourceNameFieldId'], $_GET['modalTransferInformation']['modalId']
);
echo ModalSearchListControllerUtil::setAjaxModeAndRenderModalSearchList($this, $modalListLinkProvider);
}
public function actionRouteTracking($id) {
$routeTracking = '';
$routeTracking = new RouteTrackingView($routeTracking, $id);
$zurmoView = new RoutesPageView(ZurmoDefaultViewUtil::makeStandardViewForCurrentUser($this, $routeTracking));
echo $zurmoView->render();
}
public function actionrouteTrackingDetailsView($id){
$routeTracking = '';
$routeTracking = new RouteTrackingDetailView($routeTracking, $id);
$zurmoView = new RoutesPageView(ZurmoDefaultViewUtil::makeStandardViewForCurrentUser($this, $routeTracking));
echo $zurmoView->render();
}
public function actionCreateStep3($id, $ClonedRouteId, $type) {
$view = new RouteStep3View($id, $ClonedRouteId, $type);
$routeView = new RoutesPageView(ZurmoDefaultViewUtil::makeStandardViewForCurrentUser($this, $view));
echo $routeView->render();
}
public function actionGetAddNewRouteAndCategories($routeInformation) {
// echo "1";exit;
$clonedRouteInfo = array();
$routes = json_decode($routeInformation, TRUE);
if(isset($routes['isEdit'][0]) && $routes['isEdit'][1] == 'edit'){
$updateRoute = Route::getById($routes['isEdit'][0]);
$updateRoute->name = $routes['routeName'];
$updateRoute->crewname = $routes['crewName'];
$updateRoute->save();
if (isset($updateRoute->id) && $updateRoute->id > 0) {
$clonedRouteInfo['newClonedRouteId'] = 0;
$clonedRouteInfo['type'] = 'edit';
$clonedRouteInfo['oldRouteId'] = $routes['isEdit'][0];
$categoryList = explode(',', $routes['totalSelectedCategories']);
$categoryExist = RouteCategory::getCatByRouteId($routes['isEdit'][0]);
if(!empty ($categoryExist)){
foreach ($categoryExist as $routeCategory) {
$routeCategory->id;
$routeCategory->delete();
}
foreach ($categoryList as $value) {
// if (in_array($value, $existedCategories)){
// continue;
// }
$updateRouteCategory = new RouteCategory();
$updateRouteCategory->route = Route::getById($updateRoute->id);
$category_details = Category::getById($value);
// For the categroy based Agmts
$_SESSION['categoryList'][] = $category_details->name;
$updateRouteCategory->category = $category_details;
$updateRouteCategory->save();
}
}
echo json_encode($clonedRouteInfo);
}
}elseif(!empty($routes['isEdit'][0]) && $routes['isEdit'][1] == 'clone'){
if(isset($routes['isCloneBack']))
{
$cloneEditArr = explode('_', $routes['isCloneBack']);
}
else
$cloneEditArr[0] = 'clone';
if($cloneEditArr[0] == 'edit')
{
$updateRoute = Route::getById($routes['isEdit'][0]);
$updateRoute->name = $routes['routeName'];
$updateRoute->crewname = $routes['crewName'];
$updateRoute->save();
if (isset($updateRoute->id) && $updateRoute->id > 0) {
$updatedRouteInfo['newClonedRouteId'] = $routes['isEdit'][0];
$updatedRouteInfo['type'] = 'clone';
$updatedRouteInfo['oldRouteId'] = $cloneEditArr[1];
$categoryList = explode(',', $routes['totalSelectedCategories']);
$categoryExist = RouteCategory::getCatByRouteId($routes['isEdit'][0]);
if(!empty ($categoryExist)){
foreach ($categoryExist as $routeCategory) {
$routeCategory->id;
$routeCategory->delete();
}
foreach ($categoryList as $value) {
$updateRouteCategory = new RouteCategory();
$updateRouteCategory->route = Route::getById($updateRoute->id);
$category_details = Category::getById($value);
// For the categroy based Agmts
$_SESSION['categoryList'][] = $category_details->name;
$updateRouteCategory->category = $category_details;
$updateRouteCategory->save();
}
echo json_encode($updatedRouteInfo);
}
}
}
else
{
$newClonedRoute = new Route();
$newClonedRoute->name = $routes['routeName'];
$newClonedRoute->crewname = $routes['crewName'];
$newClonedRoute->save();
if (isset($newClonedRoute->id) && $newClonedRoute->id > 0) {
$clonedRouteInfo['newClonedRouteId'] = $newClonedRoute->id;
$clonedRouteInfo['type'] = 'clone';
$clonedRouteInfo['oldRouteId'] = $routes['isEdit'][0];
$categoryList = explode(',', $routes['totalSelectedCategories']);
$categoryExist = RouteCategory::getCatByRouteId($routes['isEdit'][0]);
foreach ($categoryExist as $values) {
$existedCategories[] = $values->category->id;
}
foreach ($categoryList as $value) {
$cloneRouteCategory = new RouteCategory();
$cloneRouteCategory->route = Route::getById($newClonedRoute->id);
$cloneRouteCategory->category = Category::getById($value);
$cloneRouteCategory->save();
}
}
echo json_encode($clonedRouteInfo);
}
}else{
$newRoute = new Route();
$newRoute->name = $routes['routeName'];
$newRoute->crewname = $routes['crewName'];
$newRoute->save();
if (isset($newRoute->id) && $newRoute->id > 0) {
$clonedRouteInfo['newClonedRouteId'] = 0;
$clonedRouteInfo['type'] = 'create';
$clonedRouteInfo['oldRouteId'] = $newRoute->id;
$categoryList = explode(',', $routes['totalSelectedCategories']);
foreach ($categoryList as $value) {
$newRouteCategory = new RouteCategory();
$newRouteCategory->route = Route::getById($newRoute->id);
$category_details = Category::getById($value);
// For the categroy based Agmts
$_SESSION['categoryList'][] = $category_details->name;
$newRouteCategory->category = $category_details;
$newRouteCategory->save();
}
}
echo json_encode($clonedRouteInfo);
}
}
public function actionGetAddNewRouteAgreement($routeAgreementInformation) {
$routAgmntInfo = array();
$routeAgreements = json_decode($routeAgreementInformation, TRUE);
$routAgmntInfo['oldRouteId'] = $routeAgreements['routeId'];
$routAgmntInfo['newClonedRouteId'] = $routeAgreements['newClonedRouteId'];
$agreementList = explode(',', $routeAgreements['totalSelectedAgreement']);
$agreementNameList = explode(',', $routeAgreements['totalSelectedAgreementName']);
if(isset($agreementList)){
$_SESSION['agreementList'] = $agreementList;
$_SESSION['agreementNameList'] = $agreementNameList;
}
echo json_encode($routAgmntInfo);
}
public function actionTrackView($id) {
$printData = '';
$trackingView = new RouteTrackView($printData, $id);
echo $trackingView->render();
}
public function actionGetActiveAgreement($pageOffset, $agmtName, $routeId) {
$pageSize = Yii::app()->pagination->resolveActiveForCurrentUserByType(
'listPageSize', get_class($this->getModule()));
$items_per_page = $pageOffset * ($pageSize * 2);
$routeCategories = RouteCategory::getCatByRouteId($routeId);
foreach ($routeCategories as $key => $routeCategory) {
$cat_arr[] = $routeCategory->category->name;
}
$agmt_arr = AgreementProduct::getAgmtIdByCategory($cat_arr);
$agmt_ids_arr = array();
foreach($agmt_arr as $agmt)
{
$agmt_ids_arr[] = $agmt['agreement_id'];
}
if(count($agmt_ids_arr))
$agmt_ids_arr = $agmt_ids_arr;
else
$agmt_ids_arr = array('0');
$searchData = Agreement::getAllRecurringActiveAgmt(1, $items_per_page, $agmtName, $agmt_ids_arr);
foreach ($searchData as $key => $val) {
$format_arr[$key]['account_name'] = $searchData[$key]->account->name;
}
echo CJSON::encode($searchData);
}
public function actionCreateStep4($id, $ClonedRouteId, $type) {
$routeAgmnt = RouteAgreement::getAgmtByRouteId($id);
if(empty($routeAgmnt)){
Yii::app()->user->setFlash('notification', Zurmo::t('ZurmoModule', 'No agreement added under this route.'));
$this->redirect(array($this->getId() . '/details?id='.$id));
}
$view = new RouteStep4View($id, $ClonedRouteId, $type);
$routeView = new RoutesPageView(ZurmoDefaultViewUtil::makeStandardViewForCurrentUser($this, $view));
echo $routeView->render();
}
public function actionAddNewRouteAgreements($routeInformation){
$existedAgreements = array();
$routAgmntInfo = array();
$routes = json_decode($routeInformation, TRUE);
if (isset($routes['routeId']) && $routes['routeId'] > 0 ){
$routAgmntInfo['oldRouteId'] = $routes['routeId'];
$routAgmntInfo['newClonedRouteId'] = $routes['newClonedRouteId'];
$agmtExist = RouteAgreement::getAgmtByRouteId($routes['routeId']);
if($routes['newClonedRouteId'] == 'null' || $routes['newClonedRouteId'] == 0){
if(!empty ($agmtExist) && isset($routes['isEdit'])){
foreach ($agmtExist as $routeAgreement) {
$routeAgreement->id;
$routeAgreement->delete();
}
}
}
if($routes['newClonedRouteId'] == 'null' || $routes['newClonedRouteId'] > 0){
$agmtExist = RouteAgreement::getAgmtByRouteId($routes['newClonedRouteId']);
if(!empty ($agmtExist)){
foreach ($agmtExist as $routeAgreement) {
$routeAgreement->id;
$routeAgreement->delete();
}
}
}
foreach ($routes['agmt_ids'] as $agmt_value) {
// if (in_array($agmt_value, $existedAgreements)){
// continue;
// }
$newRouteAgreement = new RouteAgreement();
if($routes['newClonedRouteId'] == 'null' || $routes['newClonedRouteId'] == 0){
$newRouteAgreement->route = Route::getById($routes['routeId']);
}else{
$newRouteAgreement->route = Route::getById($routes['newClonedRouteId']);
}
$newRouteAgreement->agreement = Agreement::getById($agmt_value);
$newRouteAgreement->save();
}
}
unset($_SESSION['agreementList']);
echo json_encode($routAgmntInfo);
}
public function actionAddRouteAgreementProducts($routeInformation){
$routAgmntInfo = array();
$routes = json_decode($routeInformation, TRUE);
$routAgmntInfo['oldRouteId'] = $routes['routeId'];
$routAgmntInfo['newClonedRouteId'] = $routes['newClonedRouteId'];
if (isset($routes['routeId']) && $routes['routeId'] > 0 ){
$productExist = RouteProducts::getRouteProductsByRouteId($routes['routeId']);
if(!empty ($productExist) && $routes['isEdit'] == 'edit'){
foreach ($productExist as $routeProduct) {
$routeProduct->id;
$routeProduct->delete();
}
}
foreach ($routes['selected_agmt_prods'] as $agmt_value) {
$agmt_detail_arr = explode('~',$agmt_value);
$newRouteProduct = new RouteProducts();
if($routes['newClonedRouteId'] == 0){
$newRouteProduct->route = Route::getById($routes['routeId']);
}else{
$newRouteProduct->route = Route::getById($routes['newClonedRouteId']);
}
$newRouteProduct->agreement = Agreement::getById($agmt_detail_arr['1']);
$newRouteProduct->agreementproduct = AgreementProduct::getById($agmt_detail_arr['0']);
$newRouteProduct->save();
}
}
echo json_encode($routAgmntInfo);
}
public function actionAddRouteTrackingProducts($routeTrackingInfo){
$routeTrackingProdDatas = json_decode($routeTrackingInfo, TRUE);
foreach ($routeTrackingProdDatas as $key => $routeTrackingProdData) {
RoutesUtils::SaveNewRouteTracking($routeTrackingProdData);
}
echo $routeTrackingProdData['addRouteTrackingDetails']['route_id'];
}
// public function deleteAgmtTracking($route_tracking_id, $agmt_prod_ids)
// {
// $agmt_track_details_arr = array();
// $agreementTracking = AgreementTracking::getAgmtTrackingByRouteTrackingId($route_tracking_id);
// foreach($agreementTracking as $agmt_track_key => $agmt_track_arr)
// {
// $agmt_track_details_arr[$agmt_track_arr->agreement->id] = $agmt_track_arr->id;
// }
// foreach($agmt_track_details_arr as $agmt_id=>$agmt_track_id)
// {
// // Adding New Agreement prods
// $agt = Agreement::getById(intval($agmt_id));
// // For updating the already added agmt prods
// $prev_prod_quantity_consumed = 0;
// $prev_mhr_consumed = 0;
// $prev_equipment_consumed = 0;
// $prev_material_consumed = 0;
// $addedTrackingProducts = AgreementTrackingProducts::getAgmtTrackingProductsByAgmtTrackingId($agmt_track_id);
//
// // Updating the units consumed in agmt prods
// foreach ($addedTrackingProducts as $trackingProduct) {
// $agmt_prod = AgreementProduct::getById(intval($trackingProduct->agreementProduct->id));
// if (strpos($agmt_prod->Product_Code, 'L') !== false) {
// $prev_mhr_consumed += $trackingProduct->consumed_unit;
// }
// if (strpos($agmt_prod->Product_Code, 'E') !== false) {
// $prev_equipment_consumed += $trackingProduct->consumed_unit;
// }
// if (strpos($agmt_prod->Product_Code, 'M') !== false) {
// $prev_material_consumed += $trackingProduct->consumed_unit;
// }
//
// $agmt_prod_consumed_units_ = round($agmt_prod->Consumed_Units,4)-round($trackingProduct->consumed_unit,4);
// $agmt_prod->Consumed_Units = round($agmt_prod_consumed_units_,4);
// if(!$agmt_prod->save()){
// throw new FailedToSaveModelException();
// die;
// }
// }
// $agmntTrackingObj = AgreementTracking::getById($agmt_track_id);
// $agmntTrackingObj->delete(); //Agreement tracking delete
//
// // To update the calculations in the agreement
// $agt->Used_MHR = round($agt->Used_MHR-$prev_mhr_consumed,2);
// $agt->Total_Available_MHR = round($agt->Total_Available_MHR+$prev_mhr_consumed,2);
// $agt->Used_Material = round($agt->Used_Material-$prev_material_consumed,2);
// $agt->Available_Material = round($agt->Available_Material+$prev_material_consumed,2);
// $agt->Used_Equipment = round($agt->Used_Equipment-$prev_equipment_consumed,2);
// $agt->Available_Equipment = round($agt->Available_Equipment+$prev_equipment_consumed,2);
// $agt->Year_to_Date_MHR = round($agt->Used_MHR,2);
//
// if($agt->Total_MHR > 0)
// $agt->MHR_Used_Percentage = round(($agt->Used_MHR/$agt->Total_MHR)*100, 2);
//
// $agt->Material_Year_To_Date = round($agt->Used_Material,2);
//
// if($agt->Total_Material > 0)
// $agt->Material_Used_Percentage = round(($agt->Used_Material/$agt->Total_Material)*100, 2);
//
// $agt->Equipment_Year_To_Date = round($agt->Used_Equipment,2);
//
// if($agt->Total_Equipment > 0)
// $agt->Equipment_Used_Percentage = round(($agt->Used_Equipment/$agt->Total_Equipment)*100, 2);
//
// if(!$agt->save()){
// throw new FailedToSaveModelException();
// die;
// }
// }
// }
public function deleteAgmtTracking($route_tracking_id, $agmt_prod_ids)
{
$agmt_track_details_arr = array();
$agreementTracking = AgreementTracking::getAgmtTrackingByRouteTrackingId($route_tracking_id);
foreach($agreementTracking as $agmt_track_key => $agmt_track_arr)
{
$agmt_track_details_arr[$agmt_track_arr->agreement->id] = $agmt_track_arr->id;
}
foreach($agmt_track_details_arr as $agmt_id1=>$agmt_track_id)
{
$agt1 = Agreement::getById(intval($agmt_id1));
$opportunityId =$agt1->opportunity->id;
$opportunity = Opportunity::getById($opportunityId);
$opptProducts = OpportunityProduct::getAllByOpptId(intval($opportunityId));
$opptPdctMap;
$totalDirectCost1=$totalfinalamount=0;
if(count($opptProducts) > 0) {
foreach($opptProducts as $row) {
$opptPdctMap[$row->Category][] = $row;
}
foreach ($opptPdctMap as $key1 => $optpdctArray1) {
foreach ($optpdctArray1 as $optKey1 => $optpdt1){
$totalDirectCost1 += $optpdt1->Total_Direct_Cost->value;
}
}
foreach ($opptPdctMap as $key => $optpdctArray) {
foreach ($optpdctArray as $optKey => $optpdt){
$totalfinalamount += $optpdt->Total_Direct_Cost->value / (1- ((((($opportunity->finalAmount->value -$totalDirectCost1 )/$opportunity->finalAmount->value)*100)) /100)) ;
}
}
}
}
$totalDirectCost=0;
foreach($agmt_track_details_arr as $agmt_id=>$agmt_track_id)
{
// Adding New Agreement prods
$agt = Agreement::getById(intval($agmt_id));
// For updating the already added agmt prods
$prev_prod_quantity_consumed = 0;
$prev_mhr_consumed = 0;
$prev_equipment_consumed = 0;
$prev_material_consumed = 0;
$addedTrackingProducts = AgreementTrackingProducts::getAgmtTrackingProductsByAgmtTrackingId($agmt_track_id);
// Updating the units consumed in agmt prods
foreach ($addedTrackingProducts as $trackingProduct) {
$agmt_prod = AgreementProduct::getById(intval($trackingProduct->agreementProduct->id));
if (strpos($agmt_prod->Product_Code, 'L') !== false) {
$prev_mhr_consumed += $trackingProduct->consumed_unit;
$costcatalog= Costbook::getByProductCode($agmt_prod->Product_Code);
if(!empty($costcatalog)){
$burdenCost = $costcatalog[0]->burdenCost;
$laborcost = $costcatalog[0]->laborCost;
}
$totalDirectCost += ($burdenCost + $laborcost)* $trackingProduct->consumed_unit;
}
if (strpos($agmt_prod->Product_Code, 'E') !== false) {
$prev_equipment_consumed += $trackingProduct->consumed_unit;
$costcatalog= Costbook::getByProductCode($agmt_prod->Product_Code);
if(!empty($costcatalog)){
$costperunit = $costcatalog[0]->costperunit;
}
$totalDirectCost += $costperunit * $trackingProduct->consumed_unit;
}
if (strpos($agmt_prod->Product_Code, 'M') !== false) {
$prev_material_consumed += $trackingProduct->consumed_unit;
$costcatalog= Costbook::getByProductCode($agmt_prod->Product_Code);
if(!empty($costcatalog)){
$costperunit = $costcatalog[0]->costperunit;
}
$totalDirectCost += $trackingProduct->consumed_unit * $costperunit;
}
$agmt_prod_consumed_units_ = round($agmt_prod->Consumed_Units,4)-round($trackingProduct->consumed_unit,4);
$agmt_prod->Consumed_Units = round($agmt_prod_consumed_units_,4);
if(!$agmt_prod->save()){
throw new FailedToSaveModelException();
die;
}
}
// $newCurrent_GPM=(($totalfinalamount-$totalDirectCost)/$totalfinalamount)*100;
//$newCurrent_GPMold =$agt->newCurrent_GPM;
//$agt->newCurrent_GPM = round($newCurrent_GPM,2);
//$agt->save();
//For the Current GPM calculation
$AgmtProductGpm = AgreementProduct::getAgreementProdByAgreementId($agmt_id);
$totalDirectCostData = 0;
foreach ($AgmtProductGpm as $AgmtProductsGpm) {
if(isset($AgmtProductsGpm) && (!empty($AgmtProductsGpm->Consumed_Units)))
{
$agmtprodData = $AgmtProductsGpm;
$getCostbookData = Costbook::getById($agmtprodData->costbook->id);
if (strpos($getCostbookData->productcode, 'L') !== false) {
$costcatalogData = Costbook::getByProductCode($getCostbookData->productcode);
if(!empty($costcatalogData)){
$burdenCostData = $costcatalogData[0]->burdenCost;
$laborcostData = $costcatalogData[0]->laborCost;
}
$totalDirectCostData += ($burdenCostData + $laborcostData)* $AgmtProductsGpm->Consumed_Units;
}
if (strpos($getCostbookData->productcode, 'E') !== false) {
$costcatalogData= Costbook::getByProductCode($getCostbookData->productcode);
if(!empty($costcatalogData)){
$costperunitData = $costcatalogData[0]->costperunit;
}
$totalDirectCostData += $costperunitData * $AgmtProductsGpm->Consumed_Units;
}
if (strpos($getCostbookData->productcode, 'M') !== false) {
$costcatalogData = Costbook::getByProductCode($getCostbookData->productcode);
if(!empty($costcatalog)){
$costperunitData = $costcatalogData[0]->costperunit;
}
$totalDirectCostData += $AgmtProductsGpm->Consumed_Units * $costperunitData;
}
}
}
$newCurrent_GPM=(($totalfinalamount-$totalDirectCostData)/$totalfinalamount)*100;
$agt->newCurrent_GPM =round($newCurrent_GPM,2);
$agt->save();
$agmntTrackingObj = AgreementTracking::getById($agmt_track_id);
$agmntTrackingObj->delete(); //Agreement tracking delete
// To update the calculations in the agreement
$agt->Used_MHR = round($agt->Used_MHR-$prev_mhr_consumed,2);
$agt->Total_Available_MHR = round($agt->Total_Available_MHR+$prev_mhr_consumed,2);
$agt->Used_Material = round($agt->Used_Material-$prev_material_consumed,2);
$agt->Available_Material = round($agt->Available_Material+$prev_material_consumed,2);
$agt->Used_Equipment = round($agt->Used_Equipment-$prev_equipment_consumed,2);
$agt->Available_Equipment = round($agt->Available_Equipment+$prev_equipment_consumed,2);
$agt->Year_to_Date_MHR = round($agt->Used_MHR,2);
if($agt->Total_MHR > 0)
$agt->MHR_Used_Percentage = round(($agt->Used_MHR/$agt->Total_MHR)*100, 2);
$agt->Material_Year_To_Date = round($agt->Used_Material,2);
if($agt->Total_Material > 0)
$agt->Material_Used_Percentage = round(($agt->Used_Material/$agt->Total_Material)*100, 2);
$agt->Equipment_Year_To_Date = round($agt->Used_Equipment,2);
if($agt->Total_Equipment > 0)
$agt->Equipment_Used_Percentage = round(($agt->Used_Equipment/$agt->Total_Equipment)*100, 2);
if(!$agt->save()){
throw new FailedToSaveModelException();
die;
}
}
}
public function actionRouteProduct($id) {
// For the route product page
}
}
?>
| agpl-3.0 |
hasseboulen/WoWAnalyzer | src/Parser/Mage/Frost/Modules/Items/SoulOfTheArchmage.js | 1549 | import React from 'react';
import ITEMS from 'common/ITEMS';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import ItemLink from 'common/ItemLink';
import Wrapper from 'common/Wrapper';
import Analyzer from 'Parser/Core/Analyzer';
import Combatants from 'Parser/Core/Modules/Combatants';
import SUGGESTION_IMPORTANCE from 'Parser/Core/ISSUE_IMPORTANCE';
/**
* Soul of the Archmage:
* Gain the Frozen Touch talent
*/
class SoulOfTheArchmage extends Analyzer {
static dependencies = {
combatants: Combatants,
};
on_initialized() {
this.active = this.combatants.selected.hasFinger(ITEMS.SOUL_OF_THE_ARCHMAGE.id);
this.hasPickedOtherTalent = this.combatants.selected.hasTalent(SPELLS.ICE_NOVA_TALENT.id) || this.combatants.selected.hasTalent(SPELLS.SPLITTING_ICE_TALENT.id);
}
item() {
return {
item: ITEMS.SOUL_OF_THE_ARCHMAGE,
result: <Wrapper>This gave you <SpellLink id={SPELLS.FROZEN_TOUCH_TALENT.id} />.</Wrapper>,
};
}
suggestions(when) {
when(this.hasPickedOtherTalent).isFalse()
.addSuggestion((suggest) => {
return suggest(<Wrapper>When using <ItemLink id={ITEMS.SOUL_OF_THE_ARCHMAGE.id} /> please make sure to pick another talent in the same talent row. Your choices are <SpellLink id={SPELLS.ICE_NOVA_TALENT.id} /> or <SpellLink id={SPELLS.SPLITTING_ICE_TALENT.id} />.</Wrapper>)
.icon(ITEMS.SOUL_OF_THE_ARCHMAGE.icon)
.staticImportance(SUGGESTION_IMPORTANCE.MAJOR);
});
}
}
export default SoulOfTheArchmage;
| agpl-3.0 |
Intermesh/groupoffice-webclient | app/modules/groupoffice/users/language/fr.js | 1123 | angular.module("GO.Core")
.config(["GO.Core.Providers.TranslateProvider", function (TranslateProvider) {
TranslateProvider.addTranslations("fr",
{
"GO\\Core\\Users\\Model\\User": "Utilisateur",
"GO\\Core\\Users\\Module": "Utilisateurs",
"userLoggedIn": "utilisateur connect\u00e9",
"login": "Connexion",
"logout": "D\u00e9connexion",
"Change password": "Changer mot de passe",
"No users found": "Pas trouv\u00e9 d'utilisateurs",
"Current password": "Mot de passe actuel",
"The password was incorrect": "Mot de passe incorrect",
"New password": "Nouveau mot de passe",
"The passwords don't match": "Les mots de passe ne correspondent pas",
"Sorry, this username is already taken.": "D\u00e9sol\u00e9, mais ce nom d'utilisateur est d\u00e9j\u00e0 utilis\u00e9.",
"Invalid e-mail address": "Adresse e-mail non valide ",
"Secondary e-mail": "Adresse e-mail secondaire",
"Switch to": "Basculer sur ",
"Edit contact": "Modifier contact",
"logins": "Connexions",
"Login count": "Nombre de connexions",
"Users": "Utilisateurs"
}
);
}]); | agpl-3.0 |
bitsquare/bitsquare | core/src/main/java/bisq/core/app/CoreModule.java | 3638 | /*
* This file is part of Bisq.
*
* Bisq is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* Bisq is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Bisq. If not, see <http://www.gnu.org/licenses/>.
*/
package bisq.core.app;
import bisq.core.alert.AlertModule;
import bisq.core.btc.BitcoinModule;
import bisq.core.dao.DaoModule;
import bisq.core.filter.FilterModule;
import bisq.core.network.p2p.seed.DefaultSeedNodeRepository;
import bisq.core.offer.OfferModule;
import bisq.core.presentation.CorePresentationModule;
import bisq.core.proto.network.CoreNetworkProtoResolver;
import bisq.core.proto.persistable.CorePersistenceProtoResolver;
import bisq.core.trade.TradeModule;
import bisq.core.user.Preferences;
import bisq.core.util.FormattingUtils;
import bisq.core.util.coin.CoinFormatter;
import bisq.core.util.coin.ImmutableCoinFormatter;
import bisq.network.crypto.EncryptionServiceModule;
import bisq.network.p2p.P2PModule;
import bisq.network.p2p.network.BridgeAddressProvider;
import bisq.network.p2p.seed.SeedNodeRepository;
import bisq.common.app.AppModule;
import bisq.common.config.Config;
import bisq.common.crypto.PubKeyRing;
import bisq.common.crypto.PubKeyRingProvider;
import bisq.common.proto.network.NetworkProtoResolver;
import bisq.common.proto.persistable.PersistenceProtoResolver;
import java.io.File;
import static bisq.common.config.Config.*;
import static com.google.inject.name.Names.named;
public class CoreModule extends AppModule {
public CoreModule(Config config) {
super(config);
}
@Override
protected void configure() {
bind(Config.class).toInstance(config);
bind(BridgeAddressProvider.class).to(Preferences.class);
bind(SeedNodeRepository.class).to(DefaultSeedNodeRepository.class);
bind(File.class).annotatedWith(named(STORAGE_DIR)).toInstance(config.storageDir);
CoinFormatter btcFormatter = new ImmutableCoinFormatter(config.baseCurrencyNetworkParameters.getMonetaryFormat());
bind(CoinFormatter.class).annotatedWith(named(FormattingUtils.BTC_FORMATTER_KEY)).toInstance(btcFormatter);
bind(File.class).annotatedWith(named(KEY_STORAGE_DIR)).toInstance(config.keyStorageDir);
bind(NetworkProtoResolver.class).to(CoreNetworkProtoResolver.class);
bind(PersistenceProtoResolver.class).to(CorePersistenceProtoResolver.class);
bindConstant().annotatedWith(named(USE_DEV_PRIVILEGE_KEYS)).to(config.useDevPrivilegeKeys);
bindConstant().annotatedWith(named(USE_DEV_MODE)).to(config.useDevMode);
bindConstant().annotatedWith(named(REFERRAL_ID)).to(config.referralId);
// ordering is used for shut down sequence
install(new TradeModule(config));
install(new EncryptionServiceModule(config));
install(new OfferModule(config));
install(new P2PModule(config));
install(new BitcoinModule(config));
install(new DaoModule(config));
install(new AlertModule(config));
install(new FilterModule(config));
install(new CorePresentationModule(config));
bind(PubKeyRing.class).toProvider(PubKeyRingProvider.class);
}
}
| agpl-3.0 |
buremba/rakam | rakam-ui/src/main/resources/scheduled-task/google-webmaster/script.js | 6527 | //@ sourceURL=rakam-ui/src/main/resources/scheduled-task/google-webmaster/script.js
var countryMapping = {
"ABW": "AW",
"AFG": "AF",
"AGO": "AO",
"AIA": "AI",
"ALB": "AL",
"AND": "AD",
"ARE": "AE",
"ARG": "AR",
"ARM": "AM",
"ASM": "AS",
"ATA": "AQ",
"ATF": "TF",
"ATG": "AG",
"AUS": "AU",
"AUT": "AT",
"AZE": "AZ",
"BDI": "BI",
"BEL": "BE",
"BEN": "BJ",
"BFA": "BF",
"BGD": "BD",
"BGR": "BG",
"BHR": "BH",
"BHS": "BS",
"BIH": "BA",
"BLR": "BY",
"BLZ": "BZ",
"BMU": "BM",
"BRA": "BR",
"BRB": "BB",
"BRN": "BN",
"BTN": "BT",
"BVT": "BV",
"BWA": "BW",
"CAF": "CF",
"CAN": "CA",
"CCK": "CC",
"CHE": "CH",
"CHL": "CL",
"CHN": "CN",
"CMR": "CM",
"COG": "CG",
"COK": "CK",
"COL": "CO",
"COM": "KM",
"CRI": "CR",
"CUB": "CU",
"CXR": "CX",
"CYM": "KY",
"CYP": "CY",
"DEU": "DE",
"DJI": "DJ",
"DMA": "DM",
"DNK": "DK",
"DOM": "DO",
"DZA": "DZ",
"ECU": "EC",
"EGY": "EG",
"ERI": "ER",
"ESH": "EH",
"ESP": "ES",
"EST": "EE",
"ETH": "ET",
"FIN": "FI",
"FJI": "FJ",
"FLK": "FK",
"FRA": "FR",
"FRO": "FO",
"FSM": "FM",
"GAB": "GA",
"GBR": "GB",
"GEO": "GE",
"GGY": "GG",
"GHA": "GH",
"GIB": "GI",
"GIN": "GN",
"GLP": "GP",
"GMB": "GM",
"GNB": "GW",
"GNQ": "GQ",
"GRC": "GR",
"GRD": "GD",
"GRL": "GL",
"GTM": "GT",
"GUF": "GF",
"GUM": "GU",
"GUY": "GY",
"HKG": "HK",
"HMD": "HM",
"HND": "HN",
"HRV": "HR",
"HTI": "HT",
"HUN": "HU",
"IDN": "ID",
"IMN": "IM",
"IND": "IN",
"IOT": "IO",
"IRL": "IE",
"IRN": "IR",
"IRQ": "IQ",
"ISL": "IS",
"ISR": "IL",
"ITA": "IT",
"JAM": "JM",
"JEY": "JE",
"JOR": "JO",
"JPN": "JP",
"KAZ": "KZ",
"KEN": "KE",
"KGZ": "KG",
"KHM": "KH",
"KIR": "KI",
"KNA": "KN",
"KOR": "KR",
"KWT": "KW",
"LAO": "LA",
"LBN": "LB",
"LBR": "LR",
"LCA": "LC",
"LIE": "LI",
"LKA": "LK",
"LSO": "LS",
"LTU": "LT",
"LUX": "LU",
"LVA": "LV",
"MAC": "MO",
"MAR": "MA",
"MCO": "MC",
"MDA": "MD",
"MDG": "MG",
"MDV": "MV",
"MEX": "MX",
"MHL": "MH",
"MLI": "ML",
"MLT": "MT",
"MMR": "MM",
"MNE": "ME",
"MNG": "MN",
"MNP": "MP",
"MOZ": "MZ",
"MRT": "MR",
"MSR": "MS",
"MTQ": "MQ",
"MUS": "MU",
"MWI": "MW",
"MYS": "MY",
"MYT": "YT",
"NAM": "NA",
"NCL": "NC",
"NER": "NE",
"NFK": "NF",
"NGA": "NG",
"NIC": "NI",
"NIU": "NU",
"NLD": "NL",
"NOR": "NO",
"NPL": "NP",
"NRU": "NR",
"NZL": "NZ",
"OMN": "OM",
"PAK": "PK",
"PAN": "PA",
"PCN": "PN",
"PER": "PE",
"PHL": "PH",
"PLW": "PW",
"PNG": "PG",
"POL": "PL",
"PRI": "PR",
"PRK": "KP",
"PRT": "PT",
"PRY": "PY",
"PYF": "PF",
"QAT": "QA",
"ROU": "RO",
"RUS": "RU",
"RWA": "RW",
"SAU": "SA",
"SDN": "SD",
"SEN": "SN",
"SGP": "SG",
"SGS": "GS",
"SJM": "SJ",
"SLB": "SB",
"SLE": "SL",
"SLV": "SV",
"SMR": "SM",
"SOM": "SO",
"SPM": "PM",
"SRB": "RS",
"SSD": "SS",
"STP": "ST",
"SUR": "SR",
"SVK": "SK",
"SVN": "SI",
"SWE": "SE",
"SWZ": "SZ",
"SYC": "SC",
"SYR": "SY",
"TCA": "TC",
"TCD": "TD",
"TGO": "TG",
"THA": "TH",
"TJK": "TJ",
"TKL": "TK",
"TKM": "TM",
"TLS": "TL",
"TON": "TO",
"TTO": "TT",
"TUN": "TN",
"TUR": "TR",
"TUV": "TV",
"TZA": "TZ",
"UGA": "UG",
"UKR": "UA",
"UMI": "UM",
"URY": "UY",
"UZB": "UZ",
"VCT": "VC",
"VGB": "VG",
"VIR": "VI",
"VUT": "VU",
"WLF": "WF",
"WSM": "WS",
"YEM": "YE",
"ZAF": "ZA",
"ZMB": "ZM",
"ZWE": "ZW"
};
var oauth_url = "https://d2p3wisckg.execute-api.us-east-2.amazonaws.com/prod/google";
var report_url = "https://content.googleapis.com/webmasters/v3/sites/%s/searchAnalytics/query?fields=rows&alt=json";
var mainProperties = ["clicks", "impressions", "ctr", "position"];
var fetch = function (parameters, events, startDate, endDate) {
logger.debug("Fetching between " + startDate + " and " + (endDate || 'now'));
if (endDate == null) {
endDate = new Date();
endDate.setDate(endDate.getDate() - 1);
endDate = endDate.toJSON().slice(0, 10);
}
startDate = startDate || config.get('start_date');
if (startDate == null) {
startDate = new Date();
startDate.setMonth(startDate.getMonth() - 5);
startDate = startDate.toJSON().slice(0, 10);
}
if (startDate === endDate) {
logger.info("No data to process");
return;
}
var response = http.get(oauth_url)
.query('refresh_token', parameters.refresh_token)
.send();
if (response.getStatusCode() != 200) {
throw new Error(response.getResponseBody());
}
var data = response.getResponseBody();
response = http.post(report_url.replace('%s', encodeURIComponent(parameters.website_url)))
.header('Authorization', data)
.header('Content-Type', "application/json")
.data(JSON.stringify({
dimensions: ["date", "country", "device", "page", "query"],
responseAggregationType: "byPage",
rowLimit: 5000,
startDate: startDate, endDate: endDate
}))
.send();
if (response.getStatusCode() != 200) {
if (response.getStatusCode() == 404) {
throw new Error("The website " + parameters.website_url + " could not found");
}
throw new Error(response.getResponseBody())
}
var data = JSON.parse(response.getResponseBody());
var events = data.rows.map(function (row) {
var properties = {
'_time': row.keys[0] + "T00:00:00",
country: countryMapping[row.keys[1].toUpperCase()],
device: row.keys[2],
page: row.keys[3],
query: row.keys[4]
}
mainProperties.forEach(function (term) {
properties[term] = row[term];
});
return {collection: parameters.collection, properties: properties};
});
eventStore.store(events);
config.set('start_date', endDate);
}
var main = function (parameters) {
return fetch(parameters, [])
} | agpl-3.0 |
horus68/SuiteCRM | include/SugarObjects/templates/person/Person.php | 11923 | <?php
/**
*
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
*
* SuiteCRM is an extension to SugarCRM Community Edition developed by SalesAgility Ltd.
* Copyright (C) 2011 - 2017 SalesAgility Ltd.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
* reasonably feasible for technical reasons, the Appropriate Legal Notices must
* display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM".
*/
require_once 'include/SugarObjects/templates/basic/Basic.php';
class Person extends Basic
{
public $photo;
public $first_name;
public $last_name;
public $full_name;
public $salutation;
public $title;
public $email1;
public $phone_fax;
public $phone_work;
public $phone_other;
/**
* @var bool controls whether or not to invoke the getLocalFormattedName method with title and salutation
*/
public $createLocaleFormattedName = true;
/**
* @var Link2
*/
public $email_addresses;
/**
* @var SugarEmailAddress
*/
public $emailAddress;
/**
* Person constructor.
*/
public function __construct()
{
parent::__construct();
$this->emailAddress = new SugarEmailAddress();
}
/**
* @deprecated deprecated since version 7.6, PHP4 Style Constructors are deprecated and will be remove in 7.8,
* please update your code, use __construct instead
*/
public function Person()
{
$deprecatedMessage =
'PHP4 Style Constructors are deprecated and will be remove in 7.8, please update your code';
if (isset($GLOBALS['log'])) {
$GLOBALS['log']->deprecated($deprecatedMessage);
} else {
trigger_error($deprecatedMessage, E_USER_DEPRECATED);
}
self::__construct();
}
/**
* need to override to have a name field created for this class
*
* @see parent::retrieve()
*
* @param int $id
* @param bool $encode
* @param bool $deleted
*
* @return SugarBean
*/
public function retrieve($id = -1, $encode = true, $deleted = true)
{
$ret_val = parent::retrieve($id, $encode, $deleted);
$this->_create_proper_name_field();
return $ret_val;
}
/**
* Populate email address fields here instead of retrieve() so that they are properly available for logic hooks
*
* @see parent::fill_in_relationship_fields()
*/
public function fill_in_relationship_fields()
{
parent::fill_in_relationship_fields();
$this->emailAddress->handleLegacyRetrieve($this);
}
/**
* This function helps generate the name and full_name member field variables from the salutation, title,
* first_name and last_name fields. It takes into account the locale format settings as well as ACL settings if
* supported.
*/
public function _create_proper_name_field()
{
global $locale, $app_list_strings;
// Bug# 46125 - make first name, last name, salutation and title of Contacts respect field level ACLs
$salutation = '';
// first name has at least read access
$firstName = $this->first_name;
// last name has at least read access
$lastName = $this->last_name;
// salutation has at least read access
if (isset($this->field_defs['salutation']['options']) &&
isset($app_list_strings[$this->field_defs['salutation']['options']]) &&
isset($app_list_strings[$this->field_defs['salutation']['options']][$this->salutation])
) {
$salutation = $app_list_strings[$this->field_defs['salutation']['options']][$this->salutation];
} // if
// last name has at least read access
$title = $this->title;
// Corner Case:
// Both first name and last name cannot be empty, at least one must be shown
// In that case, we can ignore field level ACL and just display last name...
// In the ACL field level access settings, last_name cannot be set to "none"
if (empty($firstName) && empty($lastName)) {
$full_name = $locale->getLocaleFormattedName('', $lastName, $salutation, $title);
} else {
if ($this->createLocaleFormattedName) {
$full_name = $locale->getLocaleFormattedName($firstName, $lastName, $salutation, $title);
} else {
$full_name = $locale->getLocaleFormattedName($firstName, $lastName);
}
}
$this->name = $full_name;
$this->full_name = $full_name; //used by campaigns
}
/**
* @see parent::save()
*/
public function save($check_notify = false)
{
//If we are saving due to relationship changes, don't bother trying to update the emails
if (!empty($GLOBALS['resavingRelatedBeans'])) {
parent::save($check_notify);
return $this->id;
}
$this->add_address_streets('primary_address_street');
$this->add_address_streets('alt_address_street');
$ori_in_workflow = empty($this->in_workflow) ? false : true;
$this->emailAddress->handleLegacySave($this);
// bug #39188 - store emails state before workflow make any changes
$this->emailAddress->stash($this->id, $this->module_dir);
parent::save($check_notify);
$override_email = array();
if (!empty($this->email1_set_in_workflow)) {
$override_email['emailAddress0'] = $this->email1_set_in_workflow;
}
if (!empty($this->email2_set_in_workflow)) {
$override_email['emailAddress1'] = $this->email2_set_in_workflow;
}
if (!isset($this->in_workflow)) {
$this->in_workflow = false;
}
if ($ori_in_workflow === false || !empty($override_email)) {
$this->emailAddress->saveEmail(
$this->id,
$this->module_dir,
$override_email,
'',
'',
'',
'',
$this->in_workflow
);
}
return $this->id;
}
/**
* @see parent::get_summary_text()
*/
public function get_summary_text()
{
$this->_create_proper_name_field();
return $this->name;
}
/**
* @see parent::get_list_view_data()
*/
public function get_list_view_data()
{
global $current_user;
$this->_create_proper_name_field();
$temp_array = $this->get_list_view_array();
$temp_array['NAME'] = $this->name;
$temp_array['ENCODED_NAME'] = $this->full_name;
$temp_array['FULL_NAME'] = $this->full_name;
$temp_array['EMAIL1'] = $this->emailAddress->getPrimaryAddress($this);
$this->email1 = $temp_array['EMAIL1'];
$temp_array['EMAIL1_LINK'] = $current_user->getEmailLink('email1', $this, '', '', 'ListView');
return $temp_array;
}
/**
* @see SugarBean::populateRelatedBean()
*/
public function populateRelatedBean(
SugarBean $newBean
) {
parent::populateRelatedBean($newBean);
if ($newBean instanceOf Company) {
$newBean->phone_fax = $this->phone_fax;
$newBean->phone_office = $this->phone_work;
$newBean->phone_alternate = $this->phone_other;
$newBean->email1 = $this->email1;
$this->add_address_streets('primary_address_street');
$newBean->billing_address_street = $this->primary_address_street;
$newBean->billing_address_city = $this->primary_address_city;
$newBean->billing_address_state = $this->primary_address_state;
$newBean->billing_address_postalcode = $this->primary_address_postalcode;
$newBean->billing_address_country = $this->primary_address_country;
$this->add_address_streets('alt_address_street');
$newBean->shipping_address_street = $this->alt_address_street;
$newBean->shipping_address_city = $this->alt_address_city;
$newBean->shipping_address_state = $this->alt_address_state;
$newBean->shipping_address_postalcode = $this->alt_address_postalcode;
$newBean->shipping_address_country = $this->alt_address_country;
}
}
/**
* Default export query for Person based modules
* used to pick all mails (primary and non-primary)
*
* @see SugarBean::create_export_query()
*/
public function create_export_query($order_by, $where, $relate_link_join = '')
{
$custom_join = $this->custom_fields->getJOIN(true, true, $where);
// For easier code reading, reused plenty of time
$table = $this->table_name;
if ($custom_join) {
$custom_join['join'] .= $relate_link_join;
}
$query = "SELECT
$table.*,
email_addresses.email_address email_address,
'' email_addresses_non_primary, " .
// email_addresses_non_primary needed for get_field_order_mapping()
'users.user_name as assigned_user_name ';
if ($custom_join) {
$query .= $custom_join['select'];
}
$query .= " FROM $table ";
$query .= "LEFT JOIN users
ON $table.assigned_user_id=users.id ";
//Join email address table too.
$query .= " LEFT JOIN email_addr_bean_rel on $table.id = email_addr_bean_rel.bean_id and email_addr_bean_rel.bean_module = '" .
$this->module_dir .
"' and email_addr_bean_rel.deleted = 0 and email_addr_bean_rel.primary_address = 1";
$query .= ' LEFT JOIN email_addresses on email_addresses.id = email_addr_bean_rel.email_address_id ';
if ($custom_join) {
$query .= $custom_join['join'];
}
$where_auto = " $table.deleted=0 ";
if ($where != '') {
$query .= "WHERE ($where) AND " . $where_auto;
} else {
$query .= 'WHERE ' . $where_auto;
}
$order_by = $this->process_order_by($order_by);
if (!empty($order_by)) {
$query .= ' ORDER BY ' . $order_by;
}
return $query;
}
}
| agpl-3.0 |
p-acs/ethereum-secure-proxy | src/main/java/de/petendi/ethereum/secure/proxy/Application.java | 6533 | package de.petendi.ethereum.secure.proxy;
/*-
* #%L
* Ethereum Secure Proxy
* %%
* Copyright (C) 2016 P-ACS UG (haftungsbeschränkt)
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
import com.googlecode.jsonrpc4j.JsonRpcHttpClient;
import de.petendi.seccoco.InitializationException;
import de.petendi.seccoco.Seccoco;
import de.petendi.seccoco.SeccocoFactory;
import de.petendi.seccoco.argument.ArgumentList;
import org.kohsuke.args4j.CmdLineException;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableScheduling;
import java.io.Console;
import java.io.File;
import java.io.PrintStream;
import java.net.URL;
import java.util.HashMap;
import java.util.StringTokenizer;
@Configuration
@ComponentScan({"de.petendi.ethereum.secure.proxy.controller"})
@EnableAutoConfiguration
@EnableScheduling
public class Application {
private static Seccoco seccoco = null;
private static JsonRpcHttpClient jsonRpcHttpClient = null;
private static CmdLineResult cmdLineResult;
private static Settings settings;
public static void main(String[] args) {
try {
cmdLineResult = new CmdLineResult();
cmdLineResult.parseArguments(args);
} catch (CmdLineException e) {
System.out.println(e.getMessage());
System.out.println("Usage:");
cmdLineResult.printExample();
System.exit(-1);
return;
}
File workingDirectory = new File(System.getProperty("user.home"));
if (cmdLineResult.getWorkingDirectory().length() > 0) {
workingDirectory = new File(cmdLineResult.getWorkingDirectory()).getAbsoluteFile();
}
ArgumentList argumentList = new ArgumentList();
argumentList.setWorkingDirectory(workingDirectory);
File certificate = new File(workingDirectory, "seccoco-secured/cert.p12");
if (certificate.exists()) {
char[] passwd = null;
if (cmdLineResult.getPassword() != null) {
System.out.println("Using password from commandline argument - DON'T DO THIS IN PRODUCTION !!");
passwd = cmdLineResult.getPassword().toCharArray();
} else {
Console console = System.console();
if (console != null) {
passwd = console.readPassword("[%s]", "Enter application password:");
} else {
System.out.print("No suitable console found for entering password");
System.exit(-1);
}
}
argumentList.setTokenPassword(passwd);
}
try {
SeccocoFactory seccocoFactory = new SeccocoFactory("seccoco-secured", argumentList);
seccoco = seccocoFactory.create();
} catch (InitializationException e) {
System.out.println(e.getMessage());
System.exit(-1);
}
try {
System.out.println("Connecting to Ethereum RPC at " + cmdLineResult.getUrl());
URL url = new URL(cmdLineResult.getUrl());
HashMap<String,String> headers = new HashMap<String,String>();
headers.put("Content-Type","application/json");
String additionalHeaders = cmdLineResult.getAdditionalHeaders();
if(additionalHeaders != null) {
StringTokenizer tokenizer = new StringTokenizer(additionalHeaders,",");
while(tokenizer.hasMoreTokens()) {
String keyValue = tokenizer.nextToken();
StringTokenizer innerTokenizer = new StringTokenizer(keyValue,":");
headers.put(innerTokenizer.nextToken(),innerTokenizer.nextToken());
}
}
settings = new Settings(cmdLineResult.isExposeWhisper(),headers);
jsonRpcHttpClient = new JsonRpcHttpClient(url);
jsonRpcHttpClient.setRequestListener(new JsonRpcRequestListener());
jsonRpcHttpClient.invoke("eth_protocolVersion", null,Object.class,headers);
if (cmdLineResult.isExposeWhisper()) {
jsonRpcHttpClient.invoke("shh_version", null, Object.class, headers);
}
System.out.println("Connection succeeded");
} catch (Throwable e) {
System.out.println("Connection failed: " + e.getMessage());
System.exit(-1);
}
SpringApplication app = new SpringApplication(Application.class);
app.setBanner(new Banner() {
@Override
public void printBanner(Environment environment, Class<?> aClass, PrintStream printStream) {
//send the Spring Boot banner to /dev/null
}
});
app.run(new String[]{});
}
@Bean
public Seccoco seccoco() {
return seccoco;
}
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.setPort(cmdLineResult.getPort());
}
};
}
@Bean
public JsonRpcHttpClient rpcClient() throws Throwable {
return jsonRpcHttpClient;
}
@Bean
public Settings settings() {
return settings;
}
}
| agpl-3.0 |
usu/ecamp3 | backend/module/eCampCore/test/Data/ActivityTypeTestData.php | 1223 | <?php
namespace eCamp\CoreTest\Data;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use Doctrine\Persistence\ObjectManager;
use eCamp\Core\Entity\ActivityType;
use eCamp\Core\Entity\ActivityTypeContentType;
class ActivityTypeTestData extends AbstractFixture implements DependentFixtureInterface {
public static $TYPE1 = ActivityType::class.':TYPE1';
public function load(ObjectManager $manager) {
$activityType = new ActivityType();
$activityType->setName('ActivityType1');
$activityType->setDefaultColor('#FF00FF');
$activityType->setDefaultNumberingStyle('i');
$contentType = $this->getReference(ContentTypeTestData::$TYPE1);
$activityTypeContentType = new ActivityTypeContentType();
$activityTypeContentType->setActivityType($activityType);
$activityTypeContentType->setContentType($contentType);
$manager->persist($activityType);
$manager->persist($activityTypeContentType);
$manager->flush();
$this->addReference(self::$TYPE1, $activityType);
}
public function getDependencies() {
return [ContentTypeTestData::class];
}
}
| agpl-3.0 |
o2oa/o2oa | o2server/x_processplatform_assemble_designer/src/main/java/com/x/processplatform/assemble/designer/jaxrs/projection/BaseAction.java | 6190 | //package com.x.processplatform.assemble.designer.jaxrs.projection;
//
//import java.util.Objects;
//
//import org.apache.commons.lang3.StringUtils;
//
//import com.x.base.core.project.exception.ExceptionEntityFieldEmpty;
//import com.x.base.core.project.exception.ExceptionUnknowValue;
//import com.x.base.core.project.jaxrs.StandardJaxrsAction;
//import com.x.processplatform.assemble.designer.Business;
//import com.x.processplatform.core.entity.element.Projection;
//
//abstract class BaseAction extends StandardJaxrsAction {
//
// protected void empty(Projection projection) throws Exception {
//
// if (StringUtils.isEmpty(projection.getName())) {
// throw new ExceptionEntityFieldEmpty(Projection.class, Projection.name_FIELDNAME);
// }
//
// if (StringUtils.isEmpty(projection.getType())) {
// throw new ExceptionEntityFieldEmpty(Projection.class, Projection.type_FIELDNAME);
// }
//
// if (StringUtils.isEmpty(projection.getData())) {
// throw new ExceptionEntityFieldEmpty(Projection.class, Projection.data_FIELDNAME);
// }
// }
//
// protected void duplicate(Business business, Projection projection) throws Exception {
// if (this.duplicateName(business, projection)) {
// throw new ExceptionDuplicateName();
// }
// switch (Objects.toString(projection.getType())) {
// case Projection.TYPE_WORK:
// if (this.duplicateWork(business, projection)) {
// throw new ExceptionDuplicateWork();
// }
// break;
// case Projection.TYPE_WORKCOMPLETED:
// if (this.duplicateWorkCompleted(business, projection)) {
// throw new ExceptionDuplicateWorkCompleted();
// }
// break;
// case Projection.TYPE_TASK:
// if (this.duplicateTask(business, projection)) {
// throw new ExceptionDuplicateTask();
// }
// break;
// case Projection.TYPE_TASKCOMPLETED:
// if (this.duplicateTaskCompleted(business, projection)) {
// throw new ExceptionDuplicateTaskCompleted();
// }
// break;
// case Projection.TYPE_READ:
// if (this.duplicateRead(business, projection)) {
// throw new ExceptionDuplicateRead();
// }
// break;
// case Projection.TYPE_READCOMPLETED:
// if (this.duplicateReadCompleted(business, projection)) {
// throw new ExceptionDuplicateReadCompleted();
// }
// break;
// case Projection.TYPE_REVIEW:
// if (this.duplicateReview(business, projection)) {
// throw new ExceptionDuplicateReview();
// }
// break;
// default:
// throw new ExceptionUnknowValue(projection.getType());
// }
// }
//
// private boolean duplicateName(Business business, Projection projection) throws Exception {
// Long count = business.entityManagerContainer().countEqualAndEqualAndNotEqual(Projection.class,
// Projection.application_FIELDNAME, projection.getApplication(), Projection.name_FIELDNAME,
// projection.getName(), Projection.id_FIELDNAME, projection.getId());
// return count != 0;
// }
//
// private boolean duplicateWork(Business business, Projection projection) throws Exception {
// Long count = business.entityManagerContainer().countEqualAndEqualAndEqualAndNotEqual(Projection.class,
// Projection.application_FIELDNAME, projection.getApplication(), Projection.process_FIELDNAME,
// projection.getProcess(), Projection.type_FIELDNAME, Projection.TYPE_WORK, Projection.id_FIELDNAME,
// projection.getId());
// return count != 0;
// }
//
// private boolean duplicateWorkCompleted(Business business, Projection projection) throws Exception {
// Long count = business.entityManagerContainer().countEqualAndEqualAndEqualAndNotEqual(Projection.class,
// Projection.application_FIELDNAME, projection.getApplication(), Projection.process_FIELDNAME,
// projection.getProcess(), Projection.type_FIELDNAME, Projection.TYPE_WORKCOMPLETED,
// Projection.id_FIELDNAME, projection.getId());
// return count != 0;
// }
//
// private boolean duplicateTask(Business business, Projection projection) throws Exception {
// Long count = business.entityManagerContainer().countEqualAndEqualAndEqualAndNotEqual(Projection.class,
// Projection.application_FIELDNAME, projection.getApplication(), Projection.process_FIELDNAME,
// projection.getProcess(), Projection.type_FIELDNAME, Projection.TYPE_TASKCOMPLETED,
// Projection.id_FIELDNAME, projection.getId());
// return count != 0;
// }
//
// private boolean duplicateTaskCompleted(Business business, Projection projection) throws Exception {
// Long count = business.entityManagerContainer().countEqualAndEqualAndEqualAndNotEqual(Projection.class,
// Projection.application_FIELDNAME, projection.getApplication(), Projection.process_FIELDNAME,
// projection.getProcess(), Projection.type_FIELDNAME, Projection.TYPE_TASKCOMPLETED,
// Projection.id_FIELDNAME, projection.getId());
// return count != 0;
// }
//
// private boolean duplicateRead(Business business, Projection projection) throws Exception {
// Long count = business.entityManagerContainer().countEqualAndEqualAndEqualAndNotEqual(Projection.class,
// Projection.application_FIELDNAME, projection.getApplication(), Projection.process_FIELDNAME,
// projection.getProcess(), Projection.type_FIELDNAME, Projection.TYPE_READ, Projection.id_FIELDNAME,
// projection.getId());
// return count != 0;
// }
//
// private boolean duplicateReadCompleted(Business business, Projection projection) throws Exception {
// Long count = business.entityManagerContainer().countEqualAndEqualAndEqualAndNotEqual(Projection.class,
// Projection.application_FIELDNAME, projection.getApplication(), Projection.process_FIELDNAME,
// projection.getProcess(), Projection.type_FIELDNAME, Projection.TYPE_READCOMPLETED,
// Projection.id_FIELDNAME, projection.getId());
// return count != 0;
// }
//
// private boolean duplicateReview(Business business, Projection projection) throws Exception {
// Long count = business.entityManagerContainer().countEqualAndEqualAndEqualAndNotEqual(Projection.class,
// Projection.application_FIELDNAME, projection.getApplication(), Projection.process_FIELDNAME,
// projection.getProcess(), Projection.type_FIELDNAME, Projection.TYPE_REVIEW, Projection.id_FIELDNAME,
// projection.getId());
// return count != 0;
// }
//
//}
| agpl-3.0 |
Trustroots/trustroots | modules/offers/client/services/offers-by.client.service.js | 431 | // OffersBy service used for communicating with the offers REST endpoints
// Read offers by userId
// Accepts also `type` parameter
angular.module('offers').factory('OffersByService', OffersByService);
/* @ngInject */
function OffersByService($resource) {
return $resource(
'/api/offers-by/:userId',
{
userId: '@id',
},
{
query: {
method: 'GET',
isArray: true,
},
},
);
}
| agpl-3.0 |
PaloAlto/jbilling | classes/com/sapienter/jbilling/server/pluggableTask/PaymentTaskWithTimeout.java | 1925 | /*
jBilling - The Enterprise Open Source Billing System
Copyright (C) 2003-2009 Enterprise jBilling Software Ltd. and Emiliano Conde
This file is part of jbilling.
jbilling is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
jbilling is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with jbilling. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sapienter.jbilling.server.pluggableTask;
import com.sapienter.jbilling.server.pluggableTask.admin.PluggableTaskDTO;
import com.sapienter.jbilling.server.pluggableTask.admin.PluggableTaskException;
public abstract class PaymentTaskWithTimeout extends PaymentTaskBase {
public static final String PARAM_TIMEOUT_SECONDS = "timeout_sec";
private int myTimeout;
@Override
public void initializeParamters(PluggableTaskDTO task)
throws PluggableTaskException {
super.initializeParamters(task);
String timeoutText = getOptionalParameter(PARAM_TIMEOUT_SECONDS, "10");
try {
myTimeout = Integer.parseInt(timeoutText);
} catch (NumberFormatException e){
throw new PluggableTaskException("" //
+ "Integer expected for parameter: " + PARAM_TIMEOUT_SECONDS //
+ ", actual: " + timeoutText);
}
}
protected int getTimeoutSeconds() {
return myTimeout;
}
}
| agpl-3.0 |
cheery/pyllisp | bincode/common.py | 147 | hexcode = lambda s: s.replace(" ", "").decode('hex')
# Encoder produces this code, decoder reads it.
header = hexcode("89 4C 49 43 0D 0A 1A 0A")
| agpl-3.0 |
RipcordSoftware/AvanceDB | src/avancedb/rest_exceptions.cpp | 5510 | /*
* AvanceDB - an in-memory database similar to Apache CouchDB
* Copyright (C) 2015-2017 Ripcord Software
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "rest_exceptions.h"
#include <boost/format.hpp>
#include "json_helper.h"
static const char* preconditionFailedDescription = "Precondition Failed";
static const char* badRequestDescription = "Bad Request";
static const char* notFoundDescription = "Not Found";
static const char* conflictDescription = "Conflict";
static const char* forbiddenDescription = "Forbidden";
static const char* requestedRangeErrorDescription = "Requested Range Not Satisfiable";
static const char* internalServerErrorDescription = "Internal Server Error";
static const char* databaseAlreadyExistsBody = R"({
"error": "file_exists",
"reason": "The database could not be created, the file already exists."
})";
static const char* invalidDatabaseNameBody = R"({
"error": "illegal_database_name",
"reason": "Only lowercase characters (a-z), digits (0-9), and any of the characters _, $, (, ), +, -, and / are allowed. Must begin with a letter."
})";
static const char* missingDatabaseBody = R"({
"error": "not_found",
"reason": "missing"
})";
static const char* invalidJsonBody = R"({
"error":"bad_request",
"reason":"invalid_json"
})";
static const char* documentConflictJsonBody = R"({
"error":"conflict",
"reason":"Document update conflict."
})";
static const char* missingDocumentJsonBody = R"({
"error": "not_found",
"reason": "missing"
})";
static const char* missingDocumentAttachmentJsonBody = R"({
"error": "not_found",
"reason": "Document is missing attachment"
})";
static const char* uuidCountLimitJsonBody = R"({
"error": "forbidden",
"reason": "count parameter too large"
})";
static const char* queryParseErrorJsonBody = R"({
"error": "query_parse_error",
"reason": "Invalid value for %s: \"%s\""
})";
static const char* invalidRevisionFormatJsonBody = R"({
"error": "bad_request",
"reason": "Invalid rev format"
})";
static const char* compilationErrorJsonBody = R"({
"error": "compilation_error",
"reason": "%s"
})";
static const char* badLanguageErrorJsonBody = R"({
"error": "EXIT",
"reason": "%s is not a supported map/reduce language"
})";
static const char* requestedRangeErrorJsonBody = R"({
"error": "requested_range_not_satisfiable",
"reason": "Requested range not satisfiable"
})";
static const char* contentType = "application/json";
DatabaseAlreadyExists::DatabaseAlreadyExists() :
HttpServerException(412, preconditionFailedDescription, databaseAlreadyExistsBody, contentType) {
}
InvalidDatabaseName::InvalidDatabaseName() :
HttpServerException(400, badRequestDescription, invalidDatabaseNameBody, contentType) {
}
MissingDatabase::MissingDatabase() :
HttpServerException(404, notFoundDescription, missingDatabaseBody, contentType) {
}
InvalidJson::InvalidJson() :
HttpServerException(400, badRequestDescription, invalidJsonBody, contentType) {
}
InvalidMsgPack::InvalidMsgPack() :
HttpServerException(400, badRequestDescription, invalidJsonBody, contentType) {
}
DocumentConflict::DocumentConflict() :
HttpServerException(409, conflictDescription, documentConflictJsonBody, contentType) {
}
DocumentMissing::DocumentMissing() :
HttpServerException(404, notFoundDescription, missingDocumentJsonBody, contentType) {
}
DocumentAttachmentMissing::DocumentAttachmentMissing() :
HttpServerException(404, notFoundDescription, missingDocumentAttachmentJsonBody, contentType) {
}
UuidCountLimit::UuidCountLimit() :
HttpServerException(403, forbiddenDescription, uuidCountLimitJsonBody, contentType) {
}
QueryParseError::QueryParseError(const char* type, const std::string& value) :
HttpServerException(400, badRequestDescription, (boost::format(queryParseErrorJsonBody) % type % value).str(), contentType) {
}
InvalidRevisionFormat::InvalidRevisionFormat() :
HttpServerException(400, badRequestDescription, invalidRevisionFormatJsonBody, contentType) {
}
CompilationError::CompilationError(const char* msg) :
HttpServerException(500, internalServerErrorDescription, (boost::format(compilationErrorJsonBody) % JsonHelper::EscapeJsonString(msg)).str(), contentType) {
}
BadLanguageError::BadLanguageError(const char* msg) :
HttpServerException(500, internalServerErrorDescription, (boost::format(badLanguageErrorJsonBody) % JsonHelper::EscapeJsonString(msg)).str(), contentType) {
}
BadRangeError::BadRangeError() :
HttpServerException(416, requestedRangeErrorDescription, requestedRangeErrorJsonBody, contentType) {
}
BadRequestBodyError::BadRequestBodyError() :
HttpServerException(400, badRequestDescription, std::string{}, contentType) {
} | agpl-3.0 |
Tatwi/legend-of-hondo | MMOCoreORB/src/server/zone/objects/tangible/tool/recycle/RecycleToolImplementation.cpp | 3371 |
#include "engine/engine.h"
#include "server/zone/objects/tangible/tool/recycle/RecycleTool.h"
#include "server/zone/Zone.h"
#include "server/zone/objects/tangible/Container.h"
#include "server/zone/objects/tangible/TangibleObject.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/objects/player/PlayerObject.h"
#include "templates/tangible/tool/RecycleToolTemplate.h"
#include "server/zone/packets/object/ObjectMenuResponse.h"
void RecycleToolImplementation::initializeTransientMembers() {
ContainerImplementation::initializeTransientMembers();
setLoggingName("RecycleTool");
}
void RecycleToolImplementation::loadTemplateData(SharedObjectTemplate* templateData) {
ContainerImplementation::loadTemplateData(templateData);
RecycleToolTemplate* recycleToolData = dynamic_cast<RecycleToolTemplate*>(templateData);
if (recycleToolData == NULL) {
throw Exception("invalid template for RecycleTool");
}
toolType = recycleToolData->getToolType();
}
void RecycleToolImplementation::fillObjectMenuResponse(ObjectMenuResponse* menuResponse, CreatureObject* player) {
ContainerImplementation::fillObjectMenuResponse(menuResponse, player);
menuResponse->addRadialMenuItem(245, 3, "@recycler_messages:choose_type");
String stub = "@recycler_messages:";
SharedObjectTemplate* templateData = TemplateManager::instance()->getTemplate(_this.getReferenceUnsafeStaticCast()->getServerObjectCRC());
if (templateData == NULL) {
error("No template data for: " + String::valueOf(_this.getReferenceUnsafeStaticCast()->getServerObjectCRC()));
return;
}
RecycleToolTemplate* recycleToolData = dynamic_cast<RecycleToolTemplate*>(templateData);
if (recycleToolData == NULL) {
error("No RecycleToolTemplate for: " + String::valueOf(_this.getReferenceUnsafeStaticCast()->getServerObjectCRC()));
return;
}
Vector<String> resourceTypes = recycleToolData->getResourceTypes();
for (int i = 0; i < resourceTypes.size(); i++) {
menuResponse->addRadialMenuItemToRadialID(245, 246 + i, 3, stub + resourceTypes.get(i));
}
}
int RecycleToolImplementation::handleObjectMenuSelect(CreatureObject* player, byte selectedID) {
if (isASubChildOf(player)) {
SharedObjectTemplate* templateData = TemplateManager::instance()->getTemplate(_this.getReferenceUnsafeStaticCast()->getServerObjectCRC());
if (templateData == NULL || !templateData->isRecycleToolTemplate())
return 1;
RecycleToolTemplate* recycleToolData = dynamic_cast<RecycleToolTemplate*>(templateData);
Vector<String> resourceTypes = recycleToolData->getResourceTypes();
switch (selectedID) {
case 245:
break;
case 246:
setSelectedResource(toolType + 1);
setSelectedTypeName(resourceTypes.get(0));
break;
case 247:
setSelectedResource(toolType + 2);
setSelectedTypeName(resourceTypes.get(1));
break;
case 248:
setSelectedResource(toolType + 3);
setSelectedTypeName(resourceTypes.get(2));
break;
case 249:
setSelectedResource(toolType + 4);
setSelectedTypeName(resourceTypes.get(3));
break;
case 250:
setSelectedResource(toolType + 5);
setSelectedTypeName(resourceTypes.get(4));
break;
case 251:
setSelectedResource(toolType + 6);
setSelectedTypeName(resourceTypes.get(5));
break;
}
return 0;
}
return TangibleObjectImplementation::handleObjectMenuSelect(player, selectedID);
}
| agpl-3.0 |
qcri-social/AIDR | aidr-manager/src/main/webapp/resources/js/taggui/tagger-collection-details/controller/TaggerCollectionDetailsController.js | 65293 | Ext.define('TAGGUI.tagger-collection-details.controller.TaggerCollectionDetailsController', {
extend: 'Ext.app.Controller',
views: [
'TaggerCollectionDetailsPanel'
],
init: function () {
this.control({
'tagger-collection-details-view': {
beforerender: this.beforeRenderView
},
"#crisisDelete": {
click: function (btn, e, eOpts) {
this.crisisDelete();
}
},
"#crisisSave": {
click: function (btn, e, eOpts) {
this.crisisSave();
}
},
"#goToCollector": {
click: function (btn, e, eOpts) {
this.goToCollector();
}
},
"#generateCSVLink": {
click: function (btn, e, eOpts) {
this.generateCSVLinkButtonHandler(btn);
}
},
"#generateTweetIdsLink": {
click: function (btn, e, eOpts) {
this.generateTweetIdsLinkButtonHandler(btn);
}
} ,
"#generateJSONLink": {
click: function (btn, e, eOpts) {
this.generateJSONLinkButtonHandler(btn);
}
},
"#generateJsonTweetIdsLink": {
click: function (btn, e, eOpts) {
this.generateJsonTweetIdsLinkButtonHandler(btn);
}
} ,
"#pybossaClassifierFilters":{
change: function(field, newValue, oldValue, eOpts) {
var me = this;
var attID = me.mainComponent.classifierComboForPybossaApp.getValue();
me.mainComponent.uiWelcomeSaveButton.show();
me.mainComponent.uiTutorialOneSaveButton.show();
me.mainComponent.uiTutorialTwoSaveButton.show();
me.getUITemplateWithAttributeID(attID);
}
},
"#templateSave":{
click: function (btn, e, eOpts) {
this.templateUISave();
}
},
"#uiTypeFilters":{
change: function(field, newValue, oldValue, eOpts) {
var me = this;
//type == '1' || type == '2' || type == '6'
if(field.value == '' || field.value == '1' || field.value == '2' || field.value == '6'){
me.mainComponent.classifierCombo.hide();
}
else{
me.mainComponent.classifierCombo.show();
}
if(field.value == ''){
me.mainComponent.templateSaveButton.hide();
}
else{
var attID = me.mainComponent.classifierCombo.getValue();
if(attID == ''){
me.mainComponent.templateSaveButton.hide();
}
else{
me.mainComponent.templateSaveButton.show();
}
}
if(field.value == '1'){
this.getUITemplate();
}
else{
var attID = me.mainComponent.classifierCombo.getValue();
if(field.value != '' && field.value != '1' && attID !=''){
this.getUITemplate();
}
else{
me.mainComponent.uiTemplate.setValue('', false);
me.mainComponent.classifierCombo.refresh();
}
}
}
},
"#classifierFilters":{
change: function(field, newValue, oldValue, eOpts) {
var me = this;
me.mainComponent.templateSaveButton.show();
if(field.value != ''){
this.getUITemplate();
}
else{
me.mainComponent.uiTemplate.setValue('', false);
}
}
},
"#uiSkinTypeSave":{
click: function (btn, e, eOpts) {
this.templateSkinTypeSave();
}
},
"#landingTopSave":{
click: function (btn, e, eOpts) {
var me = this;
var attID = 0;
var type = 1;
var templateContent = me.mainComponent.uiLandingTemplateOne.getValue();
this.templateUIUpdateSave(0, 1, templateContent, 'Saving landing page 1 ...');
}
},
"#landingBtnSave":{
click: function (btn, e, eOpts) {
var me = this;
var attID = 0;
var type = 2;
var templateContent = me.mainComponent.uiLandingTemplateTwo.getValue();
this.templateUIUpdateSave(0, type, templateContent, 'Saving landing page 2 ...');
}
},
"#curatorSave":{
click: function (btn, e, eOpts) {
var me = this;
var attID = 0;
var type = 6;
var templateContent = me.mainComponent.curatorInfo.getValue();
this.templateUIUpdateSave(0, type, templateContent, 'Saving Curator information ...');
}
//curatorInfo
},
"#uiWelcomeSave":{
click: function (btn, e, eOpts) {
var me = this;
var attID = me.mainComponent.classifierComboForPybossaApp.getValue();
var type = 3;
var templateContent = me.mainComponent.welcomePageUI.getValue();
this.templateUIUpdateSave(attID, type, templateContent, 'Saving MicroMappers welcome page ...');
}
},
"#uiTutorialOneSave":{
click: function (btn, e, eOpts) {
var me = this;
var attID = me.mainComponent.classifierComboForPybossaApp.getValue();
var type = 4;
var templateContent = me.mainComponent.tutorial1UI.getValue();
this.templateUIUpdateSave(attID, type, templateContent, 'Saving Tutorial Page 1 ...');
}
},
"#uiTutorialTwoSave":{
click: function (btn, e, eOpts) {
var me = this;
var attID = me.mainComponent.classifierComboForPybossaApp.getValue();
var type = 5;
var templateContent = me.mainComponent.tutorial2UI.getValue();
this.templateUIUpdateSave(attID, type, templateContent, 'Saving Tutorial Page 2 ...');
}
},
"#enableMicroMappersBtn":{
click: function (btn, e, eOpts) {
this.enableMicroMappers(btn);
}
},
"#disableMicroMappersBtn":{
click: function (btn, e, eOpts) {
this.disableMicroMappers(btn);
}
}
});
},
updateUITemplateDisplayComponent: function(sVar){
var me = this;
me.mainComponent.uiTemplate.setValue(sVar, false);
me.mainComponent.uiTemplate.setReadOnly(true);
me.mainComponent.templateSaveButton.setText('Edit',false);
},
beforeRenderView: function (component, eOpts) {
AIDRFMFunctions.initMessageContainer();
this.mainComponent = component;
taggerCollectionDetailsController = this;
this.getTemplateStatus();
this.loadUITemplate();
var me = this;
this.changeMicroMappersUI();
},
crisisDelete: function () {
Ext.MessageBox.confirm('Confirm Crisis Delete', 'Do you want to delete <b>"' + CRISIS_NAME + '"</b>?',
function (buttonId) {
if (buttonId === 'yes') {
AIDRFMFunctions.setAlert("Ok", 'Will be implemented later');
}
});
},
crisisSave: function () {
var me = this;
var crisisTypeId = me.mainComponent.crysisTypesCombo.getValue();
var crisisTypeName = me.mainComponent.crisisTypesStore.findRecord("crisisTypeId", crisisTypeId).data.name;
Ext.Ajax.request({
url: BASE_URL + '/protected/tagger/updateCrisis.action',
method: 'POST',
params: {
code: CRISIS_CODE,
crisisID: CRISIS_ID,
crisisTypeID: crisisTypeId,
crisisTypeName: Ext.String.trim( crisisTypeName )
},
headers: {
'Accept': 'application/json'
},
success: function (resp) {
var response = Ext.decode(resp.responseText);
if (response.success) {
me.mainComponent.saveButton.hide();
CRISIS_TYPE_ID = crisisTypeId;
} else {
AIDRFMFunctions.setAlert("Error", 'Error while saving crisis.');
AIDRFMFunctions.reportIssue(resp);
}
}
});
},
templateUISave:function(){
var me = this;
var btnText = me.mainComponent.templateSaveButton.text;
if(btnText == 'Edit'){
me.mainComponent.uiTemplate.setReadOnly(false);
me.mainComponent.templateSaveButton.setText('Save',false);
}
else{
var templateContent = me.mainComponent.uiTemplate.getValue();
var attID = me.mainComponent.classifierCombo.getValue();
var noCustomizationRequired = false;
var status = true;
if(!noCustomizationRequired) {
Ext.getBody().mask('Saving attribute ...');
Ext.Ajax.request({
url: BASE_URL + '/protected/uitemplate/updateTemplate.action',
method: 'POST',
params: {
crisisID: CRISIS_ID,
nominalAttributeID: attID,
templateType: type,
templateValue: Ext.String.trim( templateContent ),
isActive: status
},
headers: {
'Accept': 'application/json'
},
success: function (resp) {
var response = Ext.decode(resp.responseText);
if (response.success) {
me.mainComponent.uiTemplate.setReadOnly(true);
me.mainComponent.templateSaveButton.setText('Edit',false);
} else {
AIDRFMFunctions.setAlert("Error", 'Error while updating templateSave.');
AIDRFMFunctions.reportIssue(resp);
}
Ext.getBody().unmask();
}
,
failure: function () {
Ext.getBody().unmask();
}
});
}
}
},
templateSkinTypeSave:function(){
var me = this;
//me.mainComponent.optionRG.items.items[
Ext.getBody().mask('Saving custom skin ...');
var value = me.mainComponent.optionRG.getChecked();
Ext.Ajax.request({
url: BASE_URL + '/protected/uitemplate/updateTemplate.action',
method: 'POST',
params: {
crisisID: CRISIS_ID,
nominalAttributeID: 0,
templateType: 7,
templateValue: value[0].inputValue,
isActive: true
},
headers: {
'Accept': 'application/json'
},
success: function (resp) {
var response = Ext.decode(resp.responseText);
if (response.success) {
} else {
AIDRFMFunctions.setAlert("Error", 'Error while updating templateSave.');
AIDRFMFunctions.reportIssue(resp);
}
var run = function (delay) {
Ext.create('Ext.util.DelayedTask', function () {
// console.log('run');
run(delay);
Ext.getBody().unmask();
}).delay(delay);
};
run(2000);
},
failure: function () {
Ext.getBody().unmask();
}
});
},
templateUIUpdateSave:function(attID, type, templateContent, maskText){
var me = this;
var status = true;
Ext.getBody().mask(maskText);
Ext.Ajax.request({
url: BASE_URL + '/protected/uitemplate/updateTemplate.action',
method: 'POST',
params: {
crisisID: CRISIS_ID,
nominalAttributeID: attID,
templateType: type,
templateValue: Ext.String.trim( templateContent ),
isActive: status
},
headers: {
'Accept': 'application/json'
},
success: function (resp) {
var response = Ext.decode(resp.responseText);
if (response.success) {
me.mainComponent.uiTemplate.setReadOnly(true);
me.mainComponent.templateSaveButton.setText('Edit',false);
} else {
Ext.getBody().unmask();
AIDRFMFunctions.setAlert("Error", 'Requst failed : ' + maskText );
AIDRFMFunctions.reportIssue(resp);
}
//mask.hide();
// AIDRFMFunctions.setAlert("Info", mask);
var run = function (delay) {
Ext.create('Ext.util.DelayedTask', function () {
// console.log('run');
run(delay);
Ext.getBody().unmask();
}).delay(delay);
};
run(2000);
},
failure: function (resp) {
Ext.getBody().unmask();
maskText = " Requst failed : " + maskText ;
AIDRFMFunctions.setAlert("Error", maskText);
AIDRFMFunctions.reportIssue(resp);
}
});
},
goToCollector: function() {
document.location.href = BASE_URL + '/protected/' + CRISIS_CODE +'/collection-details';
},
enableMicroMappers:function(btn) {
var me = this;
Ext.Ajax.request({
url: BASE_URL + '/protected/tagger/updateMicromapperEnabled.action',
method: 'POST',
params: {
code: CRISIS_CODE,
isMicromapperEnabled: true
},
headers: {
'Accept': 'application/json'
},
success: function (resp) {
var response = Ext.decode(resp.responseText);
if (response.success) {
IS_MICROMAPPER_ENABLED = true;
me.changeMicroMappersUI();
btn.hide();
} else {
btn.show();
AIDRFMFunctions.setAlert("Error", 'Error while enabling MicroMappers');
AIDRFMFunctions.reportIssue(resp);
}
}
});
},
disableMicroMappers: function(btn) {
var me = this;
Ext.Ajax.request({
url: BASE_URL + '/protected/tagger/updateMicromapperEnabled.action',
method: 'POST',
params: {
code: CRISIS_CODE,
isMicromapperEnabled: false
},
headers: {
'Accept': 'application/json'
},
success: function (resp) {
var response = Ext.decode(resp.responseText);
if (response.success) {
IS_MICROMAPPER_ENABLED = false;
me.changeMicroMappersUI();
btn.hide();
} else {
btn.show();
AIDRFMFunctions.setAlert("Error", 'Error while disabling MicroMappers');
AIDRFMFunctions.reportIssue(resp);
}
}
});
},
changeMicroMappersUI:function() {
var me = this;
if(IS_MICROMAPPER_ENABLED == true){
me.mainComponent.microMappersUI.hide();
me.mainComponent.disableMicroMappersButton.show();
me.mainComponent.enableMicroMappersButton.hide();
me.mainComponent.socialPublicLinkContainer.show();
me.mainComponent.pyBossaLink.show();
me.mainComponent.horizontalLineContainer.show();
me.mainComponent.UIBlock.show();
}
else{
me.mainComponent.disableMicroMappersButton.hide();
me.mainComponent.socialPublicLinkContainer.hide();
me.mainComponent.pyBossaLink.hide();
me.mainComponent.horizontalLineContainer.hide();
me.mainComponent.UIBlock.hide();
me.mainComponent.enableMicroMappersButton.show();
me.mainComponent.microMappersUI.show();
}
},
addNewClassifier: function() {
document.location.href = BASE_URL + "/protected/" + CRISIS_CODE + '/predict-new-attribute';
},
removeClassifierHandler: function (modelFamilyID, attributeName) {
var me = this;
Ext.MessageBox.confirm('Confirm Remove Tag', 'Do you want to remove tag <b>"' + attributeName + '"</b>?',
function (buttonId) {
if (buttonId === 'yes') {
me.removeClassifier(modelFamilyID);
}
}
);
},
removeClassifier: function (modelFamilyID) {
var me = this;
var removeClassifierButton = document.getElementById("removeClassifierBtn_" + modelFamilyID);
removeClassifierButton.disabled = true;
removeClassifierButton.classList.add("disabled");
Ext.Ajax.request({
url: BASE_URL + '/protected/tagger/removeAttributeFromCrises.action',
method: 'GET',
params: {
id: modelFamilyID
},
headers: {
'Accept': 'application/json'
},
success: function (response) {
var resp = Ext.decode(response.responseText);
if (resp.success) {
AIDRFMFunctions.setAlert("Ok", "Tag was removed successfully.");
me.mainComponent.crisisModelsStore.load();
} else {
AIDRFMFunctions.setAlert("Error", resp.message);
removeClassifierButton.disabled = false;
removeClassifierButton.classList.remove("disabled");
AIDRFMFunctions.reportIssue(response);
}
},
failure: function () {
removeClassifierButton.disabled = false;
removeClassifierButton.classList.remove("disabled");
}
});
},
getTemplateStatus: function() {
var me = this;
Ext.Ajax.request({
url: BASE_URL + '/protected/tagger/getTemplateStatus.action',
method: 'GET',
params: {
code: CRISIS_CODE
},
headers: {
'Accept': 'application/json'
},
success: function (response) {
var resp = Ext.decode(response.responseText);
if (resp.success && resp.data) {
try {
var data = Ext.JSON.decode(resp.data);
if (data && data.status) {
if (data.status == 'ready') {
var title = "Help us classifying tweets related to " + CRISIS_NAME;
var twitterURL = "https://twitter.com/intent/tweet?text="+title+"&url=" + data.url;
var facebookURL= "https://www.facebook.com/sharer/sharer.php?t="+title+"&u=" + data.url;
var googlePlusURL= "https://plus.google.com/share?url="+data.url;
var pinterestURL= "http://www.pinterest.com/pin/create/button/?media=IMAGEURL&description="+title+"&url=" + data.url;
me.mainComponent.pyBossaLink.setText('<div class="gray-backgrpund"><a href="' + data.url + '"><i>' + data.url + '</i></a></div>', false);
me.mainComponent.twitterLink.setText('<a href="'+ twitterURL +'"><image src="/AIDRFetchManager/resources/img/icons/twitter-icon.png" /></a>', false);
me.mainComponent.facebookLink.setText('<a href="'+ facebookURL +'"><image src="/AIDRFetchManager/resources/img/icons/facebook-icon.png" /></a>', false);
me.mainComponent.googlePlusLink.setText('<a href="'+ googlePlusURL +'"><image src="/AIDRFetchManager/resources/img/icons/google-icon.png" /></a>', false);
me.mainComponent.pinterestLink.setText('<a href="'+ pinterestURL +'"><image src="/AIDRFetchManager/resources/img/icons/pinterest-icon.png" /></a>', false);
} else if (data.status == 'not_ready') {
me.mainComponent.pyBossaLink.setText('<div class="gray-backgrpund"><i>' + data.message + '</i></div>', false);
}
}
} catch (e) {
me.mainComponent.pyBossaLink.setText('<div class="gray-backgrpund"><i>Initializing crowdsourcing task. Please come back in a few minutes.</i></div>', false);
}
} else {
me.mainComponent.pyBossaLink.setText('<div class="gray-backgrpund"><i>Initializing crowdsourcing task. Please come back in a few minutes.</i></div>', false);
AIDRFMFunctions.reportIssue(response);
}
},
failure: function () {
me.mainComponent.pyBossaLink.setText('<div class="gray-backgrpund"><i>Initializing crowdsourcing task. Please come back in a few minutes.</i></div>', false);
}
});
},
////////////////////////////////////////////
getUITemplateDefaultText: function(){
var me = this;
var sText = '';
var processNextStep = true;
if(attID == null){
processNextStep = false;
}
if(templateType == 1){
var iMax = me.mainComponent.crisisModelsStore.data.items.length -1;
for(var i=0; i < me.mainComponent.crisisModelsStore.data.items.length; i++){
var temp = me.mainComponent.crisisModelsStore.data.items[i].data.attribute;
if(i == 0){
sText = sText + temp;
}
else{
if(iMax == i && iMax !=0){
sText = sText +', and '+ temp;
}
else{
sText = sText +', '+ temp;
}
}
}
if(sText !=''){
sText = '<p>Hi! Thanks a lot for helping us tag tweets on '+CRISIS_NAME+'. We need to identify which tweets refer to ' + sText + ' to gain a better understanding of this situation. Simply click on "Start Here" to start tagging.<br/>Thank you for volunteering your time as a Digital Humanitarian!</p>' ;
me.updateUITemplateDisplayComponent(sText) ;
}
}
if(templateType == 2){
sText = 'For any questions, please see <a href="http://aidr.qcri.org/">AIDR - Artificial Intelligence for Disaster Response</a>';
me.updateUITemplateDisplayComponent(sText) ;
}
if(templateType == 5 && processNextStep){
for(var i=0; i < me.mainComponent.crisisModelsStore.data.items.length; i++){
var tempName = me.mainComponent.crisisModelsStore.data.items[i].data.attribute;
var tempID = me.mainComponent.crisisModelsStore.data.items[i].data.attributeID;
if(tempID == attID){
var labelList='';
Ext.Ajax.request({
url: BASE_URL + '/protected/uitemplate/getCrisisChildren.action',
method: 'GET',
params: {
id: CRISIS_ID
},
headers: {
'Accept': 'application/json'
},
success: function (response) {
var resp = Ext.decode(response.responseText);
if (resp.success && resp.data) {
try {
var data = Ext.JSON.decode(resp.data);
var nominalEle = data.nominalAttributeJsonModelSet;
var sVar = '';
for(var i=0; i < nominalEle.length; i++){
if(nominalEle[i].nominalAttributeID == attID){
var nominalLabelSet = nominalEle[i].nominalLabelJsonModelSet;
for(var j=0; j < nominalLabelSet.length; j++){
sVar = sVar + nominalLabelSet[i].name + ': ' + nominalLabelSet[i].description + '<br/>';
}
}
}
// console.log('svar: ' + sText);
if(sVar!=''){
sText = 'Being a Digital Humanitarian is as easy and fast as a click of the mouse. If you want to keep track of your progress and points, make sure to login! This Clicker will simply load a tweet and ask you to click on the category that best describes the tweet<br/><br/>';
sText = sText + sVar;
sText = sText + 'Note that these tweets come directly from twitter and may on rare occasions include disturbing content. Only start clicking if you understand this and still wish to volunteer.<br/>';
sText = sText + 'Thank you!'
me.updateUITemplateDisplayComponent(sText) ;
}
} catch (e) {
//console.log("resp:" + resp);
}
} else {
}
}
});
}
}
}
} ,
getUIDefaultTextWithAttribute: function(typeSet, attID){
var me = this;
var sText = '';
var processNextStep = true;
if(typeSet.length > 0){
Ext.Ajax.request({
url: BASE_URL + '/protected/uitemplate/getCrisisChildren.action',
method: 'GET',
params: {
id: CRISIS_ID
},
headers: {
'Accept': 'application/json'
},
success: function (response) {
var resp = Ext.decode(response.responseText);
if (resp.success && resp.data) {
try {
var data = Ext.JSON.decode(resp.data);
var nominalEle = data.nominalAttributeJsonModelSet;
var sTutorial = '';
var sDesc = '';
for(var i=0; i < nominalEle.length; i++){
if(nominalEle[i].nominalAttributeID == attID){
sDesc = nominalEle[i].description;
var sAttName = nominalEle[i].name;
var nominalLabelSet = nominalEle[i].nominalLabelJsonModelSet;
for(var j=0; j < nominalLabelSet.length; j++){
sTutorial = sTutorial + nominalLabelSet[j].name + ': ' + nominalLabelSet[j].description + '<br/>';
}
}
}
if(sDesc !='' && (typeSet.indexOf(3) > -1)){
me.mainComponent.welcomePageUI.setValue(sDesc, false);
}
if(sAttName !='' && (typeSet.indexOf(4) > -1)){
var sText = CRISIS_NAME+ ': '+sAttName+' Tutorial<br/><br/>Hi! Many thanks for volunteering your time as a Digital Humanitarian, in order to learn more about '+CRISIS_NAME+'. Critical information is often shared on Twitter in real time, which is where you come in.';
me.mainComponent.tutorial1UI.setValue(sText, false);
}
if(sTutorial!='' && (typeSet.indexOf(5) > -1)){
var tutorialPartOne = 'Being a Digital Humanitarian is as easy and fast as a click of the mouse. If you want to keep track of your progress and points, make sure to login! This Clicker will simply load a tweet and ask you to click on the category that best describes the tweet<br/><br/>';
tutorialPartOne = tutorialPartOne + sTutorial;
tutorialPartOne = tutorialPartOne + 'Note that these tweets come directly from twitter and may on rare occasions include disturbing content. Only start clicking if you understand this and still wish to volunteer.<br/>';
tutorialPartOne = tutorialPartOne + 'Thank you!'
me.mainComponent.tutorial2UI.setValue(tutorialPartOne, false);
}
} catch (e) {
//console.log("resp:" + resp);
}
} else {
}
}
});
}
},
loadUITemplateDisplayDefaultComponent: function(templateType){
var me = this;
var sText = '';
if(CRISIS_CODE != '161004090455_hurricane_matthew') {
me.mainComponent.hurricane_iframe.hide();
}
if(templateType == 1){
Ext.Ajax.request({
url: BASE_URL + '/protected/uitemplate/getCrisisChildren.action',
method: 'GET',
params: {
id: CRISIS_ID
},
headers: {
'Accept': 'application/json'
},
success: function (response) {
var resp = Ext.decode(response.responseText);
if (resp.success && resp.data) {
try {
var data = Ext.JSON.decode(resp.data);
var nominalEle = data.nominalAttributeJsonModelSet;
var sText = '';
var iMax = nominalEle.length -1;
for(var i=0; i < nominalEle.length; i++){
var temp = nominalEle[i].name;
if(i == 0){
sText = sText + temp;
}
else{
if(iMax == i && iMax !=0){
sText = sText +', and '+ temp;
}
else{
sText = sText +', '+ temp;
}
}
}
if(sText !=''){
sText = '<p>Hi! Thanks a lot for helping us tag tweets on '+CRISIS_NAME+'. We need to identify which tweets refer to ' + sText + ' to gain a better understanding of this situation. Simply click on "Start Here" to start tagging.<br/>Thank you for volunteering your time as a Digital Humanitarian!</p>' ;
me.mainComponent.uiLandingTemplateOne.setValue(sText, false);
}
} catch (e) {
//console.log("resp:" + resp);
}
} else {
}
}
});
}
if(templateType == 2){
sText = 'For any questions, please see <a href="http://aidr.qcri.org/">AIDR - Artificial Intelligence for Disaster Response</a>';
me.mainComponent.uiLandingTemplateTwo.setValue(sText, false);
}
},
loadUITemplate: function() {
var me = this;
Ext.Ajax.request({
url: BASE_URL + '/protected/uitemplate/getTemplate.action',
method: 'GET',
params: {
crisisID: CRISIS_ID
},
headers: {
'Accept': 'application/json'
},
success: function (response) {
var resp = Ext.decode(response.responseText);
if (resp.success && resp.data) {
try {
var data = Ext.JSON.decode(resp.data);
if(data.length == 0){
me.loadUITemplateDisplayDefaultComponent(1) ;
me.loadUITemplateDisplayDefaultComponent(2);
me.loadUITemplateDisplayDefaultComponent(7) ;
}
else{
var typeOneFound = false;
var typeTwoFound = false;
var typeSevenFound = false;
for(var i=0; i < data.length; i++){
if(data[i].templateType == 1){
typeOneFound = true;
me.mainComponent.uiLandingTemplateOne.setValue(data[i].templateValue, false);
}
if(data[i].templateType == 2){
typeTwoFound = true;
me.mainComponent.uiLandingTemplateTwo.setValue(data[i].templateValue, false);
}
if(data[i].templateType == 7){
var sVar = data[i].templateValue;
if(me.mainComponent.optionRG.items.items[0].inputValue == sVar){
me.mainComponent.optionRG.items.items[0].setValue(true);
}
if(me.mainComponent.optionRG.items.items[1].inputValue == sVar){
me.mainComponent.optionRG.items.items[1].setValue(true);
}
}
if(data[i].templateType == 6){
typeSevenFound = true;
me.mainComponent.curatorInfo.setValue(data[i].templateValue, false);
}
}
if(!typeOneFound){me.loadUITemplateDisplayDefaultComponent(1)}
if(!typeTwoFound){me.loadUITemplateDisplayDefaultComponent(2)}
if(!typeSevenFound){me.loadUITemplateDisplayDefaultComponent(6)}
}
} catch (e) {
//console.log("resp:" + resp);
//me.mainComponent.pyBossaLink.setText('<div class="gray-backgrpund"><i>Initializing crowdsourcing task. Please come back in a few minutes.</i></div>', false);
}
} else {
//me.mainComponent.pyBossaLink.setText('<div class="gray-backgrpund"><i>Initializing crowdsourcing task. Please come back in a few minutes.</i></div>', false);
}
},
failure: function () {
}
});
},
renderUpdatedUITemplateDisplayComponent: function(templateType, sText){
var me = this;
if(templateType == 1){
me.mainComponent.uiLandingTemplateOne.setValue(sText, false);
}
if(templateType == 2){
me.mainComponent.uiLandingTemplateTwo.setValue(sText, false);
}
if(templateType == 7){
if(me.mainComponent.optionRG.items.items[0].inputValue == sVar){
me.mainComponent.optionRG.items.items[0].setValue(true);
}
if(me.mainComponent.optionRG.items.items[1].inputValue == sVar){
me.mainComponent.optionRG.items.items[1].setValue(true);
}
}
if(templateType == 6){
me.mainComponent.curatorInfo.setValue(sText, false);
}
if(templateType == 3){
me.mainComponent.welcomePageUI.setValue(sText, false);
}
if(templateType == 4){
me.mainComponent.tutorial1UI.setValue(sText, false);
}
if(templateType == 5){
me.mainComponent.tutorial2UI.setValue(sText, false);
}
},
getUITemplateWithAttributeID: function(attID) {
var me = this;
Ext.Ajax.request({
url: BASE_URL + '/protected/uitemplate/getTemplate.action',
method: 'GET',
params: {
crisisID: CRISIS_ID
},
headers: {
'Accept': 'application/json'
},
success: function (response) {
var resp = Ext.decode(response.responseText);
if (resp.success && resp.data) {
try {
var data = Ext.JSON.decode(resp.data);
var sVar = '';
var typeThreeFound = false;
var typeFourFound = false;
var typeFiveFound = false;
for(var i=0; i < data.length; i++){
var type = data[i].templateType;
if(type == 3 ){
if(data[i].nominalAttributeID == attID){
typeThreeFound = true;
sVar = data[i].templateValue;
me.renderUpdatedUITemplateDisplayComponent(type, sVar);
}
}
if(type == 4 ){
if(data[i].nominalAttributeID == attID){
typeFourFound = true ;
sVar = data[i].templateValue;
me.renderUpdatedUITemplateDisplayComponent(type, sVar);
}
}
if(type == 5){
if(data[i].nominalAttributeID == attID){
typeFiveFound = true ;
sVar = data[i].templateValue;
me.renderUpdatedUITemplateDisplayComponent(type, sVar);
}
}
}
var searchTemplateID = new Array();
if(!typeThreeFound){
searchTemplateID[0] = 3;
}
if(!typeFourFound){
searchTemplateID[1] = 4;
}
if(!typeFiveFound){
searchTemplateID[2] = 5;
}
me.getUIDefaultTextWithAttribute(searchTemplateID, attID);
} catch (e) {
//console.log("resp:" + resp);
}
}
else {}
},
failure: function () {
}
});
},
getUITemplate: function(type, attID) {
var me = this;
Ext.Ajax.request({
url: BASE_URL + '/protected/uitemplate/getTemplate.action',
method: 'GET',
params: {
crisisID: CRISIS_ID
},
headers: {
'Accept': 'application/json'
},
success: function (response) {
var resp = Ext.decode(response.responseText);
if (resp.success && resp.data) {
try {
var data = Ext.JSON.decode(resp.data);
var sVar = '';
for(var i=0; i < data.length; i++){
if(data[i].templateType == type){
if(type == 1 || type == 2 || type == 6 || type == 7){
sVar = data[i].templateValue;
me.renderUpdatedUITemplateDisplayComponent(type, sVar);
}
else{
if(data[i].nominalAttributeID == attID){
sVar = data[i].templateValue;
me.renderUpdatedUITemplateDisplayComponent(type, sVar);
}
}
}
}
if(sVar == '' ){
me.getUILandingPageDefaultText(type, attID);
}
else{
me.renderUpdatedUITemplateDisplayComponent(attID, sVar);
}
} catch (e) {
//console.log("resp:" + resp);
}
}
else {}
},
failure: function () {
}
});
},
///////////////////////////////////////////////
getUISkinTemplate: function() {
var me = this;
me.mainComponent.optionRG.items.items[0].setValue(true);
me.mainComponent.uiSkinTypeSaveButton.show();
Ext.Ajax.request({
url: BASE_URL + '/protected/uitemplate/getTemplate.action',
method: 'GET',
params: {
crisisID: CRISIS_ID
},
headers: {
'Accept': 'application/json'
},
success: function (response) {
var resp = Ext.decode(response.responseText);
if (resp.success && resp.data) {
try {
var data = Ext.JSON.decode(resp.data);
var attID = me.mainComponent.classifierComboForSkinType.getValue();
var sVar = '';
for(var i=0; i < data.length; i++){
if(data[i].templateType == 5 && data[i].nominalAttributeID == attID){
sVar = data[i].templateValue;
if(me.mainComponent.optionRG.items.items[0].inputValue == sVar){
me.mainComponent.optionRG.items.items[0].setValue(true);
}
if(me.mainComponent.optionRG.items.items[1].inputValue == sVar){
me.mainComponent.optionRG.items.items[1].setValue(true);
}
}
}
} catch (e) {
// console.log("resp:" + resp);
//me.mainComponent.pyBossaLink.setText('<div class="gray-backgrpund"><i>Initializing crowdsourcing task. Please come back in a few minutes.</i></div>', false);
}
} else {
//me.mainComponent.pyBossaLink.setText('<div class="gray-backgrpund"><i>Initializing crowdsourcing task. Please come back in a few minutes.</i></div>', false);
}
},
failure: function () {
}
});
},
generateCSVLink: function() {
var me = this;
me.mainComponent.CSVLink.setText('<div class="loading-block"></div>', false);
Ext.Ajax.timeout = 900000;
Ext.override(Ext.form.Basic, {timeout: Ext.Ajax.timeout/1000});
Ext.override(Ext.data.proxy.Server, {timeout: Ext.Ajax.timeout});
Ext.override(Ext.data.Connection, {timeout: Ext.Ajax.timeout});
Ext.Ajax.request({
url: BASE_URL + '/protected/tagger/taggerGenerateCSVLink.action',
timeout: 900000,
method: 'GET',
params: {
code: CRISIS_CODE
},
headers: {
'Accept': 'application/json'
},
success: function (response) {
var resp = Ext.decode(response.responseText);
if (resp.success) {
if (resp.data && resp.data != '') {
me.mainComponent.CSVLink.setText('<div class="styled-text download-link">• <a href="' + resp.data + '">Download latest 100,000 tweets</a></div>', false);
} else {
me.mainComponent.CSVLink.setText('<div class="styled-text download-link">• Download latest 100,000 tweets - Not yet available for this crisis.</div>', false);
}
} else {
me.mainComponent.CSVLink.setText('', false);
AIDRFMFunctions.setAlert("Error", resp.message);
AIDRFMFunctions.reportIssue(response);
}
//Ext.Ajax.timeout = 30000;
//Ext.override(Ext.form.Basic, {timeout: Ext.Ajax.timeout/1000});
//Ext.override(Ext.data.proxy.Server, {timeout: Ext.Ajax.timeout});
//Ext.override(Ext.data.Connection, {timeout: Ext.Ajax.timeout});
},
failure: function () {
btn.setDisabled(false);
//Ext.Ajax.timeout = 30000;
//Ext.override(Ext.form.Basic, {timeout: Ext.Ajax.timeout/1000});
//Ext.override(Ext.data.proxy.Server, {timeout: Ext.Ajax.timeout});
//Ext.override(Ext.data.Connection, {timeout: Ext.Ajax.timeout});
}
});
},
generateTweetIdsLink: function() {
var me = this;
me.mainComponent.tweetsIdsLink.setText('<div class="loading-block"></div>', false);
Ext.Ajax.timeout = 900000;
Ext.override(Ext.form.Basic, {timeout: Ext.Ajax.timeout/1000});
Ext.override(Ext.data.proxy.Server, {timeout: Ext.Ajax.timeout});
Ext.override(Ext.data.Connection, {timeout: Ext.Ajax.timeout});
Ext.Ajax.request({
url: BASE_URL + '/protected/tagger/taggerGenerateTweetIdsLink.action',
timeout: 900000,
method: 'GET',
params: {
code: CRISIS_CODE
},
headers: {
'Accept': 'application/json'
},
success: function (response) {
var resp = Ext.decode(response.responseText);
if (resp.success) {
if (resp.data && resp.data != '') {
me.mainComponent.tweetsIdsLink.setText('<div class="styled-text download-link">• <a href="' + resp.data + '">Download all tweets (tweet-ids only)</a></div>', false);
if (resp.message) {
AIDRFMFunctions.setAlert("Error", resp.message);
}
} else {
me.mainComponent.tweetsIdsLink.setText('<div class="styled-text download-link">• Download all tweets (tweet-ids only) - Not yet available for this crisis.</div>', false);
}
} else {
me.mainComponent.tweetsIdsLink.setText('', false);
AIDRFMFunctions.setAlert("Error", resp.message);
AIDRFMFunctions.reportIssue(response);
}
//Ext.Ajax.timeout = 30000;
//Ext.override(Ext.form.Basic, {timeout: Ext.Ajax.timeout/1000});
//Ext.override(Ext.data.proxy.Server, {timeout: Ext.Ajax.timeout});
//Ext.override(Ext.data.Connection, {timeout: Ext.Ajax.timeout});
},
failure: function () {
btn.setDisabled(false);
//Ext.Ajax.timeout = 30000;
//Ext.override(Ext.form.Basic, {timeout: Ext.Ajax.timeout/1000});
//Ext.override(Ext.data.proxy.Server, {timeout: Ext.Ajax.timeout});
//Ext.override(Ext.data.Connection, {timeout: Ext.Ajax.timeout});
}
});
},
generateCSVLinkButtonHandler: function(btn) {
var me = this;
btn.setDisabled(true);
me.mainComponent.CSVLink.setText('<div class="loading-block"></div>', false);
Ext.Ajax.timeout = 900000;
Ext.override(Ext.form.Basic, {timeout: Ext.Ajax.timeout/1000});
Ext.override(Ext.data.proxy.Server, {timeout: Ext.Ajax.timeout});
Ext.override(Ext.data.Connection, {timeout: Ext.Ajax.timeout});
Ext.Ajax.request({
url: BASE_URL + '/protected/tagger/taggerGenerateCSVLink.action',
timeout: 900000,
method: 'GET',
params: {
code: CRISIS_CODE
},
headers: {
'Accept': 'application/json'
},
success: function (response) {
btn.setDisabled(false);
var resp = Ext.decode(response.responseText);
if (resp.success) {
if (resp.data && resp.data != '') {
me.mainComponent.CSVLink.setText('<div class="styled-text download-link"><a href="' + resp.data + '">' + resp.data + '</a></div>', false);
} else {
me.mainComponent.CSVLink.setText('', false);
AIDRFMFunctions.setAlert("Error", "Generate CSV service returned empty url. For further inquiries please contact admin.");
AIDRFMFunctions.reportIssue(response);
}
} else {
me.mainComponent.CSVLink.setText('', false);
AIDRFMFunctions.setAlert("Error", resp.message);
AIDRFMFunctions.reportIssue(response);
}
//Ext.Ajax.timeout = 30000;
//Ext.override(Ext.form.Basic, {timeout: Ext.Ajax.timeout/1000});
//Ext.override(Ext.data.proxy.Server, {timeout: Ext.Ajax.timeout});
//Ext.override(Ext.data.Connection, {timeout: Ext.Ajax.timeout});
},
failure: function () {
btn.setDisabled(false);
//Ext.Ajax.timeout = 30000;
//Ext.override(Ext.form.Basic, {timeout: Ext.Ajax.timeout/1000});
//Ext.override(Ext.data.proxy.Server, {timeout: Ext.Ajax.timeout});
//Ext.override(Ext.data.Connection, {timeout: Ext.Ajax.timeout});
}
});
},
generateTweetIdsLinkButtonHandler: function(btn) {
var me = this;
btn.setDisabled(true);
me.mainComponent.tweetsIdsLink.setText('<div class="loading-block"></div>', false);
Ext.Ajax.timeout = 900000;
Ext.override(Ext.form.Basic, {timeout: Ext.Ajax.timeout/1000});
Ext.override(Ext.data.proxy.Server, {timeout: Ext.Ajax.timeout});
Ext.override(Ext.data.Connection, {timeout: Ext.Ajax.timeout});
Ext.Ajax.request({
url: BASE_URL + '/protected/tagger/taggerGenerateTweetIdsLink.action',
timeout: 900000,
method: 'GET',
params: {
code: CRISIS_CODE
},
headers: {
'Accept': 'application/json'
},
success: function (response) {
btn.setDisabled(false);
var resp = Ext.decode(response.responseText);
if (resp.success) {
if (resp.data && resp.data != '') {
me.mainComponent.tweetsIdsLink.setText('<div class="styled-text download-link"><a href="' + resp.data + '">' + resp.data + '</a></div>', false);
if (resp.message) {
AIDRFMFunctions.setAlert("Error", resp.message);
}
} else {
me.mainComponent.tweetsIdsLink.setText('', false);
AIDRFMFunctions.setAlert("Error", "Generate Tweet Ids service returned empty url. For further inquiries please contact admin.");
AIDRFMFunctions.reportIssue(response);
}
} else {
me.mainComponent.tweetsIdsLink.setText('', false);
AIDRFMFunctions.setAlert("Error", resp.message);
AIDRFMFunctions.reportIssue(response);
}
//Ext.Ajax.timeout = 30000;
//Ext.override(Ext.form.Basic, {timeout: Ext.Ajax.timeout/1000});
//Ext.override(Ext.data.proxy.Server, {timeout: Ext.Ajax.timeout});
//Ext.override(Ext.data.Connection, {timeout: Ext.Ajax.timeout});
},
failure: function () {
btn.setDisabled(false);
//Ext.Ajax.timeout = 30000;
//Ext.override(Ext.form.Basic, {timeout: Ext.Ajax.timeout/1000});
//Ext.override(Ext.data.proxy.Server, {timeout: Ext.Ajax.timeout});
//Ext.override(Ext.data.Connection, {timeout: Ext.Ajax.timeout});
}
});
},
generateJSONLink: function() {
var me = this;
me.mainComponent.JSONLink.setText('<div class="loading-block"></div>', false);
Ext.Ajax.timeout = 900000;
Ext.override(Ext.form.Basic, {timeout: Ext.Ajax.timeout/1000});
Ext.override(Ext.data.proxy.Server, {timeout: Ext.Ajax.timeout});
Ext.override(Ext.data.Connection, {timeout: Ext.Ajax.timeout});
Ext.Ajax.request({
url: BASE_URL + '/protected/tagger/taggerGenerateJSONLink.action',
timeout: 900000,
method: 'GET',
params: {
code: CRISIS_CODE
},
headers: {
'Accept': 'application/json'
},
success: function (response) {
var resp = Ext.decode(response.responseText);
if (resp.success) {
if (resp.data && resp.data != '') {
me.mainComponent.JSONLink.setText('<div class="styled-text download-link">• <a href="' + resp.data + '">Download latest 100,000 tweets</a></div>', false);
} else {
me.mainComponent.JSONLink.setText('<div class="styled-text download-link">• Download latest 100,000 tweets - Not yet available for this crisis.</div>', false);
}
} else {
me.mainComponent.JSONLink.setText('', false);
AIDRFMFunctions.setAlert("Error", resp.message);
AIDRFMFunctions.reportIssue(response);
}
//Ext.Ajax.timeout = 30000;
//Ext.override(Ext.form.Basic, {timeout: Ext.Ajax.timeout/1000});
//Ext.override(Ext.data.proxy.Server, {timeout: Ext.Ajax.timeout});
//Ext.override(Ext.data.Connection, {timeout: Ext.Ajax.timeout});
},
failure: function () {
btn.setDisabled(false);
//Ext.Ajax.timeout = 30000;
//Ext.override(Ext.form.Basic, {timeout: Ext.Ajax.timeout/1000});
//Ext.override(Ext.data.proxy.Server, {timeout: Ext.Ajax.timeout});
//Ext.override(Ext.data.Connection, {timeout: Ext.Ajax.timeout});
}
});
},
generateJsonTweetIdsLink: function() {
var me = this;
me.mainComponent.JsonTweetsIdsLink.setText('<div class="loading-block"></div>', false);
Ext.Ajax.timeout = 900000;
Ext.override(Ext.form.Basic, {timeout: Ext.Ajax.timeout/1000});
Ext.override(Ext.data.proxy.Server, {timeout: Ext.Ajax.timeout});
Ext.override(Ext.data.Connection, {timeout: Ext.Ajax.timeout});
Ext.Ajax.request({
url: BASE_URL + '/protected/tagger/taggerGenerateJsonTweetIdsLink.action',
timeout: 900000,
method: 'GET',
params: {
code: CRISIS_CODE
},
headers: {
'Accept': 'application/json'
},
success: function (response) {
var resp = Ext.decode(response.responseText);
if (resp.success) {
if (resp.data && resp.data != '') {
me.mainComponent.JsonTweetsIdsLink.setText('<div class="styled-text download-link">• <a href="' + resp.data + '">Download all tweets (tweet-ids only)</a></div>', false);
if (resp.message) {
AIDRFMFunctions.setAlert("Error", resp.message);
}
} else {
me.mainComponent.JsonTweetsIdsLink.setText('<div class="styled-text download-link">• Download all tweets (tweet-ids only) - Not yet available for this crisis.</div>', false);
}
} else {
me.mainComponent.JsonTweetsIdsLink.setText('', false);
AIDRFMFunctions.setAlert("Error", resp.message);
AIDRFMFunctions.reportIssue(response);
}
//Ext.Ajax.timeout = 30000;
//Ext.override(Ext.form.Basic, {timeout: Ext.Ajax.timeout/1000});
//Ext.override(Ext.data.proxy.Server, {timeout: Ext.Ajax.timeout});
//Ext.override(Ext.data.Connection, {timeout: Ext.Ajax.timeout});
},
failure: function () {
btn.setDisabled(false);
//Ext.Ajax.timeout = 30000;
//Ext.override(Ext.form.Basic, {timeout: Ext.Ajax.timeout/1000});
//Ext.override(Ext.data.proxy.Server, {timeout: Ext.Ajax.timeout});
//Ext.override(Ext.data.Connection, {timeout: Ext.Ajax.timeout});
}
});
},
generateJSONLinkButtonHandler: function(btn) {
var me = this;
btn.setDisabled(true);
me.mainComponent.JSONLink.setText('<div class="loading-block"></div>', false);
Ext.Ajax.timeout = 900000;
Ext.override(Ext.form.Basic, {timeout: Ext.Ajax.timeout/1000});
Ext.override(Ext.data.proxy.Server, {timeout: Ext.Ajax.timeout});
Ext.override(Ext.data.Connection, {timeout: Ext.Ajax.timeout});
Ext.Ajax.request({
url: BASE_URL + '/protected/tagger/taggerGenerateJSONLink.action',
timeout: 900000,
method: 'GET',
params: {
code: CRISIS_CODE
},
headers: {
'Accept': 'application/json'
},
success: function (response) {
btn.setDisabled(false);
var resp = Ext.decode(response.responseText);
if (resp.success) {
if (resp.data && resp.data != '') {
me.mainComponent.JSONLink.setText('<div class="styled-text download-link"><a href="' + resp.data + '">' + resp.data + '</a></div>', false);
} else {
me.mainComponent.JSONLink.setText('', false);
AIDRFMFunctions.setAlert("Error", "Generate JSON service returned empty url. For further inquiries please contact admin.");
AIDRFMFunctions.reportIssue(response);
}
} else {
me.mainComponent.JSONLink.setText('', false);
AIDRFMFunctions.setAlert("Error", resp.message);
AIDRFMFunctions.reportIssue(response);
}
//Ext.Ajax.timeout = 30000;
//Ext.override(Ext.form.Basic, {timeout: Ext.Ajax.timeout/1000});
//Ext.override(Ext.data.proxy.Server, {timeout: Ext.Ajax.timeout});
//Ext.override(Ext.data.Connection, {timeout: Ext.Ajax.timeout});
},
failure: function () {
btn.setDisabled(false);
//Ext.Ajax.timeout = 30000;
//Ext.override(Ext.form.Basic, {timeout: Ext.Ajax.timeout/1000});
//Ext.override(Ext.data.proxy.Server, {timeout: Ext.Ajax.timeout});
//Ext.override(Ext.data.Connection, {timeout: Ext.Ajax.timeout});
}
});
},
generateJsonTweetIdsLinkButtonHandler: function(btn) {
var me = this;
btn.setDisabled(true);
me.mainComponent.JsonTweetsIdsLink.setText('<div class="loading-block"></div>', false);
Ext.Ajax.timeout = 900000;
Ext.override(Ext.form.Basic, {timeout: Ext.Ajax.timeout/1000});
Ext.override(Ext.data.proxy.Server, {timeout: Ext.Ajax.timeout});
Ext.override(Ext.data.Connection, {timeout: Ext.Ajax.timeout});
Ext.Ajax.request({
url: BASE_URL + '/protected/tagger/taggerGenerateJsonTweetIdsLink.action',
timeout: 900000,
method: 'GET',
params: {
code: CRISIS_CODE
},
headers: {
'Accept': 'application/json'
},
success: function (response) {
btn.setDisabled(false);
var resp = Ext.decode(response.responseText);
if (resp.success) {
if (resp.data && resp.data != '') {
me.mainComponent.JsonTweetsIdsLink.setText('<div class="styled-text download-link"><a href="' + resp.data + '">' + resp.data + '</a></div>', false);
if (resp.message) {
AIDRFMFunctions.setAlert("Error", resp.message);
}
} else {
me.mainComponent.JsonTweetsIdsLink.setText('', false);
AIDRFMFunctions.setAlert("Error", "Generate Tweet Ids service returned empty url. For further inquiries please contact admin.");
AIDRFMFunctions.reportIssue(response);
}
} else {
me.mainComponent.JsonTweetsIdsLink.setText('', false);
AIDRFMFunctions.setAlert("Error", resp.message);
AIDRFMFunctions.reportIssue(response);
}
//Ext.Ajax.timeout = 30000;
//Ext.override(Ext.form.Basic, {timeout: Ext.Ajax.timeout/1000});
//Ext.override(Ext.data.proxy.Server, {timeout: Ext.Ajax.timeout});
//Ext.override(Ext.data.Connection, {timeout: Ext.Ajax.timeout});
},
failure: function () {
btn.setDisabled(false);
//Ext.Ajax.timeout = 30000;
//Ext.override(Ext.form.Basic, {timeout: Ext.Ajax.timeout/1000});
//Ext.override(Ext.data.proxy.Server, {timeout: Ext.Ajax.timeout});
//Ext.override(Ext.data.Connection, {timeout: Ext.Ajax.timeout});
}
});
}
});
| agpl-3.0 |
nmpgaspar/PainlessProActive | src/Core/org/objectweb/proactive/core/body/ft/internalmsg/GlobalStateCompletion.java | 2325 | /*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2012 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: [email protected] or [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.objectweb.proactive.core.body.ft.internalmsg;
import org.objectweb.proactive.core.body.ft.protocols.FTManager;
import org.objectweb.proactive.core.body.ft.protocols.cic.managers.FTManagerCIC;
/**
* This event indicates to the receiver that a global state has been completed.
* @author The ProActive Team
* @since ProActive 2.2
*/
public class GlobalStateCompletion implements FTMessage {
private static final long serialVersionUID = 54L;
/**
*
*/
private int index;
/**
* Create a non-fonctional message.
* @param index the index of the completed global state
*/
public GlobalStateCompletion(int index) {
this.index = index;
}
public int getIndex() {
return this.index;
}
public Object handleFTMessage(FTManager ftm) {
return ((FTManagerCIC) ftm).handlingGSCEEvent(this);
}
}
| agpl-3.0 |
Konubinix/weboob | modules/inrocks/browser.py | 1474 | "browser for inrocks.fr website"
# -*- coding: utf-8 -*-
# Copyright(C) 2011 Julien Hebert
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# weboob is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with weboob. If not, see <http://www.gnu.org/licenses/>.
from .pages.article import ArticlePage
from .pages.inrockstv import InrocksTvPage
from weboob.deprecated.browser import Browser
class NewspaperInrocksBrowser(Browser):
"NewspaperInrocksBrowser class"
PAGES = {
'http://www.lesinrocks.com/(?!inrockstv).+/.*': ArticlePage,
'http://www.lesinrocks.com/inrockstv/.*': InrocksTvPage,
'http://blogs.lesinrocks.com/.*': ArticlePage,
}
def is_logged(self):
return False
def login(self):
pass
def fillobj(self, obj, fields):
pass
def get_content(self, _id):
"return page article content"
self.location(_id)
return self.page.get_article(_id)
| agpl-3.0 |
heroandtn3/openpaas-esn | frontend/js/modules/user-notification/toggler/user-notification-toggler.directive.js | 957 | (function() {
'use strict';
angular.module('esn.user-notification')
.directive('esnUserNotificationToggler', esnUserNotificationToggler);
function esnUserNotificationToggler($popover) {
return {
link: link,
restrict: 'E',
replace: true,
scope: true,
templateUrl: '/views/modules/user-notification/toggler/user-notification-toggler.html'
};
function link(scope, element) {
scope.togglePopover = function() {
if (!scope.popover) {
scope.popover = $popover(element, {
scope: scope,
trigger: 'manual',
placement: 'bottom',
templateUrl: '/views/modules/user-notification/popover/user-notification-popover.html'
});
scope.popover.$promise.then(scope.popover.show);
} else {
scope.popover.hide();
scope.popover.destroy();
scope.popover = null;
}
};
}
}
})();
| agpl-3.0 |
Cineca/OrcidHub | src/main/webapp/bower_components/angular-i18n/angular-locale_bs-latn-ba.js | 3222 | /*
* This file is part of huborcid.
*
* huborcid is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* huborcid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with huborcid. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"prije podne",
"popodne"
],
"DAY": [
"nedjelja",
"ponedjeljak",
"utorak",
"srijeda",
"\u010detvrtak",
"petak",
"subota"
],
"ERANAMES": [
"Prije nove ere",
"Nove ere"
],
"ERAS": [
"p. n. e.",
"n. e."
],
"FIRSTDAYOFWEEK": 0,
"MONTH": [
"januar",
"februar",
"mart",
"april",
"maj",
"juni",
"juli",
"august",
"septembar",
"oktobar",
"novembar",
"decembar"
],
"SHORTDAY": [
"ned",
"pon",
"uto",
"sri",
"\u010det",
"pet",
"sub"
],
"SHORTMONTH": [
"jan",
"feb",
"mar",
"apr",
"maj",
"jun",
"jul",
"aug",
"sep",
"okt",
"nov",
"dec"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, dd. MMMM y.",
"longDate": "dd. MMMM y.",
"medium": "dd. MMM. y. HH:mm:ss",
"mediumDate": "dd. MMM. y.",
"mediumTime": "HH:mm:ss",
"short": "dd.MM.yy. HH:mm",
"shortDate": "dd.MM.yy.",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "KM",
"DECIMAL_SEP": ",",
"GROUP_SEP": ".",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "bs-latn-ba",
"pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
| agpl-3.0 |
mrexodia/fabiano-swagger-of-doom | wServer/networking/svrPackets/FilePacket.cs | 741 | namespace wServer.networking.svrPackets
{
public class FilePacket : ServerPacket
{
public string Name { get; set; }
public byte[] Bytes { get; set; }
public override PacketID ID
{
get { return PacketID.FILE; }
}
public override Packet CreateInstance()
{
return new FilePacket();
}
protected override void Read(Client psr, NReader rdr)
{
Name = rdr.ReadUTF();
Bytes = rdr.ReadBytes(rdr.ReadInt32());
}
protected override void Write(Client psr, NWriter wtr)
{
wtr.WriteUTF(Name);
wtr.Write(Bytes.Length);
wtr.Write(Bytes);
}
}
} | agpl-3.0 |
ginkgostreet/civicrm_multiform | api/v3/EntityForm/Get.php | 659 | <?php
/**
* EntityForm.Get API specification (optional)
* This is used for documentation and validation.
*
* @param array $spec description of fields supported by this API call
* @return void
* @see http://wiki.civicrm.org/confluence/display/CRM/API+Architecture+Standards
*/
function _civicrm_api3_entity_form_get_spec(&$spec) {
}
/**
* EntityForm.Get API
*
* @param array $params
* @return array API result descriptor
* @see civicrm_api3_create_success
* @see civicrm_api3_create_error
* @throws API_Exception
*/
function civicrm_api3_entity_form_get($params) {
return _civicrm_api3_basic_get('CRM_Multiform_BAO_EntityForm', $params);
}
| agpl-3.0 |
plazari15/pi-uscs-app-de-conta-de-luz | ajax/SelecionaAno.php | 1061 | <?php
require '../_app/Config.inc.php';
$Read = new \Conn\Read();
$Post = filter_input_array(INPUT_POST, FILTER_DEFAULT);
$Read->ExeRead('bandeiras', "WHERE year = :year", "year={$Post['ano']}");
$Select = array();
$Result = array();
$Result = '';
//$Result['select'] = "<select id='SelecionaMes' name='mes[]' required class='browser-default SelectMesAjax'>";
if($Read->GetResult()){
//$Result['select'] .= "<option disabled selected id='SelecioneMes'>Selecione o mês</option>";
$Select[] = array(
'nome' => 'Selecione o mês',
'value' => '',
'attr' => 'disabled'
);
foreach ($Read->GetResult() as $Ano){
extract($Ano);
$Select[] = array(
'option' => "<option value='{$mes}'>{$nome_mes}</option>",
'nome' => $nome_mes,
'value' => $mes,
);
}
}else{
//$Result['select'] .= "<option disabled selected>Nenhuma bandeira cadastrada</option>";
}
//$Result['select'] .= "</select>";
sleep(1);
echo json_encode($Select);
| agpl-3.0 |
juju/juju | apiserver/common/crossmodel/state.go | 7649 | // Copyright 2017 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package crossmodel
import (
"github.com/juju/errors"
"github.com/juju/names/v4"
"github.com/juju/juju/core/crossmodel"
"github.com/juju/juju/core/network/firewall"
"github.com/juju/juju/state"
)
// StatePool provides the subset of a state pool.
type StatePool interface {
// Get returns a State for a given model from the pool.
Get(modelUUID string) (Backend, func(), error)
}
type statePoolShim struct {
*state.StatePool
}
func (p *statePoolShim) Get(modelUUID string) (Backend, func(), error) {
st, err := p.StatePool.Get(modelUUID)
if err != nil {
return nil, func() {}, err
}
closer := func() {
st.Release()
}
model, err := st.Model()
if err != nil {
closer()
return nil, nil, err
}
return stateShim{st.State, model}, closer, err
}
func GetStatePool(pool *state.StatePool) StatePool {
return &statePoolShim{pool}
}
// GetBackend wraps a State to provide a Backend interface implementation.
func GetBackend(st *state.State) stateShim {
model, err := st.Model()
if err != nil {
logger.Errorf("called GetBackend on a State with no Model.")
return stateShim{}
}
return stateShim{State: st, Model: model}
}
// TODO - CAAS(ericclaudejones): This should contain state alone, model will be
// removed once all relevant methods are moved from state to model.
type stateShim struct {
*state.State
*state.Model
}
func (st stateShim) KeyRelation(key string) (Relation, error) {
r, err := st.State.KeyRelation(key)
if err != nil {
return nil, errors.Trace(err)
}
return relationShim{r, st.State}, nil
}
// ControllerTag returns the tag of the controller in which we are operating.
// This is a temporary transitional step. Eventually code using
// crossmodel.Backend will only need to be passed a state.Model.
func (st stateShim) ControllerTag() names.ControllerTag {
return st.Model.ControllerTag()
}
// ModelTag returns the tag of the model in which we are operating.
// This is a temporary transitional step.
func (st stateShim) ModelTag() names.ModelTag {
return st.Model.ModelTag()
}
type applicationShim struct {
*state.Application
}
func (a applicationShim) Charm() (ch Charm, force bool, err error) {
return a.Application.Charm()
}
func (a applicationShim) EndpointBindings() (Bindings, error) {
return a.Application.EndpointBindings()
}
func (st stateShim) Application(name string) (Application, error) {
a, err := st.State.Application(name)
if err != nil {
return nil, errors.Trace(err)
}
return applicationShim{a}, nil
}
type remoteApplicationShim struct {
*state.RemoteApplication
}
func (a remoteApplicationShim) DestroyOperation(force bool) state.ModelOperation {
return a.RemoteApplication.DestroyOperation(force)
}
func (st stateShim) RemoteApplication(name string) (RemoteApplication, error) {
a, err := st.State.RemoteApplication(name)
if err != nil {
return nil, errors.Trace(err)
}
return &remoteApplicationShim{a}, nil
}
func (st stateShim) AddRelation(eps ...state.Endpoint) (Relation, error) {
r, err := st.State.AddRelation(eps...)
if err != nil {
return nil, errors.Trace(err)
}
return relationShim{r, st.State}, nil
}
func (st stateShim) EndpointsRelation(eps ...state.Endpoint) (Relation, error) {
r, err := st.State.EndpointsRelation(eps...)
if err != nil {
return nil, errors.Trace(err)
}
return relationShim{r, st.State}, nil
}
func (st stateShim) AddRemoteApplication(args state.AddRemoteApplicationParams) (RemoteApplication, error) {
a, err := st.State.AddRemoteApplication(args)
if err != nil {
return nil, errors.Trace(err)
}
return remoteApplicationShim{a}, nil
}
func (st stateShim) OfferNameForRelation(key string) (string, error) {
oc, err := st.State.OfferConnectionForRelation(key)
if err != nil {
return "", errors.Trace(err)
}
appOffers := state.NewApplicationOffers(st.State)
offer, err := appOffers.ApplicationOfferForUUID(oc.OfferUUID())
if err != nil {
return "", errors.Trace(err)
}
return offer.OfferName, nil
}
func (st stateShim) GetRemoteEntity(token string) (names.Tag, error) {
r := st.State.RemoteEntities()
return r.GetRemoteEntity(token)
}
func (st stateShim) GetToken(entity names.Tag) (string, error) {
r := st.State.RemoteEntities()
return r.GetToken(entity)
}
func (st stateShim) ExportLocalEntity(entity names.Tag) (string, error) {
r := st.State.RemoteEntities()
return r.ExportLocalEntity(entity)
}
func (st stateShim) ImportRemoteEntity(entity names.Tag, token string) error {
r := st.State.RemoteEntities()
return r.ImportRemoteEntity(entity, token)
}
func (st stateShim) ApplicationOfferForUUID(offerUUID string) (*crossmodel.ApplicationOffer, error) {
return state.NewApplicationOffers(st.State).ApplicationOfferForUUID(offerUUID)
}
func (s stateShim) SaveIngressNetworks(relationKey string, cidrs []string) (state.RelationNetworks, error) {
api := state.NewRelationIngressNetworks(s.State)
return api.Save(relationKey, false, cidrs)
}
func (s stateShim) IngressNetworks(relationKey string) (state.RelationNetworks, error) {
api := state.NewRelationIngressNetworks(s.State)
return api.Networks(relationKey)
}
func (s stateShim) FirewallRule(service firewall.WellKnownServiceType) (*state.FirewallRule, error) {
api := state.NewFirewallRules(s.State)
return api.Rule(service)
}
type relationShim struct {
*state.Relation
st *state.State
}
func (r relationShim) RemoteUnit(unitId string) (RelationUnit, error) {
ru, err := r.Relation.RemoteUnit(unitId)
if err != nil {
return nil, errors.Trace(err)
}
return relationUnitShim{ru}, nil
}
func (r relationShim) AllRemoteUnits(appName string) ([]RelationUnit, error) {
all, err := r.Relation.AllRemoteUnits(appName)
if err != nil {
return nil, errors.Trace(err)
}
result := make([]RelationUnit, len(all))
for i, ru := range all {
result[i] = relationUnitShim{ru}
}
return result, nil
}
func (r relationShim) Unit(unitId string) (RelationUnit, error) {
unit, err := r.st.Unit(unitId)
if err != nil {
return nil, errors.Trace(err)
}
ru, err := r.Relation.Unit(unit)
if err != nil {
return nil, errors.Trace(err)
}
return relationUnitShim{ru}, nil
}
func (r relationShim) ReplaceApplicationSettings(appName string, values map[string]interface{}) error {
currentSettings, err := r.ApplicationSettings(appName)
if err != nil {
return errors.Trace(err)
}
// This is a replace rather than an update so make the update
// remove any settings missing from the new values.
for key := range currentSettings {
if _, found := values[key]; !found {
values[key] = ""
}
}
// We're replicating changes from another controller so we need to
// trust them that the leadership was managed correctly - we can't
// check it here.
return errors.Trace(r.UpdateApplicationSettings(appName, &successfulToken{}, values))
}
type successfulToken struct{}
// Check is all of the lease.Token interface.
func (t successfulToken) Check(attempt int, key interface{}) error {
return nil
}
type relationUnitShim struct {
*state.RelationUnit
}
func (r relationUnitShim) Settings() (map[string]interface{}, error) {
settings, err := r.RelationUnit.Settings()
if err != nil {
return nil, errors.Trace(err)
}
return settings.Map(), nil
}
func (r relationUnitShim) ReplaceSettings(s map[string]interface{}) error {
settings, err := r.RelationUnit.Settings()
if err != nil {
return errors.Trace(err)
}
settings.Update(s)
for _, key := range settings.Keys() {
if _, ok := s[key]; ok {
continue
}
settings.Delete(key)
}
_, err = settings.Write()
return errors.Trace(err)
}
| agpl-3.0 |
quikkian-ua-devops/will-financials | kfs-core/src/main/java/org/kuali/kfs/coa/businessobject/AccountType.java | 2782 | /*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2017 Kuali, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kfs.coa.businessobject;
import org.kuali.kfs.krad.bo.PersistableBusinessObjectBase;
import org.kuali.rice.core.api.mo.common.active.MutableInactivatable;
import java.util.LinkedHashMap;
public class AccountType extends PersistableBusinessObjectBase implements MutableInactivatable {
/**
* Default no-arg constructor.
*/
public AccountType() {
}
private String accountTypeCode;
private String accountTypeName;
private boolean active;
/**
* Gets the accountTypeCode attribute.
*
* @return Returns the accountTypeCode
*/
public String getAccountTypeCode() {
return accountTypeCode;
}
/**
* Sets the accountTypeCode attribute.
*
* @param accountTypeCode The accountTypeCode to set.
*/
public void setAccountTypeCode(String accountTypeCode) {
this.accountTypeCode = accountTypeCode;
}
/**
* Gets the accountTypeName attribute.
*
* @return Returns the accountTypeName
*/
public String getAccountTypeName() {
return accountTypeName;
}
/**
* Sets the accountTypeName attribute.
*
* @param accountTypeName The accountTypeName to set.
*/
public void setAccountTypeName(String accountTypeName) {
this.accountTypeName = accountTypeName;
}
/**
* @see org.kuali.rice.krad.bo.BusinessObjectBase#toStringMapper()
*/
protected LinkedHashMap toStringMapper_RICE20_REFACTORME() {
LinkedHashMap m = new LinkedHashMap();
m.put("accountTypeCode", this.accountTypeCode);
return m;
}
/**
* Gets the active attribute.
*
* @return Returns the active.
*/
public boolean isActive() {
return active;
}
/**
* Sets the active attribute value.
*
* @param active The active to set.
*/
public void setActive(boolean active) {
this.active = active;
}
}
| agpl-3.0 |
gamesurvey/GSurveyCode | gsweb/src/main/java/views/ResetPasswordView.java | 327 | package views;
import gamesurvey.dao.MyDAOImpl;
import views.base.PublicBaseView;
/**
* Created by Martin on 24.10.2015.
*/
public class ResetPasswordView extends PublicBaseView {
private MyDAOImpl dao;
public ResetPasswordView(MyDAOImpl dao) {
super("resetPassword.ftl");
this.dao=dao;
}
}
| agpl-3.0 |
OfficineDigitali/pendola | app/Alarm.php | 2718 | <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Auth;
class Alarm extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
public function type()
{
return $this->belongsTo('App\AlarmType');
}
public function entity()
{
return $this->belongsTo('App\Entity');
}
public function author()
{
return $this->belongsTo('App\User', 'author_id');
}
public function owner()
{
return $this->belongsTo('App\User', 'owner_id');
}
public function history()
{
return $this->hasMany('App\Reminder');
}
public function filesPath()
{
$p = storage_path('app/' . $this->id);
if (file_exists($p) == false)
mkdir($p, 0777, true);
return $p;
}
public function getFilesAttribute()
{
$path = $this->filesPath();
return array_diff(scandir($path), ['.', '..']);
}
public static function getByTarget($target)
{
return Alarm::where('entity_id', '=', $target->id)->get();
}
public static function getByOwner($user)
{
return Alarm::where('owner_id', '=', $user->id)->get();
}
public function printableFullDate()
{
$t = strtotime($this->date1) + 10;
return strftime('%A %d %B %G', $t);
}
public function exportableDate($type)
{
$t = strtotime($this->$type);
return strftime('%Y%m%dT%H%M%SZ', $t);
}
public function time()
{
return strtotime($this->date1);
}
public function month()
{
return date('n', strtotime($this->date1));
}
public function year()
{
return date('Y', strtotime($this->date1));
}
public function icon()
{
if ($this->entity != null)
return $this->entity->type->icon;
else
return 'asterisk';
}
public function simpleName()
{
if ($this->entity != null)
return sprintf('%s | %s', $this->entity->name, $this->type->name);
else
return $this->type->name;
}
public function reIterate()
{
if ($this->type->recurrence == 'once')
return;
$a = new Alarm();
$a->type_id = $this->type_id;
$a->entity_id = $this->entity_id;
$a->author_id = Auth::user()->id;
$a->owner_id = $this->owner_id;
$a->notes = '';
$a->closed = false;
$a->closer_id = -1;
$a->prev_id = $this->id;
switch($this->type->recurrence) {
case 'daily':
$future = '+1 day';
break;
case 'weekly':
$future = '+1 week';
break;
case 'monthly':
$future = '+1 month';
break;
case 'yearly':
$future = '+1 year';
break;
case 'custom':
$future = sprintf('+%s', $this->type->recurrence_details);
break;
}
$a->date1 = date('Y-m-d', strtotime($this->date1 . $future));
if ($this->type->type == 'interval')
$a->date2 = date('Y-m-d', strtotime($this->date2 . $future));
$a->save();
}
}
| agpl-3.0 |
ahmedaljazzar/fairuze | accounts/factories.py | 285 | from django.contrib.auth.models import User
import factory
class UserFactory(factory.DjangoModelFactory):
username = factory.Sequence('user_{}'.format)
first_name = factory.Faker('first_name')
last_name = factory.Faker('last_name')
class Meta:
model = User
| agpl-3.0 |
retest/recheck | src/main/java/de/retest/recheck/ui/actions/ActionExecutionResult.java | 1503 | package de.retest.recheck.ui.actions;
import java.io.Serializable;
/**
* This is a lightweight class that contains the duration of the execution and the resulting error, if one occurred.
*/
public class ActionExecutionResult implements Serializable {
private static final long serialVersionUID = 1L;
private final ExceptionWrapper error;
private final TargetNotFoundException targetNotFound;
private final long duration;
public ActionExecutionResult( final ExceptionWrapper error, final TargetNotFoundException targetNotFound,
final long duration ) {
this.error = error;
this.targetNotFound = targetNotFound;
this.duration = duration;
}
public ActionExecutionResult( final ExceptionWrapper error, final long duration ) {
this( error, null, duration );
}
public ActionExecutionResult( final TargetNotFoundException targetNotFound ) {
this( null, targetNotFound, -1 );
}
public ExceptionWrapper getError() {
return error;
}
public TargetNotFoundException getTargetNotFound() {
return targetNotFound;
}
public long getDuration() {
return duration;
}
@Override
public String toString() {
final StringBuilder result = new StringBuilder( "execution took " ).append( duration ).append( "ms" );
if ( getError() != null ) {
result.append( " and resulted in " ).append( error.toString() );
}
if ( getTargetNotFound() != null ) {
result.append( " and did not find target " ).append( targetNotFound.toString() );
}
return result.toString();
}
}
| agpl-3.0 |
m-sc/yamcs | yamcs-core/src/main/java/org/yamcs/yarch/rocksdb/RdbConfig.java | 12968 | package org.yamcs.yarch.rocksdb;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.rocksdb.BlockBasedTableConfig;
import org.rocksdb.BloomFilter;
import org.rocksdb.ColumnFamilyOptions;
import org.rocksdb.CompressionOptions;
import org.rocksdb.CompressionType;
import org.rocksdb.DBOptions;
import org.rocksdb.Env;
import org.rocksdb.IndexType;
import org.rocksdb.Options;
import org.yamcs.ConfigurationException;
import org.yamcs.YConfiguration;
/**
* reads the rdbConfig from the yamcs.yaml and provides RocksDB Options when creating and opening databases
*
* singleton
*
* @author nm
*
*/
public class RdbConfig {
public static final String KEY_RDB_CONFIG = "rdbConfig";
public static final String KEY_TABLESPACE_CONFIG = "tablespaceConfig";
public static final String KEY_OPTIONS = "options";
public static final String KEY_TABLESPACE_NAME_PATTERN = "tablespaceNamePattern";
public static final String KEY_TF_CONFIG = "tableFormatConfig";
public static final int DEFAULT_MAX_OPEN_FILES = 1000;
static final Map<String, CompressionType> COMP_TYPES = new HashMap<>();
static {
COMP_TYPES.put("none", CompressionType.DISABLE_COMPRESSION_OPTION);
COMP_TYPES.put("bzlib2", CompressionType.BZLIB2_COMPRESSION);
COMP_TYPES.put("lz4", CompressionType.LZ4_COMPRESSION);
COMP_TYPES.put("lz4hc", CompressionType.LZ4HC_COMPRESSION);
COMP_TYPES.put("snappy", CompressionType.SNAPPY_COMPRESSION);
COMP_TYPES.put("xpress", CompressionType.XPRESS_COMPRESSION);
COMP_TYPES.put("zlib", CompressionType.ZLIB_COMPRESSION);
COMP_TYPES.put("zstd", CompressionType.ZSTD_COMPRESSION);
}
static final private RdbConfig INSTANTCE = new RdbConfig();
private List<TablespaceConfig> tblConfigList = new ArrayList<>();
final Env env;
final ColumnFamilyOptions defaultColumnFamilyOptions;
final Options defaultOptions;
final DBOptions defaultDBOptions;
/**
*
* @return the singleton instance
*/
public static RdbConfig getInstance() {
return INSTANTCE;
}
@SuppressWarnings("unchecked")
private RdbConfig() {
YConfiguration config = YConfiguration.getConfiguration("yamcs");
if (config.containsKey(KEY_RDB_CONFIG)) {
YConfiguration rdbOptions = config.getConfig(KEY_RDB_CONFIG);
if (rdbOptions.containsKey(KEY_TABLESPACE_CONFIG)) {
List<YConfiguration> tableConfigs = rdbOptions.getConfigList(KEY_TABLESPACE_CONFIG);
for (YConfiguration tableConfig : tableConfigs) {
TablespaceConfig tblConf = new TablespaceConfig(tableConfig);
tblConfigList.add(tblConf);
}
}
}
env = Env.getDefault();
defaultColumnFamilyOptions = new ColumnFamilyOptions();
BlockBasedTableConfig tableFormatConfig = new BlockBasedTableConfig();
tableFormatConfig.setBlockSize(256l * 1024);// 256KB
tableFormatConfig.setBlockCacheSize(10l * 1024 * 1024);// 1MB
tableFormatConfig.setFilter(new BloomFilter());
tableFormatConfig.setIndexType(IndexType.kTwoLevelIndexSearch);
defaultOptions = new Options();
defaultOptions.setWriteBufferSize(50l * 1024 * 1024);// 50MB
defaultOptions.setEnv(env);
defaultOptions.setCreateIfMissing(true);
defaultOptions.setTableFormatConfig(tableFormatConfig);
defaultOptions.useFixedLengthPrefixExtractor(4);
defaultOptions.setBottommostCompressionType(CompressionType.ZSTD_COMPRESSION);
defaultOptions.setTargetFileSizeMultiplier(2);
defaultColumnFamilyOptions.setTableFormatConfig(tableFormatConfig);
defaultColumnFamilyOptions.useFixedLengthPrefixExtractor(4);
defaultColumnFamilyOptions.setWriteBufferSize(defaultOptions.writeBufferSize());
defaultColumnFamilyOptions.setBottommostCompressionType(defaultOptions.bottommostCompressionType());
defaultColumnFamilyOptions.setTargetFileSizeMultiplier(defaultOptions.targetFileSizeMultiplier());
defaultDBOptions = new DBOptions();
defaultDBOptions.setCreateIfMissing(true);
}
/**
* default column family options if no table specific config has been configured.
*
* @return default column family options
*/
public ColumnFamilyOptions getDefaultColumnFamilyOptions() {
return defaultColumnFamilyOptions;
}
/**
* default options if no table specific config has been configured.
*
*
* @return default options
*/
public Options getDefaultOptions() {
return defaultOptions;
}
/**
* default db options if no table specific config has been configured.
*
* no specific option set
*
* @return default options
*/
public DBOptions getDefaultDBOptions() {
return defaultDBOptions;
}
/**
*
* @param tablespaceName
* @return the first table config that matches the tablespace name or null if no config matches
*
*/
public TablespaceConfig getTablespaceConfig(String tablespaceName) {
for (TablespaceConfig tc : tblConfigList) {
if (tc.tablespaceNamePattern.matcher(tablespaceName).matches()) {
return tc;
}
}
return null;
}
public static class TablespaceConfig {
Pattern tablespaceNamePattern;
ColumnFamilyOptions cfOptions = new ColumnFamilyOptions();
// these options are used for the default column family when the database is open
// for some strange reason we cannot use the cfOptions for that
Options options = new Options();
DBOptions dboptions = new DBOptions();
long targetFileSizeBase;
TablespaceConfig(YConfiguration tblspConfig) throws ConfigurationException {
String s = tblspConfig.getString(KEY_TABLESPACE_NAME_PATTERN);
try {
tablespaceNamePattern = Pattern.compile(s);
} catch (PatternSyntaxException e) {
throw new ConfigurationException("Cannot parse regexp " + e);
}
options.setCreateIfMissing(true);
int maxOpenFiles = tblspConfig.getInt("maxOpenFiles", DEFAULT_MAX_OPEN_FILES);
if (maxOpenFiles < 20) {
throw new ConfigurationException(
"Exception when reading table configuration for '" + tablespaceNamePattern
+ "': maxOpenFiles has to be at least 20");
}
options.setMaxOpenFiles(maxOpenFiles);
dboptions.setMaxOpenFiles(maxOpenFiles);
if (tblspConfig.containsKey("numLevels")) {
options.setNumLevels(tblspConfig.getInt("numLevels"));
cfOptions.setNumLevels(tblspConfig.getInt("numLevels"));
}
if (tblspConfig.containsKey("targetFileSizeBase")) {
options.setTargetFileSizeBase(1024 * tblspConfig.getLong("targetFileSizeBase"));
cfOptions.setTargetFileSizeBase(1024 * tblspConfig.getLong("targetFileSizeBase"));
}
if (tblspConfig.containsKey("targetFileSizeMultiplier")) {
options.setTargetFileSizeMultiplier(tblspConfig.getInt("targetFileSizeMultiplier"));
cfOptions.setTargetFileSizeMultiplier(tblspConfig.getInt("targetFileSizeMultiplier"));
}
if (tblspConfig.containsKey("maxBytesForLevelBase")) {
options.setMaxBytesForLevelBase(1024 * tblspConfig.getLong("maxBytesForLevelBase"));
cfOptions.setMaxBytesForLevelBase(1024 * tblspConfig.getLong("maxBytesForLevelBase"));
}
if (tblspConfig.containsKey("writeBufferSize")) {
options.setWriteBufferSize(1024 * tblspConfig.getLong("writeBufferSize"));
options.setWriteBufferSize(1024 * tblspConfig.getLong("writeBufferSize"));
}
if (tblspConfig.containsKey("maxBytesForLevelMultiplier")) {
options.setMaxBytesForLevelMultiplier(tblspConfig.getInt("maxBytesForLevelMultiplier"));
cfOptions.setMaxBytesForLevelMultiplier(tblspConfig.getInt("maxBytesForLevelMultiplier"));
}
if (tblspConfig.containsKey("maxWriteBufferNumber")) {
options.setMaxWriteBufferNumber(tblspConfig.getInt("maxWriteBufferNumber"));
cfOptions.setMaxWriteBufferNumber(tblspConfig.getInt("maxWriteBufferNumber"));
}
if (tblspConfig.containsKey("maxBackgroundFlushes")) {
options.setMaxWriteBufferNumber(tblspConfig.getInt("maxWriteBufferNumber"));
cfOptions.setMaxWriteBufferNumber(tblspConfig.getInt("maxWriteBufferNumber"));
}
if (tblspConfig.containsKey("allowConcurrentMemtableWrite")) {
options.setAllowConcurrentMemtableWrite(tblspConfig.getBoolean("allowConcurrentMemtableWrite"));
dboptions.setAllowConcurrentMemtableWrite(tblspConfig.getBoolean("allowConcurrentMemtableWrite"));
}
if (tblspConfig.containsKey("minWriteBufferNumberToMerge")) {
options.setMinWriteBufferNumberToMerge(tblspConfig.getInt("minWriteBufferNumberToMerge"));
cfOptions.setMinWriteBufferNumberToMerge(tblspConfig.getInt("minWriteBufferNumberToMerge"));
}
if (tblspConfig.containsKey("level0FileNumCompactionTrigger")) {
options.setLevel0FileNumCompactionTrigger(tblspConfig.getInt("level0FileNumCompactionTrigger"));
cfOptions.setLevel0FileNumCompactionTrigger(tblspConfig.getInt("level0FileNumCompactionTrigger"));
}
if (tblspConfig.containsKey("level0SlowdownWritesTrigger")) {
options.setLevel0SlowdownWritesTrigger(tblspConfig.getInt("level0SlowdownWritesTrigger"));
cfOptions.setLevel0SlowdownWritesTrigger(tblspConfig.getInt("level0SlowdownWritesTrigger"));
}
if (tblspConfig.containsKey("level0StopWritesTrigger")) {
options.setLevel0StopWritesTrigger(tblspConfig.getInt("level0StopWritesTrigger"));
cfOptions.setLevel0StopWritesTrigger(tblspConfig.getInt("level0StopWritesTrigger"));
}
if (tblspConfig.containsKey("compressionType")) {
options.setCompressionType(getCompressionType(tblspConfig.getString("compressionType")));
cfOptions.setCompressionType(getCompressionType(tblspConfig.getString("compressionType")));
}
if (tblspConfig.containsKey("bottommostCompressionType")) {
options.setBottommostCompressionType(getCompressionType(tblspConfig.getString("bottommostCompressionType")));
cfOptions.setBottommostCompressionType(getCompressionType(tblspConfig.getString("bottommostCompressionType")));
}
if (tblspConfig.containsKey(KEY_TF_CONFIG)) {
YConfiguration tfc = tblspConfig.getConfig(KEY_TF_CONFIG);
BlockBasedTableConfig tableFormatConfig = new BlockBasedTableConfig();
if (tfc.containsKey("blockSize")) {
tableFormatConfig.setBlockSize(1024L * tfc.getLong("blockSize"));
}
if (tfc.containsKey("blockCacheSize")) {
tableFormatConfig.setBlockCacheSize(1024L * tfc.getLong("blockCacheSize"));
}
if (tfc.containsKey("noBlockCache")) {
tableFormatConfig.setNoBlockCache(tfc.getBoolean("noBlockCache"));
}
boolean partitionedIndex = tfc.getBoolean("partitionedIndex", true);
tableFormatConfig
.setIndexType(partitionedIndex ? IndexType.kTwoLevelIndexSearch : IndexType.kBinarySearch);
options.setTableFormatConfig(tableFormatConfig);
cfOptions.useFixedLengthPrefixExtractor(4);
}
options.useFixedLengthPrefixExtractor(4);
cfOptions.useFixedLengthPrefixExtractor(4);
}
public ColumnFamilyOptions getColumnFamilyOptions() {
return cfOptions;
}
public Options getOptions() {
return options;
}
public DBOptions getDBOptions() {
return dboptions;
}
}
static CompressionType getCompressionType(String compr) {
CompressionType ct = COMP_TYPES.get(compr);
if(ct == null) {
throw new ConfigurationException("Unknown compression type '"+compr+"'. Allowed types: "+COMP_TYPES.keySet());
}
return ct;
}
}
| agpl-3.0 |
Sage-Bionetworks/rstudio | src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/AceCompletionAdapter.java | 2419 | /*
* AceCompletionAdapter.java
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.studio.client.workbench.views.source.editors.text;
import com.google.gwt.dom.client.NativeEvent;
import org.rstudio.studio.client.workbench.views.console.shell.assist.CompletionManager;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.KeyboardHandler;
public class AceCompletionAdapter
{
public AceCompletionAdapter(CompletionManager completionManager)
{
completionManager_ = completionManager;
}
public native final KeyboardHandler getKeyboardHandler() /*-{
var event = $wnd.require("pilot/event");
var self = this;
var noop = {command: "null"};
return {
handleKeyboard: $entry(function(data, hashId, keyOrText, keyCode, e) {
if (hashId != 0 || keyCode != 0) {
if (self.@org.rstudio.studio.client.workbench.views.source.editors.text.AceCompletionAdapter::onKeyDown(Lcom/google/gwt/dom/client/NativeEvent;)(e)) {
event.stopEvent(e);
return noop; // perform a no-op
}
else
return false; // allow default behavior
}
else {
if (self.@org.rstudio.studio.client.workbench.views.source.editors.text.AceCompletionAdapter::onTextInput(Ljava/lang/String;)(keyOrText))
return noop;
else
return false;
}
})
};
}-*/;
private boolean onKeyDown(NativeEvent e)
{
return completionManager_.previewKeyDown(e);
}
private boolean onTextInput(String text)
{
if (text == null)
return false;
// Escape key comes in as a character on desktop builds
if (text.equals("\u001B"))
return true;
for (int i = 0; i < text.length(); i++)
if (completionManager_.previewKeyPress(text.charAt(i)))
return true;
return false;
}
private CompletionManager completionManager_;
}
| agpl-3.0 |
ProjetSigma/frontend | src/resources/group.ts | 1108 | import {Record} from 'utils/record';
import {Collection} from 'utils/collection';
import {GroupMember} from './group-member';
import {Publication} from './publication';
import {Acknowledgment} from './acknowledgment';
import {User} from './user';
import {Chat} from './chat';
export class Group extends Record {
public pk: number;
public name: string;
public desription: string;
public score: number; //could be cleaner
public is_protected: boolean;
public can_anyone_ask: boolean;
public need_validation_to_join: boolean;
public members_visibility: number;
public group_visibility: number;
public acknowledging: Acknowledgment[];
public acknowledged_by: Acknowledgment[];
public memberships: Collection<GroupMember>;
public publications: Collection<Publication>;
public chat: Chat;
}
export const groupRessource = {
name: 'group',
klass: Group,
subCollections: [{
action: 'members',
field: 'memberships',
ressource: 'group-member'
},
{
action: 'publications',
ressource: 'publication'
}]
};
| agpl-3.0 |
colares/touke-flow | Packages/Framework/TYPO3.Flow/Classes/TYPO3/Flow/Resource/Resource.php | 4217 | <?php
namespace TYPO3\Flow\Resource;
/* *
* This script belongs to the TYPO3 Flow framework. *
* *
* It is free software; you can redistribute it and/or modify it under *
* the terms of the GNU Lesser General Public License, either version 3 *
* of the License, or (at your option) any later version. *
* *
* The TYPO3 project - inspiring people to share! *
* */
use Doctrine\ORM\Mapping as ORM;
use TYPO3\Flow\Annotations as Flow;
use TYPO3\Flow\Utility\MediaTypes;
/**
* Model representing a resource
*
* @Flow\Entity
*/
class Resource {
/**
* @var \TYPO3\Flow\Resource\ResourcePointer
* @ORM\ManyToOne(cascade={"persist", "merge"})
*/
protected $resourcePointer;
/**
* @var \TYPO3\Flow\Resource\Publishing\AbstractPublishingConfiguration
* @ORM\ManyToOne
*/
protected $publishingConfiguration;
/**
* @var string
* @Flow\Validate(type="StringLength", options={ "maximum"=100 })
*/
protected $filename = '';
/**
* @var string
* @Flow\Validate(type="StringLength", options={ "maximum"=100 })
*/
protected $fileExtension = '';
/**
* Returns the SHA1 of the ResourcePointer this Resource uses.
*
* @return string
*/
public function __toString() {
return $this->resourcePointer->__toString();
}
/**
* Returns a resource://<sha1> URI for use with file operations, …
*
* @return string
* @api
*/
public function getUri() {
return 'resource://' . $this->resourcePointer;
}
/**
* Sets the filename
*
* @param string $filename
* @return void
* @api
*/
public function setFilename($filename) {
$pathInfo = pathinfo($filename);
if (isset($pathInfo['extension'])) {
$this->fileExtension = strtolower($pathInfo['extension']);
} else {
$this->fileExtension = '';
}
$this->filename = $pathInfo['filename'];
if ($this->fileExtension !== '') {
$this->filename .= '.' . $this->fileExtension;
}
}
/**
* Gets the filename
*
* @return string The filename
* @api
*/
public function getFilename() {
return $this->filename;
}
/**
* Returns the file extension used for this resource
*
* @return string The file extension used for this file
* @api
*/
public function getFileExtension() {
return $this->fileExtension;
}
/**
* Returns the mime type for this resource
*
* @return string The mime type
* @deprecated since 1.1.0
* @see getMediaType()
*/
public function getMimeType() {
return $this->getMediaType();
}
/**
* Returns the Media Type for this resource
*
* @return string The IANA Media Type
* @api
*/
public function getMediaType() {
return MediaTypes::getMediaTypeFromFilename('x.' . $this->getFileExtension());
}
/**
* Sets the resource pointer
*
* @param \TYPO3\Flow\Resource\ResourcePointer $resourcePointer
* @return void
* @api
*/
public function setResourcePointer(\TYPO3\Flow\Resource\ResourcePointer $resourcePointer) {
$this->resourcePointer = $resourcePointer;
}
/**
* Returns the resource pointer
*
* @return \TYPO3\Flow\Resource\ResourcePointer $resourcePointer
* @api
*/
public function getResourcePointer() {
return $this->resourcePointer;
}
/**
* Sets the publishing configuration for this resource
*
* @param \TYPO3\Flow\Resource\Publishing\PublishingConfigurationInterface $publishingConfiguration The publishing configuration
* @return void
*/
public function setPublishingConfiguration(\TYPO3\Flow\Resource\Publishing\PublishingConfigurationInterface $publishingConfiguration = NULL) {
$this->publishingConfiguration = $publishingConfiguration;
}
/**
* Returns the publishing configuration for this resource
*
* @return \TYPO3\Flow\Resource\Publishing\PublishingConfigurationInterface The publishing configuration
*/
public function getPublishingConfiguration() {
return $this->publishingConfiguration;
}
}
?>
| agpl-3.0 |
prabhakhar/juju-core | charm/repo_test.go | 9902 | package charm_test
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io/ioutil"
. "launchpad.net/gocheck"
"launchpad.net/juju-core/charm"
"launchpad.net/juju-core/log"
"launchpad.net/juju-core/testing"
"net"
"net/http"
"os"
"path/filepath"
"strconv"
)
type MockStore struct {
mux *http.ServeMux
lis net.Listener
bundleBytes []byte
bundleSha256 string
downloads []*charm.URL
}
func NewMockStore(c *C) *MockStore {
s := &MockStore{}
bytes, err := ioutil.ReadFile(testing.Charms.BundlePath(c.MkDir(), "series", "dummy"))
c.Assert(err, IsNil)
s.bundleBytes = bytes
h := sha256.New()
h.Write(bytes)
s.bundleSha256 = hex.EncodeToString(h.Sum(nil))
s.mux = http.NewServeMux()
s.mux.HandleFunc("/charm-info", func(w http.ResponseWriter, r *http.Request) {
s.ServeInfo(w, r)
})
s.mux.HandleFunc("/charm/", func(w http.ResponseWriter, r *http.Request) {
s.ServeCharm(w, r)
})
lis, err := net.Listen("tcp", "127.0.0.1:4444")
c.Assert(err, IsNil)
s.lis = lis
go http.Serve(s.lis, s)
return s
}
func (s *MockStore) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.mux.ServeHTTP(w, r)
}
func (s *MockStore) ServeInfo(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
response := map[string]*charm.InfoResponse{}
for _, url := range r.Form["charms"] {
cr := &charm.InfoResponse{}
response[url] = cr
curl := charm.MustParseURL(url)
switch curl.Name {
case "borken":
cr.Errors = append(cr.Errors, "badness")
continue
case "unwise":
cr.Warnings = append(cr.Warnings, "foolishness")
fallthrough
default:
if curl.Revision == -1 {
cr.Revision = 23
} else {
cr.Revision = curl.Revision
}
cr.Sha256 = s.bundleSha256
}
}
data, err := json.Marshal(response)
if err != nil {
panic(err)
}
w.Header().Set("Content-Type", "application/json")
_, err = w.Write(data)
if err != nil {
panic(err)
}
}
func (s *MockStore) ServeCharm(w http.ResponseWriter, r *http.Request) {
curl := charm.MustParseURL("cs:" + r.URL.Path[len("/charm/"):])
s.downloads = append(s.downloads, curl)
w.Header().Set("Connection", "close")
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Length", strconv.Itoa(len(s.bundleBytes)))
_, err := w.Write(s.bundleBytes)
if err != nil {
panic(err)
}
}
type StoreSuite struct {
server *MockStore
store charm.Repository
cache string
}
var _ = Suite(&StoreSuite{})
func (s *StoreSuite) SetUpSuite(c *C) {
s.server = NewMockStore(c)
}
func (s *StoreSuite) SetUpTest(c *C) {
s.cache = c.MkDir()
s.store = charm.NewStore("http://127.0.0.1:4444", s.cache)
s.server.downloads = nil
}
func (s *StoreSuite) TearDownSuite(c *C) {
s.server.lis.Close()
}
func (s *StoreSuite) TestError(c *C) {
curl := charm.MustParseURL("cs:series/borken")
expect := `charm info errors for "cs:series/borken": badness`
_, err := s.store.Latest(curl)
c.Assert(err, ErrorMatches, expect)
_, err = s.store.Get(curl)
c.Assert(err, ErrorMatches, expect)
}
func (s *StoreSuite) TestWarning(c *C) {
orig := log.Target
log.Target = c
defer func() { log.Target = orig }()
curl := charm.MustParseURL("cs:series/unwise")
expect := `.* JUJU charm: WARNING: charm store reports for "cs:series/unwise": foolishness` + "\n"
r, err := s.store.Latest(curl)
c.Assert(r, Equals, 23)
c.Assert(err, IsNil)
c.Assert(c.GetTestLog(), Matches, expect)
ch, err := s.store.Get(curl)
c.Assert(ch, NotNil)
c.Assert(err, IsNil)
c.Assert(c.GetTestLog(), Matches, expect+expect)
}
func (s *StoreSuite) TestLatest(c *C) {
for _, str := range []string{
"cs:series/blah",
"cs:series/blah-2",
"cs:series/blah-99",
} {
r, err := s.store.Latest(charm.MustParseURL(str))
c.Assert(r, Equals, 23)
c.Assert(err, IsNil)
}
}
func (s *StoreSuite) assertCached(c *C, curl *charm.URL) {
s.server.downloads = nil
ch, err := s.store.Get(curl)
c.Assert(err, IsNil)
c.Assert(ch, NotNil)
c.Assert(s.server.downloads, IsNil)
}
func (s *StoreSuite) TestGetCacheImplicitRevision(c *C) {
os.RemoveAll(s.cache)
base := "cs:series/blah"
curl := charm.MustParseURL(base)
revCurl := charm.MustParseURL(base + "-23")
ch, err := s.store.Get(curl)
c.Assert(err, IsNil)
c.Assert(ch, NotNil)
c.Assert(s.server.downloads, DeepEquals, []*charm.URL{revCurl})
s.assertCached(c, curl)
s.assertCached(c, revCurl)
}
func (s *StoreSuite) TestGetCacheExplicitRevision(c *C) {
os.RemoveAll(s.cache)
base := "cs:series/blah-12"
curl := charm.MustParseURL(base)
ch, err := s.store.Get(curl)
c.Assert(err, IsNil)
c.Assert(ch, NotNil)
c.Assert(s.server.downloads, DeepEquals, []*charm.URL{curl})
s.assertCached(c, curl)
}
func (s *StoreSuite) TestGetBadCache(c *C) {
base := "cs:series/blah"
curl := charm.MustParseURL(base)
revCurl := charm.MustParseURL(base + "-23")
name := charm.Quote(revCurl.String()) + ".charm"
err := ioutil.WriteFile(filepath.Join(s.cache, name), nil, 0666)
c.Assert(err, IsNil)
ch, err := s.store.Get(curl)
c.Assert(err, IsNil)
c.Assert(ch, NotNil)
c.Assert(s.server.downloads, DeepEquals, []*charm.URL{revCurl})
s.assertCached(c, curl)
s.assertCached(c, revCurl)
}
type LocalRepoSuite struct {
testing.LoggingSuite
repo *charm.LocalRepository
seriesPath string
}
var _ = Suite(&LocalRepoSuite{})
func (s *LocalRepoSuite) SetUpTest(c *C) {
s.LoggingSuite.SetUpTest(c)
root := c.MkDir()
s.repo = &charm.LocalRepository{root}
s.seriesPath = filepath.Join(root, "series")
c.Assert(os.Mkdir(s.seriesPath, 0777), IsNil)
}
func (s *LocalRepoSuite) addBundle(name string) string {
return testing.Charms.BundlePath(s.seriesPath, "series", name)
}
func (s *LocalRepoSuite) addDir(name string) string {
return testing.Charms.ClonedDirPath(s.seriesPath, "series", name)
}
func (s *LocalRepoSuite) TestMissingCharm(c *C) {
_, err := s.repo.Latest(charm.MustParseURL("local:series/zebra"))
c.Assert(err, ErrorMatches, `no charms found matching "local:series/zebra"`)
_, err = s.repo.Get(charm.MustParseURL("local:series/zebra"))
c.Assert(err, ErrorMatches, `no charms found matching "local:series/zebra"`)
_, err = s.repo.Latest(charm.MustParseURL("local:badseries/zebra"))
c.Assert(err, ErrorMatches, `no charms found matching "local:badseries/zebra"`)
_, err = s.repo.Get(charm.MustParseURL("local:badseries/zebra"))
c.Assert(err, ErrorMatches, `no charms found matching "local:badseries/zebra"`)
}
func (s *LocalRepoSuite) TestMissingRepo(c *C) {
c.Assert(os.RemoveAll(s.repo.Path), IsNil)
_, err := s.repo.Latest(charm.MustParseURL("local:series/zebra"))
c.Assert(err, ErrorMatches, `no repository found at ".*"`)
_, err = s.repo.Get(charm.MustParseURL("local:series/zebra"))
c.Assert(err, ErrorMatches, `no repository found at ".*"`)
c.Assert(ioutil.WriteFile(s.repo.Path, nil, 0666), IsNil)
_, err = s.repo.Latest(charm.MustParseURL("local:series/zebra"))
c.Assert(err, ErrorMatches, `no repository found at ".*"`)
_, err = s.repo.Get(charm.MustParseURL("local:series/zebra"))
c.Assert(err, ErrorMatches, `no repository found at ".*"`)
}
func (s *LocalRepoSuite) TestMultipleVersions(c *C) {
curl := charm.MustParseURL("local:series/upgrade")
s.addDir("upgrade1")
rev, err := s.repo.Latest(curl)
c.Assert(err, IsNil)
c.Assert(rev, Equals, 1)
ch, err := s.repo.Get(curl)
c.Assert(err, IsNil)
c.Assert(ch.Revision(), Equals, 1)
s.addDir("upgrade2")
rev, err = s.repo.Latest(curl)
c.Assert(err, IsNil)
c.Assert(rev, Equals, 2)
ch, err = s.repo.Get(curl)
c.Assert(err, IsNil)
c.Assert(ch.Revision(), Equals, 2)
revCurl := curl.WithRevision(1)
rev, err = s.repo.Latest(revCurl)
c.Assert(err, IsNil)
c.Assert(rev, Equals, 2)
ch, err = s.repo.Get(revCurl)
c.Assert(err, IsNil)
c.Assert(ch.Revision(), Equals, 1)
badRevCurl := curl.WithRevision(33)
rev, err = s.repo.Latest(badRevCurl)
c.Assert(err, IsNil)
c.Assert(rev, Equals, 2)
ch, err = s.repo.Get(badRevCurl)
c.Assert(err, ErrorMatches, `no charms found matching "local:series/upgrade-33"`)
}
func (s *LocalRepoSuite) TestBundle(c *C) {
curl := charm.MustParseURL("local:series/dummy")
s.addBundle("dummy")
rev, err := s.repo.Latest(curl)
c.Assert(err, IsNil)
c.Assert(rev, Equals, 1)
ch, err := s.repo.Get(curl)
c.Assert(err, IsNil)
c.Assert(ch.Revision(), Equals, 1)
}
func (s *LocalRepoSuite) TestLogsErrors(c *C) {
err := ioutil.WriteFile(filepath.Join(s.seriesPath, "blah.charm"), nil, 0666)
c.Assert(err, IsNil)
err = os.Mkdir(filepath.Join(s.seriesPath, "blah"), 0666)
c.Assert(err, IsNil)
samplePath := s.addDir("upgrade2")
gibberish := []byte("don't parse me by")
err = ioutil.WriteFile(filepath.Join(samplePath, "metadata.yaml"), gibberish, 0666)
c.Assert(err, IsNil)
curl := charm.MustParseURL("local:series/dummy")
s.addDir("dummy")
ch, err := s.repo.Get(curl)
c.Assert(err, IsNil)
c.Assert(ch.Revision(), Equals, 1)
c.Assert(c.GetTestLog(), Matches, `
.* JUJU charm: WARNING: failed to load charm at ".*/series/blah": .*
.* JUJU charm: WARNING: failed to load charm at ".*/series/blah.charm": .*
.* JUJU charm: WARNING: failed to load charm at ".*/series/upgrade2": .*
`[1:])
}
func renameSibling(c *C, path, name string) {
c.Assert(os.Rename(path, filepath.Join(filepath.Dir(path), name)), IsNil)
}
func (s *LocalRepoSuite) TestIgnoresUnpromisingNames(c *C) {
err := ioutil.WriteFile(filepath.Join(s.seriesPath, "blah.notacharm"), nil, 0666)
c.Assert(err, IsNil)
err = os.Mkdir(filepath.Join(s.seriesPath, ".blah"), 0666)
c.Assert(err, IsNil)
renameSibling(c, s.addDir("dummy"), ".dummy")
renameSibling(c, s.addBundle("dummy"), "dummy.notacharm")
curl := charm.MustParseURL("local:series/dummy")
_, err = s.repo.Get(curl)
c.Assert(err, ErrorMatches, `no charms found matching "local:series/dummy"`)
_, err = s.repo.Latest(curl)
c.Assert(err, ErrorMatches, `no charms found matching "local:series/dummy"`)
c.Assert(c.GetTestLog(), Equals, "")
}
| agpl-3.0 |
Tatwi/legend-of-hondo | MMOCoreORB/bin/scripts/mobile/misc/seeker.lua | 698 | seeker = Creature:new {
objectName = "@droid_name:probe_droid",
socialGroup = "",
faction = "",
level = 1,
chanceHit = 0.01,
damageMin = 1,
damageMax = 1,
baseXp = 0,
baseHAM = 405,
baseHAMmax = 495,
armor = 0,
resists = {0,0,0,0,0,0,0,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = NONE,
creatureBitmask = NONE,
optionsBitmask = AIENABLED,
diet = HERBIVORE,
templates = {"object/creature/npc/droid/crafted/probe_droid.iff"},
lootGroups = {},
weapons = {},
conversationTemplate = "",
attacks = {
}
}
CreatureTemplates:addCreatureTemplate(seeker, "seeker")
| agpl-3.0 |
Zarel/Pokemon-Showdown-Client | src/panel-chat.tsx | 17124 | /**
* Chat panel
*
* @author Guangcong Luo <[email protected]>
* @license AGPLv3
*/
class ChatRoom extends PSRoom {
readonly classType: 'chat' | 'battle' = 'chat';
users: {[userid: string]: string} = {};
userCount = 0;
readonly canConnect = true;
// PM-only properties
pmTarget: string | null = null;
challengeMenuOpen = false;
challengingFormat: string | null = null;
challengedFormat: string | null = null;
constructor(options: RoomOptions) {
super(options);
if (options.pmTarget) this.pmTarget = options.pmTarget as string;
if (options.challengeMenuOpen) this.challengeMenuOpen = true;
this.updateTarget(true);
this.connect();
}
connect() {
if (!this.connected) {
if (!this.pmTarget) PS.send(`|/join ${this.id}`);
this.connected = true;
this.connectWhenLoggedIn = false;
}
}
updateTarget(force?: boolean) {
if (this.id.startsWith('pm-')) {
const [id1, id2] = this.id.slice(3).split('-');
if (id1 === PS.user.userid && toID(this.pmTarget) !== id2) {
this.pmTarget = id2;
} else if (id2 === PS.user.userid && toID(this.pmTarget) !== id1) {
this.pmTarget = id1;
} else if (!force) {
return;
} else {
this.pmTarget = id1;
}
if (!this.userCount) {
this.setUsers(2, [` ${id1}`, ` ${id2}`]);
}
this.title = `[PM] ${this.pmTarget}`;
}
}
/**
* @return true to prevent line from being sent to server
*/
handleMessage(line: string) {
if (!line.startsWith('/') || line.startsWith('//')) return false;
const spaceIndex = line.indexOf(' ');
const cmd = spaceIndex >= 0 ? line.slice(1, spaceIndex) : line.slice(1);
const target = spaceIndex >= 0 ? line.slice(spaceIndex + 1) : '';
switch (cmd) {
case 'j': case 'join': {
const roomid = /[^a-z0-9-]/.test(target) ? toID(target) as any as RoomID : target as RoomID;
PS.join(roomid);
return true;
} case 'part': case 'leave': {
const roomid = /[^a-z0-9-]/.test(target) ? toID(target) as any as RoomID : target as RoomID;
PS.leave(roomid || this.id);
return true;
} case 'chall': case 'challenge': {
if (target) {
PS.join(`challenge-${toID(target)}` as RoomID);
return true;
}
this.openChallenge();
return true;
} case 'cchall': case 'cancelchallenge': {
this.cancelChallenge();
return true;
} case 'reject': {
this.challengedFormat = null;
this.update(null);
return false;
}}
return super.handleMessage(line);
}
openChallenge() {
if (!this.pmTarget) {
this.receiveLine([`error`, `Can only be used in a PM.`]);
return;
}
this.challengeMenuOpen = true;
this.update(null);
}
cancelChallenge() {
if (!this.pmTarget) {
this.receiveLine([`error`, `Can only be used in a PM.`]);
return;
}
if (this.challengingFormat) {
this.send('/cancelchallenge', true);
this.challengingFormat = null;
this.challengeMenuOpen = true;
} else {
this.challengeMenuOpen = false;
}
this.update(null);
}
send(line: string, direct?: boolean) {
this.updateTarget();
if (!direct && !line) return;
if (!direct && this.handleMessage(line)) return;
if (this.pmTarget) {
PS.send(`|/pm ${this.pmTarget}, ${line}`);
return;
}
super.send(line, true);
}
setUsers(count: number, usernames: string[]) {
this.userCount = count;
this.users = {};
for (const username of usernames) {
const userid = toID(username);
this.users[userid] = username;
}
this.update(null);
}
addUser(username: string) {
const userid = toID(username);
if (!(userid in this.users)) this.userCount++;
this.users[userid] = username;
this.update(null);
}
removeUser(username: string, noUpdate?: boolean) {
const userid = toID(username);
if (userid in this.users) {
this.userCount--;
delete this.users[userid];
}
if (!noUpdate) this.update(null);
}
renameUser(username: string, oldUsername: string) {
this.removeUser(oldUsername, true);
this.addUser(username);
this.update(null);
}
destroy() {
if (this.pmTarget) this.connected = false;
super.destroy();
}
}
class ChatTextEntry extends preact.Component<{
room: PSRoom, onMessage: (msg: string) => void, onKey: (e: KeyboardEvent) => boolean,
left?: number,
}> {
subscription: PSSubscription | null = null;
textbox: HTMLTextAreaElement = null!;
history: string[] = [];
historyIndex = 0;
componentDidMount() {
this.subscription = PS.user.subscribe(() => {
this.forceUpdate();
});
this.textbox = this.base!.children[0].children[1] as HTMLTextAreaElement;
if (this.base) this.update();
}
componentWillUnmount() {
if (this.subscription) {
this.subscription.unsubscribe();
this.subscription = null;
}
}
update = () => {
const textbox = this.textbox;
textbox.style.height = `12px`;
const newHeight = Math.min(Math.max(textbox.scrollHeight - 2, 16), 600);
textbox.style.height = `${newHeight}px`;
};
focusIfNoSelection = (e: Event) => {
if ((e.target as HTMLElement).tagName === 'TEXTAREA') return;
const selection = window.getSelection()!;
if (selection.type === 'Range') return;
const elem = this.base!.children[0].children[1] as HTMLTextAreaElement;
elem.focus();
};
submit() {
this.props.onMessage(this.textbox.value);
this.historyPush(this.textbox.value);
this.textbox.value = '';
this.update();
return true;
}
keyDown = (e: KeyboardEvent) => {
if (this.handleKey(e) || this.props.onKey(e)) {
e.preventDefault();
e.stopImmediatePropagation();
}
};
historyUp() {
if (this.historyIndex === 0) return false;
const line = this.textbox.value;
if (line !== '') this.history[this.historyIndex] = line;
this.textbox.value = this.history[--this.historyIndex];
return true;
}
historyDown() {
const line = this.textbox.value;
if (line !== '') this.history[this.historyIndex] = line;
if (this.historyIndex === this.history.length) {
if (!line) return false;
this.textbox.value = '';
} else if (++this.historyIndex === this.history.length) {
this.textbox.value = '';
} else {
this.textbox.value = this.history[this.historyIndex];
}
return true;
}
historyPush(line: string) {
const duplicateIndex = this.history.lastIndexOf(line);
if (duplicateIndex >= 0) this.history.splice(duplicateIndex, 1);
if (this.history.length > 100) this.history.splice(0, 20);
this.history.push(line);
this.historyIndex = this.history.length;
}
handleKey(e: KeyboardEvent) {
const cmdKey = ((e.metaKey ? 1 : 0) + (e.ctrlKey ? 1 : 0) === 1) && !e.altKey && !e.shiftKey;
if (e.keyCode === 13 && !e.shiftKey) { // Enter key
return this.submit();
} else if (e.keyCode === 73 && cmdKey) { // Ctrl + I key
return this.toggleFormatChar('_');
} else if (e.keyCode === 66 && cmdKey) { // Ctrl + B key
return this.toggleFormatChar('*');
} else if (e.keyCode === 192 && cmdKey) { // Ctrl + ` key
return this.toggleFormatChar('`');
// } else if (e.keyCode === 9 && !e.ctrlKey) { // Tab key
// const reverse = !!e.shiftKey; // Shift+Tab reverses direction
// return this.handleTabComplete(this.$chatbox, reverse);
} else if (e.keyCode === 38 && !e.shiftKey && !e.altKey) { // Up key
return this.historyUp();
} else if (e.keyCode === 40 && !e.shiftKey && !e.altKey) { // Down key
return this.historyDown();
// } else if (app.user.lastPM && (textbox.value === '/reply' || textbox.value === '/r' || textbox.value === '/R') && e.keyCode === 32) { // '/reply ' is being written
// var val = '/pm ' + app.user.lastPM + ', ';
// textbox.value = val;
// textbox.setSelectionRange(val.length, val.length);
// return true;
}
return false;
}
toggleFormatChar(formatChar: string) {
const textbox = this.textbox;
if (!textbox.setSelectionRange) return false;
let value = textbox.value;
let start = textbox.selectionStart;
let end = textbox.selectionEnd;
// make sure start and end aren't midway through the syntax
if (value.charAt(start) === formatChar && value.charAt(start - 1) === formatChar &&
value.charAt(start - 2) !== formatChar) {
start++;
}
if (value.charAt(end) === formatChar && value.charAt(end - 1) === formatChar &&
value.charAt(end - 2) !== formatChar) {
end--;
}
// wrap in doubled format char
const wrap = formatChar + formatChar;
value = value.substr(0, start) + wrap + value.substr(start, end - start) + wrap + value.substr(end);
start += 2;
end += 2;
// prevent nesting
const nesting = wrap + wrap;
if (value.substr(start - 4, 4) === nesting) {
value = value.substr(0, start - 4) + value.substr(start);
start -= 4;
end -= 4;
} else if (start !== end && value.substr(start - 2, 4) === nesting) {
value = value.substr(0, start - 2) + value.substr(start + 2);
start -= 2;
end -= 4;
}
if (value.substr(end, 4) === nesting) {
value = value.substr(0, end) + value.substr(end + 4);
} else if (start !== end && value.substr(end - 2, 4) === nesting) {
value = value.substr(0, end - 2) + value.substr(end + 2);
end -= 2;
}
textbox.value = value;
textbox.setSelectionRange(start, end);
return true;
}
render() {
return <div
class="chat-log-add hasuserlist" onClick={this.focusIfNoSelection} style={{left: this.props.left || 0}}
>
<form class="chatbox">
<label style={{color: BattleLog.usernameColor(PS.user.userid)}}>{PS.user.name}:</label>
<textarea
class={this.props.room.connected ? 'textbox' : 'textbox disabled'}
autofocus
rows={1}
onInput={this.update}
onKeyDown={this.keyDown}
style={{resize: 'none', width: '100%', height: '16px', padding: '2px 3px 1px 3px'}}
placeholder={PS.focusPreview(this.props.room)}
/>
</form>
</div>;
}
}
class ChatPanel extends PSRoomPanel<ChatRoom> {
send = (text: string) => {
this.props.room.send(text);
};
focus() {
this.base!.querySelector('textarea')!.focus();
}
focusIfNoSelection = () => {
const selection = window.getSelection()!;
if (selection.type === 'Range') return;
this.focus();
};
onKey = (e: KeyboardEvent) => {
if (e.keyCode === 33) { // Pg Up key
const chatLog = this.base!.getElementsByClassName('chat-log')[0] as HTMLDivElement;
chatLog.scrollTop = chatLog.scrollTop - chatLog.offsetHeight + 60;
return true;
} else if (e.keyCode === 34) { // Pg Dn key
const chatLog = this.base!.getElementsByClassName('chat-log')[0] as HTMLDivElement;
chatLog.scrollTop = chatLog.scrollTop + chatLog.offsetHeight - 60;
return true;
}
return false;
};
makeChallenge = (e: Event, format: string, team?: Team) => {
const room = this.props.room;
const packedTeam = team ? team.packedTeam : '';
if (!room.pmTarget) throw new Error("Not a PM room");
PS.send(`|/utm ${packedTeam}`);
PS.send(`|/challenge ${room.pmTarget}, ${format}`);
room.challengeMenuOpen = false;
room.challengingFormat = format;
room.update(null);
};
acceptChallenge = (e: Event, format: string, team?: Team) => {
const room = this.props.room;
const packedTeam = team ? team.packedTeam : '';
if (!room.pmTarget) throw new Error("Not a PM room");
PS.send(`|/utm ${packedTeam}`);
this.props.room.send(`/accept`);
room.challengedFormat = null;
room.update(null);
};
render() {
const room = this.props.room;
const tinyLayout = room.width < 450;
const challengeTo = room.challengingFormat ? <div class="challenge">
<TeamForm format={room.challengingFormat} onSubmit={null}>
<button name="cmd" value="/cancelchallenge" class="button">Cancel</button>
</TeamForm>
</div> : room.challengeMenuOpen ? <div class="challenge">
<TeamForm onSubmit={this.makeChallenge}>
<button type="submit" class="button"><strong>Challenge</strong></button> {}
<button name="cmd" value="/cancelchallenge" class="button">Cancel</button>
</TeamForm>
</div> : null;
const challengeFrom = room.challengedFormat ? <div class="challenge">
<TeamForm format={room.challengedFormat} onSubmit={this.acceptChallenge}>
<button type="submit" class="button"><strong>Accept</strong></button> {}
<button name="cmd" value="/reject" class="button">Reject</button>
</TeamForm>
</div> : null;
return <PSPanelWrapper room={room}>
<div class="tournament-wrapper hasuserlist"></div>
<ChatLog class="chat-log" room={this.props.room} onClick={this.focusIfNoSelection} left={tinyLayout ? 0 : 146}>
{challengeTo || challengeFrom && [challengeTo, challengeFrom]}
</ChatLog>
<ChatTextEntry room={this.props.room} onMessage={this.send} onKey={this.onKey} left={tinyLayout ? 0 : 146} />
<ChatUserList room={this.props.room} minimized={tinyLayout} />
</PSPanelWrapper>;
}
}
class ChatUserList extends preact.Component<{room: ChatRoom, left?: number, minimized?: boolean}> {
subscription: PSSubscription | null = null;
state = {
expanded: false,
};
toggleExpanded = () => {
this.setState({expanded: !this.state.expanded});
};
componentDidMount() {
this.subscription = this.props.room.subscribe(msg => {
if (!msg) this.forceUpdate();
});
}
componentWillUnmount() {
if (this.subscription) this.subscription.unsubscribe();
}
render() {
const room = this.props.room;
let userList = Object.entries(room.users) as [ID, string][];
PSUtils.sortBy(userList, ([id, name]) => (
[PS.server.getGroup(name.charAt(0)).order, !name.endsWith('@!'), id]
));
return <ul class={'userlist' + (this.props.minimized ? (this.state.expanded ? ' userlist-maximized' : ' userlist-minimized') : '')} style={{left: this.props.left || 0}}>
<li class="userlist-count" style="text-align:center;padding:2px 0" onClick={this.toggleExpanded}><small>{room.userCount} users</small></li>
{userList.map(([userid, name]) => {
const groupSymbol = name.charAt(0);
const group = PS.server.groups[groupSymbol] || {type: 'user', order: 0};
let color;
if (name.endsWith('@!')) {
name = name.slice(0, -2);
color = '#888888';
} else {
color = BattleLog.usernameColor(userid);
}
return <li key={userid}><button class="userbutton username" data-name={name}>
<em class={`group${['leadership', 'staff'].includes(group.type!) ? ' staffgroup' : ''}`}>
{groupSymbol}
</em>
{group.type === 'leadership' ?
<strong><em style={{color}}>{name.substr(1)}</em></strong>
: group.type === 'staff' ?
<strong style={{color}}>{name.substr(1)}</strong>
:
<span style={{color}}>{name.substr(1)}</span>
}
</button></li>;
})}
</ul>;
}
}
class ChatLog extends preact.Component<{
class: string, room: ChatRoom, onClick?: (e: Event) => void, children?: preact.ComponentChildren,
left?: number, top?: number, noSubscription?: boolean;
}> {
log: BattleLog | null = null;
subscription: PSSubscription | null = null;
componentDidMount() {
if (!this.props.noSubscription) {
this.log = new BattleLog(this.base! as HTMLDivElement);
}
this.subscription = this.props.room.subscribe(tokens => {
if (!tokens) return;
switch (tokens[0]) {
case 'users':
const usernames = tokens[1].split(',');
const count = parseInt(usernames.shift()!, 10);
this.props.room.setUsers(count, usernames);
return;
case 'join': case 'j': case 'J':
this.props.room.addUser(tokens[1]);
break;
case 'leave': case 'l': case 'L':
this.props.room.removeUser(tokens[1]);
break;
case 'name': case 'n': case 'N':
this.props.room.renameUser(tokens[1], tokens[2]);
break;
}
if (!this.props.noSubscription) this.log!.add(tokens);
});
this.setControlsJSX(this.props.children);
}
componentWillUnmount() {
if (this.subscription) this.subscription.unsubscribe();
}
shouldComponentUpdate(props: typeof ChatLog.prototype.props) {
if (props.class !== this.props.class) {
this.base!.className = props.class;
}
if (props.left !== this.props.left) this.base!.style.left = `${props.left || 0}px`;
if (props.top !== this.props.top) this.base!.style.top = `${props.top || 0}px`;
this.setControlsJSX(props.children);
this.updateScroll();
return false;
}
setControlsJSX(jsx: preact.ComponentChildren | undefined) {
const children = this.base!.children;
let controlsElem = children[children.length - 1] as HTMLDivElement | undefined;
if (controlsElem && controlsElem.className !== 'controls') controlsElem = undefined;
if (!jsx) {
if (!controlsElem) return;
preact.render(null, this.base!, controlsElem);
this.updateScroll();
return;
}
if (!controlsElem) {
controlsElem = document.createElement('div');
controlsElem.className = 'controls';
this.base!.appendChild(controlsElem);
}
preact.render(<div class="controls">{jsx}</div>, this.base!, controlsElem);
this.updateScroll();
}
updateScroll() {
if (this.log) {
this.log.updateScroll();
} else if (this.props.room.battle) {
this.log = (this.props.room.battle as Battle).scene.log;
this.log.updateScroll();
}
}
render() {
return <div class={this.props.class} role="log" onClick={this.props.onClick} style={{
left: this.props.left || 0, top: this.props.top || 0,
}}></div>;
}
}
PS.roomTypes['chat'] = {
Model: ChatRoom,
Component: ChatPanel,
};
PS.updateRoomTypes();
| agpl-3.0 |
Orichievac/FallenGalaxy | src-server/fr/fg/server/test/action/trade/TestGetRates.java | 1537 | /*
Copyright 2010 Jeremie Gottero
This file is part of Fallen Galaxy.
Fallen Galaxy is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Fallen Galaxy is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Fallen Galaxy. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.fg.server.test.action.trade;
import org.json.JSONObject;
import fr.fg.server.test.action.TestAction;
public class TestGetRates extends TestAction {
// ------------------------------------------------------- CONSTANTES -- //
public final static String URI = "trade/getrates";
// -------------------------------------------------------- ATTRIBUTS -- //
// ---------------------------------------------------- CONSTRUCTEURS -- //
// --------------------------------------------------------- METHODES -- //
public void testGetEvents() throws Exception{
setPlayer("danzhig");
JSONObject answer = doRequest(URI, "fleet=16286");
System.out.println(answer.toString(2));
assertEquals("success",answer.get("type"));
}
// ------------------------------------------------- METHODES PRIVEES -- //
}
| agpl-3.0 |
aborg0/rapidminer-studio | src/main/java/com/rapidminer/operator/features/construction/ExampleSetBasedIndividual.java | 2887 | /**
* Copyright (C) 2001-2019 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.features.construction;
import com.rapidminer.example.AttributeWeights;
import com.rapidminer.example.set.AttributeWeightedExampleSet;
import com.rapidminer.operator.performance.PerformanceVector;
/**
* Individuals contain all necessary informations about example sets for population based search
* heuristics, including the performance. Each individiual can also handle a crowding distance for
* multi-objecitve optimization approaches.
*
* @author Ingo Mierswa
*/
public class ExampleSetBasedIndividual {
/** The example set. */
private AttributeWeightedExampleSet exampleSet;
/**
* The performance this example set has achieved during evaluation. Null if no evaluation has
* been performed so far.
*/
private PerformanceVector performanceVector = null;
/** The crowding distance can used for multiobjective optimization schemes. */
private double crowdingDistance = Double.NaN;
/**
* Some search schemes use attribute weights to guide the search point operations.
*/
private AttributeWeights attributeWeights = null;
/** Creates a new individual. */
public ExampleSetBasedIndividual(AttributeWeightedExampleSet exampleSet) {
this.exampleSet = exampleSet;
}
public AttributeWeightedExampleSet getExampleSet() {
return this.exampleSet;
}
public PerformanceVector getPerformance() {
return performanceVector;
}
public void setPerformance(PerformanceVector performanceVector) {
this.performanceVector = performanceVector;
}
public double getCrowdingDistance() {
return this.crowdingDistance;
}
public void setCrowdingDistance(double crowdingDistance) {
this.crowdingDistance = crowdingDistance;
}
public AttributeWeights getAttributeWeights() {
return this.attributeWeights;
}
public void setAttributeWeights(AttributeWeights weights) {
this.attributeWeights = weights;
}
@Override
public String toString() {
return "#" + exampleSet.getNumberOfUsedAttributes();
}
}
| agpl-3.0 |
tiltfactor/mg-game | www/protected/modules/plugins/modules/dictionary/views/stopWord/_search.php | 881 | <div class="wide form">
<?php $form = $this->beginWidget('GxActiveForm', array(
'action' => Yii::app()->createUrl($this->route),
'method' => 'get',
)); ?>
<div class="row">
<?php echo $form->label($model, 'word'); ?>
<?php echo $form->textField($model, 'word', array('maxlength' => 64)); ?>
</div>
<div class="row">
<?php echo $form->label($model, 'source'); ?>
<?php echo $form->textField($model, 'source', array('maxlength' => 12)); ?>
</div>
<div class="row">
<?php echo $form->label($model, 'counter'); ?>
<?php echo $form->textField($model, 'counter'); ?>
</div>
<div class="row">
<?php echo $form->label($model, 'modified'); ?>
<?php echo $form->textField($model, 'modified'); ?>
</div>
<div class="row buttons">
<?php echo GxHtml::submitButton(Yii::t('app', 'Search')); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- search-form -->
| agpl-3.0 |
AsherBond/MondocosmOS | bundler-sfm/src/keys.cpp | 28778 | /*
* Copyright (c) 2008-2010 Noah Snavely (snavely (at) cs.cornell.edu)
* and the University of Washington
*
* 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.
*
*/
/* keys.cpp */
/* Class for SIFT keypoints */
#include <assert.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#ifndef WIN32
#include <ext/hash_map>
#else
#include <hash_map>
#endif
#include "keys.h"
#include "defines.h"
#ifdef __BUNDLER_DISTR__
#include "ANN/ANN.h"
#else
#include "ann_1.1_char/include/ANN/ANN.h"
#endif
int GetNumberOfKeysNormal(FILE *fp)
{
int num, len;
if (fscanf(fp, "%d %d", &num, &len) != 2) {
printf("Invalid keypoint file.\n");
return 0;
}
#ifdef KEY_LIMIT
num = MIN(num, 65536); // we'll store at most 65536 features per
// image
#endif /* KEY_LIMIT */
return num;
}
int GetNumberOfKeysGzip(gzFile fp)
{
int num, len;
char header[256];
gzgets(fp, header, 256);
if (sscanf(header, "%d %d", &num, &len) != 2) {
printf("Invalid keypoint file.\n");
return 0;
}
#ifdef KEY_LIMIT
num = MIN(num, 65536); // we'll store at most 65536 features per
// image
#endif /* KEY_LIMIT */
return num;
}
int GetNumberOfKeysBin(FILE *f)
{
int num;
fread(&num, sizeof(int), 1, f);
#ifdef KEY_LIMIT
num = MIN(num, 65536); // we'll store at most 65536 features per
// image
#endif /* KEY_LIMIT */
return num;
}
int GetNumberOfKeysBinGzip(gzFile gzf)
{
int num;
gzread(gzf, &num, sizeof(int));
#ifdef KEY_LIMIT
num = MIN(num, 65536); // we'll store at most 65536 features per
// image
#endif /* KEY_LIMIT */
return num;
}
/* Returns the number of keys in a file */
int GetNumberOfKeys(const char *filename)
{
FILE *file;
file = fopen (filename, "r");
if (! file) {
/* Try to open a gzipped keyfile */
char buf[1024];
sprintf(buf, "%s.gz", filename);
gzFile gzf = gzopen(buf, "rb");
if (gzf == NULL) {
/* Try to open a .bin file */
sprintf(buf, "%s.bin", filename);
file = fopen(buf, "rb");
if (file == NULL) {
/* Try to open a gzipped .bin file */
sprintf(buf, "%s.bin.gz", filename);
gzf = gzopen(buf, "rb");
if (gzf == NULL) {
printf("Could not open file: %s\n", filename);
return 0;
} else {
int n = GetNumberOfKeysBinGzip(gzf);
gzclose(gzf);
return n;
}
} else {
int n = GetNumberOfKeysBin(file);
fclose(file);
return n;
}
} else {
int n = GetNumberOfKeysGzip(gzf);
gzclose(gzf);
return n;
}
} else {
int n = GetNumberOfKeysNormal(file);
fclose(file);
return n;
}
}
/* This reads a keypoint file from a given filename and returns the list
* of keypoints. */
std::vector<KeypointWithDesc> ReadKeyFileWithDesc(const char *filename,
bool descriptor)
{
FILE *file;
file = fopen (filename, "r");
if (! file) {
/* Try to file a gzipped keyfile */
char buf[1024];
sprintf(buf, "%s.gz", filename);
gzFile gzf = gzopen(buf, "rb");
if (gzf == NULL) {
/* Try to open a .bin file */
sprintf(buf, "%s.bin", filename);
file = fopen(buf, "rb");
if (file == NULL) {
/* Try to open a gzipped .bin file */
sprintf(buf, "%s.bin.gz", filename);
gzf = gzopen(buf, "rb");
if (gzf == NULL) {
std::vector<KeypointWithDesc> empty;
printf("Could not open file: %s\n", filename);
return empty;
} else {
std::vector<KeypointWithDesc> kps_desc =
ReadKeysFastBinGzip(gzf, descriptor);
gzclose(gzf);
return kps_desc;
}
} else {
std::vector<KeypointWithDesc> kps_desc =
ReadKeysFastBin(file, descriptor);
fclose(file);
return kps_desc;
}
} else {
std::vector<KeypointWithDesc> kps_desc =
ReadKeysFastGzip(gzf, descriptor);
gzclose(gzf);
return kps_desc;
}
} else {
std::vector<KeypointWithDesc> kps_desc = ReadKeysFast(file, descriptor);
fclose(file);
return kps_desc;
}
}
std::vector<Keypoint> ReadKeyFile(const char *filename)
{
std::vector<KeypointWithDesc> kps_d = ReadKeyFileWithDesc(filename, false);
std::vector<Keypoint> kps;
int num_keys = (int) kps_d.size();
kps.resize(num_keys);
for (int i = 0; i < num_keys; i++) {
kps[i].m_x = kps_d[i].m_x;
kps[i].m_y = kps_d[i].m_y;
}
kps_d.clear();
return kps;
}
/* This reads a keypoint file from a given filename and returns the list
* of keypoints. */
std::vector<KeypointWithScaleRot>
ReadKeyFileWithScaleRot(const char *filename, bool descriptor)
{
FILE *file;
std::vector<KeypointWithDesc> kps;
float *scale = NULL, *orient = NULL;
file = fopen (filename, "r");
if (! file) {
/* Try to file a gzipped keyfile */
char buf[1024];
sprintf(buf, "%s.gz", filename);
gzFile gzf = gzopen(buf, "rb");
if (gzf == NULL) {
/* Try to open a .bin file */
sprintf(buf, "%s.bin", filename);
file = fopen(buf, "rb");
if (file == NULL) {
/* Try to open a gzipped .bin file */
sprintf(buf, "%s.bin.gz", filename);
gzf = gzopen(buf, "rb");
if (gzf == NULL) {
std::vector<KeypointWithScaleRot> empty;
printf("Could not open file: %s\n", filename);
return empty;
} else {
kps = ReadKeysFastBinGzip(gzf, descriptor, &scale, &orient);
gzclose(gzf);
}
} else {
kps = ReadKeysFastBin(file, descriptor, &scale, &orient);
fclose(file);
}
} else {
kps = ReadKeysFastGzip(gzf, descriptor, &scale, &orient);
gzclose(gzf);
}
} else {
kps = ReadKeysFast(file, descriptor, &scale, &orient);
fclose(file);
}
std::vector<KeypointWithScaleRot> kps_w;
int num_keys = (int) kps.size();
kps_w.resize(num_keys);
for (int i = 0; i < num_keys; i++) {
kps_w[i].m_x = kps[i].m_x;
kps_w[i].m_y = kps[i].m_y;
kps_w[i].m_d = kps[i].m_d;
kps_w[i].m_scale = scale[i];
kps_w[i].m_orient = orient[i];
}
kps.clear();
if (scale != NULL)
delete [] scale;
if (scale != NULL)
delete [] orient;
return kps_w;
}
static char *strchrn(char *str, int c, int n) {
for (int i = 0; i < n; i++) {
str = strchr(str, c) + 1;
if (str == NULL) return NULL;
}
return str - 1;
}
#if 0
/* Read keys using MMAP to speed things up */
std::vector<Keypoint> ReadKeysMMAP(FILE *fp)
{
int i, j, num, len, val, n;
std::vector<Keypoint> kps;
struct stat sb;
/* Stat the file */
if (fstat(fileno(fp), &sb) < 0) {
printf("[ReadKeysMMAP] Error: could not stat file\n");
return kps;
}
char *file = (char *)mmap(NULL, sb.st_size, PROT_READ, MAP_SHARED,
fileno(fp), 0);
char *file_start = file;
char string_buf[1024];
char *str = string_buf;
/* Find the first '\n' */
char *newline = strchr(file, '\n');
int pos = (int) (newline - file);
memcpy(str, file, pos);
str[pos] = 0;
if (sscanf(str, "%d %d%n", &num, &len, &n) != 2) {
printf("[ReadKeysMMAP] Invalid keypoint file beginning.");
return kps;
}
#ifdef KEY_LIMIT
num = MIN(num, 65536); // we'll store at most 65536 features per
// image
#endif /* KEY_LIMIT */
file += (pos + 1);
if (len != 128) {
printf("[ReadKeysMMAP] Keypoint descriptor length invalid "
"(should be 128).");
return kps;
}
for (i = 0; i < num; i++) {
str = string_buf;
/* Allocate memory for the keypoint. */
unsigned char *d = new unsigned char[len];
float x, y, scale, ori;
/* Find the first '\n' */
newline = strchr(file, '\n');
pos = (int) (newline - file);
memcpy(str, file, pos);
str[pos] = 0;
if (sscanf(str, "%f %f %f %f%n", &y, &x, &scale, &ori, &n) != 4) {
printf("[ReadKeysMMAP] Invalid keypoint file format.");
return kps;
}
file += (pos + 1);
/* Find the next seven '\n's */
str = string_buf;
char *seventh_newline = strchrn(file, '\n', 7);
pos = (int) (seventh_newline - file);
memcpy(str, file, pos);
str[pos] = 0;
for (j = 0; j < len; j++) {
if (sscanf(str, "%d%n", &val, &n) != 1 || val < 0 || val > 255) {
printf("[ReadKeysMMAP] Invalid keypoint file value.");
return kps;
}
d[j] = (unsigned char) val;
str += n;
}
file += (pos + 1);
if (desc)
kps.Add(Keypoint(x, y, d));
else
kps.Add(Keypoint(x, y));
}
/* Unmap */
if (munmap(file_start, sb.st_size) < 0) {
printf("[ReadKeysMMAP] Error: could not unmap memory\n");
return kps;
}
return kps;
}
#endif
/* Read keypoints from the given file pointer and return the list of
* keypoints. The file format starts with 2 integers giving the total
* number of keypoints and the size of descriptor vector for each
* keypoint (currently assumed to be 128). Then each keypoint is
* specified by 4 floating point numbers giving subpixel row and
* column location, scale, and orientation (in radians from -PI to
* PI). Then the descriptor vector for each keypoint is given as a
* list of integers in range [0,255]. */
std::vector<Keypoint> ReadKeys(FILE *fp, bool descriptor)
{
int i, j, num, len, val;
std::vector<Keypoint> kps;
if (fscanf(fp, "%d %d", &num, &len) != 2) {
printf("Invalid keypoint file beginning.");
return kps;
}
#ifdef KEY_LIMIT
num = MIN(num, 65536); // we'll store at most 65536 features per
// image
#endif /* KEY_LIMIT */
if (len != 128) {
printf("Keypoint descriptor length invalid (should be 128).");
return kps;
}
for (i = 0; i < num; i++) {
/* Allocate memory for the keypoint. */
unsigned char *d = new unsigned char[len];
float x, y, scale, ori;
if (fscanf(fp, "%f %f %f %f", &y, &x, &scale, &ori) != 4) {
printf("Invalid keypoint file format.");
return kps;
}
for (j = 0; j < len; j++) {
if (fscanf(fp, "%d", &val) != 1 || val < 0 || val > 255) {
printf("Invalid keypoint file value.");
return kps;
}
d[j] = (unsigned char) val;
}
if (descriptor) {
kps.push_back(KeypointWithDesc(x, y, d));
} else {
delete [] d;
kps.push_back(Keypoint(x, y));
}
}
return kps;
}
/* Read keys more quickly */
std::vector<KeypointWithDesc> ReadKeysFast(FILE *fp, bool descriptor,
float **scales, float **orients)
{
int i, j, num, len;
std::vector<KeypointWithDesc> kps;
if (fscanf(fp, "%d %d", &num, &len) != 2) {
printf("Invalid keypoint file beginning.");
return kps;
}
#ifdef KEY_LIMIT
num = MIN(num, 65536); // we'll store at most 65536 features per
// image
#endif /* KEY_LIMIT */
if (len != 128) {
printf("Keypoint descriptor length invalid (should be 128).");
return kps;
}
kps.resize(num);
if (num > 0 && scales != NULL) {
*scales = new float[num];
}
if (num > 0 && orients != NULL) {
*orients = new float[num];
}
for (i = 0; i < num; i++) {
/* Allocate memory for the keypoint. */
float x, y, scale, ori;
if (fscanf(fp, "%f %f %f %f\n", &y, &x, &scale, &ori) != 4) {
printf("Invalid keypoint file format.");
return kps;
}
if (scales != NULL) {
(*scales)[i] = scale;
}
if (orients != NULL) {
(*orients)[i] = ori;
}
char buf[1024];
/* Allocate memory for the keypoint. */
unsigned char *d = NULL;
if (descriptor)
d = new unsigned char[len];
int start = 0;
for (int line = 0; line < 7; line++) {
fgets(buf, 1024, fp);
if (!descriptor) continue;
short int p[20];
if (line < 6) {
sscanf(buf,
"%hu %hu %hu %hu %hu %hu %hu %hu %hu %hu "
"%hu %hu %hu %hu %hu %hu %hu %hu %hu %hu",
p+0, p+1, p+2, p+3, p+4, p+5, p+6, p+7, p+8, p+9,
p+10, p+11, p+12, p+13, p+14,
p+15, p+16, p+17, p+18, p+19);
for (j = 0; j < 20; j++)
d[start + j] = p[j];
start += 20;
} else {
sscanf(buf,
"%hu %hu %hu %hu %hu %hu %hu %hu",
p+0, p+1, p+2, p+3, p+4, p+5, p+6, p+7);
for (j = 0; j < 8; j++)
d[start + j] = p[j];
}
}
// kps.push_back(KeypointWithDesc(x, y, d));
kps[i] = KeypointWithDesc(x, y, d);
}
return kps;
}
std::vector<KeypointWithDesc> ReadKeysFastGzip(gzFile fp, bool descriptor,
float **scales, float **orients)
{
int i, j, num, len;
std::vector<KeypointWithDesc> kps;
char header[256];
gzgets(fp, header, 256);
if (sscanf(header, "%d %d", &num, &len) != 2) {
printf("Invalid keypoint file.\n");
return kps;
}
#ifdef KEY_LIMIT
num = MIN(num, 65536); // we'll store at most 65536 features per
// image
#endif /* KEY_LIMIT */
if (len != 128) {
printf("Keypoint descriptor length invalid (should be 128).");
return kps;
}
kps.resize(num);
if (num > 0 && scales != NULL) {
*scales = new float[num];
}
if (num > 0 && orients != NULL) {
*orients = new float[num];
}
for (i = 0; i < num; i++) {
/* Allocate memory for the keypoint. */
float x, y, scale, ori;
char buf[1024];
gzgets(fp, buf, 1024);
if (sscanf(buf, "%f %f %f %f\n", &y, &x, &scale, &ori) != 4) {
printf("Invalid keypoint file format.");
return kps;
}
if (scales != NULL) {
(*scales)[i] = scale;
}
if (orients != NULL) {
(*orients)[i] = ori;
}
/* Allocate memory for the keypoint. */
unsigned char *d = NULL;
if (descriptor)
d = new unsigned char[len];
int start = 0;
for (int line = 0; line < 7; line++) {
gzgets(fp, buf, 1024);
if (!descriptor) continue;
short int p[20];
if (line < 6) {
sscanf(buf,
"%hu %hu %hu %hu %hu %hu %hu %hu %hu %hu "
"%hu %hu %hu %hu %hu %hu %hu %hu %hu %hu",
p+0, p+1, p+2, p+3, p+4, p+5, p+6, p+7, p+8, p+9,
p+10, p+11, p+12, p+13, p+14,
p+15, p+16, p+17, p+18, p+19);
for (j = 0; j < 20; j++)
d[start + j] = p[j];
start += 20;
} else {
sscanf(buf,
"%hu %hu %hu %hu %hu %hu %hu %hu",
p+0, p+1, p+2, p+3, p+4, p+5, p+6, p+7);
for (j = 0; j < 8; j++)
d[start + j] = p[j];
}
}
// kps.push_back(KeypointWithDesc(x, y, d));
kps[i] = KeypointWithDesc(x, y, d);
}
return kps;
}
/* Read keys from binary file */
std::vector<KeypointWithDesc> ReadKeysFastBin(FILE *fp, bool descriptor,
float **scales,
float **orients)
{
int num_keys;
fread(&num_keys, sizeof(int), 1, fp);
std::vector<KeypointWithDesc> keys;
keys.resize(num_keys);
keypt_t *info;
unsigned char *d;
info = new keypt_t[num_keys];
fread(info, sizeof(keypt_t), num_keys, fp);
if (scales != NULL)
*scales = new float[num_keys];
if (orients != NULL)
*orients = new float[num_keys];
for (int i = 0; i < num_keys; i++) {
keys[i].m_x = info[i].x;
keys[i].m_y = info[i].y;
if (scales != NULL)
(*scales)[i] = info[i].scale;
if (orients != NULL)
(*orients)[i] = info[i].orient;
}
delete [] info;
if (!descriptor)
return keys;
d = new unsigned char [128 * num_keys];
fread(d, sizeof(unsigned char), 128 * num_keys, fp);
for (int i = 0; i < num_keys; i++) {
keys[i].m_d = d + 128 * i;
}
return keys;
}
/* Read keys from gzipped binary file */
std::vector<KeypointWithDesc> ReadKeysFastBinGzip(gzFile fp, bool descriptor,
float **scales,
float **orients)
{
int num_keys;
gzread(fp, &num_keys, sizeof(int));
std::vector<KeypointWithDesc> keys;
keys.resize(num_keys);
keypt_t *info;
unsigned char *d;
info = new keypt_t[num_keys];
gzread(fp, info, sizeof(keypt_t) * num_keys);
if (scales != NULL)
*scales = new float[num_keys];
if (orients != NULL)
*orients = new float[num_keys];
for (int i = 0; i < num_keys; i++) {
keys[i].m_x = info[i].x;
keys[i].m_y = info[i].y;
if (scales != NULL)
(*scales)[i] = info[i].scale;
if (orients != NULL)
(*orients)[i] = info[i].orient;
}
delete [] info;
if (!descriptor)
return keys;
d = new unsigned char [128 * num_keys];
gzread(fp, d, sizeof(unsigned char) * 128 * num_keys);
for (int i = 0; i < num_keys; i++) {
keys[i].m_d = d + 128 * i;
}
return keys;
}
#if 0
ANNkd_tree *CreateSearchTree(const std::vector<KeypointWithDesc> &k,
bool spatial, double alpha)
{
/* Create a new array of points */
int num_pts = (int) k.size();
int dim = 128;
if (spatial) dim = 130;
ANNpointArray pts = annAllocPts(num_pts, dim);
int offset = 0;
if (spatial) offset = 2;
for (int i = 0; i < num_pts; i++) {
int j;
assert(k[i].m_d != NULL);
if (spatial) {
pts[i][0] = alpha * k[i].m_x;
pts[i][1] = alpha * k[i].m_y;
}
for (j = 0; j < 128; j++)
pts[i][j+offset] = k[i].m_d[j];
}
/* Create a search tree for k2 */
ANNkd_tree *tree = new ANNkd_tree(pts, num_pts, dim, 4);
// annDeallocPts(pts);
return tree;
}
#endif
ann_1_1_char::ANNkd_tree
*CreateSearchTreeChar(const std::vector<KeypointWithDesc> &k)
{
/* Create a new array of points */
int num_pts = (int) k.size();
int dim = 128;
ann_1_1_char::ANNpointArray pts = ann_1_1_char::annAllocPts(num_pts, dim);
int offset = 0;
for (int i = 0; i < num_pts; i++) {
int j;
for (j = 0; j < 128; j++)
pts[i][j+offset] = k[i].m_d[j];
}
/* Create a search tree for k2 */
ann_1_1_char::ANNkd_tree *tree =
new ann_1_1_char::ANNkd_tree(pts, num_pts, dim, 4);
// ann_1_1_char::annDeallocPts(pts);
return tree;
}
/* Compute likely matches between two sets of keypoints */
std::vector<KeypointMatch> MatchKeys(const std::vector<KeypointWithDesc> &k1,
const std::vector<KeypointWithDesc> &k2,
bool registered, double ratio)
{
ann_1_1_char::annMaxPtsVisit(200);
int num_pts = 0;
std::vector<KeypointMatch> matches;
int *registered_idxs = NULL;
if (!registered) {
num_pts = (int) k2.size();
} else {
registered_idxs = new int[(int) k2.size()];
for (int i = 0; i < (int) k2.size(); i++) {
if (k2[i].m_extra >= 0) {
registered_idxs[num_pts] = i;
num_pts++;
}
}
}
/* Create a new array of points */
ann_1_1_char::ANNpointArray pts = ann_1_1_char::annAllocPts(num_pts, 128);
if (!registered) {
for (int i = 0; i < num_pts; i++) {
int j;
for (j = 0; j < 128; j++) {
pts[i][j] = k2[i].m_d[j];
}
}
} else {
for (int i = 0; i < num_pts; i++) {
int j;
int idx = registered_idxs[i];
for (j = 0; j < 128; j++) {
pts[i][j] = k2[idx].m_d[j];
}
}
}
clock_t start = clock();
/* Create a search tree for k2 */
ann_1_1_char::ANNkd_tree *tree = new ann_1_1_char::ANNkd_tree(pts, num_pts, 128, 4);
clock_t end = clock();
// printf("Building tree took %0.3fs\n",
// (end - start) / ((double) CLOCKS_PER_SEC));
/* Now do the search */
ann_1_1_char::ANNpoint query = ann_1_1_char::annAllocPt(128);
start = clock();
for (int i = 0; i < (int) k1.size(); i++) {
int j;
for (j = 0; j < 128; j++) {
query[j] = k1[i].m_d[j];
}
ann_1_1_char::ANNidx nn_idx[2];
ann_1_1_char::ANNdist dist[2];
tree->annkPriSearch(query, 2, nn_idx, dist, 0.0);
if (sqrt(((double) dist[0]) / ((double) dist[1])) <= ratio) {
if (!registered) {
matches.push_back(KeypointMatch(i, nn_idx[0]));
} else {
KeypointMatch match =
KeypointMatch(i, registered_idxs[nn_idx[0]]);
matches.push_back(match);
}
}
}
end = clock();
// printf("Searching tree took %0.3fs\n",
// (end - start) / ((double) CLOCKS_PER_SEC));
int num_matches = (int) matches.size();
printf("[MatchKeys] Found %d matches\n", num_matches);
/* Cleanup */
ann_1_1_char::annDeallocPts(pts);
ann_1_1_char::annDeallocPt(query);
delete tree;
return matches;
}
/* Compute likely matches between two sets of keypoints */
std::vector<KeypointMatchWithScore>
MatchKeysWithScore(const std::vector<KeypointWithDesc> &k1,
const std::vector<KeypointWithDesc> &k2,
bool registered,
double ratio)
{
ann_1_1_char::annMaxPtsVisit(200);
int num_pts = 0;
std::vector<KeypointMatchWithScore> matches;
int *registered_idxs = NULL;
if (!registered) {
num_pts = (int) k2.size();
} else {
registered_idxs = new int[(int) k2.size()];
for (int i = 0; i < (int) k2.size(); i++) {
if (k2[i].m_extra >= 0) {
registered_idxs[num_pts] = i;
num_pts++;
}
}
}
/* Create a new array of points */
ann_1_1_char::ANNpointArray pts = ann_1_1_char::annAllocPts(num_pts, 128);
if (!registered) {
for (int i = 0; i < num_pts; i++) {
int j;
for (j = 0; j < 128; j++) {
pts[i][j] = k2[i].m_d[j];
}
}
} else {
for (int i = 0; i < num_pts; i++) {
int j;
int idx = registered_idxs[i];
for (j = 0; j < 128; j++) {
pts[i][j] = k2[idx].m_d[j];
}
}
}
clock_t start = clock();
/* Create a search tree for k2 */
ann_1_1_char::ANNkd_tree *tree = new ann_1_1_char::ANNkd_tree(pts, num_pts, 128, 4);
clock_t end = clock();
// printf("Building tree took %0.3fs\n",
// (end - start) / ((double) CLOCKS_PER_SEC));
/* Now do the search */
ann_1_1_char::ANNpoint query = ann_1_1_char::annAllocPt(128);
start = clock();
for (int i = 0; i < (int) k1.size(); i++) {
int j;
for (j = 0; j < 128; j++) {
query[j] = k1[i].m_d[j];
}
ann_1_1_char::ANNidx nn_idx[2];
ann_1_1_char::ANNdist dist[2];
tree->annkPriSearch(query, 2, nn_idx, dist, 0.0);
if (sqrt(((double) dist[0]) / ((double) dist[1])) <= ratio) {
if (!registered) {
KeypointMatchWithScore match =
KeypointMatchWithScore(i, nn_idx[0], (float) dist[0]);
matches.push_back(match);
} else {
KeypointMatchWithScore match =
KeypointMatchWithScore(i, registered_idxs[nn_idx[0]],
(float) dist[0]);
matches.push_back(match);
}
}
}
end = clock();
// printf("Searching tree took %0.3fs\n",
// (end - start) / ((double) CLOCKS_PER_SEC));
int num_matches = (int) matches.size();
printf("[MatchKeysWithScore] Found %d matches\n", num_matches);
/* Cleanup */
ann_1_1_char::annDeallocPts(pts);
ann_1_1_char::annDeallocPt(query);
delete tree;
return matches;
}
/* Prune matches so that they are 1:1 */
std::vector<KeypointMatchWithScore>
PruneMatchesWithScore(const std::vector<KeypointMatchWithScore> &matches)
{
#ifndef WIN32
__gnu_cxx::hash_map<int, float> key_hash;
__gnu_cxx::hash_map<int, int> map;
#else
stdext::hash_map<int, float> key_hash;
stdext::hash_map<int, int> map;
#endif
int num_matches = (int) matches.size();
for (int i = 0; i < num_matches; i++) {
int idx1 = matches[i].m_idx1;
int idx2 = matches[i].m_idx2;
if (key_hash.find(idx2) == key_hash.end()) {
/* Insert the new element */
key_hash[idx2] = matches[i].m_score;
map[idx2] = idx1;
} else {
float old = key_hash[idx2];
if (old > matches[i].m_score) {
/* Replace the old entry */
key_hash[idx2] = matches[i].m_score;
map[idx2] = idx1;
}
}
}
std::vector<KeypointMatchWithScore> matches_new;
/* Now go through the list again, building a new list */
for (int i = 0; i < num_matches; i++) {
int idx1 = matches[i].m_idx1;
int idx2 = matches[i].m_idx2;
if (map[idx2] == idx1) {
matches_new.push_back(KeypointMatchWithScore(idx1, idx2,
key_hash[idx2]));
}
}
return matches_new;
}
/* Compute likely matches between two sets of keypoints */
std::vector<KeypointMatch>
MatchKeysExhaustive(const std::vector<KeypointWithDesc> &k1,
const std::vector<KeypointWithDesc> &k2,
bool registered, double ratio)
{
int num_pts = 0;
std::vector<KeypointMatch> matches;
int *registered_idxs = NULL;
if (!registered) {
num_pts = (int) k2.size();
} else {
registered_idxs = new int[(int) k2.size()];
for (int i = 0; i < (int) k2.size(); i++) {
if (k2[i].m_extra >= 0) {
registered_idxs[num_pts] = i;
num_pts++;
}
}
}
/* Create a new array of points */
ann_1_1_char::ANNpointArray pts = ann_1_1_char::annAllocPts(num_pts, 128);
if (!registered) {
for (int i = 0; i < num_pts; i++) {
int j;
for (j = 0; j < 128; j++) {
pts[i][j] = k2[i].m_d[j];
}
}
} else {
for (int i = 0; i < num_pts; i++) {
int j;
int idx = registered_idxs[i];
for (j = 0; j < 128; j++) {
pts[i][j] = k2[idx].m_d[j];
}
}
}
clock_t start = clock();
/* Create a search tree for k2 */
ann_1_1_char::ANNkd_tree *tree =
new ann_1_1_char::ANNkd_tree(pts, num_pts, 128, 4);
clock_t end = clock();
// printf("Building tree took %0.3fs\n",
// (end - start) / ((double) CLOCKS_PER_SEC));
/* Now do the search */
ann_1_1_char::ANNpoint query = ann_1_1_char::annAllocPt(128);
start = clock();
for (int i = 0; i < (int) k1.size(); i++) {
int j;
for (j = 0; j < 128; j++) {
query[j] = k1[i].m_d[j];
}
ann_1_1_char::ANNidx nn_idx[2];
ann_1_1_char::ANNdist dist[2];
tree->annkSearch(query, 2, nn_idx, dist, 0.0);
if (sqrt(((double) dist[0]) / ((double) dist[1])) <= ratio) {
if (!registered) {
matches.push_back(KeypointMatch(i, nn_idx[0]));
} else {
KeypointMatch match =
KeypointMatch(i, registered_idxs[nn_idx[0]]);
matches.push_back(match);
}
}
}
end = clock();
// printf("Searching tree took %0.3fs\n",
// (end - start) / ((double) CLOCKS_PER_SEC));
int num_matches = (int) matches.size();
printf("[MatchKeys] Found %d matches\n", num_matches);
/* Cleanup */
ann_1_1_char::annDeallocPts(pts);
ann_1_1_char::annDeallocPt(query);
delete tree;
return matches;
}
| agpl-3.0 |
marincelo/mtb-timing | spec/controllers/dashboard_controller_spec.rb | 236 | require 'rails_helper'
RSpec.describe DashboardController, type: :controller do
describe "GET #index" do
pending "returns http success" do
get :index
expect(response).to have_http_status(:success)
end
end
end
| agpl-3.0 |
metabit/bitsquare | core/src/main/java/io/bitsquare/trade/protocol/availability/messages/OfferMessage.java | 1613 | /*
* This file is part of Bitsquare.
*
* Bitsquare is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* Bitsquare is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Bitsquare. If not, see <http://www.gnu.org/licenses/>.
*/
package io.bitsquare.trade.protocol.availability.messages;
import io.bitsquare.app.Version;
import io.bitsquare.p2p.messaging.DirectMessage;
import javax.annotation.concurrent.Immutable;
@Immutable
public abstract class OfferMessage implements DirectMessage {
// That object is sent over the wire, so we need to take care of version compatibility.
private static final long serialVersionUID = Version.P2P_NETWORK_VERSION;
private final int messageVersion = Version.getP2PMessageVersion();
public final String offerId;
OfferMessage(String offerId) {
this.offerId = offerId;
}
@Override
public int getMessageVersion() {
return messageVersion;
}
@Override
public String toString() {
return "OfferMessage{" +
"messageVersion=" + messageVersion +
", offerId='" + offerId + '\'' +
'}';
}
}
| agpl-3.0 |
cindy820219/milsss | UI/new_for_sim_rhythm.py | 31502 | ### import parsing
from xml.dom.minidom import parse
import xml.dom.minidom
### import ElementTree
from xml.etree.ElementTree import ElementTree, Element, parse
### import math
import math
### if it's cut note, change melody_cutnote[] of staff_data
def melody_cut_note(melody_cutnote, measure, staff_data):
if(len(melody_cutnote) < measure) :
melody_cutnote.append(staff_data)
# print(melody_cutnote)
### count right hand and left hand rhythm of a measure
def melody_rhythm_count(staff_data, rhythm, melody_rhythm_R, melody_rhythm_L):
if(rhythm == '0.25'):
if(staff_data == '1'):
melody_rhythm_R[0] = 1
elif(staff_data == '2'):
melody_rhythm_L[0] = 1
if(rhythm == '0.5' or rhythm == '0.50'):
if(staff_data == '1'):
melody_rhythm_R[1] = 1
elif(staff_data == '2'):
melody_rhythm_L[1] = 1
if(rhythm == '0.75'):
if(staff_data == '1'):
melody_rhythm_R[2] = 1
elif(staff_data == '2'):
melody_rhythm_L[2] = 1
if(rhythm == '1' or rhythm == '1.0'):
if(staff_data == '1'):
melody_rhythm_R[3] = 1
elif(staff_data == '2'):
melody_rhythm_L[3] = 1
if(rhythm == '1.25'):
if(staff_data == '1'):
melody_rhythm_R[4] = 1
elif(staff_data == '2'):
melody_rhythm_L[4] = 1
if(rhythm == '1.5' or rhythm == '1.50'):
if(staff_data == '1'):
melody_rhythm_R[5] = 1
elif(staff_data == '2'):
melody_rhythm_L[5] = 1
if(rhythm == '1.75'):
if(staff_data == '1'):
melody_rhythm_R[6] = 1
elif(staff_data == '2'):
melody_rhythm_L[6] = 1
if(rhythm == '2' or rhythm == '2.0'):
if(staff_data == '1'):
melody_rhythm_R[7] = 1
elif(staff_data == '2'):
melody_rhythm_L[7] = 1
if(rhythm == '2.25'):
if(staff_data == '1'):
melody_rhythm_R[8] = 1
elif(staff_data == '2'):
melody_rhythm_L[8] = 1
if(rhythm == '2.5' or rhythm == '2.50'):
if(staff_data == '1'):
melody_rhythm_R[9] = 1
elif(staff_data == '2'):
melody_rhythm_L[9] = 1
if(rhythm == '2.75'):
if(staff_data == '1'):
melody_rhythm_R[10] = 1
elif(staff_data == '2'):
melody_rhythm_L[10] = 1
if(rhythm == '3' or rhythm == '3.0'):
if(staff_data == '1'):
melody_rhythm_R[11] = 1
elif(staff_data == '2'):
melody_rhythm_L[11] = 1
if(rhythm == '3.25'):
if(staff_data == '1'):
melody_rhythm_R[12] = 1
elif(staff_data == '2'):
melody_rhythm_L[12] = 1
if(rhythm == '3.5' or rhythm == '3.50'):
if(staff_data == '1'):
melody_rhythm_R[13] = 1
elif(staff_data == '2'):
melody_rhythm_L[13] = 1
if(rhythm == '3.75'):
if(staff_data == '1'):
melody_rhythm_R[14] = 1
elif(staff_data == '2'):
melody_rhythm_L[14] = 1
if(rhythm == '4.0' or rhythm == '4'):
if(staff_data == '1'):
melody_rhythm_R[15] = 1
elif(staff_data == '2'):
melody_rhythm_L[15] = 1
# print('melody_rhythm_R: ',melody_rhythm_R)
# print('melody_rhythm_L: ',melody_rhythm_L)
### function about melody rhythm
def melody_rhythm_func(melody_rhythm, melody_rhythm_R, melody_rhythm_L):
# print('R: ', melody_rhythm_R)
# print('L: ', melody_rhythm_L)
# print('find RRR: ',melody_rhythm_R.index(1))
# print('find LLL: ',melody_rhythm_L.index(1))
# ### maxi sum is 15 !
sum_R = sum(melody_rhythm_R)
sum_L = sum(melody_rhythm_L)
# print('sum_R, sum_L: ',sum_R, sum_L)
### if sum_R > sum_L
if(sum_R > sum_L):
# print('--------------' )
# print('sum_R > sum_L' )
melody_rhythm.append('1')
# print('addd 1')
if(sum_R < sum_L):
# print('--------------' )
# print('sum_R < sum_L' )
melody_rhythm.append('2')
# print('addd 2')
if(sum_R == sum_L):
# print('sum_R == sum_L' )
print('find RRR: ',melody_rhythm_R.index(1))
print('find LLL: ',melody_rhythm_L.index(1))
# if(melody_rhythm_R.index(1) ==True or melody_rhythm_L.index(1) == True):
R = melody_rhythm_R.index(1)
L = melody_rhythm_L.index(1)
if( R >= L):
melody_rhythm.append('2')
elif(R <= L):
melody_rhythm.append('1')
# elif(sum_R == sum_L):
# ### index
# print('ggggggggggggggggggggggggggg')
# print(melody_rhythm_R.index(1))
# print(melody_rhythm_L.index(1))
################
# if(melody_rhythm_L.index(1) == True):
# print('aaa')
# # melody_rhythm.append('1')
# else:
# if(melody_rhythm_R.index(1) < melody_rhythm_L.index(1)):
# melody_rhythm.append('1')
# elif(melody_rhythm_R.index(1) > melody_rhythm_L.index(1)):
# melody_rhythm.append('2')
# elif(melody_rhythm_R.index(1) == melody_rhythm_L.index(1)):
# melody_rhythm.append('1')
################
# print('melody_rhythm: ', melody_rhythm)
return(melody_rhythm)
### ### function about melody pitch
def melody_pitch_func(DOMTree, collection, step_data, octave_data, alter_data, staff_data, melody_pitch_temp_R, melody_pitch_temp_L, note_num_total_PI):
# print(step_data, octave_data, alter_data)
dict = {'C': 0, 'D': 2, 'E': 4, 'F': 5, 'G': 7, 'A': 9, 'B': 11}
# print("C: ", dict['C'])
# print('step: ', dict[step_data])
midi = (int(octave_data)+1) * 12 + dict[step_data]
if(alter_data == 'natural'):
midi = midi
elif(int(alter_data) == 1):
midi = midi + 1
elif(int(alter_data) == -1):
midi = midi - 1
if(staff_data == '1'):
melody_pitch_temp_R.append(midi)
elif(staff_data == '2'):
melody_pitch_temp_L.append(midi)
# print('pitch_temp_R: ', melody_pitch_temp_R)
# print('pitch_temp_L: ', melody_pitch_temp_L)
# print('midi: ', midi)
### add_node_MIDI
newEle = DOMTree.createElement("MIDI")
newText = DOMTree.createTextNode(str(midi))
newEle.appendChild(newText)
DOMTree.getElementsByTagName("note")[note_num_total_PI].appendChild(newEle)
DOMTree.toxml()
file = open("change_temp.xml", 'w')
file.write(DOMTree.toxml())
### function about melody_pitch
def melody_pitch_set_func(melody_pitch, melody_pitch_temp_R, melody_pitch_temp_L):
len_R = len(list(set(melody_pitch_temp_R)))
len_L = len(list(set(melody_pitch_temp_L)))
if(len_R > len_L):
melody_pitch.append('1')
if(len_R < len_L):
melody_pitch.append('2')
if(len_R == len_L):
melody_pitch.append('1')
# print('melody_pitch: ', melody_pitch)
return(melody_pitch)
### funtion pasing xml file (root, all notes' x location, MIDI, key_x_str, key_y_str)
### add node about total PI
def add_node_total_PI(DOMTree, note_num_total_PI, total_PI):
newEle = DOMTree.createElement("TotalPI")
newText = DOMTree.createTextNode(str(total_PI))
newEle.appendChild(newText)
DOMTree.getElementsByTagName("note")[note_num_total_PI].appendChild(newEle)
DOMTree.toxml()
file = open("change_temp.xml", 'w')
file.write(DOMTree.toxml())
### add node about rhythm
def add_node_rhythm(DOMTree, note_num_total_PI, rhythm):
newEle = DOMTree.createElement("rhythm")
newText = DOMTree.createTextNode(str(rhythm))
newEle.appendChild(newText)
DOMTree.getElementsByTagName("note")[note_num_total_PI].appendChild(newEle)
DOMTree.toxml()
file = open("change_temp.xml", 'w')
file.write(DOMTree.toxml())
def Melody_func(Melody, melody_cutnote, melody_rhythm, melody_pitch):
### measure !
print('melody_cutnote', melody_cutnote)
print('melody_rhythm ', melody_rhythm)
print('melody_pitch ', melody_pitch)
length = len(melody_pitch)
# print('length: ',length)
if(melody_rhythm[length-1] == melody_pitch[length-1]):
# print('same', melody_rhythm[length-1])
Melody.append(melody_rhythm[length-1])
elif(melody_rhythm[length-1] != melody_pitch[length-1] ):
# print('diff: ', melody_rhythm[length-1], melody_pitch[length-1])
# Melody.append('D')
### melody_rhythm = melody_cutnote ---> melody_rhythm
if(melody_rhythm[length-1] == melody_cutnote[length-1]):
Melody.append(melody_rhythm[length-1])
print('a')
### melody_pitch = melody_cutnote ---> melody_pitch
elif(melody_pitch[length-1] == melody_cutnote[length-1]):
Melody.append(melody_pitch[length-1])
print('b')
### melody_cutnote == 0 ---> '1'
elif(melody_cutnote[length-1] == '0'):
Melody.append('1')
print('c')
def add_Melody_node_func(DOMTree, Melody, level):
# print(Melody)
tree = parse('change_temp.xml')
root = tree.getroot()
# print('reverse', reMelody)
for measure in root.iter('measure'):
Main = Melody.pop(0)
for note in measure.iter('note'):
for staff in note.iter('staff'):
staff_text = staff.text
if(Main == staff_text):
xml.etree.ElementTree.SubElement(note, 'melody')
note.find('melody').text = 'main'
else:
xml.etree.ElementTree.SubElement(note, 'melody')
note.find('melody').text = 'no_main'
tree.write('change_rhythm.xml')
if(level == 2):
high_melody()
if(level == 1):
low_melody()
def high_melody():
print('high')
tree = parse('change_rhythm.xml')
root = tree.getroot()
for beats in root.iter('beats'):
print('' )
print('' )
print('' )
print('' )
beat_t = beats.text
# print('!!!!!!!!!! beats;', beats.text)
print('' )
print('' )
print('' )
print('' )
for measure in root.iter('measure'):
for note in measure.iter('note'):
for melody in note.iter('melody'):
melody_text = melody.text
for TotalPI in note.iter('TotalPI'):
TotalPI_text = TotalPI.text
break
if(beat_t != '3'):
# print(' beats == 4')
# print('melody_text, rhythm_text: ', melody_text, TotalPI_text)
if (3.0 > float(TotalPI_text) > 1.0 and melody_text == 'no_main'):
xml.etree.ElementTree.SubElement(note, 'rest')
if (5.0 > float(TotalPI_text) > 3.0 and melody_text == 'no_main'):
xml.etree.ElementTree.SubElement(note, 'rest')
# if(beat_t == 4):
# print(' beats!!! == 4')
# # print('melody_text, rhythm_text: ', melody_text, TotalPI_text)
# if (3.0 > float(TotalPI_text) > 1.0 and melody_text == 'no_main'):
# xml.etree.ElementTree.SubElement(note, 'rest')
# if (5.0 > float(TotalPI_text) > 3.0 and melody_text == 'no_main'):
# xml.etree.ElementTree.SubElement(note, 'rest')
if(beat_t == '3'):
# print(' beats == 3')
# print('melody_text, rhythm_text: ', melody_text, TotalPI_text)
if (float(TotalPI_text) > 1.0 and melody_text == 'no_main'):
xml.etree.ElementTree.SubElement(note, 'rest')
# if(beat_t == 3):
# print(' beats == 3')
# # print('melody_text, rhythm_text: ', melody_text, TotalPI_text)
# if (float(TotalPI_text) > 1.0 and melody_text == 'no_main'):
# xml.etree.ElementTree.SubElement(note, 'rest')
tree.write('delete_high.xml')
tree.write('change_temp.xml')
print(' ----------> have change high rhythm')
print(' save the file name "delete_high.xml"')
def low_melody():
print('low')
tree = parse('change_rhythm.xml')
root = tree.getroot()
for measure in root.iter('measure'):
for note in measure.iter('note'):
for melody in note.iter('melody'):
melody_text = melody.text
if(melody_text == 'no_main'):
xml.etree.ElementTree.SubElement(note, 'rest')
tree.write('delete_low.xml')
tree.write('change_temp.xml')
print(' ----------> have change low rhythm')
print(' save the file name "delete_low.xml"')
def rhythm_parsing(DOMTree, collection, hands, rhythm, level):
print(' ----------> in rhythm_parsing funtion')
# print('level: ',level)
### melody define
melody_cutnote = []
melody_rhythm = []
melody_rhythm_R = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
melody_rhythm_L = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
sum_R = 0
sum_L = 0
melody_pitch = []
melody_pitch_temp_R = []
melody_pitch_temp_L = []
Melody = []
'''
count all the notes
'''
notes_all = 0
notes_rest = 0
notes_whole = 0
notes_half = 0
notes_quarter = 0
notes_eighth = 0
notes_16th = 0
notes_notes = 0
### measure's tag
measure_tag = 0
### pre staff - right hand or left hand
pre_staff = 0
### measure
measure = 1
### pre right hand pre x, left hand pre x, step and octave
pre_x_1 = pre_x_2 = ''
pre_step_data = pre_octave_data = ''
### pre staff
pre_staff_data = 1
# about the mini_rhythm for the simple
mini_rhythm = 6
'''
### about the ID
# ID = ''
'''
# about the (time.rhythm / measure)
timing = 0
flag_of_daul = 0
### single
single_measure = 1
single_time = 0
single_pre_x = ''
single_flag_of_daul = 0
### hand default is 1, but we need to input the 2 hands xml file
hand = 1
### the number of notes
note_num = 0
### total PI
total_PI = 1
note_num_total_PI = 0
'''
to defind the sheet: key && divs && time
### divisions 3/4 or 4/4
### key : fifths
### time : beats and beattype
'''
attrs = collection.getElementsByTagName('attributes')
for attr in attrs:
divs = collection.getElementsByTagName('divisions')
for div in divs:
divisions = div.childNodes[0].data
keys = collection.getElementsByTagName('key')
for key in keys:
fifths = key.getElementsByTagName('fifths')[0]
fifths = fifths.childNodes[0].data
print('key:' ,fifths)
times = collection.getElementsByTagName('time')
for time in times:
beats = time.getElementsByTagName('beats')[0]
beattype = time.getElementsByTagName('beat-type')[0]
beats = beats.childNodes[0].data
beattype = beattype.childNodes[0].data
print('times: ',beats+'/'+beattype+' ')
### about the write tempo
directions = collection.getElementsByTagName('direction')
for direction in directions:
per_minute = collection.getElementsByTagName('per-minute')[0]
per_minute = per_minute.childNodes[0].data
### about the real tempo
sounds = collection.getElementsByTagName('sound')
for sound in sounds:
if (sound.hasAttribute('tempo')):
sound = sound.getAttribute('tempo')
print('tempo: ',sound)
### ### count all_notes
notes = collection.getElementsByTagName('note')
for note in notes:
notes_all += 1
### print about the pitch / type / staff / rhyth / PI
print('pitch\t\ttype\t\tstaff\t\trhythm\t\tPI')
print('1=======================================================================')
for note in notes:
### if note.hasAttribute('default-x'):
### print('default-x: %s' % note.getAttribute('default-x'))
### count note when for run again
note_num = int(note_num) + 1
### bool : whether the notes are daul?
is_daul = 0
### daul
daul = ''
close_daul = 0
### default str = ''
pitch = step_data = octave_data = type_data = staff_next_data = staff_data = alter_data = ''
### duration and count the rhythm
duration = note.getElementsByTagName('duration')[0]
rhythm = str(float(duration.childNodes[0].data)/float(divisions))
### about stem : up and down
if (note.getElementsByTagName('stem')):
stem = note.getElementsByTagName('stem')[0]
stem = stem.childNodes[0].data
# print('stem: ',stem)
else:
### notes are rest
stem = 0
### single
if(timing >= int(beats) and (hand != 1)):
# print('=======================================================================')
# single_measure += 1
timing = 0
### accidental : temporary sharp or flat
### if no temporary accidental --> alter = 0
### else alter = 50 (it has been changed)
if (note.getElementsByTagName('accidental')):
accidental = note.getElementsByTagName('accidental')[0]
alter_data = accidental.childNodes[0].data
# print(?'haaaaa' , alter_data)
# alter_data = '1'
if(alter_data == 'natural'):
# print(' is natural')
alter_data = alter_data
else:
alter_data = '5'
### about the type: type = note.getElementsByTagName('type')[0]
if (note.getElementsByTagName('type')):
type = note.getElementsByTagName('type')[0]
type_data = type.childNodes[0].data
### about the pitch and octave
if (note.getElementsByTagName('pitch')):
pitch = note.getElementsByTagName('pitch')[0]
step = pitch.getElementsByTagName('step')[0]
octave = pitch.getElementsByTagName('octave')[0]
#if (step.childNodes):
step_data = step.childNodes[0].data
#if (octave.childNodes):
octave_data = octave.childNodes[0].data
if(pitch.getElementsByTagName('alter')):
alter = pitch.getElementsByTagName('alter')[0]
alter_data = alter.childNodes[0].data
# print(alter.childNodes[0].data)
# print('alter_data: ',alter_data)
'''
rest notes :
octave_data = 10,
pre_step_data = pre_x_1 = pre_x_2 = ''
step_data = '[ ]'
type_data = '---'
'''
if (step_data == ''):
step_data = '[ ]'
pre_step_data = pre_x_1 = pre_x_2 = ''
octave_data = 9
if (type_data == ''):
type_data = '---'
### to reguar the right-hand or left-hand
# if (note.getElementsByTagName('staff')):
### both hands
if (hands != 1):
hand = 2
### find out the staff
staff = note.getElementsByTagName('staff')[0]
staff_data = staff.childNodes[0].data
# flag_of_daul to 0
flag_of_daul = 0
### next measure
if (staff_data != pre_staff_data):
total_PI = 1
### staff_data change the pre_staff_data
pre_staff_data = staff_data
### dual !!! (int(staff_data),pre_staff)
if(note.hasAttribute('default-x')):
#if(int(staff_data) == pre_staff):
now_x = note.getAttribute('default-x')
### when daul very close
if(int(staff_data)==1):
if(pre_x_1 != ''):
pre_x_1_flaot = float(pre_x_1)
if(now_x != ''):
now_x_float = float(now_x)
close_daul = math.fabs(pre_x_1_flaot-now_x_float)
#if(pre_x_1==now_x):
if(close_daul < 15):
if(pre_x_1 != ''):
daul = 'there is a right daul: '+pre_step_data+pre_octave_data+' and '+step_data+octave_data
flag_of_daul = 1
# simple_daul(pre_step_data, pre_octave_data, step_data, octave_data)
if(int(staff_data)==2):
if(pre_x_2 != ''):
pre_x_2_flaot = float(pre_x_2)
if(now_x != ''):
now_x_float = float(now_x)
close_daul = math.fabs(pre_x_2_flaot-now_x_float)
if(close_daul < 15):
if(pre_x_2 != ''):
# if(pre_x_2==now_x):
#if(b <= 30):
#print('there is a left daul: ', pre_step_data+pre_octave_data, 'and',step_data+octave_data)
daul = 'there is a left daul: '+pre_step_data+pre_octave_data+' and '+step_data+octave_data
flag_of_daul = 1
# simple_daul(pre_step_data, pre_octave_data, step_data, octave_data)
# next measure
if (int(staff_data)== 1):
if(pre_staff == 2):
### melody about cut note !
### if no cut note, then put '0' in the array melody_cutnote[]
if(len(melody_cutnote) < measure) :
melody_cutnote.append('0')
### important !!!
# print('melody_cutnote:' ,melody_cutnote)
### melody about rhythm and count all the different
# print(melody_rhythm_R, ' ', sum(melody_rhythm_R))
# print(melody_rhythm_L, ' ', sum(melody_rhythm_L))
melody_rhythm = melody_rhythm_func(melody_rhythm, melody_rhythm_R, melody_rhythm_L)
### important !!!
# print('melody_rhythm: ', melody_rhythm)
### next measure, need to clear melody_rhythm_R and melody_rhythm_L
melody_pitch = melody_pitch_set_func(melody_pitch, melody_pitch_temp_R, melody_pitch_temp_L)
### important !!!
# print('melody_pitch: ', melody_pitch)
### function for the Melody
Melody_func(Melody, melody_cutnote, melody_rhythm, melody_pitch)
### clear for the next measure !!
melody_rhythm_R = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
melody_rhythm_L = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
melody_pitch_temp_R = []
melody_pitch_temp_L = []
# print('pre_staff == 2 and staff_data == 1')
#print(measure)
timing = 0
measure = measure+1
print(measure,'=======================================================================')
pre_staff = 1
pre_step_data = pre_x_1 = pre_x_2 = ''
total_PI = 1
if(int(staff_data)== 1):
pre_staff = 1
pre_x_1 = note.getAttribute('default-x')
pre_step_data = step_data
pre_octave_data = octave_data
if(int(staff_data)== 2):
pre_staff = 2
pre_x_2 = note.getAttribute('default-x')
pre_step_data = step_data
pre_octave_data = octave_data
# print(staff_data_2_x)
if(timing > int(beats)):
timing = 0
'''single'''
'''single'''
### one-hand for measure and daul
if (hands == 1):
single_flag_of_daul = 0
# PI = 1
staff = note.getElementsByTagName('staff')[0]
staff_data = staff.childNodes[0].data
if(note.hasAttribute('default-x')):
single_now_x = note.getAttribute('default-x')
if(single_pre_x != ''):
single_pre_x_flaot = float(single_pre_x)
if(single_now_x != ''):
single_now_x_float = float(single_now_x)
close_daul = math.fabs(single_pre_x_flaot-single_now_x_float)
if(close_daul < 10):
if(single_pre_x != ''):
daul='there is a daul: ' + str(pre_step_data) + str(pre_octave_data) + ' and ' + str(step_data) + str(octave_data)
single_flag_of_daul = 1
else:
single_now_x = ''
pre_step_data = step_data
pre_octave_data = octave_data
single_pre_x = single_now_x
#print(single_time,timing)
if (single_flag_of_daul == 0):
single_time += float(rhythm)
if (single_time > int(beats)):
single_measure += 1
print(single_measure,'----------------------------------------------------------------------')
single_time = 0
single_time += float(rhythm)
timing = 0
single_pre_x = ''
###
measure = single_measure
total_PI = 1
timing = single_time
# print ('timing: ', timing)
'''single'''
'''single'''
### staff_data = 0
# if (staff_data == ''):
# staff_data = '0'
if (staff_data == ''):
staff_data = '0'
# about the timing
if(flag_of_daul == 0 and (hand != 1) and hands == 0):
timing += float(rhythm)
if(single_flag_of_daul == 0 and hands == 1):
timing += float(rhythm)
### About the PI
PI = math.floor(timing - float(rhythm) +1)
### about the ID : note num(4) // measure(2) // staff(1) // timing(1)
### ID: note_num
# note_num = str(note_num).zfill(4)
### ID: measure_id
# measure_id = str(measure)
# measure_id = measure_id.zfill(2)
'''
single
### ID: measure_id of one-hand
if staff_data == '0':
measure_id = str(single_measure)
measure_id = measure_id.zfill(2)
'''
### ID: staff_id
# staff_id = staff_data
# ID = note_num + measure_id + staff_id + str(PI)
### $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ ####
print(step_data
+str(octave_data)
+' '+alter_data
+'\t\t'+type_data
+'\t\t'+staff_data
+'\t\t'+rhythm
+' '+str(PI))
add_node_rhythm(DOMTree, note_num_total_PI, rhythm)
### melody - cut note !!
if(rhythm =='0.75'):
melody_cut_note(melody_cutnote, measure, staff_data)
# print(melody_cutnote)
### melody - rhythm !!
if(step_data != '[ ]'):
melody_rhythm_count(staff_data, rhythm, melody_rhythm_R, melody_rhythm_L)
### melody - pitch !!
if(step_data != '[ ]'):
melody_pitch_func(DOMTree, collection, step_data, str(octave_data), alter_data, staff_data, melody_pitch_temp_R, melody_pitch_temp_L, note_num_total_PI)
### count parameters of all the notes
if (step_data == '[ ]'):
notes_rest += 1
else:
if (type_data == 'whole'):
notes_whole += 1
if (type_data == 'half'):
notes_half += 1
if (type_data == 'quarter'):
notes_quarter += 1
if (type_data == 'eighth'):
notes_eighth += 1
if (type_data == '16th'):
notes_16th += 1
# print('notes_all, notes_whole, notes_half, notes_quarter, notes_eighth, notes_16th, notes_rest: ',
# notes_all
# notes_whole,
# notes_half,
# notes_quarter,
# notes_eighth,
# notes_16th,
# notes_rest)
### is daul
if (daul != ''):
print(daul)
is_daul = 1
### no daul
if(is_daul == 0):
total_PI = total_PI
#########
if(total_PI ==0):
total_PI = 1
### is daul and then is_daul_2 = 1
if (is_daul == 1):
total_PI = total_PI - float(rhythm)
#########
if(total_PI ==0):
total_PI = 1
is_daul_2 = 1
if (total_PI >= (int(beats)+1)):
total_PI = float(total_PI) - float(rhythm)
# print('total_PI: ',total_PI)
### add_node about total_PI !!!
add_node_total_PI(DOMTree, note_num_total_PI, total_PI)
total_PI = float(total_PI)
note_num_total_PI = note_num_total_PI + 1
# print('note_num: ',note_num_total_PI)
if (total_PI < int(beats)+1):
total_PI = total_PI + float(rhythm)
if(total_PI > int(beats)+1):
total_PI = 1
### mini_rhythm
if(float(rhythm) < float(mini_rhythm)):
mini_rhythm = rhythm
# ### max_measure
# if(int(measure) > int(max_measure)):
# max_measure = measure
# print('max_measure:' ,max_measure)
print('mini rhythm is : ',mini_rhythm)
# print('max_measure: ',max_measure)
### melody
###### the final measure !!!
### melody cut note
if(len(melody_cutnote) < measure) :
melody_cutnote.append('0')
# print('melody_cutnote:', melody_cutnote)
### melody rhythm final measure
melody_rhythm = melody_rhythm_func(melody_rhythm, melody_rhythm_R, melody_rhythm_L)
# print('melody_pitch: ', melody_rhythm)
### melody pitch final measure
melody_pitch = melody_pitch_set_func(melody_pitch, melody_pitch_temp_R, melody_pitch_temp_L)
# print('melody_pitch: ', melody_pitch)
Melody_func(Melody, melody_cutnote, melody_rhythm, melody_pitch)
print()
print()
print()
print('//////////////////////////////////////////////////////////////')
print()
print()
print()
# print(Melody)
add_Melody_node_func(DOMTree, Melody, level)
# DOMTree = xml.dom.minidom.parse('sonatina2.xml')
# collection = DOMTree.documentElement
# rhythm = 1
# hands = 0
# level = 0
# rhythm_parsing(DOMTree, collection, hands, rhythm, level) | agpl-3.0 |
automenta/narchy | lab/src/main/java/jake2/sound/jsound/SND_MIX.java | 13066 | /*
* SND_MIX.java
* Copyright (C) 2004
*
* $Id: SND_MIX.java,v 1.2 2004-09-22 19:22:09 salomo Exp $
*/
/*
Copyright (C) 1997-2001 Id Software, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 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 jake2.sound.jsound;
import jake2.game.cvar_t;
import jake2.sound.WaveLoader;
import jake2.sound.sfx_t;
import jake2.sound.sfxcache_t;
import jake2.util.Math3D;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
/**
* SND_MIX
*/
public class SND_MIX extends SND_JAVA {
static final int MAX_CHANNELS = 32;
static final int MAX_RAW_SAMPLES = 8192;
static class playsound_t {
playsound_t prev, next;
sfx_t sfx;
float volume;
float attenuation;
int entnum;
int entchannel;
boolean fixed_origin;
final float[] origin = { 0, 0, 0 };
long begin;
public void clear() {
prev = next = null;
sfx = null;
volume = attenuation = begin = entnum = entchannel = 0;
fixed_origin = false;
Math3D.VectorClear(origin);
}
}
static class channel_t {
sfx_t sfx;
int leftvol;
int rightvol;
int end;
int pos;
int looping;
int entnum;
int entchannel;
final float[] origin = { 0, 0, 0 };
float dist_mult;
int master_vol;
boolean fixed_origin;
boolean autosound;
void clear() {
sfx = null;
dist_mult = leftvol = rightvol = end = pos = looping = entnum = entchannel = master_vol = 0;
Math3D.VectorClear(origin);
fixed_origin = autosound = false;
}
}
static class portable_samplepair_t {
int left;
int right;
}
static cvar_t s_volume;
static int s_rawend;
static final int PAINTBUFFER_SIZE = 2048;
static final IntBuffer paintbuffer = IntBuffer.allocate(PAINTBUFFER_SIZE * 2);
static final int[][] snd_scaletable = new int[32][256];
static IntBuffer snd_p;
static ShortBuffer snd_out;
static int snd_linear_count;
static int snd_vol;
public static int paintedtime;
static final playsound_t s_pendingplays = new playsound_t();
static final IntBuffer s_rawsamples = IntBuffer.allocate(MAX_RAW_SAMPLES * 2);
static final channel_t[] channels = new channel_t[MAX_CHANNELS];
static {
for (int i = 0; i < MAX_CHANNELS; i++)
channels[i] = new channel_t();
}
static void WriteLinearBlastStereo16() {
int i;
int val;
for (i = 0; i < snd_linear_count; i += 2) {
val = snd_p.get(i) >> 8;
if (val > 0x7fff)
snd_out.put(i, (short) 0x7fff);
else if (val < (short) 0x8000)
snd_out.put(i, (short) 0x8000);
else
snd_out.put(i, (short) val);
val = snd_p.get(i + 1) >> 8;
if (val > 0x7fff)
snd_out.put(i + 1, (short) 0x7fff);
else if (val < (short) 0x8000)
snd_out.put(i + 1, (short) 0x8000);
else
snd_out.put(i + 1, (short) val);
}
}
static void TransferStereo16(ByteBuffer pbuf, int endtime) {
int lpos;
int lpaintedtime;
snd_p = paintbuffer;
lpaintedtime = paintedtime;
while (lpaintedtime < endtime) {
lpos = lpaintedtime & ((dma.samples >> 1) - 1);
snd_out = pbuf.asShortBuffer();
snd_out.position(lpos << 1);
snd_out = snd_out.slice();
snd_linear_count = (dma.samples >> 1) - lpos;
if (lpaintedtime + snd_linear_count > endtime)
snd_linear_count = endtime - lpaintedtime;
snd_linear_count <<= 1;
WriteLinearBlastStereo16();
paintbuffer.position(snd_linear_count);
snd_p = paintbuffer.slice();
lpaintedtime += (snd_linear_count >> 1);
}
}
/*
* =================== S_TransferPaintBuffer
*
* ===================
*/
static void TransferPaintBuffer(int endtime) {
int out_idx;
int count;
int out_mask;
int p;
int step;
int val;
ByteBuffer pbuf = ByteBuffer.wrap(dma.buffer);
pbuf.order(ByteOrder.LITTLE_ENDIAN);
if (SND_DMA.s_testsound.value != 0.0f) {
int i;
int count2;
count2 = (endtime - paintedtime) * 2;
int v;
for (i = 0; i < count2; i += 2) {
v = (int) (Math.sin((paintedtime + i) * 0.1) * 20000 * 256);
paintbuffer.put(i, v);
paintbuffer.put(i + 1, v);
}
}
if (dma.samplebits == 16 && dma.channels == 2) {
TransferStereo16(pbuf, endtime);
} else {
p = 0;
count = (endtime - paintedtime) * dma.channels;
out_mask = dma.samples - 1;
out_idx = paintedtime * dma.channels & out_mask;
step = 3 - dma.channels;
if (dma.samplebits == 16) {
ShortBuffer out = pbuf.asShortBuffer();
while (count-- > 0) {
val = paintbuffer.get(p) >> 8;
p += step;
if (val > 0x7fff)
val = 0x7fff;
else if (val < (short) 0x8000)
val = (short) 0x8000;
out.put(out_idx, (short) val);
out_idx = (out_idx + 1) & out_mask;
}
} else if (dma.samplebits == 8) {
while (count-- > 0) {
val = paintbuffer.get(p) >> 8;
p += step;
if (val > 0x7fff)
val = 0x7fff;
else if (val < (short) 0x8000)
val = (short) 0x8000;
pbuf.put(out_idx, (byte) (val >>> 8));
out_idx = (out_idx + 1) & out_mask;
}
}
}
}
/*
* ===============================================================================
*
* CHANNEL MIXING
*
* ===============================================================================
*/
static void PaintChannels(int endtime) {
int i;
int end;
channel_t ch;
sfxcache_t sc;
int ltime, count;
playsound_t ps;
snd_vol = (int) (s_volume.value * 256);
while (paintedtime < endtime) {
end = endtime;
if (endtime - paintedtime > PAINTBUFFER_SIZE)
end = paintedtime + PAINTBUFFER_SIZE;
while (true) {
ps = s_pendingplays.next;
if (ps == s_pendingplays)
break;
if (ps.begin <= paintedtime) {
SND_DMA.IssuePlaysound(ps);
continue;
}
if (ps.begin < end)
end = (int) ps.begin;
break;
}
if (s_rawend < paintedtime) {
for (i = 0; i < (end - paintedtime) * 2; i++) {
paintbuffer.put(i, 0);
}
} else {
int s;
int stop;
stop = (end < s_rawend) ? end : s_rawend;
for (i = paintedtime; i < stop; i++) {
s = i & (MAX_RAW_SAMPLES - 1);
paintbuffer.put((i - paintedtime) * 2, s_rawsamples
.get(2 * s));
paintbuffer.put((i - paintedtime) * 2 + 1, s_rawsamples
.get(2 * s) + 1);
}
for (; i < end; i++) {
paintbuffer.put((i - paintedtime) * 2, 0);
paintbuffer.put((i - paintedtime) * 2 + 1, 0);
}
}
for (i = 0; i < MAX_CHANNELS; i++) {
ch = channels[i];
ltime = paintedtime;
while (ltime < end) {
if (ch.sfx == null || (ch.leftvol == 0 && ch.rightvol == 0))
break;
count = end - ltime;
if (ch.end - ltime < count)
count = ch.end - ltime;
sc = WaveLoader.LoadSound(ch.sfx);
if (sc == null)
break;
if (count > 0 && ch.sfx != null) {
if (sc.width == 1)
PaintChannelFrom8(ch, sc, count, ltime
- paintedtime);
else
PaintChannelFrom16(ch, sc, count, ltime
- paintedtime);
ltime += count;
}
if (ltime >= ch.end) {
if (ch.autosound) {
ch.pos = 0;
ch.end = ltime + sc.length;
} else if (sc.loopstart >= 0) {
ch.pos = sc.loopstart;
ch.end = ltime + sc.length - ch.pos;
} else {
ch.sfx = null;
}
}
}
}
TransferPaintBuffer(end);
paintedtime = end;
}
}
static void InitScaletable() {
int i, j;
int scale;
s_volume.modified = false;
for (i = 0; i < 32; i++) {
scale = (int) (i * 8 * 256 * s_volume.value);
for (j = 0; j < 256; j++)
snd_scaletable[i][j] = ((byte) j) * scale;
}
}
static void PaintChannelFrom8(channel_t ch, sfxcache_t sc, int count,
int offset) {
int data;
int[] lscale;
int[] rscale;
int sfx;
int i;
portable_samplepair_t samp;
if (ch.leftvol > 255)
ch.leftvol = 255;
if (ch.rightvol > 255)
ch.rightvol = 255;
lscale = snd_scaletable[ch.leftvol >> 3];
rscale = snd_scaletable[ch.rightvol >> 3];
sfx = ch.pos;
for (i = 0; i < count; i++, offset++) {
int left = paintbuffer.get(offset * 2);
int right = paintbuffer.get(offset * 2 + 1);
data = sc.data[sfx + i];
left += lscale[data];
right += rscale[data];
paintbuffer.put(offset * 2, left);
paintbuffer.put(offset * 2 + 1, right);
}
ch.pos += count;
}
private static ByteBuffer bb;
static void PaintChannelFrom16(channel_t ch, sfxcache_t sc, int count,
int offset) {
int data;
int left, right;
int leftvol, rightvol;
int sfx;
int i;
portable_samplepair_t samp;
leftvol = ch.leftvol * snd_vol;
rightvol = ch.rightvol * snd_vol;
ByteBuffer bb = ByteBuffer.wrap(sc.data);
bb.order(ByteOrder.LITTLE_ENDIAN);
ShortBuffer sb = bb.asShortBuffer();
sfx = ch.pos;
for (i = 0; i < count; i++, offset++) {
left = paintbuffer.get(offset * 2);
right = paintbuffer.get(offset * 2 + 1);
data = sb.get(sfx + i);
left += (data * leftvol) >> 8;
right += (data * rightvol) >> 8;
paintbuffer.put(offset * 2, left);
paintbuffer.put(offset * 2 + 1, right);
}
ch.pos += count;
}
} | agpl-3.0 |
KWZwickau/KREDA-Sphere | Library/Bootstrap.Jasny/3.1.3/vendor/twitter/bootstrap/grunt/bs-lessdoc-parser.js | 6582 | /*!
* Bootstrap Grunt task for parsing Less docstrings
* http://getbootstrap.com
* Copyright 2014-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
'use strict';
var Markdown = require( 'markdown-it' );
function markdown2html( markdownString )
{
var md = new Markdown();
// the slice removes the <p>...</p> wrapper output by Markdown processor
return md.render( markdownString.trim() ).slice( 3, -5 );
}
/*
Mini-language:
//== This is a normal heading, which starts a section. Sections group variables together.
//## Optional description for the heading
//=== This is a subheading.
//** Optional description for the following variable. You **can** use Markdown in descriptions to discuss `<html>` stuff.
@foo: #fff;
//-- This is a heading for a section whose variables shouldn't be customizable
All other lines are ignored completely.
*/
var CUSTOMIZABLE_HEADING = /^[/]{2}={2}(.*)$/;
var UNCUSTOMIZABLE_HEADING = /^[/]{2}-{2}(.*)$/;
var SUBSECTION_HEADING = /^[/]{2}={3}(.*)$/;
var SECTION_DOCSTRING = /^[/]{2}#{2}(.+)$/;
var VAR_ASSIGNMENT = /^(@[a-zA-Z0-9_-]+):[ ]*([^ ;][^;]*);[ ]*$/;
var VAR_DOCSTRING = /^[/]{2}[*]{2}(.+)$/;
function Section( heading, customizable )
{
this.heading = heading.trim();
this.id = this.heading.replace( /\s+/g, '-' ).toLowerCase();
this.customizable = customizable;
this.docstring = null;
this.subsections = [];
}
Section.prototype.addSubSection = function( subsection )
{
this.subsections.push( subsection );
};
function SubSection( heading )
{
this.heading = heading.trim();
this.id = this.heading.replace( /\s+/g, '-' ).toLowerCase();
this.variables = [];
}
SubSection.prototype.addVar = function( variable )
{
this.variables.push( variable );
};
function VarDocstring( markdownString )
{
this.html = markdown2html( markdownString );
}
function SectionDocstring( markdownString )
{
this.html = markdown2html( markdownString );
}
function Variable( name, defaultValue )
{
this.name = name;
this.defaultValue = defaultValue;
this.docstring = null;
}
function Tokenizer( fileContent )
{
this._lines = fileContent.split( '\n' );
this._next = undefined;
}
Tokenizer.prototype.unshift = function( token )
{
if (this._next !== undefined) {
throw new Error( 'Attempted to unshift twice!' );
}
this._next = token;
};
Tokenizer.prototype._shift = function()
{
// returning null signals EOF
// returning undefined means the line was ignored
if (this._next !== undefined) {
var result = this._next;
this._next = undefined;
return result;
}
if (this._lines.length <= 0) {
return null;
}
var line = this._lines.shift();
var match = null;
match = SUBSECTION_HEADING.exec( line );
if (match !== null) {
return new SubSection( match[1] );
}
match = CUSTOMIZABLE_HEADING.exec( line );
if (match !== null) {
return new Section( match[1], true );
}
match = UNCUSTOMIZABLE_HEADING.exec( line );
if (match !== null) {
return new Section( match[1], false );
}
match = SECTION_DOCSTRING.exec( line );
if (match !== null) {
return new SectionDocstring( match[1] );
}
match = VAR_DOCSTRING.exec( line );
if (match !== null) {
return new VarDocstring( match[1] );
}
var commentStart = line.lastIndexOf( '//' );
var varLine = commentStart === -1 ? line : line.slice( 0, commentStart );
match = VAR_ASSIGNMENT.exec( varLine );
if (match !== null) {
return new Variable( match[1], match[2] );
}
return undefined;
};
Tokenizer.prototype.shift = function()
{
while (true) {
var result = this._shift();
if (result === undefined) {
continue;
}
return result;
}
};
function Parser( fileContent )
{
this._tokenizer = new Tokenizer( fileContent );
}
Parser.prototype.parseFile = function()
{
var sections = [];
while (true) {
var section = this.parseSection();
if (section === null) {
if (this._tokenizer.shift() !== null) {
throw new Error( 'Unexpected unparsed section of file remains!' );
}
return sections;
}
sections.push( section );
}
};
Parser.prototype.parseSection = function()
{
var section = this._tokenizer.shift();
if (section === null) {
return null;
}
if (!(section instanceof Section)) {
throw new Error( 'Expected section heading; got: ' + JSON.stringify( section ) );
}
var docstring = this._tokenizer.shift();
if (docstring instanceof SectionDocstring) {
section.docstring = docstring;
} else {
this._tokenizer.unshift( docstring );
}
this.parseSubSections( section );
return section;
};
Parser.prototype.parseSubSections = function( section )
{
while (true) {
var subsection = this.parseSubSection();
if (subsection === null) {
if (section.subsections.length === 0) {
// Presume an implicit initial subsection
subsection = new SubSection( '' );
this.parseVars( subsection );
} else {
break;
}
}
section.addSubSection( subsection );
}
if (section.subsections.length === 1 && !section.subsections[0].heading && section.subsections[0].variables.length === 0) {
// Ignore lone empty implicit subsection
section.subsections = [];
}
};
Parser.prototype.parseSubSection = function()
{
var subsection = this._tokenizer.shift();
if (subsection instanceof SubSection) {
this.parseVars( subsection );
return subsection;
}
this._tokenizer.unshift( subsection );
return null;
};
Parser.prototype.parseVars = function( subsection )
{
while (true) {
var variable = this.parseVar();
if (variable === null) {
return;
}
subsection.addVar( variable );
}
};
Parser.prototype.parseVar = function()
{
var docstring = this._tokenizer.shift();
if (!(docstring instanceof VarDocstring)) {
this._tokenizer.unshift( docstring );
docstring = null;
}
var variable = this._tokenizer.shift();
if (variable instanceof Variable) {
variable.docstring = docstring;
return variable;
}
this._tokenizer.unshift( variable );
return null;
};
module.exports = Parser;
| agpl-3.0 |
ANAXRIDER/OpenAI | OpenAI/OpenAI/Penalties/Pen_GVG_039.cs | 284 | using System;
using System.Collections.Generic;
using System.Text;
namespace OpenAI
{
class Pen_GVG_039 : PenTemplate //vitalitytotem
{
public override float getPlayPenalty(Playfield p, Handmanager.Handcard hc, Minion target, int choice, bool isLethal)
{
return 0;
}
}
}
| agpl-3.0 |
cloudbau/donar | app/controllers/application_controller.rb | 566 | class ApplicationController < ActionController::Base
protect_from_forgery
before_filter { I18n.locale = params[:locale] || :en }
before_filter :set_open_stack_connection
rescue_from Excon::Errors::Unauthorized do |exception|
# sign out user when session has timed out
sign_out(current_user)
redirect_to new_user_session_path, error: exception.message
end
protected
def set_open_stack_connection
OpenStack.user = current_user if user_signed_in?
end
def default_url_options(options = {})
{ :locale => I18n.locale }
end
end
| agpl-3.0 |
ivaylokenov/MyTested.Mvc | test/MyTested.AspNetCore.Mvc.ViewComponents.Test/Properties/AssemblyInfo.cs | 369 | using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Xunit;
[assembly: ApplicationPart("MyTested.AspNetCore.Mvc.Test.Setups")]
[assembly: AssemblyProduct("MyTested.AspNetCore.Mvc.ViewComponents.Test")]
[assembly: ComVisible(false)]
[assembly: CollectionBehavior(DisableTestParallelization = true)]
| agpl-3.0 |
wwood/ApiLocServer | db/migrate/053_create_annotations.rb | 334 | class CreateAnnotations < ActiveRecord::Migration
def self.up
create_table :annotations do |t|
t.references :coding_region
t.string :annotation
t.timestamps
end
add_index :annotations, [:coding_region_id, :annotation], :unique => true
end
def self.down
drop_table :annotations
end
end
| agpl-3.0 |
402231466/cda-0512 | wsgi.py | 21446 | # coding=utf-8
# 上面的程式內容編碼必須在程式的第一或者第二行才會有作用
################# (1) 模組導入區
# 導入 cherrypy 模組, 為了在 OpenShift 平台上使用 cherrypy 模組, 必須透過 setup.py 安裝
import cherrypy
# 導入 Python 內建的 os 模組, 因為 os 模組為 Python 內建, 所以無需透過 setup.py 安裝
import os
# 導入 random 模組
import random
import math
from cherrypy.lib.static import serve_file
# 導入 gear 模組
#import gear
import man
import man2
################# (2) 廣域變數設定區
# 確定程式檔案所在目錄, 在 Windows 下有最後的反斜線
_curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
# 設定在雲端與近端的資料儲存目錄
if 'OPENSHIFT_REPO_DIR' in os.environ.keys():
# 表示程式在雲端執行
download_root_dir = os.environ['OPENSHIFT_DATA_DIR']
data_dir = os.environ['OPENSHIFT_DATA_DIR']
else:
# 表示程式在近端執行
download_root_dir = _curdir + "/local_data/"
data_dir = _curdir + "/local_data/"
def downloadlist_access_list(files, starti, endi):
# different extension files, associated links were provided
# popup window to view images, video or STL files, other files can be downloaded directly
# files are all the data to list, from starti to endi
# add file size
outstring = ""
for index in range(int(starti)-1, int(endi)):
fileName, fileExtension = os.path.splitext(files[index])
fileExtension = fileExtension.lower()
fileSize = sizeof_fmt(os.path.getsize(download_root_dir+"downloads/"+files[index]))
# images files
if fileExtension == ".png" or fileExtension == ".jpg" or fileExtension == ".gif":
outstring += '<input type="checkbox" name="filename" value="'+files[index]+'"><a href="javascript:;" onClick="window.open(\'/downloads/'+ \
files[index]+'\',\'images\', \'catalogmode\',\'scrollbars\')">'+files[index]+'</a> ('+str(fileSize)+')<br />'
# stl files
elif fileExtension == ".stl":
outstring += '<input type="checkbox" name="filename" value="'+files[index]+'"><a href="javascript:;" onClick="window.open(\'/static/viewstl.html?src=/downloads/'+ \
files[index]+'\',\'images\', \'catalogmode\',\'scrollbars\')">'+files[index]+'</a> ('+str(fileSize)+')<br />'
# flv files
elif fileExtension == ".flv":
outstring += '<input type="checkbox" name="filename" value="'+files[index]+'"><a href="javascript:;" onClick="window.open(\'/flvplayer?filepath=/downloads/'+ \
files[index]+'\',\'images\', \'catalogmode\',\'scrollbars\')">'+files[index]+'</a> ('+str(fileSize)+')<br />'
# direct download files
else:
outstring += "<input type='checkbox' name='filename' value='"+files[index]+"'><a href='/download/?filepath="+download_root_dir.replace('\\', '/')+ \
"downloads/"+files[index]+"'>"+files[index]+"</a> ("+str(fileSize)+")<br />"
return outstring
def sizeof_fmt(num):
for x in ['bytes','KB','MB','GB']:
if num < 1024.0:
return "%3.1f%s" % (num, x)
num /= 1024.0
return "%3.1f%s" % (num, 'TB')
################# (3) 程式類別定義區
# 以下改用 CherryPy 網際框架程式架構
# 以下為 Hello 類別的設計內容, 其中的 object 使用, 表示 Hello 類別繼承 object 的所有特性, 包括方法與屬性設計
class Midterm(object):
# Midterm 類別的啟動設定
_cp_config = {
'tools.encode.encoding': 'utf-8',
'tools.sessions.on' : True,
'tools.sessions.storage_type' : 'file',
#'tools.sessions.locking' : 'explicit',
# session 以檔案儲存, 而且位於 data_dir 下的 tmp 目錄
'tools.sessions.storage_path' : data_dir+'/tmp',
# session 有效時間設為 60 分鐘
'tools.sessions.timeout' : 60
}
def __init__(self):
# hope to create downloads and images directories
if not os.path.isdir(download_root_dir+"downloads"):
try:
os.makedirs(download_root_dir+"downloads")
except:
print("mkdir error")
if not os.path.isdir(download_root_dir+"images"):
try:
os.makedirs(download_root_dir+"images")
except:
print("mkdir error")
if not os.path.isdir(download_root_dir+"tmp"):
try:
os.makedirs(download_root_dir+"tmp")
except:
print("mkdir error")
# 以 @ 開頭的 cherrypy.expose 為 decorator, 用來表示隨後的成員方法, 可以直接讓使用者以 URL 連結執行
@cherrypy.expose
# index 方法為 CherryPy 各類別成員方法中的內建(default)方法, 當使用者執行時未指定方法, 系統將會優先執行 index 方法
# 有 self 的方法為類別中的成員方法, Python 程式透過此一 self 在各成員方法間傳遞物件內容
def index(self):
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
</head>
<body>
<h1>40223146<h1>
<a href="spur">spur</a><br />
<a href="drawspur">drawspur</a><br />
<a href="fileuploadform">上傳檔案</a><br />
<a href="download_list">列出上傳檔案</a><br />
</body>
</html>
'''
return outstring
@cherrypy.expose
# N 為齒數, M 為模數, P 為壓力角
def spur(self, N=20, M=5, P=15):
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<!-- 載入 brython.js -->
<script type="text/javascript" src="/static/Brython3.1.1-20150328-091302/brython.js"></script>
</head>
<!-- 啟動 brython() -->
<body onload="brython()">
<form method=POST action=spuraction>
齒數:<input type=text name=N value='''+str(N)+'''><br />
模數:<input type=text name=M value = '''+str(M)+'''><br />
壓力角:<input type=text name=P value = '''+str(P)+'''><br />
<input type=submit value=send>
</form>
<br /><a href="index">index</a><br />
</body>
</html>
'''
return outstring
@cherrypy.expose
# N 為齒數, M 為模數, P 為壓力角
def spuraction(self, N=20, M=5, P=15):
output = '''
<!doctype html><html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>2015CD Midterm</title>
</head>
<body>
'''
output += "齒數為"+str(N)+"<br />"
output += "模數為"+str(M)+"<br />"
output += "壓力角為"+str(P)+"<br />"
output +='''<br /><a href="/spur">spur</a>(按下後再輸入)<br />'''
output +='''<br /><a href="index">index</a><br />
</body>
</html>
'''
return output
@cherrypy.expose
# N 為齒數, M 為模數, P 為壓力角
def drawspur(self, N=20, M=5, P=15):
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
</head>
<body>
<form method=POST action=drawspuraction>
齒數:<input type=text name=N value='''+str(N)+'''><br />
模數:<input type=text name=M value = '''+str(M)+'''><br />
壓力角:<input type=text name=P value = '''+str(P)+'''><br />
<input type=submit value=畫出正齒輪輪廓>
</form>
<br /><a href="index">index</a><br />
<!-- 載入 brython.js -->
<script type="text/javascript" src="/static/Brython3.1.1-20150328-091302/brython.js"></script>
<script>
window.onload=function(){
brython();
}
</script>
</body>
</html>
'''
return outstring
@cherrypy.expose
# N 為齒數, M 為模數, P 為壓力角
def drawspuraction(self, N=20, M=5, P=15):
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
</head>
<body>
<a href="index">index</a><br />
<!-- 以下為 canvas 畫圖程式 -->
<script type="text/python">
# 從 browser 導入 document
from browser import document
from math import *
# 請注意, 這裡導入位於 Lib/site-packages 目錄下的 spur.py 檔案
import spur
# 準備在 id="plotarea" 的 canvas 中繪圖
canvas = document["plotarea"]
ctx = canvas.getContext("2d")
# 以下利用 spur.py 程式進行繪圖
# N 為齒數
N = '''+str(N)+'''
# M 為模數
M = '''+str(M)+'''
# 壓力角 P 單位為角度
P = '''+str(P)+'''
# 計算兩齒輪的節圓半徑
rp = N*M/2
spur.Spur(ctx).Gear(600, 600, rp, N, P, "blue")
</script>
<canvas id="plotarea" width="1200" height="1200"></canvas>
<!-- 載入 brython.js -->
<script type="text/javascript" src="/static/Brython3.1.1-20150328-091302/brython.js"></script>
<script>
window.onload=function(){
brython();
}
</script>
</body>
</html>
'''
return outstring
@cherrypy.expose
# W 為正方體的邊長
def cube(self, W=10):
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
</head>
<body>
<!-- 使用者輸入表單的參數交由 cubeaction 方法處理 -->
<form method=POST action=cubeaction>
正方體邊長:<input type=text name=W value='''+str(W)+'''><br />
<input type=submit value=送出>
</form>
<br /><a href="index">index</a><br />
</body>
</html>
'''
return outstring
@cherrypy.expose
# W 為正方體邊長, 內定值為 10
def cubeaction(self, W=10):
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<!-- 先載入 pfcUtils.js 與 wl_header.js -->
<script type="text/javascript" src="/static/weblink/pfcUtils.js"></script>
<script type="text/javascript" src="/static/weblink/wl_header.js">
<!-- 載入 brython.js -->
<script type="text/javascript" src="/static/Brython3.1.1-20150328-091302/brython.js"></script>
document.writeln ("Error loading Pro/Web.Link header!");
</script>
<script>
window.onload=function(){
brython();
}
</script>
</head>
<!-- 不要使用 body 啟動 brython() 改為 window level 啟動 -->
<body onload="">
<h1>Creo 參數化零件</h1>
<a href="index">index</a><br />
<!-- 以下為 Creo Pro/Web.Link 程式, 將 JavaScrip 改為 Brython 程式 -->
<script type="text/python">
from browser import document, window
from math import *
# 這個區域為 Brython 程式範圍, 註解必須採用 Python 格式
# 因為 pfcIsWindows() 為原生的 JavaScript 函式, 在 Brython 中引用必須透過 window 物件
if (!window.pfcIsWindows()) window.netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
# 若第三輸入為 false, 表示僅載入 session, 但是不顯示
# ret 為 model open return
ret = document.pwl.pwlMdlOpen("cube.prt", "v:/tmp", false)
if (!ret.Status):
window.alert("pwlMdlOpen failed (" + ret.ErrorCode + ")")
# 將 ProE 執行階段設為變數 session
session = window.pfcGetProESession()
# 在視窗中打開零件檔案, 並且顯示出來
pro_window = session.OpenFile(pfcCreate("pfcModelDescriptor").CreateFromFileName("cube.prt"))
solid = session.GetModel("cube.prt", window.pfcCreate("pfcModelType").MDL_PART)
# 在 Brython 中與 Python 語法相同, 只有初值設定問題, 無需宣告變數
# length, width, myf, myn, i, j, volume, count, d1Value, d2Value
# 將模型檔中的 length 變數設為 javascript 中的 length 變數
length = solid.GetParam("a1")
# 將模型檔中的 width 變數設為 javascript 中的 width 變數
width = solid.GetParam("a2")
# 改變零件尺寸
# myf=20
# myn=20
volume = 0
count = 0
try:
# 以下採用 URL 輸入對應變數
# createParametersFromArguments ();
# 以下則直接利用 javascript 程式改變零件參數
for i in range(5):
myf ='''+str(W)+'''
myn ='''+str(W)+''' + i*2.0
# 設定變數值, 利用 ModelItem 中的 CreateDoubleParamValue 轉換成 Pro/Web.Link 所需要的浮點數值
d1Value = window.pfcCreate ("MpfcModelItem").CreateDoubleParamValue(myf)
d2Value = window.pfcCreate ("MpfcModelItem").CreateDoubleParamValue(myn)
# 將處理好的變數值, 指定給對應的零件變數
length.Value = d1Value
width.Value = d2Value
# 零件尺寸重新設定後, 呼叫 Regenerate 更新模型
# 在 JavaScript 為 null 在 Brython 為 None
solid.Regenerate(None)
# 利用 GetMassProperty 取得模型的質量相關物件
properties = solid.GetMassProperty(None)
# volume = volume + properties.Volume
volume = properties.Volume
count = count + 1
window.alert("執行第"+count+"次,零件總體積:"+volume)
# 將零件存為新檔案
newfile = document.pwl.pwlMdlSaveAs("cube.prt", "v:/tmp", "cube"+count+".prt")
if (!newfile.Status):
window.alert("pwlMdlSaveAs failed (" + newfile.ErrorCode + ")")
# window.alert("共執行:"+count+"次,零件總體積:"+volume)
# window.alert("零件體積:"+properties.Volume)
# window.alert("零件體積取整數:"+Math.round(properties.Volume));
except:
window.alert ("Exception occurred: "+window.pfcGetExceptionType (err))
</script>
'''
return outstring
@cherrypy.expose
def fileuploadform(self):
return '''<h1>file upload</h1>
<script src="/static/jquery.js" type="text/javascript"></script>
<script src="/static/axuploader.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$('.prova').axuploader({url:'fileaxupload', allowExt:['jpg','png','gif','7z','pdf','zip','flv','stl','swf'],
finish:function(x,files)
{
alert('All files have been uploaded: '+files);
},
enable:true,
remotePath:function(){
return 'downloads/';
}
});
});
</script>
<div class="prova"></div>
<input type="button" onclick="$('.prova').axuploader('disable')" value="asd" />
<input type="button" onclick="$('.prova').axuploader('enable')" value="ok" />
</section></body></html>
'''
@cherrypy.expose
def fileaxupload(self, *args, **kwargs):
filename = kwargs["ax-file-name"]
flag = kwargs["start"]
if flag == "0":
file = open(download_root_dir+"downloads/"+filename, "wb")
else:
file = open(download_root_dir+"downloads/"+filename, "ab")
file.write(cherrypy.request.body.read())
file.close()
return "files uploaded!"
@cherrypy.expose
def download_list(self, item_per_page=5, page=1, keyword=None, *args, **kwargs):
files = os.listdir(download_root_dir+"downloads/")
total_rows = len(files)
totalpage = math.ceil(total_rows/int(item_per_page))
starti = int(item_per_page) * (int(page) - 1) + 1
endi = starti + int(item_per_page) - 1
outstring = "<form method='post' action='delete_file'>"
notlast = False
if total_rows > 0:
outstring += "<br />"
if (int(page) * int(item_per_page)) < total_rows:
notlast = True
if int(page) > 1:
outstring += "<a href='"
outstring += "download_list?&page=1&item_per_page="+str(item_per_page)+"&keyword="+str(cherrypy.session.get('download_keyword'))
outstring += "'><<</a> "
page_num = int(page) - 1
outstring += "<a href='"
outstring += "download_list?&page="+str(page_num)+"&item_per_page="+str(item_per_page)+"&keyword="+str(cherrypy.session.get('download_keyword'))
outstring += "'>Previous</a> "
span = 10
for index in range(int(page)-span, int(page)+span):
if index>= 0 and index< totalpage:
page_now = index + 1
if page_now == int(page):
outstring += "<font size='+1' color='red'>"+str(page)+" </font>"
else:
outstring += "<a href='"
outstring += "download_list?&page="+str(page_now)+"&item_per_page="+str(item_per_page)+"&keyword="+str(cherrypy.session.get('download_keyword'))
outstring += "'>"+str(page_now)+"</a> "
if notlast == True:
nextpage = int(page) + 1
outstring += " <a href='"
outstring += "download_list?&page="+str(nextpage)+"&item_per_page="+str(item_per_page)+"&keyword="+str(cherrypy.session.get('download_keyword'))
outstring += "'>Next</a>"
outstring += " <a href='"
outstring += "download_list?&page="+str(totalpage)+"&item_per_page="+str(item_per_page)+"&keyword="+str(cherrypy.session.get('download_keyword'))
outstring += "'>>></a><br /><br />"
if (int(page) * int(item_per_page)) < total_rows:
notlast = True
outstring += downloadlist_access_list(files, starti, endi)+"<br />"
else:
outstring += "<br /><br />"
outstring += downloadlist_access_list(files, starti, total_rows)+"<br />"
if int(page) > 1:
outstring += "<a href='"
outstring += "download_list?&page=1&item_per_page="+str(item_per_page)+"&keyword="+str(cherrypy.session.get('download_keyword'))
outstring += "'><<</a> "
page_num = int(page) - 1
outstring += "<a href='"
outstring += "download_list?&page="+str(page_num)+"&item_per_page="+str(item_per_page)+"&keyword="+str(cherrypy.session.get('download_keyword'))
outstring += "'>Previous</a> "
span = 10
for index in range(int(page)-span, int(page)+span):
#for ($j=$page-$range;$j<$page+$range;$j++)
if index >=0 and index < totalpage:
page_now = index + 1
if page_now == int(page):
outstring += "<font size='+1' color='red'>"+str(page)+" </font>"
else:
outstring += "<a href='"
outstring += "download_list?&page="+str(page_now)+"&item_per_page="+str(item_per_page)+"&keyword="+str(cherrypy.session.get('download_keyword'))
outstring += "'>"+str(page_now)+"</a> "
if notlast == True:
nextpage = int(page) + 1
outstring += " <a href='"
outstring += "download_list?&page="+str(nextpage)+"&item_per_page="+str(item_per_page)+"&keyword="+str(cherrypy.session.get('download_keyword'))
outstring += "'>Next</a>"
outstring += " <a href='"
outstring += "download_list?&page="+str(totalpage)+"&item_per_page="+str(item_per_page)+"&keyword="+str(cherrypy.session.get('download_keyword'))
outstring += "'>>></a>"
else:
outstring += "no data!"
outstring += "<br /><br /><input type='submit' value='delete'><input type='reset' value='reset'></form>"
return "<div class='container'><nav>"+ \
"</nav><section><h1>Download List</h1>"+outstring+"<br/><br /></body></html>"
class Download:
@cherrypy.expose
def index(self, filepath):
return serve_file(filepath, "application/x-download", "attachment")
################# (4) 程式啟動區
# 配合程式檔案所在目錄設定靜態目錄或靜態檔案
application_conf = {'/static':{
'tools.staticdir.on': True,
# 程式執行目錄下, 必須自行建立 static 目錄
'tools.staticdir.dir': _curdir+"/static"},
'/downloads':{
'tools.staticdir.on': True,
'tools.staticdir.dir': data_dir+"/downloads"},
'/images':{
'tools.staticdir.on': True,
'tools.staticdir.dir': data_dir+"/images"}
}
root = Midterm()
root.download = Download()
root.man = man.MAN()
root.man2 = man2.MAN()
#root.gear = gear.Gear()
if 'OPENSHIFT_REPO_DIR' in os.environ.keys():
# 表示在 OpenSfhit 執行
application = cherrypy.Application(root, config=application_conf)
else:
# 表示在近端執行
cherrypy.quickstart(root, config=application_conf)
| agpl-3.0 |
tis-innovation-park/carsharing-ds | src/main/java/it/bz/tis/integreen/carsharingbzit/tis/FakeConnector.java | 2515 | /*
carsharing-ds: car sharing datasource for the integreen cloud
Copyright (C) 2015 TIS Innovation Park - Bolzano/Bozen - Italy
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package it.bz.tis.integreen.carsharingbzit.tis;
import java.io.IOException;
import java.io.StringWriter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
/**
*
* @author Davide Montesin <[email protected]>
*/
public class FakeConnector implements IXMLRPCPusher
{
static final Logger logger = LogManager.getLogger(FakeConnector.class);
ObjectMapper mapper;
public FakeConnector()
{
this.mapper = new ObjectMapper();
this.mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
this.mapper.enable(SerializationFeature.INDENT_OUTPUT);
}
@Override
public Object syncStations(String datasourceName, Object[] data)
{
StringWriter sw = new StringWriter();
try
{
this.mapper.writeValue(sw, data);
}
catch (IOException e)
{
throw new IllegalStateException("Why???");
}
String txt = sw.getBuffer().toString();
logger.debug("FakeConnector.syncStations: " + datasourceName + " - " + txt);
return null;
}
@Override
public Object pushData(String datasourceName, Object[] data)
{
StringWriter sw = new StringWriter();
try
{
this.mapper.writeValue(sw, data);
}
catch (IOException e)
{
throw new IllegalStateException("Why???");
}
String txt = sw.getBuffer().toString();
logger.debug("FakeConnector.pushData: " + datasourceName + " - " + txt);
return null;
}
} | agpl-3.0 |
mihir-parikh/sugarcrm_playground | custom/metadata/car_f_car_file_car_f_car_fileMetaData.php | 2030 | <?php
// created: 2014-10-03 15:53:48
$dictionary["car_f_car_file_car_f_car_file"] = array (
'true_relationship_type' => 'one-to-many',
'relationships' =>
array (
'car_f_car_file_car_f_car_file' =>
array (
'lhs_module' => 'car_f_car_file',
'lhs_table' => 'car_f_car_file',
'lhs_key' => 'id',
'rhs_module' => 'car_f_car_file',
'rhs_table' => 'car_f_car_file',
'rhs_key' => 'id',
'relationship_type' => 'many-to-many',
'join_table' => 'car_f_car_file_car_f_car_file_c',
'join_key_lhs' => 'car_f_car_file_car_f_car_filecar_f_car_file_ida',
'join_key_rhs' => 'car_f_car_file_car_f_car_filecar_f_car_file_idb',
),
),
'table' => 'car_f_car_file_car_f_car_file_c',
'fields' =>
array (
0 =>
array (
'name' => 'id',
'type' => 'varchar',
'len' => 36,
),
1 =>
array (
'name' => 'date_modified',
'type' => 'datetime',
),
2 =>
array (
'name' => 'deleted',
'type' => 'bool',
'len' => '1',
'default' => '0',
'required' => true,
),
3 =>
array (
'name' => 'car_f_car_file_car_f_car_filecar_f_car_file_ida',
'type' => 'varchar',
'len' => 36,
),
4 =>
array (
'name' => 'car_f_car_file_car_f_car_filecar_f_car_file_idb',
'type' => 'varchar',
'len' => 36,
),
),
'indices' =>
array (
0 =>
array (
'name' => 'car_f_car_file_car_f_car_filespk',
'type' => 'primary',
'fields' =>
array (
0 => 'id',
),
),
1 =>
array (
'name' => 'car_f_car_file_car_f_car_file_ida1',
'type' => 'index',
'fields' =>
array (
0 => 'car_f_car_file_car_f_car_filecar_f_car_file_ida',
),
),
2 =>
array (
'name' => 'car_f_car_file_car_f_car_file_alt',
'type' => 'alternate_key',
'fields' =>
array (
0 => 'car_f_car_file_car_f_car_filecar_f_car_file_idb',
),
),
),
); | agpl-3.0 |
itstar4tech/news | l10n/tr.php | 8519 | <?php
$TRANSLATIONS = array(
"Feed contains invalid XML" => "Besleme, geçersiz XML içeriyor",
"Feed not found: either the website does not provide a feed or blocks access. To rule out blocking, try to download the feed on your server's command line using curl: curl http://the-feed.tld" => "Besleme bulunamadı: ya web sitesi besleme sağlamıyor ya da erişimi engelliyor. Engellemeyi aşmak için beslemeyi sunucunuzdan şu curl komutunu kullanarak indirmeyi deneyin: curl http://the-feed.tld",
"Detected feed format is not supported" => "Tespit edilen biçim desteklenmiyor",
"SSL Certificate is invalid" => "SSL Sertifikası geçersiz",
"Website not found" => "Web sitesi bulunamadı",
"More redirects than allowed, aborting" => "İzin verilenden daha fazla yeniden yönlendirme. İptal ediliyor",
"Bigger than maximum allowed size" => "İzin verilen boyuttan daha büyük",
"Request timed out" => "İstek zaman aşımına uğradı",
"Request failed, network connection unavailable!" => "İstek başarısız, ağ bağlantısı kullanılamıyor!",
"Request unauthorized. Are you logged in?" => "İstek yetkisiz. Oturumunuz açık mı?",
"Request forbidden. Are you an admin?" => "İsteğe izin verilmedi. Bir yönetici misiniz?",
"Token expired or app not enabled! Reload the page!" => "Belirteç süresi doldu ya da uygulama etkin değil! Sayfayı yenileyin!",
"Internal server error! Please check your " => "Dahili sunucu hatası! Lütfen denetleyin:",
"Request failed, ownCloud is in currently " => "İstek başarısız, ownCloud şu anda",
"Can not add feed: Exists already" => "Besleme eklenemiyor: Zaten mevcut",
"Articles without feed" => "Beslemesiz makaleler",
"Can not add folder: Exists already" => "Klasör eklenemiyor: Zaten mevcut",
"Use ownCloud cron for updates" => "Güncellemeler için ownCloud cron'u kullan",
"Disable this if you run a custom updater such as the Python updater included in the app" => "Uygulamaya dahil edilmiş Python güncelleyicisi gibi bir özel güncelleştirici çalıştırıyorsanız bunu devre dışı bırakın",
"Purge interval" => "Temizleme aralığı",
"Minimum amount of seconds after deleted feeds and folders are removed from the database; values below 60 seconds are ignored" => "Silinen besleme ve klasörlerin, veritabanından kaldırılacağı asgari süre; 60 altındaki saniyeler yoksayılır",
"Maximum read count per feed" => "Besleme başına azami okuma sayısı",
"Defines the maximum amount of articles that can be read per feed which won't be deleted by the cleanup job; if old articles reappear after being read, increase this value; negative values such as -1 will turn this feature off completely" => "Temizleme görevinde silinmeyecek, besleme başına okunabilecek azami makale sayısını tanımlar. Eski makaleler okunduktan sonra yeniden görülüyorsa, bu değeri arttırın. -1 gibi negatif değerler bu özelliği tamamen kapatacaktır.",
"Maximum redirects" => "En fazla yeniden yönlendirme",
"How many redirects the feed fetcher should follow" => "Besleme getirici kaç yönlendirmeyi takip etmeli",
"Maximum feed page size" => "Azami besleme sayfa boyutu",
"Maximum feed size in bytes. If the RSS/Atom page is bigger than this value, the update will be aborted" => "Bayt cinsinden azami besleme boyutu. RSS/Atom sayfası bu değerden daha büyükse, güncelleme iptal edilecek",
"Feed fetcher timeout" => "Besleme getirici zaman aşımı",
"Maximum number of seconds to wait for an RSS or Atom feed to load; if it takes longer the update will be aborted" => "Bir RSS veya Atom beslemesinin yüklenmesi için beklenilecek azami süre. Uzun sürüyorsa iptal edilecek",
"Explore Service URL" => "Keşfetme Hizmet URL'si",
"If given, this service's URL will be queried for displaying the feeds in the explore feed section. To fall back to the built in explore service, leave this input empty" => "Belirtilmişse, hizmetin URL'si beslemeyi keşfetme bölümünde beslemelerin görüntülenebilmesi için sorgulanacak. Dahili keşfetme hizmeti için bu alanı boş bırakın",
"Saved" => "Kaydedildi",
"Download" => "İndir",
"Close" => "Kapat",
"Ajax or webcron cron mode detected! Your feeds will not be updated correctly. It is recommended to either use the operating system cron or a custom updater." => "Ajax veya webcron modu tespit edildi. Beslemeleriniz düzgün olarak güncellenemeyecektir. Özel bir güncelleyeci yada işletim sistemi cron kullanmanız önerilir.",
"How to set up the operating system cron" => "İşletim sistemi cron görevi nasıl ayarlanır",
"How to set up a custom updater (faster and no possible deadlock) " => "Özel bir güncelleyici nasıl ayarlanır (daha hızlı ve kördüğüm ihtimali yok)",
"Subscribe" => "Abone ol",
"Refresh" => "Yenile",
"No articles available" => "Hiç makale yok",
"No unread articles available" => "Okunmamış makale yok",
"Open website" => "Web sitesini aç",
"Star article" => "Makaleyi yıldızla",
"Unstar article" => "Makale yıldızını kaldır",
"Keep article unread" => "Makaleyi okunmadı olarak bırak",
"Remove keep article unread" => "Makaleyi okunmadı olarak bırak",
"by" => "yazar",
"from" => "kaynak",
"Play audio" => "Ses oynat",
"Download video" => "Video indir",
"Download audio" => "Ses indir",
"Keyboard shortcut" => "Klavye kısayolu",
"Description" => "Açıklama",
"right" => "sağ",
"Jump to next article" => "Sonraki makaleye atla",
"left" => "sol",
"Jump to previous article" => "Önceki makaleye atla",
"Toggle star article" => "Makale yıldızını aç/kapat",
"Star article and jump to next one" => "Makaleyi yıldızla ve sonrakine atla",
"Toggle keep current article unread" => "Geçerli makaleyi okunmamış tut özelliğini aç/kapat",
"Open article in new tab" => "Makaleyi yeni sekmede aç",
"Toggle expand article in compact view" => "Sıkışık görünümde makaleyi genişlet/daralt",
"Load next feed" => "Sonraki beslemeyi yükle",
"Load previous feed" => "Önceki beslemeyi yükle",
"Load next folder" => "Sonraki klasörü yükle",
"Load previous folder" => "Önceki klasörü yükle",
"Scroll to active navigation entry" => "Gezinti girdisini etkinleştirmek için kaydır",
"Focus search field" => "Arama alanına odaklan",
"Mark current article's feed/folder read" => "Geçerli makalenin beslemesini/klasörünü okundu işaretle",
"Web address" => "Web adresi",
"Feed exists already!" => "Besleme zaten mevcut!",
"Folder" => "Klasör",
"No folder" => "Klasör yok",
"New folder" => "Yeni klasör",
"Folder name" => "Klasör adı",
"Go back" => "Geri dön",
"Folder exists already!" => "Klasör zaten mevcut!",
"New Folder" => "Yeni Klasör",
"Create" => "Oluştur",
"Explore" => "Keşfet",
"Deleted feed" => "Beslemeyi sil",
"Undo delete feed" => "Beslemeyi geri al",
"Rename" => "Yeniden adlandır",
"Menu" => "Menü",
"No feed ordering" => "Besleme sıralaması yok",
"Reversed feed ordering" => "Ters besleme sıralaması",
"Normal feed ordering" => "Normal besleme sıralaması",
"Enable full text feed fetching" => "Tam metin besleme getirmesini etkinleştir",
"Disable full text feed fetching" => "Tam metin besleme getirmesini kapat",
"Rename feed" => "Beslemeyi yeniden adlandır",
"Delete feed" => "Beslemeyi sil",
"Mark all articles read" => "Tüm makaleleri okundu işaretle",
"Dismiss" => "İptal et",
"Collapse" => "Daralt",
"Deleted folder" => "Klasör silindi",
"Undo delete folder" => "Klasör silmeyi geri al",
"Rename folder" => "Klasörü yeniden adlandır",
"Delete folder" => "Klasörü sil",
"Starred" => "Yıldızlı",
"Unread articles" => "Okunmamış makaleler",
"All articles" => "Tüm makaleler",
"Settings" => "Ayarlar",
"Keyboard shortcuts" => "Klavye kısayolları",
"Disable mark read through scrolling" => "Kaydırma sırasında okundu olarak işaretlemeyi kapat",
"Compact view" => "Sıkışık görünüm",
"Expand articles on key navigation" => "Tuşla gezinme sırasında makaleleri genişlet",
"Show all articles" => "Tüm makaleleri göster",
"Reverse ordering (oldest on top)" => "Sıralamayı tersine çevir (en eski üstte)",
"Subscriptions (OPML)" => "Abonelikler (OPML)",
"Import" => "İçe aktar",
"Export" => "Dışa aktar",
"Error when importing: file does not contain valid OPML" => "Dosya alımında hata: dosya geçerli OPML içermiyor",
"Unread/Starred Articles" => "Okunmamış/Yıldızlı Makaleler",
"Error when importing: file does not contain valid JSON" => "İçe alınırken hata: dosya geçerli JSON içermiyor"
);
$PLURAL_FORMS = "nplurals=2; plural=(n > 1);";
| agpl-3.0 |
boramko/PiSnap | snap/byob.js | 100435 | /*
byob.js
"build your own blocks" for SNAP!
based on morphic.js, widgets.js blocks.js, threads.js and objects.js
inspired by Scratch
written by Jens Mönig
[email protected]
Copyright (C) 2015 by Jens Mönig
This file is part of Snap!.
Snap! is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
prerequisites:
--------------
needs blocks.js, threads.js, objects.js, widgets.js and morphic.js
hierarchy
---------
the following tree lists all constructors hierarchically,
indentation indicating inheritance. Refer to this list to get a
contextual overview:
BlockLabelFragment
CustomBlockDefinition
CommandBlockMorph***
CustomCommandBlockMorph
HatBlockMorph***
PrototypeHatBlockMorph
DialogBoxMorph**
BlockDialogMorph
BlockEditorMorph
BlockExportDialogMorph
BlockImportDialogMorph
InputSlotDialogMorph
VariableDialogMorph
ReporterBlockMorph***
CustomReporterBlockMorph
JaggedBlockMorph
StringMorph*
BlockLabelFragmentMorph
BlockLabelPlaceHolderMorph
TemplateSlotMorph***
BlockInputFragmentMorph
* from morphic.js
** from widgets.js
*** from blocks.js
toc
---
the following list shows the order in which all constructors are
defined. Use this list to locate code in this document:
CustomBlockDefinition
CustomCommandBlockMorph
CustomReporterBlockMorph
JaggedBlockMorph
BlockDialogMorph
BlockEditorMorph
PrototypeHatBlockMorph
BlockLabelFragmentMorph
BlockLabelPlaceHolderMorph
BlockInputFragmentMorph
InputSlotDialogMorph
VariableDialogMorph
BlockExportDialogMorph
BlockImportDialogMorph
*/
/*global modules, CommandBlockMorph, SpriteMorph, TemplateSlotMorph,
StringMorph, Color, DialogBoxMorph, ScriptsMorph, ScrollFrameMorph,
Point, HandleMorph, HatBlockMorph, BlockMorph, detect, List, Process,
AlignmentMorph, ToggleMorph, InputFieldMorph, ReporterBlockMorph,
Context, StringMorph, nop, newCanvas, radians, BoxMorph,
ArrowMorph, PushButtonMorph, contains, InputSlotMorph, ShadowMorph,
ToggleButtonMorph, IDE_Morph, MenuMorph, copy, ToggleElementMorph,
Morph, fontHeight, StageMorph, SyntaxElementMorph, SnapSerializer,
CommentMorph, localize, CSlotMorph, SpeechBubbleMorph, MorphicPreferences,
SymbolMorph, isNil*/
// Global stuff ////////////////////////////////////////////////////////
modules.byob = '2015-May-01';
// Declarations
var CustomBlockDefinition;
var CustomCommandBlockMorph;
var CustomReporterBlockMorph;
var BlockDialogMorph;
var BlockEditorMorph;
var PrototypeHatBlockMorph;
var BlockLabelFragment;
var BlockLabelFragmentMorph;
var BlockInputFragmentMorph;
var BlockLabelPlaceHolderMorph;
var InputSlotDialogMorph;
var VariableDialogMorph;
var JaggedBlockMorph;
var BlockExportDialogMorph;
var BlockImportDialogMorph;
// CustomBlockDefinition ///////////////////////////////////////////////
// CustomBlockDefinition instance creation:
function CustomBlockDefinition(spec, receiver) {
this.body = null; // a Context (i.e. a reified top block)
this.scripts = [];
this.category = null;
this.isGlobal = false;
this.type = 'command';
this.spec = spec || '';
// format: {'inputName' : [type, default, options, readonly]}
this.declarations = {};
this.comment = null;
this.codeMapping = null; // experimental, generate text code
this.codeHeader = null; // experimental, generate text code
// don't serialize (not needed for functionality):
this.receiver = receiver || null; // for serialization only (pointer)
}
// CustomBlockDefinition instantiating blocks
CustomBlockDefinition.prototype.blockInstance = function () {
var block;
if (this.type === 'command') {
block = new CustomCommandBlockMorph(this);
} else {
block = new CustomReporterBlockMorph(
this,
this.type === 'predicate'
);
}
block.isDraggable = true;
return block;
};
CustomBlockDefinition.prototype.templateInstance = function () {
var block;
block = this.blockInstance();
block.refreshDefaults();
block.isDraggable = false;
block.isTemplate = true;
return block;
};
CustomBlockDefinition.prototype.prototypeInstance = function () {
var block, slot, myself = this;
// make a new block instance and mark it as prototype
if (this.type === 'command') {
block = new CustomCommandBlockMorph(this, true);
} else {
block = new CustomReporterBlockMorph(
this,
this.type === 'predicate',
true
);
}
// assign slot declarations to prototype inputs
block.parts().forEach(function (part) {
if (part instanceof BlockInputFragmentMorph) {
slot = myself.declarations[part.fragment.labelString];
if (slot) {
part.fragment.type = slot[0];
part.fragment.defaultValue = slot[1];
part.fragment.options = slot[2];
part.fragment.isReadOnly = slot[3] || false;
}
}
});
return block;
};
// CustomBlockDefinition duplicating
CustomBlockDefinition.prototype.copyAndBindTo = function (sprite) {
var c = copy(this);
c.receiver = sprite; // only for (kludgy) serialization
c.declarations = copy(this.declarations); // might have to go deeper
if (c.body) {
c.body = Process.prototype.reify.call(
null,
this.body.expression,
new List(this.inputNames())
);
c.body.outerContext = null;
}
return c;
};
// CustomBlockDefinition accessing
CustomBlockDefinition.prototype.blockSpec = function () {
var myself = this,
ans = [],
parts = this.parseSpec(this.spec),
spec;
parts.forEach(function (part) {
if (part[0] === '%' && part.length > 1) {
spec = myself.typeOf(part.slice(1));
} else {
spec = part;
}
ans.push(spec);
ans.push(' ');
});
return ''.concat.apply('', ans).trim();
};
CustomBlockDefinition.prototype.helpSpec = function () {
var ans = [],
parts = this.parseSpec(this.spec);
parts.forEach(function (part) {
if (part[0] !== '%') {
ans.push(part);
}
});
return ''.concat.apply('', ans).replace(/\?/g, '');
};
CustomBlockDefinition.prototype.typeOf = function (inputName) {
if (this.declarations[inputName]) {
return this.declarations[inputName][0];
}
return '%s';
};
CustomBlockDefinition.prototype.defaultValueOf = function (inputName) {
if (this.declarations[inputName]) {
return this.declarations[inputName][1];
}
return '';
};
CustomBlockDefinition.prototype.defaultValueOfInputIdx = function (idx) {
var inputName = this.inputNames()[idx];
return this.defaultValueOf(inputName);
};
CustomBlockDefinition.prototype.dropDownMenuOfInputIdx = function (idx) {
var inputName = this.inputNames()[idx];
return this.dropDownMenuOf(inputName);
};
CustomBlockDefinition.prototype.isReadOnlyInputIdx = function (idx) {
var inputName = this.inputNames()[idx];
return this.isReadOnlyInput(inputName);
};
CustomBlockDefinition.prototype.inputOptionsOfIdx = function (idx) {
var inputName = this.inputNames()[idx];
return this.inputOptionsOf(inputName);
};
CustomBlockDefinition.prototype.dropDownMenuOf = function (inputName) {
var dict = {};
if (this.declarations[inputName] && this.declarations[inputName][2]) {
this.declarations[inputName][2].split('\n').forEach(function (line) {
var pair = line.split('=');
dict[pair[0]] = isNil(pair[1]) ? pair[0] : pair[1];
});
return dict;
}
return null;
};
CustomBlockDefinition.prototype.isReadOnlyInput = function (inputName) {
return this.declarations[inputName] &&
this.declarations[inputName][3] === true;
};
CustomBlockDefinition.prototype.inputOptionsOf = function (inputName) {
return [
this.dropDownMenuOf(inputName),
this.isReadOnlyInput(inputName)
];
};
CustomBlockDefinition.prototype.inputNames = function () {
var vNames = [],
parts = this.parseSpec(this.spec);
parts.forEach(function (part) {
if (part[0] === '%' && part.length > 1) {
vNames.push(part.slice(1));
}
});
return vNames;
};
CustomBlockDefinition.prototype.parseSpec = function (spec) {
// private
var parts = [], word = '', i, quoted = false, c;
for (i = 0; i < spec.length; i += 1) {
c = spec[i];
if (c === "'") {
quoted = !quoted;
} else if (c === ' ' && !quoted) {
parts.push(word);
word = '';
} else {
word = word.concat(c);
}
}
parts.push(word);
return parts;
};
// CustomBlockDefinition picturing
CustomBlockDefinition.prototype.scriptsPicture = function () {
var scripts, proto, block, comment;
scripts = new ScriptsMorph();
scripts.cleanUpMargin = 10;
proto = new PrototypeHatBlockMorph(this);
proto.setPosition(scripts.position().add(10));
if (this.comment !== null) {
comment = this.comment.fullCopy();
proto.comment = comment;
comment.block = proto;
}
if (this.body !== null) {
proto.nextBlock(this.body.expression.fullCopy());
}
scripts.add(proto);
proto.fixBlockColor(null, true);
this.scripts.forEach(function (element) {
block = element.fullCopy();
block.setPosition(scripts.position().add(element.position()));
scripts.add(block);
if (block instanceof BlockMorph) {
block.allComments().forEach(function (comment) {
comment.align(block);
});
}
});
proto.allComments().forEach(function (comment) {
comment.align(proto);
});
proto.children[0].fixLayout();
scripts.fixMultiArgs();
return scripts.scriptsPicture();
};
// CustomCommandBlockMorph /////////////////////////////////////////////
// CustomCommandBlockMorph inherits from CommandBlockMorph:
CustomCommandBlockMorph.prototype = new CommandBlockMorph();
CustomCommandBlockMorph.prototype.constructor = CustomCommandBlockMorph;
CustomCommandBlockMorph.uber = CommandBlockMorph.prototype;
// CustomCommandBlockMorph instance creation:
function CustomCommandBlockMorph(definition, isProto) {
this.init(definition, isProto);
}
CustomCommandBlockMorph.prototype.init = function (definition, isProto) {
this.definition = definition; // mandatory
this.isPrototype = isProto || false; // optional
CustomCommandBlockMorph.uber.init.call(this);
this.category = definition.category;
this.selector = 'evaluateCustomBlock';
if (definition) { // needed for de-serializing
this.refresh();
}
};
CustomCommandBlockMorph.prototype.refresh = function () {
var def = this.definition,
newSpec = this.isPrototype ?
def.spec : def.blockSpec(),
oldInputs;
this.setCategory(def.category);
if (this.blockSpec !== newSpec) {
oldInputs = this.inputs();
if (!this.zebraContrast) {
this.forceNormalColoring();
} else {
this.fixBlockColor();
}
this.setSpec(newSpec);
this.fixLabelColor();
this.restoreInputs(oldInputs);
} else { // update all input slots' drop-downs
this.inputs().forEach(function (inp, i) {
if (inp instanceof InputSlotMorph) {
inp.setChoices.apply(inp, def.inputOptionsOfIdx(i));
}
});
}
// find unnahmed upvars and label them
// to their internal definition (default)
this.cachedInputs = null;
this.inputs().forEach(function (inp, idx) {
if (inp instanceof TemplateSlotMorph && inp.contents() === '\u2191') {
inp.setContents(def.inputNames()[idx]);
}
});
};
CustomCommandBlockMorph.prototype.restoreInputs = function (oldInputs) {
// try to restore my previous inputs when my spec has been changed
var i = 0,
old,
myself = this;
if (this.isPrototype) {return; }
this.cachedInputs = null;
this.inputs().forEach(function (inp) {
old = oldInputs[i];
if (old instanceof ReporterBlockMorph &&
(!(inp instanceof TemplateSlotMorph))) {
myself.silentReplaceInput(inp, old);
} else if (old instanceof InputSlotMorph
&& inp instanceof InputSlotMorph) {
inp.setContents(old.evaluate());
} else if (old instanceof TemplateSlotMorph
&& inp instanceof TemplateSlotMorph) {
inp.setContents(old.evaluate());
} else if (old instanceof CSlotMorph
&& inp instanceof CSlotMorph) {
inp.nestedBlock(old.evaluate());
}
i += 1;
});
this.cachedInputs = null;
};
CustomCommandBlockMorph.prototype.refreshDefaults = function () {
// fill my editable slots with the defaults specified in my definition
var inputs = this.inputs(), idx = 0, myself = this;
inputs.forEach(function (inp) {
if (inp instanceof InputSlotMorph) {
inp.setContents(myself.definition.defaultValueOfInputIdx(idx));
}
idx += 1;
});
this.cachedInputs = null;
};
CustomCommandBlockMorph.prototype.refreshPrototype = function () {
// create my label parts from my (edited) fragments only
var hat,
protoSpec,
frags = [],
myself = this,
words,
newFrag,
i = 0;
if (!this.isPrototype) {return null; }
hat = this.parentThatIsA(PrototypeHatBlockMorph);
// remember the edited fragments
this.parts().forEach(function (part) {
if (!part.fragment.isDeleted) {
// take into consideration that a fragment may spawn others
// if it isn't an input label consisting of several words
if (part.fragment.type) { // marked as input, take label as is
frags.push(part.fragment);
} else { // not an input, devide into several non-input fragments
words = myself.definition.parseSpec(
part.fragment.labelString
);
words.forEach(function (word) {
newFrag = part.fragment.copy();
newFrag.labelString = word;
frags.push(newFrag);
});
}
}
});
// remember the edited prototype spec
protoSpec = this.specFromFragments();
// update the prototype's type
// and possibly exchange 'this' for 'myself'
if (this instanceof CustomCommandBlockMorph
&& ((hat.type === 'reporter') || (hat.type === 'predicate'))) {
myself = new CustomReporterBlockMorph(
this.definition,
hat.type === 'predicate',
true
);
hat.silentReplaceInput(this, myself);
} else if (this instanceof CustomReporterBlockMorph) {
if (hat.type === 'command') {
myself = new CustomCommandBlockMorph(
this.definition,
true
);
hat.silentReplaceInput(this, myself);
} else {
this.isPredicate = (hat.type === 'predicate');
this.drawNew();
}
}
myself.setCategory(hat.blockCategory || 'other');
hat.fixBlockColor();
// update the (new) prototype's appearance
myself.setSpec(protoSpec);
// update the (new) prototype's (new) fragments
// with the previously edited ones
myself.parts().forEach(function (part) {
if (!(part instanceof BlockLabelPlaceHolderMorph)) {
if (frags[i]) { // don't delete the default fragment
part.fragment = frags[i];
}
i += 1;
}
});
// refresh slot type indicators
this.refreshPrototypeSlotTypes();
hat.fixLayout();
};
CustomCommandBlockMorph.prototype.refreshPrototypeSlotTypes = function () {
this.parts().forEach(function (part) {
if (part instanceof BlockInputFragmentMorph) {
part.template().instantiationSpec = part.contents();
part.setContents(part.fragment.defTemplateSpecFragment());
}
});
this.fixBlockColor(null, true); // enforce zebra coloring of templates
};
CustomCommandBlockMorph.prototype.inputFragmentNames = function () {
// for the variable name slot drop-down menu (in the block editor)
var ans = [];
this.parts().forEach(function (part) {
if (!part.fragment.isDeleted && (part.fragment.type)) {
ans.push(part.fragment.labelString);
}
});
return ans;
};
CustomCommandBlockMorph.prototype.upvarFragmentNames = function () {
// for the variable name slot drop-down menu (in the block editor)
var ans = [];
this.parts().forEach(function (part) {
if (!part.fragment.isDeleted && (part.fragment.type === '%upvar')) {
ans.push(part.fragment.labelString);
}
});
return ans;
};
CustomCommandBlockMorph.prototype.upvarFragmentName = function (idx) {
// for block prototypes while they are being edited
return this.upvarFragmentNames()[idx] || '\u2191';
};
CustomCommandBlockMorph.prototype.specFromFragments = function () {
// for block prototypes while they are being edited
var ans = '';
this.parts().forEach(function (part) {
if (!part.fragment.isDeleted) {
ans = ans + part.fragment.defSpecFragment() + ' ';
}
});
return ans.trim();
};
CustomCommandBlockMorph.prototype.blockSpecFromFragments = function () {
// for block instances while their prototype is being edited
var ans = '';
this.parts().forEach(function (part) {
if (!part.fragment.isDeleted) {
ans = ans + part.fragment.blockSpecFragment() + ' ';
}
});
return ans.trim();
};
CustomCommandBlockMorph.prototype.declarationsFromFragments = function () {
// format for type declarations: {inputName : [type, default]}
var ans = {};
this.parts().forEach(function (part) {
if (part instanceof BlockInputFragmentMorph) {
ans[part.fragment.labelString] = [
part.fragment.type,
part.fragment.defaultValue,
part.fragment.options,
part.fragment.isReadOnly
];
}
});
return ans;
};
CustomCommandBlockMorph.prototype.parseSpec = function (spec) {
if (!this.isPrototype) {
return CustomCommandBlockMorph.uber.parseSpec.call(this, spec);
}
return this.definition.parseSpec.call(this, spec);
};
CustomCommandBlockMorph.prototype.mouseClickLeft = function () {
if (!this.isPrototype) {
return CustomCommandBlockMorph.uber.mouseClickLeft.call(this);
}
this.edit();
};
CustomCommandBlockMorph.prototype.edit = function () {
var myself = this, block, hat;
if (this.isPrototype) {
block = this.definition.blockInstance();
block.addShadow();
hat = this.parentThatIsA(PrototypeHatBlockMorph);
new BlockDialogMorph(
null,
function (definition) {
if (definition) { // temporarily update everything
hat.blockCategory = definition.category;
hat.type = definition.type;
myself.refreshPrototype();
}
},
myself
).openForChange(
'Change block',
hat.blockCategory,
hat.type,
myself.world(),
block.fullImage(),
myself.isInUse()
);
} else {
new BlockEditorMorph(this.definition, this.receiver()).popUp();
}
};
CustomCommandBlockMorph.prototype.labelPart = function (spec) {
var part;
if (!this.isPrototype) {
return CustomCommandBlockMorph.uber.labelPart.call(this, spec);
}
if ((spec[0] === '%') && (spec.length > 1)) {
// part = new BlockInputFragmentMorph(spec.slice(1));
part = new BlockInputFragmentMorph(spec.replace(/%/g, ''));
} else {
part = new BlockLabelFragmentMorph(spec);
part.fontSize = this.fontSize;
part.color = new Color(255, 255, 255);
part.isBold = true;
part.shadowColor = this.color.darker(this.labelContrast);
part.shadowOffset = this.embossing;
part.drawNew();
}
return part;
};
CustomCommandBlockMorph.prototype.placeHolder = function () {
var part;
part = new BlockLabelPlaceHolderMorph();
part.fontSize = this.fontSize * 1.4;
part.color = new Color(45, 45, 45);
part.drawNew();
return part;
};
CustomCommandBlockMorph.prototype.attachTargets = function () {
if (this.isPrototype) {
return [];
}
return CustomCommandBlockMorph.uber.attachTargets.call(this);
};
CustomCommandBlockMorph.prototype.isInUse = function () {
// anser true if an instance of my definition is found
// in any of my receiver's scripts or block definitions
return this.receiver().usesBlockInstance(this.definition);
};
// CustomCommandBlockMorph menu:
CustomCommandBlockMorph.prototype.userMenu = function () {
var menu;
if (this.isPrototype) {
menu = new MenuMorph(this);
menu.addItem(
"script pic...",
function () {
window.open(this.topBlock().fullImage().toDataURL());
},
'open a new window\nwith a picture of this script'
);
} else {
menu = this.constructor.uber.userMenu.call(this);
if (!menu) {
menu = new MenuMorph(this);
} else {
menu.addLine();
}
// menu.addItem("export definition...", 'exportBlockDefinition');
menu.addItem("delete block definition...", 'deleteBlockDefinition');
}
menu.addItem("edit...", 'edit'); // works also for prototypes
return menu;
};
CustomCommandBlockMorph.prototype.exportBlockDefinition = function () {
var xml = new SnapSerializer().serialize(this.definition);
window.open('data:text/xml,' + encodeURIComponent(xml));
};
CustomCommandBlockMorph.prototype.deleteBlockDefinition = function () {
var idx, rcvr, stage, ide, myself = this, block;
if (this.isPrototype) {
return null; // under construction...
}
block = myself.definition.blockInstance();
block.addShadow();
new DialogBoxMorph(
this,
function () {
rcvr = myself.receiver();
rcvr.deleteAllBlockInstances(myself.definition);
if (myself.definition.isGlobal) {
stage = rcvr.parentThatIsA(StageMorph);
idx = stage.globalBlocks.indexOf(myself.definition);
if (idx !== -1) {
stage.globalBlocks.splice(idx, 1);
}
} else {
idx = rcvr.customBlocks.indexOf(myself.definition);
if (idx !== -1) {
rcvr.customBlocks.splice(idx, 1);
}
}
ide = rcvr.parentThatIsA(IDE_Morph);
if (ide) {
ide.flushPaletteCache();
ide.refreshPalette();
}
},
this
).askYesNo(
'Delete Custom Block',
localize('block deletion dialog text'), // long string lookup
myself.world(),
block.fullImage()
);
};
// CustomCommandBlockMorph events:
CustomCommandBlockMorph.prototype.mouseEnter = function () {
var comment, help;
if (this.isTemplate && this.definition.comment) {
comment = this.definition.comment.fullCopy();
comment.contents.parse();
help = '';
comment.contents.lines.forEach(function (line) {
help = help + '\n' + line;
});
this.bubbleHelp(
help.substr(1),
this.definition.comment.color
);
}
};
CustomCommandBlockMorph.prototype.mouseLeave = function () {
if (this.isTemplate && this.definition.comment) {
this.world().hand.destroyTemporaries();
}
};
// CustomCommandBlockMorph bubble help:
CustomCommandBlockMorph.prototype.bubbleHelp = function (contents, color) {
var myself = this;
this.fps = 2;
this.step = function () {
if (this.bounds.containsPoint(this.world().hand.position())) {
myself.popUpbubbleHelp(contents, color);
}
myself.fps = 0;
delete myself.step;
};
};
CustomCommandBlockMorph.prototype.popUpbubbleHelp = function (
contents,
color
) {
new SpeechBubbleMorph(
contents,
color,
null,
1
).popUp(this.world(), this.rightCenter().add(new Point(-8, 0)));
};
// CustomCommandBlockMorph relabelling
CustomCommandBlockMorph.prototype.relabel = function (alternatives) {
var menu = new MenuMorph(this),
oldInputs = this.inputs().map(
function (each) {return each.fullCopy(); }
),
myself = this;
alternatives.forEach(function (def) {
var block = def.blockInstance();
block.restoreInputs(oldInputs);
block.fixBlockColor(null, true);
block.addShadow(new Point(3, 3));
menu.addItem(
block,
function () {
myself.definition = def;
myself.refresh();
}
);
});
menu.popup(this.world(), this.bottomLeft().subtract(new Point(
8,
this instanceof CommandBlockMorph ? this.corner : 0
)));
};
CustomCommandBlockMorph.prototype.alternatives = function () {
var rcvr = this.receiver(),
stage = rcvr.parentThatIsA(StageMorph),
allDefs = rcvr.customBlocks.concat(stage.globalBlocks),
myself = this;
return allDefs.filter(function (each) {
return each !== myself.definition &&
each.type === myself.definition.type;
});
};
// CustomReporterBlockMorph ////////////////////////////////////////////
// CustomReporterBlockMorph inherits from ReporterBlockMorph:
CustomReporterBlockMorph.prototype = new ReporterBlockMorph();
CustomReporterBlockMorph.prototype.constructor = CustomReporterBlockMorph;
CustomReporterBlockMorph.uber = ReporterBlockMorph.prototype;
// CustomReporterBlockMorph instance creation:
function CustomReporterBlockMorph(definition, isPredicate, isProto) {
this.init(definition, isPredicate, isProto);
}
CustomReporterBlockMorph.prototype.init = function (
definition,
isPredicate,
isProto
) {
this.definition = definition; // mandatory
this.isPrototype = isProto || false; // optional
CustomReporterBlockMorph.uber.init.call(this, isPredicate);
this.category = definition.category;
this.selector = 'evaluateCustomBlock';
if (definition) { // needed for de-serializing
this.refresh();
}
};
CustomReporterBlockMorph.prototype.refresh = function () {
CustomCommandBlockMorph.prototype.refresh.call(this);
if (!this.isPrototype) {
this.isPredicate = (this.definition.type === 'predicate');
}
if (this.parent instanceof SyntaxElementMorph) {
this.parent.cachedInputs = null;
}
this.drawNew();
};
CustomReporterBlockMorph.prototype.mouseClickLeft = function () {
if (!this.isPrototype) {
return CustomReporterBlockMorph.uber.mouseClickLeft.call(this);
}
this.edit();
};
CustomReporterBlockMorph.prototype.placeHolder
= CustomCommandBlockMorph.prototype.placeHolder;
CustomReporterBlockMorph.prototype.parseSpec
= CustomCommandBlockMorph.prototype.parseSpec;
CustomReporterBlockMorph.prototype.edit
= CustomCommandBlockMorph.prototype.edit;
CustomReporterBlockMorph.prototype.labelPart
= CustomCommandBlockMorph.prototype.labelPart;
CustomReporterBlockMorph.prototype.upvarFragmentNames
= CustomCommandBlockMorph.prototype.upvarFragmentNames;
CustomReporterBlockMorph.prototype.upvarFragmentName
= CustomCommandBlockMorph.prototype.upvarFragmentName;
CustomReporterBlockMorph.prototype.inputFragmentNames
= CustomCommandBlockMorph.prototype.inputFragmentNames;
CustomReporterBlockMorph.prototype.specFromFragments
= CustomCommandBlockMorph.prototype.specFromFragments;
CustomReporterBlockMorph.prototype.blockSpecFromFragments
= CustomCommandBlockMorph.prototype.blockSpecFromFragments;
CustomReporterBlockMorph.prototype.declarationsFromFragments
= CustomCommandBlockMorph.prototype.declarationsFromFragments;
CustomReporterBlockMorph.prototype.refreshPrototype
= CustomCommandBlockMorph.prototype.refreshPrototype;
CustomReporterBlockMorph.prototype.refreshPrototypeSlotTypes
= CustomCommandBlockMorph.prototype.refreshPrototypeSlotTypes;
CustomReporterBlockMorph.prototype.restoreInputs
= CustomCommandBlockMorph.prototype.restoreInputs;
CustomReporterBlockMorph.prototype.refreshDefaults
= CustomCommandBlockMorph.prototype.refreshDefaults;
CustomReporterBlockMorph.prototype.isInUse
= CustomCommandBlockMorph.prototype.isInUse;
// CustomReporterBlockMorph menu:
CustomReporterBlockMorph.prototype.userMenu
= CustomCommandBlockMorph.prototype.userMenu;
CustomReporterBlockMorph.prototype.deleteBlockDefinition
= CustomCommandBlockMorph.prototype.deleteBlockDefinition;
// CustomReporterBlockMorph events:
CustomReporterBlockMorph.prototype.mouseEnter
= CustomCommandBlockMorph.prototype.mouseEnter;
CustomReporterBlockMorph.prototype.mouseLeave
= CustomCommandBlockMorph.prototype.mouseLeave;
// CustomReporterBlockMorph bubble help:
CustomReporterBlockMorph.prototype.bubbleHelp
= CustomCommandBlockMorph.prototype.bubbleHelp;
CustomReporterBlockMorph.prototype.popUpbubbleHelp
= CustomCommandBlockMorph.prototype.popUpbubbleHelp;
// CustomReporterBlockMorph relabelling
CustomReporterBlockMorph.prototype.relabel
= CustomCommandBlockMorph.prototype.relabel;
CustomReporterBlockMorph.prototype.alternatives
= CustomCommandBlockMorph.prototype.alternatives;
// JaggedBlockMorph ////////////////////////////////////////////////////
/*
I am a reporter block with jagged left and right edges conveying the
appearance of having the broken out of a bigger block. I am used to
display input types in the long form input dialog.
*/
// JaggedBlockMorph inherits from ReporterBlockMorph:
JaggedBlockMorph.prototype = new ReporterBlockMorph();
JaggedBlockMorph.prototype.constructor = JaggedBlockMorph;
JaggedBlockMorph.uber = ReporterBlockMorph.prototype;
// JaggedBlockMorph preferences settings:
JaggedBlockMorph.prototype.jag = 5;
// JaggedBlockMorph instance creation:
function JaggedBlockMorph(spec) {
this.init(spec);
}
JaggedBlockMorph.prototype.init = function (spec) {
JaggedBlockMorph.uber.init.call(this);
if (spec) {this.setSpec(spec); }
if (spec === '%cs') {
this.minWidth = 25;
this.fixLayout();
}
};
// JaggedBlockMorph drawing:
JaggedBlockMorph.prototype.drawNew = function () {
var context;
this.cachedClr = this.color.toString();
this.cachedClrBright = this.bright();
this.cachedClrDark = this.dark();
this.image = newCanvas(this.extent());
context = this.image.getContext('2d');
context.fillStyle = this.cachedClr;
this.drawBackground(context);
if (!MorphicPreferences.isFlat) {
this.drawEdges(context);
}
// erase holes
this.eraseHoles(context);
};
JaggedBlockMorph.prototype.drawBackground = function (context) {
var w = this.width(),
h = this.height(),
jags = Math.round(h / this.jag),
delta = h / jags,
i,
y;
context.fillStyle = this.cachedClr;
context.beginPath();
context.moveTo(0, 0);
context.lineTo(w, 0);
y = 0;
for (i = 0; i < jags; i += 1) {
y += delta / 2;
context.lineTo(w - this.jag / 2, y);
y += delta / 2;
context.lineTo(w, y);
}
context.lineTo(0, h);
y = h;
for (i = 0; i < jags; i += 1) {
y -= delta / 2;
context.lineTo(this.jag / 2, y);
y -= delta / 2;
context.lineTo(0, y);
}
context.closePath();
context.fill();
};
JaggedBlockMorph.prototype.drawEdges = function (context) {
var w = this.width(),
h = this.height(),
jags = Math.round(h / this.jag),
delta = h / jags,
shift = this.edge / 2,
gradient,
i,
y;
context.lineWidth = this.edge;
context.lineJoin = 'round';
context.lineCap = 'round';
gradient = context.createLinearGradient(
0,
0,
0,
this.edge
);
gradient.addColorStop(0, this.cachedClrBright);
gradient.addColorStop(1, this.cachedClr);
context.strokeStyle = gradient;
context.beginPath();
context.moveTo(shift, shift);
context.lineTo(w - shift, shift);
context.stroke();
y = 0;
for (i = 0; i < jags; i += 1) {
context.strokeStyle = this.cachedClrDark;
context.beginPath();
context.moveTo(w - shift, y);
y += delta / 2;
context.lineTo(w - this.jag / 2 - shift, y);
context.stroke();
y += delta / 2;
}
gradient = context.createLinearGradient(
0,
h - this.edge,
0,
h
);
gradient.addColorStop(0, this.cachedClr);
gradient.addColorStop(1, this.cachedClrDark);
context.strokeStyle = gradient;
context.beginPath();
context.moveTo(w - shift, h - shift);
context.lineTo(shift, h - shift);
context.stroke();
y = h;
for (i = 0; i < jags; i += 1) {
context.strokeStyle = this.cachedClrBright;
context.beginPath();
context.moveTo(shift, y);
y -= delta / 2;
context.lineTo(this.jag / 2 + shift, y);
context.stroke();
y -= delta / 2;
}
};
// BlockDialogMorph ////////////////////////////////////////////////////
// BlockDialogMorph inherits from DialogBoxMorph:
BlockDialogMorph.prototype = new DialogBoxMorph();
BlockDialogMorph.prototype.constructor = BlockDialogMorph;
BlockDialogMorph.uber = DialogBoxMorph.prototype;
// BlockDialogMorph instance creation:
function BlockDialogMorph(target, action, environment) {
this.init(target, action, environment);
}
BlockDialogMorph.prototype.init = function (target, action, environment) {
// additional properties:
this.blockType = 'command';
this.category = 'other';
this.isGlobal = true;
this.types = null;
this.categories = null;
// initialize inherited properties:
BlockDialogMorph.uber.init.call(
this,
target,
action,
environment
);
// override inherited properites:
this.key = 'makeABlock';
this.types = new AlignmentMorph('row', this.padding);
this.add(this.types);
this.scopes = new AlignmentMorph('row', this.padding);
this.add(this.scopes);
this.categories = new BoxMorph();
this.categories.color = SpriteMorph.prototype.paletteColor.lighter(8);
this.categories.borderColor = this.categories.color.lighter(40);
this.createCategoryButtons();
this.fixCategoriesLayout();
this.add(this.categories);
this.createTypeButtons();
this.createScopeButtons();
this.fixLayout();
};
BlockDialogMorph.prototype.openForChange = function (
title,
category,
type,
world,
pic,
preventTypeChange // <bool>
) {
var clr = SpriteMorph.prototype.blockColor[category];
this.key = 'changeABlock';
this.category = category;
this.blockType = type;
this.categories.children.forEach(function (each) {
each.refresh();
});
this.types.children.forEach(function (each) {
each.setColor(clr);
each.refresh();
});
this.labelString = title;
this.createLabel();
if (pic) {this.setPicture(pic); }
this.addButton('ok', 'OK');
this.addButton('cancel', 'Cancel');
if (preventTypeChange) {
this.types.destroy();
this.types = null;
}
this.scopes.destroy();
this.scopes = null;
this.fixLayout();
this.drawNew();
this.popUp(world);
};
// category buttons
BlockDialogMorph.prototype.createCategoryButtons = function () {
var myself = this,
oldFlag = Morph.prototype.trackChanges;
Morph.prototype.trackChanges = false;
SpriteMorph.prototype.categories.forEach(function (cat) {
myself.addCategoryButton(cat);
});
Morph.prototype.trackChanges = oldFlag;
};
BlockDialogMorph.prototype.addCategoryButton = function (category) {
var labelWidth = 75,
myself = this,
colors = [
SpriteMorph.prototype.paletteColor,
SpriteMorph.prototype.paletteColor.darker(50),
SpriteMorph.prototype.blockColor[category]
],
button;
button = new ToggleButtonMorph(
colors,
this, // this block dialog box is the target
function () {
myself.category = category;
myself.categories.children.forEach(function (each) {
each.refresh();
});
if (myself.types) {
myself.types.children.forEach(function (each) {
each.setColor(colors[2]);
});
}
myself.edit();
},
category[0].toUpperCase().concat(category.slice(1)), // UCase label
function () {return myself.category === category; }, // query
null, // env
null, // hint
null, // template cache
labelWidth, // minWidth
true // has preview
);
button.corner = 8;
button.padding = 0;
button.labelShadowOffset = new Point(-1, -1);
button.labelShadowColor = colors[1];
button.labelColor = IDE_Morph.prototype.buttonLabelColor;
button.contrast = this.buttonContrast;
button.fixLayout();
button.refresh();
this.categories.add(button);
return button;
};
BlockDialogMorph.prototype.fixCategoriesLayout = function () {
var buttonWidth = this.categories.children[0].width(), // all the same
buttonHeight = this.categories.children[0].height(), // all the same
xPadding = 15,
yPadding = 2,
border = 10, // this.categories.border,
rows = Math.ceil((this.categories.children.length) / 2),
l = this.categories.left(),
t = this.categories.top(),
i = 0,
row,
col,
oldFlag = Morph.prototype.trackChanges;
Morph.prototype.trackChanges = false;
this.categories.children.forEach(function (button) {
i += 1;
row = Math.ceil(i / 2);
col = 2 - (i % 2);
button.setPosition(new Point(
l + (col * xPadding + ((col - 1) * buttonWidth)),
t + (row * yPadding + ((row - 1) * buttonHeight) + border)
));
});
if (MorphicPreferences.isFlat) {
this.categories.corner = 0;
this.categories.border = 0;
this.categories.edge = 0;
}
this.categories.setExtent(new Point(
3 * xPadding + 2 * buttonWidth,
(rows + 1) * yPadding + rows * buttonHeight + 2 * border
));
Morph.prototype.trackChanges = oldFlag;
this.categories.changed();
};
// type radio buttons
BlockDialogMorph.prototype.createTypeButtons = function () {
var block,
myself = this,
clr = SpriteMorph.prototype.blockColor[this.category];
block = new CommandBlockMorph();
block.setColor(clr);
block.setSpec(localize('Command'));
this.addBlockTypeButton(
function () {myself.setType('command'); },
block,
function () {return myself.blockType === 'command'; }
);
block = new ReporterBlockMorph();
block.setColor(clr);
block.setSpec(localize('Reporter'));
this.addBlockTypeButton(
function () {myself.setType('reporter'); },
block,
function () {return myself.blockType === 'reporter'; }
);
block = new ReporterBlockMorph(true);
block.setColor(clr);
block.setSpec(localize('Predicate'));
this.addBlockTypeButton(
function () {myself.setType('predicate'); },
block,
function () {return myself.blockType === 'predicate'; }
);
};
BlockDialogMorph.prototype.addBlockTypeButton = function (
action,
element,
query
) {
var button = new ToggleElementMorph(
this,
action,
element,
query,
null,
null,
'rebuild'
);
button.refresh();
this.types.add(button);
return button;
};
BlockDialogMorph.prototype.addTypeButton = function (action, label, query) {
var button = new ToggleMorph(
'radiobutton',
this,
action,
label,
query
);
button.edge = this.buttonEdge / 2;
button.outline = this.buttonOutline / 2;
button.outlineColor = this.buttonOutlineColor;
button.outlineGradient = this.buttonOutlineGradient;
button.contrast = this.buttonContrast;
button.drawNew();
button.fixLayout();
this.types.add(button);
return button;
};
BlockDialogMorph.prototype.setType = function (blockType) {
this.blockType = blockType || this.blockType;
this.types.children.forEach(function (c) {
c.refresh();
});
this.edit();
};
// scope radio buttons
BlockDialogMorph.prototype.createScopeButtons = function () {
var myself = this;
this.addScopeButton(
function () {myself.setScope('gobal'); },
"for all sprites",
function () {return myself.isGlobal; }
);
this.addScopeButton(
function () {myself.setScope('local'); },
"for this sprite only",
function () {return !myself.isGlobal; }
);
};
BlockDialogMorph.prototype.addScopeButton = function (action, label, query) {
var button = new ToggleMorph(
'radiobutton',
this,
action,
label,
query
);
button.edge = this.buttonEdge / 2;
button.outline = this.buttonOutline / 2;
button.outlineColor = this.buttonOutlineColor;
button.outlineGradient = this.buttonOutlineGradient;
button.contrast = this.buttonContrast;
button.drawNew();
button.fixLayout();
this.scopes.add(button);
return button;
};
BlockDialogMorph.prototype.setScope = function (varType) {
this.isGlobal = (varType === 'gobal');
this.scopes.children.forEach(function (c) {
c.refresh();
});
this.edit();
};
// other ops
BlockDialogMorph.prototype.getInput = function () {
var spec, def, body;
if (this.body instanceof InputFieldMorph) {
spec = this.normalizeSpaces(this.body.getValue());
}
def = new CustomBlockDefinition(spec);
def.type = this.blockType;
def.category = this.category;
def.isGlobal = this.isGlobal;
if (def.type === 'reporter' || def.type === 'predicate') {
body = Process.prototype.reify.call(
null,
SpriteMorph.prototype.blockForSelector('doReport'),
new List(),
true // ignore empty slots for custom block reification
);
body.outerContext = null;
def.body = body;
}
return def;
};
BlockDialogMorph.prototype.fixLayout = function () {
var th = fontHeight(this.titleFontSize) + this.titlePadding * 2;
if (this.body) {
this.body.setPosition(this.position().add(new Point(
this.padding,
th + this.padding
)));
this.silentSetWidth(this.body.width() + this.padding * 2);
this.silentSetHeight(
this.body.height()
+ this.padding * 2
+ th
);
if (this.categories) {
this.categories.setCenter(this.body.center());
this.categories.setTop(this.body.top());
this.body.setTop(this.categories.bottom() + this.padding);
this.silentSetHeight(
this.height()
+ this.categories.height()
+ this.padding
);
}
} else if (this.head) { // when changing an existing prototype
if (this.types) {
this.types.fixLayout();
this.silentSetWidth(
Math.max(this.types.width(), this.head.width())
+ this.padding * 2
);
} else {
this.silentSetWidth(
Math.max(this.categories.width(), this.head.width())
+ this.padding * 2
);
}
this.head.setCenter(this.center());
this.head.setTop(th + this.padding);
this.silentSetHeight(
this.head.height()
+ this.padding * 2
+ th
);
if (this.categories) {
this.categories.setCenter(this.center());
this.categories.setTop(this.head.bottom() + this.padding);
this.silentSetHeight(
this.height()
+ this.categories.height()
+ this.padding
);
}
}
if (this.label) {
this.label.setCenter(this.center());
this.label.setTop(this.top() + (th - this.label.height()) / 2);
}
if (this.types) {
this.types.fixLayout();
this.silentSetHeight(
this.height()
+ this.types.height()
+ this.padding
);
this.silentSetWidth(Math.max(
this.width(),
this.types.width() + this.padding * 2
));
this.types.setCenter(this.center());
if (this.body) {
this.types.setTop(this.body.bottom() + this.padding);
} else if (this.categories) {
this.types.setTop(this.categories.bottom() + this.padding);
}
}
if (this.scopes) {
this.scopes.fixLayout();
this.silentSetHeight(
this.height()
+ this.scopes.height()
+ (this.padding / 3)
);
this.silentSetWidth(Math.max(
this.width(),
this.scopes.width() + this.padding * 2
));
this.scopes.setCenter(this.center());
if (this.types) {
this.scopes.setTop(this.types.bottom() + (this.padding / 3));
}
}
if (this.buttons && (this.buttons.children.length > 0)) {
this.buttons.fixLayout();
this.silentSetHeight(
this.height()
+ this.buttons.height()
+ this.padding
);
this.buttons.setCenter(this.center());
this.buttons.setBottom(this.bottom() - this.padding);
}
};
// BlockEditorMorph ////////////////////////////////////////////////////
// BlockEditorMorph inherits from DialogBoxMorph:
BlockEditorMorph.prototype = new DialogBoxMorph();
BlockEditorMorph.prototype.constructor = BlockEditorMorph;
BlockEditorMorph.uber = DialogBoxMorph.prototype;
// BlockEditorMorph instance creation:
function BlockEditorMorph(definition, target) {
this.init(definition, target);
}
BlockEditorMorph.prototype.init = function (definition, target) {
var scripts, proto, scriptsFrame, block, comment, myself = this;
// additional properties:
this.definition = definition;
this.handle = null;
// initialize inherited properties:
BlockEditorMorph.uber.init.call(
this,
target,
function () {myself.updateDefinition(); },
target
);
// override inherited properites:
this.key = 'editBlock' + definition.spec;
this.labelString = 'Block Editor';
this.createLabel();
// create scripting area
scripts = new ScriptsMorph(target);
scripts.isDraggable = false;
scripts.color = IDE_Morph.prototype.groupColor;
scripts.cachedTexture = IDE_Morph.prototype.scriptsPaneTexture;
scripts.cleanUpMargin = 10;
proto = new PrototypeHatBlockMorph(this.definition);
proto.setPosition(scripts.position().add(10));
if (definition.comment !== null) {
comment = definition.comment.fullCopy();
proto.comment = comment;
comment.block = proto;
}
if (definition.body !== null) {
proto.nextBlock(definition.body.expression.fullCopy());
}
scripts.add(proto);
proto.fixBlockColor(null, true);
this.definition.scripts.forEach(function (element) {
block = element.fullCopy();
block.setPosition(scripts.position().add(element.position()));
scripts.add(block);
if (block instanceof BlockMorph) {
block.allComments().forEach(function (comment) {
comment.align(block);
});
}
});
proto.allComments().forEach(function (comment) {
comment.align(proto);
});
scriptsFrame = new ScrollFrameMorph(scripts);
scriptsFrame.padding = 10;
scriptsFrame.growth = 50;
scriptsFrame.isDraggable = false;
scriptsFrame.acceptsDrops = false;
scriptsFrame.contents.acceptsDrops = true;
scripts.scrollFrame = scriptsFrame;
this.addBody(scriptsFrame);
this.addButton('ok', 'OK');
this.addButton('updateDefinition', 'Apply');
this.addButton('cancel', 'Cancel');
this.setExtent(new Point(375, 300));
this.fixLayout();
proto.children[0].fixLayout();
scripts.fixMultiArgs();
};
BlockEditorMorph.prototype.popUp = function () {
var world = this.target.world();
if (world) {
BlockEditorMorph.uber.popUp.call(this, world);
this.handle = new HandleMorph(
this,
280,
220,
this.corner,
this.corner
);
}
};
// BlockEditorMorph ops
BlockEditorMorph.prototype.accept = function () {
// check DialogBoxMorph comment for accept()
if (this.action) {
if (typeof this.target === 'function') {
if (typeof this.action === 'function') {
this.target.call(this.environment, this.action.call());
} else {
this.target.call(this.environment, this.action);
}
} else {
if (typeof this.action === 'function') {
this.action.call(this.target, this.getInput());
} else { // assume it's a String
this.target[this.action](this.getInput());
}
}
}
this.close();
};
BlockEditorMorph.prototype.cancel = function () {
//this.refreshAllBlockInstances();
this.close();
};
BlockEditorMorph.prototype.close = function () {
var doubles, block,
myself = this;
// assert that no scope conflicts exists, i.e. that a global
// definition doesn't contain any local custom blocks, as they
// will be rendered "Obsolete!" when reloading the project
if (this.definition.isGlobal) {
block = detect(
this.body.contents.allChildren(),
function (morph) {
return morph.definition && !morph.definition.isGlobal;
}
);
if (block) {
block = block.definition.blockInstance();
block.addShadow();
new DialogBoxMorph().inform(
'Local Block(s) in Global Definition',
'This global block definition contains one or more\n'
+ 'local custom blocks which must be removed first.',
myself.world(),
block.fullImage()
);
return;
}
}
// allow me to disappear only when name collisions
// have been resolved
doubles = this.target.doubleDefinitionsFor(this.definition);
if (doubles.length > 0) {
block = doubles[0].blockInstance();
block.addShadow();
new DialogBoxMorph(this, 'consolidateDoubles', this).askYesNo(
'Same Named Blocks',
'Another custom block with this name exists.\n'
+ 'Would you like to replace it?',
myself.world(),
block.fullImage()
);
return;
}
this.destroy();
};
BlockEditorMorph.prototype.consolidateDoubles = function () {
this.target.replaceDoubleDefinitionsFor(this.definition);
this.destroy();
};
BlockEditorMorph.prototype.refreshAllBlockInstances = function () {
var template = this.target.paletteBlockInstance(this.definition);
this.target.allBlockInstances(this.definition).forEach(
function (block) {
block.refresh();
}
);
if (template) {
template.refreshDefaults();
}
};
BlockEditorMorph.prototype.updateDefinition = function () {
var head, ide,
pos = this.body.contents.position(),
element,
myself = this;
this.definition.receiver = this.target; // only for serialization
this.definition.spec = this.prototypeSpec();
this.definition.declarations = this.prototypeSlots();
this.definition.scripts = [];
this.body.contents.children.forEach(function (morph) {
if (morph instanceof PrototypeHatBlockMorph) {
head = morph;
} else if (morph instanceof BlockMorph ||
(morph instanceof CommentMorph && !morph.block)) {
element = morph.fullCopy();
element.parent = null;
element.setPosition(morph.position().subtract(pos));
myself.definition.scripts.push(element);
}
});
if (head) {
this.definition.category = head.blockCategory;
this.definition.type = head.type;
if (head.comment) {
this.definition.comment = head.comment.fullCopy();
this.definition.comment.block = true; // serialize in short form
} else {
this.definition.comment = null;
}
}
this.definition.body = this.context(head);
this.refreshAllBlockInstances();
ide = this.target.parentThatIsA(IDE_Morph);
ide.flushPaletteCache();
ide.refreshPalette();
};
BlockEditorMorph.prototype.context = function (prototypeHat) {
// answer my script reified for deferred execution
// if no prototypeHat is given, my body is scanned
var head, topBlock, stackFrame;
head = prototypeHat || detect(
this.body.contents.children,
function (c) {return c instanceof PrototypeHatBlockMorph; }
);
topBlock = head.nextBlock();
if (topBlock === null) {
return null;
}
topBlock.allChildren().forEach(function (c) {
if (c instanceof BlockMorph) {c.cachedInputs = null; }
});
stackFrame = Process.prototype.reify.call(
null,
topBlock,
new List(this.definition.inputNames()),
true // ignore empty slots for custom block reification
);
stackFrame.outerContext = null; //;
return stackFrame;
};
BlockEditorMorph.prototype.prototypeSpec = function () {
// answer the spec represented by my (edited) block prototype
return detect(
this.body.contents.children,
function (c) {return c instanceof PrototypeHatBlockMorph; }
).parts()[0].specFromFragments();
};
BlockEditorMorph.prototype.prototypeSlots = function () {
// answer the slot declarations from my (edited) block prototype
return detect(
this.body.contents.children,
function (c) {return c instanceof PrototypeHatBlockMorph; }
).parts()[0].declarationsFromFragments();
};
// BlockEditorMorph layout
BlockEditorMorph.prototype.fixLayout = function () {
var th = fontHeight(this.titleFontSize) + this.titlePadding * 2;
if (this.buttons && (this.buttons.children.length > 0)) {
this.buttons.fixLayout();
}
if (this.body) {
this.body.setPosition(this.position().add(new Point(
this.padding,
th + this.padding
)));
this.body.setExtent(new Point(
this.width() - this.padding * 2,
this.height() - this.padding * 3 - th - this.buttons.height()
));
}
if (this.label) {
this.label.setCenter(this.center());
this.label.setTop(this.top() + (th - this.label.height()) / 2);
}
if (this.buttons && (this.buttons.children.length > 0)) {
this.buttons.setCenter(this.center());
this.buttons.setBottom(this.bottom() - this.padding);
}
};
// PrototypeHatBlockMorph /////////////////////////////////////////////
// PrototypeHatBlockMorph inherits from HatBlockMorph:
PrototypeHatBlockMorph.prototype = new HatBlockMorph();
PrototypeHatBlockMorph.prototype.constructor = PrototypeHatBlockMorph;
PrototypeHatBlockMorph.uber = HatBlockMorph.prototype;
// PrototypeHatBlockMorph instance creation:
function PrototypeHatBlockMorph(definition) {
this.init(definition);
}
PrototypeHatBlockMorph.prototype.init = function (definition) {
var proto = definition.prototypeInstance();
this.definition = definition;
// additional attributes to store edited data
this.blockCategory = definition ? definition.category : null;
this.type = definition ? definition.type : null;
// init inherited stuff
HatBlockMorph.uber.init.call(this);
this.color = SpriteMorph.prototype.blockColor.control;
this.category = 'control';
this.add(proto);
proto.refreshPrototypeSlotTypes(); // show slot type indicators
this.fixLayout();
};
PrototypeHatBlockMorph.prototype.mouseClickLeft = function () {
// relay the mouse click to my prototype block to
// pop-up a Block Dialog
this.children[0].mouseClickLeft();
};
PrototypeHatBlockMorph.prototype.userMenu = function () {
return this.children[0].userMenu();
};
// PrototypeHatBlockMorph zebra coloring
PrototypeHatBlockMorph.prototype.fixBlockColor = function (
nearestBlock,
isForced
) {
var nearest = this.children[0] || nearestBlock;
if (!this.zebraContrast && !isForced) {
return;
}
if (!this.zebraContrast && isForced) {
return this.forceNormalColoring();
}
if (nearest.category === this.category) {
if (nearest.color.eq(this.color)) {
this.alternateBlockColor();
}
} else if (this.category && !this.color.eq(
SpriteMorph.prototype.blockColor[this.category]
)) {
this.alternateBlockColor();
}
if (isForced) {
this.fixChildrensBlockColor(true);
}
};
// BlockLabelFragment //////////////////////////////////////////////////
// BlockLabelFragment instance creation:
function BlockLabelFragment(labelString) {
this.labelString = labelString || '';
this.type = '%s'; // null for label, a spec for an input
this.defaultValue = '';
this.options = '';
this.isReadOnly = false; // for input slots
this.isDeleted = false;
}
// accessing
BlockLabelFragment.prototype.defSpecFragment = function () {
// answer a string representing my prototype's spec
var pref = this.type ? '%\'' : '';
return this.isDeleted ?
'' : pref + this.labelString + (this.type ? '\'' : '');
};
BlockLabelFragment.prototype.defTemplateSpecFragment = function () {
// answer a string representing my prototype's spec
// which also indicates my type, default value or arity
var suff = '';
if (!this.type) {return this.defSpecFragment(); }
if (this.isUpvar()) {
suff = ' \u2191';
} else if (this.isMultipleInput()) {
suff = '...';
} else if (this.type === '%cs') {
suff = ' \u03BB'; // ' [\u03BB'
} else if (this.type === '%b') {
suff = ' ?';
} else if (this.type === '%l') {
suff = ' \uFE19';
} else if (this.type === '%obj') {
suff = ' %turtleOutline';
} else if (contains(
['%cmdRing', '%repRing', '%predRing', '%anyUE', '%boolUE'],
this.type
)) {
suff = ' \u03BB';
} else if (this.defaultValue) {
if (this.type === '%n') {
suff = ' # = ' + this.defaultValue.toString();
} else { // 'any' or 'text'
suff = ' = ' + this.defaultValue.toString();
}
} else if (this.type === '%n') {
suff = ' #';
}
return this.labelString + suff;
};
BlockLabelFragment.prototype.blockSpecFragment = function () {
// answer a string representing my block spec
return this.isDeleted ? '' : this.type || this.labelString;
};
BlockLabelFragment.prototype.copy = function () {
var ans = new BlockLabelFragment(this.labelString);
ans.type = this.type;
ans.defaultValue = this.defaultValue;
ans.options = this.options;
ans.isReadOnly = this.isReadOnly;
return ans;
};
// arity
BlockLabelFragment.prototype.isSingleInput = function () {
return !this.isMultipleInput() &&
(this.type !== '%upvar');
};
BlockLabelFragment.prototype.isMultipleInput = function () {
// answer true if the type begins with '%mult'
if (!this.type) {
return false; // not an input at all
}
return this.type.indexOf('%mult') > -1;
};
BlockLabelFragment.prototype.isUpvar = function () {
if (!this.type) {
return false; // not an input at all
}
return this.type === '%upvar';
};
BlockLabelFragment.prototype.setToSingleInput = function () {
if (!this.type) {return null; } // not an input at all
if (this.type === '%upvar') {
this.type = '%s';
} else {
this.type = this.singleInputType();
}
};
BlockLabelFragment.prototype.setToMultipleInput = function () {
if (!this.type) {return null; } // not an input at all
if (this.type === '%upvar') {
this.type = '%s';
}
this.type = '%mult'.concat(this.singleInputType());
};
BlockLabelFragment.prototype.setToUpvar = function () {
if (!this.type) {return null; } // not an input at all
this.type = '%upvar';
};
BlockLabelFragment.prototype.singleInputType = function () {
// answer the type of my input withtou any preceding '%mult'
if (!this.type) {
return null; // not an input at all
}
if (this.isMultipleInput()) {
return this.type.substr(5); // everything following '%mult'
}
return this.type;
};
BlockLabelFragment.prototype.setSingleInputType = function (type) {
if (!this.type || !this.isMultipleInput()) {
this.type = type;
} else {
this.type = '%mult'.concat(type);
}
};
// BlockLabelFragmentMorph ///////////////////////////////////////////////
/*
I am a single word in a custom block prototype's label. I can be clicked
to edit my contents and to turn me into an input placeholder.
*/
// BlockLabelFragmentMorph inherits from StringMorph:
BlockLabelFragmentMorph.prototype = new StringMorph();
BlockLabelFragmentMorph.prototype.constructor = BlockLabelFragmentMorph;
BlockLabelFragmentMorph.uber = StringMorph.prototype;
// BlockLabelFragmentMorph instance creation:
function BlockLabelFragmentMorph(text) {
this.init(text);
}
BlockLabelFragmentMorph.prototype.init = function (text) {
this.fragment = new BlockLabelFragment(text);
this.fragment.type = null;
this.sO = null; // temporary backup for shadowOffset
BlockLabelFragmentMorph.uber.init.call(
this,
text,
null, // font size
SyntaxElementMorph.prototype.labelFontStyle,
null, // bold
null, // italic
null, // numeric
null, // shadow offset
null, // shadow color
null, // color
SyntaxElementMorph.prototype.labelFontName
);
};
// BlockLabelFragmentMorph events:
BlockLabelFragmentMorph.prototype.mouseEnter = function () {
this.sO = this.shadowOffset;
this.shadowOffset = this.sO.neg();
this.drawNew();
this.changed();
};
BlockLabelFragmentMorph.prototype.mouseLeave = function () {
this.shadowOffset = this.sO;
this.drawNew();
this.changed();
};
BlockLabelFragmentMorph.prototype.mouseClickLeft = function () {
/*
make a copy of my fragment object and open an InputSlotDialog on it.
If the user acknowledges the DialogBox, assign the - edited - copy
of the fragment object to be my new fragment object and update the
custom block'label (the prototype in the block editor). Do not yet update
the definition and every block instance, as this happens only after
the user acknowledges and closes the block editor
*/
var frag = this.fragment.copy(),
myself = this,
isPlaceHolder = this instanceof BlockLabelPlaceHolderMorph,
isOnlyElement = this.parent.parseSpec(this.parent.blockSpec).length
< 2;
new InputSlotDialogMorph(
frag,
null,
function () {myself.updateBlockLabel(frag); },
this,
this.parent.definition.category
).open(
this instanceof BlockLabelFragmentMorph ?
'Edit label fragment' :
isPlaceHolder ? 'Create input name' : 'Edit input name',
frag.labelString,
this.world(),
null,
isPlaceHolder || isOnlyElement
);
};
BlockLabelFragmentMorph.prototype.updateBlockLabel = function (newFragment) {
var prot = this.parentThatIsA(BlockMorph);
this.fragment = newFragment;
if (prot) {
prot.refreshPrototype();
}
};
BlockLabelFragmentMorph.prototype.userMenu = function () {
// show a menu of built-in special symbols
var myself = this,
symbolColor = new Color(100, 100, 130),
menu = new MenuMorph(
function (string) {
var tuple = myself.text.split('-');
myself.changed();
tuple[0] = '$' + string;
myself.text = tuple.join('-');
myself.fragment.labelString = myself.text;
myself.drawNew();
myself.changed();
},
null,
this,
this.fontSize
);
SymbolMorph.prototype.names.forEach(function (name) {
menu.addItem(
[new SymbolMorph(name, menu.fontSize, symbolColor), name],
name
);
});
return menu;
};
// BlockLabelPlaceHolderMorph ///////////////////////////////////////////////
/*
I am a space between words or inputs in a custom block prototype's label.
When I am moused over I display a plus sign on a colored background
circle. I can be clicked to add a new word or input to the prototype.
*/
// BlockLabelPlaceHolderMorph inherits from StringMorph:
BlockLabelPlaceHolderMorph.prototype = new StringMorph();
BlockLabelPlaceHolderMorph.prototype.constructor = BlockLabelPlaceHolderMorph;
BlockLabelPlaceHolderMorph.uber = StringMorph.prototype;
// BlockLabelPlaceHolderMorph preferences settings
BlockLabelPlaceHolderMorph.prototype.plainLabel = false; // always show (+)
// BlockLabelPlaceHolderMorph instance creation:
function BlockLabelPlaceHolderMorph() {
this.init();
}
BlockLabelPlaceHolderMorph.prototype.init = function () {
this.fragment = new BlockLabelFragment('');
this.fragment.type = '%s';
this.fragment.isDeleted = true;
this.isHighlighted = false;
this.isProtectedLabel = true; // doesn't participate in zebra coloring
BlockLabelFragmentMorph.uber.init.call(this, '+');
};
// BlockLabelPlaceHolderMorph drawing
BlockLabelPlaceHolderMorph.prototype.drawNew = function () {
var context, width, x, y, cx, cy;
// set my text contents depending on the "plainLabel" flag
if (this.plainLabel) {
this.text = this.isHighlighted ? ' + ' : '';
}
// initialize my surface property
this.image = newCanvas();
context = this.image.getContext('2d');
context.font = this.font();
// set my extent
width = Math.max(
context.measureText(this.text).width
+ Math.abs(this.shadowOffset.x),
1
);
this.bounds.corner = this.bounds.origin.add(
new Point(
width,
fontHeight(this.fontSize) + Math.abs(this.shadowOffset.y)
)
);
this.image.width = width;
this.image.height = this.height();
// draw background, if any
if (this.isHighlighted) {
cx = Math.floor(width / 2);
cy = Math.floor(this.height() / 2);
context.fillStyle = this.color.toString();
context.beginPath();
context.arc(
cx,
cy * 1.2,
Math.min(cx, cy),
radians(0),
radians(360),
false
);
context.closePath();
context.fill();
}
// prepare context for drawing text
context.font = this.font();
context.textAlign = 'left';
context.textBaseline = 'bottom';
// first draw the shadow, if any
if (this.shadowColor) {
x = Math.max(this.shadowOffset.x, 0);
y = Math.max(this.shadowOffset.y, 0);
context.fillStyle = this.shadowColor.toString();
context.fillText(this.text, x, fontHeight(this.fontSize) + y);
}
// now draw the actual text
x = Math.abs(Math.min(this.shadowOffset.x, 0));
y = Math.abs(Math.min(this.shadowOffset.y, 0));
context.fillStyle = this.isHighlighted ?
'white' : this.color.toString();
context.fillText(this.text, x, fontHeight(this.fontSize) + y);
// notify my parent of layout change
if (this.parent) {
if (this.parent.fixLayout) {
this.parent.fixLayout();
}
}
};
// BlockLabelPlaceHolderMorph events:
BlockLabelPlaceHolderMorph.prototype.mouseEnter = function () {
this.isHighlighted = true;
this.drawNew();
this.changed();
};
BlockLabelPlaceHolderMorph.prototype.mouseLeave = function () {
this.isHighlighted = false;
this.drawNew();
this.changed();
};
BlockLabelPlaceHolderMorph.prototype.mouseClickLeft
= BlockLabelFragmentMorph.prototype.mouseClickLeft;
BlockLabelPlaceHolderMorph.prototype.updateBlockLabel
= BlockLabelFragmentMorph.prototype.updateBlockLabel;
// BlockInputFragmentMorph ///////////////////////////////////////////////
/*
I am a variable blob in a custom block prototype's label. I can be clicked
to edit my contents and to turn me into an part of the block's label text.
*/
// BlockInputFragmentMorph inherits from TemplateSlotMorph:
BlockInputFragmentMorph.prototype = new TemplateSlotMorph();
BlockInputFragmentMorph.prototype.constructor = BlockInputFragmentMorph;
BlockInputFragmentMorph.uber = TemplateSlotMorph.prototype;
// BlockInputFragmentMorph instance creation:
function BlockInputFragmentMorph(text) {
this.init(text);
}
BlockInputFragmentMorph.prototype.init = function (text) {
this.fragment = new BlockLabelFragment(text);
this.fragment.type = '%s';
BlockInputFragmentMorph.uber.init.call(this, text);
};
// BlockInputFragmentMorph events:
BlockInputFragmentMorph.prototype.mouseClickLeft
= BlockLabelFragmentMorph.prototype.mouseClickLeft;
BlockInputFragmentMorph.prototype.updateBlockLabel
= BlockLabelFragmentMorph.prototype.updateBlockLabel;
// InputSlotDialogMorph ////////////////////////////////////////////////
// ... "inherits" some methods from BlockDialogMorph
// InputSlotDialogMorph inherits from DialogBoxMorph:
InputSlotDialogMorph.prototype = new DialogBoxMorph();
InputSlotDialogMorph.prototype.constructor = InputSlotDialogMorph;
InputSlotDialogMorph.uber = DialogBoxMorph.prototype;
// InputSlotDialogMorph preferences settings:
// if "isLaunchingExpanded" is true I always open in the long form
InputSlotDialogMorph.prototype.isLaunchingExpanded = false;
// InputSlotDialogMorph instance creation:
function InputSlotDialogMorph(
fragment,
target,
action,
environment,
category
) {
this.init(fragment, target, action, environment, category);
}
InputSlotDialogMorph.prototype.init = function (
fragment,
target,
action,
environment,
category
) {
var scale = SyntaxElementMorph.prototype.scale,
fh = fontHeight(10) / 1.2 * scale; // "raw height"
// additional properties:
this.fragment = fragment || new BlockLabelFragment();
this.textfield = null;
this.types = null;
this.slots = null;
this.isExpanded = false;
this.category = category || 'other';
this.cachedRadioButton = null; // "template" for radio button backgrounds
// initialize inherited properties:
BlockDialogMorph.uber.init.call(
this,
target,
action,
environment
);
// override inherited properites:
this.types = new AlignmentMorph('row', this.padding);
this.types.respectHiddens = true; // prevent the arrow from flipping
this.add(this.types);
this.slots = new BoxMorph();
this.slots.color = new Color(55, 55, 55); // same as palette
this.slots.borderColor = this.slots.color.lighter(50);
this.slots.setExtent(new Point((fh + 10) * 24, (fh + 10 * scale) * 10.4));
this.add(this.slots);
this.createSlotTypeButtons();
this.fixSlotsLayout();
this.addSlotsMenu();
this.createTypeButtons();
this.fixLayout();
};
InputSlotDialogMorph.prototype.createTypeButtons = function () {
var block,
arrow,
myself = this,
clr = SpriteMorph.prototype.blockColor[this.category];
block = new JaggedBlockMorph(localize('Title text'));
block.setColor(clr);
this.addBlockTypeButton(
function () {myself.setType(null); },
block,
function () {return myself.fragment.type === null; }
);
block = new JaggedBlockMorph('%inputName');
block.setColor(clr);
this.addBlockTypeButton(
function () {myself.setType('%s'); },
block,
function () {return myself.fragment.type !== null; }
);
// add an arrow button for long form/short form toggling
arrow = new ArrowMorph(
'right',
PushButtonMorph.prototype.fontSize + 4,
2
);
arrow.noticesTransparentClick = true;
this.types.add(arrow);
this.types.fixLayout();
// configure arrow button
arrow.refresh = function () {
if (myself.fragment.type === null) {
myself.isExpanded = false;
arrow.hide();
myself.drawNew();
} else {
arrow.show();
if (myself.isExpanded) {
arrow.direction = 'down';
} else {
arrow.direction = 'right';
}
arrow.drawNew();
arrow.changed();
}
};
arrow.mouseClickLeft = function () {
if (arrow.isVisible) {
myself.isExpanded = !myself.isExpanded;
myself.types.children.forEach(function (c) {
c.refresh();
});
myself.drawNew();
myself.edit();
}
};
arrow.refresh();
};
InputSlotDialogMorph.prototype.addTypeButton
= BlockDialogMorph.prototype.addTypeButton;
InputSlotDialogMorph.prototype.addBlockTypeButton
= BlockDialogMorph.prototype.addBlockTypeButton;
InputSlotDialogMorph.prototype.setType = function (fragmentType) {
this.textfield.choices = fragmentType ? null : this.symbolMenu;
this.textfield.drawNew();
this.fragment.type = fragmentType || null;
this.types.children.forEach(function (c) {
c.refresh();
});
this.slots.children.forEach(function (c) {
c.refresh();
});
this.edit();
};
InputSlotDialogMorph.prototype.getInput = function () {
var lbl;
if (this.body instanceof InputFieldMorph) {
lbl = this.normalizeSpaces(this.body.getValue());
}
if (lbl) {
this.fragment.labelString = lbl;
this.fragment.defaultValue = this.slots.defaultInputField.getValue();
return lbl;
}
this.fragment.isDeleted = true;
return null;
};
InputSlotDialogMorph.prototype.fixLayout = function () {
var maxWidth,
left = this.left(),
th = fontHeight(this.titleFontSize) + this.titlePadding * 2;
if (!this.isExpanded) {
if (this.slots) {
this.slots.hide();
}
return BlockDialogMorph.prototype.fixLayout.call(this);
}
this.slots.show();
maxWidth = this.slots.width();
// arrange panes :
// body (input field)
this.body.setPosition(this.position().add(new Point(
this.padding + (maxWidth - this.body.width()) / 2,
th + this.padding
)));
// label
this.label.setLeft(
left + this.padding + (maxWidth - this.label.width()) / 2
);
this.label.setTop(this.top() + (th - this.label.height()) / 2);
// types
this.types.fixLayout();
this.types.setTop(this.body.bottom() + this.padding);
this.types.setLeft(
left + this.padding + (maxWidth - this.types.width()) / 2
);
// slots
this.slots.setPosition(new Point(
this.left() + this.padding,
this.types.bottom() + this.padding
));
this.slots.children.forEach(function (c) {
c.refresh();
});
// buttons
this.buttons.fixLayout();
this.buttons.setTop(this.slots.bottom() + this.padding);
this.buttons.setLeft(
left + this.padding + (maxWidth - this.buttons.width()) / 2
);
// set dialog box dimensions:
this.silentSetHeight(this.buttons.bottom() - this.top() + this.padding);
this.silentSetWidth(this.slots.right() - this.left() + this.padding);
};
InputSlotDialogMorph.prototype.open = function (
title,
defaultString,
world,
pic,
noDeleteButton
) {
var txt = new InputFieldMorph(defaultString),
oldFlag = Morph.prototype.trackChanges;
if (!this.fragment.type) {
txt.choices = this.symbolMenu;
}
Morph.prototype.trackChanges = false;
this.isExpanded = this.isLaunchingExpanded;
txt.setWidth(250);
this.labelString = title;
this.createLabel();
if (pic) {this.setPicture(pic); }
this.addBody(txt);
txt.drawNew();
this.textfield = txt;
this.addButton('ok', 'OK');
if (!noDeleteButton) {
this.addButton('deleteFragment', 'Delete');
}
this.addButton('cancel', 'Cancel');
this.fixLayout();
this.drawNew();
this.fixLayout();
this.popUp(world);
this.add(this.types); // make the types come to front
Morph.prototype.trackChanges = oldFlag;
this.changed();
};
InputSlotDialogMorph.prototype.symbolMenu = function () {
var symbols = [],
symbolColor = new Color(100, 100, 130),
myself = this;
SymbolMorph.prototype.names.forEach(function (symbol) {
symbols.push([
[
new SymbolMorph(symbol, myself.fontSize, symbolColor),
localize(symbol)
],
'$' + symbol
]);
});
return symbols;
};
InputSlotDialogMorph.prototype.deleteFragment = function () {
this.fragment.isDeleted = true;
this.accept();
};
InputSlotDialogMorph.prototype.createSlotTypeButtons = function () {
// populate my 'slots' area with radio buttons, labels and input fields
var myself = this, defLabel, defInput,
oldFlag = Morph.prototype.trackChanges;
Morph.prototype.trackChanges = false;
// slot types
this.addSlotTypeButton('Object', '%obj');
this.addSlotTypeButton('Text', '%txt');
this.addSlotTypeButton('List', '%l');
this.addSlotTypeButton('Number', '%n');
this.addSlotTypeButton('Any type', '%s');
this.addSlotTypeButton('Boolean (T/F)', '%b');
this.addSlotTypeButton('Command\n(inline)', '%cmdRing'); //'%cmd');
this.addSlotTypeButton('Reporter', '%repRing'); //'%r');
this.addSlotTypeButton('Predicate', '%predRing'); //'%p');
this.addSlotTypeButton('Command\n(C-shape)', '%cs');
this.addSlotTypeButton('Any\n(unevaluated)', '%anyUE');
this.addSlotTypeButton('Boolean\n(unevaluated)', '%boolUE');
// arity and upvars
this.slots.radioButtonSingle = this.addSlotArityButton(
function () {myself.setSlotArity('single'); },
"Single input.",
function () {return myself.fragment.isSingleInput(); }
);
this.addSlotArityButton(
function () {myself.setSlotArity('multiple'); },
"Multiple inputs (value is list of inputs)",
function () {return myself.fragment.isMultipleInput(); }
);
this.addSlotArityButton(
function () {myself.setSlotArity('upvar'); },
"Upvar - make internal variable visible to caller",
function () {return myself.fragment.isUpvar(); }
);
// default values
defLabel = new StringMorph(localize('Default Value:'));
defLabel.fontSize = this.slots.radioButtonSingle.fontSize;
defLabel.setColor(new Color(255, 255, 255));
defLabel.refresh = function () {
if (myself.isExpanded && contains(
['%s', '%n', '%txt', '%anyUE'],
myself.fragment.type
)) {
defLabel.show();
} else {
defLabel.hide();
}
};
this.slots.defaultInputLabel = defLabel;
this.slots.add(defLabel);
defInput = new InputFieldMorph(this.fragment.defaultValue);
defInput.contents().fontSize = defLabel.fontSize;
defInput.contrast = 90;
defInput.contents().drawNew();
defInput.setWidth(50);
defInput.refresh = function () {
if (defLabel.isVisible) {
defInput.show();
if (myself.fragment.type === '%n') {
defInput.setIsNumeric(true);
} else {
defInput.setIsNumeric(false);
}
} else {
defInput.hide();
}
};
this.slots.defaultInputField = defInput;
this.slots.add(defInput);
defInput.drawNew();
Morph.prototype.trackChanges = oldFlag;
};
InputSlotDialogMorph.prototype.setSlotType = function (type) {
this.fragment.setSingleInputType(type);
this.slots.children.forEach(function (c) {
c.refresh();
});
this.edit();
};
InputSlotDialogMorph.prototype.setSlotArity = function (arity) {
if (arity === 'single') {
this.fragment.setToSingleInput();
} else if (arity === 'multiple') {
this.fragment.setToMultipleInput();
} else if (arity === 'upvar') {
this.fragment.setToUpvar();
// hide other options - under construction
}
this.slots.children.forEach(function (c) {
c.refresh();
});
this.edit();
};
InputSlotDialogMorph.prototype.addSlotTypeButton = function (
label,
spec
) {
/*
this method produces a radio button with a picture of the
slot type indicated by "spec" and the "label" text to
its right.
Note that you can make the slot picture interactive (turn
it into a ToggleElementMorph by changing the
element.fullImage()
line to just
element
I've opted for the simpler representation because it reduces
the duration of time it takes for the InputSlotDialog to load
and show. But in the future computers and browsers may be
faster.
*/
var myself = this,
action = function () {myself.setSlotType(spec); },
query,
element = new JaggedBlockMorph(spec),
button;
query = function () {
return myself.fragment.singleInputType() === spec;
};
element.setCategory(this.category);
element.rebuild();
button = new ToggleMorph(
'radiobutton',
this,
action,
label,
query,
null,
null,
this.cachedRadioButton,
element.fullImage(), // delete the "fullImage()" part for interactive
'rebuild'
);
button.edge = this.buttonEdge / 2;
button.outline = this.buttonOutline / 2;
button.outlineColor = this.buttonOutlineColor;
button.outlineGradient = this.buttonOutlineGradient;
button.drawNew();
button.fixLayout();
button.label.isBold = false;
button.label.setColor(new Color(255, 255, 255));
if (!this.cachedRadioButton) {
this.cachedRadioButton = button;
}
this.slots.add(button);
return button;
};
InputSlotDialogMorph.prototype.addSlotArityButton = function (
action,
label,
query
) {
var button = new ToggleMorph(
'radiobutton',
this,
action,
label,
query,
null,
null,
this.cachedRadioButton
);
button.edge = this.buttonEdge / 2;
button.outline = this.buttonOutline / 2;
button.outlineColor = this.buttonOutlineColor;
button.outlineGradient = this.buttonOutlineGradient;
button.drawNew();
button.fixLayout();
// button.label.isBold = false;
button.label.setColor(new Color(255, 255, 255));
this.slots.add(button);
if (!this.cachedRadioButton) {
this.cachedRadioButton = button;
}
return button;
};
InputSlotDialogMorph.prototype.fixSlotsLayout = function () {
var slots = this.slots,
scale = SyntaxElementMorph.prototype.scale,
xPadding = 10 * scale,
ypadding = 14 * scale,
bh = (fontHeight(10) / 1.2 + 15) * scale, // slot type button height
ah = (fontHeight(10) / 1.2 + 10) * scale, // arity button height
size = 12, // number slot type radio buttons
cols = [
slots.left() + xPadding,
slots.left() + slots.width() / 3,
slots.left() + slots.width() * 2 / 3
],
rows = [
slots.top() + ypadding,
slots.top() + ypadding + bh,
slots.top() + ypadding + bh * 2,
slots.top() + ypadding + bh * 3,
slots.top() + ypadding + bh * 4,
slots.top() + ypadding + bh * 5,
slots.top() + ypadding + bh * 5 + ah,
slots.top() + ypadding + bh * 5 + ah * 2
],
idx,
row = -1,
col,
oldFlag = Morph.prototype.trackChanges;
Morph.prototype.trackChanges = false;
// slot types:
for (idx = 0; idx < size; idx += 1) {
col = idx % 3;
if (idx % 3 === 0) {row += 1; }
slots.children[idx].setPosition(new Point(
cols[col],
rows[row]
));
}
// arity:
col = 0;
row = 5;
for (idx = size; idx < size + 3; idx += 1) {
slots.children[idx].setPosition(new Point(
cols[col],
rows[row + idx - size]
));
}
// default input
this.slots.defaultInputLabel.setPosition(
this.slots.radioButtonSingle.label.topRight().add(new Point(5, 0))
);
this.slots.defaultInputField.setCenter(
this.slots.defaultInputLabel.center().add(new Point(
this.slots.defaultInputField.width() / 2
+ this.slots.defaultInputLabel.width() / 2 + 5,
0
))
);
Morph.prototype.trackChanges = oldFlag;
this.slots.changed();
};
InputSlotDialogMorph.prototype.addSlotsMenu = function () {
var myself = this;
this.slots.userMenu = function () {
if (contains(['%s', '%n', '%txt', '%anyUE'], myself.fragment.type)) {
var menu = new MenuMorph(myself),
on = '\u2611 ',
off = '\u2610 ';
menu.addItem('options...', 'editSlotOptions');
menu.addItem(
(myself.fragment.isReadOnly ? on : off) +
localize('read-only'),
function () {myself.fragment.isReadOnly =
!myself.fragment.isReadOnly;
}
);
return menu;
}
return Morph.prototype.userMenu.call(myself);
};
};
InputSlotDialogMorph.prototype.editSlotOptions = function () {
var myself = this;
new DialogBoxMorph(
myself,
function (options) {
myself.fragment.options = options.trim();
},
myself
).promptCode(
'Input Slot Options',
myself.fragment.options,
myself.world(),
null,
localize('Enter one option per line.' +
'Optionally use "=" as key/value delimiter\n' +
'e.g.\n the answer=42')
);
};
// InputSlotDialogMorph hiding and showing:
/*
override the inherited behavior to recursively hide/show all
children, so that my instances get restored correctly when
hiding/showing my parent.
*/
InputSlotDialogMorph.prototype.hide = function () {
this.isVisible = false;
this.changed();
};
InputSlotDialogMorph.prototype.show = function () {
this.isVisible = true;
this.changed();
};
// VariableDialogMorph ////////////////////////////////////////////////////
// VariableDialogMorph inherits from DialogBoxMorph:
VariableDialogMorph.prototype = new DialogBoxMorph();
VariableDialogMorph.prototype.constructor = VariableDialogMorph;
VariableDialogMorph.uber = DialogBoxMorph.prototype;
// ... and some behavior from BlockDialogMorph
// VariableDialogMorph instance creation:
function VariableDialogMorph(target, action, environment) {
this.init(target, action, environment);
}
VariableDialogMorph.prototype.init = function (target, action, environment) {
// additional properties:
this.types = null;
this.isGlobal = true;
// initialize inherited properties:
BlockDialogMorph.uber.init.call(
this,
target,
action,
environment
);
// override inherited properites:
this.types = new AlignmentMorph('row', this.padding);
this.add(this.types);
this.createTypeButtons();
};
VariableDialogMorph.prototype.createTypeButtons = function () {
var myself = this;
this.addTypeButton(
function () {myself.setType('gobal'); },
"for all sprites",
function () {return myself.isGlobal; }
);
this.addTypeButton(
function () {myself.setType('local'); },
"for this sprite only",
function () {return !myself.isGlobal; }
);
};
VariableDialogMorph.prototype.addTypeButton
= BlockDialogMorph.prototype.addTypeButton;
VariableDialogMorph.prototype.setType = function (varType) {
this.isGlobal = (varType === 'gobal');
this.types.children.forEach(function (c) {
c.refresh();
});
this.edit();
};
VariableDialogMorph.prototype.getInput = function () {
// answer a tuple: [varName, isGlobal]
var name = this.normalizeSpaces(this.body.getValue());
return name ? [name, this.isGlobal] : null;
};
VariableDialogMorph.prototype.fixLayout = function () {
var th = fontHeight(this.titleFontSize) + this.titlePadding * 2;
if (this.body) {
this.body.setPosition(this.position().add(new Point(
this.padding,
th + this.padding
)));
this.silentSetWidth(this.body.width() + this.padding * 2);
this.silentSetHeight(
this.body.height()
+ this.padding * 2
+ th
);
}
if (this.label) {
this.label.setCenter(this.center());
this.label.setTop(this.top() + (th - this.label.height()) / 2);
}
if (this.types) {
this.types.fixLayout();
this.silentSetHeight(
this.height()
+ this.types.height()
+ this.padding
);
this.silentSetWidth(Math.max(
this.width(),
this.types.width() + this.padding * 2
));
this.types.setCenter(this.center());
if (this.body) {
this.types.setTop(this.body.bottom() + this.padding);
} else if (this.categories) {
this.types.setTop(this.categories.bottom() + this.padding);
}
}
if (this.buttons && (this.buttons.children.length > 0)) {
this.buttons.fixLayout();
this.silentSetHeight(
this.height()
+ this.buttons.height()
+ this.padding
);
this.buttons.setCenter(this.center());
this.buttons.setBottom(this.bottom() - this.padding);
}
};
// BlockExportDialogMorph ////////////////////////////////////////////////////
// BlockExportDialogMorph inherits from DialogBoxMorph:
BlockExportDialogMorph.prototype = new DialogBoxMorph();
BlockExportDialogMorph.prototype.constructor = BlockExportDialogMorph;
BlockExportDialogMorph.uber = DialogBoxMorph.prototype;
// BlockExportDialogMorph constants:
BlockExportDialogMorph.prototype.key = 'blockExport';
// BlockExportDialogMorph instance creation:
function BlockExportDialogMorph(serializer, blocks) {
this.init(serializer, blocks);
}
BlockExportDialogMorph.prototype.init = function (serializer, blocks) {
var myself = this;
// additional properties:
this.serializer = serializer;
this.blocks = blocks.slice(0);
this.handle = null;
// initialize inherited properties:
BlockExportDialogMorph.uber.init.call(
this,
null, // target
function () {myself.exportBlocks(); },
null // environment
);
// override inherited properites:
this.labelString = 'Export blocks';
this.createLabel();
// build contents
this.buildContents();
};
BlockExportDialogMorph.prototype.buildContents = function () {
var palette, x, y, block, checkBox, lastCat,
myself = this,
padding = 4;
// create plaette
palette = new ScrollFrameMorph(
null,
null,
SpriteMorph.prototype.sliderColor
);
palette.color = SpriteMorph.prototype.paletteColor;
palette.padding = padding;
palette.isDraggable = false;
palette.acceptsDrops = false;
palette.contents.acceptsDrops = false;
// populate palette
x = palette.left() + padding;
y = palette.top() + padding;
SpriteMorph.prototype.categories.forEach(function (category) {
myself.blocks.forEach(function (definition) {
if (definition.category === category) {
if (lastCat && (category !== lastCat)) {
y += padding;
}
lastCat = category;
block = definition.templateInstance();
checkBox = new ToggleMorph(
'checkbox',
myself,
function () {
var idx = myself.blocks.indexOf(definition);
if (idx > -1) {
myself.blocks.splice(idx, 1);
} else {
myself.blocks.push(definition);
}
},
null,
function () {
return contains(
myself.blocks,
definition
);
},
null,
null,
null,
block.fullImage()
);
checkBox.setPosition(new Point(
x,
y + (checkBox.top() - checkBox.toggleElement.top())
));
palette.addContents(checkBox);
y += checkBox.fullBounds().height() + padding;
}
});
});
palette.scrollX(padding);
palette.scrollY(padding);
this.addBody(palette);
this.addButton('ok', 'OK');
this.addButton('cancel', 'Cancel');
this.setExtent(new Point(220, 300));
this.fixLayout();
};
BlockExportDialogMorph.prototype.popUp = function (wrrld) {
var world = wrrld || this.target.world();
if (world) {
BlockExportDialogMorph.uber.popUp.call(this, world);
this.handle = new HandleMorph(
this,
200,
220,
this.corner,
this.corner
);
}
};
// BlockExportDialogMorph menu
BlockExportDialogMorph.prototype.userMenu = function () {
var menu = new MenuMorph(this, 'select');
menu.addItem('all', 'selectAll');
menu.addItem('none', 'selectNone');
return menu;
};
BlockExportDialogMorph.prototype.selectAll = function () {
this.body.contents.children.forEach(function (checkBox) {
if (!checkBox.state) {
checkBox.trigger();
}
});
};
BlockExportDialogMorph.prototype.selectNone = function () {
this.blocks = [];
this.body.contents.children.forEach(function (checkBox) {
checkBox.refresh();
});
};
// BlockExportDialogMorph ops
BlockExportDialogMorph.prototype.exportBlocks = function () {
var str = this.serializer.serialize(this.blocks);
if (this.blocks.length > 0) {
window.open(encodeURI('data:text/xml,<blocks app="'
+ this.serializer.app
+ '" version="'
+ this.serializer.version
+ '">'
+ str
+ '</blocks>'));
} else {
new DialogBoxMorph().inform(
'Export blocks',
'no blocks were selected',
this.world()
);
}
};
// BlockExportDialogMorph layout
BlockExportDialogMorph.prototype.fixLayout
= BlockEditorMorph.prototype.fixLayout;
// BlockImportDialogMorph ////////////////////////////////////////////////////
// BlockImportDialogMorph inherits from DialogBoxMorph
// and pseudo-inherits from BlockExportDialogMorph:
BlockImportDialogMorph.prototype = new DialogBoxMorph();
BlockImportDialogMorph.prototype.constructor = BlockImportDialogMorph;
BlockImportDialogMorph.uber = DialogBoxMorph.prototype;
// BlockImportDialogMorph constants:
BlockImportDialogMorph.prototype.key = 'blockImport';
// BlockImportDialogMorph instance creation:
function BlockImportDialogMorph(blocks, target, name) {
this.init(blocks, target, name);
}
BlockImportDialogMorph.prototype.init = function (blocks, target, name) {
var myself = this;
// additional properties:
this.blocks = blocks.slice(0);
this.handle = null;
// initialize inherited properties:
BlockExportDialogMorph.uber.init.call(
this,
target,
function () {myself.importBlocks(name); },
null // environment
);
// override inherited properites:
this.labelString = localize('Import blocks')
+ (name ? ': ' : '')
+ name || '';
this.createLabel();
// build contents
this.buildContents();
};
BlockImportDialogMorph.prototype.buildContents
= BlockExportDialogMorph.prototype.buildContents;
BlockImportDialogMorph.prototype.popUp
= BlockExportDialogMorph.prototype.popUp;
// BlockImportDialogMorph menu
BlockImportDialogMorph.prototype.userMenu
= BlockExportDialogMorph.prototype.userMenu;
BlockImportDialogMorph.prototype.selectAll
= BlockExportDialogMorph.prototype.selectAll;
BlockImportDialogMorph.prototype.selectNone
= BlockExportDialogMorph.prototype.selectNone;
// BlockImportDialogMorph ops
BlockImportDialogMorph.prototype.importBlocks = function (name) {
var ide = this.target.parentThatIsA(IDE_Morph);
if (!ide) {return; }
if (this.blocks.length > 0) {
this.blocks.forEach(function (def) {
def.receiver = ide.stage;
ide.stage.globalBlocks.push(def);
ide.stage.replaceDoubleDefinitionsFor(def);
});
ide.flushPaletteCache();
ide.refreshPalette();
ide.showMessage(
'Imported Blocks Module' + (name ? ': ' + name : '') + '.',
2
);
} else {
new DialogBoxMorph().inform(
'Import blocks',
'no blocks were selected',
this.world()
);
}
};
// BlockImportDialogMorph layout
BlockImportDialogMorph.prototype.fixLayout
= BlockEditorMorph.prototype.fixLayout;
| agpl-3.0 |
harish-patel/ecrm | include/Expressions/Expression/Boolean/IsAlphaExpression.php | 3161 | <?php
/* * *******************************************************************************
* The contents of this file are subject to the SugarCRM Master Subscription
* Agreement ("License") which can be viewed at
* http://www.sugarcrm.com/crm/en/msa/master_subscription_agreement_11_April_2011.pdf
* By installing or using this file, You have unconditionally agreed to the
* terms and conditions of the License, and You may not use this file except in
* compliance with the License. Under the terms of the license, You shall not,
* among other things: 1) sublicense, resell, rent, lease, redistribute, assign
* or otherwise transfer Your rights to the Software, and 2) use the Software
* for timesharing or service bureau purposes such as hosting the Software for
* commercial gain and/or for the benefit of a third party. Use of the Software
* may be subject to applicable fees and any use of the Software without first
* paying applicable fees is strictly prohibited. You do not have the right to
* remove SugarCRM copyrights from the source code or user interface.
*
* All copies of the Covered Code must include on each user interface screen:
* (i) the "Powered by SugarCRM" logo and
* (ii) the SugarCRM copyright notice
* in the same form as they appear in the distribution. See full license for
* requirements.
*
* Your Warranty, Limitations of liability and Indemnity are expressly stated
* in the License. Please refer to the License for the specific language
* governing these rights and limitations under the License. Portions created
* by SugarCRM are Copyright (C) 2004-2011 SugarCRM, Inc.; All Rights Reserved.
* ****************************************************************************** */
require_once("include/Expressions/Expression/Boolean/BooleanExpression.php");
/**
* <b>isAlpha(String string)</b><br>
* Returns true if "string" contains only letters.
*
*/
class IsAlphaExpression extends BooleanExpression
{
/**
* Returns itself when evaluating.
*/
function evaluate()
{
$params = $this->getParameters()->evaluate();
if (preg_match('/^[a-zA-Z]+$/', $params))
return AbstractExpression::$TRUE;
return AbstractExpression::$FALSE;
}
/**
* Returns the JS Equivalent of the evaluate function.
*/
static function getJSEvaluate()
{
return <<<EOQ
var params = this.getParameters().evaluate();
if ( /^[a-zA-Z]+$/.test(params) ) return SUGAR.expressions.Expression.TRUE;
return SUGAR.expressions.Expression.FALSE;
EOQ;
}
/**
* Any generic type will suffice.
*/
function getParameterTypes()
{
return array("string");
}
/**
* Returns the maximum number of parameters needed.
*/
static function getParamCount()
{
return 1;
}
/**
* Returns the opreation name that this Expression should be
* called by.
*/
static function getOperationName()
{
return "isAlpha";
}
/**
* Returns the String representation of this Expression.
*/
function toString()
{
}
}
?> | agpl-3.0 |
sysraj86/carnivalcrm | include/javascript/yui3/build/stylesheet/stylesheet-min.js | 7698 | /*
Copyright (c) 2009, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 3.0.0
build: 1549
*/
YUI.add("stylesheet", function (B) {
var J = B.config.doc, C = J.createElement("p"), F = C.style, D = B.Lang.isString, M = {}, I = {}, K = ("cssFloat"in F) ? "cssFloat" : "styleFloat", G, A, L, N = "opacity", O = "float", E = "";
A = (N in F) ? function (P) {
P.opacity = E;
} : function (P) {
P.filter = E;
};
F.border = "1px solid red";
F.border = E;
L = F.borderLeft ? function (P, R) {
var Q;
if (R !== K && R.toLowerCase().indexOf(O) != -1) {
R = K;
}
if (D(P[R])) {
switch (R) {
case N:
case"filter":
A(P);
break;
case"font":
P.font = P.fontStyle = P.fontVariant = P.fontWeight = P.fontSize = P.lineHeight = P.fontFamily = E;
break;
default:
for (Q in P) {
if (Q.indexOf(R) === 0) {
P[Q] = E;
}
}
}
}
} : function (P, Q) {
if (Q !== K && Q.toLowerCase().indexOf(O) != -1) {
Q = K;
}
if (D(P[Q])) {
if (Q === N) {
A(P);
} else {
P[Q] = E;
}
}
};
function H(W, R) {
var Z, U, Y, X = {}, Q, a, T, V, P, S;
if (!(this instanceof H)) {
return new H(W, R);
}
if (W) {
if (B.Node && W instanceof B.Node) {
U = B.Node.getDOMNode(W);
} else {
if (W.nodeName) {
U = W;
} else {
if (D(W)) {
if (W && I[W]) {
return I[W];
}
U = J.getElementById(W.replace(/^#/, E));
}
}
}
if (U && I[B.stamp(U)]) {
return I[B.stamp(U)];
}
}
if (!U || !/^(?:style|link)$/i.test(U.nodeName)) {
U = J.createElement("style");
U.type = "text/css";
}
if (D(W)) {
if (W.indexOf("{") != -1) {
if (U.styleSheet) {
U.styleSheet.cssText = W;
} else {
U.appendChild(J.createTextNode(W));
}
} else {
if (!R) {
R = W;
}
}
}
if (!U.parentNode || U.parentNode.nodeName.toLowerCase() !== "head") {
Z = (U.ownerDocument || J).getElementsByTagName("head")[0];
Z.appendChild(U);
}
Y = U.sheet || U.styleSheet;
Q = Y && ("cssRules"in Y) ? "cssRules" : "rules";
T = ("deleteRule"in Y) ? function (b) {
Y.deleteRule(b);
} : function (b) {
Y.removeRule(b);
};
a = ("insertRule"in Y) ? function (d, c, b) {
Y.insertRule(d + " {" + c + "}", b);
} : function (d, c, b) {
Y.addRule(d, c, b);
};
for (V = Y[Q].length - 1; V >= 0; --V) {
P = Y[Q][V];
S = P.selectorText;
if (X[S]) {
X[S].style.cssText += ";" + P.style.cssText;
T(V);
} else {
X[S] = P;
}
}
H.register(B.stamp(U), this);
if (R) {
H.register(R, this);
}
B.mix(this, {getId:function () {
return B.stamp(U);
}, enable:function () {
Y.disabled = false;
return this;
}, disable:function () {
Y.disabled = true;
return this;
}, isEnabled:function () {
return!Y.disabled;
}, set:function (e, d) {
var g = X[e], f = e.split(/\s*,\s*/), c, b;
if (f.length > 1) {
for (c = f.length - 1; c >= 0; --c) {
this.set(f[c], d);
}
return this;
}
if (!H.isValidSelector(e)) {
return this;
}
if (g) {
g.style.cssText = H.toCssText(d, g.style.cssText);
} else {
b = Y[Q].length;
d = H.toCssText(d);
if (d) {
a(e, d, b);
X[e] = Y[Q][b];
}
}
return this;
}, unset:function (e, d) {
var g = X[e], f = e.split(/\s*,\s*/), b = !d, h, c;
if (f.length > 1) {
for (c = f.length - 1; c >= 0; --c) {
this.unset(f[c], d);
}
return this;
}
if (g) {
if (!b) {
d = B.Array(d);
F.cssText = g.style.cssText;
for (c = d.length - 1; c >= 0; --c) {
L(F, d[c]);
}
if (F.cssText) {
g.style.cssText = F.cssText;
} else {
b = true;
}
}
if (b) {
h = Y[Q];
for (c = h.length - 1; c >= 0; --c) {
if (h[c] === g) {
delete X[e];
T(c);
break;
}
}
}
}
return this;
}, getCssText:function (c) {
var d, b;
if (D(c)) {
d = X[c.split(/\s*,\s*/)[0]];
return d ? d.style.cssText : null;
} else {
b = [];
for (c in X) {
if (X.hasOwnProperty(c)) {
d = X[c];
b.push(d.selectorText + " {" + d.style.cssText + "}");
}
}
return b.join("\n");
}
}});
}
G = function (Q, S) {
var R = Q.styleFloat || Q.cssFloat || Q[O], P = B.Lang.trim, U;
F.cssText = S || E;
if (R && !Q[K]) {
Q = B.merge(Q);
delete Q.styleFloat;
delete Q.cssFloat;
delete Q[O];
Q[K] = R;
}
for (U in Q) {
if (Q.hasOwnProperty(U)) {
try {
F[U] = P(Q[U]);
} catch (T) {
}
}
}
return F.cssText;
};
B.mix(H, {toCssText:((N in F) ? G : function (P, Q) {
if (N in P) {
P = B.merge(P, {filter:"alpha(opacity=" + (P.opacity * 100) + ")"});
delete P.opacity;
}
return G(P, Q);
}), register:function (P, Q) {
return!!(P && Q instanceof H && !I[P] && (I[P] = Q));
}, isValidSelector:function (Q) {
var P = false;
if (Q && D(Q)) {
if (!M.hasOwnProperty(Q)) {
M[Q] = !/\S/.test(Q.replace(/\s+|\s*[+~>]\s*/g, " ").replace(/([^ ])\[.*?\]/g, "$1").replace(/([^ ])::?[a-z][a-z\-]+[a-z](?:\(.*?\))?/ig, "$1").replace(/(?:^| )[a-z0-6]+/ig, " ").replace(/\\./g, E).replace(/[.#]\w[\w\-]*/g, E));
}
P = M[Q];
}
return P;
}}, true);
B.StyleSheet = H;
}, "3.0.0"); | agpl-3.0 |
opensourceBIM/BIMserver | PluginBase/generated/org/bimserver/models/store/impl/PercentageChangeImpl.java | 3076 | /**
* Copyright (C) 2009-2014 BIMserver.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.bimserver.models.store.impl;
/******************************************************************************
* Copyright (C) 2009-2019 BIMserver.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see {@literal<http://www.gnu.org/licenses/>}.
*****************************************************************************/
import org.bimserver.models.store.PercentageChange;
import org.bimserver.models.store.StorePackage;
import org.eclipse.emf.ecore.EClass;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Percentage Change</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link org.bimserver.models.store.impl.PercentageChangeImpl#getPercentage <em>Percentage</em>}</li>
* </ul>
*
* @generated
*/
public class PercentageChangeImpl extends RemoteServiceUpdateImpl implements PercentageChange {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected PercentageChangeImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return StorePackage.Literals.PERCENTAGE_CHANGE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public int getPercentage() {
return (Integer) eGet(StorePackage.Literals.PERCENTAGE_CHANGE__PERCENTAGE, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setPercentage(int newPercentage) {
eSet(StorePackage.Literals.PERCENTAGE_CHANGE__PERCENTAGE, newPercentage);
}
} //PercentageChangeImpl
| agpl-3.0 |
see-r/SeerDataCruncher | src/main/java/com/datacruncher/jpa/Update.java | 1439 | /*
* DataCruncher
* Copyright (c) Mario Altimari. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.datacruncher.jpa;
public class Update {
private Object results;
private boolean success;
private String message;
private String extraMessage;
public Object getResults() {
return results;
}
public void setResults(Object results) {
this.results = results;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public String getExtraMessage() {
return extraMessage;
}
public void setMessage(String message) {
this.message = message;
}
public void setExtraMessage(String message) {
this.extraMessage = message;
}
} | agpl-3.0 |
dhongu/l10n-romania | l10n_ro_dvi/tests/test_dvi.py | 7749 | # Copyright (C) 2020 Terrabit
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.tests import Form
from odoo.tests.common import SavepointCase
class TestDVI(SavepointCase):
@classmethod
def setUpClass(cls):
super(TestDVI, cls).setUpClass()
account_type_inc = cls.env.ref("account.data_account_type_revenue")
account_type_exp = cls.env.ref("account.data_account_type_expenses")
account_type_cur = cls.env.ref("account.data_account_type_current_assets")
account_expense = cls.env["account.account"].search([("code", "=", "607000")], limit=1)
if not account_expense:
account_expense = cls.env["account.account"].create(
{
"name": "Expense",
"code": "607000",
"user_type_id": account_type_exp.id,
"reconcile": False,
}
)
account_income = cls.env["account.account"].search([("code", "=", "707000")])
if not account_income:
account_income = cls.env["account.account"].create(
{
"name": "Income",
"code": "707000",
"user_type_id": account_type_inc.id,
"reconcile": False,
}
)
# se poate utiliza foarte bine si 408
account_input = cls.env["account.account"].search([("code", "=", "371000.i")])
if not account_input:
account_input = cls.env["account.account"].create(
{
"name": "Income",
"code": "371000.i",
"user_type_id": account_type_cur.id,
"reconcile": False,
}
)
# se poate utiliza foarte bine si 418
account_output = cls.env["account.account"].search([("code", "=", "371000.o")])
if not account_output:
account_output = cls.env["account.account"].create(
{
"name": "Output",
"code": "371000.o",
"user_type_id": account_type_cur.id,
"reconcile": False,
}
)
account_valuation = cls.env["account.account"].search([("code", "=", "371000")])
if not account_valuation:
account_valuation = cls.env["account.account"].create(
{
"name": "Valuation",
"code": "371000",
"user_type_id": account_type_cur.id,
"reconcile": False,
}
)
account_other_tax = cls.env["account.account"].search([("code", "=", "446000")])
if not account_other_tax:
account_other_tax = cls.env["account.account"].create(
{
"name": "Valuation",
"code": "446000",
"user_type_id": account_type_cur.id,
"reconcile": True,
}
)
account_special_funds = cls.env["account.account"].search([("code", "=", "447000")])
if not account_special_funds:
account_special_funds = cls.env["account.account"].create(
{
"name": "Valuation",
"code": "447000",
"user_type_id": account_type_cur.id,
"reconcile": False,
}
)
stock_journal = cls.env["account.journal"].search([("code", "=", "STJ")])
if not stock_journal:
stock_journal = cls.env["account.journal"].create(
{"name": "Stock Journal", "code": "STJ", "type": "general"}
)
cls.category = cls.env["product.category"].create(
{
"name": "Marfa",
"property_cost_method": "fifo",
"property_valuation": "real_time",
"property_account_income_categ_id": account_income.id,
"property_account_expense_categ_id": account_expense.id,
"property_stock_account_input_categ_id": account_input.id,
"property_stock_account_output_categ_id": account_output.id,
"property_stock_valuation_account_id": account_valuation.id,
"property_stock_journal": stock_journal.id,
}
)
cls.product_1 = cls.env["product.product"].create(
{
"name": "Product A",
"type": "product",
"categ_id": cls.category.id,
"invoice_policy": "delivery",
}
)
cls.product_2 = cls.env["product.product"].create(
{
"name": "Product B",
"type": "product",
"categ_id": cls.category.id,
"invoice_policy": "delivery",
}
)
cls.vendor = cls.env["res.partner"].search([("name", "=", "vendor1")], limit=1)
if not cls.vendor:
cls.vendor = cls.env["res.partner"].create({"name": "vendor1"})
def test_call_wizard(self):
po = Form(self.env["purchase.order"])
po.partner_id = self.vendor
with po.order_line.new() as po_line:
po_line.product_id = self.product_1
po_line.product_qty = 10
po_line.price_unit = 100
with po.order_line.new() as po_line:
po_line.product_id = self.product_2
po_line.product_qty = 10
po_line.price_unit = 200
po = po.save()
po.button_confirm()
self.picking = po.picking_ids[0]
self.picking.move_line_ids.write({"qty_done": 10.0})
self.picking.button_validate()
domain = [("product_id", "in", [self.product_1.id, self.product_2.id])]
valuations = self.env["stock.valuation.layer"].read_group(domain, ["value:sum", "quantity:sum"], ["product_id"])
for valuation in valuations:
if valuation["product_id"][0] == self.product_1.id:
self.assertEqual(valuation["value"], 10 * 100)
if valuation["product_id"][0] == self.product_2.id:
self.assertEqual(valuation["value"], 10 * 200)
invoice = Form(self.env["account.move"].with_context(default_type="in_invoice"))
invoice.partner_id = self.vendor
invoice.purchase_id = po
invoice = invoice.save()
invoice.post()
# se deschide wizardul pt generare DVI
action = invoice.button_dvi()
wizard = self.env[(action.get("res_model"))].browse(action.get("res_id"))
wizard = Form(wizard.with_context({"active_id": invoice.id}))
wizard.custom_duty = 5.0
wizard.customs_commission = 6.0
wizard.tax_value = wizard.tax_value + 1
wizard = wizard.save()
action = wizard.do_create_dvi()
dvi = self.env[(action.get("res_model"))].browse(action.get("res_id"))
dvi = Form(dvi)
dvi = dvi.save()
dvi.compute_landed_cost()
dvi.button_validate()
domain = [("product_id", "in", [self.product_1.id, self.product_2.id])]
valuations = self.env["stock.valuation.layer"].read_group(domain, ["value:sum", "quantity:sum"], ["product_id"])
for valuation in valuations:
if valuation["product_id"][0] == self.product_1.id:
self.assertEqual(valuation["value"], 10 * 100 + 1.67 + 2)
if valuation["product_id"][0] == self.product_2.id:
self.assertEqual(valuation["value"], 10 * 200 + 3.33 + 4)
action = invoice.button_dvi()
self.assertEqual(action.get("res_id"), dvi.id)
| agpl-3.0 |
DBezemer/server | alpha/apps/kaltura/lib/batch2/kFlowManager.php | 23756 | <?php
/**
*
* Manages the batch flow
*
* @package Core
* @subpackage Batch
*
*/
class kFlowManager implements kBatchJobStatusEventConsumer, kObjectAddedEventConsumer, kObjectChangedEventConsumer, kObjectDeletedEventConsumer, kObjectReadyForReplacmentEventConsumer,kObjectDataChangedEventConsumer
{
public final function __construct()
{
}
protected function updatedImport(BatchJob $dbBatchJob, kImportJobData $data)
{
switch($dbBatchJob->getStatus())
{
case BatchJob::BATCHJOB_STATUS_FINISHED:
return kFlowHelper::handleImportFinished($dbBatchJob, $data);
case BatchJob::BATCHJOB_STATUS_RETRY:
return kFlowHelper::handleImportRetried($dbBatchJob, $data);
case BatchJob::BATCHJOB_STATUS_FAILED:
case BatchJob::BATCHJOB_STATUS_FATAL:
return kFlowHelper::handleImportFailed($dbBatchJob, $data);
default:
return $dbBatchJob;
}
}
protected function updatedConcat(BatchJob $dbBatchJob, kConcatJobData $data)
{
switch($dbBatchJob->getStatus())
{
case BatchJob::BATCHJOB_STATUS_FINISHED:
return kFlowHelper::handleConcatFinished($dbBatchJob, $data);
case BatchJob::BATCHJOB_STATUS_FAILED:
case BatchJob::BATCHJOB_STATUS_FATAL:
return kFlowHelper::handleConcatFailed($dbBatchJob, $data);
default:
return $dbBatchJob;
}
}
protected function updatedConvertLiveSegment(BatchJob $dbBatchJob, kConvertLiveSegmentJobData $data)
{
switch($dbBatchJob->getStatus())
{
case BatchJob::BATCHJOB_STATUS_FINISHED:
return kFlowHelper::handleConvertLiveSegmentFinished($dbBatchJob, $data);
case BatchJob::BATCHJOB_STATUS_FAILED:
case BatchJob::BATCHJOB_STATUS_FATAL:
return kFlowHelper::handleConvertLiveSegmentFailed($dbBatchJob, $data);
default:
return $dbBatchJob;
}
}
protected function updatedIndex(BatchJob $dbBatchJob, kIndexJobData $data)
{
switch($dbBatchJob->getStatus())
{
case BatchJob::BATCHJOB_STATUS_PENDING:
return kFlowHelper::handleIndexPending($dbBatchJob, $data);
case BatchJob::BATCHJOB_STATUS_FINISHED:
return kFlowHelper::handleIndexFinished($dbBatchJob, $data);
case BatchJob::BATCHJOB_STATUS_FAILED:
case BatchJob::BATCHJOB_STATUS_FATAL:
return kFlowHelper::handleIndexFailed($dbBatchJob, $data);
return $dbBatchJob;
default:
return $dbBatchJob;
}
}
protected function updatedCopy(BatchJob $dbBatchJob, kCopyJobData $data)
{
switch($dbBatchJob->getStatus())
{
case BatchJob::BATCHJOB_STATUS_FINISHED:
// return kFlowHelper::handleCopyFinished($dbBatchJob, $data);
case BatchJob::BATCHJOB_STATUS_FAILED:
case BatchJob::BATCHJOB_STATUS_FATAL:
// return kFlowHelper::handleCopyFailed($dbBatchJob, $data);
return $dbBatchJob;
default:
return $dbBatchJob;
}
}
protected function updatedDelete(BatchJob $dbBatchJob, kDeleteJobData $data)
{
switch($dbBatchJob->getStatus())
{
case BatchJob::BATCHJOB_STATUS_FINISHED:
// return kFlowHelper::handleDeleteFinished($dbBatchJob, $data);
case BatchJob::BATCHJOB_STATUS_FAILED:
case BatchJob::BATCHJOB_STATUS_FATAL:
// return kFlowHelper::handleDeleteFailed($dbBatchJob, $data);
return $dbBatchJob;
default:
return $dbBatchJob;
}
}
protected function updatedExtractMedia(BatchJob $dbBatchJob, kExtractMediaJobData $data)
{
switch($dbBatchJob->getStatus())
{
case BatchJob::BATCHJOB_STATUS_FINISHED:
case BatchJob::BATCHJOB_STATUS_FAILED:
case BatchJob::BATCHJOB_STATUS_FATAL:
return kFlowHelper::handleExtractMediaClosed($dbBatchJob, $data);
default:
return $dbBatchJob;
}
}
protected function updatedMoveCategoryEntries(BatchJob $dbBatchJob, kMoveCategoryEntriesJobData $data)
{
switch($dbBatchJob->getStatus())
{
case BatchJob::BATCHJOB_STATUS_FINISHED:
// return kFlowHelper::handleMoveCategoryEntriesFinished($dbBatchJob, $data);
case BatchJob::BATCHJOB_STATUS_FAILED:
case BatchJob::BATCHJOB_STATUS_FATAL:
// return kFlowHelper::handleMoveCategoryEntriesFailed($dbBatchJob, $data);
default:
return $dbBatchJob;
}
}
protected function updatedStorageExport(BatchJob $dbBatchJob, kStorageExportJobData $data)
{
switch($dbBatchJob->getStatus())
{
case BatchJob::BATCHJOB_STATUS_FINISHED:
return kFlowHelper::handleStorageExportFinished($dbBatchJob, $data);
case BatchJob::BATCHJOB_STATUS_FAILED:
case BatchJob::BATCHJOB_STATUS_FATAL:
return kFlowHelper::handleStorageExportFailed($dbBatchJob, $data);
default:
return $dbBatchJob;
}
}
protected function updatedStorageDelete(BatchJob $dbBatchJob, kStorageDeleteJobData $data)
{
switch($dbBatchJob->getStatus())
{
case BatchJob::BATCHJOB_STATUS_FINISHED:
return kFlowHelper::handleStorageDeleteFinished($dbBatchJob, $data);
default:
return $dbBatchJob;
}
}
protected function updatedCaptureThumb(BatchJob $dbBatchJob, kCaptureThumbJobData $data)
{
switch($dbBatchJob->getStatus())
{
case BatchJob::BATCHJOB_STATUS_FINISHED:
return kFlowHelper::handleCaptureThumbFinished($dbBatchJob, $data);
case BatchJob::BATCHJOB_STATUS_FAILED:
case BatchJob::BATCHJOB_STATUS_FATAL:
return kFlowHelper::handleCaptureThumbFailed($dbBatchJob, $data);
default:
return $dbBatchJob;
}
}
protected function updatedDeleteFile (BatchJob $dbBatchJob, kDeleteFileJobData $data)
{
switch ($dbBatchJob->getStatus())
{
case BatchJob::BATCHJOB_STATUS_PROCESSING:
kFlowHelper::handleDeleteFileProcessing($data);
case BatchJob::BATCHJOB_STATUS_FINISHED:
return kFlowHelper::handleDeleteFileFinished($dbBatchJob, $data);
case BatchJob::BATCHJOB_STATUS_FAILED:
case BatchJob::BATCHJOB_STATUS_FATAL:
default:
return $dbBatchJob;
}
}
protected function updatedConvert(BatchJob $dbBatchJob, kConvertJobData $data)
{
switch($dbBatchJob->getStatus())
{
case BatchJob::BATCHJOB_STATUS_PENDING:
return kFlowHelper::handleConvertPending($dbBatchJob, $data);
case BatchJob::BATCHJOB_STATUS_QUEUED:
return kFlowHelper::handleConvertQueued($dbBatchJob, $data);
case BatchJob::BATCHJOB_STATUS_FINISHED:
return kFlowHelper::handleConvertFinished($dbBatchJob, $data);
case BatchJob::BATCHJOB_STATUS_FAILED:
case BatchJob::BATCHJOB_STATUS_FATAL:
return kFlowHelper::handleConvertFailed($dbBatchJob, $data);
default:
return $dbBatchJob;
}
}
protected function updatedPostConvert(BatchJob $dbBatchJob, kPostConvertJobData $data)
{
switch($dbBatchJob->getStatus())
{
case BatchJob::BATCHJOB_STATUS_FINISHED:
return kFlowHelper::handlePostConvertFinished($dbBatchJob, $data);
case BatchJob::BATCHJOB_STATUS_FAILED:
case BatchJob::BATCHJOB_STATUS_FATAL:
return kFlowHelper::handlePostConvertFailed($dbBatchJob, $data);
default:
return $dbBatchJob;
}
}
protected function updatedBulkUpload(BatchJob $dbBatchJob, kBulkUploadJobData $data)
{
switch($dbBatchJob->getStatus())
{
case BatchJob::BATCHJOB_STATUS_FAILED:
case BatchJob::BATCHJOB_STATUS_FATAL:
return kFlowHelper::handleBulkUploadFailed($dbBatchJob, $data);
case BatchJob::BATCHJOB_STATUS_FINISHED:
return kFlowHelper::handleBulkUploadFinished($dbBatchJob, $data);
default: return $dbBatchJob;
}
}
protected function updatedConvertCollection(BatchJob $dbBatchJob, kConvertCollectionJobData $data)
{
switch($dbBatchJob->getStatus())
{
case BatchJob::BATCHJOB_STATUS_PENDING:
return kFlowHelper::handleConvertCollectionPending($dbBatchJob, $data);
case BatchJob::BATCHJOB_STATUS_FINISHED:
return kFlowHelper::handleConvertCollectionFinished($dbBatchJob, $data);
case BatchJob::BATCHJOB_STATUS_FAILED:
case BatchJob::BATCHJOB_STATUS_FATAL:
return kFlowHelper::handleConvertCollectionFailed($dbBatchJob, $data);
default:
return $dbBatchJob;
}
}
protected function updatedConvertProfile(BatchJob $dbBatchJob, kConvertProfileJobData $data)
{
switch($dbBatchJob->getStatus())
{
case BatchJob::BATCHJOB_STATUS_PENDING:
return kFlowHelper::handleConvertProfilePending($dbBatchJob, $data);
case BatchJob::BATCHJOB_STATUS_FINISHED:
return kFlowHelper::handleConvertProfileFinished($dbBatchJob, $data);
case BatchJob::BATCHJOB_STATUS_FAILED:
case BatchJob::BATCHJOB_STATUS_FATAL:
return kFlowHelper::handleConvertProfileFailed($dbBatchJob, $data);
default:
return $dbBatchJob;
}
}
protected function updatedBulkDownload(BatchJob $dbBatchJob, kBulkDownloadJobData $data)
{
switch($dbBatchJob->getStatus())
{
case BatchJob::BATCHJOB_STATUS_PENDING:
return kFlowHelper::handleBulkDownloadPending($dbBatchJob, $data);
case BatchJob::BATCHJOB_STATUS_FINISHED:
return kFlowHelper::handleBulkDownloadFinished($dbBatchJob, $data);
default:
return $dbBatchJob;
}
}
protected function updatedProvisionDelete(BatchJob $dbBatchJob, kProvisionJobData $data)
{
return $dbBatchJob;
}
protected function updatedProvisionProvide(BatchJob $dbBatchJob, kProvisionJobData $data)
{
switch($dbBatchJob->getStatus())
{
case BatchJob::BATCHJOB_STATUS_FINISHED:
return kFlowHelper::handleProvisionProvideFinished($dbBatchJob, $data);
case BatchJob::BATCHJOB_STATUS_FAILED:
case BatchJob::BATCHJOB_STATUS_FATAL:
return kFlowHelper::handleProvisionProvideFailed($dbBatchJob, $data);
default:
return $dbBatchJob;
}
}
protected function updatedLiveReportExport(BatchJob $dbBatchJob, kLiveReportExportJobData $data)
{
switch($dbBatchJob->getStatus())
{
case BatchJob::BATCHJOB_STATUS_FINISHED:
return kFlowHelper::handleLiveReportExportFinished($dbBatchJob, $data);
case BatchJob::BATCHJOB_STATUS_FAILED:
case BatchJob::BATCHJOB_STATUS_FATAL:
return kFlowHelper::handleLiveReportExportFailed($dbBatchJob, $data);
case BatchJob::BATCHJOB_STATUS_ABORTED:
return kFlowHelper::handleLiveReportExportAborted($dbBatchJob, $data);
default:
return $dbBatchJob;
}
}
/* (non-PHPdoc)
* @see kBatchJobStatusEventConsumer::shouldConsumeJobStatusEvent()
*/
public function shouldConsumeJobStatusEvent(BatchJob $dbBatchJob)
{
return true;
}
/* (non-PHPdoc)
* @see kBatchJobStatusEventConsumer::updatedJob()
*/
public function updatedJob(BatchJob $dbBatchJob)
{
$dbBatchJobLock = $dbBatchJob->getBatchJobLock();
try
{
if($dbBatchJob->getStatus() == BatchJob::BATCHJOB_STATUS_FAILED || $dbBatchJob->getStatus() == BatchJob::BATCHJOB_STATUS_FATAL) {
kJobsManager::abortChildJobs($dbBatchJob);
}
$jobType = $dbBatchJob->getJobType();
switch($jobType)
{
case BatchJobType::IMPORT:
$dbBatchJob = $this->updatedImport($dbBatchJob, $dbBatchJob->getData());
break;
case BatchJobType::EXTRACT_MEDIA:
$dbBatchJob = $this->updatedExtractMedia($dbBatchJob, $dbBatchJob->getData());
break;
case BatchJobType::CONVERT:
$dbBatchJob = $this->updatedConvert($dbBatchJob, $dbBatchJob->getData());
break;
case BatchJobType::POSTCONVERT:
$dbBatchJob = $this->updatedPostConvert($dbBatchJob, $dbBatchJob->getData());
break;
case BatchJobType::BULKUPLOAD:
$dbBatchJob = $this->updatedBulkUpload($dbBatchJob, $dbBatchJob->getData());
break;
case BatchJobType::CONVERT_PROFILE:
$dbBatchJob = $this->updatedConvertProfile($dbBatchJob, $dbBatchJob->getData());
break;
case BatchJobType::BULKDOWNLOAD:
$dbBatchJob = $this->updatedBulkDownload($dbBatchJob, $dbBatchJob->getData());
break;
case BatchJobType::PROVISION_PROVIDE:
$dbBatchJob = $this->updatedProvisionProvide($dbBatchJob, $dbBatchJob->getData());
break;
case BatchJobType::PROVISION_DELETE:
$dbBatchJob = $this->updatedProvisionDelete($dbBatchJob, $dbBatchJob->getData());
break;
case BatchJobType::CONVERT_COLLECTION:
$dbBatchJob = $this->updatedConvertCollection($dbBatchJob, $dbBatchJob->getData());
break;
case BatchJobType::STORAGE_EXPORT:
$dbBatchJob = $this->updatedStorageExport($dbBatchJob, $dbBatchJob->getData());
break;
case BatchJobType::MOVE_CATEGORY_ENTRIES:
$dbBatchJob = $this->updatedMoveCategoryEntries($dbBatchJob, $dbBatchJob->getData());
break;
case BatchJobType::STORAGE_DELETE:
$dbBatchJob = $this->updatedStorageDelete($dbBatchJob, $dbBatchJob->getData());
break;
case BatchJobType::CAPTURE_THUMB:
$dbBatchJob = $this->updatedCaptureThumb($dbBatchJob, $dbBatchJob->getData());
break;
case BatchJobType::DELETE_FILE:
$dbBatchJob=$this->updatedDeleteFile($dbBatchJob, $dbBatchJob->getData());
break;
case BatchJobType::INDEX:
$dbBatchJob=$this->updatedIndex($dbBatchJob, $dbBatchJob->getData());
break;
case BatchJobType::COPY:
$dbBatchJob=$this->updatedCopy($dbBatchJob, $dbBatchJob->getData());
break;
case BatchJobType::DELETE:
$dbBatchJob=$this->updatedDelete($dbBatchJob, $dbBatchJob->getData());
break;
case BatchJobType::CONCAT:
$dbBatchJob=$this->updatedConcat($dbBatchJob, $dbBatchJob->getData());
break;
case BatchJobType::CONVERT_LIVE_SEGMENT:
$dbBatchJob=$this->updatedConvertLiveSegment($dbBatchJob, $dbBatchJob->getData());
break;
case BatchJobType::LIVE_REPORT_EXPORT:
$dbBatchJob=$this->updatedLiveReportExport($dbBatchJob, $dbBatchJob->getData());
break;
case BatchJobType::USERS_CSV:
$dbBatchJob=$this->updatedUsersCsv($dbBatchJob, $dbBatchJob->getData());
break;
default:
break;
}
if($dbBatchJob->getStatus() == BatchJob::BATCHJOB_STATUS_RETRY) {
if($dbBatchJobLock && $dbBatchJobLock->getExecutionAttempts() >= BatchJobLockPeer::getMaxExecutionAttempts($jobType))
$dbBatchJob = kJobsManager::updateBatchJob($dbBatchJob, BatchJob::BATCHJOB_STATUS_FAILED);
}
if(in_array($dbBatchJob->getStatus(), BatchJobPeer::getClosedStatusList()))
{
$jobEntry = $dbBatchJob->getEntry();
if($jobEntry && $jobEntry->getMarkedForDeletion())
myEntryUtils::deleteEntry($jobEntry,null,true);
}
}
catch ( Exception $ex )
{
self::alert($dbBatchJob, $ex);
KalturaLog::err( "Error:" . $ex->getMessage() );
}
return true;
}
// creates a mail job with the exception data
protected static function alert(BatchJob $dbBatchJob, Exception $exception)
{
$jobData = new kMailJobData();
$jobData->setMailPriority( kMailJobData::MAIL_PRIORITY_HIGH);
$jobData->setStatus(kMailJobData::MAIL_STATUS_PENDING);
KalturaLog::alert("Error in job [{$dbBatchJob->getId()}]\n".$exception);
$jobData->setMailType(90); // is the email template
$jobData->setBodyParamsArray(array($dbBatchJob->getId(), $exception->getFile(), $exception->getLine(), $exception->getMessage(), $exception->getTraceAsString()));
$jobData->setFromEmail(kConf::get("batch_alert_email"));
$jobData->setFromName(kConf::get("batch_alert_name"));
$jobData->setRecipientEmail(kConf::get("batch_alert_email"));
$jobData->setSubjectParamsArray( array() );
kJobsManager::addJob($dbBatchJob->createChild(BatchJobType::MAIL, $jobData->getMailType()), $jobData, BatchJobType::MAIL, $jobData->getMailType());
}
/* (non-PHPdoc)
* @see kObjectAddedEventConsumer::shouldConsumeAddedEvent()
*/
public function shouldConsumeAddedEvent(BaseObject $object)
{
if($object instanceof asset)
return true;
return false;
}
/* (non-PHPdoc)
* @see kObjectAddedEventConsumer::objectAdded()
*/
public function objectAdded(BaseObject $object, BatchJob $raisedJob = null)
{
$entry = $object->getentry();
if ($object->getStatus() == asset::FLAVOR_ASSET_STATUS_QUEUED || $object->getStatus() == asset::FLAVOR_ASSET_STATUS_IMPORTING)
{
if (!($object instanceof flavorAsset))
{
$object->setStatus(asset::FLAVOR_ASSET_STATUS_READY);
$object->save();
} elseif ($object->getIsOriginal())
{
if ($entry->getType() == entryType::MEDIA_CLIP)
{
if ($entry->getOperationAttributes() && $object->getIsOriginal() && is_null($entry->getClipConcatTrimFlow()))
kBusinessPreConvertDL::convertSource($object, null, null, $raisedJob);
else
{
$syncKey = $object->getSyncKey(flavorAsset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
if (kFileSyncUtils::fileSync_exists($syncKey))
{
list($fileSync, $local) = kFileSyncUtils::getReadyFileSyncForKey($syncKey, true, false);
kJobsManager::addConvertProfileJob($raisedJob, $entry, $object->getId(), $fileSync);
}
}
}
} else
{
$object->setStatus(asset::FLAVOR_ASSET_STATUS_VALIDATING);
$object->save();
}
}
if ($object->getStatus() == asset::FLAVOR_ASSET_STATUS_READY && $object instanceof thumbAsset)
{
if ($object->getFlavorParamsId())
kFlowHelper::generateThumbnailsFromFlavor($object->getEntryId(), $raisedJob, $object->getFlavorParamsId());
else
if ($object->hasTag(thumbParams::TAG_DEFAULT_THUMB))
kBusinessConvertDL::setAsDefaultThumbAsset($object);
return true;
}
if ($object->getIsOriginal() && $entry->getStatus() == entryStatus::NO_CONTENT)
{
$entry->setStatus(entryStatus::PENDING);
$entry->save();
}
return true;
}
/* (non-PHPdoc)
* @see kObjectChangedEventConsumer::shouldConsumeChangedEvent()
*/
public function shouldConsumeChangedEvent(BaseObject $object, array $modifiedColumns)
{
if(
$object instanceof entry
&& in_array(entryPeer::STATUS, $modifiedColumns)
&& ($object->getStatus() == entryStatus::READY || $object->getStatus() == entryStatus::ERROR_CONVERTING)
&& $object->getReplacedEntryId()
)
return true;
if(
$object instanceof UploadToken
&& in_array(UploadTokenPeer::STATUS, $modifiedColumns)
&& $object->getStatus() == UploadToken::UPLOAD_TOKEN_FULL_UPLOAD
)
return true;
if(
$object instanceof flavorAsset
&& in_array(assetPeer::STATUS, $modifiedColumns)
)
return true;
if(
$object instanceof BatchJob
&& $object->getJobType() == BatchJobType::BULKUPLOAD
&& $object->getStatus() == BatchJob::BATCHJOB_STATUS_ABORTED
&& in_array(BatchJobPeer::STATUS, $modifiedColumns)
&& in_array($object->getColumnsOldValue(BatchJobPeer::STATUS), BatchJobPeer::getClosedStatusList())
)
return true;
if ($object instanceof UserRole
&& in_array(UserRolePeer::PERMISSION_NAMES, $modifiedColumns))
{
return true;
}
return false;
}
/* (non-PHPdoc)
* @see kObjectChangedEventConsumer::objectChanged()
*/
public function objectChanged(BaseObject $object, array $modifiedColumns)
{
if(
$object instanceof entry
&& in_array(entryPeer::STATUS, $modifiedColumns)
&& ($object->getStatus() == entryStatus::READY || $object->getStatus() == entryStatus::ERROR_CONVERTING)
&& $object->getReplacedEntryId()
)
{
kFlowHelper::handleEntryReplacement($object);
return true;
}
if(
$object instanceof UploadToken
&& in_array(UploadTokenPeer::STATUS, $modifiedColumns)
&& $object->getStatus() == UploadToken::UPLOAD_TOKEN_FULL_UPLOAD
)
{
kFlowHelper::handleUploadFinished($object);
return true;
}
if(
$object instanceof BatchJob
&& $object->getJobType() == BatchJobType::BULKUPLOAD
&& $object->getStatus() == BatchJob::BATCHJOB_STATUS_ABORTED
&& in_array(BatchJobPeer::STATUS, $modifiedColumns)
&& in_array($object->getColumnsOldValue(BatchJobPeer::STATUS), BatchJobPeer::getClosedStatusList())
)
{
$partner = $object->getPartner();
if($partner->getEnableBulkUploadNotificationsEmails())
kFlowHelper::sendBulkUploadNotificationEmail($object, MailType::MAIL_TYPE_BULKUPLOAD_ABORTED, array($partner->getAdminName(), $object->getId(), kFlowHelper::createBulkUploadLogUrl($object)));
return true;
}
if ($object instanceof UserRole
&& in_array(UserRolePeer::PERMISSION_NAMES, $modifiedColumns))
{
$filter = new kuserFilter();
$filter->set('_eq_role_ids', $object->getId());
kJobsManager::addIndexJob($object->getPartnerId(), IndexObjectType::USER, $filter, false);
return true;
}
if(
!($object instanceof flavorAsset)
|| !in_array(assetPeer::STATUS, $modifiedColumns)
)
return true;
$entry = entryPeer::retrieveByPKNoFilter($object->getEntryId());
KalturaLog::info("Asset id [" . $object->getId() . "] isOriginal [" . $object->getIsOriginal() . "] status [" . $object->getStatus() . "]");
if($object->getIsOriginal())
return true;
if($object->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_VALIDATING)
{
$postConvertAssetType = BatchJob::POSTCONVERT_ASSET_TYPE_FLAVOR;
$offset = $entry->getThumbOffset(); // entry getThumbOffset now takes the partner DefThumbOffset into consideration
$syncKey = $object->getSyncKey(asset::FILE_SYNC_FLAVOR_ASSET_SUB_TYPE_ASSET);
$fileSync = kFileSyncUtils::getLocalFileSyncForKey($syncKey, false);
if(!$fileSync)
return true;
if(kFileSyncUtils::getLocalFilePathForKey($syncKey))
kJobsManager::addPostConvertJob(null, $postConvertAssetType, $syncKey, $object->getId(), null, $entry->getCreateThumb(), $offset);
}
elseif ($object->getStatus() == flavorAsset::FLAVOR_ASSET_STATUS_READY)
{
// If we get a ready flavor and the entry is in no content
if($entry->getStatus() == entryStatus::NO_CONTENT)
{
$entry->setStatus(entryStatus::PENDING); // we change the entry to pending
$entry->save();
}
}
return true;
}
/* (non-PHPdoc)
* @see kObjectDeletedEventConsumer::shouldConsumeDeletedEvent()
*/
public function shouldConsumeDeletedEvent(BaseObject $object)
{
if($object instanceof UploadToken)
return true;
return false;
}
/* (non-PHPdoc)
* @see kObjectAddedEventConsumer::shouldConsumeReadyForReplacmentEvent()
*/
public function shouldConsumeReadyForReplacmentEvent(BaseObject $object)
{
if($object instanceof entry)
return true;
return false;
}
/* (non-PHPdoc)
* @see kObjectAddedEventConsumer::objectReadyForReplacment()
*/
public function objectReadyForReplacment(BaseObject $object, BatchJob $raisedJob = null)
{
$entry = entryPeer::retrieveByPK($object->getReplacedEntryId());
if(!$entry)
{
KalturaLog::err("Real entry id [" . $object->getReplacedEntryId() . "] not found");
return true;
}
kBusinessConvertDL::replaceEntry($entry, $object);
return true;
}
/* (non-PHPdoc)
* @see kObjectDeletedEventConsumer::objectDeleted()
*/
public function objectDeleted(BaseObject $object, BatchJob $raisedJob = null)
{
kFlowHelper::handleUploadCanceled($object);
return true;
}
/**
* @param BaseObject $object
* @param string $previousVersion
* @return bool true if the consumer should handle the event
*/
public function shouldConsumeDataChangedEvent(BaseObject $object, $previousVersion = null)
{
if($object instanceof asset)
return true;
return false;
}
/**
* @param BaseObject $object
* @param string $previousVersion
* @param BatchJob $raisedJob
* @return bool true if should continue to the next consumer
*/
public function objectDataChanged(BaseObject $object, $previousVersion = null, BatchJob $raisedJob = null)
{
if ($object instanceof flavorAsset)
{
if ($object->getStatus() == asset::FLAVOR_ASSET_STATUS_QUEUED)
{
if (!$object->getIsOriginal())
{
$object->setStatus(asset::FLAVOR_ASSET_STATUS_VALIDATING);
$object->save();
}
}
}
return true;
}
protected function updatedUsersCsv(BatchJob $dbBatchJob, kUsersCsvJobData $data)
{
switch($dbBatchJob->getStatus())
{
case BatchJob::BATCHJOB_STATUS_FINISHED:
return kFlowHelper::handleUsersCsvFinished($dbBatchJob, $data);
default:
return $dbBatchJob;
}
}
}
| agpl-3.0 |
battlecode/battlecode-server | src/main/battlecode/server/GameState.java | 82 | package battlecode.server;
public enum GameState {
RUNNING,
DONE
}
| agpl-3.0 |
brewingagile/backoffice.brewingagile.org | application/src/main/java/org/brewingagile/backoffice/db/operations/StripeChargeSql.java | 1777 | package org.brewingagile.backoffice.db.operations;
import fj.data.List;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.brewingagile.backoffice.instances.PreparedStatements;
import org.brewingagile.backoffice.instances.ResultSets;
import org.brewingagile.backoffice.types.Account;
import org.brewingagile.backoffice.types.ChargeId;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.Instant;
public class StripeChargeSql {
public void insertCharge(Connection c, Account account, Charge charge) throws SQLException {
String sql = "INSERT INTO stripe_charge (account, charge_id, amount, \"when\") VALUES (?, ?, ?, ?);";
try (PreparedStatement ps = c.prepareStatement(sql)) {
PreparedStatements.set(ps, 1, account);
ps.setString(2, charge.chargeId.value);
ps.setBigDecimal(3, charge.amount);
ps.setTimestamp(4, Timestamp.from(charge.when));
ps.execute();
}
}
public List<Charge> byAccount(Connection c, Account account) throws SQLException {
String sql = "SELECT * FROM stripe_charge WHERE account = ? ORDER BY \"when\";";
try (PreparedStatement ps = c.prepareStatement(sql)) {
PreparedStatements.set(ps, 1, account);
return SqlOps.list(ps, rs -> new Charge(
ResultSets.chargeId(rs, "charge_id"),
rs.getBigDecimal("amount"),
rs.getTimestamp("when").toInstant()
));
}
}
@ToString
@EqualsAndHashCode
public static final class Charge {
public final ChargeId chargeId;
public final BigDecimal amount;
public final Instant when;
public Charge(ChargeId chargeId, BigDecimal amount, Instant when) {
this.chargeId = chargeId;
this.amount = amount;
this.when = when;
}
}
} | agpl-3.0 |
Siyy/RoadFlow | src/RoadFlow/Data.MSSQL/UsersRelation.cs | 8859 | using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace Data.MSSQL
{
public class UsersRelation : Data.Interface.IUsersRelation
{
private DBHelper dbHelper = new DBHelper();
/// <summary>
/// 构造函数
/// </summary>
public UsersRelation()
{
}
/// <summary>
/// 添加记录
/// </summary>
/// <param name="model">Data.Model.UsersRelation实体类</param>
/// <returns>操作所影响的行数</returns>
public int Add(Data.Model.UsersRelation model)
{
string sql = @"INSERT INTO UsersRelation
(UserID,OrganizeID,IsMain,Sort)
VALUES(@UserID,@OrganizeID,@IsMain,@Sort)";
SqlParameter[] parameters = new SqlParameter[]{
new SqlParameter("@UserID", SqlDbType.UniqueIdentifier, -1){ Value = model.UserID },
new SqlParameter("@OrganizeID", SqlDbType.UniqueIdentifier, -1){ Value = model.OrganizeID },
new SqlParameter("@IsMain", SqlDbType.Int, -1){ Value = model.IsMain },
new SqlParameter("@Sort", SqlDbType.Int, -1){ Value = model.Sort }
};
return dbHelper.Execute(sql, parameters);
}
/// <summary>
/// 更新记录
/// </summary>
/// <param name="model">Data.Model.UsersRelation实体类</param>
public int Update(Data.Model.UsersRelation model)
{
string sql = @"UPDATE UsersRelation SET
IsMain=@IsMain,Sort=@Sort
WHERE UserID=@UserID and OrganizeID=@OrganizeID";
SqlParameter[] parameters = new SqlParameter[]{
new SqlParameter("@IsMain", SqlDbType.Int, -1){ Value = model.IsMain },
new SqlParameter("@Sort", SqlDbType.Int, -1){ Value = model.Sort },
new SqlParameter("@UserID", SqlDbType.UniqueIdentifier, -1){ Value = model.UserID },
new SqlParameter("@OrganizeID", SqlDbType.UniqueIdentifier, -1){ Value = model.OrganizeID }
};
return dbHelper.Execute(sql, parameters);
}
/// <summary>
/// 删除记录
/// </summary>
public int Delete(Guid userid, Guid organizeid)
{
string sql = "DELETE FROM UsersRelation WHERE UserID=@UserID AND OrganizeID=@OrganizeID";
SqlParameter[] parameters = new SqlParameter[]{
new SqlParameter("@UserID", SqlDbType.UniqueIdentifier){ Value = userid },
new SqlParameter("@OrganizeID", SqlDbType.UniqueIdentifier){ Value = organizeid }
};
return dbHelper.Execute(sql, parameters);
}
/// <summary>
/// 将DataRedar转换为List
/// </summary>
private List<Data.Model.UsersRelation> DataReaderToList(SqlDataReader dataReader)
{
List<Data.Model.UsersRelation> List = new List<Data.Model.UsersRelation>();
Data.Model.UsersRelation model = null;
while (dataReader.Read())
{
model = new Data.Model.UsersRelation();
model.UserID = dataReader.GetGuid(0);
model.OrganizeID = dataReader.GetGuid(1);
model.IsMain = dataReader.GetInt32(2);
model.Sort = dataReader.GetInt32(3);
List.Add(model);
}
return List;
}
/// <summary>
/// 查询所有记录
/// </summary>
public List<Data.Model.UsersRelation> GetAll()
{
string sql = "SELECT * FROM UsersRelation";
SqlDataReader dataReader = dbHelper.GetDataReader(sql);
List<Data.Model.UsersRelation> List = DataReaderToList(dataReader);
dataReader.Close();
return List;
}
/// <summary>
/// 查询记录数
/// </summary>
public long GetCount()
{
string sql = "SELECT COUNT(*) FROM UsersRelation";
long count;
return long.TryParse(dbHelper.GetFieldValue(sql), out count) ? count : 0;
}
/// <summary>
/// 根据主键查询一条记录
/// </summary>
public Data.Model.UsersRelation Get(Guid userid, Guid organizeid)
{
string sql = "SELECT * FROM UsersRelation WHERE UserID=@UserID AND OrganizeID=@OrganizeID";
SqlParameter[] parameters = new SqlParameter[]{
new SqlParameter("@UserID", SqlDbType.UniqueIdentifier){ Value = userid },
new SqlParameter("@OrganizeID", SqlDbType.UniqueIdentifier){ Value = organizeid }
};
SqlDataReader dataReader = dbHelper.GetDataReader(sql, parameters);
List<Data.Model.UsersRelation> List = DataReaderToList(dataReader);
dataReader.Close();
return List.Count > 0 ? List[0] : null;
}
/// <summary>
/// 查询一个岗位下所有记录
/// </summary>
public List<Data.Model.UsersRelation> GetAllByOrganizeID(Guid organizeID)
{
string sql = "SELECT * FROM UsersRelation WHERE OrganizeID=@OrganizeID";
SqlParameter[] parameters = new SqlParameter[]{
new SqlParameter("@OrganizeID", SqlDbType.UniqueIdentifier){ Value = organizeID }
};
SqlDataReader dataReader = dbHelper.GetDataReader(sql, parameters);
List<Data.Model.UsersRelation> List = DataReaderToList(dataReader);
dataReader.Close();
return List;
}
/// <summary>
/// 查询一个用户所有记录
/// </summary>
public List<Data.Model.UsersRelation> GetAllByUserID(Guid userID)
{
string sql = "SELECT * FROM UsersRelation WHERE UserID=@UserID";
SqlParameter[] parameters = new SqlParameter[]{
new SqlParameter("@UserID", SqlDbType.UniqueIdentifier){ Value = userID }
};
SqlDataReader dataReader = dbHelper.GetDataReader(sql, parameters);
List<Data.Model.UsersRelation> List = DataReaderToList(dataReader);
dataReader.Close();
return List;
}
/// <summary>
/// 查询一个用户主要岗位
/// </summary>
public Data.Model.UsersRelation GetMainByUserID(Guid userID)
{
string sql = "SELECT * FROM UsersRelation WHERE UserID=@UserID AND IsMain=1";
SqlParameter[] parameters = new SqlParameter[]{
new SqlParameter("@UserID", SqlDbType.UniqueIdentifier){ Value = userID }
};
SqlDataReader dataReader = dbHelper.GetDataReader(sql, parameters);
List<Data.Model.UsersRelation> List = DataReaderToList(dataReader);
dataReader.Close();
return List.Count > 0 ? List[0] : null;
}
/// <summary>
/// 删除一个用户记录
/// </summary>
public int DeleteByUserID(Guid userID)
{
string sql = "DELETE FROM UsersRelation WHERE UserID=@UserID";
SqlParameter[] parameters = new SqlParameter[]{
new SqlParameter("@UserID", SqlDbType.UniqueIdentifier){ Value = userID }
};
return dbHelper.Execute(sql, parameters);
}
/// <summary>
/// 删除一个用户的兼职记录
/// </summary>
public int DeleteNotIsMainByUserID(Guid userID)
{
string sql = "DELETE FROM UsersRelation WHERE IsMain=0 AND UserID=@UserID";
SqlParameter[] parameters = new SqlParameter[]{
new SqlParameter("@UserID", SqlDbType.UniqueIdentifier){ Value = userID }
};
return dbHelper.Execute(sql, parameters);
}
/// <summary>
/// 删除一个机构下所有记录
/// </summary>
public int DeleteByOrganizeID(Guid organizeID)
{
string sql = "DELETE FROM UsersRelation WHERE OrganizeID=@OrganizeID";
SqlParameter[] parameters = new SqlParameter[]{
new SqlParameter("@OrganizeID", SqlDbType.UniqueIdentifier){ Value = organizeID }
};
return dbHelper.Execute(sql, parameters);
}
/// <summary>
/// 得到最大排序值
/// </summary>
/// <returns></returns>
public int GetMaxSort(Guid organizeID)
{
string sql = "SELECT ISNULL(MAX(Sort),0)+1 FROM UsersRelation WHERE OrganizeID=@OrganizeID";
SqlParameter[] parameters = new SqlParameter[]{
new SqlParameter("@OrganizeID", SqlDbType.UniqueIdentifier){ Value = organizeID }
};
DBHelper dbHelper = new DBHelper();
string sort = dbHelper.GetFieldValue(sql, parameters);
return sort.ToInt();
}
}
} | agpl-3.0 |
BagelOrb/SpreadMaximizationJava | src/objective/ChaObjective.java | 28106 | package objective;
import io.Images.InputSample;
import java.util.Arrays;
import layer.CnnDoubleLayer;
import layer.CnnDoubleLayerState;
import learningMechanism.LearningParameter;
import network.LayerParameters;
import network.Network;
import network.NetworkState;
import network.analysis.Debug;
import network.main.JFrameExperiment;
import org.apache.commons.math3.linear.BlockRealMatrix;
import org.apache.commons.math3.stat.descriptive.SummaryStatistics;
import org.apache.commons.math3.stat.descriptive.moment.Mean;
import org.apache.commons.math3.stat.descriptive.moment.Variance;
import util.basics.DoubleArray1D;
import util.basics.DoubleArray3D;
import util.basics.DoubleArray3Dext.Loc;
import util.math.DifferentiableFunction;
import util.math.Math2;
import util.math.MathFunction2D;
import util.math.MathFunction3D;
public class ChaObjective extends ObjectiveFunction {
public double[] meansUsed;
public double[] movingMeans;
public double[] newMeans;
public double[] lastMeans;
private static final boolean useMeans = true;
private static final boolean useConstraints = true;
private static final boolean useNormalizationConstraint = true;
private static final boolean useMovingMeans = false;
// TODO: make tanh conversion possible as well!
private double optimalStdDev_logisticSigmoid = 1.8137993369195464;
private double optimalStdDev_tanh = optimalStdDev_logisticSigmoid/2;
public double[] featureObjectives;
public ChaObjective(Network nw) {
super(nw);
}
@Override
double computeValue(NetworkState[] states) {
CnnDoubleLayer lastLayer = network.getLastLayer();
featureObjectives = new double[lastLayer.params.nFeatures];
double gho = getGhoObjective(states);
Debug.checkNaN(gho);
double totWeightConstraints = 0;
for (NetworkState nwState : states)
{
CnnDoubleLayerState state = nwState.getLast();
totWeightConstraints += getWeightObjective(state);
}
Debug.checkNaN(totWeightConstraints);
// double ff = 0;
// for (int i = 0; i< this.featureObjectives.length; i++)
// ff += featureObjectives[i];
// double diff = ff - (gho+totWeightConstraints);
double zeroMeaning = 0;
for (double mean : meansUsed)
zeroMeaning += network.netParams.etaMean *
(-1/4 * Math2.pow(mean, 4)
- 1/2 * mean*mean );
return gho + ((useConstraints)? totWeightConstraints :0) + zeroMeaning ;
}
private double getGhoObjective(NetworkState[] states) {
double total = 0;
for (NetworkState nwState : states) {
CnnDoubleLayerState state = nwState.getLast();
InputSample out = state.outputMaps;
// total += out.mapped(DifferentiableFunction.square).foldr(MathFunction2D.addition, 0);
double totState = 0;
for (int x = 0; x< out.width; x++)
for (int y = 0; y< out.height; y++)
for (int f = 0; f< out.depth; f++)
{
double ghoLocal = Math2.square(out.get(x, y, f)- meansUsed[f]);
totState += ghoLocal;
featureObjectives[f] += ghoLocal;
}
total += totState;
}
double gho = .5*total;
for (int i = 0 ; i< featureObjectives.length; i++)
featureObjectives[i] *= .5;
return gho;
}
private double getWeightObjective(CnnDoubleLayerState state) {
double tot = 0;
for (int xf = 0; xf < state.outputMaps.width; xf++)
for (int yf = 0; yf < state.outputMaps.height; yf++)
tot += getWeightObjective(xf, yf, state);
return tot;
}
private double getWeightObjective(int xf, int yf, CnnDoubleLayerState state) {
CnnDoubleLayer lastLayer = network.getLastLayer();
LayerParameters params = lastLayer.params;
double tot = 0;
for (int k = 0; k<params.nFeatures; k++)
{
double p = state.poolingMaps.get(xf, yf, k);
for (int j = 0; j < k; j++)
{
double weightedActivationMaps = getWeightedActionvationMaps(xf, yf, k, j, state);
double wjTwk =
state.cnnDoubleLayer.weights[j].zipFold(new MathFunction3D() {
@Override
public double apply(double arg1, double arg2, double result) {
return result + arg1 * arg2;
}
}, 0, state.cnnDoubleLayer.weights[k]); // vector multiplication
// DoubleArray3D q = state.cnnDoubleLayer.weights[j].times(state.cnnDoubleLayer.weights[k]);
//
// wjTwk = q.totalSum();
double localOrthogonalizationObj = (p- meansUsed[k]) * wjTwk * weightedActivationMaps;
tot -= localOrthogonalizationObj ;
featureObjectives[k] -= localOrthogonalizationObj;
}
// for j=k
if (useNormalizationConstraint)
{
double weightedActivationMaps = getWeightedActionvationMaps(xf, yf, k, k, state);
double wkTwk = state.cnnDoubleLayer.weights[k].foldr(new MathFunction2D() {
@Override public double apply(double arg1, double arg2) {
return arg2+ arg1*arg1;
}
}, 0); // total squared sum
// wkTwk = Math2.limit(-1E10, wkTwk, 1E10);
Debug.checkNaN(weightedActivationMaps);
Debug.checkNaN(wkTwk);
double localNormalizationObj = .5* (p-meansUsed[k]) * (1-wkTwk) * weightedActivationMaps;
tot += localNormalizationObj ;
featureObjectives[k] += localNormalizationObj;
}
}
Debug.checkNaN(tot);
return tot;
}
/*
* Derivatives
*/
@Override
public void computeCommonDerivativeStuff(NetworkState[] states) {
CnnDoubleLayer lastLayer = network.getLastLayer();
int nf = lastLayer.params.nFeatures;
lastMeans = meansUsed;
meansUsed = new double[nf];
newMeans = new double[nf];
if (!useMeans )
return;
Mean[] meanComps = new Mean[nf];
for (int f = 0 ; f < nf ; f++)
meanComps[f] = new Mean();
for (NetworkState state : states)
{
InputSample out = state.getLast().outputMaps;
for (Loc l : out) {
meanComps[l.z].increment(out.get(l));
}
}
for (int f = 0 ; f < nf ; f++)
{
newMeans[f] = meanComps[f].getResult();
Debug.checkNaN(newMeans[f]);
if (Math.abs(newMeans[f])>1E5)
Debug.out("Mean too high!!! : "+newMeans[f]);
}
// compute moving means:
// double ratio = ((double) network.currentBatchSize) / ((double) network.netParams.nSamples);
// ratio = Math2.limit(1./((double) network.netParams.nSamples), ratio, 1);
// ratio = 1 - .9 * (1-ratio); // depend a little more on the current batch!
// ratio *= .5; // depend a little less on the current batch!
double ratio = .1;
if (lastMeans == null)
movingMeans = newMeans;
else
for (int m = 0; m< meansUsed.length; m++)
{
movingMeans[m] = movingMeans[m] *(1-ratio) + ratio * newMeans[m];
}
if (!useMovingMeans)
meansUsed = newMeans;
else
meansUsed = movingMeans;
}
/*
public void computeCommonDerivativeStuff(NetworkState[] states, int f) {
lastMeans = meansUsed;
newMeans = Arrays.copyOf(meansUsed, lastMeans.length);
newMeans[f] = 0;
meansUsed = null;
if (!useMeans )
return;
{
double totF = 0;
for (NetworkState nwState : states)
{
CnnDoubleLayerState state = nwState.getLast();
double totState = 0;
InputSample out = state.outputMaps;
for (int x = 0; x < out.width; x++)
for (int y = 0; y < out.height; y++)
totState += out.get(x, y, f);
totF += totState;
}
newMeans[f] = totF / ( states.length * states[0].getLast().outputMaps.width * states[0].getLast().outputMaps.height);
Debug.checkNaN(newMeans[f]);
if (Math.abs(newMeans[f])>1E5)
Debug.out("Mean too high!!!");
}
// Debug.out("\nstate0 out = "+states[0].poolingMaps.get(0, 0, 0)+"\t\tbiases= " +Arrays.toString(network.cnnDoubleLayer.biases));
// network.debugout("\nstate0 out = "+states[0].getLast().outputMaps+"means = "+ Arrays.toString(means)+"\t\tbiases= " +Arrays.toString(network.getLastLayer().biases));
// network.debugout("means = "+ Arrays.toString(means)+"\t\tbiases= " +Arrays.toString(network.getLastLayer().biases));
// compute moving means:
// double ratio = ((double) network.currentBatchSize) / ((double) network.netParams.nSamples);
// ratio = Math2.limit(1./((double) network.netParams.nSamples), ratio, 1);
//// ratio = 1 - .9 * (1-ratio); // depend a little more on the current batch!
// ratio *= .5; // depend a little less on the current batch!
double ratio = .1;
if (lastMeans == null)
movingMeans = newMeans;
else
movingMeans[f] = movingMeans[f] *(1-ratio) + ratio * newMeans[f];
if (!useMovingMeans)
meansUsed = newMeans;
else
meansUsed = movingMeans;
}
*/
@Override
public double getDerivative(int feature, int xOutput, int yOutput, CnnDoubleLayerState state) {
return state.outputMaps.get(xOutput,yOutput,feature) - meansUsed[feature];
}
@Override
public void addWeightDerivatives(NetworkState[] states) {
if (!useConstraints)
return;
if (Debug.checkDerivatives && Debug.debugLevel >= 3)
{
DoubleArray3D[] totalResult = getGhoWeightsDerivatives(network, states);
Debug.out("difference between backpropagated derivatives and computed derivatives:\n"
+ totalResult[0].plus(network.getLastLayer().weightsDerivatives[0].times(-1)));
}
for (NetworkState nwState : states)
{
CnnDoubleLayerState state = nwState.getLast();
LayerParameters params = network.getLastLayer().params;
for (int k = 0; k<params.nFeatures; k++)
addWeightDerivatives(state, k);
}
Debug.checkNaN(network.getLastLayer().weightsDerivatives[0].get(0, 0, 0));
addBiasDerivatives(states);
}
public void addWeightDerivatives(NetworkState[] states, int f) {
if (!useConstraints)
return;
if (Debug.checkDerivatives && Debug.debugLevel >= 3)
{
DoubleArray3D[] totalResult = getGhoWeightsDerivatives(network, states);
Debug.out("difference between backpropagated derivatives and computed derivatives:\n"
+ totalResult[0].plus(network.getLastLayer().weightsDerivatives[0].times(-1)));
}
for (NetworkState nwState : states)
{
CnnDoubleLayerState state = nwState.getLast();
addWeightDerivatives(state, f);
}
Debug.checkNaN(network.getLastLayer().weightsDerivatives[0].get(0, 0, 0));
addBiasDerivatives(states, f);
}
private void addBiasDerivatives(NetworkState[] states) {
CnnDoubleLayer lastLayer = network.getLastLayer();
for (int f = 0; f<lastLayer.params.nFeatures; f++)
addBiasDerivatives(states, f);
}
private void addBiasDerivatives(NetworkState[] states, int f) {
CnnDoubleLayer lastLayer = network.getLastLayer();
lastLayer.biasesDerivatives[f] = -1*
network.netParams.etaMean *
// ( Math2.pow(meansUsed[f], 3) +
// states.length *
meansUsed[f]
// )
; // (discard backpropagated derivatives)
Debug.checkNaN(lastLayer.biasesDerivatives[f]);
}
private void addWeightDerivatives(CnnDoubleLayerState state, int k) {
for (int xf = 0; xf < state.outputMaps.width; xf++)
for (int yf = 0; yf < state.outputMaps.height; yf++)
addWeightDerivatives(k, xf, yf, state);
}
private void addWeightDerivatives(int k, int xf, int yf, CnnDoubleLayerState state) {
// int wcf = params.widthConvolutionField;
// int hcf = params.heightConvolutionField;
// int wps = params.widthPoolingStep;
// int hps = params.heightPoolingStep;
double p = state.poolingMaps.get(xf, yf, k);
int kk = (useNormalizationConstraint)? k : k-1;
for (int j = 0; j <= kk; j++)
{
double weightedActivationMaps = getWeightedActionvationMaps(xf, yf, k, j, state);
DoubleArray3D dw = state.cnnDoubleLayer.weights[j].times( -(p-meansUsed[k]) * weightedActivationMaps );
state.cnnDoubleLayer.weightsDerivatives[k].add(dw);
// for (int xi = 0 ; xi < wcf; xi++)
// for (int yi = 0 ; yi < hcf; yi++)
// for (int z = 0 ; z < params.nInputFeatures; z++)
// {
// double oDer = -p * weightedActivationMaps
// * state.cnnDoubleLayer.weights[j].get(xi, yi, z);
// Debug.checkNaN(oDer);
// state.cnnDoubleLayer.weightsDerivatives[k].add(xi, yi, z, oDer);
// }
}
Debug.checkNaN(network.getLastLayer().weightsDerivatives[0].get(0, 0, 0));
}
private double getWeightedActionvationMaps(int xf, int yf, int k, int j, CnnDoubleLayerState state) {
// TODO: assumes linear transfer function!
CnnDoubleLayer lastLayer = network.getLastLayer();
LayerParameters params = lastLayer.params;
int wpf = params.widthPoolingField;
int hpf = params.heightPoolingField;
int wps = params.widthPoolingStep;
int hps = params.heightPoolingStep;
double weightedActivationMaps = 0;
for (int xp = 0 ; xp < wpf; xp++)
for (int yp = 0 ; yp < hpf; yp++)
{
weightedActivationMaps += state.cnnDoubleLayer.poolingFunction.computeDerivative(xf, yf, k, state, xp, yp)
* state.convolutionMaps.get(xf*wps + xp, yf*hps + yp, j);
}
return weightedActivationMaps;
}
/*
* evaluation of derivatives without backprop
*/
private DoubleArray3D[] getGhoWeightsDerivatives(Network network,
NetworkState[] states) {
CnnDoubleLayer lastLayer = network.getLastLayer();
LayerParameters params = lastLayer.params;
DoubleArray3D[] ret = new DoubleArray3D[params.nFeatures];
for (int k = 0; k<params.nFeatures; k++)
{
DoubleArray3D totalResult = new DoubleArray3D(params.widthConvolutionField, params.heightConvolutionField, params.nInputFeatures);
{ // compute original derivatives (debug)
for (NetworkState nwState : states)
{
CnnDoubleLayerState state = nwState.getLast();
for (int xf = 0; xf < state.outputMaps.width; xf++)
for (int yf = 0; yf < state.outputMaps.height; yf++)
totalResult.add(getGhoDerivative(xf, yf, k, state));
}
}
ret[k] = totalResult;
}
return ret;
}
private DoubleArray3D getGhoDerivative(int xf, int yf, int k, CnnDoubleLayerState state) {
// TODO: assumes linear transfer function!
double p = state.poolingMaps.get(xf, yf, k);
CnnDoubleLayer lastLayer = network.getLastLayer();
LayerParameters params = lastLayer.params;
int wcf = params.widthConvolutionField;
int hcf = params.heightConvolutionField;
int wpf = params.widthPoolingField;
int hpf = params.heightPoolingField;
int wps = params.widthPoolingStep;
int hps = params.heightPoolingStep;
DoubleArray3D weightedInputMaps = new DoubleArray3D(wcf, hcf, params.nInputFeatures);
for (int xp = 0 ; xp < wpf; xp++)
for (int yp = 0 ; yp < hpf; yp++)
{
double pDer = state.cnnDoubleLayer.poolingFunction.computeDerivative(xf, yf, k, state, xp, yp);
for (int xi = 0 ; xi < wcf; xi++)
for (int yi = 0 ; yi < hcf; yi++)
for (int fi = 0 ; fi < params.nInputFeatures; fi++)
{
double d = pDer * state.inputMaps.get(xf*wps + xp + xi, yf*hps + yp + yi, fi);
weightedInputMaps.add(xi, yi, fi, d);
}
}
weightedInputMaps.multiply(p-meansUsed[k]);
return weightedInputMaps;
}
/*
* weight transformation
*/
public void orthonormalizeWeights() {
CnnDoubleLayer layer = network.getLastLayer();
LayerParameters params = layer.params;
for (int f = 0 ; f< params.nFeatures; f++)
orthonormalizeWeights(f);
// network.outputConstraints(network.getLastLayer());
}
public void orthonormalizeWeights(int k) {
CnnDoubleLayer layer = network.getLastLayer();
DoubleArray3D w_k = layer.weights[k];
// orthogonalize
DoubleArray3D projections = new DoubleArray3D(w_k.width, w_k.height, w_k.depth);
for (int j = 0 ; j< k; j++)
{
DoubleArray3D w_j = layer.weights[j];
projections.add(w_j.times(w_k.dotProduct(w_j)));
}
w_k.add(projections.times(-1));
// normalize
double weightLength = Math.sqrt(w_k.foldr(new MathFunction2D() {
@Override
public double apply(double arg1, double arg2) {
return arg1*arg1+arg2;
}
}, 0)
);
w_k.multiply(1. / weightLength );
// layer.biases[f] *= 1. ;
}
/*
* F I N A L I Z E N E T W O R K
*/
public void finalizeNetwork() {
orthonormalizeWeights();
transformWeights();
learnBiases();
// transformWeightsAndBiasesIteratively();
transformNetwork();
}
private void transformWeightsAndBiasesIteratively() {
Debug.out("transformWeightsAndBiasesIteratively...");
int nGoodEstimate = 500;
int nBatches = Math.max(1, nGoodEstimate / network.netParams.batchSize);
int nf = network.getLastLayer().params.nFeatures;
// network.netParams.nIterations/2
int totalIterations = 100;
for (int i = network.jumpToIteration; i< totalIterations; i++)
{
SummaryStatistics[] stats = new SummaryStatistics[nf];
for (int f = 0; f< nf; f++)
stats[f] = new SummaryStatistics();
for (int b = 0; b< nBatches; b++)
{
NetworkState[] batch = network.signalBatch(network.netParams.batchSize);
for (NetworkState state : batch)
for (Loc l : state.getLast().outputMaps)
{
Debug.checkNaN(state.getLast().outputMaps.get(l));
stats[l.z].addValue(state.getLast().outputMaps.get(l));
}
}
if (transformationHasConverged(stats))
{
Debug.out("Converged after "+i+" iterations!");
break;
}
if (monitorWeightAndBiasLearning(i, totalIterations, stats))
{
break;
}
transformBiasesAndWeights(stats);
}
Debug.out("Finished transformWeightsAndBiasesIteratively...");
}
private boolean monitorWeightAndBiasLearning(int i, int totalIterations, SummaryStatistics[] stats) {
int nf = network.getLastLayer().params.nFeatures;
// if (i%Math.max(1, totalIterations / 10) == 0)
// {
Network.output((int) ((i*100.) / (totalIterations)) + "%");
double[] means = new double[nf];
for (int f = 0; f<nf; f++)
means[f] = Math.sqrt(stats[f].getMean());
Debug.out(" means = "+Arrays.toString(means));
double[] stdDevs = new double[nf];
for (int f = 0; f<nf; f++)
stdDevs[f] = Math.sqrt(stats[f].getVariance());
Debug.out(" standard deviations = "+Arrays.toString(stdDevs));
//
// String varsStr = "";
// for (Variance var : vars)
// varsStr += var.getResult()+", ";
// Debug.out(" vars = "+varsStr);
// }
if (Debug.useWindowQuitExperiment && !JFrameExperiment.keepRunning) {
Network.output("=================================");
Network.output("Stopped after "+i+" iterations");
JFrameExperiment.keepRunning = true;
return true;
}
return false;
}
private void transformBiasesAndWeights(SummaryStatistics[] stats) {
int nf = network.getLastLayer().params.nFeatures;
CnnDoubleLayer layer = network.getLastLayer();
for (int f = 0 ; f< nf; f++)
{
layer.biases[f] -= stats[f].getMean();
double var = stats[f].getVariance();
layer.weights[f].multiply(optimalStdDev_tanh / Math.sqrt(var));
layer.biases[f] *= optimalStdDev_tanh / Math.sqrt(var) ;
}
}
private boolean transformationHasConverged(SummaryStatistics[] stats) {
int nf = network.getLastLayer().params.nFeatures;
for (int f = 0 ; f< nf; f++)
if ( ! (stats[f].getMean() < 1E-3
&& Math.sqrt(stats[f].getVariance()-Math2.square(optimalStdDev_tanh))<1E-3))
return false;
return true;
}
/*
* T R A N S F O R M W E I G H T S
*/
public void transformWeights() {
transformWeightsByOneGoodEstimate(10000);
transformWeightsIteratively();
// transformWeightsByOneGoodEstimate();
}
private void transformWeightsIteratively() {
lastMeans = null;
network.learningMechanism.resetState(network.getLastLayer());
JFrameExperiment.keepRunning = true;
Network.output("=================================");
Network.output("== Learning scalings ==");
double etaWeightsBefore = network.netParams.etaWeights;
network.netParams.etaWeights = 2E-4;
Network.output("Setting etaWeights to " + network.netParams.etaWeights);
int nf = network.getLastLayer().params.nFeatures;
LearningParameter[] scalingParams = new LearningParameter[nf];
for (int f = 0; f<nf; f++)
scalingParams[f] = network.learningMechanism.newLearningParameter(network.netParams);
for (int i = network.jumpToIteration; i<network.netParams.nIterations/2; i++) {
Variance[] vars = processBatchForScalings(scalingParams);
boolean stop = monitorScalingLearningProgress(i, scalingParams, vars);
if (stop)
break;
}
network.jumpToIteration = 0;
network.netParams.etaWeights = etaWeightsBefore;
Network.output("\r\n== Finished learning scalings ==\r\n");
}
private Variance[] processBatchForScalings(LearningParameter[] scalingParams) {
NetworkState[] states = network.signalBatch(Math.min(100, network.netParams.nSamples)); // .nSamples); //
Variance[] vars = computeVariances(states);
CnnDoubleLayer layer = network.getLastLayer();
int nf = layer.params.nFeatures;
for (int f = 0; f<nf; f++)
{
double stdDev = Math.sqrt(vars[f].getResult());
scalingParams[f].setValue(stdDev);
double update = scalingParams[f].computeUpdate(optimalStdDev_tanh - stdDev);
double ratio = (stdDev + update) / stdDev;
// double sqVecL = Math2.square(layer.weights[f].vectorLength());
// double totalVectorLength = Math.sqrt(sqVecL + Math2.square(layer.biases[f]));
layer.weights[f].multiply(ratio);
layer.biases[f] *= ratio;
}
return vars;
}
private Variance[] computeVariances(NetworkState[] states) {
int nf = network.getLastLayer().params.nFeatures;
Variance[] vars = new Variance[nf];
for (int f = 0 ; f < nf; f++)
vars[f] = new Variance();
for (NetworkState state : states)
{
InputSample out = state.getLast().outputMaps;
for (Loc l : out)
vars[l.z].increment(out.get(l));
}
return vars;
}
private boolean monitorScalingLearningProgress(int i, LearningParameter[] scalingParams, Variance[] vars) {
if (i%Math.max(1, network.netParams.nIterations / 2 / 10) == 0)
{
Network.output((int) ((i*100.) / (network.netParams.nIterations / 2.)) + "%");
Debug.out(" scaling params = "+Arrays.toString(scalingParams));
//
// String varsStr = "";
// for (Variance var : vars)
// varsStr += var.getResult()+", ";
// Debug.out(" vars = "+varsStr);
}
if (Debug.useWindowQuitExperiment && !JFrameExperiment.keepRunning) {
Network.output("=================================");
Network.output("Stopped after "+i+" iterations");
JFrameExperiment.keepRunning = true;
return true;
}
return false;
}
/*
* non-iterative variance update
*/
private void transformWeightsByOneGoodEstimate(int nGoodEstimates) {
Network.output("Estimating variances...");
int nBatches = nGoodEstimates / network.netParams.batchSize;
if (nBatches<1)
nBatches = 1;
int nFeatures = network.getLastLayer().params.nFeatures;
Variance[] vars = new Variance[nFeatures];
for (int f = 0 ; f < nFeatures; f++)
vars[f] = new Variance();
for (int b = 0; b< nBatches; b++)
{
NetworkState[] states = network.signalBatch(network.netParams.batchSize);
for (NetworkState state : states)
{
InputSample out = state.getLast().outputMaps;
for (Loc l : out)
vars[l.z].increment(out.get(l));
}
}
Network.output("Variances estimated! Transforming weights..");
CnnDoubleLayer layer = network.getLastLayer();
LayerParameters params = layer.params;
for (int f = 0 ; f< params.nFeatures; f++)
{
double var = vars[f].getResult();
layer.weights[f].multiply(optimalStdDev_tanh / Math.sqrt(var));
layer.biases[f] *= optimalStdDev_tanh / Math.sqrt(var) ;
}
Network.output("Weights transformed!");
}
/*
* ==========================================================================================
*/
private BlockRealMatrix getCovarMatrixbatch() {
NetworkState[] states = network.signalBatch(Math.min(100, network.netParams.nSamples));
return getCovarMatrix(states);
}
private BlockRealMatrix getCovarMatrix(NetworkState[] states) {
CovarComputation comp = new CovarComputation(network);
comp.updateCovarMatrixBatch(network, states);
return comp.covarMatrix;
}
public void transformNetwork() {
network.getLastLayer().params.signallingFunction = DifferentiableFunction.tanh;
}
/*
* L E A R N B I A S E S
*
*/
public void learnBiases() {
lastMeans = null;
network.learningMechanism.resetState(network.getLastLayer());
JFrameExperiment.keepRunning = true;
Network.output("=================================");
Network.output("== Learning biases ==");
Network.output("Setting etaBias to " + 1E-5);
double etaBiasesBefore = network.netParams.etaBiases;
network.netParams.etaBiases = 1E-5;
for (int i = network.jumpToIteration; i<network.netParams.nIterations/2; i++) {
processBatchForBiases();
boolean stop = monitorBiasLearningProgress(i);
if (stop || new DoubleArray1D(movingMeans).vectorLength() < 1E-4)
break;
}
network.jumpToIteration = 0;
network.netParams.etaBiases = etaBiasesBefore;
Network.output("\r\n== Finished learning biases ==\r\n");
}
/*
public void learnBiases(int f) {
double eta_rProp_min_before = network.netParams.eta_rPropMin;
network.netParams.eta_rPropMin = .25;
double eta_Weights_before = network.netParams.etaWeights;
network.netParams.etaWeights = .25;
double alpha_momentum = network.netParams.alpha_momentum ;
network.netParams.alpha_momentum = .9;
lastMeans = null;
network.learningMechanism.resetState(network.getLastLayer());
JFrameExperiment.keepRunning = true;
Network.output("=================================");
Network.output("== Learning biases ==");
for (int i = 0; i<network.netParams.nIterations/2; i++) {
processBatchForBiases(f);
boolean stop = monitorBiasLearningProgress(i);
if (stop || Math.abs(movingMeans[f]) < 1E-4)
break;
}
network.netParams.etaWeights = eta_Weights_before;
network.netParams.eta_rPropMin = eta_rProp_min_before;
network.netParams.alpha_momentum = alpha_momentum;
Network.output("\r\n== Finished learning biases ==\r\n");
}
*/
public boolean monitorBiasLearningProgress(int i) {
if (i%Math.max(1, network.netParams.nIterations / 2 / 10) == 0)
{
Network.output((int) ((i*100.) / (network.netParams.nIterations / 2.)) + "%");
Debug.out(" moving means =\n "+Arrays.toString(movingMeans));
Debug.out(" means =\n "+Arrays.toString(newMeans));
}
{ // rendering
// network.valuesOverTime.add(Arrays.copyOf(newMeans, getDimensionality()));
//
// if (System.currentTimeMillis() - network.lastRenderUpdate > 5000)
// {
// network.lastRenderUpdate = System.currentTimeMillis();
//
// try {
// JFrameExperiment.frame.graphValues(network.valuesOverTime);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
}
if (Debug.useWindowQuitExperiment && !JFrameExperiment.keepRunning) {
Network.output("=================================");
Network.output("Stopped after "+i+" iterations");
JFrameExperiment.keepRunning = true;
return true;
}
return false;
}
public NetworkState[] processBatchForBiases() {
NetworkState[] states = network.signalBatch(Math.min(100, network.netParams.nSamples)); // .nSamples); //
computeCommonDerivativeStuff(states);
addBiasDerivatives(states);
network.learningMechanism.updateBiases(network.getLastLayer());
return states;
}
/*
private NetworkState[] processBatchForBiases(int f) {
if (!network.netParams.staticData)
network.inputNewImages(Math.min(100, network.netParams.nSamples));
NetworkState[] states = network.signalBatchCHA(Math.min(100, network.netParams.nSamples), f); // .nSamples); //
computeCommonDerivativeStuff(states, f);
addBiasDerivatives(states, f);
network.learningMechanism.updateBiases(network.getLastLayer());
return states;
}
*/
public String toString() {
return "ChaObjective: "+lastValue;
}
}
| agpl-3.0 |
KiddoKiddo/WebSecA1Q1 | lib/MDB2/Driver/Native/sqlite3.php | 1035 | <?php
/**
* ownCloud
*
* @author Robin Appelman
* @copyright 2011 Robin Appelman [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
require_once 'MDB2/Driver/Native/Common.php';
/**
* MDB2 SQLite driver for the native module
*
* @package MDB2
* @category Database
* @author Lukas Smith <[email protected]>
*/
class MDB2_Driver_Native_sqlite extends MDB2_Driver_Native_Common
{
}
?> | agpl-3.0 |
noelhunter/SuiteCRM | tests/unit/lib/SuiteCRM/API/v8/Exception/UnsupportedMediaTypeTest.php | 1223 | <?php
namespace SuiteCRM\Exception;
use Psr\Log\LogLevel;
use SuiteCRM\API\v8\Exception\ApiException;
use SuiteCRM\API\v8\Exception\UnsupportedMediaType;
class UnsupportedMediaTypeTest extends \Codeception\Test\Unit
{
/**
* @var \UnitTester
*/
protected $tester;
/**#
* @var ApiException $exception
*/
private static $exception;
protected function _before()
{
if(self::$exception === null) {
self::$exception = new UnsupportedMediaType();
}
}
protected function _after()
{
}
public function testGetMessage()
{
$this->assertEquals('[SuiteCRM] [API] [Unsupported Media Type] ', self::$exception->getMessage());
}
public function testGetSetDetail()
{
$this->assertEquals('Json API expects the "Content-Type" header to be application/vnd.api+json', self::$exception->getDetail());
}
public function testGetSetSource()
{
self::$exception->setSource('/data');
$this->assertSame(array('pointer' => '/data'), self::$exception->getSource());
}
public function testGetHttpStatus()
{
$this->assertEquals(415, self::$exception->getHttpStatus());
}
} | agpl-3.0 |
superdesk/web-publisher | src/SWP/Bundle/ElasticSearchBundle/Loader/SearchResultLoader.php | 3871 | <?php
declare(strict_types=1);
/*
* This file is part of the Superdesk Web Publisher ElasticSearch Bundle.
*
* Copyright 2017 Sourcefabric z.ú. and contributors.
*
* For the full copyright and license information, please see the
* AUTHORS and LICENSE files distributed with this source code.
*
* @copyright 2017 Sourcefabric z.ú
* @license http://www.superdesk.org/license
*/
namespace SWP\Bundle\ElasticSearchBundle\Loader;
use FOS\ElasticaBundle\Manager\RepositoryManagerInterface;
use SWP\Bundle\ElasticSearchBundle\Criteria\Criteria;
use SWP\Bundle\ElasticSearchBundle\Repository\ArticleRepository;
use SWP\Component\MultiTenancy\Context\TenantContextInterface;
use SWP\Component\TemplatesSystem\Gimme\Factory\MetaFactoryInterface;
use SWP\Component\TemplatesSystem\Gimme\Loader\LoaderInterface;
use SWP\Component\TemplatesSystem\Gimme\Meta\MetaCollection;
final class SearchResultLoader implements LoaderInterface
{
public const MAX_RESULTS = 10000;
/**
* @var RepositoryManagerInterface
*/
private $repositoryManager;
/**
* @var MetaFactoryInterface
*/
private $metaFactory;
/**
* @var TenantContextInterface
*/
private $tenantContext;
/**
* @var string
*/
private $modelClass;
/**
* @var array
*/
private $extraFields;
/**
* SearchResultLoader constructor.
*
* @param RepositoryManagerInterface $repositoryManager
* @param MetaFactoryInterface $metaFactory
* @param TenantContextInterface $tenantContext
* @param string $modelClass
*/
public function __construct(
RepositoryManagerInterface $repositoryManager,
MetaFactoryInterface $metaFactory,
TenantContextInterface $tenantContext,
string $modelClass,
array $extraFields
) {
$this->repositoryManager = $repositoryManager;
$this->metaFactory = $metaFactory;
$this->tenantContext = $tenantContext;
$this->modelClass = $modelClass;
$this->extraFields = $extraFields;
}
/**
* {@inheritdoc}
*/
public function load($metaType, $withParameters = [], $withoutParameters = [], $responseType = self::COLLECTION)
{
if (isset($withParameters['order']) && 2 === count($withParameters['order'])) {
$withParameters['sort'] = [$withParameters['order'][0] => $withParameters['order'][1]];
unset($withParameters['order']);
}
$criteria = Criteria::fromQueryParameters($withParameters['term'] ?? '', $withParameters);
/** @var ArticleRepository $repository */
$repository = $this->repositoryManager->getRepository($this->modelClass);
$query = $repository->findByCriteria($criteria, $this->extraFields);
$pagination = $criteria->getPagination();
$metaCollection = new MetaCollection();
if (($pagination->getCurrentPage() * $pagination->getItemsPerPage()) > (self::MAX_RESULTS + $pagination->getItemsPerPage())) {
return $metaCollection;
}
$partialResult = $query->getResults(
$pagination->getOffset(),
$pagination->getItemsPerPage()
);
$metaCollection->setTotalItemsCount($query->getTotalHits());
foreach ($partialResult->toArray() as $article) {
if (null !== ($articleMeta = $this->metaFactory->create($article))) {
$metaCollection->add($articleMeta);
}
}
$metaCollection->suggestedTerm = $repository->getSuggestedTerm($criteria->getTerm());
$metaCollection->maxScore = $query->getMaxScore();
return $metaCollection;
}
/**
* {@inheritdoc}
*/
public function isSupported(string $type): bool
{
return in_array($type, ['searchResults']);
}
}
| agpl-3.0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.