repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
shobhit-m/meta_notification | spec/models/meta_notification/user_notification_setting_spec.rb | 818 | require 'rails_helper'
module MetaNotification
RSpec.describe UserNotificationSetting, type: :model do
10.times do
it 'check valid user notification settings' do
type = FactoryGirl.build(:valid_user_notification_settings)
pp type
expect(type).to be_valid
end
end
3.times do |index|
it 'check invalid user notification settings' do
method_name = 'invalid_user_notification_setting' + "_#{index}"
pp method_name
type = FactoryGirl.build(method_name)
pp type
expect(type).not_to be_valid
end
end
10.times do
it 'create valid user notification settings' do
type = FactoryGirl.create(:valid_user_notification_settings)
pp type
expect(type).to be_valid
end
end
end
end
| mit |
pellaea/mushroom-observer | test/controllers/sequence_controller_test.rb | 16204 | # frozen_string_literal: true
require "test_helper"
# Controller tests for nucleotide sequences
class SequenceControllerTest < FunctionalTestCase
def test_list_sequences
get_with_dump(:list_sequences)
assert(:success)
end
def test_sequence_search
get(:sequence_search, pattern: Sequence.last.id)
assert_redirected_to(Sequence.last.show_link_args)
get(:sequence_search, pattern: "ITS")
assert(:success)
end
def test_observation_index
obs = observations(:locally_sequenced_obs)
get(:observation_index, id: obs.id)
assert(:success)
obs = observations(:genbanked_obs)
get(:observation_index, id: obs.id)
assert(:success)
end
def test_index_sequence
obs = observations(:genbanked_obs)
query = Query.lookup_and_save(:Sequence, :for_observation, observation: obs)
results = query.results
assert_operator(results.count, :>, 3)
q = query.id.alphabetize
get(:index_sequence, q: q, id: results[2].id)
assert_response(:success)
get(:next_sequence, q: q, id: results[1].id)
assert_redirected_to(results[2].show_link_args.merge(q: q))
get(:prev_sequence, q: q, id: results[2].id)
assert_redirected_to(results[1].show_link_args.merge(q: q))
end
def test_show_sequence
# Prove sequence displayed if called with id of sequence in db
sequence = sequences(:local_sequence)
get_with_dump(:show_sequence, id: sequence.id)
assert_response(:success)
# Prove index displayed if called with id of sequence not in db
get(:show_sequence, id: 666)
assert_redirected_to(action: :index_sequence)
end
def test_create_sequence_get
# choose an obs not owned by Rolf (`requires_login` will login Rolf)
obs = observations(:minimal_unknown_obs)
owner = obs.user
# Prove method requires login
requires_login(:create_sequence, id: obs.id)
# Prove logged-in user can add Sequence to someone else's Observation
login("zero")
get(:create_sequence, id: obs.id)
assert_response(:success)
# Prove Observation owner can add Sequence
login(owner.login)
get_with_dump(:create_sequence, id: obs.id)
assert_response(:success)
# Prove admin can add Sequence
make_admin("zero")
get(:create_sequence, id: obs.id)
assert_response(:success)
end
def test_create_sequence_post
old_count = Sequence.count
obs = observations(:detailed_unknown_obs)
owner = obs.user
locus = "ITS"
bases = "gagtatgtgc acacctgccg tctttatcta tccacctgtg cacacattgt agtcttgggg"\
"gattggttag cgacaatttt tgttgccatg tcgtcctctg gggtctatgt tatcataaac"\
"cacttagtat gtcgtagaat gaagtatttg ggcctcagtg cctataaaac aaaatacaac"\
"tttcagcaac ggatctcttg gctctcgcat cgatgaagaa cgcagcgaaa tgcgataagt"\
"aatgtgaatt gcagaattca gtgaatcatc gaatctttga acgcaccttg cgctccttgg"\
"tattccgagg agcatgcctg tttgagtgtc attaaattct caacccctcc agcttttgtt"\
"gctggtcgtg gcttggatat gggagtgttt gctggtctca ttcgagatca gctctcctga"\
"aatacattag tggaaccgtt tgcgatccgt caccggtgtg ataattatct acgccataga"\
"ctgtgaacgc tctctgtatt gttctgcttc taactgtctt attaaaggac aacaatattg"\
"aacttttgac ctcaaatcag gtaggactac ccgctgaact taagcatatc aataa"
params = {
id: obs.id,
sequence: { locus: locus,
bases: bases }
}
# Prove user must be logged in to create Sequence
post(:create_sequence, params)
assert_equal(old_count, Sequence.count)
# Prove logged-in user can add sequence to someone else's Observation
user = users(:zero_user)
login(user.login)
post(:create_sequence, params)
assert_equal(old_count + 1, Sequence.count)
sequence = Sequence.last
assert_objs_equal(obs, sequence.observation)
assert_users_equal(user, sequence.user)
assert_equal(locus, sequence.locus)
assert_equal(bases, sequence.bases)
assert_empty(sequence.archive)
assert_empty(sequence.accession)
assert_redirected_to(obs.show_link_args)
assert_flash_success
assert(obs.rss_log.notes.include?("log_sequence_added"),
"Failed to include Sequence added in RssLog for Observation")
# Prove user can create non-repository Sequence
old_count = Sequence.count
locus = "ITS"
bases = "gagtatgtgc acacctgccg tctttatcta tccacctgtg cacacattgt agtcttgggg"
params = {
id: obs.id,
sequence: { locus: locus,
bases: bases }
}
login(owner.login)
post(:create_sequence, params)
assert_equal(old_count + 1, Sequence.count)
sequence = Sequence.last
assert_objs_equal(obs, sequence.observation)
assert_users_equal(owner, sequence.user)
assert_equal(locus, sequence.locus)
assert_equal(bases, sequence.bases)
assert_empty(sequence.archive)
assert_empty(sequence.accession)
assert_redirected_to(obs.show_link_args)
assert_flash_success
assert(obs.rss_log.notes.include?("log_sequence_added"),
"Failed to include Sequence added in RssLog for Observation")
# Prove admin can create repository Sequence
locus = "ITS"
archive = "GenBank"
accession = "KY366491.1"
params = {
id: obs.id,
sequence: { locus: locus,
archive: archive,
accession: accession }
}
old_count = Sequence.count
make_admin("zero")
post(:create_sequence, params)
assert_equal(old_count + 1, Sequence.count)
sequence = Sequence.last
assert_equal(locus, sequence.locus)
assert_empty(sequence.bases)
assert_equal(archive, sequence.archive)
assert_equal(accession, sequence.accession)
assert_redirected_to(obs.show_link_args)
end
def test_create_sequence_post_wrong_parameters
old_count = Sequence.count
obs = observations(:coprinus_comatus_obs)
login(obs.user.login)
# Prove that locus is required.
params = {
id: obs.id,
sequence: { locus: "",
bases: "actgct" }
}
post(:create_sequence, params)
assert_equal(old_count, Sequence.count)
# response is 200 because it just reloads the form
assert_response(:success)
assert_flash_error
# Prove that bases or archive+accession required.
params = {
id: obs.id,
sequence: { locus: "ITS" }
}
post(:create_sequence, params)
assert_equal(old_count, Sequence.count)
assert_response(:success)
assert_flash_error
# Prove that accession required if archive present.
params = {
id: obs.id,
sequence: { locus: "ITS", archive: "GenBank" }
}
post(:create_sequence, params)
assert_equal(old_count, Sequence.count)
assert_response(:success)
assert_flash_error
# Prove that archive required if accession present.
params = {
id: obs.id,
sequence: { locus: "ITS", accession: "KY133294.1" }
}
post(:create_sequence, params)
assert_equal(old_count, Sequence.count)
assert_response(:success)
assert_flash_error
end
def test_create_sequence_redirect
obs = observations(:genbanked_obs)
query = Query.lookup_and_save(:Sequence, :all)
q = query.id.alphabetize
params = {
id: obs.id,
sequence: { locus: "ITS", bases: "atgc" },
q: q
}
# Prove that query params are added to form action.
login(obs.user.login)
get(:create_sequence, params)
assert_select("form[action*='sequence/#{obs.id}?q=#{q}']")
# Prove that post keeps query params intact.
post(:create_sequence, params)
assert_redirected_to(obs.show_link_args.merge(q: q))
end
def test_edit_sequence_get
sequence = sequences(:local_sequence)
obs = sequence.observation
observer = obs.user
# Prove method requires login
assert_not_equal(rolf, observer)
assert_not_equal(rolf, sequence.user)
requires_login(:edit_sequence, id: sequence.id)
# Prove user cannot edit Sequence he didn't create for Obs he doesn't own
login("zero")
get(:edit_sequence, id: sequence.id)
assert_redirected_to(obs.show_link_args)
# Prove Observation owner can edit Sequence
login(observer.login)
get(:edit_sequence, id: sequence.id)
assert_response(:success)
# Prove admin can edit Sequence
make_admin("zero")
get(:edit_sequence, id: sequence.id)
assert_response(:success)
end
def test_edit_sequence_post
sequence = sequences(:local_sequence)
obs = sequence.observation
observer = obs.user
sequencer = sequence.user
locus = "mtSSU"
bases = "gagtatgtgc acacctgccg tctttatcta tccacctgtg cacacattgt agtcttgggg"\
"gattggttag cgacaatttt tgttgccatg tcgtcctctg gggtctatgt tatcataaac"\
"cacttagtat gtcgtagaat gaagtatttg ggcctcagtg cctataaaac aaaatacaac"\
"tttcagcaac ggatctcttg gctctcgcat cgatgaagaa cgcagcgaaa tgcgataagt"\
"aatgtgaatt gcagaattca gtgaatcatc gaatctttga acgcaccttg cgctccttgg"\
"tattccgagg agcatgcctg tttgagtgtc attaaattct caacccctcc agcttttgtt"\
"gctggtcgtg gcttggatat gggagtgttt gctggtctca ttcgagatca gctctcctga"\
"aatacattag tggaaccgtt tgcgatccgt caccggtgtg ataattatct acgccataga"\
"ctgtgaacgc tctctgtatt gttctgcttc taactgtctt attaaaggac aacaatattg"\
"aacttttgac ctcaaatcag gtaggactac ccgctgaact taagcatatc aataa"
params = {
id: sequence.id,
sequence: { locus: locus,
bases: bases }
}
# Prove user must be logged in to edit Sequence.
post(:edit_sequence, params)
assert_not_equal(locus, sequence.reload.locus)
# Prove user must be owner to edit Sequence.
login("zero")
post(:edit_sequence, params)
assert_not_equal(locus, sequence.reload.locus)
assert_flash_text(:permission_denied.t)
# Prove Observation owner user can edit Sequence
login(observer.login)
post(:edit_sequence, params)
sequence.reload
obs.rss_log.reload
assert_objs_equal(obs, sequence.observation)
assert_users_equal(sequencer, sequence.user)
assert_equal(locus, sequence.locus)
assert_equal(bases, sequence.bases)
assert_empty(sequence.archive)
assert_empty(sequence.accession)
assert_redirected_to(obs.show_link_args)
assert_flash_success
assert(obs.rss_log.notes.include?("log_sequence_updated"),
"Failed to include Sequence updated in RssLog for Observation")
# Prove admin can accession Sequence
archive = "GenBank"
accession = "KT968655"
params = {
id: sequence.id,
sequence: { locus: locus,
bases: bases,
archive: archive,
accession: accession }
}
make_admin("zero")
post(:edit_sequence, params)
sequence.reload
obs.rss_log.reload
assert_equal(archive, sequence.archive)
assert_equal(accession, sequence.accession)
assert(obs.rss_log.notes.include?("log_sequence_accessioned"),
"Failed to include Sequence accessioned in RssLog for Observation")
# Prove Observation owner user can edit locus
locus = "ITS"
params = {
id: sequence.id,
sequence: { locus: locus,
bases: bases,
archive: archive,
accession: accession }
}
post(:edit_sequence, params)
assert_equal(locus, sequence.reload.locus)
# Prove locus required.
params = {
id: sequence.id,
sequence: { locus: "",
bases: bases,
archive: archive,
accession: accession }
}
post(:edit_sequence, params)
# response is 200 because it just reloads the form
assert_response(:success)
assert_flash_error
# Prove bases or archive+accession required.
params = {
id: sequence.id,
sequence: { locus: locus,
bases: "",
archive: "",
accession: "" }
}
post(:edit_sequence, params)
assert_response(:success)
assert_flash_error
# Prove accession required if archive present.
params = {
id: sequence.id,
sequence: { locus: locus,
bases: bases,
archive: archive,
accession: "" }
}
post(:edit_sequence, params)
assert_response(:success)
assert_flash_error
# Prove archive required if accession present.
params = {
id: sequence.id,
sequence: { locus: locus,
bases: bases,
archive: "",
accession: accession }
}
post(:edit_sequence, params)
assert_response(:success)
assert_flash_error
end
def test_edit_sequence_redirect
obs = observations(:genbanked_obs)
sequence = obs.sequences[2]
assert_operator(obs.sequences.count, :>, 3)
query = Query.lookup_and_save(:Sequence, :for_observation, observation: obs)
q = query.id.alphabetize
login(obs.user.login)
params = {
id: sequence.id,
sequence: { locus: sequence.locus,
bases: sequence.bases,
archive: sequence.archive,
accession: sequence.accession }
}
# Prove that GET passes "back" and query param through to form.
get(:edit_sequence, params.merge(back: "foo", q: q))
assert_select("form[action*='sequence/#{sequence.id}?back=foo&q=#{q}']")
# Prove by default POST goes back to observation.
post(:edit_sequence, params)
assert_redirected_to(obs.show_link_args)
# Prove that POST keeps query param when returning to observation.
post(:edit_sequence, params.merge(q: q))
assert_redirected_to(obs.show_link_args.merge(q: q))
# Prove that POST can return to show_sequence, too, with query intact.
post(:edit_sequence, params.merge(back: "show", q: q))
assert_redirected_to(sequence.show_link_args.merge(q: q))
end
def test_destroy_sequence
old_count = Sequence.count
sequence = sequences(:local_sequence)
obs = sequence.observation
observer = obs.user
# Prove user must be logged in to destroy Sequence.
post(:destroy_sequence, id: sequence.id)
assert_equal(old_count, Sequence.count)
# Prove user cannot destroy Sequence he didn't create for Obs he doesn't own
login("zero")
post(:destroy_sequence, id: sequence.id)
assert_equal(old_count, Sequence.count)
assert_redirected_to(obs.show_link_args)
assert_flash_text(:permission_denied.t)
# Prove Observation owner can destroy Sequence
login(observer.login)
post(:destroy_sequence, id: sequence.id)
assert_equal(old_count - 1, Sequence.count)
assert_redirected_to(obs.show_link_args)
assert_flash_success
assert(obs.rss_log.notes.include?("log_sequence_destroy"),
"Failed to include Sequence destroyed in RssLog for Observation")
end
def test_destroy_sequence_admin
old_count = Sequence.count
sequence = sequences(:local_sequence)
obs = sequence.observation
observer = obs.user
# Prove admin can destroy Sequence
make_admin("zero")
post(:destroy_sequence, id: sequence.id)
assert_equal(old_count - 1, Sequence.count)
assert_redirected_to(obs.show_link_args)
assert_flash_success
assert(obs.rss_log.notes.include?("log_sequence_destroy"),
"Failed to include Sequence destroyed in RssLog for Observation")
end
def test_destroy_sequence_redirect
obs = observations(:genbanked_obs)
seqs = obs.sequences
query = Query.lookup_and_save(:Sequence, :for_observation, observation: obs)
q = query.id.alphabetize
login(obs.user.login)
# Prove by default it goes back to observation.
post(:destroy_sequence, id: seqs[0].id)
assert_redirected_to(obs.show_link_args)
# Prove that it keeps query param intact when returning to observation.
post(:destroy_sequence, id: seqs[1].id, q: q)
assert_redirected_to(obs.show_link_args.merge(q: q))
# Prove that it can return to index, too, with query intact.
post(:destroy_sequence, id: seqs[2].id, q: q, back: "index")
assert_redirected_to(action: :index_sequence, q: q)
end
end
| mit |
KMFleischer/PyEarthScience | Transition_examples_NCL_to_PyNGL/read_data/test.py | 755 | """
Transition Guide Python Example: TRANS_read_netCDF.py
- read netCDF file
- retrieve variable informations
Test_6h.csv
2.00;3.50;5.10;8.20
2.40;3.10;4.80;8.90
2.60;3.70;5.30;10.10
2.75;3.90;5.55;10.25
3.00;4.10;6.05;10.50
2018-08-28 kmf
"""
import numpy as np
import Ngl,Nio
print("")
#-- data file name
diri = "/Users/k204045/local/miniconda2/envs/pyn_env/lib/ncarg/data/nug/"
fili = "Test_6h.csv"
#-- number of lines and columns in input file
nrows = 5
ncols = 4
#-- read all data
vals = Ngl.asciiread(diri+fili,(nrows,ncols),"float",sep=';')
#-- print information
print("vals: " + str(vals))
print("")
print("--> rank of vals: " + str(len(vals.shape)))
print("--> shape vals: " + str(vals.shape))
exit()
| mit |
phan91/STOMP_agilis | Stomp/server/server.py | 14354 | import socket
import threading
import uuid
import argparse
from Stomp.Decoder import Decode
from Stomp.Encoder import Encode
class Server(object):
"""
Server class for STOMP server functionality.
Listen on a given socket and respond to STOMP clients depends on the input message.
"""
def __init__(self):
"""
Server class initialization.
decoder: Decoder class object. Supports making STOMP frames from TCP messages.
encoder: Encoder class object. Supports making STOMP frames from commands.
supported_versions: tells which STOMP version supported by the server.
serversocket: TCP socket for the communication
server-command = "CONNECTED"
| "MESSAGE"
| "RECEIPT"
| "ERROR"
"""
self.decoder = Decode.Decoder()
self.encoder = Encode.Encoder()
self.supported_versions = ['1.2']
# create an INET, STREAMing socket
self.serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.connection_pool = []
self.subscriptions = []
self.transactions = []
def receive(self, msg, connection):
"""
This method called when the server get a message from a client.
First it decodes the msg to a frame. After that call a function depends on the frame's command.
:param msg: received TCP message
:param connection: active TCP connection with one of the client
:return:
"""
try:
frame = self.decoder.decode(msg)
print 'Server received frame: \n' + str(frame) + '\n'
self.requests.get(type(frame).__name__)(self, frame, connection)
except Exception:
raise
def connect_frame_received(self, request_frame, connection):
"""
This method called when the server get CONNECT frame.
If the client and server do not share any common protocol versions, raise an exception
else the server responds with CONNECTED frame.
:param request_frame: Decoded frame from client message
:param connection: active TCP connection with one of the client
:return:
"""
common_versions = list(set(request_frame.headers['accept-version'].split(',')).intersection(self.supported_versions))
if len(common_versions) == 0:
error_message = 'Supported protocol versions are ' + str(self.supported_versions)
self.error(error_message, connection)
raise RuntimeError(error_message)
else:
connected_frame = self.encoder.encode('CONNECTED', **{'version': max(common_versions)})
self.respond(str(connected_frame), connection)
def respond(self, msg, connection):
"""
This method called when the client sends frame, which need some respond.
:param msg: STOMP frame as a string
:param connection: active TCP connection with one of the client
:return:
"""
print 'Server will send frame: \n' + msg
totalsent = 0
while totalsent < len(msg):
sent = connection.send(msg[totalsent:])
if sent == 0:
raise RuntimeError("socket connection broken")
totalsent = totalsent + sent
def start(self, address, port):
"""
This function starts the listening on the given address and port.
Creates a new thread after every TCP connection
:param address: Address server listening on
:param port: Port server listening on
:return:
"""
try:
# bind the socket to localhost, and STOMP port
self.serversocket.bind((address, port))
print 'Server started at: ' + address + ':' + str(port)
print 'Server supports STOMP version: ' + str(self.supported_versions)
# become a server socket
self.serversocket.listen(5)
while True:
# accept connections from outside
(connection, client_address) = self.serversocket.accept()
t = threading.Thread(target=self.run_client_thread,kwargs={'connection': connection,
'address': client_address})
self.connection_pool.append(t)
t.start()
#t.join()
finally:
self.serversocket.close()
def run_client_thread(self, connection, address):
"""
This method is waiting for messages from client.
:param connection: TCP connection variable
:param address: Client address variable
:return:
"""
while True:
try:
data = connection.recv(1024)
if not data:
break
self.receive(data, connection)
except Exception as ex:
connection.close()
raise
def disconnect_frame_received(self, request_frame, connection):
"""
A graceful shutdown, where if the client is assured that all previous frames have been received by the server,
then DISCONNECT frame contains receipt header. In that case server has to reply with RECEIPT frame,
with the given id.
If client has active subscription, remove it.
:param request_frame: received DISCONNECT frame
:param connection: TCP connection variable with the client
:return:
"""
if 'receipt' in request_frame.headers:
self.receipt(request_frame.headers['receipt'], connection)
else:
connection.close()
for sub in self.subscriptions:
if sub['connection'] == connection:
self.subscriptions.remove(sub)
def receipt(self, receipt_id, connection):
"""
A RECEIPT frame is sent from the server to the client once a server has successfully processed a client frame
that requests a receipt. A RECEIPT frame MUST include the header receipt-id.
:param receipt_id: the value is the value of the receipt header in the frame which this is a receipt for
:param connection: TCP connection variable
:return:
"""
receipt_frame = self.encoder.encode('RECEIPT', **{'receipt-id': str(receipt_id)})
self.respond(str(receipt_frame), connection)
def send_frame_received(self, request_frame, connection):
"""
When STOMP server receive SEND frame, this method forwards the frame to the right clients.
Check who is subscribed on the destination. Not allowed, to resend the message to the owner client.
:param request_frame: received SEND frame
:param connection: TCP connection variable, where the message came from
:return:
"""
message_id = str(uuid.uuid4()) # TODO generate namespace dependent unique message ID if it is requiered somewhere
if 'transaction' in request_frame.headers:
for t in self.transactions:
if t['id'] == request_frame.headers['transaction'] and connection == t['beginner']:
t['messages'].append({'destination': request_frame.headers['destination'],
'message-id': message_id, 'content': request_frame.msg})
else:
for sub in self.subscriptions:
if sub['destination'] == request_frame.headers['destination'] and sub['connection'] != connection:
msg_frame = self.encoder.encode('MESSAGE', **{'destination': request_frame.headers['destination'],
'message-id': message_id, 'subscription': sub['id'],
'msg': request_frame.msg})
self.respond(str(msg_frame), sub['connection'])
self.receipt('message-'+str(message_id), connection)
def subscribe_frame_received(self, request_frame, connection):
"""
Check if there is a subscription with the same id. If yes send an error message.
Else make the subscription, and append to the subscription list.
:param request_frame: received SUBSCRIBE frame from client
:param connection: TCP connection variable
:return:
"""
if any(int(request_frame.headers['id']) == s['id'] and
request_frame.headers['destination'] == s['destination'] for s in self.subscriptions):
error_message = 'Given SUBSCRIBE id: ' + request_frame.headers['id'] + ' already registered'
self.error(error_message, connection)
else:
subscription = {'id': int(request_frame.headers['id']), 'destination': request_frame.headers['destination'],
'connection': connection, 'ack': 'auto'}
if 'ack' in request_frame.headers:
subscription['ack'] = request_frame.headers['ack']
self.subscriptions.append(subscription)
def unsubscribe_frame_received(self, request_frame, connection):
"""
If no subscription with the received id, send error message.
If the subscription is in the list, but its not belongs to this client, send error message.
If everything is ok, remove subscription from the list.
:param request_frame: Received UNSUBSCRIBE frame
:param connection: TCP connection variable
:return:
"""
if not any(int(request_frame.headers['id']) == s['id'] for s in self.subscriptions):
error_message = 'Given SUBSCRIBE id: ' + request_frame.headers['id'] + ' is NOT registered'
self.error(error_message, connection)
else:
for sub in self.subscriptions:
if sub['id'] == request_frame.headers['id']:
if sub['connection'] != connection:
error_message = 'Given SUBSCRIBE id: ' + request_frame.headers['id'] + ' is NOT belongs to you'
self.error(error_message, connection)
else:
self.subscriptions.remove(sub)
def error(self, error_msg, connection):
"""
Crete ERROR Frame if something went wrong. Raise exception with error message.
:param error_msg: Error message. What went wrong.
:param connection: TCP connection variable
:return:
"""
error_frame = self.encoder.encode('ERROR', **{'msg': error_msg})
self.respond(str(error_frame), connection)
# raise RuntimeError(error_msg)
def begin_received(self, request_frame, connection):
"""
BEGIN frame received. Store the transaction informations if there is no other transaction
with the same id from the same client.
:param request_frame: Received BEGIN frame
:param connection: TCP connection variable
:return:
"""
if any(int(request_frame.headers['transaction']) == t['transaction'] and
connection == t['beginner'] for t in self.transactions):
error_message = 'Given Transaction id: ' + request_frame.headers['transaction'] + \
' is already registered from this session'
self.error(error_message, connection)
else:
self.transactions.append({'id': request_frame.headers['transaction'], 'beginner': connection,
'messages': []})
def ack_nack_received(self, request_frame):
"""
:param request_frame: Received ACK or NACK frame
:return:
"""
if 'transaction' in request_frame.headers:
for transaction in self.transactions:
if transaction['id'] == request_frame.headers['transaction']:
self.respond(str(request_frame), transaction['beginner'])
def abort_received(self, request_frame, connection):
"""
:param request_frame:
:param connection:
:return:
"""
for t in self.transactions:
if t['id'] == request_frame.headers['transaction'] and t['beginner'] == connection:
self.transactions.remove(t)
def commit_received(self, request_frame, connection):
"""
:param request_frame:
:param connection:
:return:
"""
for t in self.transactions:
if request_frame.headers['transaction'] == t['id'] and connection == t['beginner']:
for m in t['messages']:
for sub in self.subscriptions:
if sub['destination'] == m['destination'] and sub['connection'] != connection:
msg_frame = self.encoder.encode('MESSAGE',
**{'destination': m['destination'],
'message-id': m['message-id'], 'subscription': sub['id'],
'msg': m['content']})
self.respond(str(msg_frame), sub['connection'])
requests = {
'CONNECT': connect_frame_received,
'STOMP': connect_frame_received,
'DISCONNECT': disconnect_frame_received,
'SEND': send_frame_received,
'SUBSCRIBE': subscribe_frame_received,
'UNSUBSCRIBE': unsubscribe_frame_received,
'ACK': ack_nack_received,
'NACK': ack_nack_received,
'ABORT': abort_received,
'COMMIT': commit_received,
'BEGIN': begin_received,
}
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='STOMP Server')
parser.add_argument('--host', action='store', dest='host', type=str,
default='0.0.0.0',
help='Set host or ip (default: 0.0.0.0 (all interfaces))')
parser.add_argument('--port', action='store', dest='port', type=int,
default=1212,
help='Set http api port (default: 1212)')
arg_results = parser.parse_args()
stomp_server = Server()
stomp_server.start(arg_results.host, arg_results.port)
| mit |
motki/motkid | vendor/github.com/leekchan/accounting/formatnumber_test.go | 4341 | package accounting
import (
"math/big"
"testing"
)
func TestFormatNumber(t *testing.T) {
AssertEqual(t, FormatNumber(123456789.213123, 3, ",", "."), "123,456,789.213")
AssertEqual(t, FormatNumber(123456789.213123, 3, ".", ","), "123.456.789,213")
AssertEqual(t, FormatNumber(-12345.123123, 5, ",", "."), "-12,345.12312")
AssertEqual(t, FormatNumber(-1234.123123, 5, ",", "."), "-1,234.12312")
AssertEqual(t, FormatNumber(-123.123123, 5, ",", "."), "-123.12312")
AssertEqual(t, FormatNumber(-12.123123, 5, ",", "."), "-12.12312")
AssertEqual(t, FormatNumber(-1.123123, 5, ",", "."), "-1.12312")
AssertEqual(t, FormatNumber(-1, 3, ",", "."), "-1.000")
AssertEqual(t, FormatNumber(-10, 3, ",", "."), "-10.000")
AssertEqual(t, FormatNumber(-100, 3, ",", "."), "-100.000")
AssertEqual(t, FormatNumber(-1000, 3, ",", "."), "-1,000.000")
AssertEqual(t, FormatNumber(-10000, 3, ",", "."), "-10,000.000")
AssertEqual(t, FormatNumber(-100000, 3, ",", "."), "-100,000.000")
AssertEqual(t, FormatNumber(-1000000, 3, ",", "."), "-1,000,000.000")
AssertEqual(t, FormatNumber(1, 3, ",", "."), "1.000")
AssertEqual(t, FormatNumber(10, 3, ",", "."), "10.000")
AssertEqual(t, FormatNumber(100, 3, ",", "."), "100.000")
AssertEqual(t, FormatNumber(1000, 3, ",", "."), "1,000.000")
AssertEqual(t, FormatNumber(10000, 3, ",", "."), "10,000.000")
AssertEqual(t, FormatNumber(100000, 3, ",", "."), "100,000.000")
AssertEqual(t, FormatNumber(1000000, 3, ",", "."), "1,000,000.000")
AssertEqual(t, FormatNumber(1000000, 10, " ", "."), "1 000 000.0000000000")
AssertEqual(t, FormatNumber(1000000, 10, " ", "."), "1 000 000.0000000000")
AssertEqual(t, FormatNumber(uint(1000000), 3, ",", "."), "1,000,000.000")
AssertEqual(t, FormatNumber(big.NewRat(77777777, 3), 3, ",", "."), "25,925,925.667")
AssertEqual(t, FormatNumber(big.NewRat(-77777777, 3), 3, ",", "."), "-25,925,925.667")
AssertEqual(t, FormatNumber(big.NewRat(-7777777, 3), 3, ",", "."), "-2,592,592.333")
AssertEqual(t, FormatNumber(big.NewRat(-777776, 3), 3, ",", "."), "-259,258.667")
func() {
defer func() {
recover()
}()
FormatNumber(false, 3, ",", ".") // panic: Unsupported type - bool
}()
func() {
defer func() {
recover()
}()
FormatNumber(big.NewInt(1), 3, ",", ".") // panic: Unsupported type - *big.Int
}()
}
func TestFormatNumberInt(t *testing.T) {
AssertEqual(t, FormatNumberInt(-1, 3, ",", "."), "-1.000")
AssertEqual(t, FormatNumberInt(-10, 3, ",", "."), "-10.000")
AssertEqual(t, FormatNumberInt(-100, 3, ",", "."), "-100.000")
AssertEqual(t, FormatNumberInt(-1000, 3, ",", "."), "-1,000.000")
AssertEqual(t, FormatNumberInt(-10000, 3, ",", "."), "-10,000.000")
AssertEqual(t, FormatNumberInt(-100000, 3, ",", "."), "-100,000.000")
AssertEqual(t, FormatNumberInt(-1000000, 3, ",", "."), "-1,000,000.000")
AssertEqual(t, FormatNumberInt(1, 3, ",", "."), "1.000")
AssertEqual(t, FormatNumberInt(10, 3, ",", "."), "10.000")
AssertEqual(t, FormatNumberInt(100, 3, ",", "."), "100.000")
AssertEqual(t, FormatNumberInt(1000, 3, ",", "."), "1,000.000")
AssertEqual(t, FormatNumberInt(10000, 3, ",", "."), "10,000.000")
AssertEqual(t, FormatNumberInt(100000, 3, ",", "."), "100,000.000")
AssertEqual(t, FormatNumberInt(1000000, 3, ",", "."), "1,000,000.000")
AssertEqual(t, FormatNumberInt(1000000, 10, " ", "."), "1 000 000.0000000000")
AssertEqual(t, FormatNumberInt(1000000, 10, " ", "."), "1 000 000.0000000000")
}
func TestFormatNumberFloat64(t *testing.T) {
AssertEqual(t, FormatNumber(123456789.213123, 3, ",", "."), "123,456,789.213")
AssertEqual(t, FormatNumber(-12345.123123, 5, ",", "."), "-12,345.12312")
AssertEqual(t, FormatNumber(-1234.123123, 5, ",", "."), "-1,234.12312")
AssertEqual(t, FormatNumber(-123.123123, 5, ",", "."), "-123.12312")
AssertEqual(t, FormatNumber(-12.123123, 5, ",", "."), "-12.12312")
AssertEqual(t, FormatNumber(-1.123123, 5, ",", "."), "-1.12312")
}
func TestFormatNumberBigRat(t *testing.T) {
AssertEqual(t, FormatNumberBigRat(big.NewRat(77777777, 3), 3, ",", "."), "25,925,925.667")
AssertEqual(t, FormatNumberBigRat(big.NewRat(-77777777, 3), 3, ",", "."), "-25,925,925.667")
AssertEqual(t, FormatNumberBigRat(big.NewRat(-7777777, 3), 3, ",", "."), "-2,592,592.333")
AssertEqual(t, FormatNumberBigRat(big.NewRat(-777776, 3), 3, ",", "."), "-259,258.667")
}
| mit |
alanning/meteor-package-stubber | package-stubber/community-stubs/iron-router.js | 2794 | // iron-router package
var _emptyFn = function emptyFn () {},
_returnStringFn = function () { return '' },
_returnBooleanFn = function () { return true },
_returnArrayFn = function () { return '' }
RouteController = function () {
this.options = {}
this.router = null
this.route = null
this.path = ''
this.params = []
this.where = 'client'
this.action = null
this.request = {}
this.response = {}
this.next = {}
this._dataValue = {}
this.data = _emptyFn
this.layout = _emptyFn
this.setRegion = _emptyFn
this.clearRegion = _emptyFn
}
RouteController.extend = function () {
return new RouteController()
}
RouteController.prototype = {
constructor: RouteController,
lookupProperty: _returnStringFn,
runHooks: _returnBooleanFn,
action: _emptyFn,
stop: _emptyFn,
extend: function () {
return new RouteController()
},
setLayout: _emptyFn,
ready: _emptyFn,
redirect: _emptyFn,
subscribe: _emptyFn,
lookupLayoutTemplate: _emptyFn,
lookupTemplate: _emptyFn,
lookupRegionTemplates: _emptyFn,
lookupWaitOn: _emptyFn,
render: _emptyFn,
renderRegions: _emptyFn,
wait: _emptyFn,
onBeforeAction: _emptyFn,
onAfterAction: _emptyFn
}
Router = {
HOOK_TYPES: [
'onRun', 'onData', 'onBeforeAction',
'onAfterAction', 'onStop', 'waitOn'
],
LEGACY_HOOK_TYPES: {
'load': 'onRun',
'before': 'onBeforeAction',
'after': 'onAfterAction',
'unload': 'onStop'
},
map: _emptyFn,
configure: _emptyFn,
routes: {},
go: _emptyFn,
before: _emptyFn,
load: _emptyFn,
unload: _emptyFn,
hooks: {
dataNotFound: _emptyFn,
loading: _emptyFn
},
start: _emptyFn,
onRequest: _emptyFn,
run: _emptyFn,
start: _emptyFn,
stop: _emptyFn,
onUnhandled: _emptyFn,
current: _emptyFn,
render: _emptyFn,
autoRender: _emptyFn,
bindEvents: _emptyFn,
unbindEvents: _emptyFn,
onRouteNotFound: _emptyFn,
onClick: _emptyFn,
onBeforeAction: _emptyFn,
onAfterAction: _emptyFn
}
Router.prototype = {
constructor: Router,
configure: _emptyFn,
convertTemplateName: _emptyFn,
convertRouteControllerName: _emptyFn,
setNameConverter: _emptyFn,
addHook: _emptyFn,
getHooks: _emptyFn,
map: _emptyFn,
route: _emptyFn,
dispatch: _emptyFn,
run: _emptyFn,
onUnhandled: _emptyFn,
onRouteNotFound: _emptyFn
}
Route = {}
Route.prototype = {
constructor: Route,
compile: _emptyFn,
params: _returnArrayFn,
normalizePath: _returnStringFn,
test: _returnBooleanFn,
exec: _emptyFn,
resolve: _returnBooleanFn,
path: _returnStringFn,
url: _returnStringFn,
findController: function () {
return RouteController
},
newController: function () {
return new RouteController()
},
getController: function () {
return this.newController()
}
}
| mit |
andyautida14/tamaraw-reservation | src/main/listeners/tour.js | 621 | 'use strict';
module.exports = (function(){
return function(Tour) {
var listener = {
getTours: function(event) {
Tour.findAll({
order: [['for_date', 'ASC']]
}).then(function(tours) {
event.returnValue = tours;
}).catch(function(reason) {
console.log(reason);
});
},
createTour: function(event, tour) {
Tour.create(tour)
.then(function(new_tour) {
event.returnValue = new_tour;
});
},
deleteTour: function(event, tour) {
Tour.destroy({id: tour.id})
.then(function() {
event.returnValue = tour;
});
}
};
return listener;
}
}()); | mit |
richlander/test-repo | foo/Controllers/TestController.cs | 314 | using Microsoft.AspNet.Mvc;
using System.Collections.Generic;
namespace MvcSample.Web
{
[Route("api/[controller]")]
public class TestController : Controller
{
[HttpGet]
public IEnumerable<string> GetAll()
{
return new string[] {"1", "two", "III"};
}
}
} | mit |
fcc-joemcintyre/pollster | app/client/src/components/app/NavAuth.js | 3557 | // @ts-check
import { useState } from 'react';
import { Link, useHistory, useLocation } from 'react-router-dom';
import styled from '@emotion/styled';
import { AppBar, Button, Drawer, IconButton, List, ListItemText, ListItem,
Toolbar, Typography, useMediaQuery }
from '@mui/material';
import MenuIcon from '@mui/icons-material/Menu';
import { GenDialog } from '@cygns/muikit'; // eslint-disable-line no-unused-vars
const items = [
{ key: 1, text: 'Results', to: '/results', exact: true, when: 0 },
{ key: 2, text: 'Manage', to: '/manage', exact: true, when: 0 },
{ key: 3, text: 'Profile', to: '/profile', exact: true, when: 0 },
{ key: 4, text: 'About', to: '/about', exact: true, when: 0 },
{ key: 5, text: 'Logout', to: '/logout', exact: true, when: 0 },
];
export const NavAuth = () => {
const mobile = useMediaQuery ('(max-width: 767px)');
return mobile ? <MobileNav /> : <DesktopNav />;
};
const MobileNav = () => {
const [drawer, setDrawer] = useState (false);
const history = useHistory ();
const path = useLocation ().pathname;
const onToggleDrawer = (open) => (e) => {
// ignore if tab or shift keys to allow keyboard navigation
if (!((e.type === 'keydown') && (e.key === 'Tab' || e.key === 'Shift'))) {
setDrawer (open);
}
};
const menus = (
<List sx={{ backgroundColor: '#000', height: '100%' }}>
{items.map ((a) => (
<Link key={a.key} to={a.to} style={{ textDecoration: 'none' }}>
<ListItem button selected={path === a.to}>
<ListItemText sx={{ color: 'white' }}>{a.text}</ListItemText>
</ListItem>
</Link>
))}
</List>
);
return (
<>
<AppBar position='fixed'>
<StyledToolbar>
<Title onClick={() => history.push ('/')}>
Pollster
</Title>
<IconButton
color='inherit'
aria-label='open drawer'
edge='start'
onClick={onToggleDrawer (true)}
>
<MenuIcon />
</IconButton>
<Drawer
variant='temporary'
anchor='right'
open={drawer}
onClose={onToggleDrawer (false)}
>
<Toolbar sx={{ backgroundColor: (theme) => theme.palette.primary.main }} />
<div
role='presentation'
style={{ height: '100%' }}
onClick={onToggleDrawer (false)}
onKeyDown={onToggleDrawer (false)}
>
{menus}
</div>
</Drawer>
</StyledToolbar>
</AppBar>
<Toolbar />
</>
);
};
const DesktopNav = () => {
const history = useHistory ();
return (
<>
<AppBar position='fixed'>
<StyledToolbar>
<div>
<Title onClick={() => history.push ('/')}>
Pollster
</Title>
</div>
<div>
{ items.map ((a) => (
<Link key={a.key} to={a.to} style={{ textDecoration: 'none' }}>
<Button variant='text' sx={{ color: '#fff' }}>{a.text}</Button>
</Link>
))}
</div>
</StyledToolbar>
</AppBar>
<Toolbar />
</>
);
};
const StyledToolbar = styled (Toolbar)`
display: flex;
justify-content: space-between;
width: 100%;
max-width: 1024px;
margin: 0 auto;
padding: 0 4px;
`;
const Title = styled (Typography)`
font-size: 30px;
vertical-align: top;
text-shadow: 1px 1px 1px #3333ff;
line-height: 1.0;
cursor: pointer;
`;
| mit |
paulcuth/starlight | Gruntfile.js | 4120 |
module.exports = function(grunt) {
require('grunt-task-loader')(grunt);
grunt.initConfig({
starlight: {
test: {
src: 'test/lua/**/*.lua',
dest: 'dist/test/test.lua.js',
options: {
main: 'test-runner.lua',
basePath: 'test/lua'
}
}
},
concat: {
'browser-lib': {
src: [
'dist/browser/runtime.js',
'src/DOMAPI/DOMAPI.js',
'dist/browser/parser.js'
],
dest: 'dist/browser-lib/starlight.js'
}
},
uglify: {
test: {
src: 'dist/test/test.lua.js',
dest: 'dist/test/test.lua.js'
},
runtime: {
src: 'dist/browser/runtime.js',
dest: 'dist/browser/runtime.js'
},
parser: {
src: 'dist/browser/parser.js',
dest: 'dist/browser/parser.js'
},
babel: {
src: 'node_modules/babel/node_modules/babel-core/browser.min.js',
dest: 'dist/browser/babel.js'
},
'browser-lib': {
src: 'dist/browser-lib/starlight.js',
dest: 'dist/browser-lib/starlight.js'
}
},
babel: {
'grunt-plugin-common': {
files: [
{
expand: true,
src: ['*.js'],
cwd: 'src/build-tools/common/',
dest: 'dist/build-tools/grunt-starlight/lib/',
ext: '.js'
}
]
},
runtime: {
files: [
{
expand: true,
src: ['**/*.js'],
cwd: 'src/runtime/',
dest: 'dist/node/',
ext: '.js'
}
]
},
test: {
src: 'dist/test/test.lua.js',
dest: 'dist/test/test.lua.js'
},
parser: {
files: [
{
expand: true,
src: ['index.js'],
cwd: 'src/parser/',
dest: 'dist/node/parser/',
ext: '.js'
}
]
},
'parser-codegen': {
files: [
{
expand: true,
src: ['*.js'],
cwd: 'src/build-tools/common/',
dest: 'dist/node/parser/',
ext: '.js'
}
]
},
},
copy: {
'grunt-plugin': {
files: [
{
expand: true,
src: ['**/*'],
cwd: 'src/build-tools/grunt/',
dest: 'dist/build-tools/grunt-starlight/'
}
],
},
'grunt-plugin-module': {
files: [
{
expand: true,
src: ['**/*'],
cwd: 'dist/build-tools/grunt-starlight/',
dest: 'node_modules/grunt-starlight/'
}
],
},
test: {
src: 'test/index.html',
dest: 'dist/test/index.html'
},
'browser-lib': {
files: {
'dist/browser-lib/index.html': 'src/browser-lib/index.html',
'dist/browser-lib/README.md': 'src/browser-lib/README.md'
}
}
},
browserify: {
runtime: {
files: {
'dist/browser/runtime.js': ['dist/node/index.js'],
}
},
test: {
files: {
'dist/test/test.lua.js': ['dist/test/test.lua.js'],
}
},
parser: {
files: {
'dist/browser/parser.js': ['dist/node/parser/index.js'],
}
}
}
});
grunt.registerTask('grunt-plugin', ['copy:grunt-plugin', 'babel:grunt-plugin-common', 'copy:grunt-plugin-module']);
grunt.registerTask('runtime', ['babel:runtime', 'browserify:runtime', 'uglify:runtime']);
grunt.registerTask('test', ['starlight:test', 'babel:test', 'browserify:test', 'uglify:test', 'copy:test']);
grunt.registerTask('parser', ['babel:parser', 'babel:parser-codegen', 'browserify:parser', 'uglify:parser', 'uglify:babel']);
grunt.registerTask('browser-lib', ['babel:runtime', 'browserify:runtime', 'babel:parser', 'babel:parser-codegen', 'browserify:parser', 'concat:browser-lib', 'uglify:browser-lib', 'copy:browser-lib']);
grunt.registerTask('node-test', ['babel:parser', 'babel:parser-codegen', 'babel:runtime', 'starlight:test', 'babel:test', 'run-test']);
grunt.registerTask('run-test', function () {
global.babel = {
transform: require('./node_modules/babel').transform
};
global.starlight = { config: { env: {
getTimestamp: Date.now.bind(Date),
inspect: console.log.bind(console)
} } };
require('./dist/node/parser/index.js');
require('./dist/node/index.js');
require('./dist/test/test.lua.js');
})
grunt.registerTask('default', ['runtime', 'babel:parser', 'babel:parser-codegen', 'test', 'run-test']);
}; | mit |
GlowstoneMC/GlowstonePlusPlus | src/main/java/net/glowstone/net/rcon/RconFramingHandler.java | 1235 | package net.glowstone.net.rcon;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import java.nio.ByteOrder;
import java.util.List;
/**
* Framing handler that splits up Rcon messages using their length prefix.
*/
public class RconFramingHandler extends ByteToMessageCodec<ByteBuf> {
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
out.order(ByteOrder.LITTLE_ENDIAN).writeInt(msg.readableBytes());
out.writeBytes(msg);
}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
throws Exception {
if (in.readableBytes() < 4) {
return;
}
in.markReaderIndex();
int length = in.order(ByteOrder.LITTLE_ENDIAN).readInt();
if (in.readableBytes() < length) {
in.resetReaderIndex();
return;
}
ByteBuf buf = ctx.alloc().buffer(length);
in.readBytes(buf, length);
out.add(buf.retain());
}
}
| mit |
heisedebaise/tephra | tephra-dao/src/main/java/org/lpw/tephra/dao/orm/hibernate/HibernateOrmImpl.java | 7685 | package org.lpw.tephra.dao.orm.hibernate;
import org.hibernate.LockOptions;
import org.hibernate.query.Query;
import org.lpw.tephra.bean.BeanFactory;
import org.lpw.tephra.dao.Mode;
import org.lpw.tephra.dao.model.Model;
import org.lpw.tephra.dao.orm.OrmSupport;
import org.lpw.tephra.dao.orm.PageList;
import org.lpw.tephra.util.Converter;
import org.lpw.tephra.util.Numeric;
import org.springframework.stereotype.Repository;
import javax.inject.Inject;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
/**
* @author lpw
*/
@Repository("tephra.dao.orm.hibernate")
public class HibernateOrmImpl extends OrmSupport<HibernateQuery> implements HibernateOrm {
private static final String[] ARG = {"?", ":arg", "arg"};
@Inject
private Converter converter;
@Inject
private Numeric numeric;
@Inject
private Session session;
@Override
public <T extends Model> T findById(String dataSource, Class<T> modelClass, String id, boolean lock) {
if (validator.isEmpty(id))
return null;
if (lock) {
session.beginTransaction();
return session.get(getDataSource(dataSource, null, null, modelClass), Mode.Write).get(modelClass, (Object) id, LockOptions.UPGRADE);
}
return session.get(getDataSource(dataSource, null, null, modelClass), Mode.Read).get(modelClass, (Object) id);
}
@SuppressWarnings("unchecked")
@Override
public <T extends Model> T findOne(HibernateQuery query, Object[] args) {
query.size(1).page(1);
List<T> list = createQuery(getDataSource(null, query, null, null), Mode.Read, getQueryHql(query),
args, query.isLocked(), 1, 1).list();
return list.isEmpty() ? null : list.get(0);
}
@SuppressWarnings("unchecked")
@Override
public <T extends Model> PageList<T> query(HibernateQuery query, Object[] args) {
PageList<T> models = BeanFactory.getBean(PageList.class);
if (query.getSize() > 0)
models.setPage(query.isCountable() ? count(query, args) : query.getSize() * query.getPage(), query.getSize(), query.getPage());
models.setList(createQuery(getDataSource(null, query, null, null), Mode.Read, getQueryHql(query),
args, query.isLocked(), models.getSize(), models.getNumber()).list());
return models;
}
@SuppressWarnings("unchecked")
@Override
public <T extends Model> Iterator<T> iterate(HibernateQuery query, Object[] args) {
return createQuery(getDataSource(null, query, null, null), Mode.Read, getQueryHql(query),
args, query.isLocked(), query.getSize(), query.getPage()).list().iterator();
}
private StringBuilder getQueryHql(HibernateQuery query) {
StringBuilder hql = from(new StringBuilder().append("FROM "), query);
if (!validator.isEmpty(query.getWhere()))
hql.append(" WHERE ").append(query.getWhere());
if (!validator.isEmpty(query.getGroup()))
hql.append(" GROUP BY ").append(query.getGroup());
if (!validator.isEmpty(query.getOrder()))
hql.append(" ORDER BY ").append(query.getOrder());
return hql;
}
@Override
public int count(HibernateQuery query, Object[] args) {
StringBuilder hql = from(new StringBuilder().append("SELECT COUNT(*) FROM "), query);
if (!validator.isEmpty(query.getWhere()))
hql.append(" WHERE ").append(query.getWhere());
if (!validator.isEmpty(query.getGroup()))
hql.append(" GROUP BY ").append(query.getGroup());
return numeric.toInt(createQuery(getDataSource(null, query, null, null), Mode.Read, hql, args,
query.isLocked(), 0, 0).list().get(0));
}
@Override
public <T extends Model> boolean save(String dataSource, T model) {
if (model == null) {
logger.warn(null, "要保存的Model为null!");
return false;
}
if (validator.isEmpty(model.getId()))
model.setId(null);
session.get(getDataSource(dataSource, null, null, model.getClass()), Mode.Write).saveOrUpdate(model);
return true;
}
@Override
public <T extends Model> boolean insert(String dataSource, T model) {
if (model == null) {
logger.warn(null, "要保存的Model为null!");
return false;
}
session.get(getDataSource(dataSource, null, null, model.getClass()), Mode.Write).save(model);
return true;
}
@Override
public boolean update(HibernateQuery query, Object[] args) {
StringBuilder hql = from(new StringBuilder().append("UPDATE "), query).append(" SET ").append(query.getSet());
if (!validator.isEmpty(query.getWhere()))
hql.append(" WHERE ").append(query.getWhere());
createQuery(getDataSource(null, query, null, null), Mode.Write, hql, args, query.isLocked(), 0, 0).executeUpdate();
return true;
}
@Override
public <T extends Model> boolean delete(String dataSource, T model) {
if (model == null) {
logger.warn(null, "要删除的Model为null。");
return false;
}
session.get(getDataSource(dataSource, null, null, model.getClass()), Mode.Write).delete(model);
return true;
}
@Override
public boolean delete(HibernateQuery query, Object[] args) {
StringBuilder hql = from(new StringBuilder().append("DELETE "), query);
if (!validator.isEmpty(query.getWhere()))
hql.append(" WHERE ").append(query.getWhere());
createQuery(getDataSource(null, query, null, null), Mode.Write, hql, args, query.isLocked(), 0, 0).executeUpdate();
return true;
}
@Override
public <T extends Model> boolean deleteById(String dataSource, Class<T> modelClass, String id) {
return delete(new HibernateQuery(modelClass).dataSource(dataSource).where("id=?"), new Object[]{id});
}
private StringBuilder from(StringBuilder hql, HibernateQuery query) {
return hql.append(query.getModelClass().getName());
}
private Query createQuery(String dataSource, Mode mode, StringBuilder hql, Object[] args, boolean lock, int size, int page) {
if (logger.isDebugEnable())
logger.debug("hql:{};args:{}", hql, converter.toString(args));
Query query = session.get(dataSource, mode).createQuery(replaceArgs(hql));
if (lock) {
session.beginTransaction();
query.setLockOptions(LockOptions.UPGRADE);
}
if (size > 0)
query.setFirstResult(size * (page - 1)).setMaxResults(size);
if (validator.isEmpty(args))
return query;
for (int i = 0; i < args.length; i++) {
if (args[i] == null)
query.setParameter(ARG[2] + i, args[i]);
else if (args[i] instanceof Collection<?>)
query.setParameterList(ARG[2] + i, (Collection<?>) args[i]);
else if (args[i].getClass().isArray())
query.setParameterList(ARG[2] + i, (Object[]) args[i]);
else
query.setParameter(ARG[2] + i, args[i]);
}
return query;
}
private String replaceArgs(StringBuilder hql) {
for (int i = 0, position; (position = hql.indexOf(ARG[0])) > -1; i++)
hql.replace(position, position + 1, ARG[1] + i);
return hql.toString();
}
@Override
public void fail(Throwable throwable) {
session.fail(throwable);
}
@Override
public void close() {
session.close();
}
}
| mit |
gBritz/ShellProgress | ShellProgress/ProgressBar.cs | 1587 | using System;
namespace ShellProgress
{
public class ProgressBar : IProgressing
{
private readonly Int32 maxValue;
public ProgressBar(Int32 maxValue)
{
if (maxValue <= 0)
throw new ArgumentException("Max value should be greater than zero.", "maxValue");
this.maxValue = maxValue;
BarSize = 10;
ProgressCharacter = '.';
}
public Int32 BarSize { get; set; }
public Char ProgressCharacter { get; set; }
public void Update(int completed)
{
Console.CursorVisible = false;
int left = Console.CursorLeft;
decimal perc = (decimal)completed / (decimal)maxValue;
int chars = (int)Math.Floor(perc / ((decimal)1 / (decimal)BarSize));
string p1 = String.Empty, p2 = String.Empty;
Console.Write('[');
for (int i = 0; i < chars; i++)
p1 += ProgressCharacter;
for (int i = 0; i < BarSize - chars; i++)
p2 += ProgressCharacter;
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(p1);
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.Write(p2);
Console.ResetColor();
Console.Write(']');
Console.Write(" {0}%", (perc * 100).ToString("N2"));
Console.CursorLeft = left;
}
public void Complete()
{
Update(maxValue);
Console.Write(Environment.NewLine);
}
}
} | mit |
PNNL-Comp-Mass-Spec/Atreyu | DevDocs/html API Documentation/namespace_viewer_1_1_properties.js | 270 | var namespace_viewer_1_1_properties =
[
[ "Resources", "class_viewer_1_1_properties_1_1_resources.html", "class_viewer_1_1_properties_1_1_resources" ],
[ "Settings", "class_viewer_1_1_properties_1_1_settings.html", "class_viewer_1_1_properties_1_1_settings" ]
]; | mit |
arturhoo/ADVISe | python/p1.py | 1661 | #coding: utf-8
import MySQLdb
import uuid
try:
from mysql_local_settings import *
except ImportError:
sys.exit("No MySQL settings found!")
conn = MySQLdb.connect( host=host, \
user=user, \
passwd=passwd, \
db=db, \
charset='utf8', \
use_unicode=True, \
init_command='SET NAMES utf8')
c = conn.cursor()
for i in range(2,16):
for j in range(4):
for k in range(0,5-j):
for l in range(0,5-j):
t = (i, j, k, l)
try:
c.execute(''' select count(*)
from id_ec
where ver_estudo = %s
and prefixo = %s
and subidas = %s
and descidas = %s''', t)
except Exception, err:
print err
for row in c:
print "Version: " + str(i) + \
" Prefix: " + str(j) + \
" Subidas: " + str(k) + \
" Descidas: " + str(l) + \
" Count: " + str(row[0])
try:
t1 = (uuid.uuid4(), i, j, k, l, row[0])
c.execute(''' insert into nivel1
values (%s, %s, %s, %s, %s, %s)''', t1)
except Exception, err:
print err
conn.commit()
c.close()
| mit |
continuousphp/tools | tests/ToolsTest/Service/Queue/Adapter/SqsTest.php | 4562 | <?php
/**
* SqsTest.php
*
* @date 05.02.2016
* @author Pascal Paulis <[email protected]>
* @file SqsTest.php
* @license Unauthorized copying of this source code, via any medium is strictly
* prohibited, proprietary and confidential.
*/
namespace ToolsTest\Service\Queue\Adapter;
use Tools\Service\AwsConfig;
use Zend\ServiceManager\ServiceManager;
/**
* Class SqsTest
*
* @package ToolsTest
* @subpackage Service
* @author Pascal Paulis <[email protected]>
* @license Unauthorized copying of this source code, via any medium is strictly
* prohibited, proprietary and confidential.
*/
class SqsTest extends \PHPUnit_Framework_TestCase
{
/** @var \Tools\Service\Queue\Adapter\Sqs */
protected $instance;
/** @var \Zend\ServiceManager\ServiceManager */
protected $serviceManager;
public function setUp()
{
$this->instance = new \Tools\Service\Queue\Adapter\Sqs();
$awsConfig = new AwsConfig();
$awsConfig
->setAwsRegion('eu-west-1')
->setAwsKey('AZERTY1234')
->setAwsSecret('azerty1234!');
$this->instance->setAwsConfig($awsConfig);
$awsMock = $this->getMock('\Aws\Common\Aws');
$this->serviceManager = new ServiceManager();
$this->serviceManager->setService('aws', $awsMock);
$this->instance->setServiceLocator($this->serviceManager);
}
public function testSendMessage()
{
$queueUrl = 'my-queue';
$messageBody = 'gzegezbzrbrzbzrgagaebrzbnrzb';
$sqsMock = $this->getMockBuilder('\Aws\Sqs\SqsClient')
->setMethods(['sendMessage'])
->disableOriginalConstructor()
->getMock();
$sqsMock
->expects($this->any())
->method('sendMessage')
->with([
'QueueUrl' => $queueUrl,
'MessageBody' => $messageBody,
]);
$awsMock = $this->getMock('Aws\Sdk', ['createSqs']);
$awsMock->expects($this->once())
->method('createSqs')
->with([
'version' => '2012-11-05',
'region' => 'eu-west-1',
'credentials' =>
[
'key' => 'AZERTY1234',
'secret' => 'azerty1234!'
]
])
->will($this->returnValue($sqsMock));
$this->serviceManager->setService('Aws\Sdk', $awsMock);
$this->instance->sendMessage($queueUrl, $messageBody);
}
public function testReceiveMessage()
{
$queueUrl = 'my-queue';
$message = [
'Body' => 'message-body',
'ReceiptHandle' => 'receipt-handle'
];
$response =
[
'Messages' =>
[
$message
]
];
$sqsMock = $this->getMockBuilder('\Aws\Sqs\SqsClient')
->setMethods(['receiveMessage'])
->disableOriginalConstructor()
->getMock();
$sqsMock
->expects($this->once())
->method('receiveMessage')
->with(['QueueUrl' => $queueUrl])
->will($this->returnValue($response));
$awsMock = $this->getMock('Aws\Sdk', ['createSqs']);
$awsMock
->expects($this->any())
->method('createSqs')
->will($this->returnValue($sqsMock));
$this->serviceManager->setService('Aws\Sdk', $awsMock);
$response = $this->instance->receiveMessage($queueUrl);
$this->assertEquals($message, $response);
}
public function testDeleteMessage()
{
$queueUrl = 'my-queue';
$receiptHandle = 'receipt-handle';
$sqsMock = $this
->getMockBuilder('\Aws\Sqs\SqsClient')
->setMethods(['deleteMessage'])
->disableOriginalConstructor()
->getMock();
$sqsMock
->expects($this->once())
->method('deleteMessage')
->with(['QueueUrl' => $queueUrl, 'ReceiptHandle' => $receiptHandle]);
$awsMock = $this->getMock('Aws\Sdk', ['createSqs']);
$awsMock
->expects($this->any())
->method('createSqs')
->will($this->returnValue($sqsMock));
$this->serviceManager->setService('Aws\Sdk', $awsMock);
$this->instance->deleteMessage($queueUrl, $receiptHandle);
}
} | mit |
sherlockcoin/growthcoin-resurection | src/qt/guiutil.cpp | 13320 | #include "guiutil.h"
#include "bitcoinaddressvalidator.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "util.h"
#include "init.h"
#include <QString>
#include <QDateTime>
#include <QDoubleValidator>
#include <QFont>
#include <QLineEdit>
#include <QUrl>
#include <QTextDocument> // For Qt::escape
#include <QAbstractItemView>
#include <QApplication>
#include <QClipboard>
#include <QFileDialog>
#include <QDesktopServices>
#include <QThread>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#ifdef WIN32
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "shlwapi.h"
#include "shlobj.h"
#include "shellapi.h"
#endif
namespace GUIUtil {
QString dateTimeStr(const QDateTime &date)
{
return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm");
}
QString dateTimeStr(qint64 nTime)
{
return dateTimeStr(QDateTime::fromTime_t((qint32)nTime));
}
QFont bitcoinAddressFont()
{
QFont font("Monospace");
font.setStyleHint(QFont::TypeWriter);
return font;
}
void setupAddressWidget(QLineEdit *widget, QWidget *parent)
{
widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength);
widget->setValidator(new BitcoinAddressValidator(parent));
widget->setFont(bitcoinAddressFont());
}
void setupAmountWidget(QLineEdit *widget, QWidget *parent)
{
QDoubleValidator *amountValidator = new QDoubleValidator(parent);
amountValidator->setDecimals(8);
amountValidator->setBottom(0.0);
widget->setValidator(amountValidator);
widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
}
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
{
if(uri.scheme() != QString("bitcoin"))
return false;
SendCoinsRecipient rv;
rv.address = uri.path();
rv.amount = 0;
QList<QPair<QString, QString> > items = uri.queryItems();
for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++)
{
bool fShouldReturnFalse = false;
if (i->first.startsWith("req-"))
{
i->first.remove(0, 4);
fShouldReturnFalse = true;
}
if (i->first == "label")
{
rv.label = i->second;
fShouldReturnFalse = false;
}
else if (i->first == "amount")
{
if(!i->second.isEmpty())
{
if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount))
{
return false;
}
}
fShouldReturnFalse = false;
}
if (fShouldReturnFalse)
return false;
}
if(out)
{
*out = rv;
}
return true;
}
bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
{
// Convert bitcoin:// to bitcoin:
//
// Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
// which will lower-case it (and thus invalidate the address).
if(uri.startsWith("bitcoin://"))
{
uri.replace(0, 10, "bitcoin:");
}
QUrl uriInstance(uri);
return parseBitcoinURI(uriInstance, out);
}
QString HtmlEscape(const QString& str, bool fMultiLine)
{
QString escaped = Qt::escape(str);
if(fMultiLine)
{
escaped = escaped.replace("\n", "<br>\n");
}
return escaped;
}
QString HtmlEscape(const std::string& str, bool fMultiLine)
{
return HtmlEscape(QString::fromStdString(str), fMultiLine);
}
void copyEntryData(QAbstractItemView *view, int column, int role)
{
if(!view || !view->selectionModel())
return;
QModelIndexList selection = view->selectionModel()->selectedRows(column);
if(!selection.isEmpty())
{
// Copy first item
QApplication::clipboard()->setText(selection.at(0).data(role).toString());
}
}
QString getSaveFileName(QWidget *parent, const QString &caption,
const QString &dir,
const QString &filter,
QString *selectedSuffixOut)
{
QString selectedFilter;
QString myDir;
if(dir.isEmpty()) // Default to user documents location
{
myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
}
else
{
myDir = dir;
}
QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter);
/* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */
QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]");
QString selectedSuffix;
if(filter_re.exactMatch(selectedFilter))
{
selectedSuffix = filter_re.cap(1);
}
/* Add suffix if needed */
QFileInfo info(result);
if(!result.isEmpty())
{
if(info.suffix().isEmpty() && !selectedSuffix.isEmpty())
{
/* No suffix specified, add selected suffix */
if(!result.endsWith("."))
result.append(".");
result.append(selectedSuffix);
}
}
/* Return selected suffix if asked to */
if(selectedSuffixOut)
{
*selectedSuffixOut = selectedSuffix;
}
return result;
}
Qt::ConnectionType blockingGUIThreadConnection()
{
if(QThread::currentThread() != QCoreApplication::instance()->thread())
{
return Qt::BlockingQueuedConnection;
}
else
{
return Qt::DirectConnection;
}
}
bool checkPoint(const QPoint &p, const QWidget *w)
{
QWidget *atW = qApp->widgetAt(w->mapToGlobal(p));
if (!atW) return false;
return atW->topLevelWidget() == w;
}
bool isObscured(QWidget *w)
{
return !(checkPoint(QPoint(0, 0), w)
&& checkPoint(QPoint(w->width() - 1, 0), w)
&& checkPoint(QPoint(0, w->height() - 1), w)
&& checkPoint(QPoint(w->width() - 1, w->height() - 1), w)
&& checkPoint(QPoint(w->width() / 2, w->height() / 2), w));
}
void openDebugLogfile()
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
/* Open debug.log with the associated application */
if (boost::filesystem::exists(pathDebug))
QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string())));
}
ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) :
QObject(parent), size_threshold(size_threshold)
{
}
bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
{
if(evt->type() == QEvent::ToolTipChange)
{
QWidget *widget = static_cast<QWidget*>(obj);
QString tooltip = widget->toolTip();
if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip))
{
// Prefix <qt/> to make sure Qt detects this as rich text
// Escape the current message as HTML and replace \n by <br>
tooltip = "<qt/>" + HtmlEscape(tooltip, true);
widget->setToolTip(tooltip);
return true;
}
}
return QObject::eventFilter(obj, evt);
}
#ifdef WIN32
boost::filesystem::path static StartupShortcutPath()
{
return GetSpecialFolderPath(CSIDL_STARTUP) / "GrowthCoin.lnk";
}
bool GetStartOnSystemStartup()
{
// check for Bitcoin.lnk
return boost::filesystem::exists(StartupShortcutPath());
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
// If the shortcut exists already, remove it for updating
boost::filesystem::remove(StartupShortcutPath());
if (fAutoStart)
{
CoInitialize(NULL);
// Get a pointer to the IShellLink interface.
IShellLink* psl = NULL;
HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL,
CLSCTX_INPROC_SERVER, IID_IShellLink,
reinterpret_cast<void**>(&psl));
if (SUCCEEDED(hres))
{
// Get the current executable path
TCHAR pszExePath[MAX_PATH];
GetModuleFileName(NULL, pszExePath, sizeof(pszExePath));
TCHAR pszArgs[5] = TEXT("-min");
// Set the path to the shortcut target
psl->SetPath(pszExePath);
PathRemoveFileSpec(pszExePath);
psl->SetWorkingDirectory(pszExePath);
psl->SetShowCmd(SW_SHOWMINNOACTIVE);
psl->SetArguments(pszArgs);
// Query IShellLink for the IPersistFile interface for
// saving the shortcut in persistent storage.
IPersistFile* ppf = NULL;
hres = psl->QueryInterface(IID_IPersistFile,
reinterpret_cast<void**>(&ppf));
if (SUCCEEDED(hres))
{
WCHAR pwsz[MAX_PATH];
// Ensure that the string is ANSI.
MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH);
// Save the link by calling IPersistFile::Save.
hres = ppf->Save(pwsz, TRUE);
ppf->Release();
psl->Release();
CoUninitialize();
return true;
}
psl->Release();
}
CoUninitialize();
return false;
}
return true;
}
#elif defined(LINUX)
// Follow the Desktop Application Autostart Spec:
// http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html
boost::filesystem::path static GetAutostartDir()
{
namespace fs = boost::filesystem;
char* pszConfigHome = getenv("XDG_CONFIG_HOME");
if (pszConfigHome) return fs::path(pszConfigHome) / "autostart";
char* pszHome = getenv("HOME");
if (pszHome) return fs::path(pszHome) / ".config" / "autostart";
return fs::path();
}
boost::filesystem::path static GetAutostartFilePath()
{
return GetAutostartDir() / "GrowthCoin.desktop";
}
bool GetStartOnSystemStartup()
{
boost::filesystem::ifstream optionFile(GetAutostartFilePath());
if (!optionFile.good())
return false;
// Scan through file for "Hidden=true":
std::string line;
while (!optionFile.eof())
{
getline(optionFile, line);
if (line.find("Hidden") != std::string::npos &&
line.find("true") != std::string::npos)
return false;
}
optionFile.close();
return true;
}
bool SetStartOnSystemStartup(bool fAutoStart)
{
if (!fAutoStart)
boost::filesystem::remove(GetAutostartFilePath());
else
{
char pszExePath[MAX_PATH+1];
memset(pszExePath, 0, sizeof(pszExePath));
if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1)
return false;
boost::filesystem::create_directories(GetAutostartDir());
boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc);
if (!optionFile.good())
return false;
// Write a bitcoin.desktop file to the autostart directory:
optionFile << "[Desktop Entry]\n";
optionFile << "Type=Application\n";
optionFile << "Name=GrowthCoin\n";
optionFile << "Exec=" << pszExePath << " -min\n";
optionFile << "Terminal=false\n";
optionFile << "Hidden=false\n";
optionFile.close();
}
return true;
}
#else
// TODO: OSX startup stuff; see:
// https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html
bool GetStartOnSystemStartup() { return false; }
bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
#endif
HelpMessageBox::HelpMessageBox(QWidget *parent) :
QMessageBox(parent)
{
header = tr("GrowthCoin-Qt") + " " + tr("version") + " " +
QString::fromStdString(FormatFullVersion()) + "\n\n" +
tr("Usage:") + "\n" +
" GrowthCoin-qt [" + tr("command-line options") + "] " + "\n";
coreOptions = QString::fromStdString(HelpMessage());
uiOptions = tr("UI options") + ":\n" +
" -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" +
" -min " + tr("Start minimized") + "\n" +
" -splash " + tr("Show splash screen on startup (default: 1)") + "\n";
setWindowTitle(tr("GrowthCoin-Qt"));
setTextFormat(Qt::PlainText);
// setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider.
setText(header + QString(QChar(0x2003)).repeated(50));
setDetailedText(coreOptions + "\n" + uiOptions);
}
void HelpMessageBox::printToConsole()
{
// On other operating systems, the expected action is to print the message to the console.
QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions;
fprintf(stdout, "%s", strUsage.toStdString().c_str());
}
void HelpMessageBox::showOrPrint()
{
#if defined(WIN32)
// On Windows, show a message box, as there is no stderr/stdout in windowed applications
exec();
#else
// On other operating systems, print help text to console
printToConsole();
#endif
}
} // namespace GUIUtil
| mit |
blumug/georges | server/publications/tags.js | 163 | Meteor.publish('tags', function() {
return Tags.find();
});
Meteor.publish('user-tags', function() {
return UserTags.find({
userId: this.userId
});
});
| mit |
yotsuashi/cbtrainer | tool/training-cnv.rb | 1430 | # -*- coding: utf-8 -*-
require 'csv'
require 'json'
#
class Training < Hash
#
def initialize(keys, values)
@weight = 0
@params = Hash.new
keys.each_with_index { |key, i|
value = values[i]
case key
when '[name]'
self[:name] = value
when '[card1]', '[card2]', '[card3]'
self[:cards] ||= Array.new
if value
self[:cards].push(value)
end
when '[option]'
case value
when 'GK'
self[:isGk] = true
when 'PERFORMANCE'
self[:isPerformance] = true
end
when '疲労', 'ディフェンス', 'オフェンス'
@params[key] = Integer(value)
else
value = Integer(value)
if value < 0
self[:hasMinus] = true
end
@params[key] = value
@weight += value
end
}
@params['キック+'] =
@params['シュート'] + @params['キック']
@params['テクニック+'] =
@params['キープ'] + @params['タックル'] + @params['トラップ']
self[:params] = @params
self[:defaultWeight] = @weight * 100 - @params['疲労']
end
end
#
keys = nil
trainings = Array.new
CSV.foreach(ARGV[0]) { |row|
if !keys
keys = row
elsif row[0]
trainings.push(Training.new(keys, row))
end
}
#
puts("TRAININGS = #{JSON.pretty_generate(trainings)};")
puts(trainings.collect { |training| training[:sum] }.max)
| mit |
asiaon123/examples | examples-ds/src/main/java/com/gyz/examples/ds/tree/Tree.java | 351 | package com.gyz.examples.ds.tree;
/**
* Created by YaZhou.Gu on 2018/2/27.
*/
public interface Tree<E> {
void addRoot(E e);
void addChild(E e, E parent);
void remove(E e);
void removeAll();
void clear();
// update
E get(int index);
boolean contains(E e);
boolean isEmpty();
}
| mit |
FlyingTopHat/PoliceUK.NET | PoliceUK/Entities/Neighbourhood/NeighbourhoodTeamMember.cs | 1024 | namespace PoliceUk.Entities.Neighbourhood
{
using System.Runtime.Serialization;
/// <summary>
/// Description of a member of a Neighbourhood Team
/// </summary>
[DataContract]
public class NeighbourhoodTeamMember
{
/// <summary>
/// Name of the Neighbourhood Team Member.
/// </summary>
[DataMember(Name = "name")]
public string Name { get; set; }
/// <summary>
/// Rank of the Neighbourhood Team Member (i.e. "Sgt" or "PC").
/// </summary>
[DataMember(Name = "rank")]
public string Rank { get; set; }
/// <summary>
/// Bio of the Neighbourhood Team Member (if available).
/// </summary>
[DataMember(Name = "bio")]
public string Bio { get; set; }
/// <summary>
/// Contact details of the Neighbourhood Team Member.
/// </summary>
[DataMember(Name = "contact_details")]
public ContactDetails ContactDetails { get; set; }
}
}
| mit |
KristianOellegaard/django-health-check | health_check/contrib/celery_ping/__init__.py | 126 | import django
if django.VERSION < (3, 2):
default_app_config = 'health_check.contrib.celery_ping.apps.HealthCheckConfig'
| mit |
kodmunki/ku4js-workers | example/scripts/example/bin/example-workers-uncompressed.js | 515 | (function(l){
function calculator() { }
calculator.prototype = {
calculateNumberOfAnswers: function(iteration){
var answers = $.list(), i = 0, value = 0;
while(iteration > i++) {
var answer = $.math.round(Math.random() * Math.random() * 10, -5);
answers.add(answer);
}
answers.each(function(item){
return value += item
});
return $.math.round(value, -3);
}
};
$.calculator = function(){ return new calculator(); };
})();
| mit |
hliang71/jmeter-amq-plugin | src/main/java/com/hliang/jmeter/protocol/amqp/AMQPSampler.java | 18117 | package com.icix.jmeter.protocol.amqp;
import java.io.IOException;
import java.util.*;
import java.security.*;
import org.apache.jmeter.samplers.AbstractSampler;
import org.apache.jmeter.testelement.ThreadListener;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.AMQP.Queue.BindOk;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.apache.commons.lang.StringUtils;
public abstract class AMQPSampler extends AbstractSampler implements ThreadListener {
/**
*
*/
private static final long serialVersionUID = 8788563225815907169L;
public static final boolean DEFAULT_EXCHANGE_DURABLE = true;
public static final boolean DEFAULT_EXCHANGE_REDECLARE = false;
public static final boolean DEFAULT_QUEUE_REDECLARE = false;
public static final int DEFAULT_PORT = 5672;
public static final String DEFAULT_PORT_STRING = Integer.toString(DEFAULT_PORT);
public static final int DEFAULT_TIMEOUT = 1000;
public static final String DEFAULT_TIMEOUT_STRING = Integer.toString(DEFAULT_TIMEOUT);
public static final int DEFAULT_ITERATIONS = 1;
public static final String DEFAULT_ITERATIONS_STRING = Integer.toString(DEFAULT_ITERATIONS);
private static final Logger log = LoggingManager.getLoggerForClass();
//++ These are JMX names, and must not be changed
private static final String EXCHANGE = "AMQPSampler.Exchange";
private static final String EXCHANGE_TYPE = "AMQPSampler.ExchangeType";
private static final String EXCHANGE_DURABLE = "AMQPSampler.ExchangeDurable";
private static final String EXCHANGE_REDECLARE = "AMQPSampler.ExchangeRedeclare";
private static final String QUEUE = "AMQPSampler.Queue";
private static final String ROUTING_KEY = "AMQPSampler.RoutingKey";
private static final String VIRUTAL_HOST = "AMQPSampler.VirtualHost";
private static final String HOST = "AMQPSampler.Host";
private static final String PORT = "AMQPSampler.Port";
private static final String SSL = "AMQPSampler.SSL";
private static final String USERNAME = "AMQPSampler.Username";
private static final String PASSWORD = "AMQPSampler.Password";
private static final String TIMEOUT = "AMQPSampler.Timeout";
private static final String ITERATIONS = "AMQPSampler.Iterations";
private static final String MESSAGE_TTL = "AMQPSampler.MessageTTL";
private static final String QUEUE_DURABLE = "AMQPSampler.QueueDurable";
private static final String QUEUE_REDECLARE = "AMQPSampler.Redeclare";
private static final String QUEUE_EXCLUSIVE = "AMQPSampler.QueueExclusive";
private static final String QUEUE_AUTO_DELETE = "AMQPSampler.QueueAutoDelete";
private static final int DEFAULT_HEARTBEAT = 1;
private transient ConnectionFactory factory;
private transient Connection connection;
private transient String replyTo;
protected AMQPSampler(){
factory = new ConnectionFactory();
factory.setRequestedHeartbeat(DEFAULT_HEARTBEAT);
}
protected boolean initChannel() throws IOException, NoSuchAlgorithmException, KeyManagementException {
Channel consumerChannel = this.getConsumerChannel();
Channel publisherChannel = this.getPublisherChannel();
boolean changeToRedeclare = false;
if(this.getExchangeRedeclare() || this.getPublisherExchangeRedeclare())
{
synchronized(DEFAULT_PORT_STRING)
{
changeToRedeclare = (!this.getExchangeRedeclare().equals(this.getConsumerRedeclareFlag())) || (!this.getPublisherExchangeRedeclare().equals(this.getPublisherRedeclareFlag()));
if(changeToRedeclare)
{
this.setConsumerRedeclareFlag(this.getExchangeRedeclare());
this.setPublisherRedeclareFlag(this.getPublisherExchangeRedeclare());
}
}
}
if(consumerChannel != null && !consumerChannel.isOpen()){
log.warn("consumerChannel " + consumerChannel.getChannelNumber()
+ " closed unexpectedly: ", consumerChannel.getCloseReason());
consumerChannel = null; // so we re-open it below
}
if(publisherChannel != null && !publisherChannel.isOpen()){
log.warn("publisherChannel " + publisherChannel.getChannelNumber()
+ " closed unexpectedly: ", publisherChannel.getCloseReason());
publisherChannel = null; // so we re-open it below
}
if(changeToRedeclare)
{
if(!StringUtils.isBlank(getExchange()))
{
this.deleteExchange();
}
if(!StringUtils.isBlank(getPublisherExchange()))
{
this.deletePublisherExchange();
}
}
if(consumerChannel == null) {
consumerChannel = createChannel();
this.setConsumerChannel(consumerChannel);
//TODO: Break out queue binding
boolean queueConfigured = (getQueue() != null && !getQueue().isEmpty());
if(queueConfigured) {
if (getQueueRedeclare()) {
deleteQueue();
}
AMQP.Queue.DeclareOk declareQueueResp = consumerChannel.queueDeclare(getQueue(), queueDurable(), queueExclusive(), queueAutoDelete(), getQueueArguments());
}
if(!StringUtils.isBlank(getExchange())) { //Use a named exchange
AMQP.Exchange.DeclareOk declareExchangeResp = consumerChannel.exchangeDeclare(getExchange(), getExchangeType(), getExchangeDurable());
if (queueConfigured) {
BindOk ok = consumerChannel.queueBind(getQueue(), getExchange(), getRoutingKey());
this.replyTo = getRoutingKey();
}
}
log.info("bound to:"
+"\n\t queue: " + getQueue()
+"\n\t exchange: " + getExchange()
+"\n\t routing key: " + getRoutingKey()
+"\n\t arguments: " + getQueueArguments()
);
}
if(publisherChannel == null) {
publisherChannel = createChannel();
this.setPublisherChannel(publisherChannel);
if(!StringUtils.isBlank(getPublisherExchange())) { //Use a named exchange
AMQP.Exchange.DeclareOk declarePublisherExchangeResp = publisherChannel.exchangeDeclare(getPublisherExchange(), getPublisherExchangeType(), getPublisherExchangeDurable());
}
log.info("publisher bound to:"
+"\n\t exchange: " + getPublisherExchange());
}
return true;
}
private Map<String, Object> getQueueArguments() {
Map<String, Object> arguments = new HashMap<String, Object>();
if(getMessageTTL() != null && !getMessageTTL().isEmpty())
arguments.put("x-message-ttl", getMessageTTLAsInt());
return arguments;
}
protected abstract Channel getConsumerChannel();
protected abstract void setConsumerChannel(Channel channel);
protected abstract Channel getPublisherChannel();
protected abstract void setPublisherChannel(Channel channel);
protected abstract String getPublisherExchange() ;
protected abstract void setPublisherExchange(String name);
protected abstract String getPublisherExchangeType() ;
protected abstract void setPublisherExchangeType(String name);
protected abstract Boolean getPublisherExchangeDurable() ;
protected abstract void setPublisherExchangeDurable(Boolean content);
protected abstract Boolean getPublisherExchangeRedeclare() ;
protected abstract void setPublisherExchangeRedeclare(Boolean content);
protected abstract String getCorrelationId();
protected abstract void setCorrelationId(String c);
protected abstract String getMessageRoutingKey();
protected abstract void setMessageRoutingKey(String content) ;
protected abstract void setConsumerRedeclareFlag(Boolean b);
protected abstract void setPublisherRedeclareFlag(Boolean b);
protected abstract Boolean getConsumerRedeclareFlag();
protected abstract Boolean getPublisherRedeclareFlag();
// TODO: make this configurable
protected BasicProperties getProperties() {
String uuid = UUID.randomUUID().toString();
AMQP.BasicProperties properties = new BasicProperties("application/json",
null,
null,
1,
0, uuid, null, null,
uuid, new Date(), null, null,
null, null);
return properties;
}
/**
* @return a string for the sampleResult Title
*/
protected String getTitle() {
return this.getName();
}
protected int getTimeoutAsInt() {
if (getPropertyAsInt(TIMEOUT) < 1) {
return DEFAULT_TIMEOUT;
}
return getPropertyAsInt(TIMEOUT);
}
public String getTimeout() {
return getPropertyAsString(TIMEOUT, DEFAULT_TIMEOUT_STRING);
}
public void setTimeout(String s) {
setProperty(TIMEOUT, s);
}
public String getIterations() {
return getPropertyAsString(ITERATIONS, DEFAULT_ITERATIONS_STRING);
}
public void setIterations(String s) {
setProperty(ITERATIONS, s);
}
public int getIterationsAsInt() {
return getPropertyAsInt(ITERATIONS);
}
public String getExchange() {
return getPropertyAsString(EXCHANGE);
}
public void setExchange(String name) {
setProperty(EXCHANGE, name);
}
public String getExchangeType() {
return getPropertyAsString(EXCHANGE_TYPE);
}
public void setExchangeType(String name) {
setProperty(EXCHANGE_TYPE, name);
}
public Boolean getExchangeDurable() {
return getPropertyAsBoolean(EXCHANGE_DURABLE);
}
public void setExchangeDurable(Boolean content) {
setProperty(EXCHANGE_DURABLE, content);
}
public Boolean getExchangeRedeclare() {
return getPropertyAsBoolean(EXCHANGE_REDECLARE);
}
public void setExchangeRedeclare(Boolean content) {
setProperty(EXCHANGE_REDECLARE, content);
}
public String getQueue() {
return getPropertyAsString(QUEUE);
}
public void setQueue(String name) {
setProperty(QUEUE, name);
}
public String getRoutingKey() {
return getPropertyAsString(ROUTING_KEY);
}
public void setRoutingKey(String name) {
setProperty(ROUTING_KEY, name);
}
public String getVirtualHost() {
return getPropertyAsString(VIRUTAL_HOST);
}
public void setVirtualHost(String name) {
setProperty(VIRUTAL_HOST, name);
}
public String getMessageTTL() {
return getPropertyAsString(MESSAGE_TTL);
}
public void setMessageTTL(String name) {
setProperty(MESSAGE_TTL, name);
}
public String getReplyTo() {
return replyTo;
}
public void setReplyTo(String replyTo) {
this.replyTo = replyTo;
}
protected Integer getMessageTTLAsInt() {
if (getPropertyAsInt(MESSAGE_TTL) < 1) {
return null;
}
return getPropertyAsInt(MESSAGE_TTL);
}
public String getHost() {
return getPropertyAsString(HOST);
}
public void setHost(String name) {
setProperty(HOST, name);
}
public String getPort() {
return getPropertyAsString(PORT);
}
public void setPort(String name) {
setProperty(PORT, name);
}
protected int getPortAsInt() {
if (getPropertyAsInt(PORT) < 1) {
return DEFAULT_PORT;
}
return getPropertyAsInt(PORT);
}
public void setConnectionSSL(String content) {
setProperty(SSL, content);
}
public void setConnectionSSL(Boolean value) {
setProperty(SSL, value.toString());
}
public boolean connectionSSL() {
return getPropertyAsBoolean(SSL);
}
public String getUsername() {
return getPropertyAsString(USERNAME);
}
public void setUsername(String name) {
setProperty(USERNAME, name);
}
public String getPassword() {
return getPropertyAsString(PASSWORD);
}
public void setPassword(String name) {
setProperty(PASSWORD, name);
}
/**
* @return the whether or not the queue is durable
*/
public String getQueueDurable() {
return getPropertyAsString(QUEUE_DURABLE);
}
public void setQueueDurable(String content) {
setProperty(QUEUE_DURABLE, content);
}
public void setQueueDurable(Boolean value) {
setProperty(QUEUE_DURABLE, value.toString());
}
public boolean queueDurable(){
return getPropertyAsBoolean(QUEUE_DURABLE);
}
/**
* @return the whether or not the queue is exclusive
*/
public String getQueueExclusive() {
return getPropertyAsString(QUEUE_EXCLUSIVE);
}
public void setQueueExclusive(String content) {
setProperty(QUEUE_EXCLUSIVE, content);
}
public void setQueueExclusive(Boolean value) {
setProperty(QUEUE_EXCLUSIVE, value.toString());
}
public boolean queueExclusive(){
return getPropertyAsBoolean(QUEUE_EXCLUSIVE);
}
/**
* @return the whether or not the queue should auto delete
*/
public String getQueueAutoDelete() {
return getPropertyAsString(QUEUE_AUTO_DELETE);
}
public void setQueueAutoDelete(String content) {
setProperty(QUEUE_AUTO_DELETE, content);
}
public void setQueueAutoDelete(Boolean value) {
setProperty(QUEUE_AUTO_DELETE, value.toString());
}
public boolean queueAutoDelete(){
return getPropertyAsBoolean(QUEUE_AUTO_DELETE);
}
public Boolean getQueueRedeclare() {
return getPropertyAsBoolean(QUEUE_REDECLARE);
}
public void setQueueRedeclare(Boolean content) {
setProperty(QUEUE_REDECLARE, content);
}
protected void cleanup() {
try {
//getChannel().close(); // closing the connection will close the channel if it's still open
this.setConsumerRedeclareFlag(false);
this.setPublisherRedeclareFlag(false);
if(connection != null && connection.isOpen())
connection.close();
} catch (IOException e) {
log.error("Failed to close connection", e);
}
}
@Override
public void threadFinished() {
log.info("AMQPSampler.threadFinished called");
cleanup();
}
@Override
public void threadStarted() {
}
protected Channel createChannel() throws IOException, NoSuchAlgorithmException, KeyManagementException {
log.info("Creating channel " + getVirtualHost()+":"+getPortAsInt());
if (connection == null || !connection.isOpen()) {
factory.setConnectionTimeout(getTimeoutAsInt());
factory.setVirtualHost(getVirtualHost());
factory.setHost(getHost());
factory.setPort(getPortAsInt());
factory.setUsername(getUsername());
factory.setPassword(getPassword());
if (connectionSSL()) {
factory.useSslProtocol("TLS");
}
log.info("RabbitMQ ConnectionFactory using:"
+"\n\t virtual host: " + getVirtualHost()
+"\n\t host: " + getHost()
+"\n\t port: " + getPort()
+"\n\t username: " + getUsername()
+"\n\t password: " + getPassword()
+"\n\t timeout: " + getTimeout()
+"\n\t heartbeat: " + factory.getRequestedHeartbeat()
+"\nin " + this
);
connection = factory.newConnection();
}
Channel channel = connection.createChannel();
if(!channel.isOpen()){
log.fatalError("Failed to open channel: " + channel.getCloseReason().getLocalizedMessage());
}
return channel;
}
protected void deleteQueue() throws IOException, NoSuchAlgorithmException, KeyManagementException {
// use a different channel since channel closes on exception.
Channel channel = createChannel();
try {
log.info("Deleting queue " + getQueue());
channel.queueDelete(getQueue());
}
catch(Exception ex) {
log.debug(ex.toString(), ex);
// ignore it.
}
finally {
if (channel.isOpen()) {
channel.close();
}
}
}
protected void deleteExchange() throws IOException, NoSuchAlgorithmException, KeyManagementException {
// use a different channel since channel closes on exception.
Channel channel = createChannel();
try {
log.info("Deleting exchange " + getExchange());
channel.exchangeDelete(getExchange());
}
catch(Exception ex) {
log.debug(ex.toString(), ex);
// ignore it.
}
finally {
if (channel.isOpen()) {
channel.close();
}
}
}
protected void deletePublisherExchange() throws IOException, NoSuchAlgorithmException, KeyManagementException {
// use a different channel since channel closes on exception.
Channel channel = createChannel();
try {
log.info("Deleting exchange " + getPublisherExchange());
channel.exchangeDelete(getPublisherExchange());
}
catch(Exception ex) {
log.debug(ex.toString(), ex);
// ignore it.
}
finally {
if (channel.isOpen()) {
channel.close();
}
}
}
}
| mit |
dladowitz/rails-testing | db/migrate/20140608184055_add_editor_to_users.rb | 113 | class AddEditorToUsers < ActiveRecord::Migration
def change
add_column :users, :editor, :boolean
end
end
| mit |
pcg79/marvel_api | test/marvel_api/configuration_test.rb | 577 | require 'test_helper'
describe MarvelApi::Configuration do
before do
MarvelApi.reset!
end
it "should have nil default keys" do
assert_nil MarvelApi.api_key
assert_nil MarvelApi.private_key
end
it "allows setting the api key" do
MarvelApi.config do |config|
config.api_key = "new key"
end
assert_equal "new key", MarvelApi.api_key
end
it "allows setting the private key" do
MarvelApi.config do |config|
config.private_key = "new private key"
end
assert_equal "new private key", MarvelApi.private_key
end
end
| mit |
faisal-bhatti/pos | db/migrate/20130703080904_add_cash_register_id_to_payment_method_items.rb | 332 | class AddCashRegisterIdToPaymentMethodItems < ActiveRecord::Migration
def change
add_column :payment_method_items, :cash_register_id, :integer
Vendor.connection.execute("UPDATE payment_method_items SET cash_register_id = orders.cash_register_id from orders WHERE orders.id = payment_method_items.order_id")
end
end
| mit |
rgeyer/rs_selfservice | module/SelfService/test/SelfService/Controller/Api/ProvisionedProductControllerTest.php | 5055 | <?php
namespace SelfServiceTest\Controller\Api;
use Zend\Http\Request;
use Zend\Http\Response;
use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;
class ProvisionedProductControllerTest extends AbstractHttpControllerTestCase {
public function setUp() {
$this->setApplicationConfig(
include __DIR__ . '/../../../../../../config/application.config.php'
);
parent::setUp();
$cli = $this->getApplicationServiceLocator()->get('doctrine.cli');
$cli->setAutoExit(false);
$cli->run(
new \Symfony\Component\Console\Input\ArrayInput(array('odm:schema:drop')),
new \Symfony\Component\Console\Output\NullOutput()
);
$cli->run(
new \Symfony\Component\Console\Input\ArrayInput(array('odm:schema:create')),
new \Symfony\Component\Console\Output\NullOutput()
);
}
/**
* @return \SelfService\Service\Entity\ProvisionedProductService
*/
protected function getProvisionedProductService() {
return $this->getApplicationServiceLocator()->get('SelfService\Service\Entity\ProvisionedProductService');
}
public function testCreateCanBeAccessed() {
\SelfServiceTest\Helpers::disableAuthenticationAndAuthorization($this->getApplicationServiceLocator());
$sm = $this->getApplicationServiceLocator();
$standin_adapter = new \Zend\Cache\Storage\Adapter\Memory();
$sm->setAllowOverride(true);
$sm->setService('cache_storage_adapter', $standin_adapter);
$this->dispatch('/api/provisionedproduct', Request::METHOD_POST);
$this->assertActionName('create');
$this->assertControllerName('selfservice\controller\api\provisionedproduct');
$this->assertResponseStatusCode(201);
$this->assertHasResponseHeader('Location');
$this->assertRegExp(',api/provisionedproduct/[0-9a-z]+,', strval($this->getResponse()));
}
public function testDeleteCanBeAccessed() {
\SelfServiceTest\Helpers::disableAuthenticationAndAuthorization($this->getApplicationServiceLocator());
$this->dispatch('/api/provisionedproduct/1', Request::METHOD_DELETE);
$this->assertResponseStatusCode(501);
}
public function testGetCanBeAccessed() {
\SelfServiceTest\Helpers::disableAuthenticationAndAuthorization($this->getApplicationServiceLocator());
$this->dispatch('/api/provisionedproduct/1', Request::METHOD_GET);
$this->assertResponseStatusCode(501);
}
public function testGetListCanBeAccessed() {
\SelfServiceTest\Helpers::disableAuthenticationAndAuthorization($this->getApplicationServiceLocator());
$this->dispatch('/api/provisionedproduct', Request::METHOD_GET);
$this->assertResponseStatusCode(501);
}
public function testUpdateCanBeAccessed() {
\SelfServiceTest\Helpers::disableAuthenticationAndAuthorization($this->getApplicationServiceLocator());
$this->dispatch('/api/provisionedproduct/1', Request::METHOD_PUT);
$this->assertResponseStatusCode(501);
}
public function testObjectsCanBeAccessed() {
\SelfServiceTest\Helpers::disableAuthenticationAndAuthorization($this->getApplicationServiceLocator());
$sm = $this->getApplicationServiceLocator();
$standin_adapter = new \Zend\Cache\Storage\Adapter\Memory();
$sm->setAllowOverride(true);
$sm->setService('cache_storage_adapter', $standin_adapter);
$provisionedProductService = $this->getProvisionedProductService();
$provisionedProduct = $provisionedProductService->create(array());
$this->dispatch(sprintf('/api/provisionedproduct/%s/objects', $provisionedProduct->id),
Request::METHOD_POST,
array(
'type' => 'rs.deployments',
'href' => 'http://foo.bar.baz'
)
);
$this->assertResponseStatusCode(201);
}
public function testObjectsReturns405OnNonPostMethod() {
\SelfServiceTest\Helpers::disableAuthenticationAndAuthorization($this->getApplicationServiceLocator());
$this->dispatch('/api/provisionedproduct/abc123/objects', Request::METHOD_PUT);
$this->assertResponseStatusCode(405);
}
public function testObjectReturns400WhenTypeIsMissing() {
\SelfServiceTest\Helpers::disableAuthenticationAndAuthorization($this->getApplicationServiceLocator());
$this->dispatch('/api/provisionedproduct/abc123/objects',Request::METHOD_POST,array('href' => 'http://foo.bar.baz'));
$response = strval($this->getResponse());
$this->assertResponseStatusCode(Response::STATUS_CODE_400);
$this->assertContains('missing', strtolower($response));
$this->assertContains('type', strtolower($response));
}
public function testObjectReturns400WhenHrefIsMissing() {
\SelfServiceTest\Helpers::disableAuthenticationAndAuthorization($this->getApplicationServiceLocator());
$this->dispatch('/api/provisionedproduct/abc123/objects',Request::METHOD_POST, array('type' => 'rs.deployments'));
$response = strval($this->getResponse());
$this->assertResponseStatusCode(Response::STATUS_CODE_400);
$this->assertContains('missing', strtolower($response));
$this->assertContains('href', strtolower($response));
}
} | mit |
claudiosanchez/QBank | QBank.Model/IAccountRepository.cs | 198 | using System.Collections.Generic;
namespace QBank.Model
{
public interface IAccountRepository
{
IEnumerable<Account> Accounts();
Account GetById(int id);
}
} | mit |
wwidea/bootstrap_feedbacker | db/migrate/20170306210545_convert_source_url_to_text.rb | 234 | class ConvertSourceUrlToText < ActiveRecord::Migration[5.1]
def up
change_column :bootstrap_feedbacker_remarks, :source_url, :text
end
def down
change_column :bootstrap_feedbacker_remarks, :source_url, :string
end
end
| mit |
frogocomics/SpongeAPI | src/main/java/org/spongepowered/api/data/properties/ApplicableEffect.java | 3275 | /*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.data.properties;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import org.spongepowered.api.data.Property;
import org.spongepowered.api.potion.PotionEffect;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Represents an {@link Property} that applies a set of
* {@link PotionEffect}s on use, consumption, or on equip. The properties
* are not mutable, but can be compared against.
*
* <p>Examples of these properties include: hunger from eating zombie flesh,
* regeneration from a golden apple, etc.</p>
*/
public class ApplicableEffect extends AbstractProperty<String, Set<PotionEffect>> {
/**
* Creates a {@link ApplicableEffect} with a specific set of {@link PotionEffect}s.
*
* @param value The potion effects
*/
public ApplicableEffect(@Nullable Set<PotionEffect> value) {
super(value == null ? ImmutableSet.<PotionEffect>of() : ImmutableSet.copyOf(value));
}
/**
* Creates a {@link ApplicableEffect} with a specific set of {@link PotionEffect}s.
*
* @param value The potion effects
* @param op The operator to use when comparing against other properties
*/
public ApplicableEffect(@Nullable Set<PotionEffect> value, Operator op) {
super(value == null ? ImmutableSet.<PotionEffect>of() : ImmutableSet.copyOf(value), op);
}
@Override
public int compareTo(Property<?, ?> o) {
if (o instanceof ApplicableEffect) {
ApplicableEffect effect = (ApplicableEffect) o;
Set<PotionEffect> set = Sets.newHashSet(effect.getValue());
for (PotionEffect effect1 : this.getValue()) {
if (set.contains(effect1)) {
set.remove(effect1);
} else {
return 1;
}
}
return set.size() > 0 ? -set.size() : 0;
}
return this.getClass().getName().compareTo(o.getClass().getName());
}
}
| mit |
pitpitman/GraduateWork | Java_tutorial/essential/threads/example/Consumer.java | 425 | public class Consumer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Consumer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
int value = 0;
for (int i = 0; i < 10; i++) {
value = cubbyhole.get();
System.out.println("Consumer #" + this.number + " got: " + value);
}
}
}
| mit |
gromver/rx-form | src/permissions/InScenariosPermission.spec.ts | 1040 | declare const jest;
declare const describe;
declare const it;
declare const expect;
declare const require;
import InScenariosPermission from './InScenariosPermission';
import Model from '../Model';
import ValueContext from '../ValueContext';
function getTestModel(attributes?) {
return Model.object(
{},
attributes,
);
}
describe('InScenariosPermission', () => {
it('Should return InScenarios permission. The permission must works properly.', () => {
const permission = InScenariosPermission(['a', 'b']);
const model = getTestModel();
const context = new ValueContext({
model,
path: [],
value: null,
attribute: '',
});
expect(() => permission(context)).toThrow(new Error('InScenarios - you have no access.'));
model.setScenarios('a');
expect(() => permission(context)).not.toThrow();
model.setScenarios('b');
expect(() => permission(context)).not.toThrow();
model.setScenarios(['a', 'b', 'c']);
expect(() => permission(context)).not.toThrow();
});
});
| mit |
buildo/webseed | paths.js | 621 | var path = require('path');
module.exports = {
SRC: path.resolve(__dirname, 'src'),
APP: path.resolve(__dirname, 'src/app'),
THEME: path.resolve(__dirname, 'src/app/theme'),
THEME_FONTS: path.resolve(__dirname, 'src/app/theme/fonts'),
BUILD: path.resolve(__dirname, 'build'),
ASSETS: path.resolve(__dirname, 'assets'),
NODE_MODULES: path.resolve(__dirname, 'node_modules'),
COMPONENTS: path.resolve(__dirname, 'src/app/components'),
BASIC_COMPONENTS: path.resolve(__dirname, 'src/app/components/Basic'),
ROUTES: path.resolve(__dirname, 'src/app/routes'),
VARIABLES_MATCH: /(v|V)ariables\.scss$/
};
| mit |
mstoppert/grr | public/js/select.js | 418 | (function() {
$('#result').on('click', function() {
$(this).find('input').select();
});
var clip = new ZeroClipboard($('#clipboard'), {
moviePath: "js/ZeroClipboard.swf",
hoverClass: "zeroclipboard-is-hover",
activeClass: "zeroclipboard-is-active",
forceHandCursor: true
});
clip.on( 'complete', function(client, args) {
$(this).text('Link copied to clipboard');
});
})(); | mit |
BeSite/jQuery.mmenu | src/addons/sidebar/mmenu.sidebar.ts | 3546 | import Mmenu from '../../core/oncanvas/mmenu.oncanvas';
import OPTIONS from './options';
import * as DOM from '../../_modules/dom';
import * as media from '../../_modules/matchmedia';
import { extend } from '../../_modules/helpers';
export default function (this: Mmenu) {
// Only for off-canvas menus.
if (!this.opts.offCanvas.use) {
return;
}
this.opts.sidebar = this.opts.sidebar || {};
// Extend options.
const options = extend(this.opts.sidebar, OPTIONS);
// Collapsed
if (options.collapsed.use) {
// Make the menu collapsable.
this.bind('initMenu:after', () => {
this.node.menu.classList.add('mm-menu--sidebar-collapsed');
if (
options.collapsed.blockMenu &&
!DOM.children(this.node.menu, '.mm-menu__blocker')[0]
) {
const blocker = DOM.create('a.mm-menu__blocker');
blocker.setAttribute('href', `#${this.node.menu.id}`);
this.node.menu.prepend(blocker);
// Add screenreader support
blocker.title = this.i18n(this.conf.screenReader.openMenu);
// TODO: Keyboard navigation support?
// shouldnt be able to tab inside the menu while it's closed..?
}
});
// En-/disable the collapsed sidebar.
let enable = () => {
this.node.wrpr.classList.add('mm-wrapper--sidebar-collapsed');
};
let disable = () => {
this.node.wrpr.classList.remove('mm-wrapper--sidebar-collapsed');
};
if (typeof options.collapsed.use == 'boolean') {
this.bind('initMenu:after', enable);
} else {
media.add(options.collapsed.use, enable, disable);
}
}
// Expanded
if (options.expanded.use) {
// Make the menu expandable
this.bind('initMenu:after', () => {
this.node.menu.classList.add('mm-menu--sidebar-expanded');
});
let expandedEnabled = false;
// En-/disable the expanded sidebar.
let enable = () => {
expandedEnabled = true;
this.node.wrpr.classList.add('mm-wrapper--sidebar-expanded');
this.open();
};
let disable = () => {
expandedEnabled = false;
this.node.wrpr.classList.remove('mm-wrapper--sidebar-expanded');
this.close();
};
if (typeof options.expanded.use == 'boolean') {
this.bind('initMenu:after', enable);
} else {
media.add(options.expanded.use, enable, disable);
}
// Store exanded state when opening and closing the menu.
this.bind('close:after', () => {
if (expandedEnabled) {
window.sessionStorage.setItem('mmenuExpandedState', 'closed');
}
});
this.bind('open:after', () => {
if (expandedEnabled) {
window.sessionStorage.setItem('mmenuExpandedState', 'open');
}
});
// Set the initial state
let initialState = options.expanded.initial;
const state = window.sessionStorage.getItem('mmenuExpandedState');
switch (state) {
case 'open':
case 'closed':
initialState = state;
break;
}
if (initialState == 'closed') {
this.bind('init:after', () => {
this.close();
});
}
}
}
| mit |
zarqman/can_has_state | lib/can_has_state/machine.rb | 3117 | module CanHasState
module Machine
extend ActiveSupport::Concern
module ClassMethods
def state_machine(column, &block)
d = Definition.new(column, self, &block)
define_method "allow_#{column}?" do |to|
state_machine_allow?(column.to_sym, to.to_s)
end
self.state_machines += [[column.to_sym, d]]
end
def extend_state_machine(column, &block)
sm = state_machines.detect{|(col, _)| col == column}
# |(col, stm)|
raise(ArgumentError, "Unknown state machine #{column}") unless sm
sm[1].extend_machine(&block)
sm
end
end
included do
unless method_defined? :state_machines
class_attribute :state_machines, :instance_writer=>false
self.state_machines = []
end
before_validation :can_has_initial_states
before_validation :can_has_state_triggers
validate :can_has_valid_state_machines
after_save :can_has_deferred_state_triggers if respond_to?(:after_save)
end
private
def can_has_initial_states
state_machines.each do |(column, sm)|
if send(column).blank?
send("#{column}=", sm.initial_state)
end
end
end
def can_has_state_triggers
# skip triggers if any state machine isn't valid
return if can_has_state_errors.any?
@triggers_called ||= {}
state_machines.each do |(column, sm)|
from, to = send("#{column}_was"), send(column)
next if from == to
# skip triggers if they've already been called for this from/to transition
next if @triggers_called[column] == [from, to]
sm.trigger(self, from, to)
# record that triggers were called
@triggers_called[column] = [from, to]
end
end
def can_has_deferred_state_triggers
@triggers_called ||= {}
state_machines.each do |(column, sm)|
# clear record of called triggers
@triggers_called[column] = nil
if respond_to?("#{column}_before_last_save") # rails 5.1+
from, to = send("#{column}_before_last_save"), send(column)
else
from, to = send("#{column}_was"), send(column)
end
next if from == to
sm.trigger(self, from, to, :deferred)
end
end
def can_has_state_errors
err = []
state_machines.each do |(column, sm)|
from, to = send("#{column}_was"), send(column)
next if from == to
if !sm.known?(to)
err << [column, :invalid_state]
elsif !sm.allow?(self, to) #state_machine_allow?(column, to)
err << [column, sm.message(to), {from: from, to: to}]
end
end
err
end
def can_has_valid_state_machines
can_has_state_errors.each do |(column, msg, opts)|
errors.add column, msg, **(opts||{})
end
end
def state_machine_allow?(column, to)
sm = state_machines.detect{|(col, _)| col == column}
# |(col, stm)|
raise("Unknown state machine #{column}") unless sm
sm[1].allow?(self, to)
end
end
end
| mit |
BenPhegan/renderconfig | source/RenderConfig.MSBuild/RenderConfig.cs | 6438 | // Copyright (c) 2010 Ben Phegan
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
using System;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using RenderConfig.Core;
namespace RenderConfig.MSBuild
{
/// <summary>
/// Provides the RenderConfig functionality to MSBuild as a plugin
/// </summary>
public class RenderConfig : Task
{
private string configFile;
private string configuration;
private string outputDirectory;
private Boolean deleteOutputDirectory = true;
private Boolean cleanOutput = false;
private Boolean breakOnNoMatch = false;
private string inputDirectory;
private Boolean preserveSourceStructure = false;
private Boolean subDirectoryEachConfiguration = false;
/// <summary>
/// Gets or sets a value indicating whether a subdirectory will be created for each configuration rendered.
/// </summary>
public Boolean SubDirectoryEachConfiguration
{
get { return this.subDirectoryEachConfiguration;}
set { subDirectoryEachConfiguration = value;}
}
/// <summary>
/// Gets or sets a value indicating whether [preserve source structure] when creating the target files.
/// </summary>
/// <value>
/// <c>true</c> if [preserve source structure]; otherwise, <c>false</c>.
/// </value>
public Boolean PreserveSourceStructure
{
get { return preserveSourceStructure; }
set { preserveSourceStructure = value; }
}
/// <summary>
/// Gets or sets the input directory to use as the base for all relative source file paths.
/// </summary>
/// <value>The input directory.</value>
public string InputDirectory
{
get { return inputDirectory; }
set { inputDirectory = value; }
}
/// <summary>
/// Gets or sets the config file to parse.
/// </summary>
/// <value>The config file.</value>
[Required]
public string ConfigFile
{
get { return configFile; }
set { configFile = value; }
}
/// <summary>
/// Gets or sets the configuration we want to output. Must exist in the configuration file.
/// </summary>
/// <value>The configuration.</value>
[Required]
public string Configuration
{
get { return configuration; }
set { configuration = value; }
}
/// <summary>
/// Gets or sets the config output directory.
/// </summary>
/// <value>The config directory.</value>
public string OutputDirectory
{
get { return outputDirectory; }
set { outputDirectory = value; }
}
/// <summary>
/// Gets or sets a value indicating whether to [delete output directory].
/// </summary>
/// <value>
/// <c>true</c> if [delete output directory]; otherwise, <c>false</c>.
/// </value>
public bool DeleteOutputDirectory
{
get { return deleteOutputDirectory; }
set { deleteOutputDirectory = value; }
}
/// <summary>
/// Gets or sets a value indicating whether to clean the output of the applied xml modifications.
/// </summary>
/// <value><c>true</c> if [clean ouptut]; otherwise, <c>false</c>.</value>
public bool CleanOutput
{
get { return cleanOutput; }
set { cleanOutput = value; }
}
/// <summary>
/// Forces the RenderConfig task to fail if it does not find a match for a particular XPath change
/// </summary>
public bool BreakOnNoMatch
{
get { return breakOnNoMatch; }
set { breakOnNoMatch = value; }
}
/// <summary>
/// When overridden in a derived class, executes the task.
/// </summary>
/// <returns>
/// true if the task successfully executed; otherwise, false.
/// </returns>
public override bool Execute()
{
RenderConfigConfig config = new RenderConfigConfig();
config.BreakOnNoMatch = breakOnNoMatch;
config.CleanOutput = cleanOutput;
config.ConfigFile = configFile;
config.Configuration = configuration;
config.DeleteOutputDirectory = deleteOutputDirectory;
config.OutputDirectory = outputDirectory;
config.InputDirectory = inputDirectory;
config.SubDirectoryEachConfiguration = SubDirectoryEachConfiguration;
config.PreserveSourceStructure = PreserveSourceStructure;
IRenderConfigLogger log = new MSBuildLogger(Log);
Boolean returnVal = true;
try
{
RenderConfigEngine.RunAllConfigurations(config, log);
}
catch (Exception i)
{
log.LogError("Failed to render configuration : " + i.Message);
return false;
}
return returnVal;
}
}
}
| mit |
marcelohg/NasajonWebTeamplateProject | vendor/composer/autoload_real.php | 1665 | <?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit686f8f191939dfbe9c01f3b6b1cfd352
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInit686f8f191939dfbe9c01f3b6b1cfd352', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInit686f8f191939dfbe9c01f3b6b1cfd352', 'loadClassLoader'));
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
$loader->addClassMap($classMap);
}
$loader->register(true);
$includeFiles = require __DIR__ . '/autoload_files.php';
foreach ($includeFiles as $file) {
composerRequire686f8f191939dfbe9c01f3b6b1cfd352($file);
}
return $loader;
}
}
function composerRequire686f8f191939dfbe9c01f3b6b1cfd352($file)
{
require $file;
}
| mit |
brad7928/new.bradlysharpe.com.au | grunt/tasks/optimise.js | 122 | module.exports = function(grunt) {
grunt.registerTask('optimise', [ 'imagemin', 'htmlmin', 'cmq', 'postcss:sass' ]);
};
| mit |
rishii7/vscode | src/vs/workbench/parts/debug/common/debugViewModel.ts | 4023 | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Event, Emitter } from 'vs/base/common/event';
import { CONTEXT_EXPRESSION_SELECTED, IViewModel, IStackFrame, ISession, IThread, IExpression, IFunctionBreakpoint, CONTEXT_BREAKPOINT_SELECTED } from 'vs/workbench/parts/debug/common/debug';
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
export class ViewModel implements IViewModel {
private _focusedStackFrame: IStackFrame;
private _focusedSession: ISession;
private _focusedThread: IThread;
private selectedExpression: IExpression;
private selectedFunctionBreakpoint: IFunctionBreakpoint;
private readonly _onDidFocusSession: Emitter<ISession | undefined>;
private readonly _onDidFocusStackFrame: Emitter<{ stackFrame: IStackFrame, explicit: boolean }>;
private readonly _onDidSelectExpression: Emitter<IExpression>;
private multiSessionView: boolean;
private expressionSelectedContextKey: IContextKey<boolean>;
private breakpointSelectedContextKey: IContextKey<boolean>;
constructor(contextKeyService: IContextKeyService) {
this._onDidFocusSession = new Emitter<ISession | undefined>();
this._onDidFocusStackFrame = new Emitter<{ stackFrame: IStackFrame, explicit: boolean }>();
this._onDidSelectExpression = new Emitter<IExpression>();
this.multiSessionView = false;
this.expressionSelectedContextKey = CONTEXT_EXPRESSION_SELECTED.bindTo(contextKeyService);
this.breakpointSelectedContextKey = CONTEXT_BREAKPOINT_SELECTED.bindTo(contextKeyService);
}
public getId(): string {
return 'root';
}
public get focusedSession(): ISession {
return this._focusedSession;
}
public get focusedThread(): IThread {
if (this._focusedStackFrame) {
return this._focusedStackFrame.thread;
}
if (this._focusedSession) {
const threads = this._focusedSession.getAllThreads();
if (threads && threads.length) {
return threads[threads.length - 1];
}
}
return undefined;
}
public get focusedStackFrame(): IStackFrame {
return this._focusedStackFrame;
}
public setFocus(stackFrame: IStackFrame, thread: IThread, session: ISession, explicit: boolean): void {
let shouldEmit = this._focusedSession !== session || this._focusedThread !== thread || this._focusedStackFrame !== stackFrame;
if (this._focusedSession !== session) {
this._focusedSession = session;
this._onDidFocusSession.fire(session);
}
this._focusedThread = thread;
this._focusedStackFrame = stackFrame;
if (shouldEmit) {
this._onDidFocusStackFrame.fire({ stackFrame, explicit });
}
}
public get onDidFocusSession(): Event<ISession> {
return this._onDidFocusSession.event;
}
public get onDidFocusStackFrame(): Event<{ stackFrame: IStackFrame, explicit: boolean }> {
return this._onDidFocusStackFrame.event;
}
public getSelectedExpression(): IExpression {
return this.selectedExpression;
}
public setSelectedExpression(expression: IExpression) {
this.selectedExpression = expression;
this.expressionSelectedContextKey.set(!!expression);
this._onDidSelectExpression.fire(expression);
}
public get onDidSelectExpression(): Event<IExpression> {
return this._onDidSelectExpression.event;
}
public getSelectedFunctionBreakpoint(): IFunctionBreakpoint {
return this.selectedFunctionBreakpoint;
}
public setSelectedFunctionBreakpoint(functionBreakpoint: IFunctionBreakpoint): void {
this.selectedFunctionBreakpoint = functionBreakpoint;
this.breakpointSelectedContextKey.set(!!functionBreakpoint);
}
public isMultiSessionView(): boolean {
return this.multiSessionView;
}
public setMultiSessionView(isMultiSessionView: boolean): void {
this.multiSessionView = isMultiSessionView;
}
}
| mit |
Musashi178/GenericStl | GenericStl.Tests/TestDataStructures/Vertex.cs | 1307 | using System;
namespace GenericStl.Tests.TestDataStructures
{
public class Vertex : IEquatable<Vertex>
{
private readonly float _x;
private readonly float _y;
private readonly float _z;
public Vertex(float x, float y, float z)
{
_x = x;
_y = y;
_z = z;
}
public float X
{
get { return _x; }
}
public float Y
{
get { return _y; }
}
public float Z
{
get { return _z; }
}
public bool Equals(Vertex other)
{
if (other == null)
{
return false;
}
return Math.Abs(other.X - X) < float.Epsilon && Math.Abs(other.Y - Y) < float.Epsilon && Math.Abs(other.Z - Z) < float.Epsilon;
}
public override int GetHashCode()
{
unchecked
{
var hashCode = X.GetHashCode();
hashCode = (hashCode*397) ^ Y.GetHashCode();
hashCode = (hashCode*397) ^ Z.GetHashCode();
return hashCode;
}
}
public override bool Equals(object other)
{
return Equals(other as Vertex);
}
}
} | mit |
romainneutron/PHPExiftool | lib/PHPExiftool/Driver/Tag/XMPPlus/LicenseEndDate.php | 839 | <?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\XMPPlus;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class LicenseEndDate extends AbstractTag
{
protected $Id = 'LicenseEndDate';
protected $Name = 'LicenseEndDate';
protected $FullName = 'XMP::plus';
protected $GroupName = 'XMP-plus';
protected $g0 = 'XMP';
protected $g1 = 'XMP-plus';
protected $g2 = 'Author';
protected $Type = 'date';
protected $Writable = true;
protected $Description = 'License End Date';
protected $local_g2 = 'Time';
}
| mit |
aurelia/templating | src/element-events.js | 4119 | import {DOM} from 'aurelia-pal';
interface EventHandler {
eventName: string;
bubbles: boolean;
capture: boolean;
dispose: Function;
handler: Function;
}
/**
* Dispatches subscribets to and publishes events in the DOM.
* @param element
*/
export class ElementEvents {
static defaultListenerOptions: boolean | AddEventListenerOptions = true;
constructor(element: EventTarget) {
this.element = element;
this.subscriptions = {};
}
_enqueueHandler(handler: EventHandler): void {
this.subscriptions[handler.eventName] = this.subscriptions[handler.eventName] || [];
this.subscriptions[handler.eventName].push(handler);
}
_dequeueHandler(handler: EventHandler): EventHandler {
let index;
let subscriptions = this.subscriptions[handler.eventName];
if (subscriptions) {
index = subscriptions.indexOf(handler);
if (index > -1) {
subscriptions.splice(index, 1);
}
}
return handler;
}
/**
* Dispatches an Event on the context element.
* @param eventName
* @param detail
* @param bubbles
* @param cancelable
*/
publish(eventName: string, detail?: Object = {}, bubbles?: boolean = true, cancelable?: boolean = true) {
let event = DOM.createCustomEvent(eventName, {cancelable, bubbles, detail});
this.element.dispatchEvent(event);
}
/**
* Adds and Event Listener on the context element.
* @return Returns the eventHandler containing a dispose method
*/
subscribe(eventName: string, handler: Function, captureOrOptions?: boolean | AddEventListenerOptions): EventHandler {
if (typeof handler === 'function') {
if (captureOrOptions === undefined) {
captureOrOptions = ElementEvents.defaultListenerOptions;
}
const eventHandler = new EventHandlerImpl(this, eventName, handler, captureOrOptions, false);
return eventHandler;
}
return undefined;
}
/**
* Adds an Event Listener on the context element, that will be disposed on the first trigger.
* @return Returns the eventHandler containing a dispose method
*/
subscribeOnce(eventName: string, handler: Function, captureOrOptions?: boolean | AddEventListenerOptions): EventHandler {
if (typeof handler === 'function') {
if (captureOrOptions === undefined) {
captureOrOptions = ElementEvents.defaultListenerOptions;
}
const eventHandler = new EventHandlerImpl(this, eventName, handler, captureOrOptions, true);
return eventHandler;
}
return undefined;
}
/**
* Removes all events that are listening to the specified eventName.
* @param eventName
*/
dispose(eventName: string): void {
if (eventName && typeof eventName === 'string') {
let subscriptions = this.subscriptions[eventName];
if (subscriptions) {
while (subscriptions.length) {
let subscription = subscriptions.pop();
if (subscription) {
subscription.dispose();
}
}
}
} else {
this.disposeAll();
}
}
/**
* Removes all event handlers.
*/
disposeAll() {
for (let key in this.subscriptions) {
this.dispose(key);
}
}
}
class EventHandlerImpl {
constructor(owner: ElementEvents, eventName: string, handler: Function, captureOrOptions: boolean, once: boolean) {
this.owner = owner;
this.eventName = eventName;
this.handler = handler;
// For compat with interface
this.capture = typeof captureOrOptions === 'boolean' ? captureOrOptions : captureOrOptions.capture;
this.bubbles = !this.capture;
this.captureOrOptions = captureOrOptions;
this.once = once;
owner.element.addEventListener(eventName, this, captureOrOptions);
owner._enqueueHandler(this);
}
handleEvent(e) {
// To keep `undefined` as context, same as the old way
const fn = this.handler;
fn(e);
if (this.once) {
this.dispose();
}
}
dispose() {
this.owner.element.removeEventListener(this.eventName, this, this.captureOrOptions);
this.owner._dequeueHandler(this);
this.owner = this.handler = null;
}
}
| mit |
WaywardGame/developertools | out/action/helpers/CopyStats.d.ts | 94 | import Entity from "entity/Entity";
export default function (from: Entity, to: Entity): void;
| mit |
php-api-clients/github | src/Resource/Git/Tree.php | 1104 | <?php declare(strict_types=1);
namespace ApiClients\Client\Github\Resource\Git;
use ApiClients\Foundation\Hydrator\Annotation\Collection;
use ApiClients\Foundation\Hydrator\Annotation\EmptyResource;
use ApiClients\Foundation\Resource\AbstractResource;
/**
* @Collection(
* tree="Git\NamedBlob"
* )
* @EmptyResource("Git\EmptyTree")
*/
abstract class Tree extends AbstractResource implements TreeInterface
{
/**
* @var string
*/
protected $sha;
/**
* @var string
*/
protected $url;
/**
* @var array
*/
protected $tree;
/**
* @var bool
*/
protected $truncated;
/**
* @return string
*/
public function sha(): string
{
return $this->sha;
}
/**
* @return string
*/
public function url(): string
{
return $this->url;
}
/**
* @return array
*/
public function tree(): array
{
return $this->tree;
}
/**
* @return bool
*/
public function truncated(): bool
{
return $this->truncated;
}
}
| mit |
blodstone/CCS590v2 | collinsHead/fig/basic/BipartiteMatcher.java | 9140 | package fig.basic;
import java.util.*;
/**
* An implementation of the classic hungarian algorithm for the assignment problem.
*
* Copyright 2007 Gary Baker (GPL v3)
* @author gbaker
* Modified by pliang 12/28/07, 11/26/08
*/
public class BipartiteMatcher {
public double[][] copy(double[][] matrix) {
double[][] newMatrix = new double[matrix.length][matrix[0].length];
for(int i = 0; i < matrix.length; i++)
for(int j = 0; j < matrix[i].length; j++)
newMatrix[i][j] = matrix[i][j];
return newMatrix;
}
public int[] findMaxWeightAssignment(double[][] matrix) {
matrix = copy(matrix);
for(int i = 0; i < matrix.length; i++)
for(int j = 0; j < matrix[i].length; j++)
matrix[i][j] = -matrix[i][j];
return findBestAssignment(matrix);
}
public int[] findMinWeightAssignment(double[][] matrix) {
matrix = copy(matrix);
return findBestAssignment(matrix);
}
// Finds a minimum weight assignment
// WARNING: modifies matrix
public int[] findBestAssignment(double[][] matrix) {
// subtract minumum value from rows and columns to create lots of zeroes
reduceMatrix(matrix);
// non negative values are the index of the starred or primed zero in the row or column
int[] starsByRow = new int[matrix.length]; Arrays.fill(starsByRow,-1);
int[] starsByCol = new int[matrix[0].length]; Arrays.fill(starsByCol,-1);
int[] primesByRow = new int[matrix.length]; Arrays.fill(primesByRow,-1);
// 1s mean covered, 0s mean not covered
int[] coveredRows = new int[matrix.length];
int[] coveredCols = new int[matrix[0].length];
// star any zero that has no other starred zero in the same row or column
initStars(matrix, starsByRow, starsByCol);
coverColumnsOfStarredZeroes(starsByCol,coveredCols);
while (!allAreCovered(coveredCols)) {
int[] primedZero = primeSomeUncoveredZero(matrix, primesByRow, coveredRows, coveredCols);
while (primedZero == null) {
// keep making more zeroes until we find something that we can prime (i.e. a zero that is uncovered)
makeMoreZeroes(matrix,coveredRows,coveredCols);
primedZero = primeSomeUncoveredZero(matrix, primesByRow, coveredRows, coveredCols);
}
// check if there is a starred zero in the primed zero's row
int columnIndex = starsByRow[primedZero[0]];
if (-1 == columnIndex){
// if not, then we need to increment the zeroes and start over
incrementSetOfStarredZeroes(primedZero, starsByRow, starsByCol, primesByRow);
Arrays.fill(primesByRow,-1);
Arrays.fill(coveredRows,0);
Arrays.fill(coveredCols,0);
coverColumnsOfStarredZeroes(starsByCol,coveredCols);
} else {
// cover the row of the primed zero and uncover the column of the starred zero in the same row
coveredRows[primedZero[0]] = 1;
coveredCols[columnIndex] = 0;
}
}
// ok now we should have assigned everything
// take the starred zeroes in each column as the correct assignments
int[] assign = new int[starsByCol.length];
for(int i = 0; i < starsByCol.length; i++)
assign[starsByCol[i]] = i;
return assign;
/*int[][] retval = new int[matrix.length][];
for (int i = 0; i < starsByCol.length; i++) {
retval[i] = new int[]{starsByCol[i],i};
}
return retval;*/
}
private boolean allAreCovered(int[] coveredCols) {
for (int covered : coveredCols) {
if (0 == covered) return false;
}
return true;
}
/**
* the first step of the hungarian algorithm
* is to find the smallest element in each row
* and subtract it's values from all elements
* in that row
*
* @return the next step to perform
*/
private void reduceMatrix(double[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
// find the min value in the row
double minValInRow = Double.MAX_VALUE;
for (int j = 0; j < matrix[i].length; j++) {
if (minValInRow > matrix[i][j]) {
minValInRow = matrix[i][j];
}
}
// subtract it from all values in the row
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] -= minValInRow;
}
}
for (int i = 0; i < matrix[0].length; i++) {
double minValInCol = Double.MAX_VALUE;
for (int j = 0; j < matrix.length; j++) {
if (minValInCol > matrix[j][i]) {
minValInCol = matrix[j][i];
}
}
for (int j = 0; j < matrix.length; j++) {
matrix[j][i] -= minValInCol;
}
}
}
/**
* init starred zeroes
*
* for each column find the first zero
* if there is no other starred zero in that row
* then star the zero, cover the column and row and
* go onto the next column
*
* @param costMatrix
* @param starredZeroes
* @param coveredRows
* @param coveredCols
* @return the next step to perform
*/
private void initStars(double costMatrix[][], int[] starsByRow, int[] starsByCol) {
int [] rowHasStarredZero = new int[costMatrix.length];
int [] colHasStarredZero = new int[costMatrix[0].length];
for (int i = 0; i < costMatrix.length; i++) {
for (int j = 0; j < costMatrix[i].length; j++) {
if (0 == costMatrix[i][j] && 0 == rowHasStarredZero[i] && 0 == colHasStarredZero[j]) {
starsByRow[i] = j;
starsByCol[j] = i;
rowHasStarredZero[i] = 1;
colHasStarredZero[j] = 1;
break; // move onto the next row
}
}
}
}
/**
* just marke the columns covered for any coluimn containing a starred zero
* @param starsByCol
* @param coveredCols
*/
private void coverColumnsOfStarredZeroes(int[] starsByCol, int[] coveredCols) {
for (int i = 0; i < starsByCol.length; i++) {
coveredCols[i] = -1 == starsByCol[i] ? 0 : 1;
}
}
/**
* finds some uncovered zero and primes it
* @param matrix
* @param primesByRow
* @param coveredRows
* @param coveredCols
* @return
*/
private int[] primeSomeUncoveredZero(double matrix[][], int[] primesByRow,
int[] coveredRows, int[] coveredCols) {
// find an uncovered zero and prime it
for (int i = 0; i < matrix.length; i++) {
if (1 == coveredRows[i]) continue;
for (int j = 0; j < matrix[i].length; j++) {
// if it's a zero and the column is not covered
if (0 == matrix[i][j] && 0 == coveredCols[j]) {
// ok this is an unstarred zero
// prime it
primesByRow[i] = j;
return new int[]{i,j};
}
}
}
return null;
}
/**
*
* @param unpairedZeroPrime
* @param starsByRow
* @param starsByCol
* @param primesByRow
*/
private void incrementSetOfStarredZeroes(int[] unpairedZeroPrime, int[] starsByRow, int[] starsByCol, int[] primesByRow) {
// build the alternating zero sequence (prime, star, prime, star, etc)
int i, j = unpairedZeroPrime[1];
Set<int[]> zeroSequence = new LinkedHashSet<int[]>();
zeroSequence.add(unpairedZeroPrime);
boolean paired = false;
do {
i = starsByCol[j];
paired = -1 != i && zeroSequence.add(new int[]{i,j});
if (!paired) break;
j = primesByRow[i];
paired = -1 != j && zeroSequence.add(new int[]{ i, j });
} while (paired);
// unstar each starred zero of the sequence
// and star each primed zero of the sequence
for (int[] zero : zeroSequence) {
if (starsByCol[zero[1]] == zero[0]) {
starsByCol[zero[1]] = -1;
starsByRow[zero[0]] = -1;
}
if (primesByRow[zero[0]] == zero[1]) {
starsByRow[zero[0]] = zero[1];
starsByCol[zero[1]] = zero[0];
}
}
}
private void makeMoreZeroes(double[][] matrix, int[] coveredRows, int[] coveredCols) {
// find the minimum uncovered value
double minUncoveredValue = Double.MAX_VALUE;
for (int i = 0; i < matrix.length; i++) {
if (0 == coveredRows[i]) {
for (int j = 0; j < matrix[i].length; j++) {
if (0 == coveredCols[j] && matrix[i][j] < minUncoveredValue) {
minUncoveredValue = matrix[i][j];
}
}
}
}
// add the min value to all covered rows
for (int i = 0; i < coveredRows.length; i++) {
if (1 == coveredRows[i]) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] += minUncoveredValue;
}
}
}
// subtract the min value from all uncovered columns
for (int i = 0; i < coveredCols.length; i++) {
if (0 == coveredCols[i]) {
for (int j = 0; j < matrix.length; j++) {
matrix[j][i] -= minUncoveredValue;
}
}
}
}
public static void main(String[] args) {
//double[][] mat = { { 3 } };
//double[][] mat = { { 3, 0 }, { 0, 3 } };
double[][] mat = {
{ 3, 3, 0 },
{ 3, 3, 0 },
{ 0, 5, 0 },
};
int[] assign = new BipartiteMatcher().findBestAssignment(mat);
for(int i = 0; i < assign.length; i++)
System.out.println(i + " => " + assign[i]);
}
}
| mit |
ucsd-ccbb/jupyter-genomics | src/dnaSeq/VAPr/variantannotation/tests/test_parse_csv.py | 2088 | import unittest
import sys
#quick and dirty way of importing functions
from variantannotation import csv_to_df
sys.path.append('/Users/carlomazzaferro/Documents/Code/variant-annotation/variantannotation')
file_name = "/Users/carlomazzaferro/Desktop/CSV to be tested/Tumor_targeted_processed.csv"
sample_list = csv_to_df.open_and_parse("/Users/carlomazzaferro/Documents/Bioinformatics Internship/Python Codes/test data/UnitTestData/test_MiniCsv.csv")
sample_df = csv_to_df.parse_to_df(sample_list)
class OpenParseTest(unittest.TestCase):
def setUp(self):
self.data = file_name
def test_csv_read_data_headers(self):
list2 = csv_to_df.open_and_parse(self.data)
self.assertEqual(
['Chr', 'Start', 'End', 'Ref', 'Alt', 'Func.knownGene', 'Gene.knownGene', 'GeneDetail.knownGene',
'ExonicFunc.knownGene', 'AAChange.knownGene', 'tfbsConsSites', 'cytoBand', 'targetScanS',
'genomicSuperDups', 'gwasCatalog', 'esp6500siv2_all', '1000g2015aug_all', 'PopFreqMax', '1000G2012APR_ALL',
'1000G2012APR_AFR', '1000G2012APR_AMR', '1000G2012APR_ASN', '1000G2012APR_EUR', 'ESP6500si_ALL',
'ESP6500si_AA', 'ESP6500si_EA', 'CG46', 'clinvar_20140929', 'cosmic70', 'nci60', 'Otherinfo'],
list2[0]
)
def test_parse_to_df(self):
self.assertEqual(list(sample_df.columns), list(csv_to_df.parse_to_df(sample_list).columns))
def test_parse_csv_chunks(self):
list3 = csv_to_df.open_and_parse_chunks(self.data, 1000, 0)
list2 = csv_to_df.open_and_parse(self.data)
self.assertEqual(len(list3[0:1000]), len(list2[0:1000]))
"""
def test_csv_read_data_points(self):
self.assertEqual(read_data(self.data)[1][7], '87')
def test_get_min_score_difference(self):
self.assertEqual(get_min_score_difference(self.parsed_data), 1)
def test_get_team(self):
index_value = get_min_score_difference(self.parsed_data)
self.assertEqual(get_team(index_value), 'Liverpool')
"""
if __name__ == '__main__':
unittest.main() | mit |
mitelg/sw-cli-tools | src/Extensions/Shopware/AutoUpdate/Bootstrap.php | 3337 | <?php
/**
* (c) shopware AG <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Shopware\AutoUpdate;
use Humbug\SelfUpdate\Updater;
use Shopware\AutoUpdate\Command\RollbackCommand;
use Shopware\AutoUpdate\Command\SelfUpdateCommand;
use ShopwareCli\Application\ConsoleAwareExtension;
use ShopwareCli\Application\ContainerAwareExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* Provides self update capability
*/
class Bootstrap implements ConsoleAwareExtension, ContainerAwareExtension
{
/** @var ContainerBuilder */
protected $container;
/**
* {@inheritdoc}
*/
public function setContainer(ContainerBuilder $container)
{
$this->container = $container;
if (!$this->isPharFile()) {
return;
}
$this->populateContainer($container);
}
/**
* {@inheritdoc}
*/
public function getConsoleCommands()
{
if (!$this->isPharFile()) {
return [];
}
if ($this->checkUpdateOnRun()) {
$this->runUpdate();
}
return [
new SelfUpdateCommand($this->container->get('updater')),
new RollbackCommand($this->container->get('updater')),
];
}
/**
* Checks if script is run as phar archive and manifestUrl is available
*/
public function isPharFile(): bool
{
$toolPath = $this->container->get('path_provider')->getCliToolPath();
return strpos($toolPath, 'phar:') !== false;
}
/**
* @param ContainerBuilder $container
*/
private function populateContainer($container)
{
$container->set('updater', $this->createUpdater());
}
private function createUpdater(): Updater
{
$config = $this->container->get('config');
$updateConfig = $config['update'];
$pharUrl = $updateConfig['pharUrl'];
$versionUrl = $updateConfig['vesionUrl'];
if ($versionUrl === null) {
$versionUrl = $updateConfig['versionUrl'];
}
$verifyKey = (bool) $updateConfig['verifyPublicKey'];
$updater = new Updater(null, $verifyKey);
$strategy = $updater->getStrategy();
$strategy->setPharUrl($pharUrl);
$strategy->setVersionUrl($versionUrl);
return $updater;
}
/**
* perform update on the fly
*/
private function runUpdate()
{
$updater = $this->container->get('updater');
try {
$result = $updater->update();
if (!$result) {
return;
}
$new = $updater->getNewVersion();
$old = $updater->getOldVersion();
exit(sprintf(
"Updated from SHA-1 %s to SHA-1 %s. Please run again\n",
$old,
$new
));
} catch (\Exception $e) {
echo "\nCheck your connection\n";
exit(1);
}
}
private function checkUpdateOnRun(): bool
{
$config = $this->container->get('config');
if (!isset($config['update']['checkOnStartup'])) {
return false;
}
return $config['update']['checkOnStartup'];
}
}
| mit |
adcox/ofxPlots | src/interactiveObj.cpp | 12597 | /**
* @author Andrew Cox
* @version July 7, 2016
*
* Copyright (c) 2016 Andrew Cox
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so, subject
* to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
* THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "interactiveObj.hpp"
#include "DataSelectedEvent.hpp"
//-----------------------------------------------------------------------------
// -- *structors --
//-----------------------------------------------------------------------------
/**
* @brief Construct a default InteractiveObject.
* @details This function should be called in the initialization list
* for all derived classes as it initializes several important variables
* and pointers.
*/
InteractiveObj::InteractiveObj(){
if(!areEventsSet)
setEvents(ofEvents());
ofAddListener(DataSelectedEvent::selected, this, &InteractiveObj::dataSelected);
ofAddListener(DataSelectedEvent::deselected, this, &InteractiveObj::dataDeselected);
enableMouseInput();
enableKeyInput();
}//====================================================
/**
* @brief Default destructor.
* @details This function removes all listeners from the object before
* it is destroyed
*/
InteractiveObj::~InteractiveObj(){
ofRemoveListener(DataSelectedEvent::selected, this, &InteractiveObj::dataSelected);
ofRemoveListener(DataSelectedEvent::deselected, this, &InteractiveObj::dataDeselected);
disableKeyInput();
disableMouseInput();
}//=====================================================
//-----------------------------------------------------------------------------
// -- Graphics & Event Loop --
//-----------------------------------------------------------------------------
/**
* @brief A function to set up the object.
* @details By default, this function does
* nothing but can be overridden to provide
* custom behavior
*/
void InteractiveObj::setup(){}
/**
* @brief A function to update the object.
* @details By default, this function does
* nothing but can be overridden to provide
* custom behavior
*/
void InteractiveObj::update(){}
/**
* @brief Call this function to draw the object.
* @details In this base class, this function draws
* only the background and border. This function can be
* overridden to provide custom behavior
*/
void InteractiveObj::draw(){
ofDisableDepthTest();
ofPushStyle();
ofSetColor(bgColor);
ofDrawRectangle(viewport);
if(isMouseInside){
ofNoFill();
ofSetColor(edgeColor);
ofDrawRectangle(viewport);
}
ofPopStyle();
ofEnableDepthTest();
}//====================================================
//-----------------------------------------------------------------------------
// -- Get and Set --
//-----------------------------------------------------------------------------
/**
* @brief Enable mouse input for the plot.
* @details This allows the user to interact with the plot area
*/
void InteractiveObj::enableMouseInput(){
if(!isMouseInputEnabled && events){
ofAddListener(events->mouseMoved, this, &InteractiveObj::mouseMoved);
ofAddListener(events->mousePressed, this, &InteractiveObj::mousePressed);
ofAddListener(events->mouseReleased, this, &InteractiveObj::mouseReleased);
ofAddListener(events->mouseDragged, this, &InteractiveObj::mouseDragged);
}
isMouseInputEnabled = true;
}//====================================================
/**
* @brief Disable mouse input for the plot.
*/
void InteractiveObj::disableMouseInput(){
if(isMouseInputEnabled && events){
ofRemoveListener(events->mouseMoved, this, &InteractiveObj::mouseMoved);
ofRemoveListener(events->mousePressed, this, &InteractiveObj::mousePressed);
ofRemoveListener(events->mouseReleased, this, &InteractiveObj::mouseReleased);
ofRemoveListener(events->mouseDragged, this, &InteractiveObj::mouseDragged);
}
isMouseInputEnabled = false;
}//====================================================
/**
* @brief Enable keyboard input for this object
*/
void InteractiveObj::enableKeyInput(){
if(!isKeyInputEnabled && events){
ofAddListener(events->keyPressed, this, &InteractiveObj::keyPressed);
ofAddListener(events->keyReleased, this, &InteractiveObj::keyReleased);
}
isKeyInputEnabled = true;
}//====================================================
/**
* @brief Disable keyboard input for this object
*/
void InteractiveObj::disableKeyInput(){
if(isKeyInputEnabled && events){
ofRemoveListener(events->keyPressed, this, &InteractiveObj::keyPressed);
ofRemoveListener(events->keyReleased, this, &InteractiveObj::keyReleased);
}
isKeyInputEnabled = false;
}//====================================================
/**
* @brief Determine whether the mouse is hovering over this object
* @return whether or not the mouse is hovering over this object
*/
bool InteractiveObj::isHovered() const { return isMouseInside; }
/**
* @brief Retrieve the position of the bounding viewport rectangle
* @details Position describes the top-left corner in screen coordinates
* @return the position of the bounding viewport rectangle
*/
ofVec2f InteractiveObj::getPosition() const { return viewport.getPosition(); }
/**
* @brief Retrieve the size of the bounding viewport rectangle
* @return the size of the bounding viewport rectangle
*/
ofVec2f InteractiveObj::getSize() const { return ofVec2f(viewport.width, viewport.height); }
/**
* @brief Retrieve the bounding viewport rectangle
* @return the bounding viewport rectangle
*/
ofRectangle InteractiveObj::getViewport() const { return viewport; }
/**
* @brief Set the background color
* @param c background color
*/
void InteractiveObj::setBGColor(ofColor c){ bgColor = c;}
/**
* @brief Set the edge/outline color
* @param c edge color
*/
void InteractiveObj::setEdgeColor(ofColor c){ edgeColor = c;}
/**
* @brief Set the font for the plot area
*
* @param f font to use for the plot
*/
void InteractiveObj::setFont(ofTrueTypeFont f){ font = f; }
/**
* @brief Set the position of the viewport
*
* @param x pixels, screen coordinates
* @param y pixels, screen coordinates
*/
void InteractiveObj::setPosition(float x, float y){
viewport.setPosition(x, y);
}//====================================================
/**
* @brief Set the position of the viewport area
*
* @param pos vector storing (x, y)
* @see setPosition(float, float)
*/
void InteractiveObj::setPosition(ofVec2f pos){
setPosition(pos.x, pos.y);
}//====================================================
/**
* @brief Set the size of the viewport area
*
* @param w width, pixels
* @param h height, pixels
*/
void InteractiveObj::setSize(float w, float h){
viewport.setSize(w, h);
}//====================================================
/**
* @brief Set the size of the viewport area
*
* @param size vector storing (width, height)
* @see setSize(float, float)
*/
void InteractiveObj::setSize(ofVec2f size){
setSize(size.x, size.y);
}//====================================================
void InteractiveObj::setX(float x){ viewport.x = x; }
void InteractiveObj::setY(float y){ viewport.y = y; }
void InteractiveObj::setWidth(float w){ viewport.width = w; }
void InteractiveObj::setHeight(float h){ viewport.height = h; }
//-----------------------------------------------------------------------------
// -- Event Handlers --
//-----------------------------------------------------------------------------
/**
* @brief A function to handle data selection events
* @param args data structure containing information about the event
* @see dataSelectedEventArgs
*/
void InteractiveObj::dataSelected(DataSelectedEventArgs &args){}
/**
* @brief A function to handle data deselection events
* @param args data structure containing information about the event
* @see dataSelectedEventArgs
*/
void InteractiveObj::dataDeselected(DataSelectedEventArgs &args){}
/**
* @brief Handle keyPressed events
* @details This function can be overridden, but should be called
* from the derived class's version to preserve functionality
* provided by this base class.
* @param evt A set of arguments that describe the keyPressed event
*/
void InteractiveObj::keyPressed(ofKeyEventArgs &evt){
heldKey = evt.key;
}//====================================================
/**
* @brief Handle keyReleased events
* @details This function can be overridden, but should be called
* from the derived class's version to preserve functionality
* provided by this base class.
* @param evt A set of arguments that describe the keyReleased event
*/
void InteractiveObj::keyReleased(ofKeyEventArgs &evt){
heldKey = 0;
}//====================================================
/**
* @brief Handle mousePressed events
* @details This function can be overridden, but should be called
* from the derived class's version to preserve functionality
* provided by this base class.
* @param mouse a set of arguments that describes the mousePressed event
*/
void InteractiveObj::mousePressed(ofMouseEventArgs &mouse){
if(viewport.inside(mouse.x, mouse.y)){
mousePressedPt.x = mouse.x;
mousePressedPt.y = mouse.y;
isMousePressedInside = true;
}
}//====================================================
/**
* @brief Handle mouseReleased events
* @details This function can be overridden, but should be called
* from the derived class's version to preserve functionality
* provided by this base class.
* @param mouse a set of arguments that describes the mouseReleased event
*/
void InteractiveObj::mouseReleased(ofMouseEventArgs &mouse){
isMousePressedInside = false;
isMouseDragged = false;
}//====================================================
/**
* @brief Handle mouseDragged events
* @details This function can be overridden, but should be called
* from the derived class's version to preserve functionality
* provided by this base class.
* @param mouse a set of arguments that describes the mouseDragged event
*/
void InteractiveObj::mouseDragged(ofMouseEventArgs &mouse){
isMouseDragged = true;
}//====================================================
/**
* @brief Handle mousePressed events
* @details This function can be overridden, but should be called
* from the derived class's version to preserve functionality
* provided by this base class.
* @param mouse a set of arguments that describes the mouseMoved event
*/
void InteractiveObj::mouseMoved(ofMouseEventArgs &mouse){
mouseX = mouse.x;
mouseY = mouse.y;
if(viewport.inside(mouse.x, mouse.y)){
isMouseInside = true;
}else{
isMouseInside = false;
}
}//====================================================
//-----------------------------------------------------------------------------
// -- Miscellaneous --
//-----------------------------------------------------------------------------
/**
* @brief Give the camera the event object
* @param evts reference to the window's events object
*/
void InteractiveObj::setEvents(ofCoreEvents & evts){
// If en/disableMouseInput were called within ofApp::setup(),
// mouseInputEnabled will tell us about whether the camera
// mouse input needs to be initialised as enabled or disabled.
// we will still set `events`, so that subsequent enabling
// and disabling can work.
// we need a temporary copy of bMouseInputEnabled, since it will
// get changed by disableMouseInput as a side-effect.
bool wasMouseInputEnabled = isMouseInputEnabled;
disableMouseInput();
events = &evts;
if (wasMouseInputEnabled) {
// note: this will set bMouseInputEnabled to true as a side-effect.
enableMouseInput();
}
areEventsSet = true;
}//==================================================== | mit |
philnash/twilio-node | lib/rest/autopilot/v1/assistant/dialogue.js | 7032 | 'use strict';
/* jshint ignore:start */
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
/* jshint ignore:end */
var Q = require('q'); /* jshint ignore:line */
var _ = require('lodash'); /* jshint ignore:line */
var Page = require('../../../../base/Page'); /* jshint ignore:line */
var values = require('../../../../base/values'); /* jshint ignore:line */
var DialogueList;
var DialoguePage;
var DialogueInstance;
var DialogueContext;
/* jshint ignore:start */
/**
* @description Initialize the DialogueList
* PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact [email protected].
*
* @param {Twilio.Autopilot.V1} version - Version of the resource
* @param {string} assistantSid - The unique ID of the parent Assistant.
*/
/* jshint ignore:end */
DialogueList = function DialogueList(version, assistantSid) {
/* jshint ignore:start */
/**
* @param {string} sid - sid of instance
*
* @returns {Twilio.Autopilot.V1.AssistantContext.DialogueContext}
*/
/* jshint ignore:end */
function DialogueListInstance(sid) {
return DialogueListInstance.get(sid);
}
DialogueListInstance._version = version;
// Path Solution
DialogueListInstance._solution = {assistantSid: assistantSid};
/* jshint ignore:start */
/**
* Constructs a dialogue
*
* @param {string} sid - The sid
*
* @returns {Twilio.Autopilot.V1.AssistantContext.DialogueContext}
*/
/* jshint ignore:end */
DialogueListInstance.get = function get(sid) {
return new DialogueContext(this._version, this._solution.assistantSid, sid);
};
return DialogueListInstance;
};
/* jshint ignore:start */
/**
* Initialize the DialoguePagePLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact [email protected].
*
* @param {V1} version - Version of the resource
* @param {Response<string>} response - Response from the API
* @param {DialogueSolution} solution - Path solution
*
* @returns DialoguePage
*/
/* jshint ignore:end */
DialoguePage = function DialoguePage(version, response, solution) {
// Path Solution
this._solution = solution;
Page.prototype.constructor.call(this, version, response, this._solution);
};
_.extend(DialoguePage.prototype, Page.prototype);
DialoguePage.prototype.constructor = DialoguePage;
/* jshint ignore:start */
/**
* Build an instance of DialogueInstance
*
* @param {DialoguePayload} payload - Payload response from the API
*
* @returns DialogueInstance
*/
/* jshint ignore:end */
DialoguePage.prototype.getInstance = function getInstance(payload) {
return new DialogueInstance(this._version, payload, this._solution.assistantSid);
};
/* jshint ignore:start */
/**
* Initialize the DialogueContextPLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact [email protected].
*
* @property {string} accountSid -
* The unique ID of the Account that created this Field.
* @property {string} assistantSid - The unique ID of the parent Assistant.
* @property {string} sid - The unique ID of the Dialogue
* @property {string} data - The dialogue session object as json
* @property {string} url - The url
*
* @param {V1} version - Version of the resource
* @param {DialoguePayload} payload - The instance payload
* @param {sid} assistantSid - The unique ID of the parent Assistant.
* @param {sid_like} sid - The sid
*/
/* jshint ignore:end */
DialogueInstance = function DialogueInstance(version, payload, assistantSid,
sid) {
this._version = version;
// Marshaled Properties
this.accountSid = payload.account_sid; // jshint ignore:line
this.assistantSid = payload.assistant_sid; // jshint ignore:line
this.sid = payload.sid; // jshint ignore:line
this.data = payload.data; // jshint ignore:line
this.url = payload.url; // jshint ignore:line
// Context
this._context = undefined;
this._solution = {assistantSid: assistantSid, sid: sid || this.sid, };
};
Object.defineProperty(DialogueInstance.prototype,
'_proxy', {
get: function() {
if (!this._context) {
this._context = new DialogueContext(this._version, this._solution.assistantSid, this._solution.sid);
}
return this._context;
}
});
/* jshint ignore:start */
/**
* fetch a DialogueInstance
*
* @param {function} [callback] - Callback to handle processed record
*
* @returns {Promise} Resolves to processed DialogueInstance
*/
/* jshint ignore:end */
DialogueInstance.prototype.fetch = function fetch(callback) {
return this._proxy.fetch(callback);
};
/* jshint ignore:start */
/**
* Produce a plain JSON object version of the DialogueInstance for serialization.
* Removes any circular references in the object.
*
* @returns Object
*/
/* jshint ignore:end */
DialogueInstance.prototype.toJSON = function toJSON() {
let clone = {};
_.forOwn(this, function(value, key) {
if (!_.startsWith(key, '_') && ! _.isFunction(value)) {
clone[key] = value;
}
});
return clone;
};
/* jshint ignore:start */
/**
* Initialize the DialogueContextPLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact [email protected].
*
* @param {V1} version - Version of the resource
* @param {sid_like} assistantSid - The assistant_sid
* @param {sid_like} sid - The sid
*/
/* jshint ignore:end */
DialogueContext = function DialogueContext(version, assistantSid, sid) {
this._version = version;
// Path Solution
this._solution = {assistantSid: assistantSid, sid: sid, };
this._uri = _.template(
'/Assistants/<%= assistantSid %>/Dialogues/<%= sid %>' // jshint ignore:line
)(this._solution);
};
/* jshint ignore:start */
/**
* fetch a DialogueInstance
*
* @param {function} [callback] - Callback to handle processed record
*
* @returns {Promise} Resolves to processed DialogueInstance
*/
/* jshint ignore:end */
DialogueContext.prototype.fetch = function fetch(callback) {
var deferred = Q.defer();
var promise = this._version.fetch({uri: this._uri, method: 'GET'});
promise = promise.then(function(payload) {
deferred.resolve(new DialogueInstance(
this._version,
payload,
this._solution.assistantSid,
this._solution.sid
));
}.bind(this));
promise.catch(function(error) {
deferred.reject(error);
});
if (_.isFunction(callback)) {
deferred.promise.nodeify(callback);
}
return deferred.promise;
};
module.exports = {
DialogueList: DialogueList,
DialoguePage: DialoguePage,
DialogueInstance: DialogueInstance,
DialogueContext: DialogueContext
};
| mit |
wongatech/remi | ReMi.Api/BusinessLogic/ReMi.BusinessEntities/ExecPoll/CommandStateType.cs | 180 | namespace ReMi.BusinessEntities.ExecPoll
{
public enum CommandStateType
{
NotRegistered = 1,
Waiting,
Running,
Success,
Failed
}
}
| mit |
EFSKnyc/Programy-Java | BEZ KOMENTARZA_komunikat.java | 117 | class Program
{
public static void main(String[] args)
{
System.out.println("Hello world!");
}
}
| mit |
juui/juui.org | tasks/test.js | 154 | 'use strict';
var gulp = require('gulp');
function test(done) {
console.log('Testing');
done();
}
gulp.task('test', test);
module.exports = gulp;
| mit |
mnipper/AndroidSurvey | src/org/adaptlab/chpir/android/survey/QuestionFragments/ListOfItemsQuestionFragment.java | 2434 | package org.adaptlab.chpir.android.survey.QuestionFragments;
import java.util.ArrayList;
import org.adaptlab.chpir.android.survey.QuestionFragment;
import org.adaptlab.chpir.android.survey.R;
import org.adaptlab.chpir.android.survey.Models.Option;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
public abstract class ListOfItemsQuestionFragment extends QuestionFragment {
private ArrayList<EditText> mResponses;
protected abstract EditText createEditText();
protected void createQuestionComponent(ViewGroup questionComponent) {
mResponses = new ArrayList<EditText>();
for (Option option : getQuestion().options()) {
final TextView optionText = new TextView(getActivity());
optionText.setText(option.getText());
questionComponent.addView(optionText);
EditText editText = createEditText();
editText.setHint(R.string.free_response_edittext);
editText.setTypeface(getInstrument().getTypeFace(getActivity().getApplicationContext()));
questionComponent.addView(editText);
mResponses.add(editText);
editText.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
saveResponse();
}
// Required by interface
public void beforeTextChanged(CharSequence s, int start,
int count, int after) { }
public void afterTextChanged(Editable s) { }
});
}
}
@Override
protected String serialize() {
String serialized = "";
for (int i = 0; i < mResponses.size(); i++) {
serialized += mResponses.get(i).getText().toString();
if (i < mResponses.size() - 1) serialized += LIST_DELIMITER;
}
return serialized;
}
@Override
protected void deserialize(String responseText) {
if (responseText.equals("")) return;
String[] listOfResponses = responseText.split(LIST_DELIMITER);
for (int i = 0; i < listOfResponses.length; i++) {
if (mResponses.size() > i)
mResponses.get(i).setText(listOfResponses[i]);
}
}
}
| mit |
dianbaer/grain | httpclient/src/test/java/org/grain/httpclient/HttpUtilTest.java | 1916 | //package org.grain.httpclient;
//
//import static org.junit.Assert.assertEquals;
//
//import java.io.File;
//import java.io.UnsupportedEncodingException;
//import java.net.URLEncoder;
//import java.util.HashMap;
//
//import org.junit.BeforeClass;
//import org.junit.Test;
//
//public class HttpUtilTest {
//
// @BeforeClass
// public static void setUpBeforeClass() throws Exception {
// HttpUtil.init("UTF-8", null);
// }
//
// @Test
// public void testGet() throws UnsupportedEncodingException {
// byte[] result = HttpUtil.send(null, "http://localhost:8080/httpserver-test/", null, HttpUtil.GET);
// String str = new String(result, "UTF-8");
// System.out.println(str);
// assertEquals(true, str != null);
// }
//
// @Test
// public void testPost() throws UnsupportedEncodingException {
// String str = "{hOpCode: \"1\", userName: \"admin\", userPassword: \"123456\"}";
// byte[] result = HttpUtil.send(str, "http://localhost:8080/httpserver-test/s", null, HttpUtil.POST);
// String returnStr = new String(result, "UTF-8");
// System.out.println(returnStr);
// assertEquals(true, str != null);
// }
//
// @Test
// public void testSendFile() throws UnsupportedEncodingException {
// String tokenId = "38bfecab619b48db8466ea7dd064f0d8";
// String str = "{hOpCode: \"1\", userName: \"dianbaer333\", userPassword: \"123456\"}";
// HashMap<String, String> headMap = new HashMap<String, String>();
// headMap.put("token", tokenId);
// headMap.put("packet", URLEncoder.encode(str, HttpUtil.ENCODE));
// File file = new File("D:\\github\\product\\grain\\httpclient\\src\\test\\resources\\k_nearest_neighbors.png");
// System.out.println(file.exists());
// byte[] result = HttpUtil.sendFile(file, "http://localhost:8080/httpserver-test/s", headMap, HttpUtil.POST);
// String returnStr = new String(result, "UTF-8");
// System.out.println(returnStr);
// assertEquals(true, str != null);
//
// }
//
//}
| mit |
rohit00082002/intro | vendor/autoload.php | 182 | <?php
// autoload.php generated by Composer
require_once __DIR__ . '/composer' . '/autoload_real.php';
return ComposerAutoloaderInit9ce3a7f93aad22dda3e2e92183afb784::getLoader();
| mit |
shashank7200/FreeCodeCamp-Projects | Intermediate Front End Development Projects/twitch-client/src/App.js | 244 | import React, { Component } from 'react';
import Home from './helpers/Home'
import './App.css'
class App extends Component {
render() {
return (
<div className="App">
<Home />
</div>
);
}
}
export default App;
| mit |
kmlewis/_old_stuff | ReferralTracker/MisInfrastructure/Models/MisTeacherClass.cs | 362 | namespace Mock_MisInfrastructure.Models
{
public class Mock_MisTeacherClass
{
public string ClassName { get; set; }
public string Subject { get; set; }
public string StaffCode { get; set; }
public string StaffName { get; set; }
public int PersonId { get; set; }
public int ClassId { get; set; }
}
}
| mit |
cesarAugusto1994/blog3 | web/assets/build/Components/modal.js | 2048 | /**
* Created by cesar on 22/10/16.
*/
$(function () {
var Modal = React.createClass({displayName: "Modal",
componentDidMount: function() {
$(this.getDOMNode)
.modal({backdrop: "static", keyboard: true, show: false});
},
componentWillUnmount: function() {
$(this.getDOMNode)
.off("hidden", this.handleHidden);
},
open: function() {
$(this.getDOMNode).modal("show");
},
close: function() {
$(this.getDOMNode).modal("hide");
},
render: function() {
return (
React.createElement("div", {id: "scheduleentry-modal", className: "modal fade", tabIndex: "-1"},
React.createElement("div", {className: "modal-dialog"},
React.createElement("div", {className: "modal-content"},
React.createElement("div", {className: "modal-header"},
React.createElement("button", {type: "button", className: "close", "data-dismiss": "modal"},
React.createElement("span", null, "×")
),
React.createElement("h4", {className: "modal-title"}, this.props.title)
),
React.createElement("div", {className: "modal-body"},
this.props.children
),
React.createElement("div", {className: "modal-footer"},
React.createElement("button", {type: "button", className: "button is-danger is-outlined is-pulled-left", "data-dismiss": "modal"}, "Cancelar"),
React.createElement("button", {type: "submit", className: "button is-success"}, "Salvar")
)
)
)
)
)
}
});
}); | mit |
OfficeDev/PnP-OfficeAddins | Samples/Outlook.MailCRM/DXDemos.Office365/Properties/AssemblyInfo.cs | 1365 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DXDemos.Office365")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DXDemos.Office365")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6bfb5af2-e92d-4b52-95f3-f472f2e2a419")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
SMUnlimited/sonar-stash | src/test/java/org/sonar/plugins/stash/StashPluginConfigurationTest.java | 2988 | package org.sonar.plugins.stash;
import java.util.Optional;
import org.junit.Test;
import org.sonar.api.CoreProperties;
import org.sonar.api.config.Settings;
import static org.junit.Assert.assertEquals;
public class StashPluginConfigurationTest {
@Test
public void testStashPluginConfiguration_ConstructorAndAccessors() {
Integer SPRI = 1337;
Settings settings = new Settings();
settings.setProperty(StashPlugin.STASH_NOTIFICATION, true);
settings.setProperty(StashPlugin.STASH_PROJECT, "take-over-the-world");
settings.setProperty(StashPlugin.STASH_REPOSITORY, "death-ray");
settings.setProperty(StashPlugin.STASH_PULL_REQUEST_ID, SPRI);
settings.setProperty(StashPlugin.STASH_URL, "https://stash");
settings.setProperty(StashPlugin.STASH_LOGIN, "me");
settings.setProperty(StashPlugin.STASH_USER_SLUG, "mini.me");
settings.setProperty(StashPlugin.STASH_PASSWORD, "unsecure");
settings.setProperty(StashPlugin.STASH_PASSWORD_ENVIRONMENT_VARIABLE, "you-should-not");
settings.setProperty(CoreProperties.LOGIN, "him");
settings.setProperty(CoreProperties.PASSWORD, "notsafe");
settings.setProperty(StashPlugin.STASH_ISSUE_THRESHOLD, 42000);
settings.setProperty(StashPlugin.STASH_TIMEOUT, 42);
settings.setProperty(StashPlugin.STASH_REVIEWER_APPROVAL, true);
settings.setProperty(StashPlugin.STASH_RESET_COMMENTS, false);
settings.setProperty(StashPlugin.STASH_TASK_SEVERITY_THRESHOLD, "Minor");
settings.setProperty(StashPlugin.STASH_INCLUDE_ANALYSIS_OVERVIEW, true);
//Optional getRepositoryRoot() ???
settings.setProperty("sonar.scanAllFiles", false);
StashPluginConfiguration SPC = new StashPluginConfiguration(settings, null);
assertEquals(true, SPC.hasToNotifyStash());
assertEquals("take-over-the-world", SPC.getStashProject());
assertEquals("death-ray", SPC.getStashRepository());
assertEquals(SPRI, SPC.getPullRequestId());
assertEquals("https://stash", SPC.getStashURL());
assertEquals("me", SPC.getStashLogin());
assertEquals("mini.me", SPC.getStashUserSlug());
assertEquals("unsecure", SPC.getStashPassword());
assertEquals("you-should-not", SPC.getStashPasswordEnvironmentVariable());
assertEquals("him", SPC.getSonarQubeLogin());
assertEquals("notsafe", SPC.getSonarQubePassword());
assertEquals(42000, SPC.getIssueThreshold());
assertEquals(42, SPC.getStashTimeout());
assertEquals(true, SPC.canApprovePullRequest());
assertEquals(false, SPC.resetComments());
assertEquals(Optional.of("Minor"), SPC.getTaskIssueSeverityThreshold());
assertEquals(true, SPC.includeAnalysisOverview());
//assertEquals(, SPC.getRepositoryRoot());
assertEquals(false, SPC.scanAllFiles());
settings.setProperty(StashPlugin.STASH_TASK_SEVERITY_THRESHOLD, "NONE");
assertEquals(Optional.empty(), SPC.getTaskIssueSeverityThreshold());
}
} | mit |
OfficialTitcoin/titcoin-wallet | src/qt/sendcoinsdialog.cpp | 9228 | #include "sendcoinsdialog.h"
#include "ui_sendcoinsdialog.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "addressbookpage.h"
#include "optionsmodel.h"
#include "sendcoinsentry.h"
#include "guiutil.h"
#include "askpassphrasedialog.h"
#include "base58.h"
#include <QMessageBox>
#include <QTextDocument>
#include <QScrollBar>
SendCoinsDialog::SendCoinsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SendCoinsDialog),
model(0)
{
ui->setupUi(this);
#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
ui->addButton->setIcon(QIcon());
ui->clearButton->setIcon(QIcon());
ui->sendButton->setIcon(QIcon());
#endif
addEntry();
connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry()));
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
fNewRecipientAllowed = true;
}
void SendCoinsDialog::setModel(WalletModel *model)
{
this->model = model;
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
entry->setModel(model);
}
}
if(model && model->getOptionsModel())
{
setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance());
connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64)));
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
}
}
SendCoinsDialog::~SendCoinsDialog()
{
delete ui;
}
void SendCoinsDialog::on_sendButton_clicked()
{
QList<SendCoinsRecipient> recipients;
bool valid = true;
if(!model)
return;
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
if(entry->validate())
{
recipients.append(entry->getValue());
}
else
{
valid = false;
}
}
}
if(!valid || recipients.isEmpty())
{
return;
}
// Format confirmation message
QStringList formatted;
foreach(const SendCoinsRecipient &rcp, recipients)
{
formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::TIT, rcp.amount), Qt::escape(rcp.label), rcp.address));
}
fNewRecipientAllowed = false;
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"),
tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval != QMessageBox::Yes)
{
fNewRecipientAllowed = true;
return;
}
WalletModel::UnlockContext ctx(model->requestUnlock());
if(!ctx.isValid())
{
// Unlock wallet was cancelled
fNewRecipientAllowed = true;
return;
}
WalletModel::SendCoinsReturn sendstatus = model->sendCoins(recipients);
switch(sendstatus.status)
{
case WalletModel::InvalidAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("The recipient address is not valid, please recheck."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::InvalidAmount:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount to pay must be larger than 0."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::AmountExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount exceeds your balance."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::AmountWithFeeExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("The total exceeds your balance when the %1 transaction fee is included.").
arg(BitcoinUnits::formatWithUnit(BitcoinUnits::TIT, sendstatus.fee)),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::DuplicateAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("Duplicate address found, can only send to each address once per send operation."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::TransactionCreationFailed:
QMessageBox::warning(this, tr("Send Coins"),
tr("Error: Transaction creation failed!"),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::TransactionCommitFailed:
QMessageBox::warning(this, tr("Send Coins"),
tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case WalletModel::Aborted: // User aborted, nothing to do
break;
case WalletModel::OK:
accept();
break;
}
fNewRecipientAllowed = true;
}
void SendCoinsDialog::clear()
{
// Remove entries until only one left
while(ui->entries->count())
{
ui->entries->takeAt(0)->widget()->deleteLater();
}
addEntry();
updateRemoveEnabled();
ui->sendButton->setDefault(true);
}
void SendCoinsDialog::reject()
{
clear();
}
void SendCoinsDialog::accept()
{
clear();
}
SendCoinsEntry *SendCoinsDialog::addEntry()
{
SendCoinsEntry *entry = new SendCoinsEntry(this);
entry->setModel(model);
ui->entries->addWidget(entry);
connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*)));
updateRemoveEnabled();
// Focus the field, so that entry can start immediately
entry->clear();
entry->setFocus();
ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint());
qApp->processEvents();
QScrollBar* bar = ui->scrollArea->verticalScrollBar();
if(bar)
bar->setSliderPosition(bar->maximum());
return entry;
}
void SendCoinsDialog::updateRemoveEnabled()
{
// Remove buttons are enabled as soon as there is more than one send-entry
bool enabled = (ui->entries->count() > 1);
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
entry->setRemoveEnabled(enabled);
}
}
setupTabChain(0);
}
void SendCoinsDialog::removeEntry(SendCoinsEntry* entry)
{
entry->deleteLater();
updateRemoveEnabled();
}
QWidget *SendCoinsDialog::setupTabChain(QWidget *prev)
{
for(int i = 0; i < ui->entries->count(); ++i)
{
SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());
if(entry)
{
prev = entry->setupTabChain(prev);
}
}
QWidget::setTabOrder(prev, ui->addButton);
QWidget::setTabOrder(ui->addButton, ui->sendButton);
return ui->sendButton;
}
void SendCoinsDialog::setAddress(const QString &address)
{
SendCoinsEntry *entry = 0;
// Replace the first entry if it is still unused
if(ui->entries->count() == 1)
{
SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());
if(first->isClear())
{
entry = first;
}
}
if(!entry)
{
entry = addEntry();
}
entry->setAddress(address);
}
void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv)
{
if(!fNewRecipientAllowed)
return;
SendCoinsEntry *entry = 0;
// Replace the first entry if it is still unused
if(ui->entries->count() == 1)
{
SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());
if(first->isClear())
{
entry = first;
}
}
if(!entry)
{
entry = addEntry();
}
entry->setValue(rv);
}
bool SendCoinsDialog::handleURI(const QString &uri)
{
SendCoinsRecipient rv;
// URI has to be valid
if (GUIUtil::parseBitcoinURI(uri, &rv))
{
CBitcoinAddress address(rv.address.toStdString());
if (!address.IsValid())
return false;
pasteEntry(rv);
return true;
}
return false;
}
void SendCoinsDialog::setBalance(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance)
{
Q_UNUSED(unconfirmedBalance);
Q_UNUSED(immatureBalance);
if(!model || !model->getOptionsModel())
return;
int unit = model->getOptionsModel()->getDisplayUnit();
ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance));
}
void SendCoinsDialog::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update labelBalance with the current balance and the current unit
ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->getBalance()));
}
}
| mit |
srycyk/mine | test/support/html_example.rb | 1532 |
class HtmlExample
attr_accessor :content
def initialize(content='')
self.content = content
end
def call(excerpt=nil)
html.sub(/PLACEHOLDER/, excerpt || content)
end
def html
<<-END_OF_HTML
<!doctype html>
<html>
<head>
<title>Example Domain</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style type="text/css">
body {
background-color: #f0f0f2;
margin: 0;
padding: 0;
font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
}
div {
width: 600px;
margin: 5em auto;
padding: 50px;
background-color: #fff;
border-radius: 1em;
}
a:link, a:visited {
color: #38488f;
text-decoration: none;
}
@media (max-width: 700px) {
body {
background-color: #fff;
}
div {
width: auto;
margin: 0 auto;
border-radius: 0;
padding: 1em;
}
}
</style>
</head>
<body>
<div>
<h1>Example Domain</h1>
<p>This domain is established to be used for illustrative examples in documents. You may use this
domain in examples without prior coordination or asking for permission.</p>
<p><a href="http://www.iana.org/domains/example">More information...</a></p>
<div>PLACEHOLDER</div>
</div>
</body>
</html>
END_OF_HTML
end
end
| mit |
surfcoalho/catalogo | src/main/java/com/catalogo/api/dtos/CadastroPFDto.java | 2709 | package com.catalogo.api.dtos;
import java.util.Optional;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.br.CNPJ;
import org.hibernate.validator.constraints.br.CPF;
public class CadastroPFDto {
private Long id;
private String nome;
private String email;
private String senha;
private String cpf;
private Optional<String> valorHora = Optional.empty();
private Optional<String> qtdHorasTrabalhoDia = Optional.empty();
private Optional<String> qtdHorasAlmoco = Optional.empty();
private String cnpj;
public CadastroPFDto() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@NotEmpty(message = "Nome não pode ser vazio.")
@Length(min = 3, max = 200, message = "Nome deve conter entre 3 e 200 caracteres.")
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
@NotEmpty(message = "Email não pode ser vazio.")
@Length(min = 5, max = 200, message = "Email deve conter entre 5 e 200 caracteres.")
@Email(message="Email inválido.")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@NotEmpty(message = "Senha não pode ser vazia.")
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
@NotEmpty(message = "CPF não pode ser vazio.")
@CPF(message="CPF inválido")
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public Optional<String> getValorHora() {
return valorHora;
}
public void setValorHora(Optional<String> valorHora) {
this.valorHora = valorHora;
}
public Optional<String> getQtdHorasTrabalhoDia() {
return qtdHorasTrabalhoDia;
}
public void setQtdHorasTrabalhoDia(Optional<String> qtdHorasTrabalhoDia) {
this.qtdHorasTrabalhoDia = qtdHorasTrabalhoDia;
}
public Optional<String> getQtdHorasAlmoco() {
return qtdHorasAlmoco;
}
public void setQtdHorasAlmoco(Optional<String> qtdHorasAlmoco) {
this.qtdHorasAlmoco = qtdHorasAlmoco;
}
@NotEmpty(message = "CNPJ não pode ser vazio.")
@CNPJ(message="CNPJ inválido.")
public String getCnpj() {
return cnpj;
}
public void setCnpj(String cnpj) {
this.cnpj = cnpj;
}
@Override
public String toString() {
return "FuncionarioDto [id=" + id + ", nome=" + nome + ", email=" + email + ", senha=" + senha + ", cpf=" + cpf
+ ", valorHora=" + valorHora + ", qtdHorasTrabalhoDia=" + qtdHorasTrabalhoDia + ", qtdHorasAlmoco="
+ qtdHorasAlmoco + ", cnpj=" + cnpj + "]";
}
}
| mit |
sprinkle-tool/sprinkle | lib/sprinkle/commands/reconnect.rb | 184 | module Sprinkle
module Commands
class Reconnect < Command
def initialize()
end
def inspect
":RECONNECT"
end
end
end
end | mit |
upfluence/oss-components | index.js | 2048 | /* jshint node: true */
'use strict';
const mergeTrees = require('broccoli-merge-trees');
const Funnel = require('broccoli-funnel');
const fs = require('fs');
const { name, version } = require('./package');
let faPath = 'node_modules/@fortawesome/fontawesome-pro';
if (!fs.existsSync(faPath)) {
faPath = 'node_modules/@fortawesome/fontawesome-free';
}
module.exports = {
name,
version,
isDevelopingAddon: function () {
return true;
},
_registerLessDependencies(app) {
let lessOptions = app.options.lessOptions || {};
if (!lessOptions.paths) {
lessOptions.paths = [];
}
lessOptions.paths.push('node_modules/bootstrap/less', 'node_modules/@upfluence/oss/less');
app.options.lessOptions = lessOptions;
},
included: function (app) {
this._super.included.apply(this, app);
this.hasFontAwesomePro = Object.keys(app.dependencies()).includes('@fortawesome/fontawesome-pro');
this._registerLessDependencies(app);
this.import('node_modules/bootstrap/dist/js/bootstrap.min.js');
this.import('node_modules/countdown.js/lib/countdown.js');
this.import('node_modules/ion-rangeslider/js/ion.rangeSlider.min.js');
this.import('node_modules/ion-rangeslider/css/ion.rangeSlider.min.css');
this.import(`${faPath}/css/all.css`);
this.import(`${faPath}/css/v4-shims.min.css`);
},
treeForPublic() {
let publicTree = this._super.treeForPublic.apply(this, arguments);
let trees = [];
if (publicTree) {
trees.push(publicTree);
}
let publicAssets = ['images', 'fonts', 'upf-icons'];
publicAssets.forEach((assetType) => {
trees.push(
new Funnel(`node_modules/@upfluence/oss/${assetType}/`, {
srcDir: '/',
destDir: `assets/${assetType}`
})
);
});
trees.push(
new Funnel(`${faPath}/webfonts/`, {
srcDir: '/',
include: ['**/*.woff', '**/*.woff2', '**/*.eot', '**/*.ttf', '**/*.svg'],
destDir: '/webfonts'
})
);
return mergeTrees(trees);
}
};
| mit |
mybuilder/cronos-bundle | MyBuilderCronosBundle.php | 145 | <?php
namespace MyBuilder\Bundle\CronosBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class MyBuilderCronosBundle extends Bundle
{
}
| mit |
Weisses/Ebonheart-Mods | ViesCraft/Archived/1.9.4 - 1976/src/main/java/com/viesis/viescraft/common/entity/airshipcolors/EntityAirshipV4Core.java | 43707 | package com.viesis.viescraft.common.entity.airshipcolors;
import java.util.List;
import com.viesis.viescraft.api.FuelVC;
import com.viesis.viescraft.common.utils.events.EventHandlerAirship;
import com.viesis.viescraft.configs.ViesCraftConfig;
import com.viesis.viescraft.init.InitItemsVC;
import com.viesis.viescraft.network.NetworkHandler;
import com.viesis.viescraft.network.server.v4.MessageGuiV4Default;
import com.viesis.viescraft.network.server.v4.MessageGuiV4ModuleInventoryLarge;
import com.viesis.viescraft.network.server.v4.MessageGuiV4ModuleInventorySmall;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.passive.EntityWaterMob;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.init.SoundEvents;
import net.minecraft.inventory.InventoryHelper;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.datasync.DataParameter;
import net.minecraft.network.datasync.DataSerializers;
import net.minecraft.network.datasync.EntityDataManager;
import net.minecraft.util.EntitySelectors;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.ItemStackHandler;
public class EntityAirshipV4Core extends EntityAirshipBaseVC {
/** Fuel */
protected static final DataParameter<Integer> POWERED = EntityDataManager.<Integer>createKey(EntityAirshipV4Core.class, DataSerializers.VARINT);
protected static final DataParameter<Integer> TOTALPOWERED = EntityDataManager.<Integer>createKey(EntityAirshipV4Core.class, DataSerializers.VARINT);
protected static final DataParameter<Integer> ITEMFUELSTACKPOWERED = EntityDataManager.<Integer>createKey(EntityAirshipV4Core.class, DataSerializers.VARINT);
protected static final DataParameter<Integer> ITEMFUELSTACKSIZEPOWERED = EntityDataManager.<Integer>createKey(EntityAirshipV4Core.class, DataSerializers.VARINT);
/** Passive Modules */
protected static final DataParameter<Boolean> MODULE_INVENTORY_SMALL = EntityDataManager.<Boolean>createKey(EntityAirshipV4Core.class, DataSerializers.BOOLEAN);
protected static final DataParameter<Boolean> MODULE_INVENTORY_LARGE = EntityDataManager.<Boolean>createKey(EntityAirshipV4Core.class, DataSerializers.BOOLEAN);
protected static final DataParameter<Boolean> MODULE_FUEL_INFINITE = EntityDataManager.<Boolean>createKey(EntityAirshipV4Core.class, DataSerializers.BOOLEAN);
protected static final DataParameter<Boolean> MODULE_SPEED_MINOR = EntityDataManager.<Boolean>createKey(EntityAirshipV4Core.class, DataSerializers.BOOLEAN);
protected static final DataParameter<Boolean> MODULE_SPEED_MAJOR = EntityDataManager.<Boolean>createKey(EntityAirshipV4Core.class, DataSerializers.BOOLEAN);
public String customName;
private int dropNumber;
/** Fuel */
public int airshipBurnTime;
public int airshipTotalBurnTime;
public int itemFuelStackSize;
public int itemFuelStack;
/** Passive Modules */
public static boolean moduleInventorySmall;
public static boolean moduleInventoryLarge;
public static boolean moduleFuelInfinite;
public static boolean moduleSpeedMinor;
public static boolean moduleSpeedMajor;
/** My capabilities inventory */
public ItemStackHandler inventory;
private int size = 20;
public float AirshipSpeedTurn = 0.18F * (ViesCraftConfig.v4AirshipSpeed / 100);
public float AirshipSpeedForward = 0.0125F * (ViesCraftConfig.v4AirshipSpeed / 100);
public float AirshipSpeedUp = 0.0035F * (ViesCraftConfig.v4AirshipSpeed / 100);
public float AirshipSpeedDown = 0.0035F * (ViesCraftConfig.v4AirshipSpeed / 100);
public EntityAirshipV4Core(World worldIn)
{
super(worldIn);
this.ignoreFrustumCheck = true;
this.preventEntitySpawning = true;
this.setSize(1.0F, 0.35F);
this.inventory = new ItemStackHandler(size);
}
public EntityAirshipV4Core(World worldIn, double x, double y, double z, int frameIn, int colorIn)
{
this(worldIn);
this.setPosition(x, y + 0.5D, z);
this.motionX = 0.0D;
this.motionY = 0.0D;
this.motionZ = 0.0D;
this.prevPosX = x;
this.prevPosY = y;
this.prevPosZ = z;
this.inventory = new ItemStackHandler(size);
}
@Override
public void entityInit()
{
this.dataManager.register(TIME_SINCE_HIT, Integer.valueOf(0));
this.dataManager.register(FORWARD_DIRECTION, Integer.valueOf(1));
this.dataManager.register(DAMAGE_TAKEN, Float.valueOf(0.0F));
this.dataManager.register(BOAT_TYPE_FRAME, Integer.valueOf(this.metaFrame));
this.dataManager.register(BOAT_TYPE_COLOR, Integer.valueOf(this.metaColor));
this.dataManager.register(POWERED, Integer.valueOf(this.airshipBurnTime));
this.dataManager.register(TOTALPOWERED, Integer.valueOf(this.airshipTotalBurnTime));
this.dataManager.register(ITEMFUELSTACKPOWERED, Integer.valueOf(this.itemFuelStack));
this.dataManager.register(ITEMFUELSTACKSIZEPOWERED, Integer.valueOf(this.itemFuelStackSize));
this.dataManager.register(MODULE_INVENTORY_SMALL, Boolean.valueOf(this.moduleInventorySmall));
this.dataManager.register(MODULE_INVENTORY_LARGE, Boolean.valueOf(this.moduleInventoryLarge));
this.dataManager.register(MODULE_FUEL_INFINITE, Boolean.valueOf(this.moduleFuelInfinite));
this.dataManager.register(MODULE_SPEED_MINOR, Boolean.valueOf(this.moduleSpeedMinor));
this.dataManager.register(MODULE_SPEED_MAJOR, Boolean.valueOf(this.moduleSpeedMajor));
}
//================================================================================
@Override
public boolean hasCapability(Capability<?> capability, EnumFacing facing)
{
if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) return true;
return super.hasCapability(capability, facing);
}
@Override
public <T> T getCapability(Capability<T> capability, EnumFacing facing)
{
if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) return (T) inventory;
return super.getCapability(capability, facing);
}
//==================================//
// TODO Read/Write //
//==================================//
@Override
public NBTTagCompound writeToNBT(NBTTagCompound compound)
{
super.writeToNBT(compound);
compound.setInteger("Frame", this.getBoatFrame().getMetadata());
compound.setInteger("Color", this.getBoatColor().getMetadata());
compound.setTag("Slots", inventory.serializeNBT());
compound.setInteger("BurnTime", this.airshipBurnTime);
compound.setInteger("TotalBurnTime", this.airshipTotalBurnTime);
compound.setInteger("FuelStackTime", this.itemFuelStack);
compound.setInteger("FuelStackTimeSize", this.itemFuelStackSize);
return compound;
}
@Override
public void readFromNBT(NBTTagCompound compound)
{
super.readFromNBT(compound);
this.metaFrame = compound.getInteger("Frame");
this.metaColor = compound.getInteger("Color");
inventory.deserializeNBT(compound.getCompoundTag("Slots"));
this.airshipBurnTime = compound.getInteger("BurnTime");
this.airshipTotalBurnTime = compound.getInteger("TotalBurnTime");
this.itemFuelStack = compound.getInteger("FuelStackTime");
this.itemFuelStackSize = compound.getInteger("FuelStackTimeSize");
}
//==================================//
// TODO On Update //
//==================================//
@Override
public void onUpdate()
{
this.previousStatus = this.status;
this.status = this.getAirshipStatus();
//Sets explosion ticks to 0 if not in water, else increase the tick count
if (this.status != EntityAirshipBaseVC.Status.UNDER_WATER && this.status != EntityAirshipBaseVC.Status.UNDER_FLOWING_WATER)
{
this.outOfControlTicks = 0.0F;
}
else
{
++this.outOfControlTicks;
}
//Removes passenger if they do not get out of water in time to explode the airship.
if (!this.worldObj.isRemote && this.outOfControlTicks >= 60.0F)
{
this.removePassengers();
}
if (this.getTimeSinceHit() > 0)
{
this.setTimeSinceHit(this.getTimeSinceHit() - 1);
}
if (this.getDamageTaken() > 0.0F)
{
this.setDamageTaken(this.getDamageTaken() - 1.0F);
}
this.updateAirshipMeta();
this.prevPosX = this.posX;
this.prevPosY = this.posY;
this.prevPosZ = this.posZ;
super.onUpdate();
this.tickLerp();
this.fuelFlight();
this.getTotalFuelSlotBurnTime();
this.currentModule();
if (this.canPassengerSteer())
{
this.updateMotion();
this.controlAirship();
if (this.worldObj.isRemote)
{
this.updateInputs();
this.controlAirshipGui();
}
this.moveEntity(this.motionX, this.motionY, this.motionZ);
}
else
{
this.motionX = 0.0D;
this.motionY = 0.0D;
this.motionZ = 0.0D;
}
this.doBlockCollisions();
List<Entity> list = this.worldObj.getEntitiesInAABBexcluding(this, this.getEntityBoundingBox().expand(0.20000000298023224D, -0.009999999776482582D, 0.20000000298023224D), EntitySelectors.<Entity>getTeamCollisionPredicate(this));
if (!list.isEmpty())
{
boolean flag = !this.worldObj.isRemote && !(this.getControllingPassenger() instanceof EntityPlayer);
for (int j = 0; j < list.size(); ++j)
{
Entity entity = (Entity)list.get(j);
if (!entity.isPassenger(this))
{
if (flag && this.getPassengers().size() < 2 && !entity.isRiding() && entity.width < this.width && entity instanceof EntityLivingBase && !(entity instanceof EntityWaterMob) && !(entity instanceof EntityPlayer))
if (flag && this.getPassengers().size() < 1 && !entity.isRiding() && entity.width < this.width && entity instanceof EntityLivingBase && !(entity instanceof EntityWaterMob) && !(entity instanceof EntityPlayer))
{
entity.startRiding(this);
}
else
{
this.applyEntityCollision(entity);
}
}
}
}
}
//==================================//
// TODO Speed and Motion //
//==================================//
@Override
public void updateMotion()
{
double d0 = 0.0D;
double d5 = -0.001D;
this.momentum = 0.05F;
if (this.previousStatus == EntityAirshipBaseVC.Status.IN_AIR && this.status != EntityAirshipBaseVC.Status.IN_AIR && this.status != EntityAirshipBaseVC.Status.ON_LAND)
{
this.waterLevel = this.getEntityBoundingBox().minY + (double)this.height;
this.setPosition(this.posX, (double)(this.getWaterLevelAbove() - this.height) + 0.101D, this.posZ);
this.motionY = 0.0D;
this.lastYd = 0.0D;
this.status = EntityAirshipBaseVC.Status.IN_WATER;
}
else
{
if (this.status == EntityAirshipBaseVC.Status.IN_WATER)
{
this.momentum = 0.45F;
}
else if (this.status == EntityAirshipBaseVC.Status.UNDER_FLOWING_WATER
|| this.status == EntityAirshipBaseVC.Status.UNDER_WATER)
{
if (!this.worldObj.isRemote)
{
this.worldObj.createExplosion(this, this.posX, this.posY + (double)(this.height / 16.0F), this.posZ, 2.0F, true);
int drop1 = random.nextInt(100) + 1;
int drop2 = random.nextInt(100) + 1;
int drop3 = random.nextInt(100) + 1;
int drop4 = random.nextInt(100) + 1;
int drop5 = random.nextInt(100) + 1;
if (drop1 < 75)
{
this.dropItemWithOffset(InitItemsVC.airship_balloon, 1, 0.0F);
}
if (drop2 < 55)
{
this.dropItemWithOffset(InitItemsVC.airship_engine, 1, 0.0F);
if (drop3 < 35)
{
this.dropItemWithOffset(InitItemsVC.airship_engine, 1, 0.0F);
}
}
if (drop5 < 15)
{
this.dropItemWithOffset(InitItemsVC.airship_ignition, 1, 0.0F);
}
}
this.setDeadVC();
}
else if (this.status == EntityAirshipBaseVC.Status.IN_AIR
|| this.status == EntityAirshipBaseVC.Status.ON_LAND)
{
this.momentum = 0.9F;
}
this.motionX *= (double)this.momentum;
this.motionZ *= (double)this.momentum;
this.deltaRotation *= this.momentum;
if(this.getControllingPassenger() == null)
{
if(this.isCollidedVertically)
{
this.motionY = 0;
}
else
{
this.motionY += d5;
}
}
else if(isClientAirshipBurning())
{
this.motionY *= (double)this.momentum;
}
else if(this.isCollidedVertically)
{
this.motionY = 0;
}
else
{
this.motionY += d5;
}
}
}
@Override
public void controlAirship()
{
if (this.isBeingRidden())
{
float f = 0.0F;
float f1 = 0.0F;
//Turning Left
if (this.leftInputDown)
{
if(isClientAirshipBurning())
{
this.deltaRotation -= AirshipSpeedTurn;
}
else
{
this.deltaRotation -= AirshipSpeedTurn * 0.5F;
}
}
//Turning Right
if (this.rightInputDown)
{
if(isClientAirshipBurning())
{
this.deltaRotation += AirshipSpeedTurn;
}
else
{
this.deltaRotation += AirshipSpeedTurn * 0.5F;
}
}
if (this.rightInputDown != this.leftInputDown && !this.forwardInputDown && !this.backInputDown)
{
f += 0.005F;
}
this.rotationYaw += this.deltaRotation;
//Moving Forward
if (this.forwardInputDown)
{
//If airship is on & small inv module installed
if(isClientAirshipBurning()
&& this.getModuleInventorySmall())
{
f += AirshipSpeedForward - (AirshipSpeedForward * 0.2F);
}
//If airship is on & large inv module installed
else if(isClientAirshipBurning()
&& this.getModuleInventoryLarge())
{
f += AirshipSpeedForward - (AirshipSpeedForward * 0.3F);
}
//If airship is on & infinite fuel module installed
else if(isClientAirshipBurning()
&& this.getModuleFuelInfinite())
{
f += AirshipSpeedForward - (AirshipSpeedForward * 0.4F);
}
//If airship is on & minor speed module installed
else if(isClientAirshipBurning()
&& this.getModuleSpeedMinor())
{
f += AirshipSpeedForward + 0.008F;
}
//If airship is on & major speed module installed
else if(isClientAirshipBurning()
&& this.getModuleSpeedMajor())
{
f += AirshipSpeedForward + 0.016F;
}
//If airship is on
else if(isClientAirshipBurning())
{
f += AirshipSpeedForward;
}
//If airship is off
else
{
f += 0.0030F;
}
}
//Moving Backwards
if (this.backInputDown)
{
//If airship is on & small inv module installed
if(isClientAirshipBurning()
&& this.getModuleInventorySmall())
{
f -= (AirshipSpeedForward * 0.5) - ((AirshipSpeedForward * 0.5)* 0.2);
}
//If airship is on & large inv module installed
else if(isClientAirshipBurning()
&& this.getModuleInventoryLarge())
{
f -= (AirshipSpeedForward * 0.5) - ((AirshipSpeedForward * 0.5)* 0.3);
}
//If airship is on & infinite fuel module installed
else if(isClientAirshipBurning()
&& this.getModuleFuelInfinite())
{
f -= (AirshipSpeedForward * 0.5) - ((AirshipSpeedForward * 0.4)* 0.5);
}
//If airship is on & minor speed module installed
else if(isClientAirshipBurning()
&& this.getModuleSpeedMinor())
{
f -= (AirshipSpeedForward * 0.5) + 0.004F;
}
//If airship is on & major speed module installed
else if(isClientAirshipBurning()
&& this.getModuleSpeedMajor())
{
f -= (AirshipSpeedForward * 0.5) + 0.008F;
}
//If airship is on
else if(isClientAirshipBurning())
{
f -= AirshipSpeedForward * 0.5;
}
//If airship is off
else
{
f -= 0.0030F * 0.5;
}
}
//Moving Up
if (this.upInputDown)
{
//If airship is on & small inv module installed
if(isClientAirshipBurning()
&& this.getModuleInventorySmall())
{
f1 += AirshipSpeedUp - (AirshipSpeedUp * 0.2);
}
//If airship is on & large inv module installed
else if(isClientAirshipBurning()
&& this.getModuleInventoryLarge())
{
f1 += AirshipSpeedUp - (AirshipSpeedUp * 0.3);
}
//If airship is on & infinite fuel module installed
else if(isClientAirshipBurning()
&& this.getModuleFuelInfinite())
{
f1 += AirshipSpeedUp - (AirshipSpeedUp * 0.4);
}
//If airship is on & minor speed module installed
else if(isClientAirshipBurning()
&& this.getModuleSpeedMinor())
{
f1 += AirshipSpeedUp;
}
//If airship is on & major speed module installed
else if(isClientAirshipBurning()
&& this.getModuleSpeedMajor())
{
f1 += AirshipSpeedUp;
}
//If airship is on
else if(isClientAirshipBurning())
{
f1 += AirshipSpeedUp;
}
}
//Moving down
if (this.downInputDown)
{
f1 -= AirshipSpeedDown;
}
this.motionX += (double)(MathHelper.sin(-this.rotationYaw * 0.017453292F) * f);
this.motionZ += (double)(MathHelper.cos(this.rotationYaw * 0.017453292F) * f);
this.motionY += (double)(3.017453292F * f1);
this.rotationPitch += 10;
}
}
//==================================//
// TODO GUI //
//==================================//
/**
* Opens the correct inventory on button press.
*/
protected void controlAirshipGui()
{
if(this.openInputDown
&& this.getControllingPassenger() != null)
{
//If airship has small inv module installed
if(this.getModuleInventorySmall())
{
NetworkHandler.sendToServer(new MessageGuiV4ModuleInventorySmall());
Minecraft.getMinecraft().setIngameFocus();
}
//If airship has large inv module installed
else if(this.getModuleInventoryLarge())
{
NetworkHandler.sendToServer(new MessageGuiV4ModuleInventoryLarge());
Minecraft.getMinecraft().setIngameFocus();
}
//Default for airship gui
else
{
NetworkHandler.sendToServer(new MessageGuiV4Default());
Minecraft.getMinecraft().setIngameFocus();
}
}
}
//==================================//
// TODO Misc //
//==================================//
@Override
public void setDeadVC()
{
if (!this.worldObj.isRemote)
{
this.dropInvDead();
this.playSound(SoundEvents.ENTITY_ENDEREYE_LAUNCH, 0.5F, 0.4F / .5F * 0.4F + 0.8F);
this.playSound(SoundEvents.ENTITY_SHEEP_SHEAR, 0.5F, 0.4F / .5F * 0.4F + 0.8F);
this.isDead = true;
}
else
{
this.worldObj.spawnParticle(EnumParticleTypes.EXPLOSION_LARGE,
this.posX + this.worldObj.rand.nextFloat() * this.width * 2.0F - this.width,
this.posY + 0.5D,
this.posZ + this.worldObj.rand.nextFloat() * this.width * 2.0F - this.width,
0.0D, 0.0D, 0.0D, new int[0]);
for (int ii = 0; ii < 10; ++ii)
{
int d = random.nextInt(100) + 1;
if (d <= 2)
{
this.worldObj.spawnParticle(EnumParticleTypes.EXPLOSION_LARGE,
this.posX + this.worldObj.rand.nextFloat() * this.width * 2.0F - this.width,
this.posY + 0.5D,
this.posZ + this.worldObj.rand.nextFloat() * this.width * 2.0F - this.width,
0.0D, 0.0D, 0.0D, new int[0]);
}
if (d <= 15)
{
this.worldObj.spawnParticle(EnumParticleTypes.EXPLOSION_NORMAL,
this.posX + this.worldObj.rand.nextFloat() * this.width * 2.0F - this.width,
this.posY + 0.5D,
this.posZ + this.worldObj.rand.nextFloat() * this.width * 2.0F - this.width,
0.0D, 0.25D, 0.0D, new int[0]);
}
if (d <= 25)
{
this.worldObj.spawnParticle(EnumParticleTypes.SMOKE_NORMAL,
this.posX + this.worldObj.rand.nextFloat() * this.width * 2.0F - this.width,
this.posY + 0.5D,
this.posZ + this.worldObj.rand.nextFloat() * this.width * 2.0F - this.width,
0.0D, 0.0D, 0.0D, new int[0]);
}
}
}
}
//==================================//
// TODO Inventory //
//==================================//
public int getField(int id)
{
switch (id)
{
case 0:
return this.airshipBurnTime;
case 1:
return this.airshipTotalBurnTime;
default:
return 0;
}
}
public void setField(int id, int value)
{
switch (id)
{
//Current Airship Burn Time
case 0:
this.airshipBurnTime = value;
break;
case 1:
this.airshipTotalBurnTime = value;
break;
default:
break;
}
}
public int getFieldCount()
{
return 2;
}
//==================================//
// TODO Fuel Consumption //
//==================================//
/**
* Core fuel logic responsible for flight.
*/
public void fuelFlight()
{
boolean flag = this.isClientAirshipBurning();
boolean flag1 = false;
//Syncs the server info to the client
if(this.worldObj.isRemote)
{
this.airshipBurnTime = this.getPowered();
this.airshipTotalBurnTime = this.getTotalPowered();
}
//Handles how burn time is ticked down
if (this.isClientAirshipBurning())
{
//Airship has Infinite Fuel Module installed
if(this.getModuleFuelInfinite())
{
}
//The player in the airship is in Creative Mode
else if(EventHandlerAirship.creativeBurn)
{
if(this.getEntityId() == EventHandlerAirship.playerRidingEntity)
{
if(this.getControllingPassenger() == null)
{
--this.airshipBurnTime;
}
else
{
}
}
else
{
--this.airshipBurnTime;
}
}
//Airship has either Large Inventory or Minor Speed Module installed
else if(this.getModuleInventoryLarge()
|| this.getModuleSpeedMajor())
{
--this.airshipBurnTime;
--this.airshipBurnTime;
}
//Airship has no controlling passenger
else if(this.getControllingPassenger() == null)
{
--this.airshipBurnTime;
}
//Anything else
else
{
--this.airshipBurnTime;
}
}
//Handles when the airship is off
if (!this.isClientAirshipBurning())
{
//Airship has Infinite Fuel Module installed
if(this.getModuleFuelInfinite())
{
this.airshipBurnTime = 1;
}
//Airship has no controlling passenger
else if(this.getControllingPassenger() == null)
{
this.airshipBurnTime = 0;
}
//The player in the airship is in Creative Mode
else if(EventHandlerAirship.creativeBurn)
{
if (this.getEntityId() == EventHandlerAirship.playerRidingEntity)
{
this.airshipBurnTime = 1;
}
}
else
{
this.airshipBurnTime = 0;
}
}
//Core fuel slot logic
if (this.isClientAirshipBurning() || this.inventory.getStackInSlot(0) != null)
{
if (!this.isClientAirshipBurning()
&& this.getControllingPassenger() != null)
{
this.airshipBurnTime = getItemBurnTime(this.inventory.getStackInSlot(0));
this.airshipTotalBurnTime = getItemBurnTime(this.inventory.getStackInSlot(0));
if (this.isClientAirshipBurning())
{
flag1 = true;
//Consumes the fuel item
if (this.inventory.getStackInSlot(0) != null)
{
if (this.inventory.getStackInSlot(0).stackSize == 0)
{
ItemStack test = this.inventory.getStackInSlot(0);
test = inventory.getStackInSlot(0).getItem().getContainerItem(inventory.getStackInSlot(0));
}
this.inventory.extractItem(0, 1, false);
}
}
}
}
if (flag != this.isClientAirshipBurning())
{
flag1 = true;
}
//Saves the fuel burntime server side
if(!this.worldObj.isRemote)
{
this.setPowered(this.airshipBurnTime);
this.setTotalPowered(this.airshipTotalBurnTime);
}
}
/**
* Is Airship Engine On
*/
public boolean isClientAirshipBurning()
{
return this.airshipBurnTime > 0;
}
/**
* Returns the number of ticks that the supplied fuel item will keep the furnace burning, or 0 if the item isn't
* fuel
*/
public static int getItemBurnTime(ItemStack stack)
{
if (stack == null)
{
return 0;
}
else
{
Item item = stack.getItem();
if (item instanceof ItemBlock && Block.getBlockFromItem(item) != Blocks.AIR)
{
Block block = Block.getBlockFromItem(item);
if (block == Blocks.WOODEN_SLAB)
{
return FuelVC.wooden_slab;
}
if (block.getDefaultState().getMaterial() == Material.WOOD)
{
return FuelVC.wood_block_material;
}
if (block == Blocks.COAL_BLOCK)
{
return FuelVC.coal_block;
}
}
if (item == Items.STICK) return FuelVC.stick;
if (item == Item.getItemFromBlock(Blocks.SAPLING)) return FuelVC.sapling;
if (item == Items.COAL) return FuelVC.coal;
if (item == Items.BLAZE_ROD) return FuelVC.blaze_rod;
if (item == InitItemsVC.viesoline_pellets) return (ViesCraftConfig.viesolineBurnTime * 20);
return net.minecraftforge.fml.common.registry.GameRegistry.getFuelValue(stack);
}
}
public static boolean isItemFuel(ItemStack stack)
{
/**
* Returns the number of ticks that the supplied fuel item will keep the furnace burning, or 0 if the item isn't
* fuel
*/
return getItemBurnTime(stack) > 0;
}
/**
* Calculates total fuel burn time by stack size for GUI
*/
//TODO
public void getTotalFuelSlotBurnTime()
{
//Passes itemFuelStack to client for gui
if(this.worldObj.isRemote)
{
this.itemFuelStack = this.getItemFuelStackPowered();
this.itemFuelStackSize = this.getItemFuelStackSizePowered();
}
if(this.getControllingPassenger() != null)
{
if (this.isClientAirshipBurning())
{
ItemStack itemFuel = this.inventory.getStackInSlot(0);
if(itemFuel != null)
{
this.itemFuelStackSize = this.inventory.getStackInSlot(0).stackSize;
this.itemFuelStack = this.itemFuelStackSize
* this.getItemBurnTime(this.inventory.getStackInSlot(0));
}
else
{
this.itemFuelStack = 0;
this.itemFuelStackSize = 0;
}
}
else
{
this.itemFuelStack = 0;
this.itemFuelStackSize = 0;
}
}
if(!this.worldObj.isRemote)
{
this.setItemFuelStackPowered(this.itemFuelStack);
this.setItemFuelStackSizePowered(this.itemFuelStackSize);
}
}
/**
* Sets the airshipBurnTime to pass from server to client.
*/
public void setPowered(int airshipBurnTime1)
{
this.dataManager.set(POWERED, Integer.valueOf(airshipBurnTime1));
}
/**
* Gets the airshipBurnTime to pass from server to client.
*/
public int getPowered()
{
return ((Integer)this.dataManager.get(POWERED)).intValue();
}
/**
* Sets the airshipTotalBurnTime to pass from server to client.
*/
public void setTotalPowered(int airshipTotalBurnTime1)
{
this.dataManager.set(TOTALPOWERED, Integer.valueOf(airshipTotalBurnTime1));
}
/**
* Gets the airshipTotalBurnTime to pass from server to client.
*/
public int getTotalPowered()
{
return ((Integer)this.dataManager.get(TOTALPOWERED)).intValue();
}
/**
* Sets the itemFuelStack to pass from server to client.
*/
public void setItemFuelStackPowered(int itemFuelStack1)
{
this.dataManager.set(ITEMFUELSTACKPOWERED, Integer.valueOf(itemFuelStack1));
}
/**
* Gets the itemFuelStack to pass from server to client.
*/
public int getItemFuelStackPowered()
{
return ((Integer)this.dataManager.get(ITEMFUELSTACKPOWERED)).intValue();
}
/**
* Sets the itemFuelStackSize to pass from server to client.
*/
public void setItemFuelStackSizePowered(int itemFuelStackSize1)
{
this.dataManager.set(ITEMFUELSTACKSIZEPOWERED, Integer.valueOf(itemFuelStackSize1));
}
/**
* Gets the itemFuelStackSize to pass from server to client.
*/
public int getItemFuelStackSizePowered()
{
return ((Integer)this.dataManager.get(ITEMFUELSTACKSIZEPOWERED)).intValue();
}
//==================================//
// TODO Airship Modules //
//==================================//
public void currentModule()
{
ItemStack itemModule = this.inventory.getStackInSlot(1);
int moduleNumber = this.getModuleID(itemModule);
/**
if(this.worldObj.isRemote)
{
if(this.getModuleInventorySmall())
LogHelper.info("1");
if(this.getModuleInventoryLarge())
LogHelper.info("2");
if(this.getModuleSpeedMinor())
LogHelper.info("3");
if(this.getModuleFuelInfinite())
LogHelper.info("4");
if(this.getModuleStealth())
LogHelper.info("5");
if(this.getModuleDash())
LogHelper.info("6");
}
*/
//Syncs the module boolean client side
if(this.worldObj.isRemote)
{
this.moduleInventorySmall = this.getModuleInventorySmall();
this.moduleInventoryLarge = this.getModuleInventoryLarge();
this.moduleSpeedMinor = this.getModuleSpeedMinor();
this.moduleSpeedMajor = this.getModuleSpeedMajor();
this.moduleFuelInfinite = this.getModuleFuelInfinite();
}
if(moduleNumber == 1)
{
this.moduleInventorySmall = true;
this.moduleInventoryLarge = false;
this.moduleSpeedMinor = false;
this.moduleSpeedMajor = false;
this.moduleFuelInfinite = false;
}
else if(moduleNumber == 2)
{
this.moduleInventorySmall = false;
this.moduleInventoryLarge = true;
this.moduleSpeedMinor = false;
this.moduleSpeedMajor = false;
this.moduleFuelInfinite = false;
}
else if(moduleNumber == 3)
{
this.moduleInventorySmall = false;
this.moduleInventoryLarge = false;
this.moduleSpeedMinor = true;
this.moduleSpeedMajor = false;
this.moduleFuelInfinite = false;
}
else if(moduleNumber == 4)
{
this.moduleInventorySmall = false;
this.moduleInventoryLarge = false;
this.moduleSpeedMinor = false;
this.moduleSpeedMajor = true;
this.moduleFuelInfinite = false;
}
else if(moduleNumber == 5)
{
this.moduleInventorySmall = false;
this.moduleInventoryLarge = false;
this.moduleSpeedMinor = false;
this.moduleSpeedMajor = false;
this.moduleFuelInfinite = true;
}
else// if(moduleNumber == 0)
{
this.moduleInventorySmall = false;
this.moduleInventoryLarge = false;
this.moduleSpeedMinor = false;
this.moduleSpeedMajor = false;
this.moduleFuelInfinite = false;
}
//Used to drop inventory if inv modules are removed/switched
// If there is no module in slot
if(this.inventory.getStackInSlot(1) == null)
{
//If small inv mod is removed and slot is empty
if(dropNumber == 1)
{
dropNumber = 0;
this.dropInv();
}
//If large inv mod is removed and slot is empty
if(dropNumber == 2)
{
dropNumber = 0;
this.dropInv();
}
}
//If a module is still in the slot
else
{
//If the module in the slot is small inv mod
if(this.inventory.getStackInSlot(1).getItem() == InitItemsVC.module_inventory_small
&& dropNumber == 0)
{
dropNumber = 1;
}
//If the module in the slot is large inv mod
else if(this.inventory.getStackInSlot(1).getItem() == InitItemsVC.module_inventory_large
&& dropNumber == 0)
{
dropNumber = 2;
}
//If the module in the slot is not small inv mod but had it in previously
else if(this.inventory.getStackInSlot(1).getItem() != InitItemsVC.module_inventory_small
&& dropNumber == 1)
{
dropNumber = 0;
this.dropInv();
}
//If the module in the slot is not large inv mod but had it in previously
else if(this.inventory.getStackInSlot(1).getItem() != InitItemsVC.module_inventory_large
&& dropNumber == 2)
{
dropNumber = 0;
this.dropInv();
}
}
//Saves the module boolean to server side
if(!this.worldObj.isRemote)
{
this.setModuleInventorySmall(this.moduleInventorySmall);
this.setModuleInventoryLarge(this.moduleInventoryLarge);
this.setModuleSpeedMinor(this.moduleSpeedMinor);
this.setModuleSpeedMajor(this.moduleSpeedMajor);
this.setModuleFuelInfinite(this.moduleFuelInfinite);
}
}
/**
* Checks if a module is in the module slot.
*/
public static boolean getItemModule(ItemStack stack)
{
if (stack == null)
{
return false;
}
else
{
Item item = stack.getItem();
//Passive
if (item == InitItemsVC.module_inventory_small) return true;
if (item == InitItemsVC.module_inventory_large) return true;
if (item == InitItemsVC.module_speed_increase_minor) return true;
if (item == InitItemsVC.module_speed_increase_major) return true;
if (item == InitItemsVC.module_fuel_infinite) return true;
return false;
}
}
/**
* Set module ID for module in slot.
*/
public static int getModuleID(ItemStack stack)
{
if (stack == null)
{
return 0;
}
else
{
Item item = stack.getItem();
if (item == InitItemsVC.module_inventory_small)
{
return 1;
}
else if (item == InitItemsVC.module_inventory_large)
{
return 2;
}
else if (item == InitItemsVC.module_speed_increase_minor)
{
return 3;
}
else if (item == InitItemsVC.module_speed_increase_major)
{
return 4;
}
else if (item == InitItemsVC.module_fuel_infinite)
{
return 5;
}
else
{
return 0;
}
}
}
public static boolean isItemModule(ItemStack stack)
{
/**
* Returns the number of ticks that the supplied fuel item will keep the furnace burning, or 0 if the item isn't
* fuel
*/
return getItemModule(stack);
}
/**
* Drops inventory contents only from airship (not fuel/module).
*/
public void dropInv()
{
if(this.worldObj.isRemote)
{
for (int x = 2; x < 20; ++x)
{
if(this.inventory.getStackInSlot(x) != null)
{
ItemStack test = this.inventory.getStackInSlot(x);
test = null;
}
}
}
else
{
for (int x = 2; x < 20; ++x)
{
if(this.inventory.getStackInSlot(x) != null)
{
ItemStack test = this.inventory.getStackInSlot(x);
InventoryHelper.spawnItemStack(this.worldObj, this.posX, this.posY, this.posZ, this.inventory.getStackInSlot(x));
test = null;
}
}
}
}
/**
* Drops all inventory contents.
*/
public void dropInvDead()
{
if(this.worldObj.isRemote)
{
for (int x = 0; x < 20; ++x)
{
if(this.inventory.getStackInSlot(x) != null)
{
ItemStack test = this.inventory.getStackInSlot(x);
test = null;
}
}
}
else
{
for (int x = 0; x < 20; ++x)
{
if(this.inventory.getStackInSlot(x) != null)
{
ItemStack test = this.inventory.getStackInSlot(x);
InventoryHelper.spawnItemStack(this.worldObj, this.posX, this.posY, this.posZ, this.inventory.getStackInSlot(x));
test = null;
}
}
}
}
/**
* Sets the Small Inventory boolean to pass from server to client.
*/
public void setModuleInventorySmall(boolean moduleInvSmall1)
{
this.dataManager.set(MODULE_INVENTORY_SMALL, Boolean.valueOf(moduleInvSmall1));
}
/**
* Gets the Small Inventory boolean to pass from server to client.
*/
public boolean getModuleInventorySmall()
{
return ((Boolean)this.dataManager.get(MODULE_INVENTORY_SMALL)).booleanValue();
}
/**
* Sets the Large Inventory boolean to pass from server to client.
*/
public void setModuleInventoryLarge(boolean moduleInvLarge1)
{
this.dataManager.set(MODULE_INVENTORY_LARGE, Boolean.valueOf(moduleInvLarge1));
}
/**
* Gets the Large Inventory boolean to pass from server to client.
*/
public boolean getModuleInventoryLarge()
{
return ((Boolean)this.dataManager.get(MODULE_INVENTORY_LARGE)).booleanValue();
}
/**
* Sets the Infinite Fuel boolean to pass from server to client.
*/
public void setModuleFuelInfinite(boolean moduleFuelInfinite1)
{
this.dataManager.set(MODULE_FUEL_INFINITE, Boolean.valueOf(moduleFuelInfinite1));
}
/**
* Gets the Infinite Fuel boolean to pass from server to client.
*/
public boolean getModuleFuelInfinite()
{
return ((Boolean)this.dataManager.get(MODULE_FUEL_INFINITE)).booleanValue();
}
/**
* Sets if Minor Speed Increase mod is installed to pass from server to client.
*/
public void setModuleSpeedMinor(boolean moduleSpeed1)
{
this.dataManager.set(MODULE_SPEED_MINOR, Boolean.valueOf(moduleSpeed1));
}
/**
* Gets the Minor Speed boolean to pass from server to client.
*/
public boolean getModuleSpeedMinor()
{
return ((Boolean)this.dataManager.get(MODULE_SPEED_MINOR)).booleanValue();
}
/**
* Sets if Major Speed Increase mod is installed to pass from server to client.
*/
public void setModuleSpeedMajor(boolean moduleSpeed2)
{
this.dataManager.set(MODULE_SPEED_MAJOR, Boolean.valueOf(moduleSpeed2));
}
/**
* Gets the Major Speed boolean to pass from server to client.
*/
public boolean getModuleSpeedMajor()
{
return ((Boolean)this.dataManager.get(MODULE_SPEED_MAJOR)).booleanValue();
}
}
| mit |
likelion-goals320/SE_assingment | application/config/database.php | 4618 | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| DATABASE CONNECTIVITY SETTINGS
| -------------------------------------------------------------------
| This file will contain the settings needed to access your database.
|
| For complete instructions please consult the 'Database Connection'
| page of the User Guide.
|
| -------------------------------------------------------------------
| EXPLANATION OF VARIABLES
| -------------------------------------------------------------------
|
| ['dsn'] The full DSN string describe a connection to the database.
| ['hostname'] The hostname of your database server.
| ['username'] The username used to connect to the database
| ['password'] The password used to connect to the database
| ['database'] The name of the database you want to connect to
| ['dbdriver'] The database driver. e.g.: mysqli.
| Currently supported:
| cubrid, ibase, mssql, mysql, mysqli, oci8,
| odbc, pdo, postgre, sqlite, sqlite3, sqlsrv
| ['dbprefix'] You can add an optional prefix, which will be added
| to the table name when using the Query Builder class
| ['pconnect'] TRUE/FALSE - Whether to use a persistent connection
| ['db_debug'] TRUE/FALSE - Whether database errors should be displayed.
| ['cache_on'] TRUE/FALSE - Enables/disables query caching
| ['cachedir'] The path to the folder where cache files should be stored
| ['char_set'] The character set used in communicating with the database
| ['dbcollat'] The character collation used in communicating with the database
| NOTE: For MySQL and MySQLi databases, this setting is only used
| as a backup if your server is running PHP < 5.2.3 or MySQL < 5.0.7
| (and in table creation queries made with DB Forge).
| There is an incompatibility in PHP with mysql_real_escape_string() which
| can make your site vulnerable to SQL injection if you are using a
| multi-byte character set and are running versions lower than these.
| Sites using Latin-1 or UTF-8 database character set and collation are unaffected.
| ['swap_pre'] A default table prefix that should be swapped with the dbprefix
| ['encrypt'] Whether or not to use an encrypted connection.
|
| 'mysql' (deprecated), 'sqlsrv' and 'pdo/sqlsrv' drivers accept TRUE/FALSE
| 'mysqli' and 'pdo/mysql' drivers accept an array with the following options:
|
| 'ssl_key' - Path to the private key file
| 'ssl_cert' - Path to the public key certificate file
| 'ssl_ca' - Path to the certificate authority file
| 'ssl_capath' - Path to a directory containing trusted CA certificats in PEM format
| 'ssl_cipher' - List of *allowed* ciphers to be used for the encryption, separated by colons (':')
| 'ssl_verify' - TRUE/FALSE; Whether verify the server certificate or not ('mysqli' only)
|
| ['compress'] Whether or not to use client compression (MySQL only)
| ['stricton'] TRUE/FALSE - forces 'Strict Mode' connections
| - good for ensuring strict SQL while developing
| ['ssl_options'] Used to set various SSL options that can be used when making SSL connections.
| ['failover'] array - A array with 0 or more data for connections if the main should fail.
| ['save_queries'] TRUE/FALSE - Whether to "save" all executed queries.
| NOTE: Disabling this will also effectively disable both
| $this->db->last_query() and profiling of DB queries.
| When you run a query, with this setting set to TRUE (default),
| CodeIgniter will store the SQL statement for debugging purposes.
| However, this may cause high memory usage, especially if you run
| a lot of SQL queries ... disable this to avoid that problem.
|
| The $active_group variable lets you choose which connection group to
| make active. By default there is only one group (the 'default' group).
|
| The $query_builder variables lets you determine whether or not to load
| the query builder class.
*/
$active_group = 'default';
$query_builder = TRUE;
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost', //다른 pc에 있는 database를 쓰고 싶다면 그 머신의 ip나 domain 입력
'username' => 'root',
'password' => 'a231564',
'database' => 'topguard',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
| mit |
DenysZakharov/task-tracker | src/UserBundle/Tests/Controller/ManagerSecurityTest.php | 794 | <?php
namespace UserBundle\Tests\Controller;
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Tests\Controller\WebTestCase;
class ManagerSecurityTest extends WebTestCase
{
/**
* @dataProvider urlProvider
*/
public function testPageIsSuccessful($url)
{
$client = static::createClient([], [
'PHP_AUTH_USER' => 'manager',
'PHP_AUTH_PW' => 'test'
]);
$client->request('GET', $url);
$this->assertTrue($client->getResponse()->isSuccessful());
}
public function urlProvider()
{
return [
['/'],
['/issue/new'],
['/issue/task-three/edit'],
['/issue/task-three'],
['/project/'],
['/project/new'],
];
}
}
| mit |
TheOneTheOnlyDavidBrown/crunchpowjs | example/scripts/Routes.js | 680 | // puts routes on the router class
import Router from './Router';
// TODO: not attach this to the global namespace
window.router = window.router || new Router();
window.router.state({
name: '/users',
templateUrl: 'templates/userindex.html',
}).state({
name: '/user/:id',
templateUrl: 'templates/user.html',
}).state({
name: '/user/:id/details',
templateUrl: 'templates/userdetails.html',
}).state({
name: '/user/:id/:subid',
templateUrl: 'templates/usersub.html',
}).state({
name: '/list',
templateUrl: 'templates/list.html',
}).state({
name: '/',
templateUrl: 'templates/list.html',
}).fallback({
name: '/404',
templateUrl: 'templates/404.html',
});
| mit |
pellucidanalytics/decks | lib/events/decksevent.js | 861 | var validate = require("../utils/validate");
/**
* A custom event class for use within decks.js
*
* @class
* @param {!String} type - The type of event (e.g. "item:changed")
* @param {!*} sender - The sender of the event (e.g. the object which is emitting the event)
* @param {?*} [data={}] - Custom data to include with the event (any type, Object, array, primitive, etc.)
*/
function DecksEvent(type, sender, data) {
validate(type, "type", { isString: true });
validate(sender, "sender", { isRequired: true });
if (!(this instanceof DecksEvent)) {
return new DecksEvent(type, sender, data);
}
/** The type of event */
this.type = type;
/** The sender of the event (the object that emitted the event) */
this.sender = sender;
/** Custom event data (can be anything) */
this.data = data || {};
}
module.exports = DecksEvent;
| mit |
CPGFinanceSystems/verita | verita-api/src/main/java/de/cpg/oss/verita/event/Event.java | 1109 | package de.cpg.oss.verita.event;
import java.io.Serializable;
import java.util.Optional;
import java.util.UUID;
/**
* Represents a persistent immutable event within the system - A business fact which happened in the past.
* The events are processed by the {@link de.cpg.oss.verita.service.EventBus} and handled by their respective
* {@link EventHandler}s.
* An event is something which the system must be able to process from a business point of view since it represents
* something which happened already in the past. Events can only be 'deleted' or 'undone' if another event with the
* logical reverse operation is applied (for example this could be a <code>UserDeletedEvent</code>).
*/
public abstract class Event implements Serializable {
private static final long serialVersionUID = 1L;
/**
* Supply a unique logical identifier - for example in a <code>CreatedUserEvent</code> this could be the user's
* email address.
*
* @return A unique logical identifier for this event
*/
public Optional<String> uniqueKey() {
return Optional.empty();
}
}
| mit |
gryphonmyers/weddell | src/plugins/router/index.js | 21339 | var Mixin = require('@weddell/mixwith').Mixin;
var mix = require('@weddell/mixwith').mix;
var Router = require('./router');
var StateMachineMixin = require('./state-machine-mixin');
var MachineStateMixin = require('./machine-state-mixin');
var defaults = require('defaults-es6/deep-merge');
var RouterState = mix(class {
constructor(opts) {
this.Component = opts.Component;
this.componentName = opts.componentName;
}
}).with(MachineStateMixin);
// $currentRoute: null,
// $currentRouteName: null,
// $pathParams: null
/**
* @typedef {object} RouterComponentState
* @property {} $currentRouteName
* @property {} $pathParams Key-value pairs of all path params matched
*/
/**
* @typedef {(String|undefined)[]} PathToRegExpMatch The result from the match as performed by path-to-regexp. Array items will be undefined if no value is specified for optional path params.
*/
/**
* @typedef {object} PathToRegExpParams The available path params (not their values) as parsed from a route pattern by path-to-regexp.
*/
/**
* @typedef {String} PathToRegExpPath Path string as accepted by path-to-regexp.
*/
/**
* @typedef {object} RouterMatch
* @property {PathToRegExpParams[]} params Params that were
* @property {PathToRegExpMatch} match The result returned by path-to-regexp after matching the current location against the component tree.
* @property {RouteObject} route The matched route
*/
/**
* @typedef {object} RouteObject
*
* @property {RoutingHandler} handler
* @property {PathToRegExpPath} pattern Note that a partial match will be performed on this path, separate from its children.
* @property {RouteObject[]} children Subroutes that will be available for continued matching once this route matches.
* @property {Function} validator Function used to validate the
* @property {String} [name] Name of this route object. Required for direct routing via link generation.
*/
/**
* Event object that is passed to a routing handler callback.
*
* @typedef {RouterMatch[]} RoutingEvent An event object is passed to routing handlers after a successful match. Each item in the array corresponds to a tier in the route tree.
* @property {String} fullPath The full path that was matched to this route.
* @property {String} hash Location hash at the time the route was matched.
* @property {Boolean} isRouteUpdate Whether or not this route matched to the same component at this point in the routing tree.
* @property {object} paramVals Key-pairs of all path params from route match.
* @property {RouteObject} route The route object that was matched.
*
*/
/**
* Callback that executes when a route is matched in the route tree.
*
* @callback RoutingHandler
* @param {RoutingEvent} evt
* @returns {Promise|String} The component key to select in the component tree. Every node in the component tree should correspond to a node in the routing tree. A returned Promise will defer route matching. If the Promise is rejected, the route matching process will be restarted with the rejected value (a redirect).
* @example
* var myApp = new Weddell.App({
* routes: [
* {
* pattern: '/foo',
* handler: evt => 'my-component-a',
* children: [
* {
* pattern: ':myParam/'
* handler: evt => 'my-subcomponent'
* }
* ]
* }
* ],
* Component: class extends Weddell.Component {
* static get components() {
* return {
* 'my-component-a': class extends Weddell.Component {
* static get components() {
* return {
* 'my-subcomponent': MySubComponent
* }
* }
* }
* }
* }
* }
* })
*
* // If a route is performed against the path 'foo/bar', 'my-component-a' will be mounted into the root component's routerview, and 'my-subcomponent' will be routed into that component's routerview.
*/
/**
* Event fired whenever the location path is matched against the component tree, but before component tree transitions are fired.
*
* @event App#routematched
* @type {object}
* @property {RouterMatch[]} matches
*/
/**
* Event fired whenever the location path is matched against the component tree, after all component tree transitions have finished firing.
*
* @event App#route
* @type {object}
* @property {RouterMatch[]} matches
* @property {*} results If any data was returned by the transition events fired over the course of routing, it will be available here. Usually this is null.
*/
/**
* Weddell decorator function.
*
* @param {Weddell} _Weddell The Weddell class to augment.
* @returns {Weddell} The passed Weddell class, augmented with routing functionality.
*/
module.exports = function (_Weddell) {
return _Weddell.plugin({
id: 'router',
classes: {
App: Mixin(function (App) {
/**
* A decorated Weddell class will generate an App class with routing functionality.
*
* @extends App
*/
return class extends App {
/**
* App routing hook. Fires after a location match has been made against the routed path, but before the routing event has started.
*
* @returns {Promise} Routing may be deferred by returning a Promise in this method.
*/
onBeforeRoute() { }
/**
* Augments the App constructor with new parameters and events.
*
* @param {object} opts
* @param {RouteObject[]} opts.routes Specifies routes that will be available to this app, matching location.path against the component tree.
*
*/
constructor(opts) {
super(opts);
this.router = new Router({
routes: opts.routes,
/**
* Router object callback that maps the routing result to the Weddell app and its configured routes.
*
* @private
* @fires App#routematched
* @fires App#route
* @returns {Promise}
*/
onRoute: function (matches, componentNames) {
var jobs = [];
this.el.classList.add('routing');
this.el.setAttribute('data-current-route', matches.route.name);
if (matches.isRouteUpdate) {
this.el.classList.add('route-update');
if (matches.keepUpdateScrollPos) {
this.el.classList.add('keep-scroll-pos');
}
}
this.trigger('routematched', { matches });
return Promise.resolve(this.onBeforeRoute.call(this, { matches, componentNames }))
.then(() => {
this.el.classList.add('prerouting-finished');
return componentNames
.map(componentName => componentName.toLowerCase())
.reduce((promise, componentName) => {
return promise
.then(currentComponent => {
return currentComponent.getInitComponentInstance(componentName, 'router')
.then(component => {
if (!component) return Promise.reject('Failed to resolve ' + componentName + ' while routing.');// throw "Could not navigate to component " + key;
jobs.push({
component,
currentComponent,
componentName
});
return component;
});
})
}, Promise.resolve(this.component))
.then(lastComponent => {
jobs.push({
currentComponent: lastComponent,
component: null,
componentName: null
});
return jobs.reduce((promise, obj) => {
return promise
.then(() => obj.currentComponent.changeState.call(obj.currentComponent, obj.componentName, { matches }))
}, Promise.resolve())
.then(results =>
this.queuePatch()
.then(() => results));
}, console.warn)
.then(results => {
this.el.classList.remove('routing');
this.el.classList.remove('prerouting-finished');
this.el.classList.remove('route-update');
this.el.classList.remove('keep-scroll-pos');
this.trigger('route', { matches, results });
return results;
})
})
}.bind(this),
onHashChange: function (hash) {
return hash;
}.bind(this)
});
this.on('createcomponent', evt => {
function serializeRouteMatches(routeMatches) {
return Object.assign(JSON.parse(JSON.stringify(routeMatches)), JSON.parse(JSON.stringify(Object.assign({}, routeMatches))))
}
const state = evt.component.state;
this.on('routematched', ({ matches }) => {
state.$currentMatchedRoute = serializeRouteMatches(matches);
state.$matchedPathParams = matches.paramVals;
state.$currentMatchedRouteName = matches.route.name;
});
this.on('route', ({ matches, results }) => {
state.$currentRoute = serializeRouteMatches(matches);
state.$pathParams = matches.paramVals;
state.$currentRouteName = matches.route.name;
});
if (this.router.currentRoute) {
state.$currentRoute = state.$currentMatchedRoute = serializeRouteMatches(this.router.currentRoute);
state.$currentRouteName = state.$currentMatchedRouteName = this.router.currentRoute && this.router.currentRoute.route.name;
state.$pathParams = state.$matchedPathParams = this.router.currentRoute.paramVals;
}
});
}
/**
* Augments root component initialization to also initialize the app's router.
*
* @param {object} initObj
* @property {String} [initObj.initialPath] Path to match at initialization. Defaults to location.pathname
*/
initRootComponent(initObj) {
return super.initRootComponent(initObj)
.then(() => this.router.init(initObj.initialPath))
}
async makeComponent(componentOpts = {}) {
componentOpts = defaults({
router: this.router
}, componentOpts);
return super.makeComponent(componentOpts);
}
}
}),
Component: Mixin(function (Component) {
var RouterComponent = class extends mix(Component).with(StateMachineMixin) {
/**
* Component routing hook. Fires during the routing process, when a component in the component tree has been matched to a route in the route tree.
*
* If the matched route is not the current route, the current routed component is exited.
*
* @param {RoutingEvent}
* @returns {Promise} Routing may be deferred by overriding this method with one that returns a Promise.
*/
onExit() { }
/**
* Component routing hook. Fires during the routing process, after a component in the component tree has been matched to a route in the route tree.
*
* After the current component is exited, the newly matched component is entered.
*
* @param {RoutingEvent}
* @returns {Promise} Routing may be deferred by returning a Promise in this method.
*/
onEnter() { }
/**
* Component routing hook. Fires during the routing process, after a component in the component tree has been matched to a route in the route tree.
*
* If the matched route is the currently matched route, the component will be updated instead of being exited or entered.
*
* @param {RoutingEvent}
* @returns {Promise} Routing may be deferred by returning a Promise in this method.
*/
onUpdate() { }
/**
* Component routing hook. Fires during the routing process, after a component in the component tree has been matched to a route in the route tree.
*
* Whether the component is updated or entered, this hook will fire in addition to the respective primary hook.
*
* @param {RoutingEvent}
* @returns {Promise} Routing may be deferred by returning a Promise in this method.
*/
onEnterOrUpdate() { }
static get tagDirectives() {
return defaults({
routerview: function (vNode, content, props, renderedComponents) {
return this.currentState ? this.makeChildComponentWidget(this.currentState.componentName, 'router', content, props, renderedComponents) : null;
}
}, super.tagDirectives)
}
async makeComponentInstance(componentName, index, componentOpts = {}) {
componentOpts = defaults({
router: this.router
}, componentOpts);
return super.makeComponentInstance(componentName, index, componentOpts);
}
constructor(opts) {
opts.stateClass = RouterState;
var self;
super(defaults(opts, {
consts: defaults({
$routerLink: function () {
return self.compileRouterLink.apply(self, arguments);
},
$router: opts.router
}, opts.consts || {}),
state: defaults({
$currentRoute: null,
$currentRouteName: null,
$pathParams: null,
$currentMatchedRoute: null,
$currentMatchedRouteName: null,
$matchedPathParams: null
}, opts.state || {})
}));
Object.defineProperties(this, {
_initialRouterStateName: { value: opts.initialRouterStateName, writable: false },
router: { value: opts.router }
})
self = this;
this.on('init', () => {
Object.entries(this.components)
.forEach(entry => {
var componentName = entry[0]
var routerState = new RouterState([['onEnterState', ['onEnter', 'onEnterOrUpdate']], ['onExitState', 'onExit'], ['onUpdateState', ['onUpdate', 'onEnterOrUpdate']]].reduce((finalObj, methods) => {
var machineStateMethod = methods[0];
finalObj[machineStateMethod] = (evt) => {
var markDirty = async componentInstance => {
await this.markDirty()
return componentInstance
}
return this.getInitComponentInstance(componentName, 'router')
.then(markDirty)
.then(async componentInstance => {
var methodNames = methods[1];
if (!Array.isArray(methodNames)) {
methodNames = [methodNames]
}
await Promise.all(
methodNames.map(methodName =>
componentInstance[methodName].call(componentInstance, Object.assign({}, evt))
)
)
return componentInstance
})
.then(markDirty)
}
return finalObj;
}, {
Component: entry[1],
componentName
}));
this.addState(componentName, routerState);
});
})
}
compileRouterLink(obj) {
var matches = this.router.compileRouterLink(obj);
if (matches && typeof matches === 'object') {
return matches.fullPath + (matches.hash ? '#' + matches.hash : '');
} else if (typeof matches === 'string') {
return matches;
}
}
route(pathname) {
this.router.route(pathname);
}
}
return RouterComponent;
}),
Router
}
});
}
| mit |
longde123/MultiversePlatform | client/Movie/Codecs/DirectShowLib/TvRatings.cs | 9176 | /********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
#region license
/*
DirectShowLib - Provide access to DirectShow interfaces via .NET
Copyright (C) 2006
http://sourceforge.net/projects/directshownet/
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#endregion
using System;
using System.Runtime.InteropServices;
namespace DirectShowLib.BDA
{
#region Declarations
#if ALLOW_UNTESTED_INTERFACES
/// <summary>
/// From EnTvRat_System
/// </summary>
public enum EnTvRat_System
{
MPAA = 0,
US_TV = 1,
Canadian_English = 2,
Canadian_French = 3,
Reserved4 = 4,
System5 = 5,
System6 = 6,
Reserved7 = 7,
TvRat_kSystems = 8,
TvRat_SystemDontKnow = 255
}
/// <summary>
/// From EnTvRat_GenericLevel
/// </summary>
public enum EnTvRat_GenericLevel
{
TvRat_0 = 0,
TvRat_1 = 1,
TvRat_2 = 2,
TvRat_3 = 3,
TvRat_4 = 4,
TvRat_5 = 5,
TvRat_6 = 6,
TvRat_7 = 7,
TvRat_kLevels = 8,
TvRat_LevelDontKnow = 255
}
/// <summary>
/// From EnTvRat_MPAA
/// </summary>
public enum EnTvRat_MPAA
{
MPAA_NotApplicable = EnTvRat_GenericLevel.TvRat_0,
MPAA_G = EnTvRat_GenericLevel.TvRat_1,
MPAA_PG = EnTvRat_GenericLevel.TvRat_2,
MPAA_PG13 = EnTvRat_GenericLevel.TvRat_3,
MPAA_R = EnTvRat_GenericLevel.TvRat_4,
MPAA_NC17 = EnTvRat_GenericLevel.TvRat_5,
MPAA_X = EnTvRat_GenericLevel.TvRat_6,
MPAA_NotRated = EnTvRat_GenericLevel.TvRat_7
}
/// <summary>
/// From EnTvRat_US_TV
/// </summary>
public enum EnTvRat_US_TV
{
US_TV_None = EnTvRat_GenericLevel.TvRat_0,
US_TV_Y = EnTvRat_GenericLevel.TvRat_1,
US_TV_Y7 = EnTvRat_GenericLevel.TvRat_2,
US_TV_G = EnTvRat_GenericLevel.TvRat_3,
US_TV_PG = EnTvRat_GenericLevel.TvRat_4,
US_TV_14 = EnTvRat_GenericLevel.TvRat_5,
US_TV_MA = EnTvRat_GenericLevel.TvRat_6,
US_TV_None7 = EnTvRat_GenericLevel.TvRat_7
}
/// <summary>
/// From EnTvRat_CAE_TV
/// </summary>
public enum EnTvRat_CAE_TV
{
CAE_TV_Exempt = EnTvRat_GenericLevel.TvRat_0,
CAE_TV_C = EnTvRat_GenericLevel.TvRat_1,
CAE_TV_C8 = EnTvRat_GenericLevel.TvRat_2,
CAE_TV_G = EnTvRat_GenericLevel.TvRat_3,
CAE_TV_PG = EnTvRat_GenericLevel.TvRat_4,
CAE_TV_14 = EnTvRat_GenericLevel.TvRat_5,
CAE_TV_18 = EnTvRat_GenericLevel.TvRat_6,
CAE_TV_Reserved = EnTvRat_GenericLevel.TvRat_7
}
/// <summary>
/// From EnTvRat_CAF_TV
/// </summary>
public enum EnTvRat_CAF_TV
{
CAF_TV_Exempt = EnTvRat_GenericLevel.TvRat_0,
CAF_TV_G = EnTvRat_GenericLevel.TvRat_1,
CAF_TV_8 = EnTvRat_GenericLevel.TvRat_2,
CAF_TV_13 = EnTvRat_GenericLevel.TvRat_3,
CAF_TV_16 = EnTvRat_GenericLevel.TvRat_4,
CAF_TV_18 = EnTvRat_GenericLevel.TvRat_5,
CAF_TV_Reserved6 = EnTvRat_GenericLevel.TvRat_6,
CAF_TV_Reserved = EnTvRat_GenericLevel.TvRat_7
}
/// <summary>
/// From BfEnTvRat_GenericAttributes
/// </summary>
[Flags]
public enum BfEnTvRat_GenericAttributes
{
BfAttrNone = 0,
BfIsBlocked = 1,
BfIsAttr_1 = 2,
BfIsAttr_2 = 4,
BfIsAttr_3 = 8,
BfIsAttr_4 = 16,
BfIsAttr_5 = 32,
BfIsAttr_6 = 64,
BfIsAttr_7 = 128,
BfValidAttrSubmask = 255
}
/// <summary>
/// From BfEnTvRat_Attributes_US_TV
/// </summary>
[Flags]
public enum BfEnTvRat_Attributes_US_TV
{
None = 0,
IsBlocked = BfEnTvRat_GenericAttributes.BfIsBlocked,
IsViolent = BfEnTvRat_GenericAttributes.BfIsAttr_1,
IsSexualSituation = BfEnTvRat_GenericAttributes.BfIsAttr_2,
IsAdultLanguage = BfEnTvRat_GenericAttributes.BfIsAttr_3,
IsSexuallySuggestiveDialog = BfEnTvRat_GenericAttributes.BfIsAttr_4,
ValidAttrSubmask = 31
}
/// <summary>
/// From BfEnTvRat_Attributes_MPAA
/// </summary>
[Flags]
public enum BfEnTvRat_Attributes_MPAA
{
None = 0,
MPAA_IsBlocked = BfEnTvRat_GenericAttributes.BfIsBlocked,
MPAA_ValidAttrSubmask = 1
}
/// <summary>
/// From BfEnTvRat_Attributes_CAE_TV
/// </summary>
[Flags]
public enum BfEnTvRat_Attributes_CAE_TV
{
None = 0,
CAE_IsBlocked = BfEnTvRat_GenericAttributes.BfIsBlocked,
CAE_ValidAttrSubmask = 1
}
/// <summary>
/// From BfEnTvRat_Attributes_CAF_TV
/// </summary>
[Flags]
public enum BfEnTvRat_Attributes_CAF_TV
{
None = 0,
CAF_IsBlocked = BfEnTvRat_GenericAttributes.BfIsBlocked,
CAF_ValidAttrSubmask = 1
}
[ComImport, Guid("C5C5C5F0-3ABC-11D6-B25B-00C04FA0C026")]
public class XDSToRat
{
}
[ComImport, Guid("C5C5C5F1-3ABC-11D6-B25B-00C04FA0C026")]
public class EvalRat
{
}
#endif
#endregion
#region Interfaces
#if ALLOW_UNTESTED_INTERFACES
[ComImport,
Guid("C5C5C5B0-3ABC-11D6-B25B-00C04FA0C026"),
InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IXDSToRat
{
[PreserveSig]
int Init();
[PreserveSig]
int ParseXDSBytePair(
[In] byte byte1,
[In] byte byte2,
[Out] out EnTvRat_System pEnSystem,
[Out] out EnTvRat_GenericLevel pEnLevel,
[Out] BfEnTvRat_GenericAttributes plBfEnAttributes
);
}
[ComImport,
Guid("C5C5C5B1-3ABC-11D6-B25B-00C04FA0C026"),
InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IEvalRat
{
[PreserveSig]
int get_BlockedRatingAttributes(
[In] EnTvRat_System enSystem,
[In] EnTvRat_GenericLevel enLevel,
[Out] out BfEnTvRat_GenericAttributes plbfAttrs
);
[PreserveSig]
int put_BlockedRatingAttributes(
[In] EnTvRat_System enSystem,
[In] EnTvRat_GenericLevel enLevel,
[In] BfEnTvRat_GenericAttributes plbfAttrs
);
[PreserveSig]
int get_BlockUnRated([Out, MarshalAs(UnmanagedType.Bool)] out bool pfBlockUnRatedShows);
[PreserveSig]
int put_BlockUnRated([In, MarshalAs(UnmanagedType.Bool)] bool pfBlockUnRatedShows);
[PreserveSig]
int MostRestrictiveRating(
[In] EnTvRat_System enSystem1,
[In] EnTvRat_GenericLevel enEnLevel1,
[In] BfEnTvRat_GenericAttributes lbfEnAttr1,
[In] EnTvRat_System enSystem2,
[In] EnTvRat_GenericLevel enEnLevel2,
[In] BfEnTvRat_GenericAttributes lbfEnAttr2,
[Out] out EnTvRat_System penSystem,
[Out] out EnTvRat_GenericLevel penEnLevel,
[Out] out BfEnTvRat_GenericAttributes plbfEnAttr
);
[PreserveSig]
int TestRating(
[In] EnTvRat_System enShowSystem,
[In] EnTvRat_GenericLevel enShowLevel,
[In] BfEnTvRat_GenericAttributes lbfEnShowAttributes
);
}
#endif
#endregion
}
| mit |
pakoito/DT3 | DT3Core/Types/FileBuffer/Package.hpp | 2756 | #ifndef DT3_PACKAGE
#define DT3_PACKAGE
//==============================================================================
///
/// File: Package.hpp
///
/// Copyright (C) 2000-2014 by Smells Like Donkey Software Inc. All rights reserved.
///
/// This file is subject to the terms and conditions defined in
/// file 'LICENSE.txt', which is part of this source code package.
///
//==============================================================================
#include "DT3Core/Types/Base/BaseClass.hpp"
#include "DT3Core/Types/FileBuffer/FilePath.hpp"
#include <string>
#include <map>
//==============================================================================
//==============================================================================
namespace DT3 {
//==============================================================================
/// Forward declarations
//==============================================================================
//==============================================================================
/// Class
//==============================================================================
class Package: public BaseClass {
public:
DEFINE_TYPE(Package,BaseClass)
DEFINE_CREATE
Package (void);
private:
Package (const Package &rhs);
Package & operator = (const Package &rhs);
public:
virtual ~Package (void);
public:
/// Loads a package and indexes it
/// \param pathname path to package
/// \return Error
DTerr load_package (const FilePath &pathname);
/// Retrieve information about a file from the package
/// \param pathname path to file
/// \param start start of file
/// \param length length of file
/// \param uncompressed_length uncompressed length of file
/// \return description
DTerr start_and_length (const FilePath &pathname, DTsize &start, DTsize &length, DTsize &uncompressed_length) const;
/// Get Package Start
// DTsize offset (void) const { return _offset; }
private:
struct Entry {
std::string _name;
DTsize _start;
DTsize _length;
DTsize _uncompressed_length;
};
DTsize _offset;
std::map<std::string, Entry> _entries;
};
//==============================================================================
//==============================================================================
} // DT3
#endif
| mit |
ggustilo/rails_blog | peanut_gallery/config/routes.rb | 2530 | Rails.application.routes.draw do
# homepage
get "/" => "posts#index"
# login and writers routes
get "/login" => "writers#login_form"
post "/login" => "writers#login"
delete "/logout" => "writers#logout"
get "/register" => "writers#new"
post "/register" => "writers#create"
get "/writers/:id" => "writers#show"
get "/writers/:id/public" => "writers#public_show"
get "/writers/:id/edit" => "writers#edit"
patch "/writers/:id" => "writers#update"
put "/writers/:id" => "writers#update"
delete "/writers/:id" => "writers#destroy"
# posts by type
get "/posts/active_posts" => "posts#active_posts"
get "/posts/economics_posts" => "posts#economics_posts"
get "/posts/environment_posts" => "posts#environment_posts"
get "/posts/politics_posts" => "posts#politics_posts"
get "/posts/social_values_posts" => "posts#social_values_posts"
get "/posts/education_posts" => "posts#education_posts"
get "/posts/religion_posts" => "posts#religion_posts"
get "/posts/health_posts" => "posts#health_posts"
get "/posts/foreign_policy_posts" => "posts#foreign_policy_posts"
get "/posts/military_posts" => "posts#military_posts"
get "/posts/science_technology_posts" => "posts#science_technology_posts"
# posts routes
get "/posts/new" => "posts#new"
post "/posts" => "posts#create"
get "/posts/:id" => "posts#show", as: "posts_show"
post "/posts/:id/publish" => "posts#publish", as: "posts_published"
get "/posts/:id/edit" => "posts#edit"
patch "/posts/:id" => "posts#update"
put "/posts/:id" => "posts#update"
delete "/posts/:id" => "posts#destroy"
post "/posts/:id/upvote" => "posts#upvote", as: "posts_upvote"
post "/posts/:id/downvote" => "posts#downvote", as: "posts_downvote"
post "/posts/:id/flag" => "posts#flag", as: "posts_flag"
# responses routes
get "/posts/:post_id/responses/new" => "responses#new"
post "/responses" => "responses#create"
get "/responses/:id" => "responses#show", as: "responses_show"
get "/responses/:id/edit" => "responses#edit"
patch "/responses/:id" => "responses#update"
put "/responses/:id" => "responses#update"
delete "/responses/:id" => "responses#destroy"
get "/responses" => "responses#index"
post "/responses/:id" => "responses#approve", as: "responses_approve"
post "/responses/:id/upvote" => "responses#upvote", as: "responses_upvote"
post "/responses/:id/downvote" => "responses#downvote", as: "responses_downvote"
post "/responses/:id/flag" => "responses#flag", as: "responses_flag"
end
| mit |
dgg/Papayoo-Scores | app/src/main/java/net/dgg/papayoo_scores/core/BusObserver.java | 298 | package net.dgg.papayoo_scores.core;
import com.squareup.otto.Bus;
public class BusObserver implements IObserver{
private final Bus _bus;
public BusObserver(Bus bus){
_bus = bus;
}
@Override
public void notify(Object message) {
_bus.post(message);
}
}
| mit |
MaxZoosk/johnny-five-build-light | node_modules/johnny-five/lib/motor.js | 22621 | var IS_TEST_MODE = !!process.env.IS_TEST_MODE;
var Board = require("./board");
var Expander = require("./expander.js");
var EVS = require("./evshield");
var __ = require("./fn");
var events = require("events");
var util = require("util");
var Collection = require("./mixins/collection");
var Sensor = require("./sensor");
var ShiftRegister = require("./shiftregister");
var priv = new Map();
var registers = new Map();
function registerKey(registerOpts) {
return ["clock", "data", "latch"].reduce(function(accum, key) {
return accum + "." + registerOpts[key];
}, "");
}
function latch(state, bit, on) {
return on ? state |= (1 << bit) : state &= ~(1 << bit);
}
function updateShiftRegister(motor, dir) {
var rKey = registerKey(motor.opts.register),
register = registers.get(motor.board)[rKey],
latchState = register.value,
bits = priv.get(motor).bits,
forward = dir !== "reverse";
// There are two ShiftRegister bits which we need to change based on the
// direction of the motor. These will be the pins that control the HBridge
// on the board. They will get flipped high/low based on the current flow
// in the HBridge.
latchState = latch(latchState, bits.a, forward);
latchState = latch(latchState, bits.b, !forward);
if (register.value !== latchState) {
register.send(latchState);
}
}
var Controllers = {
ShiftRegister: {
initialize: {
value: function(opts) {
var rKey = registerKey(opts.register);
if (!opts.bits || opts.bits.a === undefined || opts.bits.b === undefined) {
throw new Error("ShiftRegister Motors MUST contain HBRIDGE bits {a, b}");
}
priv.get(this).bits = opts.bits;
if (!registers.has(this.board)) {
registers.set(this.board, {});
}
if (!registers.get(this.board)[rKey]) {
registers.get(this.board)[rKey] = new ShiftRegister({
board: this.board,
pins: opts.register
});
}
this.io.pinMode(this.pins.pwm, this.io.MODES.PWM);
}
},
dir: {
value: function(dir) {
this.stop();
updateShiftRegister(this, dir.name);
this.direction = dir;
process.nextTick(this.emit.bind(this, dir.name));
return this;
}
}
},
PCA9685: {
setPWM: {
writable: true,
value: function(pin, speed) {
var state = priv.get(this);
state.expander.analogWrite(pin, speed);
}
},
setPin: {
writable: true,
value: function(pin, value) {
var state = priv.get(this);
state.expander.digitalWrite(pin, value);
}
},
initialize: {
value: function(opts) {
var state = priv.get(this);
this.address = opts.address || 0x40;
this.pwmRange = opts.pwmRange || [0, 4080];
this.frequency = opts.frequency || 50;
state.expander = Expander.get({
address: this.address,
controller: this.controller,
bus: this.bus,
pwmRange: this.pwmRange,
frequency: this.frequency,
});
Object.keys(this.pins).forEach(function(pinName) {
this.pins[pinName] = state.expander.normalize(this.pins[pinName]);
}, this);
}
}
},
EVS_EV3: {
initialize: {
value: function(opts) {
var state = priv.get(this);
state.shield = EVS.shieldPort(opts.pin);
state.ev3 = new EVS(Object.assign(opts, {
io: this.io
}));
this.opts.pins = {
pwm: opts.pin,
dir: opts.pin,
};
}
},
setPWM: {
value: function(pin, value) {
var state = priv.get(this);
var register = state.shield.motor === EVS.M1 ? EVS.SPEED_M1 : EVS.SPEED_M2;
var speed = __.scale(value, 0, 255, 0, 100) | 0;
if (value === 0) {
state.ev3.write(state.shield, EVS.COMMAND, EVS.Motor_Reset);
} else {
if (!this.direction.value) {
speed = -speed;
}
var data = [
// 0-100
speed,
// Duration (0 is forever)
0,
// Command B
0,
// Command A
EVS.CONTROL_SPEED | EVS.CONTROL_GO
];
state.ev3.write(state.shield, register, data);
}
}
},
setPin: {
value: function(pin, value) {
this.setPWM(this.pin, value);
}
},
},
GROVE_I2C_MOTOR_DRIVER: {
REGISTER: {
value: {
ADDRESS: 0x0F,
}
},
COMMANDS: {
value: {
SET_SPEED: 0x82,
SET_PWM_FREQUENCY: 0x84,
SET_DIRECTION: 0xAA,
NOOP: 0x01,
}
},
initialize: {
value: function(opts) {
var state = priv.get(this);
var shared = priv.get("GROVE_I2C_MOTOR_DRIVER");
if (!shared) {
shared = {
direction: {
A: 0x01,
B: 0x01,
},
speed: {
A: 0,
B: 0,
}
};
priv.set("GROVE_I2C_MOTOR_DRIVER", shared);
}
state.shared = shared;
state.pin = opts.pin.toUpperCase();
this.opts.pins = {
pwm: opts.pin,
dir: opts.pin,
};
this.address = opts.address || this.REGISTER.ADDRESS;
opts.address = this.address;
this.io.i2cConfig(opts);
}
},
setPWM: {
value: function(pin, value) {
var state = priv.get(this);
var speed = Board.constrain(value, 0, 255) | 0;
state.shared.speed[state.pin] = speed;
this.io.i2cWrite(this.address, [
this.COMMANDS.SET_SPEED,
state.shared.speed.A,
state.shared.speed.B,
]);
}
},
setPin: {
value: function(pin, value) {
var state = priv.get(this);
// DIR_CCW = 0x02
// DIR_CW = 0x01
state.shared.direction[state.pin] = value ? 0x01 : 0x02;
var a = state.shared.direction.A & 0x03;
var b = state.shared.direction.B & 0x03;
var direction = (b << 2) | a;
this.io.i2cWrite(this.address, [
this.COMMANDS.SET_DIRECTION,
direction,
this.COMMANDS.NOOP,
]);
}
}
}
};
// Aliases
//
// NXT motors have the exact same control commands as EV3 motors
Controllers.EVS_NXT = Controllers.EVS_EV3;
var Devices = {
NONDIRECTIONAL: {
pins: {
get: function() {
return {
pwm: this.opts.pin
};
}
},
dir: {
writable: true,
configurable: true,
value: function(speed) {
speed = speed || this.speed();
return this;
}
},
resume: {
value: function() {
var speed = this.speed();
this.speed({
speed: speed
});
return this;
}
}
},
DIRECTIONAL: {
pins: {
get: function() {
if (Array.isArray(this.opts.pins)) {
return {
pwm: this.opts.pins[0],
dir: this.opts.pins[1]
};
} else {
return this.opts.pins;
}
}
},
dir: {
writable: true,
configurable: true,
value: function(dir) {
this.stop();
this.setPin(this.pins.dir, dir.value);
this.direction = dir;
process.nextTick(this.emit.bind(this, dir.name));
return this;
}
}
},
CDIR: {
pins: {
get: function() {
if (Array.isArray(this.opts.pins)) {
return {
pwm: this.opts.pins[0],
dir: this.opts.pins[1],
cdir: this.opts.pins[2]
};
} else {
return this.opts.pins;
}
}
},
dir: {
value: function(dir) {
this.stop();
this.direction = dir;
this.setPin(this.pins.cdir, 1 ^ dir.value);
this.setPin(this.pins.dir, dir.value);
process.nextTick(this.emit.bind(this, dir.name));
return this;
}
},
brake: {
value: function(duration) {
this.speed({
speed: 0,
saveSpeed: false
});
this.setPin(this.pins.dir, 1, 127);
this.setPin(this.pins.cdir, 1, 128, 127);
this.speed({
speed: 255,
saveSpeed: false,
braking: true
});
process.nextTick(this.emit.bind(this, "brake"));
if (duration) {
var motor = this;
this.board.wait(duration, function() {
motor.stop();
});
}
return this;
}
}
}
};
/**
* Motor
* @constructor
*
* @param {Object} opts Options: pin|pins{pwm, dir[, cdir]}, device, controller, current
* @param {Number} pin A single pin for basic
* @param {Array} pins A two or three digit array of pins [pwm, dir]|[pwm, dir, cdir]
*
*
* Initializing "Hobby Motors"
*
* new five.Motor(9);
*
* ...is the same as...
*
* new five.Motor({
* pin: 9
* });
*
*
* Initializing 2 pin, Bi-Directional DC Motors:
*
* new five.Motor([ 3, 12 ]);
*
* ...is the same as...
*
* new five.Motor({
* pins: [ 3, 12 ]
* });
*
* ...is the same as...
*
* new five.Motor({
* pins: {
* pwm: 3,
* dir: 12
* }
* });
*
*
* Initializing 3 pin, I2C PCA9685 Motor Controllers:
* i.e. The Adafruit Motor Shield V2
*
* new five.Motor({
* pins: [ 8, 9, 10 ],
* controller: "PCA9685",
* address: 0x60
* });
*
*
* Initializing 3 pin, Bi-Directional DC Motors:
*
* new five.Motor([ 3, 12, 11 ]);
*
* ...is the same as...
*
* new five.Motor({
* pins: [ 3, 12, 11 ]
* });
*
* ...is the same as...
*
* new five.Motor({
* pins: {
* pwm: 3,
* dir: 12,
* cdir: 11
* }
* });
*
*
* Initializing Bi-Directional DC Motors with brake:
*
* new five.Motor({
* pins: {
* pwm: 3,
* dir: 12,
* brake: 11
* }
* });
*
*
* Initializing Bi-Directional DC Motors with current sensing pins:
* See Sensor.js for details on options
*
* new five.Motor({
* pins: [3, 12],
* current: {
* pin: "A0",
* freq: 250,
* range: [0, 2000]
* }
* });
*
*
* Initializing Bi-Directional DC Motors with inverted speed for reverse:
* Most likely used for non-commercial H-Bridge controllers
*
* new five.Motor({
* pins: [3, 12],
* invertPWM: true
* });
*
*/
function Motor(opts) {
var device, controller, state;
if (!(this instanceof Motor)) {
return new Motor(opts);
}
Board.Component.call(
this, this.opts = Board.Options(opts)
);
controller = opts.controller || null;
// Derive device based on pins passed
if (typeof this.opts.device === "undefined") {
this.opts.device = (typeof this.opts.pins === "undefined" && typeof this.opts.register !== "object") ?
"NONDIRECTIONAL" : "DIRECTIONAL";
if (this.opts.pins && (this.opts.pins.cdir || this.opts.pins.length > 2)) {
this.opts.device = "CDIR";
}
if (typeof controller === "string" &&
(controller.startsWith("EVS") || controller.startsWith("GROVE_I2C"))) {
this.opts.device = "DIRECTIONAL";
}
}
// Allow users to pass in custom device types
device = typeof this.opts.device === "string" ?
Devices[this.opts.device] : this.opts.device;
this.threshold = typeof this.opts.threshold !== "undefined" ?
this.opts.threshold : 30;
this.invertPWM = typeof this.opts.invertPWM !== "undefined" ?
this.opts.invertPWM : false;
Object.defineProperties(this, device);
if (this.opts.register) {
this.opts.controller = "ShiftRegister";
}
/**
* Note: Controller decorates the device. Used for adding
* special controllers (i.e. PCA9685)
**/
if (this.opts.controller) {
controller = typeof this.opts.controller === "string" ?
Controllers[this.opts.controller] : this.opts.controller;
Board.Controller.call(this, controller, opts);
}
// current just wraps a Sensor
if (this.opts.current) {
this.opts.current.board = this.board;
this.current = new Sensor(this.opts.current);
}
// Create a "state" entry for privately
// storing the state of the motor
state = {
isOn: false,
currentSpeed: typeof this.opts.speed !== "undefined" ?
this.opts.speed : 128,
braking: false,
enabled: true
};
priv.set(this, state);
Object.defineProperties(this, {
// Calculated, read-only motor on/off state
// true|false
isOn: {
get: function() {
return state.isOn;
}
},
currentSpeed: {
get: function() {
return state.currentSpeed;
}
},
braking: {
get: function() {
return state.braking;
}
},
enabled: {
get: function() {
return state.enabled;
}
}
});
// We need to store and initialize the state of the dir pin(s)
this.direction = {
value: 1
};
if (this.initialize) {
this.initialize(opts);
}
this.enable();
this.dir(this.direction);
}
util.inherits(Motor, events.EventEmitter);
Motor.prototype.initialize = function() {
this.io.pinMode(this.pins.pwm, this.io.MODES.PWM);
["dir", "cdir", "brake", "enable"].forEach(function(pin) {
if (typeof this.pins[pin] !== "undefined") {
this.io.pinMode(this.pins[pin], this.io.MODES.OUTPUT);
}
}, this);
};
Motor.prototype.setPin = function(pin, value) {
this.io.digitalWrite(pin, value);
};
Motor.prototype.setPWM = function(pin, value) {
this.io.analogWrite(pin, value);
};
Motor.prototype.speed = function(opts) {
var state = priv.get(this);
if (typeof opts === "undefined") {
return state.currentSpeed;
} else {
if (typeof opts === "number") {
opts = {
speed: opts
};
}
opts.speed = Board.constrain(opts.speed, 0, 255);
opts.saveSpeed = typeof opts.saveSpeed !== "undefined" ?
opts.saveSpeed : true;
if (opts.speed < this.threshold) {
opts.speed = 0;
}
state.isOn = opts.speed === 0 ? false : true;
if (opts.saveSpeed) {
state.currentSpeed = opts.speed;
}
if (opts.braking) {
state.braking = true;
}
if (this.invertPWM && this.direction.value === 1) {
opts.speed ^= 0xff;
}
this.setPWM(this.pins.pwm, opts.speed);
return this;
}
};
// start a motor - essentially just switch it on like a normal motor
Motor.prototype.start = function(speed) {
// Send a signal to turn on the motor and run at given speed in whatever
// direction is currently set.
if (this.pins.brake && this.braking) {
this.setPin(this.pins.brake, 0);
}
// get current speed if nothing provided.
speed = typeof speed !== "undefined" ?
speed : this.speed();
this.speed({
speed: speed,
braking: false
});
// "start" event is fired when the motor is started
if (speed > 0) {
process.nextTick(this.emit.bind(this, "start"));
}
return this;
};
Motor.prototype.stop = function() {
this.speed({
speed: 0,
saveSpeed: false
});
process.nextTick(this.emit.bind(this, "stop"));
return this;
};
Motor.prototype.brake = function(duration) {
if (typeof this.pins.brake === "undefined") {
if (this.board.io.name !== "Mock") {
console.log("Non-braking motor type");
}
this.stop();
} else {
this.setPin(this.pins.brake, 1);
this.setPin(this.pins.dir, 1);
this.speed({
speed: 255,
saveSpeed: false,
braking: true
});
process.nextTick(this.emit.bind(this, "brake"));
if (duration) {
var motor = this;
this.board.wait(duration, function() {
motor.resume();
});
}
}
return this;
};
Motor.prototype.release = function() {
this.resume();
process.nextTick(this.emit.bind(this, "release"));
return this;
};
Motor.prototype.resume = function() {
var speed = this.speed();
this.dir(this.direction);
this.start(speed);
return this;
};
Motor.prototype.enable = function() {
var state = priv.get(this);
if (typeof this.pins.enable !== "undefined" && !this.enabled) {
this.setPin(this.pins.enable, 1);
state.enabled = true;
}
};
Motor.prototype.disable = function() {
var state = priv.get(this);
if (typeof this.pins.enable !== "undefined" && this.enabled) {
this.setPin(this.pins.enable, 0);
state.enabled = false;
}
};
[
/**
* forward Turn the Motor in its forward direction
* fwd Turn the Motor in its forward direction
*
* @param {Number} 0-255, 0 is stopped, 255 is fastest
* @return {Object} this
*/
{
name: "forward",
abbr: "fwd",
value: 1
},
/**
* reverse Turn the Motor in its reverse direction
* rev Turn the Motor in its reverse direction
*
* @param {Number} 0-255, 0 is stopped, 255 is fastest
* @return {Object} this
*/
{
name: "reverse",
abbr: "rev",
value: 0
}
].forEach(function(dir) {
var method = function(speed) {
this.dir(dir);
this.start(speed);
return this;
};
Motor.prototype[dir.name] = Motor.prototype[dir.abbr] = method;
});
Motor.SHIELD_CONFIGS = {
ADAFRUIT_V1: {
M1: {
pins: {
pwm: 11
},
register: {
data: 8,
clock: 4,
latch: 12
},
bits: {
a: 2,
b: 3
}
},
M2: {
pins: {
pwm: 3
},
register: {
data: 8,
clock: 4,
latch: 12
},
bits: {
a: 1,
b: 4
}
},
M3: {
pins: {
pwm: 6
},
register: {
data: 8,
clock: 4,
latch: 12
},
bits: {
a: 5,
b: 7
}
},
M4: {
pins: {
pwm: 5
},
register: {
data: 8,
clock: 4,
latch: 12
},
bits: {
a: 0,
b: 6
}
}
},
ADAFRUIT_V2: {
M1: {
pins: {
pwm: 8,
dir: 9,
cdir: 10
},
address: 0x60,
controller: "PCA9685"
},
M2: {
pins: {
pwm: 13,
dir: 12,
cdir: 11
},
address: 0x60,
controller: "PCA9685"
},
M3: {
pins: {
pwm: 2,
dir: 3,
cdir: 4
},
address: 0x60,
controller: "PCA9685"
},
M4: {
pins: {
pwm: 7,
dir: 6,
cdir: 5
},
address: 0x60,
controller: "PCA9685"
}
},
SEEED_STUDIO: {
A: {
pins: {
pwm: 9,
dir: 8,
cdir: 11
}
},
B: {
pins: {
pwm: 10,
dir: 12,
cdir: 13
}
}
},
FREETRONICS_HBRIDGE: {
A: {
pins: {
pwm: 6,
dir: 4,
cdir: 7
}
},
B: {
pins: {
pwm: 5,
dir: 3,
cdir: 2
}
}
},
ARDUINO_MOTOR_SHIELD_R3_1: {
A: {
pins: {
pwm: 3,
dir: 12
}
},
B: {
pins: {
pwm: 11,
dir: 13
}
}
},
ARDUINO_MOTOR_SHIELD_R3_2: {
A: {
pins: {
pwm: 3,
dir: 12,
brake: 9
}
},
B: {
pins: {
pwm: 11,
dir: 13,
brake: 8
}
}
},
ARDUINO_MOTOR_SHIELD_R3_3: {
A: {
pins: {
pwm: 3,
dir: 12,
brake: 9,
current: "A0"
}
},
B: {
pins: {
pwm: 11,
dir: 13,
brake: 8,
current: "A1"
}
}
},
DF_ROBOT: {
A: {
pins: {
pwm: 6,
dir: 7
}
},
B: {
pins: {
pwm: 5,
dir: 4
}
}
},
NKC_ELECTRONICS_KIT: {
A: {
pins: {
pwm: 9,
dir: 12
}
},
B: {
pins: {
pwm: 10,
dir: 13
}
}
},
RUGGED_CIRCUITS: {
A: {
pins: {
pwm: 3,
dir: 12
}
},
B: {
pins: {
pwm: 11,
dir: 13
}
}
},
SPARKFUN_ARDUMOTO: {
A: {
pins: {
pwm: 3,
dir: 12
}
},
B: {
pins: {
pwm: 11,
dir: 13
}
}
},
POLOLU_DRV8835_SHIELD: {
M1: {
pins: {
pwm: 9,
dir: 7
}
},
M2: {
pins: {
pwm: 10,
dir: 8
}
}
},
MICRO_MAGICIAN_V2: {
A: {
pins: {
pwm: 6,
dir: 8
},
invertPWM: true
},
B: {
pins: {
pwm: 5,
dir: 7
},
invertPWM: true
}
},
SPARKFUN_LUDUS: {
A: {
pins: {
pwm: 3,
dir: 4,
cdir: 5
}
},
B: {
pins: {
pwm: 6,
dir: 7,
cdir: 8
}
}
},
SPARKFUN_DUAL_HBRIDGE_EDISON_BLOCK: {
A: {
pins: {
pwm: 20,
dir: 33,
cdir: 46,
enable: 47
}
},
B: {
pins: {
pwm: 14,
dir: 48,
cdir: 36,
enable: 47
}
}
},
};
/**
* Motors()
* new Motors()
*
* Constructs an Array-like instance of all servos
*/
function Motors(numsOrObjects) {
if (!(this instanceof Motors)) {
return new Motors(numsOrObjects);
}
Object.defineProperty(this, "type", {
value: Motor
});
Collection.call(this, numsOrObjects);
}
Motors.prototype = Object.create(Collection.prototype, {
constructor: {
value: Motors
}
});
/*
* Motors, forward(speed)/fwd(speed)
*
* eg. array.forward(speed);
* Motors, reverse(speed)/rev(speed)
*
* eg. array.reverse(speed);
* Motors, start(speed)
*
* eg. array.start(speed);
* Motors, stop()
*
* eg. array.stop();
* Motors, brake()
*
* eg. array.brake();
* Motors, release()
*
* eg. array.release();
*/
Object.keys(Motor.prototype).forEach(function(method) {
// Create Motors wrappers for each method listed.
// This will allow us control over all Motor instances
// simultaneously.
Motors.prototype[method] = function() {
var length = this.length;
for (var i = 0; i < length; i++) {
this[i][method].apply(this[i], arguments);
}
return this;
};
});
if (IS_TEST_MODE) {
Motor.purge = function() {
priv.clear();
registers.clear();
};
}
// Assign Motors Collection class as static "method" of Motor.
Motor.Array = Motors;
module.exports = Motor;
// References
// http://arduino.cc/en/Tutorial/SecretsOfArduinoPWM
| mit |
techa03/goodsKill | goodskill-spring-boot-starter/src/main/java/com/goodskill/autoconfigure/oauth2/OAuth2LoginConfig.java | 4468 | package com.goodskill.autoconfigure.oauth2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties;
import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientPropertiesRegistrationAdapter;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import java.util.ArrayList;
import java.util.List;
/**
* 自定义OAuth2授权服务提供方配置
* 支持gitee码云OAuth2.0授权方式
*
* @author techa03
* @since 2021/3/21
*/
@Configuration(proxyBeanMethods = false)
//@ConfigurationProperties(prefix = "spring.security.oauth2.client.registration")
@EnableConfigurationProperties(OAuth2ClientProperties.class)
public class OAuth2LoginConfig {
@Value("${spring.security.oauth2.client.registration.goodskill.client-id}")
private String goodskillClientId;
@Value("${spring.security.oauth2.client.registration.goodskill.client-secret}")
private String goodskillClientSecret;
@Value("${spring.security.oauth2.client.registration.gitee.client-id}")
private String clientId;
@Value("${spring.security.oauth2.client.registration.gitee.client-secret}")
private String clientSecret;
@Bean
public ClientRegistrationRepository clientRegistrationRepository(OAuth2ClientProperties properties) {
properties.getRegistration().remove("gitee");
properties.getRegistration().remove("goodskill");
List<ClientRegistration> registrations = new ArrayList<>(
OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties).values());
registrations.add(giteeClientRegistration());
registrations.add(goodskillClientRegistration());
return new InMemoryClientRegistrationRepository(registrations);
}
private ClientRegistration giteeClientRegistration() {
return ClientRegistration.withRegistrationId("gitee")
.clientId(clientId)
.clientSecret(clientSecret)
.clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri("{baseUrl}/login/oauth2/code/{registrationId}")
.scope("user_info")
.authorizationUri("https://gitee.com/oauth/authorize")
.tokenUri("https://gitee.com/oauth/token")
.userInfoUri("https://gitee.com/api/v5/user")
.userNameAttributeName("id")
.clientName("Gitee")
.build();
}
private ClientRegistration goodskillClientRegistration() {
return ClientRegistration.withRegistrationId("goodskill")
.clientId(goodskillClientId)
.clientSecret(goodskillClientSecret)
.clientAuthenticationMethod(ClientAuthenticationMethod.BASIC)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri("{baseUrl}/login/oauth2/code/{registrationId}")
.scope("resource:read")
.authorizationUri("http://www.goodskill.com/oauth/authorize")
.tokenUri("http://www.goodskill.com/oauth/token")
.userInfoUri("http://www.goodskill.com/api/v5/user")
.userNameAttributeName("id")
.clientName("Goodskill")
.build();
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
public void setGoodskillClientId(String goodskillClientId) {
this.goodskillClientId = goodskillClientId;
}
public void setGoodskillClientSecret(String goodskillClientSecret) {
this.goodskillClientSecret = goodskillClientSecret;
}
}
| mit |
TristanBaoui/PB | src/PB/BijouterieBundle/DependencyInjection/PBBijouterieExtension.php | 764 | <?php
namespace PB\BijouterieBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class PBBijouterieExtension extends Extension
{
/**
* {@inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
}
}
| mit |
alkammar/morkim | examples/src/main/java/lib/morkim/examples/screen/ExampleNonGenericFragment.java | 349 | package lib.morkim.examples.screen;
import lib.morkim.examples.R;
import lib.morkim.mfw.ui.MorkimFragment;
/**
* Created by Kammar on 12/10/2016.
*/
public class ExampleNonGenericFragment extends MorkimFragment {
@Override
protected int layoutId() {
return R.layout.fragment_example;
}
@Override
public void onAssignListeners() {
}
}
| mit |
sairion/Loaderlet | src/loaderlet_bookmark.js | 371 | (function(window){
if(typeof(lodrlt)==="undefined"){
var l = document.createElement('script');
//l.setAttribute('type', 'text/javascript');
l.setAttribute('charset', 'UTF-8');
l.setAttribute('src', 'https://raw.github.com/sairion/Loaderlet/master/src/loaderlet_v0_01_min.js' + Math.random() * 99999999);
document.body.appendChild(l);
}
else{lodrlt();}
})(window); | mit |
mode777/electron-play | src/db.retro-play/platform.source.ts | 523 | import { Injectable } from "@angular/core";
import { DbSource, DbConnection } from "../db";
import { PlatformModel, PlatformEntity } from "./platform.model";
import { RetroPlayConnection } from "./retro-play.connection";
import { TableSource } from "../db/common/table.source";
@Injectable()
export class PlatformSource extends TableSource<PlatformModel, PlatformEntity> {
constructor(connection: RetroPlayConnection){
super(connection, (ent) => new PlatformModel(connection,ent, true), "platforms");
}
} | mit |
zoowii/readerproxy | RP/src/RP/controllers/SiteController.php | 5893 | <?php
/**
* Created by PhpStorm.
* User: zoowii
* Date: 14-2-3
* Time: 下午10:10
*/
namespace RP\controllers;
use RP\core\CCache;
use RP\models\Role;
use RP\models\User;
use RP\util\Common;
use RP\util\HttpClient;
use RP\util\UserCommon;
class SiteController extends BaseController
{
protected function routes()
{
$this->get('/', 'indexAction');
$this->get('/login', 'loginPageAction');
$this->post('/login', 'loginAction');
$this->get('/logout', 'logoutAction');
$this->get('/profile', 'profileAction');
$this->post('/sites/cross_proxy', 'crossProxyAction');
$this->get('/register', 'registerPageAction');
$this->post('/register', 'registerAction');
$this->post('/change_password', 'changePasswordAction');
}
public function indexAction()
{
$currentUser = $this->currentUser();
if (!$currentUser) {
return $this->redirect('/index.php/login');
}
$this->bind('title', '我的小工具们');
$this->bind('currentUser', $currentUser);
$this->bindAllFlashes();
return $this->render('site/index.php');
}
public function loginPageAction()
{
$this->bind('title', '登录');
$this->clearLayouts();
$this->setLayout('_layout/website.php');
$this->bindAllFlashes();
return $this->render('site/login.php');
}
public function registerPageAction()
{
$this->bind('title', '注册');
$this->clearLayouts();
$this->setLayout('_layout/website.php');
$this->bindAllFlashes();
return $this->render('site/register.php');
}
public function registerAction()
{
$username = $this->form('username');
$password = $this->form('password');
if (strlen($username) < 5) {
$this->errorFlash("用户名长度不允许小于5");
return $this->redirectToAction(null, 'registerPageAction');
}
if (strlen($password) < 5) {
$this->errorFlash('密码长度不允许小于5');
return $this->redirectToAction(null, 'registerPageAction');
}
$user = User::findByUsername($username);
if (!is_null($user)) {
$this->errorFlash("用户$username 已存在");
return $this->redirectToAction(null, 'registerPageAction');
}
$user = new User();
$user->username = $username;
$user->email = null;
$user->salt = Common::randomString(10);
$user->password = UserCommon::encryptPassword($password, $user->salt);
$commonRole = Role::getCommonUser();
$user->role_id = $commonRole->id;
$user->alias_name = $username;
$user->saveOrUpdate();
$this->successFlash("用户$username 注册成功!");
return $this->redirectToAction(null, 'loginPageAction');
}
/**
* 如果用户表为空,即初始化一个root用户,用于部署安装
*/
private function createRootUserIfEmpty()
{
$usersCount = $this->db()->count(User::getFullTableName());
if ($usersCount < 1) {
$user = new User();
$user->username = 'root';
$user->email = 'root@localhost';
$user->salt = Common::randomString(10);
$user->password = UserCommon::encryptPassword('root', $user->salt);
$rootRole = Role::getRootRole();
$user->role_id = $rootRole->id;
$user->alias_name = 'root';
$user->save();
}
}
public function loginAction()
{
$username = trim($this->form('username'));
$password = trim($this->form('password'));
$this->createRootUserIfEmpty();
$user = User::findByUsernameAndPassword($username, $password);
if ($user !== null && $user->isActive()) {
$this->login($user);
return $this->redirectToAction(null, 'indexAction');
} else {
$this->warningFlash('用户名或密码错误');
return $this->redirectToAction(null, 'loginPageAction');
}
}
public function logoutAction()
{
$this->logout();
return $this->redirectToAction(null, 'indexAction');
}
public function profileAction()
{
if ($this->isGuest()) {
return $this->redirectToAction(null, 'indexAction');
}
$currentUser = $this->currentUser();
$bindings = $currentUser->getAccountBindings();
$this->bind('user', $currentUser);
$this->bind('bindings', $bindings);
$this->bindAllFlashes();
return $this->render('site/profile.php');
}
public function changePasswordAction()
{
if ($this->isGuest()) {
$this->warningFlash('请先登录');
return $this->redirectToAction(null, 'profileAction');
}
$password = $this->form('password');
if (strlen($password) < 5) {
$this->warningFlash('密码长度需要不小于5');
return $this->redirectToAction(null, 'profileAction');
}
$user = $this->currentUser();
$user->password = UserCommon::encryptPassword($password, $user->salt);
$user->saveOrUpdate();
$this->successFlash('修改密码成功');
return $this->redirectToAction(null, 'profileAction');
}
/**
* 跨域代理,因为浏览器有不允许跨域的限制,所以从服务器中转一下
*/
public function crossProxyAction()
{
$url = $this->form('url');
$method = $this->form('method');
if (isset($_POST['params'])) {
$params = $this->form('params');
} else {
$params = array();
}
$res = HttpClient::fetch_page('proxy', $url, $method, $params);
return $res;
}
} | mit |
Department-for-Work-and-Pensions/ClaimCapture | c3/app/controllers/circs/report_changes/GBreaksInCareSummary.scala | 2255 | package controllers.circs.report_changes
import play.api.Play._
import play.api.mvc.Controller
import models.view.{CachedChangeOfCircs, Navigable}
import scala.language.postfixOps
import play.api.data.{FormError, Form}
import play.api.data.Forms._
import utils.helpers.CarersForm._
import controllers.mappings.Mappings._
import models.yesNo.YesNoWithText
import models.domain.{CircumstancesBreaksInCareSummary, CircumstancesBreaksInCare}
import controllers.CarersForms._
import play.api.i18n._
object GBreaksInCareSummary extends Controller with CachedChangeOfCircs with Navigable with I18nSupport {
override val messagesApi: MessagesApi = current.injector.instanceOf[MMessages]
val backCall = controllers.circs.your_details.routes.GYourDetails.present()
val additionalBreaksMapping =
"additionalBreaks" -> mapping(
"answer" -> nonEmptyText.verifying(validYesNo),
"text" -> optional(carersNonEmptyText(maxLength = 300))
)(YesNoWithText.apply)(YesNoWithText.unapply)
.verifying("additionalBreaks.text.required", YesNoWithText.validateOnYes _)
val form = Form(mapping(
additionalBreaksMapping
)(CircumstancesBreaksInCareSummary.apply)(CircumstancesBreaksInCareSummary.unapply)
)
def present = claiming { implicit circs => implicit request => implicit request2lang =>
track(CircumstancesBreaksInCareSummary) {
implicit circs => Ok(views.html.circs.report_changes.breaksInCareSummary(form.fill(CircumstancesBreaksInCareSummary), circs.questionGroup[CircumstancesBreaksInCare].getOrElse(new CircumstancesBreaksInCare()), backCall))
}
}
def submit = claiming { implicit circs => implicit request => implicit request2lang =>
form.bindEncrypted.fold(
formWithErrors => {
val formWithErrorsUpdate = formWithErrors
.replaceError("additionalBreaks", "additionalBreaks.text.required", FormError("additionalBreaks.text", errorRequired))
BadRequest(views.html.circs.report_changes.breaksInCareSummary(formWithErrorsUpdate, circs.questionGroup[CircumstancesBreaksInCare].getOrElse(new CircumstancesBreaksInCare()), backCall))
},
f => circs.update(f) -> Redirect(controllers.circs.consent_and_declaration.routes.GCircsDeclaration.present())
)
}
}
| mit |
ReceipeFinder/frontend | src/components/app.js | 2464 | import React, {Component} from 'react';
import c from 'classnames'
import TopBar from '../_components/TopBar'
import UserProfile from '../components/UserProfile'
import RecipeFinder from '../components/RecipeFinder'
import RecipesList from '../components/RecipesList'
import '../styles/main.less'
import './UserProfile/styles.less'
import './RecipesList/styles.less'
import './RecipeFinder/styles.less'
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
showUserProfile: false,
showRecipesList: false,
hideRecipeFinder: false
};
this.toggleUserProfile = this.toggleUserProfile.bind(this);
this.toggleRecipesList = this.toggleRecipesList.bind(this);
this.toggleRecipeFinder = this.toggleRecipeFinder.bind(this);
}
toggleUserProfile() {
this.setState({showUserProfile: !this.state.showUserProfile})
}
toggleRecipesList() {
this.setState({showRecipesList: !this.state.showRecipesList})
}
toggleRecipeFinder() {
this.setState({hideRecipeFinder: !this.state.hideRecipeFinder})
}
render() {
return (
<div className="main__layout">
{/*<TopBar/>*/}
<main>
{/*<div className={c({"user-profile__wrapper": true, "visible": this.state.showUserProfile})}>*/}
{/*<UserProfile/>*/}
{/*<div className="user-profile__toggler clickable" onClick={this.toggleUserProfile}>*/}
{/*<span className={c({*/}
{/*"pt-icon-standard": true,*/}
{/*"pt-icon-chevron-right": !this.state.showUserProfile,*/}
{/*"pt-icon-chevron-left": this.state.showUserProfile*/}
{/*})}/>*/}
{/*</div>*/}
{/*</div>*/}
<div className="recipes-list__wrapper">
<RecipesList visible={this.state.hideRecipeFinder}/>
</div>
<div className={c({"recipe-finder__wrapper": true, "hidden": this.state.hideRecipeFinder})}>
<div className="recipe-finder__toggler clickable" onClick={this.toggleRecipeFinder}>
<span className={c({
"pt-icon-standard": true,
"pt-icon-chevron-right": !this.state.hideRecipeFinder,
"pt-icon-chevron-left": this.state.hideRecipeFinder
})}/>
</div>
<RecipeFinder hidden={this.state.hideRecipeFinder}/>
</div>
</main>
</div>
);
}
}
| mit |
SofiaRin/Game | template/runtime/native_require.js | 2148 |
var game_file_list = [
//以下为自动修改,请勿修改
//----auto game_file_list start----
"libs/modules/egret/egret.js",
"libs/modules/egret/egret.native.js",
"libs/modules/game/game.js",
"libs/modules/game/game.native.js",
"libs/modules/res/res.js",
"libs/modules/tween/tween.js",
"bin-debug/Animation.js",
"bin-debug/Astar.js",
"bin-debug/Command.js",
"bin-debug/CommandList.js",
"bin-debug/DialoguePanel.js",
"bin-debug/Equipment.js",
"bin-debug/Grid.js",
"bin-debug/LoadingUI.js",
"bin-debug/Main.js",
"bin-debug/Map.js",
"bin-debug/MissionPanel.js",
"bin-debug/MoveCtrl.js",
"bin-debug/NPC.js",
"bin-debug/Observer.js",
"bin-debug/Panel.js",
"bin-debug/Player.js",
"bin-debug/Point.js",
"bin-debug/Property.js",
"bin-debug/Sence.js",
"bin-debug/SenceService.js",
"bin-debug/Ship.js",
"bin-debug/StateMachine.js",
"bin-debug/Task.js",
"bin-debug/TaskService.js",
"bin-debug/Technician.js",
"bin-debug/User.js",
//----auto game_file_list end----
];
var window = this;
egret_native.setSearchPaths([""]);
egret_native.requireFiles = function () {
for (var key in game_file_list) {
var src = game_file_list[key];
require(src);
}
};
egret_native.egretInit = function () {
egret_native.requireFiles();
egret.TextField.default_fontFamily = "/system/fonts/DroidSansFallback.ttf";
//egret.dom为空实现
egret.dom = {};
egret.dom.drawAsCanvas = function () {
};
};
egret_native.egretStart = function () {
var option = {
//以下为自动修改,请勿修改
//----auto option start----
entryClassName: "Main",
frameRate: 30,
scaleMode: "showAll",
contentWidth: 640,
contentHeight: 1236,
showPaintRect: false,
showFPS: false,
fpsStyles: "x:0,y:0,size:12,textColor:0xffffff,bgAlpha:0.9",
showLog: false,
logFilter: "",
maxTouches: 2,
textureScaleFactor: 1
//----auto option end----
};
egret.native.NativePlayer.option = option;
egret.runEgret();
egret_native.Label.createLabel(egret.TextField.default_fontFamily, 20, "", 0);
egret_native.EGTView.preSetOffScreenBufferEnable(true);
}; | mit |
slavaschmidt/akka-antipatterns | src/test/scala/scalaua2017/ConnectionPoolBenchmark.scala | 1772 | package scalaua2017
import akka.actor._
import akka.pattern.ask
import akka.util.Timeout
import scala.concurrent._
import scala.concurrent.duration._
import scala.language.postfixOps
import org.scalameter.api._
import org.scalameter.picklers.Implicits._
import scalaua2017.database._
trait ConnectionPoolBenchmark extends TestConfig {
override def executeTests(): Boolean = {
val result = super.executeTests()
system.terminate()
Await.result(system.whenTerminated, Duration.Inf)
result
}
private def testSingle(pong: Props, ping: Props)(count: Int)(implicit system:ActorSystem) {
implicit val timeout = Timeout(600 seconds)
val actor = system.actorOf(ping)
val future = actor ? Start(pong, count)
Await.ready(future, timeout.duration)
actor ! PoisonPill
}
private val testNoPool = testSingle(PongActor.nprops, PingActor.props) _
private val testLiftPool = testSingle(PongActor.lprops, PingActor.props) _
private val testBoneCpPool = testSingle(PongActor.bprops, PingActor.props) _
private val testWithRouter = testSingle(PongActor.rprops, PingActor.rprops) _
def compareLogging(implicit system: ActorSystem): Unit =
performance of "Database Connection Pool" in {
/* measure method "without connection pool" in {
using(messageCount) in { testNoPool }
}
measure method "with bad behaving pool" in {
using(messageCount) in { testLiftPool }
}
measure method "with good behaving pool" in {
using(messageCount) in { testBoneCpPool }
}
*/
measure method "with actor based pool and router" in {
using(messageCount) in { testWithRouter }
}
}
compareLogging
}
object ConnectionPoolBenchmark extends ConnectionPoolBenchmark
| mit |
igee/igeey.com | test/unit/sync_test.rb | 151 | require 'test_helper'
class SyncTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
end
| mit |
avbotz/eva-public | src/camera.hpp | 2342 | /*
_
___ __ _ _ __ ___ ___ _ __ __ _ | |__ _ __ _ __
/ __/ _` | '_ ` _ \ / _ \ '__/ _` | | '_ \| '_ \| '_ \
| (_| (_| | | | | | | __/ | | (_| |_| | | | |_) | |_) |
\___\__,_|_| |_| |_|\___|_| \__,_(_)_| |_| .__/| .__/
|_| |_|
*/
/* Copyright (c) 2014 AVBotz
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* ========================================================================== */
#ifndef CAMERA_H__
#define CAMERA_H__
#include "threadimpl.hpp"
#include "types.hpp"
#include "log.hpp"
struct buffer
{
void* start;
size_t length;
};
class Camera
{
public:
Camera(const char* name, int w, int h);
~Camera();
void* getImageBuffer();
int getIndex();
void pauseCapturing();
void resumeCapturing();
bool isCapturing;
buffer* buffers;
private:
void openDevice();
void initDevice();
void initMMap();
void startCapturing();
void stopCapturing();
void uninitDevice();
void closeDevice();
int readFrame();
void runVision();
void errno_exit(const char *s);
int xioctl(int request, void *arg);
int fd;
char devName[20];
IO_METHOD io;
void* latestBuffer;
unsigned int numBuffers;
int dropFrames;
ThreadImpl* timpl;
int width, height;
int index;
};
#endif
| mit |
katherinealbany/rodentia | logger/logger.go | 1476 | package logger
import (
"fmt"
"os"
"strconv"
"time"
)
type Logger struct {
Level uint8
Name string
}
var start time.Time
func init() {
start = time.Now()
}
func New(name string) *Logger {
return &Logger{
Name: name,
Level: 6,
}
}
func (logger *Logger) Debug(args ...interface{}) {
if logger.Level >= 0 {
fmt.Println(timestamp(), since(), "[DEBUG]", name(logger.Name), args)
}
}
func (logger *Logger) Info(args ...interface{}) {
if logger.Level >= 1 {
fmt.Println(timestamp(), since(), "[INFO ]", name(logger.Name), args)
}
}
func (logger *Logger) Warn(args ...interface{}) {
if logger.Level >= 2 {
fmt.Println(timestamp(), since(), "[WARN ]", name(logger.Name), args)
}
}
func (logger *Logger) Error(args ...interface{}) {
if logger.Level >= 3 {
fmt.Println(timestamp(), since(), "[ERROR]", name(logger.Name), args)
}
}
func (logger *Logger) Panic(err error, args ...interface{}) {
if logger.Level >= 5 {
fmt.Println(timestamp(), since(), "[PANIC]", name(logger.Name), args)
panic(err)
}
}
func (logger *Logger) Fatal(args ...interface{}) {
if logger.Level >= 5 {
fmt.Println(timestamp(), since(), "[FATAL]", name(logger.Name), args)
os.Exit(1)
}
}
func name(name string) string {
return "[" + name + "]"
}
func timestamp() string {
t := time.Now()
return "[" + t.Format("15:04:05.000") + "]"
}
func since() string {
ms := int64(time.Since(start) / time.Millisecond)
return "[" + strconv.FormatInt(ms, 10) + "]"
}
| mit |
accelazh/TetrixGame | src/com/accela/tetrixgame/conn/connectionLauncher/FailedToLaunchConnectionException.java | 611 | package com.accela.tetrixgame.conn.connectionLauncher;
import com.accela.tetrixgame.conn.shared.IConstants;
public class FailedToLaunchConnectionException extends Exception {
private static final long serialVersionUID = IConstants.SERIAL_VERSION_UID;
public FailedToLaunchConnectionException() {
super();
}
public FailedToLaunchConnectionException(String message) {
super(message);
}
public FailedToLaunchConnectionException(String message, Throwable cause) {
super(message, cause);
}
public FailedToLaunchConnectionException(Throwable cause) {
super(cause);
}
}
| mit |
Azure/azure-sdk-for-go | services/preview/synapse/mgmt/2021-06-01-preview/synapse/workspacemanagedsqlserverblobauditingpolicies.go | 16133 | package synapse
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"github.com/Azure/go-autorest/tracing"
"net/http"
)
// WorkspaceManagedSQLServerBlobAuditingPoliciesClient is the azure Synapse Analytics Management Client
type WorkspaceManagedSQLServerBlobAuditingPoliciesClient struct {
BaseClient
}
// NewWorkspaceManagedSQLServerBlobAuditingPoliciesClient creates an instance of the
// WorkspaceManagedSQLServerBlobAuditingPoliciesClient client.
func NewWorkspaceManagedSQLServerBlobAuditingPoliciesClient(subscriptionID string) WorkspaceManagedSQLServerBlobAuditingPoliciesClient {
return NewWorkspaceManagedSQLServerBlobAuditingPoliciesClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewWorkspaceManagedSQLServerBlobAuditingPoliciesClientWithBaseURI creates an instance of the
// WorkspaceManagedSQLServerBlobAuditingPoliciesClient client using a custom endpoint. Use this when interacting with
// an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack).
func NewWorkspaceManagedSQLServerBlobAuditingPoliciesClientWithBaseURI(baseURI string, subscriptionID string) WorkspaceManagedSQLServerBlobAuditingPoliciesClient {
return WorkspaceManagedSQLServerBlobAuditingPoliciesClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// CreateOrUpdate create or Update a workspace managed sql server's blob auditing policy.
// Parameters:
// resourceGroupName - the name of the resource group. The name is case insensitive.
// workspaceName - the name of the workspace
// parameters - properties of extended blob auditing policy.
func (client WorkspaceManagedSQLServerBlobAuditingPoliciesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, workspaceName string, parameters ServerBlobAuditingPolicy) (result WorkspaceManagedSQLServerBlobAuditingPoliciesCreateOrUpdateFuture, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WorkspaceManagedSQLServerBlobAuditingPoliciesClient.CreateOrUpdate")
defer func() {
sc := -1
if result.FutureAPI != nil && result.FutureAPI.Response() != nil {
sc = result.FutureAPI.Response().StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: client.SubscriptionID,
Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil {
return result, validation.NewError("synapse.WorkspaceManagedSQLServerBlobAuditingPoliciesClient", "CreateOrUpdate", err.Error())
}
req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, workspaceName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "synapse.WorkspaceManagedSQLServerBlobAuditingPoliciesClient", "CreateOrUpdate", nil, "Failure preparing request")
return
}
result, err = client.CreateOrUpdateSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "synapse.WorkspaceManagedSQLServerBlobAuditingPoliciesClient", "CreateOrUpdate", result.Response(), "Failure sending request")
return
}
return
}
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
func (client WorkspaceManagedSQLServerBlobAuditingPoliciesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, workspaceName string, parameters ServerBlobAuditingPolicy) (*http.Request, error) {
pathParameters := map[string]interface{}{
"blobAuditingPolicyName": autorest.Encode("path", "default"),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
"workspaceName": autorest.Encode("path", workspaceName),
}
const APIVersion = "2021-06-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Synapse/workspaces/{workspaceName}/auditingSettings/{blobAuditingPolicyName}", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
// http.Response Body if it receives an error.
func (client WorkspaceManagedSQLServerBlobAuditingPoliciesClient) CreateOrUpdateSender(req *http.Request) (future WorkspaceManagedSQLServerBlobAuditingPoliciesCreateOrUpdateFuture, err error) {
var resp *http.Response
future.FutureAPI = &azure.Future{}
resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
if err != nil {
return
}
var azf azure.Future
azf, err = azure.NewFutureFromResponse(resp)
future.FutureAPI = &azf
future.Result = future.result
return
}
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
// closes the http.Response Body.
func (client WorkspaceManagedSQLServerBlobAuditingPoliciesClient) CreateOrUpdateResponder(resp *http.Response) (result ServerBlobAuditingPolicy, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Get get a workspace managed sql server's blob auditing policy.
// Parameters:
// resourceGroupName - the name of the resource group. The name is case insensitive.
// workspaceName - the name of the workspace
func (client WorkspaceManagedSQLServerBlobAuditingPoliciesClient) Get(ctx context.Context, resourceGroupName string, workspaceName string) (result ServerBlobAuditingPolicy, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WorkspaceManagedSQLServerBlobAuditingPoliciesClient.Get")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: client.SubscriptionID,
Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil {
return result, validation.NewError("synapse.WorkspaceManagedSQLServerBlobAuditingPoliciesClient", "Get", err.Error())
}
req, err := client.GetPreparer(ctx, resourceGroupName, workspaceName)
if err != nil {
err = autorest.NewErrorWithError(err, "synapse.WorkspaceManagedSQLServerBlobAuditingPoliciesClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "synapse.WorkspaceManagedSQLServerBlobAuditingPoliciesClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "synapse.WorkspaceManagedSQLServerBlobAuditingPoliciesClient", "Get", resp, "Failure responding to request")
return
}
return
}
// GetPreparer prepares the Get request.
func (client WorkspaceManagedSQLServerBlobAuditingPoliciesClient) GetPreparer(ctx context.Context, resourceGroupName string, workspaceName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"blobAuditingPolicyName": autorest.Encode("path", "default"),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
"workspaceName": autorest.Encode("path", workspaceName),
}
const APIVersion = "2021-06-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Synapse/workspaces/{workspaceName}/auditingSettings/{blobAuditingPolicyName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client WorkspaceManagedSQLServerBlobAuditingPoliciesClient) GetSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client WorkspaceManagedSQLServerBlobAuditingPoliciesClient) GetResponder(resp *http.Response) (result ServerBlobAuditingPolicy, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListByWorkspace list workspace managed sql server's blob auditing policies.
// Parameters:
// resourceGroupName - the name of the resource group. The name is case insensitive.
// workspaceName - the name of the workspace
func (client WorkspaceManagedSQLServerBlobAuditingPoliciesClient) ListByWorkspace(ctx context.Context, resourceGroupName string, workspaceName string) (result ServerBlobAuditingPolicyListResultPage, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WorkspaceManagedSQLServerBlobAuditingPoliciesClient.ListByWorkspace")
defer func() {
sc := -1
if result.sbaplr.Response.Response != nil {
sc = result.sbaplr.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: client.SubscriptionID,
Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil {
return result, validation.NewError("synapse.WorkspaceManagedSQLServerBlobAuditingPoliciesClient", "ListByWorkspace", err.Error())
}
result.fn = client.listByWorkspaceNextResults
req, err := client.ListByWorkspacePreparer(ctx, resourceGroupName, workspaceName)
if err != nil {
err = autorest.NewErrorWithError(err, "synapse.WorkspaceManagedSQLServerBlobAuditingPoliciesClient", "ListByWorkspace", nil, "Failure preparing request")
return
}
resp, err := client.ListByWorkspaceSender(req)
if err != nil {
result.sbaplr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "synapse.WorkspaceManagedSQLServerBlobAuditingPoliciesClient", "ListByWorkspace", resp, "Failure sending request")
return
}
result.sbaplr, err = client.ListByWorkspaceResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "synapse.WorkspaceManagedSQLServerBlobAuditingPoliciesClient", "ListByWorkspace", resp, "Failure responding to request")
return
}
if result.sbaplr.hasNextLink() && result.sbaplr.IsEmpty() {
err = result.NextWithContext(ctx)
return
}
return
}
// ListByWorkspacePreparer prepares the ListByWorkspace request.
func (client WorkspaceManagedSQLServerBlobAuditingPoliciesClient) ListByWorkspacePreparer(ctx context.Context, resourceGroupName string, workspaceName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
"workspaceName": autorest.Encode("path", workspaceName),
}
const APIVersion = "2021-06-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Synapse/workspaces/{workspaceName}/auditingSettings", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListByWorkspaceSender sends the ListByWorkspace request. The method will close the
// http.Response Body if it receives an error.
func (client WorkspaceManagedSQLServerBlobAuditingPoliciesClient) ListByWorkspaceSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// ListByWorkspaceResponder handles the response to the ListByWorkspace request. The method always
// closes the http.Response Body.
func (client WorkspaceManagedSQLServerBlobAuditingPoliciesClient) ListByWorkspaceResponder(resp *http.Response) (result ServerBlobAuditingPolicyListResult, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listByWorkspaceNextResults retrieves the next set of results, if any.
func (client WorkspaceManagedSQLServerBlobAuditingPoliciesClient) listByWorkspaceNextResults(ctx context.Context, lastResults ServerBlobAuditingPolicyListResult) (result ServerBlobAuditingPolicyListResult, err error) {
req, err := lastResults.serverBlobAuditingPolicyListResultPreparer(ctx)
if err != nil {
return result, autorest.NewErrorWithError(err, "synapse.WorkspaceManagedSQLServerBlobAuditingPoliciesClient", "listByWorkspaceNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListByWorkspaceSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "synapse.WorkspaceManagedSQLServerBlobAuditingPoliciesClient", "listByWorkspaceNextResults", resp, "Failure sending next results request")
}
result, err = client.ListByWorkspaceResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "synapse.WorkspaceManagedSQLServerBlobAuditingPoliciesClient", "listByWorkspaceNextResults", resp, "Failure responding to next results request")
}
return
}
// ListByWorkspaceComplete enumerates all values, automatically crossing page boundaries as required.
func (client WorkspaceManagedSQLServerBlobAuditingPoliciesClient) ListByWorkspaceComplete(ctx context.Context, resourceGroupName string, workspaceName string) (result ServerBlobAuditingPolicyListResultIterator, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WorkspaceManagedSQLServerBlobAuditingPoliciesClient.ListByWorkspace")
defer func() {
sc := -1
if result.Response().Response.Response != nil {
sc = result.page.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.page, err = client.ListByWorkspace(ctx, resourceGroupName, workspaceName)
return
}
| mit |
drahmel/chirpchirp | js/identityBank.js | 226 | function identityBank(bar) {
this.bar = bar;
this.blank = {
firstName: '',
lastName: '',
category: '',
bio: '',
interestes: '',
};
}
identityBank.prototype.name = function() {
};
module.exports = identityBank;
| mit |
AlexeyPopovUA/Java-disign-patterns | decorator/src/com/studying/decorator/decorators/Whip.java | 502 | package com.studying.decorator.decorators;
import com.studying.decorator.business.Beverage;
import com.studying.decorator.business.CondimentDecorator;
public class Whip extends CondimentDecorator{
Beverage beverage;
public Whip(Beverage beverage) {
this.beverage = beverage;
}
@Override
public String getDescription() {
return beverage.getDescription() + ", Whip";
}
@Override
public double cost() {
return 0.56 + beverage.cost();
}
}
| mit |
LugosFingite/LudOS | kern/i686/pc/terminal/termio.hpp | 1689 | /*
termio.hpp
Copyright (c) 13 Yann BOUCHER (yann)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef TERMIO_HPP
#define TERMIO_HPP
#include <stdint.h>
#include "io.hpp"
#include "i686/pc/bios/bda.hpp"
inline void termio_move_cursor(size_t x, size_t y, size_t width)
{
const size_t index = y * width + x;
static const uint16_t port_low = BDA::video_io_port();
const uint16_t port_high = port_low + 1;
// cursor LOW port to vga INDEX register
outb(port_low, 0x0F);
outb(port_high, static_cast<uint8_t>(index&0xFF));
// cursor HIGH port to vga INDEX register
outb(port_low, 0x0E);
outb(port_high, static_cast<uint8_t>((index>>8)&0xFF));
}
#endif // TERMIO_HPP
| mit |
yukik/cocotte-htmlparser | lib/tags/svg/rect.js | 241 | var rule = require('../../rule');
// SVG 四角形
module.exports = {
type: {
flow: true
},
empty: true,
attributes: 'x,y,width,height,rx,ry,fill',
parent: 'svg',
rules: [
rule.hasAllAttributes('x,y,width,height')
]
}; | mit |
digiworks/libcutl | cutl/details/boost/regex/v4/regex_merge.hpp | 2804 | /*
*
* Copyright (c) 1998-2002
* John Maddock
*
* Use, modification and distribution are subject to the
* Boost Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
*/
/*
* LOCATION: see http://www.boost.org for most recent version.
* FILE regex_format.hpp
* VERSION see <cutl/details/boost/version.hpp>
* DESCRIPTION: Provides formatting output routines for search and replace
* operations. Note this is an internal header file included
* by regex.hpp, do not include on its own.
*/
#ifndef BOOST_REGEX_V4_REGEX_MERGE_HPP
#define BOOST_REGEX_V4_REGEX_MERGE_HPP
namespace cutl_details_boost{
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable: 4103)
#endif
#ifdef BOOST_HAS_ABI_HEADERS
# include BOOST_ABI_PREFIX
#endif
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif
template <class OutputIterator, class Iterator, class traits, class charT>
inline OutputIterator regex_merge(OutputIterator out,
Iterator first,
Iterator last,
const basic_regex<charT, traits>& e,
const charT* fmt,
match_flag_type flags = match_default)
{
return regex_replace(out, first, last, e, fmt, flags);
}
template <class OutputIterator, class Iterator, class traits, class charT>
inline OutputIterator regex_merge(OutputIterator out,
Iterator first,
Iterator last,
const basic_regex<charT, traits>& e,
const std::basic_string<charT>& fmt,
match_flag_type flags = match_default)
{
return regex_merge(out, first, last, e, fmt.c_str(), flags);
}
template <class traits, class charT>
inline std::basic_string<charT> regex_merge(const std::basic_string<charT>& s,
const basic_regex<charT, traits>& e,
const charT* fmt,
match_flag_type flags = match_default)
{
return regex_replace(s, e, fmt, flags);
}
template <class traits, class charT>
inline std::basic_string<charT> regex_merge(const std::basic_string<charT>& s,
const basic_regex<charT, traits>& e,
const std::basic_string<charT>& fmt,
match_flag_type flags = match_default)
{
return regex_replace(s, e, fmt, flags);
}
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable: 4103)
#endif
#ifdef BOOST_HAS_ABI_HEADERS
# include BOOST_ABI_SUFFIX
#endif
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif
} // namespace cutl_details_boost
#endif // BOOST_REGEX_V4_REGEX_MERGE_HPP
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.