repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
PsychoLlama/mytosis
packages/mytosis/src/connection-group/test.js
8301
/* eslint-disable require-jsdoc */ import expect, { createSpy } from 'expect'; import { Connection } from '../mocks'; import ConnectionGroup from './index'; import Stream from '../stream'; describe('ConnectionGroup', () => { let group, conn; beforeEach(() => { group = new ConnectionGroup(); conn = new Connection({ id: 'conn1' }); }); describe('static "ensure" method', () => { it('returns the value if it is a connection group', () => { const result = ConnectionGroup.ensure(group); expect(result).toBe(group); }); it('wraps connections into a connection group', () => { const result = ConnectionGroup.ensure(conn); expect(result).toBeA(ConnectionGroup); expect([...result]).toContain(conn); }); }); describe('id()', () => { it('returns null if no connection is found', () => { const result = group.id('no such connection'); expect(result).toBe(null); }); it('returns the matching connection', () => { group.add(conn); const result = group.id(conn.id); expect(result).toBe(conn); }); }); describe('add()', () => { it('adds the connection', () => { group.add(conn); expect(group.id(conn.id)).toBe(conn); }); it('emits "add"', () => { const spy = createSpy(); group.on('add', spy); group.add(conn); expect(spy).toHaveBeenCalled(); expect(spy).toHaveBeenCalledWith(conn); }); it('does not emit "add" if already contained', () => { const spy = createSpy(); group.on('add', spy); group.add(conn); group.add(conn); expect(spy.calls.length).toBe(1); }); it('returns the connection', () => { const result = group.add(conn); expect(result).toBe(conn); }); }); describe('remove()', () => { it('removes connections from the group', () => { group.add(conn); group.remove(conn); expect(group.id(conn.id)).toBe(null); }); it('emits "remove"', () => { const spy = createSpy(); group.on('remove', spy); group.add(conn); group.remove(conn); expect(spy).toHaveBeenCalled(); expect(spy).toHaveBeenCalledWith(conn); }); it('does not emit "remove" twice', () => { const spy = createSpy(); group.on('remove', spy); group.add(conn); group.remove(conn); group.remove(conn); expect(spy.calls.length).toBe(1); }); it('does not explode if the connection does not exist', () => { expect(() => group.remove(conn)).toNotThrow(); }); it('returns the connection', () => { const result = group.remove(conn); expect(result).toBe(conn); }); }); describe('has()', () => { it('returns true if the connection is contained', () => { const group = new ConnectionGroup(); group.add(conn); const isContained = group.has(conn); expect(isContained).toBe(true); }); it('returns false if there is no such connection', () => { const group = new ConnectionGroup(); const isContained = group.has(conn); expect(isContained).toBe(false); }); it('ignores inherited properties', () => { const conn = new Connection({ id: 'toString' }); const group = new ConnectionGroup(); const isContained = group.has(conn); expect(isContained).toBe(false); }); }); describe('iterator', () => { it('yields every connection', () => { const conn1 = new Connection({ id: 'conn1' }); const conn2 = new Connection({ id: 'conn2' }); group.add(conn1); group.add(conn2); const results = [...group]; expect(results).toContain(conn1); expect(results).toContain(conn2); expect(results.length).toBe(2); }); }); describe('send()', () => { it('sends the message through each member', () => { conn.send = createSpy(); group.add(conn); const msg = { isMessage: true }; group.send(msg); expect(conn.send).toHaveBeenCalled(); expect(conn.send).toHaveBeenCalledWith(msg); }); }); describe('filter()', () => { it('returns a new ConnectionGroup', () => { const result = group.filter(() => false); expect(result).toBeA(ConnectionGroup); expect(result).toNotBe(group); }); it('only contains items that match the terms', () => { group.add(conn); group.add(new Connection({ id: 'conn2' })); const result = group.filter(conn => conn.id === 'conn1'); expect([...result].length).toBe(1); }); }); describe('type()', () => { it('returns a new group', () => { const result = group.type('connection-type'); expect(result).toBeA(ConnectionGroup); expect(result).toNotBe(group); }); it('returns connections matching the type', () => { const conn = new Connection({ id: 'conn1', type: 'websocket' }); group.add(conn); group.add(new Connection({ id: 'conn2', type: 'http' })); group.add(new Connection({ id: 'conn3', type: 'http' })); const result = group.type('websocket'); expect([...result]).toContain(conn); expect([...result].length).toBe(1); }); }); describe('messages stream', () => { let spy; beforeEach(() => { spy = createSpy(); group.add(conn); }); it('is a stream', () => { expect(group.messages).toBeA(Stream); }); it('reports every message in the group', () => { group.messages.forEach(spy); conn.push('hello'); expect(spy).toHaveBeenCalled(); expect(spy).toHaveBeenCalledWith('hello', conn); }); it('reports messages from connections added later', () => { const conn = new Connection({ id: 'conn2' }); group.messages.forEach(spy); group.add(conn); conn.push('message'); expect(spy).toHaveBeenCalled(); expect(spy).toHaveBeenCalledWith('message', conn); }); it('does not report messages from removed connections', () => { group.messages.forEach(spy); group.remove(conn); conn.push('message'); expect(spy).toNotHaveBeenCalled(); }); it('does not report messages from added, then removed connections', () => { const conn = new Connection({ id: 'conn2' }); group.messages.forEach(spy); group.add(conn); group.remove(conn); conn.push('message'); expect(spy).toNotHaveBeenCalled(); }); it('disposes of each subscription when dispose is called', () => { const dispose = createSpy(); conn.messages.forEach = createSpy().andReturn({ dispose }); group.add(conn); group.messages.forEach(spy).dispose(); expect(dispose).toHaveBeenCalled(); }); it('unsubscribes on dispose', () => { group.messages.forEach(() => {}).dispose(); expect(group.listeners('add')).toEqual([]); expect(group.listeners('remove')).toEqual([]); }); }); describe('"union" method', () => { let group1, group2, conn1, conn2; beforeEach(() => { group1 = new ConnectionGroup(); group2 = new ConnectionGroup(); conn1 = new Connection({ id: 'conn1' }); conn2 = new Connection({ id: 'conn2' }); }); it('creates a new group', () => { const group = group1.union(group2); expect(group).toBeA(ConnectionGroup); expect(group).toNotBe(group1); expect(group).toNotBe(group2); }); it('adds every item in both source groups', () => { group1.add(conn1); group2.add(conn2); const group = group1.union(group2); expect([...group]).toContain(conn1); expect([...group]).toContain(conn2); }); it('adds connections as they arive', () => { const group = group1.union(group2); group1.add(conn1); group2.add(conn2); expect([...group]).toContain(conn1); expect([...group]).toContain(conn2); }); it('removes a connection if neither group has it', () => { group1.add(conn1); group2.add(conn1); group2.add(conn2); const group = group1.union(group2); group1.remove(conn1); group2.remove(conn2); expect([...group]).toContain(conn1); expect([...group]).toNotContain(conn2); }); }); });
mit
wael-Fadlallah/overflow
asset/tinymce/src/core/src/test/js/browser/undo/LevelsTest.js
5857
asynctest( 'browser.tinymce.core.undo.LevelsTest', [ 'ephox.agar.api.Pipeline', 'ephox.mcagar.api.LegacyUnit', 'ephox.mcagar.api.TinyLoader', 'tinymce.core.Env', 'tinymce.core.undo.Levels', 'tinymce.themes.modern.Theme' ], function (Pipeline, LegacyUnit, TinyLoader, Env, Levels, Theme) { var success = arguments[arguments.length - 2]; var failure = arguments[arguments.length - 1]; var suite = LegacyUnit.createSuite(); Theme(); var getBookmark = function (editor) { return editor.selection.getBookmark(2, true); }; suite.test('createFragmentedLevel', function () { LegacyUnit.deepEqual(Levels.createFragmentedLevel(['a', 'b']), { 'beforeBookmark': null, 'bookmark': null, 'content': '', 'fragments': ['a', 'b'], 'type': 'fragmented' }); }); suite.test('createCompleteLevel', function () { LegacyUnit.deepEqual(Levels.createCompleteLevel('a'), { 'beforeBookmark': null, 'bookmark': null, 'content': 'a', 'fragments': null, 'type': 'complete' }); }); suite.test('createFromEditor', function (editor) { LegacyUnit.deepEqual(Levels.createFromEditor(editor), { 'beforeBookmark': null, 'bookmark': null, 'content': Env.ie && Env.ie < 11 ? '<p></p>' : '<p><br data-mce-bogus="1"></p>', 'fragments': null, 'type': 'complete' }); editor.getBody().innerHTML = '<iframe src="about:blank"></iframe>a<!--b-->c'; LegacyUnit.deepEqual(Levels.createFromEditor(editor), { 'beforeBookmark': null, 'bookmark': null, 'content': '', 'fragments': ['<iframe src="about:blank"></iframe>', 'a', '<!--b-->', 'c'], 'type': 'fragmented' }); }); suite.test('createFromEditor removes bogus=al', function (editor) { editor.getBody().innerHTML = '<p data-mce-bogus="all">a</p> <span>b</span>'; LegacyUnit.deepEqual(Levels.createFromEditor(editor), { 'beforeBookmark': null, 'bookmark': null, 'content': ' <span>b</span>', 'fragments': null, 'type': 'complete' }); }); suite.test('createFromEditor removes bogus=all', function (editor) { editor.getBody().innerHTML = '<iframe src="about:blank"></iframe> <p data-mce-bogus="all">a</p> <span>b</span>'; LegacyUnit.deepEqual(Levels.createFromEditor(editor), { 'beforeBookmark': null, 'bookmark': null, 'content': '', 'fragments':[ "<iframe src=\"about:blank\"></iframe>", " ", "", " ", "<span>b</span>" ], 'type': 'fragmented' }); }); suite.test('applyToEditor to equal content with complete level', function (editor) { var level = Levels.createCompleteLevel('<p>a</p>'); level.bookmark = { start: [1, 0, 0] }; editor.getBody().innerHTML = '<p>a</p>'; LegacyUnit.setSelection(editor, 'p', 0); Levels.applyToEditor(editor, level, false); LegacyUnit.strictEqual(editor.getBody().innerHTML, '<p>a</p>'); LegacyUnit.deepEqual(getBookmark(editor), { start: [1, 0, 0] }); }); suite.test('applyToEditor to different content with complete level', function (editor) { var level = Levels.createCompleteLevel('<p>b</p>'); level.bookmark = { start: [1, 0, 0] }; editor.getBody().innerHTML = '<p>a</p>'; LegacyUnit.setSelection(editor, 'p', 0); Levels.applyToEditor(editor, level, false); LegacyUnit.strictEqual(editor.getBody().innerHTML, '<p>b</p>'); LegacyUnit.deepEqual(getBookmark(editor), { start: [1, 0, 0] }); }); suite.test('applyToEditor to different content with fragmented level', function (editor) { var level = Levels.createFragmentedLevel(['<p>a</p>', '<p>b</p>']); level.bookmark = { start: [1, 0, 0] }; editor.getBody().innerHTML = '<p>c</p>'; LegacyUnit.setSelection(editor, 'p', 0); Levels.applyToEditor(editor, level, false); LegacyUnit.strictEqual(editor.getBody().innerHTML, '<p>a</p><p>b</p>'); LegacyUnit.deepEqual(getBookmark(editor), { start: [1, 0, 0] }); }); suite.test('isEq', function () { LegacyUnit.strictEqual(Levels.isEq(Levels.createFragmentedLevel(['a', 'b']), Levels.createFragmentedLevel(['a', 'b'])), true); LegacyUnit.strictEqual(Levels.isEq(Levels.createFragmentedLevel(['a', 'b']), Levels.createFragmentedLevel(['a', 'c'])), false); LegacyUnit.strictEqual(Levels.isEq(Levels.createCompleteLevel('a'), Levels.createCompleteLevel('a')), true); LegacyUnit.strictEqual(Levels.isEq(Levels.createCompleteLevel('a'), Levels.createCompleteLevel('b')), false); LegacyUnit.strictEqual(Levels.isEq(Levels.createFragmentedLevel(['a']), Levels.createCompleteLevel('a')), true); LegacyUnit.strictEqual(Levels.isEq(Levels.createCompleteLevel('a'), Levels.createFragmentedLevel(['a'])), true); }); suite.test('isEq passed undefined', function () { LegacyUnit.strictEqual(Levels.isEq(undefined, Levels.createFragmentedLevel(['a', 'b'])), false); LegacyUnit.strictEqual(Levels.isEq(Levels.createCompleteLevel('a'), undefined), false); LegacyUnit.strictEqual(Levels.isEq(undefined, undefined), false); LegacyUnit.strictEqual(Levels.isEq(Levels.createFragmentedLevel([]), Levels.createFragmentedLevel([])), true); }); TinyLoader.setup(function (editor, onSuccess, onFailure) { Pipeline.async({}, suite.toSteps(editor), onSuccess, onFailure); }, { selector: "textarea", add_unload_trigger: false, disable_nodechange: true, entities: 'raw', indent: false, skin_url: '/project/src/skins/lightgray/dist/lightgray' }, success, failure); } );
mit
numedik/nmcore
db/migrate/20150804070337_create_treatmentnotetypes.rb
251
class CreateTreatmentnotetypes < ActiveRecord::Migration def change create_table :treatmentnotetypes do |t| t.string :code t.string :name t.boolean :disabled, :default => false t.timestamps null: false end end end
mit
RealGeeks/lead_router.py
leadrouter/alerts.py
1519
import pprint import json from leadrouter import sentry class Alerts(object): '''Alerts is an interface to both a standard python logger and sentry Only critical() messages are sent to sentry. Make sure SENTRY_DSN environment variable is set (see sentry.py) ''' def __init__(self, logger): self.logger = logger def info(self, msg, details={}): '''Send INFO message to logger''' self.logger.info(self._format('INFO', msg, details)) def debug(self, msg, details={}): '''Send DEBUG message to logger''' self.logger.debug(self._format('DEBUG', msg, details)) def warning(self, msg, details={}): '''Send WARNING message to logger''' self.logger.warning(self._format('WARNING', msg, details)) def critical(self, msg, details={}): '''Send ERROR message to logger and send notification to pagerduty''' msg = self._format('ERROR', msg, details) self.logger.error(msg) sentry.captureMessage(msg) def _format(self, level, msg, details): data = details.copy() data['log_message'] = msg data['log_level'] = level try: return json.dumps(data) except (TypeError, ValueError): return "%s" % data class NullAlerts(object): def info(self, msg, details={}): pass def debug(self, msg, details={}): pass def warning(self, msg, details={}): pass def critical(self, msg, details={}): pass
mit
red2901/sandbox
exceldna/Libs/Bemu/BEmu_cpp/src/HistoricalDataRequest/HistoricElementFieldData.cpp
4374
//------------------------------------------------------------------------------ // <copyright project="BEmu_cpp" file="src/HistoricalDataRequest/HistoricElementFieldData.cpp" company="Jordan Robinson"> // Copyright (c) 2013 Jordan Robinson. All rights reserved. // // The use of this software is governed by the Microsoft Public License // which is included with this distribution. // </copyright> //------------------------------------------------------------------------------ #include "HistoricalDataRequest/HistoricElementFieldData.h" #include "HistoricalDataRequest/HistoricElementDateTime.h" #include "HistoricalDataRequest/HistoricElementDouble.h" #include "BloombergTypes/Name.h" #include "Types/ObjectType.h" #include "Types/IndentType.h" namespace BEmu { namespace HistoricalDataRequest { HistoricElementFieldData::HistoricElementFieldData(const Datetime& date, const std::map<std::string, ObjectType>& values) { boost::shared_ptr<HistoricElementDateTime> elmDate(new HistoricElementDateTime(date)); boost::shared_ptr<ElementPtr> elmDateP(elmDate); this->_fields[elmDateP->name().string()] = elmDateP; for(std::map<std::string, ObjectType>::const_iterator iter = values.begin(); iter != values.end(); ++iter) { const std::string str = iter->first; const ObjectType obj = iter->second; double dvalue; if(obj.TryGetDouble(dvalue)) { boost::shared_ptr<HistoricElementDouble> elmDouble(new HistoricElementDouble(str, dvalue)); boost::shared_ptr<ElementPtr> elmDoubleP(elmDouble); this->_fields[elmDoubleP->name().string()] = elmDoubleP; } } } HistoricElementFieldData::~HistoricElementFieldData() { this->_fields.clear(); } Name HistoricElementFieldData::name() const { Name result("fieldData"); return result; } size_t HistoricElementFieldData::numValues() const { return 1; } size_t HistoricElementFieldData::numElements() const { return this->_fields.size(); } SchemaElementDefinition HistoricElementFieldData::elementDefinition() const { ::blpapi_DataType_t dtype = (::blpapi_DataType_t)this->datatype(); SchemaElementDefinition result(dtype, Name("HistoricalDataRow")); return result; } bool HistoricElementFieldData::isNull() const { return false; } bool HistoricElementFieldData::isArray() const { return false; } bool HistoricElementFieldData::isComplexType() const { return true; } bool HistoricElementFieldData::hasElement(const char* name, bool excludeNullElements) const { return this->_fields.find(name) != this->_fields.end(); } boost::shared_ptr<ElementPtr> HistoricElementFieldData::getElement(const char* name) const { std::string key(name); std::map<std::string, boost::shared_ptr<ElementPtr> >::const_iterator it = this->_fields.find(key); if(it == this->_fields.end()) throw elementPtrEx; else return it->second; } int HistoricElementFieldData::getElementAsInt32(const char* name) const { return this->getElement(name)->getValueAsInt32(0); } Datetime HistoricElementFieldData::getElementAsDatetime(const char* name) const { return this->getElement(name)->getValueAsDatetime(0); } const char* HistoricElementFieldData::getElementAsString(const char* name) const { return this->getElement(name)->getValueAsString(0); } float HistoricElementFieldData::getElementAsFloat32(const char* name) const { return this->getElement(name)->getValueAsFloat32(0); } double HistoricElementFieldData::getElementAsFloat64(const char* name) const { return this->getElement(name)->getValueAsFloat64(0); } long HistoricElementFieldData::getElementAsInt64(const char* name) const { return this->getElement(name)->getValueAsInt64(0); } std::ostream& HistoricElementFieldData::print(std::ostream& stream, int level, int spacesPerLevel) const { std::string tabs(IndentType::Indent(level, spacesPerLevel)); stream << tabs << "fieldData = {" << std::endl; for(std::map<std::string, boost::shared_ptr<ElementPtr> >::const_iterator iter = this->_fields.begin(); iter != this->_fields.end(); ++iter) { const boost::shared_ptr<ElementPtr> elm = iter->second; elm->print(stream, level + 1, spacesPerLevel); } stream << tabs << std::endl; return stream; } } }
mit
codeforanchorage/collective-development
app/mod_user/views.py
5138
import string from random import randint from flask import Blueprint, g, current_app, render_template, flash, redirect, request, url_for, jsonify, session, Markup, abort from flask.ext.login import current_user, login_required, login_user from flask.ext.babel import gettext as _ #from app.utils import url_for_school #from app.mod_school import get_school_context from .forms import UserSettingsForm, PasswordForm, UserAddForm #from app.utils import url_for_school #from app.mod_school import get_school_context, all_schools from .forms import UserSettingsForm, PasswordForm, UserAddForm, UserAddFormOneSchool, UserSettingsFormOneSchool from .models import User from .services import can_edit, can_edit_user # Blueprint definition users = Blueprint('users', __name__, url_prefix='/users') @users.route('/<user_id>/proposals/<proposal_id>/proposal_get_interested_status') def proposal_get_interested_status(user_id, proposal_id): from app.mod_proposal import Proposal u = User.objects.get_or_404(id=user_id) p = Proposal.objects.get_or_404(id=proposal_id) for interest in p.interested: if(u.id == interest.user.id): return "true" return "false" @users.route('/<user_id>/events/<event_id>/event_get_interested_status') def event_get_interested_status(user_id, event_id): from app.mod_event import Event u = User.objects.get_or_404(id=user_id) p = Event.objects.get_or_404(id=event_id) for interest in p.interested: if(u.id == interest.user.id): return "true" return "false" @users.route('/<id>', methods=['GET']) def detail(id): """ Show a single userproposal, redirecting to the appropriate school if necessary """ u = User.objects.get_or_404(id=id) #c = get_school_context(u) #if not g.school==c: # flash(_("You've been redirected to the school the user is following.")) # return redirect(url_for_school('users.detail', school=c, id=u.id), code=301) return render_template('user/detail.html', title = u.display_name, user = u) @users.route('/edit/<id>', methods=['GET', 'POST']) @users.route('/edit', methods=['GET', 'POST']) @can_edit @login_required def edit(id=None): """ Edit a user """ if id: u = User.objects.get_or_404(id=id) else: u = current_user._get_current_object() if len(all_schools()) > 1: form = UserSettingsForm(request.form, u) else: form = UserSettingsFormOneSchool(request.form, u) # submit if form.validate_on_submit(): form.populate_obj(u) u.save() flash(Markup("<span class=\"glyphicon glyphicon-ok\"></span> The settings have been saved."), 'success') return render_template('user/settings.html', title=_('Edit settings'), user = u, form=form) @users.route('/password', methods=['GET', 'POST']) @login_required def password(): user = current_user._get_current_object() form = PasswordForm(next=request.args.get('next')) if form.validate_on_submit(): user.set_password(form.new_password.data) user.save() flash(Markup('<span class=\"glyphicon glyphicon-ok\"></span> Password updated.'), 'success') return redirect(url_for('users.edit')) return render_template('user/password.html', user=user, form=form) @users.route('/create', methods=['GET', 'POST']) def create(): """ Register a new user """ # create the form if len(all_schools()) > 1: form = UserAddForm(request.form, schools=[g.school,], next=request.args.get('next')) else: form = UserAddFormOneSchool(request.form, next=request.args.get('next')) # submit if form.validate_on_submit(): u = User(password=form.new_password.data) form.populate_obj(u) u.save() login_user(u) flash(_("Welcome %(user)s!", user=u.display_name), 'success') #return redirect(form.next.data or url_for_school('schools.home', user_school=True)) return redirect(form.next.data or url_for('schools.home')) # Our simple custom captcha implementation #gotcha = 'which letter in this sentence is uppercase?' #gotcha_cap = '-' #while gotcha_cap not in string.letters: # idx = randint(0, len(gotcha)-1) # gotcha_cap = gotcha[idx] #form.gotcha.label = gotcha[:idx].lower() + gotcha[idx:].capitalize() #session['gotcha'] = gotcha_cap return render_template('user/create.html', title=_('Create an account'), form=form) @users.route('/give_admin', methods=['GET']) def give_admin(): if current_user.is_anonymous(): flash(Markup("<span class=\"glyphicon glyphicon-info-sign\"></span> You have to login before giving admin privileges."), "info") return redirect('/login?next=' + str(request.path)) # Throw 403 if user isn't an admin if not current_user.is_admin(): abort(403) return render_template('user/give_admin.html') @users.route('/post_give_admin', methods=['POST']) def post_give_admin(): # Throw 403 if user isn't an admin if not current_user.is_admin(): abort(403) try: u = User.objects.get(username=request.form['username']) u.role = 100 u.save() flash(Markup("<span class=\"glyphicon glyphicon-ok\"></span> The username \"" + u.username + "\" was given admin privileges."), "success") except User.DoesNotExist: return render_template('user/give_admin.html', username_error = True) return redirect(url_for('users.edit'))
mit
chregu/hack-examples
opaquetypealiasing.php
208
<?hh // File1.php newtype SecretID = int; function modify_secret_id(SecretID $sid): SecretID { return $sid - time() - 2042; } function main_ot1(): void { echo modify_secret_id(44596); } main_ot1();
mit
ccoakley/dbcbet
dbcbet/dbcbet.py
25651
""" dbcbet: The library for design-by-contract The public API is: @inv(some_predicate) and @dbc applied to a class @pre(some_predicate) and @post(some_predicate) applied to a method @pre_final applied to a method @throws(exception1, ...) applied to a method The functions (predicates) used by the decorators have different signatures based on the type of contract component and on the signature of the method they apply to """ """TODO: reintroduce contract write braces and contract execution braces Global level for write and execute proposed syntax: global: dbcbet.contract.write(True) # or False dbcbet.contract.enforce(True) # or False granular: ClassName._contract.enforce(True) ClassName._contract.enforce(methodname, True) ClassName._contract.enforce(methodname, "pre", True) # pre, post, inv, and throws are valid for second param """ class inv(object): """A callable object (decorator) which attaches an invariant to a class""" def __get__(self, instance, owner): from types import MethodType return MethodType(self, instance, owner) def __init__(self, invariant, inherit=True): self.invariant = invariant self.inherit=inherit def __call__(self, clazz): self.clazz = clazz if hasattr(clazz, "_invariant_class") and clazz._invariant_class == clazz.__name__: clazz._invariant.append(self.invariant) else: clazz._invariant = [self.invariant] clazz._invariant_class = clazz.__name__ ensure_invoker(self.clazz) if self.inherit: inherit_contract(clazz) return clazz def ensure_invoker(class_): import inspect mets = inspect.getmembers(class_, predicate=inspect.ismethod) for methodname, method in mets: if is_public(methodname): if not hasattr(method, "_invoker_exists"): setattr(class_, methodname, create_invoker(method)) def check_preconditions(wrapped_method, s, *args, **kwargs): violations = [] if not hasattr(wrapped_method, "_precondition"): return for pred_list in wrapped_method._precondition: for pred in pred_list: if not pred(s, *args, **kwargs): violations.append(pred) break else: # pred_list was exhausted with no break return raise PreconditionViolation(violations, s, wrapped_method.__wrapped__, args, kwargs) def check_postconditions(wrapped_method, s, old, ret, *args, **kwargs): if not hasattr(wrapped_method, "_postcondition"): return for pred in wrapped_method._postcondition: if not pred(s, old, ret, *args, **kwargs): raise PostconditionViolation(pred, s, old, ret, wrapped_method.__wrapped__, args, kwargs) def check_invariants(wrapped_method, s, *args, **kwargs): if not hasattr(s.__class__, "_invariant"): return for pred in s.__class__._invariant: if not pred(s): raise InvariantViolation(pred, s, wrapped_method.__wrapped__, args, kwargs) def check_throws(wrapped_method, ex, s, *args, **kwargs): """Exceptions are checked against the contractually allowed types.""" # suppport underspecification, no @throws means all exceptions allowed if not hasattr(wrapped_method, "_throws"): return True # ContractViolations are treated differently from other ThrowsViolations check = wrapped_method._throws + [ContractViolation] # See if the exception was in the permitted list for exception_type in check: if isinstance(ex, exception_type): return True # Exception was not allowed raise ThrowsViolation(ex, s, wrapped_method.__wrapped__, args, kwargs) def create_invoker(method): """One wrapper checks all contract components and invokes the method.""" from functools import wraps @wraps(method) def wrapped_method(s, *args, **kwargs): check_preconditions(wrapped_method, s, *args, **kwargs) # A deep copy of the object and arguments are created for the postcondition o = old(method, s, args, kwargs) try: ret = method(s, *args, **kwargs) check_postconditions(wrapped_method, s, o, ret, *args, **kwargs) check_invariants(wrapped_method, s, *args, **kwargs) except Exception as ex: if check_throws(wrapped_method, ex, s, *args, **kwargs): raise return ret wrapped_method.__wrapped__ = method wrapped_method._invoker_exists = True return wrapped_method def dbc(clazz): """A callable object (decorator) which applies the inheritance of a contract without applying an invariant""" ensure_invoker(clazz) inherit_contract(clazz) return clazz def propogate_unwrapped(method): while True: try: if hasattr(method, "__wrapped__"): unwrapped = method.__wrapped__ preserve_contracts_instance(unwrapped, method) method = unwrapped else: break except AttributeError: break # def preserve_contracts(wrapped_method, method): # if hasattr(method, "_postcondition"): wrapped_method._postcondition = method._postcondition # if hasattr(method, "_precondition"): wrapped_method._precondition = method._precondition # if hasattr(method, "_invariant"): wrapped_method._invariant = method._invariant # if hasattr(method, "_throws"): wrapped_method._throws = method._throws def preserve_contracts_instance(wrapped_method, method): if hasattr(method.__func__, "_postcondition"): try: wrapped_method.__func__._postcondition = method.__func__._postcondition except AttributeError: wrapped_method._postcondition = method.__func__._postcondition if hasattr(method.__func__, "_precondition"): try: wrapped_method.__func__._precondition = method.__func__._precondition except AttributeError: wrapped_method._precondition = method.__func__._precondition if hasattr(method.__func__, "_throws"): try: wrapped_method.__func__._throws = method.__func__._throws except AttributeError: wrapped_method._throws = method.__func__._throws # # This is how we handle inheritance # def inherit_contract(clazz): for baseclass in clazz.__bases__: if check_contract_inherited(clazz, baseclass): inherit_invariant_from(clazz, baseclass) inherit_method_contract_components_from(clazz, baseclass) declare_contract_inherited(clazz, baseclass) def check_contract_inherited(clazz, baseclass): return not hasattr(clazz, "_inherited_contract_from") or baseclass.__name__ not in clazz._inherited_contract_from def declare_contract_inherited(clazz, baseclass): if hasattr(clazz, "_inherited_contract_from"): clazz._inherited_contract_from.append(baseclass.__name__) else: clazz._inherited_contract_from = [baseclass.__name__] def inherit_invariant_from(clazz, baseclass): if hasattr(baseclass, "_invariant"): for pred in baseclass._invariant: inv(pred, inherit=False)(clazz) def inherit_method_contract_components_from(clazz, baseclass): import inspect mets = inspect.getmembers(clazz, predicate=inspect.ismethod) for methodname, method in mets: if is_public(methodname): # is there anything to inherit from? if hasattr(baseclass, methodname): baseclass_version = getattr(baseclass, methodname) # is there anything to inherit? if hasattr(baseclass_version, "_precondition"): pre(baseclass_version._precondition)._compose_baseclass_precondition(method.__func__, baseclass_version) if hasattr(baseclass_version, "_postcondition"): setattr(method.__func__, "_postcondition", post(baseclass_version._postcondition).compose_list(method.__func__)) if hasattr(baseclass_version, "_throws"): setattr(method.__func__, "_throws", throws(*tuple(baseclass_version._throws)).compose_list(method.__func__)) propogate_unwrapped(method) # # Some helper functions used by the invariant class # def is_public(methodname): """Determines if a method is public by looking for leading underscore. pseudo-public methods are skipped""" return methodname[0] != "_" or methodname == "__str__" or methodname == "__init__" or methodname == "__eq__" or methodname == "__hash__" # # reduce(lambda x, y: x and y, map(has_property, list), 1) # reduce(lambda x, y: x or y, map(has_property, list), 0) # class ContractViolation(Exception): """Base class for all contract violation classes""" def __init__(self, message): self.message = message def __str__(self): return self.message def predicate_string(self, predicate): outstring = str(predicate.__name__) if hasattr(predicate, "error"): outstring = predicate.error() elif hasattr(predicate, "__doc__") and predicate.__doc__ is not None: outstring = predicate.__doc__ return outstring class PreconditionViolation(ContractViolation): def __init__(self, predicate_list, instance, method, *args, **kwargs): self.predicate_list = predicate_list self.instance = instance self.method = method self.args = args self.kwargs = kwargs def __str__(self): outstring = "Precondition Violation: Instance of %s failed when calling %s with arguments (%s), keywords %s. Contract: %s" % (self.instance.__class__.__name__, self.method.__name__, ', '.join(map(str,self.args)), self.kwargs, ', '.join(map(self.predicate_string, self.predicate_list))) return outstring class PostconditionViolation(ContractViolation): def __init__(self, predicate, instance, old, ret, method, args, kwargs): self.predicate = predicate self.instance = instance self.old = old self.ret = ret self.method = method self.args = args self.kwargs = kwargs def __str__(self): outstring = "Postcondition Violation: Instance of %s with initialization failed when calling %s with arguments (%s), keywords %s, old values: %s, return: %s. Contract: %s" % (self.instance.__class__.__name__, self.method.__name__, ', '.join(map(str,self.args)), self.kwargs, self.old, self.ret, self.predicate_string(self.predicate)) return outstring class InvariantViolation(ContractViolation): def __init__(self, predicate, instance, method, args, kwargs): self.predicate = predicate self.instance = instance self.method = method self.args = args self.kwargs = kwargs def __str__(self): outstring = "Invariant Violation: Instance of %s failed when calling %s with arguments (%s), keywords %s. Contract: %s" % (self.instance.__class__.__name__, self.method.__name__, ', '.join(map(str,self.args)), self.kwargs, self.predicate_string(self.predicate)) return outstring class ThrowsViolation(ContractViolation): def __init__(self, exception, instance, method, args, kwargs): self.exception = exception self.instance = instance self.method = method self.args = args self.kwargs = kwargs def __str__(self): outstring = "Throws Violation: Instance of %s failed when calling %s with arguments (%s), keywords %s. Threw %s" % (self.instance.__class__.__name__, self.method.__name__, ', '.join(map(str, self.args)), self.kwargs, str(type(self.exception))) return outstring class throws(object): """A callable object (decorator) which attaches an allowable exception type to a method""" def __get__(self, instance, owner): from types import MethodType return MethodType(self, instance, owner) def __init__(self, *exceptions): self.exceptions = list(exceptions) def __call__(self, method): if hasattr(method, "_invoker_exists"): wrapped_method = method else: wrapped_method = create_invoker(method) # this allows additional exceptions self.compose(method, wrapped_method) return wrapped_method def compose(self, method, wrapped_method): # append acceptable throws if hasattr(method, "_throws"): method._throws.extend(self.exceptions) wrapped_method._throws = method._throws else: wrapped_method._throws = self.exceptions def compose_list(self,method): # each element of the throws list should either be # 1. in the superclass list or # 2. have a superclass in the superclass list if hasattr(method, "_throws"): for ex in method._throws: if not (ex in self.exceptions or issubclass(ex, tuple(self.exceptions))): raise ContractViolation("throws has an implicit precondition: the exception or a supertype of the exception must be in the supertype throws list") return method._throws return self.exceptions if hasattr(method, "_throws"): method._throws.extend(self.exceptions) return method._throws return self.exceptions class pre(object): """A callable object (decorator) which attaches a precondition to a method""" def __get__(self, instance, owner): from types import MethodType return MethodType(self, instance, owner) def __init__(self, precondition): self.precondition = precondition def __call__(self, method): if hasattr(method, "_invoker_exists"): wrapped_method = method else: wrapped_method = create_invoker(method) # this conjuncts existing preconditions (chained preconditions) self.compose(method, wrapped_method) return wrapped_method def compose(self, method, wrapped_method): # possibly replace the precondition with the conjunct of previous preconditions if hasattr(method, "_precondition"): method._uninherited_precondition.append(self.precondition) wrapped_method._uninherited_precondition = method._uninherited_precondition wrapped_method._precondition = method._precondition else: wrapped_method._uninherited_precondition = [self.precondition] wrapped_method._precondition = [wrapped_method._uninherited_precondition] def _compose_baseclass_precondition(self,method,baseclass_method): if hasattr(method, "_precondition"): if not hasattr(baseclass_method, "_final_pre"): method._precondition.extend(self.precondition) else: method._precondition[0:len(method._precondition)] = [] method._precondtion.extend(self.precondition) else: method._uninherited_precondition = [] method._precondition = [method._uninherited_precondition, self.precondition] if hasattr(baseclass_method, "_final_pre"): method._final_pre = True class post(object): """A callable object (decorator) which attaches a postcondition to a method""" def __get__(self, instance, owner): from types import MethodType return MethodType(self, instance, owner) def __init__(self, postcondition): self.postcondition = postcondition def __call__(self, method): if hasattr(method, "_invoker_exists"): wrapped_method = method else: wrapped_method = create_invoker(method) # this conjuncts existing postconditions self.compose(method, wrapped_method) return wrapped_method def compose(self, method, wrapped_method): # possibly replace the postcondition with the conjunct of previous postcondition if hasattr(method, "_postcondition"): method._postcondition.append(self.postcondition) wrapped_method._postcondition = method._postcondition else: wrapped_method._postcondition = [self.postcondition] def compose_list(self,method): # possibly replace the postcondition with the conjunct of previous postcondition if hasattr(method, "_postcondition"): method._postcondition.extend(self.postcondition) return method._postcondition return self.postcondition class old(object): """A nicer interface for old in postconditions""" def __init__(self, method, s, args, kwargs): """Performs a deep copy of self (s, not the current old-self), args, and kwargs""" import copy self.self = copy.deepcopy(s) self.args = copy.deepcopy(args) self.kwargs = copy.deepcopy(kwargs) def __repr__(self): return "old(self=%s,args=%s,kwargs=%s)" % (self.self, self.args, self.kwargs) # # Bounded exhaustive testing support # class bet(object): """The Bounded Exhaustive Testing class""" def __init__(self, clazz): """Binds us to the class""" self.clazz = clazz self.invariant_violations = 0 self.precondition_violations = 0 self.failures = 0 self.successes = 0 self.candidates = 0 self.method_call_candidates = 0 self.running_log = [] self.arg_scope = -1 def with_arg_scope(self, scope): self.arg_scope = scope def run(self): """Intantiates all objects satisfying the invariant. Then, for each instance, calls each method with the finitization arguments satisfying the precondition. Deep copying is used.""" for fs in enumerate(self.clazz): candidate = self.instantiate_with(self.clazz, fs) self.process_candidate(candidate, fs) if self.candidates == 0: candidate = self.instantiate_with(self.clazz, {}) self.process_candidate(candidate, {}) self.print_invoice() def process_candidate(self, candidate, fs): for pred in candidate._invariant: if not pred(candidate): self.invariant_violations += 1 return self.process_methods(candidate, fs) self.candidates += 1 def print_invoice(self): print "\n".join(self.running_log) print "Summary: " print " Instance Candidates: " + str(self.candidates) print " Invariant Violations: " + str(self.invariant_violations) print " Method Call Candidates: " + str(self.method_call_candidates) print " Precondition Violations: " + str(self.precondition_violations) print " Failures: " + str(self.failures) print " Successes: " + str(self.successes) def process_methods(self, candidate, fs): import inspect mets = inspect.getmembers(candidate, predicate=inspect.ismethod) for key, val in mets: if hasattr(val, "_bet_arguments"): self.call_method(candidate, fs, val) def call_with_args_and_precondition(self, candidate, fs, val, args): import copy candidate_copy = copy.deepcopy(candidate) if self.process_precondition(val, candidate_copy, args): self.call_with_args(candidate, fs, val, args) else: self.precondition_violations += 1 def process_precondition(self, val, candidate, args): for predlist in getattr(val, "_precondition"): success = True for pred in predlist: if not pred(candidate, *args): success = False if success: return True return False def call_with_args(self, candidate, fs, val, args): try: val(*args) self.successes += 1 except ContractViolation as cv: self.log_call_failure(candidate, fs, val, args, cv) self.failures += 1 def log_call_failure(self, candidate, fs, val, args, cv): self.running_log.append("instance of %s with initialization %s failed when calling %s with arguments %s. Reason: %s" % (candidate.__class__.__name__, fs, val.__name__, ', '.join(map(str,args)), cv)) def log_precondition_not_found(self, val): self.running_log.append("No precondition found when attempting to call %s" % (val.__name__)) def call_method(self, candidate, fs, val): for args in enumerate_args(val._bet_arguments, self.arg_scope): self.method_call_candidates += 1 if hasattr(val, "_precondition"): self.call_with_args_and_precondition(candidate, fs, val, args) else: self.log_precondition_not_found(val) self.call_with_args(candidate, fs, val, args) def instantiate_with(self, clazz, fieldset): """Instantiates an object and sets its fields to the values in the dictionary""" instance = self.find_acceptable_instance(clazz) for k, v in fieldset.items(): setattr(instance, k, v) return instance def find_acceptable_instance(self, clazz): import inspect mets = inspect.getmembers(clazz, predicate=inspect.ismethod) found = False for key, val in mets: if key == "__init__": found = True if hasattr(val, "_bet_arguments"): return self.call_init(clazz, val) else: return clazz() if not found: return clazz() def call_init(self, candidate, val): for args in enumerate_args(val._bet_arguments, self.arg_scope): try: return candidate(*args) except ContractViolation: pass # I used to check the precondition separately, but it's more compact without it # def call_init(candidate, val): # for args in enumerate_args(val._bet_arguments): # if hasattr(val, "_precondition"): # for pred in getattr(val, "_precondition"): # if not pred(candidate, *args): # break # try: # return candidate(*args) # except ContractViolation: # pass # else: # return candidate(*args) class finitize(object): def __init__(self, finitization): self. finitization = finitization self.fieldset = finitization() def __call__(self, clazz): clazz._finitization_field_set = self.fieldset return clazz class finitize_method(object): def __init__(self, *bet_arguments): self.bet_arguments = bet_arguments def __call__(self, method): method._bet_arguments = self.bet_arguments return method # def enumerate_gen(ob): # """The generator version of instance enumeration.""" # fieldvector = ob._finitization_field_set.keys() # indexvector = [0 for f in fieldvector] # maxindexvector = [len(ob._finitization_field_set[fi]) for fi in fieldvector] # while(indexvector): # yield dict( (key, ob._finitization_field_set[key][indexvector[fieldvector.index(key)]]) for key in fieldvector) # indexvector = increment_vec(indexvector, maxindexvector) class enumerate_args(object): def __init__(self, arg, arg_scope): self.fieldvector = arg self.arg_scope = arg_scope self.indexvector = [0 for f in self.fieldvector] self.maxindexvector = [len(a) for a in arg] def __iter__(self): return self def next(self): self.arg_scope -= 1 if self.arg_scope == -1: raise StopIteration if self.indexvector: ret = [self.fieldvector[pos][self.indexvector[pos]] for pos in xrange(len(self.indexvector))] self.indexvector = increment_vec(self.indexvector, self.maxindexvector) return ret else: raise StopIteration def __len__(self): return reduce(lambda x, y: x*len(y), self.ob._finitization_field_set.values(), 1) class enumerate(object): """The iterator version of instance enumeration. This version supports len(), so BET can recurse on instances.""" def __init__(self, ob): self.ob = ob if not hasattr(ob, "_finitization_field_set"): ob._finitization_field_set = {} self.fieldvector = ob._finitization_field_set.keys() self.indexvector = [0 for f in self.fieldvector] self.maxindexvector = [len(ob._finitization_field_set[fi]) for fi in self.fieldvector] def __iter__(self): return self def next(self): if self.indexvector: ret = dict( (key,self.ob._finitization_field_set[key][self.indexvector[self.fieldvector.index(key)]]) for key in self.fieldvector) self.indexvector = increment_vec(self.indexvector, self.maxindexvector) return ret else: raise StopIteration def __len__(self): return reduce(lambda x, y: x*len(y), self.ob._finitization_field_set.values(), 1) def increment_vec(vec, max_vec): def hidden_increment(vec, max_vec, pos): if pos >= len(vec): return False if vec[pos] == max_vec[pos] - 1: vec[pos] = 0 return hidden_increment(vec, max_vec, pos+1) vec[pos] = vec[pos]+1 return vec return hidden_increment(vec, max_vec, 0)
mit
twasilczyk/gg-dissector
dissect-gg11.cpp
11536
#include "packet-gg.hpp" #include "dissect-gg11.hpp" #include "dissect-protobuf.hpp" #include <vector> #include <iostream> using namespace std; gint ett_option = -1; gint ett_mpanotify_data = -1; class GGPDisplayOption : public PBDisplay { public: GGPDisplayOption():PBDisplay(PBTYPE_STRING) {} virtual void display(proto_tree *tree, tvbuff_t *tvb); }; class GGPDisplayJson : public PBDisplay { public: GGPDisplayJson():PBDisplay(PBTYPE_STRING) {} virtual void display(proto_tree *tree, tvbuff_t *tvb); }; static vector<shared_ptr<PBDisplay>> packet_login105 = { make_shared<PBDisplayString>(GGPFieldString("language", "gg.login105.language", NULL)), make_shared<PBDisplayUIN>(GGPFieldString("uin", "gg.login105.uin", NULL)), make_shared<PBDisplayBlob>(GGPFieldBlob("hash", "gg.login105.hash", NULL)), make_shared<PBDisplayVarint>(GGPFieldUINT64("dummy1", "gg.login105.dummy1", NULL)), make_shared<PBDisplayUINT32>(GGPFieldHEX32("dummy2", "gg.login105.dummy2", NULL)), make_shared<PBDisplayUINT32>(GGPFieldHEX32("dummy3", "gg.login105.dummy3", NULL)), make_shared<PBDisplayString>(GGPFieldString("client", "gg.login105.client", NULL)), make_shared<PBDisplayUINT32>(GGPFieldHEX32("initial_status", "gg.login105.initial_status", NULL)), make_shared<PBDisplayString>(GGPFieldString("initial_descr", "gg.login105.initial_descr", NULL)), make_shared<PBDisplayBlob>(GGPFieldBlob("dummy4", "gg.login105.dummy4", NULL)), make_shared<PBDisplayString>(GGPFieldString("supported_features", "gg.login105.supported_features", NULL)), make_shared<PBDisplayVarint>(GGPFieldUINT64("dummy5", "gg.login105.dummy5", NULL)), make_shared<PBDisplayVarint>(GGPFieldUINT64("dummy6", "gg.login105.dummy6", NULL)), make_shared<PBDisplayUINT32>(GGPFieldUINT32("dummy7", "gg.login105.dummy7", NULL)), make_shared<PBDisplayVarint>(GGPFieldUINT64("dummy8", "gg.login105.dummy8", NULL)), make_shared<PBDisplayUnknown>(), make_shared<PBDisplayVarint>(GGPFieldUINT64("dummy10", "gg.login105.dummy10", NULL)), make_shared<PBDisplayUnknown>(), make_shared<PBDisplayUnknown>(), make_shared<PBDisplayUnknown>(), make_shared<PBDisplayUnknown>(), make_shared<PBDisplayBlob>(GGPFieldBlob("dummy15", "gg.login105.dummy15", NULL)), make_shared<PBDisplayVarint>(GGPFieldUINT64("dummy16", "gg.login105.dummy16", NULL)), make_shared<PBDisplayBlob>(GGPFieldBlob("dummy17", "gg.login105.dummy17", NULL)), make_shared<PBDisplayVarint>(GGPFieldUINT64("dummy18", "gg.login105.dummy18", NULL)), make_shared<PBDisplayUnknown>(), make_shared<PBDisplayUnknown>(), make_shared<PBDisplayUnknown>(), make_shared<PBDisplayBlob>(GGPFieldBlob("dummy21", "gg.login105.dummy21", NULL)), }; static vector<shared_ptr<PBDisplay>> packet_login105_ok = { make_shared<PBDisplayVarint>(GGPFieldUINT64("dummy1", "gg.login105ok.dummy1", NULL)), make_shared<PBDisplayString>(GGPFieldString("dummyhash", "gg.login105ok.dummyhash", NULL)), make_shared<PBDisplayVarint>(GGPFieldUINT64("uin", "gg.login105ok.uin", NULL)), make_shared<PBDisplayTimestamp>(GGPFieldTimestamp("server_time", "gg.login105ok.server_time", NULL)), }; static vector<shared_ptr<PBDisplay>> packet_send_msg110 = { make_shared<PBDisplayUIN>(GGPFieldString("recipient", "gg.sendmsg110.recipient", NULL)), make_shared<PBDisplayVarint>(GGPFieldUINT64("dummy1", "gg.sendmsg110.dummy1", NULL)), make_shared<PBDisplayVarint>(GGPFieldUINT64("seq", "gg.sendmsg110.seq", NULL)), make_shared<PBDisplayUnknown>(), make_shared<PBDisplayString>(GGPFieldString("msg_plain", "gg.sendmsg110.msg_plain", NULL)), make_shared<PBDisplayString>(GGPFieldString("msg_xhtml", "gg.sendmsg110.xhtml", NULL)), make_shared<PBDisplayBlob>(GGPFieldBlob("dummy3", "gg.sendmsg110.dummy3", NULL)), make_shared<PBDisplayUnknown>(), make_shared<PBDisplayUnknown>(), make_shared<PBDisplayUINT64>(GGPFieldHEX64("chat_id", "gg.sendmsg110.chat_id", NULL)), }; static vector<shared_ptr<PBDisplay>> packet_recv_msg110 = { make_shared<PBDisplayUIN>(GGPFieldString("sender", "gg.recvmsg110.sender", NULL)), make_shared<PBDisplayVarint>(GGPFieldHEX64("flags", "gg.recvmsg110.flags", NULL)), make_shared<PBDisplayVarint>(GGPFieldUINT64("seq", "gg.recvmsg110.seq", NULL)), make_shared<PBDisplayUINT32>(GGPFieldUINT32("time", "gg.recvmsg110.time", NULL)), make_shared<PBDisplayString>(GGPFieldString("msg_plain", "gg.recvmsg110.msg_plain", NULL)), make_shared<PBDisplayString>(GGPFieldString("msg_xhtml", "gg.recvmsg110.msg_xhtml", NULL)), make_shared<PBDisplayBlob>(GGPFieldBlob("data", "gg.recvmsg110.data", NULL)), make_shared<PBDisplayUnknown>(), make_shared<PBDisplayUINT64>(GGPFieldHEX64("msg_id", "gg.recvmsg110.msg_id", NULL)), make_shared<PBDisplayUINT64>(GGPFieldHEX64("chat_id", "gg.recvmsg110.chat_id", NULL)), make_shared<PBDisplayUINT64>(GGPFieldHEX64("conv_id", "gg.recvmsg110.conv_id", NULL)), }; static vector<shared_ptr<PBDisplay>> packet_imtoken = { make_shared<PBDisplayString>(GGPFieldString("imtoken", "gg.imtoken.imtoken", NULL)), }; GGPFieldBlob option_field("option", "gg.options.option", NULL); static vector<shared_ptr<PBDisplay>> packet_options = { make_shared<GGPDisplayOption>(), make_shared<PBDisplayVarint>(GGPFieldUINT64("dummy1", "gg.options.dummy1", NULL)), }; GGPFieldString option_key_field("key", "gg.options.option.key", NULL); GGPFieldString option_value_field("value", "gg.options.option.value", NULL); static vector<shared_ptr<PBDisplay>> packet_options_option = { make_shared<PBDisplayString>(option_key_field), make_shared<PBDisplayString>(option_value_field), }; static vector<shared_ptr<PBDisplay>> packet_lastdates = { make_shared<PBDisplayVarint>(GGPFieldUINT64("dummy1", "gg.lastdates.dummy1", NULL)), make_shared<PBDisplayVarint>(GGPFieldUINT64("dummy2", "gg.lastdates.dummy2", NULL)), make_shared<PBDisplayVITimestamp>(GGPFieldTimestamp("dummydate1", "gg.lastdates.dummydate1", NULL)), make_shared<PBDisplayVITimestamp>(GGPFieldTimestamp("dummydate2", "gg.lastdates.dummydate2", NULL)), make_shared<PBDisplayVITimestamp>(GGPFieldTimestamp("dummydate3", "gg.lastdates.dummydate3", NULL)), }; GGPFieldString packet_mpanotify_data("data", "gg.mpanotify.data", NULL); static vector<shared_ptr<PBDisplay>> packet_mpanotify = { make_shared<PBDisplayVarint>(GGPFieldUINT64("dummy1", "gg.mpanotify.dummy1", NULL)), make_shared<PBDisplayVarint>(GGPFieldUINT64("dummy2", "gg.mpanotify.dummy2", NULL)), make_shared<GGPDisplayJson>(), make_shared<PBDisplayString>(GGPFieldString("content_type", "gg.mpanotify.content_type", NULL)), make_shared<PBDisplayVarint>(GGPFieldUINT64("dummyid", "gg.mpanotify.dummyid", NULL)), }; const value_string ack110_types[] = { { 1, "MSG" }, { 2, "CHAT" }, { 3, "CHAT_INFO" }, { 6, "MPA" }, { 7, "TRANSFER_INFO" }, { 0, NULL } }; static vector<shared_ptr<PBDisplay>> packet_ack110 = { make_shared<PBDisplayEnum>(GGPFieldEnum("type", "gg.ack110.type", NULL, VALS(ack110_types))), make_shared<PBDisplayVarint>(GGPFieldUINT64("seq", "gg.ack110.seq", NULL)), make_shared<PBDisplayVarint>(GGPFieldUINT64("dummy1", "gg.ack110.dummy1", NULL)), }; static vector<shared_ptr<PBDisplay>> packet_send_msg_ack110 = { make_shared<PBDisplayVarint>(GGPFieldUINT64("msg_type", "gg.sendmsgack110.msg_type", NULL)), make_shared<PBDisplayVarint>(GGPFieldUINT64("seq", "gg.sendmsgack110.seq", NULL)), make_shared<PBDisplayTimestamp>(GGPFieldTimestamp("time", "gg.sendmsgack110.time", NULL)), make_shared<PBDisplayUINT64>(GGPFieldHEX64("msg_id", "gg.sendmsgack110.msg_id", NULL)), make_shared<PBDisplayUINT64>(GGPFieldHEX64("conv_id", "gg.sendmsgack110.conv_id", NULL)), make_shared<PBDisplayBlob>(GGPFieldBlob("link", "gg.sendmsgack110.link", NULL)), make_shared<PBDisplayVarint>(GGPFieldUINT64("dummy1", "gg.sendmsgack110.dummy1", NULL)), }; static vector<shared_ptr<PBDisplay>> packet_chat_info_update = { make_shared<PBDisplayUIN>(GGPFieldString("participant", "gg.chat_info_update.participant", NULL)), make_shared<PBDisplayUIN>(GGPFieldString("inviter", "gg.chat_info_update.inviter", NULL)), make_shared<PBDisplayUINT32>(GGPFieldUINT32("update_type", "gg.chat_info_update.update_type", NULL)), make_shared<PBDisplayTimestamp>(GGPFieldTimestamp("time", "gg.chat_info_update.time", NULL)), make_shared<PBDisplayUINT32>(GGPFieldUINT32("dummy1", "gg.chat_info_update.dummy1", NULL)), make_shared<PBDisplayVarint>(GGPFieldUINT64("version", "gg.chat_info_update.version", NULL)), make_shared<PBDisplayVarint>(GGPFieldUINT64("dummy2", "gg.chat_info_update.dummy2", NULL)), make_shared<PBDisplayUnknown>(), make_shared<PBDisplayUINT64>(GGPFieldHEX64("msg_id", "gg.chat_info_update.msg_id", NULL)), make_shared<PBDisplayUINT64>(GGPFieldHEX64("chat_id", "gg.chat_info_update.chat_id", NULL)), make_shared<PBDisplayUINT64>(GGPFieldHEX64("conv_id", "gg.chat_info_update.conv_id", NULL)), }; void init_gg11() { static gint *ett[] = { &ett_option, &ett_mpanotify_data }; proto_register_subtree_array(ett, array_length(ett)); } void dissect_gg11_login105(tvbuff_t *tvb, proto_tree *tree) { dissect_protobuf(tvb, tree, packet_login105); } void dissect_gg11_login105_ok(tvbuff_t *tvb, proto_tree *tree) { dissect_protobuf(tvb, tree, packet_login105_ok); } void dissect_gg11_send_msg110(tvbuff_t *tvb, proto_tree *tree) { dissect_protobuf(tvb, tree, packet_send_msg110); } void dissect_gg11_recv_msg110(tvbuff_t *tvb, proto_tree *tree) { dissect_protobuf(tvb, tree, packet_recv_msg110); } void dissect_gg11_imtoken(tvbuff_t *tvb, proto_tree *tree) { dissect_protobuf(tvb, tree, packet_imtoken); } void dissect_gg11_options(tvbuff_t *tvb, proto_tree *tree) { dissect_protobuf(tvb, tree, packet_options); } void dissect_gg11_lastdates(tvbuff_t *tvb, proto_tree *tree) { dissect_protobuf(tvb, tree, packet_lastdates); } void dissect_gg11_mpanotify(tvbuff_t *tvb, proto_tree *tree) { dissect_protobuf(tvb, tree, packet_mpanotify); } void dissect_gg11_ack110(tvbuff_t *tvb, proto_tree *tree) { dissect_protobuf(tvb, tree, packet_ack110); } void dissect_gg11_send_msg_ack110(tvbuff_t *tvb, proto_tree *tree) { dissect_protobuf(tvb, tree, packet_send_msg_ack110); } void dissect_gg11_chat_info_update(tvbuff_t *tvb, proto_tree *tree) { dissect_protobuf(tvb, tree, packet_chat_info_update); } void GGPDisplayOption::display(proto_tree *tree, tvbuff_t *tvb) { proto_item *ti = proto_tree_add_item(tree, option_field, tvb, 0, tvb_length(tvb), 0); proto_tree *subtree = proto_item_add_subtree(ti, ett_option); dissect_protobuf(tvb, subtree, packet_options_option); GPtrArray *fields = proto_all_finfos(subtree); if (fields->len == 3) { field_info *key_f = (field_info*)g_ptr_array_index(fields, 1); field_info *value_f = (field_info*)g_ptr_array_index(fields, 2); char *key = NULL, *value = NULL; if (key_f) key = fvalue_to_string_repr(&key_f->value, FTREPR_DISPLAY, NULL); if (value_f) value = fvalue_to_string_repr(&value_f->value, FTREPR_DISPLAY, NULL); if (key && value) proto_item_set_text(ti, "option: %s=%s", key, value); free(key); free(value); } g_ptr_array_free(fields, TRUE); } void GGPDisplayJson::display(proto_tree *tree, tvbuff_t *tvb) { proto_item *ti = proto_tree_add_item(tree, packet_mpanotify_data, tvb, 0, tvb_length(tvb), 0); if (!json_dissector) return; proto_tree *subtree = proto_item_add_subtree(ti, ett_mpanotify_data); packet_info *pinfo = tree->tree_data->pinfo; void *private_data = pinfo->private_data; pinfo->private_data = NULL; call_dissector(json_dissector, tvb, pinfo, subtree); pinfo->private_data = private_data; }
mit
robertrypula/AudioNetwork
src-still-es5/data-link-layer/data-link-layer-builder.js
3786
// Copyright (c) 2015-2018 Robert Rypuła - https://audio-network.rypula.pl 'use strict'; (function () { AudioNetwork.Injector .registerFactory('Rewrite.DataLinkLayer.DataLinkLayerBuilder', DataLinkLayerBuilder); DataLinkLayerBuilder.$inject = [ 'Rewrite.DataLinkLayer.DataLinkLayer' ]; function DataLinkLayerBuilder( DataLinkLayer ) { var DataLinkLayerBuilder; DataLinkLayerBuilder = function () { this._framePayloadLengthLimit = 7; // data link layer listeners this._rxFrameListener = undefined; this._rxFrameCandidateListener = undefined; this._txFrameListener = undefined; this._txFrameProgressListener = undefined; // physical layer listeners this._rxSymbolListener = undefined; this._rxSampleDspDetailsListener = undefined; this._rxSyncDspDetailsListener = undefined; this._rxDspConfigListener = undefined; this._dspConfigListener = undefined; this._txSymbolProgressListener = undefined; this._txDspConfigListener = undefined; }; DataLinkLayerBuilder.prototype.framePayloadLengthLimit = function (framePayloadLengthLimit) { this._framePayloadLengthLimit = framePayloadLengthLimit; return this; }; DataLinkLayerBuilder.prototype.rxFrameListener = function (listener) { this._rxFrameListener = listener; return this; }; DataLinkLayerBuilder.prototype.txFrameListener = function (listener) { this._txFrameListener = listener; return this; }; DataLinkLayerBuilder.prototype.txFrameProgressListener = function (listener) { this._txFrameProgressListener = listener; return this; }; DataLinkLayerBuilder.prototype.rxFrameCandidateListener = function (listener) { this._rxFrameCandidateListener = listener; return this; }; DataLinkLayerBuilder.prototype.rxSymbolListener = function (listener) { this._rxSymbolListener = listener; return this; }; DataLinkLayerBuilder.prototype.rxSampleDspDetailsListener = function (listener) { this._rxSampleDspDetailsListener = listener; return this; }; DataLinkLayerBuilder.prototype.rxSyncStatusListener = function (listener) { this._rxSyncStatusListener = listener; return this; }; DataLinkLayerBuilder.prototype.rxSyncDspDetailsListener = function (listener) { this._rxSyncDspDetailsListener = listener; return this; }; DataLinkLayerBuilder.prototype.rxDspConfigListener = function (listener) { this._rxDspConfigListener = listener; return this; }; DataLinkLayerBuilder.prototype.dspConfigListener = function (listener) { this._dspConfigListener = listener; return this; }; DataLinkLayerBuilder.prototype.txSymbolListener = function (listener) { this._txSymbolListener = listener; return this; }; DataLinkLayerBuilder.prototype.txSymbolProgressListener = function (listener) { this._txSymbolProgressListener = listener; return this; }; DataLinkLayerBuilder.prototype.txDspConfigListener = function (listener) { this._txDspConfigListener = listener; return this; }; DataLinkLayerBuilder.prototype.build = function () { return new DataLinkLayer(this); }; return DataLinkLayerBuilder; } })();
mit
billletson/dominion
dominion/__init__.py
103
from .deck import * from .game import * from .strategies import buy_strategies, action_strategies
mit
Guillaume-Docquier/Thingy
static/javascript/posts/controllers/search.controller.js
5041
(function(){ 'use strict' angular .module('thingy.posts.controllers') .controller('SearchController', SearchController); SearchController.$inject = ['$rootScope', '$scope', 'Posts', '$route', '$cookies', '$location', '$sce']; function SearchController($rootScope, $scope, Posts, $route, $cookies, $location, $sce) { var vm = this; // Function and Data vm.posts = []; vm.categories = []; vm.regions = []; vm.conditions = []; vm.search = search; vm.selection = selection; vm.toggleAdvanced = toggleAdvanced; vm.advanced = { status: $location.search().advanced == 'true', text: $location.search().advanced == 'true' ? '<< Basic search' : 'Advanced search >>' } // Bindings // Empty strings to prevent errors due to undefined values vm.searchTerm = $location.search().search; vm.category = ''; vm.subcategory = ''; vm.minPrice = ''; vm.maxPrice = ''; vm.region = ''; vm.subregion = ''; vm.condition = ''; vm.selectedPost; vm.geoloc = ''; activate(); function activate() { // Get db data by nesting callbacks // getAllCategories -> getAllRegions -> getAllConditions -> search Posts.getAllCategories().then(categoriesSuccessFn, categoriesErrorFn); function categoriesSuccessFn(data, status, headers, config) { vm.categories = data.data; // Url might contain search settings if($location.search().category) { vm.category = findObjectContainingKey(vm.categories, 'cname', $location.search().category); vm.subcategory = findObjectContainingKey(vm.category.subcategories, 'name', ($location.search().subcategory || '')); } // Done Posts.getAllRegions().then(regionsSuccessFn, regionsErrorFn); } function categoriesErrorFn(data) { alert('Could not load categories.'); console.error('Error: ' + JSON.stringify(data.data)); } function regionsSuccessFn(data, status, headers, config) { vm.regions = data.data; if($location.search().region) { vm.region = findObjectContainingKey(vm.regions, 'name', $location.search().region); vm.subregion = findObjectContainingKey(vm.region.towns, 'name', ($location.search().subregion || '')); } // Done Posts.getAllConditions().then(conditionsSuccessFn, conditionsErrorFn); } function regionsErrorFn(data) { alert('Could not load regions.'); console.error('Error: ' + JSON.stringify(data.data)); } function conditionsSuccessFn(data, status, headers, config) { vm.conditions = data.data; if($location.search().condition) vm.condition = findObjectContainingKey(vm.conditions, 'cond_grade', $location.search().condition); // This will search as specified in the url or return all posts vm.search(); } function conditionsErrorFn(data) { alert('Could not load conditions.'); console.error('Error: ' + JSON.stringify(data.data)); } } function search() { Posts.search( vm.searchTerm, // Matches Title or Description vm.category ? vm.category.cname : '', vm.subcategory ? vm.subcategory.name : '', vm.minPrice, vm.maxPrice, vm.region ? vm.region.name : '', vm.subregion ? vm.subregion.name : '', vm.condition ? vm.condition.cond_desc : '' ).then(searchSuccessFn, searchErrorFn); /** * @name postsSuccessFn * @desc Update posts array on view */ function searchSuccessFn(data, status, headers, config) { vm.posts = data.data; // Very basic, not fault proof $("body").animate({scrollTop: $('#searchresult').offset().top - 90}, "slow"); } /** * @name postsErrorFn * @desc Show snackbar with error */ function searchErrorFn(data) { alert('Could not proceed with the search.'); console.error('Error: ' + JSON.stringify(data.data)); } } function selection(thingy) { vm.selectedPost = thingy; vm.locationUrl ='https://www.google.com/maps/embed/v1/place?key=AIzaSyAu_fehsrcpOMagU3vcHVOaxbnkuxU4LLc&q=' + thingy.location_details.name + ',Sweden'; //vm.trustedLocationUrl = $sce.getTrustedResourceUrl(vm.locationUrl); vm.locationUrlt = 'https://www.google.com/maps/embed/v1/place?key=AIzaSyAu_fehsrcpOMagU3vcHVOaxbnkuxU4LLc &q= Stockholm,Sweden'; } // Finds which object contains value as key. function findObjectContainingKey(objects, key, value) { for(var i = 0; i < objects.length; i++) { if(objects[i][key].toLowerCase() == value.toLowerCase()) return objects[i]; } return ''; } // Toggle advanced search text function toggleAdvanced() { vm.advanced.text = ( vm.advanced.text == 'Advanced search >>' ? '<< Basic search' : 'Advanced search >>' ); } } })();
mit
BlueEastCode/loopback-graphql-relay
server/boot/root.js
1469
// Copyright IBM Corp. 2015. All Rights Reserved. // Node module: loopback-example-relations // This file is licensed under the MIT License. // License text available at https://opensource.org/licenses/MIT 'use strict'; module.exports = function(app) { const router = app.loopback.Router(); router.get('/', (req, res, next) => { app.models.Customer.findOne({ where: { name: 'Customer A', }, }, (err, customer) => { if (err) { return next(err); } return res.render('index', { customer, }); }); }); router.get('/email', (req, res, next) => { app.models.Customer.findOne({ where: { name: 'Larry Smith', }, }, (err, customer) => { if (err) { return next(err); } return res.render('email', { customer, }); }); }); router.get('/address', (req, res, next) => { app.models.Customer.findOne({ where: { name: 'John Smith', }, }, (err, customer) => { if (err) { return next(err); } return res.render('address', { customer, }); }); }); router.get('/account', (req, res, next) => { app.models.Customer.findOne({ where: { name: 'Mary Smith', }, }, (err, customer) => { if (err) { return next(err); } return res.render('account', { customer, }); }); }); app.use(router); };
mit
rawphp/Http-Bundle
src/Behat/HttpContext.php
3887
<?php namespace RawPHP\HttpBundle\Behat; use Behat\Behat\Context\Context; use Behat\Behat\Hook\Scope\ScenarioScope; use Behat\Gherkin\Node\TableNode; use Behat\Symfony2Extension\Context\KernelAwareContext; use Behat\Symfony2Extension\Context\KernelDictionary; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Response; use InvalidArgumentException; use Psr\Http\Message\RequestInterface; use RawPHP\Http\Factory\IClientFactory; use RawPHP\Http\Handler\PredictedHandler; use RawPHP\Http\Util\RequestMap; use Symfony\Component\Filesystem\Exception\FileNotFoundException; /** * Class HttpContext * * @package RawPHP\HttpBundle */ class HttpContext implements Context, KernelAwareContext { use KernelDictionary; /** @var string */ protected $resourcePath; /** @var IClientFactory */ protected $clientFactory; /** @var PredictedHandler */ protected $handler; /** * @BeforeScenario */ public function init(ScenarioScope $scope) { $this->resourcePath = $this->getContainer()->getParameter('rawphp_http.resource_dir'); $this->clientFactory = $this->getContainer()->get('rawphp_http.factory.client'); $this->handler = new PredictedHandler(); $this->clientFactory->setHandler($this->handler); } /** * @Given /^there are the following requests and responses:$/ */ public function thereAreTheFollowingRequestsAndResponses(TableNode $table) { foreach ($table->getHash() as $data) { $url = null; $body = null; $method = 'GET'; $responseContent = ''; $responseCode = 200; if (!empty($data['url'])) { $url = $data['url']; } if (!empty($data['method'])) { $method = $data['method']; } if (!empty($data['request_body'])) { $file = $this->resourcePath . '/' . $data['request_body']; if (!file_exists($file)) { throw new FileNotFoundException(sprintf('File "%s" not found', $file)); } $body = file_get_contents($file); } if (!empty($data['response_body'])) { $file = $this->resourcePath . '/' . $data['response_body']; if (!file_exists($file)) { throw new FileNotFoundException(sprintf('File "%s" not found', $file)); } $responseContent = file_get_contents($file); } if (!empty($data['response_code'])) { $responseCode = $data['response_code']; } $request = new Request($method, $url, [], $body); $response = new Response($responseCode, [], $responseContent); $map = new RequestMap($request, $response); $this->handler->addRequestMap($map); } } /** * @Given /^the following matchers exist:$/ */ public function theFollowingMatchersExist(TableNode $table) { foreach ($table->getHash() as $data) { $name = $data['name']; $class = $data['class']; $method = $data['method']; if (!class_exists($class)) { throw new InvalidArgumentException(sprintf('Class "%s" not found', $class)); } $object = new $class(); if (!method_exists($object, $method)) { throw new InvalidArgumentException(sprintf('Method "%s" not found on "%s"', $method, $class)); } $this->handler->addMatcher( $name, function (RequestInterface $request, array $maps) use ($object, $method) { return $object->$method($request, $maps); } ); }; } }
mit
ElofssonLab/web_common_backend
proj/pred/app/run_job.py
35204
#!/usr/bin/env python # Description: run job for the backend. result will not be cached import os import sys import subprocess from libpredweb import myfunc from libpredweb import webserver_common as webcom import glob import hashlib import shutil from datetime import datetime from dateutil import parser as dtparser from pytz import timezone import time import site import fcntl import json import urllib.request, urllib.parse, urllib.error FORMAT_DATETIME = webcom.FORMAT_DATETIME TZ = webcom.TZ progname = os.path.basename(sys.argv[0]) wspace = ''.join([" "]*len(progname)) rundir = os.path.dirname(os.path.realpath(__file__)) webserver_root = os.path.realpath("%s/../../../"%(rundir)) activate_env="%s/env/bin/activate_this.py"%(webserver_root) exec(compile(open(activate_env, "rb").read(), activate_env, 'exec'), dict(__file__=activate_env)) site.addsitedir("%s/env/lib/python2.7/site-packages/"%(webserver_root)) sys.path.append("/usr/local/lib/python2.7/dist-packages") basedir = os.path.realpath("%s/.."%(rundir)) # path of the application, i.e. pred/ path_md5cache = "%s/static/md5"%(basedir) path_cache = "%s/static/result/cache"%(basedir) path_result = "%s/static/result/"%(basedir) gen_errfile = "%s/static/log/%s.err"%(basedir, progname) gen_logfile = "%s/static/log/%s.log"%(basedir, progname) contact_email = "nanjiang.shu@scilifelab.se" vip_email_file = "%s/config/vip_email.txt"%(basedir) # note that here the url should be without http:// usage_short=""" Usage: %s seqfile_in_fasta %s -jobid JOBID -outpath DIR -tmpdir DIR %s -email EMAIL -baseurl BASE_WWW_URL %s -only-get-cache """%(progname, wspace, wspace, wspace) usage_ext="""\ Description: run job OPTIONS: -h, --help Print this help message and exit Created 2016-12-01, 2017-05-26, Nanjiang Shu """ usage_exp=""" Examples: %s /data3/tmp/tmp_dkgSD/query.fa -outpath /data3/result/rst_mXLDGD -tmpdir /data3/tmp/tmp_dkgSD """%(progname) def PrintHelp(fpout=sys.stdout):#{{{ print(usage_short, file=fpout) print(usage_ext, file=fpout) print(usage_exp, file=fpout)#}}} def CleanResult(name_software, query_para, outpath_this_seq, runjob_logfile, runjob_errfile):#{{{ if name_software in ["prodres", "docker_prodres"]: if not 'isKeepTempFile' in query_para or query_para['isKeepTempFile'] == False: temp_result_folder = "%s/temp"%(outpath_this_seq) if os.path.exists(temp_result_folder): try: shutil.rmtree(temp_result_folder) except Exception as e: msg = "Failed to delete the folder %s with message \"%s\""%(temp_result_folder, str(e)) webcom.loginfo(msg, runjob_errfile) flist = [ "%s/outputs/%s"%(outpath_this_seq, "Alignment.txt"), "%s/outputs/%s"%(outpath_this_seq, "tableOut.txt"), "%s/outputs/%s"%(outpath_this_seq, "fullOut.txt") ] for f in flist: if os.path.exists(f): try: os.remove(f) except Exception as e: msg = "Failed to delete the file %s with message \"%s\""%(f, str(e)) webcom.loginfo(msg, runjob_errfile) elif name_software in ["subcons", "docker_subcons"]: if not 'isKeepTempFile' in query_para or query_para['isKeepTempFile'] == False: temp_result_folder = "%s/tmp"%(outpath_this_seq) if os.path.exists(temp_result_folder): try: shutil.rmtree(temp_result_folder) except Exception as e: msg = "Failed to delete the folder %s with message \"%s\""%( temp_result_folder, str(e)) webcom.loginfo(msg, runjob_errfile) #}}} def GetCommand(name_software, seqfile_this_seq, tmp_outpath_result, tmp_outpath_this_seq, query_para):#{{{ """Return the command for subprocess """ try: docker_tmp_outpath_result = os.sep + os.sep.join(tmp_outpath_result.split(os.sep)[tmp_outpath_result.split(os.sep).index("static"):]) docker_seqfile_this_seq = os.sep + os.sep.join(seqfile_this_seq.split(os.sep)[seqfile_this_seq.split(os.sep).index("static"):]) docker_tmp_outpath_this_seq = os.sep + os.sep.join(tmp_outpath_this_seq.split(os.sep)[tmp_outpath_this_seq.split(os.sep).index("static"):]) except: raise cmd = [] if name_software in ['dummy']: runscript = "%s/%s"%(rundir, "soft/dummyrun.sh") cmd = ["bash", runscript, seqfile_this_seq, tmp_outpath_this_seq] elif name_software in ['scampi2-single']: if not os.path.exists(tmp_outpath_this_seq): os.makedirs(tmp_outpath_this_seq) runscript = "%s/%s"%(rundir, "soft/scampi2/bin/scampi/SCAMPI_run.pl") outtopfile = "%s/query.top"%(tmp_outpath_this_seq) cmd = [runscript, seqfile_this_seq, outtopfile] elif name_software in ['scampi2-msa']: if not os.path.exists(tmp_outpath_this_seq): os.makedirs(tmp_outpath_this_seq) runscript = "%s/%s"%(rundir, "soft/scampi2/bin/scampi-msa/run_SCAMPI_multi.pl") outtopfile = "%s/query.top"%(tmp_outpath_this_seq) blastdir = "%s/%s"%(rundir, "soft/blast/blast-2.2.26") os.environ['BLASTMAT'] = "%s/data"%(blastdir) os.environ['BLASTBIN'] = "%s/bin"%(blastdir) os.environ['BLASTDB'] = "%s/%s"%(rundir, "soft/blastdb") blastdb = "%s/%s"%(os.environ['BLASTDB'], "uniref90.fasta" ) cmd = [runscript, seqfile_this_seq, outtopfile, blastdir, blastdb] elif name_software in ['topcons2']: runscript = "%s/%s"%(rundir, "soft/topcons2_webserver/workflow/pfam_workflow.py") blastdir = "%s/%s"%(rundir, "soft/blast/blast-2.2.26") os.environ['BLASTMAT'] = "%s/data"%(blastdir) os.environ['BLASTBIN'] = "%s/bin"%(blastdir) os.environ['BLASTDB'] = "%s/%s"%(rundir, "soft/blastdb") blastdb = "%s/%s"%(os.environ['BLASTDB'], "uniref90.fasta" ) cmd = ["python", runscript, seqfile_this_seq, tmp_outpath_result, blastdir, blastdb] elif name_software in ['docker_topcons2']: containerID = 'topcons2' apppath = '/app/topcons2' runscript = '%s/workflow/pfam_workflow.py'%(apppath) blastdir = "%s/%s"%(apppath, "tools/blast-2.2.26") blastdb = "%s/%s/%s"%(apppath, "database/blast", "uniref90.fasta" ) cmd = ["/usr/bin/docker", "exec", "--user", "user", containerID, "script", "/dev/null", "-c", "cd %s; export BLASTMAT=%s/data; export BLASTBIN=%s/bin; export BLASTDB=%s/database/blast; export HOME=/home/user; python %s %s %s %s %s"%( docker_tmp_outpath_result, blastdir, blastdir, apppath, runscript, docker_seqfile_this_seq, docker_tmp_outpath_result, blastdir, blastdb)] elif name_software in ['singularity_topcons2']: path_image = '/data/singularity_images/topcons2.img' apppath = '/app/topcons2' runscript = '%s/workflow/pfam_workflow.py'%(apppath) blastdir = "%s/%s"%(apppath, "tools/blast-2.2.26") blastdb = "%s/%s/%s"%(apppath, "database/blast", "uniref90.fasta" ) os.environ['BLASTMAT'] = "%s/data"%(blastdir) os.environ['BLASTBIN'] = "%s/bin"%(blastdir) os.environ['BLASTDB'] = "%s/%s"%(apppath, "database/blast") cmd = ["singularity", "exec", "-B", "%s:%s"%('/scratch', '/scratch'), "-B", "%s:%s"%('/data', '/data'), "-B", "%s:%s"%('%s/static'%(basedir), '/static'), path_image, "python", runscript, docker_seqfile_this_seq, docker_tmp_outpath_result, blastdir, blastdb] elif name_software in ['subcons']: runscript = "%s/%s"%(rundir, "soft/subcons/master_subcons.sh") cmd = ["bash", runscript, seqfile_this_seq, tmp_outpath_this_seq, "-verbose"] elif name_software in ['docker_subcons']: containerID = 'subcons' cmd = ["/usr/bin/docker", "exec", "--user", "user", containerID, "script", "/dev/null", "-c", "cd %s; export HOME=/home/user; /app/subcons/master_subcons.sh %s %s"%( docker_tmp_outpath_result, docker_seqfile_this_seq, docker_tmp_outpath_this_seq)] elif name_software in ['singularity_subcons']: path_image = '/data/singularity_images/subcons.img' apppath = '/app/subcons' runscript = '%s/master_subcons.sh'%(apppath) cmd = ["singularity", "exec", "-B", "%s:%s"%('/scratch', '/scratch'), "-B", "%s:%s"%('/data', '/data'), "-B", "%s:%s"%('%s/static'%(basedir), '/static'), path_image, runscript, docker_seqfile_this_seq, docker_tmp_outpath_result] elif name_software in ['docker_boctopus2']: containerID = 'boctopus2' cmd = ["/usr/bin/docker", "exec", "--user", "user", containerID, "script", "/dev/null", "-c", "cd %s; export HOME=/home/user; python /app/boctopus2/boctopus_main.py %s %s"%( docker_tmp_outpath_result, docker_seqfile_this_seq, docker_tmp_outpath_this_seq)] elif name_software in ['docker_pathopred']: if not os.path.exists(tmp_outpath_this_seq): os.makedirs(tmp_outpath_this_seq) variant_text = query_para['variants'] variant_file = "%s/variants.fa" % tmp_outpath_result myfunc.WriteFile(variant_text, variant_file) docker_variant_file = os.sep + os.sep.join(variant_file.split(os.sep)[variant_file.split(os.sep).index("static"):]) identifier_name = query_para['identifier_name'] containerID = 'pathopred' cmd = ["docker", "exec", "--user", "user", containerID, "script", "/dev/null", "-c", "cd %s; export HOME=/home/user; /app/pathopred/master_pathopred.sh %s %s %s %s"%( docker_tmp_outpath_result, docker_seqfile_this_seq, docker_variant_file, docker_tmp_outpath_this_seq, identifier_name)] elif name_software in ['docker_predzinc']: containerID = 'predzinc' cmd = ["/usr/bin/docker", "exec", "--user", "user", containerID, "script", "/dev/null", "-c", "cd %s; export HOME=/home/user; /app/predzinc/predzinc.sh --cpu 4 %s -outpath %s"%( docker_tmp_outpath_result, docker_seqfile_this_seq, docker_tmp_outpath_this_seq)] elif name_software in ['docker_frag1d']: containerID = 'frag1d' cmd = ["/usr/bin/docker", "exec", "--user", "user", containerID, "script", "/dev/null", "-c", "cd %s; export HOME=/home/user; /app/frag1d/frag1d.sh --cpu 4 %s -outpath %s"%( docker_tmp_outpath_result, docker_seqfile_this_seq, docker_tmp_outpath_this_seq)] elif name_software in ['prodres']:#{{{ runscript = "%s/%s"%(rundir, "soft/PRODRES/PRODRES/PRODRES.py") path_pfamscan = "%s/misc/PfamScan"%(webserver_root) path_pfamdatabase = "%s/soft/PRODRES/databases"%(rundir) path_pfamscanscript = "%s/pfam_scan.pl"%(path_pfamscan) blastdb = "%s/soft/PRODRES/databases/blastdb/uniref90.fasta"%(rundir) if 'PERL5LIB' not in os.environ: os.environ['PERL5LIB'] = "" os.environ['PERL5LIB'] = os.environ['PERL5LIB'] + ":" + path_pfamscan cmd = ["python", runscript, "--input", seqfile_this_seq, "--output", tmp_outpath_this_seq, "--pfam-dir", path_pfamdatabase, "--pfamscan-script", path_pfamscanscript, "--fallback-db-fasta", blastdb] if 'second_method' in query_para and query_para['second_method'] != "": cmd += ['--second-search', query_para['second_method']] if 'pfamscan_evalue' in query_para and query_para['pfamscan_evalue'] != "": cmd += ['--pfamscan_e-val', query_para['pfamscan_evalue']] elif ('pfamscan_bitscore' in query_para and query_para['pfamscan_bitscore'] != ""): cmd += ['--pfamscan_bitscore', query_para['pfamscan_bitscore']] if 'pfamscan_clanoverlap' in query_para: if query_para['pfamscan_clanoverlap'] == False: cmd += ['--pfamscan_clan-overlap', 'no'] else: cmd += ['--pfamscan_clan-overlap', 'yes'] if ('jackhmmer_iteration' in query_para and query_para['jackhmmer_iteration'] != ""): cmd += ['--jackhmmer_max_iter', query_para['jackhmmer_iteration']] if ('jackhmmer_threshold_type' in query_para and query_para['jackhmmer_threshold_type'] != ""): cmd += ['--jackhmmer-threshold-type', query_para['jackhmmer_threshold_type']] if 'jackhmmer_evalue' in query_para and query_para['jackhmmer_evalue'] != "": cmd += ['--jackhmmer_e-val', query_para['jackhmmer_evalue']] elif ('jackhmmer_bitscore' in query_para and query_para['jackhmmer_bitscore'] != ""): cmd += ['--jackhmmer_bit-score', query_para['jackhmmer_bitscore']] if ('psiblast_iteration' in query_para and query_para['psiblast_iteration'] != ""): cmd += ['--psiblast_iter', query_para['psiblast_iteration']] if 'psiblast_outfmt' in query_para and query_para['psiblast_outfmt'] != "": cmd += ['--psiblast_outfmt', query_para['psiblast_outfmt']] #}}} return cmd #}}} def RunJob_proq3(modelfile, targetseq, outpath, tmpdir, email, jobid, query_para, g_params):# {{{ all_begin_time = time.time() rootname = os.path.basename(os.path.splitext(modelfile)[0]) starttagfile = "%s/runjob.start"%(outpath) runjob_errfile = "%s/runjob.err"%(outpath) runjob_logfile = "%s/runjob.log"%(outpath) app_logfile = "%s/app.log"%(outpath) finishtagfile = "%s/runjob.finish"%(outpath) failtagfile = "%s/runjob.failed"%(outpath) rmsg = "" webcom.WriteDateTimeTagFile(starttagfile, runjob_logfile, runjob_errfile) try: method_quality = query_para['method_quality'] except KeyError: method_quality = 'sscore' try: isDeepLearning = query_para['isDeepLearning'] except KeyError: isDeepLearning = True if isDeepLearning: m_str = "proq3d" else: m_str = "proq3" try: name_software = query_para['name_software'] except KeyError: name_software = "" resultpathname = jobid outpath_result = "%s/%s"%(outpath, resultpathname) tmp_outpath_result = "%s/%s"%(tmpdir, resultpathname) zipfile = "%s.zip"%(resultpathname) zipfile_fullpath = "%s.zip"%(outpath_result) resultfile_text = "%s/%s"%(outpath_result, "query.proq3.txt") finished_model_file = "%s/finished_models.txt"%(outpath_result) for folder in [tmp_outpath_result]: if os.path.exists(folder): try: shutil.rmtree(folder) except Exception as e: msg = "Failed to delete folder %s with message %s"%(folder, str(e)) webcom.loginfo(msg, runjob_errfile) webcom.WriteDateTimeTagFile(failtagfile, runjob_logfile, runjob_errfile) return 1 try: os.makedirs(folder) except Exception as e: msg = "Failed to create folder %s with return message \"%s\""%(folder, str(e)) webcom.loginfo(msg, runjob_errfile) webcom.WriteDateTimeTagFile(failtagfile, runjob_logfile, runjob_errfile) return 1 tmp_outpath_this_model = "%s/%s"%(tmp_outpath_result, "model_%d"%(0)) outpath_this_model = "%s/%s"%(outpath_result, "model_%d"%(0)) # First try to retrieve the profile from archive isGetProfileSuccess = False# {{{ if 'url_profile' in query_para: # try to retrieve the profile url_profile = query_para['url_profile'] remote_id = os.path.splitext(os.path.basename(url_profile))[0] outfile_zip = "%s/%s.zip"%(tmp_outpath_result, remote_id) webcom.loginfo("Trying to retrieve profile from %s"%(url_profile), runjob_logfile) isRetrieveSuccess = False if myfunc.IsURLExist(url_profile,timeout=5): try: myfunc.urlretrieve (url_profile, outfile_zip, timeout=10) isRetrieveSuccess = True except Exception as e: msg = "Failed to retrieve profile from %s. Err = %s"%(url_profile, str(e)) webcom.loginfo(msg, runjob_errfile) pass if os.path.exists(outfile_zip) and isRetrieveSuccess: msg = "Retrieved profile from %s"%(url_profile) webcom.loginfo("Retrieved profile from %s"%(url_profile), runjob_logfile) cmd = ["unzip", outfile_zip, "-d", tmp_outpath_result] try: subprocess.check_output(cmd) try: os.rename("%s/%s"%(tmp_outpath_result, remote_id), "%s/profile_0"%(tmp_outpath_result)) isGetProfileSuccess = True try: os.remove(outfile_zip) except: pass except: pass except: pass # }}} tmp_seqfile = "%s/query.fasta"%(tmp_outpath_result) tmp_outpath_profile = "%s/profile_0"%(tmp_outpath_result) docker_tmp_seqfile = os.sep + os.sep.join(tmp_seqfile.split(os.sep)[tmp_seqfile.split(os.sep).index("static"):]) docker_modelfile= os.sep + os.sep.join(modelfile.split(os.sep)[modelfile.split(os.sep).index("static"):]) docker_tmp_outpath_profile = os.sep + os.sep.join(tmp_outpath_profile.split(os.sep)[tmp_outpath_profile.split(os.sep).index("static"):]) docker_tmp_outpath_this_model = os.sep + os.sep.join(tmp_outpath_this_model.split(os.sep)[tmp_outpath_this_model.split(os.sep).index("static"):]) docker_tmp_outpath_result = os.sep + os.sep.join(tmp_outpath_result.split(os.sep)[tmp_outpath_result.split(os.sep).index("static"):]) timefile = "%s/time.txt"%(tmp_outpath_result) runtime_in_sec_profile = -1.0 runtime_in_sec_model = -1.0 if name_software in ['docker_proq3']: myfunc.WriteFile(">query\n%s\n"%(targetseq), tmp_seqfile) containerID = 'proq3' if not isGetProfileSuccess: # try to generate profile cmd = ["/usr/bin/docker", "exec", "--user", "user", containerID, "script", "/dev/null", "-c", "cd %s; export HOME=/home/user; /app/proq3/run_proq3.sh -fasta %s -outpath %s -only-build-profile"%( docker_tmp_outpath_result, docker_tmp_seqfile, docker_tmp_outpath_profile)] (t_success, runtime_in_sec) = webcom.RunCmd(cmd, runjob_logfile, runjob_errfile, verbose=True) myfunc.WriteFile("%s;%f\n"%("profile_0",runtime_in_sec), timefile, "a", True) runtime_in_sec_profile = runtime_in_sec # then run with the pre-created profile proq3opt = webcom.GetProQ3Option(query_para) cmd = ["/usr/bin/docker", "exec", "--user", "user", containerID, "script", "/dev/null", "-c", "cd %s; export HOME=/home/user; /app/proq3/run_proq3.sh --profile %s %s -outpath %s -verbose %s"%( docker_tmp_outpath_result, "%s/query.fasta"%(docker_tmp_outpath_profile), docker_modelfile, docker_tmp_outpath_this_model, " ".join(proq3opt))] (t_success, runtime_in_sec) = webcom.RunCmd(cmd, runjob_logfile, runjob_errfile, verbose=True) webcom.loginfo("cmdline: %s"%(" ".join(cmd)), runjob_logfile) myfunc.WriteFile("%s;%f\n"%("model_0",runtime_in_sec), timefile, "a", True) runtime_in_sec_model = runtime_in_sec if os.path.exists(tmp_outpath_result): cmd = ["mv","-f", tmp_outpath_result, outpath_result] (isCmdSuccess, t_runtime) = webcom.RunCmd(cmd, runjob_logfile, runjob_errfile, True) # copy time.txt to within the model folder try: shutil.copyfile("%s/time.txt"%(outpath_result), "%s/model_0/time.txt"%(outpath_result)) except Exception as e: webcom.loginfo("Copy time.txt failed with errmsg=%s"%(str(e)), runjob_errfile) CleanResult(name_software, query_para, outpath_result, runjob_logfile, runjob_errfile) if isCmdSuccess: globalscorefile = "%s/%s.%s.%s.global"%(outpath_this_model, "query.pdb", m_str, method_quality) (globalscore, itemList) = webcom.ReadProQ3GlobalScore(globalscorefile) modelseqfile = "%s/%s.fasta"%(outpath_this_model, "query.pdb") modellength = myfunc.GetSingleFastaLength(modelseqfile) modelinfo = ["model_0", str(modellength), str(runtime_in_sec_model)] if globalscore: for i in range(len(itemList)): modelinfo.append(str(globalscore[itemList[i]])) myfunc.WriteFile("\t".join(modelinfo)+"\n", finished_model_file, "a") modelFileList = ["%s/%s"%(outpath_this_model, "query.pdb")] webcom.WriteProQ3TextResultFile(resultfile_text, query_para, modelFileList, runtime_in_sec_model, g_params['base_www_url'], proq3opt, statfile="") # make the zip file for all result os.chdir(outpath) cmd = ["zip", "-rq", zipfile, resultpathname] webcom.RunCmd(cmd, runjob_logfile, runjob_errfile) webcom.WriteDateTimeTagFile(finishtagfile, runjob_logfile, runjob_errfile) isSuccess = False if (os.path.exists(finishtagfile) and os.path.exists(zipfile_fullpath)): isSuccess = True else: isSuccess = False webcom.WriteDateTimeTagFile(failtagfile, runjob_logfile, runjob_errfile) if os.path.exists(runjob_errfile) and os.stat(runjob_errfile).st_size > 0: return 1 else: # no error, delete the tmpdir try: webcom.loginfo("shutil.rmtree(%s)"%(tmpdir), runjob_logfile) shutil.rmtree(tmpdir) return 0 except Exception as e: msg = "Failed to delete tmpdir %s with message \"%s\""%(tmpdir, str(e)) webcom.loginfo(msg, runjob_errfile) return 1 # }}} def RunJob(infile, outpath, tmpdir, email, jobid, query_para, g_params):#{{{ all_begin_time = time.time() rootname = os.path.basename(os.path.splitext(infile)[0]) starttagfile = "%s/runjob.start"%(outpath) runjob_errfile = "%s/runjob.err"%(outpath) runjob_logfile = "%s/runjob.log"%(outpath) app_logfile = "%s/app.log"%(outpath) finishtagfile = "%s/runjob.finish"%(outpath) failtagfile = "%s/runjob.failed"%(outpath) webcom.WriteDateTimeTagFile(starttagfile, runjob_logfile, runjob_errfile) rmsg = "" try: name_software = query_para['name_software'] except KeyError: name_software = "" resultpathname = jobid outpath_result = "%s/%s"%(outpath, resultpathname) tmp_outpath_result = "%s/%s"%(tmpdir, resultpathname) zipfile = "%s.zip"%(resultpathname) zipfile_fullpath = "%s.zip"%(outpath_result) resultfile_text = "%s/%s"%(outpath_result, "query.result.txt") finished_seq_file = "%s/finished_seqs.txt"%(outpath_result) for folder in [outpath_result, tmp_outpath_result]: if os.path.exists(folder): try: shutil.rmtree(folder) except Exception as e: msg = "Failed to delete folder %s with message %s"%(folder, str(e)) webcom.loginfo(msg, runjob_errfile) webcom.WriteDateTimeTagFile(failtagfile, runjob_logfile, runjob_errfile) return 1 try: os.makedirs(folder) except Exception as e: msg = "Failed to create folder %s with message %s"%(folder, str(e)) webcom.loginfo(msg, runjob_errfile) webcom.WriteDateTimeTagFile(failtagfile, runjob_logfile, runjob_errfile) return 1 try: open(finished_seq_file, 'w').close() except: pass (seqIDList , seqAnnoList, seqList) = myfunc.ReadFasta(infile) for ii in range(len(seqIDList)): origIndex = ii seq = seqList[ii] seqid = seqIDList[ii] description = seqAnnoList[ii] subfoldername_this_seq = "seq_%d"%(origIndex) outpath_this_seq = "%s/%s"%(outpath_result, subfoldername_this_seq) tmp_outpath_this_seq = "%s/%s"%(tmp_outpath_result, "seq_%d"%(0)) if os.path.exists(tmp_outpath_this_seq): try: shutil.rmtree(tmp_outpath_this_seq) except OSError: pass seqfile_this_seq = "%s/%s"%(tmp_outpath_result, "query_%d.fa"%(origIndex)) seqcontent = ">query_%d\n%s\n"%(origIndex, seq) myfunc.WriteFile(seqcontent, seqfile_this_seq, "w") if not os.path.exists(seqfile_this_seq): msg = "Failed to generate seq index %d"%(origIndex) webcom.loginfo(msg, runjob_errfile) continue cmd = GetCommand(name_software, seqfile_this_seq, tmp_outpath_result, tmp_outpath_this_seq, query_para) if len(cmd) < 1: msg = "empty cmd for name_software = %s"%(name_software) webcom.loginfo(msg, runjob_errfile) pass (t_success, runtime_in_sec) = webcom.RunCmd(cmd, runjob_logfile, runjob_errfile, verbose=True) aaseqfile = "%s/seq.fa"%(tmp_outpath_this_seq) if not os.path.exists(aaseqfile): seqcontent = ">%s\n%s\n"%(description, seq) myfunc.WriteFile(seqcontent, aaseqfile, "w") timefile = "%s/time.txt"%(tmp_outpath_this_seq) if not os.path.exists(timefile): myfunc.WriteFile("%s;%f\n"%(seqid,runtime_in_sec), timefile, "w") if os.path.exists(tmp_outpath_this_seq): fromdir = tmp_outpath_this_seq if name_software in ["prodres", "docker_prodres", "singularity_prodres"]: fromdir = fromdir + os.sep + "query_0" # for prodres, also copy the aaseqfile and timefile to the # fromdir try: shutil.copy(aaseqfile, fromdir) shutil.copy(timefile, fromdir) except Exception as e: msg = "failed to copy aaseqfile or timefile to the folder %s"%(fromdir) webcom.loginfo(msg, runjob_errfile) pass cmd = ["mv","-f", fromdir, outpath_this_seq] (isCmdSuccess, t_runtime) = webcom.RunCmd(cmd, runjob_logfile, runjob_errfile, True) CleanResult(name_software, query_para, outpath_this_seq, runjob_logfile, runjob_errfile) if isCmdSuccess: runtime = runtime_in_sec #in seconds timefile = "%s/time.txt"%(outpath_this_seq) if os.path.exists(timefile): content = myfunc.ReadFile(timefile).split("\n")[0] strs = content.split(";") try: runtime = "%.1f"%(float(strs[1])) except: pass extItem1 = None extItem2 = None info_finish = [ "seq_%d"%origIndex, str(len(seq)), str(extItem1), str(extItem2), "newrun", str(runtime), description] myfunc.WriteFile("\t".join(info_finish)+"\n", finished_seq_file, "a", isFlush=True) # now write the text output for this seq info_this_seq = "%s\t%d\t%s\t%s"%("seq_%d"%origIndex, len(seq), description, seq) resultfile_text_this_seq = "%s/%s"%(outpath_this_seq, "query.result.txt") webcom.loginfo("Write resultfile_text %s"%(resultfile_text_this_seq), runjob_logfile) webcom.WriteTextResultFile(name_software, resultfile_text_this_seq, outpath_result, [info_this_seq], runtime_in_sec, g_params['base_www_url']) all_end_time = time.time() all_runtime_in_sec = all_end_time - all_begin_time # make the zip file for all result statfile = "%s/%s"%(outpath_result, "stat.txt") os.chdir(outpath) cmd = ["zip", "-rq", zipfile, resultpathname] webcom.RunCmd(cmd, runjob_logfile, runjob_errfile) webcom.WriteDateTimeTagFile(finishtagfile, runjob_logfile, runjob_errfile) isSuccess = False if (os.path.exists(finishtagfile) and os.path.exists(zipfile_fullpath)): isSuccess = True else: isSuccess = False webcom.WriteDateTimeTagFile(failtagfile, runjob_logfile, runjob_errfile) # try to delete the tmpdir if there is no error if os.path.exists(runjob_errfile) and os.stat(runjob_errfile).st_size > 0: return 1 else: try: webcom.loginfo("shutil.rmtree(%s)"%(tmpdir), runjob_logfile) shutil.rmtree(tmpdir) return 0 except Exception as e: msg = "Failed to delete tmpdir %s with message \"%s\""%(tmpdir, str(e)) webcom.loginfo(msg, runjob_errfile) return 1 #}}} def main(g_params):#{{{ argv = sys.argv numArgv = len(argv) if numArgv < 2: PrintHelp() return 1 outpath = "" infile = "" tmpdir = "" email = "" jobid = "" i = 1 isNonOptionArg=False while i < numArgv: if isNonOptionArg == True: infile = argv[i] isNonOptionArg = False i += 1 elif argv[i] == "--": isNonOptionArg = True i += 1 elif argv[i][0] == "-": if argv[i] in ["-h", "--help"]: PrintHelp() return 1 elif argv[i] in ["-outpath", "--outpath"]: (outpath, i) = myfunc.my_getopt_str(argv, i) elif argv[i] in ["-tmpdir", "--tmpdir"] : (tmpdir, i) = myfunc.my_getopt_str(argv, i) elif argv[i] in ["-jobid", "--jobid"] : (jobid, i) = myfunc.my_getopt_str(argv, i) elif argv[i] in ["-baseurl", "--baseurl"] : (g_params['base_www_url'], i) = myfunc.my_getopt_str(argv, i) elif argv[i] in ["-email", "--email"] : (email, i) = myfunc.my_getopt_str(argv, i) elif argv[i] in ["-q", "--q"]: g_params['isQuiet'] = True i += 1 else: print("Error! Wrong argument:", argv[i], file=sys.stderr) return 1 else: infile = argv[i] i += 1 if jobid == "": print("%s: jobid not set. exit"%(sys.argv[0]), file=sys.stderr) return 1 g_params['jobid'] = jobid # create a lock file in the resultpath when run_job.py is running for this # job, so that daemon will not run on this folder lockname = "runjob.lock" lock_file = "%s/%s/%s"%(path_result, jobid, lockname) g_params['lockfile'] = lock_file fp = open(lock_file, 'w') try: fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError: print("Another instance of %s is running"%(progname), file=sys.stderr) return 1 if myfunc.checkfile(infile, "infile") != 0: return 1 if outpath == "": print("outpath not set. exit", file=sys.stderr) return 1 elif not os.path.exists(outpath): try: subprocess.check_output(["mkdir", "-p", outpath]) except subprocess.CalledProcessError as e: print(e, file=sys.stderr) return 1 if tmpdir == "": print("tmpdir not set. exit", file=sys.stderr) return 1 elif not os.path.exists(tmpdir): try: subprocess.check_output(["mkdir", "-p", tmpdir]) except subprocess.CalledProcessError as e: print(e, file=sys.stderr) return 1 if os.path.exists(vip_email_file): g_params['vip_user_list'] = myfunc.ReadIDList(vip_email_file) query_parafile = "%s/query.para.txt"%(outpath) query_para = {} content = myfunc.ReadFile(query_parafile) if content != "": query_para = json.loads(content) try: name_software = query_para['name_software'] except KeyError: name_software = "" status = 0 if name_software in ["proq3", "docker_proq3", "singularity_proq3"]: # for proq3, model is provided in query_para # provided in the query_para runjob_errfile = "%s/runjob.err"%(outpath) runjob_logfile = "%s/runjob.log"%(outpath) modelfile = "%s/query.pdb"%(outpath) if 'pdb_model' in query_para: model = query_para['pdb_model'] myfunc.WriteFile(model, modelfile) elif 'url_pdb_model' in query_para: url_pdb_model = query_para['url_pdb_model'] webcom.loginfo("Trying to retrieve profile from %s"%(url_pdb_model), runjob_logfile) isRetrieveSuccess = False if myfunc.IsURLExist(url_pdb_model,timeout=5): try: myfunc.urlretrieve (url_pdb_model, modelfile, timeout=10) isRetrieveSuccess = True except Exception as e: msg = "Failed to retrieve modelfile from %s. Err = %s"%(url_pdb_model, e) webcom.loginfo(msg, runjob_logfile) return 1 else: webcom.loginfo("Neither pdb_model nor url_pdb_model are provided. Exit", gen_errfile) return 1 try: targetseq = query_para['targetseq'] except: seqList = myfunc.PDB2Seq(modelfile) if len(seqList) >= 1: targetseq = seqList[0] print("Run proq3") status = RunJob_proq3(modelfile, targetseq, outpath, tmpdir, email, jobid, query_para, g_params) else: status = RunJob(infile, outpath, tmpdir, email, jobid, query_para, g_params) return status #}}} def InitGlobalParameter():#{{{ g_params = {} g_params['isQuiet'] = True g_params['base_www_url'] = "" g_params['jobid'] = "" g_params['lockfile'] = "" g_params['vip_user_list'] = [] return g_params #}}} if __name__ == '__main__' : g_params = InitGlobalParameter() status = main(g_params) if os.path.exists(g_params['lockfile']): try: os.remove(g_params['lockfile']) except: myfunc.WriteFile("Failed to delete lockfile %s\n"%(g_params['lockfile']), gen_errfile, "a", True) sys.exit(status)
mit
OysteinAmundsen/gymsystems
server/src/api/graph/user/dto/login-user.dto.ts
322
import { ApiModelProperty } from '@nestjs/swagger'; export class LoginUserDto { @ApiModelProperty({ description: `The username as previously registerred in the system` }) username: string; @ApiModelProperty({ description: `The unencrypted password as previously registerred in the system` }) password: string; }
mit
techdev-solutions/trackr-frontend
test/backendMock.js
12757
define(['fixtures'], function(fixtures) { 'use strict'; return function($httpBackend) { $httpBackend.when('GET', 'api/principal').respond({ id: 0, email: 'admin@techdev.de', enabled: true, authorities: [ {authority: 'ROLE_ADMIN'} ] }); /** * Mocks a request to an entity root that can contain parameters like page, sort, size (they will be ignored though). * Responds with data from the fixtures. * @param url The URL to mock, like '/api/companies'. */ function mockRoot(url) { //base $httpBackend.whenGET(url).respond(fixtures[url]); //with query parameters var pattern = new RegExp('^' + url + '\\?.*$'); $httpBackend.whenGET(pattern).respond(fixtures[url]); } /** * Mocks a POST to an entity root, just answers with 201 and the data inserted. * @param url The url on which to mock POST. */ function mockPost(url) { $httpBackend.whenPOST(url).respond(function(method, url, data) { return [201, data]; }); } /** * Mock patching a single entitiy * @param url The url to mock (e.g. 'api/employees' */ function mockPatch(url) { var pattern = new RegExp('^' + url + '/\\d+$'); $httpBackend.whenPATCH(pattern).respond(function(method, url, data) { return [200, data]; }); } //##### -- ADDRESSES mockPatch('api/addresses'); $httpBackend.whenPOST('api/addresses') .respond(function() { var address = { _links: { self: { href: '' } } }; return [200, address]; }); $httpBackend.whenPUT(/^api\/addresses\/\d+$/).respond(function(method, url, data) { return [201, data]; }); //#### -- BILLABLE TIMES mockPost('api/billableTimes'); $httpBackend.whenGET(/^api\/billableTimes\/findEmployeeMappingByProjectAndDateBetween\?.*/) .respond(fixtures['api/billableTimes']); $httpBackend.whenGET(/^api\/billableTimes\/search\/findByDateBetween\?end=\d+&projection=withProject&start=\d+/) .respond(function() { var data = fixtures['api/billableTimes']; data._embedded.billableTimes.forEach(function(billableTime) { billableTime.project = fixtures['api/projects']._embedded.projects[0]; }); return [200, data]; }); //#### -- COMPANIES mockRoot('api/companies'); mockPost('api/companies'); mockPatch('api/companies'); $httpBackend.when('GET', /^api\/companies\/[\d]+$/) .respond(fixtures['api/companies']._embedded.companies[0]); $httpBackend.when('GET', /^api\/companies\/[\d]+\/projects/) .respond(fixtures['api/projects']); $httpBackend.whenGET(/^api\/companies\/search\/findByCompanyId\?companyId=\w+$/) .respond(fixtures['api/companies']); $httpBackend.whenGET(/^api\/companies\/search\/findByCompanyId\?companyId=\w+&projection=\w+$/) .respond(function() { var response = fixtures['api/companies']._embedded.companies[0]; response.address = fixtures['api/addresses']._embedded.addresses[0]; response.contactPersons = fixtures['api/contactPersons']._embedded.contactPersons; return [200, response]; }); $httpBackend.whenGET(/^api\/companies\/search\/findByNameLikeIgnoreCaseOrderByNameAsc\?.*/) .respond(fixtures['api/companies']); //#### -- CONTACT PERSONS mockRoot('api/contactPersons'); mockPost('api/contactPersons'); $httpBackend.whenGET(/^api\/contactPersons\/[\d]+$/).respond(fixtures['api/contactPersons']._embedded.contactPersons[0]); $httpBackend.whenDELETE(/^api\/contactPersons\/\d+/).respond([204]); //#### -- EMPLOYEES mockRoot('api/employees'); mockPatch('api/employees'); mockPost('api/employees'); $httpBackend.whenGET(/^api\/employees\/\d+$/).respond(fixtures['api/employees']._embedded.employees[0]); $httpBackend.whenGET(/^api\/employees\/\d+\?projection=withAddress$/).respond(function() { var employee = fixtures['api/employees']._embedded.employees[0]; employee.address = fixtures['api/addresses']._embedded.addresses[0]; return [200, employee]; }); $httpBackend.whenGET(/^api\/employees\/\d+\/self$/).respond(fixtures['api/employees']._embedded.employees[0]); $httpBackend.whenPUT(/^api\/employees\/\d+\/self$/).respond(function(method, url, data) { return [200, data]; }); $httpBackend.whenPUT(/^api\/employees\/\d+\/address$/).respond([204]); //#### -- FEDERAL STATES mockRoot('api/federalStates'); //#### -- INVOICES mockRoot('api/invoices'); mockPost('api/invoices'); $httpBackend.whenGET(/^api\/invoices\/search\/findByInvoiceState\?page=\d+&projection=\w+&size=\d+&sort=creationDate&state=\w+/) .respond(fixtures['api/invoices']); $httpBackend.whenGET(/^api\/invoices\/search\/findByIdentifierLikeIgnoreCaseAndInvoiceState\?identifier=%25\w+%25&page=\d+&projection=\w+&size=\d+&sort=creationDate&state=\w+/) .respond(fixtures['api/invoices']); $httpBackend.whenGET(/^api\/invoices\/search\/findByCreationDateBetween\?end=\d+&projection=withDebitor&start=\d+/) .respond(function() { //add a debitor var invoices = fixtures['api/invoices']; invoices._embedded.invoices.forEach(function(invoice) { invoice.debitor = fixtures['api/companies']._embedded.companies[0]; }); return [200, invoices]; }); $httpBackend.whenPOST(/^api\/invoices\/\d+\/markPaid$/) .respond([204, 'Ok.']); //#### -- PROJECTS mockRoot('api/projects'); mockPost('api/projects'); $httpBackend.whenGET(/^api\/projects\/\d+$/) .respond(fixtures['api/projects']._embedded.projects[0]); $httpBackend.whenGET(/api\/projects\/search\/findByNameLikeIgnoreCaseOrIdentifierLikeIgnoreCaseOrderByNameAsc\?.*/) .respond(fixtures['api/projects']); $httpBackend.whenGET(/api\/projects\/search\/findByIdentifier\?.*/) .respond(fixtures['api/projects']); //#### -- REDUCED EMPLOYEES / ADDRESSBOOK $httpBackend.whenGET(/^api\/address_book\?page=\d+&size=\d+/) .respond(fixtures['api/address_book']._embedded.reducedEmployees); //#### -- TRAVEL EXPENSES mockPost('api/travelExpenses'); mockPatch('api/travelExpenses'); $httpBackend.whenDELETE(/^api\/travelExpenses\/\d+/).respond([204]); //#### -- TRAVEL EXPENSE REPORTS mockPost('api/travelExpenseReports'); $httpBackend.whenGET(/^api\/travelExpenseReports\/\d+\?projection=\w+/) .respond(function() { var fixture = fixtures['api/travelExpenseReports']._embedded.travelExpenseReports[0]; fixture.expenses = fixtures['api/travelExpenses']._embedded.travelExpenses; return [200, fixture]; }); $httpBackend.whenGET(/^api\/travelExpenseReports\/\d+\/comments\?projection=\w+/) .respond(function() { var fixture = fixtures['api/travelExpenseReportComments']._embedded.travelExpenseReportComments; fixture.forEach(function(comment) { comment.employee = fixtures['api/employees']._embedded.employees[0]; }); return [200, fixture]; }); $httpBackend.whenGET(/^api\/travelExpenseReports\/search\/findByEmployeeAndStatusOrderByStatusAsc\?employee=%2Femployees%2F\d+&page=\d+&projection=\w+&size=\d+&sort=\w*&status=\w+$/) .respond(fixtures['api/travelExpenseReports']); $httpBackend.whenGET(/^api\/travelExpenseReports\/search\/findByStatus\?page=\d+&projection=\w+&size=\d+&sort=[\w,\.]*&status=\w+$/) .respond(fixtures['api/travelExpenseReports']); $httpBackend.whenGET(/^api\/travelExpenseReports\/search\/findBySubmissionDateBetween\?end=\d+&projection=withEmployeeAndExpenses&start=\d+$/) .respond(function() { var data = fixtures['api/travelExpenseReports']; data._embedded.travelExpenseReports.forEach(function(report) { report.employee = fixtures['api/employees']._embedded.employees[0]; report.expenses = fixtures['api/travelExpenses']._embedded.expenses; }); return [200, data]; }); $httpBackend.whenPUT(/^api\/travelExpenseReports\/\d+\/submit/) .respond([204]); $httpBackend.whenPUT(/^api\/travelExpenseReports\/\d+\/approve/) .respond([204]); $httpBackend.whenPUT(/^api\/travelExpenseReports\/\d+\/reject/) .respond([204]); //#### -- TRANSLATIONS $httpBackend.whenPUT(/^api\/translations\?.*/).respond({}); $httpBackend.whenGET(/^api\/translations\?.*/).respond({}); //#### -- VACATION REQUESTS mockPost('api/vacationRequests'); $httpBackend.whenGET(/^api\/vacationRequests\/search\/findByEmployeeOrderByStartDateAsc\?.*/) .respond(fixtures['api/vacationRequests']); $httpBackend.whenGET(/^api\/vacationRequests\/search\/findByStatusOrderBySubmissionTimeAsc\?.*/) .respond(fixtures['api/vacationRequests']); $httpBackend.whenGET(/^api\/vacationRequests\/daysPerEmployeeBetween\?end=\d+&projection=withEmployeeAndApprover&start=\d+$/) .respond(function() { var data = fixtures['api/vacationRequests']; data._embedded.vacationRequests.forEach(function(vacationRequest) { var employee = fixtures['api/employees']._embedded.employees[0]; vacationRequest.employee = employee; vacationRequest.approver = employee; }); return [200, data]; }); $httpBackend.whenDELETE(/^api\/vacationRequests\/\d+/).respond([204]); $httpBackend.whenPUT(/^api\/vacationRequests\/\d+\/approve/).respond(function() { return [200, { approver: 'api/employees/0', status: 'APPROVED', approvalDate: new Date() }]; }); $httpBackend.whenPUT(/^api\/vacationRequests\/\d+\/reject/).respond(function() { return [200, { approver: 'api/employees/0', status: 'REJECTED', approvalDate: new Date() }]; }); //#### -- WORK TIMES mockPost('api/workTimes'); $httpBackend.whenGET(/api\/workTimes\/findEmployeeMappingByProjectAndDateBetween\?.*/) .respond(fixtures['api/workTimes/findEmployeeMappingByProjectAndDateBetween']); $httpBackend.whenGET(/api\/workTimes\/search\/findByEmployeeAndDateBetweenOrderByDateAscStartTimeAsc\?.*/) .respond(fixtures['api/workTimes']); $httpBackend.whenGET(/api\/workTimes\/\d+\/project/).respond(fixtures['api/projects']._embedded.projects[0]); $httpBackend.whenGET(/^api\/workTimes\/search\/findByDateBetween\?end=\d+&projection=withProject&start=\d+/) .respond(function() { var data = fixtures['api/workTimes']; data._embedded.workTimes.forEach(function(workTime) { workTime.project = fixtures['api/projects']._embedded.projects[0]; }); return [200, data]; }); $httpBackend.whenGET(/^api\/workTimes\/search\/findByDateBetween\?end=\d+&projection=withEmployee&start=\d+$/) .respond(function() { var data = fixtures['api/workTimes']; data._embedded.workTimes.forEach(function(workTime) { workTime.employee = fixtures['api/employees']._embedded.employees[0]; }); return [200, data]; }); /* ############################ TEMPLATES ########################### */ /* Just return an empty template. */ $httpBackend.whenGET(/^.*\.tpl\.html$/).respond( [200, '<div></div>'] ); }; });
mit
desjarlais/restfuloutlook
RESTfulOutlook/Forms/CategoriesForm.Designer.cs
2392
namespace RESTfulOutlook.Forms { partial class CategoriesForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(CategoriesForm)); this.lstCategories = new System.Windows.Forms.ListBox(); this.SuspendLayout(); // // lstCategories // this.lstCategories.FormattingEnabled = true; this.lstCategories.Location = new System.Drawing.Point(12, 12); this.lstCategories.Name = "lstCategories"; this.lstCategories.Size = new System.Drawing.Size(260, 238); this.lstCategories.TabIndex = 0; // // CategoriesForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(284, 261); this.Controls.Add(this.lstCategories); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.Name = "CategoriesForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Items List"; this.ResumeLayout(false); } #endregion private System.Windows.Forms.ListBox lstCategories; } }
mit
giannispan/cms-laravel-angular
app/Http/Controllers/Auth/AuthController.php
1813
<?php namespace App\Http\Controllers\Auth; use App\User; use Validator; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\ThrottlesLogins; use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers; class AuthController extends Controller { /* |-------------------------------------------------------------------------- | Registration & Login Controller |-------------------------------------------------------------------------- | | This controller handles the registration of new users, as well as the | authentication of existing users. By default, this controller uses | a simple trait to add these behaviors. Why don't you explore it? | */ use AuthenticatesAndRegistersUsers, ThrottlesLogins; protected $redirectTo = '/pages'; /** * Create a new authentication controller instance. * * @return void */ public function __construct() { $this->middleware('guest', ['except' => 'logout']); } /** * Get a validator for an incoming registration request. * * @param array $data * @return \Illuminate\Contracts\Validation\Validator */ protected function validator(array $data) { return Validator::make($data, [ 'name' => 'required|max:255', 'email' => 'required|email|max:255|unique:users', 'password' => 'required|confirmed|min:6', ]); } /** * Create a new user instance after a valid registration. * * @param array $data * @return User */ protected function create(array $data) { return User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => bcrypt($data['password']), ]); } }
mit
chentr/silverplate
silverplate/urls.py
822
"""silverplate URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^crawl/', include('crawler.urls')), ]
mit
rustyhann/examples
csharp/FtpSync/SqlServerMigrations/Migrations/20160506100955_CREATE_CSP_SYNC_TRANSACTIONS.cs
384
using System; using FluentMigrator; namespace SqlServerMigrations { [Migration(20160506100955)] public class CREATE_CSP_SYNC_TRANSACTIONS : Migration { public override void Up() { Execute.EmbeddedScript("20160506100955_CREATE_CSP_SYNC_TRANSACTIONS.sql"); } public override void Down() { } } }
mit
irfanHasbek/mkb-andios-backend
back-end/Routers/HesapRouter.js
4525
var express = require('express'); var fs = require('fs') var KullaniciModeli = require('../Modeller/KullaniciModeli') var VersionModeli = require('../Modeller/VersiyonModeli') var KurumsalIzinler = require('../Modeller/KurumsalIzinlerModeli') var HakkimizdaModeli = require('../Modeller/HakkimizdaModeli') var IletisimModeli = require('../Modeller/IletisimModeli') function HesapRouter(){ var router = express.Router(); router.post('/giris', function(req, res){ var kullaniciBilgileri = req.body; KullaniciModeli.findOne({kullaniciKodu : kullaniciBilgileri.kullaniciKodu, sifre : kullaniciBilgileri.sifre}, function(kullaniciHata, kullanici){ if (kullanici) { req.session.kullanici = kullanici; req.session.giris = true; req.session.mesaj = "Giris Basarili !"; res.redirect('/sayfalar/anasayfa'); }else { req.session.kullanici = null; req.session.giris = false; req.session.mesaj = "Giris Basarisiz ! Lütfen bilgilerinizi kontrol edin. !"; res.redirect('/sayfalar/giris'); } }); }); router.get('/cikis', function(req, res){ req.session.kullanici = null; req.session.giris = false; req.session.mesaj = ""; res.redirect('/sayfalar/giris'); }); router.post('/kaydol', function(req, res){ var kullaniciBilgileri = req.body; var yeniKullanici = new KullaniciModeli(kullaniciBilgileri); yeniKullanici.save(function(kullaniciHata, kullanici){ //console.log(kullanici); if (kullanici) { var yeniVersiyon = new VersionModeli({mobilVersiyon : "0", kullaniciKodu : kullanici.kullaniciKodu}); yeniVersiyon.save(function (versiyonHata, versiyon) { if (versiyonHata) { hataVer(req, res) } if (versiyon) { var yeniKurumsalIzin = new KurumsalIzinler({kullaniciKodu : kullanici.kullaniciKodu}) yeniKurumsalIzin.save(function (izinHata, izinler) { if (izinHata) { hataVer(req, res) } var _hakkimizda = new HakkimizdaModeli({kullaniciKodu : kullanici.kullaniciKodu, vizyon : "", misyon : "", kalitePolitikasi : ""}) _hakkimizda.save( function (hataHakkimizda, hakkimizda) { if (hataHakkimizda) { hataVer(req, res) } var _iletisim = new IletisimModeli({kullaniciKodu : kullanici.kullaniciKodu, adres :"", tel1 : "", tel2 : "", tel3 : "", latitude : "", longtitude : ""}) _iletisim.save( function (hataIletisim, iletisim) { if (hataIletisim) { hataVer(req, res) } req.session.kullanici = kullanici; req.session.giris = true; req.session.mesaj = "Giris Basarili !"; var dir = './front-end/public/yuklemeler/' + kullanici._id; if (!fs.existsSync(dir)){ fs.mkdirSync(dir); var dirDosya = './front-end/public/yuklemeler/' + kullanici._id + "/dosyalar"; var dirMedya = './front-end/public/yuklemeler/' + kullanici._id + "/medyalar"; var dirCertificate = './front-end/public/yuklemeler/' + kullanici._id + "/sertifikalar"; if (!fs.existsSync(dirDosya) && !fs.existsSync(dirMedya)) { fs.mkdirSync(dirDosya); fs.mkdirSync(dirMedya); fs.mkdirSync(dirCertificate); } res.redirect('/sayfalar/anasayfa'); }else { hataVer(req, res) } }) }) }) }else { hataVer(req, res) } }) }else { hataVer(req, res, kullaniciHata) } }); }); return router; } function hataVer (req, res, hata) { req.session.kullanici = null; req.session.giris = false; req.session.mesaj = "Giris Basarisiz ! Lütfen servis saglayicinizla iletisime gecin !"; console.log("Hata : " + hata); res.redirect('/sayfalar/giris'); } module.exports = HesapRouter;
mit
msburgess3200/PERP
gamemodes/perp/gamemode/vgui/phone.lua
15329
local PANEL = {}; surface.CreateFont("PhoneFont", { font="Tahoma", size=ScreenScale(7), weight=1000, antialias=true }) surface.CreateFont("PhoneFontSmall", { font="Tahoma", size=ScreenScale(6), weight=1000, antialias=true }) local phone_text_r = CreateClientConVar("perp2_phone_text_r", "0", true, false); local phone_text_g = CreateClientConVar("perp2_phone_text_g", "0", true, false); local phone_text_b = CreateClientConVar("perp2_phone_text_b", "0", true, false); local phone_highlight_r = CreateClientConVar("perp2_phone_highlight_r", "0", true, false); local phone_highlight_g = CreateClientConVar("perp2_phone_highlight_g", "0", true, false); local phone_highlight_b = CreateClientConVar("perp2_phone_highlight_b", "255", true, false); local phone_background_r = CreateClientConVar("perp2_phone_background_r", "255", true, false); local phone_background_g = CreateClientConVar("perp2_phone_background_g", "255", true, false); local phone_background_b = CreateClientConVar("perp2_phone_background_b", "255", true, false); local phoneMaterial = surface.GetTextureID("PERP2/cell_phone"); local phoneIcon = surface.GetTextureID("PERP2/phone_icon"); function PANEL:Init ( ) self.curSpot = 1; self.startPos = 1; self.level = 1; self.lastScroll = 0; self:SetAlpha(0); self.SpotToRing = {} end function PANEL:PerformLayout ( ) local W = ScrW() * .15; local H = (W / 349) * 780; self:SetPos(ScrW() - W - 30, ScrH() - 1); self:SetSize(W, H); surface.SetFont("PhoneFontSmall"); self.smallX, self.smallY = surface.GetTextSize("Size"); end local slideTime = 0.25; local percentShown = .8; function PANEL:Paint ( ) if (!self.ShowingTime && !self.CurUp) then return; end local OX, OY = self:GetPos(); if (self.CurrentlyShowing) then if (self.ShowingTime) then local percOpen = math.Clamp((CurTime() - self.ShowingTime) / slideTime, 0, 1); if (percOpen == 1) then self.ShowingTime = nil; end self:SetPos(OX, (ScrH() - 1) - (percOpen * self:GetTall() * percentShown)); end elseif (self.ShowingTime) then local percOpen = math.Clamp((self.ShowingTime - CurTime()) / slideTime, 0, 1); if (percOpen == 0) then self.ShowingTime = nil; self:SetAlpha(0); if (self.demoSound) then self.demoSound:Stop(); self.demoSound = nil; self.demoPlaying = nil; return; end end self:SetPos(OX, (ScrH() - 1) - (percOpen * self:GetTall() * percentShown)); end surface.SetDrawColor(255, 255, 255, 255); surface.SetTexture(phoneMaterial); surface.DrawTexturedRect(0, 0, self:GetWide(), self:GetTall()); // Screen Stuff local screenX = self:GetWide() * 0.14453125; local screenY = self:GetTall() * 0.19055944055944; local screenW = (self:GetWide() * 0.85546875) - screenX; local screenH = (self:GetTall() * 0.58391608391608) - screenY; local tColor = Color(math.Clamp(phone_text_r:GetInt(), 0, 255), math.Clamp(phone_text_g:GetInt(), 0, 255), math.Clamp(phone_text_b:GetInt(), 0, 255), 255); surface.SetDrawColor(math.Clamp(phone_background_r:GetInt(), 0, 255), math.Clamp(phone_background_g:GetInt(), 0, 255), math.Clamp(phone_background_b:GetInt(), 0, 255), 150); surface.DrawRect(screenX, screenY, screenW, screenH); if (GAMEMODE.Call_Time) then if (GAMEMODE.PhoneText == "Calling") then if (!self.ringing) then self.ringing = CreateSound(LocalPlayer(), Sound("PERP2.5/phone_ring.mp3")); end if (!self.lastRing || self.lastRing < CurTime()) then self.lastRing = CurTime() + SoundDuration("PERP2.5/phone_ring.mp3") + 1; self.ringing:Stop(); self.ringing:Play(); end elseif (self.ringing) then self.lastRing = nil; self.ringing:Stop(); self.ringing = nil; end draw.SimpleText(GAMEMODE.PhoneText or "#ERROR", "PhoneFontSmall", screenX + screenW * .5, screenY + self.smallY, tColor, 1, 1); draw.SimpleText(GAMEMODE.Call_Player or "#ERROR", "PhoneFontSmall", screenX + screenW * .5, screenY + self.smallY * 2, tColor, 1, 1); surface.SetDrawColor(255, 255, 255, 255); surface.SetTexture(phoneIcon); local size = screenW * .8; surface.DrawTexturedRect(screenX + screenW * .5 - size * .5, screenY + screenH * .5 - size * .5, size, size); local seconds = math.ceil(CurTime() - GAMEMODE.Call_Time); local minutes = math.floor(seconds / 60); local seconds = seconds - (minutes * 60); if (seconds < 10) then seconds = "0" .. seconds; end if (minutes < 10) then minutes = "0" .. minutes; end if (GAMEMODE.PhoneText == "Call From") then draw.SimpleText("Z To Answer", "PhoneFontSmall", screenX + screenW * .5, screenY + screenH - self.smallY * 1.5, tColor, 1, 1); else draw.SimpleText(minutes .. ":" .. seconds, "PhoneFontSmall", screenX + screenW * .5, screenY + screenH - self.smallY * 1.5, tColor, 1, 1); end if (!GAMEMODE.Call_Player) then GAMEMODE.Call_Time = nil; end return; elseif (self.ringing && self.lastRing) then self.lastRing = nil; self.ringing:Stop(); end self.toDisplayStuff = {}; if (self.level == 1) then table.insert(self.toDisplayStuff, {"Contacts", 2}); table.insert(self.toDisplayStuff, {"Settings", 3}); if (GAMEMODE.Options_EuroStuff:GetBool()) then table.insert(self.toDisplayStuff, {"999", 911}); else table.insert(self.toDisplayStuff, {"911", 911}); end elseif (self.level == 2) then for k, v in pairs(GAMEMODE.Buddies) do table.insert(self.toDisplayStuff, {v[1], v[2]}); end for k, v in pairs(self.toDisplayStuff) do for _, pl in pairs(player.GetAll()) do if (tostring(pl:UniqueID()) == tostring(v[2])) then v[1] = pl:GetRPName(); end end end for k, v in pairs(player.GetAll()) do if (v != LocalPlayer() && v:GetUMsgInt("org", 0) == LocalPlayer():GetUMsgInt("org", 0) && v:GetUMsgInt("org", 0) != 0) then local alreadyInList = false; for k, l in pairs(self.toDisplayStuff) do if (tostring(l[2]) == tostring(v:UniqueID())) then alreadyInList = true; end end if (!alreadyInList) then table.insert(self.toDisplayStuff, {v:GetRPName(), v:UniqueID()}); end end end elseif (self.level == 3) then table.insert(self.toDisplayStuff, {"Ringtones", 4}); if (GAMEMODE.Options_EuroStuff:GetBool()) then table.insert(self.toDisplayStuff, {"Backlight Colour", 5}); table.insert(self.toDisplayStuff, {"Highlight Colour", 6}); table.insert(self.toDisplayStuff, {"Text Colour", 7}); else table.insert(self.toDisplayStuff, {"Backlight Color", 5}); table.insert(self.toDisplayStuff, {"Highlight Color", 6}); table.insert(self.toDisplayStuff, {"Text Color", 7}); end elseif (self.level == 4) then local curSpot = 0 for k, v in pairs(GAMEMODE.Ringtones) do if (!v[3] || LocalPlayer()[v[3]](LocalPlayer())) then table.insert(self.toDisplayStuff, v); curSpot = curSpot + 1 self.SpotToRing[curSpot] = k end end // Check to see if we should play a demo. if (CurTime() - self.lastScroll > 1 && self.toDisplayStuff[self.curSpot] && (!self.demoPlaying || self.demoPlaying != self.curSpot)) then if (self.demoSound) then self.demoSound:Stop(); self.demoSound = nil; self.demoPlaying = nil; end self.demoSound = CreateSound(LocalPlayer(), Sound("PERP2.5/ringtones/" .. self.toDisplayStuff[self.curSpot][2])); self.demoSound:Play(); self.demoPlaying = self.curSpot; end else table.insert(self.toDisplayStuff, {"Black", Color(0, 0, 0, 255)}); table.insert(self.toDisplayStuff, {"White", Color(255, 255, 255, 255)}); table.insert(self.toDisplayStuff, {"Red", Color(255, 0, 0, 255)}); table.insert(self.toDisplayStuff, {"Blood Red", Color(150, 0, 0, 255)}); table.insert(self.toDisplayStuff, {"Green", Color(0, 255, 0, 255)}); table.insert(self.toDisplayStuff, {"Forest Green", Color(0, 150, 0, 255)}); table.insert(self.toDisplayStuff, {"Blue", Color(0, 0, 255, 255)}); table.insert(self.toDisplayStuff, {"Ocean Blue", Color(0, 0, 150, 255)}); table.insert(self.toDisplayStuff, {"Purple", Color(255, 0, 255, 255)}); table.insert(self.toDisplayStuff, {"Yellow", Color(255, 255, 0, 255)}); table.insert(self.toDisplayStuff, {"Orange", Color(255, 165, 0, 255)}); table.insert(self.toDisplayStuff, {"Teal", Color(0, 255, 255, 255)}); table.insert(self.toDisplayStuff, {"Pink", Color(255, 105, 180, 255)}); table.insert(self.toDisplayStuff, {"Brown", Color(150, 75, 0, 255)}); end if (self.curSpot < 1) then self.curSpot = #self.toDisplayStuff; self.startPos = math.Clamp(self.curSpot - 4, 1, #self.toDisplayStuff); elseif (self.curSpot > #self.toDisplayStuff) then self.curSpot = 1; self.startPos = 1; end local perArea = screenH * .2; local curArea = 0; if (self.level == 1) then local hours, mins = GAMEMODE.GetTime(); local text; if (GAMEMODE.Options_EuroStuff:GetBool()) then if (mins < 10) then mins = "0" .. mins; end text = hours .. ":" .. mins; else local a = "AM"; if (hours > 11) then a = "PM"; end if (hours > 12) then hours = hours - 12; elseif (hours == 0) then hours = 12; end if (mins < 10) then mins = "0" .. mins; end text = hours .. ":" .. mins .. " " .. a; end draw.SimpleText(text, "PhoneFontSmall", screenX + screenW * .5, screenY + self.smallY, tColor, 1, 1); screenY = screenY + self.smallY * 2; end for i = self.startPos, self.startPos + 4 do if (self.toDisplayStuff[i]) then local prefix = ""; if (self.level == 4 && self.SpotToRing[i] == LocalPlayer():GetUMsgInt("ringtone", 1)) then prefix = "> "; end if (self.level == 5 && self.toDisplayStuff[i][2].r == phone_background_r:GetInt() && self.toDisplayStuff[i][2].g == phone_background_g:GetInt() && self.toDisplayStuff[i][2].b == phone_background_b:GetInt()) then prefix = "> "; end if (self.level == 6 && self.toDisplayStuff[i][2].r == phone_highlight_r:GetInt() && self.toDisplayStuff[i][2].g == phone_highlight_g:GetInt() && self.toDisplayStuff[i][2].b == phone_highlight_b:GetInt()) then prefix = "> "; end if (self.level == 7 && self.toDisplayStuff[i][2].r == phone_text_r:GetInt() && self.toDisplayStuff[i][2].g == phone_text_g:GetInt() && self.toDisplayStuff[i][2].b == phone_text_b:GetInt()) then prefix = "> "; end if (i == self.curSpot) then surface.SetDrawColor(255, 255, 255, 255); surface.DrawRect(screenX, screenY + perArea * curArea, screenW, perArea); surface.SetDrawColor(math.Clamp(phone_highlight_r:GetInt(), 0, 255), math.Clamp(phone_highlight_g:GetInt(), 0, 255), math.Clamp(phone_highlight_b:GetInt(), 0, 255), 200); surface.DrawRect(screenX, screenY + perArea * curArea, screenW, perArea); end draw.SimpleText(prefix .. self.toDisplayStuff[i][1], "PhoneFont", screenX + 5, screenY + (perArea * (curArea + .5)), tColor, 0, 1); end curArea = curArea + 1; end end function PANEL:GoUp ( ) self.CurrentlyShowing = true; self.ShowingTime = CurTime(); self:SetAlpha(255); self.CurUp = true; self.lastScroll = CurTime(); if (self.demoSound) then self.demoSound:Stop(); self.demoSound = nil; self.demoPlaying = nil; end self:MakePopup(); self:SetMouseInputEnabled(); end function PANEL:GoDown ( ) self.CurrentlyShowing = nil; self.ShowingTime = CurTime() + slideTime; self.CurUp = nil; self:SetKeyboardInputEnabled(); end local rewindNumbers = {}; rewindNumbers[2] = 1; rewindNumbers[3] = 1; rewindNumbers[4] = 3; rewindNumbers[5] = 3; rewindNumbers[6] = 3; rewindNumbers[7] = 3; function PANEL:OnKeyCodePressed ( Key ) if (Key == GAMEMODE.GetPhoneKey()) then self:GoDown(); elseif (Key == KEY_S || Key == KEY_DOWN) then self.curSpot = self.curSpot + 1; self.lastScroll = CurTime(); if (self.demoSound) then self.demoSound:Stop(); self.demoSound = nil; self.demoPlaying = nil; end if (self.curSpot - 4 > self.startPos) then self.startPos = self.curSpot - 4; end elseif (Key == KEY_W || Key == KEY_UP) then self.curSpot = self.curSpot - 1; self.lastScroll = CurTime(); if (self.demoSound) then self.demoSound:Stop(); self.demoSound = nil; self.demoPlaying = nil; end if (self.curSpot < self.startPos) then self.startPos = self.curSpot; end elseif (Key == KEY_D || Key == KEY_RIGHT || Key == KEY_SPACE) then if (self.level == 2 || (self.level == 1 && self.toDisplayStuff[self.curSpot][2] == 911)) then if (!GAMEMODE.Call_Time && self.toDisplayStuff[self.curSpot]) then surface.PlaySound(Sound("PERP2.5/phone_dial.mp3")); local pd = SoundDuration("PERP2.5/phone_dial.mp3") local pe = SoundDuration("PERP2.5/phone_error.mp3"); local playerExists; if (self.level == 1) then if (team.NumPlayers(TEAM_DISPATCHER) != 0) then for k, v in pairs(team.GetPlayers(TEAM_DISPATCHER)) do playerExists = v; break end end if (GAMEMODE.Options_EuroStuff:GetBool()) then GAMEMODE.Call_Player = "999" else GAMEMODE.Call_Player = "911" end else for k, v in pairs(player.GetAll()) do if (tostring(v:UniqueID()) == tostring(self.toDisplayStuff[self.curSpot][2])) then playerExists = v; break; end end if (playerExists) then GAMEMODE.Call_Player = playerExists:GetRPName(); else GAMEMODE.Call_Player = self.toDisplayStuff[self.curSpot][1]; end end GAMEMODE.Call_Time = CurTime(); GAMEMODE.PhoneText = "Calling"; self:SetKeyboardInputEnabled(); if (playerExists && playerExists != LocalPlayer()) then timer.Simple(pd + .5, function() RunConsoleCommand("perp_dp", tostring(playerExists:UniqueID())) end); self.lastRing = CurTime() + pd + .5; else self.lastRing = CurTime() + 50000; timer.Simple(pd + .5, function() surface.PlaySound(Sound("PERP2.5/phone_error.mp3")) end); timer.Simple(pd + .5, function ( ) GAMEMODE.PhoneText = "Connected To"; end); timer.Simple(pd + .5 + pe, function ( ) if (GAMEMODE.Call_Player) then GAMEMODE.Phone:GoDown(); end GAMEMODE.Call_Player = nil; GAMEMODE.Call_Time = nil; end); end end elseif (self.level < 4) then self.level = self.toDisplayStuff[self.curSpot][2]; self.curSpot = 1; self.startPos = 1; elseif (self.level == 4) then if (self.SpotToRing[self.curSpot]) then LocalPlayer().StringRedun["ringtone"] = {entity = LocalPlayer(), value = self.curSpot}; RunConsoleCommand("perp_rt", self.SpotToRing[self.curSpot]); Msg("send req : " .. self.SpotToRing[self.curSpot] .. "\n") end else local prefix; if (self.level == 5) then prefix = "perp2_phone_background_"; end if (self.level == 6) then prefix = "perp2_phone_highlight_"; end if (self.level == 7) then prefix = "perp2_phone_text_"; end local col = self.toDisplayStuff[self.curSpot][2] RunConsoleCommand(prefix .. "r", col.r); RunConsoleCommand(prefix .. "g", col.g); RunConsoleCommand(prefix .. "b", col.b); end elseif (Key == KEY_A || Key == KEY_LEFT) then if (!rewindNumbers[self.level]) then return; end self.level = rewindNumbers[self.level]; self.curSpot = 1; self.startPos = 1; if (self.demoSound) then self.demoSound:Stop(); self.demoSound = nil; self.demoPlaying = nil; end end end vgui.Register("perp2_phone", PANEL);
mit
leschenko/simple_slug
lib/simple_slug/railtie.rb
215
module SimpleSlug class Railtie < Rails::Railtie initializer 'simple_slug.model_additions' do ActiveSupport.on_load :active_record do include SimpleSlug::ModelAddition end end end end
mit
jmhol9/Scheme
test/mailers/invite_notifier_test.rb
127
require 'test_helper' class InviteNotifierTest < ActionMailer::TestCase # test "the truth" do # assert true # end end
mit
freezestudio/hana.zh
hana/detail/has_common_embedding.hpp
2449
/*! @file Defines `boost::hana::detail::has_[nontrivial_]common_embedding`. @copyright Louis Dionne 2013-2016 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_HANA_DETAIL_HAS_COMMON_EMBEDDING_HPP #define BOOST_HANA_DETAIL_HAS_COMMON_EMBEDDING_HPP #include <hana/config.hpp> #include <hana/core/common.hpp> #include <hana/core/to.hpp> #include <hana/detail/void_t.hpp> #include <type_traits> BOOST_HANA_NAMESPACE_BEGIN namespace detail { template <template <typename...> class Concept, typename T, typename U, typename = void> struct has_common_embedding_impl : std::false_type { }; template <template <typename...> class Concept, typename T, typename U> struct has_common_embedding_impl<Concept, T, U, detail::void_t< typename common<T, U>::type >> { using Common = typename common<T, U>::type; using type = std::integral_constant<bool, Concept<T>::value && Concept<U>::value && Concept<Common>::value && is_embedded<T, Common>::value && is_embedded<U, Common>::value >; }; //! @ingroup group-details //! Returns whether `T` and `U` both have an embedding into a //! common type. //! //! If `T` and `U` do not have a common-type, this metafunction returns //! false. template <template <typename...> class Concept, typename T, typename U> using has_common_embedding = typename has_common_embedding_impl<Concept, T, U>::type; template <template <typename...> class Concept, typename T, typename U> struct has_nontrivial_common_embedding_impl : has_common_embedding_impl<Concept, T, U> { }; template <template <typename...> class Concept, typename T> struct has_nontrivial_common_embedding_impl<Concept, T, T> : std::false_type { }; //! @ingroup group-details //! Returns whether `T` and `U` are distinct and both have an embedding //! into a common type. //! //! If `T` and `U` do not have a common-type, this metafunction returns //! false. template <template <typename...> class Concept, typename T, typename U> using has_nontrivial_common_embedding = typename has_nontrivial_common_embedding_impl<Concept, T, U>::type; } BOOST_HANA_NAMESPACE_END #endif // !BOOST_HANA_DETAIL_HAS_COMMON_EMBEDDING_HPP
mit
julesbond007/owlpad
owlpad-service-impl/src/main/java/com/owlpad/service/model/Region.java
1603
package com.owlpad.service.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; /** * * @author Jay Paulynice * */ @Entity(name = "region") public class Region { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @Column(name = "name") private String name; @Column(name = "selector") private String selector; /** * @return the selector */ public String getSelector() { return selector; } /** * @param selector * the selector to set */ public void setSelector(final String selector) { this.selector = selector; } @ManyToOne(optional = false) private Layout layout; /** * @return the id */ public int getId() { return id; } /** * @param id * the id to set */ public void setId(final int id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(final String name) { this.name = name; } /** * @return the layout */ public Layout getLayout() { return layout; } /** * @param layout * the layout to set */ public void setLayout(final Layout layout) { this.layout = layout; } }
mit
datokrat/nodejs-odata-server
ast2query.js
1772
module.exports = { getQueryFromSyntaxTree: getQueryFromSyntaxTree }; var queries = require('./queries'); var navi = require('../abnfjs/ast-navigator'); var queryFactory = require('./dbqueryfactory'); function getQueryFromSyntaxTree(ast, schema) { return getQueryFromCondensedSyntaxTree(ast.evaluate(), schema); } function getQueryFromCondensedSyntaxTree(ast, schema) { var fty = getQueryStackWithFactory(ast, schema); return new queries.EntitySetQuery({ entitySetName: fty.entitySetName, navigationStack: fty.path, filterOption: fty.filterOption, expandTree: fty.expandTree, }); } function getQueryStackWithFactory(ast, schema) { if(ast.type == 'resourceQuery') { if(ast.resourcePath.type !== 'entitySet') throw new Error('unsupported resource path type: ' + ast.resourcePath.type); if(ast.resourcePath.navigation && ast.resourcePath.navigation.qualifiedEntityTypeName) throw new Error('qualified entity type name not supported'); var fty = new queryFactory.DbQueryFactory(ast.resourcePath.entitySetName, schema); fty.filter(ast.queryOptions.filter); fty.expand(ast.queryOptions.expand); switch(ast.resourcePath.navigation.type) { case 'none': return fty; case 'collection-navigation': var navPath = ast.resourcePath.navigation.path; var key = parseInt(navPath.keyPredicate.simpleKey.value); //TODO: check type fty.selectById(key); if(navPath.singleNavigation) { fty.selectProperty(navPath.singleNavigation.propertyPath.propertyName); } return fty; default: throw new Error('this resourcePath navigation type is not supported'); } } else throw new Error('unsupported query type: ' + ast.type); }
mit
YaniLozanov/Software-University
C#/05. C# Web Development/Back-End/04. Web Server - EF Core Exercises/WebServer/ByTheCakeApplication/ViewModels/Products/ProductInCartViewModel.cs
205
namespace WebServer.ByTheCakeApplication.ViewModels.Products { public class ProductInCartViewModel { public string Name { get; set; } public decimal Price { get; set; } } }
mit
auth0/java-jwt
lib/src/main/java/com/auth0/jwt/impl/PayloadSerializer.java
2628
package com.auth0.jwt.impl; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.std.StdSerializer; import java.io.IOException; import java.util.*; /** * Jackson serializer implementation for converting into JWT Payload parts. * * @see com.auth0.jwt.JWTCreator * <p> * This class is thread-safe. */ public class PayloadSerializer extends StdSerializer<ClaimsHolder> { public PayloadSerializer() { this(null); } private PayloadSerializer(Class<ClaimsHolder> t) { super(t); } @Override public void serialize(ClaimsHolder holder, JsonGenerator gen, SerializerProvider provider) throws IOException { gen.writeStartObject(); for (Map.Entry<String, Object> e : holder.getClaims().entrySet()) { if (PublicClaims.AUDIENCE.equals(e.getKey())) { writeAudience(gen, e); } else { gen.writeFieldName(e.getKey()); if (e.getValue() instanceof Date) { // true for EXPIRES_AT, ISSUED_AT, NOT_BEFORE gen.writeNumber(dateToSeconds((Date) e.getValue())); } else { gen.writeObject(e.getValue()); } } } gen.writeEndObject(); } private void writeAudience(JsonGenerator gen, Map.Entry<String, Object> e) throws IOException { if (e.getValue() instanceof String) { gen.writeFieldName(e.getKey()); gen.writeString((String) e.getValue()); } else { List<String> audArray = new ArrayList<>(); if (e.getValue() instanceof String[]) { audArray = Arrays.asList((String[]) e.getValue()); } else if (e.getValue() instanceof List) { List<?> audList = (List<?>) e.getValue(); for (Object aud : audList) { if (aud instanceof String) { audArray.add((String)aud); } } } if (audArray.size() == 1) { gen.writeFieldName(e.getKey()); gen.writeString(audArray.get(0)); } else if (audArray.size() > 1) { gen.writeFieldName(e.getKey()); gen.writeStartArray(); for (String aud : audArray) { gen.writeString(aud); } gen.writeEndArray(); } } } private long dateToSeconds(Date date) { return date.getTime() / 1000; } }
mit
Projesh07/Python-basic
python data types/string.py
4196
#String with double qoutes variable_string="Hello world" print(variable_string) #Output Hello world #String with single qoutes you migh use escape char for this kind of string variable_string='Python\'s world' print(variable_string) #Output Python's world #String with multi line python use three double quotes variable_string=""" Python\'s world This is actuall fun and dream""" print(variable_string) #Output Python's world #This is actuall fun and dream #String function len(string var) #It takes one arg and return length of the string variable_string="ptyhon is my world" print(len(variable_string)) #output 18 #GetCharacter using location in String #After varibale just use [] and specify number variable_string="Hello world" #Before : it is the starting point #After : end point that exclude the end point print(variable_string[0:6]) #Both same print(variable_string[:6]) #Output Hello print(variable_string[6:11]) #Both same print(variable_string[6:]) #Output World print(variable_string[6:10]) #Output worl #Bcz 1st index inclusive 2nd index is not cluded #So string will be 6 to 9 w-6 o-7 r-8 l-9 print(variable_string[:]) #Output Hell World (or full string) #Getting char using index variable_string="Hello world" print(variable_string[0]) #Output H #print(variable_string[11]) #Output error index out range #Becz indexing strat from 0 so #The last char will be at 10 in this case #String lower() method. it doesn't take any args #All char lower variable_string="Hello world" print(variable_string.lower()) #Output hello world #String upper() method. it doesn't take any args #All char upper variable_string="Hello world" print(variable_string.upper()) #Output HELLO WORLD #String count() method. it takes a string as args #return number after counting variable_string="Hello world" print(variable_string.count('world')) #Output 1 print(variable_string.count('l')) #Output 3 #String find() method. it takes a string as args #return number where it's started from variable_string="Hello world" print(variable_string.find('world')) #Output 6 print(variable_string.find('gone')) #Output -1 #Bcz it return negative when it doen't find any matching string #String replace() #Takes two argument #1st argument that you want to #Second argument that u want to replace with #Remebr it returns a new string after replacing variable_string="Hello world" new_var_string=variable_string.replace("Hello","Python") print(new_var_string) #Output Python world #string concate using +sign var_st1="Hello" var_st2="World" full_str=var_st1 + var_st2 print(full_str) #Output HelloWorld (No space) #string concate using +sign with space var_st1="Hello" var_st2="World" full_str=var_st1 + ' ' +var_st2 print(full_str) #Output Hello World (with space) #string concate using placeholder with format() method #format() takes all placeholder as arguments var_st1="Hello" var_st2="World" full_str='{} {}'.format(var_st1,var_st2) print(full_str) #Output Hello world #If format() arg is not eqaul to placeholder then it occur an error #full_str='{} {}'.format(var_st2) print(full_str) #Output Error tuple index out of range #another way to do this just placing string inside the place holder #and placing f at the begening of the string #It only possible at upper version of python 3 #full_str= f'{var_st1} {var_st2}' print(full_str) #Output Error tuple index out of range #lastly # dir() method will show you all the method and attr #Related to a variable in this case string variable print(dir(variable_string)) #output all related method and attr #You can do it by help function but #Help function works with class and methods #so you have to pass help() function args as calss name or class method # print (help(str)) # print (help(str.lower())) # numList = ['1', '2', '3', '4'] # seperator = ', ' # print(seperator.join(numList)) # numTuple = ('1', '2', '3', '4') # print(seperator.join(numTuple)) # s1 = 'abc' # s2 = '123' # """ Each character of s2 is concatenated to the front of s1""" # print('s1.join(s2):', s1.join(s2)) # """ Each character of s1 is concatenated to the front of s2""" # print('s2.join(s1):', s2.join(s1)) #str.islower() #str.isupper()
mit
tlossen/stakkenblokken
src/main/java/stakkenblokken/model/Color.java
397
// automatically generated by the FlatBuffers compiler, do not modify package stakkenblokken.model; public final class Color { private Color() { } public static final byte Red = 1; public static final byte Green = 2; public static final byte Blue = 3; public static final String[] names = { "Red", "Green", "Blue", }; public static String name(int e) { return names[e - Red]; } }
mit
fayfox/fayfox
vendor/cms/modules/admin/controllers/CommentController.php
1143
<?php namespace cms\modules\admin\controllers; use cms\library\AdminController; use fay\core\Sql; use fay\models\tables\Messages; use fay\common\ListView; class CommentController extends AdminController{ public function __construct(){ parent::__construct(); $this->layout->current_directory = 'message'; } public function index(){ $this->layout->subtitle = '文章评论'; $sql = new Sql(); $sql->from('messages', 'm') ->joinLeft('posts', 'p', 'm.target = p.id', 'title AS post_title, id AS post_id') ->joinLeft('users', 'u', 'm.user_id = u.id', 'realname,username') ->where('m.type = '.Messages::TYPE_POST_COMMENT) ->order('id DESC') ; if($this->input->get('deleted')){ $sql->where(array( 'm.deleted = 1', )); }else if($this->input->get('status') !== null && $this->input->get('status') !== ''){ $sql->where(array( 'm.status = ?'=>$this->input->get('status', 'intval'), 'm.deleted = 0', )); }else{ $sql->where('m.deleted = 0'); } $listview = new ListView($sql, array( 'pageSize'=>30, )); $this->view->listview = $listview; $this->view->render(); } }
mit
PublicaMundi/pycsw
pycsw/plugins/outputschemas/atom.py
5170
# -*- coding: iso-8859-15 -*- # ================================================================= # # Authors: Tom Kralidis <tomkralidis@gmail.com> # # Copyright (c) 2012 Tom Kralidis # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. # # ================================================================= import os from lxml import etree from pycsw import util NAMESPACE = 'http://www.w3.org/2005/Atom' NAMESPACES = {'atom': NAMESPACE, 'georss': 'http://www.georss.org/georss'} XPATH_MAPPINGS = { 'pycsw:Identifier': 'atom:id', 'pycsw:Title': 'atom:title', 'pycsw:Creator': 'atom:author', 'pycsw:Abstract': 'atom:summary', 'pycsw:PublicationDate': 'atom:published', 'pycsw:Keywords': 'atom:category', 'pycsw:Contributor': 'atom:contributor', 'pycsw:AccessConstraints': 'atom:rights', 'pycsw:Modified': 'atom:updated', 'pycsw:Source': 'atom:source', } def write_record(result, esn, context, url=None): ''' Return csw:SearchResults child as lxml.etree.Element ''' typename = util.getqattr(result, context.md_core_model['mappings']['pycsw:Typename']) if esn == 'full' and typename == 'atom:entry': # dump record as is and exit return etree.fromstring(util.getqattr(result, context.md_core_model['mappings']['pycsw:XML']), context.parser) node = etree.Element(util.nspath_eval('atom:entry', NAMESPACES), nsmap=NAMESPACES) node.attrib[util.nspath_eval('xsi:schemaLocation', context.namespaces)] = \ '%s http://www.kbcafe.com/rss/atom.xsd.xml' % NAMESPACES['atom'] # author val = util.getqattr(result, context.md_core_model['mappings']['pycsw:Creator']) if val: etree.SubElement(node, util.nspath_eval('atom:author', NAMESPACES)).text = val # category val = util.getqattr(result, context.md_core_model['mappings']['pycsw:Keywords']) if val: for kw in val.split(','): etree.SubElement(node, util.nspath_eval('atom:category', NAMESPACES)).text = kw for qval in ['pycsw:Contributor', 'pycsw:Identifier']: val = util.getqattr(result, context.md_core_model['mappings'][qval]) if val: etree.SubElement(node, util.nspath_eval(XPATH_MAPPINGS[qval], NAMESPACES)).text = val rlinks = util.getqattr(result, context.md_core_model['mappings']['pycsw:Links']) if rlinks: for link in rlinks.split('^'): linkset = link.split(',') url2 = etree.SubElement(node, util.nspath_eval('atom:link', NAMESPACES), href=linkset[-1], type=linkset[2], title=linkset[1]) etree.SubElement(node, util.nspath_eval('atom:link', NAMESPACES), href='%s?service=CSW&version=2.0.2&request=GetRepositoryItem&id=%s' % (url, util.getqattr(result, context.md_core_model['mappings']['pycsw:Identifier']))) for qval in ['pycsw:PublicationDate', 'pycsw:AccessConstraints', 'pycsw:Source', 'pycsw:Abstract', 'pycsw:Title', 'pycsw:Modified']: val = util.getqattr(result, context.md_core_model['mappings'][qval]) if val: etree.SubElement(node, util.nspath_eval(XPATH_MAPPINGS[qval], NAMESPACES)).text = val # bbox extent val = util.getqattr(result, context.md_core_model['mappings']['pycsw:BoundingBox']) bboxel = write_extent(val, context.namespaces) if bboxel is not None: node.append(bboxel) return node def write_extent(bbox, nsmap): ''' Generate BBOX extent ''' if bbox is not None: try: bbox2 = util.wkt2geom(bbox, bounds=False) except: return None where = etree.Element(util.nspath_eval('georss:where', NAMESPACES)) polygon = etree.SubElement(where, util.nspath_eval('gml:Polygon', nsmap), srsName='urn:x-ogc:def:crs:EPSG:6.11:4326') exterior = etree.SubElement(polygon, util.nspath_eval('gml:exterior', nsmap)) lring = etree.SubElement(exterior, util.nspath_eval('gml:LinearRing', nsmap)) poslist = etree.SubElement(lring, util.nspath_eval('gml:posList', nsmap)).text = \ ' '.join(['%s %s' % (str(i[1]), str(i[0])) for i in list(bbox2.exterior.coords)]) return where return None
mit
Razborges/algGrafos
Trabalho2/bfs.py
1487
# coding: utf-8 __author__ = 'Rafael Borges' ''' Ex. de implementação do algoritmo BFS (Busca em largura em Grafo) imprimindo todos os vértices do grafo ''' import sys, os def bfs(grafo, inicio): q = [] visitado = [] pais = {} q.append(inicio) visitado.append(inicio) print(inicio, end='\t') while len(q) != 0: u = q.pop(0) for vertice in grafo[u]: if vertice not in visitado: pais.update({vertice: u}) visitado.append(vertice) q.append(vertice) print(vertice, end='\t') print('\n') if __name__ == '__main__': if len(sys.argv) != 3: sys.stderr.write('Erro na chamada do comando.\n') sys.stderr.write('Para executar digite: \'python bfs.py NOME_ARQUIVO.TXT VETOR_INICIO >>> onde NOME_ARQUIVO.TXT é o nome do arquivo que contém o grafo, e, VETOR_INICIO é o valor do vetor por onde deverá começar a ser feita a leitura.\n') sys.exit() nome_arquivo = sys.argv[1] vetor_inicio = sys.argv[2] try: arquivo = open(nome_arquivo, 'r') except IOError: sys.stderr.write('Erro ao tentar ler o arquivo, verifique se está válido.') sys.exit() grafo = {} for line in arquivo: u, v = map(str, line.split()) if u not in grafo: grafo[u] = [v] else: grafo[u].append(v) print('*** Vertices usando BFS ***') bfs(grafo, vetor_inicio)
mit
fenos/graphql-thinky
test/unit/typeMapper.test.js
7139
import test from 'ava'; import thinky from './../helpers/db/thinky'; import thinkySchema from 'thinky-export-schema'; import {expect} from 'chai'; import {toGraphQLDefinition,attributeToGraphQLType} from './../../src/typeMapper'; import { GraphQLString, GraphQLBoolean, GraphQLInt, GraphQLObjectType, GraphQLList, GraphQLEnumType, GraphQLNonNull } from 'graphql'; import { toGlobalId } from 'graphql-relay'; const thinkyType = thinky.type; test('it should return a GraphQLString for types: [string, date, id]', () => { const resultWithString = attributeToGraphQLType(thinkyType.string()); const resultWithDate = attributeToGraphQLType(thinkyType.date()); const resultWithID = attributeToGraphQLType(thinkyType.id()); expect(resultWithString).to.be.equal(GraphQLString); expect(resultWithDate).to.be.equal(GraphQLString); expect(resultWithID).to.be.equal(GraphQLString); }); test('it should return a GraphQLBoolean for types: [boolean]', () => { const result = attributeToGraphQLType(thinkyType.boolean()); expect(result).to.be.equal(GraphQLBoolean); }); test('it should return a GraphQLInt for types: [number]', () => { const result = attributeToGraphQLType(thinkyType.number()); expect(result).to.be.equal(GraphQLInt); }); test('it should return a GraphQLObjectType for types: [object]', () => { const result = attributeToGraphQLType(thinkyType.object().schema({ profile: thinkyType.string() }),'images'); expect(result).to.be.an.instanceof(GraphQLObjectType); expect(result._typeConfig.fields.profile.type).to.be.equal(GraphQLString); }); test('it should throw exception if the name of a object is not Specified', () => { const result = () => { return attributeToGraphQLType(thinkyType.object().schema({ profile: thinkyType.string() })); }; expect(result).to.throw('Specify a name for the Object Attribute type'); }); test('it should return a GraphQLList for types: [array]', () => { const result = attributeToGraphQLType( thinkyType.array().schema(thinkyType.number()) ); expect(result).to.be.an.instanceof(GraphQLList); }); test('it should return a GraphQLList of GraphQLObjectType for type: [array]', () => { const result = attributeToGraphQLType( thinkyType.array().schema(thinkyType.object().schema({ images: thinkyType.string() })),'images' ); expect(result).to.be.an.instanceof(GraphQLList); }); test('it should return a GraphQLENUM for type: [string,enum]', () => { const result = attributeToGraphQLType( thinkyType.string().enum(['yes','no']) ); expect(result).to.be.an.instanceof(GraphQLEnumType); }); test("it transform a thinky model with string attrs, to a GraphQL definition", () => { const Model = thinky.createModel('user-test', { name: thinkyType.string(), surname: thinkyType.string() }); const GraphQLFields = toGraphQLDefinition(Model); Object.keys(GraphQLFields).forEach((key) => { expect(GraphQLFields[key].type).to.be.equal(GraphQLString); }); }); test("it transform a thinky model to a GraphQL definition", () => { const Model = thinky.createModel('usertest1', { name: thinkyType.string(), surname: thinkyType.string(), images: thinkyType.object().schema({ profile: thinkyType.string(), cover: thinkyType.string() }), social: thinkyType.array().schema(thinkyType.string()), myVirtual: thinkyType.virtual(), myAny: thinkyType.any() }); const GraphQLFields = toGraphQLDefinition(Model); expect(GraphQLFields['id'].type).to.be.equal(GraphQLString); expect(GraphQLFields['name'].type).to.be.equal(GraphQLString); expect(GraphQLFields['surname'].type).to.be.equal(GraphQLString); expect(GraphQLFields['images'].type).to.be.an.instanceof(GraphQLObjectType); expect(GraphQLFields['images'].type._typeConfig.fields.profile.type).to.be.equal(GraphQLString); expect(GraphQLFields['images'].type._typeConfig.fields.cover.type).to.be.equal(GraphQLString); expect(GraphQLFields['social'].type).to.be.an.instanceof(GraphQLList); // Virtual and ANY are not converted to a graphql definition // because we can't strongly type them. expect(GraphQLFields['myVirtual']).to.be.undefined; expect(GraphQLFields['myAny']).to.be.undefined; }); test("it should add GraphQLNotNull type to required fields", () => { const Model = thinky.createModel('user-test-5', { name: thinkyType.string().allowNull(false), surname: thinkyType.string(), email: thinkyType.string() }); const GraphQLFields = toGraphQLDefinition(Model); expect(GraphQLFields['name'].type).to.be.instanceof(GraphQLNonNull); }); test("it should by pass the not null definition", () => { const Model = thinky.createModel('user-test-7', { name: thinkyType.string().allowNull(false), surname: thinkyType.string(), email: thinkyType.string() }); const GraphQLFields = toGraphQLDefinition(Model, { allowNull: false }); expect(GraphQLFields['name'].type).to.be.not.instanceof(GraphQLNonNull); expect(GraphQLFields['name'].type).to.be.equal(GraphQLString); }); test("it should exclude the specified attributes from the GraphQL Definition", () => { const Model = thinky.createModel('user-test-2', { name: thinkyType.string(), surname: thinkyType.string(), email: thinkyType.string() }); const GraphQLFields = toGraphQLDefinition(Model, { exclude: ['name','surname'] }); expect(GraphQLFields['name']).to.be.undefined expect(GraphQLFields['surname']).to.be.undefined; expect(GraphQLFields['email'].type).to.be.equal(GraphQLString); }); test("it should convert only the specified attributes to a GraphQL Definition", () => { const Model = thinky.createModel('user-test-3', { name: thinkyType.string(), surname: thinkyType.string(), email: thinkyType.string() }); const GraphQLFields = toGraphQLDefinition(Model, { only: ['name','surname'] }); expect(GraphQLFields['name'].type).to.be.equal(GraphQLString); expect(GraphQLFields['surname'].type).to.be.equal(GraphQLString); expect(GraphQLFields['email']).to.be.undefined; }); test("it should map fields", () => { const Model = thinky.createModel('user-test-4', { name: thinkyType.string(), surname: thinkyType.string(), email: thinkyType.string() }); const GraphQLFields = toGraphQLDefinition(Model, { map: { email: 'EMAIL' } }); expect(GraphQLFields['EMAIL'].type).to.be.equal(GraphQLString); expect(GraphQLFields['email']).to.be.undefined; }); test("it should add a relay global ID", () => { const Model = thinky.createModel('user-test-6', { name: thinkyType.string(), surname: thinkyType.string(), email: thinkyType.string() }); const GraphQLFields = toGraphQLDefinition(Model, { globalId: true }); expect(GraphQLFields.id.resolve).to.be.ok; expect(GraphQLFields.id.type.ofType.name).to.equal('ID'); expect(GraphQLFields.id.resolve({ id: 'hello' })).to.equal(toGlobalId('User-test-6', 'hello')); expect(GraphQLFields['user-test-6ID'].type).to.be.deep.equal(GraphQLString); });
mit
olavloite/spanner-jdbc-converter
src/main/java/nl/topicus/spanner/converter/data/TablePreparer.java
793
package nl.topicus.spanner.converter.data; import java.sql.Connection; import java.util.concurrent.Callable; public class TablePreparer implements Callable<ConversionResult> { private final AbstractTableWorker worker; private final Connection source; private final Connection destination; public TablePreparer(AbstractTableWorker worker, Connection source, Connection destination) { this.worker = worker; this.source = source; this.destination = destination; } @Override public ConversionResult call() throws Exception { long startTime = System.currentTimeMillis(); worker.prepare(source, destination); long endTime = System.currentTimeMillis(); return new ConversionResult(worker.getTotalRecordCount(), 0, startTime, endTime); } }
mit
slolam/XecMe
src/Common/Zip/IZipIOBlock.cs
745
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace Axp.Fx.Common.Zip { internal interface IZipIOBlock { // Methods bool GetDirtyFlag(bool closingFlag); void Move(long shiftSize); PreSaveNotificationScanControlInstruction PreSaveNotification(long offset, long size); void Save(); void UpdateReferences(bool closingFlag); // Properties long Offset { get; } long Size { get; } } internal interface ITrackingMemoryStreamFactory { // Methods MemoryStream Create(); MemoryStream Create(int capacity); void ReportMemoryUsageDelta(int delta); } }
mit
RPGroup-PBoC/gist_pboc_2017
code/fly_transcription.py
5909
# Import the necessary modules. import numpy as np import matplotlib.pyplot as plt import seaborn as sns # For getting file names. import glob # For image processsing. import skimage.io import skimage.filters import skimage.segmentation import skimage.measure # In this exercise, we will measure the rate of transcription in a nuclear # cycle 14 of a developing Drosophila melanogaster embryo. Specificially, we # are watching the beginning and end of transcription of the Hunchback # morphogen. This was done in a particularly clever way by using the MS2 system # to tag the 5' and 3' ends of the mRNA in separate embryos. In this # experimental systems, fluorescent puncta appear when that region of the mRNA # is properly transcribed. By watching the appearance of the relevant spots, we # can make a measurement of the rate of transcription and investigate whether # the timing makes sense, given the time in between nuclear divisions. It is # important to know that the length of this gene is 3361 base pairs. # In this exercise, we will measure the rate of transcription in a nuclear # cycle 14 of a developing Drosophila melanogaster embryo. Specificially, we # are watching the beginning and end of transcription of the Hunchback # morphogen. This was done in a particularly clever way by using the MS2 system # to tag the 5' and 3' ends of the mRNA in separate embryos. In this # experimental systems, fluorescent puncta appear when that region of the mRNA # is properly transcribed. By watching the appearance of the relevant spots, we # can make a measurement of the rate of transcription and investigate whether # the timing makes sense, given the time in between nuclear divisions. # To begin with, let's take a look at an image somewhere in the middle of the # movie for the 5' labeled mRNA case. im = skimage.io.imread('data/fly_elongation/5Loops0200.tif') plt.figure() plt.imshow(im, cmap=plt.cm.viridis) plt.show() # How can we count? It seems like we would be able to threshold # the images to find the spots. To pick a threshold, let's take a look at the # histogram. plt.figure() plt.hist(im.flatten(), bins=1000) plt.xlabel('pixel value') plt.ylabel('counts') # We see that we have a very large peak which corresponds to the background # pixels and a long tail to the right which likely corresponds to our spots. # Let's try applying a threshold of 0.11 and see how we've done. im_thresh = im > 900 plt.figure() plt.imshow(im_thresh, cmap=plt.cm.viridis) plt.show() # That seems to do a pretty good job! But we still have some spots right on the # edge which are unclear if they are spots or not. To prevent our selves from # overcounting, we can remove any spots touching the border. im_border = skimage.segmentation.clear_border(im_thresh) # We can individually label each spot and count them to double check our # segmentation. im_lab, num_spots = skimage.measure.label(im_border, return_num=True) print('There are ' + str(num_spots) + ' mRNA spots in this image.') # That is pretty good, it matches our count by eye exactly! Our goal is to # count the number of spots per frame and plot their arrival as a function of # time. With about 300 frames, this is too much to do by hand. Let's write a # function so this can be automated. def spot_counter(im, threshold): """Counts the number of puncta in an image""" # Threshold the image. im_thresh = im > threshold # Clear the border. im_border = skimage.segmentation.clear_border(im_thresh) # Label the image and return the number of spots. im_lab, num_spots = skimage.measure.label(im_border, return_num=True) return num_spots # Now let's iterate over all of the 5' labeled images. We can get all of the # files through using glob. spots_5p_files = glob.glob('data/fly_elongation/5Loops*.tif') spots_5p = [] for i in range(len(spots_5p_files)): im = skimage.io.imread(spots_5p_files[i]) num_spots = spot_counter(im, 900) spots_5p.append(num_spots) # While we are at it, we can do the same procedure with the 3' labeled mRNA. spots_3p_files = glob.glob('data/fly_elongation/3Loops*.tif') spots_3p = [] for i in range(len(spots_3p_files)): im = skimage.io.imread(spots_3p_files[i]) num_spots = spot_counter(im, 900) spots_3p.append(num_spots) # Let's plot the number of spots as a function of time. time_5p = np.arange(0, len(spots_5p), 1) * 10 # conversion to seconds time_3p = np.arange(0, len(spots_3p), 1) * 10 # conversion to seconds plt.figure() plt.plot(time_5p, spots_5p, '-', label="5' labeled") plt.plot(time_3p, spots_3p, '-', label="3' labeled") plt.xlabel('time (s)') plt.ylabel('spot number') plt.legend() plt.show() # This looks good, but we know that these two image sets are not synchronized. # By this, I mean that each image does not correspond to the same point in # development between the two labeling types. By looking at the image stacks # in ImageJ, we can see that the anaphase of the last nuclear cycle (nuclear # cycle 14) for the 5' labeled sample begins at frame 99 and at frame 125 # for the 3' labeled sample. We can plot only these ranges to determine the # rate of transcription. spots_5p_sync = spots_5p[98:] time_5p_sync = time_5p[98:] spots_3p_sync = spots_3p[124:] time_3p_sync = time_3p[124:] # Now let's take a look. plt.figure() plt.plot(time_5p_sync, spots_5p_sync, label="5' labeled") plt.plot(time_3p_sync, spots_3p_sync, label="3' labeled") plt.xlabel('time (s)') plt.ylabel('spot number') plt.legend(loc='upper left') plt.show() # We can see that the difference in the onset of peaks is about 250 - 300 # seconds. Knowing that the length of the gene is 3361 base pairs, we # can get to a transcription rate of about 10 - 20 base pairs per second. # Since a nuclei takes about ten minutes to duplicate, half of that time is # being spent just transcribing this gene! We haven't even mentioned the # translation!.
mit
luiighi2693/karma
karmathegame/phpMyAdmin/libraries/ip_allow_deny.lib.php
5212
<?php /* $Id: ip_allow_deny.lib.php 9781 2006-12-07 18:00:46Z lem9 $ */ // vim: expandtab sw=4 ts=4 sts=4: /** * This library is used with the server IP allow/deny host authentication * feature */ /** * Gets the "true" IP address of the current user * * @return string the ip of the user * * @access private */ function PMA_getIp() { /* Get the address of user */ if (!empty($_SERVER['REMOTE_ADDR'])) { $direct_ip = $_SERVER['REMOTE_ADDR']; } else { /* We do not know remote IP */ return false; } /* Do we trust this IP as a proxy? If yes we will use it's header. */ if (isset($GLOBALS['cfg']['TrustedProxies'][$direct_ip])) { $proxy_ip = PMA_getenv($GLOBALS['cfg']['TrustedProxies'][$direct_ip]); // the $ checks that the header contains only one IP address $is_ip = preg_match('|^([0-9]{1,3}\.){3,3}[0-9]{1,3}$|', $proxy_ip, $regs); if ($is_ip && (count($regs) > 0)) { // True IP behind a proxy return $regs[0]; } } /* Return true IP */ return $direct_ip; } // end of the 'PMA_getIp()' function /** * Based on IP Pattern Matcher * Originally by J.Adams <jna@retina.net> * Found on <http://www.php.net/manual/en/function.ip2long.php> * Modified by Robbat2 <robbat2@users.sourceforge.net> * * Matches: * xxx.xxx.xxx.xxx (exact) * xxx.xxx.xxx.[yyy-zzz] (range) * xxx.xxx.xxx.xxx/nn (CIDR) * * Does not match: * xxx.xxx.xxx.xx[yyy-zzz] (range, partial octets not supported) * * @param string string of IP range to match * @param string string of IP to test against range * * @return boolean always true * * @access public */ function PMA_ipMaskTest($testRange, $ipToTest) { $result = true; if (preg_match('|([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)/([0-9]+)|', $testRange, $regs)) { // performs a mask match $ipl = ip2long($ipToTest); $rangel = ip2long($regs[1] . '.' . $regs[2] . '.' . $regs[3] . '.' . $regs[4]); $maskl = 0; for ($i = 0; $i < 31; $i++) { if ($i < $regs[5] - 1) { $maskl = $maskl + pow(2, (30 - $i)); } // end if } // end for if (($maskl & $rangel) == ($maskl & $ipl)) { return true; } else { return false; } } else { // range based $maskocts = explode('.', $testRange); $ipocts = explode('.', $ipToTest); // perform a range match for ($i = 0; $i < 4; $i++) { if (preg_match('|\[([0-9]+)\-([0-9]+)\]|', $maskocts[$i], $regs)) { if (($ipocts[$i] > $regs[2]) || ($ipocts[$i] < $regs[1])) { $result = false; } // end if } else { if ($maskocts[$i] <> $ipocts[$i]) { $result = false; } // end if } // end if/else } //end for } //end if/else return $result; } // end of the "PMA_IPMaskTest()" function /** * Runs through IP Allow/Deny rules the use of it below for more information * * @param string 'allow' | 'deny' type of rule to match * * @return bool Matched a rule ? * * @access public * * @see PMA_getIp() */ function PMA_allowDeny($type) { global $cfg; // Grabs true IP of the user and returns if it can't be found $remote_ip = PMA_getIp(); if (empty($remote_ip)) { return false; } // copy username $username = $cfg['Server']['user']; // copy rule database $rules = $cfg['Server']['AllowDeny']['rules']; // lookup table for some name shortcuts $shortcuts = array( 'all' => '0.0.0.0/0', 'localhost' => '127.0.0.1/8' ); // Provide some useful shortcuts if server gives us address: if (PMA_getenv('SERVER_ADDR')) { $shortcuts['localnetA'] = PMA_getenv('SERVER_ADDR') . '/8'; $shortcuts['localnetB'] = PMA_getenv('SERVER_ADDR') . '/16'; $shortcuts['localnetC'] = PMA_getenv('SERVER_ADDR') . '/24'; } foreach ($rules as $rule) { // extract rule data $rule_data = explode(' ', $rule); // check for rule type if ($rule_data[0] != $type) { continue; } // check for username if (($rule_data[1] != '%') //wildcarded first && ($rule_data[1] != $username)) { continue; } // check if the config file has the full string with an extra // 'from' in it and if it does, just discard it if ($rule_data[2] == 'from') { $rule_data[2] = $rule_data[3]; } // Handle shortcuts with above array // DON'T use "array_key_exists" as it's only PHP 4.1 and newer. if (isset($shortcuts[$rule_data[2]])) { $rule_data[2] = $shortcuts[$rule_data[2]]; } // Add code for host lookups here // Excluded for the moment // Do the actual matching now if (PMA_ipMaskTest($rule_data[2], $remote_ip)) { return true; } } // end while return false; } // end of the "PMA_AllowDeny()" function ?>
mit
digital-local-laws/git_law
spec/spec_helper.rb
4397
# Add coverage testing require "codeclimate-test-reporter" CodeClimate::TestReporter.start # Support specs for access control policies require 'pundit/rspec' # This file was generated by the `rspec --init` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # The generated `.rspec` file contains `--require spec_helper` which will cause # this file to always be loaded, without a need to explicitly require it in any # files. # # Given that it is always loaded, you are encouraged to keep this file as # light-weight as possible. Requiring heavyweight dependencies from this file # will add to the boot time of your test suite on EVERY test run, even for an # individual file that may not need all of that loaded. Instead, consider making # a separate helper file that requires the additional dependencies and performs # the additional setup, and require it from the spec files that actually need # it. # # The `.rspec` file also contains a few flags that are not defaults but that # users commonly want. # # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration RSpec.configure do |config| # rspec-expectations config goes here. You can use an alternate # assertion/expectation library such as wrong or the stdlib/minitest # assertions if you prefer. config.expect_with :rspec do |expectations| # This option will default to `true` in RSpec 4. It makes the `description` # and `failure_message` of custom matchers include text for helper methods # defined using `chain`, e.g.: # be_bigger_than(2).and_smaller_than(4).description # # => "be bigger than 2 and smaller than 4" # ...rather than: # # => "be bigger than 2" expectations.include_chain_clauses_in_custom_matcher_descriptions = true end # rspec-mocks config goes here. You can use an alternate test double # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| # Prevents you from mocking or stubbing a method that does not exist on # a real object. This is generally recommended, and will default to # `true` in RSpec 4. mocks.verify_partial_doubles = true end # The settings below are suggested to provide a good initial experience # with RSpec, but feel free to customize to your heart's content. =begin # These two settings work together to allow you to limit a spec run # to individual examples or groups you care about by tagging them with # `:focus` metadata. When nothing is tagged with `:focus`, all examples # get run. config.filter_run :focus config.run_all_when_everything_filtered = true # Limits the available syntax to the non-monkey patched syntax that is # recommended. For more details, see: # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax # - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ # - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching config.disable_monkey_patching! # This setting enables warnings. It's recommended, but in some cases may # be too noisy due to issues in dependencies. config.warnings = true # Many RSpec users commonly either run the entire suite or an individual # file, and it's useful to allow more verbose output when running an # individual spec file. if config.files_to_run.one? # Use the documentation formatter for detailed output, # unless a formatter has already been configured # (e.g. via a command-line flag). config.default_formatter = 'doc' end # Print the 10 slowest examples and example groups at the # end of the spec run, to help surface which specs are running # particularly slow. config.profile_examples = 10 # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = :random # Seed global randomization in this process using the `--seed` CLI option. # Setting this allows you to use `--seed` to deterministically reproduce # test failures related to randomization by passing the same `--seed` value # as the one that triggered the failure. Kernel.srand config.seed =end end
mit
karim/adila
database/src/main/java/adila/db/t6wl.java
202
// This file is automatically generated. package adila.db; /* * HTC OneMaxVZW * * DEVICE: t6wl * MODEL: HTC6600LVW */ final class t6wl { public static final String DATA = "HTC|OneMaxVZW|"; }
mit
Beanstream-DRWP/beanstream-java
src/main/java/com/beanstream/domain/Token.java
2178
/* The MIT License (MIT) * * Copyright (c) 2014 Beanstream Internet Commerce Corp, Digital River, Inc. * * 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 com.beanstream.domain; /** * * @author ctihor */ public class Token { private boolean complete = true; private String name; private String code; private String function; public Token() { super(); } public Token(String name, String code) { super(); this.name = name; this.code = code; } public String getName() { return name; } public Token setName(String name) { this.name = name; return this; } public String getCode() { return code; } public Token setCode(String code) { this.code = code; return this; } public String getFunction() { return function; } public Token setFunction(String function) { this.function = function; return this; } public boolean isComplete() { return complete; } public Token setComplete(boolean complete) { this.complete = complete; return this; } }
mit
kbccoin/kbc
src/init.cpp
58514
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Darkcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "bitcoin-config.h" #endif #include "init.h" #include "addrman.h" #include "checkpoints.h" #include "key.h" #include "main.h" #include "miner.h" #include "net.h" #include "rpcserver.h" #include "txdb.h" #include "ui_interface.h" #include "util.h" #include "activemasternode.h" #include "spork.h" #ifdef ENABLE_WALLET #include "db.h" #include "wallet.h" #include "walletdb.h" #include "keepass.h" #endif #include <stdint.h> #include <stdio.h> #ifndef WIN32 #include <signal.h> #endif #include <boost/algorithm/string/predicate.hpp> #include <boost/filesystem.hpp> #include <boost/interprocess/sync/file_lock.hpp> #include <openssl/crypto.h> using namespace std; using namespace boost; #ifdef ENABLE_WALLET std::string strWalletFile; CWallet* pwalletMain; #endif #ifdef WIN32 // Win32 LevelDB doesn't use filedescriptors, and the ones used for // accessing block files, don't count towards to fd_set size limit // anyway. #define MIN_CORE_FILEDESCRIPTORS 0 #else #define MIN_CORE_FILEDESCRIPTORS 150 #endif // Used to pass flags to the Bind() function enum BindFlags { BF_NONE = 0, BF_EXPLICIT = (1U << 0), BF_REPORT_ERROR = (1U << 1) }; ////////////////////////////////////////////////////////////////////////////// // // Shutdown // // // Thread management and startup/shutdown: // // The network-processing threads are all part of a thread group // created by AppInit() or the Qt main() function. // // A clean exit happens when StartShutdown() or the SIGTERM // signal handler sets fRequestShutdown, which triggers // the DetectShutdownThread(), which interrupts the main thread group. // DetectShutdownThread() then exits, which causes AppInit() to // continue (it .joins the shutdown thread). // Shutdown() is then // called to clean up database connections, and stop other // threads that should only be stopped after the main network-processing // threads have exited. // // Note that if running -daemon the parent process returns from AppInit2 // before adding any threads to the threadGroup, so .join_all() returns // immediately and the parent exits from main(). // // Shutdown for Qt is very similar, only it uses a QTimer to detect // fRequestShutdown getting set, and then does the normal Qt // shutdown thing. // volatile bool fRequestShutdown = false; void StartShutdown() { fRequestShutdown = true; } bool ShutdownRequested() { return fRequestShutdown; } class CCoinsViewErrorCatcher : public CCoinsViewBacked { public: CCoinsViewErrorCatcher(CCoinsView& view) : CCoinsViewBacked(view) {} bool GetCoins(const uint256 &txid, CCoins &coins) { try { return CCoinsViewBacked::GetCoins(txid, coins); } catch(const std::runtime_error& e) { uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR); LogPrintf("Error reading from database: %s\n", e.what()); // Starting the shutdown sequence and returning false to the caller would be // interpreted as 'entry not found' (as opposed to unable to read data), and // could lead to invalid interpration. Just exit immediately, as we can't // continue anyway, and all writes should be atomic. abort(); } } // Writes do not need similar protection, as failure to write is handled by the caller. }; static CCoinsViewDB *pcoinsdbview; static CCoinsViewErrorCatcher *pcoinscatcher = NULL; void Shutdown() { LogPrintf("Shutdown : In progress...\n"); static CCriticalSection cs_Shutdown; TRY_LOCK(cs_Shutdown, lockShutdown); if (!lockShutdown) return; RenameThread("darkcoin-shutoff"); mempool.AddTransactionsUpdated(1); StopRPCThreads(); ShutdownRPCMining(); #ifdef ENABLE_WALLET if (pwalletMain) bitdb.Flush(false); GenerateBitcoins(false, NULL, 0); #endif StopNode(); UnregisterNodeSignals(GetNodeSignals()); { LOCK(cs_main); #ifdef ENABLE_WALLET if (pwalletMain) pwalletMain->SetBestChain(chainActive.GetLocator()); #endif if (pblocktree) pblocktree->Flush(); if (pcoinsTip) pcoinsTip->Flush(); delete pcoinsTip; pcoinsTip = NULL; delete pcoinscatcher; pcoinscatcher = NULL; delete pcoinsdbview; pcoinsdbview = NULL; delete pblocktree; pblocktree = NULL; } #ifdef ENABLE_WALLET if (pwalletMain) bitdb.Flush(true); #endif boost::filesystem::remove(GetPidFile()); UnregisterAllWallets(); #ifdef ENABLE_WALLET if (pwalletMain) delete pwalletMain; #endif LogPrintf("Shutdown : done\n"); } // // Signal handlers are very limited in what they are allowed to do, so: // void HandleSIGTERM(int) { fRequestShutdown = true; } void HandleSIGHUP(int) { fReopenDebugLog = true; } bool static InitError(const std::string &str) { uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR | CClientUIInterface::NOSHOWGUI); return false; } bool static InitWarning(const std::string &str) { uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING | CClientUIInterface::NOSHOWGUI); return true; } bool static Bind(const CService &addr, unsigned int flags) { if (!(flags & BF_EXPLICIT) && IsLimited(addr)) return false; std::string strError; if (!BindListenPort(addr, strError)) { if (flags & BF_REPORT_ERROR) return InitError(strError); return false; } return true; } // Core-specific options shared between UI, daemon and RPC client std::string HelpMessage(HelpMessageMode hmm) { string strUsage = _("Options:") + "\n"; strUsage += " -? " + _("This help message") + "\n"; strUsage += " -alertnotify=<cmd> " + _("Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)") + "\n"; strUsage += " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n"; strUsage += " -checkblocks=<n> " + _("How many blocks to check at startup (default: 288, 0 = all)") + "\n"; strUsage += " -checklevel=<n> " + _("How thorough the block verification of -checkblocks is (0-4, default: 3)") + "\n"; strUsage += " -conf=<file> " + _("Specify configuration file (default: darkcoin.conf)") + "\n"; if (hmm == HMM_BITCOIND) { #if !defined(WIN32) strUsage += " -daemon " + _("Run in the background as a daemon and accept commands") + "\n"; #endif } strUsage += " -datadir=<dir> " + _("Specify data directory") + "\n"; strUsage += " -dbcache=<n> " + strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache) + "\n"; strUsage += " -loadblock=<file> " + _("Imports blocks from external blk000??.dat file") + " " + _("on startup") + "\n"; strUsage += " -maxorphanblocks=<n> " + strprintf(_("Keep at most <n> unconnectable blocks in memory (default: %u)"), DEFAULT_MAX_ORPHAN_BLOCKS) + "\n"; strUsage += " -maxorphantx=<n> " + strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS) + "\n"; strUsage += " -par=<n> " + strprintf(_("Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)"), -(int)boost::thread::hardware_concurrency(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS) + "\n"; strUsage += " -pid=<file> " + _("Specify pid file (default: darkcoind.pid)") + "\n"; strUsage += " -reindex " + _("Rebuild block chain index from current blk000??.dat files") + " " + _("on startup") + "\n"; strUsage += " -txindex " + _("Maintain a full transaction index (default: 0)") + "\n"; strUsage += "\n" + _("Connection options:") + "\n"; strUsage += " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n"; strUsage += " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n"; strUsage += " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n"; strUsage += " -bind=<addr> " + _("Bind to given address and always listen on it. Use [host]:port notation for IPv6") + "\n"; strUsage += " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n"; strUsage += " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n"; strUsage += " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + _("(default: 1)") + "\n"; strUsage += " -dnsseed " + _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)") + "\n"; strUsage += " -forcednsseed " + _("Always query for peer addresses via DNS lookup (default: 0)") + "\n"; strUsage += " -externalip=<ip> " + _("Specify your own public address") + "\n"; strUsage += " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n"; strUsage += " -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n"; strUsage += " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n"; strUsage += " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n"; strUsage += " -onion=<ip:port> " + _("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: -proxy)") + "\n"; strUsage += " -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n"; strUsage += " -port=<port> " + _("Listen for connections on <port> (default: 9999 or testnet: 19999)") + "\n"; strUsage += " -proxy=<ip:port> " + _("Connect through SOCKS proxy") + "\n"; strUsage += " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n"; strUsage += " -socks=<n> " + _("Select SOCKS version for -proxy (4 or 5, default: 5)") + "\n"; strUsage += " -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n"; #ifdef USE_UPNP #if USE_UPNP strUsage += " -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n"; #else strUsage += " -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n"; #endif #endif #ifdef ENABLE_WALLET strUsage += "\n" + _("Wallet options:") + "\n"; strUsage += " -disablewallet " + _("Do not load the wallet and disable wallet RPC calls") + "\n"; strUsage += " -keepass " + _("Use KeePass 2 integration using KeePassHttp plugin (default: 0)") + "\n"; strUsage += " -keepassport=<port> " + _("Connect to KeePassHttp on port <port> (default: 19455)") + "\n"; strUsage += " -keepasskey=<key> " + _("KeePassHttp key for AES encrypted communication with KeePass") + "\n"; strUsage += " -keepassid=<name> " + _("KeePassHttp id for the established association") + "\n"; strUsage += " -keepassname=<name> " + _("Name to construct url for KeePass entry that stores the wallet passphrase") + "\n"; strUsage += " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n"; strUsage += " -paytxfee=<amt> " + _("Fee per kB to add to transactions you send") + "\n"; strUsage += " -rescan " + _("Rescan the block chain for missing wallet transactions") + " " + _("on startup") + "\n"; strUsage += " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + " " + _("on startup") + "\n"; strUsage += " -spendzeroconfchange " + _("Spend unconfirmed change when sending transactions (default: 1)") + "\n"; strUsage += " -upgradewallet " + _("Upgrade wallet to latest format") + " " + _("on startup") + "\n"; strUsage += " -wallet=<file> " + _("Specify wallet file (within data directory)") + " " + _("(default: wallet.dat)") + "\n"; strUsage += " -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n"; strUsage += " -zapwallettxes " + _("Clear list of wallet transactions (diagnostic tool; implies -rescan)") + "\n"; #endif strUsage += "\n" + _("Debugging/Testing options:") + "\n"; if (GetBoolArg("-help-debug", false)) { strUsage += " -benchmark " + _("Show benchmark information (default: 0)") + "\n"; strUsage += " -checkpoints " + _("Only accept block chain matching built-in checkpoints (default: 1)") + "\n"; strUsage += " -dblogsize=<n> " + _("Flush database activity from memory pool to disk log every <n> megabytes (default: 100)") + "\n"; strUsage += " -disablesafemode " + _("Disable safemode, override a real safe mode event (default: 0)") + "\n"; strUsage += " -testsafemode " + _("Force safe mode (default: 0)") + "\n"; strUsage += " -dropmessagestest=<n> " + _("Randomly drop 1 of every <n> network messages") + "\n"; strUsage += " -fuzzmessagestest=<n> " + _("Randomly fuzz 1 of every <n> network messages") + "\n"; strUsage += " -flushwallet " + _("Run a thread to flush wallet periodically (default: 1)") + "\n"; } strUsage += " -debug=<category> " + _("Output debugging information (default: 0, supplying <category> is optional)") + "\n"; strUsage += " " + _("If <category> is not supplied, output all debugging information.") + "\n"; strUsage += " " + _("<category> can be:"); strUsage += " addrman, alert, coindb, db, lock, rand, rpc, selectcoins, mempool, net"; // Don't translate these and qt below if (hmm == HMM_BITCOIN_QT) strUsage += ", qt"; strUsage += ".\n"; #ifdef ENABLE_WALLET strUsage += " -gen " + _("Generate coins (default: 0)") + "\n"; strUsage += " -genproclimit=<n> " + _("Set the processor limit for when generation is on (-1 = unlimited, default: -1)") + "\n"; #endif strUsage += " -help-debug " + _("Show all debugging options (usage: --help -help-debug)") + "\n"; strUsage += " -logtimestamps " + _("Prepend debug output with timestamp (default: 1)") + "\n"; if (GetBoolArg("-help-debug", false)) { strUsage += " -limitfreerelay=<n> " + _("Continuously rate-limit free transactions to <n>*1000 bytes per minute (default:15)") + "\n"; strUsage += " -maxsigcachesize=<n> " + _("Limit size of signature cache to <n> entries (default: 50000)") + "\n"; } strUsage += " -mintxfee=<amt> " + _("Fees smaller than this are considered zero fee (for transaction creation) (default:") + " " + FormatMoney(CTransaction::nMinTxFee) + ")" + "\n"; strUsage += " -minrelaytxfee=<amt> " + _("Fees smaller than this are considered zero fee (for relaying) (default:") + " " + FormatMoney(CTransaction::nMinRelayTxFee) + ")" + "\n"; strUsage += " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n"; if (GetBoolArg("-help-debug", false)) { strUsage += " -printblock=<hash> " + _("Print block on startup, if found in block index") + "\n"; strUsage += " -printblocktree " + _("Print block tree on startup (default: 0)") + "\n"; strUsage += " -printpriority " + _("Log transaction priority and fee per kB when mining blocks (default: 0)") + "\n"; strUsage += " -privdb " + _("Sets the DB_PRIVATE flag in the wallet db environment (default: 1)") + "\n"; strUsage += " -regtest " + _("Enter regression test mode, which uses a special chain in which blocks can be solved instantly.") + "\n"; strUsage += " " + _("This is intended for regression testing tools and app development.") + "\n"; strUsage += " " + _("In this mode -genproclimit controls how many blocks are generated immediately.") + "\n"; } strUsage += " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n"; strUsage += " -testnet " + _("Use the test network") + "\n"; strUsage += " -litemode=<n> " + _("Disable all Masternode and Darksend related functionality (0-1, default: 0)") + "\n"; strUsage += "\n" + _("Masternode options:") + "\n"; strUsage += " -masternode=<n> " + _("Enable the client to act as a masternode (0-1, default: 0)") + "\n"; strUsage += " -mnconf=<file> " + _("Specify masternode configuration file (default: masternode.conf)") + "\n"; strUsage += " -masternodeprivkey=<n> " + _("Set the masternode private key") + "\n"; strUsage += " -masternodeaddr=<n> " + _("Set external address:port to get to this masternode (example: address:port)") + "\n"; strUsage += " -masternodeminprotocol=<n> " + _("Ignore masternodes less than version (example: 70050; default : 0)") + "\n"; strUsage += "\n" + _("Darksend options:") + "\n"; strUsage += " -enabledarksend=<n> " + _("Enable use of automated darksend for funds stored in this wallet (0-1, default: 0)") + "\n"; strUsage += " -darksendrounds=<n> " + _("Use N separate masternodes to anonymize funds (2-8, default: 2)") + "\n"; strUsage += " -anonymizedarkcoinamount=<n> " + _("Keep N darkcoin anonymized (default: 0)") + "\n"; strUsage += " -liquidityprovider=<n> " + _("Provide liquidity to Darksend by infrequently mixing coins on a continual basis (0-100, default: 0, 1=very frequent, high fees, 100=very infrequent, low fees)") + "\n"; strUsage += "\n" + _("InstantX options:") + "\n"; strUsage += " -enableinstantx=<n> " + _("Enable instantx, show confirmations for locked transactions (bool, default: true)") + "\n"; strUsage += " -instantxdepth=<n> " + _("Show N confirmations for a successfully locked transaction (0-9999, default: 1)") + "\n"; strUsage += "\n" + _("Block creation options:") + "\n"; strUsage += " -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n"; strUsage += " -blockmaxsize=<n> " + strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE) + "\n"; strUsage += " -blockprioritysize=<n> " + strprintf(_("Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"), DEFAULT_BLOCK_PRIORITY_SIZE) + "\n"; strUsage += "\n" + _("RPC server options:") + "\n"; strUsage += " -server " + _("Accept command line and JSON-RPC commands") + "\n"; strUsage += " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n"; strUsage += " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n"; strUsage += " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 9998 or testnet: 19998)") + "\n"; strUsage += " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n"; strUsage += " -rpcthreads=<n> " + _("Set the number of threads to service RPC calls (default: 4)") + "\n"; strUsage += "\n" + _("RPC SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n"; strUsage += " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n"; strUsage += " -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n"; strUsage += " -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n"; strUsage += " -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)") + "\n"; return strUsage; } struct CImportingNow { CImportingNow() { assert(fImporting == false); fImporting = true; } ~CImportingNow() { assert(fImporting == true); fImporting = false; } }; void ThreadImport(std::vector<boost::filesystem::path> vImportFiles) { RenameThread("darkcoin-loadblk"); // -reindex if (fReindex) { CImportingNow imp; int nFile = 0; while (true) { CDiskBlockPos pos(nFile, 0); FILE *file = OpenBlockFile(pos, true); if (!file) break; LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile); LoadExternalBlockFile(file, &pos); nFile++; } pblocktree->WriteReindexing(false); fReindex = false; LogPrintf("Reindexing finished\n"); // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked): InitBlockIndex(); } // hardcoded $DATADIR/bootstrap.dat filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat"; if (filesystem::exists(pathBootstrap)) { FILE *file = fopen(pathBootstrap.string().c_str(), "rb"); if (file) { CImportingNow imp; filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old"; LogPrintf("Importing bootstrap.dat...\n"); LoadExternalBlockFile(file); RenameOver(pathBootstrap, pathBootstrapOld); } else { LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string()); } } // -loadblock= BOOST_FOREACH(boost::filesystem::path &path, vImportFiles) { FILE *file = fopen(path.string().c_str(), "rb"); if (file) { CImportingNow imp; LogPrintf("Importing blocks file %s...\n", path.string()); LoadExternalBlockFile(file); } else { LogPrintf("Warning: Could not open blocks file %s\n", path.string()); } } } /** Sanity checks * Ensure that Darkcoin is running in a usable environment with all * necessary library support. */ bool InitSanityCheck(void) { if(!ECC_InitSanityCheck()) { InitError("OpenSSL appears to lack support for elliptic curve cryptography. For more " "information, visit https://en.bitcoin.it/wiki/OpenSSL_and_EC_Libraries"); return false; } // TODO: remaining sanity checks, see #4081 return true; } /** Initialize darkcoin. * @pre Parameters should be parsed and config file should be read. */ bool AppInit2(boost::thread_group& threadGroup) { // ********************************************************* Step 1: setup #ifdef _MSC_VER // Turn off Microsoft heap dump noise _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); #endif #if _MSC_VER >= 1400 // Disable confusing "helpful" text message on abort, Ctrl-C _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); #endif #ifdef WIN32 // Enable Data Execution Prevention (DEP) // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008 // A failure is non-critical and needs no further attention! #ifndef PROCESS_DEP_ENABLE // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7), // which is not correct. Can be removed, when GCCs winbase.h is fixed! #define PROCESS_DEP_ENABLE 0x00000001 #endif typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD); PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy"); if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE); // Initialize Windows Sockets WSADATA wsadata; int ret = WSAStartup(MAKEWORD(2,2), &wsadata); if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2) { return InitError(strprintf("Error: Winsock library failed to start (WSAStartup returned error %d)", ret)); } #endif #ifndef WIN32 umask(077); // Clean shutdown on SIGTERM struct sigaction sa; sa.sa_handler = HandleSIGTERM; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGTERM, &sa, NULL); sigaction(SIGINT, &sa, NULL); // Reopen debug.log on SIGHUP struct sigaction sa_hup; sa_hup.sa_handler = HandleSIGHUP; sigemptyset(&sa_hup.sa_mask); sa_hup.sa_flags = 0; sigaction(SIGHUP, &sa_hup, NULL); #if defined (__SVR4) && defined (__sun) // ignore SIGPIPE on Solaris signal(SIGPIPE, SIG_IGN); #endif #endif // ********************************************************* Step 2: parameter interactions if (mapArgs.count("-bind")) { // when specifying an explicit binding address, you want to listen on it // even when -connect or -proxy is specified if (SoftSetBoolArg("-listen", true)) LogPrintf("AppInit2 : parameter interaction: -bind set -> setting -listen=1\n"); } if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { // when only connecting to trusted nodes, do not seed via DNS, or listen by default if (SoftSetBoolArg("-dnsseed", false)) LogPrintf("AppInit2 : parameter interaction: -connect set -> setting -dnsseed=0\n"); if (SoftSetBoolArg("-listen", false)) LogPrintf("AppInit2 : parameter interaction: -connect set -> setting -listen=0\n"); } if (mapArgs.count("-proxy")) { // to protect privacy, do not listen by default if a default proxy server is specified if (SoftSetBoolArg("-listen", false)) LogPrintf("AppInit2 : parameter interaction: -proxy set -> setting -listen=0\n"); } if (!GetBoolArg("-listen", true)) { // do not map ports or try to retrieve public IP when not listening (pointless) if (SoftSetBoolArg("-upnp", false)) LogPrintf("AppInit2 : parameter interaction: -listen=0 -> setting -upnp=0\n"); if (SoftSetBoolArg("-discover", false)) LogPrintf("AppInit2 : parameter interaction: -listen=0 -> setting -discover=0\n"); } if (mapArgs.count("-externalip")) { // if an explicit public IP is specified, do not try to find others if (SoftSetBoolArg("-discover", false)) LogPrintf("AppInit2 : parameter interaction: -externalip set -> setting -discover=0\n"); } if (GetBoolArg("-salvagewallet", false)) { // Rewrite just private keys: rescan to find transactions if (SoftSetBoolArg("-rescan", true)) LogPrintf("AppInit2 : parameter interaction: -salvagewallet=1 -> setting -rescan=1\n"); } // -zapwallettx implies a rescan if (GetBoolArg("-zapwallettxes", false)) { if (SoftSetBoolArg("-rescan", true)) LogPrintf("AppInit2 : parameter interaction: -zapwallettxes=1 -> setting -rescan=1\n"); } // Make sure enough file descriptors are available int nBind = std::max((int)mapArgs.count("-bind"), 1); nMaxConnections = GetArg("-maxconnections", 125); nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0); int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS); if (nFD < MIN_CORE_FILEDESCRIPTORS) return InitError(_("Not enough file descriptors available.")); if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections) nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS; // ********************************************************* Step 3: parameter-to-internal-flags fDebug = !mapMultiArgs["-debug"].empty(); // Special-case: if -debug=0/-nodebug is set, turn off debugging messages const vector<string>& categories = mapMultiArgs["-debug"]; if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end()) fDebug = false; // Check for -debugnet (deprecated) if (GetBoolArg("-debugnet", false)) InitWarning(_("Warning: Deprecated argument -debugnet ignored, use -debug=net")); fBenchmark = GetBoolArg("-benchmark", false); mempool.setSanityCheck(GetBoolArg("-checkmempool", RegTest())); Checkpoints::fEnabled = GetBoolArg("-checkpoints", true); // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS); if (nScriptCheckThreads <= 0) nScriptCheckThreads += boost::thread::hardware_concurrency(); if (nScriptCheckThreads <= 1) nScriptCheckThreads = 0; else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS) nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS; fServer = GetBoolArg("-server", false); fPrintToConsole = GetBoolArg("-printtoconsole", false); fLogTimestamps = GetBoolArg("-logtimestamps", true); setvbuf(stdout, NULL, _IOLBF, 0); #ifdef ENABLE_WALLET bool fDisableWallet = GetBoolArg("-disablewallet", false); #endif if (mapArgs.count("-timeout")) { int nNewTimeout = GetArg("-timeout", 5000); if (nNewTimeout > 0 && nNewTimeout < 600000) nConnectTimeout = nNewTimeout; } // Continue to put "/P2SH/" in the coinbase to monitor // BIP16 support. // This can be removed eventually... const char* pszP2SH = "/P2SH/"; COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH)); // Fee-per-kilobyte amount considered the same as "free" // If you are mining, be careful setting this: // if you set it to zero then // a transaction spammer can cheaply fill blocks using // 1-satoshi-fee transactions. It should be set above the real // cost to you of processing a transaction. if (mapArgs.count("-mintxfee")) { int64_t n = 0; if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0) CTransaction::nMinTxFee = n; else return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"])); } if (mapArgs.count("-minrelaytxfee")) { int64_t n = 0; if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0) CTransaction::nMinRelayTxFee = n; else return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"])); } #ifdef ENABLE_WALLET if (mapArgs.count("-paytxfee")) { if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee)) return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"])); if (nTransactionFee > nHighTransactionFeeWarning) InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.")); } bSpendZeroConfChange = GetArg("-spendzeroconfchange", true); strWalletFile = GetArg("-wallet", "wallet.dat"); #endif // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log // Sanity check if (!InitSanityCheck()) return InitError(_("Initialization sanity check failed. Darkcoin Core is shutting down.")); std::string strDataDir = GetDataDir().string(); #ifdef ENABLE_WALLET // Wallet file must be a plain filename without a directory if (strWalletFile != boost::filesystem::basename(strWalletFile) + boost::filesystem::extension(strWalletFile)) return InitError(strprintf(_("Wallet %s resides outside data directory %s"), strWalletFile, strDataDir)); #endif // Make sure only a single Darkcoin process is using the data directory. boost::filesystem::path pathLockFile = GetDataDir() / ".lock"; FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist. if (file) fclose(file); static boost::interprocess::file_lock lock(pathLockFile.string().c_str()); if (!lock.try_lock()) return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Darkcoin Core is probably already running."), strDataDir)); if (GetBoolArg("-shrinkdebugfile", !fDebug)) ShrinkDebugFile(); LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); LogPrintf("Darkcoin version %s (%s)\n", FormatFullVersion(), CLIENT_DATE); LogPrintf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION)); #ifdef ENABLE_WALLET LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0)); #endif if (!fLogTimestamps) LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime())); LogPrintf("Default data directory %s\n", GetDefaultDataDir().string()); LogPrintf("Using data directory %s\n", strDataDir); LogPrintf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD); std::ostringstream strErrors; if (nScriptCheckThreads) { LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads); for (int i=0; i<nScriptCheckThreads-1; i++) threadGroup.create_thread(&ThreadScriptCheck); } if (mapArgs.count("-masternodepaymentskey")) // masternode payments priv key { if (!masternodePayments.SetPrivKey(GetArg("-masternodepaymentskey", ""))) return InitError(_("Unable to sign masternode payment winner, wrong key?")); if (!sporkManager.SetPrivKey(GetArg("-masternodepaymentskey", ""))) return InitError(_("Unable to sign spork message, wrong key?")); } //ignore masternodes below protocol version nMasternodeMinProtocol = GetArg("-masternodeminprotocol", 70051); int64_t nStart; // ********************************************************* Step 5: verify wallet database integrity #ifdef ENABLE_WALLET if (!fDisableWallet) { LogPrintf("Using wallet %s\n", strWalletFile); uiInterface.InitMessage(_("Verifying wallet...")); if (!bitdb.Open(GetDataDir())) { // try moving the database env out of the way boost::filesystem::path pathDatabase = GetDataDir() / "database"; boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%d.bak", GetTime()); try { boost::filesystem::rename(pathDatabase, pathDatabaseBak); LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string(), pathDatabaseBak.string()); } catch(boost::filesystem::filesystem_error &error) { // failure is ok (well, not really, but it's not worse than what we started with) } // try again if (!bitdb.Open(GetDataDir())) { // if it still fails, it probably means we can't even create the database env string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir); return InitError(msg); } } if (GetBoolArg("-salvagewallet", false)) { // Recover readable keypairs: if (!CWalletDB::Recover(bitdb, strWalletFile, true)) return false; } if (filesystem::exists(GetDataDir() / strWalletFile)) { CDBEnv::VerifyResult r = bitdb.Verify(strWalletFile, CWalletDB::Recover); if (r == CDBEnv::RECOVER_OK) { string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!" " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if" " your balance or transactions are incorrect you should" " restore from a backup."), strDataDir); InitWarning(msg); } if (r == CDBEnv::RECOVER_FAIL) return InitError(_("wallet.dat corrupt, salvage failed")); } // Initialize KeePass Integration keePassInt.init(); } // (!fDisableWallet) #endif // ENABLE_WALLET // ********************************************************* Step 6: network initialization RegisterNodeSignals(GetNodeSignals()); int nSocksVersion = GetArg("-socks", 5); if (nSocksVersion != 4 && nSocksVersion != 5) return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion)); if (mapArgs.count("-onlynet")) { std::set<enum Network> nets; BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) { enum Network net = ParseNetwork(snet); if (net == NET_UNROUTABLE) return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet)); nets.insert(net); } for (int n = 0; n < NET_MAX; n++) { enum Network net = (enum Network)n; if (!nets.count(net)) SetLimited(net); } } CService addrProxy; bool fProxy = false; if (mapArgs.count("-proxy")) { addrProxy = CService(mapArgs["-proxy"], 9050); if (!addrProxy.IsValid()) return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"])); SetProxy(NET_IPV4, addrProxy, nSocksVersion); if (nSocksVersion > 4) { SetProxy(NET_IPV6, addrProxy, nSocksVersion); SetNameProxy(addrProxy, nSocksVersion); } fProxy = true; } // -onion can override normal proxy, -noonion disables tor entirely // -tor here is a temporary backwards compatibility measure if (mapArgs.count("-tor")) printf("Notice: option -tor has been replaced with -onion and will be removed in a later version.\n"); if (!(mapArgs.count("-onion") && mapArgs["-onion"] == "0") && !(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-onion") || mapArgs.count("-tor"))) { CService addrOnion; if (!mapArgs.count("-onion") && !mapArgs.count("-tor")) addrOnion = addrProxy; else addrOnion = mapArgs.count("-onion")?CService(mapArgs["-onion"], 9050):CService(mapArgs["-tor"], 9050); if (!addrOnion.IsValid()) return InitError(strprintf(_("Invalid -onion address: '%s'"), mapArgs.count("-onion")?mapArgs["-onion"]:mapArgs["-tor"])); SetProxy(NET_TOR, addrOnion, 5); SetReachable(NET_TOR); } // see Step 2: parameter interactions for more information about these fNoListen = !GetBoolArg("-listen", true); fDiscover = GetBoolArg("-discover", true); fNameLookup = GetBoolArg("-dns", true); bool fBound = false; if (!fNoListen) { if (mapArgs.count("-bind")) { BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) { CService addrBind; if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false)) return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind)); fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR)); } } else { struct in_addr inaddr_any; inaddr_any.s_addr = INADDR_ANY; fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE); fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE); } if (!fBound) return InitError(_("Failed to listen on any port. Use -listen=0 if you want this.")); } if (mapArgs.count("-externalip")) { BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) { CService addrLocal(strAddr, GetListenPort(), fNameLookup); if (!addrLocal.IsValid()) return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr)); AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL); } } BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"]) AddOneShot(strDest); // ********************************************************* Step 7: load block chain fReindex = GetBoolArg("-reindex", false); // Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/ filesystem::path blocksDir = GetDataDir() / "blocks"; if (!filesystem::exists(blocksDir)) { filesystem::create_directories(blocksDir); bool linked = false; for (unsigned int i = 1; i < 10000; i++) { filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i); if (!filesystem::exists(source)) break; filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1); try { filesystem::create_hard_link(source, dest); LogPrintf("Hardlinked %s -> %s\n", source.string(), dest.string()); linked = true; } catch (filesystem::filesystem_error & e) { // Note: hardlink creation failing is not a disaster, it just means // blocks will get re-downloaded from peers. LogPrintf("Error hardlinking blk%04u.dat : %s\n", i, e.what()); break; } } if (linked) { fReindex = true; } } // cache size calculations size_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20); if (nTotalCache < (nMinDbCache << 20)) nTotalCache = (nMinDbCache << 20); // total cache cannot be less than nMinDbCache else if (nTotalCache > (nMaxDbCache << 20)) nTotalCache = (nMaxDbCache << 20); // total cache cannot be greater than nMaxDbCache size_t nBlockTreeDBCache = nTotalCache / 8; if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", false)) nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB nTotalCache -= nBlockTreeDBCache; size_t nCoinDBCache = nTotalCache / 2; // use half of the remaining cache for coindb cache nTotalCache -= nCoinDBCache; nCoinCacheSize = nTotalCache / 300; // coins in memory require around 300 bytes bool fLoaded = false; while (!fLoaded) { bool fReset = fReindex; std::string strLoadError; uiInterface.InitMessage(_("Loading block index...")); nStart = GetTimeMillis(); do { try { UnloadBlockIndex(); delete pcoinsTip; delete pcoinsdbview; delete pcoinscatcher; delete pblocktree; pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex); pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex); pcoinscatcher = new CCoinsViewErrorCatcher(*pcoinsdbview); pcoinsTip = new CCoinsViewCache(*pcoinscatcher); if (fReindex) pblocktree->WriteReindexing(true); if (!LoadBlockIndex()) { strLoadError = _("Error loading block database"); break; } // If the loaded chain has a wrong genesis, bail out immediately // (we're likely using a testnet datadir, or the other way around). if (!mapBlockIndex.empty() && chainActive.Genesis() == NULL) return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?")); // Initialize the block index (no-op if non-empty database was already loaded) if (!InitBlockIndex()) { strLoadError = _("Error initializing block database"); break; } // Check for changed -txindex state if (fTxIndex != GetBoolArg("-txindex", false)) { strLoadError = _("You need to rebuild the database using -reindex to change -txindex"); break; } uiInterface.InitMessage(_("Verifying blocks...")); if (!VerifyDB(GetArg("-checklevel", 3), GetArg("-checkblocks", 288))) { strLoadError = _("Corrupted block database detected"); break; } } catch(std::exception &e) { if (fDebug) LogPrintf("%s\n", e.what()); strLoadError = _("Error opening block database"); break; } fLoaded = true; } while(false); if (!fLoaded) { // first suggest a reindex if (!fReset) { bool fRet = uiInterface.ThreadSafeMessageBox( strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"), "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT); if (fRet) { fReindex = true; fRequestShutdown = false; } else { LogPrintf("Aborted block database rebuild. Exiting.\n"); return false; } } else { return InitError(strLoadError); } } } // As LoadBlockIndex can take several minutes, it's possible the user // requested to kill the GUI during the last operation. If so, exit. // As the program has not fully started yet, Shutdown() is possibly overkill. if (fRequestShutdown) { LogPrintf("Shutdown requested. Exiting.\n"); return false; } LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart); if (GetBoolArg("-printblockindex", false) || GetBoolArg("-printblocktree", false)) { PrintBlockTree(); return false; } if (mapArgs.count("-printblock")) { string strMatch = mapArgs["-printblock"]; int nFound = 0; for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi) { uint256 hash = (*mi).first; if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0) { CBlockIndex* pindex = (*mi).second; CBlock block; ReadBlockFromDisk(block, pindex); block.BuildMerkleTree(); block.print(); LogPrintf("\n"); nFound++; } } if (nFound == 0) LogPrintf("No blocks matching %s were found\n", strMatch); return false; } // ********************************************************* Step 8: load wallet #ifdef ENABLE_WALLET if (fDisableWallet) { pwalletMain = NULL; LogPrintf("Wallet disabled!\n"); } else { if (GetBoolArg("-zapwallettxes", false)) { uiInterface.InitMessage(_("Zapping all transactions from wallet...")); pwalletMain = new CWallet(strWalletFile); DBErrors nZapWalletRet = pwalletMain->ZapWalletTx(); if (nZapWalletRet != DB_LOAD_OK) { uiInterface.InitMessage(_("Error loading wallet.dat: Wallet corrupted")); return false; } delete pwalletMain; pwalletMain = NULL; } uiInterface.InitMessage(_("Loading wallet...")); nStart = GetTimeMillis(); bool fFirstRun = true; pwalletMain = new CWallet(strWalletFile); DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun); if (nLoadWalletRet != DB_LOAD_OK) { if (nLoadWalletRet == DB_CORRUPT) strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n"; else if (nLoadWalletRet == DB_NONCRITICAL_ERROR) { string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data" " or address book entries might be missing or incorrect.")); InitWarning(msg); } else if (nLoadWalletRet == DB_TOO_NEW) strErrors << _("Error loading wallet.dat: Wallet requires newer version of Darkcoin") << "\n"; else if (nLoadWalletRet == DB_NEED_REWRITE) { strErrors << _("Wallet needed to be rewritten: restart Darkcoin to complete") << "\n"; LogPrintf("%s", strErrors.str()); return InitError(strErrors.str()); } else strErrors << _("Error loading wallet.dat") << "\n"; } if (GetBoolArg("-upgradewallet", fFirstRun)) { int nMaxVersion = GetArg("-upgradewallet", 0); if (nMaxVersion == 0) // the -upgradewallet without argument case { LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST); nMaxVersion = CLIENT_VERSION; pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately } else LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion); if (nMaxVersion < pwalletMain->GetVersion()) strErrors << _("Cannot downgrade wallet") << "\n"; pwalletMain->SetMaxVersion(nMaxVersion); } if (fFirstRun) { // Create new keyUser and set as default key RandAddSeedPerfmon(); CPubKey newDefaultKey; if (pwalletMain->GetKeyFromPool(newDefaultKey)) { pwalletMain->SetDefaultKey(newDefaultKey); if (!pwalletMain->SetAddressBook(pwalletMain->vchDefaultKey.GetID(), "", "receive")) strErrors << _("Cannot write default address") << "\n"; } pwalletMain->SetBestChain(chainActive.GetLocator()); } LogPrintf("%s", strErrors.str()); LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart); RegisterWallet(pwalletMain); CBlockIndex *pindexRescan = chainActive.Tip(); if (GetBoolArg("-rescan", false)) pindexRescan = chainActive.Genesis(); else { CWalletDB walletdb(strWalletFile); CBlockLocator locator; if (walletdb.ReadBestBlock(locator)) pindexRescan = chainActive.FindFork(locator); else pindexRescan = chainActive.Genesis(); } if (chainActive.Tip() && chainActive.Tip() != pindexRescan) { uiInterface.InitMessage(_("Rescanning...")); LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight); nStart = GetTimeMillis(); pwalletMain->ScanForWalletTransactions(pindexRescan, true); LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart); pwalletMain->SetBestChain(chainActive.GetLocator()); nWalletDBUpdated++; } } // (!fDisableWallet) #else // ENABLE_WALLET LogPrintf("No wallet compiled in!\n"); #endif // !ENABLE_WALLET // ********************************************************* Step 9: import blocks // scan for better chains in the block chain database, that are not yet connected in the active best chain CValidationState state; if (!ActivateBestChain(state)) strErrors << "Failed to connect best block"; std::vector<boost::filesystem::path> vImportFiles; if (mapArgs.count("-loadblock")) { BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"]) vImportFiles.push_back(strFile); } threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles)); // ********************************************************* Step 10: setup DarkSend //string strNode = "23.23.186.131"; //CAddress addr; //ConnectNode(addr, strNode.c_str(), true); fMasterNode = GetBoolArg("-masternode", false); if(fMasterNode) { LogPrintf("IS DARKSEND MASTER NODE\n"); strMasterNodeAddr = GetArg("-masternodeaddr", ""); LogPrintf(" addr %s\n", strMasterNodeAddr.c_str()); if(!strMasterNodeAddr.empty()){ CService addrTest = CService(strMasterNodeAddr); if (!addrTest.IsValid()) { return InitError("Invalid -masternodeaddr address: " + strMasterNodeAddr); } } strMasterNodePrivKey = GetArg("-masternodeprivkey", ""); if(!strMasterNodePrivKey.empty()){ std::string errorMessage; CKey key; CPubKey pubkey; if(!darkSendSigner.SetKey(strMasterNodePrivKey, errorMessage, key, pubkey)) { return InitError(_("Invalid masternodeprivkey. Please see documenation.")); } activeMasternode.pubKeyMasternode = pubkey; } else { return InitError(_("You must specify a masternodeprivkey in the configuration. Please see documentation for help.")); } } fEnableDarksend = GetBoolArg("-enabledarksend", false); nDarksendRounds = GetArg("-darksendrounds", 2); if(nDarksendRounds > 16) nDarksendRounds = 16; if(nDarksendRounds < 1) nDarksendRounds = 1; nLiquidityProvider = GetArg("-liquidityprovider", 0); //0-100 if(nLiquidityProvider != 0) { darkSendPool.SetMinBlockSpacing(std::min(nLiquidityProvider,100)*15); fEnableDarksend = true; nDarksendRounds = 99999; } nAnonymizeDarkcoinAmount = GetArg("-anonymizedarkcoinamount", 0); if(nAnonymizeDarkcoinAmount > 999999) nAnonymizeDarkcoinAmount = 999999; if(nAnonymizeDarkcoinAmount < 2) nAnonymizeDarkcoinAmount = 2; bool fEnableInstantX = GetBoolArg("-enableinstantx", true); if(fEnableInstantX){ nInstantXDepth = GetArg("-instantxdepth", 5); if(nInstantXDepth > 60) nInstantXDepth = 60; if(nInstantXDepth < 0) nAnonymizeDarkcoinAmount = 0; } else { nInstantXDepth = 0; } //lite mode disables all Masternode and Darksend related functionality fLiteMode = GetBoolArg("-litemode", false); if(fMasterNode && fLiteMode){ return InitError("You can not start a masternode in litemode"); } LogPrintf("fLiteMode %d\n", fLiteMode); LogPrintf("nInstantXDepth %d\n", nInstantXDepth); LogPrintf("Darksend rounds %d\n", nDarksendRounds); LogPrintf("Anonymize Darkcoin Amount %d\n", nAnonymizeDarkcoinAmount); /* Denominations A note about convertability. Within Darksend pools, each denomination is convertable to another. For example: 1DRK+1000 == (.1DRK+100)*10 10DRK+10000 == (1DRK+1000)*10 */ darkSendDenominations.push_back( (100 * COIN)+100000 ); darkSendDenominations.push_back( (10 * COIN)+10000 ); darkSendDenominations.push_back( (1 * COIN)+1000 ); darkSendDenominations.push_back( (.1 * COIN)+100 ); /* Disabled till we need them darkSendDenominations.push_back( (.01 * COIN)+10 ); darkSendDenominations.push_back( (.001 * COIN)+1 ); */ darkSendPool.InitCollateralAddress(); threadGroup.create_thread(boost::bind(&ThreadCheckDarkSendPool)); // ********************************************************* Step 11: load peers uiInterface.InitMessage(_("Loading addresses...")); nStart = GetTimeMillis(); { CAddrDB adb; if (!adb.Read(addrman)) LogPrintf("Invalid or missing peers.dat; recreating\n"); } LogPrintf("Loaded %i addresses from peers.dat %dms\n", addrman.size(), GetTimeMillis() - nStart); // ********************************************************* Step 12: start node if (!CheckDiskSpace()) return false; if (!strErrors.str().empty()) return InitError(strErrors.str()); RandAddSeedPerfmon(); //// debug print LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size()); LogPrintf("chainActive.Tip()->nHeight = %d\n", chainActive.Height()); #ifdef ENABLE_WALLET LogPrintf("setKeyPool.size() = %u\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0); LogPrintf("mapWallet.size() = %u\n", pwalletMain ? pwalletMain->mapWallet.size() : 0); LogPrintf("mapAddressBook.size() = %u\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0); #endif StartNode(threadGroup); // InitRPCMining is needed here so getwork/getblocktemplate in the GUI debug console works properly. InitRPCMining(); if (fServer) StartRPCThreads(); #ifdef ENABLE_WALLET // Generate coins in the background if (pwalletMain) GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain, GetArg("-genproclimit", -1)); #endif // ********************************************************* Step 13: finished uiInterface.InitMessage(_("Done loading")); #ifdef ENABLE_WALLET if (pwalletMain) { // Add wallet transactions that aren't already in a block to mapTransactions pwalletMain->ReacceptWalletTransactions(); // Run a thread to flush wallet periodically threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile))); } #endif return !fRequestShutdown; }
mit
authbucket/user
src/Pantarei/User/Model/RoleManagerInterface.php
586
<?php /** * This file is part of the pantarei/user package. * * (c) Wong Hoi Sing Edison <hswong3i@pantarei-design.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Pantarei\User\Model; interface RoleManagerInterface extends ModelManagerInterface { public function createRole(); public function deleteRole(RoleInterface $role); public function reloadRole(RoleInterface $role); public function updateRole(RoleInterface $role); public function findRoles(); }
mit
muravjov/fablib
src/o_p.py
4628
#!/usr/bin/env python # coding: utf-8 import os import shutil def join(path, *fname): return os.path.join(path, *fname) def without_ext(fname): # удалить расширение из имени файла/пути return os.path.splitext(fname)[0] def extension(fname): """ В отличие от splitext, точка вначале убирается; если расширения нет вообще (а оно может быть, но при этом пустым, ''), то вернется не '', а None """ ext = os.path.splitext(fname)[1] if ext: assert ext[0] == '.' ext = ext[1:] else: ext = None return ext def exists(path): return os.path.exists(path) def force_makedirs(dir_path): # обертка makedirs из-за ругани при сущ. директории if not exists(dir_path): os.makedirs(dir_path) def split_all(fpath): # просто split(os.sep) неправилен для win32, потому что # c:\\foo должно превращаться в ['c:\\', 'foo'] # (ведь os.path.join("c:", "foo") это "c:foo", и означает # "текущий путь + foo на диске c:", а не абсолютный путь c:\\foo) #return fpath.split(os.sep) res = [] head, tail = os.path.split(fpath) if tail: # для "с:\\", "/" tail == "" if head: # для "ttt" head == "" res = split_all(head) res.append(tail) else: if head: # split() для путей типа "hhh/ggg/" дает единственный вариант с пустым tail, но # при этом работу продолжать нужно #res = [head] res = split_all(head) if (fpath != head) else [head] return res def remove_file(fpath): res = False if os.path.isfile(fpath): res = True os.remove(fpath) return res def del_any_fpath(fpath): if exists(fpath): if not remove_file(fpath): shutil.rmtree(fpath) def for_write(fpath): """ Эта обертка над open() для записи в новый файл, чтобы минимизировать варианты подобных вызовов """ return open(fpath, "wb") def for_text_write(fpath): """ For Python3 we often should open as a text file (like for json, csv.reader, etc) """ return open(fpath, "w") def fix_rights(fpath): # :TRICKY: при выдаче контента через Apache (1gb.ru) последний работает # под отличным от скрипта пользователем, потому надо ему дать права на # чтение; это актуально для файлов, созданных через tempfile.NamedTemporaryFile() # tempfile.mkdtemp(), так как они создаются с маской 0600 и 0700 # (что само по себе правильно для многопользовательской системы и /tmp) add_read_rights = True if add_read_rights: import stat mode = os.stat(fpath).st_mode # если не дать чтение для группы, а для всех дать, то запрет для группы пересилит, # не нужно read_flags = stat.S_IRGRP|stat.S_IROTH os.chmod(fpath, mode | read_flags) import tempfile import contextlib @contextlib.contextmanager def create_named_tmp_file(need_delete=True, suffix="", all_read=False): """ Клиент обязан закрыть файл """ f = tempfile.NamedTemporaryFile(delete=False, suffix=suffix) if all_read: # :KLUDGE: лучше сразу с нужными правами файла создавать => править tempfile.NamedTemporaryFile fix_rights(f.name) # :TRICKY: нам хочется свою инфо хранить assert not("need_delete" in dir(f)) f.need_delete = need_delete try: yield f finally: if f.need_delete: os.remove(f.name) def create_public_tmp_file(): return create_named_tmp_file(all_read=True) def for_all_files(dirname, fnr): for path, dirs, files in os.walk(dirname): for fname in files: full_name = path + '/' + fname fnr(full_name) def src_dst2files(src_fpath, dst_fpath): return contextlib.nested(open(src_fpath), for_write(dst_fpath))
mit
1wheel/scraping
blackout/bin/parse.js
992
var fs = require('fs') var d3 = require('d3') var ƒ = require('forte-f') var queue = require('queue-async') var glob = require('glob') var request = require('request') var _ = require('lodash') var zips = d3.tsv.parse(fs.readFileSync(__dirname + '/zip.tsv', 'utf-8')) glob(__dirname + "/raw-html/*.html", function (er, files) { files.forEach(scrape) fs.writeFileSync(__dirname + '/zips.json', JSON.stringify(zips, null, 2)) }) function scrape(path){ var zipStr = path.slice(-10, -5) var zip = _.findWhere(zips, {zip: zipStr}) console.log(zipStr) var html = fs.readFileSync(path, 'utf-8') if (_.contains(html, 'The U.S. zip code you entered is not within our database.') || _.contains(html, 'We are unable to definitively determine your location.') ){ zip.mlb = [] } else { zip.mlb = html .split('<ul style="margin:7px 0px 0px 17px;">')[1] .split('</ul>')[0] .split('<li>') .map(function(d){ return d.trim() }) .filter(ƒ()) } console.log(zip) }
mit
andest01/trout-maps
src/ui/core/MapboxModule.selectors.js
530
// import { createSelector } from 'reselect' export const mapboxModuleSelector = state => { return state.mapModule.mapModule } export const isMapboxModuleLoadedSelector = state => { return state.mapModule.mapModuleStatus } // const ROOT = '/' // export const isRootPageSelector = createSelector( // [locationSelector], (location) => { // let isRoot = isRootPageByUrl(location.pathname) // return isRoot // } // ) // export const isRootPageByUrl = url => { // let isRoot = url === ROOT // return isRoot // }
mit
dylan-danse/Recyzone
src/AppBundle/Entity/Commune.php
1100
<?php namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Commune * * @ORM\Table(name="commune") * @ORM\Entity(repositoryClass="AppBundle\Repository\CommuneRepository") */ class Commune { /** * @var int * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="name", type="string", length=255) */ private $name; /** * Commune constructor. * @param string $name */ public function __construct($name) { $this->name = $name; } /** * Get id * * @return int */ public function getId() { return $this->id; } /** * Set name * * @param string $name * * @return Commune */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } }
mit
edosgn/colossus-sit
src/JHWEB/SeguridadVialBundle/Repository/SvSenialDemarcacionRepository.php
277
<?php namespace JHWEB\SeguridadVialBundle\Repository; /** * SvSenialDemarcacionRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class SvSenialDemarcacionRepository extends \Doctrine\ORM\EntityRepository { }
mit
Travix-International/frint
packages/frint-react-server/src/renderToString.spec.js
2896
/* eslint-disable import/no-extraneous-dependencies, func-names, react/prop-types */ /* global describe, it */ import React from 'react'; import { expect } from 'chai'; import { createApp } from 'frint'; import { observe, streamProps, Region } from 'frint-react'; import renderToString from './renderToString'; describe('frint-react-server › renderToString', function () { it('is a function', function () { expect(renderToString).to.be.a('function'); }); it('returns HTML output of an App instance', function () { function TestComponent() { return ( <div> <p>Hello World!</p> </div> ); } const TestApp = createApp({ name: 'TestAppname', providers: [ { name: 'component', useValue: TestComponent, }, ], }); const app = new TestApp(); const html = renderToString(app); expect(html).to.contain('>Hello World!</p></div>'); }); it('returns HTML output of an App instance, with observed props', function () { function TestComponent({ name }) { return ( <div> <p>{name}</p> </div> ); } const ObservedTestComponent = observe(function (app) { const defaultProps = { name: app.getName(), }; return streamProps(defaultProps) .get$(); })(TestComponent); const TestApp = createApp({ name: 'TestAppName', providers: [ { name: 'component', useValue: ObservedTestComponent, }, ], }); const app = new TestApp(); const html = renderToString(app); expect(html).to.contain('>TestAppName</p></div>'); }); it('returns HTML output of an App instance, with childs Apps', function () { // root function RootComponent() { return ( <div> <Region name="sidebar" /> </div> ); } const RootApp = createApp({ name: 'RootApp', providers: [ { name: 'component', useValue: RootComponent }, ], }); // apps function App1Component() { return <p>App 1</p>; } const App1 = createApp({ name: 'App1', providers: [ { name: 'component', useValue: App1Component }, ], }); function App2Component() { return <p>App 2</p>; } const App2 = createApp({ name: 'App2', providers: [ { name: 'component', useValue: App2Component }, ], }); // render const rootApp = new RootApp(); // register apps rootApp.registerApp(App1, { regions: ['sidebar'], weight: 10, }); rootApp.registerApp(App2, { regions: ['sidebar2'], weight: 10, }); const string = renderToString(rootApp); // verify expect(string).to.include('>App 1</p>'); expect(string).not.to.include('>App 2</p>'); }); });
mit
Myndale/Simbuino
src/Simbuino.Emulator/HiPerfTimer.cs
1569
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Simbuino.Emulator { // high performance timer used for profiling, code courtesy Daniel Strigl http://www.codeproject.com/Articles/2635/High-Performance-Timer-in-C public class HiPerfTimer { [DllImport("Kernel32.dll")] private static extern bool QueryPerformanceCounter( out long lpPerformanceCount); [DllImport("Kernel32.dll")] private static extern bool QueryPerformanceFrequency( out long lpFrequency); private long startTime, stopTime; private long freq; public double CurrentTime = 0; // Constructor public HiPerfTimer() { startTime = 0; stopTime = 0; if (QueryPerformanceFrequency(out freq) == false) { // high-performance counter not supported throw new Win32Exception(); } } // Start the timer public void Start() { // lets do the waiting threads there work //Thread.Sleep(0); QueryPerformanceCounter(out startTime); stopTime = startTime; this.CurrentTime = stopTime / (double)freq; } // Stop the timer public void Stop() { QueryPerformanceCounter(out stopTime); this.CurrentTime = stopTime / (double)freq; } public void Restart() { this.startTime = this.stopTime; } // Returns the duration of the timer (in seconds) public double Duration { get { return (double)(stopTime - startTime) / (double)freq; } } } }
mit
travismartinjones/Dauber.Azure
Dauber.Azure.Settings/ISettingsBlobStoreSettings.cs
141
using Dauber.Azure.Blob.Contracts; namespace Dauber.Azure.Settings { public interface ISettingsBlobStoreSettings : IBlobSettings {} }
mit
space-wizards/space-station-14
Content.Server/StationEvents/Events/PowerGridCheck.cs
2685
using System.Collections.Generic; using System.Threading; using Content.Server.Power.Components; using JetBrains.Annotations; using Robust.Shared.Audio; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Player; using Robust.Shared.Random; using Timer = Robust.Shared.Timing.Timer; namespace Content.Server.StationEvents.Events { [UsedImplicitly] public sealed class PowerGridCheck : StationEvent { public override string Name => "PowerGridCheck"; public override float Weight => WeightNormal; public override int? MaxOccurrences => 3; public override string StartAnnouncement => Loc.GetString("station-event-power-grid-check-start-announcement"); protected override string EndAnnouncement => Loc.GetString("station-event-power-grid-check-end-announcement"); public override string? StartAudio => "/Audio/Announcements/power_off.ogg"; // If you need EndAudio it's down below. Not set here because we can't play it at the normal time without spamming sounds. protected override float StartAfter => 12.0f; private CancellationTokenSource? _announceCancelToken; private readonly List<EntityUid> _powered = new(); public override void Announce() { base.Announce(); EndAfter = IoCManager.Resolve<IRobustRandom>().Next(60, 120); } public override void Startup() { var entityManager = IoCManager.Resolve<IEntityManager>(); foreach (var component in entityManager.EntityQuery<ApcPowerReceiverComponent>(true)) { component.PowerDisabled = true; _powered.Add(component.Owner); } base.Startup(); } public override void Shutdown() { var entMan = IoCManager.Resolve<IEntityManager>(); foreach (var entity in _powered) { if (entMan.Deleted(entity)) continue; if (entMan.TryGetComponent(entity, out ApcPowerReceiverComponent? powerReceiverComponent)) { powerReceiverComponent.PowerDisabled = false; } } // Can't use the default EndAudio _announceCancelToken?.Cancel(); _announceCancelToken = new CancellationTokenSource(); Timer.Spawn(3000, () => { SoundSystem.Play(Filter.Broadcast(), "/Audio/Announcements/power_on.ogg"); }, _announceCancelToken.Token); _powered.Clear(); base.Shutdown(); } } }
mit
freeman-lab/pixel-grid
util/layout.js
381
function layout (rows, columns, padding, size, aspect) { var grid = [] for (var i = 0; i < rows; i++) { for (var j = 0; j < columns; j++) { var x = -1 + aspect * ((i) * (padding + size) + (padding) + (size / 2)) var y = 1 - ((j) * (padding + size) + (padding) + (size / 2)) grid.push([y, x]) } } return grid.reverse() } module.exports = layout
mit
PhillyNJ/SAMD21
cryptoauthlib/docs/html/search/defines_c.js
109
var searchData= [ ['tbd',['TBD',['../a00179.html#a427c0d9dc4a1052229c8c75a6d126577',1,'atca_basic.h']]] ];
mit
StadGent/laravel_site_opening-hours
database/seeds/DefaultCalendarSeeder.php
210
<?php use Illuminate\Database\Seeder; class DefaultCalendarSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // } }
mit
okgreece/RDFBrowser
resources/themes/obeu/views/layouts/browser_partials/footer.blade.php
244
<footer class="footer"> Powered by <a href='http://github.com/okgreece/RDFBrowser'>RDFBrowser</a>. Developed by <a href="http://www.okfn.gr">OKF GREECE</a>.</strong> {!! trans('theme/browser/footer.aknowledgement') !!} </footer>
mit
Sudei/Anagram-Hero
web/app/Modules/game/game.js
5956
'use strict'; var game = angular.module('anagram_hero.game', [ 'ngRoute', 'anagram_hero.game.round_service', 'anagram_hero.game.anagram_service', 'anagram_hero.game.filters' ]) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/game', { templateUrl : 'Modules/game/game.html', controller : 'GameCtrl', title : 'Game', authenticated: true }); }]) .controller('GameCtrl', ['$rootScope', '$scope', '$window', 'AuthService', 'AnagramService', 'RoundService', function($rootScope, $scope, $window, AuthService, AnagramService, RoundService) { $scope.user = AuthService.getUser(); $scope.game_words = AnagramService.words; $scope.game_score = 0; $scope.default_timer_counter = 40; $scope.guess = ''; $scope.round = {}; $scope.running = false; $scope.reloadRoute = function() { // console.log($window.location); $window.location.reload(); } // Check the pressed value is autorhized by the game $scope.authorizeValue = function(event) { if( $scope.running === true ){ RoundService.authorize(event); }else{ event.preventDefault(); } }; // Check the user entry to calculate score $scope.checkGuess = function(event) { if( $scope.running === true ){ $scope.round = RoundService.score($scope.guess, event); } }; // Check user submit to calculate game score and init new round $scope.checkWord = function(guess) { var isvalid = RoundService.check($scope.guess); if( isvalid && $scope.running === true ){ $scope.game_score += $scope.round.score; // Generate the winning points var round_score_parts = splitNumber($scope.round.score); // Destination point for each winning points var dest = $('.game--page .game--wrapper .game--board .game--board--score').offset(); angular.forEach(round_score_parts, function(round_score_part, key) { var div = angular.element('<div class="win-point">+'+round_score_part+'</div>'); $('.game--round-win-points').append(div); // Calculate a random position in percent to place the win-point var x = Math.floor(Math.random() * 60) + 20; var y = Math.floor(Math.random() * 60) + 20; $(div).css({left:y+'%',top:x+'%', scale: 0}); // Save the origin of this point for moving it to the dest point later var origin = $(div).offset(); $(div).transition({ scale: 1.3, opacity: 1, delay: key * 250 }, 200).delay(550).transition({ opacity: 0, x: dest.left - origin.left, y: dest.top - origin.top}, 500, 'cubic-bezier(.47,.2,.31,.54)', function(){ // $scope.game_score += round_score_part; $('.game--board--score .score').transition({ scale: 1.3 }, 50, function(){ $scope.game_score += round_score_part; }).transition({ scale: 1 }, 50); // Remove element when animation is finished this.remove() }); }); RoundService.init().$promise.then(function(word) { $scope.guess = ''; $scope.round = RoundService.get(); }); }else{ // Error animation $('.game--wrapper').addClass('shake'); setTimeout(function() { $('.game--wrapper').removeClass("shake"); }, 800); } }; // When Times up $rootScope.$on('times-up', function() { $scope.running = false; // Show the wrapper timeout $('.game--page .timeout--wrapper').css({display: 'block'}); // Show the wrapper controls $('.game--page .controls--wrapper').css({display: 'block'}); // Animate the left cartridge $('.game--page .timeout--wrapper .timeout--board .left-background').transition({ left: 0 }, 300, 'cubic-bezier(.65,.01,.72,.22)').transition({ left: '-20%' }, 300, 'cubic-bezier(0,1,.5,1.3)').transition({ left: 0 }, 150).transition({ left: '-5%' }, 300, 'cubic-bezier(0,1,.5,1.3)').transition({ left: 0 }, 50); // Animate the right cartridge $('.game--page .timeout--wrapper .timeout--board .right-background').transition({ right: 0 }, 300, 'cubic-bezier(.65,.01,.72,.22)').transition({ right: '-20%' }, 300, 'cubic-bezier(0,1,.5,1.3)').transition({ right: 0 }, 150).transition({ right: '-5%' }, 300, 'cubic-bezier(0,1,.5,1.3)').transition({ right: 0 }, 50); // Display the timeout text $('.game--page .timeout--wrapper .timeout-text').transition({ delay: 1000, opacity: 1 }, 200); // Display the replay control $('.game--page .controls--wrapper .controls--replay').transition({ delay: 1000, opacity: 1 }, 200); }); var gameInit = function(){ // Init game animations RoundService.init().$promise.then(function(word) { $scope.round = RoundService.get(); $scope.running = true; }); } /** * Splitting a number into integer and decimal portions * Will generate a list of [chunk] random numbers that sum of [sum] * @method function * @param {[type]} sum [description] * @return {[type]} [description] */ var splitNumber = function(sum){ // Number of maximum chunk we want to retrieve var chunk = 7; var splitted = new Array(); while(sum > 0 && chunk > 0) { var part = Math.floor(Math.random() * sum) + 1; chunk--; sum -= part; splitted.push(part); } if (sum != 0) { splitted.push(sum); } return splitted; } gameInit(); }]);
mit
neotext/neotext-wordpress
js/versions/0.4/0.4.1-CiteIt-quote-context.js
17220
/* * Quote-Context JS Library * https://github.com/CiteIt/citeit-jquery * * Copyright 2015-2020, Tim Langeman * http://www.openpolitics.com/tim * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT * * This is a jQuery function that locates all "blockquote" and "q" tags * within an html document and calls the CiteIt.net web service to * locate contextualsnippets about the requested quote. * * The CiteIt.net web service returns a json dictionary and this script * injects the returned contextual data into hidden html elements to be * displayed when the user hovers over or clicks on the cited quote. * * Demo: http://www.CiteIt.net * * Dependencies: * - jQuery: https://jquery.com/ * - Sha256: https://github.com/brillout/forge-sha256/ * - jsVideoUrlParser: https://www.npmjs.com/package/js-video-url-parser * */ var popup_library = "jQuery"; // div in footer than holds injected json data, requires css class to hide var hidden_container = "citeit_container"; var webservice_version_num = "0.4"; // major version number of webservice // Remove anchor from URL var current_page_url = window.location.href.split("#")[0]; jQuery.fn.quoteContext = function() { // Add "before" and "after" sections to quote excerpts // Designed to work for "blockquote" and "q" tags //Setup hidden div to store all quote metadata jQuery(this).each(function(){ // Loop through all the submitted tags (blockquote or q tags) to // see if any have a "cite" attribute if( jQuery(this).attr("cite") ){ var blockcite = jQuery(this); var cited_url = blockcite.attr("cite"); var citing_url = current_page_url; var citing_quote = blockcite.text(); var embed_icon = ""; var embed_html = ""; // Remove Querystring if WordPress Preview if (isWordpressPreview(citing_url)) { citing_url = citing_url.substring(0, citing_url.indexOf("?")); // get citing_url before ? } // Test the URL to see if it is from one of the Supported Media Providers: var media_providers = ["youtube","vimeo","soundcloud"]; var url_provider = ""; console.log("cited_url: " + cited_url); var url_parsed = urlParser.parse(cited_url); if (!(typeof url_parsed === 'undefined')) { if (url_parsed.hasOwnProperty("provider")){ url_provider = url_parsed.provider; } } if (url_provider == "youtube"){ // Generate YouTube Embed URL var embed_url = urlParser.create({ videoInfo: { provider: url_provider, id: url_parsed.id, mediaType: 'video' }, format: 'long', params: { start: url_parsed.params.start } }); // Create Embed iframe embed_icon = "<br /><span class='view_on_youtube'>" + "Expand: Show Video Clip</span>"; embed_html = "<iframe class='youtube' src='" + embed_url + "' width='560' height='315' " + "frameborder='0' allowfullscreen='allowfullscreen'>" + "</iframe>"; } else if (url_provider == "vimeo") { // Create Canonical Embed URL: embed_url = "https://player.vimeo.com/video/" + url_parsed.id; embed_icon = "<br ><span class='view_on_youtube'>" + "Expand: Show Video Clip</span>"; embed_html = "<iframe class='youtube' src='" + embed_url + "' width='640' height='360' " + "frameborder='0' allowfullscreen='allowfullscreen'>" + "</iframe>"; } else if (url_provider == "soundcloud") { // Webservice Query: Get Embed Code $.getJSON('http://soundcloud.com/oembed?callback=?', { format: 'js', url: cited_url, iframe: true }, function(data) { var embed_html = data.html; }); embed_icon = "<br ><span class='view_on_youtube'>" + "Expand: Show SoundCloud Clip</span>"; } // If the quote has a valid 'cite' tag, check to see if its hash is already saved if (cited_url.length > 3){ var tag_type = jQuery(this)[0].tagName.toLowerCase(); var hash_key = quoteHashKey(citing_quote, citing_url, cited_url); console.log(hash_key); var hash_value = forge_sha256(hash_key); console.log(hash_value); var shard = hash_value.substring(0,2); var read_base = "https://read.citeit.net/quote/"; var read_url = read_base.concat("sha256/", webservice_version_num, "/", shard, "/", hash_value, ".json"); var json = null; // See if a json summary of this quote was already created and // uploaded to the content delivery network that hosts the JSON snippets jQuery.ajax({ type: "GET", url: read_url, dataType: "json", success: function(json) { addQuoteToDom(tag_type, json ); console.log("CiteIt Found: " + read_url); console.log(" Quote: " + citing_quote); }, error: function() { console.log("CiteIt Missed: " + read_url); console.log(" Quote: " + citing_quote); } }); // Add Hidden div with context to DOM function addQuoteToDom(tag_type, json ) { if ( tag_type == "q"){ var q_id = "hidden_" + json.sha256; //Add content to a hidden div, so that the popup can later grab it jQuery("#" + hidden_container).append( "<div id='" + q_id + "' class='highslide-maincontent'>.. " + json.cited_context_before + " " + " <strong>" + json.citing_quote + "</strong> " + json.cited_context_after + ".. </p>" + "<p><a href='" + json.cited_url + "' target='_blank'>Read more</a> | " + "<a href='javascript:closePopup(" + q_id + ");'>Close</a> </p></div>"); //Style quote as a link that calls the popup expander: blockcite.wrapInner("<a href='" + blockcite.attr("cite") + "' " + "onclick='return expandPopup(this ,\"" + q_id +"\")' " + " />"); } else if (tag_type == "blockquote"){ //Fill "before" and "after" divs and then quickly hide them blockcite.before("<div id='quote_before_" + json.sha256 + "' class='quote_context'>" + "<blockquote class='quote_context'>" + embed_html + "</a><br />.. " + json.cited_context_before + " .. </blockquote></div>"); blockcite.after("<div id='quote_after_" + json.sha256 + "' class='quote_context'>" + "<blockquote class='quote_context'>" + json.cited_context_after + " ..</blockquote></div>" + "<div class='citeit_source'>" + "<span class='citeit_source_label'>source: </span> " + "<a class='citeit_source_domain' href='" + json.cited_url + "'>" + extractDomain( json.cited_url ) + "</a></div>" ); var context_before = jQuery("#quote_before_" + json.sha256); var context_after = jQuery("#quote_after_" + json.sha256); context_before.hide(); context_after.hide(); //Display arrows if content is found if (json.cited_context_before.length > 0){ context_before.before("<div class='quote_arrows context_up' "+ "id='context_up_" + json.sha256 + "'> " + "<a href=\"javascript:toggleQuote('before', 'quote_before_" + json.sha256 + "');\">&#9650;</a> " + "<a href=\"javascript:toggleQuote('before', 'quote_before_" + json.sha256 + "');\">" + embed_icon + "</a></div>"); } if (json.cited_context_after.length > 0){ context_after.after("<div class='quote_arrows context_down' "+ "id='context_down_" + json.sha256 +"'> " + "<a href=\"javascript:toggleQuote('after', 'quote_after_" + json.sha256 +"');\">&#9660;</a></div>" ); } } // elseif (tag_type == 'blockquote') } // end: function addQuoteToDom } // if url.length is not blank } // if "this" has a "cite" attribute }); // jQuery(this).each(function() { : blockquote, or q tag }; function toggleQuote(section, id){ jQuery("#" + id).fadeToggle(); } function expandPopup(tag, hidden_popup_id){ // Configure jQuery Popup Library jQuery.curCSS = jQuery.css; // Setup Initial Dialog box jQuery("#" + hidden_popup_id).dialog({ autoOpen: false, closeOnEscape: true, closeText: "hide", draggableType: true, resizable: true, width: 400, modal: false, title: "powered by CiteIt.net", hide: { effect: "size", duration: 400 }, show: { effect: "scale", duration: 400 }, }); // Add centering and other settings jQuery("#" + hidden_popup_id).dialog("option", "position", { at: "center center", of: tag} ).dialog("option", "hide", { effect: "size", duration: 400 } ).dialog("option", "show", { effect: "scale", duration: 400 } ).dialog( {"title" : "powered by CiteIt.net"} ).dialog("open" ).blur( ); // Close popup when you click outside of it jQuery(document).mouseup(function(e) { var popupbox = jQuery(".ui-widget-overlay"); if (popupbox.has(e.target).length === 0){ // Uncomment line below to close popup when you click outside it //$("#" + hidden_popup_id).dialog("close"); } }); return false; // Don't follow link } function closePopup(hidden_popup_id){ // assumes jQuery library jQuery(hidden_popup_id).dialog("close"); } function urlWithoutProtocol(url){ // Purpose: Remove http(s):// and trailing slash // Before: https://www.example.com/blog/first-post/ // After: www.example.com/blog/first-post var url_without_trailing_slash = url.replace(/\/$/, ""); var url_without_protocol = url_without_trailing_slash.replace(/^https?\:\/\//i, ""); return url_without_protocol; } function escapeUrl(str){ // This is a list of Unicode character points that should be filtered out from the quote hash // This list should match the webservice settings: // * https://github.com/CiteIt/citeit-webservice/blob/master/app/settings-default.py // - URL_ESCAPE_CODE_POINTS var replace_chars = new Set([ 10, 20, 160 ]); // str = trimRegex(str); // remove whitespace at beginning and end return normalizeText(str, replace_chars); } function escapeQuote(str){ // This is a list of Unicode character points that should be filtered out from the quote hash // This list should match the webservice settings: // * https://github.com/CiteIt/citeit-webservice/blob/master/app/settings-default.py // - TEXT_ESCAPE_CODE_POINTS var replace_chars = new Set([ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 , 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 39 , 96, 160, 173, 699, 700, 701, 702, 703, 712, 713, 714, 715, 716 , 717, 718, 719, 732, 733, 750, 757, 8211, 8212, 8213, 8216, 8217 , 8219, 8220, 8221, 8226, 8203, 8204, 8205, 65279, 8232, 8233, 133 , 5760, 6158, 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, 8200 , 8201, 8202, 8239, 8287, 8288, 12288 ]); return normalizeText(str, replace_chars); } function normalizeText(str, escape_code_points){ /* This javascript function performs the same functionality as the python method: citeit_quote_context.text_convert.escape() It removes an array of symbols from the input str */ var str_return = ''; //default: empty string var input_code_point = -1; var str_array = stringToArray(str); // convert string to array for (idx in str_array){ // Get Unicode Code Point of Current Character chr = str_array[idx]; chr_code = chr.codePointAt(0); input_code_point = chr.codePointAt(0); // Only Include this character if it is not in the supplied set of escape_code_points if(!(escape_code_points.has(input_code_point))){ str_return += chr; // Add this character } } return str_return; } function quoteHashKey(citing_quote, citing_url, cited_url){ // The quote identifier is a sha256 hash of these 3 formatted strings: // citing_quote: "Nothing is more certainly written in the book of fate than that these people are to be free." // citing_url: https://demo.citeit.net/2017/09/17/jefferson-on-emancipation-from-slavery/ // cited_url: https://avalon.law.yale.edu/19th_century/jeffauto.asp var quote_hash = escapeQuote(citing_quote) + "|" + urlWithoutProtocol(escapeUrl(citing_url)) + "|" + urlWithoutProtocol(escapeUrl(cited_url)); return quote_hash; } function quoteHash(citing_quote, citing_url, cited_url){ // The quote identifier is a sha256 hash of the hash key // This key is used to name the JSON file: // quote_hash: e7c117fdd8602d8c7dce3a74fe0d80b650bdf222e3f84e8cbcad476ea8673c4c // JSON URL: https://read.citeit.net/quote/sha256/0.4/e7/e7c117fdd8602d8c7dce3a74fe0d80b650bdf222e3f84e8cbcad476ea8673c4c.json var url_quote_text = quoteHashKey(citing_quote, citing_url, cited_url); var quote_hash = forge_sha256(url_quote_text); // sha256 library:https://github.com/brillout/forge-sha256 return quote_hash; } function extractDomain(url) { // Purpose: remove protocol from url: http(s):// var domain; if (url.indexOf("://") > -1) { domain = url.split("/")[2]; } else { domain = url.split("/")[0]; } //find & remove port number domain = domain.split(":")[0]; return domain; } function isWordpressPreview(citing_url){ // Is the user in WordPress "Preview" mode, while authoring a blog post with TinyMCE Editor // If so, remove the querystring because that prevents the citation from having the correct hash // Example: https://demo.citeit.net/2017/09/17/jefferson-on-emancipation-from-slavery/?preview_id=209&preview_nonce=d73deaada1&_thumbnail_id=-1&preview=true var is_wordpress_preview = false; // Remove Querystring if it exists and matches 3 criteria // Example: ?preview_id=209&preview_nonce=d73deaada1&_thumbnail_id=-1&preview=true if (citing_url.split('?')[1]) { var querystring = citing_url.split('?')[1]; // text after the "?" var url_params = new URLSearchParams(querystring); var preview_id = url_params.get('preview_id'); // integer: 209 var preview_nonce = url_params.get('preview_nonce'); // hex: d73deaada1 var is_preview = url_params.get('preview'); // boolean: true // Only Assume is_wordpress_preview if url matches all three parameters if (is_preview && isInt(preview_id) && isHexadecimal(preview_nonce)) { is_wordpress_preview = true; } } return is_wordpress_preview; //boolean } /******************** Begin: Outside Helper Javascript Libraries ***************************/ function stringToArray(s) { // Purpose: convert string to Array // Credit: Gil Tayar: https://medium.com/@giltayar // GitHub Profile: https://github.com/giltayar // https://medium.com/@giltayar/iterating-over-emoji-characters-the-es6-way-f06e4589516 const retVal = []; for (const ch of s) { retVal.push(ch); } return retVal; } function isInt(value) { // Purpose: Is the input an integer? return boolean // Credit: Davide Pizzolato: https://stackoverflow.com/users/7490904/davide-pizzolato // GitHub Profile: https://github.com/pizzo00 // https://stackoverflow.com/questions/14636536/how-to-check-if-a-variable-is-an-integer-in-javascript return !isNaN(value) && parseInt(Number(value)) == value && !isNaN(parseInt(value, 10)); } function isValidHttpUrl(string) { // Purpose: Test whether string is a URL, returns boolean // Credit: Pavlo: https://stackoverflow.com/users/1092711/pavlo // https://stackoverflow.com/questions/5717093/check-if-a-javascript-string-is-a-url let url; try { url = new URL(string); } catch (_) { return false; } return url.protocol === "http:" || url.protocol === "https:"; } function trimRegex(str){ // Purpose: Backwards-compatible string trim (may not be necessary) // Credit: Jhankar Mahbub: (used for backward compatibility. // GitHub Profile: https://github.com/khan4019/jhankarMahbub.com // Homepage: http://www.jhankarmahbub.com/ // Source: http://stackoverflow.com/questions/10032024/how-to-remove-leading-and-trailing-white-spaces-from-a-given-html-string return str.replace(/^[ ]+|[ ]+$/g,""); } function isHexadecimal(str){ // Credit: https://www.w3resource.com/javascript-exercises/javascript-regexp-exercise-16.php regexp = /^[0-9a-fA-F]+$/; if (regexp.test(str)) { return true; } else { return false; } }
mit
onedata/oneclient
src/events/types/quotaExceeded.cc
974
/** * @file quotaExceeded.cc * @author Krzysztof Trzepla * @copyright (C) 2016 ACK CYFRONET AGH * @copyright This software is released under the MIT license cited in * 'LICENSE.txt' */ #include "quotaExceeded.h" #include "messages.pb.h" #include <sstream> namespace one { namespace client { namespace events { QuotaExceeded::QuotaExceeded(const ProtocolMessage &msg) { for (const auto &spaceId : msg.spaces()) { m_spaces.emplace_back(spaceId); } } StreamKey QuotaExceeded::streamKey() const { return StreamKey::QUOTA_EXCEEDED; } const std::vector<std::string> &QuotaExceeded::spaces() const { return m_spaces; } std::string QuotaExceeded::toString() const { std::stringstream stream; stream << "type: 'QuotaExceeded', spaces: ["; for (const auto &spaceId : m_spaces) { stream << "'" << spaceId << "', "; } stream << "]"; return stream.str(); } } // namespace events } // namespace client } // namespace one
mit
danopia/uberha.us
occupancy/input.js
2142
var spawn = require('child_process').spawn; var http = require('http'); var util = require('util'); var config = require('./../lib/config'); var ddwrt = config.node.occupancy.ddwrt; var routerUrl = util.format('http://%s:%s@%s/Info.live.htm', ddwrt.user, ddwrt.pass, ddwrt.ip); exports.scanWifi = function (cb) { var proc = spawn('/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport', ['en1', 'scan']); var output = ''; proc.stdout.on('data', function (data) { output += data; }).setEncoding('utf8'); proc.on('close', function () { var lines = output.split('\n '); lines.pop(); lines.shift(); var nets = lines.map(function (line) { return line.match(/ +(.+) ([0-9a-f:]+) ([\-0-9]+) +([0-9,+\-]+) +([YN]) +([A-Z0-9\-]+) (.+?) *$/).slice(1,8); }); cb(nets); }); }; exports.getDDWRTstate = function (cb) { http.get(routerUrl, function (res) { if (res.statusCode != 200) { console.log('Router returned code', res.statusCode); return; } var raw = ''; res.on('data', function (chunk) { raw += chunk; }).setEncoding('utf8'); res.on('end', function () { var props = {}; raw.replace(/\n$/, '').split('\n').forEach(function (line) { var match = line.match(/\{([a-z_]+)::(.*)\}/); if (match[2][0] == "'") { props[match[1]] = match[2].substr(1, match[2].length - 2).split("','"); } else { props[match[1]] = match[2]; } }); cb(props); }); }).on('error', function (e) { cb(null); }); }; exports.getStations = function (cb) { exports.getDDWRTstate(function (props) { if (!props) { return cb(null); }; var aw = []; while (props.active_wireless.length) { aw.push(props.active_wireless.splice(0, 9)); } cb(aw); }) }; exports.getMyMac = function (cb) { var proc = spawn('ifconfig', ['en1']); var output = ''; proc.stdout.on('data', function (data) { output += data; }).setEncoding('utf8'); proc.on('close', function () { cb(output.match(/ether ([0-9a-f:]+)/)[1]); }); };
mit
adam3smith/csl-editor
src/cslParser.js
5326
"use strict"; // This converts between the following two formats: // // 1. A *.csl text file. // 2. A JSON object as used by get() and set() in src/Data define(['src/xmlUtility', 'src/debug'], function (CSLEDIT_xmlUtility, debug) { // Recursively generates and returns a CSL style JSON node, converted from the given xmlNode // // nodeIndex.index is the depth-first traversal position of CSL node // it must start at 0, and it will be returned with nodeIndex.index = number of nodes - 1 var jsonNodeFromXml = function (xmlNode, nodeIndex) { var children = [], index, jsonData, childNode, textValue, TEXT_NODE, thisNodeIndex = nodeIndex.index; TEXT_NODE = 3; for (index = 0; index < xmlNode.childNodes.length; index++) { childNode = xmlNode.childNodes[index]; //to be compatible with all Chrome versions and Firefox versions, //we have to combine both conditions: undefined, null if (childNode.localName !== undefined && childNode.localName !== null) { nodeIndex.index++; children.push(jsonNodeFromXml(xmlNode.childNodes[index], nodeIndex)); } else { if (childNode.nodeType === TEXT_NODE && typeof childNode.data !== "undefined" && childNode.data.trim() !== "") { textValue = childNode.data; } } } debug.assert(typeof textValue === "undefined" || children.length === 0, "textValue = " + textValue + " children.length = " + children.length); var attributesList = []; var thisNodeData; if (xmlNode.attributes !== null && xmlNode.attributes.length > 0) { for (index = 0; index < xmlNode.attributes.length; index++) { attributesList.push( { key : xmlNode.attributes.item(index).nodeName, value : xmlNode.attributes.item(index).nodeValue, enabled : true }); } } thisNodeData = { name : xmlNode.localName, attributes : attributesList, cslId : thisNodeIndex, children : children }; if (typeof textValue !== "undefined") { thisNodeData.textValue = textValue; } return thisNodeData; }; var generateIndent = function (indentAmount) { var index, result = ""; for (index = 0; index < indentAmount; index++) { result += " "; } return result; }; // Recursively generates and returns an XML string from the given jsonData var xmlNodeFromJson = function (jsonData, indent, fullClosingTags) { var attributesString = "", xmlString, index, innerString; if (jsonData.attributes.length > 0) { for (index = 0; index < jsonData.attributes.length; index++) { if (jsonData.attributes[index].enabled) { // TODO: the key probably shouldn't have characters needing escaping anyway, // should not allow to input them in the first place attributesString += " " + CSLEDIT_xmlUtility.htmlEscape(jsonData.attributes[index].key) + '="' + CSLEDIT_xmlUtility.htmlEscape(jsonData.attributes[index].value) + '"'; } } } xmlString = generateIndent(indent); if (typeof jsonData.textValue !== "undefined") { xmlString += "<" + jsonData.name + attributesString + ">"; xmlString += CSLEDIT_xmlUtility.htmlEscape(jsonData.textValue) + "</" + CSLEDIT_xmlUtility.htmlEscape(jsonData.name) + ">\n"; } else { xmlString += "<" + jsonData.name + attributesString; innerString = ""; if (typeof jsonData.children !== "undefined" && jsonData.children.length > 0) { for (index = 0; index < jsonData.children.length; index++) { innerString += xmlNodeFromJson(jsonData.children[index], indent + 1, fullClosingTags); } } if (innerString !== "") { xmlString += ">\n" + innerString + generateIndent(indent) + "</" + CSLEDIT_xmlUtility.htmlEscape(jsonData.name) + ">\n"; } else if (fullClosingTags) { xmlString += "></" + jsonData.name + ">\n"; } else { xmlString += "/>\n"; } } return xmlString; }; // Returns a JSON representation of the CSL 'style' node in the given xmlData string var cslDataFromCslCode = function (xmlData) { var parser = new DOMParser(), xmlDoc = parser.parseFromString(xmlData, "application/xml"), errors; errors = xmlDoc.getElementsByTagName('parsererror'); debug.assertEqual(errors.length, 0, "xml parser error"); var styleNode = xmlDoc.childNodes[0]; debug.assertEqual(styleNode.localName, "style", "Invalid style - no style node"); var jsonData = jsonNodeFromXml(styleNode, { index: 0 }); return jsonData; }; // Returns a CSL style code string // // - jsonData - the CSL 'style' node JSON representation // - comment - an optional comment string to insert after the 'style' element // - fullClosingTags - use separate closing tags (e.g. <link></link> instead of <link/>) var cslCodeFromCslData = function (jsonData, comment /* optional */, fullClosingTags /* optional */) { var cslXml = '<?xml version="1.0" encoding="utf-8"?>\n', lines, lineIndex; cslXml += xmlNodeFromJson(jsonData, 0, fullClosingTags); if (typeof(comment) === "string") { lines = cslXml.split("\n"); // comment needs to go on line no. 3, after the style node lines.splice(2, 0, "<!-- " + comment + " -->"); cslXml = lines.join("\n"); } return cslXml; }; // public: return { cslDataFromCslCode : cslDataFromCslCode, cslCodeFromCslData : cslCodeFromCslData }; });
mit
JohnBat26/league_tutorial
src/app/club/club.spec.js
1463
/** * Unit tests for the club functionality */ describe( 'Clubs list controller', function() { var scope, httpBackend; //mock Application to allow us to inject our own dependencies beforeEach(angular.mock.module('league')); //mock the controller for the same reason and include $rootScope and $controller beforeEach(angular.mock.inject(function($rootScope, $controller, _$httpBackend_ ){ //create an empty scope scope = $rootScope.$new(); scope.httpBackend = _$httpBackend_; scope.httpBackend.expect('GET', '../clubs.json').respond([ {"contact_officer":"Officer 1","created_at":"2012-02-02T00:00:00Z","date_created":"2012-01-01T00:00:00Z","id":1,"name":"Club 1","updated_at":"2012-03-03T00:00:00Z"}, {"contact_officer":"Officer 2","created_at":"2012-02-02T00:00:00Z","date_created":"2012-01-01T00:00:00Z","id":2,"name":"Club 2","updated_at":"2012-03-03T00:00:00Z"}]); //declare the controller and inject our empty scope $controller('ClubsCtrl', {$scope: scope}); })); // tests start here it('Has two clubs defined', function(){ scope.$digest(); scope.httpBackend.flush(); expect(scope.clubs.length).toEqual(2); }); it('First club\'s contact officer is as expected', function(){ scope.$digest(); scope.httpBackend.flush(); expect(scope.clubs[0].contact_officer).toEqual('Officer 1'); }); });
mit
bfleyshe/ProjectAttitude
ProjectAttitude/app/src/main/java/com/projectattitude/projectattitude/Activities/ViewProfileActivity.java
19205
/* * MIT License * * Copyright (c) 2017 CMPUT301W17T12 * Authors rsauveho vuk bfleyshe henrywei cs3 * * 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 com.projectattitude.projectattitude.Activities; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.util.Base64; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.projectattitude.projectattitude.Adapters.MoodMainAdapter; import com.projectattitude.projectattitude.Controllers.ElasticSearchRequestController; import com.projectattitude.projectattitude.Controllers.ElasticSearchUserController; import com.projectattitude.projectattitude.Controllers.UserController; import com.projectattitude.projectattitude.Objects.FollowRequest; import com.projectattitude.projectattitude.Objects.Mood; import com.projectattitude.projectattitude.Objects.User; import com.projectattitude.projectattitude.R; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.concurrent.ExecutionException; /** * This is the profile page of the user. It shows the name of the user, as well as the portrait, * followed by the user's most recent mood. From here, the user can add moods to follow */ public class ViewProfileActivity extends AppCompatActivity { protected ArrayList<Mood> recentMoodList = new ArrayList<Mood>(); protected ArrayList<Mood> followingMoodList = new ArrayList<Mood>(); private UserController userController = UserController.getInstance(); private MoodMainAdapter recentMoodAdapter; private ArrayAdapter<String> followUserAdapter; private ArrayAdapter<String> followedUserAdapter; private Button searchButton; private Button removeButton; private EditText searchBar; private TextView nameView; private ListView recentMoodView; // refers to user's most recent mood private ListView followUserList; private ListView followedUserList; private ImageView image; private Activity thisActivity = this; String s = ""; final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1; private User user = userController.getActiveUser();; /** * Initial set up on creation including setting up references, adapters, and readying the search * button. * @param savedInstanceState */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_profile); searchBar = (EditText) findViewById(R.id.searchBar); searchButton = (Button) findViewById(R.id.searchButton); removeButton = (Button) findViewById(R.id.removeButton); image = (ImageView) findViewById(R.id.profileImage); nameView = (TextView) findViewById(R.id.profileUname); recentMoodView = (ListView) findViewById(R.id.latestMood); followUserList = (ListView) findViewById(R.id.followList); followedUserList = (ListView) findViewById(R.id.followedList); recentMoodAdapter = new MoodMainAdapter(this, recentMoodList); recentMoodView.setAdapter(recentMoodAdapter); user = userController.getActiveUser(); followUserAdapter = new ArrayAdapter<String>(this, R.layout.list_item, user.getFollowList()); followedUserAdapter = new ArrayAdapter<String>(this, R.layout.list_item,user.getFollowedList()); followUserList.setAdapter(followUserAdapter); followedUserList.setAdapter(followedUserAdapter); searchButton.setOnClickListener(new View.OnClickListener() { // adding a new user to following list @Override public void onClick(View v) { String followingName = searchBar.getText().toString(); User followedUser = new User(); followedUser.setUserName(followingName); if (followingName.equals("")) { // no username entered to search for searchBar.requestFocus(); // search has been canceled } else { if(isNetworkAvailable()){ ElasticSearchUserController.GetUserTask getUserTask = new ElasticSearchUserController.GetUserTask(); try{ if (getUserTask.execute(followedUser.getUserName()).get() == null){ Log.d("Error", "User did not exist"); Toast.makeText(ViewProfileActivity.this, "User not found.", Toast.LENGTH_SHORT).show(); } else { Log.d("Error", "User did exist"); //grab user from db and add to following list getUserTask = new ElasticSearchUserController.GetUserTask(); try { followedUser = getUserTask.execute(followingName).get(); if(followedUser != null){ // user exists if(followedUser.getUserName().equals(user.getUserName())){ Toast.makeText(ViewProfileActivity.this, "You cannot be friends with yourself. Ever", Toast.LENGTH_SHORT).show(); } else{ if(user.getFollowList().contains(followedUser.getUserName())){ Toast.makeText(ViewProfileActivity.this, "You're already following that user.", Toast.LENGTH_SHORT).show(); } else{// user not already in list //check if request between users already exists in database boolean isContained = false; ArrayList<FollowRequest> requests = followedUser.getRequests(); for(int i = 0; i < followedUser.getRequests().size(); i++){ //Checks if request already exists if(requests.get(i).getRequester().equals(user.getUserName()) && requests.get(i).getRequestee().equals(followedUser.getUserName())){ isContained = true; break; } } if(!isContained){ //request doesn't exists - not sure why .get always returns an filled array or empty array followedUser.getRequests().add(new FollowRequest(user.getUserName(), followedUser.getUserName())); ElasticSearchRequestController.UpdateRequestsTask updateRequestsTask = new ElasticSearchRequestController.UpdateRequestsTask(); updateRequestsTask.execute(followedUser); Toast.makeText(ViewProfileActivity.this, "Request sent!", Toast.LENGTH_SHORT).show(); }else{ // request exists Toast.makeText(ViewProfileActivity.this, "Request already exists.", Toast.LENGTH_SHORT).show(); } } } } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } else{ Toast.makeText(ViewProfileActivity.this, "Must be connected to internet to search for users!", Toast.LENGTH_LONG).show(); } } } }); //On-click for removeButton removeButton.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ String followingName = searchBar.getText().toString(); if (followingName.equals("")) { // no username entered to search for searchBar.requestFocus(); // search has been canceled } else { if(isNetworkAvailable()){ if (!user.getFollowList().contains(followingName)){ //If user not in following list Log.d("Error", "Invalid user."); Toast.makeText(ViewProfileActivity.this, "Invalid user. User not found.", Toast.LENGTH_SHORT).show(); } else { Log.d("Error", "Followed User exists"); setResult(RESULT_OK); //remove followedList of who user is following try{ ElasticSearchUserController.GetUserTask getUserTask = new ElasticSearchUserController.GetUserTask(); User followedUser = getUserTask.execute(followingName).get(); if(followedUser != null){ //Remove followee and update database followedUser.getFollowedList().remove(user.getUserName()); ElasticSearchUserController.UpdateUserRequestFollowedTask updateUserRequestFollowedTask = new ElasticSearchUserController.UpdateUserRequestFollowedTask(); updateUserRequestFollowedTask.execute(followedUser); } }catch(Exception e){ e.printStackTrace(); } //user exists --> delete follower and update database user.removeFollow(followingName); ElasticSearchUserController.UpdateUserRequestTask updateUserRequestTask = new ElasticSearchUserController.UpdateUserRequestTask(); updateUserRequestTask.execute(user); Toast.makeText(ViewProfileActivity.this, "Followed user has been removed!", Toast.LENGTH_SHORT).show(); followUserAdapter.notifyDataSetChanged(); } } else{ Toast.makeText(ViewProfileActivity.this, "Must be connected to internet to remove user!", Toast.LENGTH_LONG).show(); } } } }); //If image exists in user, set image if(user.getPhoto() != null && user.getPhoto().length() > 0){ //decode base64 image stored in User byte[] imageBytes = Base64.decode(user.getPhoto(), Base64.DEFAULT); Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length); image.setImageBitmap(decodedImage); } /** * This handles when a user clicks on their most recent mood, taking them to the view mood screen */ recentMoodView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intentView = new Intent(ViewProfileActivity.this, ViewMoodActivity.class); intentView.putExtra("mood", recentMoodList.get(position)); startActivityForResult(intentView, 1); } }); //Adjusted from http://codetheory.in/android-pick-select-image-from-gallery-with-intents/ //on 3/29/17 /** * This handles when the user clicks on their image */ image.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Check if user has permission to get picture from gallery if(ContextCompat.checkSelfPermission(thisActivity, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){ ActivityCompat.requestPermissions(thisActivity, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE); }else{ //user already has permission Intent intent = new Intent(); // Show only images, no videos or anything else intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); // Always show the chooser (if there are multiple options available) startActivityForResult(Intent.createChooser(intent, "Select Picture"),1); } } }); } /** * This method is called as soon as the activity starts, */ @Override protected void onStart(){ super.onStart(); //Profile setup nameView.setText(userController.getActiveUser().getUserName()); //getting the name of the user User user = (User) getIntent().getSerializableExtra("user"); Mood userMood = (Mood) getIntent().getSerializableExtra("mood"); // getting user mood if(userMood != null && recentMoodList.size() == 0){ recentMoodList.add(userMood); recentMoodAdapter.notifyDataSetChanged(); } //adding recent moods for each followed person //TODO Check if the user has a profile pic, if so set image } private boolean isNetworkAvailable() { // checks if network available for searching database ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) { Uri uri = data.getData(); try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri); // Log.d(TAG, String.valueOf(bitmap)); Log.d("PhotoBytes1", bitmap.getByteCount() + ""); Log.d("PhotoHeight1", bitmap.getHeight() + ""); Log.d("PhotoHeight1", bitmap.getWidth() + ""); //if greater then byte threshold, compress if (bitmap.getByteCount() > 65536) { while(bitmap.getByteCount() > 65536){ //Keep compressing photo until photo is small enough bitmap = Bitmap.createScaledBitmap(bitmap, (bitmap.getWidth() / 2), (bitmap.getHeight() / 2), false); Log.d("imageCompressed", bitmap.getByteCount() + ""); } } ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] byteArray = stream.toByteArray(); s = Base64.encodeToString(byteArray, Base64.DEFAULT); image.setImageBitmap(bitmap); user.setPhoto(s); //TODO Update the database } catch (IOException e) { e.printStackTrace(); } //TODO: Update user with profile picture userController.getActiveUser().setPhoto(s); ElasticSearchUserController.UpdateUserPictureTask updateUserPictureTask = new ElasticSearchUserController.UpdateUserPictureTask(); updateUserPictureTask.execute(UserController.getInstance().getActiveUser()); } } //When return from requesting read external storage permissions @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch(requestCode){ case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: //If requesting gallery permissions if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ //If result cancelled, grantResults is empty //If permissions granted, activate image button again image.performClick(); } } } }
mit
JaniAnttonen/BierCell
config/env/test.js
1271
'use strict'; module.exports = { db: 'mongodb://localhost/bier-cell-test', port: 3001, app: { title: 'Bier Cell - Test Environment' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: '/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: '/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: '/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: '/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: '/auth/github/callback' }, mailer: { from: process.env.MAILER_FROM || 'MAILER_FROM', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } } } };
mit
dayse/gesplan
src/xfuzzy/xfsg/XfsgBlock.java
3566
//--------------------------------------------------------------------------------// // COPYRIGHT NOTICE // //--------------------------------------------------------------------------------// // Copyright (c) 2012, Instituto de Microelectronica de Sevilla (IMSE-CNM) // // // // All rights reserved. // // // // Redistribution and use in source and binary forms, with or without // // modification, are permitted provided that the following conditions are met: // // // // * Redistributions of source code must retain the above copyright notice, // // this list of conditions and the following disclaimer. // // // // * Redistributions in binary form must reproduce the above copyright // // notice, this list of conditions and the following disclaimer in the // // documentation and/or other materials provided with the distribution. // // // // * Neither the name of the IMSE-CNM nor the names of its contributors may // // be used to endorse or promote products derived from this software // // without specific prior written permission. // // // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE // // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // //--------------------------------------------------------------------------------// package xfuzzy.xfsg; import javax.swing.Box; import javax.swing.JCheckBox; /** * Interfaz que representa a los componente que pueden aparecer en un sistema * difuso (bases de reglas y bloques crisp) * * @author Jesús Izquierdo Tena */ public interface XfsgBlock { // gerera el texto del fichero .m para los FLCs public void generaM(JCheckBox include); // genera el texto del fichero .m para los bloques crisp public void generaM(); public void generaMdl(); public void generaTxt(); public Box gui(); public void setoutputs(int outputs); public void setinputs(int inputs); public void setname(String name); public String getMdl(); public String getTxt(); public int getoutputs(); public int getinputs(); public String getname(); }
mit
snitko/straight-server
spec/lib/orders_controller_spec.rb
10996
require 'spec_helper' RSpec.describe StraightServer::OrdersController do before(:each) do DB.run("DELETE FROM orders") @gateway = gateway = StraightServer::Gateway.find_by_id(2) allow(gateway).to receive_message_chain("address_provider.takes_fees?").and_return(false) allow(gateway).to receive_message_chain("address_provider.new_address").and_return("address#{gateway.last_keychain_id+1}") allow(gateway).to receive(:fetch_transactions_for).with(anything).and_return([]) allow(gateway).to receive(:send_callback_http_request) end describe "create action" do it "creates an order and renders its attrs in json" do allow(StraightServer::Thread).to receive(:new) # ignore periodic status checks, we're not testing it here send_request "POST", '/gateways/2/orders', amount: 10 expect(response).to render_json_with(status: 0, amount: 10, address: "address1", tid: nil, id: :anything, keychain_id: @gateway.last_keychain_id, last_keychain_id: @gateway.last_keychain_id) end it "renders 409 error when an order cannot be created due to invalid amount" do send_request "POST", '/gateways/2/orders', amount: 0 expect(response[0]).to eq(409) expect(response[2]).to eq("Invalid order: amount cannot be nil and should be more than 0") end it "renders 409 error when an order cannot be created due to other validation errors" do send_request "POST", '/gateways/2/orders', amount: 1, description: 'A'*256 expect(response[0]).to eq(409) expect(response[2]).to eq("Invalid order: description should be shorter than 256 characters") end it "starts tracking the order status in a separate thread" do order_mock = double("order mock") expect(order_mock).to receive(:start_periodic_status_check) expect(order_mock).to receive(:payment_id).and_return('blabla') allow(order_mock).to receive(:to_h).and_return({}) expect(@gateway).to receive(:create_order).and_return(order_mock) send_request "POST", '/gateways/2/orders', amount: 10 end it "passes data and callback_data param to Order which then saves it serialized" do allow(StraightServer::Thread).to receive(:new) # ignore periodic status checks, we're not testing it here send_request "POST", '/gateways/2/orders', amount: 10, data: { hello: 'world' }, callback_data: 'some random data' expect(StraightServer::Order.last.data.hello).to eq('world') expect(StraightServer::Order.last.callback_data).to eq('some random data') end it "renders 503 page when the gateway is inactive" do @gateway.active = false send_request "POST", '/gateways/2/orders', amount: 1 expect(response[0]).to eq(503) expect(response[2]).to eq("The gateway is inactive, you cannot create order with it") @gateway.active = true end it "finds gateway using hashed_id" do allow(StraightServer::Thread).to receive(:new) send_request "POST", "/gateways/#{@gateway.id}/orders", amount: 10 end it "warns about a deprecated order_id param" do send_request "POST", "/gateways/#{@gateway.id}/orders", amount: 10, order_id: 1 expect(response[2]).to eq("Error: order_id is no longer a valid param. Use keychain_id instead and consult the documentation.") end it 'limits creation of orders without signature' do new_config = StraightServer::Config.clone new_config.throttle = {requests_limit: 1, period: 1} stub_const 'StraightServer::Config', new_config allow(StraightServer::Thread).to receive(:new) send_request "POST", '/gateways/2/orders', amount: 10 expect(response).to render_json_with(status: 0, amount: 10, address: "address1", tid: nil, id: :anything, keychain_id: @gateway.last_keychain_id, last_keychain_id: @gateway.last_keychain_id) send_request "POST", '/gateways/2/orders', amount: 10 expect(response).to eq [429, {}, "Too many requests, please try again later"] @gateway1 = StraightServer::Gateway.find_by_id(1) @gateway1.check_signature = true 5.times do |i| i += 1 send_signed_request @gateway1, "POST", '/gateways/1/orders', amount: 10, keychain_id: i expect(response[0]).to eq 200 expect(response).to render_json_with(status: 0, amount: 10, tid: nil, id: :anything, keychain_id: i, last_keychain_id: i) end end it "warns you about the use of callback_data instead of data" do allow(StraightServer::Thread).to receive(:new) send_request "POST", '/gateways/2/orders', amount: 10, data: "I meant this to be callback_data" expect(response).to render_json_with(WARNING: "Maybe you meant to use callback_data? The API has changed now. Consult the documentation.") end end describe "show action" do before(:each) do @order_mock = double('order mock') allow(@order_mock).to receive(:status).and_return(2) allow(@order_mock).to receive(:to_json).and_return("order json mock") end it "renders json info about an order if it is found" do allow(@order_mock).to receive(:status_changed?).and_return(false) expect(StraightServer::Order).to receive(:[]).with(1).and_return(@order_mock) send_request "GET", '/gateways/2/orders/1' expect(response).to eq([200, {}, "order json mock"]) end it "saves an order if status is updated" do allow(@order_mock).to receive(:status_changed?).and_return(true) expect(@order_mock).to receive(:save) expect(StraightServer::Order).to receive(:[]).with(1).and_return(@order_mock) send_request "GET", '/gateways/2/orders/1' expect(response).to eq([200, {}, "order json mock"]) end it "renders 404 if order is not found" do expect(StraightServer::Order).to receive(:[]).with(1).and_return(nil) send_request "GET", '/gateways/2/orders/1' expect(response).to eq([404, {}, "GET /gateways/2/orders/1 Not found"]) end it "finds order by payment_id" do allow(@order_mock).to receive(:status_changed?).and_return(false) expect(StraightServer::Order).to receive(:[]).with(:payment_id => 'payment_id').and_return(@order_mock) send_request "GET", '/gateways/2/orders/payment_id' expect(response).to eq([200, {}, "order json mock"]) end end describe "websocket action" do before(:each) do StraightServer::GatewayModule.class_variable_set(:@@websockets, { @gateway.id => {} }) @ws_mock = double("websocket mock") @order_mock = double("order mock") allow(@ws_mock).to receive(:rack_response).and_return("ws rack response") [:id, :gateway=, :save, :to_h, :id=].each { |m| allow(@order_mock).to receive(m) } allow(@ws_mock).to receive(:on) allow(Faye::WebSocket).to receive(:new).and_return(@ws_mock) end it "returns a websocket connection" do allow(@order_mock).to receive(:status).and_return(0) allow(StraightServer::Order).to receive(:[]).with(1).and_return(@order_mock) send_request "GET", '/gateways/2/orders/1/websocket' expect(response).to eq("ws rack response") end it "returns 403 when socket already exists" do allow(@order_mock).to receive(:status).and_return(0) allow(StraightServer::Order).to receive(:[]).with(1).twice.and_return(@order_mock) send_request "GET", '/gateways/2/orders/1/websocket' send_request "GET", '/gateways/2/orders/1/websocket' expect(response).to eq([403, {}, "Someone is already listening to that order"]) end it "returns 403 when order has is completed (status > 1 )" do allow(@order_mock).to receive(:status).and_return(2) allow(StraightServer::Order).to receive(:[]).with(1).and_return(@order_mock) send_request "GET", '/gateways/2/orders/1/websocket' expect(response).to eq([403, {}, "You cannot listen to this order because it is completed (status > 1)"]) end it "finds order by payment_id" do allow(@order_mock).to receive(:status).and_return(0) expect(StraightServer::Order).to receive(:[]).with(:payment_id => 'payment_id').and_return(@order_mock) send_request "GET", '/gateways/2/orders/payment_id/websocket' expect(response).to eq("ws rack response") end end describe "cancel action" do it "cancels new order" do allow(StraightServer::Thread).to receive(:new) send_request "POST", '/gateways/2/orders', amount: 1 payment_id = JSON.parse(response[2])['payment_id'] send_request "POST", "/gateways/2/orders/#{payment_id}/cancel" expect(response[0]).to eq 200 end it "requires signature to cancel signed order" do allow(StraightServer::Thread).to receive(:new) @gateway1 = StraightServer::Gateway.find_by_id(1) @gateway1.check_signature = true @order_mock = double('order mock') allow(@order_mock).to receive(:status).with(reload: true) allow(@order_mock).to receive(:status_changed?).and_return(false) allow(@order_mock).to receive(:cancelable?).and_return(true) expect(@order_mock).to receive(:cancel) allow(StraightServer::Order).to receive(:[]).and_return(@order_mock) send_request "POST", "/gateways/1/orders/payment_id/cancel" expect(response).to eq [409, {}, 'X-Nonce is invalid: nil'] send_signed_request @gateway1, "POST", "/gateways/1/orders/payment_id/cancel" expect(response[0]).to eq 200 end it "do not cancel orders with status != new" do @order_mock = double('order mock') allow(@order_mock).to receive(:status).with(reload: true) allow(@order_mock).to receive(:status_changed?).and_return(true) expect(@order_mock).to receive(:save) allow(@order_mock).to receive(:cancelable?).and_return(false) allow(StraightServer::Order).to receive(:[]).and_return(@order_mock) send_request "POST", "/gateways/2/orders/payment_id/cancel" expect(response).to eq [409, {}, "Order is not cancelable"] end end it 'return last_keychain_id' do lk_id = 123 @gateway = StraightServer::Gateway.find_by_id(1) @gateway.last_keychain_id = lk_id @gateway.save send_request "GET", '/gateway/1/last_keychain_id' expect(response).to render_json_with(gateway_id: @gateway.id, last_keychain_id: lk_id) end def send_request(method, path, params={}) env = Hashie::Mash.new('REQUEST_METHOD' => method, 'REQUEST_PATH' => path, 'params' => params) @controller = StraightServer::OrdersController.new(env) end def send_signed_request(gateway, method, path, params={}) env = Hashie::Mash.new('REQUEST_METHOD' => method, 'REQUEST_PATH' => path, 'params' => params, 'HTTP_X_NONCE' => (Time.now.to_f * 1e6).to_i) env['HTTP_X_SIGNATURE'] = StraightServer::SignatureValidator.new(gateway, env).signature @controller = StraightServer::OrdersController.new(env) end def response @controller.response end end
mit
wromero/mentornotas
src/Jazzyweb/AulasMentor/NotasBackendBundle/Admin/TarifaAdmin.php
1096
<?php namespace Jazzyweb\AulasMentor\NotasBackendBundle\Admin; use Sonata\AdminBundle\Admin\Admin; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Datagrid\DatagridMapper; use Sonata\AdminBundle\Validator\ErrorElement; use Sonata\AdminBundle\Form\FormMapper; class TarifaAdmin extends Admin { protected function configureFormFields(FormMapper $formMapper) { $formMapper ->add('nombre') ->add('periodo') ->add('precio') ->add('validoDesde') ->add('validoHasta') ; } protected function configureDatagridFilters(DatagridMapper $datagridMapper) { $datagridMapper ->add('nombre') ->add('periodo') ->add('precio') ; } protected function configureListFields(ListMapper $listMapper) { $listMapper ->addIdentifier('nombre') ->add('periodo') ->add('precio') ->add('validoDesde') ->add('validoHasta') ; } public function validate(ErrorElement $errorElement, $object) { } }
mit
hasaki/ExpressiveData
ExpressiveData.Sample/Models/Repositories/SampleDataRepository.cs
2546
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; namespace ExpressiveData.Sample.Models.Repositories { public abstract class SampleDataRepository { protected void ExecuteQuery<TModel>(string sql, IEnumerable<SqlParameter> parameters, Action<IExpressiveReader<TModel>> callback) { using (var cmd = GetCommand(sql, parameters)) { cmd.Connection.Open(); using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)) { var expressive = reader.GetExpressive(); expressive.ReadResultSet(callback); } } } protected IEnumerable<TModel> ExecuteQuery<TModel>(string sql, IEnumerable<SqlParameter> parameters, Func<IExpressiveReader<TModel>, TModel> callback) { using (var cmd = GetCommand(sql, parameters)) { cmd.Connection.Open(); using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)) { var expressive = reader.GetExpressive(); return expressive.GetModelsForResultSet(callback); } } } protected async Task ExecuteQueryAsync<TModel>(string sql, IEnumerable<SqlParameter> parameters, Func<IExpressiveReaderAsync<TModel>, Task> callback) { using (var cmd = GetCommand(sql, parameters)) { await cmd.Connection.OpenAsync(); using (var reader = await cmd.ExecuteReaderAsync(CommandBehavior.CloseConnection)) { var expressive = reader.GetExpressive(); await expressive.ReadResultSetAsync(callback); } } } protected async Task<IEnumerable<TModel>> ExecuteQueryAsync<TModel>(string sql, IEnumerable<SqlParameter> parameters, Func<IExpressiveReaderAsync<TModel>, Task<TModel>> callback) { using (var cmd = GetCommand(sql, parameters)) { await cmd.Connection.OpenAsync(); using (var reader = await cmd.ExecuteReaderAsync(CommandBehavior.CloseConnection)) { var expressive = reader.GetExpressive(); return await expressive.GetModelsForResultSetAsync(callback); } } } private SqlConnection GetDb() { var connectionString = ConfigurationManager.ConnectionStrings["SampleDB"].ConnectionString; return new SqlConnection(connectionString); } private SqlCommand GetCommand(string sql, IEnumerable<SqlParameter> parameters) { parameters = parameters ?? Enumerable.Empty<SqlParameter>(); var cmd = new SqlCommand(sql, GetDb()); foreach (var p in parameters) cmd.Parameters.Add(p); return cmd; } } }
mit
Karasiq/scalajs-highcharts
src/main/scala/com/highcharts/config/SeriesScatterDragDropDragHandle.scala
4116
/** * Automatically generated file. Please do not edit. * @author Highcharts Config Generator by Karasiq * @see [[http://api.highcharts.com/highcharts]] */ package com.highcharts.config import scalajs.js, js.`|` import com.highcharts.CleanJsObject import com.highcharts.HighchartsUtils._ /** * @note JavaScript name: <code>series&lt;scatter&gt;-dragDrop-dragHandle</code> */ @js.annotation.ScalaJSDefined class SeriesScatterDragDropDragHandle extends com.highcharts.HighchartsGenericObject { /** * <p>Function to define the SVG path to use for the drag handles. Takes * the point as argument. Should return an SVG path in array format. The * SVG path is automatically positioned on the point.</p> * @since 6.2.0 */ val pathFormatter: js.UndefOr[js.Function] = js.undefined /** * <p>The mouse cursor to use for the drag handles. By default this is * intelligently switching between <code>ew-resize</code> and <code>ns-resize</code> depending * on the direction the point is being dragged.</p> * @since 6.2.0 */ val cursor: js.UndefOr[String] = js.undefined /** * <p>The class name of the drag handles. Defaults to <code>highcharts-drag-handle</code>.</p> * @since 6.2.0 */ val className: js.UndefOr[String] = js.undefined /** * <p>The fill color of the drag handles.</p> * @since 6.2.0 */ val color: js.UndefOr[String | js.Object] = js.undefined /** * <p>The line color of the drag handles.</p> * @since 6.2.0 */ val lineColor: js.UndefOr[String | js.Object] = js.undefined /** * <p>The line width for the drag handles.</p> * @since 6.2.0 */ val lineWidth: js.UndefOr[Double] = js.undefined /** * <p>The z index for the drag handles.</p> * @since 6.2.0 */ val zIndex: js.UndefOr[Double] = js.undefined } object SeriesScatterDragDropDragHandle { /** * @param pathFormatter <p>Function to define the SVG path to use for the drag handles. Takes. the point as argument. Should return an SVG path in array format. The. SVG path is automatically positioned on the point.</p> * @param cursor <p>The mouse cursor to use for the drag handles. By default this is. intelligently switching between <code>ew-resize</code> and <code>ns-resize</code> depending. on the direction the point is being dragged.</p> * @param className <p>The class name of the drag handles. Defaults to <code>highcharts-drag-handle</code>.</p> * @param color <p>The fill color of the drag handles.</p> * @param lineColor <p>The line color of the drag handles.</p> * @param lineWidth <p>The line width for the drag handles.</p> * @param zIndex <p>The z index for the drag handles.</p> */ def apply(pathFormatter: js.UndefOr[js.Function] = js.undefined, cursor: js.UndefOr[String] = js.undefined, className: js.UndefOr[String] = js.undefined, color: js.UndefOr[String | js.Object] = js.undefined, lineColor: js.UndefOr[String | js.Object] = js.undefined, lineWidth: js.UndefOr[Double] = js.undefined, zIndex: js.UndefOr[Double] = js.undefined): SeriesScatterDragDropDragHandle = { val pathFormatterOuter: js.UndefOr[js.Function] = pathFormatter val cursorOuter: js.UndefOr[String] = cursor val classNameOuter: js.UndefOr[String] = className val colorOuter: js.UndefOr[String | js.Object] = color val lineColorOuter: js.UndefOr[String | js.Object] = lineColor val lineWidthOuter: js.UndefOr[Double] = lineWidth val zIndexOuter: js.UndefOr[Double] = zIndex com.highcharts.HighchartsGenericObject.toCleanObject(new SeriesScatterDragDropDragHandle { override val pathFormatter: js.UndefOr[js.Function] = pathFormatterOuter override val cursor: js.UndefOr[String] = cursorOuter override val className: js.UndefOr[String] = classNameOuter override val color: js.UndefOr[String | js.Object] = colorOuter override val lineColor: js.UndefOr[String | js.Object] = lineColorOuter override val lineWidth: js.UndefOr[Double] = lineWidthOuter override val zIndex: js.UndefOr[Double] = zIndexOuter }) } }
mit
eddmash/powerorm
tests/RegistryApp/Models/Author.php
565
<?php /** * This file is part of the powerorm package. * * (c) Eddilbert Macharia (http://eddmash.com)<edd.cowan@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Eddmash\PowerOrm\Tests\RegistryApp\Models; use Eddmash\PowerOrm\Model\Model; class Author extends Model { public function unboundFields() { return [ 'name' => Model::CharField(['maxLength' => 200]), 'email' => Model::EmailField(), ]; } }
mit
Brodan/PubNub-Neopixel-Demo
publisher.py
1416
import re import os import argparse from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub def hex_to_rgb(value): """Return (Red, Green, Blue) for the color given as #rrggbb. src: http://stackoverflow.com/a/214657/5045925 """ value = value.lstrip('#') lv = len(value) return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3)) def pub(message): pubnub.publish().channel('demo').message(message).sync() if __name__ == '__main__': # Configure and initialize Pubnub pnconfig = PNConfiguration() pnconfig.subscribe_key = os.environ['PUBNUB_SUBSCRIBE_KEY'] pnconfig.publish_key = os.environ['PUBNUB_PUBLISH_KEY'] pnconfig.enable_subscribe = False pubnub = PubNub(pnconfig) # Parse command line arguement. parser = argparse.ArgumentParser( description='Display a color on a Neopixel grid.') parser.add_argument('hexcolor', action="store") args = parser.parse_args() # Validate command line argument is proper hex code. # regex src: http://stackoverflow.com/a/1637260/5045925 if re.match('^#(([0-9a-fA-F]{2}){3}|([0-9a-fA-F]){3})$', args.hexcolor) is not None: hexcolor = hex_to_rgb(args.hexcolor) data = { 'color': hexcolor } pub(data) else: print('Please pass a valid color hex code. e.g. #FFF000 or #FFF')
mit
AccelerateX-org/NINE
Sources/TimeTable/MyStik.TimeTable.Data/Migrations/201712291128017_ExamV3.designer.cs
811
// <auto-generated /> namespace MyStik.TimeTable.Data.Migrations { using System.CodeDom.Compiler; using System.Data.Entity.Migrations; using System.Data.Entity.Migrations.Infrastructure; using System.Resources; [GeneratedCode("EntityFramework.Migrations", "6.2.0-61023")] public sealed partial class ExamV3 : IMigrationMetadata { private readonly ResourceManager Resources = new ResourceManager(typeof(ExamV3)); string IMigrationMetadata.Id { get { return "201712291128017_ExamV3"; } } string IMigrationMetadata.Source { get { return null; } } string IMigrationMetadata.Target { get { return Resources.GetString("Target"); } } } }
mit
J-Y/RubyQuiz
ruby_quiz/quiz100_sols/solutions/Marcel Ward/lexer_mw.rb
10533
#!/usr/bin/env ruby ################################################################## # = lexer_mw.rb - generic lexical analyser # # Author:: Marcel Ward <wardies ^a-t^ gmaildotcom> # Documentation:: Marcel Ward # Last Modified:: Monday, 06 November 2006 # # Solution for Ruby Quiz number 100 - http://www.rubyquiz.com/ $DEBUG = 0 # If the lexer fails to find an appropriate entry in the state # transition table for the current character and state, it # raises this exception. class LexerFailure < StandardError end # If the lexer encounters a character for which no matching charset # has been supplied then it raises this exception. # # This exception will never be raised if #init_state_transitions # has been called with an appropriate catch-all charset id. class InvalidLexeme < StandardError end class LexerMW # Creates an instance of the lexer class. # # _lexer_eof_ascii_:: # defines the ASCII byte value that the lexer considers as # end-of-file when it is encountered. When #tokenize is called, # the supplied datastream is automatically appended with this # character. def initialize(lexer_eof_ascii = 0) @s_trans = {} @columns = {} @lex_eof = lexer_eof_ascii end # Initialize the character set columns to be used by the lexer. # # _cs_defs_:: # a hash containing entries of the form <tt>id => match</tt>, # where _match_ defines the characters to be matched and _id_ # is the id that will be passed to the finite state machine # to inidicate the character grouping encountered. # _eof_charset_id_:: # defines the character set identifier which the lexer will # attempt to match in the state machine table when the # end-of-file character defined in #new is encountered. # # The content of _match_ falls into one of two main categories: # # _regexp_:: e.g. <tt>/\d/</tt> will match any digit 0..9; or # _enum_:: an enumeration that describes the set of allowed # character byte values, e.g. # the array <tt>[?*, ?/, ?%]</tt> matches # <b>*</b>, <b>/</b> or <b>%</b>, while the range # <tt>(?a..?z)</tt> matches lowercase alphas. # # e.g. # # init_char_sets({ # :alphanum => /[A-Z0-9]/, # :underscore => [?_], # :lower_vowel => [?a, ?e, ?i, ?o, ?u], # :special => (0..31) # }, # :end_line) # # It is the responsibility of the caller to ensure that the # match sets for each column are mutually exclusive. # # If a 'catch-all' set is needed then it is not necessary # to build the set of all characters not already matched. # Instead, see #init_state_transitions parameter list. # # Note, the contents of the hash is duplicated and stored # internally to avoid any inadvertent corruption from outside. def init_char_sets(cs_defs, eof_charset_id = :eof) @charsets = {} # Make a verbatim copy of the lexer charset columns cs_defs.each_pair do |charset_id, match| @charsets[charset_id] = match.dup # works for array/regexp end # Add an end-of-file charset column for free @charsets[eof_charset_id] = [@lex_eof] puts "@charsets =\n#{@charsets.inspect}\n\n" if $DEBUG == 1 end # Initialize the state transition table that will be used by the # finite state machine to convert incoming characters to tokens. # # _st_:: # a hash that defines the state transition table to be used # (see below). # _start_state_:: # defines the starting state for the finite state machine. # _catch_all_charset_id_:: # defines an optional charset id to be tried if the character # currently being analysed matches none of the charsets # in the charset table. The default +nil+ ensures that the # InvalidLexeme exception is raised if no charsets match. # # The state transition table hash _st_ maps each valid original # state to a hash containing the _rules_ to match when in that # state. # # Each hash entry _rule_ maps one of the character set ids # (defined in the call to #init_char_sets) to the _actions_ to be # carried out if the current character being analysed by the lexer # matches. # # The _action_ is a hash of distinct actions to be carried out for # a match. The following actions are supported: # # <tt>:next_s => _state_</tt>:: # sets the finite state machine next state to be _state_ and # appends the current character to the lexeme string being # prepared, absorbing the current character in the datastream. # # <tt>:next_s_skip => _state_</tt>:: # as above but the lexeme string being prepared remains static. # # <tt>:next_s_backtrack => _state_</tt>:: # as for _next_s_skip_ above but does not absorb the current # character (it will be used for the next state test). # # <tt>:token => _tok_</tt>:: # appends a hash containing a single entry to the array of # generated tokens, using _tok_ as the key and a copy of the # prepared lexeme string as the value. # # When the end of the datastream is reached, the lexer looks for # a match against charset <tt>:eof</tt>. # # When the performed actions contain no +next_s+... action, the # lexer assumes that a final state has been reached and returns # the accumulated array of tokens up to that point. # # e.g. # # init_state_transitions({ # :s1 => {:alpha => {next_s = :s2}, # :period => {:token => :tok_period}}, # :s2 => {:alphanum => {next_s = :s2}, # :underscore => {next_s_skip == :s2}, # :period => {next_s_backtrack = :s1} # :eof => {}}, // final state, return tokens # }, :s1, :other_chars) # # Note, the contents of the hash is duplicated and stored # internally to avoid any inadvertent corruption from outside. def init_state_transitions(st, start_state = :s_start, catch_all_charset_id = nil) @start_state = start_state @others_key = catch_all_charset_id @s_trans = {} # Make a verbatim copy of the state transition table st.each_pair do |orig_state, lexer_rules| @s_trans[orig_state] = state_rules = {} lexer_rules.each_pair do |lexer_charset, lexer_actions| state_rules[lexer_charset] = cur_actions = {} lexer_actions.each_pair do |action, new_val| cur_actions[action] = new_val end end end puts "@s_trans =\n#{@s_trans.inspect}\n\n" if $DEBUG == 1 end # Tokenize the datastream in _str_ according to the specific # character set and state transition table initialized through # #init_char_sets and #init_state_transitions. # # Returns an array of token elements where each element is # a pair of the form: # # [:token_name, "extracted lexeme string"] # # The end token marker [:tok_end, nil] is appended to the end # of the result on success, e.g. # # tokenize(str) # # => [[:tok_a, "123"], [:tok_b, "abc"], [:tok_end, nil]] # # Raises the LexerFailure exception if no matching state # transition is found for the current state and character. def tokenize(str) state = @start_state lexeme = '' tokens = [] # Append our end of file marker to the string to be tokenized str += "%c" % @lex_eof str.each_byte do |char| char_as_str = "%c" % char loop do match = @charsets.find { |id, match| (match.kind_of? Regexp) ? \ (match =~ char_as_str) : (match.include? char) } || [@others_key, @charsets[@others_key]] or \ raise InvalidLexeme # Look for the action matching our current state and the # character set id for our current char. action = @s_trans[state][match.first] or raise LexerFailure # If found, action contains our hash of actions, e.g. # {:next_s_backtrack => :s_operator, :token => :tok_int} puts "#{char==@lex_eof?'<eof>':char_as_str}: " \ "#{state.inspect} - #{action.inspect}" if $DEBUG == 1 # Build up the lexeme unless we're backtracking or skipping lexeme << char_as_str if action.has_key? :next_s tokens << [action[:token], lexeme.dup] && lexeme = '' if \ action.has_key? :token # Set the next state, or - when there is no specified next # state - we've finished, so return the tokens. state = action[:next_s] || action[:next_s_skip] || action[:next_s_backtrack] or return tokens << [:tok_end, nil] break unless action.has_key? :next_s_backtrack end end tokens end end if $0 == __FILE__ eval DATA.read, nil, $0, __LINE__+4 end __END__ require 'test/unit' class TC_LexerMW < Test::Unit::TestCase def test_simple @lexer = LexerMW.new() @char_sets = { :letter => (?a..?z), :digit => (/\d/), :space => [?\s, ?_] } @lexer.init_char_sets(@char_sets) @st = { :extract_chars => { :letter => {:next_s => :extract_chars}, :digit => {:next_s => :extract_chars}, :space => {:next_s_skip => :extract_chars, :token => :tok_text}, :eof => {:token => :tok_text} }, :extract_alpha => { :letter => {:next_s => :extract_alpha}, :digit => {:next_s_backtrack => :extract_num, :token => :tok_alpha}, :space => {:next_s_skip => :extract_alpha, :token => :tok_alpha}, :other => {:next_s_skip => :extract_alpha}, :eof_exit => {} }, :extract_num => { :letter => {:next_s_backtrack => :extract_alpha, :token => :tok_num}, :digit => {:next_s => :extract_num}, :space => {:next_s_skip => :extract_num}, :others => {:next_s_skip => :extract_alpha, :token => :tok_num} } } @lexer.init_state_transitions(@st, :extract_chars) assert_equal [ [:tok_text, "123"], [:tok_text, "45"], [:tok_text, "6"], [:tok_text, "78"], [:tok_text, "abcd"], [:tok_text, "efghi"], [:tok_text, "jklmn"], [:tok_end, nil] ], @lexer.tokenize("123 45 6_78 abcd efghi_jklmn") @lexer = LexerMW.new(?$) @lexer.init_char_sets(@char_sets, :eof_exit) @lexer.init_state_transitions(@st, :extract_num, :others) assert_equal [ [:tok_num, "12345678"], [:tok_alpha, "abcd"], [:tok_alpha, "efghi"], [:tok_num, "445"], [:tok_alpha, ""], [:tok_num, "1222"], [:tok_end, nil] ], @lexer.tokenize("123 45 6_78 abcd efghi445!12_22!ab$45") end end
mit
Puliyedath/NoteSharer
config/env/production.js
1424
'use strict'; module.exports = { db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://localhost/notesharer', assets: { lib: { css: [ ], js: [ 'public/lib/angular/angular.min.js', 'public/lib/angular-resource/angular-resource.min.js', 'public/lib/angular-touch/angular-touch.min.js', 'public/lib/angular-sanitize/angular-sanitize.min.js', 'public/lib/angular-ui-router/release/angular-ui-router.min.js', 'public/lib/angular-ui-utils/ui-utils.min.js', 'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js' ] }, css: 'public/dist/application.min.css', js: 'public/dist/application.min.js' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: 'http://localhost:3000/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/linkedin/callback' } };
mit
Allov/obgj-tap-dungeon
src/objects/ColoredText.js
853
// example: // let center = { x: this.game.world.centerX, y: this.game.world.centerY } // let text = new ColoredText(this.game, center.x, center.y, '- ph{#ff0000}aser -\nwith a spr{#00ff00}inkle of\nco{#0000ff}lors', { font: '45px Arial', fill: '#ffffff', align: 'center' }); const PATTERN = /\{(.*?)\}/g; export default class ColoredText extends Phaser.Text { set coloredText(text) { this.unparsedText = text.replace(/\n/g, ''); this.text = text.replace(PATTERN, ''); this.parseColorFromText(); } constructor(game, x, y, text, style) { super(game, x, y, text, style); this.coloredText = text; this.game.stage.addChild(this); } parseColorFromText() { let match = null; let i = 0; while (match = PATTERN.exec(this.unparsedText)) { this.addColor(match[1], match.index - (i * match[0].length)); i++; } } }
mit
jeremytammik/forgefader
src/client/viewer.components/Viewer.Extensions/Viewing.Extension.Configurator.Predix/index.js
129
import './Viewing.Extension.Configurator.Predix' import './Predix.scss' export default 'Viewing.Extension.Configurator.Predix'
mit
mixerp4/frapid
src/Frapid.Web/Areas/Frapid.Core/WebAPI/Properties/AssemblyInfo.cs
1366
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("Frapid.Core.Api")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Frapid.Core.Api")] [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("793d1121-14e8-483c-836f-888c1b6ebf26")] // 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
NullVoxPopuli/aeonvera-ui
app/routes/events/show/raffles/show/raffle-tickets/index.js
240
import Ember from 'ember'; import Index from 'aeonvera/mixins/routes/crud/events/index'; export default Ember.Route.extend(Index, { modelName: 'raffle-ticket', parentIdKey: 'raffle_id', parentPathRoot: 'events.show.raffles.show' });
mit
Nrupesh29/Web-Traffic-Visualizer
vizceral/src/base/node.js
8573
/** * * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ import _ from 'lodash'; import GraphObject from './graphObject'; import Notices from '../notices'; const Console = console; class Node extends GraphObject { constructor (node, renderer) { super(); this.type = 'node'; this.update(node); this.minimumNoticeLevel = 0; this.graphRenderer = renderer; this.position = this.position || {}; this.position.x = this.position.x || 0; this.position.y = this.position.y || 0; this.updateBoundingBox(); this.incomingConnections = []; this.outgoingConnections = []; this.connected = false; this.invalidatedSinceLastViewUpdate = true; this.options = { showLabel: true }; this.data = { volume: NaN, volumePercent: 0, classPercents: {} }; this.metadata = node.metadata; this.detailedMode = 'volume'; // 'volume' is default, can be a string that matches a data set in metadata: { details: {} } } addIncomingConnection (connection) { this.incomingConnections.push(connection); this.invalidateIncomingVolume(); this.connected = true; } addOutgoingConnection (connection) { this.outgoingConnections.push(connection); this.invalidateOutgoingVolume(); this.connected = true; } removeIncomingConnection (connection) { _.remove(this.incomingConnections, incomingConnection => incomingConnection.name === connection.name); this.invalidateIncomingVolume(); if (this.incomingConnections.length === 0 && this.outgoingConnections.length === 0) { this.connected = false; } } removeOutgoingConnection (connection) { _.remove(this.outgoingConnections, outgoingConnection => outgoingConnection.name === connection.name); this.invalidateOutgoingVolume(); if (this.incomingConnections.length === 0 && this.outgoingConnections.length === 0) { this.connected = false; } } invalidateIncomingVolume () { this.invalidatedSinceLastViewUpdate = true; this.incomingVolumeTotal = undefined; this.incomingVolume = {}; } validateIncomingVolume () { this.incomingVolumeTotal = _.reduce(this.incomingConnections, (total, connection) => total + connection.getVolumeTotal(), 0); _.each(this.incomingConnections, (c) => { _.each(c.volume, (value, key) => { this.incomingVolume[key] = this.incomingVolume[key] || 0; this.incomingVolume[key] += value; }); }); } getIncomingVolume (key) { if (!key) { if (!this.incomingVolumeTotal) { this.validateIncomingVolume(); } return this.incomingVolumeTotal; } if (!this.incomingVolume[key]) { this.validateIncomingVolume(); } return this.incomingVolume[key]; } invalidateOutgoingVolume () { this.invalidatedSinceLastViewUpdate = true; this.outgoingVolumeTotal = undefined; this.outgoingVolume = {}; } validateOutgoingVolume () { this.outgoingVolumeTotal = _.reduce(this.outgoingConnections, (total, connection) => total + connection.getVolumeTotal(), 0); _.each(this.outgoingConnections, (c) => { _.each(c.volume, (value, key) => { this.outgoingVolume[key] = this.outgoingVolume[key] || 0; this.outgoingVolume[key] += value; }); }); } getOutgoingVolume (key) { if (!key) { if (!this.outgoingVolumeTotal) { this.validateOutgoingVolume(); } return this.outgoingVolumeTotal; } if (!this.outgoingVolume[key]) { this.validateOutgoingVolume(); } return this.outgoingVolume[key]; } updatePosition (position, depth) { if (position !== undefined) { if ((position.x !== undefined && position.x !== this.position.x) || (position.y !== undefined && position.y !== this.position.y)) { this.position.x = position.x; this.position.y = position.y; } } if (depth !== undefined) { this.depth = depth; } this.updateBoundingBox(); } updateBoundingBox () { if (this.view) { this.boundingBox = { top: this.position.y - this.view.radius, right: this.position.x + this.view.radius, bottom: this.position.y + this.view.radius, left: this.position.x - this.view.radius }; } else { this.boundingBox = { top: this.position.y - 16, right: this.position.x + 16, bottom: this.position.y + 16, left: this.position.x - 16 }; } } getClass () { return this.class || 'normal'; } hasVisibleConnections () { return !(_.every(this.incomingConnections, connection => !connection.isVisible()) && _.every(this.outgoingConnections, connection => !connection.isVisible())); } hasDefaultVisibleConnections () { return !(_.every(this.incomingConnections, connection => connection.defaultFiltered) && _.every(this.outgoingConnections, connection => connection.defaultFiltered)); } setContext (context) { super.setContext(context); if (this.view) { this.view.updateText(); } } render () { Console.warn('Attempted to render a Node base class. Extend the Node base class and provide a render() function that creates a view property.'); } showNotices () { if (this.view) { Notices.showNotices(this.view.container, this.notices); } } updateData (totalVolume) { let updated = false; if (this.invalidatedSinceLastViewUpdate) { this.invalidatedSinceLastViewUpdate = false; const serviceVolume = this.isEntryNode() ? totalVolume : this.getIncomingVolume(); const serviceVolumePercent = serviceVolume / totalVolume; if (this.data.volume !== serviceVolume) { this.data.volume = serviceVolume; updated = true; } if (!serviceVolume) { this.data.volumePercent = 0; _.each(this.data.classPercents, (v, k) => { this.data.classPercents[k] = 0; }); } else { if (this.data.volumePercent !== serviceVolumePercent) { this.data.volumePercent = serviceVolumePercent; updated = true; } _.each(this.isEntryNode() ? this.outgoingVolume : this.incomingVolume, (volume, key) => { const classVolumePercent = volume / serviceVolume; this.data.classPercents[key] = this.data.classPercents[key] || 0; if (this.data.classPercents[key] !== classVolumePercent) { this.data.classPercents[key] = classVolumePercent; updated = true; } }); } } if (updated) { this.data.globalClassPercents = this.data.globalClassPercents || {}; const percentGlobal = this.data.volume / totalVolume; // generate global class percents _.each(this.data.classPercents, (classPercent, key) => { this.data.globalClassPercents[key] = classPercent * percentGlobal; }); } return updated; } update (stateNode) { this.classInvalidated = this.class !== stateNode.class; _.assign(this, stateNode); this.notices = stateNode.notices; if (this.view) { this.view.refresh(false); } } updateVolume (volume) { this.updated = this.updateData(volume); } showLabel (showLabel) { if (this.options.showLabel !== showLabel) { this.options.showLabel = showLabel; if (this.view !== undefined) { this.view.showLabel(showLabel); } } } setModes (modes) { this.detailedMode = modes.detailedNode; if (this.view) { this.view.refresh(true); } } connectedTo (nodeName) { if (super.connectionTo(nodeName)) { return true; } return !(_.every(this.incomingConnections, connection => connection.source.getName() !== nodeName) && _.every(this.outgoingConnections, connection => connection.source.getName() !== nodeName)); } isEntryNode () { return this.incomingConnections.length === 0 && this.outgoingConnections.length > 0; } cleanup () { if (this.view) { this.view.cleanup(); } } } export default Node;
mit
OblivionNW/Nucleus
src/main/java/io/github/nucleuspowered/nucleus/modules/item/commands/lore/LoreCommand.java
1058
/* * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file * at the root of this project for more details. */ package io.github.nucleuspowered.nucleus.modules.item.commands.lore; import io.github.nucleuspowered.nucleus.internal.annotations.command.Permissions; import io.github.nucleuspowered.nucleus.internal.annotations.command.RegisterCommand; import io.github.nucleuspowered.nucleus.internal.command.AbstractCommand; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.args.CommandContext; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.cause.Cause; import org.spongepowered.api.util.annotation.NonnullByDefault; @Permissions @NonnullByDefault @RegisterCommand(value = "lore", hasExecutor = false) public class LoreCommand extends AbstractCommand<Player> { // Not executed. @Override public CommandResult executeCommand(Player src, CommandContext args, Cause cause) { return CommandResult.empty(); } }
mit
alphaleonis/AlphaFS
src/AlphaFS/Filesystem/Directory Class/Directory Junctions, Links/Directory.CreateSymbolicLinkTransacted.cs
4839
/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * 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 System.Diagnostics.CodeAnalysis; using System.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// <summary>[AlphaFS] Creates a symbolic link (similar to CMD command: "MKLINK /D") to a directory as a transacted operation.</summary> /// <para>&#160;</para> /// <remarks> /// <para>Symbolic links can point to a non-existent target.</para> /// <para>When creating a symbolic link, the operating system does not check to see if the target exists.</para> /// <para>Symbolic links are reparse points.</para> /// <para>There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path.</para> /// <para>See <see cref="Security.Privilege.CreateSymbolicLink"/> to run this method in an elevated state.</para> /// </remarks> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="IOException"/> /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception> /// <param name="transaction">The transaction.</param> /// <param name="symlinkDirectoryName">The name of the target for the symbolic link to be created.</param> /// <param name="targetDirectoryName">The symbolic link to be created.</param> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "symlink")] [SecurityCritical] public static void CreateSymbolicLinkTransacted(KernelTransaction transaction, string symlinkDirectoryName, string targetDirectoryName) { File.CreateSymbolicLinkCore(transaction, symlinkDirectoryName, targetDirectoryName, SymbolicLinkTarget.Directory, PathFormat.RelativePath); } /// <summary>[AlphaFS] Creates a symbolic link (similar to CMD command: "MKLINK /D") to a directory as a transacted operation.</summary> /// <para>&#160;</para> /// <remarks> /// <para>Symbolic links can point to a non-existent target.</para> /// <para>When creating a symbolic link, the operating system does not check to see if the target exists.</para> /// <para>Symbolic links are reparse points.</para> /// <para>There is a maximum of 31 reparse points (and therefore symbolic links) allowed in a particular path.</para> /// <para>See <see cref="Security.Privilege.CreateSymbolicLink"/> to run this method in an elevated state.</para> /// </remarks> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="IOException"/> /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception> /// <param name="transaction">The transaction.</param> /// <param name="symlinkDirectoryName">The name of the target for the symbolic link to be created.</param> /// <param name="targetDirectoryName">The symbolic link to be created.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "symlink")] [SecurityCritical] public static void CreateSymbolicLinkTransacted(KernelTransaction transaction, string symlinkDirectoryName, string targetDirectoryName, PathFormat pathFormat) { File.CreateSymbolicLinkCore(transaction, symlinkDirectoryName, targetDirectoryName, SymbolicLinkTarget.Directory, pathFormat); } } }
mit
redg3ar/aeiou
vendor/github.com/bwmarrin/discordgo/user.go
751
package discordgo import "fmt" // A User stores all data for an individual Discord user. type User struct { ID string `json:"id"` Email string `json:"email"` Username string `json:"username"` Avatar string `json:"avatar"` Discriminator string `json:"discriminator"` Token string `json:"token"` Verified bool `json:"verified"` MFAEnabled bool `json:"mfa_enabled"` Bot bool `json:"bot"` } // String returns a unique identifier of the form username#discriminator func (u *User) String() string { return fmt.Sprintf("%s#%s", u.Username, u.Discriminator) } // Mention return a string which mentions the user func (u *User) Mention() string { return fmt.Sprintf("<@%s>", u.ID) }
mit
Rebilly/ReDoc
src/common-elements/schema.ts
1510
import styled from '../styled-components'; import { darken } from 'polished'; export const OneOfList = styled.div` margin: 0 0 3px 0; display: inline-block; `; export const OneOfLabel = styled.span` font-size: 0.9em; margin-right: 10px; color: ${props => props.theme.colors.primary.main}; font-family: ${props => props.theme.typography.headings.fontFamily}; } `; export const OneOfButton = styled.button<{ active: boolean }>` display: inline-block; margin-right: 10px; margin-bottom: 5px; font-size: 0.8em; cursor: pointer; border: 1px solid ${props => props.theme.colors.primary.main}; padding: 2px 10px; line-height: 1.5em; outline: none; &:focus { box-shadow: 0 0 0 1px ${props => props.theme.colors.primary.main}; } ${props => { if (props.active) { return ` color: white; background-color: ${props.theme.colors.primary.main}; &:focus { box-shadow: none; background-color: ${darken(0.15, props.theme.colors.primary.main)}; } `; } else { return ` color: ${props.theme.colors.primary.main}; background-color: white; `; } }} `; export const ArrayOpenningLabel = styled.div` font-size: 0.9em; font-family: ${props => props.theme.typography.code.fontFamily}; &::after { content: ' ['; } `; export const ArrayClosingLabel = styled.div` font-size: 0.9em; font-family: ${props => props.theme.typography.code.fontFamily}; &::after { content: ']'; } `;
mit
yolosec/zeman-parser
zemanfeed/daemon.py
6751
''' *** Modified generic daemon class *** Author: http://www.jejik.com/articles/2007/02/ a_simple_unix_linux_daemon_in_python/www.boxedice.com License: http://creativecommons.org/licenses/by-sa/3.0/ Changes: 23rd Jan 2009 (David Mytton <david@boxedice.com>) - Replaced hard coded '/dev/null in __init__ with os.devnull - Added OS check to conditionally remove code that doesn't work on OS X - Added output to console on completion - Tidied up formatting 11th Mar 2009 (David Mytton <david@boxedice.com>) - Fixed problem with daemon exiting on Python 2.4 (before SystemExit was part of the Exception base) 13th Aug 2010 (David Mytton <david@boxedice.com> - Fixed unhandled exception if PID file is empty ''' # Core modules import atexit import os import sys import time import signal class Daemon(object): """ A generic daemon class. Usage: subclass the Daemon class and override the run() method """ def __init__(self, pidfile, stdin=os.devnull, stdout=os.devnull, stderr=os.devnull, home_dir='.', umask=022, verbose=1, use_gevent=False, *args, **kwargs): self.stdin = stdin self.stdout = stdout self.stderr = stderr self.pidfile = pidfile self.home_dir = home_dir self.verbose = verbose self.umask = umask self.daemon_alive = True self.use_gevent = use_gevent def daemonize(self): """ Do the UNIX double-fork magic, see Stevens' "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 """ try: pid = os.fork() if pid > 0: # Exit first parent sys.exit(0) except OSError, e: sys.stderr.write( "fork #1 failed: %d (%s)\n" % (e.errno, e.strerror)) sys.exit(1) # Decouple from parent environment os.chdir(self.home_dir) # os.setsid() os.umask(self.umask) # Do second fork try: pid = os.fork() if pid > 0: # Exit from second parent sys.exit(0) except OSError, e: sys.stderr.write( "fork #2 failed: %d (%s)\n" % (e.errno, e.strerror)) sys.exit(1) if sys.platform != 'darwin': # This block breaks on OS X # Redirect standard file descriptors sys.stdout.flush() sys.stderr.flush() si = file(self.stdin, 'r') so = file(self.stdout, 'a+') if self.stderr: se = file(self.stderr, 'a+', 0) else: se = so os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) def sigtermhandler(signum, frame): self.daemon_alive = False sys.exit() if self.use_gevent: import gevent gevent.reinit() gevent.signal(signal.SIGTERM, sigtermhandler, signal.SIGTERM, None) gevent.signal(signal.SIGINT, sigtermhandler, signal.SIGINT, None) else: signal.signal(signal.SIGTERM, sigtermhandler) signal.signal(signal.SIGINT, sigtermhandler) if self.verbose >= 1: print "Started" # Write pidfile atexit.register( self.delpid) # Make sure pid file is removed if we quit pid = str(os.getpid()) file(self.pidfile, 'w+').write("%s\n" % pid) def delpid(self): os.remove(self.pidfile) def start(self, *args, **kwargs): """ Start the daemon """ if self.verbose >= 1: print "Starting..." # Check for a pidfile to see if the daemon already runs try: pf = file(self.pidfile, 'r') pid = int(pf.read().strip()) pf.close() except IOError: pid = None except SystemExit: pid = None if pid: message = "pidfile %s already exists. Is it already running?\n" sys.stderr.write(message % self.pidfile) sys.exit(1) # Start the daemon self.daemonize() self.run(*args, **kwargs) def stop(self): """ Stop the daemon """ if self.verbose >= 1: print "Stopping..." # Get the pid from the pidfile pid = self.get_pid() if not pid: message = "pidfile %s does not exist. Not running?\n" sys.stderr.write(message % self.pidfile) # Just to be sure. A ValueError might occur if the PID file is # empty but does actually exist if os.path.exists(self.pidfile): os.remove(self.pidfile) return # Not an error in a restart # Try killing the daemon process try: i = 0 while 1: os.kill(pid, signal.SIGTERM) time.sleep(0.1) i = i + 1 if i % 10 == 0: os.kill(pid, signal.SIGHUP) except OSError, err: err = str(err) if err.find("No such process") > 0: if os.path.exists(self.pidfile): os.remove(self.pidfile) else: print str(err) sys.exit(1) if self.verbose >= 1: print "Stopped" def restart(self): """ Restart the daemon """ self.stop() self.start() def get_pid(self): try: pf = file(self.pidfile, 'r') pid = int(pf.read().strip()) pf.close() except IOError: pid = None except SystemExit: pid = None return pid def is_running(self): pid = self.get_pid() if pid is None: print 'Process is stopped' elif os.path.exists('/proc/%d' % pid): print 'Process (pid %d) is running...' % pid else: print 'Process (pid %d) is killed' % pid return pid and os.path.exists('/proc/%d' % pid) def run(self): """ You should override this method when you subclass Daemon. It will be called after the process has been daemonized by start() or restart(). """ raise NotImplementedError
mit
makasim/ValuesORM
tests/ValuesTest.php
8272
<?php namespace Formapro\Values\Tests; use function Formapro\Values\add_value; use function Formapro\Values\build_object; use function Formapro\Values\clone_object; use function Formapro\Values\get_value; use function Formapro\Values\get_values; use function Formapro\Values\set_value; use function Formapro\Values\set_values; use Formapro\Values\Tests\Model\EmptyObject; use Formapro\Values\ValuesTrait; use PHPUnit\Framework\TestCase; class ValuesTest extends TestCase { public function testShouldAllowSetValuesAndGetPreviouslySet() { $values = ['foo' => 'fooVal', 'bar' => ['bar1' => 'bar1Val', 'bar2' => 'bar2Val']]; $obj = new EmptyObject(); set_values($obj, $values); self::assertSame($values, get_values($obj)); } public function testShouldAllowSetNewValueAndGetPreviouslySet() { $obj = new EmptyObject(); set_value($obj, 'aKey', 'aVal'); self::assertSame('aVal', get_value($obj, 'aKey')); self::assertSame(['aKey' => 'aVal'], get_values($obj)); } public function testShouldAllowSetNewNameSpacedValueAndGetPreviouslySet() { $obj = new EmptyObject(); set_value($obj, 'aNamespace.aKey', 'aVal'); self::assertSame('aVal', get_value($obj, 'aNamespace.aKey')); self::assertSame(['aNamespace' => ['aKey' => 'aVal']], get_values($obj)); } public function testShouldAllowGetDefaultValueIfSimpleValueNotSet() { $obj = new EmptyObject(); self::assertSame('aDefaultVal', get_value($obj, 'aKey', 'aDefaultVal')); set_value($obj, 'aKey', 'aVal'); self::assertSame('aVal', get_value($obj, 'aKey', 'aDefaultVal')); } public function testShouldAllowGetDefaultValueIfNameSpacedValueNotSet() { $obj = new EmptyObject(); self::assertSame('aDefaultVal', get_value($obj, 'aNamespace.aKey', 'aDefaultVal')); set_value($obj, 'aNamespace.aKey', 'aVal'); self::assertSame('aVal', get_value($obj, 'aNamespace.aKey', 'aDefaultVal')); } public function testShouldResetChangedValuesOnSetValues() { $obj = new EmptyObject(); set_value($obj, 'aNamespace.aKey', 'aVal'); self::assertSame(['aNamespace' => ['aKey' => 'aVal']], get_values($obj)); $values = ['bar' => 'barVal']; set_values($obj, $values); self::assertSame(['bar' => 'barVal'], get_values($obj)); } public function testShouldAllowUnsetPreviouslySetSimpleValue() { $obj = new EmptyObject(); set_value($obj, 'aKey', 'aVal'); set_value($obj, 'anotherKey', 'anotherVal'); self::assertSame('aVal', get_value($obj, 'aKey')); self::assertSame(['aKey' => 'aVal', 'anotherKey' => 'anotherVal'], get_values($obj)); set_value($obj, 'aKey', null); self::assertSame(null, get_value($obj, 'aKey')); self::assertSame(['anotherKey' => 'anotherVal'], get_values($obj)); } public function testShouldAllowUnsetPreviouslySetNameSpacedValue() { $obj = new EmptyObject(); set_value($obj, 'aName.aKey', 'aVal'); set_value($obj, 'anotherName.aKey', 'anotherVal'); self::assertSame('aVal', get_value($obj, 'aName.aKey')); self::assertSame( [ 'aName' => ['aKey' => 'aVal'], 'anotherName' => ['aKey' => 'anotherVal'], ], get_values($obj) ); set_value($obj, 'aName.aKey', null); self::assertSame(null, get_value($obj, 'aName.aKey')); self::assertSame( [ 'aName' => [], 'anotherName' => ['aKey' => 'anotherVal'], ], get_values($obj) ); } public function testShouldAllowAddSimpleValueToEmptyArray() { $obj = new EmptyObject(); add_value($obj, 'aKey', 'aVal'); self::assertSame(['aVal'], get_value($obj, 'aKey')); self::assertSame(['aKey' => ['aVal']], get_values($obj)); } public function testShouldAllowAddSeveralSimpleValuesToEmptyArray() { $obj = new EmptyObject(); add_value($obj, 'aKey', 'foo'); add_value($obj, 'aKey', 'bar'); add_value($obj, 'aKey', 'baz', 'customKey'); add_value($obj, 'aKey', 'ololo'); self::assertSame( [ 'aKey' => [ 0 => 'foo', 1 => 'bar', 'customKey' => 'baz', 2 => 'ololo', ] ], get_values($obj) ); } public function testAddValueReturnsAddedValueKey() { $obj = new EmptyObject(); self::assertSame(0, add_value($obj, 'aKey', 'aVal')); self::assertSame('customKey', add_value($obj, 'aKey', 'aVal', 'customKey')); self::assertSame(1, add_value($obj, 'aKey', 'aVal')); } public function testShouldAllowAddNameSpacedValueToEmptyArray() { $obj = new EmptyObject(); add_value($obj, 'aNamespace.aKey', 'aVal'); self::assertSame(['aVal'], get_value($obj, 'aNamespace.aKey')); self::assertSame(['aNamespace' => ['aKey' => ['aVal']]], get_values($obj)); } public function testShouldAllowAddSimpleValueToExistingArray() { $values = ['aKey' => ['aVal']]; $obj = new EmptyObject(); set_values($obj, $values); add_value($obj, 'aKey', 'aNewVal'); self::assertSame(['aVal', 'aNewVal'], get_value($obj, 'aKey')); self::assertSame(['aKey' => ['aVal', 'aNewVal']], get_values($obj)); } public function testShouldAllowAddNameSpacedValueToExistingArray() { $values = ['aNamespace' => ['aKey' => ['aVal']]]; $obj = new EmptyObject(); set_values($obj, $values); add_value($obj, 'aNamespace.aKey', 'aNewVal'); self::assertSame(['aVal', 'aNewVal'], get_value($obj, 'aNamespace.aKey')); self::assertSame(['aNamespace' => ['aKey' => ['aVal', 'aNewVal']]], get_values($obj)); } public function testShouldAllowAddValueWithCustomValueKeyThatContainsDot() { $obj = new EmptyObject(); add_value($obj, 'aKey', 'aVal', 'valueKey.withDot'); self::assertSame(['valueKey.withDot' => 'aVal'], get_value($obj, 'aKey')); self::assertSame(['aKey' => ['valueKey.withDot' => 'aVal']], get_values($obj)); } /** * @expectedException \LogicException * @expectedExceptionMessage Cannot set value to aNamespace.aKey it is already set and not array */ public function testThrowsIfAddValueButExistingValueIsNotArray() { $values = ['aNamespace' => ['aKey' => 'aVal']]; $obj = new EmptyObject(); set_values($obj, $values); add_value($obj, 'aNamespace.aKey', 'aVal'); } public function testShouldNotReflectChangesOnClonedObject() { $obj = new EmptyObject(); set_value($obj, 'aNamespace.aKey', 'foo'); $clonedObj = clone_object($obj); set_value($clonedObj, 'aNamespace.aKey', 'bar'); self::assertSame('foo', get_value($obj, 'aNamespace.aKey')); self::assertSame('bar', get_value($clonedObj, 'aNamespace.aKey')); } public function testShouldReplaceStringValueWithArray() { $obj = new EmptyObject(); set_value($obj, 'aKey', 'foo'); set_value($obj, 'aKey.aSubKey', 'bar'); self::assertSame(['aSubKey' => 'bar'], get_value($obj, 'aKey')); self::assertSame(['aKey' => ['aSubKey' => 'bar']], get_values($obj)); } public function testShouldUseValuesSetInConstructorAsDefaultsOnBuildObject() { $obj = new class { use ValuesTrait; public function __construct() { $this->values = [ 'foo' => 'fooVal', 'bar' => 'barVal', ]; } }; $builtObj = build_object(get_class($obj), [ 'bar' => 'newBarVal' ]); $this->assertInstanceOf(get_class($obj), $builtObj); $this->assertEquals([ 'foo' => 'fooVal', 'bar' => 'newBarVal' ], get_values($builtObj)); } }
mit
manishksmd/react-scheduler-smartdata
src/ResourceGrid.js
9874
import React, { Component } from 'react'; import cn from 'classnames'; import { findDOMNode } from 'react-dom'; import dates from './utils/dates'; import localizer from './localizer' import DayColumn from './DayColumn'; import TimeColumn from './TimeColumn'; import Header from './Header'; import getWidth from 'dom-helpers/query/width'; import scrollbarSize from 'dom-helpers/util/scrollbarSize'; import { accessor, dateFormat } from './utils/propTypes'; import { notify } from './utils/helpers'; import { accessor as get } from './utils/accessors'; import { inRange, sortEvents, segStyle } from './utils/eventLevels'; import PropTypes from 'prop-types'; export default class ResourceGrid extends Component { static propTypes = { events: PropTypes.array.isRequired, resources: PropTypes.array.isRequired, step: PropTypes.number, start: PropTypes.instanceOf(Date), end: PropTypes.instanceOf(Date), min: PropTypes.instanceOf(Date), max: PropTypes.instanceOf(Date), now: PropTypes.instanceOf(Date), scrollToTime: PropTypes.instanceOf(Date), eventPropGetter: PropTypes.func, dayFormat: dateFormat, culture: PropTypes.string, rtl: PropTypes.bool, width: PropTypes.number, titleAccessor: accessor.isRequired, allDayAccessor: accessor.isRequired, startAccessor: accessor.isRequired, endAccessor: accessor.isRequired, selected: PropTypes.object, selectable: PropTypes.oneOf([true, false, 'ignoreEvents']), onNavigate: PropTypes.func, onSelectSlot: PropTypes.func, onSelectEnd: PropTypes.func, onSelectStart: PropTypes.func, onSelectEvent: PropTypes.func, onDrillDown: PropTypes.func, messages: PropTypes.object, components: PropTypes.object.isRequired, businessHours: PropTypes.array, } static defaultProps = { step: 30, min: dates.startOf(new Date(), 'day'), businessHours: [], max: dates.endOf(new Date(), 'day'), scrollToTime: dates.startOf(new Date(), 'day'), /* these 2 are needed to satisfy requirements from TimeColumn required props * There is a strange bug in React, using ...TimeColumn.defaultProps causes weird crashes */ type: 'gutter', now: new Date() } constructor(props) { super(props) this.state = { gutterWidth: undefined, isOverflowing: null }; this.handleSelectEvent = this.handleSelectEvent.bind(this) } componentWillMount() { this._gutters = []; this.calculateScroll(); } componentDidMount() { this.checkOverflow(); if (this.props.width == null) { this.measureGutter() } this.applyScroll(); this.positionTimeIndicator(); this.triggerTimeIndicatorUpdate(); } componentWillUnmount() { window.clearTimeout(this._timeIndicatorTimeout); } componentDidUpdate() { if (this.props.width == null && !this.state.gutterWidth) { this.measureGutter() } this.applyScroll(); this.positionTimeIndicator(); } componentWillReceiveProps(nextProps) { const { start, scrollToTime } = this.props; // When paginating, reset scroll if ( !dates.eq(nextProps.start, start, 'minute') || !dates.eq(nextProps.scrollToTime, scrollToTime, 'minute') ) { this.calculateScroll(); } } handleSelectAllDaySlot = (slots) => { const { onSelectSlot } = this.props; notify(onSelectSlot, { slots, start: slots[0], end: slots[slots.length - 1] }) } render() { let { events , start , end , width , startAccessor , endAccessor , allDayAccessor } = this.props; width = width || this.state.gutterWidth; let range = dates.range(start, end, 'day') this.slots = range.length; let allDayEvents = [] , rangeEvents = []; events.forEach(event => { if (inRange(event, start, end, this.props)) { let eStart = get(event, startAccessor) , eEnd = get(event, endAccessor); if ( get(event, allDayAccessor) || !dates.eq(eStart, eEnd, 'day') || (dates.isJustDate(eStart) && dates.isJustDate(eEnd))) { allDayEvents.push(event) } else rangeEvents.push(event) } }) allDayEvents.sort((a, b) => sortEvents(a, b, this.props)) let gutterRef = ref => this._gutters[1] = ref && findDOMNode(ref); return ( <div className='rbc-time-view'> {this.renderResourceHeader(range, allDayEvents, width, this.props.resources)} <div ref='content' className='rbc-time-content'> <div ref='timeIndicator' className='rbc-current-time-indicator' /> <TimeColumn {...this.props} showLabels style={{ width }} ref={gutterRef} isGutter={true} className='rbc-time-gutter' /> {this.props.resources.map(resource => { return this.renderEvents(range, rangeEvents, this.props.now, resource.id) })} </div> </div> ); } renderEvents(range, events, today, id){ let { min, max, endAccessor, startAccessor, components } = this.props; return range.map((date, idx) => { let daysEvents = events.filter( event => dates.inRange(date, get(event, startAccessor), get(event, endAccessor), 'day') && event.resourceId === id ) return ( <DayColumn {...this.props } key={id} resource={id} min={dates.merge(date, min)} max={dates.merge(date, max)} eventComponent={components.event} eventWrapperComponent={components.eventWrapper} dayWrapperComponent={components.dayWrapper} className={cn({ 'rbc-now': dates.eq(date, today, 'day') })} style={segStyle(1, this.slots)} key={idx} date={date} events={daysEvents} /> ) }) } renderResourceHeader(range, events, width, resources) { let { rtl } = this.props; let { isOverflowing } = this.state || {}; let style = {}; if (isOverflowing) style[rtl ? 'marginLeft' : 'marginRight'] = scrollbarSize() + 'px'; return ( <div ref='headerCell' className={cn( 'rbc-time-header', isOverflowing && 'rbc-overflowing' )} style={style} > <div className='rbc-row'> <div className='rbc-label rbc-header-gutter' style={{ width }} /> {resources.map(resource => { return this.renderHeaderCells(range, resource.id, resource.title) })} </div> </div> ) } renderHeaderCells(range, id, title){ let { dayFormat, culture, components } = this.props; let HeaderComponent = components.header || Header return range.map((date, i) => { let label = localizer.format(date, dayFormat, culture); let header = ( <HeaderComponent date={date} label={label} localizer={localizer} format={dayFormat} culture={culture} /> ) return ( <div key={i} className={cn( 'rbc-header', dates.isToday(date) && 'rbc-today', )} style={segStyle(1, this.slots)} > <span> {title || header} </span> </div> ) }) } handleSelectEvent(...args) { notify(this.props.onSelectEvent, args) } clearSelection(){ clearTimeout(this._selectTimer) this._pendingSelection = []; } measureGutter() { let width = this.state.gutterWidth; let gutterCells = this._gutters.filter(g => !!g); if (!width) { width = Math.max(...gutterCells.map(getWidth)); if (width) { this.setState({ gutterWidth: width }) } } } applyScroll() { if (this._scrollRatio) { const { content } = this.refs; content.scrollTop = content.scrollHeight * this._scrollRatio; // Only do this once this._scrollRatio = null; } } calculateScroll() { const { min, max, scrollToTime } = this.props; const diffMillis = scrollToTime - dates.startOf(scrollToTime, 'day'); const totalMillis = dates.diff(max, min); this._scrollRatio = diffMillis / totalMillis; } checkOverflow() { if (this._updatingOverflow) return; let isOverflowing = this.refs.content.scrollHeight > this.refs.content.clientHeight; if (this.state.isOverflowing !== isOverflowing) { this._updatingOverflow = true; this.setState({ isOverflowing }, () => { this._updatingOverflow = false; }) } } positionTimeIndicator() { const { rtl, min, max } = this.props const now = new Date(); const secondsGrid = dates.diff(max, min, 'seconds'); const secondsPassed = dates.diff(now, min, 'seconds'); const timeIndicator = this.refs.timeIndicator; const factor = secondsPassed / secondsGrid; const timeGutter = this._gutters[this._gutters.length - 1]; if (timeGutter && now >= min && now <= max) { const pixelHeight = timeGutter.offsetHeight; const offset = Math.floor(factor * pixelHeight); timeIndicator.style.display = 'block'; timeIndicator.style[rtl ? 'left' : 'right'] = 0; timeIndicator.style[rtl ? 'right' : 'left'] = timeGutter.offsetWidth + 'px'; timeIndicator.style.top = offset + 'px'; } else { timeIndicator.style.display = 'none'; } } triggerTimeIndicatorUpdate() { // Update the position of the time indicator every minute this._timeIndicatorTimeout = window.setTimeout(() => { this.positionTimeIndicator(); this.triggerTimeIndicatorUpdate(); }, 60000) } }
mit
mickleness/pumpernickel
src/main/java/com/pump/plaf/AquaTileLocationBrowserUI.java
739
/** * This software is released as part of the Pumpernickel project. * * All com.pump resources in the Pumpernickel project are distributed under the * MIT License: * https://raw.githubusercontent.com/mickleness/pumpernickel/master/License.txt * * More information about the Pumpernickel project is available here: * https://mickleness.github.io/pumpernickel/ */ package com.pump.plaf; import javax.swing.JComponent; import com.pump.swing.io.LocationBrowser; public class AquaTileLocationBrowserUI extends TileLocationBrowserUI { public AquaTileLocationBrowserUI(LocationBrowser b) { super(b); } @Override public void installUI(JComponent c) { super.installUI(c); thumbnail.setUI(new AquaThumbnailLabelUI()); } }
mit
CasualX/CasualX.github.io
docs/pupil-rs/0.1.3/implementors/core/cmp/trait.Ord.js
515
(function() {var implementors = {}; implementors["libc"] = [];implementors["pupil"] = ["impl <a class='trait' href='https://doc.rust-lang.org/nightly/core/cmp/trait.Ord.html' title='core::cmp::Ord'>Ord</a> for <a class='enum' href='pupil/op/enum.Order.html' title='pupil::op::Order'>Order</a>",]; if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })()
mit
skettios/Text-Adventure-API
TA-API/src/test/java/com/skettios/textadventure/command/CommandJeric.java
966
package com.skettios.textadventure.command; import com.skettios.textadventure.api.TextAdventureAPI; import com.skettios.textadventure.api.command.ICommand; import java.util.List; public class CommandJeric implements ICommand { @Override public String[] getCommandAliases() { return new String[]{ "jeric", "ako-si-jeric", "ako-si-silver" }; } @Override public void onExecute(List<String> args) { for (String arg : args) { if (arg.equals("silver")) TextAdventureAPI.sendMessage("KEK"); if (arg.equals("csgo")) TextAdventureAPI.sendMessage("I suck at this."); if (arg.equals("carry")) TextAdventureAPI.sendMessage("Haha, Good One. LOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOLOL"); } } @Override public boolean canExecute(List<String> args) { return true; } @Override public String getErrorMessage(List<String> args) { return null; } }
mit
TelerikWebFormsOrganization/SimpleBlogSystem
SimpleBlogSystemSolution/SimpleBlogSystem.Common/Properties/AssemblyInfo.cs
1422
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("SimpleBlogSystem.Common")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SimpleBlogSystem.Common")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("224c2ddd-61a5-46cf-8a00-d356867df492")] // 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 Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
maxstorm/investorreports
adodb/drivers/adodb-pdo.inc.php
19326
<? /* V4.63 17 May 2005 (c) 2000-2005 John Lim (jlim#natsoft.com.my). All rights reserved. Released under both BSD license and Lesser GPL library license. Whenever there is any discrepancy between the two licenses, the BSD license will take precedence. Set tabs to 4 for best viewing. Latest version is available at http://adodb.sourceforge.net Requires ODBC. Works on Windows and Unix. Problems: Where is float/decimal type in pdo_param_type LOB handling for CLOB/BLOB differs significantly */ // security - hide paths if (!defined('ADODB_DIR')) die(); /* enum pdo_param_type { PDO_PARAM_NULL, 0 /* int as in long (the php native int type). * If you mark a column as an int, PDO expects get_col to return * a pointer to a long PDO_PARAM_INT, 1 /* get_col ptr should point to start of the string buffer PDO_PARAM_STR, 2 /* get_col: when len is 0 ptr should point to a php_stream *, * otherwise it should behave like a string. Indicate a NULL field * value by setting the ptr to NULL PDO_PARAM_LOB, 3 /* get_col: will expect the ptr to point to a new PDOStatement object handle, * but this isn't wired up yet PDO_PARAM_STMT, 4 /* hierarchical result set /* get_col ptr should point to a zend_bool PDO_PARAM_BOOL, 5 /* magic flag to denote a parameter as being input/output PDO_PARAM_INPUT_OUTPUT = 0x80000000 }; */ function adodb_pdo_type($t) { switch($t) { case 2: return 'VARCHAR'; case 3: return 'BLOB'; default: return 'NUMERIC'; } } /*-------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------*/ class ADODB_pdo_pgsql extends ADODB_pdo { var $metaDatabasesSQL = "select datname from pg_database where datname not in ('template0','template1') order by 1"; var $metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%' and tablename not in ('sql_features', 'sql_implementation_info', 'sql_languages', 'sql_packages', 'sql_sizing', 'sql_sizing_profiles') union select viewname,'V' from pg_views where viewname not like 'pg\_%'"; //"select tablename from pg_tables where tablename not like 'pg_%' order by 1"; var $isoDates = true; // accepts dates in ISO format var $sysDate = "CURRENT_DATE"; var $sysTimeStamp = "CURRENT_TIMESTAMP"; var $blobEncodeType = 'C'; var $metaColumnsSQL = "SELECT a.attname,t.typname,a.attlen,a.atttypmod,a.attnotnull,a.atthasdef,a.attnum FROM pg_class c, pg_attribute a,pg_type t WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s')) and a.attname not like '....%%' AND a.attnum > 0 AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum"; // used when schema defined var $metaColumnsSQL1 = "SELECT a.attname, t.typname, a.attlen, a.atttypmod, a.attnotnull, a.atthasdef, a.attnum FROM pg_class c, pg_attribute a, pg_type t, pg_namespace n WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s')) and c.relnamespace=n.oid and n.nspname='%s' and a.attname not like '....%%' AND a.attnum > 0 AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum"; // get primary key etc -- from Freek Dijkstra var $metaKeySQL = "SELECT ic.relname AS index_name, a.attname AS column_name,i.indisunique AS unique_key, i.indisprimary AS primary_key FROM pg_class bc, pg_class ic, pg_index i, pg_attribute a WHERE bc.oid = i.indrelid AND ic.oid = i.indexrelid AND (i.indkey[0] = a.attnum OR i.indkey[1] = a.attnum OR i.indkey[2] = a.attnum OR i.indkey[3] = a.attnum OR i.indkey[4] = a.attnum OR i.indkey[5] = a.attnum OR i.indkey[6] = a.attnum OR i.indkey[7] = a.attnum) AND a.attrelid = bc.oid AND bc.relname = '%s'"; var $hasAffectedRows = true; var $hasLimit = false; // set to true for pgsql 7 only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10 // below suggested by Freek Dijkstra var $true = 't'; // string that represents TRUE for a database var $false = 'f'; // string that represents FALSE for a database var $fmtDate = "'Y-m-d'"; // used by DBDate() as the default date format used by the database var $fmtTimeStamp = "'Y-m-d G:i:s'"; // used by DBTimeStamp as the default timestamp fmt. var $hasMoveFirst = true; var $hasGenID = true; var $_genIDSQL = "SELECT NEXTVAL('%s')"; var $_genSeqSQL = "CREATE SEQUENCE %s START %s"; var $_dropSeqSQL = "DROP SEQUENCE %s"; var $metaDefaultsSQL = "SELECT d.adnum as num, d.adsrc as def from pg_attrdef d, pg_class c where d.adrelid=c.oid and c.relname='%s' order by d.adnum"; var $random = 'random()'; /// random function var $concat_operator='||'; function ServerInfo() { $arr['description'] = ADOConnection::GetOne("select version()"); $arr['version'] = ADOConnection::_findvers($arr['description']); return $arr; } function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) { $offsetStr = ($offset >= 0) ? " OFFSET $offset" : ''; $limitStr = ($nrows >= 0) ? " LIMIT $nrows" : ''; if ($secs2cache) $rs =& $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr); else $rs =& $this->Execute($sql."$limitStr$offsetStr",$inputarr); return $rs; } function &MetaTables($ttype=false,$showSchema=false,$mask=false) { $info = $this->ServerInfo(); if ($info['version'] >= 7.3) { $this->metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%' and schemaname not in ( 'pg_catalog','information_schema') union select viewname,'V' from pg_views where viewname not like 'pg\_%' and schemaname not in ( 'pg_catalog','information_schema') "; } if ($mask) { $save = $this->metaTablesSQL; $mask = $this->qstr(strtolower($mask)); if ($info['version']>=7.3) $this->metaTablesSQL = " select tablename,'T' from pg_tables where tablename like $mask and schemaname not in ( 'pg_catalog','information_schema') union select viewname,'V' from pg_views where viewname like $mask and schemaname not in ( 'pg_catalog','information_schema') "; else $this->metaTablesSQL = " select tablename,'T' from pg_tables where tablename like $mask union select viewname,'V' from pg_views where viewname like $mask"; } $ret =& ADOConnection::MetaTables($ttype,$showSchema); if ($mask) { $this->metaTablesSQL = $save; } return $ret; } function &MetaColumns($table,$normalize=true) { global $ADODB_FETCH_MODE; $schema = false; $this->_findschema($table,$schema); if ($normalize) $table = strtolower($table); $save = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); if ($schema) $rs =& $this->Execute(sprintf($this->metaColumnsSQL1,$table,$table,$schema)); else $rs =& $this->Execute(sprintf($this->metaColumnsSQL,$table,$table)); if (isset($savem)) $this->SetFetchMode($savem); $ADODB_FETCH_MODE = $save; if ($rs === false) { $false = false; return $false; } if (!empty($this->metaKeySQL)) { // If we want the primary keys, we have to issue a separate query // Of course, a modified version of the metaColumnsSQL query using a // LEFT JOIN would have been much more elegant, but postgres does // not support OUTER JOINS. So here is the clumsy way. $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; $rskey = $this->Execute(sprintf($this->metaKeySQL,($table))); // fetch all result in once for performance. $keys =& $rskey->GetArray(); if (isset($savem)) $this->SetFetchMode($savem); $ADODB_FETCH_MODE = $save; $rskey->Close(); unset($rskey); } $rsdefa = array(); if (!empty($this->metaDefaultsSQL)) { $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; $sql = sprintf($this->metaDefaultsSQL, ($table)); $rsdef = $this->Execute($sql); if (isset($savem)) $this->SetFetchMode($savem); $ADODB_FETCH_MODE = $save; if ($rsdef) { while (!$rsdef->EOF) { $num = $rsdef->fields['num']; $s = $rsdef->fields['def']; if (strpos($s,'::')===false && substr($s, 0, 1) == "'") { /* quoted strings hack... for now... fixme */ $s = substr($s, 1); $s = substr($s, 0, strlen($s) - 1); } $rsdefa[$num] = $s; $rsdef->MoveNext(); } } else { ADOConnection::outp( "==> SQL => " . $sql); } unset($rsdef); } $retarr = array(); while (!$rs->EOF) { $fld = new ADOFieldObject(); $fld->name = $rs->fields[0]; $fld->type = $rs->fields[1]; $fld->max_length = $rs->fields[2]; if ($fld->max_length <= 0) $fld->max_length = $rs->fields[3]-4; if ($fld->max_length <= 0) $fld->max_length = -1; if ($fld->type == 'numeric') { $fld->scale = $fld->max_length & 0xFFFF; $fld->max_length >>= 16; } // dannym // 5 hasdefault; 6 num-of-column $fld->has_default = ($rs->fields[5] == 't'); if ($fld->has_default) { $fld->default_value = $rsdefa[$rs->fields[6]]; } //Freek if ($rs->fields[4] == $this->true) { $fld->not_null = true; } // Freek if (is_array($keys)) { foreach($keys as $key) { if ($fld->name == $key['column_name'] AND $key['primary_key'] == $this->true) $fld->primary_key = true; if ($fld->name == $key['column_name'] AND $key['unique_key'] == $this->true) $fld->unique = true; // What name is more compatible? } } if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld; else $retarr[($normalize) ? strtoupper($fld->name) : $fld->name] = $fld; $rs->MoveNext(); } $rs->Close(); return empty($retarr) ? false : $retarr; } } class ADODB_pdo_base extends ADODB_pdo { function ServerInfo() { return ADOConnection::ServerInfo(); } function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) { $ret = ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache); return $ret; } function MetaTables() { return false; } function MetaColumns() { return false; } } class ADODB_pdo extends ADOConnection { var $databaseType = "pdo"; var $dataProvider = "pdo"; var $fmtDate = "'Y-m-d'"; var $fmtTimeStamp = "'Y-m-d, h:i:sA'"; var $replaceQuote = "''"; // string to use to replace quotes var $hasAffectedRows = true; var $_bindInputArray = true; var $_genSeqSQL = "create table %s (id integer)"; var $_autocommit = true; var $_haserrorfunctions = true; var $_lastAffectedRows = 0; var $dsnType = ''; var $stmt = false; function ADODB_pdo() { } function _UpdatePDO() { $d = &$this->_driver; $this->fmtDate = $d->fmtDate; $this->fmtTimeStamp = $d->fmtTimeStamp; $this->replaceQuote = $d->replaceQuote; $this->sysDate = $d->sysDate; $this->sysTimeStamp = $d->sysTimeStamp; $this->random = $d->random; $this->concat_operator = $d->concat_operator; } function Time() { return false; } // returns true or false function _connect($argDSN, $argUsername, $argPassword, $argDatabasename, $persist=false) { $at = strpos($argDSN,':'); $this->dsnType = substr($argDSN,0,$at); $this->_connectionID = new PDO($argDSN, $argUsername, $argPassword); if ($this->_connectionID) { switch(ADODB_ASSOC_CASE){ case 0: $m = PDO_CASE_LOWER; break; case 1: $m = PDO_CASE_UPPER; break; default: case 2: $m = PDO_CASE_NATURAL; break; } //$this->_connectionID->setAttribute(PDO_ATTR_ERRMODE,PDO_ERRMODE_SILENT ); $this->_connectionID->setAttribute(PDO_ATTR_CASE,$m); $class = 'ADODB_pdo_'.$this->dsnType; //$this->_connectionID->setAttribute(PDO_ATTR_AUTOCOMMIT,true); if (class_exists($class)) $this->_driver = new $class(); else $this->_driver = new ADODB_pdo_base(); $this->_driver->_connectionID = $this->_connectionID; $this->_UpdatePDO(); return true; } $this->_driver = new ADODB_pdo_base(); return false; } // returns true or false function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename) { return $this->_connect($argDSN, $argUsername, $argPassword, $argDatabasename, true); } /*------------------------------------------------------------------------------*/ function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) { $save = $this->_driver->fetchMode; $this->_driver->fetchMode = $this->fetchMode; $ret = $this->_driver->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache); $this->_driver->fetchMode = $save; return $ret; } function ServerInfo() { return $this->_driver->ServerInfo(); } function MetaTables($ttype=false,$showSchema=false,$mask=false) { return $this->_driver->MetaTables($ttype,$showSchema,$mask); } function MetaColumns($table,$normalize=true) { return $this->_driver->MetaColumns($table,$normalize); } function ErrorMsg() { if ($this->_stmt) $arr = $this->_stmt->errorInfo(); else $arr = $this->_connectionID->errorInfo(); if ($arr) { if ((integer)$arr[0]) return $arr[2]; else return ''; } else return '-1'; } function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false) { $obj = $stmt[1]; if ($type) $obj->bindParam($name,$var,$type,$maxLen); else $obj->bindParam($name, $var); } function ErrorNo() { if ($this->_stmt) $err = $this->_stmt->errorCode(); else { $arr = $this->_connectionID->errorInfo(); if (isset($arr[0])) $err = $arr[0]; else $err = -1; } if ($err == '00000') return 0; // allows empty check return $err; } function BeginTrans() { if (!$this->hasTransactions) return false; if ($this->transOff) return true; $this->transCnt += 1; $this->_autocommit = false; $this->_connectionID->setAttribute(PDO_ATTR_AUTOCOMMIT,false); return $this->_connectionID->beginTransaction(); } function CommitTrans($ok=true) { if (!$this->hasTransactions) return false; if ($this->transOff) return true; if (!$ok) return $this->RollbackTrans(); if ($this->transCnt) $this->transCnt -= 1; $this->_autocommit = true; $ret = $this->_connectionID->commit(); $this->_connectionID->setAttribute(PDO_ATTR_AUTOCOMMIT,true); return $ret; } function RollbackTrans() { if (!$this->hasTransactions) return false; if ($this->transOff) return true; if ($this->transCnt) $this->transCnt -= 1; $this->_autocommit = true; $ret = $this->_connectionID->rollback(); $this->_connectionID->setAttribute(PDO_ATTR_AUTOCOMMIT,true); return $ret; } function Prepare($sql) { $this->_stmt = $this->_connectionID->prepare($sql); if ($this->_stmt) return array($sql,$this->_stmt); return false; } function PrepareStmt($sql) { $stmt = $this->_connectionID->prepare($sql); if (!$stmt) return false; $obj = new ADOPDOStatement($stmt,$this); return $obj; } /* returns queryID or false */ function _query($sql,$inputarr=false) { if (is_array($sql)) { $stmt = $sql[1]; } else { $stmt = $this->_connectionID->prepare($sql); } if ($stmt) { if ($inputarr) $ok = $stmt->execute($inputarr); else $ok = $stmt->execute(); } if ($ok) { $this->_stmt = $stmt; return $stmt; } return false; } // returns true or false function _close() { $this->_stmt = false; return true; } function _affectedrows() { return ($this->_stmt) ? $this->_stmt->rowCount() : 0; } function _insertid() { return ($this->_connectionID) ? $this->_connectionID->lastInsertId() : 0; } } class ADOPDOStatement { var $databaseType = "pdo"; var $dataProvider = "pdo"; var $_stmt; var $_connectionID; function ADOPDOStatement($stmt,$connection) { $this->_stmt = $stmt; $this->_connectionID = $connection; } function Execute($inputArr=false) { $savestmt = $this->_connectionID->_stmt; $rs = $this->_connectionID->Execute(array(false,$this->_stmt),$inputArr); $this->_connectionID->_stmt = $savestmt; return $rs; } function InParameter(&$var,$name,$maxLen=4000,$type=false) { if ($type) $this->_stmt->bindParam($name,$var,$type,$maxLen); else $this->_stmt->bindParam($name, $var); } function Affected_Rows() { return ($this->_stmt) ? $this->_stmt->rowCount() : 0; } function ErrorMsg() { if ($this->_stmt) $arr = $this->_stmt->errorInfo(); else $arr = $this->_connectionID->errorInfo(); print_r($arr); if (is_array($arr)) { if ((integer) $arr[0] && isset($arr[2])) return $arr[2]; else return ''; } else return '-1'; } function NumCols() { return ($this->_stmt) ? $this->_stmt->columnCount() : 0; } function ErrorNo() { if ($this->_stmt) return $this->_stmt->errorCode(); else return $this->_connectionID->errorInfo(); } } /*-------------------------------------------------------------------------------------- Class Name: Recordset --------------------------------------------------------------------------------------*/ class ADORecordSet_pdo extends ADORecordSet { var $bind = false; var $databaseType = "pdo"; var $dataProvider = "pdo"; function ADORecordSet_pdo($id,$mode=false) { if ($mode === false) { global $ADODB_FETCH_MODE; $mode = $ADODB_FETCH_MODE; } $this->adodbFetchMode = $mode; switch($mode) { case ADODB_FETCH_NUM: $mode = PDO_FETCH_NUM; break; case ADODB_FETCH_ASSOC: $mode = PDO_FETCH_ASSOC; break; case ADODB_FETCH_BOTH: default: $mode = PDO_FETCH_BOTH; break; } $this->fetchMode = $mode; $this->_queryID = $id; $this->ADORecordSet($id); } function Init() { if ($this->_inited) return; $this->_inited = true; if ($this->_queryID) @$this->_initrs(); else { $this->_numOfRows = 0; $this->_numOfFields = 0; } if ($this->_numOfRows != 0 && $this->_currentRow == -1) { $this->_currentRow = 0; if ($this->EOF = ($this->_fetch() === false)) { $this->_numOfRows = 0; // _numOfRows could be -1 } } else { $this->EOF = true; } } function _initrs() { global $ADODB_COUNTRECS; $this->_numOfRows = ($ADODB_COUNTRECS) ? @$this->_queryID->rowCount() : -1; if (!$this->_numOfRows) $this->_numOfRows = -1; $this->_numOfFields = $this->_queryID->columnCount(); } // returns the field object function &FetchField($fieldOffset = -1) { $off=$fieldOffset+1; // offsets begin at 1 $o= new ADOFieldObject(); $arr = $this->_queryID->getColumnMeta($fieldOffset); if (!$arr) return false; //adodb_pr($arr); $o->name = $arr['name']; if (isset($arr['native_type'])) $o->type = $arr['native_type']; else $o->type = adodb_pdo_type($arr['pdo_type']); $o->max_length = $arr['len']; $o->precision = $arr['precision']; if (ADODB_ASSOC_CASE == 0) $o->name = strtolower($o->name); else if (ADODB_ASSOC_CASE == 1) $o->name = strtoupper($o->name); return $o; } function _seek($row) { return false; } function _fetch() { if (!$this->_queryID) return false; $this->fields = $this->_queryID->fetch($this->fetchMode); return !empty($this->fields); } function _close() { $this->_queryID = false; } function Fields($colname) { if ($this->adodbFetchMode != ADODB_FETCH_NUM) return @$this->fields[$colname]; if (!$this->bind) { $this->bind = array(); for ($i=0; $i < $this->_numOfFields; $i++) { $o = $this->FetchField($i); $this->bind[strtoupper($o->name)] = $i; } } return $this->fields[$this->bind[strtoupper($colname)]]; } } ?>
mit
werrett/ssh-ldap-publickey
main.go
2793
package main import ( "bufio" "crypto/tls" "flag" "fmt" "net" "net/url" "os" "regexp" "strconv" "strings" "github.com/mavricknz/ldap" ) var config = make(map[string]string) var configFile = "/etc/openldap/ldap.conf" var configRegexp = regexp.MustCompile(`^(\w+)\s+(.+)$`) var sshAttributeName = "sshPublicKey" var flagVerbose bool func init() { flag.BoolVar(&flagVerbose, "verbose", false, "Print errors rather than failing silently") } func main() { flag.Parse() args := flag.Args() if len(args) != 1 { fmt.Println("Must provide user account name.") fmt.Println() fmt.Println("Usage: ssh-ldap-publickey [-verbose] user") os.Exit(1) } uid := strings.TrimSpace(args[0]) // TODO: Whitelist uid. No LDAP query characters. loadConfig() // TODO: Sanity check config var filter string pamFilter := config["pam_filter"] if pamFilter == "" { filter = fmt.Sprintf("(uid=%s)", uid) } else { filter = fmt.Sprintf("(&(%s)(uid=%s))", pamFilter, uid) } attributes := []string{sshAttributeName} port, err := strconv.ParseUint(config["port"], 10, 16) check(err) tlsConfig := tls.Config{InsecureSkipVerify: true} ldapConn := ldap.NewLDAPSSLConnection(config["host"], uint16(port), &tlsConfig) err = ldapConn.Connect() check(err) err = ldapConn.Bind(config["binddn"], config["bindpw"]) check(err) var searchBase string if config["nss_base_passwd"] != "" { searchBase = config["nss_base_passwd"] } else { searchBase = config["base"] } userSearch := ldap.NewSimpleSearchRequest( searchBase, ldap.ScopeSingleLevel, filter, attributes, ) result, err := ldapConn.Search(userSearch) check(err) if len(result.Entries) > 1 { newError("Search returned more than one user account") } else if len(result.Entries) < 1 { newError("No user accounts match search") } var sshAttributeFound = false for _, v := range result.Entries[0].Attributes { if v.Name == sshAttributeName { fmt.Println(v.Values[0]) sshAttributeFound = true } } if !sshAttributeFound { newError("SSH Public Key not found") } } // Load configuration from file. Set the config map. func loadConfig() { file, err := os.Open(configFile) check(err) defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { line := scanner.Text() v := configRegexp.FindStringSubmatch(line) if len(v) != 0 { if v[1] != "" && v[2] != "" { config[strings.ToLower(v[1])] = v[2] } } } err = scanner.Err() check(err) u, err := url.Parse(config["uri"]) check(err) host, port, err := net.SplitHostPort(u.Host) if err != nil { // Then no port specified host = u.Host if u.Scheme == "ldaps" { port = "636" } else { port = "389" } } config["scheme"] = u.Scheme config["host"] = host config["port"] = port }
mit
cruzfg/izi_inventory_tracker
src/main/java/com/izi/inventory/tracker/repository/ParkRepository.java
652
package com.izi.inventory.tracker.repository; import com.izi.inventory.tracker.model.Park; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import java.util.List; /** * Created by cruzfg on 8/18/16. */ @RepositoryRestResource(collectionResourceRel = "parks", path = "parks") public interface ParkRepository extends PagingAndSortingRepository<Park, Long> { List<Park> findByName(@Param("name") String name); }
mit
md2k/fabio
route/target.go
676
package route import ( "net/url" "github.com/eBay/fabio/metrics" ) type Target struct { // Service is the name of the service the targetURL points to Service string // Tags are the list of tags for this target Tags []string // URL is the endpoint the service instance listens on URL *url.URL // FixedWeight is the weight assigned to this target. // If the value is 0 the targets weight is dynamic. FixedWeight float64 // Weight is the actual weight for this service in percent. Weight float64 // Timer measures throughput and latency of this target Timer metrics.Timer // timerName is the name of the timer in the metrics registry timerName string }
mit
techynaf/incuba
model/messages.js
176
Messages = new Mongo.Collection("messages"); Messages.allow({ 'insert' : function(){ return true; }, 'update' : function(){ return true; } });
mit
dmsr45/github_sf_media
src/Service/General.php
26461
<?php namespace App\Service; use Psr\Log\LoggerInterface; use Psr\Log\NullLogger; use Symfony\Component\Yaml\Yaml; class General { const TYPE_BOOL = 'bool'; const TYPE_INT = 'int'; const TYPE_FLOAT = 'float'; const TYPE_NULL = 'null'; const TYPE_ARRAY = 'array'; const TYPE_OBJECT = 'object'; const TYPE_RESOURCE = 'resource'; const TYPE_STRING = 'string'; /** * @var LoggerInterface */ private $logger; /** * Constructeur. */ public function __construct() { } /** * Accesseur. * * @return LoggerInterface */ public function getLogger() { return $this->logger; } /** * Mutateur. * * @param LoggerInterface $logger */ public function setLogger(LoggerInterface $logger = null) { if ($logger instanceof LoggerInterface) { $this->logger = $logger; } else { $this->logger = new NullLogger(); } } /** * Retourne la liste des différents types PHP. * * @return array */ public function getTypes(): array { return [ self::TYPE_BOOL, self::TYPE_INT, self::TYPE_FLOAT, self::TYPE_STRING, self::TYPE_ARRAY, self::TYPE_OBJECT, self::TYPE_RESOURCE, self::TYPE_NULL, ]; } /** * Retourne la liste des différents types scalaires PHP. * * @return array */ public function getTypesScalaires(): array { return [ self::TYPE_BOOL, self::TYPE_INT, self::TYPE_FLOAT, self::TYPE_STRING, ]; } /** * Retourne un message d'erreur pour les exceptions de type DomainException. * * @param string $methode Méthode appelée avec un argument invalide * @param string|int $rang Rang de l'argument invalide * @param mixed $argument Argument invalide * @param array $domain Liste des valeurs autorisées * * @return string * Message d'erreur */ public function messageDomainException( string $methode, $rang = '', $argument = '', array $domain = [] ): string { $message = 'Argument ' . $rang . ' invalide lors de l\'appel de la méthode "' . $methode . '" '; $argument = print_r($argument, true); if (!empty($argument)) { $message = $message . '- Cette méthode ne peut pas être appelée avec l\'argument "' . $argument . '"'; } if (!empty($domain)) { $message = $message . ' - Les arguments valides sont : '; foreach ($domain as $valeur) { $message .= '"' . print_r($valeur, true) . '" '; } } return $message; } /** * Retourne un message d'erreur pour les exceptions de type InvalidArgumentException. * * @param string $methode Méthode appelée avec un argument invalide * @param int $rang Rang de l'argument invalide * @param string $typeAttendu Type valide pour l'argument * @param string $typeFourni Type de l'argument invalide * * @return string * Message d'erreur */ public function messageInvalidArgumentException( string $methode, int $rang = 0, string $typeAttendu = null, string $typeFourni = null ): string { $message = 'Argument '; if ($rang > 0) { $message .= $rang; } $message .= ' de type invalide lors de l\'appel de la méthode "' . $methode . '"'; if (null !== $typeAttendu && null !== $typeFourni) { $message = $message . ' - Type attendu : "' . $typeAttendu . '" - Type fourni : "' . $typeFourni . '"'; } return $message; } /** * Retourne un message d'erreur pour les exceptions de type RuntimeException. * * @param string $methode * Méthode d'où a été lancée l'exception * * @return string * Message d'erreur */ public function messageRuntimeException(string $methode): string { return 'Une erreur est survenue lors de l\'exécution de la méthode "' . $methode . '"'; } /** * Retourne un message d'erreur pour les exceptions de type LogicException. * * @param string $methode * Méthode d'où est issue l'erreur * * @return string * Message d'erreur */ public function messageLogicException(string $methode): string { return 'Une erreur est apparue lors de l\'exécution de la méthode "' . $methode . '" - Cette erreur n\'aurait pas dû survenir, le programme doit être corrigé'; } /** * Retourne le type d'une variable. * * @param mixed $var * Variable dont on souhaite obtenir le type * * @throws \RuntimeException * Lorsque le type n'a pas pu être déterminé * * @return string * Type de la variable $var */ public function getType($var): string { if (is_array($var)) { return self::TYPE_ARRAY; } if (is_bool($var)) { return self::TYPE_BOOL; } if (is_float($var)) { return self::TYPE_FLOAT; } if (is_int($var)) { return self::TYPE_INT; } if (null === $var) { return self::TYPE_NULL; } if (is_object($var)) { return self::TYPE_OBJECT; } if (is_resource($var)) { return self::TYPE_RESOURCE; } if (is_string($var)) { return self::TYPE_STRING; } $message = $this->messageRuntimeException(__METHOD__); $this->logger->error($message); throw new \RuntimeException($message); } /** * Formate une chaîne de caractères censée être égale au type d'une variable. * * @param string $type * Chaîne à formater * * @throws \InvalidArgumentException * Lorsque $type n'est pas de type string * * @return false|string * Retourne false si $type ne correspond pas à un type PHP * Sinon la méthode retourne le type formaté */ public function formaterType($type) { $typeType = $this->getType($type); if (self::TYPE_STRING !== $typeType) { $message = $this->messageInvalidArgumentException( __METHOD__, 1, self::TYPE_STRING, $typeType ); $this->logger->error($message); throw new \InvalidArgumentException($message); } $type = trim(mb_strtolower($type)); if (in_array($type, ['bool', 'boolean'], true)) { return self::TYPE_BOOL; } if (in_array($type, ['double', 'float', 'real'], true)) { return self::TYPE_FLOAT; } if (in_array($type, ['int', 'integer'], true)) { return self::TYPE_INT; } if (in_array($type, $this->getTypes(), true)) { return $type; } return false; } /** * Vérifie qu'une variable passée en paramètre d'une méthode est bien du * type approprié. * * @param mixed $variable Variable dont on souhaite vérifier le type * @param string $typeAttendu Type attendu de $variable * @param string $methode Nom de la méthode * @param int $rang Position de la variable dans les paramètres de la méthode * * @throws \InvalidArgumentException * Lorsqu'un des paramètres n'est pas du type attendu * Lorsque le type de $variable n'est pas égal à $typeAttendu * * @return bool */ public function checkType( $variable, string $typeAttendu, string $methode, int $rang = 0 ): bool { $arguments = [ 2 => [$typeAttendu, self::TYPE_STRING], 3 => [$methode, self::TYPE_STRING], 4 => [$rang, self::TYPE_INT], ]; foreach ($arguments as $rangArgument => $argument) { $typeArgument = $this->getType($argument[0]); if ($typeArgument !== $argument[1]) { $message = $this->messageInvalidArgumentException( __METHOD__, $rangArgument, $argument[1], $typeArgument ); $this->logger->error($message); throw new \InvalidArgumentException($message); } } $typeVariable = $this->getType($variable); $typeAttendu = $this->formaterType($typeAttendu); if ($typeVariable === $typeAttendu) { return true; } $message = $this->messageInvalidArgumentException( $methode, $rang, $typeAttendu, $typeVariable ); $this->logger->error($message); throw new \InvalidArgumentException($message); } /** * Détermine si une chaîne de caractères correspond à un type PHP. * * @param string $type * Chaîne de caractères à analyser, passée par référence pour permettre * son formatage dans le cas où il s'agit d'un type PHP * * @throws \InvalidArgumentException * Lorsque $type n'est pas de type string * * @return bool * Vrai ou faux suivant que l'argument est un type PHP ou pas */ public function isType(&$type): bool { $typeSaved = $type; $type = $this->formaterType($type); if (in_array($type, $this->getTypes(), true)) { return true; } $type = $typeSaved; return false; } /** * Détermine si une chaîne de caractères correspond à un type scalaire PHP. * * @param string $type * Chaîne de caractères à analyser, passée par référence pour permettre * son formatage dans le cas où il s'agit d'un type scalaire * * @throws \InvalidArgumentException * Lorsque l'argument n'est pas de type string * * @return bool * Vrai ou faux suivant que l'argument est un type scalaire ou pas */ public function isTypeScalaire(&$type): bool { $typeSaved = $type; $type = $this->formaterType($type); if (!in_array($type, $this->getTypesScalaires(), true)) { $type = $typeSaved; return false; } return true; } /** * Convertit une variable en variable de type chaîne de caractères (string). * * @param mixed $var * * @return string|false * La méthode retourne false lorsque la conversion n'est pas possible */ public function stringVal($var) { if (empty($var)) { return '0'; } $type = $this->getType($var); if (self::TYPE_ARRAY === $type) { if (1 === count($var)) { $var = $var[0]; $type = $this->getType($var); } } if (!$this->isTypeScalaire($type)) { $log = 'Pas de conversion d\'un élément de type "' . $type . '" en élément de type "' . self::TYPE_STRING . '" lors de l\'appel de la méthode "' . __METHOD__ . '"'; $this->logger->notice($log); return false; } return (string) $var; } /** * Convertit une variable en variable de type entier (int). * * @param mixed $var * * @return false|int * La méthode retourne false lorsque la conversion n'est pas possible */ public function intVal($var) { if (empty($var)) { return 0; } $type = $this->getType($var); if (self::TYPE_ARRAY === $type) { if (1 === count($var)) { $var = $var[0]; $type = $this->getType($var); } } if (!$this->isTypeScalaire($type)) { $log = 'Pas de conversion d\'un élément de type "' . $type . '" en élément de type "' . self::TYPE_INT . '" lors de l\'appel de la méthode "' . __METHOD__ . '"'; $this->logger->notice($log); return false; } if (self::TYPE_STRING === $type) { // A part '0', '00', '000', ..., on ne veut pas qu'une chaîne // de caractères soit traduite par 0 $fullOfZeros = true; $lenVar = mb_strlen($var); $varTronque = $var; for ($i = 0; $i < $lenVar; ++$i) { if ('0' !== $var[$i]) { $fullOfZeros = false; $varTronque = mb_substr($var, $i, $lenVar - $i); break; } } if ($fullOfZeros) { return 0; } if (0 === (int) $varTronque) { $log = 'Pas de conversion d\'un élément de type "' . $type . '" en élément de type "' . self::TYPE_INT . '" lors de l\'appel de la méthode "' . __METHOD__ . '" car cet élément vaut "' . $var . '"'; $this->logger->notice($log); return false; } } return (int) $var; } /** * Convertit une variable en variable de type décimal (float). * * @param mixed $var Variable à convertir * * @return float|false * La méthode retourne false lorsque la conversion n'est pas possible */ public function floatVal($var) { if (empty($var)) { return 0.; } $type = $this->getType($var); if (self::TYPE_ARRAY === $type) { if (1 === count($var)) { $var = $var[0]; $type = $this->getType($var); } } if (!$this->isTypeScalaire($type)) { $log = 'Pas de conversion d\'un élément de type "' . $type . '" en élément de type "' . self::TYPE_FLOAT . '" lors de l\'appel de la méthode "' . __METHOD__ . '"'; $this->logger->notice($log); return false; } if (self::TYPE_STRING === $type) { // A part '0', '00', '000', ..., on ne veut pas qu'une chaîne // de caractères soit traduite par 0. $fullOfZeros = true; $lenVar = mb_strlen($var); $varTronque = $var; for ($i = 0; $i < $lenVar; ++$i) { if ('0' !== $var[$i]) { $fullOfZeros = false; $varTronque = mb_substr($var, $i, $lenVar - $i); break; } } if ($fullOfZeros) { return 0.; } if (0. === (float) $varTronque) { $log = 'Pas de conversion d\'un élément de type "' . $type . '" en élément de type "' . self::TYPE_FLOAT . '" lors de l\'appel de la méthode "' . __METHOD__ . '" car cet élément vaut "' . $var . '"'; $this->logger->notice($log); return false; } } return (float) $var; } /** * Retourne la concaténation des noms de répertoire à l'aide du séparateur * de dossiers. * * @throws \InvalidArgumentException * Lorsque l'un des arguments n'est pas de type string * * @return string|false * La méthode retourne false quand elle est appelée sans paramètres */ public function buildFullFilename() { if (func_num_args() > 0) { $arguments = func_get_args(); foreach ($arguments as $cle => $argument) { $this->checkType( $argument, self::TYPE_STRING, __METHOD__, $cle + 1 ); } return implode(\DIRECTORY_SEPARATOR, $arguments); } $log = 'La méthode "' . __METHOD__ . '" a été appelée sans arguments !'; $this->logger->notice($log); return ''; } /** * Retourne un tableau de correspondance entre caractères spéciaux * et caractères simples. * * @return array */ public function mapsSpecialCharsToSimpleChars(): array { return [ 'Š' => 'S', 'š' => 's', 'Ð' => 'Dj', 'Ž' => 'Z', 'ž' => 'z', 'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'A', 'Å' => 'A', 'Æ' => 'A', 'Ç' => 'C', 'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I', 'Ï' => 'I', 'Ñ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => 'O', 'Ø' => 'O', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'U', 'Ý' => 'Y', 'Þ' => 'B', 'ß' => 'Ss', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a', 'å' => 'a', 'æ' => 'a', 'ç' => 'c', 'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'ð' => 'o', 'ñ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'o', 'ø' => 'o', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ü' => 'u', 'ý' => 'y', 'þ' => 'b', 'ÿ' => 'y', 'ƒ' => 'f', ]; } /** * Remplace les caractères spéciaux d'une chaîne de caractères * par des caractères simples. * * @param string $chaine * Chaîne de caractères à simplifier * * @throws \TypeError * Dans le cas où l'argument fourni n'est pas de type string * * @return string * Chaîne de caractères simplifiée (sans accents, sans cédilles, ...) */ public function remplacerCaracteresSpeciaux(string $chaine) { return strtr($chaine, $this->mapsSpecialCharsToSimpleChars()); } /** * Méthode permettant de simplifier une chaîne de caractères. * * Cette méthode s'efforce de garder l'essentiel de la chaîne en supprimant * les caractères inutiles et en remplaçant les caractères spéciaux par des * caractères simples * * @param string $chaine * Chaîne de caractères à simplifier * @param bool $replaceSpecialChars * A mettre à true (valeur par défaut) si l'on souhaite simplifier * les caractères spéciaux (sinon mettre false) * @param array $charsToDelete * Tableau des caractères à supprimer * @param array $charsToReplace * Tableau des caractères à remplacer * @param string $replacementChar * Caractère de remplacement pour les caractères de $charsToReplace * @param array $doublesToDelete * Tableau des caractères dont on veut supprimer les doublons * * @throws \TypeError * Lorsque l'un des argument n'est pas du type approprié * Dans le cas où l'argument est un tableau, les éléments du tableau * sont vérifiés (ils doivent être de type string) * * @return string * Chaîne de caractères simplifiée (en minuscules) */ public function simplifierChaine( string $chaine, bool $replaceSpecialChars = true, array $charsToDelete = [], array $charsToReplace = [' ', '\'', '"', '_', '.'], string $replacementChar = '-', array $doublesToDelete = ['-'] ): string { if ('' === $chaine) { return $chaine; } if (!empty($charsToReplace) && empty($replacementChar)) { $message = 'Lors de l\'appel de la méthode "' . __METHOD__ . '" il a été demandé de remplacer des caractères de la chaîne "' . $chaine . 'par la chaîne de caractères vide \'\', ce qui revient à demander ' . 'que ces caractères soient supprimés...'; $this->logger->notice($message); } if ([] !== empty($charsToDelete)) { $chaine = str_replace($charsToDelete, '', $chaine); } $chaine = trim($chaine); if ([] !== $replaceSpecialChars) { $chaine = $this->remplacerCaracteresSpeciaux($chaine); } if ([] !== $charsToReplace) { $chaine = str_replace($charsToReplace, $replacementChar, $chaine); } foreach ($doublesToDelete as $char) { $expr = '/[\\' . $char . ']+/'; $chaine = preg_replace($expr, $char, $chaine); } while ($chaine[0] === $replacementChar) { $chaine = mb_substr($chaine, 1); } while (mb_substr($chaine, -1, 1) === $replacementChar) { $chaine = mb_substr($chaine, 0, mb_strlen($chaine) - 1); } return mb_strtolower($chaine); } /** * Retourne la chaîne de caractère correspondant à un nombre décimal. * * @param $nombre * Le nombre décimal à traiter * @param $nbMaxiChiffresDecimaux * Le nombre de chiffres après la virgule à afficher (au maximum) * @param $separateurDecimal * Point ou virgule * @param $separateurMilliers = ' ' * Espace, point ou rien * * @return string */ public function nombreToString( float $nombre, int $nbMaxiChiffresDecimaux = 4, string $separateurDecimal = ',', string $separateurMilliers = ' ' ): string { $nbChiffresApresVirgule = 0; // Pour que les chiffres après la virgule soient significatifs : $nbMaxiChiffresDecimaux = min( $nbMaxiChiffresDecimaux, max(0, ini_get('precision') - ceil(log10($nombre)) - 1) ); $plafond = 1000; $go = ($nombre < $plafond); while ($go) { ++$nbChiffresApresVirgule; $plafond /= 10; $go = (($nombre < $plafond) && ($nbChiffresApresVirgule < $nbMaxiChiffresDecimaux)); } return number_format( $nombre, $nbChiffresApresVirgule, $separateurDecimal, $separateurMilliers ); } /** * Retourne l'horodatage (timestamp), i. e. le nombre de secondes écoulées * depuis le 1er janvier 1970 minuit (ordre de grandeur : 1.45 milliards). * * @param null|string $operation * * @throws \TypeError * Lorsque l'un des arguments n'est pas du type approprié * * @return float */ public function tic(string $operation = null): float { if (null !== $operation) { $this->logger->debug($operation); } return microtime(true); } /** * Retourne le nombre de secondes écoulées depuis le tic précédent. * * @param float $tic * @param string $operation * * @throws \TypeError * Lorsque l'un des arguments n'est pas du type approprié * * @return string */ public function toc(float $tic, string $operation = null) { $duree = microtime(true) - $tic; $affichageDuree = $this->nombreToString($duree, 4); if (false === $affichageDuree) { return ''; } if (null !== $operation) { $log = $operation . ' effectué en '; } else { $log = 'Effectué en '; } $log .= $affichageDuree . ' seconde'; if ($duree > 1.) { $log .= 's'; } $this->logger->debug($log); return $affichageDuree; } /** * Retourne le contenu d'un fichier yaml sous la forme d'un tableau PHP. * * @param string $fileName * * @throws \LogicException * Lorsque le fichier n'existe pas ou est vide * * @return array */ public function getYamlContent(string $fileName): array { if (!file_exists($fileName)) { $message = 'Fichier "' . $fileName . '" introuvable ! "'; $this->logger->error($message); throw new \LogicException($message); } $tab = Yaml::parse(file_get_contents($fileName)); if (empty($tab)) { $message = 'Le contenu du fichier "' . $fileName . '" est vide !'; $this->logger->error($message); throw new \LogicException($message); } return $tab; } }
mit
hgabka/KunstmaanBundlesCMS
src/Kunstmaan/MediaBundle/Helper/RemoteSlide/RemoteSlideHandler.php
4764
<?php namespace Kunstmaan\MediaBundle\Helper\RemoteSlide; use Kunstmaan\MediaBundle\Entity\Media; use Kunstmaan\MediaBundle\Form\RemoteSlide\RemoteSlideType; use Kunstmaan\MediaBundle\Helper\Media\AbstractMediaHandler; /** * RemoteSlideStrategy. */ class RemoteSlideHandler extends AbstractMediaHandler { /** * @var string */ const CONTENT_TYPE = 'remote/slide'; const TYPE = 'slide'; /** * @return string */ public function getName() { return 'Remote Slide Handler'; } /** * @return string */ public function getType() { return self::TYPE; } /** * @return string */ public function getFormType() { return RemoteSlideType::class; } /** * @param mixed $object * * @return bool */ public function canHandle($object) { if ( (is_string($object)) || ($object instanceof Media && self::CONTENT_TYPE === $object->getContentType()) ) { return true; } return false; } /** * @param Media $media * * @return RemoteSlideHelper */ public function getFormHelper(Media $media) { return new RemoteSlideHelper($media); } /** * @param Media $media * * @throws \RuntimeException when the file does not exist */ public function prepareMedia(Media $media) { if (null === $media->getUuid()) { $uuid = uniqid(); $media->setUuid($uuid); } $slide = new RemoteSlideHelper($media); $code = $slide->getCode(); // update thumbnail switch ($slide->getType()) { case 'slideshare': try { $json = json_decode( file_get_contents( 'https://www.slideshare.net/api/oembed/2?url=https://www.slideshare.net/slideshow/embed_code/key/'.$code.'&format=json' ) ); $slide->setThumbnailUrl($json->thumbnail); } catch (\ErrorException $e) { // Silent exception - should not bubble up since failure to create a thumbnail is not a fatal error } break; } } /** * @param Media $media */ public function saveMedia(Media $media) { } /** * @param Media $media */ public function removeMedia(Media $media) { } /** * {@inheritdoc} */ public function updateMedia(Media $media) { } /** * @param array $params * * @return array */ public function getAddUrlFor(array $params = []) { return [ 'slide' => [ 'path' => 'KunstmaanMediaBundle_folder_slidecreate', 'params' => [ 'folderId' => $params['folderId'], ], ], ]; } /** * @param mixed $data * * @return Media */ public function createNew($data) { $result = null; if (is_string($data)) { if (0 !== strpos($data, 'http')) { $data = 'https://'.$data; } $parsedUrl = parse_url($data); switch ($parsedUrl['host']) { case 'www.slideshare.net': case 'slideshare.net': $result = new Media(); $slide = new RemoteSlideHelper($result); $slide->setType('slideshare'); $json = json_decode( file_get_contents('https://www.slideshare.net/api/oembed/2?url='.$data.'&format=json') ); $slide->setCode($json->{'slideshow_id'}); $result = $slide->getMedia(); $result->setName('SlideShare '.$data); break; } } return $result; } /** * {@inheritdoc} */ public function getShowTemplate(Media $media) { return 'KunstmaanMediaBundle:Media\RemoteSlide:show.html.twig'; } /** * @param Media $media The media entity * @param string $basepath The base path * * @return string */ public function getImageUrl(Media $media, $basepath) { $helper = new RemoteSlideHelper($media); return $helper->getThumbnailUrl(); } /** * @return array */ public function getAddFolderActions() { return [ self::TYPE => [ 'type' => self::TYPE, 'name' => 'media.slide.add', ], ]; } }
mit
grokify/swaggman
openapi3lint/openapi3lint1/check_parameters.go
916
package openapi3lint1 import ( "strconv" "strings" oas3 "github.com/getkin/kin-openapi/openapi3" "github.com/grokify/simplego/text/stringcase" ) func ParametersCheck(params oas3.Parameters, jsPointerParameters string, rules Policy) PolicyViolationsSets { vsets := NewPolicyViolationsSets() for i, paramRef := range params { if paramRef.Value != nil { paramName := paramRef.Value.Name if strings.ToLower(paramRef.Value.In) == "path" { jsPointerPath := PointerCondense(jsPointerParameters + "/parameters/" + strconv.Itoa(i) + "/name") if len(paramName) == 0 { vsets.AddSimple( RulePathParamNameExist, jsPointerPath, paramName) } else { if rules.HasRule(RulePathParamStyleCamelCase) && !stringcase.IsCamelCase(paramName) { vsets.AddSimple( RulePathParamStyleCamelCase, jsPointerPath, paramName) } } } } } return vsets }
mit