text
stringlengths 2
6.14k
|
|---|
/* Copyright (C) 2013-2022 TU Dortmund
* This file is part of AutomataLib, http://www.automatalib.net/.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.automatalib.automata.words.growing;
import java.util.List;
import net.automatalib.automata.words.util.AlphabetTestUtil;
import net.automatalib.words.impl.GrowingMapAlphabet;
/**
* @author frohme
*/
public class GrowingMapAlphabetTest extends AbstractGrowingAlphabetTest<Integer, GrowingMapAlphabet<Integer>> {
@Override
protected List<Integer> getInitialAlphabetSymbols() {
return AlphabetTestUtil.CONTAINED_SYMBOLS_LIST;
}
@Override
protected List<Integer> getAdditionalAlphabetSymbols() {
return AlphabetTestUtil.NON_CONTAINED_SYMBOLS_LIST;
}
@Override
protected GrowingMapAlphabet<Integer> getInitialAlphabet() {
return new GrowingMapAlphabet<>(AlphabetTestUtil.CONTAINED_SYMBOLS_LIST);
}
}
|
"""
"""
import datetime
import json
import logging
import subprocess
import torch.distributed as dist
logger = logging.getLogger('mlbench')
def _warp(string, symbol='*', length=80):
one_side_length = (length - len(string) - 2) // 2
if one_side_length > 0:
return symbol * one_side_length + ' ' + string + ' ' + symbol * one_side_length
else:
return string
def centering(content, who='all', symbol='*', length=80):
info(_warp(content, symbol, length), who=who)
def info(content, who='all'):
if who == 'all' or who == dist.get_rank():
logger.info(content)
def debug(content, who='all'):
if who == 'all' or who == dist.get_rank():
logger.debug(content)
def warning(content, who='all'):
if who == 'all' or who == dist.get_rank():
logger.warning("{}".format(content))
class AsyncMetricsPost(object):
"""Post metrics payload to endpoint in an asynchronized way."""
def __init__(self):
self._initialized = False
self._incluster = True
def init(self):
from kubernetes import config, client
try:
config.load_incluster_config()
except Exception as e:
self._incluster = False
return
configuration = client.Configuration()
class MyApiClient(client.ApiClient):
"""
A bug introduced by a fix.
https://github.com/kubernetes-client/python/issues/411
https://github.com/swagger-api/swagger-codegen/issues/6392
"""
def __del__(self):
pass
self.api_instance = client.CoreV1Api(MyApiClient(configuration))
# TODO: remove hardcoded part in the future.
self.namespace = 'default'
label_selector = 'component=master,app=mlbench'
try:
api_response = self.api_instance.list_namespaced_pod(
self.namespace, label_selector=label_selector)
except Exception as e:
print("Exception when calling CoreV1Api->list_namespaced_pod: %s\n" % e)
assert len(api_response.items) == 1
master_pod = api_response.items[0]
ip = master_pod.status.pod_ip
self.endpoint = "http://{ip}/api/metrics/".format(ip=ip)
self._initialized = True
def post(self, payload):
"""Post information via kubernetes client.
Example:
>>> async_post = AsyncMetricsPost()
>>> payload = {
... "run_id": "1",
... "name": "accuracy",
... "cumulative": False,
... "date": "2018-08-14T09:21:44.331823Z",
... "value": "1.0",
... "metadata": "some additional data"
... }
>>> async_post.post(payload)
See `KubeMetric` in kubemetric.py for the fields and types.
"""
if not self._initialized:
self.init()
if not self._incluster:
return
command = [
"/usr/bin/curl",
"-d", json.dumps(payload),
"-H", "Content-Type: application/json",
"-X", "POST", self.endpoint
]
subprocess.Popen(command)
async_post = AsyncMetricsPost()
def _post_metrics(payload, rank, dont_post_to_dashboard):
if rank == 0 and not dont_post_to_dashboard and async_post._incluster:
async_post.post(payload)
def configuration_information(options):
centering("Configuration Information", 0)
options.log('meta')
options.log('optimizer')
options.log('model')
options.log('dataset')
options.log('controlflow')
centering("START TRAINING", 0)
def log_val(options, best_metric_name):
info('{} for rank {}:(best epoch {}, current epoch {}): {:.3f}'.format(
best_metric_name,
options.rank,
options.runtime['best_epoch'],
options.runtime['current_epoch'],
options.runtime[best_metric_name]), 0)
def post_metrics(options, metric_name, value):
data = {
"run_id": options.run_id,
"rank": options.rank,
"name": metric_name,
"value": "{:.6f}".format(value),
"date": str(datetime.datetime.now()),
"epoch": str(options.runtime['current_epoch']),
"cumulative": "False",
"metadata": ""
}
_post_metrics(data, options.rank, options.dont_post_to_dashboard)
options.runtime['records'].append(data)
|
import os
from wptserve.utils import isomorphic_decode
def get_template(template_basename):
script_directory = os.path.dirname(os.path.abspath(isomorphic_decode(__file__)))
template_directory = os.path.abspath(
os.path.join(script_directory, u"template"))
template_filename = os.path.join(template_directory, template_basename)
with open(template_filename, "r") as f:
return f.read()
def __noop(request, response):
return u""
def respond(request,
response,
status_code=200,
content_type=b"text/html",
payload_generator=__noop,
cache_control=b"no-cache; must-revalidate",
access_control_allow_origin=b"*",
maybe_additional_headers=None):
response.add_required_headers = False
response.writer.write_status(status_code)
if access_control_allow_origin != None:
response.writer.write_header(b"access-control-allow-origin",
access_control_allow_origin)
response.writer.write_header(b"content-type", content_type)
response.writer.write_header(b"cache-control", cache_control)
additional_headers = maybe_additional_headers or {}
for header, value in additional_headers.items():
response.writer.write_header(header, value)
response.writer.end_headers()
payload = payload_generator()
response.writer.write(payload)
|
Boolean({
x: 0,,
});
|
'use strict';
/**
* @ngdoc directive
* @name moviebaseApp.directive:wdcmResults
* @description
* # wdcmResults
*/
angular.module('moviebaseApp')
.directive('wdcmResults', function () {
return {
templateUrl: 'views/directives/wdcm-results.html',
restrict: 'E',
replace: true,
transclude: true,
scope: {
movies: '=',
pages: '=',
detail: '@'
}
};
});
|
#include "layerstack.h"
#include "layer.h"
Event LayerStack::at(const Mask& layerMask,
int row,
int column) const
{
Event keyId;
auto layerIterator(layerMask.bitIterator());
while (layerIterator.more())
{
auto index(layerIterator.next());
auto next(mLayers[index].at(row, column));
if (next != Event())
{
keyId = next;
}
}
return keyId;
}
int LayerStack::activeLayer(const Mask& layerMask,
int row,
int column) const
{
int activeIndex(0);
auto layerIterator(layerMask.bitIterator());
while (layerIterator.more())
{
auto index(layerIterator.next());
auto next(mLayers[index].at(row, column));
if (next != Event())
{
activeIndex = index;
}
}
return activeIndex;
}
Event LayerStack::atIndex(int index, int row, int column) const
{
return mLayers[index].at(row, column);
}
void LayerStack::clear()
{
mLayers = Layers();
}
|
from app import db
from werkzeug import generate_password_hash, check_password_hash
import os
from app import page
from app import whooshee
followers = db.Table('followers',
db.Column('follower_id', db.Integer, db.ForeignKey('user.id')),
db.Column('followed_id', db.Integer, db.ForeignKey('user.id'))
)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
nickname = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
pwdhash = db.Column(db.String(54))
activation_status = db.Column(db.Boolean, index=True)
posts = db.relationship('Post', backref='author', lazy='dynamic')
flwrs = db.Column(db.Integer, index=True)
tokens = db.Column(db.Text)
followed = db.relationship('User',
secondary=followers,
primaryjoin=(followers.c.follower_id == id),
secondaryjoin=(followers.c.followed_id == id),
backref=db.backref('followers', lazy='dynamic'),
lazy='dynamic')
def __init__(self, nickname, email, password):
self.nickname = nickname
self.email = email.lower()
self.set_password(password)
self.activation_status = False
self.flwrs = -1
def follow(self, user):
if not self.is_following(user):
self.followed.append(user)
user.flwrs = user.flwrs + 1
db.session.commit()
return self
def unfollow(self, user):
if self.is_following(user):
self.followed.remove(user)
user.flwrs = user.flwrs - 1
db.session.commit()
return self
def is_following(self, user):
return self.followed.filter(followers.c.followed_id == user.id).count() > 0
def has_liked(self, post_id):
res = Like.query.filter_by(post_id = post_id).all()
for r in res:
if r.user_id == self.id:
return True
return False
def has_bookmarked(self, post_id):
res = Bookmark.query.filter_by(post_id = post_id).all()
for r in res:
if r.user_id == self.id:
return True
return False
def set_password(self, password):
self.pwdhash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.pwdhash, password)
def make_dirs(self):
os.makedirs('/home/manan/Programs/EduTech/app/static/userdata/'+str(self.nickname), exist_ok=True)
def avatar(self):
for root, dirs, files in os.walk("/home/manan/Programs/EduTech/app/static/userdata/" + str(self.nickname)):
for file in files:
if file.endswith(".jpg") or file.endswith(".png"):
return "/static/userdata/" + str(self.nickname) + '/' + str(file)
return "/static/userdata/avatar.png"
def __repr__(self):
return '<User %s, Email %s, Activation %s>' %(self.nickname, self.email, self.activation_status)
@whooshee.register_model('title', 'body')
class Post(db.Model):
id = db.Column(db.Integer, primary_key = True)
title = db.Column(db.String(140))
body = db.Column(db.String(140))
link = db.Column(db.String(140))
image = db.Column(db.String(140))
timestamp = db.Column(db.DateTime)
likes = db.Column(db.Integer)
category = db.Column(db.String(140))
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
def __repr__(self):
return '%s' %(self.title)
class Like(db.Model):
id = db.Column(db.Integer, primary_key = True)
user_id = db.Column(db.Integer)
post_id = db.Column(db.Integer)
def __init__(self, user_id, post_id):
self.user_id = user_id
self.post_id = post_id
def __repr__(self):
return '%s, %s' %(self.post_id, self.user_id)
class Bookmark(db.Model):
id = db.Column(db.Integer, primary_key = True)
user_id = db.Column(db.Integer)
post_id = db.Column(db.Integer)
def __init__(self, user_id, post_id):
self.user_id = user_id
self.post_id = post_id
def __repr__(self):
return '%s, %s' %(self.post_id, self.user_id)
|
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import copy, httplib, ssl
from cookielib import CookieJar, Cookie
from mechanize import Browser as B, HTTPSHandler
class ModernHTTPSHandler(HTTPSHandler):
ssl_context = None
def https_open(self, req):
if self.client_cert_manager is not None:
key_file, cert_file = self.client_cert_manager.find_key_cert(
req.get_full_url())
if cert_file:
self.ssl_context.load_cert_chain(cert_file, key_file)
def conn_factory(hostport, **kw):
kw['context'] = self.ssl_context
return httplib.HTTPSConnection(hostport, **kw)
return self.do_open(conn_factory, req)
class Browser(B):
'''
A cloneable mechanize browser. Useful for multithreading. The idea is that
each thread has a browser clone. Every clone uses the same thread safe
cookie jar. All clones share the same browser configuration.
Also adds support for fine-tuning SSL verification via an SSL context object.
'''
handler_classes = B.handler_classes.copy()
handler_classes['https'] = ModernHTTPSHandler
def __init__(self, *args, **kwargs):
self._clone_actions = {}
sc = kwargs.pop('ssl_context', None)
if sc is None:
sc = ssl.create_default_context() if kwargs.pop('verify_ssl', True) else ssl._create_unverified_context(cert_reqs=ssl.CERT_NONE)
B.__init__(self, *args, **kwargs)
self.set_cookiejar(CookieJar())
self._ua_handlers['https'].ssl_context = sc
@property
def https_handler(self):
return self._ua_handlers['https']
def set_current_header(self, header, value=None):
found = False
q = header.lower()
remove = []
for i, (k, v) in enumerate(tuple(self.addheaders)):
if k.lower() == q:
if value:
self.addheaders[i] = (header, value)
found = True
else:
remove.append(i)
if not found:
self.addheaders.append((header, value))
if remove:
for i in reversed(remove):
del self.addheaders[i]
def current_user_agent(self):
for k, v in self.addheaders:
if k.lower() == 'user-agent':
return v
def set_user_agent(self, newval):
self.set_current_header('User-agent', newval)
def set_handle_refresh(self, *args, **kwargs):
B.set_handle_refresh(self, *args, **kwargs)
self._clone_actions['set_handle_refresh'] = ('set_handle_refresh',
args, kwargs)
def set_cookiejar(self, *args, **kwargs):
B.set_cookiejar(self, *args, **kwargs)
self._clone_actions['set_cookiejar'] = ('set_cookiejar', args, kwargs)
def set_cookie(self, name, value, domain, path='/'):
self.cookiejar.set_cookie(Cookie(
None, name, value,
None, False,
domain, True, False,
path, True,
False, None, False, None, None, None
))
@property
def cookiejar(self):
return self._clone_actions['set_cookiejar'][1][0]
def set_handle_redirect(self, *args, **kwargs):
B.set_handle_redirect(self, *args, **kwargs)
self._clone_actions['set_handle_redirect'] = ('set_handle_redirect',
args, kwargs)
def set_handle_equiv(self, *args, **kwargs):
B.set_handle_equiv(self, *args, **kwargs)
self._clone_actions['set_handle_equiv'] = ('set_handle_equiv',
args, kwargs)
def set_handle_gzip(self, handle):
B._set_handler(self, '_gzip', handle)
self._clone_actions['set_handle_gzip'] = ('set_handle_gzip',
(handle,), {})
def set_debug_redirects(self, *args, **kwargs):
B.set_debug_redirects(self, *args, **kwargs)
self._clone_actions['set_debug_redirects'] = ('set_debug_redirects',
args, kwargs)
def set_debug_responses(self, *args, **kwargs):
B.set_debug_responses(self, *args, **kwargs)
self._clone_actions['set_debug_responses'] = ('set_debug_responses',
args, kwargs)
def set_debug_http(self, *args, **kwargs):
B.set_debug_http(self, *args, **kwargs)
self._clone_actions['set_debug_http'] = ('set_debug_http',
args, kwargs)
def set_handle_robots(self, *args, **kwargs):
B.set_handle_robots(self, *args, **kwargs)
self._clone_actions['set_handle_robots'] = ('set_handle_robots',
args, kwargs)
def set_proxies(self, *args, **kwargs):
B.set_proxies(self, *args, **kwargs)
self._clone_actions['set_proxies'] = ('set_proxies', args, kwargs)
def add_password(self, *args, **kwargs):
B.add_password(self, *args, **kwargs)
self._clone_actions['add_password'] = ('add_password', args, kwargs)
def add_proxy_password(self, *args, **kwargs):
B.add_proxy_password(self, *args, **kwargs)
self._clone_actions['add_proxy_password'] = ('add_proxy_password', args, kwargs)
def clone_browser(self):
clone = Browser()
clone.https_handler.ssl_context = self.https_handler.ssl_context
clone.addheaders = copy.deepcopy(self.addheaders)
for func, args, kwargs in self._clone_actions.values():
func = getattr(clone, func)
func(*args, **kwargs)
return clone
if __name__ == '__main__':
from calibre import browser
from pprint import pprint
orig = browser()
clone = orig.clone_browser()
pprint(orig._ua_handlers)
pprint(clone._ua_handlers)
assert orig._ua_handlers.keys() == clone._ua_handlers.keys()
assert orig._ua_handlers['_cookies'].cookiejar is \
clone._ua_handlers['_cookies'].cookiejar
assert orig.addheaders == clone.addheaders
|
from __future__ import division
from collections import OrderedDict
from vsr.modules.metrics.measures import precision,recall
import sys
# the f score produces a value that weights both recall and precision. The value beta (positive real) is
# the magnitude with which recall should be considered more important than precision. When beta is 1,
# it means that both recall and precision are given equal weights
def calculate(expected_results,actual_results,beta=1):
assert(expected_results.keys() == actual_results.keys())
precisions = precision.calculate(expected_results,actual_results)
recalls = recall.calculate(expected_results,actual_results)
f_scores = OrderedDict()
for query_id,doc_id in expected_results.iteritems():
p = precisions[query_id]
r = recalls[query_id]
try:
f_score = ( (1 + pow(beta,2) ) *( p * r ) ) / ( ( pow(beta,2) * p ) + r )
except ZeroDivisionError:
continue
sys.exit()
f_scores[query_id] = round(f_score,3)
return(f_scores)
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/lookoutvision/model/DescribeModelPackagingJobResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::LookoutforVision::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
DescribeModelPackagingJobResult::DescribeModelPackagingJobResult()
{
}
DescribeModelPackagingJobResult::DescribeModelPackagingJobResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
DescribeModelPackagingJobResult& DescribeModelPackagingJobResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("ModelPackagingDescription"))
{
m_modelPackagingDescription = jsonValue.GetObject("ModelPackagingDescription");
}
return *this;
}
|
# Copyright 2016-2017 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import unicode_literals
from __future__ import division
from __future__ import print_function
from trappy.base import Base
from trappy.dynamic import register_ftrace_parser
class CpuIdle(Base):
"""Parse cpu_idle"""
unique_word = "cpu_idle"
pivot = "cpu_id"
def finalize_object(self):
# The trace contains "4294967295" instead of "-1" when exiting an idle
# state.
uint32_max = (2 ** 32) - 1
self.data_frame.replace(uint32_max, -1, inplace=True)
super(CpuIdle, self).finalize_object()
register_ftrace_parser(CpuIdle)
|
/*******************************************************************************
* Copyright (c) 2012-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.ide.api.event.ng;
import com.google.web.bindery.event.shared.EventBus;
import org.eclipse.che.api.core.jsonrpc.commons.RequestHandlerConfigurator;
import org.eclipse.che.api.project.shared.dto.event.FileStateUpdateDto;
import org.eclipse.che.api.project.shared.dto.event.FileWatcherEventType;
import org.eclipse.che.ide.api.app.AppContext;
import org.eclipse.che.ide.api.editor.EditorAgent;
import org.eclipse.che.ide.api.editor.EditorPartPresenter;
import org.eclipse.che.ide.api.event.FileContentUpdateEvent;
import org.eclipse.che.ide.api.notification.NotificationManager;
import org.eclipse.che.ide.api.resources.ExternalResourceDelta;
import org.eclipse.che.ide.resource.Path;
import org.eclipse.che.ide.util.loging.Log;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import java.util.List;
import java.util.function.BiConsumer;
import static org.eclipse.che.ide.api.notification.StatusNotification.DisplayMode.EMERGE_MODE;
import static org.eclipse.che.ide.api.notification.StatusNotification.Status.SUCCESS;
import static org.eclipse.che.ide.api.resources.ResourceDelta.REMOVED;
/**
* Receives file status notifications from sever VFS file watchers for registered files.
* The list of registered files contains files opened in an editor. Notifications can be
* of only two types: file modified and file deleted. Each kind of notification invokes
* specified behaviour.
*
* @author Dmitry Kuleshov
*/
@Singleton
public class EditorFileStatusNotificationOperation implements BiConsumer<String, FileStateUpdateDto> {
private final EventBus eventBus;
private final DeletedFilesController deletedFilesController;
private final Provider<EditorAgent> editorAgentProvider;
private final AppContext appContext;
private NotificationManager notificationManager;
@Inject
public EditorFileStatusNotificationOperation(EventBus eventBus,
DeletedFilesController deletedFilesController,
Provider<EditorAgent> editorAgentProvider,
AppContext appContext) {
this.eventBus = eventBus;
this.deletedFilesController = deletedFilesController;
this.editorAgentProvider = editorAgentProvider;
this.appContext = appContext;
}
@Inject
public void configureHandler(RequestHandlerConfigurator configurator) {
configurator.newConfiguration()
.methodName("event:file-state-changed")
.paramsAsDto(FileStateUpdateDto.class)
.noResult()
.withBiConsumer(this);
}
public void inject(NotificationManager notificationManager) {
this.notificationManager = notificationManager;
}
public void accept(String endpointId, FileStateUpdateDto params) {
final FileWatcherEventType status = params.getType();
final String stringPath = params.getPath();
final String name = stringPath.substring(stringPath.lastIndexOf("/") + 1);
switch (status) {
case MODIFIED: {
Log.debug(getClass(), "Received updated file event status: " + stringPath);
eventBus.fireEvent(new FileContentUpdateEvent(stringPath, params.getHashCode()));
break;
}
case DELETED: {
Log.debug(getClass(), "Received removed file event status: " + stringPath);
final Path path = Path.valueOf(stringPath);
appContext.getWorkspaceRoot().synchronize(new ExternalResourceDelta(path, path, REMOVED));
if (notificationManager != null && !deletedFilesController.remove(stringPath)) {
notificationManager.notify("External operation", "File '" + name + "' is removed", SUCCESS, EMERGE_MODE);
closeOpenedEditor(path);
}
break;
}
}
}
private void closeOpenedEditor(Path path) {
final EditorAgent editorAgent = editorAgentProvider.get();
final List<EditorPartPresenter> openedEditors = editorAgent.getOpenedEditors();
for (EditorPartPresenter openEditor : openedEditors) {
if (openEditor.getEditorInput().getFile().getLocation().equals(path)) {
editorAgent.closeEditor(openEditor);
}
}
}
}
|
#!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
## \package pts.do.developer.deinstall_all Uninstall SKIRT/PTS on all remotes.
# -----------------------------------------------------------------
# Ensure Python 3 compatibility
from __future__ import absolute_import, division, print_function
# Import the relevant PTS classes and modules
from pts.core.prep.uninstaller import Uninstaller
from pts.core.remote.host import find_host_ids
from pts.core.basics.log import log
from pts.core.remote.remote import Remote
from pts.core.basics.configuration import ConfigurationDefinition, parse_arguments
# -----------------------------------------------------------------
# Create definition
definition = ConfigurationDefinition()
definition.add_positional_optional("skirt_and_or_pts", "string_list", "SKIRT and/or PTS", default=["skirt", "pts"], choices=["skirt", "pts"])
# Add flags
definition.add_flag("conda", "also remove conda installation")
definition.add_flag("qt", "also remove Qt installation")
definition.add_flag("one_attempt", "only perform one attempt at connecting to a remote")
# Get the config
config = parse_arguments("deinstall_all", definition)
# -----------------------------------------------------------------
# Loop over the remote hosts
for host_id in find_host_ids():
# Setup
remote = Remote()
if not remote.setup(host_id, one_attempt=config.one_attempt):
log.warning("Remote host '" + host_id + "' is offline")
continue
# Create uninstaller
uninstaller = Uninstaller()
# Set options
uninstaller.config.skirt_and_or_pts = config.skirt_and_or_pts
uninstaller.config.conda = config.conda
uninstaller.config.qt = config.qt
# Inform the user
log.info("Running the uninstaller for remote host '" + host_id + "' ...")
# Uninstall
uninstaller.run(remote=remote)
# -----------------------------------------------------------------
|
{% load wagtailcore_tags %}
{{ email_text|richtext }}
<p>To reset your password click here:</p>
<p><a href="{{ reset_link }}">{{ reset_link }}</a></p>
|
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
import signal
import sys
from random import randint
import os, pipes
from shutil import rmtree
from shutil import copyfile
import subprocess
class PdfMaker:
def cmdparse(self, cmd):
fct = {
'help': self.helpmenu,
'?': self.helpmenu,
'create': self.create,
'show': self.show,
'compile': self.compilePDF,
'flag': self.flag
}.get(cmd, self.unknown)
return fct
def handle(self):
self.initConnection()
print " Welcome to p.d.f.maker! Send '?' or 'help' to get the help. Type 'exit' to disconnect."
instruction_counter = 0
while(instruction_counter < 77):
try:
cmd = (raw_input("> ")).strip().split()
if len(cmd) < 1:
continue
if cmd[0] == "exit":
self.endConnection()
return
print self.cmdparse(cmd[0])(cmd)
instruction_counter += 1
except Exception, e:
print "An Exception occured: ", e.args
self.endConnection()
break
print "Maximum number of instructions reached"
self.endConnection()
def initConnection(self):
cwd = os.getcwd()
self.directory = cwd + "/tmp/" + str(randint(0, 2**60))
while os.path.exists(self.directory):
self.directory = cwd + "/tmp/" + str(randint(0, 2**60))
os.makedirs(self.directory)
flag = self.directory + "/" + "33C3" + "%X" % randint(0, 2**31) + "%X" % randint(0, 2**31)
copyfile("flag", flag)
def endConnection(self):
if os.path.exists(self.directory):
rmtree(self.directory)
def unknown(self, cmd):
return "Unknown Command! Type 'help' or '?' to get help!"
def helpmenu(self, cmd):
if len(cmd) < 2:
return " Available commands: ?, help, create, show, compile.\n Type 'help COMMAND' to get information about the specific command."
if (cmd[1] == "create"):
return (" Create a file. Syntax: create TYPE NAME\n"
" TYPE: type of the file. Possible types are log, tex, sty, mp, bib\n"
" NAME: name of the file (without type ending)\n"
" The created file will have the name NAME.TYPE")
elif (cmd[1] == "show"):
return (" Shows the content of a file. Syntax: show TYPE NAME\n"
" TYPE: type of the file. Possible types are log, tex, sty, mp, bib\n"
" NAME: name of the file (without type ending)")
elif (cmd[1] == "compile"):
return (" Compiles a tex file with the help of pdflatex. Syntax: compile NAME\n"
" NAME: name of the file (without type ending)")
def show(self, cmd):
if len(cmd) < 3:
return " Invalid number of parameters. Type 'help show' to get more info."
if not cmd[1] in ["log", "tex", "sty", "mp", "bib"]:
return " Invalid file ending. Only log, tex, sty and mp allowed"
filename = cmd[2] + "." + cmd[1]
full_filename = os.path.join(self.directory, filename)
full_filename = os.path.abspath(full_filename)
if full_filename.startswith(self.directory) and os.path.exists(full_filename):
with open(full_filename, "r") as file:
content = file.read()
else:
content = "File not found."
return content
def flag(self, cmd):
pass
def create(self, cmd):
if len(cmd) < 3:
return " Invalid number of parameters. Type 'help create' to get more info."
if not cmd[1] in ["log", "tex", "sty", "mp", "bib"]:
return " Invalid file ending. Only log, tex, sty and mp allowed"
filename = cmd[2] + "." + cmd[1]
full_filename = os.path.join(self.directory, filename)
full_filename = os.path.abspath(full_filename)
if not full_filename.startswith(self.directory):
return "Could not create file."
with open(full_filename, "w") as file:
print "File created. Type the content now and finish it by sending a line containing only '\q'."
while 1:
text = raw_input("");
if text.strip("\n") == "\q":
break
write_to_file = True;
for filter_item in ("..", "*", "/", "\\x"):
if filter_item in text:
write_to_file = False
break
if (write_to_file):
file.write(text + "\n")
return "Written to " + filename + "."
def compilePDF(self, cmd):
if (len(cmd) < 2):
return " Invalid number of parameters. Type 'help compile' to get more info."
filename = cmd[1] + ".tex"
full_filename = os.path.join(self.directory, filename)
full_filename = os.path.abspath(full_filename)
if not full_filename.startswith(self.directory) or not os.path.exists(full_filename):
return "Could not compile file."
compile_command = "cd " + self.directory + " && pdflatex " + pipes.quote(full_filename)
compile_result = subprocess.check_output(compile_command, shell=True)
return compile_result
def signal_handler_sigint(signal, frame):
print 'Exiting...'
pdfmaker.endConnection()
sys.exit(0)
if __name__ == "__main__":
signal.signal(signal.SIGINT, signal_handler_sigint)
pdfmaker = PdfMaker()
pdfmaker.handle()
|
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""TensorBoard HTTP utilities."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import gzip
import json
import re
import time
import wsgiref.handlers
import six
from werkzeug import wrappers
from tensorflow.python.util import compat
from tensorflow.tensorboard.lib.python import json_util
_EXTRACT_MIMETYPE_PATTERN = re.compile(r'^[^;\s]*')
_EXTRACT_CHARSET_PATTERN = re.compile(r'charset=([-_0-9A-Za-z]+)')
# Allows *, gzip or x-gzip, but forbid gzip;q=0
# https://tools.ietf.org/html/rfc7231#section-5.3.4
_ALLOWS_GZIP_PATTERN = re.compile(
r'(?:^|,|\s)(?:(?:x-)?gzip|\*)(?!;q=0)(?:\s|,|$)')
_TEXTUAL_MIMETYPES = set([
'application/javascript',
'application/json',
'application/json+protobuf',
'image/svg+xml',
'text/css',
'text/csv',
'text/html',
'text/plain',
'text/tab-separated-values',
'text/x-protobuf',
])
_JSON_MIMETYPES = set([
'application/json',
'application/json+protobuf',
])
def Respond(request,
content,
content_type,
code=200,
expires=0,
content_encoding=None,
encoding='utf-8'):
"""Construct a werkzeug Response.
Responses are transmitted to the browser with compression if: a) the browser
supports it; b) it's sane to compress the content_type in question; and c)
the content isn't already compressed, as indicated by the content_encoding
parameter.
Browser and proxy caching is completely disabled by default. If the expires
parameter is greater than zero then the response will be able to be cached by
the browser for that many seconds; however, proxies are still forbidden from
caching so that developers can bypass the cache with Ctrl+Shift+R.
For textual content that isn't JSON, the encoding parameter is used as the
transmission charset which is automatically appended to the Content-Type
header. That is unless of course the content_type parameter contains a
charset parameter. If the two disagree, the characters in content will be
transcoded to the latter.
If content_type declares a JSON media type, then content MAY be a dict, list,
tuple, or set, in which case this function has an implicit composition with
json_util.Cleanse and json.dumps. The encoding parameter is used to decode
byte strings within the JSON object; therefore transmitting binary data
within JSON is not permitted. JSON is transmitted as ASCII unless the
content_type parameter explicitly defines a charset parameter, in which case
the serialized JSON bytes will use that instead of escape sequences.
Args:
request: A werkzeug Request object. Used mostly to check the
Accept-Encoding header.
content: Payload data as byte string, unicode string, or maybe JSON.
content_type: Media type and optionally an output charset.
code: Numeric HTTP status code to use.
expires: Second duration for browser caching.
content_encoding: Encoding if content is already encoded, e.g. 'gzip'.
encoding: Input charset if content parameter has byte strings.
Returns:
A werkzeug Response object (a WSGI application).
"""
mimetype = _EXTRACT_MIMETYPE_PATTERN.search(content_type).group(0)
charset_match = _EXTRACT_CHARSET_PATTERN.search(content_type)
charset = charset_match.group(1) if charset_match else encoding
textual = charset_match or mimetype in _TEXTUAL_MIMETYPES
if mimetype in _JSON_MIMETYPES and (isinstance(content, dict) or
isinstance(content, list) or
isinstance(content, set) or
isinstance(content, tuple)):
content = json.dumps(json_util.Cleanse(content, encoding),
ensure_ascii=not charset_match)
if charset != encoding:
content = compat.as_text(content, encoding)
content = compat.as_bytes(content, charset)
if textual and not charset_match and mimetype not in _JSON_MIMETYPES:
content_type += '; charset=' + charset
if (not content_encoding and textual and
_ALLOWS_GZIP_PATTERN.search(request.headers.get('Accept-Encoding', ''))):
out = six.BytesIO()
f = gzip.GzipFile(fileobj=out, mode='wb', compresslevel=3)
f.write(content)
f.close()
content = out.getvalue()
content_encoding = 'gzip'
if request.method == 'HEAD':
content = ''
headers = []
headers.append(('Content-Length', str(len(content))))
if content_encoding:
headers.append(('Content-Encoding', content_encoding))
if expires > 0:
e = wsgiref.handlers.format_date_time(time.time() + float(expires))
headers.append(('Expires', e))
headers.append(('Cache-Control', 'private, max-age=%d' % expires))
else:
headers.append(('Expires', '0'))
headers.append(('Cache-Control', 'no-cache, must-revalidate'))
return wrappers.Response(
response=content, status=code, headers=headers, content_type=content_type)
|
<div id="page-content">
<div class="card card-md">
<div class="card-header">Log in</div>
<form action="#" method="post">
<paper-input-decorator floatingLabel label="Username">
<input is="core-input" name="username" id="username">
</paper-input-decorator>
<paper-input-decorator floatingLabel label="Password">
<input is="core-input" name="password" id="password" type="password">
</paper-input-decorator>
<div horizontal center-justified layout>
<button type="submit" id="connexion" onclick="document.getElementById('toast').show()" is="paper-button-submit">
Log in
</button>
</div>
<paper-toast id="toast" text="Your username or password is incorrect."></paper-toast>
<paper-toast id="toastError" text="Server unreachable."></paper-toast>
</form>
<script>
$(function() {
'use strict';
/**
* Logs the user in.
*
* @param {object} e The event
*/
$('#connexion').on('click', function(e) {
e.preventDefault();
var objet = {
login: $('#username').val(),
password: $('#password').val()
}
$.ajax({
data: objet,
type: 'GET',
url: 'http://164.81.20.57/gestion_js/php/checkPassword.php',
headers: {
"Access-Control-Allow-Origin": 'http://164.81.20.57:3030',
"Access-Control-Allow-Methods": 'GET, POST, OPTIONS, PUT, PATCH, DELETE',
'Access-Control-Allow-Headers': 'X-Requested-With,content-type',
'Access-Control-Allow-Credentials': true
},
success: function(user) {
if (user) {
$('#login').html('Connecté en tant que ' + user.login);
$('#login').append(' (' + user.nbCredit + ' crédits)');
$(location).attr('href', '#home');
} else {
console.log('Erreur d\'authentification');
}
},
error: function(err) {
document.getElementById('toastError').show();
}
});
});
});
</script>
</div>
</div>
|
/*
Mango - Open Source M2M - http://mango.serotoninsoftware.com
Copyright (C) 2006-2011 Serotonin Software Technologies Inc.
@author Matthew Lohbihler
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.serotonin.mango.view.component;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import com.serotonin.json.JsonRemoteEntity;
import com.serotonin.json.JsonRemoteProperty;
import com.serotonin.mango.DataTypes;
import com.serotonin.mango.rt.dataImage.PointValueTime;
import com.serotonin.mango.rt.dataImage.types.NumericValue;
import com.serotonin.mango.view.ImplDefinition;
/**
* @author Matthew Lohbihler
*/
@JsonRemoteEntity
public class AnalogGraphicComponent extends ImageSetComponent {
public static ImplDefinition DEFINITION = new ImplDefinition("analogGraphic", "ANALOG_GRAPHIC",
"graphic.analogGraphic", new int[] { DataTypes.NUMERIC });
@JsonRemoteProperty
private double min;
@JsonRemoteProperty
private double max;
public double getMin() {
return min;
}
public void setMin(double min) {
this.min = min;
}
public double getMax() {
return max;
}
public void setMax(double max) {
this.max = max;
}
@Override
public ImplDefinition definition() {
return DEFINITION;
}
@Override
public String getImage(PointValueTime pointValue) {
if (imageSet == null)
// Image set not loaded?
return "imageSetNotLoaded";
if (pointValue == null || !(pointValue.getValue() instanceof NumericValue) || imageSet.getImageCount() == 1)
return imageSet.getImageFilename(0);
double dvalue = pointValue.getDoubleValue();
int index = (int) ((dvalue - min) / (max - min) * imageSet.getImageCount());
if (index < 0)
index = 0;
if (index >= imageSet.getImageCount())
index = imageSet.getImageCount() - 1;
return imageSet.getImageFilename(index);
}
//
// /
// / Serialization
// /
//
private static final long serialVersionUID = -1;
private static final int version = 1;
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeInt(version);
out.writeDouble(min);
out.writeDouble(max);
}
private void readObject(ObjectInputStream in) throws IOException {
int ver = in.readInt();
// Switch on the version of the class so that version changes can be elegantly handled.
if (ver == 1) {
min = in.readDouble();
max = in.readDouble();
}
}
}
|
""""""
import importlib
class StructGenerator:
"""Struct生成器"""
def __init__(self, filename: str, prefix: str):
"""Constructor"""
self.filename = filename
self.prefix = prefix
self.typedefs = {}
self.current_struct = {}
self.load_constant()
def load_constant(self):
""""""
module_name = f"{self.prefix}_typedef"
module = importlib.import_module(module_name)
for name in dir(module):
if "__" not in name:
self.typedefs[name] = getattr(module, name)
def run(self):
"""运行生成"""
self.f_cpp = open(self.filename, "r")
self.f_struct = open(f"{self.prefix}_struct.py", "w")
for n, line in enumerate(self.f_cpp):
if "*" in line:
continue
try:
self.process_line(line)
except Exception:
print(n, line)
import traceback
traceback.print_exc()
return
self.f_cpp.close()
self.f_struct.close()
print("Struct生成成功")
def process_line(self, line: str):
"""处理每行"""
line = line.replace(";", "")
line = line.replace("\n", "")
line = line.replace("\t", " ")
if self.prefix == "nh_stock" and line.startswith(" "):
line = line[4:]
if "///" in line:
return
elif line.startswith(" struct") or line.startswith(" typedef struct"):
self.process_declare(line)
elif line.startswith(" {"):
self.process_start(line)
elif line.startswith(" }"):
self.process_end(line)
elif line.startswith(" "):
self.process_member(line)
def process_declare(self, line: str):
"""处理声明"""
words = line.split(" ")
words = [word for word in words if word]
if "typedef" in words:
name = words[2]
else:
name = words[1]
end = "{"
new_line = f"{name} = {end}\n"
self.f_struct.write(new_line)
self.current_struct = name
def process_start(self, line: str):
"""处理开始"""
pass
def process_end(self, line: str):
"""处理结束"""
new_line = "}\n\n"
self.f_struct.write(new_line)
def process_member(self, line: str):
"""处理成员"""
if "//" in line:
ix = line.index("//")
line = line[:ix]
words = line.split(" ")
words = [word for word in words if word]
if words[0] not in self.typedefs:
return
if words[0] == "ReqOrderInsertData":
return
elif words[0] == "Commi_Info_t":
return
elif words[0] == "char":
py_type = "string"
elif words[0] == "int":
py_type = "int"
else:
py_type = self.typedefs[words[0]]
name = words[1]
new_line = f" \"{name}\": \"{py_type}\",\n"
self.f_struct.write(new_line)
if __name__ == "__main__":
generator = StructGenerator("../../include/nh/stock/NhStockUserApiStruct.h", "nh")
generator.run()
|
<?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
namespace pocketmine\block;
use pocketmine\entity\Entity;
use pocketmine\item\Item;
use pocketmine\level\Level;
use pocketmine\math\AxisAlignedBB;
use pocketmine\Player;
class Ladder extends Transparent{
public $hasEntityCollision = true;
public function __construct($meta = 0){
parent::__construct(self::LADDER, $meta, "Ladder");
$this->isSolid = false;
$this->isFullBlock = false;
$this->hardness = 2;
}
public function onEntityCollide(Entity $entity){
$entity->fallDistance = 0;
$entity->onGround = true;
}
public function getBoundingBox(){
if($this->boundingBox !== null){
return $this->boundingBox;
}
$f = 0.125;
if($this->meta === 2){
return $this->boundingBox = new AxisAlignedBB(
$this->x,
$this->y,
$this->z + 1 - $f,
$this->x + 1,
$this->y + 1,
$this->z + 1
);
}elseif($this->meta === 3){
return $this->boundingBox = new AxisAlignedBB(
$this->x,
$this->y,
$this->z,
$this->x + 1,
$this->y + 1,
$this->z + $f
);
}elseif($this->meta === 4){
return $this->boundingBox = new AxisAlignedBB(
$this->x + 1 - $f,
$this->y,
$this->z,
$this->x + 1,
$this->y + 1,
$this->z + 1
);
}elseif($this->meta === 5){
return $this->boundingBox = new AxisAlignedBB(
$this->x,
$this->y,
$this->z,
$this->x + $f,
$this->y + 1,
$this->z + 1
);
}
return null;
}
public function place(Item $item, Block $block, Block $target, $face, $fx, $fy, $fz, Player $player = null){
if($target->isTransparent === false){
$faces = [
2 => 2,
3 => 3,
4 => 4,
5 => 5,
];
if(isset($faces[$face])){
$this->meta = $faces[$face];
$this->getLevel()->setBlock($block, $this, true, true);
return true;
}
}
return false;
}
public function onUpdate($type){
if($type === Level::BLOCK_UPDATE_NORMAL){
/*if($this->getSide(0)->getID() === self::AIR){ //Replace with common break method
Server::getInstance()->api->entity->drop($this, Item::get(LADDER, 0, 1));
$this->getLevel()->setBlock($this, new Air(), true, true, true);
return Level::BLOCK_UPDATE_NORMAL;
}*/
}
return false;
}
public function getDrops(Item $item){
return [
[$this->id, 0, 1],
];
}
}
|
jQuery(function($) {
/*
* Liste du nombre de films par page
*/
$('#movies_per_page_form select').on('change',function(){
$('#movies_per_page_form').submit();
return false;
});
$('.movie_delete').confirmDelete('Supprimer le film sélectionné ?');
});
|
export function apply(dest: any, source: any) {
for (var name in source)
if (!dest.hasOwnProperty(name))
dest[name] = source[name];
}
|
import dronekit
import time
import SUASSystem
from time import sleep
from SUASSystem import settings
from SUASSystem import converter_functions
from SUASSystem import gcs
from settings import GCSSettings
def connect_to_rover():
print("Connecting to rover")
rover = dronekit.connect(GCSSettings.UGV_CONNECTION_STRING, wait_ready=True)
rover.wait_ready('autopilot_version')
print("Connected to rover")
return rover
def has_rover_reached_airdrop(r):
rover_location = converter_functions.get_location(r)
print(rover_location)
lat_from_drop = abs(GCSSettings.AIRDROP_POINT_SCHOOL[0][0] - rover_location.get_lat())
lon_from_drop = abs(GCSSettings.AIRDROP_POINT_SCHOOL[0][1] - rover_location.get_lon())
print("Latitude from Drop: " + str(lat_from_drop))
print("Longitude from Drop: " + str(lon_from_drop) + "\n")
if (rover_location.get_alt() < 10 and rover_location.get_alt() > -1
and lat_from_drop < 0.00035 and lon_from_drop < 0.00035):
return True
else:
return False
def airdrop_countdown(wait):
print("Rover Has Reached AirDrop")
for x in range(wait):
print("Rover Arming in: " + str(wait-x) + " seconds")
sleep(1)
rover = connect_to_rover()
landed = False
while not landed:
if (has_rover_reached_airdrop(rover)):
landed = True
airdrop_countdown(120) #Change wait period (In seconds) here
rover.armed = True
print("Rover is Armed")
rover.mode = dronekit.VehicleMode("AUTO")
print("Rover Mode: AUTO")
|
/**
* omap-twl4030.h - ASoC machine driver for TI SoC based boards with twl4030
* codec, header.
*
* Copyright (C) 2012 Texas Instruments Incorporated - http://www.ti.com
* All rights reserved.
*
* Author: Peter Ujfalusi <peter.ujfalusi@ti.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#ifndef _OMAP_TWL4030_H_
#define _OMAP_TWL4030_H_
struct omap_tw4030_pdata {
const char *card_name;
};
#endif /* _OMAP_TWL4030_H_ */
|
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'Twig_Extensions_' => array($vendorDir . '/twig/extensions/lib'),
'Twig_' => array($vendorDir . '/twig/twig/lib'),
'Symfony\\Component\\Icu\\' => array($vendorDir . '/symfony/icu'),
'Symfony\\Bundle\\SwiftmailerBundle' => array($vendorDir . '/symfony/swiftmailer-bundle'),
'Symfony\\Bundle\\MonologBundle' => array($vendorDir . '/symfony/monolog-bundle'),
'Symfony\\Bundle\\AsseticBundle' => array($vendorDir . '/symfony/assetic-bundle'),
'Symfony\\' => array($vendorDir . '/symfony/symfony/src'),
'Sensio\\Bundle\\GeneratorBundle' => array($vendorDir . '/sensio/generator-bundle'),
'Sensio\\Bundle\\FrameworkExtraBundle' => array($vendorDir . '/sensio/framework-extra-bundle'),
'Sensio\\Bundle\\DistributionBundle' => array($vendorDir . '/sensio/distribution-bundle'),
'Psr\\Log\\' => array($vendorDir . '/psr/log'),
'Incenteev\\ParameterHandler' => array($vendorDir . '/incenteev/composer-parameter-handler'),
'Doctrine\\ORM\\' => array($vendorDir . '/doctrine/orm/lib'),
'Doctrine\\DBAL\\' => array($vendorDir . '/doctrine/dbal/lib'),
'Doctrine\\Common\\Lexer\\' => array($vendorDir . '/doctrine/lexer/lib'),
'Doctrine\\Common\\Inflector\\' => array($vendorDir . '/doctrine/inflector/lib'),
'Doctrine\\Common\\Collections\\' => array($vendorDir . '/doctrine/collections/lib'),
'Doctrine\\Common\\Cache\\' => array($vendorDir . '/doctrine/cache/lib'),
'Doctrine\\Common\\Annotations\\' => array($vendorDir . '/doctrine/annotations/lib'),
'Doctrine\\Common\\' => array($vendorDir . '/doctrine/common/lib'),
'Doctrine\\Bundle\\DoctrineBundle' => array($vendorDir . '/doctrine/doctrine-bundle'),
'DoctrineExtensions' => array($vendorDir . '/beberlei/DoctrineExtensions/lib'),
'Assetic' => array($vendorDir . '/kriswallsmith/assetic/src'),
'' => array($baseDir . '/src'),
);
|
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
files: ['Gruntfile.js', 'dist/**/*.js', 'src/**/*.js'],
options: {
esversion: 6,
globals: {
jQuery: true
}
}
},
watch: {
files: ['<%= jshint.files %>'],
tasks: ['jshint']
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['jshint']);
};
|
namespace IdentityModel.Client;
/// <summary>
/// Models a client assertion
/// </summary>
public class ClientAssertion
{
/// <summary>
/// Gets or sets the assertion type.
/// </summary>
/// <value>
/// The type.
/// </value>
public string Type { get; set; }
/// <summary>
/// Gets or sets the assertion value.
/// </summary>
/// <value>
/// The value.
/// </value>
public string Value { get; set; }
}
|
package exter.eveindustry.dataprovider.planet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import exter.eveindustry.data.inventory.IItem;
import exter.eveindustry.data.planet.IPlanet;
import exter.eveindustry.dataprovider.item.ItemDA;
import exter.tsl.TSLObject;
public class Planet implements IPlanet
{
public final List<IItem> Resources;
public final String TypeName;
public final int ID;
public final boolean Advanced;
public Planet(TSLObject tsl,ItemDA inventory)
{
ID = tsl.getStringAsInt("id",-1);
TypeName = tsl.getString("name",null);
Advanced = (tsl.getStringAsInt("advanced",0) != 0);
List<IItem> res = new ArrayList<IItem>();
for(Integer id:tsl.getStringAsIntegerList("resource"))
{
res.add(inventory.items.get(id));
}
Resources = Collections.unmodifiableList(res);
}
@Override
public List<IItem> getResources()
{
return Resources;
}
@Override
public int getID()
{
return ID;
}
@Override
public boolean isAdvanced()
{
return Advanced;
}
}
|
<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8>
<title></title>
<link rel="stylesheet" type="text/css" href="./assets/first-screen.css">
</head>
<body>
<div id="wc-loading">
<div class="wc-icon" lang="en">
<span class="wc-icon-cloud"></span>
</div>
</div>
</body>
</html>
|
import Route from '@ember/routing/route';
import Service from '@ember/service';
import debug from 'debug';
import debugLogger from 'ember-debug-logger';
import { module, test } from 'qunit';
import { setupApplicationTest } from 'ember-qunit';
import sinon, { SinonStub } from 'sinon';
import { visit } from '@ember/test-helpers';
import { TestContext } from 'ember-test-helpers';
module('Acceptance | logging from container-managed objects', function(hooks) {
let log: SinonStub;
setupApplicationTest(hooks);
hooks.beforeEach(function(this: TestContext) {
this.owner.register('route:application', Route.extend({ debug: debugLogger() }), {});
this.owner.register('service:my/test/module', Service.extend({ debug: debugLogger() }), {});
debug.enable('route:*, service:*');
log = sinon.stub(console, 'log');
});
hooks.afterEach(function() {
log.restore();
debug.disable();
});
test('it automatically finds keys when attached to container-managed objects', async function(assert) {
await visit('/');
const appRoute = this.owner.lookup('route:application');
appRoute.debug('test message from the application route');
let [routeMessage] = log.lastCall.args;
assert.ok(/route:application/.test(routeMessage), 'Route message should include its container key');
const testService = this.owner.lookup('service:my/test/module');
testService.debug('test message from the mysterious service');
let [serviceMessage] = log.lastCall.args;
assert.ok(/service:my\/test\/module/.test(serviceMessage), 'Service message should include its container key');
});
});
|
#!/home/jpadula/uframes/ooi/uframe-1.0/python/bin/python
__author__ = 'Joe Padula'
from mi.core.log import get_logger
log = get_logger()
from mi.idk.config import Config
import unittest
import os
from mi.dataset.driver.velpt_ab.dcl.velpt_ab_dcl_telemetered_driver import parse
from mi.dataset.dataset_driver import ParticleDataHandler
class SampleTest(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_one(self):
sourceFilePath = os.path.join('mi', 'dataset', 'driver',
'velpt_ab', 'dcl', 'resource',
'20140813.velpt.log')
particle_data_hdlr_obj = ParticleDataHandler()
particle_data_hdlr_obj = parse(Config().base_dir(), sourceFilePath, particle_data_hdlr_obj)
log.debug("SAMPLES: %s", particle_data_hdlr_obj._samples)
log.debug("FAILURE: %s", particle_data_hdlr_obj._failure)
self.assertEquals(particle_data_hdlr_obj._failure, False)
if __name__ == '__main__':
test = SampleTest('test_one')
test.test_one()
|
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-compass');
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
compass: {
files: ['**/*.{scss,sass,css}'],
tasks: ['compass:dev']
}
},
compass: {
dev: {
options: {
sassDir: ['assets/css/sass'],
cssDir: ['assets/css'],
environment: 'development'
}
},
prod: {
options: {
sassDir: ['assets/css/sass'],
cssDir: ['assets/css'],
environment: 'production'
}
}
}
});
grunt.registerTask('default', ['watch', 'compass:dev']);
};
|
<div *ngIf="session.project" class="card-container">
<md-card class="{{story.colour}}" *ngFor="let story of session.project.stories; let i=index">
<md-card-title>{{i+1}}.{{story.title}}</md-card-title>
<div>{{story.description}}</div>
<md-button-toggle-group name="storyPoints" (click)="showTasks(i,$event)">
<md-button-toggle>1/2</md-button-toggle>
<md-button-toggle>1</md-button-toggle>
<md-button-toggle>3</md-button-toggle>
<md-button-toggle>5</md-button-toggle>
<md-button-toggle>8</md-button-toggle>
<md-button-toggle>13</md-button-toggle>
<md-button-toggle>20</md-button-toggle>
<md-button-toggle>40</md-button-toggle>
<md-button-toggle>100</md-button-toggle>
<md-button-toggle>E</md-button-toggle>
<md-button-toggle>?</md-button-toggle>
</md-button-toggle-group>
<div *ngIf="listTasks[i]">
<form [formGroup]="taskForm" (ngSubmit)="onSubmit()">
<p md-line *ngFor="let task of story.tasks; let i=index">{{i+1}}. {{task.title}}
<button type="button" (click)="removeTask(story,i)" md-mini-fab>
<md-icon class="md-24">-</md-icon>
</button>
</p>
<p md-line>
<md-input #tasks autofocus class="ac-input" [formControl]="newTaskTitle" placeholder="Task"></md-input>
<md-input class="ac-input" [formControl]="newTaskTime" placeholder="Time"></md-input>
<button type="button" (click)="addTask(story)" md-mini-fab><i class="material-icons" md-24>add</i>
</button>
</p>
</form>
</div>
<md-card-actions align="end">
<button md-button (click)="edit(i)" color="primary">EDIT</button>
<button *ngIf="i > 0" (click)="moveUp(i)" md-button>
<md-icon md-list-icon="" class="material-icons" aria-label="assignment ind">vertical_align_top</md-icon>
</button>
<button *ngIf="i === 0" md-button>
<md-icon md-list-icon="" class="material-icons" aria-label="assignment ind">top</md-icon>
</button>
<button *ngIf="i < session.project.stories.length-1" (click)="moveDown(i)" md-button>
<md-icon md-list-icon="" class="material-icons" aria-label="assignment ind">vertical_align_bottom</md-icon>
</button>
</md-card-actions>
</md-card>
</div>
|
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
import {Tensor} from '../../tensor';
import {convertToTensor} from '../../tensor_util_env';
import {TensorLike} from '../../types';
import {assertShapesMatch} from '../../util';
import {Reduction} from '../loss_ops_utils';
import {mul} from '../mul';
import {op} from '../operation';
import {relu} from '../relu';
import {scalar} from '../scalar';
import {sub} from '../sub';
import {computeWeightedLoss} from './compute_weighted_loss';
/**
* Computes the Hinge loss between two tensors.
*
* @param labels The ground truth output tensor, same dimensions as
* 'predictions'.
* @param predictions The predicted outputs.
* @param weights Tensor whose rank is either 0, or the same rank as
* `labels`, and must be broadcastable to `labels` (i.e., all dimensions
* must be either `1`, or the same as the corresponding `losses`
* dimension).
* @param reduction Type of reduction to apply to loss. Should be of type
* `Reduction`
*
* @doc {heading: 'Training', subheading: 'Losses', namespace: 'losses'}
*/
function hingeLoss_<T extends Tensor, O extends Tensor>(
labels: T|TensorLike, predictions: T|TensorLike,
weights?: Tensor|TensorLike,
reduction = Reduction.SUM_BY_NONZERO_WEIGHTS): O {
let $labels = convertToTensor(labels, 'labels', 'hingeLoss');
const $predictions = convertToTensor(predictions, 'predictions', 'hingeLoss');
let $weights: Tensor = null;
if (weights != null) {
$weights = convertToTensor(weights, 'weights', 'hingeLoss');
}
assertShapesMatch($labels.shape, $predictions.shape, 'Error in hingeLoss: ');
const one = scalar(1);
// Convert binary labels to (-1, 1)
$labels = sub(mul(scalar(2), $labels), one);
const losses = relu(sub(one, mul($labels, $predictions)));
return computeWeightedLoss(losses, $weights, reduction);
}
export const hingeLoss = op({hingeLoss_});
|
from itertools import chain
import logging
from greplin import scales
log = logging.getLogger(__name__)
class Metrics(object):
request_timer = None
"""
A :class:`greplin.scales.PmfStat` timer for requests. This is a dict-like
object with the following keys:
* count - number of requests that have been timed
* min - min latency
* max - max latency
* mean - mean latency
* stdev - standard deviation for latencies
* median - median latency
* 75percentile - 75th percentile latencies
* 97percentile - 97th percentile latencies
* 98percentile - 98th percentile latencies
* 99percentile - 99th percentile latencies
* 999percentile - 99.9th percentile latencies
"""
connection_errors = None
"""
A :class:`greplin.scales.IntStat` count of the number of times that a
request to a Cassandra node has failed due to a connection problem.
"""
write_timeouts = None
"""
A :class:`greplin.scales.IntStat` count of write requests that resulted
in a timeout.
"""
read_timeouts = None
"""
A :class:`greplin.scales.IntStat` count of read requests that resulted
in a timeout.
"""
unavailables = None
"""
A :class:`greplin.scales.IntStat` count of write or read requests that
failed due to an insufficient number of replicas being alive to meet
the requested :class:`.ConsistencyLevel`.
"""
other_errors = None
"""
A :class:`greplin.scales.IntStat` count of all other request failures,
including failures caused by invalid requests, bootstrapping nodes,
overloaded nodes, etc.
"""
retries = None
"""
A :class:`greplin.scales.IntStat` count of the number of times a
request was retried based on the :class:`.RetryPolicy` decision.
"""
ignores = None
"""
A :class:`greplin.scales.IntStat` count of the number of times a
failed request was ignored based on the :class:`.RetryPolicy` decision.
"""
known_hosts = None
"""
A :class:`greplin.scales.IntStat` count of the number of nodes in
the cluster that the driver is aware of, regardless of whether any
connections are opened to those nodes.
"""
connected_to = None
"""
A :class:`greplin.scales.IntStat` count of the number of nodes that
the driver currently has at least one connection open to.
"""
open_connections = None
"""
A :class:`greplin.scales.IntStat` count of the number connections
the driver currently has open.
"""
def __init__(self, cluster_proxy):
log.debug("Starting metric capture")
self.stats = scales.collection('/cassandra',
scales.PmfStat('request_timer'),
scales.IntStat('connection_errors'),
scales.IntStat('write_timeouts'),
scales.IntStat('read_timeouts'),
scales.IntStat('unavailables'),
scales.IntStat('other_errors'),
scales.IntStat('retries'),
scales.IntStat('ignores'),
# gauges
scales.Stat('known_hosts',
lambda: len(cluster_proxy.metadata.all_hosts())),
scales.Stat('connected_to',
lambda: len(set(chain.from_iterable(s._pools.keys() for s in cluster_proxy.sessions)))),
scales.Stat('open_connections',
lambda: sum(sum(p.open_count for p in s._pools.values()) for s in cluster_proxy.sessions)))
self.request_timer = self.stats.request_timer
self.connection_errors = self.stats.connection_errors
self.write_timeouts = self.stats.write_timeouts
self.read_timeouts = self.stats.read_timeouts
self.unavailables = self.stats.unavailables
self.other_errors = self.stats.other_errors
self.retries = self.stats.retries
self.ignores = self.stats.ignores
self.known_hosts = self.stats.known_hosts
self.connected_to = self.stats.connected_to
self.open_connections = self.stats.open_connections
def on_connection_error(self):
self.stats.connection_errors += 1
def on_write_timeout(self):
self.stats.write_timeouts += 1
def on_read_timeout(self):
self.stats.read_timeouts += 1
def on_unavailable(self):
self.stats.unavailables += 1
def on_other_error(self):
self.stats.other_errors += 1
def on_ignore(self):
self.stats.ignores += 1
def on_retry(self):
self.stats.retries += 1
|
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.AIPlatform.V1.Snippets
{
// [START aiplatform_v1_generated_TensorboardService_CreateTensorboardTimeSeries_sync]
using Google.Cloud.AIPlatform.V1;
public sealed partial class GeneratedTensorboardServiceClientSnippets
{
/// <summary>Snippet for CreateTensorboardTimeSeries</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void CreateTensorboardTimeSeriesRequestObject()
{
// Create client
TensorboardServiceClient tensorboardServiceClient = TensorboardServiceClient.Create();
// Initialize request argument(s)
CreateTensorboardTimeSeriesRequest request = new CreateTensorboardTimeSeriesRequest
{
ParentAsTensorboardTimeSeriesName = TensorboardTimeSeriesName.FromProjectLocationTensorboardExperimentRunTimeSeries("[PROJECT]", "[LOCATION]", "[TENSORBOARD]", "[EXPERIMENT]", "[RUN]", "[TIME_SERIES]"),
TensorboardTimeSeries = new TensorboardTimeSeries(),
TensorboardTimeSeriesId = "",
};
// Make the request
TensorboardTimeSeries response = tensorboardServiceClient.CreateTensorboardTimeSeries(request);
}
}
// [END aiplatform_v1_generated_TensorboardService_CreateTensorboardTimeSeries_sync]
}
|
import os
import device
import logging
def getDevices(dir, adapterDevices):
files = os.listdir(dir)
devices = []
# Check in the config directory and load each device.
for file in files:
device = __loadFile(dir + "/" + file, adapterDevices)
if device == None:
print('There was an error loading device "' + file + '"')
else:
devices.append(device)
# Check to see if there are any devices present and loaded.
if len(devices) == 0:
print("No devices found.")
logging.error("No devices found.")
return False
else:
return devices
def __loadFile(device_path, adapterDevices):
deviceAttr = []
inputAttr = []
# Load file into variable lists.
file = open(device_path, 'r')
for line in file:
if line.strip().lower() == '[device]':
section = "DEVICE"
elif line.strip().lower() == '[inputs]':
section = "INPUTS"
elif line.strip() != "":
if section == "DEVICE":
result = __addAttribute(line)
if result != False:
# Load config name and type
if result[0] == "name":
configName = result[1].lower()
if result[0] == "type":
configType = result[1].lower()
if section == "INPUTS":
result = __addAttribute(line)
if result != False:
inputAttr.append(result)
file.close()
# Check that the name and type match the vendor and osd string from cec-client.
foundName = False
foundType = False
for dev in adapterDevices:
for attribute in dev:
if attribute[0] == "vendor" and attribute[1].lower() == configName:
deviceName = attribute[1].lower()
foundName = True
if attribute[0] == "osd string" and attribute[1].lower() == configType:
deviceType = attribute[1].lower()
foundType = True
if foundName == True and foundType == True:
break
# Exit if the name/vendor or type/osd string.
if foundName == False or foundType == False:
print('No matching device found for "' + device_path + '"')
return None
# Get the ID and address attribute.
for attribute in dev:
if attribute[0] == "id":
deviceID = attribute[1].lower().strip()
if attribute[0] == "address":
deviceAddress = attribute[1].lower().strip()
return device.Device(deviceID, deviceName, deviceType, deviceAddress, inputAttr)
# Parse config file line.
def __addAttribute(line):
attribute = line.split("=")
if len(attribute) == 2 and attribute[1].strip() != "":
return (attribute[0].lower().strip(), attribute[1].lower().strip())
else:
return False
|
#!/usr/bin/env python
#-*- coding: utf-8 -*-
###########################################################################
## ##
## Copyrights David Morais Ferreira 2020 ##
## ##
## This program is free software: you can redistribute it and/or modify ##
## it under the terms of the GNU General Public License as published by ##
## the Free Software Foundation, either version 3 of the License, or ##
## (at your option) any later version. ##
## ##
## This program is distributed in the hope that it will be useful, ##
## but WITHOUT ANY WARRANTY; without even the implied warranty of ##
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ##
## GNU General Public License for more details. ##
## ##
## You should have received a copy of the GNU General Public License ##
## along with this program. If not, see <http://www.gnu.org/licenses/>. ##
## ##
###########################################################################
from modules.OsmoseTranslation import T_
from .Analyser_Merge import Analyser_Merge, SourcePublicLu, CSV, Load, Conflate, Select, Mapping
class Analyser_Merge_Emergency_Points_LU(Analyser_Merge):
def __init__(self, config, logger=None):
Analyser_Merge.__init__(self, config, logger)
self.missing_official = self.def_class(item=8440, id=1, level=3, tags=['merge', 'emergency', 'fix:survey'],
title=T_('Emergency point not integrated'))
self.possible_merge = self.def_class(item=8441, id=3, level=3, tags=['merge', 'emergency', 'fix:survey', 'fix:chair'],
title=T_('Emergency point integration suggestion'))
self.init(
"https://data.public.lu/fr/datasets/linstallation-des-points-de-secours-rettungspunkte",
"Points de secours",
CSV(SourcePublicLu(attribution="Corps grand-ducal d'incendie et de secours",
dataset="5eec6f76d2bfb251e132f1ba",
resource="b8d9d38a-7894-49fb-ab88-94072fe2c722",
encoding="iso-8859-1"),
separator=";"),
Load("GEOGRAPHISCHE LÄNGE", "GEOGRAPHISCHE BREITE"),
Conflate(
select=Select(
types=["nodes"],
tags={"highway": "emergency_access_point"}),
osmRef = "ref",
conflationDistance=50,
mapping=Mapping(
static1={
"highway": "emergency_access_point"
},
static2={
"source": self.source,
},
mapping1={
"ref": "NAME",
"name": "ZUSATZ"
}
)))
|
import demistomock as demisto
from CommonServerPython import *
import urllib3
import traceback
from typing import Dict, List
# Disable insecure warnings
urllib3.disable_warnings()
''' CONSTANTS '''
DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
BITCOIN = 'bitcoin'
INTEGRATION_NAME = 'Cryptocurrency'
SCORE = {
'None': 0,
'Good': 1,
'Suspicious': 2,
'Bad': 3,
}
def get_bitcoin_reputation(addresses, reliability, reputation, score) -> List[CommandResults]:
command_results: List[CommandResults] = []
for address in addresses:
dbot_score = Common.DBotScore(
indicator=address,
indicator_type=DBotScoreType.CRYPTOCURRENCY,
integration_name=INTEGRATION_NAME, # Vendor
score=score,
reliability=reliability,
)
crypto_context = Common.Cryptocurrency(
address=address,
address_type=BITCOIN,
dbot_score=dbot_score,
)
table_data = {
'Address': address,
'Cryptocurrency Address Type': BITCOIN,
'Reputation': reputation,
}
table_name = f'{INTEGRATION_NAME} reputation for {address}'
hr = tableToMarkdown(table_name, table_data)
command_results.append(CommandResults(
outputs_prefix='Cryptocurrency',
readable_output=hr,
outputs_key_field='Address',
indicator=crypto_context,
))
return command_results
def crypto_reputation_command(args: Dict[str, str], reliability: str, reputation: str):
crypto_addresses = argToList(args.get('crypto', ''))
# For cases the command was executed by a playbook/user and the addresses received are verified
# Stripping the `bitcoin` prefix from the given addresses (if exists) then add it to match the convention.
if args.get('address_type') == BITCOIN:
bitcoin_addresses = [f'bitcoin:{address.lstrip("bitcoin:")}' for address in crypto_addresses]
else:
bitcoin_addresses = [address for address in crypto_addresses if BITCOIN in address]
score = SCORE[reputation]
result = get_bitcoin_reputation(bitcoin_addresses, reliability, reputation, score)
return result
def main():
params = demisto.params()
reliability = params['reliability']
reputation = params['reputation']
demisto.info(f'Command being called is {demisto.command()}')
try:
if demisto.command() == 'test-module':
return_results('ok')
elif demisto.command() == 'crypto':
return_results(crypto_reputation_command(demisto.args(), reliability, reputation))
# Log exceptions and return errors
except Exception as e:
demisto.error(traceback.format_exc()) # print the traceback
return_error(f'Failed to execute {demisto.command()} command.\nError:\n{str(e)}')
''' ENTRY POINT '''
if __name__ in ('__main__', '__builtin__', 'builtins'):
main()
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2014 Savoir-faire Linux
# (<http://www.savoirfairelinux.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.addons.connector.connector import (
Environment, install_in_connector)
from openerp.addons.connector.checkpoint import checkpoint
install_in_connector()
def get_environment(session, model_name, backend_id):
""" Create an environment to work with. """
backend_record = session.browse('cmis.backend', backend_id)
env = Environment(backend_record, session, model_name)
lang = backend_record.default_lang_id
lang_code = lang.code if lang else 'en_US'
env.set_lang(code=lang_code)
return env
def add_checkpoint(session, model_name, record_id, backend_id):
""" Add a row in the model ``connector.checkpoint`` for a record,
meaning it has to be reviewed by a user.
:param session: current session
:type session: :class:`openerp.addons.connector.session.ConnectorSession`
:param model_name: name of the model of the record to be reviewed
:type model_name: str
:param record_id: ID of the record to be reviewed
:type record_id: int
:param backend_id: ID of the Cmis Backend
:type backend_id: int
"""
return checkpoint.add_checkpoint(
session, model_name, record_id, 'cmis.backend', backend_id)
|
from topbeat import BaseTest
import getpass
import re
import os
"""
Contains tests for per process statistics.
"""
class Test(BaseTest):
def test_procs(self):
"""
Checks that the per proc stats are found in the output and
have the expected types.
"""
self.render_config_template(
system_stats=False,
process_stats=True,
filesystem_stats=False,
proc_patterns=["(?i)topbeat.test"] # monitor itself
)
topbeat = self.start_beat()
self.wait_until(lambda: self.output_count(lambda x: x >= 1))
topbeat.check_kill_and_wait()
output = self.read_output()[0]
print output["proc.name"]
assert re.match("(?i)topbeat.test(.exe)?", output["proc.name"])
assert re.match("(?i).*topbeat.test(.exe)? -systemTest", output["proc.cmdline"])
assert isinstance(output["proc.state"], basestring)
assert isinstance(output["proc.cpu.start_time"], basestring)
self.check_username(output["proc.username"])
for key in [
"proc.pid",
"proc.ppid",
"proc.cpu.user",
"proc.cpu.system",
"proc.cpu.total",
"proc.mem.size",
"proc.mem.rss",
"proc.mem.share",
]:
assert type(output[key]) is int
for key in [
"proc.cpu.total_p",
"proc.mem.rss_p",
]:
assert type(output[key]) in [int, float]
def check_username(self, observed, expected = None):
if expected == None:
expected = getpass.getuser()
if os.name == 'nt':
parts = observed.split("\\", 2)
assert len(parts) == 2, "Expected proc.username to be of form DOMAIN\username, but was %s" % observed
observed = parts[1]
assert expected == observed, "proc.username = %s, but expected %s" % (observed, expected)
|
# encoding: utf-8
# create year data 2月用30天去算
def cdateList(year):
# days31 (1,3,5,7,8,10,12) days30(2,4,6,9,11)
month31=[1,3,5,7,8,10,12]
nday31=range(1,32)
nday30=range(1,31)
day10=['01','02','03','04','05','06','07','08','09']
month12=day10+['10','11','12']
nday31 = map(str,nday31[9:])
nday30 = map(str,nday30[9:])
day31 = day10 + nday31
day30 = day10 + nday30
yearData=[]
s=""
for month,strmonth in zip(range(1,13),month12):
if month in month31:
for day in day31:
s = year+'-'+strmonth+'-'+day
yearData.append(s)
else :
for day in day30:
s = year+'-'+strmonth+'-'+day
yearData.append(s)
return yearData
# 爬取主函式
def crawler(url,station,year,date):
resp = requests.get(url)
soup = BeautifulSoup(resp.text)
# find no data page
error = soup.find(class_="imp").string.encode('utf-8')
if error == '本段時間區間內無觀測資料。':
with open ("./nodata.txt",'a') as f:
f.write(url+'\n')
form =[]
# title
titles = soup.find_all("th")
titles = titles[9:]
strtitle=[]
for title in titles:
title = title.contents
title=title[0]+title[2]+title[4]
strtitle.append(title)
# parameter
soup = soup.tbody
tmps = soup.find_all("tr")
tmps = tmps[2:]
for tmp in tmps:
tmp = tmp.find_all("td")
parameter =[]
for strtmp in tmp:
strtmp = strtmp.string
parameter .append(strtmp)
form.append(parameter)
form = pd.DataFrame(form, columns=strtitle)
form.to_csv("./data/"+station+'/'+year+'/'+date+".csv", encoding ="utf-8")
# sleep(0.5)
# 有分nodata.txt 和 error.txt,nodata.txt是指網站沒資料
# error.txt 可能是連線失敗或是沒抓到,因此兩組相對再去抓沒抓到的
def errorCrawler():
nodatadirPath = './nodata.txt'
if os.path.exists(nodatadirPath) == 1 :
with open ("./nodata.txt",'r') as f:
nodataUrls = f.readlines()
with open ("./error.txt",'r') as f:
urls = f.readlines()
for url in urls:
url = url.strip()
url = url.split(',')
compareUrl = url[0]+'\n'
# 對照nodata.txt,本來就沒有資料就不抓
if compareUrl in nodataUrls:
pass
else:
try:
sleep(1)
crawler(url[0],url[1],url[2],url[3])
print('again:'+url[1]+','+url[2]+','+url[3])
# 再次紀錄第二次抓哪些資料
with open ("./error_reCrawler.txt",'a') as f:
f.write(url[0]+','+url[1]+','+url[2]+','+url[3]+'\n')
except :
print('error:'+url[1]+','+url[2]+','+url[3])
else:
with open ("./error.txt",'r') as f:
urls = f.readlines()
for url in urls:
url = url.strip()
url = url.split(',')
sleep(1)
print('again:'+url[1]+','+url[2]+','+url[3])
crawler(url[0],url[1],url[2],url[3])
# -*- coding: utf-8 -*-
import os
import requests
import pandas as pd
from time import sleep
from bs4 import BeautifulSoup
# 臺南 (467410) 永康 (467420) 嘉義 (467480) 臺中 (467490) 阿里山 (467530) 新竹 (467571) 恆春 (467590)
# 成功 (467610) 蘭嶼 (467620) 日月潭 (467650) 臺東 (467660) 梧棲 (467770) 七股 (467780) 墾丁 (467790)
# 馬祖 (467990) 新屋 (467050) 板橋 (466880) 淡水 (466900) 鞍部 (466910) 臺北 (466920) 竹子湖 (466930)
# 基隆 (466940) 彭佳嶼 (466950) 花蓮 (466990) 蘇澳 (467060) 宜蘭 (467080) 金門 (467110) 東吉島 (467300)
# 澎湖 (467350) 高雄 (467440) 大武 (467540) 玉山 (467550)
# 新竹 (467571) 真正的 url station 467570 官網標示錯誤
twStationList = ['467410','467420','467480','467490','467530','467570','467590','467610'
,'467620','467650','467660','467770','467780','467790','467990','467050','466880','466900'
,'466910','466920','466930','466940','466950','466990','467060','467080','467110','467300'
,'467350','467440','467540','467550']
# station
for station in twStationList:
# create station folder
dirPath = './data/'+station
if os.path.exists(dirPath) == 0:
os.makedirs(dirPath)
# year
yearList=['2013','2014']
for year in yearList:
dateList = cdateList(year)
# create year folder
dirPath = './data/'+station+'/'+year
if os.path.exists(dirPath) == 0:
os.makedirs(dirPath)
# date
for date in dateList:
# http://e-service.cwb.gov.tw/HistoryDataQuery/DayDataController.do?command=viewMain&station=467410&datepicker=2014-11-26
url="http://e-service.cwb.gov.tw/HistoryDataQuery/DayDataController.do?command=viewMain&station="+station+"&datepicker="+date
try:
print(station+':'+date)
crawler(url,station,year,date)
except:
print(station+':'+date+'error')
with open ("./error.txt",'a') as f:
f.write(url+','+station+','+year+','+date+'\n')
errordirPath = './error.txt'
if os.path.exists(errordirPath) == 1 :
errorCrawler()
|
Template.select.events({
'submit form': function(e) {
e.preventDefault();
var sync = $(e.target).find('[name=code]').val();
var num = Users.find({ "sync": sync}).count() + 1;
user = {
gameid: sync,
num: num
};
user._id = Users.insert(user);
Router.go('waiting');
}
});
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2018-06-30 08:41
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='ModelWithCustomPermissions',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
],
options={
'permissions': (('can_deliver_pizzas', 'Can deliver pizzas'),),
},
),
migrations.CreateModel(
name='ModelWithCustomPermissionsNoDefault',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
],
options={
'default_permissions': (),
'permissions': (('can_do_stuff', 'Can Do stuff'), ('can_do_more_stuff', 'Can do more stuff')),
},
),
migrations.CreateModel(
name='ModelWithDefaultPermissions',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
],
),
migrations.CreateModel(
name='ModelWithEditedDefaultPermission',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
],
options={
'default_permissions': ('change',),
},
),
migrations.CreateModel(
name='ModelWithNoPermissions',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
],
options={
'default_permissions': (),
},
),
]
|
{{<govuk_template}}
{{$head}}
{{>includes/elements_head}}
<script type="text/javascript" src="/public/javascripts/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="/public/javascripts/application.js"></script>
<script type="text/javascript" src="/public/javascripts/selection-buttons.js"></script>
{{/head}}
{{$propositionHeader}}
{{>includes/govuk_evlprop}}
{{/propositionHeader}}
{{$headerClass}}with-proposition{{/headerClass}}
{{$content}}
<link href="/public/stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />
<main id="content" role="main">
<div>
<a class="back-to-previous" href="evl-11">Back <span class="visuallyhidden"> to the previous question</span></a>
</div>
<br clear="all">
<!-- changed -->
<form action="evl-3-flow" method="get" class="form" data-parsley-validate>
<input type="hidden" name="nextlink" value="evl-vehicle-details">
<input type="hidden" name="nextbacklink" value="evl-3-v5c">
<h1 class="form-title heading-large" style="margin:0 0 1em 0;padding:0">
Using a Last Chance letter
</h1>
<!-- <h2 class="heading-medium" style="font-weight:normal;padding:0;margin:1em 0 1em 0">Using a Last Chance letter</h2> -->
<img src="/public/images/lastchance-diagram.png" width="280" height="150" align="middle" style="padding:0.3em 0 1.5em 0">
<p>Your Last Chance letter will include either an 11 or 16 digit reference number.</p>
<p>If it is 11 digits you need to enter the vehicle registration number as well.</p>
<div style="border-left:8px solid #ccc;padding-left:1em;padding-bottom:1em">
<label class="form-label" for="nationality-other-v11" style="font-size:120%;padding-top:0.75em">
16 digit reference number</label>
<div id="validfield-3">
<input class="num form-control" type="text" maxlength="16" autocomplete="off" id="ref-v5c" style="border:#ccc solid 2px;font-size:120%;width:280px;border-radius:4px;line-height:1.6" size="16" data-parsley-trigger="change" data-parsley-required-message="The 16 digit reference number is required" required data-parsley-errors-container="validfield-3">
</div>
</div>
<br clear="all">
<p>Or</p>
<div style="border-left:8px solid #ccc;padding-left:1em;padding-bottom:1em">
<label class="form-label" for="vehicle-reg" style="font-size:120%;padding-top:0.75em">
Vehicle registration (number plate)</label>
<div id="validfield-1">
<input class="form-control" type="text" maxlength="8" id="regmark" name="regmark" style="border:#ccc solid 2px;font-size:120%;width:280px;border-radius:4px;line-height:1.6;text-transform:uppercase" size="8" data-parsley-trigger="change" data-parsley-required-message="A vehicle registration is required" required required data-parsley-errors-container="validfield-1">
</div>
<label class="form-label" for="nationality-other-v11" style="font-size:120%;padding-top:0.75em">
and a 11 digit reference number</label>
<div id="validfield-2">
<input class="num form-control" type="text" maxlength="11" autocomplete="off" id="ref-v5c" style="border:#ccc solid 2px;font-size:120%;width:280px;border-radius:4px;line-height:1.6" size="11" data-parsley-trigger="change" data-parsley-required-message="The 11 digit reference number is required" required data-parsley-errors-container="validfield-2">
</div>
</div>
<br clear="all">
<script>
$(document).ready(function() {
$("input.num").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: Ctrl+C
(e.keyCode == 67 && e.ctrlKey === true) ||
// Allow: Ctrl+X
(e.keyCode == 88 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});
</script>
<!-- div class="grid-row">
<div class="column-two-thirds">
<p style="margin-top:1em">You should have received a V5C vehicle registration certificate with your name on, within two weeks of acquiring your vehicle.</p>
</div-->
</div>
</div>
</fieldset>
<!-- Primary buttons, secondary links -->
<div class="form-group" style="padding-top:2.2em">
<input type="submit" class="button" value="Continue">
</div>
</form>
</main><!-- / #page-container -->
{{/content}}
{{$bodyEnd}}
{{>includes/elements_scripts}}
{{/bodyEnd}}
{{/govuk_template}}
|
<?php
namespace Imbo\MetadataSearch\Interfaces;
/**
* A interface for value-comparisons in our DSL AST. Useful for type-hinting
* functions that transforms comparisons.
*
* @author Morten Fangel <fangel@sevengoslings.net>
*/
interface DslAstComparisonInterface {}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas</title>
<script type="text/javascript">
</script>
<script src="js/canvas.js"></script>
</head>
<body>
<canvas id="canvas" width="1000" height="800"></canvas>
</body>
</html>
|
# -*- coding: utf-8 -*-
# © 2014 Alexis de Lattre <alexis.delattre@akretion.com>
# © 2014 Lorenzo Battistini <lorenzo.battistini@agilebg.com>
# © 2016 Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import models, fields, api, _
from openerp.exceptions import UserError
import requests
import tempfile
import StringIO
import zipfile
import os
import logging
try:
import unicodecsv
except ImportError:
unicodecsv = None
logger = logging.getLogger(__name__)
class BetterZipGeonamesImport(models.TransientModel):
_name = 'better.zip.geonames.import'
_description = 'Import Better Zip from Geonames'
_rec_name = 'country_id'
country_id = fields.Many2one('res.country', 'Country', required=True)
title_case = fields.Boolean(
string='Title Case',
help='Converts retreived city and state names to Title Case.',
)
@api.model
def transform_city_name(self, city, country):
"""Override it for transforming city name (if needed)
:param city: Original city name
:param country: Country record
:return: Transformed city name
"""
return city
@api.model
def _domain_search_better_zip(self, row, country):
return [('name', '=', row[1]),
('city', '=', self.transform_city_name(row[2], country)),
('country_id', '=', country.id)]
@api.model
def _prepare_better_zip(self, row, country):
state = self.select_or_create_state(row, country)
vals = {
'name': row[1],
'city': self.transform_city_name(row[2], country),
'state_id': state.id,
'country_id': country.id,
}
return vals
@api.model
def create_better_zip(self, row, country):
if row[0] != country.code:
raise UserError(
_("The country code inside the file (%s) doesn't "
"correspond to the selected country (%s).")
% (row[0], country.code))
logger.debug('ZIP = %s - City = %s' % (row[1], row[2]))
if (self.title_case):
row[2] = row[2].title()
row[3] = row[3].title()
if row[1] and row[2]:
zip_model = self.env['res.better.zip']
zips = zip_model.search(self._domain_search_better_zip(
row, country))
if zips:
return zips[0]
else:
vals = self._prepare_better_zip(row, country)
if vals:
return zip_model.create(vals)
else:
return False
@api.model
def select_or_create_state(
self, row, country, code_row_index=4, name_row_index=3):
states = self.env['res.country.state'].search([
('country_id', '=', country.id),
('code', '=', row[code_row_index]),
])
if len(states) > 1:
raise UserError(
_("Too many states with code %s for country %s")
% (row[code_row_index], country.code))
if len(states) == 1:
return states[0]
else:
return self.env['res.country.state'].create({
'name': row[name_row_index],
'code': row[code_row_index],
'country_id': country.id
})
@api.multi
def run_import(self):
self.ensure_one()
zip_model = self.env['res.better.zip']
country_code = self.country_id.code
config_url = self.env['ir.config_parameter'].get_param(
'geonames.url',
default='http://download.geonames.org/export/zip/%s.zip')
url = config_url % country_code
logger.info('Starting to download %s' % url)
res_request = requests.get(url)
if res_request.status_code != requests.codes.ok:
raise UserError(
_('Got an error %d when trying to download the file %s.')
% (res_request.status_code, url))
# Store current record list
zips_to_delete = zip_model.search(
[('country_id', '=', self.country_id.id)])
f_geonames = zipfile.ZipFile(StringIO.StringIO(res_request.content))
tempdir = tempfile.mkdtemp(prefix='openerp')
f_geonames.extract('%s.txt' % country_code, tempdir)
logger.info('The geonames zipfile has been decompressed')
data_file = open(os.path.join(tempdir, '%s.txt' % country_code), 'r')
data_file.seek(0)
logger.info('Starting to create the better zip entries')
max_import = self.env.context.get('max_import', 0)
reader = unicodecsv.reader(data_file, encoding='utf-8', delimiter=' ')
for i, row in enumerate(reader):
zip_code = self.create_better_zip(row, self.country_id)
if zip_code in zips_to_delete:
zips_to_delete -= zip_code
if max_import and (i + 1) == max_import:
break
data_file.close()
if zips_to_delete and not max_import:
zips_to_delete.unlink()
logger.info('%d better zip entries deleted for country %s' %
(len(zips_to_delete), self.country_id.name))
logger.info(
'The wizard to create better zip entries from geonames '
'has been successfully completed.')
return True
|
'''
Given a sorted array of integers, find the number of times
a given number K occurs in the array.
'''
def find_k(arr, item):
first_occurence = None
last_occurence = None
# find the first occurence
count = 0
l = 0
u = len(arr) - 1
while l <= u:
mid = int(l + (u-l)/2)
if arr[mid] == item:
first_occurence = mid
if mid == 0:
break
if arr[mid-1] < item:
break
if arr[mid-1] == item:
u = mid - 1
else:
if arr[mid] < item:
l = mid + 1
else:
u = mid -1
if first_occurence is None:
return None
# find the last occurence
l = first_occurence
u = len(arr) - 1
while l <= u:
mid = int(l + (u-l)/2)
if arr[mid] == item:
last_occurence = mid
if mid == len(arr) - 1:
break
if arr[mid+1] > item:
break
if arr[mid+1] == item:
l = mid + 1
else:
if arr[mid] < item:
l = mid + 1
else:
u = mid -1
if last_occurence is None:
return None
return last_occurence - first_occurence + 1
assert find_k([1, 2, 3, 3, 4, 5], 3) == 2
assert find_k([1, 2, 3, 3, 4, 5], 1) == 1
assert find_k([1, 2, 2, 2, 4, 5], 2) == 3
assert find_k([2, 2, 2, 2, 2, 2], 2) == 6
assert find_k([1, 1, 2, 2, 2, 2, 3], 2) == 4
assert find_k([1, 1, 2, 2, 2, 2, 3], 4) == None
|
"""
pkgdata is a simple, extensible way for a package to acquire data file
resources.
The getResource function is equivalent to the standard idioms, such as
the following minimal implementation:
import sys, os
def getResource(identifier, pkgname=__name__):
pkgpath = os.path.dirname(sys.modules[pkgname].__file__)
path = os.path.join(pkgpath, identifier)
return file(os.path.normpath(path), mode='rb')
When a __loader__ is present on the module given by __name__, it will defer
getResource to its get_data implementation and return it as a file-like
object (such as StringIO).
"""
__all__ = ['getResource']
import sys
import os
from pygame.compat import get_BytesIO
BytesIO = get_BytesIO()
try:
from pkg_resources import resource_stream, resource_exists
except ImportError:
def resource_exists(package_or_requirement, resource_name):
return False
def resource_stream(package_of_requirement, resource_name):
raise NotImplementedError
def getResource(identifier, pkgname=__name__):
"""
Acquire a readable object for a given package name and identifier.
An IOError will be raised if the resource can not be found.
For example:
mydata = getResource('mypkgdata.jpg').read()
Note that the package name must be fully qualified, if given, such
that it would be found in sys.modules.
In some cases, getResource will return a real file object. In that
case, it may be useful to use its name attribute to get the path
rather than use it as a file-like object. For example, you may
be handing data off to a C API.
"""
if resource_exists(pkgname, identifier):
return resource_stream(pkgname, identifier)
mod = sys.modules[pkgname]
fn = getattr(mod, '__file__', None)
if fn is None:
raise IOError("%s has no __file__!" % repr(mod))
path = os.path.join(os.path.dirname(fn), identifier)
loader = getattr(mod, '__loader__', None)
if loader is not None:
try:
data = loader.get_data(path)
except IOError:
pass
else:
return BytesIO(data)
return open(os.path.normpath(path), 'rb')
|
#!/usr/bin/python3
import sys, json
USAGE = 'Usage: {} <file>'.format(sys.argv[0])
def html(tag, content, attributes = {}):
attr = ''.join(' {}="{}"'.format(i, a) for i, a in attributes.items())
if hasattr(content, '__iter__'):
content = ''.join(content)
return '<{0}{1}>{2}</{0}>'.format(tag, attr, content)
def wrap(tag, attributes = {}):
def iwrap(f):
def wrapped(*args, **kwargs):
return html(tag, f(*args, **kwargs), attributes)
return wrapped
return iwrap
class HtmlGenerator:
template = """<html><head><meta charset="utf-8">
<link rel="stylesheet" href="//code.cdn.mozilla.net/fonts/fira.css">
<link rel="stylesheet" href="style.css">
</head><body>
<div><h1>{title}</h1>{puzzle}{description}</div>
{down}
{across}
<script src="player.js"></script>
<script>new IpuzPlayer({solution})</script></body></html>
"""
displayedFields = [
'copyright', 'publisher', 'publication', 'url', 'uniqueid', 'intro',
'author', 'editor', 'date', 'notes', 'difficulty', 'origin'
]
def __init__(self, puzzle):
self.puzzle = puzzle
self.block = self.puzzle.get('block', '#')
self.empty = self.puzzle.get('empty', 0)
@wrap('dl')
def genDescription(self):
for name in self.displayedFields:
if name in self.puzzle:
yield html('dt', name) + html('dd', self.puzzle[name])
@wrap('ol')
def genClues(self, section):
for clue in self.puzzle['clues'][section]:
if type(clue) is list:
nr, text = clue
elif type(clue) is dict:
nr, text = clue['number'], clue['clue']
yield html('li', text, {'value': nr, 'data-index': self.getIndex(nr), 'class': 'clue ' + section.lower()})
@wrap('div', {'class': 'clues'})
def genClueBlock(self, section):
return html('h2', section) + self.genClues(section)
def getIndex(self, nr):
for y, row in enumerate(self.puzzle['puzzle']):
for x, cell in enumerate(row):
if type(cell) is dict:
cell = cell['cell']
if str(cell) == str(nr):
return '{},{}'.format(x,y)
@wrap('table', {'class': 'puzzle'})
def genPuzzle(self):
for y, row in enumerate(self.puzzle['puzzle']):
yield self.genPuzzleRow(y, row)
def genPuzzleCell(self, x, y, cell):
classes = []
if type(cell) is dict:
if cell.get('style', {}).get('shapebg') == 'circle':
classes.append('circle')
cell = cell['cell']
letter = ''
if cell is None:
classes.append('empty')
elif cell == self.block:
classes.append('block')
else:
letter = html('span', '', {'class': 'letter'})
attributes = {'data-index': '{},{}'.format(x, y)}
nr = ''
if str(cell) not in map(str, [self.block, self.empty]):
nr = html('span', cell, {'class': 'nr'})
attributes['data-nr'] = cell
if len(classes):
attributes['class'] = ' '.join(classes)
return html('td', nr + letter, attributes)
@wrap('tr')
def genPuzzleRow(self, y, row):
for x, cell in enumerate(row):
yield self.genPuzzleCell(x, y, cell)
def genSolution(self):
solution = self.puzzle['solution']
return [[self.mapSolutionCell(cell) for cell in row] for row in solution]
def mapSolutionCell(self, value):
if value is None or str(value) == str(self.block):
return '#'
return value
def genHtml(self):
return self.template.format(
title=self.puzzle['title'],
puzzle=self.genPuzzle(),
description=self.genDescription(),
down=self.genClueBlock('Down'),
across=self.genClueBlock('Across'),
solution=self.genSolution()
)
if len(sys.argv) < 2:
sys.stderr.write('Error: Missing crossword file\n{}\n'.format(USAGE))
exit(1)
with open(sys.argv[1]) as file:
try:
import ipuz
puzzle = ipuz.core.read(file.read())
except:
puzzle = json.load(file)
sys.stdout.write(HtmlGenerator(puzzle).genHtml())
|
<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle navbar-toggle-context"
data-toggle="collapse" data-target=".navbar-top-collapse">
<span class="sr-only">Toggle Navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<div class="navbar-brand-container">
<span class="navbar-brand">
<h1 class="text-overflow"><i class="icon-rental"></i> Rentals</h1>
</span>
</div>
</div>
<div class="collapse navbar-collapse navbar-top-collapse">
<div class="navbar-right">
<button class="btn btn-secondary navbar-btn" type="button">Button</button>
<button class="btn btn-primary navbar-btn" type="button">Call to action</button>
</div>
</div>
</div>
</nav>
<section class="main-content">
<div class="sheet">
<p>Body</p>
</div>
</section>
|
/*
* $Id$
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2.views.java.simple;
import org.apache.struts2.views.java.Attributes;
import org.apache.struts2.views.java.TagGenerator;
import java.io.IOException;
import java.util.Map;
public class DivHandler extends AbstractTagHandler implements TagGenerator {
public void generate() throws IOException {
Map<String, Object> params = context.getParameters();
Attributes attrs = new Attributes();
attrs.addIfExists("name", params.get("name"))
.addIfExists("id", params.get("id"))
.addIfExists("class", params.get("cssClass"))
.addIfExists("style", params.get("cssStyle"))
.addIfExists("title", params.get("title"));
super.start("div", attrs);
}
public static class CloseHandler extends AbstractTagHandler implements TagGenerator {
public void generate() throws IOException {
end("div");
}
}
}
|
<?php
namespace Phobetor\RabbitMqSupervisorBundle\Helpers;
class ConfigurationHelper
{
public function getConfigurationStringFromDataArray(array $data)
{
$configurationString = '';
foreach ($data as $key => $value) {
if (is_array($value)) {
$configurationString .= sprintf("[%s]\n", $key);
$configurationString .= $this->getConfigurationStringFromDataArray($value);
$configurationString .= "\n";
} else {
$configurationString .= sprintf("%s=%s\n", $key, $value);
}
}
return $configurationString;
}
}
|
#!/usr/bin/python
import sys
import json
reload(sys)
sys.setdefaultencoding("utf-8")
sys.path.append('/')
import cgi
import cgitb
cgitb.enable()
from alkivi.common import logger
# Define the global logger
logger.Logger.instance(
#min_log_level_to_mail = logger.WARNING,
min_log_level_to_mail = None,
min_log_level_to_save = logger.DEBUG_DEBUG,
min_log_level_to_print = logger.INFO,
filename='/var/log/alkivi/archive.log',
emails=['root@localhost'])
from alkivi.l0 import archive
def main():
#
# Params
#
arguments = cgi.FieldStorage()
action = arguments['action'].value
#
# Get Local PCA data
#
dbInstance = archive.Db()
logger.debug('action to do: %s' % (action))
if(action=='sessionList'):
response = getSessions(arguments)
elif(action=='pcaList'):
response = getPCAs()
elif(action=='fileList'):
response = getFiles(arguments)
elif(action=='searchFiles'):
response = searchFiles(arguments)
else:
returnError('I did not understand this action')
print "Content-type: application/json"
print
print json.JSONEncoder().encode(response)
def searchFiles(arg):
fileName = arg['fileName'].value
if(not(fileName)):
returnError('Filename is missing')
response = {}
try:
fileList = archive.File().newListFromCharacteristics(characteristics = { 'fileName': { 'operator': 'like', 'value': fileName } })
response['status'] = 100
data = []
for file in fileList:
data.append(file.as_dict())
response['value'] = data
except Exception as e:
logger.warning('Unable to fetch file list', e)
response['status'] = 200
return response
def getFiles(arg):
sessionId = arg['sessionId'].value
if(not(sessionId)):
returnError('PCA id is missing')
response = {}
try:
fileList = archive.File().newListFromCharacteristics(characteristics = { 'session_id': sessionId })
response['status'] = 100
data = []
for file in fileList:
data.append(file.as_dict())
response['value'] = data
except Exception as e:
logger.warning('Unable to fetch file list', e)
response['status'] = 200
return response
def getSessions(arg):
pcaId = arg['pcaId'].value
if(not(pcaId)):
returnError('PCA id is missing')
response = {}
try:
sessionList = archive.Session().newListFromCharacteristics(characteristics = { 'pca_id': pcaId })
response['status'] = 100
data = []
for session in sessionList:
data.append(session.as_dict())
response['value'] = data
except Exception as e:
logger.warning('Unable to fetch session list', e)
response['status'] = 200
return response
def getPCAs():
response = {}
try:
pcaList = archive.PCA().newListFromCharacteristics()
response['status'] = 100
data = []
for pca in pcaList:
data.append(pca.as_dict())
response['value'] = data
except Exception as e:
logger.warning('Unable to fetch pca list', e)
response['status'] = 200
return response
def returnError(message):
response = { 'status': 200, 'msg': message }
print "Content-type: application/json"
print
print json.JSONEncoder().encode(response)
if __name__ == "__main__":
main()
|
<?php
/**
* WooCommerce Auth
*
* Handles wc-auth endpoint requests
*
* @author Prospress
* @category API
* @since 2.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class WCS_Auth {
/**
* Setup class
*
* @since 2.0.0
*/
public function __construct() {
add_filter( 'woocommerce_api_permissions_in_scope', array( $this, 'get_permissions_in_scope' ), 10, 2 );
}
/**
* Return a list of permissions a scope allows
*
* @param array $permissions
* @param string $scope
* @since 2.0.0
* @return array
*/
public function get_permissions_in_scope( $permissions, $scope ) {
switch ( $scope ) {
case 'read' :
$permissions[] = __( 'View subscriptions', 'woocommerce-subscriptions' );
break;
case 'write' :
$permissions[] = __( 'Create subscriptions', 'woocommerce-subscriptions' );
break;
case 'read_write' :
$permissions[] = __( 'View and manage subscriptions', 'woocommerce-subscriptions' );
break;
}
return $permissions;
}
}
return new WCS_Auth();
|
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef CONSTANTS_H
#define CONSTANTS_H
namespace Constants {
const char CMD_HELP[] ="help";
const char CMD_HELP2[] = "h";
const char CMD_HELP3[] = "?";
const char CMD_RECORD[] ="record";
const char CMD_RECORD2[] ="r";
const char CMD_QUIT[] ="quit";
const char CMD_QUIT2[] = "q";
} // Constants
#endif // CONSTANTS_H
|
#!/usr/bin/python -tt
# An incredibly simple agent. All we do is find the closest enemy tank, drive
# towards it, and shoot. Note that if friendly fire is allowed, you will very
# often kill your own tanks with this code.
#################################################################
# NOTE TO STUDENTS
# This is a starting point for you. You will need to greatly
# modify this code if you want to do anything useful. But this
# should help you to know how to interact with BZRC in order to
# get the information you need.
#
# After starting the bzrflag server, this is one way to start
# this code:
# python agent0.py [hostname] [port]
#
# Often this translates to something like the following (with the
# port name being printed out by the bzrflag server):
# python agent0.py localhost 49857
#################################################################
import sys
import math
import time
import random
from bzrc import BZRC, Command
from time import sleep
class Agent(object):
"""Class handles all command and control logic for a teams tanks."""
def __init__(self, bzrc):
self.bzrc = bzrc
self.constants = self.bzrc.get_constants()
self.commands = []
def tick(self, time_diff):
"""Some time has passed; decide what to do next."""
mytanks, othertanks, flags, shots = self.bzrc.get_lots_o_stuff()
self.mytanks = mytanks
self.othertanks = othertanks
self.flags = flags
self.shots = shots
self.enemies = [tank for tank in othertanks if tank.color !=
self.constants['team']]
self.commands = []
# for tank in mytanks:
# self.attack_enemies(tank)
self.attack_enemies(mytanks)
def attack_enemies(self, tanks):
for tank in tanks:
self.move_straight(tank,tank.x,tank.y)
t0 = time.time()
rint = random.randint(3, 8)
while ( (time.time() - t0) < rint):
results = self.bzrc.do_commands(self.commands)
commands = []
for tank in tanks:
self.move_to_position(tank, tank.x, tank.y)
t0 = time.time()
while ( (time.time() - t0) < 1.8):
results = self.bzrc.do_commands(self.commands)
def move_straight(self, tank, target_x, target_y):
"""Set command to move to given coordinates."""
command = Command(tank.index, 1, 0, True)
#print tank.angle
self.commands.append(command)
def move_to_position(self, tank, target_x, target_y):
"""Set command to move to given coordinates."""
target_angle = tank.angle + 60
relative_angle = self.normalize_angle(target_angle - tank.angle)
#print str(relative_angle)
command = Command(tank.index, 0, 1, True)
self.commands.append(command)
def normalize_angle(self, angle):
"""Make any angle be between +/- pi."""
angle -= 2 * math.pi * int (angle / (2 * math.pi))
if angle <= -math.pi:
angle += 2 * math.pi
elif angle > math.pi:
angle -= 2 * math.pi
return angle
def main():
# Process CLI arguments.
try:
execname, host, port = sys.argv
except ValueError:
execname = sys.argv[0]
print >>sys.stderr, '%s: incorrect number of arguments' % execname
print >>sys.stderr, 'usage: %s hostname port' % sys.argv[0]
sys.exit(-1)
# Connect.
#bzrc = BZRC(host, int(port), debug=True)
bzrc = BZRC(host, int(port))
agent = Agent(bzrc)
prev_time = time.time()
# Run the agent
try:
while True:
time_diff = time.time() - prev_time
agent.tick(time_diff)
except KeyboardInterrupt:
print "Exiting due to keyboard interrupt."
bzrc.close()
if __name__ == '__main__':
main()
# vim: et sw=4 sts=4
|
//Tue Mar 9 02:40:39 CST 2010
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(int argc, const char* argv[])
{
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
string str;
while(getline(cin, str))
{
int count = 0;
bool flag = false;
for(int i=0; i<(int)str.size(); i++)
{
if(isalpha(str[i]))
{
count += (flag==false ? 1 : 0);
flag = true;
}
else
flag = false;
}
cout << count << endl;
}
fclose(stdin);
fclose(stdout);
return 0;
}
|
<?php
namespace TimeMachine\ICal\Parser\Tokenizer;
/**
* @author Jean-François Simon <contact@jfsimon.fr>
*/
interface TokenizerInterface
{
/**
* @param string $content
*
* @return array
*
* @throws \TimeMachine\ICal\Exception\TokenizerException;;
*/
function buildTokens($content);
}
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# HORTON: Helpful Open-source Research TOol for N-fermion systems.
# Copyright (C) 2011-2017 The HORTON Development Team
#
# This file is part of HORTON.
#
# HORTON is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# HORTON is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>
#
# --
import argparse
import numpy as np
from horton import log, __version__
from horton.scripts.common import parse_h5, write_script_output, \
check_output
from horton.scripts.espfit import load_cost
# All, except underflows, is *not* fine.
np.seterr(divide='raise', over='raise', invalid='raise')
def parse_args():
parser = argparse.ArgumentParser(prog='horton-esp-fit.py',
description='Estimate charges from an ESP cost function.')
parser.add_argument('-V', '--version', action='version',
version="%%(prog)s (HORTON version %s)" % __version__)
parser.add_argument('cost',
help='The location of the cost function in the form '
'"file.h5:group/cost". This argument must be the same as the '
'output argument of the script horton-esp-cost.py.')
parser.add_argument('output',
help='The output destination in the form file.h5:group. The colon and '
'the group name are optional. When omitted, the root group of the '
'HDF5 file is used.')
parser.add_argument('--overwrite', default=False, action='store_true',
help='Overwrite existing output in the HDF5 file')
parser.add_argument('--qtot', '-q', default=0.0, type=float,
help='The total charge of the system. [default=%(default)s]')
parser.add_argument('--ridge', default=0.0, type=float,
help='The thikonov regularization strength used when solving the '
'charges. [default=%(default)s]')
# TODO: more constraint and restraint options
return parser.parse_args()
def main():
args = parse_args()
fn_h5, grp_name = parse_h5(args.output, 'output')
# check if the group is already present (and not empty) in the output file
if check_output(fn_h5, grp_name, args.overwrite):
return
# Load the cost function from the HDF5 file
cost, used_volume = load_cost(args.cost)
# Find the optimal charges
results = {}
results['x'] = cost.solve(args.qtot, args.ridge)
results['charges'] = results['x'][:cost.natom]
# Related properties
results['cost'] = cost.value(results['x'])
if results['cost'] < 0:
results['rmsd'] = 0.0
else:
results['rmsd'] = (results['cost']/used_volume)**0.5
# Worst case stuff
results['cost_worst'] = cost.worst(0.0)
if results['cost_worst'] < 0:
results['rmsd_worst'] = 0.0
else:
results['rmsd_worst'] = (results['cost_worst']/used_volume)**0.5
# Write some things on screen
if log.do_medium:
log('Important parameters:')
log.hline()
log('RMSD charges: %10.5e' % np.sqrt((results['charges']**2).mean()))
log('RMSD ESP: %10.5e' % results['rmsd'])
log('Worst RMSD ESP: %10.5e' % results['rmsd_worst'])
log.hline()
# Store the results in an HDF5 file
write_script_output(fn_h5, grp_name, results, args)
if __name__ == '__main__':
main()
|
"""
This dependency resolver resolves tool shed dependencies (those defined
tool_dependencies.xml) installed using Platform Homebrew and converted
via shed2tap (e.g. https://github.com/jmchilton/homebrew-toolshed).
"""
import logging
import os
from xml.etree import ElementTree as ET
from .resolver_mixins import (
UsesHomebrewMixin,
UsesToolDependencyDirMixin,
UsesInstalledRepositoriesMixin,
)
from ..resolvers import DependencyResolver, INDETERMINATE_DEPENDENCY
log = logging.getLogger(__name__)
class HomebrewToolShedDependencyResolver(
DependencyResolver,
UsesHomebrewMixin,
UsesToolDependencyDirMixin,
UsesInstalledRepositoriesMixin,
):
resolver_type = "tool_shed_tap"
def __init__(self, dependency_manager, **kwds):
self._init_homebrew(**kwds)
self._init_base_path(dependency_manager, **kwds)
def resolve(self, name, version, type, **kwds):
if type != "package":
return INDETERMINATE_DEPENDENCY
if version is None:
return INDETERMINATE_DEPENDENCY
return self._find_tool_dependencies(name, version, type, **kwds)
def _find_tool_dependencies(self, name, version, type, **kwds):
installed_tool_dependency = self._get_installed_dependency(name, type, version=version, **kwds)
if installed_tool_dependency:
return self._resolve_from_installed_tool_dependency(name, version, installed_tool_dependency)
if "tool_dir" in kwds:
tool_directory = os.path.abspath(kwds["tool_dir"])
tool_depenedencies_path = os.path.join(tool_directory, "tool_dependencies.xml")
if os.path.exists(tool_depenedencies_path):
return self._resolve_from_tool_dependencies_path(name, version, tool_depenedencies_path)
return INDETERMINATE_DEPENDENCY
def _resolve_from_installed_tool_dependency(self, name, version, installed_tool_dependency):
tool_shed_repository = installed_tool_dependency.tool_shed_repository
recipe_name = build_recipe_name(
package_name=name,
package_version=version,
repository_owner=tool_shed_repository.owner,
repository_name=tool_shed_repository.name,
)
return self._find_dep_default(recipe_name, None)
def _resolve_from_tool_dependencies_path(self, name, version, tool_dependencies_path):
try:
raw_dependencies = RawDependencies(tool_dependencies_path)
except Exception:
log.debug("Failed to parse dependencies in file %s" % tool_dependencies_path)
return INDETERMINATE_DEPENDENCY
raw_dependency = raw_dependencies.find(name, version)
if not raw_dependency:
return INDETERMINATE_DEPENDENCY
recipe_name = build_recipe_name(
package_name=name,
package_version=version,
repository_owner=raw_dependency.repository_owner,
repository_name=raw_dependency.repository_name
)
dep = self._find_dep_default(recipe_name, None)
return dep
class RawDependencies(object):
def __init__(self, dependencies_file):
self.root = ET.parse(dependencies_file).getroot()
dependencies = []
package_els = self.root.findall("package") or []
for package_el in package_els:
repository_el = package_el.find("repository")
if repository_el is None:
continue
dependency = RawDependency(self, package_el, repository_el)
dependencies.append(dependency)
self.dependencies = dependencies
def find(self, package_name, package_version):
target_dependency = None
for dependency in self.dependencies:
if dependency.package_name == package_name and dependency.package_version == package_version:
target_dependency = dependency
break
return target_dependency
class RawDependency(object):
def __init__(self, dependencies, package_el, repository_el):
self.dependencies = dependencies
self.package_el = package_el
self.repository_el = repository_el
def __repr__(self):
temp = "Dependency[package_name=%s,version=%s,dependent_package=%s]"
return temp % (
self.package_el.attrib["name"],
self.package_el.attrib["version"],
self.repository_el.attrib["name"]
)
@property
def repository_owner(self):
return self.repository_el.attrib["owner"]
@property
def repository_name(self):
return self.repository_el.attrib["name"]
@property
def package_name(self):
return self.package_el.attrib["name"]
@property
def package_version(self):
return self.package_el.attrib["version"]
def build_recipe_name(package_name, package_version, repository_owner, repository_name):
# TODO: Consider baking package_name and package_version into name? (would be more "correct")
owner = repository_owner.replace("-", "")
name = repository_name
name = name.replace("_", "").replace("-", "")
base = "%s_%s" % (owner, name)
return base
__all__ = ['HomebrewToolShedDependencyResolver']
|
/*
*
* Copyright (C) International Business Machines Corp., 2004, 2005
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* NAME
* Tspi_Policy_SetSecret03.c
*
* DESCRIPTION
* This test will verify Tspi_Policy_SetSecret.
* The purpose of this test is to get TSS_E_BAD_PARAMETER
* to be returned. This is easily accomplished by
* passing in an incorrect second parameter. For
* this test case TSS_KEY_SIZE_1024 is passed
* in instead of TSS_SECRET_MODE_PLAIN.
* ALGORITHM
* Setup:
* Create Context
* Connect Context
* Get Default Policy
*
* Test: Call Policy_SetSecret and if it is not a success
* Make sure that it returns the proper return codes
*
* Cleanup:
* Free memory associated with the context
* Close Context
* Print error/success message
*
* USAGE: First parameter is --options
* -v or --version
* Second Parameter is the version of the test case to be run.
* This test case is currently only implemented for 1.1
*
* HISTORY
* Author: Kathy Robertson.
* Date: June 2004
* Email: klrobert@us.ibm.com
*
* RESTRICTIONS
* None.
*/
#include "common.h"
int main(int argc, char **argv)
{
char version;
version = parseArgs( argc, argv );
if (version)
main_v1_1();
else
print_wrongVersion();
}
main_v1_1(void){
char *nameOfFunction = "Tspi_Policy_SetSecret03";
TSS_HCONTEXT hContext;
TSS_HPOLICY hPolicy;
TSS_RESULT result;
print_begin_test(nameOfFunction);
//Create Context
result = Tspi_Context_Create(&hContext);
if (result != TSS_SUCCESS) {
print_error("Tspi_Context_Create ", result);
print_error_exit(nameOfFunction, err_string(result));
exit(result);
}
//Connect Context
result = Tspi_Context_Connect(hContext, get_server(GLOBALSERVER));
if (result != TSS_SUCCESS) {
print_error("Tspi_Context_Connect ", result);
print_error_exit(nameOfFunction, err_string(result));
Tspi_Context_Close(hContext);
exit(result);
}
//Get Default Policy
result = Tspi_Context_GetDefaultPolicy(hContext, &hPolicy);
if (result != TSS_SUCCESS) {
print_error("Tspi_Context_GetDefaultPolicy ", result);
print_error_exit(nameOfFunction, err_string(result));
Tspi_Context_Close(hContext);
exit(result);
}
//Set Secret
result = Tspi_Policy_SetSecret(hPolicy, TSS_KEY_SIZE_1024,
TESTSUITE_NEW_SECRET_LEN, TESTSUITE_NEW_SECRET);
if (TSS_ERROR_CODE(result) != TSS_E_BAD_PARAMETER) {
if(!checkNonAPI(result)){
print_error(nameOfFunction, result);
print_end_test(nameOfFunction);
Tspi_Context_FreeMemory(hContext, NULL);
Tspi_Context_Close(hContext);
exit(result);
}
else{
print_error_nonapi(nameOfFunction, result);
print_end_test(nameOfFunction);
Tspi_Context_FreeMemory(hContext, NULL);
Tspi_Context_Close(hContext);
exit(result);
}
}
else{
print_success(nameOfFunction, result);
print_end_test(nameOfFunction);
Tspi_Context_FreeMemory(hContext, NULL);
Tspi_Context_Close(hContext);
exit(0);
}
}
|
import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';
import { DataSource } from '../../../../lib/data-source/data-source';
import { Column } from '../../../../lib/data-set/column';
@Component({
selector: 'ng2-smart-table-title',
styleUrls: ['./title.component.scss'],
template: `
<a href="#" *ngIf="column.isSortable"
(click)="_sort($event, column)"
class="ng2-smart-sort-link sort"
[ngClass]="currentDirection">
{{ column.title }}
</a>
<span class="ng2-smart-sort" *ngIf="!column.isSortable">{{ column.title }}</span>
`,
})
export class TitleComponent implements OnInit {
currentDirection = '';
@Input() column: Column;
@Input() source: DataSource;
@Output() sort = new EventEmitter<any>();
ngOnInit() {
this.source.onChanged().subscribe((elements) => {
const sortConf = this.source.getSort();
if (sortConf.length > 0 && sortConf[0]['field'] === this.column.id) {
this.currentDirection = sortConf[0]['direction'];
} else {
this.currentDirection = '';
}
sortConf.forEach((fieldConf: any) => {
});
});
}
_sort(event: any) {
event.preventDefault();
this.changeSortDirection();
this.source.setSort([
{
field: this.column.id,
direction: this.currentDirection,
compare: this.column.getCompareFunction(),
},
]);
this.sort.emit(null);
}
changeSortDirection(): string {
if (this.currentDirection) {
const newDirection = this.currentDirection === 'asc' ? 'desc' : 'asc';
this.currentDirection = newDirection;
} else {
this.currentDirection = this.column.sortDirection;
}
return this.currentDirection;
}
}
|
define([
'lodash',
'jquery',
'knockout',
'when'
], function (
_,
$,
ko,
when
) {
var Woodhouse = function (user) {
this.user = user;
this.available = ko.observable(false);
this.current_recipe = ko.observable();
when($.ajax({
type: 'GET',
url: 'http://woodhouse/',
contentType: 'application/json',
processData: false
})).done(_.bind(function () {
this.available(true);
}, this), _.bind(function () {
this.available(false);
}, this));
};
Woodhouse.prototype.pour = function (recipe) {
this.current_recipe(recipe);
$('#woodhouse').modal('show');
};
return Woodhouse;
});
|
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from novaclient import base
from novaclient import exceptions
from novaclient.tests import utils
from novaclient.tests.v1_1 import fakes
from novaclient.v1_1 import flavors
cs = fakes.FakeClient()
class BaseTest(utils.TestCase):
def test_resource_repr(self):
r = base.Resource(None, dict(foo="bar", baz="spam"))
self.assertEqual(repr(r), "<Resource baz=spam, foo=bar>")
def test_getid(self):
self.assertEqual(base.getid(4), 4)
class TmpObject(object):
id = 4
self.assertEqual(base.getid(TmpObject), 4)
def test_resource_lazy_getattr(self):
f = flavors.Flavor(cs.flavors, {'id': 1})
self.assertEqual(f.name, '256 MB Server')
cs.assert_called('GET', '/flavors/1')
# Missing stuff still fails after a second get
self.assertRaises(AttributeError, getattr, f, 'blahblah')
def test_eq(self):
# Two resources of the same type with the same id: equal
r1 = base.Resource(None, {'id': 1, 'name': 'hi'})
r2 = base.Resource(None, {'id': 1, 'name': 'hello'})
self.assertEqual(r1, r2)
# Two resoruces of different types: never equal
r1 = base.Resource(None, {'id': 1})
r2 = flavors.Flavor(None, {'id': 1})
self.assertNotEqual(r1, r2)
# Two resources with no ID: equal if their info is equal
r1 = base.Resource(None, {'name': 'joe', 'age': 12})
r2 = base.Resource(None, {'name': 'joe', 'age': 12})
self.assertEqual(r1, r2)
def test_findall_invalid_attribute(self):
# Make sure findall with an invalid attribute doesn't cause errors.
# The following should not raise an exception.
cs.flavors.findall(vegetable='carrot')
# However, find() should raise an error
self.assertRaises(exceptions.NotFound,
cs.flavors.find,
vegetable='carrot')
|
export default class Boot extends Phaser.State {
public create ()
{
this.physics.startSystem(Phaser.Physics.ARCADE);
this.game.state.start('Preload');
}
}
|
# -*- coding: utf-8 -*-
from openprocurement.api.utils import raise_operation_error, error_handler
from openprocurement.tender.core.utils import optendersresource
from openprocurement.tender.openua.views.award_complaint_document import (
TenderUaAwardComplaintDocumentResource
)
from openprocurement.tender.openua.constants import STATUS4ROLE
@optendersresource(name='negotiation:Tender Award Complaint Documents',
collection_path='/tenders/{tender_id}/awards/{award_id}/complaints/{complaint_id}/documents',
path='/tenders/{tender_id}/awards/{award_id}/complaints/{complaint_id}/documents/{document_id}',
procurementMethodType='negotiation',
description="Tender negotiation award complaint documents")
class TenderNegotiationAwardComplaintDocumentResource(TenderUaAwardComplaintDocumentResource):
def validate_complaint_document(self, operation):
""" TODO move validators
This class is inherited from openua package, but validate_complaint_document function has different validators.
For now, we have no way to use different validators on methods according to procedure type.
"""
if operation == 'update' and self.request.authenticated_role != self.context.author:
self.request.errors.add('url', 'role', 'Can update document only author')
self.request.errors.status = 403
raise error_handler(self.request.errors)
if self.request.validated['tender_status'] != 'active':
raise_operation_error(self.request, 'Can\'t {} document in current ({}) tender status'.format(operation, self.request.validated['tender_status']))
if self.request.validated['complaint'].status not in STATUS4ROLE.get(self.request.authenticated_role, []):
raise_operation_error(self.request, 'Can\'t {} document in current ({}) complaint status'.format(operation, self.request.validated['complaint'].status))
return True
@optendersresource(name='negotiation.quick:Tender Award Complaint Documents',
collection_path='/tenders/{tender_id}/awards/{award_id}/complaints/{complaint_id}/documents',
path='/tenders/{tender_id}/awards/{award_id}/complaints/{complaint_id}/documents/{document_id}',
procurementMethodType='negotiation.quick',
description="Tender negotiation.quick award complaint documents")
class TenderNegotiationQuickAwardComplaintDocumentResource(TenderNegotiationAwardComplaintDocumentResource):
""" Tender Negotiation Quick Award Complaint Document Resource """
|
name = "Min or max rank enforcer"
author = "codesuela"
import base, logging, ConfigParser
class Bf3Mod(base.Bf3Mod):
def playerOnAuthenticated(self, name):
if self.modLoader.battleQuery:
self.modLoader.battleQuery.resolveQueryAndCallback(name, self, "bqCallback")
else:
logging.warn("Battlequery not enabled, could not get player stats")
def bqCallback(self, playerName, jsonData):
playerRank = int(jsonData["rank"])
if playerRank < self.minRank:
self.actionHandler.kickPlayer(playerName, "Minimum rank is %s" % str(self.minRank))
elif playerRank > self.maxRank and self.maxRank != 0:
self.actionHandler.kickPlayer(playerName, "Max rank is %s" % str(self.maxRank))
return None
def onLoad(self):
self.minRank = 0
self.maxRank = 0
try:
self.minRank = int(self.modConfig.get("settings", "minRank"))
except ConfigParser.NoOptionError:
pass
try:
self.maxRank = int(self.modConfig.get("settings", "maxRank"))
except ConfigParser.NoOptionError:
pass
|
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>doc-ja/changes.rd</title>
<link href="style.css" type="text/css" rel="stylesheet" />
</head>
<body>
<h1><a name="label-0" id="label-0">Changes</a></h1><!-- RDLabel: "Changes" -->
<h2><a name="label-1" id="label-1">0.71(2005.07.26)</a></h2><!-- RDLabel: "0.71(2005.07.26)" -->
<ul>
<li>MPolynomial#derivate</li>
<li>MPolynomial#map_to</li>
</ul>
<h2><a name="label-2" id="label-2">0.70(2005.02.02)</a></h2><!-- RDLabel: "0.70(2005.02.02)" -->
<ul>
<li>id => object_id</li>
</ul>
<h2><a name="label-3" id="label-3">0.69(2004.10.15)</a></h2><!-- RDLabel: "0.69(2004.10.15)" -->
<ul>
<li>MRationalFunctionField</li>
<li>MPolynomial#gcd</li>
<li>SquareMatrix#inverse depends on ufd?</li>
</ul>
<h2><a name="label-4" id="label-4">0.68(2004.07.28)</a></h2><!-- RDLabel: "0.68(2004.07.28)" -->
<ul>
<li>fix Mpolynomial#to_s (for tex)</li>
</ul>
<h2><a name="label-5" id="label-5">0.67(2004.06.10)</a></h2><!-- RDLabel: "0.67(2004.06.10)" -->
<ul>
<li>need_paren_in_coeff?</li>
<li>Matrix: entries are regulated.</li>
<li>Matrix: type*type is due to wedge.</li>
<li>AlgebraicSystem: wedge, superior?</li>
<li>Polynomial#sub, MPolynomial#sub</li>
<li>SquareMatrix.determinant</li>
<li>fix MPolynomial#to_s</li>
<li>fix Factors#normalize!</li>
<li>(Co)Vector#norm2, inner_product</li>
</ul>
<h2><a name="label-6" id="label-6">0.66(2004.06.05)</a></h2><!-- RDLabel: "0.66(2004.06.05)" -->
<ul>
<li>fix _hensel_lift (add param 'where')</li>
<li>sample-geometry01.rb</li>
<li>title of docs</li>
</ul>
<h2><a name="label-7" id="label-7">0.65(2004.06.04)</a></h2><!-- RDLabel: "0.65(2004.06.04)" -->
<ul>
<li>Polynomial#factor over Polynomial</li>
<li>reverse var's order in value_on & convert_to in polynomial-convert.rb</li>
</ul>
<h2><a name="label-8" id="label-8">0.64(2004.03.01)</a></h2><!-- RDLabel: "0.64(2004.03.01)" -->
<ul>
<li>return value of SquareMatrix#diagonalize is Strut</li>
</ul>
<h2><a name="label-9" id="label-9">0.63(2004.01.08)</a></h2><!-- RDLabel: "0.63(2004.01.08)" -->
<ul>
<li>fix matrix[i, j] = x</li>
</ul>
<h2><a name="label-10" id="label-10">0.62(2003.11.13)</a></h2><!-- RDLabel: "0.62(2003.11.13)" -->
<ul>
<li>allow f.gcd_coeff_all()</li>
</ul>
<h2><a name="label-11" id="label-11">0.61(2003.11.06)</a></h2><!-- RDLabel: "0.61(2003.11.06)" -->
<ul>
<li>corrected Enumerable#any? in finite-set.rb</li>
</ul>
<h2><a name="label-12" id="label-12">0.60(2003.07.28)</a></h2><!-- RDLabel: "0.60(2003.07.28)" -->
<ul>
<li>AlgebraMatrix(cofactor, cofactor_matrix, adjoint)</li>
</ul>
<h2><a name="label-13" id="label-13">0.59(2003.07.28)</a></h2><!-- RDLabel: "0.59(2003.07.28)" -->
<ul>
<li>adapted to the version 1.8.0(preview 4)</li>
<li>include installer</li>
</ul>
<h2><a name="label-14" id="label-14">0.58(2002.04.00)</a></h2><!-- RDLabel: "0.58(2002.04.00)" -->
<ul>
<li>AlgebraicExtensionField#[n] is lift[n]</li>
<li>abolish the field of 'poly_exps' of the splitting field' and add 'proots'</li>
<li>MatrixAlgebra#rank</li>
<li>Raise Exception for the inverse of the non invertible square matrix</li>
<li>Use "import-module" for monomial order (0.57.18.01)</li>
</ul>
<h2><a name="label-15" id="label-15">0.57 (2002.03.16)</a></h2><!-- RDLabel: "0.57 (2002.03.16)" -->
<ul>
<li>New class
<ul>
<li>Set</li>
<li>Map</li>
<li>Group</li>
<li>PermuationGroup</li>
<li>AlgebraicExtensionField</li>
</ul></li>
<li>New methods
<ul>
<li>Galois#group</li>
<li>Polynomial#splitting_field</li>
</ul></li>
<li>Rename MinimalDecompositionField to decompose</li>
<li>Move *.rb to lib/</li>
<li>Define Polynomial.to_ary and MPolynomial.to_ary</li>
</ul>
<h2><a name="label-16" id="label-16">0.56 (2002.02.06)</a></h2><!-- RDLabel: "0.56 (2002.02.06)" -->
<ul>
<li>MPolynomial#with_ord</li>
<li>Orderings belong to MPolynomial.</li>
<li>MIndex is not a subclass of Array, now.</li>
<li>"Integer < Numeric" ==> "Integer"</li>
</ul>
<h2><a name="label-17" id="label-17">0.55 (2001.11.15)</a></h2><!-- RDLabel: "0.55 (2001.11.15)" -->
<ul>
<li>Improve Algorithm of Factorization over algebraic fields</li>
</ul>
<h2><a name="label-18" id="label-18">0.54 (2001.11.05)</a></h2><!-- RDLabel: "0.54 (2001.11.05)" -->
<ul>
<li>Elementary Divisor</li>
<li>Jordan Form</li>
<li>Minimal Decomposition Field</li>
</ul>
<h2><a name="label-19" id="label-19">0.53 (2001.10.03)</a></h2><!-- RDLabel: "0.53 (2001.10.03)" -->
<ul>
<li>move "MatrixAlgebra" to "Algebra::MatrixAlgebra"</li>
<li>move "MatrixAlgebra::Vector" to "Algebra::Vector"</li>
<li>move "MatrixAlgebra::Covector" to "Algebra::Covector",</li>
<li>move "MatrixAlgebra::SquareMatrix" to "Algebra::SquareMatrix"</li>
</ul>
<h2><a name="label-20" id="label-20">0.52 (2001.09.22)</a></h2><!-- RDLabel: "0.52 (2001.09.22)" -->
<ul>
<li>One-variate polynomial
<ul>
<li>Fundamental operations (addition, multiplication, quotient/remainder, ...)</li>
<li>factorization</li>
</ul></li>
<li>Multi-variate polynomial
<ul>
<li>Fundamental operations (addition, multiplication, ...)</li>
<li>factorization</li>
<li>Creating Groebner-basis, quotient/remainder by Groebner-basis.</li>
</ul></li>
<li>Algebraic systems
<ul>
<li>Creating quotient fields</li>
<li>Creating residue class fields</li>
<li>Operating matrices.</li>
</ul></li>
<li>Linear Algebra
<ul>
<li>Diagonalization of Symmetrix Matrix</li>
</ul></li>
</ul>
<h2><a name="label-21" id="label-21">0.40 (2001.03.03)</a></h2><!-- RDLabel: "0.40 (2001.03.03)" -->
<ul>
<li>Initial Version</li>
</ul>
</body>
</html>
|
enyo.kind({
name: "moon.sample.DialogSample",
classes: "moon enyo-unselectable enyo-fit",
components: [
{kind: "moon.Divider", content: "Dialog"},
{kind: "moon.Button", content: "Open Dialog", ontap: "showDialog"},
{classes: "moon-1v"},
{kind: "moon.ToggleButton", content: "Showing", name: "showingToggle"},
{kind: "moon.ToggleButton", content: "Animate", name: "animateToggle"},
{
name: "dialog",
kind: "moon.Dialog",
title: "You've been watching TV a very long time.",
subTitle: "This TV has been active for 10 hours.",
message: "Perhaps it is time to take a break and get some fresh air. There is a nice coffee shop around the corner",
components: [
{kind: "moon.Button", content: "Go get a coffee", ontap: "addMessage"},
{kind: "moon.Button", content: "Keep watching TV", ontap: "hideDialog"}
]
}
],
bindings: [
{from: ".$.showingToggle.value", to: ".$.dialog.showing", oneWay:false},
{from: ".$.dialog.animate", to: ".$.animateToggle.value", oneWay:false}
],
showDialog: function(inSender) {
this.$.dialog.show();
},
hideDialog: function(inSender, inEvent) {
this.$.dialog.hide();
},
addMessage: function() {
this.$.dialog.setMessage(this.$.dialog.getMessage() + "<br> No, seriously, you should probably take a break.");
}
});
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Help</title>
</head>
<body>
</body>
</html>
|
'use strict';
var convert = require('./convert'),
func = convert('lt', require('../lt'));
func.placeholder = require('./placeholder');
module.exports = func;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL2NsaWVudC9saWIvbG9kYXNoL2ZwL2x0LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsSUFBSSxVQUFVLFFBQVEsV0FBUixDQUFWO0lBQ0EsT0FBTyxRQUFRLElBQVIsRUFBYyxRQUFRLE9BQVIsQ0FBZCxDQUFQOztBQUVKLEtBQUssV0FBTCxHQUFtQixRQUFRLGVBQVIsQ0FBbkI7QUFDQSxPQUFPLE9BQVAsR0FBaUIsSUFBakIiLCJmaWxlIjoibHQuanMiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgY29udmVydCA9IHJlcXVpcmUoJy4vY29udmVydCcpLFxuICAgIGZ1bmMgPSBjb252ZXJ0KCdsdCcsIHJlcXVpcmUoJy4uL2x0JykpO1xuXG5mdW5jLnBsYWNlaG9sZGVyID0gcmVxdWlyZSgnLi9wbGFjZWhvbGRlcicpO1xubW9kdWxlLmV4cG9ydHMgPSBmdW5jO1xuIl19
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace usage_samples_003_web_app.Pages
{
public class PrivacyModel : PageModel
{
public void OnGet()
{
}
}
}
|
// DlgTimeDelay.cpp : ʵÏÖÎļþ
//
#include "stdafx.h"
#include "Calibration.h"
#include "DlgTimeDelay.h"
#include "afxdialogex.h"
#include "CalibrationDlg.h"
// CDlgTimeDelay ¶Ô»°¿ò
IMPLEMENT_DYNAMIC(CDlgTimeDelay, CDialogEx)
CDlgTimeDelay::CDlgTimeDelay(CWnd* pParent /*=NULL*/)
: CDialogEx(CDlgTimeDelay::IDD, pParent)
{
}
CDlgTimeDelay::~CDlgTimeDelay()
{
}
void CDlgTimeDelay::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CDlgTimeDelay, CDialogEx)
ON_BN_CLICKED(IDOK, &CDlgTimeDelay::OnBnClickedOk)
ON_BN_CLICKED(IDCANCEL, &CDlgTimeDelay::OnBnClickedCancel)
END_MESSAGE_MAP()
// CDlgTimeDelay ÏûÏ¢´¦Àí³ÌÐò
BOOL CDlgTimeDelay::OnInitDialog()
{
CDialogEx::OnInitDialog();
// TODO: ÔÚ´ËÌí¼Ó¶îÍâµÄ³õʼ»¯
ModuleDelay *pTimeDelay = (ModuleDelay *)m_pModuleData->pData;
SetDlgItemInt(IDC_EDIT_TIMEDELAY, pTimeDelay->nDelayTime);
return TRUE; // return TRUE unless you set the focus to a control
// Òì³£: OCX ÊôÐÔÒ³Ó¦·µ»Ø FALSE
}
void CDlgTimeDelay::OnBnClickedOk()
{
// TODO: ÔÚ´ËÌí¼Ó¿Ø¼þ֪ͨ´¦Àí³ÌÐò´úÂë
ModuleDelay *pTimeDelay = (ModuleDelay *)m_pModuleData->pData;
pTimeDelay->nDelayTime = GetDlgItemInt(IDC_EDIT_TIMEDELAY);
if(g_pMainDlg->IsWindowEnabled()){
DestroyWindow();
::SendMessage(g_pMainDlg->m_hWnd, TIMEDELAY_EXIT, 0, 0);
}else{
CDialogEx::OnOK();
}
}
void CDlgTimeDelay::OnBnClickedCancel()
{
// TODO: ÔÚ´ËÌí¼Ó¿Ø¼þ֪ͨ´¦Àí³ÌÐò´úÂë
if(g_pMainDlg->IsWindowEnabled()){
DestroyWindow();
::SendMessage(g_pMainDlg->m_hWnd, TIMEDELAY_EXIT, 0, 0);
}else{
CDialogEx::OnCancel();
}
}
|
using NUnit.Framework;
using OpenQA.Selenium;
using PersonalFinanceManager.IntegrationTests.Infrastructure;
using TechTalk.SpecFlow;
namespace PersonalFinanceManager.IntegrationTests.Scenarios.Steps
{
[Binding, Scope(Feature = "DeleteIncomes")]
public class DeleteIncomesSteps
{
private int _countMovements, _countIncomes, _sourceAccountId;
private decimal _sourceAccountAmount;
private IWebElement _firstRow;
[BeforeScenario]
public void PrepareForTest()
{
SiteMap.IncomeCreatePage.QuickCreate();
}
[Given(@"I have accessed the Income List page")]
public void GivenIHaveAccessedTheIncomeListPage()
{
SiteMap.AccountManagementDashboardPage.GoTo();
_sourceAccountId = SiteMap.AccountManagementDashboardPage.SelectAccount();
_sourceAccountAmount = DatabaseChecker.GetBankAccountAmount(_sourceAccountId);
SiteMap.IncomeListPage.GoTo();
_countIncomes = DatabaseChecker.CountIncomes();
_countMovements = DatabaseChecker.CountMovements();
}
[Given(@"I have at least one income in the list")]
public void GivenIHaveAtLeastOneIncomeInTheList()
{
_firstRow = SiteMap.IncomeListPage.FindFirstRow();
}
[When(@"I click on delete for the first income")]
public void WhenIClickOnDeleteForTheFirstIncome()
{
SiteMap.IncomeListPage.ClickDeleteButton(_firstRow);
}
[When(@"I confirm the deletion")]
public void WhenIConfirmTheDeletion()
{
SiteMap.IncomeListPage.CheckDeletionConfirmationModalTitle();
SiteMap.IncomeListPage.ClickConfirmDeletionButton();
}
[Then(@"the income has been removed")]
public void ThenTheIncomeHasBeenRemoved()
{
var newCountIncomes = DatabaseChecker.CountIncomes();
Assert.AreEqual(newCountIncomes, _countIncomes - 1);
}
[Then(@"the source account is updated")]
public void ThenTheSourceAccountIsUpdated()
{
var newSourceAccountAmount = DatabaseChecker.GetBankAccountAmount(_sourceAccountId);
Assert.AreEqual(newSourceAccountAmount, _sourceAccountAmount - 100);
}
[Then(@"a mouvement entry has been saved")]
public void ThenAMouvementEntryHasBeenSaved()
{
var newCountMovements = DatabaseChecker.CountMovements();
Assert.AreEqual(newCountMovements, _countMovements + 1);
}
}
}
|
import * as React from "react";
import * as Gallery from "react-grid-gallery";
import { style } from "typestyle";
interface Props {
photos: any[];
}
class PhotoGrid extends React.Component<Props, {}> {
constructor(props: Props) {
super(props);
}
render() {
const { photos } = this.props;
const GalleryComponent: any = Gallery;
return <GalleryComponent images={photos} enableImageSelection={false} />;
}
}
export default PhotoGrid;
|
import asposeslidescloud
from asposeslidescloud.SlidesApi import SlidesApi
from asposeslidescloud.SlidesApi import ApiException
import asposestoragecloud
from asposestoragecloud.StorageApi import StorageApi
from asposestoragecloud.StorageApi import ResponseMessage
apiKey = "XXXXX" #sepcify App Key
appSid = "XXXXX" #sepcify App SID
apiServer = "http://api.aspose.com/v1.1"
data_folder = "../../data/"
#Instantiate Aspose Storage API SDK
storage_apiClient = asposestoragecloud.ApiClient.ApiClient(apiKey, appSid, True)
storageApi = StorageApi(storage_apiClient)
#Instantiate Aspose Slides API SDK
api_client = asposeslidescloud.ApiClient.ApiClient(apiKey, appSid, True)
slidesApi = SlidesApi(api_client);
#set input file name
name = "sample-input.pptx"
slideIndex = 1
try:
#upload file to aspose cloud storage
response = storageApi.PutCreate(name, data_folder + name)
#invoke Aspose.Slides Cloud SDK API to get background information of a particular slide
response = slidesApi.GetSlidesSlideBackground(name, slideIndex)
if response.Status == "OK":
slideBackground = response.Background
print "SlideBackground Type :: " + slideBackground.Type
except ApiException as ex:
print "ApiException:"
print "Code:" + str(ex.code)
print "Message:" + ex.message
|
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
/*
druid.h
Copyright (C) 2004 Sebastien Granjoux
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef __DRUID_H__
#define __DRUID_H__
#define ICON_FILE "anjuta-project-wizard-plugin-48.png"
#include <glib.h>
struct _NPWPlugin;
typedef struct _NPWDruid NPWDruid;
NPWDruid* npw_druid_new (struct _NPWPlugin* plugin, const gchar *directory);
void npw_druid_free (NPWDruid* druid);
void npw_druid_show (NPWDruid* druid);
#endif
|
/*
* Copyright (C) 2011-2014 Morwenn
*
* POLDER is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* POLDER is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program. If not,
* see <http://www.gnu.org/licenses/>.
*/
/**
* @file POLDER/geometry/distance.h
* @brief Distance between geometric entities.
*
* The distances can be computed for every norm of
* the module POLDER/math/norm.h which are to be passed
* as tag types to the functions.
*
* By default the euclidean norm is used, or the P norm
* if an additional unsigned parameter is passed to the
* function (and if an overload is provided).
*/
#ifndef POLDER_GEOMETRY_DISTANCE_H_
#define POLDER_GEOMETRY_DISTANCE_H_
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <cmath>
#include <cstdlib>
#include <POLDER/geometry/point.h>
#include <POLDER/math/distnorm.h>
namespace polder
{
namespace geometry
{
////////////////////////////////////////////////////////////
// Distance between
// - Point
// - Point
template<typename Dist=math::dist::euclidean,
std::size_t N, typename T>
auto distance(const Point<N, T>& p1, const Point<N, T>& p2)
-> T;
template<typename Dist=math::dist::minkowski,
std::size_t N, typename T>
auto distance(const Point<N, T>& p1, const Point<N, T>& p2, unsigned p)
-> T;
////////////////////////////////////////////////////////////
// Distance between
// - Point
// - Hypersphere
template<typename Dist=math::dist::euclidean,
std::size_t N, typename T>
auto distance(const Point<N, T>& p, const Hypersphere<N, T>& h)
-> T;
template<typename Dist=math::dist::euclidean,
std::size_t N, typename T>
auto distance(const Hypersphere<N, T>& h, const Point<N, T>& p)
-> T;
#include "details/distance.inl"
}}
#endif // POLDER_GEOMETRY_DISTANCE_H_
|
/*
* Copyright (C) 2011 Carl Green
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package info.carlwithak.mpxg2.printing;
/**
*
* @author carl
*/
public class PrintException extends Exception {
private static final long serialVersionUID = 1L;
PrintException(final String message) {
super(message);
}
}
|
var CordSharp;
(function (CordSharp) {
var TaskResult = (function () {
function TaskResult() {
this.isCompleted = false;
}
TaskResult.prototype.setTaskId = function (taskId) {
this.taskId = taskId;
};
TaskResult.prototype.setResult = function (result) {
this.result = result;
this.isCompleted = true;
};
return TaskResult;
})();
CordSharp.TaskResult = TaskResult;
})(CordSharp || (CordSharp = {}));
//# sourceMappingURL=TaskResult.js.map
|
package fr.cubiccl.generator.gameobject.templatetags.custom;
import java.util.ArrayList;
import fr.cubiccl.generator.CommandGenerator;
import fr.cubiccl.generator.gameobject.baseobjects.BaseObject;
import fr.cubiccl.generator.gameobject.tags.Tag;
import fr.cubiccl.generator.gameobject.tags.TagCompound;
import fr.cubiccl.generator.gameobject.tags.TagString;
import fr.cubiccl.generator.gameobject.target.Target;
import fr.cubiccl.generator.gameobject.templatetags.Tags;
import fr.cubiccl.generator.gameobject.templatetags.TemplateCompound;
import fr.cubiccl.generator.gui.component.panel.CGPanel;
import fr.cubiccl.generator.gui.component.panel.tag.PanelCommandStats;
import fr.cubiccl.generator.utils.CommandGenerationException;
public class TemplateCommandStats extends TemplateCompound
{
@Override
protected CGPanel createPanel(BaseObject<?> object, Tag previousValue)
{
TagCompound previous = (TagCompound) previousValue;
PanelCommandStats p = new PanelCommandStats();
if (previous != null)
{
p.setObjective(PanelCommandStats.SUCCESS_COUNT, (String) previous.getTagFromId(Tags.STATS_SUCCESS_OBJECTIVE.id()).value());
p.setObjective(PanelCommandStats.AFFECTED_BLOCKS, (String) previous.getTagFromId(Tags.STATS_BLOCKS_OBJECTIVE.id()).value());
p.setObjective(PanelCommandStats.AFFECTED_ENTITIES, (String) previous.getTagFromId(Tags.STATS_ENTITIES_OBJECTIVE.id()).value());
p.setObjective(PanelCommandStats.AFFECTED_ITEMS, (String) previous.getTagFromId(Tags.STATS_ITEMS_OBJECTIVE.id()).value());
p.setObjective(PanelCommandStats.QUERY_RESULT, (String) previous.getTagFromId(Tags.STATS_QUERY_OBJECTIVE.id()).value());
if (previous.hasTag(Tags.STATS_SUCCESS_NAME.id())) p.setTarget(PanelCommandStats.SUCCESS_COUNT,
new Target().fromString((String) previous.getTagFromId(Tags.STATS_SUCCESS_NAME.id()).value()));
if (previous.hasTag(Tags.STATS_BLOCKS_NAME.id())) p.setTarget(PanelCommandStats.AFFECTED_BLOCKS,
new Target().fromString((String) previous.getTagFromId(Tags.STATS_BLOCKS_NAME.id()).value()));
if (previous.hasTag(Tags.STATS_ENTITIES_NAME.id())) p.setTarget(PanelCommandStats.AFFECTED_ENTITIES,
new Target().fromString((String) previous.getTagFromId(Tags.STATS_ENTITIES_NAME.id()).value()));
if (previous.hasTag(Tags.STATS_ITEMS_NAME.id())) p.setTarget(PanelCommandStats.AFFECTED_ITEMS,
new Target().fromString((String) previous.getTagFromId(Tags.STATS_ITEMS_NAME.id()).value()));
if (previous.hasTag(Tags.STATS_QUERY_NAME.id())) p.setTarget(PanelCommandStats.QUERY_RESULT,
new Target().fromString((String) previous.getTagFromId(Tags.STATS_QUERY_NAME.id()).value()));
}
p.setName(this.title());
return p;
}
@Override
public Tag generateTag(BaseObject<?> object, CGPanel panel)
{
PanelCommandStats p = (PanelCommandStats) panel;
ArrayList<TagString> tags = new ArrayList<TagString>();
tags.add(Tags.STATS_SUCCESS_OBJECTIVE.create(p.getObjective(PanelCommandStats.SUCCESS_COUNT)));
tags.add(Tags.STATS_BLOCKS_OBJECTIVE.create(p.getObjective(PanelCommandStats.AFFECTED_BLOCKS)));
tags.add(Tags.STATS_ENTITIES_OBJECTIVE.create(p.getObjective(PanelCommandStats.AFFECTED_ENTITIES)));
tags.add(Tags.STATS_ITEMS_OBJECTIVE.create(p.getObjective(PanelCommandStats.AFFECTED_ITEMS)));
tags.add(Tags.STATS_QUERY_OBJECTIVE.create(p.getObjective(PanelCommandStats.QUERY_RESULT)));
Target t = p.getTarget(PanelCommandStats.SUCCESS_COUNT);
if (t != null) tags.add(Tags.STATS_SUCCESS_NAME.create(t.toCommand()));
t = p.getTarget(PanelCommandStats.AFFECTED_BLOCKS);
if (t != null) tags.add(Tags.STATS_BLOCKS_NAME.create(t.toCommand()));
t = p.getTarget(PanelCommandStats.AFFECTED_ENTITIES);
if (t != null) tags.add(Tags.STATS_ENTITIES_NAME.create(t.toCommand()));
t = p.getTarget(PanelCommandStats.AFFECTED_ITEMS);
if (t != null) tags.add(Tags.STATS_ITEMS_NAME.create(t.toCommand()));
t = p.getTarget(PanelCommandStats.QUERY_RESULT);
if (t != null) tags.add(Tags.STATS_QUERY_NAME.create(t.toCommand()));
return this.create(tags.toArray(new TagString[tags.size()]));
}
@Override
protected boolean isInputValid(BaseObject<?> object, CGPanel panel)
{
try
{
((PanelCommandStats) panel).saveCurrent();
} catch (CommandGenerationException e)
{
CommandGenerator.report(e);
return false;
}
return true;
}
}
|
using System;
using System.Linq;
using System.IO;
using System.Security.Cryptography;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
namespace PowerLib.SqlServer.Security.Cryptography
{
public static class SqlCryptographyFunctions
{
#region Random generation functions
[SqlFunction(Name = "cryptRandom", IsDeterministic = true)]
public static SqlBytes Random(SqlInt32 count)
{
if (count.IsNull)
return SqlBytes.Null;
RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();
Byte[] data = new Byte[count.Value];
random.GetBytes(data);
return new SqlBytes(data);
}
[SqlFunction(Name = "cryptNonZeroRandom", IsDeterministic = true)]
public static SqlBytes NonZeroRandom(SqlInt32 count)
{
if (count.IsNull)
return SqlBytes.Null;
RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();
Byte[] data = new Byte[count.Value];
random.GetNonZeroBytes(data);
return new SqlBytes(data);
}
#endregion
#region Hash calculation functions
[SqlFunction(Name = "cryptComputeHash", IsDeterministic = true)]
public static SqlBytes ComputeHash(SqlBytes input, [SqlFacet(MaxSize = 128)] SqlString algorithmName)
{
if (input.IsNull || algorithmName.IsNull)
return SqlBytes.Null;
HashAlgorithm hashAlgorithm = HashAlgorithm.Create(algorithmName.Value);
if (hashAlgorithm == null)
return SqlBytes.Null;
return new SqlBytes(hashAlgorithm.ComputeHash(input.Stream));
}
[SqlFunction(Name = "cryptVerifyHash", IsDeterministic = true)]
public static SqlBoolean VerifyHash(SqlBytes input, SqlBytes hash, [SqlFacet(MaxSize = 128)] SqlString algorithmName)
{
if (input.IsNull || hash.IsNull || algorithmName.IsNull)
return SqlBoolean.Null;
HashAlgorithm hashAlgorithm = HashAlgorithm.Create(algorithmName.Value);
if (hashAlgorithm == null)
return SqlBoolean.Null;
return new SqlBoolean(hashAlgorithm.ComputeHash(input.Stream).SequenceEqual(hash.Value));
}
[SqlFunction(Name = "cryptComputeKeyedHash", IsDeterministic = true)]
public static SqlBytes ComputeKeyedHash(SqlBytes input, SqlBytes key, [SqlFacet(MaxSize = 128)] SqlString algorithmName)
{
if (input.IsNull || key.IsNull || algorithmName.IsNull)
return SqlBytes.Null;
KeyedHashAlgorithm hashAlgorithm = KeyedHashAlgorithm.Create(algorithmName.Value);
if (hashAlgorithm == null)
return SqlBytes.Null;
hashAlgorithm.Key = key.Value;
return new SqlBytes(hashAlgorithm.ComputeHash(input.Stream));
}
[SqlFunction(Name = "cryptVerifyKeyedHash", IsDeterministic = true)]
public static SqlBoolean VerifyKeyedHash(SqlBytes input, SqlBytes key, SqlBytes hash, [SqlFacet(MaxSize = 128)] SqlString algorithmName)
{
if (input.IsNull || key.IsNull || hash.IsNull || algorithmName.IsNull)
return SqlBoolean.Null;
KeyedHashAlgorithm hashAlgorithm = KeyedHashAlgorithm.Create(algorithmName.Value);
if (hashAlgorithm == null)
return SqlBoolean.Null;
hashAlgorithm.Key = key.Value;
return new SqlBoolean(hashAlgorithm.ComputeHash(input.Stream).SequenceEqual(hash.Value));
}
#endregion
#region Symmetric cryptography functions
[SqlFunction(Name = "cryptEncryptSymmetric", IsDeterministic = true)]
public static SqlBytes EncryptSymmetric(SqlBytes input, SqlBytes key, SqlBytes iv, [SqlFacet(MaxSize = 128)] SqlString algorithmName, SqlInt32 mode, SqlInt32 padding)
{
if (input.IsNull || key.IsNull || iv.IsNull || algorithmName.IsNull)
return SqlBytes.Null;
SymmetricAlgorithm symmAlgorithm = SymmetricAlgorithm.Create(algorithmName.Value);
if (symmAlgorithm == null)
return SqlBytes.Null;
if (!mode.IsNull)
symmAlgorithm.Mode = (CipherMode)mode.Value;
if (!padding.IsNull)
symmAlgorithm.Padding = (PaddingMode)padding.Value;
using (ICryptoTransform encryptor = symmAlgorithm.CreateEncryptor(key.Value, iv.Value))
using (MemoryStream ms = new MemoryStream())
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
input.Stream.CopyTo(cs);
return new SqlBytes(ms);
}
}
[SqlFunction(Name = "cryptDecryptSymmetric", IsDeterministic = true)]
public static SqlBytes DecryptSymmetric(SqlBytes input, SqlBytes key, SqlBytes iv, [SqlFacet(MaxSize = 128)] SqlString algorithmName, SqlInt32 mode, SqlInt32 padding)
{
if (input.IsNull || key.IsNull || iv.IsNull || algorithmName.IsNull)
return SqlBytes.Null;
SymmetricAlgorithm symmAlgorithm = SymmetricAlgorithm.Create(algorithmName.Value);
if (symmAlgorithm == null)
return SqlBytes.Null;
if (!mode.IsNull)
symmAlgorithm.Mode = (CipherMode)mode.Value;
if (!padding.IsNull)
symmAlgorithm.Padding = (PaddingMode)padding.Value;
using (ICryptoTransform decryptor = symmAlgorithm.CreateDecryptor(key.Value, iv.Value))
using (MemoryStream ms = new MemoryStream())
using (CryptoStream cs = new CryptoStream(input.Stream, decryptor, CryptoStreamMode.Read))
{
cs.CopyTo(ms);
return new SqlBytes(ms);
}
}
#endregion
}
}
|
import base64, json, ntpath
try:
#For Python 3.0 and later
from urllib import request as urllib2
from urllib import parse as urllib
basestring = str
except ImportError:
#For Python 2's urllib2
import urllib2, urllib
from MultiPartForm import MultiPartForm
class ZiggeoConnect:
def __init__(self, application, baseuri):
self.__application = application
self.__baseuri = baseuri
def request(self, method, path, data = None, file = None, timeout = None):
if timeout is None:
timeout = self.__application.config.request_timeout
for trying in range(0, self.__application.config.resilience_factor) :
request_result = self.singleRequest(method, path, data, file, timeout)
if (request_result.code < 500 and request_result.code >= 200):
if request_result.code >= 300:
return "{\"code\": \""+str(request_result.code)+"\", \"msg\": \""+request_result.msg+"\"}"
try:
accept_ranges = request_result.getheader('Accept-Ranges')
if (accept_ranges == 'bytes'):
return request_result.read()
else:
return request_result.read().decode('ascii')
except AttributeError as e:
return request_result.read()
break
return "{\"code\": \""+str(request_result.code)+"\", \"msg\": \""+request_result.msg+"\"}"
def singleRequest(self, method, path, data, file, timeout):
path = path.encode("ascii", "ignore")
if (method == "GET" and data != None):
path = path.decode('ascii', 'ignore') + "?" + urllib.urlencode(data)
if (method != "GET" and method != "POST"):
path = path.decode('ascii', 'ignore') + "?_method=" + method
if not isinstance(path, basestring):
path = path.decode("ascii", "ignore")
if (path.split(":")[0] == 'https'): #S3 based upload
request = urllib2.Request(path)
else:
request = urllib2.Request(self.__baseuri + path)
base64string = base64.encodestring(('%s:%s' % (self.__application.token, self.__application.private_key)).encode()).decode().replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)
if (method == "GET"):
try:
result = urllib2.urlopen(request, None, timeout)
return result
except urllib2.HTTPError as e:
return e
else:
if (data == None):
data = {}
if (file == None):
data = urllib.urlencode(data)
binary_data = data.encode("ascii")
try:
result = urllib2.urlopen(request, binary_data, timeout)
return result
except urllib2.HTTPError as e:
return e
else:
form_file = [('file', ntpath.basename(file), open(file, "rb"))]
content_type, body = MultiPartForm().encode(data, form_file)
request.add_header('Content-type', content_type)
request.add_header('Content-length', len(body))
try:
result = urllib2.urlopen(request, body, timeout)
return result
except urllib2.HTTPError as e:
return e
def requestJSON(self, method, path, data = None, file = None):
return json.loads(self.request(method, path, data, file))
def get(self, path, data = None, file = None):
return self.request("GET", path, data, file)
def getJSON(self, path, data = None, file = None):
return self.requestJSON("GET", path, data, file)
def post(self, path, data = None, file = None):
return self.request("POST", path, data, file)
def postJSON(self, path, data = None, file = None):
return self.requestJSON("POST", path, data, file)
def postUploadJSON(self, path, scope, data = None, file = None, type_key = None):
if (data == None):
data={}
data[type_key] = file.split(".")[-1]
result = self.requestJSON("POST", path, data, None)
self.request("POST", result['url_data']['url'], result['url_data']['fields'], file)
return result[scope]
def delete(self, path, data = None, file = None):
return self.request("DELETE", path, data, file)
def deleteJSON(self, path, data = None, file = None):
return self.requestJSON("DELETE", path, data, file)
|
import { isPlural } from './matchers'
const createArray = rootValue => Array.from(Array(3)).map(() => rootValue)
const createRootValue = entityName => {
const rootValue = { __typeName: entityName }
if (isPlural(entityName)) return createArray(rootValue)
return rootValue
}
export default createRootValue
|
// online/online-faster-decoder.h
// Copyright 2012 Cisco Systems (author: Matthias Paulik)
// Modifications to the original contribution by Cisco Systems made by:
// Vassil Panayotov
// See ../../COPYING for clarification regarding multiple authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#ifndef KALDI_ONLINE_ONLINE_FASTER_DECODER_H_
#define KALDI_ONLINE_ONLINE_FASTER_DECODER_H_
#include "util/stl-utils.h"
#include "decoder/faster-decoder.h"
#include "hmm/transition-model.h"
namespace kaldi {
// Extends the definition of FasterDecoder's options to include additional
// parameters. The meaning of the "beam" option is also redefined as
// the _maximum_ beam value allowed.
struct OnlineFasterDecoderOpts : public FasterDecoderOptions {
BaseFloat rt_min; // minimum decoding runtime factor
BaseFloat rt_max; // maximum decoding runtime factor
int32 batch_size; // number of features decoded in one go
int32 inter_utt_sil; // minimum silence (#frames) to trigger end of utterance
int32 max_utt_len_; // if utt. is longer, we accept shorter silence as utt. separators
int32 update_interval; // beam update period in # of frames
BaseFloat beam_update; // rate of adjustment of the beam
BaseFloat max_beam_update; // maximum rate of beam adjustment
OnlineFasterDecoderOpts() :
rt_min(.7), rt_max(.75), batch_size(27),
inter_utt_sil(50), max_utt_len_(1500),
update_interval(3), beam_update(.01),
max_beam_update(0.05) {}
void Register(OptionsItf *po, bool full) {
FasterDecoderOptions::Register(po, full);
po->Register("rt-min", &rt_min,
"Approximate minimum decoding run time factor");
po->Register("rt-max", &rt_max,
"Approximate maximum decoding run time factor");
po->Register("update-interval", &update_interval,
"Beam update interval in frames");
po->Register("beam-update", &beam_update, "Beam update rate");
po->Register("max-beam-update", &max_beam_update, "Max beam update rate");
po->Register("inter-utt-sil", &inter_utt_sil,
"Maximum # of silence frames to trigger new utterance");
po->Register("max-utt-length", &max_utt_len_,
"If the utterance becomes longer than this number of frames, "
"shorter silence is acceptable as an utterance separator");
}
};
class OnlineFasterDecoder : public FasterDecoder {
public:
// Codes returned by Decode() to show the current state of the decoder
enum DecodeState {
kEndFeats = 1, // No more scores are available from the Decodable
kEndUtt = 2, // End of utterance, caused by e.g. a sufficiently long silence
kEndBatch = 4 // End of batch - end of utterance not reached yet
};
// "sil_phones" - the IDs of all silence phones
OnlineFasterDecoder(const fst::Fst<fst::StdArc> &fst,
const OnlineFasterDecoderOpts &opts,
const std::vector<int32> &sil_phones,
const TransitionModel &trans_model)
: FasterDecoder(fst, opts), opts_(opts),
silence_set_(sil_phones), trans_model_(trans_model),
max_beam_(opts.beam), effective_beam_(FasterDecoder::config_.beam),
state_(kEndFeats), frame_(0), utt_frames_(0) {}
DecodeState Decode(DecodableInterface *decodable);
// Makes a linear graph, by tracing back from the last "immortal" token
// to the previous one
bool PartialTraceback(fst::MutableFst<LatticeArc> *out_fst);
// Makes a linear graph, by tracing back from the best currently active token
// to the last immortal token. This method is meant to be invoked at the end
// of an utterance in order to get the last chunk of the hypothesis
void FinishTraceBack(fst::MutableFst<LatticeArc> *fst_out);
// Returns "true" if the best current hypothesis ends with long enough silence
bool EndOfUtterance();
int32 frame() { return frame_; }
private:
void ResetDecoder(bool full);
// Returns a linear fst by tracing back the last N frames, beginning
// from the best current token
void TracebackNFrames(int32 nframes, fst::MutableFst<LatticeArc> *out_fst);
// Makes a linear "lattice", by tracing back a path delimited by two tokens
void MakeLattice(const Token *start,
const Token *end,
fst::MutableFst<LatticeArc> *out_fst) const;
// Searches for the last token, ancestor of all currently active tokens
void UpdateImmortalToken();
const OnlineFasterDecoderOpts opts_;
const ConstIntegerSet<int32> silence_set_; // silence phones IDs
const TransitionModel &trans_model_; // needed for trans-id -> phone conversion
const BaseFloat max_beam_; // the maximum allowed beam
BaseFloat &effective_beam_; // the currently used beam
DecodeState state_; // the current state of the decoder
int32 frame_; // the next frame to be processed
int32 utt_frames_; // # frames processed from the current utterance
Token *immortal_tok_; // "immortal" token means it's an ancestor of ...
Token *prev_immortal_tok_; // ... all currently active tokens
KALDI_DISALLOW_COPY_AND_ASSIGN(OnlineFasterDecoder);
};
} // namespace kaldi
#endif // KALDI_ONLINE_ONLINE_FASTER_DECODER_H_
|
/*************************************************/
/* DO NOT MODIFY THIS HEADER */
/* */
/* MASTODON */
/* */
/* (c) 2015 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/*************************************************/
#include "TestLayeredMaterialInterface.h"
registerMooseObject("MastodonTestApp", TestLayeredMaterialInterfaceDocString);
registerMooseObject("MastodonTestApp", TestLayeredMaterialInterfaceTypeError);
InputParameters
TestLayeredMaterialInterfaceDocString::validParams()
{
InputParameters params = Material::validParams();
params += LayeredMaterialInterface<>::validParams();
return params;
}
InputParameters
TestLayeredMaterialInterfaceKernel::validParams()
{
return Kernel::validParams();
}
InputParameters
TestLayeredMaterialInterfaceTypeError::validParams()
{
InputParameters params = TestLayeredMaterialInterfaceKernel::validParams();
params += LayeredMaterialInterface<>::validParams();
return params;
}
|
'use strict';
//Employeetypes service used to communicate Employeetypes REST endpoints
angular.module('employees').factory('Employeetypes', ['$resource',
function($resource) {
return $resource('employeetypes/:employeetypeId', { employeetypeId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}
]);
|
#pragma once
extern void* x11_glc;
extern void input_x11_init();
extern void input_x11_handle();
extern void event_x11_handle();
extern void x11_window_create();
extern void x11_window_set_text(const char* text);
extern void x11_window_destroy();
// numbers
const int KEY_1 = 10;
const int KEY_2 = 11;
const int KEY_3 = 12;
const int KEY_4 = 13;
const int KEY_5 = 14;
const int KEY_6 = 15;
const int KEY_7 = 16;
const int KEY_8 = 17;
const int KEY_9 = 18;
const int KEY_0 = 19;
// characters
const int KEY_A = 38;
const int KEY_B = 56;
const int KEY_C = 54;
const int KEY_D = 40;
const int KEY_E = 26;
const int KEY_F = 41;
const int KEY_G = 42;
const int KEY_H = 43;
const int KEY_I = 31;
const int KEY_J = 44;
const int KEY_K = 45;
const int KEY_L = 46;
const int KEY_M = 58;
const int KEY_N = 57;
const int KEY_O = 32;
const int KEY_P = 33;
const int KEY_Q = 24;
const int KEY_R = 27;
const int KEY_S = 39;
const int KEY_T = 28;
const int KEY_U = 30;
const int KEY_V = 55;
const int KEY_W = 25;
const int KEY_X = 53;
const int KEY_Y = 52;
const int KEY_Z = 29;
// special
const int KEY_ESC = 9;
const int KEY_TAB = 23;
const int KEY_RETURN = 36;
const int KEY_HOME = 110;
const int KEY_UP = 111;
const int KEY_PGUP = 112;
const int KEY_LEFT = 113;
const int KEY_RIGHT = 114;
const int KEY_END = 115;
const int KEY_DOWN = 116;
const int KEY_PGDOWN = 117;
const int KEY_INS = 118;
const int KEY_DEL = 118;
const int KEY_F1 = 67;
const int KEY_F2 = 68;
const int KEY_F3 = 69;
const int KEY_F4 = 70;
const int KEY_F5 = 71;
const int KEY_F6 = 72;
const int KEY_F7 = 73;
const int KEY_F8 = 74;
const int KEY_F9 = 75;
const int KEY_F10 = 76;
const int KEY_F11 = 95;
const int KEY_F12 = 96;
|
from __future__ import absolute_import
import functools
from sentry.utils.strings import (
is_valid_dot_atom, iter_callsign_choices, soft_break, soft_hyphenate, tokens_from_name
)
ZWSP = u'\u200b' # zero width space
SHY = u'\u00ad' # soft hyphen
def test_soft_break():
assert soft_break(
'com.example.package.method(argument).anotherMethod(argument)', 15
) == ZWSP.join(
['com.', 'example.', 'package.', 'method(', 'argument).', 'anotherMethod(', 'argument)']
)
def test_soft_break_and_hyphenate():
hyphenate = functools.partial(soft_hyphenate, length=6)
assert soft_break('com.reallyreallyreally.long.path', 6, hyphenate) == \
ZWSP.join(['com.', SHY.join(['really'] * 3) + '.', 'long.', 'path'])
def test_tokens_from_name():
assert list(tokens_from_name('MyHTTPProject42')) == ['my', 'http', 'project42']
assert list(tokens_from_name('MyHTTPProject42', remove_digits=True)) == [
'my', 'http', 'project'
]
assert list(tokens_from_name('MyHTTPProject Awesome 42 Stuff')) == [
'my', 'http', 'project', 'awesome', '42', 'stuff'
]
assert list(tokens_from_name('MyHTTPProject Awesome 42 Stuff', remove_digits=True)) == [
'my', 'http', 'project', 'awesome', 'stuff'
]
def test_iter_callsign_choices():
choices = iter_callsign_choices('FooBar')
assert next(choices) == 'FB'
assert next(choices) == 'FB2'
assert next(choices) == 'FB3'
assert next(choices) == 'FB4'
choices = iter_callsign_choices('FooBarBaz')
assert next(choices) == 'FBB'
assert next(choices) == 'FBB2'
assert next(choices) == 'FBB3'
assert next(choices) == 'FBB4'
choices = iter_callsign_choices('Grml')
assert next(choices) == 'GR'
assert next(choices) == 'GRM'
assert next(choices) == 'GR2'
assert next(choices) == 'GRM2'
choices = iter_callsign_choices('42')
assert next(choices) == 'PR'
assert next(choices) == 'PR2'
assert next(choices) == 'PR3'
choices = iter_callsign_choices('GetHub')
assert next(choices) == 'GH2'
assert next(choices) == 'GH3'
def test_is_valid_dot_atom():
assert is_valid_dot_atom('foo')
assert is_valid_dot_atom('foo.bar')
assert not is_valid_dot_atom('.foo.bar')
assert not is_valid_dot_atom('foo.bar.')
assert not is_valid_dot_atom('foo.\x00')
|
package ru.stqa.pft.addressbook.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import ru.stqa.pft.addressbook.model.GroupData;
import ru.stqa.pft.addressbook.model.Groups;
import java.util.List;
/**
* Created by ruslana on 18.09.16.
*/
public class GroupHelper extends HelperBase{
public GroupHelper(WebDriver wd) {
super(wd);
}
public void returnToGroupPage() {
click(By.linkText("group page"));
}
public void submitGroupCreation() {
click(By.name("submit"));
}
public void fillGroupForm(GroupData groupData) {
type(By.name("group_name"), groupData.getName());
type(By.name("group_header"), groupData.getHeader());
type(By.name("group_footer"), groupData.getFooter());
}
public void initGroupCreation() {
click(By.name("new"));
}
public void deleteSelectedGroups() {
click(By.name("delete"));
}
public void selectGroupById(int id) {
wd.findElement(By.cssSelector("input[value='" + id + "']")).click();
}
public void initGroupModification() {
click(By.name("edit"));
}
public void submitGroupModification() {
click(By.name("update"));
}
public void create(GroupData group) {
initGroupCreation();
fillGroupForm(group);
submitGroupCreation();
groupCache = null;
returnToGroupPage();
}
public void modify(GroupData group) {
selectGroupById(group.getId());
initGroupModification();
fillGroupForm(group);
submitGroupModification();
groupCache = null;
returnToGroupPage();
}
public void delete(GroupData group) {
selectGroupById(group.getId());
deleteSelectedGroups();
groupCache = null;
returnToGroupPage();
}
public boolean isThereAGroup() {
return isElementPresent(By.name("selected[]"));
}
public int count() {
return wd.findElements(By.name("selected[]")).size();
}
private Groups groupCache = null;
public Groups all() {
if (groupCache != null) {
return new Groups(groupCache);
}
groupCache = new Groups();
List<WebElement> elements = wd.findElements(By.cssSelector("span.group"));
for (WebElement element : elements) {
String name = element.getText();
int id = Integer.parseInt(element.findElement(By.tagName("input")).getAttribute("value"));
groupCache.add(new GroupData().withId(id).withName(name));
}
return new Groups(groupCache);
}
}
|
package character;
public class Ability {
private String name;
private String description;
private CharacterStats.Stats stat;
private CharacterStats.Stats additionalStat;
public Ability(String name, String description, CharacterStats.Stats stat){
this.name = name;
this.description = description;
this.stat = stat;
}
public Ability(String name, String description, CharacterStats.Stats stat, CharacterStats.Stats additionalStat){
this.name = name;
this.description = description;
this.stat = stat;
this.additionalStat = additionalStat;
}
public String getName(){
return this.name;
}
public String getDescription(){
return this.description;
}
public CharacterStats.Stats getStat(){
return this.stat;
}
public CharacterStats.Stats getAdditionalStat() throws NullPointerException{
if(this.additionalStat != null){
return this.additionalStat;
} else {
throw new NullPointerException();
}
}
public String toString(){
String s = String.format("%s: %s.\nStat:%s\n", this.name, this.description, this.stat.toString());
if(this.additionalStat != null){
s += String.format("Additional Stat:%s\n", this.additionalStat.toString());
}
return s;
}
}
|
# -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from airflow.exceptions import AirflowException
from airflow.contrib.hooks.aws_hook import AwsHook
class EmrHook(AwsHook):
"""
Interact with AWS EMR. emr_conn_id is only necessary for using the
create_job_flow method.
"""
def __init__(self, emr_conn_id=None, region_name=None, *args, **kwargs):
self.emr_conn_id = emr_conn_id
self.region_name = region_name
super(EmrHook, self).__init__(*args, **kwargs)
def get_conn(self):
self.conn = self.get_client_type('emr', self.region_name)
return self.conn
def create_job_flow(self, job_flow_overrides):
"""
Creates a job flow using the config from the EMR connection.
Keys of the json extra hash may have the arguments of the boto3
run_job_flow method.
Overrides for this config may be passed as the job_flow_overrides.
"""
if not self.emr_conn_id:
raise AirflowException('emr_conn_id must be present to use create_job_flow')
emr_conn = self.get_connection(self.emr_conn_id)
config = emr_conn.extra_dejson.copy()
config.update(job_flow_overrides)
response = self.get_conn().run_job_flow(**config)
return response
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_65) on Sun Dec 01 16:00:09 EST 2013 -->
<TITLE>
Uses of Class csc301.ultrasound.model.tests.UserTest
</TITLE>
<META NAME="date" CONTENT="2013-12-01">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class csc301.ultrasound.model.tests.UserTest";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../csc301/ultrasound/model/tests/UserTest.html" title="class in csc301.ultrasound.model.tests"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?csc301/ultrasound/model/tests//class-useUserTest.html" target="_top"><B>FRAMES</B></A>
<A HREF="UserTest.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>csc301.ultrasound.model.tests.UserTest</B></H2>
</CENTER>
No usage of csc301.ultrasound.model.tests.UserTest
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../csc301/ultrasound/model/tests/UserTest.html" title="class in csc301.ultrasound.model.tests"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?csc301/ultrasound/model/tests//class-useUserTest.html" target="_top"><B>FRAMES</B></A>
<A HREF="UserTest.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_65) on Wed Nov 12 13:03:00 UTC 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>com.hazelcast.core.server (Hazelcast Root 3.3.3 API)</title>
<meta name="date" content="2014-11-12">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="com.hazelcast.core.server (Hazelcast Root 3.3.3 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../com/hazelcast/core/package-summary.html">Prev Package</a></li>
<li><a href="../../../../com/hazelcast/executor/impl/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/hazelcast/core/server/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Package" class="title">Package com.hazelcast.core.server</h1>
<div class="docSummary">
<div class="block">This package contains classes to launch standalone Hazelcast Instance<br/></div>
</div>
<p>See: <a href="#package_description">Description</a></p>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../com/hazelcast/core/server/StartServer.html" title="class in com.hazelcast.core.server">StartServer</a></td>
<td class="colLast">
<div class="block">Starts a Hazelcast server</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
<a name="package_description">
<!-- -->
</a>
<h2 title="Package com.hazelcast.core.server Description">Package com.hazelcast.core.server Description</h2>
<div class="block"><p>This package contains classes to launch standalone Hazelcast Instance<br/></div>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../com/hazelcast/core/package-summary.html">Prev Package</a></li>
<li><a href="../../../../com/hazelcast/executor/impl/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/hazelcast/core/server/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2014 <a href="http://www.hazelcast.com/">Hazelcast, Inc.</a>. All Rights Reserved.</small></p>
</body>
</html>
|
/*
* Copyright (C) 2018 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <concepts>
#include "imr/alloc.hh"
#include "imr/compound.hh"
#include "imr/fundamental.hh"
namespace imr {
/// Check if a type T is a sizer for Structure.
template<typename Structure, typename T>
struct is_sizer_for : std::false_type { };
template<typename Continuation, typename... Members>
struct is_sizer_for<structure<Members...>,
internal::structure_sizer<Continuation, Members...>>
: std::true_type { };
template<typename Structure, typename T>
constexpr bool is_sizer_for_v = is_sizer_for<Structure, T>::value;
/// Check if a type T is a serializer for Structure.
template<typename Structure, typename T>
struct is_serializer_for : std::false_type { };
template<typename Continuation, typename... Members>
struct is_serializer_for<structure<Members...>,
internal::structure_serializer<Continuation, Members...>>
: std::true_type { };
template<typename Structure, typename T>
constexpr bool is_serializer_for_v = is_serializer_for<Structure, T>::value;
/// The default sizer for Structure.
template<typename Structure>
using default_sizer_t = decltype(Structure::get_sizer());
/// The default serializer for Structure.
template<typename Structure>
using default_serializer_t = decltype(Structure::get_serializer(nullptr));
/// A simple writer that accepts only sizer or serializer as an argument.
template<typename Writer, typename Structure>
concept WriterSimple = requires(Writer writer, default_sizer_t<Structure> sizer,
default_serializer_t<Structure> serializer)
{
writer(sizer);
writer(serializer);
};
/// A writer that accepts both sizer or serializer and a memory allocator.
template<typename Writer, typename Structure>
concept WriterAllocator = requires(Writer writer, default_sizer_t<Structure> sizer,
default_serializer_t<Structure> serializer,
imr::alloc::object_allocator::sizer alloc_sizer,
imr::alloc::object_allocator::serializer alloc_serializer)
{
writer(sizer, alloc_sizer);
writer(serializer, alloc_serializer);
};
}
|
/*
* Function for Mega Main Menu.
*/
;jQuery(document).ready(function(){
/*
* Unbinded all previous JS actions with menu.
*/
;jQuery( '#mega_main_menu, #mega_main_menu *' ).unbind();
/*
* INIT
*/
mm_sticky_menu();
mmm_fullwidth_menu();
/*
* EVENTS
*/
;jQuery(window).resize( function(){
mmm_fullwidth_menu();
mm_sticky_menu();
});
/*
* Reversal z-index.
*/
var z_index = 5000;
;jQuery( '.mega_main_menu' ).each(function(index,element){
z_index = z_index - 10;
jQuery( element ).css({
'z-index' : z_index
});
});
/*
* Mobile toggle menu
*/
;jQuery( '.mobile_toggle' ).click(function() {
jQuery( this ).parent().toggleClass( 'mobile_menu_active' );
jQuery( '#mega_main_menu .keep_open' ).removeClass('keep_open');
});
/*
* Mobile Double tap to go
*/
;if( /iphone|ipad|ipod|android|webos|blackberry|iemobile|opera mini/i.test( navigator.userAgent.toLowerCase() ) )
{
var clicked_item = false;
;jQuery('#mega_main_menu li:has(.mega_dropdown) > .item_link').on( 'click', function( index )
{
if ( clicked_item != this) {
index.preventDefault();
if ( jQuery( this ).parent().parent().parent().hasClass('keep_open') ) {
} else {
jQuery( '#mega_main_menu .keep_open' ).removeClass('keep_open');
}
jQuery( this ).parent().addClass('keep_open');
clicked_item = this;
}
});
}
/*
* Sticky menu
*/
function mm_sticky_menu () {
;jQuery( '#mega_main_menu > .menu_holder' ).each(function(index,element){
var stickyoffset = [];
var menu_inner_width = [];
var menu_inner = [];
var style_attr = [];
menu_inner[ index ] = jQuery( element ).find( '.menu_inner' );
stickyoffset[ index ] = jQuery( element ).data( 'stickyoffset' ) * 1;
if ( jQuery( element ).attr( 'data-sticky' ) == '1' && stickyoffset[ index ] == 0 ) {
menu_inner_width[ index ] = menu_inner[ index ].parents( '.mega_main_menu' ).width();
menu_inner[ index ].attr( 'style' , 'width:' + menu_inner_width[ index ] + 'px;' );
jQuery( element ).addClass( 'sticky_container' );
} else {
;jQuery(window).on('scroll', function(){
if ( jQuery( element ).attr( 'data-sticky' ) == '1' ) {
scrollpath = jQuery(window).scrollTop();
if ( scrollpath > stickyoffset[ index ] ) {
menu_inner_width[ index ] = menu_inner[ index ].parents( '.mega_main_menu' ).width();
jQuery( element ).find( '.mmm_fullwidth_container' ).css({ 'left' : '0px' });
jQuery( element ).find( '.menu_inner' ).attr( 'style' , 'width:' + menu_inner_width[ index ] + 'px;' );
if ( !jQuery( element ).hasClass( 'sticky_container' ) ) {
jQuery( element ).addClass( 'sticky_container' );
}
} else {
mmm_fullwidth_menu();
jQuery( element ).removeClass( 'sticky_container' );
style_attr[ index ] = jQuery( menu_inner[ index ] ).attr( 'style' );
if ( typeof style_attr[ index ] !== 'undefined' && style_attr[ index ] !== false ) {
menu_inner[ index ].removeAttr( 'style' );
}
}
} else {
jQuery( element ).removeClass( 'sticky_container' );
}
});
}
});
}
/*
* Fullwidth menu container
*/
function mmm_fullwidth_menu () {
body_width = jQuery( 'body' ).width();
jQuery( '.mega_main_menu.direction-horizontal.fullwidth-enable' ).each( function( index, element ) {
offset_left = jQuery( element ).offset().left;
if ( jQuery( element ).hasClass( 'coercive_styles-enable' ) ) {
rules_priority = ' !important';
} else {
rules_priority = '';
}
jQuery( element ).find( '.mmm_fullwidth_container' ).attr( 'style' , 'width:' + body_width + 'px' + rules_priority + ';left: -' + offset_left + 'px' + rules_priority + ';right:auto' + rules_priority + ';' );
});
}
/*
* Smooth scroll to anchor link
*/
jQuery(function() {
jQuery('#mega_main_menu a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = jQuery(this.hash);
target = target.length ? target : jQuery('[name=' + this.hash.slice(1) +'], [id=' + this.hash.slice(1) +']');
if (target.length) {
jQuery('html,body').animate({
scrollTop: target.offset().top - 90
}, 600);
return false;
}
}
});
});
/*
* Keep dropdown open if some inner element has a :focus.
*/
jQuery(function() {
jQuery('#mega_main_menu .menu-item *').focus(function(){
jQuery( this ).parents('.menu-item, .post_item').addClass('keep_open');
})
jQuery('#mega_main_menu .menu-item *').on( 'hover', function(){
jQuery( this ).parents('.menu-item, .post_item').removeClass('keep_open');
})
jQuery('#mega_main_menu .menu-item *').blur(function(){
jQuery( this ).parents('.menu-item, .post_item').removeClass('keep_open');
})
});
/*
*
*/
jQuery(function() {
jQuery('#mega_main_menu .tabs_dropdown > .mega_dropdown > li').on( 'hover', function(){
jQuery( this ).parent().css({
"min-height": jQuery( this ).find(' > .mega_dropdown').outerHeight( true )
});
});
jQuery('#mega_main_menu .tabs_dropdown > .mega_dropdown > li').on( 'mouseleave', function(){
jQuery( this ).parent().css({
"min-height": '0px'
});
});
});
});
|
'use strict';
/**
* @typedef {{line: number, col: number}} Pos
*/
/**
* @param {string} html
* @param node
* @return {Pos}
*/
function getLine(html, node) {
if (!node) {
return {line: 1, col: 1};
}
var linesUntil = html.substring(0, node.startIndex).split('\n');
return {line: linesUntil.length, col: linesUntil[linesUntil.length - 1].length + 1};
}
//function getLine(node) {
// if (!node) {
// return 0;
// }
// var line = 0;
// var prev = node.prev;
// while (prev) {
// var nl = prev.data.split('\n').length - 1;
// line += nl;
// prev = prev.prev;
// }
//
// line += getLine(node.parent);
// return line + 1;
//}
//function RTCodeError(message, line) {
// this.name = 'RTCodeError';
// this.message = message || '';
// this.line = line || -1;
//}
//RTCodeError.prototype = Error.prototype;
// Redefine properties on Error to be enumerable
/*eslint no-extend-native:0*/
Object.defineProperty(Error.prototype, 'message', {configurable: true, enumerable: true});
Object.defineProperty(Error.prototype, 'stack', {configurable: true, enumerable: true});
//Object.defineProperty(Error.prototype, 'line', { configurable: true, enumerable: true });
/**
* @param {string} message
* @param {number=} startOffset
* @param {number=} endOffset
* @param {number=} line
* @param {number=} column
* @constructor
*/
function RTCodeError(message, startOffset, endOffset, line, column) {
Error.captureStackTrace(this, RTCodeError);
this.name = 'RTCodeError';
this.message = message || '';
this.index = norm(startOffset);
this.startOffset = norm(startOffset);
this.endOffset = norm(endOffset);
this.line = norm(line);
this.column = norm(column);
}
function norm(n) {
return n === undefined ? -1 : n;
}
RTCodeError.prototype = Object.create(Error.prototype);
RTCodeError.build = buildError;
RTCodeError.norm = norm;
RTCodeError.prototype.toIssue = function () {
};
/**
* @param {string} msg
* @param {*} context
* @param {*} node
* @return {RTCodeError}
*/
function buildError(msg, context, node) {
var loc = getNodeLoc(context, node);
return new RTCodeError(msg, loc.start, loc.end, loc.pos.line, loc.pos.col);
}
/**
* @param context
* @param node
* @return {{pos:Pos, start:number, end:number}}
*/
function getNodeLoc(context, node) {
var pos = getLine(context.html, node);
var end;
if (node.data) {
end = node.startIndex + node.data.length;
} else if (node.next) {
end = node.next.startIndex;
} else {
end = context.html.length;
}
return {
pos: pos,
start: node.startIndex,
end: end
};
}
module.exports = {
RTCodeError: RTCodeError,
getNodeLoc: getNodeLoc
};
|
#pragma once
class CIIS6ConfigHelper
{
public:
static bool GetWebServerHostnameAndPort(IMSAdminBase* pAdminBase,
LPCTSTR pszMBPath,
CString& sHostname,
DWORD& dwPort);
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.