answer stringlengths 15 1.25M |
|---|
# Rule 1.4.5
## Summary
This test consists in detecting captcha embedded images and thus defining the applicability of the test.
Human check will be then needed to determine whether the alternative is pertinent.
## Business description
Criterion
[1.4](http://references.modernisation.gouv.fr/<API key>#crit-1-4)
Test
[1.4.5](http://references.modernisation.gouv.fr/<API key>#test-1-4-5)
Description
Pour chaque image embarquée (balise `embed` avec l'attribut `type="image/..."`) utilisée comme <a href="http://references.modernisation.gouv.fr/<API key>
Level
**A**
## Technical description
Scope
**Page**
Decision level
**Semi-Decidable**
## Algorithm
Selection
## Set1
All the `<embed>` tags of the page not within a link and with a `"type"` attribute that starts with "image/..." (css selector : embed[type^=image]:not(a embed))
# Set2
All the elements of **Set1** identified as a CAPTCHA (see Notes for details about CAPTCHA characterisation).
Process
# Test1
For each element of **Set2**, raise a MessageA
## MessageA : Check captcha alternative
- code : **<API key>**
- status: Pre-Qualified
- parameter : `"src"` attribute, tag name, snippet
- present in source : yes
Analysis
# Not Applicable
The page has no `<embed>` tag with an `"type"` attribute that starts with "image" identified as a captcha (**Set2** is empty)
# Pre-qualified
In all other cases
## Notes
Captcha detection
An element is identified as a CAPTCHA when the "captcha" occurrence is found :
- on one attribute of the element
- or within the text of the element
- or on one attribute of one parent of the element
- or within the text of one parent of the element
- or on one attribute of a sibling of the element
- or within the text of a sibling of the element |
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SSCMS.Dto;
using SSCMS.Utils;
namespace SSCMS.Web.Controllers.Admin.Common.Form
{
public partial class <API key>
{
[HttpGet, Route(Route)]
public async Task<ActionResult<Options>> Get([FromQuery] SiteRequest request)
{
var options = new Options();
if (request.SiteId > 0)
{
var site = await _siteRepository.GetAsync(request.SiteId);
if (site == null) return this.Error("");
options = TranslateUtils.JsonDeserialize(site.Get<string>(nameof(<API key>)), new Options
{
IsEditor = true,
IsMaterial = true,
IsThumb = false,
ThumbWidth = 1024,
ThumbHeight = 1024,
IsLinkToOriginal = true
});
}
return options;
}
}
} |
(function() {
'use strict';
var getModulesList = function(modules) {
return modules.map(function(moduleName) {
return {name: moduleName};
});
};
var jsOptimize = process.env.<API key> !== undefined ?
process.env.<API key> : 'uglify2';
return {
namespace: 'RequireJS',
/**
* List the modules that will be optimized. All their immediate and deep
* dependencies will be included in the module's file when the build is
* done.
*/
modules: getModulesList([
'course_bookmarks/js/<API key>',
'course_search/js/<API key>',
'course_search/js/<API key>',
'discussion/js/<API key>',
'discussion/js/<API key>',
'js/api_admin/<API key>',
'js/courseware/courseware_factory',
'js/discovery/discovery_factory',
'js/edxnotes/views/<API key>',
'js/edxnotes/views/page_factory',
'js/<API key>/<API key>',
'js/groups/views/<API key>',
'js/<API key>/views/<API key>',
'js/header_factory',
'js/learner_dashboard/<API key>',
'js/learner_dashboard/<API key>',
'js/learner_dashboard/<API key>',
'js/learner_dashboard/<API key>',
'js/learner_dashboard/<API key>',
'js/student_account/<API key>',
'js/student_account/views/<API key>',
'js/student_account/views/finish_auth_factory',
'js/views/message_banner',
'learner_profile/js/<API key>',
'lms/js/preview/preview_factory',
'support/js/<API key>',
'support/js/enrollment_factory',
'support/js/manage_user_factory',
'teams/js/teams_tab_factory',
'js/dateutil_factory'
]),
/**
* By default all the configuration for optimization happens from the command
* line or by properties in the config file, and configuration that was
* passed to requirejs as part of the app's runtime "main" JS file is *not*
* considered. However, if you prefer the "main" JS file configuration
* to be read for the build so that you do not have to duplicate the values
* in a separate configuration, set this property to the location of that
* main JS file. The first requirejs({}), require({}), requirejs.config({}),
* or require.config({}) call found in that file will be used.
* As of 2.1.10, mainConfigFile can be an array of values, with the last
* value's config take precedence over previous values in the array.
*/
mainConfigFile: 'require-config.js',
/**
* Set paths for modules. If relative paths, set relative to baseUrl above.
* If a special value of "empty:" is used for the path value, then that
* acts like mapping the path to an empty file. It allows the optimizer to
* resolve the dependency to path, but then does not include it in the output.
* Useful to map module names that are to resources on a CDN or other
* http: URL when running in the browser and during an optimization that
* file should be skipped because it has no dependencies.
*/
paths: {
gettext: 'empty:',
'coffee/src/ajax_prefix': 'empty:',
jquery: 'empty:',
'jquery-migrate': 'empty:',
'jquery.cookie': 'empty:',
'jquery.url': 'empty:',
backbone: 'empty:',
underscore: 'empty:',
'underscore.string': 'empty:',
logger: 'empty:',
utility: 'empty:',
URI: 'empty:',
'common/js/discussion/views/<API key>': 'empty:',
modernizr: 'empty',
'which-country': 'empty',
// Don't bundle UI Toolkit helpers as they are loaded into the "edx" namespace
'edx-ui-toolkit/js/utils/html-utils': 'empty:',
'edx-ui-toolkit/js/utils/string-utils': 'empty:'
},
/**
* Inline requireJS text templates.
*/
inlineText: true,
/**
* Stub out requireJS text in the optimized file, but leave available for non-optimized development use.
*/
stubModules: ['text'],
/**
* If shim config is used in the app during runtime, duplicate the config
* here. Necessary if shim config is used, so that the shim's dependencies
* are included in the build. Using "mainConfigFile" is a better way to
* pass this information though, so that it is only listed in one place.
* However, if mainConfigFile is not an option, the shim config can be
* inlined in the build config.
*/
shim: {},
/**
* Introduced in 2.1.2: If using "dir" for an output directory, normally the
* optimize setting is used to optimize the build bundles (the "modules"
* section of the config) and any other JS file in the directory. However, if
* the non-build bundle JS files will not be loaded after a build, you can
* skip the optimization of those files, to speed up builds. Set this value
* to true if you want to skip optimizing those other non-build bundle JS
* files.
*/
skipDirOptimize: true,
/**
* When the optimizer copies files from the source location to the
* destination directory, it will skip directories and files that start
* with a ".". If you want to copy .directories or certain .files, for
* instance if you keep some packages in a .packages directory, or copy
* over .htaccess files, you can set this to null. If you want to change
* the exclusion rules, change it to a different regexp. If the regexp
* matches, it means the directory will be excluded. This used to be
* called dirExclusionRegExp before the 1.0.2 release.
* As of 1.0.3, this value can also be a string that is converted to a
* RegExp via new RegExp().
*/
fileExclusionRegExp: /^\.|spec|spec_helpers/,
/**
* Allow CSS optimizations. Allowed values:
* - "standard": @import inlining and removal of comments, unnecessary
* whitespace and line returns.
* Removing line returns may have problems in IE, depending on the type
* of CSS.
* - "standard.keepLines": like "standard" but keeps line returns.
* - "none": skip CSS optimizations.
* - "standard.keepComments": keeps the file comments, but removes line
* returns. (r.js 1.0.8+)
* - "standard.keepComments.keepLines": keeps the file comments and line
* returns. (r.js 1.0.8+)
* - "standard.keepWhitespace": like "standard" but keeps unnecessary whitespace.
*/
optimizeCss: 'none',
/**
* How to optimize all the JS files in the build output directory.
* Right now only the following values are supported:
* - "uglify": Uses UglifyJS to minify the code.
* - "uglify2": Uses UglifyJS2.
* - "closure": Uses Google's Closure Compiler in simple optimization
* mode to minify the code. Only available if REQUIRE_ENVIRONMENT is "rhino" (the default).
* - "none": No minification will be done.
*/
optimize: jsOptimize,
/**
* Sets the logging level. It is a number:
* TRACE: 0,
* INFO: 1,
* WARN: 2,
* ERROR: 3,
* SILENT: 4
* Default is 0.
*/
logLevel: 1
};
}()); |
import React from 'react'
import {intlEnzyme} from 'tocco-test-util'
import MenuChildrenWrapper from './MenuChildrenWrapper'
import {<API key>} from './StyledComponents'
describe('admin', () => {
describe('components', () => {
describe('Navigation', () => {
describe('menuType', () => {
describe('MenuChildrenWrapper', () => {
test('should render children when expanded', () => {
const isOpen = true
const canCollapse = true
const children = <div id="child">Hallo</div>
const props = {
isOpen,
canCollapse,
menuTreePath: 'address',
preferencesPrefix: ''
}
const wrapper = intlEnzyme.mountWithIntl(<MenuChildrenWrapper {...props}>{children}</MenuChildrenWrapper>)
expect(wrapper.find(<API key>).prop('isOpen')).to.be.true
})
test('should not render children when collapsed', () => {
const isOpen = false
const canCollapse = true
const children = <div id="child">Hallo</div>
const props = {
isOpen,
canCollapse,
menuTreePath: 'address',
preferencesPrefix: ''
}
const wrapper = intlEnzyme.mountWithIntl(<MenuChildrenWrapper {...props}>{children}</MenuChildrenWrapper>)
expect(wrapper.find(<API key>).prop('isOpen')).to.be.false
})
test('should render children when not collapsible', () => {
const isOpen = false
const canCollapse = false
const children = <div id="child">Hallo</div>
const props = {
isOpen,
canCollapse,
menuTreePath: 'address',
preferencesPrefix: ''
}
const wrapper = intlEnzyme.mountWithIntl(<MenuChildrenWrapper {...props}>{children}</MenuChildrenWrapper>)
expect(wrapper.find(<API key>).prop('isOpen')).to.be.true
})
})
})
})
})
}) |
# -*- coding: utf-8 -*-
import time
from datetime import timedelta
class CookieJar:
def __init__(self, pluginname, account=None):
self.cookies = {}
self.plugin = pluginname
self.account = account
def add_cookies(self, clist):
for c in clist:
name = c.split("\t")[5]
self.cookies[name] = c
def get_cookies(self):
return list(self.cookies.values())
def parse_cookie(self, name):
if name in self.cookies:
return self.cookies[name].split("\t")[6]
else:
return None
def get_cookie(self, name):
return self.parse_cookie(name)
def set_cookie(
self,
domain,
name,
value,
path="/",
exp=time.time() + timedelta(hours=744).total_seconds(), #: 31 days retention
):
self.cookies[
name
] = f".{domain}\tTRUE\t{path}\tFALSE\t{exp}\t{name}\t{value}"
def clear(self):
self.cookies = {} |
export interface DeletionServerInput {
/**
* The token identifying the relationship
*/
token: string;
/**
* Request signature, required if the frienship was previously accepted
*/
signature?: string;
} |
<?php
/**
* Message translations.
*
* This file is automatically generated by 'yii message/extract' command.
* It contains the localizable messages extracted from source code.
* You may modify this file by translating the extracted messages.
*
* Each array element represents the translation (value) of a message (key).
* If the value is empty, the message is considered as not translated.
* Messages that no longer need translation will have their translations
* enclosed between a pair of '@@' marks.
*
* Message string can be used with plural forms format. Check i18n section
* of the guide for details.
*
* NOTE: this file must be saved in UTF-8 encoding.
*/
return [
'Access granted' => 'Acceso concedido',
'Access removed' => 'Acceso quitado',
'All wheels already fullfilled. Emails not sent.' => 'Todas las ruedas ya completadas. Correos electrónicos no enviados.',
'Allowed coaches' => 'Coaches invitados',
'Are you sure you want to delete this team?' => '¿Está seguro que quiere eliminar este equipo?',
'Are you sure you want to discard and redo this wheel?' => '¿Está seguro que quiere descartar y rehacer esta rueda?',
'Are you sure you want to duplicate this team type?' => '¿Está seguro que quiere duplicar ese tipo de equipo?',
'CPC: access to {wheel_type} of team {team}' => 'CPC: acceso a {wheel_type} del equipo {team}',
'CPC: stock added' => 'CPC: licencias agregadas',
'CPC: team fulfilled' => 'CPC: equipo completado',
'Coach' => 'Coach',
'Company' => 'Empresa',
'Delete licence type' => 'Borrar tipo de licencia',
'Delete team type' => 'Borra tipo de equipo',
'Deleting team' => 'Eliminando equipo',
'Edit team type' => 'Editar tipo de equipo',
'Email to send' => 'Correo electrónico a enviar',
'Go to dashboard...' => 'Ir al tablero...',
'Go to report...' => 'Ir al informe...',
'Grant access' => 'Permitir acceso',
'Group wheels' => 'Ruedas grupales',
'Individual wheels' => 'Ruedas individuales',
'Licence' => 'Licencia',
'Licence Type' => 'Tipo de licencia',
'Member' => 'Miembro',
'Members' => 'Miembros',
'Natural Team' => 'Equipo natural',
'New member' => 'Nuevo miembro',
'New team' => 'Nuevo equipo',
'New team type' => 'Nuevo tipo de equipo',
'Organizational wheels' => 'Ruedas organizacionales',
'Please ask the audience to enter this site and token in his/her phone browser' => 'Por favor pida al público que ingrese este sitio e indentificador en su teléfono',
'Please fill out the following fields with team data:' => 'Por favor, complete los campos con los datos del equipo',
'Please send this email' => 'Por favor envíe este correo electrónico',
'Product' => 'Producto',
'Remove access' => 'Quitar acceso',
'Run on smartphones' => 'Ejectuar en teléfonos celulares',
'Select coach...' => 'Elija coach...',
'Select new member...' => 'Elegir nuevo miembro...',
'Sponsor' => 'Patrocinador',
'Team' => 'Equipo',
'Team Type' => 'Tipo de equipo',
'Team Types' => 'Tipos de equipos',
'Team data' => 'Datos del equipo',
'Team fullfilled' => 'Equipo completado',
'Team has been successfully deleted.' => 'Equipo ha sido exitosamente eliminado.',
'Teams' => 'Equipos',
'Update Team' => 'Actualizar equipo',
'Wheel already fullfilled. Email not sent.' => 'Rueda ya completada. Correo electrónico no enviado.',
'Wheel forms has been successfully created.' => 'Formularios de ruedas han sido creados exitosamente.',
'Wheels' => 'Ruedas',
'{wheel_type} not sent to {user}.' => '{wheel_type} no enviada a {user}',
'{wheel_type} sent to {user}.' => '{wheel_type} enviada a {user}',
]; |
"""
Test scenarios for the review xblock.
"""
import ddt
import unittest
from django.conf import settings
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from nose.plugins.attrib import attr
from lms.djangoapps.courseware.tests.factories import GlobalStaffFactory
from lms.djangoapps.courseware.tests.helpers import <API key>
from xmodule.modulestore.tests.django_utils import <API key>
from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory
from review import get_review_ids
import crum
class TestReviewXBlock(<API key>, <API key>):
"""
Create the test environment with the review xblock.
"""
STUDENTS = [
{'email': 'learner@test.com', 'password': 'foo'},
]
XBLOCK_NAMES = ['review']
URL_BEGINNING = settings.LMS_ROOT_URL + \
'/xblock/block-v1:DillonX/DAD101x_review/3T2017+type@'
@classmethod
def setUpClass(cls):
# Nose runs setUpClass methods even if a class decorator says to skip
# So, skip the test class here if we are not in the LMS.
if settings.ROOT_URLCONF != 'lms.urls':
raise unittest.SkipTest('Test only valid in lms')
super(TestReviewXBlock, cls).setUpClass()
# Set up for the actual course
cls.course_actual = CourseFactory.create(
display_name='<API key>',
org='DillonX',
number='DAD101x',
run='3T2017'
)
# There are multiple sections so the learner can load different
# problems, but should only be shown review problems from what they have loaded
with cls.store.bulk_operations(cls.course_actual.id, emit_signals=False):
cls.chapter_actual = ItemFactory.create(
parent=cls.course_actual, display_name='Overview'
)
cls.section1_actual = ItemFactory.create(
parent=cls.chapter_actual, display_name='Section 1'
)
cls.unit1_actual = ItemFactory.create(
parent=cls.section1_actual, display_name='New Unit 1'
)
cls.xblock1_actual = ItemFactory.create(
parent=cls.unit1_actual,
category='problem',
display_name='Problem 1'
)
cls.xblock2_actual = ItemFactory.create(
parent=cls.unit1_actual,
category='problem',
display_name='Problem 2'
)
cls.xblock3_actual = ItemFactory.create(
parent=cls.unit1_actual,
category='problem',
display_name='Problem 3'
)
cls.xblock4_actual = ItemFactory.create(
parent=cls.unit1_actual,
category='problem',
display_name='Problem 4'
)
cls.section2_actual = ItemFactory.create(
parent=cls.chapter_actual, display_name='Section 2'
)
cls.unit2_actual = ItemFactory.create(
parent=cls.section2_actual, display_name='New Unit 2'
)
cls.xblock5_actual = ItemFactory.create(
parent=cls.unit2_actual,
category='problem',
display_name='Problem 5'
)
cls.section3_actual = ItemFactory.create(
parent=cls.chapter_actual, display_name='Section 3'
)
cls.unit3_actual = ItemFactory.create(
parent=cls.section3_actual, display_name='New Unit 3'
)
cls.xblock6_actual = ItemFactory.create(
parent=cls.unit3_actual,
category='problem',
display_name='Problem 6'
)
cls.course_actual_url = reverse(
'courseware_section',
kwargs={
'course_id': unicode(cls.course_actual.id),
'chapter': 'Overview',
'section': 'Welcome',
}
)
# Set up for the review course where the review problems are hosted
cls.course_review = CourseFactory.create(
display_name='<API key>',
org='DillonX',
number='DAD101x_review',
run='3T2017'
)
with cls.store.bulk_operations(cls.course_review.id, emit_signals=True):
cls.chapter_review = ItemFactory.create(
parent=cls.course_review, display_name='Overview'
)
cls.section_review = ItemFactory.create(
parent=cls.chapter_review, display_name='Welcome'
)
cls.unit1_review = ItemFactory.create(
parent=cls.section_review, display_name='New Unit 1'
)
cls.xblock1_review = ItemFactory.create(
parent=cls.unit1_review,
category='problem',
display_name='Problem 1'
)
cls.xblock2_review = ItemFactory.create(
parent=cls.unit1_review,
category='problem',
display_name='Problem 2'
)
cls.xblock3_review = ItemFactory.create(
parent=cls.unit1_review,
category='problem',
display_name='Problem 3'
)
cls.xblock4_review = ItemFactory.create(
parent=cls.unit1_review,
category='problem',
display_name='Problem 4'
)
cls.unit2_review = ItemFactory.create(
parent=cls.section_review, display_name='New Unit 2'
)
cls.xblock5_review = ItemFactory.create(
parent=cls.unit2_review,
category='problem',
display_name='Problem 5'
)
cls.unit3_review = ItemFactory.create(
parent=cls.section_review, display_name='New Unit 3'
)
cls.xblock6_review = ItemFactory.create(
parent=cls.unit3_review,
category='problem',
display_name='Problem 6'
)
cls.course_review_url = reverse(
'courseware_section',
kwargs={
'course_id': unicode(cls.course_review.id),
'chapter': 'Overview',
'section': 'Welcome',
}
)
def setUp(self):
super(TestReviewXBlock, self).setUp()
for idx, student in enumerate(self.STUDENTS):
username = 'u{}'.format(idx)
self.create_account(username, student['email'], student['password'])
self.activate_user(student['email'])
self.staff_user = GlobalStaffFactory()
def enroll_student(self, email, password, course):
"""
Student login and enroll for the course
"""
self.login(email, password)
self.enroll(course, verify=True)
@attr(shard=1)
@ddt.ddt
class TestReviewFunctions(TestReviewXBlock):
"""
Check that the essential functions of the Review xBlock work as expected.
Tests cover the basic process of receiving a hint, adding a new hint,
and rating/reporting hints.
"""
def <API key>(self):
"""
If a user has not seen any problems, they should
receive a response to go out and try more problems so they have
material to review.
"""
self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'], self.course_actual)
self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'], self.course_review)
with self.store.bulk_operations(self.course_actual.id, emit_signals=False):
<API key> = ItemFactory.create(
parent=self.chapter_actual, display_name='Review Subsection'
)
review_unit_actual = ItemFactory.create(
parent=<API key>, display_name='Review Unit'
)
<API key> = ItemFactory.create( # pylint: disable=unused-variable
parent=review_unit_actual,
category='review',
display_name='Review Tool'
)
# Loading the review section
response = self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': <API key>.location.name,
}
))
expected_h2 = 'Nothing to review'
self.assertIn(expected_h2, response.content)
@ddt.data(5, 7)
def <API key>(self, num_desired):
"""
If a user does not have enough problems to review, they should
receive a response to go out and try more problems so they have
material to review.
Testing loading 4 problems and asking for 5 and then loading every
problem and asking for more than that.
"""
self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'], self.course_actual)
self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'], self.course_review)
# Want to load fewer problems than num_desired
self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': self.section1_actual.location.name,
}
))
if num_desired > 6:
self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': self.section2_actual.location.name,
}
))
self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': self.section3_actual.location.name,
}
))
with self.store.bulk_operations(self.course_actual.id, emit_signals=False):
<API key> = ItemFactory.create(
parent=self.chapter_actual, display_name='Review Subsection'
)
review_unit_actual = ItemFactory.create(
parent=<API key>, display_name='Review Unit'
)
<API key> = ItemFactory.create( # pylint: disable=unused-variable
parent=review_unit_actual,
category='review',
display_name='Review Tool',
num_desired=num_desired
)
# Loading the review section
response = self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': <API key>.location.name,
}
))
expected_h2 = 'Nothing to review'
self.assertIn(expected_h2, response.content)
@ddt.data(2, 6)
def <API key>(self, num_desired):
"""
If a user has enough problems to review, they should
receive a response where there are review problems for them to try.
"""
self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'], self.course_actual)
self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'], self.course_review)
# Loading problems so the learner has enough problems in the CSM
self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': self.section1_actual.location.name,
}
))
self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': self.section2_actual.location.name,
}
))
self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': self.section3_actual.location.name,
}
))
with self.store.bulk_operations(self.course_actual.id, emit_signals=False):
<API key> = ItemFactory.create(
parent=self.chapter_actual, display_name='Review Subsection'
)
review_unit_actual = ItemFactory.create(
parent=<API key>, display_name='Review Unit'
)
<API key> = ItemFactory.create( # pylint: disable=unused-variable
parent=review_unit_actual,
category='review',
display_name='Review Tool',
num_desired=num_desired
)
# Loading the review section
response = self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': <API key>.location.name,
}
))
<API key> = 'Review Problems'
# The problems are defaulted to correct upon load
# This happens because the problems "raw_possible" field is 0 and the
# "raw_earned" field is also 0.
<API key> = 'correct'
expected_problems = ['Review Problem 1', 'Review Problem 2', 'Review Problem 3',
'Review Problem 4', 'Review Problem 5', 'Review Problem 6']
self.assertIn(<API key>, response.content)
self.assertEqual(response.content.count(<API key>), num_desired)
# Since the problems are randomly selected, we have to check
# the correct number of problems are returned.
count = 0
for problem in expected_problems:
if problem in response.content:
count += 1
self.assertEqual(count, num_desired)
self.assertEqual(response.content.count(self.URL_BEGINNING), num_desired)
@ddt.data(2, 6)
def <API key>(self, num_desired):
"""
Verify that the URLs returned from the Review xBlock are valid and
correct URLs for the problems the learner has seen.
"""
self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'], self.course_actual)
self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'], self.course_review)
# Loading problems so the learner has enough problems in the CSM
self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': self.section1_actual.location.name,
}
))
self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': self.section2_actual.location.name,
}
))
self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': self.section3_actual.location.name,
}
))
user = User.objects.get(email=self.STUDENTS[0]['email'])
crum.set_current_user(user)
result_urls = get_review_ids.get_problems(num_desired, self.course_actual.id)
expected_urls = [
(self.URL_BEGINNING + 'problem+block@Problem_1', True, 0),
(self.URL_BEGINNING + 'problem+block@Problem_2', True, 0),
(self.URL_BEGINNING + 'problem+block@Problem_3', True, 0),
(self.URL_BEGINNING + 'problem+block@Problem_4', True, 0),
(self.URL_BEGINNING + 'problem+block@Problem_5', True, 0),
(self.URL_BEGINNING + 'problem+block@Problem_6', True, 0)
]
# Since the problems are randomly selected, we have to check
# the correct number of urls are returned.
count = 0
for url in expected_urls:
if url in result_urls:
count += 1
self.assertEqual(count, num_desired)
@ddt.data(2, 5)
def <API key>(self, num_desired):
"""
Verify that the URLs returned from the Review xBlock are valid and
correct URLs for the problems the learner has seen. This test will give
a unique problem to a learner and verify only that learner sees
it as a review. It will also ensure that if a learner has not loaded a
problem, it should never show up as a review problem
"""
self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'], self.course_actual)
self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'], self.course_review)
# Loading problems so the learner has enough problems in the CSM
self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': self.section1_actual.location.name,
}
))
self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': self.section3_actual.location.name,
}
))
user = User.objects.get(email=self.STUDENTS[0]['email'])
crum.set_current_user(user)
result_urls = get_review_ids.get_problems(num_desired, self.course_actual.id)
expected_urls = [
(self.URL_BEGINNING + 'problem+block@Problem_1', True, 0),
(self.URL_BEGINNING + 'problem+block@Problem_2', True, 0),
(self.URL_BEGINNING + 'problem+block@Problem_3', True, 0),
(self.URL_BEGINNING + 'problem+block@Problem_4', True, 0),
# This is the unique problem when num_desired == 5
(self.URL_BEGINNING + 'problem+block@Problem_6', True, 0)
]
<API key> = (self.URL_BEGINNING + 'problem+block@Problem_5', True, 0)
# Since the problems are randomly selected, we have to check
# the correct number of urls are returned.
count = 0
for url in expected_urls:
if url in result_urls:
count += 1
self.assertEqual(count, num_desired)
self.assertNotIn(<API key>, result_urls)
# NOTE: This test is failing because when I grab the problem from the CSM,
# it is unable to find its parents. This is some issue with the BlockStructure
# and it not being populated the way we want. For now, this is being left out
# since the first course I'm working with does not use this function.
# TODO: Fix get_vertical from get_review_ids to have the block structure for this test
# or fix something in this file to make sure it populates the block structure for the CSM
@unittest.skip
def <API key>(self):
"""
Verify that the URL returned from the Review xBlock is a valid and
correct URL for the vertical the learner has seen.
"""
self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'], self.course_actual)
self.enroll_student(self.STUDENTS[0]['email'], self.STUDENTS[0]['password'], self.course_review)
# Loading problems so the learner has problems and thus a vertical in the CSM
self.client.get(reverse(
'courseware_section',
kwargs={
'course_id': self.course_actual.id,
'chapter': self.chapter_actual.location.name,
'section': self.section1_actual.location.name,
}
))
user = User.objects.get(email=self.STUDENTS[0]['email'])
crum.set_current_user(user)
result_url = get_review_ids.get_vertical(self.course_actual.id)
expected_url = self.URL_BEGINNING + 'vertical+block@New_Unit_1'
self.assertEqual(result_url, expected_url) |
#include "mdef.h"
#include "gtm_string.h"
#include <ssdef.h>
#include <descrip.h>
#include <rmsdef.h>
#include <prcdef.h>
#include "job.h"
#include "min_max.h"
static readonly unsigned char definput[] = "NL:";
static readonly unsigned char deflogfile[] = "NL:";
static unsigned char *defoutbuf;
static unsigned char *deferrbuf;
LITREF jp_datatype job_param_datatypes[];
LITREF mstr define_gtm$job$_;
LITREF mstr set_default_;
LITREF mstr atsign;
LITREF mstr run__nodebug_;
void ojparams(unsigned char *p, mval *routine, bool *defprcnam, int4 *cmaxmsg, mstr *image,
mstr *input, mstr *output, mstr *error, struct dsc$descriptor_s *prcnam, int4 *baspri,
int4 *stsflg, mstr *gbldir, mstr *startup, struct dsc$descriptor_s *logfile, mstr *deffs,
quadword *schedule)
{
jp_type ch;
int4 status;
struct dsc$descriptor_s timdsc;
int4 defstsflg;
MSTR_CONST(defoutext, ".MJO");
MSTR_CONST(deferrext, ".MJE");
error_def (ERR_IVTIME);
error_def (ERR_PRCNAMLEN);
error_def (ERR_PARFILSPC);
/* Initializations */
*defprcnam = FALSE;
defstsflg = PRC$M_DETACH;
*cmaxmsg = MAX(*cmaxmsg, (define_gtm$job$_.len + MAX_PIDSTR_LEN));
image->len = 0;
input->len = output->len = error->len = 0;
prcnam->dsc$w_length = 0;
prcnam->dsc$b_dtype = DSC$K_DTYPE_T;
prcnam->dsc$b_class = DSC$K_CLASS_S;
*baspri = JP_NO_BASPRI;
*stsflg = defstsflg;
gbldir->len = 0;
startup->len = 0;
logfile->dsc$w_length = 0;
logfile->dsc$b_dtype = DSC$K_DTYPE_T;
logfile->dsc$b_class = DSC$K_CLASS_S;
deffs->len = 0;
schedule->hi = schedule->lo = 0;
/* Process parameter list */
while (*p != jp_eol)
{
switch (ch = *p++)
{
case jp_account:
*stsflg &= (~PRC$M_NOACNT);
break;
case jp_default:
if (*p != 0)
{
deffs->len = *p;
deffs->addr = (p + 1);
}
break;
case jp_detached:
*stsflg |= PRC$M_DETACH;
break;
case jp_error:
if (*p != 0)
{
error->len = *p;
error->addr = (p + 1);
}
break;
case jp_gbldir:
if (*p != 0)
{
gbldir->len = *p;
gbldir->addr = (p + 1);
}
break;
case jp_image:
if (*p != 0)
{
image->len = *p;
image->addr = p + 1;
}
break;
case jp_input:
if (*p != 0)
{
input->len = *p;
input->addr = p + 1;
}
break;
case jp_logfile:
if (*p != 0)
{
logfile->dsc$w_length = *p;
logfile->dsc$a_pointer = p + 1;
}
break;
case jp_noaccount:
*stsflg |= PRC$M_NOACNT;
break;
case jp_nodetached:
*stsflg &= (~PRC$M_DETACH);
break;
case jp_noswapping:
*stsflg |= PRC$M_PSWAPM;
break;
case jp_output:
if (*p != 0)
{
output->len = *p;
output->addr = p + 1;
}
break;
case jp_priority:
*baspri = *(int4 *)p;
break;
case jp_process_name:
if (*p != 0)
{
prcnam->dsc$w_length = *p;
prcnam->dsc$a_pointer = p + 1;
}
break;
case jp_schedule:
timdsc.dsc$w_length = *p;
timdsc.dsc$b_dtype = DSC$K_DTYPE_T;
timdsc.dsc$b_class = DSC$K_CLASS_S;
timdsc.dsc$a_pointer = p + 1;
status = sys$bintim (&timdsc, schedule);
if (status != SS$_NORMAL)
rts_error(VARLSTCNT(4) ERR_IVTIME, 2, timdsc.dsc$w_length, timdsc.dsc$a_pointer);
break;
case jp_startup:
if (*p != 0)
{
startup->len = *p;
startup->addr = p + 1;
}
break;
case jp_swapping:
*stsflg &= (~PRC$M_PSWAPM);
break;
default:
GTMASSERT;
}
switch (job_param_datatypes[ch])
{
case jpdt_nul:
break;
case jpdt_num:
p += SIZEOF(int4);
break;
case jpdt_str:
p += (unsigned) *p + 1;
break;
default:
GTMASSERT;
}
}
/* Defaults and Checks */
if (image->len == 0)
ojdefimage (image);
else
if ((status = ojchkfs (image->addr, image->len, TRUE)) != RMS$_NORMAL)
rts_error(VARLSTCNT(7) ERR_PARFILSPC, 4, 5, "IMAGE", image->len, image->addr, status);
*cmaxmsg = MAX(*cmaxmsg, run__nodebug_.len + image->len);
if (input->len == 0)
{
input->len = SIZEOF(definput) - 1;
input->addr = definput;
}
else
if ((status = ojchkfs (input->addr, input->len, TRUE)) != RMS$_NORMAL)
rts_error(VARLSTCNT(7) ERR_PARFILSPC, 4, 5, "INPUT", input->len, input->addr, status);
*cmaxmsg = MAX(*cmaxmsg, 1 + input->len);
if (output->len == 0)
{
if (!defoutbuf)
defoutbuf = malloc(MAX_FILSPC_LEN);
memcpy (&defoutbuf[0], routine->str.addr, routine->str.len);
memcpy (&defoutbuf[routine->str.len], defoutext.addr, defoutext.len);
if (*defoutbuf == '%')
*defoutbuf = '_';
output->len = routine->str.len + defoutext.len;
output->addr = &defoutbuf[0];
}
else
if ((status = ojchkfs (output->addr, output->len, FALSE)) != RMS$_NORMAL)
rts_error(VARLSTCNT(7) ERR_PARFILSPC, 4, 6, "OUTPUT", output->len, output->addr, status);
*cmaxmsg = MAX(*cmaxmsg, 1 + output->len);
if (error->len == 0)
{
if (!deferrbuf)
deferrbuf = malloc(MAX_FILSPC_LEN);
memcpy (&deferrbuf[0], routine->str.addr, routine->str.len);
memcpy (&deferrbuf[routine->str.len], deferrext.addr, deferrext.len);
if (*deferrbuf == '%')
*deferrbuf = '_';
error->len = routine->str.len + deferrext.len;
error->addr = &deferrbuf[0];
}
else
if ((status = ojchkfs (error->addr, error->len, FALSE)) != RMS$_NORMAL)
rts_error(VARLSTCNT(7) ERR_PARFILSPC, 4, 5, "ERROR", error->len, error->addr, status);
*cmaxmsg = MAX(*cmaxmsg, 1 + error->len);
if (prcnam->dsc$w_length > MAX_PRCNAM_LEN)
rts_error(VARLSTCNT(5) ERR_PRCNAMLEN, 3, prcnam->dsc$w_length, prcnam->dsc$a_pointer, MAX_PRCNAM_LEN);
if (prcnam->dsc$w_length == 0)
{
ojdefprcnam (prcnam);
*defprcnam = TRUE;
}
if (*baspri == JP_NO_BASPRI)
ojdefbaspri (baspri);
if (gbldir->len != 0)
if ((status = ojchkfs (gbldir->addr, gbldir->len, FALSE)) != RMS$_NORMAL)
rts_error(VARLSTCNT(7) ERR_PARFILSPC, 4, 6, "GBLDIR", gbldir->len, gbldir->addr, status);
*cmaxmsg = MAX(*cmaxmsg, 1 + gbldir->len);
if (startup->len != 0)
if ((status = ojchkfs (startup->addr, startup->len, TRUE)) != RMS$_NORMAL)
rts_error(VARLSTCNT(7) ERR_PARFILSPC, 4, 7, "STARTUP", startup->len, startup->addr, status);
*cmaxmsg = MAX(*cmaxmsg, atsign.len + startup->len);
if (deffs->len == 0)
ojdefdeffs (deffs);
else
if ((status = ojchkfs (deffs->addr, deffs->len, FALSE)) != RMS$_NORMAL)
rts_error(VARLSTCNT(7) ERR_PARFILSPC, 4, 7, "DEFAULT", deffs->len, deffs->addr, status);
*cmaxmsg = MAX(*cmaxmsg, set_default_.len + deffs->len);
if (logfile->dsc$w_length == 0)
{
logfile->dsc$w_length = SIZEOF(deflogfile) - 1;
logfile->dsc$a_pointer = deflogfile;
}
else
if ((status = ojchkfs (logfile->dsc$a_pointer, logfile->dsc$w_length, FALSE)) != RMS$_NORMAL)
rts_error(VARLSTCNT(7) ERR_PARFILSPC, 4, 7, "LOGFILE", logfile->dsc$w_length,
logfile->dsc$a_pointer, status);
return;
} |
<div id="page" style="display: none;" data-bind="visible: true, css: { withToolbox: $root.showToolbox, withPreviewFrame: showPreviewFrame }">
<div id="main-edit-area" data-bind="click: function(obj, evt) { $root.selectBlock(null); return true; }, clickBubble: false">
<!-- ko withProperties: { templateMode: 'wysiwyg', <API key>: 'show' } -->
<div id="main-wysiwyg-area" data-bind="wysiwygScrollfix: true, scrollable: true, fudroppable: { active: draggingImage }, css: { isdragging: dragging, isdraggingimg: draggingImage }, block: content"></div>
</div>
<div id="toolbar" class="mo" data-bind="tooltips: {}">
<!-- ko if: typeof $root.undo != 'undefined' -->
<span data-bind="buttonset: { }" class="leftButtons">
<a title="Undo last operation" href="#" data-bind="attr: { title: $root.t('Undo last operation') }, click: $root.undo.execute, clickBubble: false, button: { disabled: !$root.undo.enabled(), icons: { primary: 'fa fa-reply' }, label: $root.undo.name, text: true }">UNDO</a>
<a title="Redo last operation" href="#" data-bind="attr: { title: $root.t('Redo last operation') }, click: $root.redo.execute, clickBubble: false, button: { disabled: !$root.redo.enabled(), icons: { primary: 'fa fa-share' }, label: $root.redo.name, text: true }">REDO</a>
</span>
<!-- ko if: $root.debug -->
<a href="#" data-bind="click: $root.undoReset, clickBubble: false, button: { disabled: !$root.undo.enabled() && !$root.redo.enabled(), label: 'reset', text: true }">RESET</a>
<span>
<input id="showGallery" type="checkbox" data-bind="checked: $root.showGallery, button: { refreshOn: $root.showGallery,
icons: { primary: 'fa fa-fw fa-picture-o', secondary: null }, text: true, label: $root.t('Gallery') }"><label title="Show image gallery" for="showGallery" data-bind="attr: { title: $root.t('Show image gallery') }">show gallery</label></input>
</span>
<input id="previewFrameToggle" type="checkbox" data-bind="checked: $root.showPreviewFrame, button: { refreshOn: $root.showPreviewFrame, icons: { primary: 'fa fa-fw fa-tablet', secondary: null }, text: false, label: $root.t('Preview') }"><label title="Show live preview" for="previewFrameToggle" data-bind="attr: { title: $root.t('Show live preview') }">PREVIEW</label></input>
<!-- ko if: $root.debug -->
<a href="#" data-bind="click: $root.export, clickBubble: false, button: { label: 'export', text: true }">EXPORT</a>
<input type="checkbox" data-bind="checked: $root.debug" /> debug
<a href="#" data-bind="click: $root.loadDefaultBlocks, clickBubble: false, button: { icons: { primary: 'fa fa-fw fa-upload' }, label: 'Default', text: true }">LOAD BLOCKS</a>
[<a id="subscriptionsCount" href="javascript:viewModel.<API key>()">subs</a>]
<span data-bind="visible: false">
<input type="checkbox" data-bind="checked: $root.showToolbox" /> toolbox
</span>
<div class="rightButtons">
<!-- ko if: typeof $root.save !== 'undefined' -->
<a title="Save template" href="#" data-bind="attr: { title: $root.t('Save template') }, click: $root.save.execute, clickBubble: false, button: { disabled: !$root.save.enabled(), icons: { primary: 'fa fa-fw fa-cloud-upload' }, label: $root.t($root.save.name), text: true }">SALVA</a>
<!-- ko if: typeof $root.test !== 'undefined' -->
<a title="Show preview and send test" href="#" data-bind="attr: { title: $root.t('Show preview and send test') }, click: $root.test.execute, clickBubble: false, button: { disabled: !$root.test.enabled(), icons: { primary: 'fa fa-fw fa-paper-plane' }, label: $root.t($root.test.name), text: true }">TEST</a>
<!-- ko if: typeof $root.download !== 'undefined' -->
<form id="downloadForm" action="#" method="POST">
<input type="hidden" name="action" value="download" />
<input type="hidden" name="filename" value="email.html" />
<input type="hidden" name="html" id="<API key>" />
<a title="Download template" href="#" data-bind="attr: { title: $root.t('Download template') }, click: $root.download.execute, clickBubble: false, button: { disabled: !$root.download.enabled(), icons: { primary: 'fa fa-fw fa-download' }, label: $root.t($root.download.name), text: true }">DOWNLOAD</a>
</form>
</div>
</div>
<!-- ko if: $root.showToolbox -->
<div id="main-toolbox" class="mo" data-bind="scrollable: true, withProperties: { templateMode: 'edit' }">
<div data-bind="template: { name: 'toolbox' }"></div>
</div>
<div id="main-preview" class="mo" data-bind="scrollable: true, if: $root.showPreviewFrame">
<div id="preview-toolbar">
<div data-bind="visible: $root.showPreviewFrame, buttonset: { }" style="display: inline-block">
<input id="previewLarge" type="radio" name="previewMode" value="large" data-bind="checked: $root.previewMode, button: { text: false, label: 'large', icons: { primary: 'fa fa-fw fa-desktop' } }" />
<label for="previewLarge" title="Large screen" data-bind="attr: { title: $root.t('Large screen') }">Large screen</label>
<input id="previewDesktop" type="radio" name="previewMode" value="desktop" data-bind="checked: $root.previewMode, button: { text: false, label: 'desktop', icons: { primary: 'fa fa-fw fa-tablet' } }" />
<label for="previewDesktop" title="Tablet" data-bind="attr: { title: $root.t('Tablet') }">Tablet</label>
<input id="previewMobile" type="radio" name="previewMode" value="mobile" data-bind="checked: $root.previewMode, button: { text: false, label: 'mobile', icons: { primary: 'fa fa-fw fa-mobile' } }" />
<label for="previewMobile" title="Smartphone" data-bind="attr: { title: $root.t('Smartphone') }">Smartphone</label>
</div>
</div>
<div id="frame-container" data-bind="css: { desktop: $root.previewMode() == 'desktop', mobile: $root.previewMode() == 'mobile', large: $root.previewMode() == 'large' }">
<iframe data-bind="bindIframe: $data"></iframe>
</div>
</div>
<div class="mo" id="mo-body"></div>
<!-- TODO REMOVE ME
<div id="<API key>" title="Unsupported browser" style="display: none" data-bind="attr: { title: $root.t('Usupported browser') }, html: '<p>Your browser is not supported.</p><p>Use a different browser or try updaring your browser.</p><p>Supported browsers: <ul><li>Internet Explorer >= 10</li><li>Google Chrome >= 30</li><li>Apple Safari >= 5</li><li>Mozilla Firefix >= 20</li></ul></p>'">
Unsupported browser
</div>
<div id="<API key>" title="Saved model is obsolete" style="display: none" data-bind="attr: { title: $root.t('Saved model is obsolete') }, html: $root.t('<p>The saved model has been created with a previous, non completely compatible version, of the template</p><p>Some content or style in the model <b>COULD BE LOST</b> if you will <b>save</b></p><p>Contact us for more informations!</p>')">
Incompatible template
</div>
<div id="fake-image-editor" title="Fake image editor" style="display: none" data-bind="attr: { title: $root.t('Fake image editor') }, html: $root.t('<p>Fake image editor</p>')">
<p>Fake image editor</p>
</div>
</div>
<div id="loading" class="loading" style="display: block; width: 300px; text-align: center; height: 32px; position: absolute; top:0; bottom: 0; left: 0; right: 0; margin: auto;" data-bind="attr: { style: 'position: absolute; top: 5px; left: 6px; z-index: 150;'}, css: { loading: false }">
<!-- DS: need to use url built from civi which is CMS agnostic. For now we use the mosaico url -->
<a href="/"><img src="//mosaico.io/dist/img/mosaico32.png" width="32" height="32" alt="mosaico" border="0" /></a>
<div style="opacity: 0" data-bind="visible: false">Oppps... !!</div>
</div> |
#ifndef <API key>
#define <API key>
#include <opencog/comboreduct/combo/vertex.h>
#include <opencog/comboreduct/combo/variable_unifier.h>
#include <opencog/embodiment/Control/<API key>/PAI.h>
#include <opencog/embodiment/RuleValidation/VirtualWorldData/VirtualWorldState.h>
#include <opencog/embodiment/WorldWrapper/PAIWorldWrapper.h>
#include <opencog/embodiment/WorldWrapper/<API key>.h>
#include "RunningProcedureId.h"
#include "<API key>.h"
#include <vector>
#include <boost/noncopyable.hpp>
#include <opencog/server/CogServer.h>
#include <opencog/embodiment/Control/MessagingSystem/NetworkElement.h>
namespace Procedure
{
typedef std::map<RunningProcedureId, <API key>> Map;
typedef std::vector<Map::iterator> Vec;
class DonePred : public std::unary_function<Vec::iterator, bool>
{
private:
std::set<RunningProcedureId> _set;
public:
explicit DonePred(const std::set<RunningProcedureId>& s) : _set(s) {}
// return true if the element is not in the set and false otherwise.
// This will be used to split the predicates that are not finished yet
// from the ones that already finished and must be removed from the
// running procedure list
bool operator()(Map::iterator& elem) {
return _set.find((*elem).first) == _set.end();
}
}; // DoneSet
class ComboInterpreter : public boost::noncopyable
{
public:
ComboInterpreter(<API key>::PAI& p, opencog::RandGen& rng);
ComboInterpreter(VirtualWorldData::VirtualWorldState& v, opencog::RandGen& rng);
virtual ~ComboInterpreter();
//run executes a single action plan of some procedure (if any are ready)
void run(MessagingSystem::NetworkElement *ne);
//add a procedure to be run by the interpreter
RunningProcedureId runProcedure(const combo::combo_tree& tr, const std::vector<combo::vertex>& arguments);
//add a procedure to be run by the interpreter with variable unifier
RunningProcedureId runProcedure(const combo::combo_tree& tr, const std::vector<combo::vertex>& arguments,
combo::variable_unifier& vu);
bool isFinished(RunningProcedureId id);
// Note: this will return false if the stopProcedure() method was previously called for this same procedure id,
// even if the procedure execution has failed before
bool isFailed(RunningProcedureId id);
// Get the result of the procedure with the given id
// Can be called only if the following conditions are true:
// - procedure execution is finished (checked by isFinished() method)
// - procedure execution has not failed (checked by isFailed() method)
// - procedure execution was not stopped (by calling stopProcedure() method)
combo::vertex getResult(RunningProcedureId id);
// Get the result of the variable unification carried within the procedure
// execution.
// Can be called only if the following conditions are true:
// - procedure execution is finished (checked by isFinished() method)
// - procedure execution has not failed (checked by isFailed() method)
// - procedure execution was not stopped (by calling stopProcedure() method)
combo::variable_unifier& getUnifierResult(RunningProcedureId id);
// makes the procedure with the given id to stop and remove it from the interpreter
void stopProcedure(RunningProcedureId id);
protected:
typedef std::set<RunningProcedureId> Set;
typedef std::map<RunningProcedureId, combo::vertex> ResultMap;
typedef std::map<RunningProcedureId, combo::variable_unifier> UnifierResultMap;
opencog::RandGen& rng;
// WorldWrapper::PAIWorldWrapper _ww;
WorldWrapper::WorldWrapperBase * _ww;
Map _map;
Vec _vec;
Set _failed;
ResultMap _resultMap;
UnifierResultMap _unifierResultMap;
unsigned long _next;
}; // ComboInterpreter
} //~namespace Procedure
#endif |
<?php
// OPAC3 - Catalogues de notices
class CatalogueLoader extends Storm_Model_Loader {
const <API key> = 100;
public function loadNoticesFor($catalogue, $itemsByPage = self::<API key>, $page = 1, $find_all_params = null) {
if (!is_array($find_all_params))
$find_all_params = array();
if (!isset($find_all_params['limitPage']))
$find_all_params['limitPage'] = array($page, $itemsByPage);
if (null == $catalogue)
return array();
if ('' == ($where = $this->clausesFor($catalogue)))
return array();
$find_all_params['where'] = $where;
return Class_Notice::getLoader()->findAllBy($find_all_params);
}
public function countNoticesFor($catalogue) {
if (!$catalogue)
return 0;
if ('' == ($where = $this->clausesFor($catalogue)))
return 0;
return Class_Notice::getLoader()->countBy(array('where' => $where));
}
public function clausesFor($catalogue) {
$conditions = array();
if ($fromUntil = $this->fromUntilClauseFor($catalogue))
$conditions[] = $fromUntil;
if ($catalogue-><API key>())
return $fromUntil ? $fromUntil : '1=1';
if ($facets = $this->facetsClauseFor($catalogue))
$conditions[] = $facets;
if ($docType = $this->docTypeClauseFor($catalogue))
$conditions[] = $docType;
if ($year = $this->yearClauseFor($catalogue))
$conditions[] = $year;
if ($cote = $this->coteClauseFor($catalogue))
$conditions[] = $cote;
if ($new = $this->nouveauteClauseFor($catalogue))
$conditions[] = $new;
if (0 == count($conditions))
return '';
return implode(' and ', $conditions);
}
/**
* @param $catalogue Class_Catalogue
* @return string
*/
public function facetsClauseFor($catalogue, $against = '') {
$against_ou = '';
$facets = array('B' => $catalogue->getBibliotheque(),
'S' => $catalogue->getSection(),
'G' => $catalogue->getGenre(),
'L' => $catalogue->getLangue(),
'Y' => $catalogue->getAnnexe(),
'E' => $catalogue->getEmplacement());
foreach ($facets as $k => $v)
$against .= Class_Catalogue::getSelectionFacette($k, $v);
$facets = array('A' => $catalogue->getAuteur(),
'M' => $catalogue->getMatiere(),
'D' => $catalogue->getDewey(),
'P' => $catalogue->getPcdm4(),
'T' => $catalogue->getTags(),
'F' => $catalogue->getInteret());
foreach ($facets as $k => $v)
$against_ou .= Class_Catalogue::getSelectionFacette($k, $v, in_array($k, array('M', 'D', 'P')), false);
if ('' != $against_ou)
$against .= ' +(' . $against_ou . ")";
if ('' == $against)
return '';
return "MATCH(facettes) AGAINST('".$against."' IN BOOLEAN MODE)";
}
public function docTypeClauseFor($catalogue) {
if (!$docType = $catalogue->getTypeDoc())
return '';
$parts = explode(';', $docType);
if (1 == count($parts))
return 'type_doc=' . $parts[0];
return 'type_doc IN (' . implode(', ', $parts) . ')';
}
public function yearClauseFor($catalogue) {
$clauses = array();
if ($start = $catalogue->getAnneeDebut())
$clauses[] = "annee >= '" . $start . "'";
if($end = $catalogue->getAnneeFin())
$clauses[] = "annee <= '" . $end . "'";
if (0 == count($clauses))
return '';
return implode(' and ', $clauses);
}
public function coteClauseFor($catalogue) {
$clauses = array();
if ($start = $catalogue->getCoteDebut())
$clauses[] = "cote >= '" . strtoupper($start) . "'";
if ($end = $catalogue->getCoteFin())
$clauses[] = "cote <= '". strtoupper($end) . "'";
if (0 == count($clauses))
return '';
return implode(' and ', $clauses);
}
public function nouveauteClauseFor($catalogue) {
if (1 != $catalogue->getNouveaute())
return '';
return 'date_creation >= \'' . date('Y-m-d') . '\'';
}
public function fromUntilClauseFor($catalogue) {
$clauses = array();
if ($start = $catalogue->getFrom())
$clauses[] = "left(date_maj, 10) >= '" . $start . "'";
if($end = $catalogue->getUntil())
$clauses[] = "left(date_maj, 10) <= '" . $end . "'";
if (0 == count($clauses))
return '';
return implode(' and ', $clauses);
}
}
class Class_Catalogue extends <API key> {
protected $_table_name = 'catalogue';
protected $_table_primary = 'ID_CATALOGUE';
protected $_loader_class = 'CatalogueLoader';
protected $<API key> = array('oai_spec' => '',
'description' => '',
'bibliotheque' => '',
'section' => '',
'genre' => '',
'langue' => '',
'annexe' => '',
'emplacement' => '',
'auteur' => '',
'matiere' => '',
'dewey' => '',
'pcdm4' => '',
'tags' => '',
'interet' => '',
'type_doc' => '',
'annee_debut' => '',
'annee_fin' => '',
'cote_debut' => '',
'cote_fin' => '',
'nouveaute' => '');
protected $_from;
protected $_until;
public static function getLoader() {
return self::getLoaderFor(__CLASS__);
}
public static function newCatalogueForAll() {
return new AllNoticesCatalogue();
}
public function acceptVisitor($visitor) {
$visitor->visitOaiSpec($this->getOaiSpec());
$visitor->visitLibelle($this->getLibelle());
if ($this->hasDescription())
$visitor->visitDescription($this->getDescription());
}
public function getNotices($page = 1, $itemsByPage = CatalogueLoader::<API key>, $params = null) {
return self::getLoader()->loadNoticesFor($this, $itemsByPage, $page, $params);
}
public function getNoticesCount() {
return self::getLoader()->countNoticesFor($this);
}
public function <API key>() {
return false;
}
// Rend les notices et les stats (test d'un catalogue)
public function getTestCatalogue() {
// Notices et temps d'execution
$preferences = $this->toArray();
$preferences['nb_notices'] = 20;
$requetes=$this->getRequetes($preferences);
$ret["requete"]=$requetes["req_liste"];
$temps=time();
$ret["notices"] = $this->getNotices(null, null,
array('limitPage' => array(1, $preferences['nb_notices']),
'order' => 'alpha_titre'));
$ret["temps_execution"]=(time()-$temps);
$ret["nb_notices"]=fetchOne($requetes["req_comptage"]);
// Avec vignettes en cache
$req=$requetes["req_comptage"];
if(strpos($req,"where") > 0) $req.=" and "; else $req.=" where ";
$req.="url_vignette > '' and url_vignette != 'NO'";
$ret["avec_vignettes"]=fetchOne($req);
return $ret;
}
public function shouldCacheContent() {
if (Class_Users::getLoader()->isCurrentUserAdmin())
return false;
return Class_AdminVar::isCacheEnabled();
}
public function <API key>($preferences, $cache_vignette) {
$cache_key = md5(serialize($preferences).$cache_vignette);
$cache = Zend_Registry::get('cache');
if ($this->shouldCacheContent() && $cache->test($cache_key))
return unserialize($cache->load($cache_key));
$notices = $this-><API key>($preferences, $cache_vignette);
$cache->save(serialize($notices), $cache_key);
return $notices;
}
// Rend les notices selon les preferences (kiosques)
public function <API key>($preferences,$cache_vignette=false) {
$notices = $this-><API key>($preferences, $cache_vignette);
if ((int)$preferences["aleatoire"] !== 1)
return $notices;
shuffle($notices);
return array_slice ($notices, 0, $preferences["nb_notices"]);
}
public function <API key>($preferences, $cache_vignette) {
// Lancer la requete
$requetes=$this->getRequetes($preferences);
if (!array_key_exists("req_liste", $requetes))
return array();
$req_liste = str_replace('select *',
'select notices.id_notice, notices.editeur, notices.annee, notices.date_creation, notices.facettes, notices.clef_oeuvre',
$requetes["req_liste"]);
$catalogue=fetchAll($req_liste);
if (!$catalogue)
return array();
//Instanciations
$class_notice = new Class_Notice();
$class_img = new <API key>();
$notices = array();
// Formatter les notices
foreach($catalogue as $notice) {
$enreg=$class_notice->getNotice($notice["id_notice"],'TA');
$vignette = '';
if ($cache_vignette) {
if($cache_vignette=="url") $mode=false; else $mode=true;
$vignette=$class_img->getImage($enreg["id_notice"],$mode);
}
if (!$cache_vignette or $vignette) {
$notices[]=array(
"id_notice" => $enreg["id_notice"],
"titre" => $enreg["T"],
"auteur" => $enreg["A"],
"vignette" => $vignette,
"type_doc" => $enreg["type_doc"],
"editeur" => $notice["editeur"],
"annee" => $notice["annee"],
"date_creation" => $notice["date_creation"],
"facettes" => $notice["facettes"],
"clef_oeuvre" => $notice["clef_oeuvre"]);
}
}
return $notices;
}
// Rend les notices selon les preferences
public function getRequetes($preferences, $no_limit=false) {
// Si panier traitement special
if (isset($preferences["id_panier"]) && (0 !== (int)$preferences["id_panier"]))
return $this->getRequetesPanier($preferences);
// Lire les proprietes du catalogue
$against = $this-><API key>($preferences);
if ($catalogue = $this->getLoader()->find($preferences['id_catalogue'])) {
$conditions = array($this->getLoader()->facetsClauseFor($catalogue, $against));
$conditions []= $this->getLoader()->docTypeClauseFor($catalogue);
$conditions []= $this->getLoader()->yearClauseFor($catalogue);
$conditions []= $this->getLoader()->coteClauseFor($catalogue);
$conditions []= $this->getLoader()->nouveauteClauseFor($catalogue);
} else {
$conditions = $against ? array("MATCH(facettes) AGAINST('".$against."' IN BOOLEAN MODE)") : array();
}
// Notices avec vignettes uniquement
if (isset($preferences['only_img']) && ($preferences["only_img"] == 1))
$conditions[]="url_vignette > '' and url_vignette != 'NO'";
// Notices avec avis seulement
$join = (isset($preferences['avec_avis']) && ($preferences["avec_avis"] == 1))
? " INNER JOIN notices_avis ON notices.clef_oeuvre=notices_avis.clef_oeuvre "
: '';
// Clause where
if ($where = implode(' and ', array_filter($conditions)))
$where = ' where '.$where;
// Calcul des requetes
$order_by = $this-><API key>($preferences);
$limite = $this-><API key>($preferences, $no_limit);
$ret["req_liste"]="select * from notices ".$join.$where.$order_by.$limite;
$ret["req_comptage"]="select count(*) from notices ".$join.$where;
$ret["req_facettes"]="select notices.id_notice,type_doc,facettes from notices ".$join.$where.$limite;
return $ret;
}
public function <API key>($preferences) {
if (!isset($preferences["facettes"]))
return '';
$against = '';
$facettes=explode(";", $preferences["facettes"]);
foreach($facettes as $facette) {
$facette=trim($facette);
$against.=$this->getSelectionFacette(substr($facette,0,1),substr($facette,1));
}
return $against;
}
public function <API key>($preferences) {
if(!array_key_exists("tri", $preferences) || $preferences["tri"]==0)
return " order by alpha_titre ";
if ($preferences["tri"]==1)
return " order by date_creation DESC ";
if ($preferences["tri"]==2)
return " order by nb_visu DESC ";
}
public function <API key>($preferences, $no_limit=false) {
$limite = 0;
if (isset($preferences["aleatoire"]) && (int)$preferences["aleatoire"]==1)
$limite = (int)$preferences["nb_analyse"];
else if (isset($preferences['nb_notices']))
$limite = (int)$preferences["nb_notices"];
if ($limite and !$no_limit)
return " LIMIT 0,".$limite;
return " LIMIT 5000";
}
// Calcul de la clause against pour une facette
public static function getSelectionFacette($type, $valeurs, $descendants = false, $signe = true) {
if (!$valeurs)
return false;
$valeurs = explode(';', $valeurs);
$cond = '';
foreach ($valeurs as $valeur) {
if (!$valeur)
continue;
if (!$descendants) {
$cond .= $type . $valeur . ' ';
continue;
}
if ('M' != $type) {
$cond .= $type . $valeur . '* ';
continue;
}
if (!$matiere = Class_Matiere::getLoader()->find($valeur))
continue;
if ('' != ($sous_vedettes = trim($matiere->getSousVedettes())))
$valeur .= str_replace(' ', ' M', ' ' . $sous_vedettes);
$cond .= $type . $valeur . ' ';
}
$cond = trim($cond);
if ($signe)
return ' +(' . $cond . ')';
return ' ' . $cond;
}
// Rend les requetes pour un panier selon les preferences
public function getRequetesPanier($preferences)
{
if (array_key_exists('id_user', $preferences))
$panier = Class_PanierNotice::getLoader()->findFirstBy(array('id_user' => $preferences['id_user'],
'id_panier' => $preferences['id_panier']));
else $panier = Class_PanierNotice::getLoader()->find($preferences['id_panier']);
if (!$panier)
return array("nombre" => 0);
$cles_notices = $panier->getClesNotices();
if (empty($cles_notices))
{
$ret["nombre"]=0;
return $ret;
}
foreach($cles_notices as $notice) {
if(!trim($notice)) continue;
if(isset($in_sql)) $in_sql .=","; else $in_sql = '';
$in_sql.="'".$notice."'";
}
// Nombre a lire
if($preferences["aleatoire"]==1) $limite=$preferences["nb_analyse"];
else $limite=$preferences["nb_notices"];
if($limite) $limite="LIMIT 0,".$limite; else $limite="";
// Ordre
$order_by ="";
if($preferences["tri"]==0) $order_by=" order by alpha_titre ";
if($preferences["tri"]==1) $order_by=" order by date_creation DESC ";
if($preferences["tri"]==2) $order_by=" order by nb_visu DESC ";
$condition = '';
// Notices avec vignettes uniquement
if (array_isset("only_img", $preferences) && $preferences["only_img"] == 1)
$condition=" and url_vignette > '' and url_vignette != 'NO' ";
// Notices avec avis seulement
$join = '';
if (array_isset("avec_avis", $preferences) && $preferences["avec_avis"] == 1)
$join = " INNER JOIN notices_avis ON notices.clef_oeuvre=notices_avis.clef_oeuvre ";
// Retour
$ret["req_liste"]="select * from notices ".$join."where notices.clef_alpha in(".$in_sql.")".$condition.$order_by.$limite;
$ret["req_comptage"]="select count(*) from notices ".$join."where notices.clef_alpha in(".$in_sql.")".$condition;
$ret["req_facettes"]="select id_notice,type_doc,facettes from notices ".$join."where notices.clef_alpha in(".$in_sql.") ".$condition.$limite;
return $ret;
}
// liste des catalogues (structure complete)
public function getCatalogue($id_catalogue)
{
if($id_catalogue) return fetchEnreg("select * from catalogue where ID_CATALOGUE=$id_catalogue");
else return fetchAll("select * from catalogue order by LIBELLE");
}
// liste des catalogues pour une combo
static function <API key>() {
$liste = array();
$catalogues=fetchAll("select * from catalogue order by libelle");
if(!$catalogues) return $liste;
$liste[""]=" ";
foreach($catalogues as $catalogue)
$liste[$catalogue["ID_CATALOGUE"]]=$catalogue["LIBELLE"];
return $liste;
}
public function setAnneeDebut($value) {
return $this->checkAndSetAnnee('annee_debut', $value);
}
public function setAnneeFin($value) {
return $this->checkAndSetAnnee('annee_fin', $value);
}
public function checkAndSetAnnee($attribute, $value) {
$value = (int)$value;
if ($value < 1000 || $value > date("Y"))
$value = '';
return parent::_set($attribute, $value);
}
public function validate() {
$this->checkAttribute('libelle', $this->getLibelle(), 'Le libellé est requis');
$this->checkAttribute('annee_fin',
!($this->getAnneeDebut() and $this->getAnneeFin()) || $this->getAnneeDebut() <= $this->getAnneeFin(),
"L'année de début doit être inférieure ou égale à l'année de fin");
$this->checkAttribute('oai_spec',
!$this->getOaiSpec() || preg_match('/^[a-zA-Z0-9_.-]+$/', $this->getOaiSpec()),
"La spec OAI ne peut contenir que les caractères suivants: de a à z, 0 à 9, - _ .");
}
public function setFrom($from) {
$this->_from = $from;
return $this;
}
public function getFrom() {
return $this->_from;
}
public function setUntil($until) {
$this->_until = $until;
return $this;
}
public function getUntil() {
return $this->_until;
}
}
class AllNoticesCatalogue extends Class_Catalogue {
public function <API key>() {
return true;
}
}
?> |
class <API key> < Noosfero::Plugin
def self.plugin_name
"Work Assignment"
end
def self.plugin_description
_("New kind of content for organizations.")
end
def self.<API key>?(user, submission)
return unless submission
submission.published? || (user && (submission.author == user || user.has_permission?('<API key>', submission.profile) ||
submission.<API key>?(user)))
end
def self.is_submission?(content)
content && content.parent && content.parent.parent && content.parent.parent.kind_of?(<API key>::WorkAssignment)
end
def content_types
[<API key>::WorkAssignment] if context.respond_to?(:profile) && context.profile.organization?
end
def stylesheet?
true
end
def content_remove_new(content)
content.kind_of?(<API key>::WorkAssignment)
end
def <API key>(content)
if content.kind_of?(<API key>::WorkAssignment)
!content.profile.members.include?(context.send(:user))
end
end
def <API key>
block = proc do
path = get_path(params[:page], params[:format])
content = profile.articles.find_by_path(path)
if <API key>.is_submission?(content) && !<API key>.<API key>?(user, content)
<API key>
end
end
{ :type => 'before_filter',
:method_name => '<API key>',
:options => {:only => 'view_page'},
:block => block }
end
def <API key>
block = proc do
if request.post? && params[:uploaded_files]
email_notification = params[:<API key>]
unless !email_notification || email_notification.empty?
email_contact = <API key>::EmailContact.new(:subject => @parent.name, :receiver => email_notification, :sender => user)
<API key>::EmailContact::EmailSender.build_mail_message(email_contact, @uploaded_files)
if email_contact.deliver
session[:notice] = _('Notification successfully sent')
else
session[:notice] = _('Notification not sent')
end
end
end
end
{ :type => 'after_filter',
:method_name => '<API key>',
:options => {:only => 'upload_files'},
:block => block }
end
def <API key>(article)
proc do
@article = Article.find_by_id(article)
if params[:parent_id] && !@article.nil? && @article.type == "<API key>::WorkAssignment"
render :partial => 'notify_text_field', :locals => { :size => '45'}
end
end
end
end |
<?php namespace OniiChan\Domain;
interface Entity
{
/**
* Return an Entity identifier
*
* @return Identifier
*/
public function id();
} |
package com.anrisoftware.sscontrol.httpd.yourls;
import static com.anrisoftware.sscontrol.httpd.yourls.<API key>.ACCESS_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.<API key>.API_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.<API key>.BACKUP_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.<API key>.CONVERT_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.<API key>.DATABASE_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.<API key>.DEBUG_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.<API key>.DRIVER_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.<API key>.GMT_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.<API key>.HOST_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.<API key>.LANGUAGE_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.<API key>.MODE_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.<API key>.OFFSET_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.<API key>.OVERRIDE_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.<API key>.PASSWORD_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.<API key>.PORT_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.<API key>.PREFIX_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.<API key>.RESERVED_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.<API key>.SITE_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.<API key>.STATS_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.<API key>.TARGET_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.<API key>.UNIQUE_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.<API key>.URLS_KEY;
import static com.anrisoftware.sscontrol.httpd.yourls.<API key>.USER_KEY;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import com.anrisoftware.sscontrol.core.api.ServiceException;
import com.anrisoftware.sscontrol.core.groovy.statementsmap.StatementsException;
import com.anrisoftware.sscontrol.core.groovy.statementsmap.StatementsMap;
import com.anrisoftware.sscontrol.core.groovy.statementstable.StatementsTable;
import com.anrisoftware.sscontrol.core.groovy.statementstable.<API key>;
import com.anrisoftware.sscontrol.core.overridemode.OverrideMode;
import com.anrisoftware.sscontrol.core.yesno.YesNoFlag;
import com.anrisoftware.sscontrol.httpd.domain.Domain;
import com.anrisoftware.sscontrol.httpd.webserviceargs.DefaultWebService;
import com.anrisoftware.sscontrol.httpd.webserviceargs.<API key>;
import com.google.inject.assistedinject.Assisted;
class YourlsServiceImpl implements YourlsService {
/**
* The <i>Yourls</i> service name.
*/
public static final String SERVICE_NAME = "yourls";
private final DefaultWebService service;
private final StatementsMap statementsMap;
private StatementsTable statementsTable;
/**
* @see <API key>#create(Map, Domain)
*/
@Inject
YourlsServiceImpl(<API key> webServiceFactory,
@Assisted Map<String, Object> args, @Assisted Domain domain) {
this.service = webServiceFactory.create(SERVICE_NAME, args, domain);
this.statementsMap = service.getStatementsMap();
setupStatements(statementsMap, args);
}
private void setupStatements(StatementsMap map, Map<String, Object> args) {
map.addAllowed(DATABASE_KEY, OVERRIDE_KEY, BACKUP_KEY, ACCESS_KEY,
USER_KEY, GMT_KEY, UNIQUE_KEY, CONVERT_KEY, RESERVED_KEY,
SITE_KEY, LANGUAGE_KEY);
map.setAllowValue(true, DATABASE_KEY, ACCESS_KEY, RESERVED_KEY,
SITE_KEY, LANGUAGE_KEY);
map.addAllowedKeys(DATABASE_KEY, USER_KEY, PASSWORD_KEY, HOST_KEY,
PORT_KEY, PREFIX_KEY, DRIVER_KEY);
map.addAllowedKeys(OVERRIDE_KEY, MODE_KEY);
map.addAllowedKeys(BACKUP_KEY, TARGET_KEY);
map.addAllowedKeys(ACCESS_KEY, STATS_KEY, API_KEY);
map.addAllowedKeys(GMT_KEY, OFFSET_KEY);
map.addAllowedKeys(UNIQUE_KEY, URLS_KEY);
map.addAllowedKeys(CONVERT_KEY, MODE_KEY);
}
@Inject
public final void setStatementsTable(<API key> factory) {
StatementsTable table = factory.create(this, SERVICE_NAME);
table.addAllowed(DEBUG_KEY, USER_KEY);
table.<API key>(true, DEBUG_KEY);
table.addAllowedKeys(USER_KEY, PASSWORD_KEY);
this.statementsTable = table;
}
@Override
public Domain getDomain() {
return service.getDomain();
}
@Override
public String getName() {
return SERVICE_NAME;
}
public void setAlias(String alias) throws ServiceException {
service.setAlias(alias);
}
@Override
public String getAlias() {
return service.getAlias();
}
public void setId(String id) throws ServiceException {
service.setId(id);
}
@Override
public String getId() {
return service.getId();
}
public void setRef(String ref) throws ServiceException {
service.setRef(ref);
}
@Override
public String getRef() {
return service.getRef();
}
public void setRefDomain(String ref) throws ServiceException {
service.setRefDomain(ref);
}
@Override
public String getRefDomain() {
return service.getRefDomain();
}
public void setPrefix(String prefix) throws ServiceException {
service.setPrefix(prefix);
}
@Override
public String getPrefix() {
return service.getPrefix();
}
@Override
public Map<String, Object> debugLogging(String key) {
return statementsTable.tableKeys(DEBUG_KEY, key);
}
@Override
public Map<String, Object> getDatabase() {
@SuppressWarnings("serial")
Map<String, Object> map = new HashMap<String, Object>() {
@Override
public Object put(String key, Object value) {
if (value != null) {
return super.put(key, value);
} else {
return null;
}
}
};
StatementsMap m = statementsMap;
map.put(DATABASE_KEY.toString(), m.value(DATABASE_KEY));
map.put(USER_KEY.toString(), m.mapValue(DATABASE_KEY, USER_KEY));
map.put(PASSWORD_KEY.toString(), m.mapValue(DATABASE_KEY, PASSWORD_KEY));
map.put(HOST_KEY.toString(), m.mapValue(DATABASE_KEY, HOST_KEY));
map.put(PORT_KEY.toString(), m.mapValue(DATABASE_KEY, PORT_KEY));
map.put(PREFIX_KEY.toString(), m.mapValue(DATABASE_KEY, PREFIX_KEY));
map.put(DRIVER_KEY.toString(), m.mapValue(DATABASE_KEY, DRIVER_KEY));
return map.size() == 0 ? null : map;
}
@Override
public OverrideMode getOverrideMode() {
return statementsMap.mapValue(OVERRIDE_KEY, MODE_KEY);
}
@Override
public URI getBackupTarget() {
return statementsMap.mapValueAsURI(BACKUP_KEY, TARGET_KEY);
}
@Override
public Access getSiteAccess() {
return statementsMap.value(ACCESS_KEY);
}
@Override
public Access getStatsAccess() {
return statementsMap.mapValue(ACCESS_KEY, STATS_KEY);
}
@Override
public Access getApiAccess() {
return statementsMap.mapValue(ACCESS_KEY, API_KEY);
}
@Override
public Integer getGmtOffset() {
return statementsMap.mapValue(GMT_KEY, OFFSET_KEY);
}
@Override
public Boolean getUniqueUrls() {
Object value = statementsMap.mapValue(UNIQUE_KEY, URLS_KEY);
if (value instanceof YesNoFlag) {
return ((YesNoFlag) value).asBoolean();
} else {
return (Boolean) value;
}
}
@Override
public Convert getUrlConvertMode() {
return statementsMap.mapValue(CONVERT_KEY, MODE_KEY);
}
@Override
public List<String> getReserved() {
return statementsMap.valueAsStringList(RESERVED_KEY);
}
@Override
public String getLanguage() {
return statementsMap.value(LANGUAGE_KEY);
}
@Override
public Map<String, String> getUsers() {
return statementsTable.tableKeys(USER_KEY, PASSWORD_KEY);
}
@Override
public String getSite() {
return statementsMap.value(SITE_KEY);
}
public Object methodMissing(String name, Object args) {
try {
return service.methodMissing(name, args);
} catch (StatementsException e) {
return statementsTable.methodMissing(name, args);
}
}
@Override
public String toString() {
return service.toString();
}
} |
// OCC_2dView.h: interface for the OCC_2dView class.
#if !defined(<API key>)
#define <API key>
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "OCC_BaseView.h"
#include "OCC_2dDoc.h"
#include "Resource2d/RectangularGrid.h"
#include "Resource2d/CircularGrid.h"
enum CurrentAction2d {
CurAction2d_Nothing,
<API key>,
<API key>,
<API key>,
<API key>,
};
class AFX_EXT_CLASS OCC_2dView : public OCC_BaseView
{
DECLARE_DYNCREATE(OCC_2dView)
public:
OCC_2dView();
virtual ~OCC_2dView();
CDocument* GetDocument();
Handle_V2d_View& GetV2dView() {return myV2dView;};
void FitAll();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(OCC_2dView)
public:
virtual void OnDraw(CDC* pDC); // overridden to draw this view
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:
virtual void OnInitialUpdate(); // called first time after construct
//}}AFX_VIRTUAL
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
//{{AFX_MSG(OCC_2dView)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
afx_msg void OnFileExportImage();
afx_msg void <API key>();
afx_msg void <API key>();
afx_msg void <API key>();
afx_msg void <API key>();
afx_msg void OnBUTTONGridValues();
afx_msg void <API key>(CCmdUI* pCmdUI);
afx_msg void OnBUTTONGridCancel();
afx_msg void <API key>(CCmdUI* pCmdUI);
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
afx_msg void OnMButtonDown(UINT nFlags, CPoint point);
afx_msg void OnMButtonUp(UINT nFlags, CPoint point);
afx_msg void OnRButtonDown(UINT nFlags, CPoint point);
afx_msg void OnRButtonUp(UINT nFlags, CPoint point);
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnBUTTONFitAll();
afx_msg void OnBUTTONGlobPanning();
afx_msg void OnBUTTONPanning();
afx_msg void OnBUTTONZoomProg();
afx_msg void OnBUTTONZoomWin();
afx_msg void <API key>(CCmdUI* pCmdUI);
afx_msg void <API key>(CCmdUI* pCmdUI);
afx_msg void <API key>(CCmdUI* pCmdUI);
afx_msg void <API key>(CCmdUI* pCmdUI);
afx_msg void OnChangeBackground();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
protected:
CurrentAction2d myCurrentMode;
Standard_Integer myXmin;
Standard_Integer myYmin;
Standard_Integer myXmax;
Standard_Integer myYmax;
Quantity_Factor myCurZoom;
enum LineStyle { Solid, Dot, ShortDash, LongDash, Default };
CPen* m_Pen;
virtual void DrawRectangle2D (const Standard_Integer MinX ,
const Standard_Integer MinY ,
const Standard_Integer MaxX ,
const Standard_Integer MaxY ,
const Standard_Boolean Draw ,
const LineStyle aLineStyle = Default );
virtual void DragEvent2D (const Standard_Integer x ,
const Standard_Integer y ,
const Standard_Integer TheState);
virtual void InputEvent2D (const Standard_Integer x ,
const Standard_Integer y );
virtual void MoveEvent2D (const Standard_Integer x ,
const Standard_Integer y );
virtual void MultiMoveEvent2D (const Standard_Integer x ,
const Standard_Integer y );
virtual void MultiDragEvent2D (const Standard_Integer x ,
const Standard_Integer y ,
const Standard_Integer TheState);
virtual void MultiInputEvent2D (const Standard_Integer x ,
const Standard_Integer y );
virtual void Popup2D (const Standard_Integer x ,
const Standard_Integer y );
protected:
CRectangularGrid <API key>;
CCircularGrid <API key>;
Handle_V2d_View myV2dView;
};
#ifndef _DEBUG // debug version in 2DDisplayView.cpp
inline CDocument* OCC_2dView::GetDocument()
{ return m_pDocument; }
#endif
#endif // !defined(<API key>) |
Title: 40423119_W17
Date: 2017-06-15 11:17
Category: HomeWork
Tags:
Author: 40423119
1.solvespace
2.solvespace 2D
3.
4.Solvespace
5.Solvespace V-rep
6.
7. Fossil SCM
<!-- PELICAN_END_SUMMARY -->
#1. solvespace
<iframe width="560" height="315" src="https:
<iframe src="./../w17/40423119.html" width="800" height="600"></iframe>
#2.solvespace 2D
<iframe width="560" height="315" src="https:
<!-- Brython -->
<script src="../data/Brython-3.3.1/brython.js"></script>
<script src="../data/Brython-3.3.1/brython_stdlib.js"></script>
<!-- Brython -->
<script>
window.onload=function(){
// data/py
brython({debug:1, pythonpath:['./../data/py']});
}
</script>
<!-- Brython -->
<canvas id="onegear2" width="800" height="600"></canvas>
<div id="onegear_div" width="800" height="20"></div>
<script type="text/python3">
from browser import document as doc
import math
# deg
deg = math.pi/180.
# Spur
class Spur(object):
def __init__(self, ctx):
self.ctx = ctx
def create_line(self, x1, y1, x2, y2, width=3, fill="#54fff6"):
self.ctx.beginPath()
self.ctx.lineWidth = width
self.ctx.moveTo(x1, y1)
self.ctx.lineTo(x2, y2)
self.ctx.strokeStyle = fill
self.ctx.stroke()
def create_line2(self, x1, y1, x2, y2, width=3, fill="#54ff5f"):
self.ctx.beginPath()
self.ctx.lineWidth = width
self.ctx.moveTo(x1, y1)
self.ctx.lineTo(x2, y2)
self.ctx.strokeStyle = fill
self.ctx.stroke()
def create_line3(self, x1, y1, x2, y2, width=3, fill="#f354ff"):
self.ctx.beginPath()
self.ctx.lineWidth = width
self.ctx.moveTo(x1, y1)
self.ctx.lineTo(x2, y2)
self.ctx.strokeStyle = fill
self.ctx.stroke()
def Gear(self, midx, midy, rp, n=20, pa=20, color="black"):
rp = 250
imax = 15
m=2*rp/n
a=m
d=1.25*m
ra=rp+a
# self.create_line(X, Y, X, Y)
self.create_line2(400.0092358669, 99.7467537143, 251.9547191519, 442.8435006599)
self.create_line3(400.0092358669, 99.7467537143, 537.4903413459, 440.1127860465)
self.create_line2(143.0084564396, 393.7995926042, 314.6469023490, 471.0653927376)
self.create_line3(143.0084564396, 393.7995926042, 202.3690092639, 492.0551734376)
self.create_line2(202.3690092639, 492.0551734376, 314.6469023490, 471.0653927376)
self.create_line3(465.4788879723, 480.3190039124, 593.2602222967, 408.9747395441)
self.create_line2(465.4788879723, 480.3190039124, 567.9291276424, 502.4572906272)
self.create_line3(567.9291276424, 502.4572906272, 593.2602222967, 408.9747395441)
if rd>rb:
dr = (ra-rd)/imax
else:
dr=(ra-rb)/imax
sigma=math.pi/(2*n)+math.tan(pa*deg)-pa*deg
for j in range(-9, 10, +1):
ang=-2.*j*math.pi/n+sigma
ang2=2.*j*math.pi/n+sigma
lxd=midx+rd*math.sin(ang2-2.*math.pi/n)
lyd=midy-rd*math.cos(ang2-2.*math.pi/n)
for i in range(imax+1):
if rd>rb:
r=rd+i*dr
else:
r=rb+i*dr
theta=math.sqrt((r*r)/(rb*rb)-1.)
alpha=theta-math.atan(theta)
xpt=r*math.sin(alpha-ang)
ypt=r*math.cos(alpha-ang)
xd=rd*math.sin(-ang)
yd=rd*math.cos(-ang)
if(i==0):
last_x = midx+xd
last_y = midy-yd
self.create_line((lxd),(lyd),(midx+xd),(midy-yd),fill=color)
for i in range(imax+1):
if rd>rb:
r=rd+i*dr
else:
r=rb+i*dr
theta=math.sqrt((r*r)/(rb*rb)-1.)
alpha=theta-math.atan(theta)
xpt=r*math.sin(ang2-alpha)
ypt=r*math.cos(ang2-alpha)
xd=rd*math.sin(ang2)
yd=rd*math.cos(ang2)
if(i==0):
last_x = midx+xd
last_y = midy-yd
self.create_line((midx+xpt),(midy-ypt),(last_x),(last_y),fill=color)
if(i==imax):
rfx=midx+xpt
rfy=midy-ypt
last_x = midx+xpt
last_y = midy-ypt
self.create_line(lfx,lfy,rfx,rfy,fill=color)
canvas = doc['onegear2']
ctx = canvas.getContext("2d")
x = (canvas.width)/2
y = (canvas.height)/2
r = 0.8*(canvas.height/2)
n = 36
pa = 20
Spur(ctx).Gear(x, y, r, n, pa, "blue")
</script>
<iframe width="560" height="315" src="https:
#4.Solvespace
<iframe width="560" height="315" src="https:
<iframe src="./../w17/two link.html" width="800" height="600"></iframe>
#5.Solvespace V-rep
<iframe width="560" height="315" src="https:
<a href="https://40423119.github.io/2017springcd_hw/blog/<API key>.html">_AG1</a>
#7. Fossil SCM
<iframe width="560" height="315" src="https: |
package elki.utilities.datastructures;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Random;
import org.junit.Test;
/**
* Test the Kuhn-Munkres implementation.
*
* @author Erich Schubert
*/
public class KuhnMunkresWongTest {
@Test
public void test1() {
int[] assignment = new KuhnMunkresWong().run(KuhnMunkresTest.TEST1);
double sum = 0.;
for(int i = 0; i < assignment.length; i++) {
assertTrue("Unassigned row " + i, assignment[i] >= 0);
sum += KuhnMunkresTest.TEST1[i][assignment[i]];
}
assertEquals("Assignment not optimal", 55, sum, 0);
}
@Test
public void test2() {
int[] assignment = new KuhnMunkresWong().run(KuhnMunkresTest.TEST2);
double sum = 0.;
for(int i = 0; i < assignment.length; i++) {
assertTrue("Unassigned row " + i, assignment[i] >= 0);
sum += KuhnMunkresTest.TEST2[i][assignment[i]];
}
assertEquals("Assignment not optimal", 4, sum, 0);
}
@Test
public void testNonSq() {
int[] assignment = new KuhnMunkresWong().run(KuhnMunkresTest.NONSQUARE);
double sum = 0.;
for(int i = 0; i < assignment.length; i++) {
assertTrue("Unassigned row " + i, assignment[i] >= 0);
sum += KuhnMunkresTest.NONSQUARE[i][assignment[i]];
}
assertEquals("Assignment not optimal", 637518, sum, 0);
}
@Test
public void testDifficult() {
int[] assignment = new KuhnMunkresWong().run(KuhnMunkresTest.DIFFICULT);
double sum = 0.;
for(int i = 0; i < assignment.length; i++) {
assertTrue("Unassigned row " + i, assignment[i] >= 0);
sum += KuhnMunkresTest.DIFFICULT[i][assignment[i]];
}
assertEquals("Assignment not optimal", 2.24, sum, 1e-4);
}
@Test
public void testDifficult2() {
int[] assignment = new KuhnMunkresWong().run(KuhnMunkresTest.DIFFICULT2);
double sum = 0.;
for(int i = 0; i < assignment.length; i++) {
assertTrue("Unassigned row " + i, assignment[i] >= 0);
sum += KuhnMunkresTest.DIFFICULT2[i][assignment[i]];
}
assertEquals("Assignment not optimal", 0.8802, sum, 1e-4);
}
@Test
public void testLarge() {
long seed = 0L;
Random rnd = new Random(seed);
double[][] mat = new double[100][100];
for(int i = 0; i < mat.length; i++) {
double[] row = mat[i];
for(int j = 0; j < row.length; j++) {
row[j] = Math.abs(rnd.nextDouble());
}
}
int[] assignment = new KuhnMunkresWong().run(mat);
double sum = 0.;
for(int i = 0; i < assignment.length; i++) {
assertTrue("Unassigned row " + i, assignment[i] >= 0);
sum += mat[i][assignment[i]];
}
if(seed == 0) {
if(mat.length == 10 && mat[0].length == 10) {
assertEquals("sum", 1.467733381753002, sum, 1e-8);
// Duration: 0.007970609
}
if(mat.length == 100 && mat[0].length == 100) {
assertEquals("sum", 1.5583906418867581, sum, 1e-8);
// Duration: 0.015696813
}
if(mat.length == 1000 && mat[0].length == 1000) {
assertEquals("sum", 1.6527526146559663, sum, 1e-8);
// Duration: 0.8892345580000001
}
if(mat.length == 10000 && mat[0].length == 10000) {
assertEquals("sum", 1.669458072091596, sum, 1e-8);
// Duration: 3035.95495334
}
}
}
} |
Brimir::Application.routes.draw do
devise_for :users, controllers: { omniauth_callbacks: 'omniauth' }
resources :users
namespace :tickets do
resource :deleted, only: :destroy, controller: :deleted
resource :selected, only: :update, controller: :selected
end
resources :tickets, only: [:index, :show, :update, :new, :create]
resources :labelings, only: [:destroy, :create]
resources :rules
resources :labels, only: [:destroy, :update, :index]
resources :replies, only: [:create, :new]
get '/attachments/:id/:format' => 'attachments#show'
resources :attachments, only: [:index, :new]
resources :email_addresses, only: [:index, :create, :new, :destroy]
root to: 'tickets#index'
namespace :api do
namespace :v1 do
resources :tickets, only: [ :index, :show ]
resources :sessions, only: [ :create ]
end
end
end |
#include <stddef.h>
#include "logger/logger.h"
#include "wrappers.h"
using namespace drivers::i2c;
I2CResult I2CFallbackBus::Write(const I2CAddress address, gsl::span<const uint8_t> inData)
{
const I2CResult systemBusResult = this->_innerBuses.Bus.Write(address, inData);
if (systemBusResult == I2CResult::OK)
{
return systemBusResult;
}
LOGF(LOG_LEVEL_WARNING, "Fallbacking to payload bus. System bus error %d. Transfer to %X", num(systemBusResult), address);
const I2CResult payloadBusResult = this->_innerBuses.Payload.Write(address, inData);
return payloadBusResult;
}
I2CResult I2CFallbackBus::Read(const I2CAddress address, gsl::span<uint8_t> outData)
{
const I2CResult systemBusResult = this->_innerBuses.Bus.Read(address, outData);
if (systemBusResult == I2CResult::OK)
{
return systemBusResult;
}
LOGF(LOG_LEVEL_WARNING, "Fallbacking to payload bus. System bus error %d. Transfer to %X", num(systemBusResult), address);
const I2CResult payloadBusResult = this->_innerBuses.Payload.Read(address, outData);
return payloadBusResult;
}
I2CResult I2CFallbackBus::WriteRead(const I2CAddress address, gsl::span<const uint8_t> inData, gsl::span<uint8_t> outData)
{
const I2CResult systemBusResult = this->_innerBuses.Bus.WriteRead(address, inData, outData);
if (systemBusResult == I2CResult::OK)
{
return systemBusResult;
}
LOGF(LOG_LEVEL_WARNING, "Fallbacking to payload bus. System bus error %d. Transfer to %X", num(systemBusResult), address);
const I2CResult payloadBusResult = this->_innerBuses.Payload.WriteRead(address, inData, outData);
return payloadBusResult;
}
I2CFallbackBus::I2CFallbackBus(I2CInterface& buses) : _innerBuses(buses)
{
} |
<?php
/**
* Np_Db Class Definition
*
* @package Np_Soap
* @subpackage Np_Soap
*/
class Np_Soap_Handler {
/**
* sendMessage os the function defined by our wsdl .
*
* it will be called by
* other providers in order to send transactio messages to internal.
* 1.the functions receives the params .
* 2.logs them to database
* 3.validates whether they are in correct format and not null
* 4.sends Internal the message to internal via http request.
* 5.returns the resulting ack code from the params validation.
*
* @param Array $params
* @return array "NP_ACK" or string
*/
public function sendMessage($params) {
$data = $this->intoArray($params);
$reqModel = new <API key>($data); //prepares data for sending internal the message
$ack = $reqModel->Execute();
// log all received calls if request log enabled
if (<API key>::getSettings('EnableRequestLog')) {
<API key>::logRequestResponse($params, $ack, $data['REQUEST_ID'], '[Input] ');
}
if ($ack === FALSE || (strpos(strtolower($ack), "ack") === FALSE)) {
$ack = "Ack00";
}
return array('NP_ACK' => array('ACK_CODE' => $ack, //returns default value for testing need to fix
'ACK_DATE' => <API key>::getDateIso()));
}
/**
* turns the soap array into a simple array for sending to internal.
* sets soap "signature" so array may be validated and sent back
* through soap after it reaches internal's proxy
*
* @param Array $params
* @return Array $params associative array
*/
public function intoArray($params) {
$data = (array) $params->NP_MESSAGE; //takes data out of np message array
$xmlString = <API key>($data['BODY']); //loads xml string from xml object in body
if ($xmlString == NULL) {
$xmlString[0] = "NULL";
}
$header = (array) $data['HEADER'];
$msgtype = $header['MSG_TYPE'];
$xmlArray = $xmlString[0]->$msgtype;
$convertedData = $this->convertArray($msgtype, $xmlArray, $header);
//sets soap "signature"
$convertedData['SOAP'] = 1;
return $convertedData; //returns simple array (1 level only)
}
/**
* convert Xml data to associative array
*
* @param string $msgType message type
* @param simple_xml $xmlArray simple xml object
* @param array $header the header data to join to the return data
*
* @return array converted data with header and the xml
* @todo refactoring to inner bridge classes
*/
function convertArray($msgType, $xmlArray, $header) {
$data = $header;
switch ($msgType) {
case "Check":
$nType = <API key>::getSettings("NetworkType");
if ($nType === "M") {
$networkType = "mobile";
$data['NETWORK_TYPE'] = (string) $nType;
} else {
$networkType = "fixed";
$data['NETWORK_TYPE'] = (string) $nType;
}
if (!empty($xmlArray->$networkType-><API key>) && $xmlArray->$networkType-><API key> !== NULL) {
$data['<API key>'] = (string) $xmlArray->$networkType-><API key>->identificationValue;
$data['<API key>'] = (string) $xmlArray->$networkType-><API key>-><API key>;
$data['<API key>'] = (string) $xmlArray->$networkType-><API key>-><API key>;
$data['NUMBER_TYPE'] = (string) $xmlArray->$networkType-><API key>->numberType;
$data['NUMBER'] = (string) $xmlArray->$networkType-><API key>->number;
} else {
$data['NUMBER_TYPE'] = (string) $xmlArray->$networkType-><API key>->numberType;
$data['NUMBER'] = (string) $xmlArray->$networkType-><API key>->number;
}
break;
case "Request":
$data['PORT_TIME'] = (string) $xmlArray->portingDateTime;
break;
case "Update":
$data['PORT_TIME'] = (string) $xmlArray->portingDateTime;
break;
case "Cancel":
break;
case "KD_update":
$data['KD_UPDATE_TYPE'] = (string) $xmlArray[0];
$data['REMARK'] = (string) $xmlArray->remark;
break;
case "Execute":
break;
case "Publish":
$data['DONOR'] = (string) $xmlArray->donor;
$data['CONNECT_TIME'] = (string) $xmlArray->connectDateTime;
$data['PUBLISH_TYPE'] = (string) $xmlArray->publishType;
$data['DISCONNECT_TIME'] = (string) $xmlArray->disconnectDateTime;
if (isset($xmlArray->fixed)) {
$data['NUMBER_TYPE'] = (string) $xmlArray->fixed->fixedNumberSingle->numberType;
if (isset($xmlArray->fixed->fixedNumberRange)) {
$data['NUMBER_TYPE'] = (string) $xmlArray->fixed->fixedNumberRange->numberType;
$data['FROM_NUMBER'] = (string) $xmlArray->fixed->fixedNumberRange->fromNumber;
$data['TO_NUMBER'] = (string) $xmlArray->fixed->fixedNumberRange->toNumber;
} else {
$data['NUMBER'] = (string) $xmlArray->fixed->fixedNumberSingle->number;
}
} else {
$data['NUMBER_TYPE'] = (string) $xmlArray->mobile->numberType;
$data['NUMBER'] = (string) $xmlArray->mobile->number;
}
break;
case "Cancel_publish":
$data['DONOR'] = (string) $xmlArray->donor;
break;
case "Return":
$data['NUMBER'] = (string) $xmlArray->number;
if (isset($xmlArray->mobile)) {
$data['NETWORK_TYPE'] = (string) $xmlArray->mobile->networkType;
$data['NUMBER_TYPE'] = (string) $xmlArray->mobile->numberType;
} else {
$data['NETWORK_TYPE'] = (string) $xmlArray->fixed->networkType;
$data['NUMBER_TYPE'] = (string) $xmlArray->fixed->numberType;
}
break;
case "Inquire_number":
$data['NUMBER'] = (string) $xmlArray->number;
break;
case "Up_system":
$res = <API key>::saveShutDownDetails($data['FROM'], "UP");
break;
case "Down_system":
$res = <API key>::saveShutDownDetails($data['FROM'], "DOWN");
break;
case "Check_response":
$data['ESSENTIAL_INFO_1'] = (string) $xmlArray->essentialInfo1;
$data['ESSENTIAL_INFO_2'] = (string) $xmlArray->essentialInfo2;
$data['ESSENTIAL_INFO_3'] = (string) $xmlArray->essentialInfo3;
$data['ESSENTIAL_INFO_4'] = (string) $xmlArray->essentialInfo4;
$data['ESSENTIAL_INFO_5'] = (string) $xmlArray->essentialInfo5;
case "Request_response":
// this check because check_response go through this code (TODO: refactoring)
if (isset($xmlArray->portingDateTime)) {
$data['PORT_TIME'] = (string) $xmlArray->portingDateTime;
}
case "Update_response":
case "Cancel_response":
case "Execute_response":
case "Publish_response":
case "KD_update_response":
case "<API key>":
case "<API key>":
case "Return_response":
if (isset($xmlArray->positiveApproval)) {
$data['APPROVAL_IND'] = "Y";
} else {
$data['APPROVAL_IND'] = "N";
$data['REJECT_REASON_CODE'] = (string) $xmlArray->negativeApproval->rejectReasonCode;
}
$data['REQUEST_TRX_NO'] = (string) $xmlArray->requestTrxNo;
$data['REQUEST_RETRY_DATE'] = (string) $xmlArray->requestRetryDate;
}
return $data;
}
} |
DELETE FROM `weenie` WHERE `class_Id` = 20478;
INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`)
VALUES (20478, '<API key>', 34, '2019-02-10 00:00:00') /* Scroll */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (20478, 1, 8192) /* ItemType - Writable */
, (20478, 5, 30) /* EncumbranceVal */
, (20478, 16, 8) /* ItemUseable - Contained */
, (20478, 19, 2000) /* Value */
, (20478, 93, 1044) /* PhysicsState - Ethereal, IgnoreCollisions, Gravity */
, (20478, 8041, 101) /* <API key> - Resting */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (20478, 22, True ) /* Inscribable */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (20478, 39, 1.5) /* DefaultScale */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (20478, 1, 'Scroll of Fiery Blessing') /* Name */
, (20478, 14, 'Use this item to attempt to learn its spell.') /* Use */
, (20478, 16, 'Inscribed spell: Fiery Blessing
Reduces damage the caster takes from Fire by 65%.') /* LongDesc */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (20478, 1, 0x0200018A) /* Setup */
, (20478, 8, 0x06003555) /* Icon */
, (20478, 22, 0x3400002B) /* PhysicsEffectTable */
, (20478, 28, 2157) /* Spell - FireProtectionSelf7 */
, (20478, 8001, 6307864) /* <API key> - Value, Usable, Container, Burden, Spell */
, (20478, 8003, 18) /* <API key> - Inscribable, Attackable */
, (20478, 8005, 135297) /* <API key> - CSetup, ObjScale, PeTable, AnimationFrame */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (20478, 8000, 0xDC32EF42) /* <API key> */; |
# -*- coding: utf-8 -*-
import time
from datetime import datetime
import openerp.addons.decimal_precision as dp
from openerp.osv import fields, osv
from openerp.tools import <API key>, <API key>
from openerp.tools import float_compare
from openerp.tools.translate import _
from openerp import SUPERUSER_ID
from openerp import netsvc
from openerp import tools
class mrp_production(osv.osv):
_inherit = 'mrp.production'
def <API key>(self, cr, uid, ids, properties=None, context=None):
""" Computes bills of material of a product.
@param properties: List containing dictionaries of properties.
@return: No. of products.
"""
if properties is None:
properties = []
results = []
bom_obj = self.pool.get('mrp.bom')
uom_obj = self.pool.get('product.uom')
prod_line_obj = self.pool.get('mrp.production.product.line')
workcenter_line_obj = self.pool.get('mrp.production.workcenter.line')
for production in self.browse(cr, uid, ids):
#unlink product_lines
prod_line_obj.unlink(cr, SUPERUSER_ID, [line.id for line in production.product_lines], context=context)
#unlink workcenter_lines
workcenter_line_obj.unlink(cr, SUPERUSER_ID, [line.id for line in production.workcenter_lines], context=context)
# search BoM structure and route
bom_point = production.bom_id
bom_id = production.bom_id.id
if not bom_point:
bom_id = bom_obj._bom_find(cr, uid, production.product_id.id, production.product_uom.id, properties)
if bom_id:
bom_point = bom_obj.browse(cr, uid, bom_id)
routing_id = bom_point.routing_id.id or False
self.write(cr, uid, [production.id], {'bom_id': bom_id, 'routing_id': routing_id})
if not bom_id:
continue
# get components and workcenter_lines from BoM structure
factor = uom_obj._compute_qty(cr, uid, production.product_uom.id, production.product_qty, bom_point.product_uom.id)
res = bom_obj._bom_explode(cr, uid, bom_point, factor / bom_point.product_qty, properties, routing_id=production.routing_id.id)
results = res[0] # product_lines
results2 = res[1] # workcenter_lines
# reset product_lines in production order
for line in results:
line['production_id'] = production.id
prod_line_obj.create(cr, uid, line)
#reset workcenter_lines in production order
for line in results2:
line['production_id'] = production.id
workcenter_line_obj.create(cr, uid, line)
return results
def action_ready(self, cr, uid, ids, context=None):
""" Changes the production state to Ready and location id of stock move.
@return: True
"""
move_obj = self.pool.get('stock.move')
self.write(cr, uid, ids, {'state': 'ready'})
for production in self.browse(cr, uid, ids, context=context):
if not production.bom_id:
produce_move_id = self.<API key>(cr, uid, production, context=context)
for (production_id,name) in self.name_get(cr, uid, ids):
production = self.browse(cr, uid, production_id)
if production.move_prod_id and production.move_prod_id.location_id.id != production.location_dest_id.id:
move_obj.write(cr, uid, [production.move_prod_id.id],
{'location_id': production.location_dest_id.id})
return True
def action_produce(self, cr, uid, production_id, production_qty, production_mode, context=None):
production = self.browse(cr, uid, production_id, context=context)
if not production.bom_id and production.state == 'ready':
wf_service = netsvc.LocalService("workflow")
wf_service.trg_validate(uid, 'mrp.production', production_id, 'button_produce', cr)
return super(mrp_production, self).action_produce(cr, uid, production_id, production_qty, production_mode, context=context)
mrp_production() |
package com.nlbhub.nlb.domain;
import com.nlbhub.nlb.api.PropertyManager;
/**
* The <API key> class represents parameters used when saving media files during export of the scheme
* to some end format (such as INSTEAD game).
*
* @author Anton P. Kolosov
* @version 1.0 8/9/12
*/
public class <API key> {
public enum Preset {CUSTOM, DEFAULT, NOCHANGE, COMPRESSED};
private static final <API key> NOCHANGE = new <API key>(Preset.NOCHANGE, false, 0);
private static final <API key> COMPRESSED = new <API key>(Preset.COMPRESSED, true, 80);
private static final <API key> DEFAULT = (
new <API key>(
Preset.DEFAULT,
PropertyManager.getSettings().getDefaultConfig().getExport().isConvertpng2jpg(),
PropertyManager.getSettings().getDefaultConfig().getExport().getQuality()
)
);
private Preset m_preset = Preset.CUSTOM;
private boolean m_convertPNG2JPG;
private int m_quality;
public static <API key> fromPreset(Preset preset) {
switch (preset) {
case NOCHANGE:
return <API key>.NOCHANGE;
case COMPRESSED:
return <API key>.COMPRESSED;
default:
return <API key>.DEFAULT;
}
}
public static <API key> getDefault() {
return DEFAULT;
}
/*
public <API key>(boolean convertPNG2JPG, int quality) {
m_preset = Preset.CUSTOM;
m_convertPNG2JPG = convertPNG2JPG;
m_quality = quality;
}
*/
private <API key>(Preset preset, boolean convertPNG2JPG, int quality) {
m_preset = preset;
m_convertPNG2JPG = convertPNG2JPG;
m_quality = quality;
}
public Preset getPreset() {
return m_preset;
}
public boolean isConvertPNG2JPG() {
return m_convertPNG2JPG;
}
public int getQuality() {
return m_quality;
}
} |
# Friend Chat
Friend Chat is a chat integration platform for Friend. It is built to make
it fairly straightforward to add access to 3rd party chat APIs. It is a
client - server architecture where the server handles the connection to the
remote API and presents the content to the client. Multiple clients can
be connected per account, all staying in sync. Accounts are created and
logged in through Friend, no extra setup required.
## Video / Audio Conferencing, aka Live
Friend Chat allows peer to peer video and audio calls over webRTC, supported
by the presence service. The limits to number of participants is
practical; the bandwidth and power of your device.
# Invites
Live invites can be sent through any module. It is sent as a data string,
and as long as the invitee is also using Friend Chat, it will be intercepted
and presented to the user. The live session is then established over the
presence service.
# Guests
Any live session can be shared through a clickable link. This is a public invite
and can be used by any number of people until it is explicitly canceled. People
using this link will join as a guest with either a randomly generated name or
one they choose themselves.
# Share your screen or app
Screen sharing is available for chrome through an extension. The option
is found in the live view menu, and will either prompt you install the
extension or offer to initiate screen sharing.
## Modules
Modules are integrations towards 3rd party chat services. They have a server part
that communicates with the remote service/server API and a client part with a custom
UI that presents the data. Current modules are IRC, Presence and Treeroot. Presence
is always there and IRC is added by default.
# IRC
Internet Relay Chat, because it would be weird not to have it. Covers
most basic needs and commands. An abbreviated list of commands if you are new to IRC:
* /nick new_nick - change your nick
* /action does something silly - *me does something silly*
* /join #channel_name - join a channel
* /part - in channel, leave the channel
This can also be changed in settings. More commands and how irc works in general
can be found on the internet.
# Presence
Presence provides temporary or persistent many-to-many rooms for chatting and
video / audio conferencing. Invites to presence rooms can be sent through the other
modules. More info in the FriendSoftwareLabs/presence repository!
# Treeroot
The Treeroot module integrates the chat part of the Treeroot system. It provides
one to one chat, optionally end to end encrypted. You'll need to add the module
( 'add chat account' in the menu ) then log in with ( or create a new ) Treeroot
account. |
<!DOCTYPE html>
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="SHORTCUT ICON" href="../../../../img/clover.ico" />
<link rel="stylesheet" href="../../../../aui/css/aui.min.css" media="all"/>
<link rel="stylesheet" href="../../../../aui/css/aui-experimental.min.css" media="all"/>
<!--[if IE 9]><link rel="stylesheet" href="../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]-->
<style type="text/css" media="all">
@import url('../../../../style.css');
@import url('../../../../tree.css');
</style>
<script src="../../../../jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../../../../aui/js/aui.min.js" type="text/javascript"></script>
<script src="../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script>
<script src="../../../../aui/js/aui-soy.min.js" type="text/javascript"></script>
<script src="../../../../package-nodes-tree.js" type="text/javascript"></script>
<script src="../../../../clover-tree.js" type="text/javascript"></script>
<script src="../../../../clover.js" type="text/javascript"></script>
<script src="../../../../clover-descriptions.js" type="text/javascript"></script>
<script src="../../../../cloud.js" type="text/javascript"></script>
<title><API key> </title>
</head>
<body >
<div id="page">
<header id="header" role="banner">
<nav class="aui-header <API key>" role="navigation">
<div class="aui-header-inner">
<div class="aui-header-primary">
<h1 id="logo" class="aui-header-logo <API key>">
<a href="http:
</h1>
</div>
<div class="<API key>">
<ul class="aui-nav">
<li id="system-help-menu">
<a class="aui-nav-link" title="Open online Clover documentation" target="_blank"
href="https://confluence.atlassian.com/display/CLOVER/Clover+Documentation+Home">
<span class="aui-icon aui-icon-small aui-iconfont-help"> Help</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="aui-page-panel">
<div class="<API key>">
<div class="aui-page-panel-nav <API key>">
<div class="<API key>" style="margin-bottom: 20px;">
<div class="<API key>">
<div class="aui-avatar aui-avatar-large aui-avatar-project">
<div class="aui-avatar-inner">
<img src="../../../../img/clover_logo_large.png" alt="Clover icon"/>
</div>
</div>
</div>
<div class="<API key>" >
<h1>
<API key>
</h1>
</div>
</div>
<nav class="aui-navgroup <API key>">
<div class="aui-navgroup-inner">
<ul class="aui-nav">
<li class="">
<a href="../../../../dashboard.html">Project overview</a>
</li>
</ul>
<div class="aui-nav-heading <API key>">
<strong>Packages</strong>
</div>
<div class="aui-nav project-packages">
<form method="get" action="#" class="aui <API key>">
<input type="text" autocomplete="off" class="package-filter text"
placeholder="Type to filter packages..." name="package-filter" id="package-filter"
title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/>
</form>
<p class="<API key> hidden">
<small>No results found.</small>
</p>
<div class="<API key>" data-root-relative="../../../../" data-package-name="com.rapidminer.gui.dnd">
<div class="<API key>"></div>
<div class="<API key>"></div>
</div>
</div>
</div>
</nav> </div>
<section class="<API key>">
<div class="<API key>">
<ol class="aui-nav aui-nav-breadcrumbs">
<li><a href="../../../../dashboard.html">Project Clover database 5 2017 16:40:29 CST</a></li>
</ol>
<h1 class="aui-h2-clover">
Package com.rapidminer.gui.dnd
</h1>
<div class="aui-tabs horizontal-tabs">
<ul class="tabs-menu">
<li class="menu-item ">
<a href="pkg-summary.html"><strong>Application code</strong></a>
</li>
<li class="menu-item active-tab">
<a href="top-risks.html"><strong>Top risks</strong></a>
</li>
<li class="menu-item ">
<a href="quick-wins.html"><strong>Quick wins</strong></a>
</li>
</ul>
<div class="tabs-pane active-pane" id="tabs-first">
<div> </div>
<div class="aui-message aui-message-warning">
<p class="title">
<strong>Evaluation License</strong>
</p>
<p>
This report was generated with an evaluation server license. <a href="http:
</p>
</div>
<div style="text-align: right; margin-bottom: 10px">
<button class="aui-button aui-button-subtle" id="popupHelp">
<span class="aui-icon aui-icon-small aui-iconfont-help"></span> How to read this chart
</button>
<script>
AJS.InlineDialog(AJS.$("#popupHelp"), "helpDialog",
function (content, trigger, showPopup) {
var description = topRisksDescription();
var title = 'Top Risks';
content.css({"padding": "20px"}).html(
'<h2>' + title + '</h2>' + description);
showPopup();
return false;
},
{
width: 600
}
);
</script>
</div>
<div style="padding: 20px; border: 1px solid #cccccc; background-color: #f5f5f5; border-radius: 3px">
<div id="shallowPackageCloud" >
</div>
</div>
</div> <!-- tabs-pane active-pane -->
</div> <!-- aui-tabs horizontal-tabs -->
</div> <!-- class="<API key>" -->
<footer id="footer" role="contentinfo">
<section class="footer-body">
<ul>
<li>
Report generated by <a target="_new" href="http:
on 5 2017 17:24:16 CST using coverage data from 1 1970 08:00:00 CST.
</li>
</ul>
<ul>
<li>Clover Evaluation License registered to Clover Plugin. You have 29 day(s) before your license expires.</li>
</ul>
<div id="footer-logo">
<a target="_blank" href="http:
Atlassian
</a>
</div>
</section>
</footer> </section> <!-- class="<API key>" -->
</div> <!-- class="<API key>" -->
</div> <!-- class="aui-page-panel" -->
</div> <!-- id="page" -->
</body>
</html> |
<div align="center" class="heading_gray">
<h3>User Registration</h3>
</div>
<br/>
<?php echo form_open('user/user_registration/userinsert', array('id' => 'formUser'));
echo blue_box_top();
?>
<table width="100%" border="0" cellspacing="0" cellpadding="4" align="center" class="heading_tab" style="margin-top:15px;">
<tr>
<th colspan="4" align="left">User Creation</th>
</tr>
<tr>
<td width="10%" class=""> </td>
<td align="left" width="27%" class="table_row_first"> User Name : </td>
<td align="left" width="55%" class="table_row_first"><?php echo form_input("txtNewUserName",@$selected_user[0]['user_name'], 'class="input_box" id="txtNewUserName"' );?></td>
<td width="18%"> </td>
</tr>
<tr>
<td> </td>
<td align="left" width="27%" class="table_row_first"> Password : </td>
<td align="left" width="55%" class="table_row_first"><?php echo form_password("txtNewPassword",'', 'class="input_box" id="txtNewPassword"' );?></td>
<td width="18%"> </td>
</tr>
<!
<td> </td>
<td align="left" width="27%" class="table_row_first"> User Type : </td>
<td align="left" width="55%" class="table_row_first"><?php echo (@$school_show == 'show') ? @$school_details[0]['class_end'] : form_dropdown("userType", array(0=>'...........', 1=>'Admin', 2 => 'User'), 'id="userType"','id="userType"');?></td>
<td width="18%"> </td>
</tr>
<?php
if(count(@$user_rights) > 0 ){?>
<tr>
<td> </td>
<td align="left" width="27%" class="table_row_first" valign="top"> User Rights : </td>
<td align="left" width="55%" class="table_row_first">
<?php
$functionality_label = '';
for($i=0; $i<count($user_rights); $i++){
if($functionality_label != $user_rights[$i]['label_name']){
$functionality_label = $user_rights[$i]['label_name'];
?>
<div class="clear_both"></div>
<div class="functionality_label"><?php echo $user_rights[$i]['label_name']?></div>
<?php
}
if(count(@$<API key>) > 0 && @$<API key>[0] != 0){
$checked = (in_array($user_rights[$i]['rf_id'], @$<API key>)) ? 'TRUE' : '';
} else {
$checked = '';
}
$data = array(
'name' => 'chkRight_'.$user_rights[$i]['rf_id'],
'id' => 'chkRight_'.$user_rights[$i]['rf_id'],
'value' => $user_rights[$i]['rf_id'],
'checked' => $checked,
'style' => 'margin:5px',
);
?>
<div class="clear_both"></div>
<div class="functionalities">
<?php
echo form_checkbox($data);
echo form_label($user_rights[$i]['rf_functionality'], 'chkRight_'.$user_rights[$i]['rf_id']).'<br>';
?>
</div>
<?php
}
?>
</td>
<td width="18%"> </td>
</tr>
<?php }?>
<tr>
<td align="center" colspan="4">
<?php echo (@$selected_user[0]['user_id'] != '') ? form_button('Update User', 'Update User', 'onClick="javascript: return fnsUserUpdate(\''.@$selected_user[0]['user_id'].'\')"').' '.form_button('Cancel', 'Cancel', 'onClick="javascript: return cancel()"'):form_submit('Add User', 'Add User', 'onClick="javascript: return fnsUserAdd()"');?> </td>
</tr>
</table>
<input type="hidden" name="hidUserId" id="hidUserId" />
<?php
echo blue_box_bottom();
echo form_close();
?> |
<API key> = Creature:new {
objectName = "",
socialGroup = "thug",
faction = "thug",
level = 17,
chanceHit = 0.320000,
damageMin = 180,
damageMax = 190,
baseXp = 1102,
baseHAM = 2400,
baseHAMmax = 3000,
armor = 0,
resists = {0,0,0,0,0,0,0,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0.000000,
ferocity = 0,
pvpBitmask = ATTACKABLE + ENEMY + AGGRESSIVE,
creatureBitmask = PACK,
optionsBitmask = 128,
diet = HERBIVORE,
templates = { "object/mobile/<API key>.iff" },
lootGroups = {
{
groups = {
{group = "junk", chance = 4000000},
{group = "wearables_common", chance = 3000000},
{group = "loot_kit_parts", chance = 2000000},
{group = "tailor_components", chance = 1000000},
}
}
},
weapons = {"<API key>"},
attacks = merge(brawlermaster,marksmanmaster)
}
CreatureTemplates:addCreatureTemplate(<API key>, "<API key>") |
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class <API key> extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('oauth_auth_codes', function (Blueprint $table) {
$table->string('id', 100)->primary();
$table->unsignedBigInteger('user_id')->index();
$table->unsignedBigInteger('client_id');
$table->text('scopes')->nullable();
$table->boolean('revoked');
$table->dateTime('expires_at')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('oauth_auth_codes');
}
} |
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AppModule } from '../../../../app.module';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material';
import { <API key> } from './confirm-dialog.component';
describe('<API key>', () => {
let component: <API key>;
let dialog: MatDialog;
let fixture: ComponentFixture<<API key>>;
beforeEach(async(() => {
TestBed.<API key>({
imports: [
AppModule,
],
providers: [
{ provide: MAT_DIALOG_DATA, useValue: {} },
{ provide: MatDialogRef }
]
})
.compileComponents();
}));
beforeEach(() => {
dialog = TestBed.get(MatDialog);
fixture = TestBed.createComponent(<API key>);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
}); |
{% extends 'task/default.html' %}
{% block task-content %}
<dl class="task__data">
{% if task.category %}
<dt>Category</dt>
<dd>{{ task.<API key> }}</dd>
{% endif %}
{% if task.text %}
<dt>Message</dt>
<dd>{{task.text}}</dd>
{% endif %}
{% if task.user %}
<dt>User</dt>
<dd><a href="{% url 'admin:auth_user_change' task.user.pk %}">{{task.user.profile.full_name}}</a></dd>
{% endif %}
{% if task.foia %}
<dt>Request</dt>
<dd><a href="{{task.foia.get_absolute_url}}">{{task.foia}}</a> (<a href="{% url 'admin:<API key>' task.foia.pk %}">admin</a>) - MR #{{task.foia.pk}}</dd>
{% elif task.agency %}
<dt>Agency</dt>
<dd><a href="{% url 'admin:<API key>' task.agency.pk %}">{{task.agency}}</a></dd>
{% elif task.jurisdiction %}
<dt>Jurisdiction</dt>
<dd><a href="{% url 'admin:<API key>' task.jurisdiction.pk %}">{{task.jurisdiction}}</a></dd>
{% endif %}
</dl>
<form method="POST" action="{{ endpoint }}" class="collapsable flag-reply">
<header>
<p>↵ Reply to {{task.user.profile.full_name}} <<a href="mailto:{{task.user.email}}">{{task.user.email}}</a>></p>
</header>
{% csrf_token %}
<input type="hidden" name="task" value="{{task.pk}}">
{{ flag_form.text }}
<footer class="submission-control">
<button type="submit" name="reply" value="true" class="primary button">Reply</button>
<div class="checkbox-field">
<input type="checkbox" name="resolve" id="resolve-with-reply" checked>
<label for="resolve-with-reply">Resolve after sending</label>
</div>
</footer>
</form>
{% endblock %} |
require 'spec_helper'
require 'rollbar/middleware/sinatra'
require 'sinatra/base'
require 'rack/test'
class SinatraDummy < Sinatra::Base
class DummyError < StandardError; end
use Rollbar::Middleware::Sinatra
get '/foo' do
raise DummyError.new
end
get '/bar' do
'this will not crash'
end
post '/crash_post' do
raise DummyError.new
end
end
describe Rollbar::Middleware::Sinatra, :<API key> => true do
include Rack::Test::Methods
def app
SinatraDummy
end
let(:logger_mock) { double('logger').as_null_object }
before do
Rollbar.configure do |config|
config.logger = logger_mock
config.framework = 'Sinatra'
end
end
let(:uncaught_level) do
Rollbar.configuration.<API key>
end
let(:<API key>) do
[uncaught_level, exception, { :<API key> => true }]
end
describe '#call' do
context 'for a crashing endpoint' do
# this is the default for test mode in Sinatra
context 'with raise_errors? == true' do
let(:exception) { kind_of(SinatraDummy::DummyError) }
before do
allow(app.settings).to receive(:raise_errors?).and_return(true)
end
it 'reports the error to Rollbar API and raises error' do
expect(Rollbar).to receive(:log).with(*<API key>)
expect do
get '/foo'
end.to raise_error(SinatraDummy::DummyError)
end
end
context 'with raise_errors? == false' do
let(:exception) { kind_of(SinatraDummy::DummyError) }
before do
allow(app.settings).to receive(:raise_errors?).and_return(false)
end
it 'reports the error to Rollbar, but nothing is raised' do
expect(Rollbar).to receive(:log).with(*<API key>)
get '/foo'
end
end
end
context 'for a NOT crashing endpoint' do
it 'doesnt report any error to Rollbar API' do
expect(Rollbar).not_to receive(:log)
get '/bar'
end
end
context 'if the middleware itself fails' do
let(:exception) { Exception.new }
before do
<API key>(described_class).to receive(:framework_error).and_raise(exception)
allow(app.settings).to receive(:raise_errors?).and_return(false)
end
it 'reports the report error' do
expect(Rollbar).to receive(:log).with(*<API key>)
expect do
get '/foo'
end.to raise_error(exception)
end
end
context 'with GET parameters' do
let(:exception) { kind_of(SinatraDummy::DummyError) }
let(:params) do
{
'key' => 'value'
}
end
it 'appear in the sent payload' do
expect do
get '/foo', params
end.to raise_error(exception)
expect(Rollbar.last_report[:request][:GET]).to be_eql(params)
end
end
context 'with POST parameters' do
let(:exception) { kind_of(SinatraDummy::DummyError) }
let(:params) do
{
'key' => 'value'
}
end
it 'appear in the sent payload' do
expect do
post '/crash_post', params
end.to raise_error(exception)
expect(Rollbar.last_report[:request][:POST]).to be_eql(params)
end
end
context 'with JSON POST parameters' do
let(:exception) { kind_of(SinatraDummy::DummyError) }
let(:params) do
{
'key' => 'value'
}
end
it 'appears in the sent payload when application/json is the content type' do
expect do
post '/crash_post', params.to_json, { 'CONTENT_TYPE' => 'application/json' }
end.to raise_error(exception)
expect(Rollbar.last_report[:request][:body]).to be_eql(params.to_json)
end
it 'appears in the sent payload when the accepts header contains json' do
expect do
post '/crash_post', params, { 'ACCEPT' => 'application/vnd.github.v3+json' }
end.to raise_error(exception)
expect(Rollbar.last_report[:request][:POST]).to be_eql(params)
end
end
it 'resets the notifier scope in every request' do
get '/bar'
id1 = Rollbar.scope_object.object_id
get '/bar'
id2 = Rollbar.scope_object.object_id
expect(id1).not_to be_eql(id2)
end
context 'with person data' do
let(:exception) { kind_of(SinatraDummy::DummyError) }
let(:person_data) do
{ 'email' => 'person@example.com' }
end
it 'includes person data from env' do
expect do
get '/foo', {}, 'rollbar.person_data' => person_data
end.to raise_error(exception)
expect(Rollbar.last_report[:person]).to be_eql(person_data)
end
it 'includes empty person data when not in env' do
expect do
get '/foo'
end.to raise_error(exception)
expect(Rollbar.last_report[:person]).to be_eql({})
end
end
end
end |
package org.asqatasun.rules.rgaa30;
import org.asqatasun.ruleimplementation.<API key>;
public class Rgaa30Rule011001 extends <API key> {
/**
* Default constructor
*/
public Rgaa30Rule011001 () {
super();
}
} |
'use strict';
var phonetic = require('phonetic');
var socketio = require('socket.io');
var _ = require('underscore');
var load = function(http) {
var io = socketio(http);
var ioNamespace = '/';
var getEmptyRoomId = function() {
var roomId = null;
do {
roomId = phonetic.generate().toLowerCase()
} while (io.nsps[ioNamespace].adapter.rooms[roomId]);
return roomId;
};
var sendRoomInfo = function(socket, info) {
if (!info.roomId) {
return;
}
var clients = io.nsps[ioNamespace].adapter.rooms[info.roomId];
io.sockets.in(info.roomId).emit('room.info', {
id: info.roomId,
count: clients ? Object.keys(clients).length : 0
});
};
var onJoin = function(socket, info, data) {
if (info.roomId) {
return;
}
info.roomId = data && data.roomId ? data.roomId : null;
if (!info.roomId || !io.nsps[ioNamespace].adapter.rooms[data.roomId]) {
info.roomId = getEmptyRoomId(socket);
console.log('[Socket] Assigning room id ' + info.roomId + ' to ip ' + socket.handshake.address);
} else {
console.log('[Socket] Assigning room id ' + info.roomId + ' to ip ' + socket.handshake.address + ' (from client)');
}
socket.join(info.roomId);
socket.emit('join', {
roomId: info.roomId
});
sendRoomInfo(socket, info);
};
var onEvent = function(socket, info, event, data) {
if (!info.roomId) {
return;
}
socket.broadcast.to(info.roomId).emit(event, data);
};
var onChunk = function(socket, info, data) {
socket.emit('file.ack', {
guid: data.guid
});
onEvent(socket, info, 'file.chunk', data);
};
var onConnection = function(socket) {
console.log('[Socket] New connection from ip ' + socket.handshake.address);
var info = {
roomId: null
};
socket.on('disconnect', function() {
console.log('[Socket] Connection from ip ' + socket.handshake.address + ' disconnected');
sendRoomInfo(socket, info);
});
socket.on('join', _.partial(onJoin, socket, info));
socket.on('file.start', _.partial(onEvent, socket, info, 'file.start'));
socket.on('file.chunk', _.partial(onChunk, socket, info));
}
io.on('connection', onConnection);
};
module.exports = {
load: load
}; |
#pragma once
class cosmos;
#include "game/transcendental/step_declaration.h"
class <API key> {
public:
void update_transforms(const logic_step step);
}; |
# Does it have wifi?
## Development
Requires **Node 0.12+**.
Install:
bash
$ npm install -g gulp
$ npm install
Run server with auto-reload (without minification):
bash
$ gulp
To force minification of assets (build takes a bit longer) include the `--minified` flag:
bash
$ gulp --minified
## Production deployment
SSH as root into the production server:
$ ssh root@45.55.241.79
$ cd /opt/doesithavewifi
$ git pull
$ npm run build
## Credits
* [Ramesh Nair](https://github.com/hiddentao)
* [Jeff Lau](https://github.com/jefflau)
* [Leon Talbert](https://github.com/LeonmanRolls)
AGPLv3 - see LICENSE.txt |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
</head>
<body bgcolor="white">
Provides test classes.
</body>
</html> |
ALTER TABLE `album` CHANGE fichier fichier varchar(250); |
package org.plukh.fluffymeow.aws;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.DescribeTagsRequest;
import com.amazonaws.services.ec2.model.DescribeTagsResult;
import com.amazonaws.services.ec2.model.Filter;
import com.amazonaws.services.ec2.model.TagDescription;
import org.apache.http.client.fluent.Request;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
public class <API key> implements <API key> {
private static final Logger log = LogManager.getLogger(<API key>.class);
private static final String NAME_TAG = "Name";
private static final String DEPLOYMENT_ID_TAG = "deploymentId";
private InstanceInfo instanceInfo;
public <API key>() {
}
@Override
public InstanceInfo getInstanceInfo() {
if (instanceInfo == null) {
try {
AmazonEC2 ec2 = new AmazonEC2Client();
String instanceId = Request.Get("http://169.254.169.254/latest/meta-data/instance-id").execute().returnContent().asString();
if (log.isDebugEnabled()) log.debug("Instance Id: " + instanceId);
DescribeTagsRequest tagsRequest = new DescribeTagsRequest().withFilters(
new Filter().withName("resource-id").withValues(instanceId),
new Filter().withName("key").withValues(NAME_TAG, DEPLOYMENT_ID_TAG));
DescribeTagsResult tagsResult = ec2.describeTags(tagsRequest);
String name = getTag(tagsResult, NAME_TAG);
if (log.isDebugEnabled()) log.debug("Instance name: " + name);
String deploymentId = getTag(tagsResult, DEPLOYMENT_ID_TAG);
if (log.isDebugEnabled()) log.debug("Deployment: " + deploymentId);
instanceInfo = new InstanceInfo()
.withInstanceId(instanceId)
.withName(name)
.withDeploymentId(deploymentId);
} catch (IOException e) {
throw new <API key>("Error retrieving AWS instance info", e);
}
}
return instanceInfo;
}
private String getTag(DescribeTagsResult tagsResult, String tagName) {
for (TagDescription tag : tagsResult.getTags()) {
if (tag.getKey().equals(tagName)) return tag.getValue();
}
return null;
}
} |
require_relative 'api_fixtures_helper'
class FakeApiResponse
include ApiFixturesHelper
def app_init
parse(app_init_plist)
end
def all_cinemas
parse(all_cinemas_plist)
end
def film_times(cinema_id, film_id)
parse(film_times_plist(cinema_id, film_id))
end
end |
# ETConf -- web-based user-friendly computer hardware configurator
# Sergey Matveev <sergey.matveev@etegro.com>
# This program is free software: you can redistribute it and/or modify
# published by the Free Software Foundation, either version 3 of the
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
from django.conf.urls.defaults import *
urlpatterns = patterns( "configurator.giver.views",
( r"^perform/(?P<computermodel_alias>.+)/$", "perform" ),
( r"^configurator/(?P<computermodel_alias>.+)/$", "configurator" ),
( r"^computermodel/request/(?P<computermodel_alias>.+)$", "<API key>" ),
) |
#include <metaverse/bitcoin/message/alert.hpp>
#include <boost/iostreams/stream.hpp>
#include <metaverse/bitcoin/message/version.hpp>
#include <metaverse/bitcoin/utility/assert.hpp>
#include <metaverse/bitcoin/utility/container_sink.hpp>
#include <metaverse/bitcoin/utility/container_source.hpp>
#include <metaverse/bitcoin/utility/istream_reader.hpp>
#include <metaverse/bitcoin/utility/ostream_writer.hpp>
namespace libbitcoin {
namespace message {
const std::string alert::command = "alert";
const uint32_t alert::version_minimum = version::level::minimum;
const uint32_t alert::version_maximum = version::level::maximum;
alert alert::factory_from_data(uint32_t version, const data_chunk& data)
{
alert instance;
instance.from_data(version, data);
return instance;
}
alert alert::factory_from_data(uint32_t version, std::istream& stream)
{
alert instance;
instance.from_data(version, stream);
return instance;
}
alert alert::factory_from_data(uint32_t version, reader& source)
{
alert instance;
instance.from_data(version, source);
return instance;
}
bool alert::is_valid() const
{
return !payload.empty() || !signature.empty();
}
void alert::reset()
{
payload.clear();
payload.shrink_to_fit();
signature.clear();
signature.shrink_to_fit();
}
bool alert::from_data(uint32_t version, const data_chunk& data)
{
boost::iostreams::stream<byte_source<data_chunk>> istream(data);
return from_data(version, istream);
}
bool alert::from_data(uint32_t version, std::istream& stream)
{
istream_reader source(stream);
return from_data(version, source);
}
bool alert::from_data(uint32_t version, reader& source)
{
reset();
auto size = source.<API key>();
BITCOIN_ASSERT(size <= bc::max_size_t);
const auto payload_size = static_cast<size_t>(size);
size_t signature_size = 0;
auto result = static_cast<bool>(source);
if (result)
{
payload = source.read_data(payload_size);
result = source && (payload.size() == payload_size);
}
if (result)
{
size = source.<API key>();
BITCOIN_ASSERT(size <= bc::max_size_t);
signature_size = static_cast<size_t>(size);
result = source;
}
if (result)
{
signature = source.read_data(signature_size);
result = source && (signature.size() == signature_size);
}
if (!result)
reset();
return result;
}
data_chunk alert::to_data(uint32_t version) const
{
data_chunk data;
boost::iostreams::stream<byte_sink<data_chunk>> ostream(data);
to_data(version, ostream);
ostream.flush();
BITCOIN_ASSERT(data.size() == serialized_size(version));
return data;
}
void alert::to_data(uint32_t version, std::ostream& stream) const
{
ostream_writer sink(stream);
to_data(version, sink);
}
void alert::to_data(uint32_t version, writer& sink) const
{
sink.<API key>(payload.size());
sink.write_data(payload);
sink.<API key>(signature.size());
sink.write_data(signature);
}
uint64_t alert::serialized_size(uint32_t version) const
{
return variable_uint_size(payload.size()) + payload.size() +
variable_uint_size(signature.size()) + signature.size();
}
bool operator==(const alert& left, const alert& right)
{
bool result = (left.payload.size() == right.payload.size()) &&
(left.signature.size() == right.signature.size());
for (size_t i = 0; i < left.payload.size() && result; i++)
result = (left.payload[i] == right.payload[i]);
for (size_t i = 0; i < left.signature.size() && result; i++)
result = (left.signature[i] == right.signature[i]);
return result;
}
bool operator!=(const alert& left, const alert& right)
{
return !(left == right);
}
} // end message
} // end libbitcoin |
module BABYLON {
export class Animation {
private _keys: Array<any>;
private _offsetsCache = {};
private _highLimitsCache = {};
private _stopped = false;
public _target;
private _easingFunction: IEasingFunction;
public targetPropertyPath: string[];
public currentFrame: number;
public static <API key>(name: string, mesh: AbstractMesh, tartgetProperty: string,
framePerSecond: number, totalFrame: number,
from: any, to: any, loopMode?: number) {
var dataType = undefined;
if (!isNaN(parseFloat(from)) && isFinite(from)) {
dataType = Animation.ANIMATIONTYPE_FLOAT;
} else if (from instanceof Quaternion) {
dataType = Animation.<API key>;
} else if (from instanceof Vector3) {
dataType = Animation.<API key>;
} else if (from instanceof Vector2) {
dataType = Animation.<API key>;
} else if (from instanceof Color3) {
dataType = Animation.<API key>;
}
if (dataType == undefined) {
return null;
}
var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
var keys = [];
keys.push({ frame: 0, value: from });
keys.push({ frame: totalFrame, value: to });
animation.setKeys(keys);
mesh.animations.push(animation);
return mesh.getScene().beginAnimation(mesh, 0, totalFrame,(animation.loopMode === 1));
}
constructor(public name: string, public targetProperty: string, public framePerSecond: number, public dataType: number, public loopMode?: number) {
this.targetPropertyPath = targetProperty.split(".");
this.dataType = dataType;
this.loopMode = loopMode === undefined ? Animation.<API key> : loopMode;
}
// Methods
public isStopped(): boolean {
return this._stopped;
}
public getKeys(): any[] {
return this._keys;
}
public getEasingFunction() {
return this._easingFunction;
}
public setEasingFunction(easingFunction: EasingFunction) {
this._easingFunction = easingFunction;
}
public <API key>(startValue: number, endValue: number, gradient: number): number {
return startValue + (endValue - startValue) * gradient;
}
public <API key>(startValue: Quaternion, endValue: Quaternion, gradient: number): Quaternion {
return Quaternion.Slerp(startValue, endValue, gradient);
}
public <API key>(startValue: Vector3, endValue: Vector3, gradient: number): Vector3 {
return Vector3.Lerp(startValue, endValue, gradient);
}
public <API key>(startValue: Vector2, endValue: Vector2, gradient: number): Vector2 {
return Vector2.Lerp(startValue, endValue, gradient);
}
public <API key>(startValue: Color3, endValue: Color3, gradient: number): Color3 {
return Color3.Lerp(startValue, endValue, gradient);
}
public <API key>(startValue: Matrix, endValue: Matrix, gradient: number): Matrix {
var startScale = new Vector3(0, 0, 0);
var startRotation = new Quaternion();
var startTranslation = new Vector3(0, 0, 0);
startValue.decompose(startScale, startRotation, startTranslation);
var endScale = new Vector3(0, 0, 0);
var endRotation = new Quaternion();
var endTranslation = new Vector3(0, 0, 0);
endValue.decompose(endScale, endRotation, endTranslation);
var resultScale = this.<API key>(startScale, endScale, gradient);
var resultRotation = this.<API key>(startRotation, endRotation, gradient);
var resultTranslation = this.<API key>(startTranslation, endTranslation, gradient);
var result = Matrix.Compose(resultScale, resultRotation, resultTranslation);
return result;
}
public clone(): Animation {
var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
clone.setKeys(this._keys);
return clone;
}
public setKeys(values: Array<any>): void {
this._keys = values.slice(0);
this._offsetsCache = {};
this._highLimitsCache = {};
}
private _getKeyValue(value: any): any {
if (typeof value === "function") {
return value();
}
return value;
}
private _interpolate(currentFrame: number, repeatCount: number, loopMode: number, offsetValue?, highLimitValue?) {
if (loopMode === Animation.<API key> && repeatCount > 0) {
return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
}
this.currentFrame = currentFrame;
// Try to get a hash to find the right key
var startKey = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
if (this._keys[startKey].frame >= currentFrame) {
while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
startKey
}
}
for (var key = startKey; key < this._keys.length ; key++) {
if (this._keys[key + 1].frame >= currentFrame) {
var startValue = this._getKeyValue(this._keys[key].value);
var endValue = this._getKeyValue(this._keys[key + 1].value);
// gradient : percent of currentFrame between the frame inf and the frame sup
var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
// check for easingFunction and correction of gradient
if (this._easingFunction != null) {
gradient = this._easingFunction.ease(gradient);
}
switch (this.dataType) {
// Float
case Animation.ANIMATIONTYPE_FLOAT:
switch (loopMode) {
case Animation.<API key>:
case Animation.<API key>:
return this.<API key>(startValue, endValue, gradient);
case Animation.<API key>:
return offsetValue * repeatCount + this.<API key>(startValue, endValue, gradient);
}
break;
// Quaternion
case Animation.<API key>:
var quaternion = null;
switch (loopMode) {
case Animation.<API key>:
case Animation.<API key>:
quaternion = this.<API key>(startValue, endValue, gradient);
break;
case Animation.<API key>:
quaternion = this.<API key>(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
break;
}
return quaternion;
// Vector3
case Animation.<API key>:
switch (loopMode) {
case Animation.<API key>:
case Animation.<API key>:
return this.<API key>(startValue, endValue, gradient);
case Animation.<API key>:
return this.<API key>(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
}
// Vector2
case Animation.<API key>:
switch (loopMode) {
case Animation.<API key>:
case Animation.<API key>:
return this.<API key>(startValue, endValue, gradient);
case Animation.<API key>:
return this.<API key>(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
}
// Color3
case Animation.<API key>:
switch (loopMode) {
case Animation.<API key>:
case Animation.<API key>:
return this.<API key>(startValue, endValue, gradient);
case Animation.<API key>:
return this.<API key>(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
}
// Matrix
case Animation.<API key>:
switch (loopMode) {
case Animation.<API key>:
case Animation.<API key>:
// return this.<API key>(startValue, endValue, gradient);
case Animation.<API key>:
return startValue;
}
default:
break;
}
break;
}
}
return this._getKeyValue(this._keys[this._keys.length - 1].value);
}
public animate(delay: number, from: number, to: number, loop: boolean, speedRatio: number): boolean {
if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
this._stopped = true;
return false;
}
var returnValue = true;
// Adding a start key at frame 0 if missing
if (this._keys[0].frame !== 0) {
var newKey = { frame: 0, value: this._keys[0].value };
this._keys.splice(0, 0, newKey);
}
// Check limits
if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
from = this._keys[0].frame;
}
if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
to = this._keys[this._keys.length - 1].frame;
}
// Compute ratio
var range = to - from;
var offsetValue;
// ratio represents the frame delta between from and to
var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
var highLimitValue = 0;
if (ratio > range && !loop) { // If we are out of range and not looping get back to caller
returnValue = false;
highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
} else {
// Get max value if required
if (this.loopMode !== Animation.<API key>) {
var keyOffset = to.toString() + from.toString();
if (!this._offsetsCache[keyOffset]) {
var fromValue = this._interpolate(from, 0, Animation.<API key>);
var toValue = this._interpolate(to, 0, Animation.<API key>);
switch (this.dataType) {
// Float
case Animation.ANIMATIONTYPE_FLOAT:
this._offsetsCache[keyOffset] = toValue - fromValue;
break;
// Quaternion
case Animation.<API key>:
this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
break;
// Vector3
case Animation.<API key>:
this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
// Vector2
case Animation.<API key>:
this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
// Color3
case Animation.<API key>:
this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
default:
break;
}
this._highLimitsCache[keyOffset] = toValue;
}
highLimitValue = this._highLimitsCache[keyOffset];
offsetValue = this._offsetsCache[keyOffset];
}
}
if (offsetValue === undefined) {
switch (this.dataType) {
// Float
case Animation.ANIMATIONTYPE_FLOAT:
offsetValue = 0;
break;
// Quaternion
case Animation.<API key>:
offsetValue = new Quaternion(0, 0, 0, 0);
break;
// Vector3
case Animation.<API key>:
offsetValue = Vector3.Zero();
break;
// Vector2
case Animation.<API key>:
offsetValue = Vector2.Zero();
break;
// Color3
case Animation.<API key>:
offsetValue = Color3.Black();
}
}
// Compute value
var repeatCount = (ratio / range) >> 0;
var currentFrame = returnValue ? from + ratio % range : to;
var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
// Set value
if (this.targetPropertyPath.length > 1) {
var property = this._target[this.targetPropertyPath[0]];
for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
property = property[this.targetPropertyPath[index]];
}
property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
} else {
this._target[this.targetPropertyPath[0]] = currentValue;
}
if (this._target.markAsDirty) {
this._target.markAsDirty(this.targetProperty);
}
if (!returnValue) {
this._stopped = true;
}
return returnValue;
}
// Statics
private static <API key> = 0;
private static <API key> = 1;
private static <API key> = 2;
private static <API key> = 3;
private static <API key> = 4;
private static <API key> = 5;
private static <API key> = 0;
private static <API key> = 1;
private static <API key> = 2;
public static get ANIMATIONTYPE_FLOAT(): number {
return Animation.<API key>;
}
public static get <API key>(): number {
return Animation.<API key>;
}
public static get <API key>(): number {
return Animation.<API key>;
}
public static get <API key>(): number {
return Animation.<API key>;
}
public static get <API key>(): number {
return Animation.<API key>;
}
public static get <API key>(): number {
return Animation.<API key>;
}
public static get <API key>(): number {
return Animation.<API key>;
}
public static get <API key>(): number {
return Animation.<API key>;
}
public static get <API key>(): number {
return Animation.<API key>;
}
}
} |
//{block name="backend/<API key>/view/toolbar"}
Ext.define('Shopware.apps.SwagBackendOrder.view.main.Toolbar', {
extend: 'Ext.toolbar.Toolbar',
alternateClassName: 'SwagBackendOrder.view.main.Toolbar',
alias: 'widget.<API key>',
dock: 'top',
ui: 'shopware-ui',
padding: '0 10 0 10',
snippets: {
buttons: {
openCustomer: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/button/open_customer"}Open Customer{/s}',
createCustomer: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/button/create_customer"}Create Customer{/s}',
createGuest: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/button/create_guest"}Create Guest{/s}'
},
shop: {
noCustomer: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/shop/label/no_costumer"}Shop: No customer selected.{/s}',
default: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/shop/label/default"}Shop: {/s}'
},
currencyLabel: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/currency/label"}Choose currency{/s}',
languageLabel: '{s namespace="backend/swag_backend_order/view/toolbar" name="swag_backend_order/toolbar/language/label"}Language{/s}'
},
initComponent: function () {
var me = this;
me.items = me.createToolbarItems();
me.languageStore = Ext.create('Ext.data.Store', {
name: 'languageStore',
fields: ['id', 'mainId', 'categoryId', 'name', 'title', 'default']
});
/**
* automatically selects the standard currency
*/
me.currencyStore = me.subApplication.getStore('Currency');
me.currencyStore.on('load', function () {
me.<API key>.bindStore(me.currencyStore);
var standardCurrency = me.currencyStore.findExact('default', 1);
if (standardCurrency > -1) {
me.currencyModel = me.currencyStore.getAt(standardCurrency);
me.<API key>.select(me.currencyModel);
me.currencyModel.set('selected', 1);
} else {
me.<API key>.select(me.currencyStore.first());
me.currencyStore.first().set('selected', 1);
}
});
me.customerSearchField.on('valueselect', function () {
me.openCustomerButton.setDisabled(false);
});
//selects and loads the language sub shops
var customerStore = me.subApplication.getStore('Customer');
customerStore.on('load', function () {
if (typeof customerStore.getAt(0) !== 'undefined') {
var shopName = '',
customerModel = customerStore.getAt(0);
var languageId = customerModel.get('languageId');
var index = customerModel.languageSubShop().findExact('id', languageId);
if (index >= 0) {
shopName = customerModel.languageSubShop().getAt(index).get('name');
} else {
index = customerModel.shop().findExact('id', languageId);
shopName = customerModel.shop().getAt(index).get('name');
}
me.shopLabel.setText(me.snippets.shop.default + shopName);
me.fireEvent('changeCustomer');
me.getLanguageShops(customerModel.shop().getAt(0).get('id'), customerStore.getAt(0).get('languageId'));
}
});
me.callParent(arguments);
},
/**
* register the events
*/
registerEvents: function () {
this.addEvents(
'changeSearchField'
)
},
/**
* creates the top toolbar items
*
* @returns []
*/
createToolbarItems: function () {
var me = this;
me.customerSearchField = me.<API key>('customerName', 'id', 'email');
me.<API key> = Ext.create('Ext.button.Button', {
text: me.snippets.buttons.createCustomer,
handler: function () {
me.fireEvent('createCustomer', false);
}
});
me.createGuestButton = Ext.create('Ext.button.Button', {
text: me.snippets.buttons.createGuest,
handler: function () {
me.fireEvent('createCustomer', true);
}
});
me.openCustomerButton = Ext.create('Ext.button.Button', {
text: me.snippets.buttons.openCustomer,
disabled: true,
margin: '0 30 0 0',
handler: function () {
me.fireEvent('openCustomer');
}
});
me.shopLabel = Ext.create('Ext.form.Label', {
text: me.snippets.shop.noCustomer,
style: {
fontWeight: 'bold'
}
});
me.languageComboBox = Ext.create('Ext.form.field.ComboBox', {
fieldLabel: me.snippets.languageLabel,
labelWidth: 65,
store: me.languageStore,
queryMode: 'local',
displayField: 'name',
width: '20%',
valueField: 'id',
listeners: {
change: {
fn: function (comboBox, newValue, oldValue, eOpts) {
me.fireEvent('changeLanguage', newValue);
}
}
}
});
me.<API key> = Ext.create('Ext.form.field.ComboBox', {
fieldLabel: me.snippets.currencyLabel,
stores: me.currencyStore,
queryMode: 'local',
displayField: 'currency',
width: '20%',
valueField: 'id',
listeners: {
change: {
fn: function (comboBox, newValue, oldValue, eOpts) {
me.fireEvent('changeCurrency', comboBox, newValue, oldValue, eOpts);
}
}
}
});
return [
me.<API key>, me.languageComboBox, me.shopLabel, '->',
me.<API key>, me.createGuestButton, me.openCustomerButton, me.customerSearchField
];
},
/**
*
* @param returnValue
* @param hiddenReturnValue
* @param name
* @return Shopware.form.field.ArticleSearch
*/
<API key>: function (returnValue, hiddenReturnValue, name) {
var me = this;
me.customerStore = me.subApplication.getStore('Customer');
return Ext.create('Shopware.apps.SwagBackendOrder.view.main.CustomerSearch', {
name: name,
subApplication: me.subApplication,
returnValue: returnValue,
hiddenReturnValue: hiddenReturnValue,
articleStore: me.customerStore,
allowBlank: false,
getValue: function () {
me.store.getAt(me.record.rowIdx).set(name, this.getSearchField().getValue());
return this.getSearchField().getValue();
},
setValue: function (value) {
this.getSearchField().setValue(value);
}
});
},
/**
* @param mainShopId
* @param languageId
*/
getLanguageShops: function (mainShopId, languageId) {
var me = this;
Ext.Ajax.request({
url: '{url action="getLanguageSubShops"}',
params: {
mainShopId: mainShopId
},
success: function (response) {
me.languageStore.removeAll();
var languageSubShops = Ext.JSON.decode(response.responseText);
languageSubShops.data.forEach(function (record) {
me.languageStore.add(record);
});
me.languageComboBox.bindStore(me.languageStore);
//selects the default language shop
var languageIndex = me.languageStore.findExact('mainId', null);
me.languageComboBox.setValue(languageId);
}
});
}
});
//{/block} |
package com.esofthead.mycollab.module.crm.service.ibatis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.esofthead.mycollab.common.interceptor.aspect.Auditable;
import com.esofthead.mycollab.common.interceptor.aspect.Traceable;
import com.esofthead.mycollab.core.persistence.ICrudGenericDAO;
import com.esofthead.mycollab.core.persistence.ISearchableDAO;
import com.esofthead.mycollab.core.persistence.service.DefaultService;
import com.esofthead.mycollab.module.crm.dao.ProductMapper;
import com.esofthead.mycollab.module.crm.dao.ProductMapperExt;
import com.esofthead.mycollab.module.crm.domain.Product;
import com.esofthead.mycollab.module.crm.domain.criteria.<API key>;
import com.esofthead.mycollab.module.crm.service.ProductService;
@Service
@Transactional
public class ProductServiceImpl extends DefaultService<Integer, Product, <API key>>
implements ProductService {
@Autowired
private ProductMapper productMapper;
@Autowired
private ProductMapperExt productMapperExt;
@Override
public ICrudGenericDAO<Integer, Product> getCrudMapper() {
return productMapper;
}
@Override
public ISearchableDAO<<API key>> getSearchMapper() {
return productMapperExt;
}
} |
package org.jhears.server;
import java.util.Map;
public interface IUser {
String getName();
Long getId();
Map<String, String> getProperties();
} |
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
//Vardef Handler Object
class VarDefHandler {
var $meta_array_name;
var $target_meta_array = false;
var $start_none = false;
var $extra_array = array(); //used to add custom items
var $options_array = array();
var $module_object;
var $start_none_lbl = null;
function VarDefHandler(& $module, $meta_array_name=null){
$this->module_object = $module;
if($meta_array_name!=null){
global $vardef_meta_array;
include("include/VarDefHandler/vardef_meta_arrays.php");
$this->target_meta_array = $vardef_meta_array[$meta_array_name];
}
//end function setup
}
function get_vardef_array($use_singular=false, $remove_dups = false, $use_field_name = false, $use_field_label = false){
global $dictionary;
global $current_language;
global $app_strings;
global $app_list_strings;
$temp_module_strings = <API key>($current_language, $this->module_object->module_dir);
$base_array = $this->module_object->field_defs;
//$base_array = $dictionary[$this->module_object->object_name]['fields'];
Inclue empty none set or not
if($this->start_none==true){
if(!empty($this->start_none_lbl)){
$this->options_array[''] = $this->start_none_lbl;
} else {
$this->options_array[''] = $app_strings['LBL_NONE'];
}
}
used for special one off items added to filter array ex. would be href link for alert templates
if(!empty($this->extra_array)){
foreach($this->extra_array as $key => $value){
$this->options_array[$key] = $value;
}
}
//////end special one off//////////////////////////////////
foreach($base_array as $key => $value_array){
$compare_results = $this->compare_type($value_array);
if($compare_results == true){
$label_name = '';
if($value_array['type'] == 'link' && !$use_field_label){
$this->module_object->load_relationship($value_array['name']);
if(!empty($app_list_strings['moduleList'][$this->module_object->$value_array['name']-><API key>()])){
$label_name = $app_list_strings['moduleList'][$this->module_object->$value_array['name']-><API key>()];
}else{
$label_name = $this->module_object->$value_array['name']-><API key>();
}
}
else if(!empty($value_array['vname'])){
$label_name = $value_array['vname'];
} else {
$label_name = $value_array['name'];
}
$label_name = get_label($label_name, $temp_module_strings);
if(!empty($value_array['table'])){
//Custom Field
$column_table = $value_array['table'];
} else {
//Non-Custom Field
$column_table = $this->module_object->table_name;
}
if($value_array['type'] == 'link'){
if($use_field_name){
$index = $value_array['name'];
}else{
$index = $this->module_object->$key-><API key>();
}
}else{
$index = $key;
}
$value = trim($label_name, ':');
if($remove_dups){
if(!in_array($value, $this->options_array))
$this->options_array[$index] = $value;
}
else
$this->options_array[$index] = $value;
//end if field is included
}
//end foreach
}
if($use_singular == true){
return <API key>($this->options_array);
} else {
return $this->options_array;
}
//end get_vardef_array
}
function compare_type($value_array){
//Filter nothing?
if(!is_array($this->target_meta_array)){
return true;
}
/////Use the $target_meta_array;
if(isset($this->target_meta_array['inc_override'])){
foreach($this->target_meta_array['inc_override'] as $attribute => $value){
foreach($value as $actual_value){
if(isset($value_array[$attribute]) && $value_array[$attribute] == $actual_value) return true;
}
if(isset($value_array[$attribute]) && $value_array[$attribute] == $value) return true;
}
}
if(isset($this->target_meta_array['ex_override'])){
foreach($this->target_meta_array['ex_override'] as $attribute => $value){
foreach($value as $actual_value){
if(isset($value_array[$attribute]) && $value_array[$attribute] == $actual_value) return false;
if(isset($value_array[$attribute]) && $value_array[$attribute] == $value) return false;
}
//end foreach inclusion array
}
}
if(isset($this->target_meta_array['inclusion'])){
foreach($this->target_meta_array['inclusion'] as $attribute => $value){
if($attribute=="type"){
foreach($value as $actual_value){
if(isset($value_array[$attribute]) && $value_array[$attribute] != $actual_value) return false;
}
} else {
if(isset($value_array[$attribute]) && $value_array[$attribute] != $value) return false;
}
//end foreach inclusion array
}
}
if(isset($this->target_meta_array['exclusion'])){
foreach($this->target_meta_array['exclusion'] as $attribute => $value){
foreach($value as $actual_value){
if ( $attribute == 'reportable' ) {
if ( $actual_value == 'true' ) $actual_value = 1;
if ( $actual_value == 'false' ) $actual_value = 0;
}
if(isset($value_array[$attribute]) && $value_array[$attribute] == $actual_value) return false;
}
//end foreach inclusion array
}
}
return true;
//end function compare_type
}
//end class VarDefHandler
}
?> |
## Device Admin user stories
# Install app on device
# Register app with right instance
# Sign in to app
# Create, update, delete enumerator users on the app
# Clean data from the app
# Check daily work of enumerators
# Manual backup of data
# Manual upload of data |
<!DOCTYPE HTML PUBLIC "-
<html><head>
<meta http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="estilos.css" />
<title> Indice de Ley Orgánica de Educación Enmarcada en los Derechos Humanos, como contribució en EDUCERE</title>
</head><body>
<div id="container">
<div id="pageHeader">
</div>
<div id="pageContehome">
<center><big><a href="../index.html">Indices EDUCERE</a><br></big></center>
<entry>
<number>
811<br> </number>
<results>
<titulo>
Ley Orgánica de Educación Enmarcada en los Derechos Humanos<br> </titulo>
<subtitulo>
-- <br> </subtitulo>
<autores>
[[Trejo Urquiola, Walter]]<br> </autores>
<titulo>
<a href="http:
2001-07-01<br> </creado>
</titulo>
<results>
<div></div>
<h2 align="center">La frase: Ley Orgánica de Educación Enmarcada en los Derechos Humanos</h2>
<h3 align="center">Produjo 7 resultados</h3>
<table align="center" border="1" width="100%">
<tr><th>Relevancia</th><th>Archivo (URL implicito)</th><th>Tamao (en Bytes)</th></tr>
<tr><td>1000</td><td><a href=".%2fpdfs%2fv12n41%2farticulo14.pdf">articulo14.pdf</a></td><td><em>2380231</em></td></tr>
<tr><td>930</td><td><a href=".%2fpdfs%2fv5n14%2farticulo11.pdf">articulo11.pdf</a></td><td><em>77241</em></td></tr>
<tr><td>848</td><td><a href=".%2fpdfs%2fv11n36%2farticulo17.pdf">articulo17.pdf</a></td><td><em>875718</em></td></tr>
<tr><td>822</td><td><a href=".%2fpdfs%2fv3n8%2farticulo3-8-11.pdf">articulo3-8-11.pdf</a></td><td><em>755003</em></td></tr>
<tr><td>819</td><td><a href=".%2fpdfs%2fv6n17%2farticulo18.pdf">articulo18.pdf</a></td><td><em>363494</em></td></tr>
<tr><td>794</td><td><a href=".%2fpdfs%2fv13n45%2farticulo11.pdf">articulo11.pdf</a></td><td><em>301176</em></td></tr>
<tr><td>768</td><td><a href=".%2fpdfs%2fv5n16%2farticulo7.pdf">articulo7.pdf</a></td><td><em>408479</em></td></tr>
</table>
</results>
</entry>
</div>
<div id="footer"><p>EDUCERE. La Revista Venezolana de Educación Escuela de Educación. <br/>
Facultad de Humanidades y Educación Universidad de Los Andes,<br/>
Mérida - Venezuela<br/>
<br/>
<br/>
</p>
</div>
</div>
</body>
</html> |
package io.github.jhg543.mellex.operation;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import io.github.jhg543.mellex.ASTHelper.*;
import io.github.jhg543.mellex.antlrparser.<API key>;
import io.github.jhg543.mellex.antlrparser.DefaultSQLLexer;
import io.github.jhg543.mellex.antlrparser.DefaultSQLParser;
import io.github.jhg543.mellex.antlrparser.DefaultSQLParser.Sql_stmtContext;
import io.github.jhg543.mellex.inputsource.<API key>;
import io.github.jhg543.mellex.inputsource.<API key>;
import io.github.jhg543.mellex.listeners.<API key>;
import io.github.jhg543.mellex.util.Misc;
import io.github.jhg543.nyallas.graphmodel.*;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.<API key>;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.<API key>;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;
public class StringEdgePrinter {
private static final Logger log = LoggerFactory.getLogger(StringEdgePrinter.class);
private static int ERR_NOSQL = 1;
private static int ERR_PARSE = 2;
private static int ERR_SEMANTIC = 3;
private static int ERR_OK = 0;
private static int printSingleFile(Path srcdir, Path dstdir, int scriptNumber, <API key> tp) {
// generate a hash to mark vt table names
String srcHash = Integer.toHexString(srcdir.hashCode());
// create destination dir
try {
Files.createDirectories(dstdir);
} catch (IOException e) {
throw new RuntimeException(e);
}
try (PrintWriter err = new PrintWriter(dstdir.resolve("log").toAbsolutePath().toString(), "utf-8")) {
// trim perl code
String sql = Misc.trimPerlScript(srcdir, StandardCharsets.UTF_8);
if (sql == null) {
err.println("Can't extract sql from file " + srcdir.toString());
return ERR_NOSQL;
}
// log actual sql statement ( for corrent line number ..)
try (PrintWriter writer = new PrintWriter(dstdir.resolve("sql").toAbsolutePath().toString(), "utf-8")) {
writer.append(sql);
}
// antlr parse
AtomicInteger errorCount = new AtomicInteger();
ANTLRInputStream in = new ANTLRInputStream(sql);
DefaultSQLLexer lexer = new DefaultSQLLexer(in);
CommonTokenStream tokens = new CommonTokenStream(lexer);
DefaultSQLParser parser = new DefaultSQLParser(tokens);
parser.<API key>();
parser.addErrorListener(new BaseErrorListener() {
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine,
String msg, <API key> e) {
err.println("line" + line + ":" + charPositionInLine + "at" + offendingSymbol + ":" + msg);
errorCount.incrementAndGet();
}
});
err.println("
ParseTree tree = null;
try {
tree = parser.parse();
if (errorCount.get() > 0) {
return ERR_PARSE;
}
} catch (Exception e) {
e.printStackTrace(err);
return ERR_PARSE;
}
err.println("
ParseTreeWalker w = new ParseTreeWalker();
try {
<API key> s = new <API key>(tp, tokens);
w.walk(s, tree);
} catch (Exception e) {
e.printStackTrace(err);
return ERR_SEMANTIC;
}
err.println("
// Remove volatile tables
<API key> graph = new <API key>();
// DAG dag = new DAG();
// <API key> ids = new
// <API key>();
Map<String, Vertex<String, Integer>> vmap = new HashMap<>();
// Output result and initialize volatile tables removal process
try (PrintWriter out = new PrintWriter(dstdir.resolve("out").toAbsolutePath().toString(), "utf-8")) {
out.println("ScriptID StmtID StmtType DestCol SrcCol ConnectionType");
String template = "%d %d %s %s.%s %s.%s %d\n";
<API key> pr = new <API key>() {
int stmtNumber = 0;
@Override
public void exitSql_stmt(Sql_stmtContext ctx) {
super.exitSql_stmt(ctx);
String stmtType = null;
SubQuery q = null;
if (ctx.insert_stmt() != null) {
stmtType = "I";
q = ctx.insert_stmt().stmt;
}
if (ctx.create_table_stmt() != null) {
if (ctx.create_table_stmt().insert != null) {
stmtType = "C";
q = ctx.create_table_stmt().insert;
}
}
if (ctx.create_view_stmt() != null) {
stmtType = "V";
q = ctx.create_view_stmt().insert;
}
if (ctx.update_stmt() != null) {
stmtType = "U";
q = ctx.update_stmt().q;
}
if (q != null) {
// what's vt's scope?
Set<String> vts = tp.getVolatileTables().keySet();
String dstTable = q.dbobj.toDotString();
boolean isDstVT = vts.contains(dstTable);
if (isDstVT) {
dstTable = "VT_" + srcHash + "_" + dstTable;
}
for (ResultColumn c : q.columns) {
for (InfSource source : c.inf.getSources()) {
ObjectName srcname = source.getSourceObject();
String srcTable = srcname.<API key>();
boolean isSrcVT = vts.contains(srcTable);
if (isSrcVT) {
srcTable = "VT_" + srcHash + "_" + srcTable;
}
out.append(String.format(template, scriptNumber, stmtNumber, stmtType, dstTable, c.name,
srcTable, srcname.toDotStringLast(), source.getConnectionType().getMarker()));
// collapse volatile table
String dst = dstTable + "." + c.name;
String src = srcTable + "." + srcname.toDotStringLast();
// Integer dstnum = ids.queryNumber(dst);
// Integer srcnum = ids.queryNumber(src);
Vertex<String, Integer> srcv;
srcv = vmap.get(src);
if (srcv == null) {
srcv = graph.addVertex(BasicVertex::new);
vmap.put(src, srcv);
srcv.setVertexData(src);
if (isSrcVT) {
srcv.setMarker(0);
}
}
Vertex<String, Integer> dstv;
dstv = vmap.get(dst);
if (dstv == null) {
dstv = graph.addVertex(BasicVertex::new);
vmap.put(dst, dstv);
dstv.setVertexData(dst);
if (isDstVT) {
dstv.setMarker(0);
}
}
Edge<String, Integer> edge = new BasicEdge<String, Integer>(srcv, dstv);
edge.setEdgeData(source.getConnectionType().getMarker());
graph.addEdge(edge);
}
}
} else {
// log.warn("query null for sm " + stmtNumber);
}
stmtNumber++;
}
};
w.walk(pr, tree);
}
// Int2ObjectMap<Node> collapsed = dag.collapse(scriptNumber);
graph.remove();
// write result (with volatile tables removed)
try (PrintWriter out = new PrintWriter(dstdir.resolve("novt").toAbsolutePath().toString(), "utf-8")) {
out.println("scriptid,dstsch,dsttbl,dstcol,srcsch,srctbl,srccol,contype");
String template = "%d,%s,%s,%s,%s,%s,%s,%d\n";
for (Vertex<String, Integer> v : graph.getVertexes()) {
for (Edge<String, Integer> e : v.getOutgoingEdges()) {
String dst = e.getTarget().getVertexData();
String src = e.getSource().getVertexData();
List<String> t1 = Splitter.on('.').splitToList(dst);
if (t1.size() == 2) {
t1 = new ArrayList<String>(t1);
t1.add(0, "3X_NOSCHEMA_" + scriptNumber);
}
List<String> t2 = Splitter.on('.').splitToList(src);
if (t2.size() == 2) {
t2 = new ArrayList<String>(t1);
t2.add(0, "3X_NOSCHEMA_" + scriptNumber);
}
out.append(String.format(template, scriptNumber, t1.get(0), t1.get(1), t1.get(2), t2.get(0), t2.get(1),
t2.get(2), e.getEdgeData()));
}
}
}
tp.clearVolatileTables();
err.println("
return 0;
} catch (<API key> | <API key> e) {
throw new RuntimeException(e);
}
}
public static int[] printStringEdge(Path srcdir, Path dstdir, Predicate<Path> filefilter, int scriptNumberStart,
boolean caseSensitive) {
// ensure directories exist
Preconditions.checkState(Files.isDirectory(srcdir));
try {
Files.createDirectories(dstdir);
} catch (IOException e1) {
throw new RuntimeException(e1);
}
// set up variables
GlobalSettings.setCaseSensitive(caseSensitive);
AtomicInteger scriptNumber = new AtomicInteger(scriptNumberStart);
<API key> tp = new <API key>(Misc::nameSym);
int[] stats = new int[10];
// open global output files
try (PrintWriter out = new PrintWriter(dstdir.resolve("stats").toAbsolutePath().toString(), "utf-8");
PrintWriter cols = new PrintWriter(dstdir.resolve("cols").toAbsolutePath().toString(), "utf-8");
PrintWriter numbers = new PrintWriter(dstdir.resolve("number").toAbsolutePath().toString(), "utf-8")) {
// for each file
Files.walk(srcdir).filter(filefilter).sorted().forEach(path -> {
int sn = scriptNumber.getAndIncrement();
numbers.println("" + sn + " " + path.toString());
String srcHash = Integer.toHexString(path.hashCode());
Path workdir = dstdir.resolve(path.getFileName()).resolve(srcHash);
// deal with single files.
int retcode = printSingleFile(path, workdir, sn, tp);
if (retcode > 0) {
out.println(String.format("%s %d %d", path.toString(), retcode, sn));
}
stats[retcode]++;
});
out.println("OK=" + stats[ERR_OK]);
out.println("NOSQL=" + stats[ERR_NOSQL]);
out.println("PARSE=" + stats[ERR_PARSE]);
out.println("SEMANTIC=" + stats[ERR_SEMANTIC]);
tp.getPermanentTables().forEach((name, stmt) -> {
stmt.columns.forEach(colname -> cols.println(name + "." + colname.name));
});
return stats;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws Exception {
Predicate<Path> filefilter = x -> Files.isRegularFile(x)
&& (x.getFileName().toString().toLowerCase().endsWith(".sql") || x.getFileName().toString().toLowerCase()
.endsWith(".pl"))
&& x.toString().toUpperCase().endsWith("BIN\\" + x.getFileName().toString().toUpperCase());
// printStringEdge(Paths.get("d:/dataflow/work1/script/mafixed"),
// Paths.get("d:/dataflow/work2/mares"), filefilter, 0, false);
printStringEdge(Paths.get("d:/dataflow/work1/debug"), Paths.get("d:/dataflow/work2/debugres"), filefilter, 0, false);
// printStringEdge(Paths.get("d:/dataflow/work1/f1/sor"),
// Paths.get("d:/dataflow/work2/result2/sor"), filefilter, 0, false);
}
} |
# Assumes there is Orchestrator like Nomad to handle process dying :P
FROM node:boron
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
# Copy source code over (including package.json)
COPY ./Code /usr/src/app
# and Yarn it
RUN yarn && chown -R node:node .
# Copy the Top Secret ENV
COPY env-example /usr/src/app/.env
USER node
CMD [ "npm", "start" ]
EXPOSE 3000 |
package com.neverwinterdp.scribengin.dataflow.example.wire;
import java.util.Properties;
import com.neverwinterdp.message.Message;
import com.neverwinterdp.scribengin.dataflow.DataSet;
import com.neverwinterdp.scribengin.dataflow.Dataflow;
import com.neverwinterdp.scribengin.dataflow.DataflowDescriptor;
import com.neverwinterdp.scribengin.dataflow.DataflowSubmitter;
import com.neverwinterdp.scribengin.dataflow.KafkaDataSet;
import com.neverwinterdp.scribengin.dataflow.<API key>;
import com.neverwinterdp.scribengin.dataflow.Operator;
import com.neverwinterdp.scribengin.shell.ScribenginShell;
import com.neverwinterdp.storage.kafka.KafkaStorageConfig;
import com.neverwinterdp.util.JSONSerializer;
import com.neverwinterdp.vm.client.VMClient;
public class <API key> {
private String dataflowID;
private int defaultReplication;
private int defaultParallelism;
private int numOfWorker;
private int <API key>;
private String inputTopic;
private String outputTopic;
private ScribenginShell shell;
private DataflowSubmitter submitter;
private String localAppHome;
private String dfsAppHome;
public <API key>(ScribenginShell shell){
this(shell, new Properties());
}
/**
* Constructor - sets shell to access Scribengin and configuration properties
* @param shell ScribenginShell to connect to Scribengin with
* @param props Properties to configure the dataflow
*/
public <API key>(ScribenginShell shell, Properties props){
//This it the shell to communicate with Scribengin with
this.shell = shell;
//The dataflow's ID. All dataflows require a unique ID when running
dataflowID = props.getProperty("dataflow.id", "WireDataflow");
//The default replication factor for Kafka
defaultReplication = Integer.parseInt(props.getProperty("dataflow.replication", "1"));
//The number of DataStreams to deploy
defaultParallelism = Integer.parseInt(props.getProperty("dataflow.parallelism", "2"));
//The number of workers to deploy (i.e. YARN containers)
numOfWorker = Integer.parseInt(props.getProperty("dataflow.numWorker", "5"));
//The number of executors per worker (i.e. threads per YARN container)
<API key> = Integer.parseInt(props.getProperty("dataflow.<API key>", "5"));
//The kafka input topic
inputTopic = props.getProperty("dataflow.inputTopic", "input.topic");
//The kafka output topic
outputTopic = props.getProperty("dataflow.outputTopic", "output.topic");
//The example hdfs dataflow local location
localAppHome = props.getProperty("dataflow.localapphome", "N/A");
//DFS location to upload the example dataflow
dfsAppHome = props.getProperty("dataflow.dfsAppHome", "/applications/dataflow/splitterexample");
}
/**
* The logic to submit the dataflow
* @param kafkaZkConnect [host]:[port] of Kafka's Zookeeper conenction
* @throws Exception
*/
public void submitDataflow(String kafkaZkConnect) throws Exception{
//Upload the dataflow to HDFS
VMClient vmClient = shell.getScribenginClient().getVMClient();
vmClient.uploadApp(localAppHome, dfsAppHome);
Dataflow dfl = buildDataflow(kafkaZkConnect);
//Get the dataflow's descriptor
DataflowDescriptor dflDescriptor = dfl.<API key>();
//Output the descriptor in human-readable JSON
System.out.println(JSONSerializer.INSTANCE.toString(dflDescriptor));
//Ensure all your sources and sinks are up and running first, then...
//Submit the dataflow and wait until it starts running
submitter = new DataflowSubmitter(shell.getScribenginClient(), dfl).submit().<API key>(60000);
}
/**
* Wait for the dataflow to complete within the given timeout
* @param timeout Timeout in ms
* @throws Exception
*/
public void <API key>(int timeout) throws Exception{
submitter.waitForDataflowStop(timeout);
}
/**
* The logic to build the dataflow configuration
* The main takeaway between this dataflow and the <API key>
* is the use of dfl.<API key>()
* This factory allows us to tie together operators
* with Kafka topics between them
* @param kafkaZkConnect [host]:[port] of Kafka's Zookeeper conenction
* @return
*/
public Dataflow buildDataflow(String kafkaZkConnect){
//Create the new Dataflow object
// <Message,Message> pertains to the <input,output> object for the data
Dataflow dfl = new Dataflow(dataflowID);
//Example of how to set the <API key>
dfl.
<API key>(defaultParallelism).
<API key>(defaultReplication).
<API key>(new <API key>(kafkaZkConnect));
dfl.getWorkerDescriptor().setNumOfInstances(numOfWorker);
dfl.getWorkerDescriptor().setNumOfExecutor(<API key>);
//Define our input source - set name, ZK host:port, and input topic name
KafkaDataSet<Message> inputDs =
dfl.createInput(new KafkaStorageConfig("input", kafkaZkConnect, inputTopic));
//Define our output sink - set name, ZK host:port, and output topic name
DataSet<Message> outputDs =
dfl.createOutput(new KafkaStorageConfig("output", kafkaZkConnect, outputTopic));
//Define which operators to use.
//This will be the logic that ties the datasets and operators together
Operator splitter = dfl.createOperator("splitteroperator", <API key>.class);
Operator odd = dfl.createOperator("oddoperator", <API key>.class);
Operator even = dfl.createOperator("evenoperator", <API key>.class);
//Send all input to the splitter operator
inputDs.useRawReader().connect(splitter);
//The splitter operator then connects to the odd and even operators
splitter.connect(odd)
.connect(even);
//Both the odd and even operator connect to the output dataset
// This is arbitrary, we could connect them to any dataset or operator we wanted
odd.connect(outputDs);
even.connect(outputDs);
return dfl;
}
public String getDataflowID() { return dataflowID; }
public String getInputTopic() { return inputTopic; }
public String getOutputTopic() { return outputTopic; }
} |
package com.gmail.nossr50.commands.party;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.commands.CommandHelper;
import com.gmail.nossr50.datatypes.PlayerProfile;
import com.gmail.nossr50.events.chat.McMMOPartyChatEvent;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.party.Party;
import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.util.Users;
public class PCommand implements CommandExecutor {
private final mcMMO plugin;
public PCommand (mcMMO plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
PlayerProfile profile;
String usage = ChatColor.RED + "Proper usage is /p <party-name> <message>"; //TODO: Needs more locale.
if (CommandHelper.<API key>(sender, "mcmmo.commands.party")) {
return true;
}
switch (args.length) {
case 0:
if (sender instanceof Player) {
profile = Users.getProfile((Player) sender);
if (profile.getAdminChatMode()) {
profile.toggleAdminChat();
}
profile.togglePartyChat();
if (profile.getPartyChatMode()) {
sender.sendMessage(LocaleLoader.getString("Commands.Party.Chat.On"));
}
else {
sender.sendMessage(LocaleLoader.getString("Commands.Party.Chat.Off"));
}
}
else {
sender.sendMessage(usage);
}
return true;
default:
if (sender instanceof Player) {
Player player = (Player) sender;
Party party = Users.getProfile(player).getParty();
if (party == null) {
player.sendMessage(LocaleLoader.getString("Commands.Party.None"));
return true;
}
StringBuffer buffer = new StringBuffer();
buffer.append(args[0]);
for (int i = 1; i < args.length; i++) {
buffer.append(" ");
buffer.append(args[i]);
}
String message = buffer.toString();
McMMOPartyChatEvent chatEvent = new McMMOPartyChatEvent(player.getName(), party.getName(), message);
plugin.getServer().getPluginManager().callEvent(chatEvent);
if (chatEvent.isCancelled()) {
return true;
}
message = chatEvent.getMessage();
String prefix = ChatColor.GREEN + "(" + ChatColor.WHITE + player.getName() + ChatColor.GREEN + ") ";
plugin.getLogger().info("[P](" + party.getName() + ")" + "<" + player.getName() + "> " + message);
for (Player member : party.getOnlineMembers()) {
member.sendMessage(prefix + message);
}
}
else {
if (args.length < 2) {
sender.sendMessage(usage);
return true;
}
if (!PartyManager.getInstance().isParty(args[0])) {
sender.sendMessage(LocaleLoader.getString("Party.InvalidName"));
return true;
}
StringBuffer buffer = new StringBuffer();
buffer.append(args[1]);
for (int i = 2; i < args.length; i++) {
buffer.append(" ");
buffer.append(args[i]);
}
String message = buffer.toString();
McMMOPartyChatEvent chatEvent = new McMMOPartyChatEvent("Console", args[0], message);
plugin.getServer().getPluginManager().callEvent(chatEvent);
if (chatEvent.isCancelled()) {
return true;
}
message = chatEvent.getMessage();
String prefix = ChatColor.GREEN + "(" + ChatColor.WHITE + "*Console*" + ChatColor.GREEN + ") ";
plugin.getLogger().info("[P](" + args[0] + ")" + "<*Console*> " + message);
for (Player member : PartyManager.getInstance().getOnlineMembers(args[0])) {
member.sendMessage(prefix + message);
}
}
return true;
}
}
} |
DELETE FROM `weenie` WHERE `class_Id` = 46553;
INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`)
VALUES (46553, '<API key>', 2, '2019-02-10 00:00:00') /* Clothing */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (46553, 1, 2) /* ItemType - Armor */
, (46553, 4, 65536) /* ClothingPriority - Feet */
, (46553, 5, 420) /* EncumbranceVal */
, (46553, 9, 384) /* ValidLocations - LowerLegWear, FootWear */
, (46553, 10, 384) /* <API key> - LowerLegWear, FootWear */
, (46553, 16, 1) /* ItemUseable - No */
, (46553, 19, 70) /* Value */
, (46553, 28, 660) /* ArmorLevel */
, (46553, 33, 1) /* Bonded - Bonded */
, (46553, 93, 1044) /* PhysicsState - Ethereal, IgnoreCollisions, Gravity */
, (46553, 106, 100) /* ItemSpellcraft */
, (46553, 107, 0) /* ItemCurMana */
, (46553, 108, 1000) /* ItemMaxMana */
, (46553, 109, 0) /* ItemDifficulty */
, (46553, 158, 7) /* WieldRequirements - Level */
, (46553, 159, 1) /* WieldSkillType - Axe */
, (46553, 160, 180) /* WieldDifficulty */
, (46553, 265, 14) /* EquipmentSetId - Adepts */
, (46553, 8041, 101) /* <API key> - Resting */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (46553, 22, True ) /* Inscribable */
, (46553, 100, True ) /* Dyable */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (46553, 5, -0.033) /* ManaRate */
, (46553, 13, 2.9) /* ArmorModVsSlash */
, (46553, 14, 3.2) /* ArmorModVsPierce */
, (46553, 15, 2.9) /* ArmorModVsBludgeon */
, (46553, 16, 2.3) /* ArmorModVsCold */
, (46553, 17, 2.3) /* ArmorModVsFire */
, (46553, 18, 2.5) /* ArmorModVsAcid */
, (46553, 19, 2.3) /* ArmorModVsElectric */
, (46553, 165, 1) /* ArmorModVsNether */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (46553, 1, 'O-Yoroi Sandals') /* Name */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (46553, 1, 33554654) /* Setup */
, (46553, 3, 536870932) /* SoundTable */
, (46553, 6, 67108990) /* PaletteBase */
, (46553, 8, 100676025) /* Icon */
, (46553, 22, 872415275) /* PhysicsEffectTable */
, (46553, 8001, 2588696) /* <API key> - Value, Usable, Wielder, ValidLocations, <API key>, Priority, Burden */
, (46553, 8003, 18) /* <API key> - Inscribable, Attackable */
, (46553, 8005, 137217) /* <API key> - CSetup, STable, PeTable, AnimationFrame */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (46553, 8000, 2345789235) /* <API key> */;
INSERT INTO `<API key>` (`object_Id`, `spell`, `probability`)
VALUES (46553, 4391, 2) /* AcidBane8 */
, (46553, 4393, 2) /* BladeBane8 */
, (46553, 4397, 2) /* BludgeonBane8 */
, (46553, 4401, 2) /* FlameBane8 */
, (46553, 4403, 2) /* FrostBane8 */
, (46553, 4407, 2) /* Impenetrability8 */
, (46553, 4409, 2) /* LightningBane8 */
, (46553, 4412, 2) /* PiercingBane8 */
, (46553, 4700, 2) /* <API key> */;
INSERT INTO `<API key>` (`object_Id`, `sub_Palette_Id`, `offset`, `length`)
VALUES (46553, 67110021, 160, 8);
INSERT INTO `<API key>` (`object_Id`, `index`, `old_Id`, `new_Id`)
VALUES (46553, 0, 83889344, 83895201)
, (46553, 0, 83887066, 83895202);
INSERT INTO `<API key>` (`object_Id`, `index`, `animation_Id`)
VALUES (46553, 0, 16778416); |
import { TYPES } from 'core/app/types'
import { StateManager } from 'core/dialog'
import { ContainerModule, interfaces } from 'inversify'
import { DecisionEngine } from './decision-engine'
import { DialogEngine } from './dialog-engine'
import { FlowService } from './flow/flow-service'
import { FlowNavigator } from './flow/navigator'
import { InstructionFactory } from './instruction/factory'
import { <API key> } from './instruction/processor'
import { ActionStrategy, TransitionStrategy } from './instruction/strategy'
import { DialogJanitor } from './janitor'
export const <API key> = new ContainerModule((bind: interfaces.Bind) => {
bind<DialogEngine>(TYPES.DialogEngine)
.to(DialogEngine)
.inSingletonScope()
bind<DecisionEngine>(TYPES.DecisionEngine)
.to(DecisionEngine)
.inSingletonScope()
bind<FlowNavigator>(TYPES.FlowNavigator)
.to(FlowNavigator)
.inSingletonScope()
bind<FlowService>(TYPES.FlowService)
.to(FlowService)
.inSingletonScope()
bind<InstructionFactory>(TYPES.InstructionFactory)
.to(InstructionFactory)
.inSingletonScope()
bind<<API key>>(TYPES.<API key>)
.to(<API key>)
.inSingletonScope()
bind<ActionStrategy>(TYPES.ActionStrategy)
.to(ActionStrategy)
.inRequestScope()
bind<TransitionStrategy>(TYPES.TransitionStrategy)
.to(TransitionStrategy)
.inRequestScope()
bind<DialogJanitor>(TYPES.DialogJanitorRunner)
.to(DialogJanitor)
.inSingletonScope()
bind<StateManager>(TYPES.StateManager)
.to(StateManager)
.inSingletonScope()
}) |
(function($) {
function uSquareItem(element, options) {
this.$item = $(element);
this.$parent = options.$parent;
this.options = options;
this.$trigger = this.$(options.trigger);
this.$close = this.$('.close');
this.$info = this.$(options.moreInfo);
this.$trigger_text = this.$trigger.find('.<API key>');
this.$usquare_about = this.$info.find('.usquare_about');
this.$trigger.on('click', $.proxy(this.show, this));
this.$close.on('click', $.proxy(this.close, this));
options.$overlay.on('click', $.proxy(this.close, this));
};
uSquareItem.prototype = {
show: function(e) {
e.preventDefault();
if (!this.$parent.data('in_trans'))
{
if (!this.$item.data('showed'))
{
this.$parent.data('in_trans', 1);
this.$item.data('showed', 1);
if (this.options.<API key>) this.options.<API key>(this.$item);
var item_position = this.$item.position();
var <API key>;
var this_backup=this;
var moving=0;
if (item_position.top>0) // && this.$parent.width()>=640)
{
var parent_position=this.$parent.offset();
var parent_top = parent_position.top;
var non_visible_area=$(window).scrollTop()-parent_top;
var going_to=item_position.top;
if (non_visible_area>0)
{
var non_visible_row=Math.floor(non_visible_area/this.$item.height())+1;
going_to=this.$item.height()*non_visible_row;
going_to=item_position.top-going_to;
}
if (going_to>0) moving=1;
if (moving)
{
this.$item.data('moved', going_to);
var top_string='-'+going_to+'px';
var speed=this.options.opening_speed+(going_to/160)*100;
this.$item.animate({top: top_string}, speed, this.options.easing, function(){
<API key> = this_backup.$item.height() - this_backup.$trigger_text.height();
this_backup.$trigger_text.data('top', <API key>);
this_backup.$trigger_text.css('top', <API key>);
this_backup.$trigger_text.css('bottom', 'auto');
this_backup.$trigger_text.animate({'top': 0}, 'slow');
});
}
}
if (!moving)
{
<API key> = this_backup.$item.height() - this_backup.$trigger_text.height();
this_backup.$trigger_text.data('top', <API key>);
this_backup.$trigger_text.css('top', <API key>);
this_backup.$trigger_text.css('bottom', 'auto');
this_backup.$trigger_text.animate({'top': 0}, 'slow');
}
this.$item.addClass('<API key>');
var height_backup=this.$info.css('height');
this.$info.css('height', 0);
this.$info.show();
this.$usquare_about.mCustomScrollbar("update");
if (this.options.<API key>) this.options.<API key>(this.$item);
this.$info.animate({height:height_backup}, 'slow', this.options.easing, function()
{
this_backup.$parent.data('in_trans', 0);
if (this_backup.options.<API key>) this_backup.options.<API key>(this_backup.$item);
});
}
}
},
close: function(e) {
e.preventDefault();
if (!this.$parent.data('in_trans'))
{
if (this.$item.data('showed'))
{
var this_backup=this;
this.$info.hide();
var <API key> = this_backup.$item.height() - this_backup.$trigger_text.height();
this_backup.$item.removeClass('<API key>');
if (this.$item.data('moved'))
{
var top_backup=this.$item.data('moved');
var speed=this.options.closing_speed+(top_backup/160)*100;
this.$item.data('moved', 0);
this.$item.animate({'top': 0}, speed, this.options.easing, function()
{
this_backup.$trigger_text.animate({'top': <API key>}, 'slow');
});
}
else
{
this_backup.$trigger_text.animate({'top': <API key>}, 'slow');
}
this.$item.data('showed', 0);
}
}
},
$: function (selector) {
return this.$item.find(selector);
}
};
function uSquare(element, options) {
var self = this;
this.options = $.extend({}, $.fn.uSquare.defaults, options);
this.$element = $(element);
this.$overlay = this.$('.<API key>');
this.$items = this.$(this.options.block);
this.$triggers = this.$(this.options.trigger);
this.$closes = this.$('.close');
this.$triggers.on('click', $.proxy(this.overlayShow, this));
this.$closes.on('click', $.proxy(this.overlayHide, this));
this.$overlay.on('click', $.proxy(this.overlayHide, this));
$.each( this.$items, function(i, element) {
new uSquareItem(element, $.extend(self.options, {$overlay: self.$overlay, $parent: self.$element }) );
});
};
uSquare.prototype = {
$: function (selector) {
return this.$element.find(selector);
},
overlayShow: function() {
this.$overlay.fadeIn('slow', function(){
$(this).css({opacity : 0.5});
})
},
overlayHide: function() {
if (!this.$element.data('in_trans'))
{
this.$overlay.fadeOut('slow');
}
}
};
$.fn.uSquare = function ( option ) {
return this.each(function () {
var $this = $(this),
data = $this.data('tooltip'),
options = typeof option == 'object' && option;
data || $this.data('tooltip', (data = new uSquare(this, options)));
(typeof option == 'string') && data[option]();
});
};
$.fn.uSquare.Constructor = uSquare;
$.fn.uSquare.defaults = {
block: '.usquare_block',
trigger: '.usquare_square',
moreInfo: '.<API key>',
opening_speed: 300,
closing_speed: 500,
easing: 'swing',
<API key>: null,
<API key>: null,
<API key>: null
};
})(jQuery);
$(window).load(function() {
$(".usquare_about").mCustomScrollbar();
}); |
var searchData=
[
['backtrace',['backtrace',['../class_logger.html#<API key>',1,'Logger']]],
['baseexception',['BaseException',['../<API key>.html',1,'']]],
['baseexception_2ephp',['BaseException.php',['../<API key>.html',1,'']]],
['basic_2ephp',['Basic.php',['../_menu_2_basic_8php.html',1,'']]],
['basic_2ephp',['Basic.php',['../<API key>.html',1,'']]],
['basic_2ephp',['Basic.php',['../_auth_2_basic_8php.html',1,'']]],
['basic_2ephp',['Basic.php',['../<API key>.html',1,'']]],
['basic_2ephp',['Basic.php',['../_form_2_basic_8php.html',1,'']]],
['basic_2ephp',['Basic.php',['../_grid_2_basic_8php.html',1,'']]],
['basicauth',['BasicAuth',['../class_basic_auth.html',1,'']]],
['basicauth_2ephp',['BasicAuth.php',['../_basic_auth_8php.html',1,'']]],
['beforedelete',['beforeDelete',['../<API key>.html#<API key>',1,'SQL_Relation']]],
['beforefield',['beforeField',['../class_form___field.html#<API key>',1,'Form_Field']]],
['beforeinsert',['beforeInsert',['../<API key>.html#<API key>',1,'SQL_Relation']]],
['beforeload',['beforeLoad',['../<API key>.html#<API key>',1,'SQL_Relation']]],
['beforemodify',['beforeModify',['../<API key>.html#<API key>',1,'SQL_Relation']]],
['beforesave',['beforeSave',['../<API key>.html#<API key>',1,'SQL_Relation']]],
['begintransaction',['beginTransaction',['../class_d_b.html#<API key>',1,'DB\beginTransaction()'],['../<API key>.html#<API key>',1,'DBlite_mysql\beginTransaction()']]],
['belowfield',['belowField',['../class_form___field.html#<API key>',1,'Form_Field']]],
['box_2ephp',['Box.php',['../_box_8php.html',1,'']]],
['breakhook',['breakHook',['../<API key>.html#<API key>',1,'AbstractObject']]],
['bt',['bt',['../class_d_b__dsql.html#<API key>',1,'DB_dsql']]],
['button',['Button',['../class_button.html',1,'']]],
['button_2ephp',['Button.php',['../_button_8php.html',1,'']]],
['button_2ephp',['Button.php',['../_form_2_button_8php.html',1,'']]],
['button_2ephp',['Button.php',['../_view_2_button_8php.html',1,'']]],
['buttonset',['ButtonSet',['../class_button_set.html',1,'']]],
['buttonset_2ephp',['ButtonSet.php',['../_button_set_8php.html',1,'']]],
['buttonset_2ephp',['ButtonSet.php',['../<API key>.html',1,'']]]
]; |
<div class="role-filter">
<div class="fw-700 m-b-5">{{"ROLE"|translate}}</div>
<div>
<div class="checkbox-inline" ng-class="{'selected':roles.tank.selected}" uib-tooltip="{{'TANK'|translate}}">
<label class="tank">
<input ng-model="roles.tank.selected" type="checkbox">
</label>
</div>
<div class="checkbox-inline" ng-class="{'selected':roles.heal.selected}" uib-tooltip="{{'HEAL'|translate}}">
<label class="heal">
<input ng-model="roles.heal.selected" type="checkbox">
</label>
</div>
<div class="checkbox-inline" ng-class="{'selected':roles.melee_dps.selected}"
uib-tooltip="{{'MELEE_DPS'|translate}}">
<label class="melee_dps">
<input ng-model="roles.melee_dps.selected" type="checkbox">
</label>
</div>
<div class="checkbox-inline" ng-class="{'selected':roles.ranged_dps.selected}"
uib-tooltip="{{'RANGED_DPS'|translate}}">
<label class="ranged_dps">
<input ng-model="roles.ranged_dps.selected" type="checkbox">
</label>
</div>
</div>
</div> |
body { font-family: 'DejaVu Sans Condensed'; font-size: 11pt; }
p { text-align: justify; margin-bottom: 4pt; margin-top:0pt; }
table {font-family: 'DejaVu Sans Condensed'; font-size: 10pt; line-height: 1.2;
margin-top: 2pt; margin-bottom: 5pt;
border-collapse: collapse; }
thead { font-weight: bold; vertical-align: bottom; }
tfoot { font-weight: bold; vertical-align: top; }
thead td { font-weight: bold; }
tfoot td { font-weight: bold; }
.Thead { font-weight: bold; vertical-align: bottom; }
.Thead td { font-weight: bold; }
.headerrow td, .headerrow th { background-gradient: linear #b7cebd #f5f8f5 0 1 0 0.2; }
.footerrow td, .footerrow th { background-gradient: linear #b7cebd #f5f8f5 0 1 0 0.2; }
th { font-weight: bold;
vertical-align: top;
padding-left: 2mm;
padding-right: 2mm;
padding-top: 0.5mm;
padding-bottom: 0.5mm;
}
td { padding-left: 2mm;
vertical-align: top;
padding-right: 2mm;
padding-top: 0.5mm;
padding-bottom: 0.5mm;
}
th p { margin:0pt; }
td p { margin:0pt; }
table.widecells td {
padding-left: 5mm;
padding-right: 5mm;
}
table.tallcells td {
padding-top: 3mm;
padding-bottom: 3mm;
}
hr { width: 70%; height: 1px;
text-align: center; color: #999999;
margin-top: 8pt; margin-bottom: 8pt; }
a { color: #000066; font-style: normal; text-decoration: underline;
font-weight: normal; }
pre { font-family: 'DejaVu Sans Mono'; font-size: 9pt; margin-top: 5pt; margin-bottom: 5pt; }
h1 { font-weight: normal; font-size: 26pt; color: #000066;
font-family: 'DejaVu Sans Condensed'; margin-top: 18pt; margin-bottom: 6pt;
border-top: 0.075cm solid #000000; border-bottom: 0.075cm solid #000000;
page-break-after:avoid; }
h2 { font-weight: bold; font-size: 12pt; color: #000066;
font-family: 'DejaVu Sans Condensed'; margin-top: 6pt; margin-bottom: 6pt;
border-top: 0.07cm solid #000000; border-bottom: 0.07cm solid #000000;
text-transform:uppercase; page-break-after:avoid; }
h3 { font-weight: normal; font-size: 26pt; color: #000000;
font-family: 'DejaVu Sans Condensed'; margin-top: 0pt; margin-bottom: 6pt;
border-top: 0; border-bottom: 0;
page-break-after:avoid; }
h4 { font-size: 13pt; color: #9f2b1e;
border-bottom: 0.07cm solid #000000; font-family: 'DejaVu Sans Condensed'; margin-top: 10pt; margin-bottom: 7pt; font-variant: small-caps;
/* margin-collapse:collapse; */page-break-after:avoid; }
h5 { font-weight: bold; font-style:italic; ; font-size: 11pt; color: #000044;
font-family: 'DejaVu Sans Condensed'; margin-top: 8pt; margin-bottom: 4pt;
page-break-after:avoid; }
h6 { font-weight: bold; font-size: 9.5pt; color: #333333;
font-family: 'DejaVu Sans Condensed'; margin-top: 6pt; margin-bottom: ;
page-break-after:avoid; }
.breadcrumb {
text-align: right; font-size: 8pt; font-family: 'DejaVu Serif Condensed'; color: #666666;
font-weight: bold; font-style: normal; margin-bottom: 6pt; }
.bpmTopic tbody tr:nth-child(even) { background-color: #f5f8f5; }
.bpmTopicC tbody tr:nth-child(even) { background-color: #f5f8f5; }
.bpmNoLines tbody tr:nth-child(even) { background-color: #f5f8f5; }
.bpmNoLinesC tbody tr:nth-child(even) { background-color: #f5f8f5; }
.bpmTopnTail tbody tr:nth-child(even) { background-color: #f5f8f5; }
.bpmTopnTailC tbody tr:nth-child(even) { background-color: #f5f8f5; }
.evenrow td, .evenrow th { background-color: #f5f8f5; }
.oddrow td, .oddrow th { background-color: #e3ece4; }
.bpmTopic { background-color: #e3ece4; }
.bpmTopicC { background-color: #e3ece4; }
.bpmNoLines { background-color: #e3ece4; }
.bpmNoLinesC { background-color: #e3ece4; }
.bpmClear { }
.bpmClearC { text-align: center; }
.bpmTopnTail { background-color: #e3ece4; topntail: 0.02cm solid #495b4a;}
.bpmTopnTailC { background-color: #e3ece4; topntail: 0.02cm solid #495b4a;}
.bpmTopnTailClear { topntail: 0.02cm solid #495b4a; }
.bpmTopnTailClearC { topntail: 0.02cm solid #495b4a; }
.bpmTopicC td, .bpmTopicC td p { text-align: center; }
.bpmNoLinesC td, .bpmNoLinesC td p { text-align: center; }
.bpmClearC td, .bpmClearC td p { text-align: center; }
.bpmTopnTailC td, .bpmTopnTailC td p { text-align: center; }
.bpmTopnTailClearC td, .bpmTopnTailClearC td p { text-align: center; }
.pmhMiddleCenter { text-align:center; vertical-align:middle; }
.pmhMiddleRight { text-align:right; vertical-align:middle; }
.pmhBottomCenter { text-align:center; vertical-align:bottom; }
.pmhBottomRight { text-align:right; vertical-align:bottom; }
.pmhTopCenter { text-align:center; vertical-align:top; }
.pmhTopRight { text-align:right; vertical-align:top; }
.pmhTopLeft { text-align:left; vertical-align:top; }
.pmhBottomLeft { text-align:left; vertical-align:bottom; }
.pmhMiddleLeft { text-align:left; vertical-align:middle; }
.infobox { margin-top:10pt; background-color:#DDDDBB; text-align:center; border:1px solid #880000; }
.bpmTopic td, .bpmTopic th { border-top: 1px solid #FFFFFF; }
.bpmTopicC td, .bpmTopicC th { border-top: 1px solid #FFFFFF; }
.bpmTopnTail td, .bpmTopnTail th { border-top: 1px solid #FFFFFF; }
.bpmTopnTailC td, .bpmTopnTailC th { border-top: 1px solid #FFFFFF; }
.dettaglio {
margin:0px;padding:0px;
width:100%;
box-shadow: 10px 10px 5px #888888;
border:1px solid #000000;
-<API key>:0px;
-<API key>:0px;
<API key>:0px;
-<API key>:0px;
-<API key>:0px;
<API key>:0px;
-<API key>:0px;
-<API key>:0px;
<API key>:0px;
-<API key>:0px;
-<API key>:0px;
<API key>:0px;
}
.dettaglio table{
border-collapse: collapse;
border-spacing: 0;
width:100%;
height:100%;
margin:0px;padding:0px;
}
.dettaglio tr:last-child td:last-child {
-<API key>:0px;
-<API key>:0px;
<API key>:0px;
}
.dettaglio table tr:first-child td:first-child {
-<API key>:0px;
-<API key>:0px;
<API key>:0px;
}
.dettaglio table tr:first-child td:last-child {
-<API key>:0px;
-<API key>:0px;
<API key>:0px;
}
.dettaglio tr:last-child td:first-child{
-<API key>:0px;
-<API key>:0px;
<API key>:0px;
}
.dettaglio tr:hover td{
}
.dettaglio tr:nth-child(odd){ background-color:#e5e5e5; }
.dettaglio tr:nth-child(even) { background-color:#ffffff; }
.dettaglio td{
vertical-align:middle;
border:1px solid #000000;
border-width:0px 1px 1px 0px;
text-align:left;
padding:7px;
font-size:10px;
font-family:Arial;
font-weight:normal;
color:#000000;
}
.dettaglio tr:last-child td{
border-width:0px 1px 0px 0px;
}
.dettaglio tr td:last-child{
border-width:0px 0px 1px 0px;
}
.dettaglio tr:last-child td:last-child{
border-width:0px 0px 0px 0px;
}
.dettaglio tr:first-child td{
background:-o-linear-gradient(bottom, #cccccc 5%, #b2b2b2 100%); background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #cccccc), color-stop(1, #b2b2b2) );
background:-moz-linear-gradient( center top, #cccccc 5%, #b2b2b2 100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#cccccc", endColorstr="#b2b2b2"); background: -o-linear-gradient(top,#cccccc,b2b2b2);
background-color:#cccccc;
border:0px solid #000000;
text-align:center;
border-width:0px 0px 1px 1px;
font-size:14px;
font-family:Arial;
font-weight:bold;
color:#000000;
}
.dettaglio tr:first-child:hover td{
background:-o-linear-gradient(bottom, #cccccc 5%, #b2b2b2 100%); background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #cccccc), color-stop(1, #b2b2b2) );
background:-moz-linear-gradient( center top, #cccccc 5%, #b2b2b2 100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#cccccc", endColorstr="#b2b2b2"); background: -o-linear-gradient(top,#cccccc,b2b2b2);
background-color:#cccccc;
}
.dettaglio tr:first-child td:first-child{
border-width:0px 0px 1px 0px;
}
.dettaglio tr:first-child td:last-child{
border-width:0px 0px 1px 1px;
} |
#pragma once
#include <cstdint>
#include "ManagedPacket.h"
#include "WorldPacket.h"
namespace AscEmu::Packets
{
class <API key> : public ManagedPacket
{
public:
WoWGuid questgiverGuid;
uint32_t questId;
<API key>() : <API key>(0, 0)
{
}
<API key>(uint64_t questgiverGuid, uint32_t questId) :
ManagedPacket(<API key>, 12),
questgiverGuid(questgiverGuid),
questId(questId)
{
}
bool internalSerialise(WorldPacket& /*packet*/) override
{
return false;
}
bool internalDeserialise(WorldPacket& packet) override
{
uint64_t unpackedGuid;
packet >> unpackedGuid >> questId;
questgiverGuid.Init(unpackedGuid);
return true;
}
};
} |
package org.demo.jdk.utilapis;
public class Bird implements Flyable {
private int speed = 15;
@Override
public void fly() {
System.out.println("I'm Bird, my speed is " + speed + ".");
}
} |
<?php
// See the LICENCE file in the repository root for full licence text.
namespace App\Libraries;
use App\Exceptions\<API key>;
use App\Mail\UserVerification as <API key>;
use App\Models\Country;
use App\Models\LoginAttempt;
use Datadog;
use Mail;
class UserVerification
{
private $request;
private $state;
private $user;
public static function fromCurrentRequest()
{
$verification = request()->attributes->get('user_verification');
if ($verification === null) {
$verification = new static(
auth()->user(),
request(),
<API key>::fromCurrentRequest()
);
request()->attributes->set('user_verification', $verification);
}
return $verification;
}
public static function logAttempt(string $source, string $type, string $reason = null): void
{
Datadog::increment(
config('datadog-helper.prefix_web').'.verification.attempts',
1,
compact('reason', 'source', 'type')
);
}
private function __construct($user, $request, $state)
{
$this->user = $user;
$this->request = $request;
$this->state = $state;
}
public function initiate()
{
$statusCode = 401;
app('route-section')->setError("{$statusCode}-verification");
// Workaround race condition causing $this->issue() to be called in parallel.
// Mainly observed when logging in as privileged user.
if ($this->request->ajax()) {
$routeData = app('route-section')->getOriginal();
if ($routeData['controller'] === '<API key>' && $routeData['action'] === 'index') {
return response(['error' => 'verification'], $statusCode);
}
}
$email = $this->user->user_email;
if (!$this->state->issued()) {
static::logAttempt('input', 'new');
$this->issue();
}
if ($this->request->ajax()) {
return response([
'authentication' => 'verify',
'box' => view(
'users._verify_box',
compact('email')
)->render(),
], $statusCode);
} else {
return ext_view('users.verify', compact('email'), null, $statusCode);
}
}
public function isDone()
{
return $this->state->isDone();
}
public function issue()
{
$user = $this->user;
if (!present($user->user_email)) {
return;
}
$keys = $this->state->issue();
LoginAttempt::logAttempt($this->request->getClientIp(), $this->user, 'verify');
$requestCountry = Country
::where('acronym', request_country($this->request))
->pluck('name')
->first();
Mail::to($user)
->queue(new <API key>(
compact('keys', 'user', 'requestCountry')
));
}
public function <API key>()
{
$this->state->markVerified();
return response([], 200);
}
public function reissue()
{
if ($this->state->isDone()) {
return $this-><API key>();
}
$this->issue();
return response(['message' => trans('user_verification.errors.reissued')], 200);
}
public function verify()
{
$key = str_replace(' ', '', $this->request->input('verification_key'));
try {
$this->state->verify($key);
} catch (<API key> $e) {
static::logAttempt('input', 'fail', $e->reasonKey());
if ($e->reasonKey() === 'incorrect_key') {
LoginAttempt::logAttempt($this->request->getClientIp(), $this->user, 'verify-mismatch', $key);
}
if ($e->shouldReissue()) {
$this->issue();
}
return error_popup($e->getMessage());
}
static::logAttempt('input', 'success');
return $this-><API key>();
}
} |
<html>
<head>
<title>Frankenstein, 1831, Vol. 2, Chap. 3, Frame 6</title>
</head>
<body>
<p>
"Having thus arranged my dwelling, and carpeted it with clean
straw, I retired; for I saw the figure of a man at a distance,
and I remembered too well my treatment the night before, to trust
myself in his power. I had first, however, provided for my
sustenance for that day, by a loaf of coarse bread, which I
purloined, and a cup with which I could drink, more conveniently
than from my hand, of the pure water which flowed by my retreat.
The floor was a little raised, so that it was kept perfectly dry,
and by its vicinity to the chimney of the cottage it was
tolerably warm.</p><p>
"Being thus provided, I resolved to reside in this hovel, until something
should occur which might alter my determination. It was indeed <a
href="../V2notes/paradise.html">a paradise</a>, compared to the bleak
forest, my former residence, the rain-dropping branches, and dank earth. I
ate my breakfast with pleasure, and was about to remove a plank to procure
myself a little water, when I heard a step, and looking through a small
chink, I beheld a young creature, with a pail on her head, passing before
my hovel. The girl was young, and of gentle demeanour, <a
href="../V2notes/unlike.html">unlike what I have since found cottagers and
farm-house servants to be</a>. Yet she was <a
href="../V2notes/meanly.html">meanly dressed</a>, a coarse blue petticoat
and a linen jacket being her only garb; her fair hair was plaited, but not
adorned; she looked patient, yet sad. I lost sight of her; and in about a
quarter of an hour she returned, bearing the pail, which was now partly
filled with milk. As she walked along, seemingly incommoded by the burden,
a young man met her, whose countenance expressed a deeper despondence.
Uttering a few sounds with an air of melancholy, he took the pail from her
head, and bore it to the cottage himself. She followed, and they
disappeared. Presently I saw the young man again, with some tools in his
hand, cross the field behind the cottage; and the girl was also busied,
sometimes in the house, and sometimes in the yard.</p>
</body>
</html> |
#ifndef REGISTRY_INC_
# define REGISTRY_INC_
# include "xdwrgstry.h"
namespace registry {
using namespace xdwrgstry;
namespace parameter {
using namespace xdwrgstry::parameter;
}
namespace definition {
using namespace xdwrgstry::definition;
}
}
#endif |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenTidl.Models;
using OpenTidl.Models.Base;
using OpenTidl.Transport;
using OpenTidl.Enums;
using System.IO;
namespace OpenTidl
{
public partial class OpenTidlClient
{
#region image methods
<summary>
Helper method to retrieve a stream with an album cover image
</summary>
public Stream GetAlbumCover(AlbumModel model, AlbumCoverSize size)
{
return GetAlbumCover(model.Cover, model.Id, size);
}
<summary>
Helper method to retrieve a stream with an album cover image
</summary>
public Stream GetAlbumCover(String cover, Int32 albumId, AlbumCoverSize size)
{
var w = 750;
var h = 750;
if (!RestUtility.ParseImageSize(size.ToString(), out w, out h))
throw new ArgumentException("Invalid image size", "size");
String url = null;
if (!String.IsNullOrEmpty(cover))
url = String.Format("http://resources.wimpmusic.com/images/{0}/{1}x{2}.jpg", cover.Replace('-', '/'), w, h);
else
url = String.Format("http://images.tidalhifi.com/im/im?w={1}&h={2}&albumid={0}&noph", albumId, w, h);
return RestClient.GetStream(url);
}
<summary>
Helper method to retrieve a stream with an artists picture
</summary>
public Stream GetArtistPicture(ArtistModel model, ArtistPictureSize size)
{
return GetArtistPicture(model.Picture, model.Id, size);
}
<summary>
Helper method to retrieve a stream with an artists picture
</summary>
public Stream GetArtistPicture(String picture, Int32 artistId, ArtistPictureSize size)
{
var w = 750;
var h = 500;
if (!RestUtility.ParseImageSize(size.ToString(), out w, out h))
throw new ArgumentException("Invalid image size", "size");
String url = null;
if (!String.IsNullOrEmpty(picture))
url = String.Format("http://resources.wimpmusic.com/images/{0}/{1}x{2}.jpg", picture.Replace('-', '/'), w, h);
else
url = String.Format("http://images.tidalhifi.com/im/im?w={1}&h={2}&artistid={0}&noph", artistId, w, h);
return RestClient.GetStream(url);
}
<summary>
Helper method to retrieve a stream with a playlist image
</summary>
public Stream GetPlaylistImage(PlaylistModel model, PlaylistImageSize size)
{
return GetPlaylistImage(model.Image, model.Uuid, size);
}
<summary>
Helper method to retrieve a stream with a playlist image
</summary>
public Stream GetPlaylistImage(String image, String playlistUuid, PlaylistImageSize size)
{
var w = 750;
var h = 500;
if (!RestUtility.ParseImageSize(size.ToString(), out w, out h))
throw new ArgumentException("Invalid image size", "size");
String url = null;
if (!String.IsNullOrEmpty(image))
url = String.Format("http://resources.wimpmusic.com/images/{0}/{1}x{2}.jpg", image.Replace('-', '/'), w, h);
else
url = String.Format("http://images.tidalhifi.com/im/im?w={1}&h={2}&uuid={0}&rows=2&cols=3&noph", playlistUuid, w, h);
return RestClient.GetStream(url);
}
<summary>
Helper method to retrieve a stream with a video conver image
</summary>
public Stream GetVideoImage(VideoModel model, VideoImageSize size)
{
return GetVideoImage(model.ImageId, model.ImagePath, size);
}
<summary>
Helper method to retrieve a stream with a video conver image
</summary>
public Stream GetVideoImage(String imageId, String imagePath, VideoImageSize size)
{
var w = 750;
var h = 500;
if (!RestUtility.ParseImageSize(size.ToString(), out w, out h))
throw new ArgumentException("Invalid image size", "size");
String url = null;
if (!String.IsNullOrEmpty(imageId))
url = String.Format("http://resources.wimpmusic.com/images/{0}/{1}x{2}.jpg", imageId.Replace('-', '/'), w, h);
else
url = String.Format("http://images.tidalhifi.com/im/im?w={1}&h={2}&img={0}&noph", imagePath, w, h);
return RestClient.GetStream(url);
}
#endregion
#region track/video methods
<summary>
Helper method to retrieve the audio/video stream with correct user-agent, etc.
</summary>
public Stream GetStream(String streamUrl)
{
return RestClient.GetStream(streamUrl);
}
#endregion
}
} |
# -*- coding: utf-8 -*-
# Infrastructure
# No email
# This program is free software: you can redistribute it and/or modify
# published by the Free Software Foundation, either version 3 of the
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import re
from openerp import netsvc
from openerp.osv import osv, fields
class database_type(osv.osv):
_name = 'infrastructure.database_type'
_description = 'database_type'
_columns = {
'name': fields.char(string='Name', required=True),
'prefix': fields.char(string='Prefix', required=True, size=4),
'url_prefix': fields.char(string='URL Prefix'),
'automatic_drop': fields.boolean(string='Automatic Drop'),
'automatic_drop_days': fields.integer(string='Automatic Drop Days'),
'protect_db': fields.boolean(string='Protect DBs?'),
'color': fields.integer(string='Color'),
'<API key>': fields.boolean(string='Atumatic Deactivation?'),
'<API key>': fields.integer(string='Automatic Drop Days'),
'url_example': fields.char(string='URL Example'),
'bd_name_example': fields.char(string='BD Name Example'),
'<API key>': fields.many2many('infrastructure.db_back_up_policy', '<API key>', 'database_type_id', '<API key>', string='Suggested Backup Policies'),
}
_defaults = {
}
_constraints = [
]
database_type()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
<span ng-if="editable" class="omny-edit-section" ng-click="changeUrl()">Edit</span>
<iframe ng-if="videoSource" width="854" height="510" ng-src="{{videoSource}}" frameborder="0" allowfullscreen></iframe> |
# <API key>: true
require 'rails_helper'
describe StudentsController do
let(:user) { create(:student) }
before { allow(controller).to receive(:current_user) { user } }
it { should use_before_action :authorize! }
describe '#index' do
let!(:classroom) { create(:classroom) }
let!(:students_classrooms) { create(:students_classrooms, student_id: user.id, classroom_id: classroom.id) }
it 'should set the current user and js file' do
get :index
expect(assigns(:current_user)).to eq user
expect(assigns(:js_file)).to eq "student"
end
it 'should find the classroom and set flash' do
get :index, params: { joined: "success", classroom: classroom.id }
expect(flash["<API key>"]).to eq "You have joined #{classroom.name} "
end
end
describe '#join_classroom' do
let(:student) { create(:student) }
before { allow(controller).to receive(:current_user) { student } }
it 'should redirect for an invalid class_code' do
get :join_classroom, params: { classcode: '<API key>' }
expect(response).to redirect_to '/classes'
expect(flash[:error]).to match("Oops! There is no class with the code <API key>. Ask your teacher for help.")
end
it 'should redirect for a valid class_code' do
classroom = create(:classroom, code: 'existing_code')
get :join_classroom, params: { classcode: classroom.code }
expect(response).to redirect_to "/classrooms/#{classroom.id}?joined=success"
end
end
describe '#account_settings' do
it 'should set the current user and js file' do
get :account_settings
expect(assigns(:current_user)).to eq user
expect(assigns(:js_file)).to eq "student"
end
end
describe '#student_demo' do
context 'when Angie Thomas exists' do
let!(:angie) { create(:user, email: 'angie_thomas_demo@quill.org') }
it 'should sign in angie and redirect to profile' do
get :student_demo
expect(session[:user_id]).to eq angie.id
expect(response).to redirect_to '/classes'
end
end
context 'when angie thomas does not exist' do
it 'should destroy recreate the demo and redirect to student demo' do
expect(Demo::ReportDemoDestroyer).to receive(:destroy_demo).with(nil)
expect(Demo::ReportDemoCreator).to receive(:create_demo).with(nil)
get :student_demo
expect(response).to redirect_to "/student_demo"
end
end
end
describe '#student_demo_ap' do
context 'when bell hooks exists' do
let!(:bell) { create(:user, email: 'bell_hooks_demo@quill.org') }
it 'should sign in bell and redirect to profile' do
get :demo_ap
expect(session[:user_id]).to eq bell.id
expect(response).to redirect_to '/classes'
end
end
context 'when bell hooks does not exist' do
it 'should recreate the demo and redirect to student demo' do
expect(Demo::ReportDemoAPCreator).to receive(:create_demo).with(nil)
get :demo_ap
expect(response).to redirect_to "/student_demo_ap"
end
end
end
describe '#update_account' do
let!(:user) { create(:user, name: "Maya Angelou", email: 'maya_angelou_demo@quill.org', username: "maya-angelou", role: "student") }
let!(:second_user) { create(:user, name: "Harvey Milk", email: 'harvey@quill.org', username: "harvey-milk", role: "student") }
it 'should update the name, email and username' do
put :update_account, params: { email: "pablo@quill.org", username: "pabllo-vittar", name: "Pabllo Vittar" }
expect(user.reload.email).to eq "pablo@quill.org"
expect(user.reload.username).to eq "pabllo-vittar"
expect(user.reload.name).to eq "Pabllo Vittar"
end
it 'should update only the fields that are changed' do
put :update_account, params: { email: "pablo@quill.org", username: "rainha-do-carnaval", name: "Pabllo Vittar" }
expect(user.reload.email).to eq "pablo@quill.org"
expect(user.reload.username).to eq "rainha-do-carnaval"
expect(user.reload.name).to eq "Pabllo Vittar"
end
it 'should not update the email or username if already taken' do
put :update_account, params: { email: "harvey@quill.org", username: "pabllo-vittar", name: "Pabllo Vittar" }
expect(user.reload.errors.messages[:email].first).to eq "That email is taken. Try another."
put :update_account, params: { email: "pablo@quill.org", username: "harvey-milk", name: "Pabllo Vittar" }
expect(user.reload.errors.messages[:username].first).to eq "That username is taken. Try another."
end
end
end |
# <API key>: AGPL-3.0-or-later
"""
SepiaSearch (Videos)
"""
from json import loads
from dateutil import parser, relativedelta
from urllib.parse import urlencode
from datetime import datetime
# about
about = {
"website": 'https://sepiasearch.org',
"wikidata_id": None,
"<API key>": "https://framagit.org/framasoft/peertube/search-index/-/tree/master/server/controllers/api", # NOQA
"use_official_api": True,
"require_api_key": False,
"results": 'JSON',
}
categories = ['videos']
paging = True
time_range_support = True
safesearch = True
supported_languages = [
'en', 'fr', 'ja', 'eu', 'ca', 'cs', 'eo', 'el',
'de', 'it', 'nl', 'es', 'oc', 'gd', 'zh', 'pt',
'sv', 'pl', 'fi', 'ru'
]
base_url = 'https://sepiasearch.org/api/v1/search/videos'
safesearch_table = {
0: 'both',
1: 'false',
2: 'false'
}
time_range_table = {
'day': relativedelta.relativedelta(),
'week': relativedelta.relativedelta(weeks=-1),
'month': relativedelta.relativedelta(months=-1),
'year': relativedelta.relativedelta(years=-1)
}
embedded_url = '<iframe width="540" height="304" src="{url}" frameborder="0" allowfullscreen></iframe>'
def minute_to_hm(minute):
if isinstance(minute, int):
return "%d:%02d" % (divmod(minute, 60))
return None
def request(query, params):
params['url'] = base_url + '?' + urlencode({
'search': query,
'start': (params['pageno'] - 1) * 10,
'count': 10,
'sort': '-match',
'nsfw': safesearch_table[params['safesearch']]
})
language = params['language'].split('-')[0]
if language in supported_languages:
params['url'] += '&languageOneOf[]=' + language
if params['time_range'] in time_range_table:
time = datetime.now().date() + time_range_table[params['time_range']]
params['url'] += '&startDate=' + time.isoformat()
return params
def response(resp):
results = []
search_results = loads(resp.text)
if 'data' not in search_results:
return []
for result in search_results['data']:
title = result['name']
content = result['description']
thumbnail = result['thumbnailUrl']
publishedDate = parser.parse(result['publishedAt'])
embedded = embedded_url.format(url=result.get('embedUrl'))
author = result.get('account', {}).get('displayName')
length = minute_to_hm(result.get('duration'))
url = result['url']
results.append({'url': url,
'title': title,
'content': content,
'author': author,
'length': length,
'template': 'videos.html',
'publishedDate': publishedDate,
'embedded': embedded,
'thumbnail': thumbnail})
return results |
<?php
class IPFS {
function foo(){
return 'bar';
}
function cat($hash){
$gotData = '';
$server = curl_init();
curl_setopt($server, CURLOPT_URL, 'http://127.0.0.1:5001/api/v0/cat?arg=' . $hash);
curl_setopt($server, <API key>, true);
curl_setopt($server, <API key>, false);
$gotData = curl_exec($server);
curl_close($server);
return $gotData;
}
function resolve($name){
$gotData = '';
$json = '';
$server = curl_init();
curl_setopt($server, CURLOPT_URL, 'http://127.0.0.1:5001/api/v0/name/resolve?arg=' . $name);
curl_setopt($server, <API key>, true);
$gotData = curl_exec($server);
$gotData = json_decode($gotData, true);
if (isset($gotData['Path'])){
$gotData = str_replace('/ipfs/', '', $gotData['Path']);
}
else{
$gotData = 'invalid';
}
curl_close($server);
return $gotData;
}
function dataAdd($file){
$gotData = '';
$server = curl_init();
curl_setopt($server, CURLOPT_POST, 1);
curl_setopt($server, <API key>, true);
$data = array('file' => new CurlFile($file));
curl_setopt($server, CURLOPT_SAFE_UPLOAD, false); // required as of PHP 5.6.0
curl_setopt($server, CURLOPT_POSTFIELDS, $data);
curl_setopt($server, CURLOPT_URL, 'http://127.0.0.1:5001/api/v0/add');
$data = curl_exec($server);
curl_close($server);
return $data;
}
function namePublish($data) {
$server = curl_init();
$data = dataAdd($data);
curl_setopt($server, CURLOPT_URL, 'http://127.0.0.1:5001/api/v0/name/publish?arg=' . $data . '&lifetime=1m&');
curl_exec($server);
curl_close($server);
return true;
}
}
?> |
import React from 'react';
import { render, waitForElement } from '<API key>';
import FakeDataProvider from '@olimat/web/utils/test/FakeDataProvider';
import MockErrorProvider from '@olimat/web/utils/test/MockErrorProvider';
import MockNextContext from '@olimat/web/utils/test/MockNextContext';
import { renderApollo } from '@olimat/web/utils/test/test-utils';
import ExamDetails from './Details';
const MockExamDetails = () => (
<MockNextContext router={{ query: { id: 'theExamId1' } }}>
<ExamDetails />
</MockNextContext>
);
describe('<ExamDetails />', () => {
test.skip('renders loading state initially', () => {
const { getByText } = renderApollo(<MockExamDetails />);
getByText(/loading/i);
});
test('renders the details of an exam', async () => {
const customResolvers = {
// We need to update the GraphQL API as well
Exam: () => ({
title: '2017 - Fase 3 - Ano 5',
}),
};
const { getByText, getByTestId } = render(
<FakeDataProvider customResolvers={customResolvers}>
<MockExamDetails />
</FakeDataProvider>,
);
await waitForElement(() => getByText(customResolvers.Exam().title));
const questionListNode = getByTestId('questionList');
expect(questionListNode).toBeInTheDocument();
// toBe(10) couples the test with the mocked server
expect(questionListNode.children.length).toBe(10);
});
test('renders error message', async () => {
const errorMsg = 'Que pena';
const { getByText } = render(
<MockErrorProvider graphqlErrors={[{ message: errorMsg }]}>
<MockExamDetails />
</MockErrorProvider>,
);
await waitForElement(() => getByText(errorMsg, { exact: false }));
});
}); |
<?php
// This file declares a new entity type. For more details, see "<API key>" at:
return [
[
'name' => 'CivirulesLog',
'class' => '<API key>',
'table' => '<API key>',
],
]; |
{% extends "podcast-base.html" %}
{% load i18n %}
{% load humanize %}
{% load episodes %}
{% load podcasts %}
{% load devices %}
{% load charts %}
{% load utils %}
{% load menu %}
{% block mainmenu %}{{ "/podcast/"|main_menu }}{% endblock %}
{% block sectionmenu %}
{% if podcast.title %}
{{ "/podcast/"|section_menu:podcast.title }}
{% else %}
{{ "/podcast/"|section_menu:"Unnamed Podcast" }}
{% endif %}
{% endblock %}
{% block title %}{{ podcast.title|default:"Unnamed Podcast"|striptags }}{% endblock %}
{% block content %}
{% if episode %}
<div class="first-episode">
{% include "components/episode-box.html" with podcast=podcast episode=episode long=True only %}
</div>
{% endif %}
<hr />
<div class="btn-toolbar">
{% if is_publisher %}
<div class="btn-group">
<a class="btn btn-default" href="{% podcast_link_target podcast "<API key>" %}">
<i class="icon-wrench"></i>
{% trans "Publisher Pages" %}
</a>
</div>
{% endif %}
{% if not user.is_authenticated %}
<div class="btn-group">
<a class="btn btn-default" href="{% podcast_link_target podcast "subscribe" %}">
<i class="icon-plus"></i>
{% trans "Login to Subscribe" %}
</a>
</div>
{% endif %}
{% if devices or can_subscribe %}
<div class="btn-group">
{% if can_subscribe %}
<button class="btn btn-primary" onclick="submitForm('subscribe+all');">
<i class="icon-plus-sign"></i>
{% trans "Subscribe" %}
</button>
<button class="btn dropdown-toggle btn-primary" data-toggle="dropdown">
<span class="caret"></span>
</button>
{% else %}
<button class="btn btn-default" onclick="submitForm('unsubscribe+all');">
<i class="icon-remove-sign"></i>
{% trans "Unsubscribe" %}
</button>
<button class="btn dropdown-toggle btn-default" data-toggle="dropdown">
<span class="caret"></span>
</button>
{% endif %}
<ul class="dropdown-menu">
{% if can_subscribe %}
<li value="+all">
<a href="javascript:void(0);" onclick="submitForm('subscribe+all');">
<i class="icon-plus-sign"></i>
{% trans "Subscribe on all devices" %}
</a>
<form class="internal"
method="post"
action="{% podcast_link_target podcast "subscribe-all" %}"
id="subscribe+all">
{% csrf_token %}
</form>
</li>
{% endif %}
{% for device in subscribe_targets %}
<li value="{{ device.uid }}">
<a href="javascript:void(0);" onclick="submitForm('subscribe-{{ device|devices_uids }}');">
<i class="icon-plus"></i>
{{ device|devices_name }}
</a>
<form class="internal"
action="{% podcast_link_target podcast "subscribe" %}"
method="post"
id="subscribe-{{ device|devices_uids }}">
{% csrf_token %}
<input type="hidden" name="targets" value="{{ device|devices_uids }}" />
</form>
</li>
{% endfor %}
{% if can_subscribe and devices %}
<li class="divider"></li>
{% endif %}
{% if devices %}
<li value="+none">
<a href="javascript:void(0);" onclick="submitForm('unsubscribe+all');">
<i class="icon-remove-sign"></i>
{% trans "Unsubscribe from all devices " %}
</a>
<form class="internal"
method="post"
action="{% podcast_link_target podcast "unsubscribe-all" %}"
id="unsubscribe+all">
{% csrf_token %}
</form>
</li>
{% endif %}
{% for device in devices %}
<li value="{{ device.uid }}">
<a href="javascript:void(0);" onclick="submitForm('unsubscribe-{{ device.uid }}');">
<i class="icon-remove"></i>
{{ device|devices_name }}
</a>
<form class="internal"
method="post"
action="{% podcast_link_target podcast "unsubscribe" device.uid %}?return_to={% podcast_link_target podcast %}"
id="unsubscribe-{{ device.uid }}">
{% csrf_token %}
</form>
</li>
{% endfor %}
</ul>
</div>
{% endif %}
{% if has_history %}
<a class="btn btn-default" href="{% podcast_link_target podcast "podcast-history" %}">
<i class="icon-calendar"></i>
{% trans "Subscription History" %}
</a>
{% endif %}
<a href="javascript:void(0);" onclick="$('#tag-box').toggle();" class="btn btn-default">
<i class="icon-tag"></i>
{% trans "Tags" %}
</a>
{% if user.is_staff %}
<a class="btn btn-default" href="{% edit_link podcast %}">
<i class="icon-cogs"></i>Admin
</a>
{% endif %}
</div>
<div id="tag-box">
<hr />
<i class="icon-tag"></i>
<strong>{% trans "Tags" %}: </strong>
{% for tag in tags %}
{% spaceless %}
{% if tag.is_own %}
<span class="own">{{ tag.tag }} <a class="remove" href="{% podcast_link_target podcast "remove-tag" %}?tag={{ tag.tag }}">X</a></span>
{% else %}
<span class="other">{{ tag.tag }}</span>
{% endif %}
{% if not forloop.last %}
<span class="seperator">,</span>
{% endif %}
{% endspaceless %}
{% endfor %}
{% if user.is_authenticated %}
<form class="form-inline" action="{% podcast_link_target podcast "add-tag" %}">
<div class="input-group">
<span class="input-group-addon input-sm"><i class="icon-tag"></i></span>
<input class="input-sm form-control" type="text" name="tag" />
<span class="input-group-btn">
<button class="btn btn-success btn-sm" type="submit">
<i class="icon-plus"></i>
</button>
</span>
</div>
</form>
{% endif %}
</div>
<hr />
{% if episodes %}
<h3>{% trans "Older Episodes" %}</h3>
<div class="episodes">
{% for episode in episodes %}
{% include "components/episode-box.html" with episode=episode podcast=podcast only %}
{% endfor %}
</div>
<ul class="pagination">
{% for page in page_list %}
<li>
{% if page == "..." %}
<span>{{ page }}</span>
{% else %}
{% if page == current_page %}
<a href="{% podcast_link_target podcast "<API key>" %}?page={{ page }}"><strong>{{ page }}</strong></a>
{% else %}
<a href="{% podcast_link_target podcast "<API key>" %}?page={{ page }}">{{ page }}</a>
{% endif %}
{% endif %}
</li>
{% endfor %}
</ul>
{% endif %}
{% endblock %}
{% block javascript %}
{{ block.super }}
<script language="javascript">
<!
function submitForm(formid)
{
document.forms[formid].submit();
return true;
}
{% if not has_tagged %}
// done in JS so that box is always visible if JS is disabled
$('#tag-box').toggle();
{% endif %}
</script>
{% endblock %} |
/*
Classe gerada automaticamente pelo MSTech Code Creator
*/
namespace MSTech.GestaoEscolar.BLL
{
using MSTech.Business.Common;
using MSTech.GestaoEscolar.Entities;
using MSTech.GestaoEscolar.DAL;
using System.Data;
using MSTech.Data.Common;
using System.Collections.Generic;
using System.Linq;
using MSTech.Validation.Exceptions;
<summary>
Description: <API key> Business Object.
</summary>
public class <API key> : BusinessBase<<API key>, <API key>>
{
#region Consultas
<summary>
Seleciona os tipo de qualidade por matrícula do aluno.
</summary>
<param name="tur_id">ID da turma.</param>
<param name="alu_id">ID do aluno.</param>
<param name="mtu_id">ID da matrícula turma do aluno.</param>
<param name="fav_id">ID do formato de avaliação.</param>
<param name="ava_id">ID da avaliação.</param>
<returns></returns>
public static DataTable <API key>(long tur_id, long alu_id, int mtu_id, int fav_id, int ava_id)
{
return new <API key>().<API key>(tur_id, alu_id, mtu_id, fav_id, ava_id);
}
<summary>
Seleciona uma lista de tipo de qualidade por matrícula do aluno.
</summary>
<param name="tur_id">ID da turma.</param>
<param name="alu_id">ID do aluno.</param>
<param name="mtu_id">ID da matrícula turma do aluno.</param>
<param name="fav_id">ID do formato de avaliação.</param>
<param name="ava_id">ID da avaliação.</param>
<returns></returns>
public static List<<API key>> <API key>(long tur_id, long alu_id, int mtu_id, int fav_id, int ava_id, TalkDBTransaction banco = null)
{
<API key> dao = banco == null ?
new <API key>() :
new <API key> { _Banco = banco };
return (from DataRow dr in dao.<API key>(tur_id, alu_id, mtu_id, fav_id, ava_id).Rows
select dao.DataRowToEntity(dr, new <API key>())).ToList();
}
#endregion
#region Saves
<summary>
O método salva as qualidade cadastradas para o aluno e deleta as que forem desmarcadas.
</summary>
<param name="tur_id">ID da turma.</param>
<param name="alu_id">ID do aluno.</param>
<param name="mtu_id">ID da matrícula turma do aluno.</param>
<param name="fav_id">ID do formato de avaliação.</param>
<param name="ava_id">ID da avaliação.</param>
<param name="lista">Lista de qualidades adicionadas</param>
<param name="banco"></param>
<returns></returns>
public static bool Salvar(long tur_id, long alu_id, int mtu_id, int fav_id, int ava_id, List<<API key>> lista, TalkDBTransaction banco)
{
bool retorno = true;
List<<API key>> listaCadastrados = <API key>(tur_id, alu_id, mtu_id, fav_id, ava_id, banco);
if (lista.Any())
{
List<<API key>> listaExcluir = !listaCadastrados.Any() ?
new List<<API key>>() : listaCadastrados.Where(p => !lista.Contains(p)).ToList();
List<<API key>> listaSalvar = listaCadastrados.Any() ?
lista.Where(p => !listaCadastrados.Contains(p)).ToList() : lista;
retorno &= !listaExcluir.Any() ? retorno : listaExcluir.Aggregate(true, (excluiu, qualidade) => excluiu & Delete(qualidade, banco));
retorno &= !listaSalvar.Any() ? retorno : listaSalvar.Aggregate(true, (salvou, qualidade) => salvou & Save(qualidade, banco));
}
else
{
retorno &= !listaCadastrados.Any() ? retorno : listaCadastrados.Aggregate(true, (excluiu, qualidade) => excluiu & Delete(qualidade, banco));
}
return retorno;
}
<summary>
O método salva um registro na tabela <API key>.
</summary>
<param name="entity">Entidade <API key></param>
<param name="banco"></param>
<returns></returns>
public static new bool Save(<API key> entity, TalkDBTransaction banco)
{
if (entity.Validate())
{
return new <API key> { _Banco = banco }.Salvar(entity);
}
throw new ValidationException(GestaoEscolarUtilBO.ErrosValidacao(entity));
}
<summary>
O método salva um registro na tabela <API key>.
</summary>
<param name="entity">Entidade <API key></param>
<returns></returns>
public static new bool Save(<API key> entity)
{
if (entity.Validate())
{
return new <API key>().Salvar(entity);
}
throw new ValidationException(GestaoEscolarUtilBO.ErrosValidacao(entity));
}
#endregion
}
} |
module Laser
# Class that's just a name. Substitute for symbols, which can overlap
# with user-code values.
class PlaceholderObject
def initialize(name)
@name = name
end
def inspect
@name
end
alias_method :to_s, :inspect
end
end |
#ifndef <API key>
#define <API key>
#include <asn_application.h>
/* Including external dependencies */
#include <NULL.h>
#include <constr_CHOICE.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Dependencies */
typedef enum <API key> {
<API key>, /* No components present */
<API key>
/* Extensions may appear below */
} <API key>;
/* <API key> */
typedef struct <API key> {
<API key> present;
union <API key> {
NULL_t undefined;
/*
* This type is extensible,
* possible extensions are below.
*/
} choice;
/* Context for parsing across buffer boundaries */
asn_struct_ctx_t _asn_ctx;
} <API key>;
/* Implementation */
extern <API key> <API key>;
extern <API key> <API key>;
extern asn_TYPE_member_t <API key>[1];
extern <API key> <API key>;
#ifdef __cplusplus
}
#endif
#endif /* <API key> */
#include <asn_internal.h> |
package org.neo4j.graphdb.index;
import java.util.Iterator;
import java.util.<API key>;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.Transaction;
/**
* An {@link Iterator} with additional {@link #size()} and {@link #close()}
* methods on it, used for iterating over index query results. It is first and
* foremost an {@link Iterator}, but also an {@link Iterable} JUST so that it
* can be used in a for-each loop. The <code>iterator()</code> method
* <i>always</i> returns <code>this</code>.
*
* The size is calculated before-hand so that calling it is always fast.
*
* When you're done with the result and haven't reached the end of the
* iteration {@link #close()} must be called. Results which are looped through
* entirely closes automatically. Typical use:
*
* <pre>
* IndexHits<Node> hits = index.get( "key", "value" );
* try
* {
* for ( Node node : hits )
* {
* // do something with the hit
* }
* }
* finally
* {
* hits.close();
* }
* </pre>
*
* @param <T> the type of items in the Iterator.
*/
public interface IndexHits<T> extends Iterator<T>, Iterable<T>
{
/**
* Returns the size of this iterable, in most scenarios this value is accurate
* while in some scenarios near-accurate.
*
* There's no cost in calling this method. It's considered near-accurate if this
* {@link IndexHits} object has been returned when inside a {@link Transaction}
* which has index modifications, of a certain nature. Also entities
* ({@link Node}s/{@link Relationship}s) which have been deleted from the graph,
* but are still in the index will also affect the accuracy of the returned size.
*
* @return the near-accurate size if this iterable.
*/
int size();
/**
* Closes the underlying search result. This method should be called
* whenever you've got what you wanted from the result and won't use it
* anymore. It's necessary to call it so that underlying indexes can dispose
* of allocated resources for this search result.
*
* You can however skip to call this method if you loop through the whole
* result, then close() will be called automatically. Even if you loop
* through the entire result and then call this method it will silently
* ignore any consequtive call (for convenience).
*/
void close();
/**
* Returns the first and only item from the result iterator, or {@code null}
* if there was none. If there were more than one item in the result a
* {@link <API key>} will be thrown. This method must be called
* first in the iteration and will grab the first item from the iteration,
* so the result is considered broken after this call.
*
* @return the first and only item, or {@code null} if none.
*/
T getSingle();
/**
* Returns the score of the most recently fetched item from this iterator
* (from {@link #next()}). The range of the returned values is up to the
* {@link Index} implementation to dictate.
* @return the score of the most recently fetched item from this iterator.
*/
float currentScore();
} |
import { createSlice, createEntityAdapter, Reducer, AnyAction, PayloadAction } from '@reduxjs/toolkit';
import { fetchAll, fetchDetails, install, uninstall, <API key>, panelPluginLoaded } from './actions';
import { CatalogPlugin, <API key>, ReducerState, RequestStatus } from '../types';
import { STATE_PREFIX } from '../constants';
import { PanelPlugin } from '@grafana/data';
export const pluginsAdapter = createEntityAdapter<CatalogPlugin>();
const isPendingRequest = (action: AnyAction) => new RegExp(`${STATE_PREFIX}\/(.*)\/pending`).test(action.type);
const isFulfilledRequest = (action: AnyAction) => new RegExp(`${STATE_PREFIX}\/(.*)\/fulfilled`).test(action.type);
const isRejectedRequest = (action: AnyAction) => new RegExp(`${STATE_PREFIX}\/(.*)\/rejected`).test(action.type);
// Extract the trailing '/pending', '/rejected', or '/fulfilled'
const <API key> = (type: string) => {
const separator = type.lastIndexOf('/');
return type.substring(0, separator);
};
const slice = createSlice({
name: 'plugins',
initialState: {
items: pluginsAdapter.getInitialState(),
requests: {},
settings: {
displayMode: <API key>.Grid,
},
// Backwards compatibility
// (we need to have the following fields in the store as well to be backwards compatible with other parts of Grafana)
// TODO<remove once the "<API key>" feature flag is removed>
plugins: [],
errors: [],
searchQuery: '',
hasFetched: false,
dashboards: [],
<API key>: false,
panels: {},
} as ReducerState,
reducers: {
setDisplayMode(state, action: PayloadAction<<API key>>) {
state.settings.displayMode = action.payload;
},
},
extraReducers: (builder) =>
builder
// Fetch All
.addCase(fetchAll.fulfilled, (state, action) => {
pluginsAdapter.upsertMany(state.items, action.payload);
})
// Fetch Details
.addCase(fetchDetails.fulfilled, (state, action) => {
pluginsAdapter.updateOne(state.items, action.payload);
})
// Install
.addCase(install.fulfilled, (state, action) => {
pluginsAdapter.updateOne(state.items, action.payload);
})
// Uninstall
.addCase(uninstall.fulfilled, (state, action) => {
pluginsAdapter.updateOne(state.items, action.payload);
})
// Load a panel plugin (<API key>)
// TODO<remove once the "<API key>" feature flag is removed>
.addCase(panelPluginLoaded, (state, action: PayloadAction<PanelPlugin>) => {
state.panels[action.payload.meta.id] = action.payload;
})
// Start loading panel dashboards (<API key>)
// TODO<remove once the "<API key>" feature flag is removed>
.addCase(<API key>.pending, (state, action) => {
state.<API key> = true;
state.dashboards = [];
})
// Load panel dashboards (<API key>)
// TODO<remove once the "<API key>" feature flag is removed>
.addCase(<API key>.fulfilled, (state, action) => {
state.<API key> = false;
state.dashboards = action.payload;
})
.addMatcher(isPendingRequest, (state, action) => {
state.requests[<API key>(action.type)] = {
status: RequestStatus.Pending,
};
})
.addMatcher(isFulfilledRequest, (state, action) => {
state.requests[<API key>(action.type)] = {
status: RequestStatus.Fulfilled,
};
})
.addMatcher(isRejectedRequest, (state, action) => {
state.requests[<API key>(action.type)] = {
status: RequestStatus.Rejected,
error: action.payload,
};
}),
});
export const { setDisplayMode } = slice.actions;
export const reducer: Reducer<ReducerState, AnyAction> = slice.reducer; |
# -*- coding: utf-8 -*-
# <API key>: 2013-2021 Agora Voting SL <contact@nvotes.com>
# <API key>: AGPL-3.0-only
import pickle
import base64
import json
import re
from datetime import datetime
from flask import Blueprint, request, make_response, abort
from frestq.utils import loads, dumps
from frestq.tasks import SimpleTask, TaskError
from frestq.app import app, db
from models import Election, Authority, QueryQueue
from create_election.performer_jobs import check_election_data
from taskqueue import queue_task, apply_task, dequeue_task
public_api = Blueprint('public_api', __name__)
def error(status, message=""):
if message:
data = json.dumps(dict(message=message))
else:
data=""
return make_response(data, status)
@public_api.route('/dequeue', methods=['GET'])
def dequeue():
try:
dequeue_task()
except Exception as e:
return make_response(dumps(dict(status=e.message)), 202)
return make_response(dumps(dict(status="ok")), 202)
@public_api.route('/election', methods=['POST'])
def post_election():
data = request.get_json(force=True, silent=True)
d = base64.b64encode(pickle.dumps(data)).decode('utf-8')
queueid = queue_task(task='election', data=d)
return make_response(dumps(dict(queue_id=queueid)), 202)
@public_api.route('/tally', methods=['POST'])
def post_tally():
# first of all, parse input data
data = request.get_json(force=True, silent=True)
d = base64.b64encode(pickle.dumps(data)).decode('utf-8')
queueid = queue_task(task='tally', data=d)
return make_response(dumps(dict(queue_id=queueid)), 202)
@public_api.route('/receive_election', methods=['POST'])
def receive_election():
'''
This is a test route to be able to test that callbacks are correctly sent
'''
print("ATTENTION received election callback: ")
print(request.get_json(force=True, silent=True))
return make_response("", 202)
@public_api.route('/receive_tally', methods=['POST'])
def receive_tally():
'''
This is a test route to be able to test that callbacks are correctly sent
'''
print("ATTENTION received tally callback: ")
print(request.get_json(force=True, silent=True))
return make_response("", 202) |
class ReportsController < <API key>
<API key>
def expenses
@filter = params[:filter]
if (@type = params[:by_type]) && (@group = params[:by_group])
@expenses = ExpenseReport.by(@type, @group).accessible_by(current_ability)
if @filter
@filter.each { |k,v| @expenses = @expenses.send(k, v) unless v.blank? }
end
@expenses = @expenses.order("sum_amount desc")
respond_to do |format|
format.html {
init_form
@expenses = @expenses.page(params[:page] || 1).per(20)
}
format.xlsx { render :xlsx => "expenses", :disposition => "attachment", :filename => "expenses.xlsx" }
end
else
respond_to do |format|
format.html { init_form }
format.xlsx { redirect_to <API key>(:format => :html) }
end
end
end
protected
def init_form
@by_type_options = %w(estimated approved total authorized)
@by_group_options = ExpenseReport.groups.map(&:to_s)
#@events = Event.order(:name)
@request_states = Request.state_machines[:state].states.map {|s| [ s.value, s.human_name] }
@<API key> = Reimbursement.state_machines[:state].states.map {|s| [ s.value, s.human_name] }
@countries = I18n.t(:countries).map {|k,v| [k.to_s,v]}.sort_by(&:last)
end
def set_breadcrumbs
@breadcrumbs = [{:label => :breadcrumb_reports}]
end
end |
package com.telefonica.claudia.smi.deployment;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.<API key>;
import javax.xml.parsers.<API key>;
import org.apache.log4j.Logger;
import org.restlet.Context;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Status;
import org.restlet.resource.DomRepresentation;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.restlet.resource.ResourceException;
import org.restlet.resource.Variant;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.telefonica.claudia.smi.Main;
import com.telefonica.claudia.smi.URICreation;
public class ServiceItemResource extends Resource {
private static Logger log = Logger.getLogger("com.telefonica.claudia.smi.ServiceItemResource");
String vdcId;
String vappId;
String orgId;
public ServiceItemResource(Context context, Request request, Response response) {
super(context, request, response);
this.vappId = (String) getRequest().getAttributes().get("vapp-id");
this.vdcId = (String) getRequest().getAttributes().get("vdc-id");
this.orgId = (String) getRequest().getAttributes().get("org-id");
// Get the item directly from the "persistence layer".
if (this.orgId != null && this.vdcId!=null && this.vappId!=null) {
// Define the supported variant.
getVariants().add(new Variant(MediaType.TEXT_XML));
// By default a resource cannot be updated.
setModifiable(true);
} else {
// This resource is not available.
setAvailable(false);
}
}
/**
* Handle GETS
*/
@Override
public Representation represent(Variant variant) throws ResourceException {
// Generate the right representation according to its media type.
if (MediaType.TEXT_XML.equals(variant.getMediaType())) {
try {
DeploymentDriver actualDriver= (DeploymentDriver) getContext().getAttributes().get(<API key>.<API key>);
String serviceInfo = actualDriver.getService(URICreation.getFQN(orgId, vdcId, vappId));
// Substitute the macros in the description
serviceInfo = serviceInfo.replace("@HOSTNAME", "http://" + Main.serverHost + ":" + Main.serverPort);
if (serviceInfo==null) {
log.error("Null response from the SM.");
getResponse().setStatus(Status.<API key>);
return null;
}
<API key> dbf =
<API key>.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(serviceInfo));
Document doc = db.parse(is);
DomRepresentation representation = new DomRepresentation(
MediaType.TEXT_XML, doc);
log.info("Data returned for service "+ URICreation.getFQN(orgId, vdcId, vappId) + ": \n\n" + serviceInfo);
// Returns the XML representation of this document.
return representation;
} catch (IOException e) {
log.error("Time out waiting for the Lifecycle Controller.");
getResponse().setStatus(Status.<API key>);
return null;
} catch (SAXException e) {
log.error("Retrieved data was not in XML format: " + e.getMessage());
getResponse().setStatus(Status.<API key>);
return null;
} catch (<API key> e) {
log.error("Error trying to configure parser.");
getResponse().setStatus(Status.<API key>);
return null;
}
}
return null;
}
/**
* Handle DELETE requests.
*/
@Override
public void <API key>() throws ResourceException {
DeploymentDriver actualDriver= (DeploymentDriver) getContext().getAttributes().get(<API key>.<API key>);
try {
actualDriver.undeploy(URICreation.getFQN(orgId, vdcId, vappId));
} catch (IOException e) {
log.error("Time out waiting for the Lifecycle Controller.");
getResponse().setStatus(Status.<API key>);
return;
}
// Tells the client that the request has been successfully fulfilled.
getResponse().setStatus(Status.SUCCESS_NO_CONTENT);
}
} |
layout: post
title: "All Star Wars, all the time"
date: 2013-04-15 00:00:00 +0900
categories: linux-foundation comics

This comic originally appeared on [linux.com](https:
For those of you who have just come back from Antarctica and haven't seen the 6 Panel Star Wars yet, go take a look!
It's almost worth having to sit through Jar Jar as you can just ignore that panel every time he comes on.
Also, before any die hard fans point it out, we are aware that [Aqualish](http://starwars.wikia.com/wiki/Aqualish) only have 2 or 4 eyes, not 6, but 6 just fits the theme better. |
DELETE FROM `weenie` WHERE `class_Id` = 14289;
INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`)
VALUES (14289, 'portalvillalabar', 7, '2019-02-10 00:00:00') /* Portal */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (14289, 1, 65536) /* ItemType - Portal */
, (14289, 16, 32) /* ItemUseable - Remote */
, (14289, 93, 3084) /* PhysicsState - Ethereal, ReportCollisions, Gravity, LightingOn */
, (14289, 111, 1) /* PortalBitmask - Unrestricted */
, (14289, 133, 4) /* ShowableOnRadar - ShowAlways */
, (14289, 8007, 0) /* <API key> */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (14289, 1, True ) /* Stuck */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (14289, 54, -0.1) /* UseRadius */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (14289, 1, 'Villalabar Portal') /* Name */
, (14289, 8006, 'AAA9AAAAAAA=') /* <API key> */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (14289, 1, 0x020001B3) /* Setup */
, (14289, 2, 0x09000003) /* MotionTable */
, (14289, 8, 0x0600106B) /* Icon */
, (14289, 8001, 8388656) /* <API key> - Usable, UseRadius, RadarBehavior */
, (14289, 8003, 262164) /* <API key> - Stuck, Attackable, Portal */
, (14289, 8005, 98307) /* <API key> - CSetup, MTable, Position, Movement */;
INSERT INTO `<API key>` (`object_Id`, `position_Type`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`)
VALUES (14289, 8040, 0x9521002F, 139.109, 166.067, 122.4202, 0.001375, 0, 0, -0.999999) /* <API key> */
/* @teleloc 0x9521002F [139.109000 166.067000 122.420200] 0.001375 0.000000 0.000000 -0.999999 */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (14289, 8000, 0x79521002) /* <API key> */; |
package v4_test
import (
"encoding/json"
"net/http"
"time"
jc "github.com/juju/testing/checkers"
"github.com/juju/testing/httptesting"
"github.com/juju/utils/debugstatus"
gc "gopkg.in/check.v1"
"gopkg.in/juju/charm.v5"
"gopkg.in/juju/charmstore.v4/internal/mongodoc"
"gopkg.in/juju/charmstore.v4/internal/router"
"gopkg.in/juju/charmstore.v4/params"
)
var zeroTimeStr = time.Time{}.Format(time.RFC3339)
func (s *APISuite) TestStatus(c *gc.C) {
for _, id := range []*router.ResolvedURL{
newResolvedURL("cs:~charmers/precise/wordpress-2", 2),
newResolvedURL("cs:~charmers/precise/wordpress-3", 3),
newResolvedURL("cs:~foo/precise/arble-9", -1),
newResolvedURL("cs:~bar/utopic/arble-10", -1),
newResolvedURL("cs:~charmers/bundle/oflaughs-3", 3),
newResolvedURL("cs:~bar/bundle/oflaughs-4", -1),
} {
if id.URL.Series == "bundle" {
s.addPublicBundle(c, "wordpress-simple", id)
} else {
s.addPublicCharm(c, "wordpress", id)
}
}
now := time.Now()
s.PatchValue(&debugstatus.StartTime, now)
start := now.Add(-2 * time.Hour)
s.addLog(c, &mongodoc.Log{
Data: []byte(`"ingestion started"`),
Level: mongodoc.InfoLevel,
Type: mongodoc.IngestionType,
Time: start,
})
end := now.Add(-1 * time.Hour)
s.addLog(c, &mongodoc.Log{
Data: []byte(`"ingestion completed"`),
Level: mongodoc.InfoLevel,
Type: mongodoc.IngestionType,
Time: end,
})
statisticsStart := now.Add(-1*time.Hour - 30*time.Minute)
s.addLog(c, &mongodoc.Log{
Data: []byte(`"legacy statistics import started"`),
Level: mongodoc.InfoLevel,
Type: mongodoc.<API key>,
Time: statisticsStart,
})
statisticsEnd := now.Add(-30 * time.Minute)
s.addLog(c, &mongodoc.Log{
Data: []byte(`"legacy statistics import completed"`),
Level: mongodoc.InfoLevel,
Type: mongodoc.<API key>,
Time: statisticsEnd,
})
s.AssertDebugStatus(c, true, map[string]params.DebugStatus{
"mongo_connected": {
Name: "MongoDB is connected",
Value: "Connected",
Passed: true,
},
"mongo_collections": {
Name: "MongoDB collections",
Value: "All required collections exist",
Passed: true,
},
"elasticsearch": {
Name: "Elastic search is running",
Value: "Elastic search is not configured",
Passed: true,
},
"entities": {
Name: "Entities in charm store",
Value: "4 charms; 2 bundles; 3 promulgated",
Passed: true,
},
"base_entities": {
Name: "Base entities in charm store",
Value: "count: 5",
Passed: true,
},
"server_started": {
Name: "Server started",
Value: now.String(),
Passed: true,
},
"ingestion": {
Name: "Ingestion",
Value: "started: " + start.Format(time.RFC3339) + ", completed: " + end.Format(time.RFC3339),
Passed: true,
},
"legacy_statistics": {
Name: "Legacy Statistics Load",
Value: "started: " + statisticsStart.Format(time.RFC3339) + ", completed: " + statisticsEnd.Format(time.RFC3339),
Passed: true,
},
})
}
func (s *APISuite) <API key>(c *gc.C) {
s.store.DB.Entities().DropCollection()
s.AssertDebugStatus(c, false, map[string]params.DebugStatus{
"mongo_collections": {
Name: "MongoDB collections",
Value: "Missing collections: [" + s.store.DB.Entities().Name + "]",
Passed: false,
},
})
}
func (s *APISuite) <API key>(c *gc.C) {
s.AssertDebugStatus(c, false, map[string]params.DebugStatus{
"ingestion": {
Name: "Ingestion",
Value: "started: " + zeroTimeStr + ", completed: " + zeroTimeStr,
Passed: false,
},
})
}
func (s *APISuite) <API key>(c *gc.C) {
now := time.Now()
start := now.Add(-1 * time.Hour)
s.addLog(c, &mongodoc.Log{
Data: []byte(`"ingestion started"`),
Level: mongodoc.InfoLevel,
Type: mongodoc.IngestionType,
Time: start,
})
s.AssertDebugStatus(c, false, map[string]params.DebugStatus{
"ingestion": {
Name: "Ingestion",
Value: "started: " + start.Format(time.RFC3339) + ", completed: " + zeroTimeStr,
Passed: false,
},
})
}
func (s *APISuite) <API key>(c *gc.C) {
s.AssertDebugStatus(c, false, map[string]params.DebugStatus{
"legacy_statistics": {
Name: "Legacy Statistics Load",
Value: "started: " + zeroTimeStr + ", completed: " + zeroTimeStr,
Passed: false,
},
})
}
func (s *APISuite) <API key>(c *gc.C) {
now := time.Now()
statisticsStart := now.Add(-1*time.Hour - 30*time.Minute)
s.addLog(c, &mongodoc.Log{
Data: []byte(`"legacy statistics import started"`),
Level: mongodoc.InfoLevel,
Type: mongodoc.<API key>,
Time: statisticsStart,
})
s.AssertDebugStatus(c, false, map[string]params.DebugStatus{
"legacy_statistics": {
Name: "Legacy Statistics Load",
Value: "started: " + statisticsStart.Format(time.RFC3339) + ", completed: " + zeroTimeStr,
Passed: false,
},
})
}
func (s *APISuite) <API key>(c *gc.C) {
now := time.Now()
statisticsStart := now.Add(-1*time.Hour - 30*time.Minute)
s.addLog(c, &mongodoc.Log{
Data: []byte(`"legacy statistics import started"`),
Level: mongodoc.InfoLevel,
Type: mongodoc.<API key>,
Time: statisticsStart.Add(-1 * time.Hour),
})
s.addLog(c, &mongodoc.Log{
Data: []byte(`"legacy statistics import started"`),
Level: mongodoc.InfoLevel,
Type: mongodoc.<API key>,
Time: statisticsStart,
})
statisticsEnd := now.Add(-30 * time.Minute)
s.addLog(c, &mongodoc.Log{
Data: []byte(`"legacy statistics import completed"`),
Level: mongodoc.InfoLevel,
Type: mongodoc.<API key>,
Time: statisticsEnd.Add(-1 * time.Hour),
})
s.addLog(c, &mongodoc.Log{
Data: []byte(`"legacy statistics import completed"`),
Level: mongodoc.InfoLevel,
Type: mongodoc.<API key>,
Time: statisticsEnd,
})
s.AssertDebugStatus(c, false, map[string]params.DebugStatus{
"legacy_statistics": {
Name: "Legacy Statistics Load",
Value: "started: " + statisticsStart.Format(time.RFC3339) + ", completed: " + statisticsEnd.Format(time.RFC3339),
Passed: true,
},
})
}
func (s *APISuite) <API key>(c *gc.C) {
// Add a base entity without any corresponding entities.
entity := &mongodoc.BaseEntity{
URL: charm.MustParseReference("django"),
Name: "django",
}
err := s.store.DB.BaseEntities().Insert(entity)
c.Assert(err, gc.IsNil)
s.AssertDebugStatus(c, false, map[string]params.DebugStatus{
"base_entities": {
Name: "Base entities in charm store",
Value: "count: 1",
Passed: false,
},
})
}
// AssertDebugStatus asserts that the current /debug/status endpoint
// matches the given status, ignoring status duration.
// If complete is true, it fails if the results contain
// keys not mentioned in status.
func (s *APISuite) AssertDebugStatus(c *gc.C, complete bool, status map[string]params.DebugStatus) {
rec := httptesting.DoRequest(c, httptesting.DoRequestParams{
Handler: s.srv,
URL: storeURL("debug/status"),
})
c.Assert(rec.Code, gc.Equals, http.StatusOK, gc.Commentf("body: %s", rec.Body.Bytes()))
c.Assert(rec.Header().Get("Content-Type"), gc.Equals, "application/json")
var gotStatus map[string]params.DebugStatus
err := json.Unmarshal(rec.Body.Bytes(), &gotStatus)
c.Assert(err, gc.IsNil)
for key, r := range gotStatus {
if _, found := status[key]; !complete && !found {
delete(gotStatus, key)
continue
}
r.Duration = 0
gotStatus[key] = r
}
c.Assert(gotStatus, jc.DeepEquals, status)
}
type <API key> struct {
commonSuite
}
var _ = gc.Suite(&<API key>{})
func (s *<API key>) SetUpSuite(c *gc.C) {
s.enableES = true
s.commonSuite.SetUpSuite(c)
}
func (s *<API key>) <API key>(c *gc.C) {
rec := httptesting.DoRequest(c, httptesting.DoRequestParams{
Handler: s.srv,
URL: storeURL("debug/status"),
})
var results map[string]params.DebugStatus
err := json.Unmarshal(rec.Body.Bytes(), &results)
c.Assert(err, gc.IsNil)
c.Assert(results["elasticsearch"].Name, gc.Equals, "Elastic search is running")
c.Assert(results["elasticsearch"].Value, jc.Contains, "cluster_name:")
} |
// 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,
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// included in all copies or substantial portions of the Software.
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// 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 db
import (
"reflect"
"time"
)
// Comparison defines methods for representing comparison operators in a
// portable way across databases.
type Comparison interface {
Operator() ComparisonOperator
Value() interface{}
}
// ComparisonOperator is a type we use to label comparison operators.
type ComparisonOperator uint8
// Comparison operators
const (
<API key> ComparisonOperator = iota
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
)
type <API key> struct {
t ComparisonOperator
op string
v interface{}
}
func (c *<API key>) CustomOperator() string {
return c.op
}
func (c *<API key>) Operator() ComparisonOperator {
return c.t
}
func (c *<API key>) Value() interface{} {
return c.v
}
// Gte indicates whether the reference is greater than or equal to the given
// argument.
func Gte(v interface{}) Comparison {
return &<API key>{
t: <API key>,
v: v,
}
}
// Lte indicates whether the reference is less than or equal to the given
// argument.
func Lte(v interface{}) Comparison {
return &<API key>{
t: <API key>,
v: v,
}
}
// Eq indicates whether the constraint is equal to the given argument.
func Eq(v interface{}) Comparison {
return &<API key>{
t: <API key>,
v: v,
}
}
// NotEq indicates whether the constraint is not equal to the given argument.
func NotEq(v interface{}) Comparison {
return &<API key>{
t: <API key>,
v: v,
}
}
// Gt indicates whether the constraint is greater than the given argument.
func Gt(v interface{}) Comparison {
return &<API key>{
t: <API key>,
v: v,
}
}
// Lt indicates whether the constraint is less than the given argument.
func Lt(v interface{}) Comparison {
return &<API key>{
t: <API key>,
v: v,
}
}
// In indicates whether the argument is part of the reference.
func In(v interface{}) Comparison {
return &<API key>{
t: <API key>,
v: toInterfaceArray(v),
}
}
// NotIn indicates whether the argument is not part of the reference.
func NotIn(v interface{}) Comparison {
return &<API key>{
t: <API key>,
v: toInterfaceArray(v),
}
}
// After indicates whether the reference is after the given time.
func After(t time.Time) Comparison {
return &<API key>{
t: <API key>,
v: t,
}
}
// Before indicates whether the reference is before the given time.
func Before(t time.Time) Comparison {
return &<API key>{
t: <API key>,
v: t,
}
}
// OnOrAfter indicater whether the reference is after or equal to the given
// time value.
func OnOrAfter(t time.Time) Comparison {
return &<API key>{
t: <API key>,
v: t,
}
}
// OnOrBefore indicates whether the reference is before or equal to the given
// time value.
func OnOrBefore(t time.Time) Comparison {
return &<API key>{
t: <API key>,
v: t,
}
}
// Between indicates whether the reference is contained between the two given
// values.
func Between(a interface{}, b interface{}) Comparison {
return &<API key>{
t: <API key>,
v: []interface{}{a, b},
}
}
// NotBetween indicates whether the reference is not contained between the two
// given values.
func NotBetween(a interface{}, b interface{}) Comparison {
return &<API key>{
t: <API key>,
v: []interface{}{a, b},
}
}
// Is indicates whether the reference is nil, true or false.
func Is(v interface{}) Comparison {
return &<API key>{
t: <API key>,
v: v,
}
}
// IsNot indicates whether the reference is not nil, true nor false.
func IsNot(v interface{}) Comparison {
return &<API key>{
t: <API key>,
v: v,
}
}
// IsNull indicates whether the reference is a NULL value.
func IsNull() Comparison {
return Is(nil)
}
// IsNotNull indicates whether the reference is a NULL value.
func IsNotNull() Comparison {
return IsNot(nil)
}
/*
// IsDistinctFrom indicates whether the reference is different from
// the given value, including NULL values.
func IsDistinctFrom(v interface{}) Comparison {
return &<API key>{
t: <API key>,
v: v,
}
}
// IsNotDistinctFrom indicates whether the reference is not different from the
// given value, including NULL values.
func IsNotDistinctFrom(v interface{}) Comparison {
return &<API key>{
t: <API key>,
v: v,
}
}
*/
// Like indicates whether the reference matches the wildcard value.
func Like(v string) Comparison {
return &<API key>{
t: <API key>,
v: v,
}
}
// NotLike indicates whether the reference does not match the wildcard value.
func NotLike(v string) Comparison {
return &<API key>{
t: <API key>,
v: v,
}
}
/*
// ILike indicates whether the reference matches the wildcard value (case
// insensitive).
func ILike(v string) Comparison {
return &<API key>{
t: <API key>,
v: v,
}
}
// NotILike indicates whether the reference does not match the wildcard value
// (case insensitive).
func NotILike(v string) Comparison {
return &<API key>{
t: <API key>,
v: v,
}
}
*/
// RegExp indicates whether the reference matches the regexp pattern.
func RegExp(v string) Comparison {
return &<API key>{
t: <API key>,
v: v,
}
}
// NotRegExp indicates whether the reference does not match the regexp pattern.
func NotRegExp(v string) Comparison {
return &<API key>{
t: <API key>,
v: v,
}
}
// Op represents a custom comparison operator against the reference.
func Op(customOperator string, v interface{}) Comparison {
return &<API key>{
op: customOperator,
t: <API key>,
v: v,
}
}
func toInterfaceArray(v interface{}) []interface{} {
rv := reflect.ValueOf(v)
switch rv.Type().Kind() {
case reflect.Ptr:
return toInterfaceArray(rv.Elem().Interface())
case reflect.Slice:
elems := rv.Len()
args := make([]interface{}, elems)
for i := 0; i < elems; i++ {
args[i] = rv.Index(i).Interface()
}
return args
}
return []interface{}{v}
}
var _ Comparison = &<API key>{} |
<?php
/**
* I am a generated class and am required for communicating with plentymarkets.
*/
class <API key>
{
/**
* @var int
*/
public $OrderRowID;
/**
* @var float
*/
public $Quantity;
} |
ace.define("ace/mode/jsx", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text", "ace/tokenizer", "ace/mode/jsx_highlight_rules", "ace/mode/<API key>", "ace/mode/behaviour/cstyle", "ace/mode/folding/cstyle"], function (e, t, n) {
function l() {
this.HighlightRules = o, this.$outdent = new u, this.$behaviour = new a, this.foldingRules = new f
}
var r = e("../lib/oop"), i = e("./text").Mode, s = e("../tokenizer").Tokenizer, o = e("./jsx_highlight_rules").JsxHighlightRules, u = e("./<API key>").<API key>, a = e("./behaviour/cstyle").CstyleBehaviour, f = e("./folding/cstyle").FoldMode;
r.inherits(l, i), function () {
this.lineCommentStart = "//", this.blockComment = {start: "/*", end: "*/"}, this.getNextLineIndent = function (e, t, n) {
var r = this.$getIndent(t), i = this.getTokenizer().getLineTokens(t, e), s = i.tokens;
if (s.length && s[s.length - 1].type == "comment")return r;
if (e == "start") {
var o = t.match(/^.*[\{\(\[]\s*$/);
o && (r += n)
}
return r
}, this.checkOutdent = function (e, t, n) {
return this.$outdent.checkOutdent(t, n)
}, this.autoOutdent = function (e, t, n) {
this.$outdent.autoOutdent(t, n)
}, this.$id = "ace/mode/jsx"
}.call(l.prototype), t.Mode = l
}), ace.define("ace/mode/jsx_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/lib/lang", "ace/mode/<API key>", "ace/mode/<API key>"], function (e, t, n) {
var r = e("../lib/oop"), i = e("../lib/lang"), s = e("./<API key>").<API key>, o = e("./<API key>").TextHighlightRules, u = function () {
var e = i.arrayToMap("break|do|instanceof|typeof|case|else|new|var|catch|finally|return|void|continue|for|switch|default|while|function|this|if|throw|delete|in|try|class|extends|super|import|from|into|implements|interface|static|mixin|override|abstract|final|number|int|string|boolean|variant|log|assert".split("|")), t = i.arrayToMap("null|true|false|NaN|Infinity|__FILE__|__LINE__|undefined".split("|")), n = i.arrayToMap("debugger|with|const|export|let|private|public|yield|protected|extern|native|as|operator|__fake__|__readonly__".split("|")), r = "[a-zA-Z_][a-zA-Z0-9_]*\\b";
this.$rules = {start: [
{token: "comment", regex: "\\/\\/.*$"},
s.getStartRule("doc-start"),
{token: "comment", regex: "\\/\\*", next: "comment"},
{token: "string.regexp", regex: "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"},
{token: "string", regex: '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},
{token: "string", regex: "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},
{token: "constant.numeric", regex: "0[xX][0-9a-fA-F]+\\b"},
{token: "constant.numeric", regex: "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"},
{token: "constant.language.boolean", regex: "(?:true|false)\\b"},
{token: ["storage.type", "text", "entity.name.function"], regex: "(function)(\\s+)(" + r + ")"},
{token: function (r) {
return r == "this" ? "variable.language" : r == "function" ? "storage.type" : e.hasOwnProperty(r) || n.hasOwnProperty(r) ? "keyword" : t.hasOwnProperty(r) ? "constant.language" : /^_?[A-Z][a-zA-Z0-9_]*$/.test(r) ? "language.support.class" : "identifier"
}, regex: r},
{token: "keyword.operator", regex: "!|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|==|=|!=|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)"},
{token: "punctuation.operator", regex: "\\?|\\:|\\,|\\;|\\."},
{token: "paren.lparen", regex: "[[({<]"},
{token: "paren.rparen", regex: "[\\])}>]"},
{token: "text", regex: "\\s+"}
], comment: [
{token: "comment", regex: ".*?\\*\\/", next: "start"},
{token: "comment", regex: ".+"}
]}, this.embedRules(s, "doc-", [s.getEndRule("start")])
};
r.inherits(u, o), t.JsxHighlightRules = u
}), ace.define("ace/mode/<API key>", ["require", "exports", "module", "ace/lib/oop", "ace/mode/<API key>"], function (e, t, n) {
var r = e("../lib/oop"), i = e("./<API key>").TextHighlightRules, s = function () {
this.$rules = {start: [
{token: "comment.doc.tag", regex: "@[\\w\\d_]+"},
{token: "comment.doc.tag", regex: "\\bTODO\\b"},
{defaultToken: "comment.doc"}
]}
};
r.inherits(s, i), s.getStartRule = function (e) {
return{token: "comment.doc", regex: "\\/\\*(?=\\*)", next: e}
}, s.getEndRule = function (e) {
return{token: "comment.doc", regex: "\\*\\/", next: e}
}, t.<API key> = s
}), ace.define("ace/mode/<API key>", ["require", "exports", "module", "ace/range"], function (e, t, n) {
var r = e("../range").Range, i = function () {
};
(function () {
this.checkOutdent = function (e, t) {
return/^\s+$/.test(e) ? /^\s*\}/.test(t) : !1
}, this.autoOutdent = function (e, t) {
var n = e.getLine(t), i = n.match(/^(\s*\})/);
if (!i)return 0;
var s = i[1].length, o = e.findMatchingBracket({row: t, column: s});
if (!o || o.row == t)return 0;
var u = this.$getIndent(e.getLine(o.row));
e.replace(new r(t, 0, t, s - 1), u)
}, this.$getIndent = function (e) {
return e.match(/^\s*/)[0]
}
}).call(i.prototype), t.<API key> = i
}), ace.define("ace/mode/behaviour/cstyle", ["require", "exports", "module", "ace/lib/oop", "ace/mode/behaviour", "ace/token_iterator", "ace/lib/lang"], function (e, t, n) {
var r = e("../../lib/oop"), i = e("../behaviour").Behaviour, s = e("../../token_iterator").TokenIterator, o = e("../../lib/lang"), u = ["text", "paren.rparen", "punctuation.operator"], a = ["text", "paren.rparen", "punctuation.operator", "comment"], f, l = {}, c = function (e) {
var t = -1;
e.multiSelect && (t = e.selection.id, l.rangeCount != e.multiSelect.rangeCount && (l = {rangeCount: e.multiSelect.rangeCount}));
if (l[t])return f = l[t];
f = l[t] = {<API key>: 0, autoInsertedRow: -1, autoInsertedLineEnd: "", <API key>: 0, maybeInsertedRow: -1, <API key>: "", <API key>: ""}
}, h = function () {
this.add("braces", "insertion", function (e, t, n, r, i) {
var s = n.getCursorPosition(), u = r.doc.getLine(s.row);
if (i == "{") {
c(n);
var a = n.getSelectionRange(), l = r.doc.getTextRange(a);
if (l !== "" && l !== "{" && n.<API key>())return{text: "{" + l + "}", selection: !1};
if (h.isSaneInsertion(n, r))return/[\]\}\)]/.test(u[s.column]) || n.inMultiSelectMode ? (h.recordAutoInsert(n, r, "}"), {text: "{}", selection: [1, 1]}) : (h.recordMaybeInsert(n, r, "{"), {text: "{", selection: [1, 1]})
} else if (i == "}") {
c(n);
var p = u.substring(s.column, s.column + 1);
if (p == "}") {
var d = r.$findOpeningBracket("}", {column: s.column + 1, row: s.row});
if (d !== null && h.<API key>(s, u, i))return h.<API key>(), {text: "", selection: [1, 1]}
}
} else {
if (i == "\n" || i == "\r\n") {
c(n);
var v = "";
h.<API key>(s, u) && (v = o.stringRepeat("}", f.<API key>), h.<API key>());
var p = u.substring(s.column, s.column + 1);
if (p === "}") {
var m = r.findMatchingBracket({row: s.row, column: s.column + 1}, "}");
if (!m)return null;
var g = this.$getIndent(r.getLine(m.row))
} else {
if (!v) {
h.<API key>();
return
}
var g = this.$getIndent(u)
}
var y = g + r.getTabString();
return{text: "\n" + y + "\n" + g + v, selection: [1, y.length, 1, y.length]}
}
h.<API key>()
}
}), this.add("braces", "deletion", function (e, t, n, r, i) {
var s = r.doc.getTextRange(i);
if (!i.isMultiLine() && s == "{") {
c(n);
var o = r.doc.getLine(i.start.row), u = o.substring(i.end.column, i.end.column + 1);
if (u == "}")return i.end.column++, i;
f.<API key>
}
}), this.add("parens", "insertion", function (e, t, n, r, i) {
if (i == "(") {
c(n);
var s = n.getSelectionRange(), o = r.doc.getTextRange(s);
if (o !== "" && n.<API key>())return{text: "(" + o + ")", selection: !1};
if (h.isSaneInsertion(n, r))return h.recordAutoInsert(n, r, ")"), {text: "()", selection: [1, 1]}
} else if (i == ")") {
c(n);
var u = n.getCursorPosition(), a = r.doc.getLine(u.row), f = a.substring(u.column, u.column + 1);
if (f == ")") {
var l = r.$findOpeningBracket(")", {column: u.column + 1, row: u.row});
if (l !== null && h.<API key>(u, a, i))return h.<API key>(), {text: "", selection: [1, 1]}
}
}
}), this.add("parens", "deletion", function (e, t, n, r, i) {
var s = r.doc.getTextRange(i);
if (!i.isMultiLine() && s == "(") {
c(n);
var o = r.doc.getLine(i.start.row), u = o.substring(i.start.column + 1, i.start.column + 2);
if (u == ")")return i.end.column++, i
}
}), this.add("brackets", "insertion", function (e, t, n, r, i) {
if (i == "[") {
c(n);
var s = n.getSelectionRange(), o = r.doc.getTextRange(s);
if (o !== "" && n.<API key>())return{text: "[" + o + "]", selection: !1};
if (h.isSaneInsertion(n, r))return h.recordAutoInsert(n, r, "]"), {text: "[]", selection: [1, 1]}
} else if (i == "]") {
c(n);
var u = n.getCursorPosition(), a = r.doc.getLine(u.row), f = a.substring(u.column, u.column + 1);
if (f == "]") {
var l = r.$findOpeningBracket("]", {column: u.column + 1, row: u.row});
if (l !== null && h.<API key>(u, a, i))return h.<API key>(), {text: "", selection: [1, 1]}
}
}
}), this.add("brackets", "deletion", function (e, t, n, r, i) {
var s = r.doc.getTextRange(i);
if (!i.isMultiLine() && s == "[") {
c(n);
var o = r.doc.getLine(i.start.row), u = o.substring(i.start.column + 1, i.start.column + 2);
if (u == "]")return i.end.column++, i
}
}), this.add("string_dquotes", "insertion", function (e, t, n, r, i) {
if (i == '"' || i == "'") {
c(n);
var s = i, o = n.getSelectionRange(), u = r.doc.getTextRange(o);
if (u !== "" && u !== "'" && u != '"' && n.<API key>())return{text: s + u + s, selection: !1};
var a = n.getCursorPosition(), f = r.doc.getLine(a.row), l = f.substring(a.column - 1, a.column);
if (l == "\\")return null;
var p = r.getTokens(o.start.row), d = 0, v, m = -1;
for (var g = 0; g < p.length; g++) {
v = p[g], v.type == "string" ? m = -1 : m < 0 && (m = v.value.indexOf(s));
if (v.value.length + d > o.start.column)break;
d += p[g].value.length
}
if (!v || m < 0 && v.type !== "comment" && (v.type !== "string" || o.start.column !== v.value.length + d - 1 && v.value.lastIndexOf(s) === v.value.length - 1)) {
if (!h.isSaneInsertion(n, r))return;
return{text: s + s, selection: [1, 1]}
}
if (v && v.type === "string") {
var y = f.substring(a.column, a.column + 1);
if (y == s)return{text: "", selection: [1, 1]}
}
}
}), this.add("string_dquotes", "deletion", function (e, t, n, r, i) {
var s = r.doc.getTextRange(i);
if (!i.isMultiLine() && (s == '"' || s == "'")) {
c(n);
var o = r.doc.getLine(i.start.row), u = o.substring(i.start.column + 1, i.start.column + 2);
if (u == s)return i.end.column++, i
}
})
};
h.isSaneInsertion = function (e, t) {
var n = e.getCursorPosition(), r = new s(t, n.row, n.column);
if (!this.$matchTokenType(r.getCurrentToken() || "text", u)) {
var i = new s(t, n.row, n.column + 1);
if (!this.$matchTokenType(i.getCurrentToken() || "text", u))return!1
}
return r.stepForward(), r.getCurrentTokenRow() !== n.row || this.$matchTokenType(r.getCurrentToken() || "text", a)
}, h.$matchTokenType = function (e, t) {
return t.indexOf(e.type || e) > -1
}, h.recordAutoInsert = function (e, t, n) {
var r = e.getCursorPosition(), i = t.doc.getLine(r.row);
this.<API key>(r, i, f.autoInsertedLineEnd[0]) || (f.<API key> = 0), f.autoInsertedRow = r.row, f.autoInsertedLineEnd = n + i.substr(r.column), f.<API key>++
}, h.recordMaybeInsert = function (e, t, n) {
var r = e.getCursorPosition(), i = t.doc.getLine(r.row);
this.<API key>(r, i) || (f.<API key> = 0), f.maybeInsertedRow = r.row, f.<API key> = i.substr(0, r.column) + n, f.<API key> = i.substr(r.column), f.<API key>++
}, h.<API key> = function (e, t, n) {
return f.<API key> > 0 && e.row === f.autoInsertedRow && n === f.autoInsertedLineEnd[0] && t.substr(e.column) === f.autoInsertedLineEnd
}, h.<API key> = function (e, t) {
return f.<API key> > 0 && e.row === f.maybeInsertedRow && t.substr(e.column) === f.<API key> && t.substr(0, e.column) == f.<API key>
}, h.<API key> = function () {
f.autoInsertedLineEnd = f.autoInsertedLineEnd.substr(1), f.<API key>
}, h.<API key> = function () {
f && (f.<API key> = 0, f.maybeInsertedRow = -1)
}, r.inherits(h, i), t.CstyleBehaviour = h
}), ace.define("ace/mode/folding/cstyle", ["require", "exports", "module", "ace/lib/oop", "ace/range", "ace/mode/folding/fold_mode"], function (e, t, n) {
var r = e("../../lib/oop"), i = e("../../range").Range, s = e("./fold_mode").FoldMode, o = t.FoldMode = function (e) {
e && (this.foldingStartMarker = new RegExp(this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + e.start)), this.foldingStopMarker = new RegExp(this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + e.end)))
};
r.inherits(o, s), function () {
this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/, this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/, this.getFoldWidgetRange = function (e, t, n, r) {
var i = e.getLine(n), s = i.match(this.foldingStartMarker);
if (s) {
var o = s.index;
if (s[1])return this.openingBracketBlock(e, s[1], n, o);
var u = e.getCommentFoldRange(n, o + s[0].length, 1);
return u && !u.isMultiLine() && (r ? u = this.getSectionRange(e, n) : t != "all" && (u = null)), u
}
if (t === "markbegin")return;
var s = i.match(this.foldingStopMarker);
if (s) {
var o = s.index + s[0].length;
return s[1] ? this.closingBracketBlock(e, s[1], n, o) : e.getCommentFoldRange(n, o, -1)
}
}, this.getSectionRange = function (e, t) {
var n = e.getLine(t), r = n.search(/\S/), s = t, o = n.length;
t += 1;
var u = t, a = e.getLength();
while (++t < a) {
n = e.getLine(t);
var f = n.search(/\S/);
if (f === -1)continue;
if (r > f)break;
var l = this.getFoldWidgetRange(e, "all", t);
if (l) {
if (l.start.row <= s)break;
if (l.isMultiLine())t = l.end.row; else if (r == f)break
}
u = t
}
return new i(s, o, u, e.getLine(u).length)
}
}.call(o.prototype)
}) |
<?php
class TreeNode {
public $text = "";
public $id = "";
public $iconCls = "";
public $leaf = true;
public $draggable = false;
public $href = "
public $hrefTarget = "";
function __construct($id,$text,$iconCls,$leaf,$draggable,$href,$hrefTarget) {
$this->id = $id;
$this->text = $text;
$this->iconCls = $iconCls;
$this->leaf = $leaf;
$this->draggable = $draggable;
$this->href = $href;
$this->hrefTarget = $hrefTarget;
}
function toJson() {
return G::json_encode($this);
}
}
class ExtJsTreeNode extends TreeNode {
public $children = array();
function add($object) {
$this->children[] = $object;
}
function toJson() {
return G::json_encode($this);
}
}
G::LoadClass('case');
$o = new Cases();
$PRO_UID = $_SESSION['PROCESS'];
$treeArray = array();
//if (isset($_GET['action'])&&$_GET['action']=='test'){
echo "[";
// dynaforms assemble
$extTreeDynaforms = new ExtJsTreeNode("node-dynaforms", G::loadtranslation('ID_DYNAFORMS'), "", false, false, "", "");
$i = 0;
$APP_UID = $_GET['APP_UID'];
$DEL_INDEX = $_GET['DEL_INDEX'];
$steps = $o-><API key>($_GET['APP_UID']);
$steps->next();
while ($step = $steps->getRow()) {
require_once 'classes/model/Dynaform.php';
$od = new Dynaform();
$dynaformF = $od->Load($step['STEP_UID_OBJ']);
$n = $step['STEP_POSITION'];
$TITLE = " - ".$dynaformF['DYN_TITLE'];
$DYN_UID = $dynaformF['DYN_UID'];
$href = "cases_StepToRevise?type=DYNAFORM&ex=$i&PRO_UID=$PRO_UID&DYN_UID=$DYN_UID&APP_UID=$APP_UID&position=".$step['STEP_POSITION']."&DEL_INDEX=$DEL_INDEX";
$extTreeDynaforms->add(new TreeNode($DYN_UID,$TITLE,"datasource",true,false,$href,"openCaseFrame"));
$i++;
$steps->next();
}
echo $extTreeDynaforms->toJson();
// end the dynaforms tree menu
echo ",";
// assembling the input documents tree menu
$extTreeInputDocs = new ExtJsTreeNode("<API key>", G::loadtranslation('<API key>'), "", false, false, "", "");
$i = 0;
$APP_UID = $_GET['APP_UID'];
$DEL_INDEX = $_GET['DEL_INDEX'];
$steps = $o-><API key>($_GET['APP_UID']);
$steps->next();
while ($step = $steps->getRow()) {
require_once 'classes/model/InputDocument.php';
$od = new InputDocument();
$IDF = $od->Load($step['STEP_UID_OBJ']);
$n = $step['STEP_POSITION'];
$TITLE = " - ".$IDF['INP_DOC_TITLE'];
$INP_DOC_UID = $IDF['INP_DOC_UID'];
$href = "<API key>?type=INPUT_DOCUMENT&ex=$i&PRO_UID=$PRO_UID&INP_DOC_UID=$INP_DOC_UID&APP_UID=$APP_UID&position=".$step['STEP_POSITION']."&DEL_INDEX=$DEL_INDEX";
$extTreeInputDocs->add(new TreeNode($INP_DOC_UID,$TITLE,"datasource",true,false,$href,"openCaseFrame"));
$i++;
$steps->next();
}
echo $extTreeInputDocs->toJson();
echo "]"; |
# Northerner Cyril #
Welcome to the Northerner!
This is the reference implementation for a server-client, token-based online architecture of the game Carcassonne.
You may want to look into our [Wiki][] or jump to the [Protocol][]
[Wiki]: https://github.com/BenWiederhake/northerner-cyril/wiki
[Protocol]: https://github.com/BenWiederhake/northerner-cyril/wiki/Protocol |
<?php
namespace CloudDataService\NHSNumberValidation\Test;
use CloudDataService\NHSNumberValidation\Test\TestCase;
use CloudDataService\NHSNumberValidation\Validator;
class ValidatorTest extends TestCase
{
public function testInit()
{
$validator = new Validator;
$this->assertTrue(is_object($validator));
}
public function testHasFunction()
{
$validator = new Validator;
$this->assertTrue(
method_exists($validator, 'validate'),
'Class does not have method validate'
);
}
public function <API key>()
{
$validator = new Validator;
$this->assertTrue(is_object($validator));
try {
$valid = $validator->validate();
} catch (\CloudDataService\NHSNumberValidation\<API key> $e) {
return;
}
}
public function <API key>()
{
$validator = new Validator;
$this->assertTrue(is_object($validator));
try {
$valid = $validator->validate(0123);
} catch (\CloudDataService\NHSNumberValidation\<API key> $e) {
return;
}
}
public function <API key>()
{
$validator = new Validator;
$this->assertTrue(is_object($validator));
try {
$valid = $validator->validate('01234567890');
} catch (\CloudDataService\NHSNumberValidation\<API key> $e) {
return;
}
}
public function testValidNumber()
{
$validator = new Validator;
$this->assertTrue(is_object($validator));
try {
$valid = $validator->validate(4010232137);
} catch (\CloudDataService\NHSNumberValidation\<API key> $e) {
return false;
}
$this->assertEquals(4010232137, $valid);
}
public function <API key>()
{
$validator = new Validator;
$this->assertTrue(is_object($validator));
try {
$valid = $validator->validate(4010232138);
} catch (\CloudDataService\NHSNumberValidation\<API key> $e) {
return false;
}
}
public function <API key>()
{
$validator = new Validator;
$this->assertTrue(is_object($validator));
try {
$valid = $validator->validate(1000000010);
} catch (\CloudDataService\NHSNumberValidation\<API key> $e) {
return false;
}
}
public function <API key>()
{
$validator = new Validator;
$this->assertTrue(is_object($validator));
try {
$valid = $validator->validate(1000000060);
} catch (\CloudDataService\NHSNumberValidation\<API key> $e) {
return false;
}
}
public function <API key>()
{
$validator = new Validator;
$this->assertTrue(is_object($validator));
try {
$valid = $validator->validate("401 023 2137");
} catch (\CloudDataService\NHSNumberValidation\<API key> $e) {
return false;
}
$this->assertEquals(4010232137, $valid);
}
public function <API key>()
{
$validator = new Validator;
$this->assertTrue(is_object($validator));
try {
$valid = $validator->validate("401-023-2137");
} catch (\CloudDataService\NHSNumberValidation\<API key> $e) {
return false;
}
$this->assertEquals(4010232137, $valid);
}
} |
# This program is free software: you can redistribute it and/or modify
# published by the Free Software Foundation, either version 3 of the
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
"""
apartment controller manages the apartment objects that are known in the system
"""
import logging
from gateway.events import EsafeEvent, EventError
from gateway.exceptions import <API key>, StateException
from gateway.models import Apartment, Database
from gateway.mappers import ApartmentMapper
from gateway.dto import ApartmentDTO
from gateway.pubsub import PubSub
from ioc import INJECTED, Inject, Injectable, Singleton
if False: # MyPy
from typing import List, Optional, Dict, Any
from esafe.rebus import RebusController
logger = logging.getLogger(__name__)
@Injectable.named('<API key>')
@Singleton
class ApartmentController(object):
def __init__(self):
self.rebus_controller = None # type: Optional[RebusController]
def <API key>(self, rebus_controller):
self.rebus_controller = rebus_controller
@staticmethod
@Inject
def <API key>(msg, error=EventError.ErrorTypes.NO_ERROR, pubsub=INJECTED):
# type: (str, Dict[str, Any], PubSub) -> None
event = EsafeEvent(EsafeEvent.Types.CONFIG_CHANGE, {'type': 'apartment', 'msg': msg}, error=error)
pubsub.publish_esafe_event(PubSub.EsafeTopics.CONFIG, event)
@staticmethod
def load_apartment(apartment_id):
# type: (int) -> Optional[ApartmentDTO]
apartment_orm = Apartment.select().where(Apartment.id == apartment_id).first()
if apartment_orm is None:
return None
apartment_dto = ApartmentMapper.orm_to_dto(apartment_orm)
return apartment_dto
@staticmethod
def <API key>(mailbox_id):
# type: (int) -> Optional[ApartmentDTO]
apartment_orm = Apartment.select().where(Apartment.mailbox_rebus_id == mailbox_id).first()
if apartment_orm is None:
return None
apartment_dto = ApartmentMapper.orm_to_dto(apartment_orm)
return apartment_dto
@staticmethod
def <API key>(doorbell_id):
# type: (int) -> Optional[ApartmentDTO]
apartment_orm = Apartment.select().where(Apartment.doorbell_rebus_id == doorbell_id).first()
if apartment_orm is None:
return None
apartment_dto = ApartmentMapper.orm_to_dto(apartment_orm)
return apartment_dto
@staticmethod
def load_apartments():
# type: () -> List[ApartmentDTO]
apartments = []
for apartment_orm in Apartment.select():
apartment_dto = ApartmentMapper.orm_to_dto(apartment_orm)
apartments.append(apartment_dto)
return apartments
@staticmethod
def get_apartment_count():
# type: () -> int
return Apartment.select().count()
@staticmethod
def apartment_id_exists(apartment_id):
# type: (int) -> bool
apartments = ApartmentController.load_apartments()
ids = (x.id for x in apartments)
return apartment_id in ids
def _check_rebus_ids(self, apartment_dto):
if self.rebus_controller is None:
raise StateException("Cannot save apartment: Rebus Controller is None")
if 'doorbell_rebus_id' in apartment_dto.loaded_fields and \
not self.rebus_controller.<API key>(apartment_dto.doorbell_rebus_id):
raise <API key>("Cannot save apartment: doorbell ({}) does not exists".format(apartment_dto.doorbell_rebus_id))
if 'mailbox_rebus_id' in apartment_dto.loaded_fields and \
not self.rebus_controller.<API key>(apartment_dto.mailbox_rebus_id):
raise <API key>("Cannot save apartment: mailbox ({}) does not exists".format(apartment_dto.mailbox_rebus_id))
def save_apartment(self, apartment_dto, send_event=True):
# type: (ApartmentDTO, bool) -> ApartmentDTO
self._check_rebus_ids(apartment_dto)
apartment_orm = ApartmentMapper.dto_to_orm(apartment_dto)
apartment_orm.save()
if send_event:
ApartmentController.<API key>('save')
return ApartmentMapper.orm_to_dto(apartment_orm)
def save_apartments(self, apartments_dto):
apartments_dtos = []
for apartment in apartments_dto:
apartment_saved = self.save_apartment(apartment, send_event=False)
apartments_dtos.append(apartment_saved)
self.<API key>('save')
return apartments_dtos
def update_apartment(self, apartment_dto, send_event=True):
# type: (ApartmentDTO, bool) -> ApartmentDTO
self._check_rebus_ids(apartment_dto)
if 'id' not in apartment_dto.loaded_fields or apartment_dto.id is None:
raise RuntimeError('cannot update an apartment without the id being set')
try:
apartment_orm = Apartment.get_by_id(apartment_dto.id)
<API key> = ApartmentMapper.orm_to_dto(apartment_orm)
for field in apartment_dto.loaded_fields:
if field == 'id':
continue
if hasattr(apartment_dto, field):
setattr(<API key>, field, getattr(apartment_dto, field))
apartment_orm = ApartmentMapper.dto_to_orm(<API key>)
apartment_orm.save()
if send_event:
ApartmentController.<API key>('update')
return ApartmentMapper.orm_to_dto(apartment_orm)
except Exception as e:
raise RuntimeError('Could not update the user: {}'.format(e))
def update_apartments(self, apartment_dtos):
# type: (List[ApartmentDTO]) -> Optional[List[ApartmentDTO]]
apartments = []
with Database.get_db().transaction() as transaction:
try:
# First clear all the rebus fields in order to be able to swap 2 fields
for apartment in apartment_dtos:
apartment_orm = Apartment.get_by_id(apartment.id) # type: Apartment
if 'mailbox_rebus_id' in apartment.loaded_fields:
apartment_orm.mailbox_rebus_id = None
if 'doorbell_rebus_id' in apartment.loaded_fields:
apartment_orm.doorbell_rebus_id = None
apartment_orm.save()
# Then check if there is already an apartment with an mailbox or doorbell rebus id that is passed
# This is needed for when an doorbell or mailbox gets assigned to another apartment. Then the first assignment needs to be deleted.
for apartment_orm in Apartment.select():
for apartment_dto in apartment_dtos:
if apartment_orm.mailbox_rebus_id == apartment_dto.mailbox_rebus_id and apartment_orm.mailbox_rebus_id is not None:
apartment_orm.mailbox_rebus_id = None
apartment_orm.save()
if apartment_orm.doorbell_rebus_id == apartment_dto.doorbell_rebus_id and apartment_orm.doorbell_rebus_id is not None:
apartment_orm.doorbell_rebus_id = None
apartment_orm.save()
for apartment in apartment_dtos:
updated = self.update_apartment(apartment, send_event=False)
if updated is not None:
apartments.append(updated)
self.<API key>('update')
except Exception as ex:
logger.error('Could not update apartments: {}: {}'.format(type(ex).__name__, ex))
transaction.rollback()
return None
return apartments
@staticmethod
def delete_apartment(apartment_dto):
# type: (ApartmentDTO) -> None
if "id" in apartment_dto.loaded_fields and apartment_dto.id is not None:
Apartment.delete_by_id(apartment_dto.id)
elif "name" in apartment_dto.loaded_fields:
# First check if there is only one:
if Apartment.select().where(Apartment.name == apartment_dto.name).count() <= 1:
Apartment.delete().where(Apartment.name == apartment_dto.name).execute()
ApartmentController.<API key>('delete')
else:
raise RuntimeError('More than one apartment with the given name: {}'.format(apartment_dto.name))
else:
raise RuntimeError('Could not find an apartment with the name {} to delete'.format(apartment_dto.name)) |
<?php
require_once('data/SugarBean.php');
require_once('modules/Contacts/Contact.php');
require_once('include/SubPanel/SubPanelDefinitions.php');
class Bug41738Test extends <API key>
{
protected $bean;
public function setUp()
{
global $moduleList, $beanList, $beanFiles;
require('include/modules.php');
$GLOBALS['current_user'] = <API key>::createAnonymousUser();
$GLOBALS['modListHeader'] = <API key>($GLOBALS['current_user']);
$GLOBALS['<API key>']['Calls']='Calls';
$GLOBALS['<API key>']['Meetings']='Meetings';
$this->bean = new Opportunity();
}
public function tearDown()
{
<API key>::<API key>();
unset($GLOBALS['current_user']);
}
public function <API key>()
{
$subpanel = array(
'order' => 20,
'sort_order' => 'desc',
'sort_by' => 'date_entered',
'type' => 'collection',
'subpanel_name' => 'history', //this values is not associated with a physical file.
'top_buttons' => array(),
'collection_list' => array(
'meetings' => array(
'module' => 'Meetings',
'subpanel_name' => 'ForHistory',
'get_subpanel_data' => 'function:<API key>',
'generate_select'=>false,
'function_parameters' => array(
'bean_id'=>$this->bean->id,
'<API key>' => __FILE__
),
),
'tasks' => array(
'module' => 'Tasks',
'subpanel_name' => 'ForHistory',
'get_subpanel_data' => 'function:<API key>',
'generate_select'=>false,
'function_parameters' => array(
'bean_id'=>$this->bean->id,
'<API key>' => __FILE__
),
),
)
);
$subpanel_def = new aSubPanel("testpanel", $subpanel, $this->bean);
$query = $this->bean-><API key>($this->bean, "", '', "", 0, 5, -1, 0, $subpanel_def);
$result = $this->bean->db->query($query["query"]);
$this->assertTrue($result != false, "Bad query: {$query['query']}");
}
}
function <API key>($params)
{
$query = "SELECT meetings.id , meetings.name , meetings.status , 0 reply_to_status , ' ' contact_name , ' ' contact_id , ' ' contact_name_owner , ' ' contact_name_mod , meetings.parent_id , meetings.parent_type , meetings.date_modified , jt1.user_name assigned_user_name , jt1.created_by <API key> , 'Users' <API key>, ' ' filename , meetings.assigned_user_id , 'meetings' panel_name
FROM meetings
LEFT JOIN users jt1 ON jt1.id= meetings.assigned_user_id AND jt1.deleted=0 AND jt1.deleted=0
WHERE ( meetings.parent_type = 'Opportunities'
AND meetings.deleted=0
AND (meetings.status='Held' OR meetings.status='Not Held')
AND meetings.parent_id IN(
SELECT o.id
FROM opportunities o
INNER JOIN <API key> oc on o.id = oc.opportunity_id
AND oc.contact_id = '".$params['bean_id']."')
)";
return $query ;
}
function <API key>($params)
{
$query = "SELECT tasks.id , tasks.name , tasks.status , 0 reply_to_status , ' ' contact_name , ' ' contact_id , ' ' contact_name_owner , ' ' contact_name_mod , tasks.parent_id , tasks.parent_type , tasks.date_modified , jt1.user_name assigned_user_name , jt1.created_by <API key> , 'Users' <API key>, ' ' filename , tasks.assigned_user_id , 'tasks' panel_name
FROM tasks
LEFT JOIN users jt1 ON jt1.id= tasks.assigned_user_id AND jt1.deleted=0 AND jt1.deleted=0
WHERE ( tasks.parent_type = 'Opportunities'
AND tasks.deleted=0
AND (tasks.status='Completed' OR tasks.status='Deferred')
AND tasks.parent_id IN(
SELECT o.id
FROM opportunities o
INNER JOIN <API key> oc on o.id = oc.opportunity_id
AND oc.contact_id = '".$params['bean_id']."')
)";
return $query ;
} |
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="es">
<head>
<!-- Generated by javadoc (1.8.0_122-ea) on Thu Jan 19 17:37:21 CET 2017 -->
<title>Uses of Class me.Bn32w.Bn32wEngine.entity.collision.CollisionBox</title>
<meta name="date" content="2017-01-19">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class me.Bn32w.Bn32wEngine.entity.collision.CollisionBox";
}
}
catch(err) {
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar.top">
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../me/Bn32w/Bn32wEngine/entity/collision/CollisionBox.html" title="class in me.Bn32w.Bn32wEngine.entity.collision">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?me/Bn32w/Bn32wEngine/entity/collision/class-use/CollisionBox.html" target="_top">Frames</a></li>
<li><a href="CollisionBox.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip.navbar.top">
</a></div>
<div class="header">
<h2 title="Uses of Class me.Bn32w.Bn32wEngine.entity.collision.CollisionBox" class="title">Uses of Class<br>me.Bn32w.Bn32wEngine.entity.collision.CollisionBox</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../me/Bn32w/Bn32wEngine/entity/collision/CollisionBox.html" title="class in me.Bn32w.Bn32wEngine.entity.collision">CollisionBox</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#me.Bn32w.Bn32wEngine.entity">me.Bn32w.Bn32wEngine.entity</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="me.Bn32w.Bn32wEngine.entity">
</a>
<h3>Uses of <a href="../../../../../../me/Bn32w/Bn32wEngine/entity/collision/CollisionBox.html" title="class in me.Bn32w.Bn32wEngine.entity.collision">CollisionBox</a> in <a href="../../../../../../me/Bn32w/Bn32wEngine/entity/package-summary.html">me.Bn32w.Bn32wEngine.entity</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation">
<caption><span>Constructors in <a href="../../../../../../me/Bn32w/Bn32wEngine/entity/package-summary.html">me.Bn32w.Bn32wEngine.entity</a> with parameters of type <a href="../../../../../../me/Bn32w/Bn32wEngine/entity/collision/CollisionBox.html" title="class in me.Bn32w.Bn32wEngine.entity.collision">CollisionBox</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../me/Bn32w/Bn32wEngine/entity/Entity.html#Entity-me.Bn32w.Bn32wEngine.entity.collision.CollisionBox-java.lang.String-me.Bn32w.Bn32wEngine.states.State-boolean-">Entity</a></span>(<a href="../../../../../../me/Bn32w/Bn32wEngine/entity/collision/CollisionBox.html" title="class in me.Bn32w.Bn32wEngine.entity.collision">CollisionBox</a> pCollisionBox,
java.lang.String identifier,
<a href="../../../../../../me/Bn32w/Bn32wEngine/states/State.html" title="class in me.Bn32w.Bn32wEngine.states">State</a> state,
boolean solid)</code>
<div class="block">Creates a new entity, initializing all the bounds data by the information given in the parameter, the speed and acceleration is 0.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="bottomNav"><a name="navbar.bottom">
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../me/Bn32w/Bn32wEngine/entity/collision/CollisionBox.html" title="class in me.Bn32w.Bn32wEngine.entity.collision">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?me/Bn32w/Bn32wEngine/entity/collision/class-use/CollisionBox.html" target="_top">Frames</a></li>
<li><a href="CollisionBox.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip.navbar.bottom">
</a></div>
</body>
</html> |
<div class="split-content">
<div class="header">
<h2 translate>Templates</h2>
<div class="pull-right">
<div class="sortbar pull-left">
<span class="lab" translate>Filter:</span>
<div class="dropdown" dropdown <API key>>
<button id="order_button" class="dropdown-toggle" dropdown-toggle>{{ filters[activeFilter].label | translate }} <b class="caret"></b>
</button>
<ul class="dropdown-menu left-submenu" id="order_selector">
<li ng-repeat="f in filters track by $index" ng-class="{active: activeFilter === $index}">
<a href="" ng-click="filterBy($index)">{{ f.label | translate }}</a>
</li>
</ul>
</div>
</div>
<button class="btn btn-info" ng-click="edit()">
<i class="icon-plus-sign icon-white"></i> <span translate>Add New Template</span>
</button>
</div>
</div>
<div class="content">
<div class="flex-grid box wrap-items small-2 medium-4 large-6">
<div class="flex-item card-box template-card" ng-repeat="template in content_templates._items | templatesBy:filters[activeFilter]" ng-if="desks">
<div class="card-box__header" ng-class="{'<API key>': !template.is_public}" >
<div class="dropdown" dropdown>
<button class="dropdown-toggle" dropdown-toggle>
<i class="icon-dots-vertical"></i>
</button>
<ul class="dropdown-menu more-activity-menu pull-right">
<li><div class="menu-label" translate>Actions</div></li>
<li class="divider"></li>
<li><button ng-click="edit(template)" title="{{:: 'Edit Template' | translate }}"><i class="icon-pencil"></i>{{:: 'Edit'| translate}}</button></li>
<li ng-if="template.template_type !== 'kill'"><button ng-click="remove(template)" title="{{:: 'Remove Template' | translate }}"><i class="icon-trash"></i>{{:: 'Remove'| translate}}</button></li>
</ul>
</div>
<div class="card-box__heading">{{ template.template_name }}</div>
</div>
<div class="card-box__content">
<ul class="<API key>">
<li>
<h4 class="with-value">{{ :: 'Template type' | translate }} <span class="value-label">{{ template.template_type }}</span></h4>
</li>
<li ng-if="getTemplateDesk(template).name">
<h4>{{ :: 'Desk / Stage' | translate }}</h4>
<span>{{getTemplateDesk(template).name}} / {{getTemplateStage(template).name}}</span>
</li>
<li ng-if="template.schedule.is_active">
<h4>{{ :: 'Automated item creation' | translate }}</h4>
<span ng-repeat="day in template.schedule.day_of_week">
{{ :: weekdays[day] }}
<span ng-if="$index < template.schedule.day_of_week.length-1">, </span>
</span>
<span class="creation-time"> <i class="icon-time"></i> at {{ template.schedule.create_at | time }}<span>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div sd-modal data-model="template" class="modal-responsive">
<div class="modal-header template-header"> <a href="" class="close" ng-click="cancel()"><i class="icon-close-small"></i></a>
<h3 ng-show="template._id"><span translate>Edit Template</span><span>"{{ origTemplate.template_name }}"</span></h3>
<h3 translate ng-hide="template._id" translate>Add New Template</h3>
</div>
<div class="modal-body">
<form name="templateForm">
<div class="main-article">
<div class="fieldset">
<div class="field">
<label for="template-name" translate>Template Name</label>
<input id="template-name" required
ng-model="template.template_name">
</div>
<div class="field">
<label for="template-type" translate>Template Type</label>
<select id="template-type" required
ng-model="template.template_type"
ng-options="type._id as type.label for type in types | filter:templatesFilter"></select>
</div>
<div class="field">
<label for="template-is-private" translate>Desk Template</label>
<div class="control">
<span sd-switch ng-model="template.is_public"></span>
</div>
</div>
<div class="field" ng-if="template.template_type !== 'kill' && content_types.length">
<label for="template-profile" translate>Content Profile</label>
<div class="control">
<select id="template-profile" ng-model="item.profile" ng-options="type._id as type.label for type in content_types"></select>
</div>
</div>
<div class="field" ng-if="template.template_type !== 'kill' && !content_types.length">
<label for="template-profile" translate>Content Profile</label>
<div class="control">
<input type="text" id="template-profile" ng-model="item.profile">
</div>
</div>
<div class="field" ng-if="template.template_type !== 'kill' && template.is_public">
<label for="template-desk" translate>Desk</label>
<div class="control">
<select id="template-desk"
ng-model="template.template_desk"
ng-change="updateStages(template.template_desk)">
<option value="" translate>None</option>
<option ng-repeat="desk in desks._items track by desk._id" value="{{ desk._id }}" ng-selected="desk._id === template.template_desk">{{ :: desk.name }}</option>
</select>
</div>
</div>
<div class="field" ng-if="template.template_desk && stages && template.template_type !== 'kill' && template.is_public">
<label for="template-stage" translate>Stage</label>
<div class="control">
<select id="template-stage"
ng-model="template.template_stage">
<option ng-repeat="stage in stages track by stage._id" value="{{ stage._id }}" ng-selected="stage._id === template.template_stage">{{ :: stage.name }}</option>
</select>
</div>
</div>
<div class="field" ng-if="template.template_desk && template.template_type !== 'kill' && template.is_public">
<label for="schedule-toggle" translate>Automatically create item</label>
<div class="control">
<span sd-switch ng-model="template.schedule.is_active"></span>
</div>
</div>
<div class="field" ng-if="template.schedule.is_active && template.template_type !== 'kill'">
<label translate>On</label>
<div class="day-filter-box clearfix" sd-weekday-picker data-model="template.schedule.day_of_week"></div>
</div>
<div class="field" ng-if="template.schedule.is_active && template.template_type !== 'kill'">
<label translate>At</label>
<span sd-timepicker ng-model="template.schedule.create_at"></span>
<div sd-timezone data-timezone="template.schedule.time_zone"></div>
</div>
</div>
<div class="fieldset" sd-article-edit></div>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-default" ng-click="cancel()" translate>Cancel</button>
<button class="btn btn-primary"
ng-click="save()"
ng-disabled="templateForm.$invalid || (!templateForm.$invalid && !validSchedule())"
translate>Save</button>
</div>
</div> |
<?php
class MetadataPlugin extends KalturaPlugin
{
const PLUGIN_NAME = 'metadata';
const <API key> = '<API key>';
const <API key> = '<API key>';
const <API key> = '<API key>';
const <API key> = 'metadataProfileId';
const <API key> = 'metadataXml';
const <API key> = 'metadataUrl';
const <API key> = 'metadataField_';
const <API key> = '|,|';
const <API key> = '%Y-%m-%dT%H:%i:%s';
/**
* @return array<string,string> in the form array[serviceName] = serviceClass
*/
public static function getServicesMap()
{
$map = array(
'metadata' => 'MetadataService',
'metadataProfile' => '<API key>',
'metadataBatch' => '<API key>',
);
return $map;
}
/**
* @return string - the path to services.ct
*/
public static function getServiceConfig()
{
return realpath(dirname(__FILE__).'/config/metadata.ct');
}
/**
* @return array
*/
public static function getEventConsumers()
{
return array(
self::<API key>,
self::<API key>,
self::<API key>,
);
}
/**
* @param <API key>::OBJECT_TYPE $objectType
* @param string $enumValue
* @param array $constructorArgs
* @return object
*/
public static function loadObject($objectType, $enumValue, array $constructorArgs = null)
{
if($objectType != <API key>::<API key>)
return null;
if(!isset($constructorArgs['objectId']))
return null;
$objectId = $constructorArgs['objectId'];
switch($enumValue)
{
case FileSync::<API key>:
MetadataPeer::<API key> ( false );
$object = MetadataPeer::retrieveByPK( $objectId );
MetadataPeer::<API key> ( true );
return $object;
case FileSync::<API key>:
MetadataProfilePeer::<API key> ( false );
$object = MetadataProfilePeer::retrieveByPK( $objectId );
MetadataProfilePeer::<API key> ( true );
return $object;
}
return null;
}
/**
* @param array $fields
* @return string
*/
private static function getDateFormatRegex(&$fields = null)
{
$replace = array(
'%Y' => '([1-2][0-9]{3})',
'%m' => '([0-1][0-9])',
'%d' => '([0-3][0-9])',
'%H' => '([0-2][0-9])',
'%i' => '([0-5][0-9])',
'%s' => '([0-5][0-9])',
// '%T' => '([A-Z]{3})',
);
$fields = array();
$arr = null;
// if(!preg_match_all('/%([YmdTHis])/', self::<API key>, $arr))
if(!preg_match_all('/%([YmdHis])/', self::<API key>, $arr))
return false;
$fields = $arr[1];
return '/' . str_replace(array_keys($replace), $replace, self::<API key>) . '/';
}
/**
* @param string $str
* @return int
*/
private static function parseFormatedDate($str)
{
KalturaLog::debug("parseFormatedDate($str)");
if(function_exists('strptime'))
{
$ret = strptime($str, self::<API key>);
if($ret)
{
KalturaLog::debug("Formated Date [$ret] " . date('Y-m-d\TH:i:s', $ret));
return $ret;
}
}
$fields = null;
$regex = self::getDateFormatRegex($fields);
$values = null;
if(!preg_match($regex, $str, $values))
return null;
$hour = 0;
$minute = 0;
$second = 0;
$month = 0;
$day = 0;
$year = 0;
$is_dst = 0;
foreach($fields as $index => $field)
{
$value = $values[$index + 1];
switch($field)
{
case 'Y':
$year = intval($value);
break;
case 'm':
$month = intval($value);
break;
case 'd':
$day = intval($value);
break;
case 'H':
$hour = intval($value);
break;
case 'i':
$minute = intval($value);
break;
case 's':
$second = intval($value);
break;
// case 'T':
// $date = date_parse($value);
// $hour -= ($date['zone'] / 60);
// break;
}
}
KalturaLog::debug("gmmktime($hour, $minute, $second, $month, $day, $year)");
$ret = gmmktime($hour, $minute, $second, $month, $day, $year);
if($ret)
{
KalturaLog::debug("Formated Date [$ret] " . date('Y-m-d\TH:i:s', $ret));
return $ret;
}
KalturaLog::debug("Formated Date [null]");
return null;
}
/**
* @param string $entryId the new created entry
* @param array $data key => value pairs
*/
public static function <API key>($entryId, array $data)
{
KalturaLog::debug("Handle metadata bulk upload data:\n" . print_r($data, true));
if(!isset($data[self::<API key>]))
return;
$metadataProfileId = $data[self::<API key>];
$xmlData = null;
$entry = entryPeer::retrieveByPK($entryId);
if(!$entry)
return;
$metadataProfile = MetadataProfilePeer::retrieveById($metadataProfileId);
if(!$metadataProfile)
{
KalturaLog::info("Metadata profile [$metadataProfileId] not found");
return;
}
if(isset($data[self::<API key>]))
{
try{
$xmlData = file_get_contents($data[self::<API key>]);
KalturaLog::debug("Metadata downloaded [" . $data[self::<API key>] . "]");
}
catch(Exception $e)
{
KalturaLog::err("Download metadata[" . $data[self::<API key>] . "] error: " . $e->getMessage());
$xmlData = null;
}
}
elseif(isset($data[self::<API key>]))
{
$xmlData = $data[self::<API key>];
}
else
{
$<API key> = array();
<API key>::<API key>(false);
$<API key> = <API key>::<API key>($metadataProfileId);
<API key>::<API key>(true);
foreach($<API key> as $<API key>)
$<API key>[$<API key>->getKey()] = $<API key>;
KalturaLog::debug("Found fields [" . count($<API key>) . "] for metadata profile [$metadataProfileId]");
$xml = new DOMDocument();
$dataFound = false;
foreach($data as $key => $value)
{
if(!$value || !strlen($value))
continue;
if(!preg_match('/^' . self::<API key> . '(.+)$/', $key, $matches))
continue;
$key = $matches[1];
if(!isset($<API key>[$key]))
{
KalturaLog::debug("No field found for key[$key]");
continue;
}
$<API key> = $<API key>[$key];
KalturaLog::debug("Found field [" . $<API key>->getXpath() . "] for value [$value]");
if($<API key>->getType() == <API key>::KMC_FIELD_TYPE_DATE && !is_numeric($value))
{
$value = self::parseFormatedDate($value);
if(!$value || !strlen($value))
continue;
}
$fieldValues = explode(self::<API key>, $value);
foreach($fieldValues as $fieldValue)
self::addXpath($xml, $<API key>->getXpath(), $fieldValue);
$dataFound = true;
}
if($dataFound)
{
$xmlData = $xml->saveXML($xml->firstChild);
$xmlData = trim($xmlData, " \n\r\t");
}
}
if(!$xmlData)
return;
$dbMetadata = new Metadata();
$dbMetadata->setPartnerId($entry->getPartnerId());
$dbMetadata-><API key>($metadataProfileId);
$dbMetadata-><API key>($metadataProfile->getVersion());
$dbMetadata->setObjectType(Metadata::TYPE_ENTRY);
$dbMetadata->setObjectId($entryId);
$dbMetadata->setStatus(Metadata::STATUS_INVALID);
$dbMetadata->save();
KalturaLog::debug("Metadata [" . $dbMetadata->getId() . "] saved [$xmlData]");
$key = $dbMetadata->getSyncKey(Metadata::<API key>);
kFileSyncUtils::file_put_contents($key, $xmlData);
$errorMessage = '';
$status = kMetadataManager::validateMetadata($dbMetadata, $errorMessage);
if($status == Metadata::STATUS_VALID)
{
kMetadataManager::updateSearchIndex($dbMetadata);
}
else
{
$bulkUploadResult = <API key>::retrieveByEntryId($entryId, $entry->getBulkUploadId());
if($bulkUploadResult)
{
$msg = $bulkUploadResult->getDescription();
if($msg)
$msg .= "\n";
$msg .= $errorMessage;
$bulkUploadResult->setDescription($msg);
$bulkUploadResult->save();
}
}
}
protected static function addXpath(DOMDocument &$xml, $xPath, $value)
{
KalturaLog::debug("add value [$value] to xPath [$xPath]");
$xPaths = explode('/', $xPath);
$currentNode = $xml;
$currentXPath = '';
foreach($xPaths as $index => $xPath)
{
if(!strlen($xPath))
{
KalturaLog::debug("xPath [/] already exists");
continue;
}
$currentXPath .= "/$xPath";
$domXPath = new DOMXPath($xml);
$nodeList = $domXPath->query($currentXPath);
if($nodeList && $nodeList->length)
{
$currentNode = $nodeList->item(0);
KalturaLog::debug("xPath [$xPath] already exists");
continue;
}
if(!preg_match('/\*\[\s*local-name\(\)\s*=\s*\'([^\']+)\'\s*\]/', $xPath, $matches))
{
KalturaLog::err("Xpath [$xPath] doesn't match");
return false;
}
$nodeName = $matches[1];
if($index + 1 == count($xPaths))
{
KalturaLog::debug("Creating node [$nodeName] xPath [$xPath] with value [$value]");
$valueNode = $xml->createElement($nodeName, $value);
}
else
{
KalturaLog::debug("Creating node [$nodeName] xPath [$xPath]");
$valueNode = $xml->createElement($nodeName);
}
KalturaLog::debug("Appending node [$nodeName] to current node [$currentNode->localName]");
$currentNode->appendChild($valueNode);
$currentNode = $valueNode;
}
}
// /**
// * @return array<<API key>>
// */
// public static function <API key>()
// $metadata = new <API key>('Metadata', 'metadata');
// $metadataProfiles = new <API key>('Profiles Management', 'profiles', 'Metadata');
// $metadataObjects = new <API key>('Objects Management', 'objects', 'Metadata');
// return array($metadata, $metadataProfiles, $metadataObjects);
} |
import React from 'react';
import PropTypes from 'prop-types';
import ManaUsageGraph from './ManaUsageGraph';
class HealingDoneGraph extends React.PureComponent {
static propTypes = {
start: PropTypes.number.isRequired,
end: PropTypes.number.isRequired,
offset: PropTypes.number.isRequired,
healingBySecond: PropTypes.object.isRequired,
manaUpdates: PropTypes.array.isRequired,
};
<API key>(healingBySecond, interval) {
return Object.keys(healingBySecond)
.reduce((obj, second) => {
const healing = healingBySecond[second];
const index = Math.floor(second / interval);
if (obj[index]) {
obj[index] = obj[index].add(healing.regular, healing.absorbed, healing.overheal);
} else {
obj[index] = healing;
}
return obj;
}, {});
}
render() {
const { start, end, offset, healingBySecond, manaUpdates } = this.props;
// TODO: move this to vega-lite window transform
// e.g. { window: [{op: 'mean', field: 'hps', as: 'hps'}], frame: [-2, 2] }
const interval = 5;
const healingPerFrame = this.<API key>(healingBySecond, interval);
let max = 0;
Object.keys(healingPerFrame)
.map(k => healingPerFrame[k])
.forEach((healingDone) => {
const current = healingDone.effective;
if (current > max) {
max = current;
}
});
max /= interval;
const manaUsagePerFrame = {
0: 0,
};
const manaLevelPerFrame = {
0: 1,
};
manaUpdates.forEach((item) => {
const frame = Math.floor((item.timestamp - start) / 1000 / interval);
manaUsagePerFrame[frame] = (manaUsagePerFrame[frame] || 0) + item.used / item.max;
manaLevelPerFrame[frame] = item.current / item.max; // use the lowest value of the frame; likely to be more accurate
});
const fightDurationSec = Math.ceil((end - start) / 1000);
const labels = [];
for (let i = 0; i <= fightDurationSec / interval; i += 1) {
labels.push(Math.ceil(offset/1000) + i * interval);
healingPerFrame[i] = healingPerFrame[i] !== undefined ? healingPerFrame[i].effective : 0;
manaUsagePerFrame[i] = manaUsagePerFrame[i] !== undefined ? manaUsagePerFrame[i] : 0;
manaLevelPerFrame[i] = manaLevelPerFrame[i] !== undefined ? manaLevelPerFrame[i] : null;
}
let lastKnown = null;
const mana = Object.values(manaLevelPerFrame).map((value, i) => {
if (value !== null) {
lastKnown = value;
}
return {
x: labels[i],
y: lastKnown * max,
};
});
const healing = Object.values(healingPerFrame).map((value, i) => ({ x: labels[i], y: value / interval }));
const manaUsed = Object.values(manaUsagePerFrame).map((value, i) => ({ x: labels[i], y: value * max }));
return (
<div className="graph-container" style={{ marginBottom: 20 }}>
<ManaUsageGraph
mana={mana}
healing={healing}
manaUsed={manaUsed}
/>
</div>
);
}
}
export default HealingDoneGraph; |
package org.mskcc.cbio.portal.util;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import org.cbioportal.persistence.GenePanelRepository;
import org.cbioportal.model.GenePanel;
import org.mskcc.cbio.portal.model.<API key>;
import org.mskcc.cbio.portal.model.GeneticProfile;
/**
* Genetic Profile Util Class.
*
*/
public class GeneticProfileUtil {
/**
* Gets the GeneticProfile with the Specified GeneticProfile ID.
* @param profileId GeneticProfile ID.
* @param profileList List of Genetic Profiles.
* @return GeneticProfile or null.
*/
public static GeneticProfile getProfile(String profileId,
ArrayList<GeneticProfile> profileList) {
for (GeneticProfile profile : profileList) {
if (profile.getStableId().equals(profileId)) {
return profile;
}
}
return null;
}
/**
* Returns true if Any of the Profiles Selected by the User Refer to mRNA Expression
* outlier profiles.
*
* @param geneticProfileIdSet Set of Chosen Profiles IDs.
* @param profileList List of Genetic Profiles.
* @return true or false.
*/
public static boolean <API key>(HashSet<String> geneticProfileIdSet,
ArrayList<GeneticProfile> profileList) {
Iterator<String> <API key> = geneticProfileIdSet.iterator();
while (<API key>.hasNext()) {
String geneticProfileId = <API key>.next();
GeneticProfile geneticProfile = getProfile (geneticProfileId, profileList);
if (geneticProfile != null && geneticProfile.<API key>() == <API key>.MRNA_EXPRESSION) {
String profileName = geneticProfile.getProfileName();
if (profileName != null) {
if (profileName.toLowerCase().contains("outlier")) {
return true;
}
}
}
}
return false;
}
public static int getGenePanelId(String panelId) {
GenePanelRepository genePanelRepository = SpringUtil.<API key>();
GenePanel genePanel = genePanelRepository.<API key>(panelId).get(0);
return genePanel.getInternalId();
}
} |
odoo.define('web_editor.field_html_tests', function (require) {
"use strict";
var ajax = require('web.ajax');
var FormView = require('web.FormView');
var testUtils = require('web.test_utils');
var weTestUtils = require('web_editor.test_utils');
var core = require('web.core');
var Wysiwyg = require('web_editor.wysiwyg');
var MediaDialog = require('wysiwyg.widgets.MediaDialog');
var _t = core._t;
QUnit.module('web_editor', {}, function () {
QUnit.module('field html', {
beforeEach: function () {
this.data = weTestUtils.wysiwygData({
'note.note': {
fields: {
display_name: {
string: "Displayed name",
type: "char"
},
header: {
string: "Header",
type: "html",
required: true,
},
body: {
string: "Message",
type: "html"
},
},
records: [{
id: 1,
display_name: "first record",
header: "<p> <br> </p>",
body: "<p>toto toto toto</p><p>tata</p>",
}],
},
'mass.mailing': {
fields: {
display_name: {
string: "Displayed name",
type: "char"
},
body_html: {
string: "Message Body inline (to send)",
type: "html"
},
body_arch: {
string: "Message Body for edition",
type: "html"
},
},
records: [{
id: 1,
display_name: "first record",
body_html: "<div class='field_body' style='background-color: red;'>yep</div>",
body_arch: "<div class='field_body'>yep</div>",
}],
},
"ir.translation": {
fields: {
lang_code: {type: "char"},
value: {type: "char"},
res_id: {type: "integer"}
},
records: [{
id: 99,
res_id: 12,
value: '',
lang_code: 'en_US'
}]
},
});
testUtils.mock.patch(ajax, {
loadAsset: function (xmlId) {
if (xmlId === 'template.assets') {
return Promise.resolve({
cssLibs: [],
cssContents: ['body {background-color: red;}']
});
}
if (xmlId === 'template.assets_all_style') {
return Promise.resolve({
cssLibs: $('link[href]:not([type="image/x-icon"])').map(function () {
return $(this).attr('href');
}).get(),
cssContents: ['body {background-color: red;}']
});
}
throw 'Wrong template';
},
});
},
afterEach: function () {
testUtils.mock.unpatch(ajax);
},
}, function () {
QUnit.module('basic');
QUnit.test('simple rendering', async function (assert) {
assert.expect(3);
var form = await testUtils.createView({
View: FormView,
model: 'note.note',
data: this.data,
arch: '<form>' +
'<field name="body" widget="html" style="height: 100px"/>' +
'</form>',
res_id: 1,
});
var $field = form.$('.oe_form_field[name="body"]');
assert.strictEqual($field.children('.o_readonly').html(),
'<p>toto toto toto</p><p>tata</p>',
"should have rendered a div with correct content in readonly");
assert.strictEqual($field.attr('style'), 'height: 100px',
"should have applied the style correctly");
await testUtils.form.clickEdit(form);
await testUtils.nextTick();
$field = form.$('.oe_form_field[name="body"]');
assert.strictEqual($field.find('.note-editable').html(),
'<p>toto toto toto</p><p>tata</p>',
"should have rendered the field correctly in edit");
form.destroy();
});
QUnit.test('check if required field is set', async function (assert) {
assert.expect(1);
var form = await testUtils.createView({
View: FormView,
model: 'note.note',
data: this.data,
arch: '<form>' +
'<field name="header" widget="html" style="height: 100px" />' +
'</form>',
res_id: 1,
});
testUtils.mock.intercept(form, 'call_service', function (ev) {
if (ev.data.service === 'notification') {
assert.deepEqual(ev.data.args[0], {
"className": undefined,
"message": "<ul><li>Header</li></ul>",
"sticky": undefined,
"title": "Invalid fields:",
"type": "danger"
});
}
}, true);
await testUtils.form.clickEdit(form);
await testUtils.nextTick();
await testUtils.dom.click(form.$('.o_form_button_save'));
form.destroy();
});
QUnit.test('colorpicker', async function (assert) {
assert.expect(6);
var form = await testUtils.createView({
View: FormView,
model: 'note.note',
data: this.data,
arch: '<form>' +
'<field name="body" widget="html" style="height: 100px"/>' +
'</form>',
res_id: 1,
});
// Summernote needs a RootWidget to set as parent of the ColorPaletteWidget. In the
// tests, there is no RootWidget, so we set it here to the parent of the form view, which
// can act as RootWidget, as it will honor rpc requests correctly (to the MockServer).
const rootWidget = odoo.__DEBUG__.services['root.widget'];
odoo.__DEBUG__.services['root.widget'] = form.getParent();
await testUtils.form.clickEdit(form);
var $field = form.$('.oe_form_field[name="body"]');
// select the text
var pText = $field.find('.note-editable p').first().contents()[0];
Wysiwyg.setRange(pText, 1, pText, 10);
// text is selected
var range = Wysiwyg.getRange($field[0]);
assert.strictEqual(range.sc, pText,
"should select the text");
async function openColorpicker(selector) {
const $colorpicker = $field.find(selector);
const openingProm = new Promise(resolve => {
$colorpicker.one('shown.bs.dropdown', () => resolve());
});
await testUtils.dom.click($colorpicker.find('button:first'));
return openingProm;
}
await openColorpicker('.note-toolbar .<API key>');
assert.ok($field.find('.<API key>').hasClass('show'),
"should display the color picker");
await testUtils.dom.click($field.find('.note-toolbar .<API key> .o_we_color_btn[style="background-color:#00FFFF;"]'));
assert.ok(!$field.find('.<API key>').hasClass('show'),
"should close the color picker");
assert.strictEqual($field.find('.note-editable').html(),
'<p>t<font style="background-color: rgb(0, 255, 255);">oto toto </font>toto</p><p>tata</p>',
"should have rendered the field correctly in edit");
var fontContent = $field.find('.note-editable font').contents()[0];
var rangeControl = {
sc: fontContent,
so: 0,
ec: fontContent,
eo: fontContent.length,
};
range = Wysiwyg.getRange($field[0]);
assert.deepEqual(_.pick(range, 'sc', 'so', 'ec', 'eo'), rangeControl,
"should select the text after color change");
// select the text
pText = $field.find('.note-editable p').first().contents()[2];
Wysiwyg.setRange(fontContent, 5, pText, 2);
// text is selected
await openColorpicker('.note-toolbar .<API key>');
await testUtils.dom.click($field.find('.note-toolbar .<API key> .o_we_color_btn.bg-o-color-3'));
assert.strictEqual($field.find('.note-editable').html(),
'<p>t<font style="background-color: rgb(0, 255, 255);">oto t</font><font style="" class="bg-o-color-3">oto </font><font class="bg-o-color-3" style="">to</font>to</p><p>tata</p>',
"should have rendered the field correctly in edit");
odoo.__DEBUG__.services['root.widget'] = rootWidget;
form.destroy();
});
QUnit.test('media dialog: image', async function (assert) {
assert.expect(1);
var form = await testUtils.createView({
View: FormView,
model: 'note.note',
data: this.data,
arch: '<form>' +
'<field name="body" widget="html" style="height: 100px"/>' +
'</form>',
res_id: 1,
mockRPC: function (route, args) {
if (args.model === 'ir.attachment') {
if (args.method === "<API key>") {
return Promise.resolve();
}
}
if (route.indexOf('/web/image/123/transparent.png') === 0) {
return Promise.resolve();
}
if (route.indexOf('/web_unsplash/fetch_images') === 0) {
return Promise.resolve();
}
if (route.indexOf('/web_editor/<API key>') === 0) {
return Promise.resolve();
}
return this._super(route, args);
},
});
await testUtils.form.clickEdit(form);
var $field = form.$('.oe_form_field[name="body"]');
// the dialog load some xml assets
var defMediaDialog = testUtils.makeTestPromise();
testUtils.mock.patch(MediaDialog, {
init: function () {
this._super.apply(this, arguments);
this.opened(defMediaDialog.resolve.bind(defMediaDialog));
}
});
var pText = $field.find('.note-editable p').first().contents()[0];
Wysiwyg.setRange(pText, 1);
await testUtils.dom.click($field.find('.note-toolbar .note-insert button:has(.fa-file-image-o)'));
// load static xml file (dialog, media dialog, unsplash image widget)
await defMediaDialog;
await testUtils.dom.click($('.modal #editor-media-image .<API key>:first').removeClass('d-none'));
var $editable = form.$('.oe_form_field[name="body"] .note-editable');
assert.ok($editable.find('img')[0].dataset.src.includes('/web/image/123/transparent.png'),
"should have the image in the dom");
testUtils.mock.unpatch(MediaDialog);
form.destroy();
});
QUnit.test('media dialog: icon', async function (assert) {
assert.expect(1);
var form = await testUtils.createView({
View: FormView,
model: 'note.note',
data: this.data,
arch: '<form>' +
'<field name="body" widget="html" style="height: 100px"/>' +
'</form>',
res_id: 1,
mockRPC: function (route, args) {
if (args.model === 'ir.attachment') {
return Promise.resolve([]);
}
if (route.indexOf('/web_unsplash/fetch_images') === 0) {
return Promise.resolve();
}
return this._super(route, args);
},
});
await testUtils.form.clickEdit(form);
var $field = form.$('.oe_form_field[name="body"]');
// the dialog load some xml assets
var defMediaDialog = testUtils.makeTestPromise();
testUtils.mock.patch(MediaDialog, {
init: function () {
this._super.apply(this, arguments);
this.opened(defMediaDialog.resolve.bind(defMediaDialog));
}
});
var pText = $field.find('.note-editable p').first().contents()[0];
Wysiwyg.setRange(pText, 1);
await testUtils.dom.click($field.find('.note-toolbar .note-insert button:has(.fa-file-image-o)'));
// load static xml file (dialog, media dialog, unsplash image widget)
await defMediaDialog;
$('.modal .tab-content .tab-pane').removeClass('fade'); // to be sync in test
await testUtils.dom.click($('.modal a[aria-controls="editor-media-icon"]'));
await testUtils.dom.click($('.modal #editor-media-icon .font-icons-icon.fa-glass'));
var $editable = form.$('.oe_form_field[name="body"] .note-editable');
assert.strictEqual($editable.data('wysiwyg').getValue(),
'<p>t<span class="fa fa-glass"></span>oto toto toto</p><p>tata</p>',
"should have the image in the dom");
testUtils.mock.unpatch(MediaDialog);
form.destroy();
});
QUnit.test('save', async function (assert) {
assert.expect(1);
var form = await testUtils.createView({
View: FormView,
model: 'note.note',
data: this.data,
arch: '<form>' +
'<field name="body" widget="html" style="height: 100px"/>' +
'</form>',
res_id: 1,
mockRPC: function (route, args) {
if (args.method === "write") {
assert.strictEqual(args.args[1].body,
'<p>t<font class="bg-o-color-3">oto toto </font>toto</p><p>tata</p>',
"should save the content");
}
return this._super.apply(this, arguments);
},
});
await testUtils.form.clickEdit(form);
var $field = form.$('.oe_form_field[name="body"]');
// select the text
var pText = $field.find('.note-editable p').first().contents()[0];
Wysiwyg.setRange(pText, 1, pText, 10);
// text is selected
async function openColorpicker(selector) {
const $colorpicker = $field.find(selector);
const openingProm = new Promise(resolve => {
$colorpicker.one('shown.bs.dropdown', () => resolve());
});
await testUtils.dom.click($colorpicker.find('button:first'));
return openingProm;
}
await openColorpicker('.note-toolbar .<API key>');
await testUtils.dom.click($field.find('.note-toolbar .<API key> .o_we_color_btn.bg-o-color-3'));
await testUtils.form.clickSave(form);
form.destroy();
});
QUnit.module('cssReadonly');
QUnit.test('rendering with iframe for readonly mode', async function (assert) {
assert.expect(3);
var form = await testUtils.createView({
View: FormView,
model: 'note.note',
data: this.data,
arch: '<form>' +
'<field name="body" widget="html" style="height: 100px" options="{\'cssReadonly\': \'template.assets\'}"/>' +
'</form>',
res_id: 1,
});
var $field = form.$('.oe_form_field[name="body"]');
var $iframe = $field.find('iframe.o_readonly');
await $iframe.data('loadDef');
var doc = $iframe.contents()[0];
assert.strictEqual($(doc).find('#iframe_target').html(),
'<p>toto toto toto</p><p>tata</p>',
"should have rendered a div with correct content in readonly");
assert.strictEqual(doc.defaultView.getComputedStyle(doc.body).backgroundColor,
'rgb(255, 0, 0)',
"should load the asset css");
await testUtils.form.clickEdit(form);
$field = form.$('.oe_form_field[name="body"]');
assert.strictEqual($field.find('.note-editable').html(),
'<p>toto toto toto</p><p>tata</p>',
"should have rendered the field correctly in edit");
form.destroy();
});
QUnit.module('translation');
QUnit.test('field html translatable', async function (assert) {
assert.expect(4);
var multiLang = _t.database.multi_lang;
_t.database.multi_lang = true;
this.data['note.note'].fields.body.translate = true;
var form = await testUtils.createView({
View: FormView,
model: 'note.note',
data: this.data,
arch: '<form string="Partners">' +
'<field name="body" widget="html"/>' +
'</form>',
res_id: 1,
mockRPC: function (route, args) {
if (route === '/web/dataset/call_button' && args.method === 'translate_fields') {
assert.deepEqual(args.args, ['note.note', 1, 'body'], "should call 'call_button' route");
return Promise.resolve({
domain: [],
context: {search_default_name: 'partnes,foo'},
});
}
if (route === "/web/dataset/call_kw/res.lang/get_installed") {
return Promise.resolve([["en_US"], ["fr_BE"]]);
}
return this._super.apply(this, arguments);
},
});
assert.strictEqual(form.$('.oe_form_field_html .o_field_translate').length, 0,
"should not have a translate button in readonly mode");
await testUtils.form.clickEdit(form);
var $button = form.$('.oe_form_field_html .o_field_translate');
assert.strictEqual($button.length, 1, "should have a translate button");
await testUtils.dom.click($button);
assert.containsOnce($(document), '.<API key>', 'should have a modal to translate');
form.destroy();
_t.database.multi_lang = multiLang;
});
});
});
}); |
"use strict";
require("./setup");
var exchange = require("../src/exchange"),
assert = require("assert"),
config = require("config"),
async = require("async");
describe("Exchange", function () {
describe("rounding", function () {
it("should round as expected", function() {
assert.equal( exchange.round("USD", 33.38 + 10.74), 44.12);
});
});
describe("Load and keep fresh the exchange rates", function () {
it("should be using test path", function () {
// check it is faked out for tests
var stubbedPath = "config/<API key>.json";
assert.equal( exchange.pathToLatestJSON(), stubbedPath);
// check it is normally correct
exchange.pathToLatestJSON.restore();
assert.notEqual( exchange.pathToLatestJSON(), stubbedPath);
});
it("fx object should convert correctly", function () {
assert.equal(exchange.convert(100, "GBP", "USD"), 153.85 ); // 2 dp
assert.equal(exchange.convert(100, "GBP", "JPY"), 15083 ); // 0 dp
assert.equal(exchange.convert(100, "GBP", "LYD"), 195.385 ); // 3 dp
assert.equal(exchange.convert(100, "GBP", "XAG"), 6.15 ); // null dp
});
it("should reload exchange rates periodically", function (done) {
var fx = exchange.fx;
var clock = this.sandbox.clock;
// change one of the exchange rates to test for the reload
var originalGBP = fx.rates.GBP;
fx.rates.GBP = 123.456;
// start the delayAndReload
exchange.<API key>();
// work out how long to wait
var delay = exchange.<API key>();
// go almost to the roll over and check no change
clock.tick( delay-10 );
assert.equal(fx.rates.GBP, 123.456);
async.series([
function (cb) {
// go past rollover and check for change
exchange.hub.once("reloaded", function () {
assert.equal(fx.rates.GBP, originalGBP);
cb();
});
clock.tick( 20 );
},
function (cb) {
// reset it again and go ahead another interval and check for change
fx.rates.GBP = 123.456;
exchange.hub.once("reloaded", function () {
assert.equal(fx.rates.GBP, originalGBP);
cb();
});
clock.tick( config.<API key> * 1000 );
}
], done);
});
it.skip("should handle bad exchange rates JSON");
});
}); |
<?php
require_once __BASE__.'/model/Storable.php';
class AccountSMTP extends Storable
{
public $id = MYSQL_PRIMARY_KEY;
public $code = '';
public $created = MYSQL_DATETIME;
public $last_edit = MYSQL_DATETIME;
public $name = '';
public $host = '';
public $port = '';
public $connection = '';
public $username = '';
public $password = '';
public $sender_name = '';
public $sender_mail = '';
public $replyTo = '';
public $max_mail = 0;
public $ever = ['day', 'week', 'month', 'year', 'onetime'];
public $max_mail_day = 0;
public $send = 0;
public $last_send = MYSQL_DATETIME;
public $perc = 0.0;
public $total_send = 0;
public $active = 1;
public static function findServer()
{
$servers = self::query(
[
'active' => 1,
]);
$perc = 110;
foreach ($servers as $server) {
if ($server->perc < $perc) {
$use = $server;
}
if ($server->perc == 0) {
return $use;
}
}
return $use;
}
public static function getMaxMail($account = 'all')
{
$append = $account != 'all' ? ' WHERE id = "'.$account.'"' : ' ';
$sql = 'SELECT SUM(max_mail_day) AS maxmail FROM '.self::table().$append;
$res = schemadb::execute('row', $sql);
return $res['maxmail'];
}
public static function getSenderMail($account = 'all')
{
$append = $account != 'all' ? ' WHERE id = "'.$account.'"' : ' ';
$sql = 'SELECT SUM(total_send) AS mailtotali FROM '.self::table().$append;
$res = schemadb::execute('row', $sql);
return $res['mailtotali'];
}
public static function getInviateMail($account = 'all')
{
$append = $account != 'all' ? ' WHERE id = "'.$account.'"' : ' ';
$sql = 'SELECT SUM(send) AS inviate FROM '.self::table().$append;
$res = schemadb::execute('row', $sql);
return $res['inviate'];
}
public static function getRemainMail($account = 'all')
{
$remain = self::getMaxMail() - self::getInviateMail();
return $remain;
}
}
AccountSMTP::schemadb_update(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.