text
stringlengths 2
6.14k
|
|---|
# uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: Mcl_Cmd_Shares_DataHandler.py
def DataHandlerMain(namespace, InputFilename, OutputFilename):
import mcl.imports
import mcl.data.Input
import mcl.data.Output
import mcl.msgtype
import mcl.status
import mcl.target
import mcl.object.Message
mcl.imports.ImportNamesWithNamespace(namespace, 'mca.network.cmd.shares', globals())
input = mcl.data.Input.GetInput(InputFilename)
output = mcl.data.Output.StartOutput(OutputFilename, input)
output.Start('Shares', 'shares', [])
msg = mcl.object.Message.DemarshalMessage(input.GetData())
if input.GetStatus() != mcl.status.MCL_SUCCESS:
errorMsg = msg.FindMessage(mcl.object.Message.MSG_KEY_RESULT_ERROR)
moduleError = errorMsg.FindU32(mcl.object.Message.MSG_KEY_RESULT_ERROR_MODULE)
osError = errorMsg.FindU32(mcl.object.Message.MSG_KEY_RESULT_ERROR_OS)
output.RecordModuleError(moduleError, osError, errorStrings)
output.EndWithStatus(input.GetStatus())
return True
else:
if input.GetMessageType() == mcl.msgtype.SHARES_QUERY:
return _handleQueryData(msg, output)
if input.GetMessageType() == mcl.msgtype.SHARES_MAP:
return _handleMapData(msg, output)
if input.GetMessageType() == mcl.msgtype.SHARES_LIST:
return _handleListData(msg, output)
output.RecordError('Unhandled message type (%u)' % input.GetMessageType())
output.EndWithStatus(mcl.target.CALL_FAILED)
return False
def _handleListData(msg, output):
from mcl.object.XmlOutput import XmlOutput
xml = XmlOutput()
xml.Start('Shares')
while msg.GetNumRetrieved() < msg.GetCount():
if mcl.CheckForStop():
output.EndWithStatus(mcl.target.CALL_FAILED)
return False
data = ResultList()
data.Demarshal(msg)
sub = xml.AddSubElement('Share')
sub.AddSubElementWithText('LocalName', data.local)
sub.AddSubElementWithText('RemoteName', data.remote)
sub.AddSubElementWithText('UserName', data.username)
sub.AddSubElementWithText('DomainName', data.domainName)
sub.AddSubElementWithText('Password', data.password)
sub.AddAttribute('referenceCount', '%u' % data.referenceCount)
sub.AddAttribute('useCount', '%u' % data.useCount)
if data.status == RESULT_LIST_STATUS_OK:
sub.AddSubElementWithText('Status', 'Ok')
elif data.status == RESULT_LIST_STATUS_PAUSED:
sub.AddSubElementWithText('Status', 'Paused')
elif data.status == RESULT_LIST_STATUS_DISCONNECTED:
sub.AddSubElementWithText('Status', 'Disconnected')
elif data.status == RESULT_LIST_STATUS_NETWORK_ERROR:
sub.AddSubElementWithText('Status', 'NetworkError')
elif data.status == RESULT_LIST_STATUS_CONNECTING:
sub.AddSubElementWithText('Status', 'Connecting')
elif data.status == RESULT_LIST_STATUS_RECONNECTING:
sub.AddSubElementWithText('Status', 'Reconnecting')
else:
sub.AddSubElementWithText('Status', 'Unknown')
if data.type == RESULT_LIST_TYPE_WILDCARD:
sub.AddSubElementWithText('Type', 'Wildcard')
elif data.type == RESULT_LIST_TYPE_DISK_DEVICE:
sub.AddSubElementWithText('Type', 'Disk Device')
elif data.type == RESULT_LIST_TYPE_SPOOL_DEVICE:
sub.AddSubElementWithText('Type', 'Spool Device')
elif data.type == RESULT_LIST_TYPE_IPC:
sub.AddSubElementWithText('Type', 'Interprocess Communication')
else:
sub.AddSubElementWithText('Type', 'Unknown')
output.RecordXml(xml)
output.EndWithStatus(mcl.target.CALL_SUCCEEDED)
return True
def _handleMapData(msg, output):
if msg.GetCount() == 0:
output.EndWithStatus(mcl.target.CALL_SUCCEEDED)
return True
results = ResultMap()
results.Demarshal(msg)
from mcl.object.XmlOutput import XmlOutput
xml = XmlOutput()
xml.Start('MapResponse')
if len(results.resourceName) > 0:
xml.AddSubElementWithText('ResourceName', results.resourceName)
xml.AddSubElementWithText('ResourcePath', results.resourcePath)
output.RecordXml(xml)
output.GoToBackground()
output.End()
return True
def _handleQueryData(msg, output):
from mcl.object.XmlOutput import XmlOutput
xml = XmlOutput()
xml.Start('QueryResponse')
while msg.GetNumRetrieved() < msg.GetCount():
if mcl.CheckForStop():
output.EndWithStatus(mcl.target.CALL_FAILED)
return False
data = ResultQuery()
data.Demarshal(msg)
sub = xml.AddSubElement('Resource')
sub.AddSubElementWithText('Name', data.name)
if data.hasPath:
sub.AddSubElementWithText('Path', data.path)
type = sub.AddSubElement('Type')
if data.admin:
type.AddAttribute('admin', 'true')
else:
type.AddAttribute('admin', 'false')
if data.type == RESULT_QUERY_TYPE_DISK:
type.SetText('Disk')
elif data.type == RESULT_QUERY_TYPE_DEVICE:
type.SetText('Device')
elif data.type == RESULT_QUERY_TYPE_PRINT:
type.SetText('Print')
elif data.type == RESULT_QUERY_TYPE_IPC:
type.SetText('IPC')
else:
type.SetText('Unknown')
sub.AddSubElementWithText('Caption', data.caption)
sub.AddSubElementWithText('Description', data.description)
output.RecordXml(xml)
output.EndWithStatus(mcl.target.CALL_SUCCEEDED)
return True
if __name__ == '__main__':
import sys
try:
namespace, InputFilename, OutputFilename = sys.argv[1:]
except:
print '%s <namespace> <input filename> <output filename>' % sys.argv[0]
sys.exit(1)
if DataHandlerMain(namespace, InputFilename, OutputFilename) != True:
sys.exit(-1)
|
import yaml
import socket
import collections
def prettyaml(data, lvl=0, indent=' ', prefix=''):
if isinstance(data, basestring):
data = yaml.load(data)
if isinstance(data, dict):
if len(data) == 1:
k, v = data.items()[0]
out_str = '{}^{}:{}'.format(indent * lvl, k, v)
else:
out_str = '\n'.join(
['{}{}:{}'.format(indent * lvl, k, prettyaml(v, lvl + 1))
for k,v in data.items()])
out_str = '\n' + out_str
elif isinstance(data, list):
out_str = ''.join(['\n{}{}'.format(indent * (lvl - 1) ,
prettyaml(x, lvl, prefix='- ')) for x in data])
else:
out_str = "{0}{1}{2}".format(indent, prefix, data)
return out_str
def get_port(host, port):
# Logic borrowed from Tornado's bind_sockets
flags = socket.AI_PASSIVE
if hasattr(socket, "AI_ADDRCONFIG"):
flags |= socket.AI_ADDRCONFIG
while True:
try:
res = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
flags)
af, socktype, proto, cannonname, sockaddr = res[0]
s = socket.socket(af, socktype, proto)
s.setblocking(0)
s.bind(sockaddr)
s.listen(128)
except socket.error as e:
print("Could not assign to port %s (%s)." % (port, e))
port += 1
continue
return port
def autoviv():
return collections.defaultdict(autoviv)
def autovivify(d):
if isinstance(d, dict):
new_d = autoviv()
new_d.update(d)
d = new_d
for k in d:
d[k] = autovivify(d[k])
return d
def dict_diff(a, b):
diffs = {}
for k in a:
if k in b and isinstance(a[k], dict) \
and isinstance(b[k], dict):
dd = dict_diff(a[k], b[k])
if dd:
diffs[k] = dd
elif k not in b or a[k] != b[k]:
diffs[k] = a[k]
return diffs
def dict_symmetric_diff(a, b):
diffs = {}
for k in set(a.keys()) & set(b.keys()):
if isinstance(a[k], dict) and isinstance(b[k], dict):
dsd = dict_symmetric_diff(a[k], b[k])
if dsd:
diffs[k] = dsd
elif a[k] != b[k]:
diffs[k] = a[k]
for k in set(a.keys()) ^ set(b.keys()):
diffs[k] = a[k] if k in a else b[k]
return diffs
|
/**************************************************************************
**
** Copyright (C) 2014 BlackBerry Limited. All rights reserved.
**
** Contact: BlackBerry ([email protected])
** Contact: KDAB ([email protected])
**
** This file is part of Qt Creator.
**
** 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.
**
****************************************************************************/
#include "bardescriptoreditorfactory.h"
#include "qnxconstants.h"
#include "bardescriptoreditor.h"
#include "bardescriptoreditorwidget.h"
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/editormanager/ieditor.h>
#include <texteditor/texteditoractionhandler.h>
using namespace Qnx;
using namespace Qnx::Internal;
class BarDescriptorActionHandler : public TextEditor::TextEditorActionHandler
{
public:
BarDescriptorActionHandler(QObject *parent)
: TextEditor::TextEditorActionHandler(parent, Constants::QNX_BAR_DESCRIPTOR_EDITOR_CONTEXT)
{
}
protected:
TextEditor::BaseTextEditorWidget *resolveTextEditorWidget(Core::IEditor *editor) const
{
BarDescriptorEditorWidget *w = qobject_cast<BarDescriptorEditorWidget *>(editor->widget());
return w ? w->sourceWidget() : 0;
}
};
BarDescriptorEditorFactory::BarDescriptorEditorFactory(QObject *parent)
: Core::IEditorFactory(parent)
{
setId(Constants::QNX_BAR_DESCRIPTOR_EDITOR_ID);
setDisplayName(tr("Bar descriptor editor"));
addMimeType(Constants::QNX_BAR_DESCRIPTOR_MIME_TYPE);
new BarDescriptorActionHandler(this);
}
Core::IEditor *BarDescriptorEditorFactory::createEditor()
{
BarDescriptorEditor *editor = new BarDescriptorEditor();
return editor;
}
|
import contextlib
import itertools
import logging
import sys
import time
from typing import IO, Iterator
from pip._vendor.progress import HIDE_CURSOR, SHOW_CURSOR
from pip._internal.utils.compat import WINDOWS
from pip._internal.utils.logging import get_indentation
logger = logging.getLogger(__name__)
class SpinnerInterface:
def spin(self):
# type: () -> None
raise NotImplementedError()
def finish(self, final_status):
# type: (str) -> None
raise NotImplementedError()
class InteractiveSpinner(SpinnerInterface):
def __init__(
self,
message,
file=None,
spin_chars="-\\|/",
# Empirically, 8 updates/second looks nice
min_update_interval_seconds=0.125,
):
# type: (str, IO[str], str, float) -> None
self._message = message
if file is None:
file = sys.stdout
self._file = file
self._rate_limiter = RateLimiter(min_update_interval_seconds)
self._finished = False
self._spin_cycle = itertools.cycle(spin_chars)
self._file.write(" " * get_indentation() + self._message + " ... ")
self._width = 0
def _write(self, status):
# type: (str) -> None
assert not self._finished
# Erase what we wrote before by backspacing to the beginning, writing
# spaces to overwrite the old text, and then backspacing again
backup = "\b" * self._width
self._file.write(backup + " " * self._width + backup)
# Now we have a blank slate to add our status
self._file.write(status)
self._width = len(status)
self._file.flush()
self._rate_limiter.reset()
def spin(self):
# type: () -> None
if self._finished:
return
if not self._rate_limiter.ready():
return
self._write(next(self._spin_cycle))
def finish(self, final_status):
# type: (str) -> None
if self._finished:
return
self._write(final_status)
self._file.write("\n")
self._file.flush()
self._finished = True
# Used for dumb terminals, non-interactive installs (no tty), etc.
# We still print updates occasionally (once every 60 seconds by default) to
# act as a keep-alive for systems like Travis-CI that take lack-of-output as
# an indication that a task has frozen.
class NonInteractiveSpinner(SpinnerInterface):
def __init__(self, message, min_update_interval_seconds=60):
# type: (str, float) -> None
self._message = message
self._finished = False
self._rate_limiter = RateLimiter(min_update_interval_seconds)
self._update("started")
def _update(self, status):
# type: (str) -> None
assert not self._finished
self._rate_limiter.reset()
logger.info("%s: %s", self._message, status)
def spin(self):
# type: () -> None
if self._finished:
return
if not self._rate_limiter.ready():
return
self._update("still running...")
def finish(self, final_status):
# type: (str) -> None
if self._finished:
return
self._update(f"finished with status '{final_status}'")
self._finished = True
class RateLimiter:
def __init__(self, min_update_interval_seconds):
# type: (float) -> None
self._min_update_interval_seconds = min_update_interval_seconds
self._last_update = 0 # type: float
def ready(self):
# type: () -> bool
now = time.time()
delta = now - self._last_update
return delta >= self._min_update_interval_seconds
def reset(self):
# type: () -> None
self._last_update = time.time()
@contextlib.contextmanager
def open_spinner(message):
# type: (str) -> Iterator[SpinnerInterface]
# Interactive spinner goes directly to sys.stdout rather than being routed
# through the logging system, but it acts like it has level INFO,
# i.e. it's only displayed if we're at level INFO or better.
# Non-interactive spinner goes through the logging system, so it is always
# in sync with logging configuration.
if sys.stdout.isatty() and logger.getEffectiveLevel() <= logging.INFO:
spinner = InteractiveSpinner(message) # type: SpinnerInterface
else:
spinner = NonInteractiveSpinner(message)
try:
with hidden_cursor(sys.stdout):
yield spinner
except KeyboardInterrupt:
spinner.finish("canceled")
raise
except Exception:
spinner.finish("error")
raise
else:
spinner.finish("done")
@contextlib.contextmanager
def hidden_cursor(file):
# type: (IO[str]) -> Iterator[None]
# The Windows terminal does not support the hide/show cursor ANSI codes,
# even via colorama. So don't even try.
if WINDOWS:
yield
# We don't want to clutter the output with control characters if we're
# writing to a file, or if the user is running with --quiet.
# See https://github.com/pypa/pip/issues/3418
elif not file.isatty() or logger.getEffectiveLevel() > logging.INFO:
yield
else:
file.write(HIDE_CURSOR)
try:
yield
finally:
file.write(SHOW_CURSOR)
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.exceptions import ObjectDoesNotExist
from django.db import migrations
from django.db.utils import IntegrityError
from django.utils.translation import ugettext_lazy as _
def create_and_assign_permissions(apps, schema_editor):
Permission = apps.get_model('auth', 'Permission')
ContentType = apps.get_model('contenttypes', 'ContentType')
# Two steps:
# 1. Create the permission for existing Queues
# 2. Assign the permission to user according to QueueMembership objects
# First step: prepare the permission for each queue
Queue = apps.get_model('helpdesk', 'Queue')
for q in Queue.objects.all():
if not q.permission_name:
basename = "queue_access_%s" % q.slug
q.permission_name = "helpdesk.%s" % basename
else:
# Strip the `helpdesk.` prefix
basename = q.permission_name[9:]
try:
Permission.objects.create(
name=_("Permission for queue: ") + q.title,
content_type=ContentType.objects.get(model="queue"),
codename=basename,
)
except IntegrityError:
# Seems that it already existed, safely ignore it
pass
q.save()
# Second step: map the permissions according to QueueMembership
QueueMembership = apps.get_model('helpdesk', 'QueueMembership')
for qm in QueueMembership.objects.all():
user = qm.user
for q in qm.queues.all():
# Strip the `helpdesk.` prefix
p = Permission.objects.get(codename=q.permission_name[9:])
user.user_permissions.add(p)
qm.delete()
def revert_queue_membership(apps, schema_editor):
Permission = apps.get_model('auth', 'Permission')
Queue = apps.get_model('helpdesk', 'Queue')
QueueMembership = apps.get_model('helpdesk', 'QueueMembership')
for p in Permission.objects.all():
if p.codename.startswith("queue_access_"):
slug = p.codename[13:]
try:
q = Queue.objects.get(slug=slug)
except ObjectDoesNotExist:
continue
for user in p.user_set.all():
qm, _ = QueueMembership.objects.get_or_create(user=user)
qm.queues.add(q)
p.delete()
class Migration(migrations.Migration):
dependencies = [
('helpdesk', '0008_extra_for_permissions'),
]
operations = [
migrations.RunPython(create_and_assign_permissions,
revert_queue_membership)
]
|
'use strict';
var debug = require('debug')('usvc:jsonrpc:client');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var when = require('when');
var whennode = require('when/node');
var jayson = require('jayson');
var json_signing = require('./json_signing');
function JSONRPCClient(options, service, name) {
this.service = service;
this.name = name;
this.options = options || {};
this.options.methodPrefix = this.options.methodPrefix || (this.name + '.');
}
util.inherits(JSONRPCClient, EventEmitter);
JSONRPCClient.prototype.initialise = function() {
return when.try(function() {
// FIXME: support pool of RPC servers
var serverKey = this.name + ':server';
var server = this.service.config.get(serverKey);
if (!server) {
throw new Error('JSON RPC Client requires configuration at ' + serverKey);
}
['hostname', 'port'].map(function(key) {
if (!server.hasOwnProperty(key)) {
throw new Error('JSON RPC Client requires configuration option: ' + key);
}
});
this.signingFunctions = json_signing.getSigningFunctions(this.service, this.name);
debug(this.name, 'Configuration for JSON RPC Client: ' + server);
this.client = jayson.client.http(server);
}.bind(this));
};
JSONRPCClient.prototype.call = function(method) {
var remoteMethod = this.options.methodPrefix + method;
var remoteArgs = [].slice.apply(arguments).slice(1);
return when.try(function() {
var deferred = when.defer();
debug('call', method, remoteArgs);
if (this.signingFunctions) {
var signedArgs = this.signingFunctions.sign({method: remoteMethod, arguments: remoteArgs});
remoteArgs = [signedArgs];
debug('signed', method, remoteArgs);
}
this.client.request(remoteMethod, remoteArgs, function(err, value) {
debug('result', err, value ? value.error : "-", value ? value.result : "-");
if (err) {
debug('call', 'rejecting with call error');
deferred.reject(err);
} else if (value.error) {
debug('call', 'rejecting remote error');
deferred.reject(value.error);
} else {
deferred.resolve(value.result);
}
});
return deferred.promise;
}.bind(this));
};
module.exports = JSONRPCClient;
|
using System;
public class BankAccount
{
private readonly object _lock = new object();
private decimal balance;
private bool isOpen;
public void Open()
{
lock(_lock)
{
isOpen = true;
}
}
public void Close()
{
lock(_lock)
{
isOpen = false;
}
}
public decimal Balance
{
get
{
lock (_lock)
{
if (!isOpen)
{
throw new InvalidOperationException("Cannot get balance on an account that isn't open");
}
return balance;
}
}
}
public void UpdateBalance(decimal change)
{
lock(_lock)
{
if (!isOpen)
{
throw new InvalidOperationException("Cannot update balance on an account that isn't open");
}
balance += change;
}
}
}
|
/* radare - LGPL - Copyright 2017 - pancake */
#include <r_fs.h>
#include <r_lib.h>
#include <sys/stat.h>
typedef int (*SquashDirCallback)(void *user,const char *name, int type, int size);
int sq_mount(RFSRoot *root, ut64 delta);
int sq_dir(const char *path, SquashDirCallback cb, void *user);
unsigned char *sq_cat(const char *path, int *len);
static RFSFile *fs_squash_open(RFSRoot *root, const char *path) {
int size = 0;
unsigned char *buf = sq_cat (path, &size);
if (buf) {
RFSFile *file = r_fs_file_new (root, path);
if (!file) {
return NULL;
}
file->path = strdup (path);
file->ptr = NULL;
file->p = root->p;
file->size = size;
free (buf);
return file;
}
return NULL;
}
static bool fs_squash_read(RFSFile *file, ut64 addr, int len) {
int size = 0;
unsigned char *buf = sq_cat (file->path, &size);
if (buf) {
file->data = buf;
// file->size = size;
return file;
}
return NULL;
}
static void fs_squash_close(RFSFile *file) {
// free (file->data);
file->data = NULL;
// fclose (file->ptr);
}
static void append_file(RList *list, const char *name, int type, int time, ut64 size) {
RFSFile *fsf = r_fs_file_new (NULL, name);
if (!fsf) {
return;
}
fsf->type = type;
fsf->time = time;
fsf->size = size;
r_list_append (list, fsf);
}
typedef struct {
RList *list;
const char *path;
} SquashUser;
static int cb(void *user, const char *name, int type, int size) {
SquashUser *su = user;
if (!su || !su->path) {
return 0;
}
if (!strncmp (name, su->path, strlen (su->path))) {
name += strlen (su->path);
if (*name == '/') {
name++;
}
}
if (*name && strchr (name, '/')) {
return 0;
}
append_file (su->list, name, type, 0, size);
return 1;
}
static RList *fs_squash_dir(RFSRoot *root, const char *path, int view /*ignored*/) {
RList *list = r_list_new ();
if (!list) {
return NULL;
}
SquashUser su = { list, path };
sq_dir (path, cb, &su);
return list;
}
static int fs_squash_mount(RFSRoot *root) {
root->ptr = NULL;
return sq_mount (root, root->delta);
}
static void fs_squash_umount(RFSRoot *root) {
root->ptr = NULL;
}
RFSPlugin r_fs_plugin_io = {
.name = "squashfs",
.desc = "SquashFS filesystem (XZ + LZMA)",
.license = "GPL",
.open = fs_squash_open,
.read = fs_squash_read,
.close = fs_squash_close,
.dir = &fs_squash_dir,
.mount = fs_squash_mount,
.umount = fs_squash_umount,
};
#ifndef CORELIB
RLibStruct radare_plugin = {
.type = R_LIB_TYPE_FS,
.data = &r_fs_plugin_io,
.version = R2_VERSION
};
#endif
|
<?xml version="1.0" encoding="iso-8859-1"?>
<!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>
<!-- template designed by Marco Von Ballmoos -->
<title>Docs for page OntProperty.php</title>
<link rel="stylesheet" href="../media/stylesheet.css" />
<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'/>
</head>
<body>
<div class="page-body">
<h2 class="file-name">/ontModel/OntProperty.php</h2>
<a name="sec-description"></a>
<div class="info-box">
<div class="info-box-title">Description</div>
<div class="nav-bar">
<span class="disabled">Description</span> |
<a href="#sec-classes">Classes</a>
</div>
<div class="info-box-body">
<!-- ========== Info from phpDoc block ========= -->
<ul class="tags">
<li><span class="field">filesource:</span> <a href="../__filesource/fsource_ontModel__ontModelOntProperty.php.html">Source Code for this file</a></li>
</ul>
</div>
</div>
<a name="sec-classes"></a>
<div class="info-box">
<div class="info-box-title">Classes</div>
<div class="nav-bar">
<a href="#sec-description">Description</a> |
<span class="disabled">Classes</span>
</div>
<div class="info-box-body">
<table cellpadding="2" cellspacing="0" class="class-table">
<tr>
<th class="class-table-header">Class</th>
<th class="class-table-header">Description</th>
</tr>
<tr>
<td style="padding-right: 2em; vertical-align: top">
<a href="../ontModel/OntProperty.html">OntProperty</a>
</td>
<td>
Class encapsulating a property in an ontology.
</td>
</tr>
</table>
</div>
</div>
<p class="notes" id="credit">
Documentation generated on Fri, 1 Jun 2007 16:50:08 +0200 by <a href="http://www.phpdoc.org" target="_blank">phpDocumentor 1.3.2</a>
</p>
</div></body>
</html>
|
from __future__ import print_function, division
import yaml
import time
import sys
import numpy as np
import itertools
from keras.utils.np_utils import to_categorical
from baal.utils import loggers
try:
input = raw_input
except:
pass
class DataServer(object):
"""
Required config:
disable_logger: {True/False}
saving_prefix
batch_size
Is also good to "stage" it by adding to it the following:
train_data
dev_data
train_vocab
"""
def __init__(self, config):
self.__dict__.update(config)
log_name = self.saving_prefix
self.logger = loggers.duallog(log_name, "info", "logs/", disable=self.disable_logger)
def print_everything(self):
for key, value in self.__dict__.items():
if isinstance(value, (bool, str, int, float)):
print("{}: {}".format(key, value))
@classmethod
def from_file(cls, config_file):
with open(config_file) as fp:
config = yaml.load(fp)
return cls(config)
@property
def num_train_batches(self):
return len(self.train_data)//self.batch_size
@property
def num_dev_batches(self):
return len(self.dev_data)//self.batch_size
@property
def num_train_samples(self):
if self.subepochs > 0:
return self.num_train_batches // self.subepochs * self.batch_size
return self.num_train_batches * self.batch_size
@property
def num_dev_samples(self):
return self.num_dev_batches * self.batch_size
def stage(self, *args, **kwargs):
""" would be great to load things here """
pass
def serve_single(self, data, unseen_data=None):
"""serve a single sample from a dataset;
yield X and Y of size appropriate to sample_size
### an example implementation
for data_i in np.random.choice(len(data), len(data), replace=False):
in_X = np.zeros(self.max_sequence_len)
out_Y = np.zeros(self.max_sequence_len, dtype=np.int32)
bigram_data = zip(data[data_i][0:-1], data[data_i][1:])
for datum_j,(datum_in, datum_out) in enumerate(bigram_data):
in_X[datum_j] = datum_in
out_Y[datum_j] = datum_out
yield in_X, out_Y
"""
raise NotImplementedError
def serve_batch(self, data, unseen_data=None):
"""serve a batch of samples from a dataset;
yield X and Y of sizes appropriate to (batch,) + sample_size
### an example implementation
### yields (batch,sequence) and (batch, sequence, vocab)
dataiter = self.serve_sentence(data)
V = self.vocab_size
S = self.max_sequence_len
B = self.batch_size
while dataiter:
in_X = np.zeros((B, S), dtype=np.int32)
out_Y = np.zeros((B, S, V), dtype=np.int32)
next_batch = list(itertools.islice(dataiter, 0, self.batch_size))
if len(next_batch) < self.batch_size:
raise StopIteration
for d_i, (d_X, d_Y) in enumerate(next_batch):
in_X[d_i] = d_X
out_Y[d_i] = to_categorical(d_Y, V)
yield in_X, out_Y
"""
raise NotImplementedError
def _data_gen(self, data, forever=True):
working = True
while working:
for batch in self.serve_batch(data):
yield batch
working = working and forever
def dev_gen(self, forever=True):
return self._data_gen(self.dev_data, forever)
def train_gen(self, forever=True):
return self._data_gen(self.train_data, forever)
|
<?php
// Exit if accessed directly
if ( !defined('ABSPATH')) exit;
$footer_left = kt_option('footer_copyright_left');
$footer_right = kt_option('footer_copyright_right', 'copyright');
if(!$footer_left && !$footer_right) return;
?>
<div class="display-table">
<div class="display-cell footer-left">
<?php get_template_part( 'templates/footers/footer', $footer_left ); ?>
</div>
<div class="display-cell footer-right">
<?php get_template_part( 'templates/footers/footer', $footer_right ); ?>
</div>
</div>
|
#include "stanza.h"
#include <QTextStream>
#include "jid.h"
StanzaData::StanzaData(const QString &ATagName)
{
FDoc.appendChild(FDoc.createElement(ATagName));
}
StanzaData::StanzaData(const QDomElement &AElem)
{
FDoc.appendChild(FDoc.importNode(AElem,true));
}
StanzaData::StanzaData(const StanzaData &AOther) : QSharedData(AOther)
{
FDoc = AOther.FDoc.cloneNode(true).toDocument();
}
Stanza::Stanza(const QString &ATagName)
{
d = new StanzaData(ATagName);
}
Stanza::Stanza(const QDomElement &AElem)
{
d = new StanzaData(AElem);
}
Stanza::~Stanza()
{
}
void Stanza::detach()
{
d.detach();
}
bool Stanza::isValid() const
{
if (element().isNull())
return false;
if (type()=="error" && firstElement("error").isNull())
return false;
return true;
}
bool Stanza::isFromServer() const
{
if (!to().isEmpty())
{
Jid toJid = to();
Jid fromJid = from();
return fromJid.isEmpty() || fromJid==toJid || fromJid==toJid.bare() || fromJid==toJid.domain();
}
return false;
}
QDomDocument Stanza::document() const
{
return d->FDoc;
}
QDomElement Stanza::element() const
{
return d->FDoc.documentElement();
}
QString Stanza::attribute(const QString &AName) const
{
return d->FDoc.documentElement().attribute(AName);
}
Stanza &Stanza::setAttribute(const QString &AName, const QString &AValue)
{
if (!AValue.isEmpty())
d->FDoc.documentElement().setAttribute(AName,AValue);
else
d->FDoc.documentElement().removeAttribute(AName);
return *this;
}
QString Stanza::tagName() const
{
return d->FDoc.documentElement().tagName();
}
Stanza &Stanza::setTagName(const QString &ATagName)
{
d->FDoc.documentElement().setTagName(ATagName);
return *this;
}
QString Stanza::type() const
{
return attribute("type");
}
Stanza &Stanza::setType(const QString &AType)
{
setAttribute("type",AType);
return *this;
}
QString Stanza::id() const
{
return attribute("id");
}
Stanza &Stanza::setId(const QString &AId)
{
setAttribute("id",AId);
return *this;
}
QString Stanza::to() const
{
return attribute("to");
}
Stanza &Stanza::setTo(const QString &ATo)
{
setAttribute("to",ATo);
return *this;
}
QString Stanza::from() const
{
return attribute("from");
}
Stanza &Stanza::setFrom(const QString &AFrom)
{
setAttribute("from",AFrom);
return *this;
}
QString Stanza::lang() const
{
return attribute("xml:lang");
}
Stanza &Stanza::setLang(const QString &ALang)
{
setAttribute("xml:lang",ALang);
return *this;
}
QDomElement Stanza::firstElement(const QString &ATagName, const QString ANamespace) const
{
return findElement(d->FDoc.documentElement(),ATagName,ANamespace);
}
QDomElement Stanza::addElement(const QString &ATagName, const QString &ANamespace)
{
return d->FDoc.documentElement().appendChild(createElement(ATagName,ANamespace)).toElement();
}
QDomElement Stanza::createElement(const QString &ATagName, const QString &ANamespace)
{
if (ANamespace.isEmpty())
return d->FDoc.createElement(ATagName);
else
return d->FDoc.createElementNS(ANamespace,ATagName);
}
QDomText Stanza::createTextNode(const QString &AData)
{
return d->FDoc.createTextNode(AData);
}
QString Stanza::toString(int AIndent) const
{
QString data;
QTextStream ts(&data, QIODevice::WriteOnly);
ts.setCodec("UTF-16");
element().save(ts, AIndent);
return data;
}
QByteArray Stanza::toByteArray() const
{
return toString(0).toUtf8();
}
QDomElement Stanza::findElement(const QDomElement &AParent, const QString &ATagName, const QString &ANamespace)
{
QDomElement elem = AParent.firstChildElement(ATagName);
if (!ANamespace.isNull())
{
while (!elem.isNull() && elem.namespaceURI()!=ANamespace)
elem = elem.nextSiblingElement(ATagName);
}
return elem;
}
|
// Generated by CoffeeScript 1.4.0
self.port.on('show', function(arg) {
var frame, image, panel_layout;
console.log("in port show");
if (arg == null) {
console.error('arg is null');
return;
}
panel_layout = document.getElementById('panel-layout');
frame = document.getElementById('frame');
if (frame === null) {
frame = document.createElement('div');
frame.id = 'frame';
panel_layout.appendChild(frame);
}
console.log(arg.timestamp);
image = document.getElementById("image_" + arg.short_id);
if (image === null) {
image = document.createElement('img');
image.id = "image_" + arg.short_id;
image.src = "http://twitpic.com/show/thumb/" + arg.short_id;
console.log(image.src);
frame.appendChild(image);
}
});
|
import { Property } from '../models';
export const properties = [
new Property('id', 'ID', false),
new Property('description'),
new Property('project_id', 'Project'),
new Property('pipeline_id', 'Pipeline'),
new Property('created_at', 'Date Created'),
new Property('created_by', 'Created By'),
new Property('status'),
];
|
# -*- coding: utf-8 -*-
from ..internal.misc import json
from ..internal.MultiHoster import MultiHoster
class MyfastfileCom(MultiHoster):
__name__ = "MyfastfileCom"
__type__ = "hoster"
__version__ = "0.16"
__status__ = "testing"
__pattern__ = r'http://\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/dl/'
__config__ = [("activated", "bool", "Activated", True),
("use_premium", "bool", "Use premium account if available", True),
("fallback", "bool", "Fallback to free download if premium fails", False),
("chk_filesize", "bool", "Check file size", True),
("max_wait", "int", "Reconnect if waiting time is greater than minutes", 10),
("revert_failed", "bool", "Revert to standard download if fails", True)]
__description__ = """Myfastfile.com multi-hoster plugin"""
__license__ = "GPLv3"
__authors__ = [("stickell", "[email protected]")]
def setup(self):
self.chunk_limit = -1
def handle_premium(self, pyfile):
self.data = self.load('http://myfastfile.com/api.php',
get={'user': self.account.user,
'pass': self.account.get_login('password'),
'link': pyfile.url})
self.log_debug("JSON data: " + self.data)
self.data = json.loads(self.data)
if self.data['status'] != 'ok':
self.fail(_("Unable to unrestrict link"))
self.link = self.data['link']
|
"""Wrapper around 'git rev-parse'."""
# =============================================================================
# CONTENTS
# -----------------------------------------------------------------------------
# phlgit_revparse
#
# Public Classes:
# Error
#
# Public Functions:
# get_sha1_or_none
# get_sha1
#
# -----------------------------------------------------------------------------
# (this contents block is generated, edits will be lost)
# =============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class Error(Exception):
pass
def get_sha1_or_none(repo, ref):
"""Return string of the ref's commit hash if valid, else None.
:repo: a callable supporting git commands, e.g. repo("status")
:ref: string of the reference to parse
:returns: string of the ref's commit hash if valid, else None.
"""
commit = repo("rev-parse", "--revs-only", ref).strip()
return commit if commit else None
def get_sha1(repo, ref):
"""Return string of the ref's commit hash.
Raise if the ref is invalid.
:repo: a callable supporting git commands, e.g. repo("status")
:ref: string of the reference to parse
:returns: string of the ref's commit hash
"""
commit = get_sha1_or_none(repo, ref)
if commit is None:
raise Error("ref '{}' is invalid.".format(ref))
return commit
# -----------------------------------------------------------------------------
# Copyright (C) 2013-2014 Bloomberg Finance L.P.
#
# 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.
# ------------------------------ END-OF-FILE ----------------------------------
|
# coding: utf-8
# view.py written by Duncan Murray 22/3/2014 (C) Acute Software
# searches AIKIF
import os
import sys
sys.path.append('..//..//aspytk')
import lib_data as dat
import lib_file as fle
import lib_net as net
import AIKIF_utils as aikif
import fileMapping as filemap
if len(sys.argv) == 2:
viewStructure = sys.argv[1]
def view():
# main function
aikif.LogProcess('Starting view', 'view.py') # sys.modules[self.__module__].__file__)
AIKIF_FileList = aikif.build_AIKIF_structure()
ShowMenu()
ProcessInputUntilUserQuits(AIKIF_FileList)
def ShowMenu():
print('---------------------')
print('AIKIF Data Structures')
print('---------------------')
print('1 - aikif.printFileList(AIKIF_FileList)')
print('2 - aikif.showColumnStructures(AIKIF_FileList)')
print('3 - aikif.debugPrintFileStructures(AIKIF_FileList)')
print('4 - filemap.ShowListOfPhysicalFiles()')
print('m - show this menu')
print('s - statistics')
print('q - quit')
def ProcessInputUntilUserQuits(AIKIF_FileList):
while True:
command = input('Enter command: (m=menu, q=quit, [string]=view entries for string ')
if command.upper() == 'Q':
quit()
if command.upper() == 'M':
ShowMenu()
if command.upper() == 'S':
ShowStatistics(AIKIF_FileList)
if command == '1':
aikif.printFileList(AIKIF_FileList)
if command == '2':
aikif.showColumnStructures(AIKIF_FileList)
if command == '3':
aikif.debugPrintFileStructures(AIKIF_FileList)
if command == '4':
filemap.ShowListOfPhysicalFiles()
def ShowStatistics(AIKIF_FileList):
print(' ----=== Statistics for AIKIF ===----')
print(' AIKIF_FileList = ' + str(len(AIKIF_FileList)))
print(' index entries = ' + str(dat.countLinesInFile('..\\data\\index\\ndxFull.txt')))
print(' indexed words - unique = ' + str(dat.countLinesInFile('..\\data\\index\\ndxWordsToFiles.txt')))
print(' Python files in getcwd = ' + str(len(fle.GetFileList([os.getcwd()], ['*.py'], ["__pycache__", ".git"], False))))
if __name__ == '__main__':
view()
|
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* [email protected]. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
namespace Microsoft.PythonTools.Logging {
public sealed class PackageInstallDetails {
private readonly string _name;
private readonly string _version;
private readonly string _interpreterName;
private readonly string _interpreterVersion;
private readonly string _interpreterArchitecture;
private readonly string _installer;
private readonly bool _elevated;
private readonly int _installResult;
public PackageInstallDetails(
string packageName,
string packageVersion,
string interpreterName,
string interpreterVersion,
string interpreterArchictecture,
string installer,
bool elevated,
int installResult) {
_name = packageName != null ? packageName : String.Empty;
_version = packageVersion != null ? packageVersion : String.Empty;
_interpreterName = interpreterName != null ? interpreterName : String.Empty;
_interpreterVersion = interpreterVersion != null ? interpreterVersion : String.Empty;
_interpreterArchitecture = interpreterArchictecture != null ? interpreterArchictecture : String.Empty;
_installer = installer != null ? installer : String.Empty;
_elevated = elevated;
_installResult = installResult;
}
private const string _header = "Name,Version,InterpreterName,InterpreterVersion,InterpreterArchitecture,Installer,Elevated,InstallResult";
public static string Header() { return _header; }
public override string ToString() {
return Name + "," +
Version + "," +
InterpreterName + "," +
InterpreterVersion + "," +
InterpreterArchitecture + "," +
Installer + "," +
Elevated + "," +
InstallResult;
}
/// <summary>
/// Name of the package installed
/// </summary>
public string Name { get { return _name; } }
/// <summary>
/// Version of the package installed
/// </summary>
public string Version { get { return _version; } }
public string InterpreterName { get { return _interpreterName; } }
public string InterpreterVersion { get { return _interpreterVersion; } }
public string InterpreterArchitecture { get { return _interpreterArchitecture; } }
public int InstallResult { get { return _installResult; } }
public bool Elevated { get { return _elevated; } }
/// <summary>
/// Represents the technology used for installation
/// ex: pip, easy_install, conda
/// </summary>
public string Installer { get { return _installer; } }
}
}
|
# table types
# First three were 0 -- was that right?
PKNR = 0 # table with a numeric primary key
SEQ = 1 # table with a numeric primary key and a sequential counter
CODE = 2 # code table with a varchar primary key
SYSTEM = 3 # system code table with a varchar primary key
LINK = 4 # many-to-many link table with a primary key that consists
# of the primary keys of the linked tables
# datatypes
INTEGER = 0
VARCHAR = 1
TEXT = 2
BOOLEAN = 3
DATETIME = 4
DATE = 5
# widgettypes
LINEEDIT = 0
MULTILINE = 1
COMBOBOX = 2
# config
USERNR = 2
# modes
INSERT = 0
UPDATE = 1
DELETE = 2
SEARCH = 4
# form types
MASTER = 0
DETAIL = 1
__copyright__="""
copyright : (C) 2002 by Boudewijn Rempt
see copyright notice for license
email : [email protected]
"""
__revision__="""$Revision: 1.2 $"""[11:-2]
__cvslog__="""
$Log: constants.py,v $
Revision 1.2 2002/05/23 18:31:16 boud
Converted some dialogs.
***************************************************************************/
"""
|
#!/usr/bin/python
import socket, thread, time
listen_port = 3007
connect_addr = ('localhost', 2007)
sleep_per_byte = 0.0001
def forward(source, destination):
source_addr = source.getpeername()
while True:
data = source.recv(4096)
if data:
for i in data:
destination.sendall(i)
time.sleep(sleep_per_byte)
else:
print 'disconnect', source_addr
destination.shutdown(socket.SHUT_WR)
break
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serversocket.bind(('', listen_port))
serversocket.listen(5)
while True:
(clientsocket, address) = serversocket.accept()
print 'accepted', address
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(connect_addr)
print 'connected', sock.getpeername()
thread.start_new_thread(forward, (clientsocket, sock))
thread.start_new_thread(forward, (sock, clientsocket))
|
# KidsCanCode - Game Development with Pygame video series
# Jumpy! (a platform game) - Part 10
# Video link: https://youtu.be/kuVsKUuVOwc
# Character animation (part 1)
# Art from Kenney.nl
import pygame as pg
import random
from settings import *
from sprites import *
from os import path
class Game:
def __init__(self):
# initialize game window, etc
pg.init()
pg.mixer.init()
self.screen = pg.display.set_mode((WIDTH, HEIGHT))
pg.display.set_caption(TITLE)
self.clock = pg.time.Clock()
self.running = True
self.font_name = pg.font.match_font(FONT_NAME)
self.load_data()
def load_data(self):
# load high score
self.dir = path.dirname(__file__)
img_dir = path.join(self.dir, 'img')
with open(path.join(self.dir, HS_FILE), 'r') as f:
try:
self.highscore = int(f.read())
except:
self.highscore = 0
# load spritesheet image
self.spritesheet = Spritesheet(path.join(img_dir, SPRITESHEET))
def new(self):
# start a new game
self.score = 0
self.all_sprites = pg.sprite.Group()
self.platforms = pg.sprite.Group()
self.player = Player(self)
self.all_sprites.add(self.player)
for plat in PLATFORM_LIST:
p = Platform(*plat)
self.all_sprites.add(p)
self.platforms.add(p)
self.run()
def run(self):
# Game Loop
self.playing = True
while self.playing:
self.clock.tick(FPS)
self.events()
self.update()
self.draw()
def update(self):
# Game Loop - Update
self.all_sprites.update()
# check if player hits a platform - only if falling
if self.player.vel.y > 0:
hits = pg.sprite.spritecollide(self.player, self.platforms, False)
if hits:
self.player.pos.y = hits[0].rect.top
self.player.vel.y = 0
# if player reaches top 1/4 of screen
if self.player.rect.top <= HEIGHT / 4:
self.player.pos.y += abs(self.player.vel.y)
for plat in self.platforms:
plat.rect.y += abs(self.player.vel.y)
if plat.rect.top >= HEIGHT:
plat.kill()
self.score += 10
# Die!
if self.player.rect.bottom > HEIGHT:
for sprite in self.all_sprites:
sprite.rect.y -= max(self.player.vel.y, 10)
if sprite.rect.bottom < 0:
sprite.kill()
if len(self.platforms) == 0:
self.playing = False
# spawn new platforms to keep same average number
while len(self.platforms) < 6:
width = random.randrange(50, 100)
p = Platform(random.randrange(0, WIDTH - width),
random.randrange(-75, -30),
width, 20)
self.platforms.add(p)
self.all_sprites.add(p)
def events(self):
# Game Loop - events
for event in pg.event.get():
# check for closing window
if event.type == pg.QUIT:
if self.playing:
self.playing = False
self.running = False
if event.type == pg.KEYDOWN:
if event.key == pg.K_SPACE:
self.player.jump()
def draw(self):
# Game Loop - draw
self.screen.fill(BGCOLOR)
self.all_sprites.draw(self.screen)
self.draw_text(str(self.score), 22, WHITE, WIDTH / 2, 15)
# *after* drawing everything, flip the display
pg.display.flip()
def show_start_screen(self):
# game splash/start screen
self.screen.fill(BGCOLOR)
self.draw_text(TITLE, 48, WHITE, WIDTH / 2, HEIGHT / 4)
self.draw_text("Arrows to move, Space to jump", 22, WHITE, WIDTH / 2, HEIGHT / 2)
self.draw_text("Press a key to play", 22, WHITE, WIDTH / 2, HEIGHT * 3 / 4)
self.draw_text("High Score: " + str(self.highscore), 22, WHITE, WIDTH / 2, 15)
pg.display.flip()
self.wait_for_key()
def show_go_screen(self):
# game over/continue
if not self.running:
return
self.screen.fill(BGCOLOR)
self.draw_text("GAME OVER", 48, WHITE, WIDTH / 2, HEIGHT / 4)
self.draw_text("Score: " + str(self.score), 22, WHITE, WIDTH / 2, HEIGHT / 2)
self.draw_text("Press a key to play again", 22, WHITE, WIDTH / 2, HEIGHT * 3 / 4)
if self.score > self.highscore:
self.highscore = self.score
self.draw_text("NEW HIGH SCORE!", 22, WHITE, WIDTH / 2, HEIGHT / 2 + 40)
with open(path.join(self.dir, HS_FILE), 'w') as f:
f.write(str(self.score))
else:
self.draw_text("High Score: " + str(self.highscore), 22, WHITE, WIDTH / 2, HEIGHT / 2 + 40)
pg.display.flip()
self.wait_for_key()
def wait_for_key(self):
waiting = True
while waiting:
self.clock.tick(FPS)
for event in pg.event.get():
if event.type == pg.QUIT:
waiting = False
self.running = False
if event.type == pg.KEYUP:
waiting = False
def draw_text(self, text, size, color, x, y):
font = pg.font.Font(self.font_name, size)
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect()
text_rect.midtop = (x, y)
self.screen.blit(text_surface, text_rect)
g = Game()
g.show_start_screen()
while g.running:
g.new()
g.show_go_screen()
pg.quit()
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// EnumerableWrapperWeakToStrong.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Linq.Parallel
{
/// <summary>
/// A simple implementation of the IEnumerable{object} interface which wraps
/// a weakly typed IEnumerable object, allowing it to be accessed as a strongly typed
/// IEnumerable{object}.
/// </summary>
internal class EnumerableWrapperWeakToStrong : IEnumerable<object>
{
private readonly IEnumerable _wrappedEnumerable; // The wrapped enumerable object.
//-----------------------------------------------------------------------------------
// Instantiates a new wrapper object.
//
internal EnumerableWrapperWeakToStrong(IEnumerable wrappedEnumerable)
{
Debug.Assert(wrappedEnumerable != null);
_wrappedEnumerable = wrappedEnumerable;
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<object>)this).GetEnumerator();
}
public IEnumerator<object> GetEnumerator()
{
return new WrapperEnumeratorWeakToStrong(_wrappedEnumerable.GetEnumerator());
}
//-----------------------------------------------------------------------------------
// A wrapper over IEnumerator that provides IEnumerator<object> interface
//
private class WrapperEnumeratorWeakToStrong : IEnumerator<object>
{
private readonly IEnumerator _wrappedEnumerator; // The weakly typed enumerator we've wrapped.
//-----------------------------------------------------------------------------------
// Wrap the specified enumerator in a new weak-to-strong converter.
//
internal WrapperEnumeratorWeakToStrong(IEnumerator wrappedEnumerator)
{
Debug.Assert(wrappedEnumerator != null);
_wrappedEnumerator = wrappedEnumerator;
}
//-----------------------------------------------------------------------------------
// These are all really simple IEnumerator<object> implementations that simply
// forward to the corresponding weakly typed IEnumerator methods.
//
object IEnumerator.Current
{
get { return _wrappedEnumerator.Current; }
}
object IEnumerator<object>.Current
{
get { return _wrappedEnumerator.Current; }
}
void IDisposable.Dispose()
{
IDisposable disposable = _wrappedEnumerator as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
bool IEnumerator.MoveNext()
{
return _wrappedEnumerator.MoveNext();
}
void IEnumerator.Reset()
{
_wrappedEnumerator.Reset();
}
}
}
}
|
<!--
Unsafe sample
input : Uses popen to read the file /tmp/tainted.txt using cat command
Uses a full_special_chars_filter via filter_var function
File : unsafe, use of untrusted data in a script
-->
<!--Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.-->
<!DOCTYPE html>
<html>
<head>
<script>
<?php
$handle = popen('/bin/cat /tmp/tainted.txt', 'r');
$tainted = fread($handle, 4096);
pclose($handle);
$sanitized = filter_var($tainted, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$tainted = $sanitized ;
//flaw
echo $tainted ;
?>
</script>
</head>
<body onload="xss()">
<h1>Hello World!</h1>
</body>
</html>
|
<html>
<head>
<meta charset="utf-8" />
<title><?php echo lang::translate('title'); ?></title>
</head>
<body>
<?php if (isset($__page)): ?><?php EE::view($__page); ?><?php endif; ?>
</body>
</html>
|
"""Support for APRS device tracking."""
import logging
import threading
import aprslib
from aprslib import ConnectionError as AprsConnectionError, LoginError
import geopy.distance
import voluptuous as vol
from homeassistant.components.device_tracker import (
PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA,
)
from homeassistant.const import (
ATTR_GPS_ACCURACY,
ATTR_LATITUDE,
ATTR_LONGITUDE,
CONF_HOST,
CONF_PASSWORD,
CONF_TIMEOUT,
CONF_USERNAME,
EVENT_HOMEASSISTANT_STOP,
)
import homeassistant.helpers.config_validation as cv
from homeassistant.util import slugify
DOMAIN = "aprs"
_LOGGER = logging.getLogger(__name__)
ATTR_ALTITUDE = "altitude"
ATTR_COURSE = "course"
ATTR_COMMENT = "comment"
ATTR_FROM = "from"
ATTR_FORMAT = "format"
ATTR_POS_AMBIGUITY = "posambiguity"
ATTR_SPEED = "speed"
CONF_CALLSIGNS = "callsigns"
DEFAULT_HOST = "rotate.aprs2.net"
DEFAULT_PASSWORD = "-1"
DEFAULT_TIMEOUT = 30.0
FILTER_PORT = 14580
MSG_FORMATS = ["compressed", "uncompressed", "mic-e"]
PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_CALLSIGNS): cv.ensure_list,
vol.Required(CONF_USERNAME): cv.string,
vol.Optional(CONF_PASSWORD, default=DEFAULT_PASSWORD): cv.string,
vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string,
vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): vol.Coerce(float),
}
)
def make_filter(callsigns: list) -> str:
"""Make a server-side filter from a list of callsigns."""
return " ".join(f"b/{sign.upper()}" for sign in callsigns)
def gps_accuracy(gps, posambiguity: int) -> int:
"""Calculate the GPS accuracy based on APRS posambiguity."""
pos_a_map = {0: 0, 1: 1 / 600, 2: 1 / 60, 3: 1 / 6, 4: 1}
if posambiguity in pos_a_map:
degrees = pos_a_map[posambiguity]
gps2 = (gps[0], gps[1] + degrees)
dist_m = geopy.distance.distance(gps, gps2).m
accuracy = round(dist_m)
else:
message = f"APRS position ambiguity must be 0-4, not '{posambiguity}'."
raise ValueError(message)
return accuracy
def setup_scanner(hass, config, see, discovery_info=None):
"""Set up the APRS tracker."""
callsigns = config.get(CONF_CALLSIGNS)
server_filter = make_filter(callsigns)
callsign = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
host = config.get(CONF_HOST)
timeout = config.get(CONF_TIMEOUT)
aprs_listener = AprsListenerThread(callsign, password, host, server_filter, see)
def aprs_disconnect(event):
"""Stop the APRS connection."""
aprs_listener.stop()
aprs_listener.start()
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, aprs_disconnect)
if not aprs_listener.start_event.wait(timeout):
_LOGGER.error("Timeout waiting for APRS to connect")
return
if not aprs_listener.start_success:
_LOGGER.error(aprs_listener.start_message)
return
_LOGGER.debug(aprs_listener.start_message)
return True
class AprsListenerThread(threading.Thread):
"""APRS message listener."""
def __init__(
self, callsign: str, password: str, host: str, server_filter: str, see
):
"""Initialize the class."""
super().__init__()
self.callsign = callsign
self.host = host
self.start_event = threading.Event()
self.see = see
self.server_filter = server_filter
self.start_message = ""
self.start_success = False
self.ais = aprslib.IS(
self.callsign, passwd=password, host=self.host, port=FILTER_PORT
)
def start_complete(self, success: bool, message: str):
"""Complete startup process."""
self.start_message = message
self.start_success = success
self.start_event.set()
def run(self):
"""Connect to APRS and listen for data."""
self.ais.set_filter(self.server_filter)
try:
_LOGGER.info(
"Opening connection to %s with callsign %s", self.host, self.callsign
)
self.ais.connect()
self.start_complete(
True, f"Connected to {self.host} with callsign {self.callsign}."
)
self.ais.consumer(callback=self.rx_msg, immortal=True)
except (AprsConnectionError, LoginError) as err:
self.start_complete(False, str(err))
except OSError:
_LOGGER.info(
"Closing connection to %s with callsign %s", self.host, self.callsign
)
def stop(self):
"""Close the connection to the APRS network."""
self.ais.close()
def rx_msg(self, msg: dict):
"""Receive message and process if position."""
_LOGGER.debug("APRS message received: %s", str(msg))
if msg[ATTR_FORMAT] in MSG_FORMATS:
dev_id = slugify(msg[ATTR_FROM])
lat = msg[ATTR_LATITUDE]
lon = msg[ATTR_LONGITUDE]
attrs = {}
if ATTR_POS_AMBIGUITY in msg:
pos_amb = msg[ATTR_POS_AMBIGUITY]
try:
attrs[ATTR_GPS_ACCURACY] = gps_accuracy((lat, lon), pos_amb)
except ValueError:
_LOGGER.warning(
"APRS message contained invalid posambiguity: %s", str(pos_amb)
)
for attr in [ATTR_ALTITUDE, ATTR_COMMENT, ATTR_COURSE, ATTR_SPEED]:
if attr in msg:
attrs[attr] = msg[attr]
self.see(dev_id=dev_id, gps=(lat, lon), attributes=attrs)
|
import { tuple } from './tuple';
import { deg, em, percent, px, rad, rem, turn, viewHeight, viewWidth } from 'csx';
export const cssNumberTransforms = tuple('percent', 'deg', 'em', 'px', 'rad', 'rem', 'vh', 'vw', 'turn');
export type CSSNumberTransform = (typeof cssNumberTransforms)[number]
export class CSSNumber extends Number {
constructor(value: any) {
super(parseInt(value));
}
/**
* Returns the number with a suffix of %
*/
toPercent = (): string => percent(this.valueOf()) as any;
/**
* Returns the number with a suffix of deg
*/
toDeg = (): string => deg(this.valueOf()) as any;
/**
* Returns the number with a suffix of em
*/
toEm = (): string => em(this.valueOf()) as any;
/**
* Returns the number with a suffix of px
*/
toPx = (): string => px(this.valueOf()) as any;
/**
* Returns the number with a suffix of rad
*/
toRad = (): string => rad(this.valueOf()) as any;
/**
* Returns the number with a suffix of rem
*/
toRem = (): string => rem(this.valueOf()) as any;
/**
* Returns the number with a suffix of vh
*/
toViewHeight = (): string => viewHeight(this.valueOf()) as any;
/**
* Returns the number with a suffix of vw
*/
toViewWidth = (): string => viewWidth(this.valueOf()) as any;
/**
* Returns the number with a suffix of turn
*/
toTurn = (): string => turn(this.valueOf()) as any;
}
|
# -*- coding: utf-8 -*-
from sqlalchemy import UniqueConstraint
from sqlalchemy.sql.expression import func
from nitrate import db
from nitrate.auth.models import User
from nitrate.plans.models import Plan
from nitrate.cases.models import Case
from nitrate.management.models import Build
run_env_value_association = db.Table(
'nitrate_run_env_value_association',
db.Column('run_id', db.Integer,
db.ForeignKey('nitrate_runs.id'), nullable=False),
db.Column('env_value_id', db.Integer,
db.ForeignKey('nitrate_env_values.id'), nullable=False),
UniqueConstraint('run_id', 'env_value_id'),
)
run_tag_association = db.Table('nitrate_run_tag_association',
db.Column('tag_id', db.Integer,
db.ForeignKey('nitrate_tags.id'), nullable=False),
db.Column('run_id', db.Integer,
db.ForeignKey('nitrate_runs.id'), nullable=False),
UniqueConstraint('tag_id', 'run_id'),
)
class Run(db.Model):
__tablename__ = 'nitrate_runs'
id = db.Column(db.Integer, primary_key=True)
summary = db.Column(db.String(255), nullable=False)
notes = db.Column(db.Text, nullable=False, default='')
estimated_time = db.Column(db.String(30), nullable=False, default=0)
start_date = db.Column(db.DateTime, nullable=False, index=True)
stop_date = db.Column(db.DateTime, nullable=False, index=True)
plan_id = db.Column(db.Integer, db.ForeignKey(Plan.id), nullable=False)
plan = db.relationship('Plan', backref=db.backref('runs', lazy='dynamic'))
build_id = db.Column(db.Integer, db.ForeignKey(Build.id), nullable=False)
build = db.relationship('Build',
backref=db.backref('runs', lazy='dynamic'))
manager_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=False)
manager = db.relationship('User',
backref=db.backref('my_managed_runs', lazy='dynamic'))
default_tester_id = db.Column(db.Integer, db.ForeignKey(User.id),
nullable=False)
default_tester = db.relationship('User',
backref=db.backref('my_runs', lazy='dynamic'))
env_values = db.relationship('EnvValue',
secondary=run_env_value_association,
backref=db.backref('runs', lazy='dynamic'))
tags = db.relationship('Tag',
secondary=run_tag_association,
backref=db.backref('runs', lazy='dynamic'))
created_on = db.Column(db.DateTime, nullable=False)
updated_on = db.Column(db.DateTime, nullable=False)
CASE_RUN_COMPLETE_STATUSS = ('PASSED', 'ERROR', 'FAILED', 'WAIVED')
CASE_RUN_FAILURE_STATUSS = ('ERROR', 'FAILED')
CASE_RUN_IDLE_STATUSS = ('IDLE',)
class CaseRunStatus(db.Model):
__tablename__ = 'nitrate_case_run_statuss'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(60), unique=True, nullable=False, default='')
description = db.Column(db.Text, nullable=False, default='')
auto_blinddown = db.Column(db.Boolean, nullable=False, default=True)
created_on = db.Column(db.DateTime, nullable=False)
updated_on = db.Column(db.DateTime, nullable=False)
class CaseRun(db.Model):
__tablename__ = 'nitrate_case_runs'
id = db.Column(db.Integer, primary_key=True)
assignee_id = db.Column(db.Integer, db.ForeignKey(User.id), nullable=True)
assignee = db.relationship(
'User', backref=db.backref('case_runs_assigned_to_me', lazy='dynamic'))
tested_by_id = db.Column(db.Integer, db.ForeignKey(User.id),
nullable=False)
tested_by = db.relationship(
'User', backref=db.backref('case_runs_tested_by_me', lazy='dynamic'))
case_text_version = db.Column(db.Integer, nullable=False)
running_date = db.Column(db.DateTime, nullable=False)
close_date = db.Column(db.DateTime, nullable=False)
notes = db.Column(db.Text, nullable=False, default='')
run_id = db.Column(db.Integer, db.ForeignKey(Run.id), nullable=False)
run = db.relationship('Run',
backref=db.backref('case_runs', lazy='dynamic'))
case_id = db.Column(db.Integer, db.ForeignKey(Case.id), nullable=False)
case = db.relationship('Case',
backref=db.backref('case_runs', lazy='dynamic'))
status_id = db.Column(db.Integer, db.ForeignKey(CaseRunStatus.id),
nullable=False)
status = db.relationship('CaseRunStatus',
backref=db.backref('case_runs', lazy='dynamic'))
build_id = db.Column(db.Integer, db.ForeignKey(Build.id), nullable=False)
build = db.relationship('Build',
backref=db.backref('case_runs', lazy='dynamic'))
created_on = db.Column(db.DateTime, nullable=False)
updated_on = db.Column(db.DateTime, nullable=False)
|
using Microsoft.Extensions.Localization;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using ObisoftWebCore.Models;
namespace ObisoftWebCore.Models.HomeViewModels
{
public class IndexViewModel
{
public virtual IEnumerable<ProductType> Types { get; set; }
public virtual IEnumerable<Product> Products { get; set; }
}
}
|
/*
* 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.jackrabbit.oak.segment;
import static com.google.common.collect.Lists.newArrayList;
import static org.apache.jackrabbit.oak.plugins.memory.MultiBinaryPropertyState.binaryPropertyFromBlob;
import static org.apache.jackrabbit.oak.segment.DefaultSegmentWriterBuilder.defaultSegmentWriterBuilder;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.apache.jackrabbit.oak.api.Blob;
import org.apache.jackrabbit.oak.api.CommitFailedException;
import org.apache.jackrabbit.oak.segment.file.FileStore;
import org.apache.jackrabbit.oak.segment.file.GCNodeWriteMonitor;
import org.apache.jackrabbit.oak.segment.file.tar.GCGeneration;
import org.apache.jackrabbit.oak.spi.commit.CommitInfo;
import org.apache.jackrabbit.oak.spi.commit.EmptyHook;
import org.apache.jackrabbit.oak.spi.gc.GCMonitor;
import org.apache.jackrabbit.oak.spi.state.ChildNodeEntry;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.apache.jackrabbit.oak.spi.state.NodeStore;
import org.jetbrains.annotations.NotNull;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Random;
public class CheckpointCompactorTestUtils {
private CheckpointCompactorTestUtils() {
}
public static void checkGeneration(NodeState node, GCGeneration gcGeneration) {
assertTrue(node instanceof SegmentNodeState);
assertEquals(gcGeneration, ((SegmentNodeState) node).getRecordId().getSegmentId().getGcGeneration());
for (ChildNodeEntry cne : node.getChildNodeEntries()) {
checkGeneration(cne.getNodeState(), gcGeneration);
}
}
public static NodeState getCheckpoint(NodeState superRoot, String name) {
NodeState checkpoint = superRoot
.getChildNode("checkpoints")
.getChildNode(name)
.getChildNode("root");
assertTrue(checkpoint.exists());
return checkpoint;
}
public static void assertSameStableId(NodeState node1, NodeState node2) {
assertTrue(node1 instanceof SegmentNodeState);
assertTrue(node2 instanceof SegmentNodeState);
assertEquals("Nodes should have the same stable ids",
((SegmentNodeState) node1).getStableId(),
((SegmentNodeState) node2).getStableId());
}
public static void assertSameRecord(NodeState node1, NodeState node2) {
assertTrue(node1 instanceof SegmentNodeState);
assertTrue(node2 instanceof SegmentNodeState);
assertEquals("Nodes should have been deduplicated",
((SegmentNodeState) node1).getRecordId(),
((SegmentNodeState) node2).getRecordId());
}
@NotNull
public static CheckpointCompactor createCompactor(@NotNull FileStore fileStore, @NotNull GCGeneration generation) {
SegmentWriter writer = defaultSegmentWriterBuilder("c")
.withGeneration(generation)
.build(fileStore);
return new CheckpointCompactor(
GCMonitor.EMPTY,
fileStore.getReader(),
writer,
fileStore.getBlobStore(),
GCNodeWriteMonitor.EMPTY);
}
public static void addTestContent(@NotNull String parent, @NotNull NodeStore nodeStore, int binPropertySize)
throws CommitFailedException, IOException {
NodeBuilder rootBuilder = nodeStore.getRoot().builder();
NodeBuilder parentBuilder = rootBuilder.child(parent);
parentBuilder.setChildNode("a").setChildNode("aa").setProperty("p", 42);
parentBuilder.getChildNode("a").setChildNode("bb").setChildNode("bbb");
parentBuilder.setChildNode("b").setProperty("bin", createBlob(nodeStore, binPropertySize));
parentBuilder.setChildNode("c").setProperty(binaryPropertyFromBlob("bins", createBlobs(nodeStore, 42, 43, 44)));
nodeStore.merge(rootBuilder, EmptyHook.INSTANCE, CommitInfo.EMPTY);
}
public static Blob createBlob(NodeStore nodeStore, int size) throws IOException {
byte[] data = new byte[size];
new Random().nextBytes(data);
return nodeStore.createBlob(new ByteArrayInputStream(data));
}
public static List<Blob> createBlobs(NodeStore nodeStore, int... sizes) throws IOException {
List<Blob> blobs = newArrayList();
for (int size : sizes) {
blobs.add(createBlob(nodeStore, size));
}
return blobs;
}
}
|
// ----------------------------------------------------------------------------------
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------
#nullable enable
namespace DurableTask.Core.Command
{
using Newtonsoft.Json;
/// <summary>
/// Defines a set of base properties for an orchestrator action.
/// </summary>
[JsonConverter(typeof(OrchestrationActionConverter))]
public abstract class OrchestratorAction
{
/// <summary>
/// The task ID associated with this orchestrator action.
/// </summary>
public int Id { get; set; }
/// <summary>
/// The type of the orchestrator action.
/// </summary>
public abstract OrchestratorActionType OrchestratorActionType { get; }
}
}
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyTitle("Video2Gif")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Video2Gif")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("6bacbb0b-476a-47f8-a392-dada66c403e4")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Plugin.Parse.V8Unpack20")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("pbazeliuk.com")]
[assembly: AssemblyProduct("Plugin.Parse.V8Unpack20")]
[assembly: AssemblyCopyright("Copyright © Petro Bazeliuk 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e2467890-f768-4183-a69b-0ceb0eb3f72c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
import { Routes, RouterModule } from '@angular/router';
import { DashboardComponent } from './components/dashboard/dashboard.component';
import { ReportComponent } from './components/report/report.component';
import { ReportDetailComponent } from './components/reportDetail/report-detail.component';
import { TopComponent } from './components/top/top.component';
import { ProfileComponent } from './components/profile/profile.component';
import { MainComponent } from './components/main/main.component';
import { DetailComponent } from './components/detail/detail.component';
import { UserComponent } from './components/user/user.component';
const appRoutes: Routes = [
// {
// path: '',
// redirectTo: '/dashboard',
// pathMatch: 'full'
// },
{
path: '',
component: MainComponent,
pathMatch: 'full'
},
{
path: 'top',
component: TopComponent
},
{
path: 'main',
component: MainComponent
},
{
path: 'detail/:id',
component: DetailComponent
},
{
path: 'user/:id',
component: UserComponent
},
{
path: 'report',
component: ReportComponent
},
{
path: 'report-detail/:id',
component: ReportDetailComponent
},
{
path: 'dashboard',
component: DashboardComponent
},
{
path: 'profile',
component: ProfileComponent
}
];
export const routing = RouterModule.forRoot(appRoutes, { useHash: true });
|
/**
* Profile repository module.
*
* @author [email protected]
*/
define(["angular", "angular-resource"], function (angular, ngResource) {
var profileRepositoryModule = angular.module("profileRepositoryModule", ["ngResource"]);
profileRepositoryModule.factory("profileRepository", ["$resource", function ($resource) {
var apiHost = "http://localhost:8080/spastructure-api";
return {
findProfileByProfileId: function (profileId) {
var profileResource = $resource(apiHost + "/api/v1/profiles/:id");
return profileResource.get({
id: profileId
});
},
findProfile: function (tokenData, successHandler, errorHandler) {
var profileResource = $resource(apiHost + "/api/v1/profiles", {}, {
findProfile: {
method: "GET",
headers: {
"token_data": tokenData
}
}
});
return profileResource.findProfile(successHandler, errorHandler);
}
};
}]);
return profileRepositoryModule;
});
|
from osmviz.animation import SimViz, TrackingViz, Simulation
from osmviz.manager import PygameImageManager, PILImageManager, OSMManager
import pygame
import PIL.Image as Image
Inf = float('inf')
def find_bounds(route):
min_time=Inf
max_time=-Inf
min_lat=min_lon=Inf
max_lat=max_lon=-Inf
for lat,lon,time in route:
min_time = min(min_time,time)
max_time = max(max_time,time)
min_lat = min(min_lat,lat)
min_lon = min(min_lon,lon)
max_lat = max(max_lat,lat)
max_lon = max(max_lon,lon)
return (min_time,max_time),(min_lat,max_lat,min_lon,max_lon)
def test_sim( route, zoom, image="images/train.png" ):
time_window,bbox = find_bounds(route)
def getLL(time):
if time <= time_window[0]:
return route[0][:2]
elif time > time_window[1]:
return route[-1][:2]
for (lat1,lon1,time1),(lat2,lon2,time2) in zip(route[:-1],route[1:]):
if time1 < time <= time2:
break
frac = (time-time1) / (time2-time1)
lat = lat1 + frac * (lat2-lat1)
lon = lon1 + frac * (lon2-lon1)
return lat,lon
viz = TrackingViz("Test Train",
image,
getLL,
time_window,
bbox,
1);
sim = Simulation([viz],[],0)
sim.run(speed=0,refresh_rate=0.1,osmzoom=zoom,windowsize=(600,600))
def test_sim_one():
begin_ll = 45+46.0/60 , -(68+39.0/60)
end_ll = 30+3.0/60 , -(118+15.0/60)
route = [ begin_ll+(0,),
end_ll+(100,) ]
test_sim(route,6)
def test_pil():
imgr = PILImageManager('RGB')
osm = OSMManager(image_manager=imgr)
image,bnds = osm.createOSMImage( (30,35,-117,-112), 9 )
wh_ratio = float(image.size[0]) / image.size[1]
image2 = image.resize( (int(800*wh_ratio),800), Image.ANTIALIAS )
del image
image2.show()
if __name__ == '__main__':
test_sim_one()
test_pil()
|
import CRUDExtend from '../extends/crud'
class CustomersEndpoint extends CRUDExtend {
constructor(endpoint) {
super(endpoint)
this.endpoint = 'customers'
this.sendToken = (tokenRequestBody, headers = {}) =>
this.request.send(
`${this.endpoint}/tokens`,
'POST',
tokenRequestBody,
null,
{
...headers
}
)
}
TokenViaPassword(email, password, headers) {
const body = {
type: 'token',
authentication_mechanism: 'password',
email,
password
}
return this.sendToken(body, headers)
}
TokenViaOIDC(code, redirectUri, codeVerifier, headers) {
const body = {
type: 'token',
authentication_mechanism: 'oidc',
oauth_authorization_code: code,
oauth_redirect_uri: redirectUri,
oauth_code_verifier: codeVerifier
}
return this.sendToken(body, headers)
}
Token(email, password) {
return this.TokenViaPassword(email, password)
}
}
export default CustomersEndpoint
|
/*
* Copyright (C) 2011 The Guava 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
*
* 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 com.google.common.hash;
import com.google.common.annotations.Beta;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
/**
* An object which can receive a stream of primitive values.
*
* @author Kevin Bourrillion
* @since 12.0 (in 11.0 as {@code Sink})
*/
@Beta
@CanIgnoreReturnValue
public interface PrimitiveSink {
/**
* Puts a byte into this sink.
*
* @param b a byte
* @return this instance
*/
PrimitiveSink putByte(byte b);
/**
* Puts an array of bytes into this sink.
*
* @param bytes a byte array
* @return this instance
*/
PrimitiveSink putBytes(byte[] bytes);
/**
* Puts a chunk of an array of bytes into this sink. {@code bytes[off]} is the first byte written,
* {@code bytes[off + len - 1]} is the last.
*
* @param bytes a byte array
* @param off the start offset in the array
* @param len the number of bytes to write
* @return this instance
* @throws IndexOutOfBoundsException if {@code off < 0} or {@code off + len > bytes.length} or
* {@code len < 0}
*/
PrimitiveSink putBytes(byte[] bytes, int off, int len);
/**
* Puts the remaining bytes of a byte buffer into this sink. {@code bytes.position()} is the first
* byte written, {@code bytes.limit() - 1} is the last. The position of the buffer will be equal
* to the limit when this method returns.
*
* @param bytes a byte buffer
* @return this instance
* @since 23.0
*/
PrimitiveSink putBytes(ByteBuffer bytes);
/** Puts a short into this sink. */
PrimitiveSink putShort(short s);
/** Puts an int into this sink. */
PrimitiveSink putInt(int i);
/** Puts a long into this sink. */
PrimitiveSink putLong(long l);
/** Puts a float into this sink. */
PrimitiveSink putFloat(float f);
/** Puts a double into this sink. */
PrimitiveSink putDouble(double d);
/** Puts a boolean into this sink. */
PrimitiveSink putBoolean(boolean b);
/** Puts a character into this sink. */
PrimitiveSink putChar(char c);
/**
* Puts each 16-bit code unit from the {@link CharSequence} into this sink.
*
* <p><b>Warning:</b> This method will produce different output than most other languages do when
* running on the equivalent input. For cross-language compatibility, use {@link #putString},
* usually with a charset of UTF-8. For other use cases, use {@code putUnencodedChars}.
*
* @since 15.0 (since 11.0 as putString(CharSequence))
*/
PrimitiveSink putUnencodedChars(CharSequence charSequence);
/**
* Puts a string into this sink using the given charset.
*
* <p><b>Warning:</b> This method, which reencodes the input before processing it, is useful only
* for cross-language compatibility. For other use cases, prefer {@link #putUnencodedChars}, which
* is faster, produces the same output across Java releases, and processes every {@code char} in
* the input, even if some are invalid.
*/
PrimitiveSink putString(CharSequence charSequence, Charset charset);
}
|
<?php
require_once '../../csrest_clients.php';
$wrap = new CS_REST_Clients('Your clients ID', 'Your API Key');
$result = $wrap->set_basics(array(
'CompanyName' => 'Clients company name',
'ContactName' => 'Clients contact name',
'EmailAddress' => 'Clients email',
'Country' => 'Clients country',
'Timezone' => 'Clients timezone'
));
echo "Result of PUT /api/v3/clients/{id}/setbasics\n<br />";
if($result->was_successful()) {
echo "Updated with Code ".$result->http_status_code;
} else {
echo 'Failed with code '.$result->http_status_code."\n<br /><pre>";
var_dump($result->response);
echo '</pre>';
}
|
"""
Django settings for PortfolioProject project.
Generated by 'django-admin startproject' using Django 1.8.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'n1t78ht)d)b7$r07xukio9c*mzs=yz7n&s8%gwj!r5y&fwh6ih'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'CaseStudyApp',
'sorl.thumbnail',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'PortfolioProject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'PortfolioProject/templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'PortfolioProject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Denver'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
THUMBNAIL_DEBUG = True
|
#include "impl/SerpMaterialListener.h"
MaterialListener::MaterialListener()
{
mBlackMat = Ogre::MaterialManager::getSingleton().create("mBlack", "Internal");
mBlackMat->getTechnique(0)->getPass(0)->setDiffuse(0,0,0,0);
mBlackMat->getTechnique(0)->getPass(0)->setSpecular(0,0,0,0);
mBlackMat->getTechnique(0)->getPass(0)->setAmbient(0,0,0);
mBlackMat->getTechnique(0)->getPass(0)->setSelfIllumination(0,0,0);
}
Ogre::Technique* MaterialListener::handleSchemeNotFound(unsigned short, const Ogre::String& schemeName,
Ogre::Material*, unsigned short, const Ogre::Renderable*)
{
if (schemeName == "glow")
{
return mBlackMat->getTechnique(0);
}
return 0;
}
|
#!/usr/bin/env python
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2009,2010,2011,2012,2013,2014,2015,2016 Contributor
#
# 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.
"""Module for testing the search observed mac command."""
import unittest
if __name__ == "__main__":
import utils
utils.import_depends()
from brokertest import TestBrokerCommand
class TestSearchObservedMac(TestBrokerCommand):
def testswitch(self):
command = ["search_observed_mac",
"--network_device=ut01ga2s01.aqd-unittest.ms.com"]
out = self.commandtest(command)
self.matchoutput(out, "ut01ga2s01.aqd-unittest.ms.com,1,02:02:04:02:06:cb,", command)
self.matchoutput(out, "ut01ga2s01.aqd-unittest.ms.com,2,02:02:04:02:06:cc,", command)
self.matchclean(out, "ut01ga2s02.aqd-unittest.ms.com", command)
def testmac(self):
command = ["search_observed_mac", "--mac=02:02:04:02:06:cb"]
out = self.commandtest(command)
self.matchoutput(out, "ut01ga2s01.aqd-unittest.ms.com,1,02:02:04:02:06:cb,", command)
self.matchclean(out, "02:02:04:02:06:cc", command)
self.matchclean(out, "ut01ga2s02.aqd-unittest.ms.com", command)
def testall(self):
command = ["search_observed_mac", "--mac=02:02:04:02:06:cb",
"--port=1", "--network_device=ut01ga2s01.aqd-unittest.ms.com"]
out = self.commandtest(command)
self.matchoutput(out, "ut01ga2s01.aqd-unittest.ms.com,1,02:02:04:02:06:cb,", command)
self.matchclean(out, "02:02:04:02:06:cc", command)
self.matchclean(out, "ut01ga2s02.aqd-unittest.ms.com", command)
def testallnegative(self):
command = ["search_observed_mac", "--mac=02:02:04:02:06:cb",
"--port=2", "--network_device=ut01ga2s01.aqd-unittest.ms.com"]
self.noouttest(command)
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(TestSearchObservedMac)
unittest.TextTestRunner(verbosity=2).run(suite)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2014, Blue Box Group, Inc.
# Copyright 2014, Craig Tracey <[email protected]>
#
# 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 os
import traceback
from hashlib import md5
from jinja2 import Environment
UPSTART_TEMPLATE = """
start on {{ start_on }}
stop on {{ stop_on }}
{% if description -%}
description {{ description }}
{% endif -%}
{% if envs -%}
{% for env in envs %}
env {{ env }}
{% endfor %}
{% endif -%}
{% if prestart_script -%}
pre-start script
{{ prestart_script }}
end script
{% endif -%}
{% if respawn -%}
respawn
{% endif -%}
exec start-stop-daemon --start --chuid {{ user }} {{ pidfile }} --exec {{ cmd }} {{ args }}
"""
def main():
module = AnsibleModule(
argument_spec=dict(
name=dict(default=None, required=True),
cmd=dict(default=None, required=True),
args=dict(default=None),
user=dict(default=None, required=True),
config_dirs=dict(default=None),
config_files=dict(default=None),
description=dict(default=None),
envs=dict(default=None, required=False, type='list'),
state=dict(default='present'),
start_on=dict(default='runlevel [2345]'),
stop_on=dict(default='runlevel [!2345]'),
prestart_script=dict(default=None),
respawn=dict(default=True),
path=dict(default=None),
pidfile=dict(default=None)
)
)
try:
changed = False
service_path = None
if not module.params['path']:
service_path = '/etc/init/%s.conf' % module.params['name']
else:
service_path = module.params['path']
symlink = os.path.join('/etc/init.d/', module.params['name'])
if module.params['state'] == 'absent':
if os.path.exists(service_path):
os.remove(service_path)
changed = True
if os.path.exists(symlink):
os.remove(symlink)
changed = True
if not changed:
module.exit_json(changed=False, result="ok")
else:
module.exit_json(changed=True, result="changed")
pidfile = ''
if module.params['pidfile'] and len(module.params['pidfile']):
pidfile = '--make-pidfile --pidfile %s' % module.params['pidfile']
args = ''
if module.params['args'] or module.params['config_dirs'] or \
module.params['config_files']:
args = '-- '
if module.params['args']:
args += module.params['args']
if module.params['config_dirs']:
for directory in module.params['config_dirs'].split(','):
args += '--config-dir %s ' % directory
if module.params['config_files']:
for filename in module.params['config_files'].split(','):
args += '--config-file %s ' % filename
template_vars = module.params
template_vars['pidfile'] = pidfile
template_vars['args'] = args
env = Environment().from_string(UPSTART_TEMPLATE)
rendered_service = env.render(template_vars)
if os.path.exists(service_path):
file_hash = md5(open(service_path, 'rb').read()).hexdigest()
template_hash = md5(rendered_service).hexdigest()
if file_hash == template_hash:
module.exit_json(changed=False, result="ok")
with open(service_path, "w") as fh:
fh.write(rendered_service)
if not os.path.exists(symlink):
os.symlink('/lib/init/upstart-job', symlink)
module.exit_json(changed=True, result="created")
except Exception as e:
formatted_lines = traceback.format_exc()
module.fail_json(msg="creating the service failed: %s" % (str(e)))
# this is magic, see lib/ansible/module_common.py
#<<INCLUDE_ANSIBLE_MODULE_COMMON>>
main()
|
from openerp.osv import fields, osv
class calendar_config_settings(osv.TransientModel):
_inherit = 'base.config.settings'
_columns = {
'google_cal_sync': fields.boolean("Show tutorial to know how to get my 'Client ID' and my 'Client Secret'"),
'cal_client_id': fields.char("Client_id"),
'cal_client_secret': fields.char("Client_key"),
'server_uri': fields.char('URI for tuto')
}
def set_calset(self,cr,uid,ids,context=None) :
params = self.pool['ir.config_parameter']
myself = self.browse(cr,uid,ids[0],context=context)
params.set_param(cr, uid, 'google_calendar_client_id', myself.cal_client_id or '', groups=['base.group_system'], context=None)
params.set_param(cr, uid, 'google_calendar_client_secret', myself.cal_client_secret or '', groups=['base.group_system'], context=None)
def get_default_all(self,cr,uid,ids,context=None):
params = self.pool.get('ir.config_parameter')
cal_client_id = params.get_param(cr, uid, 'google_calendar_client_id',default='',context=context)
cal_client_secret = params.get_param(cr, uid, 'google_calendar_client_secret',default='',context=context)
server_uri= "%s/google_account/authentication" % params.get_param(cr, uid, 'web.base.url',default="http://yourcompany.odoo.com",context=context)
return dict(cal_client_id=cal_client_id,cal_client_secret=cal_client_secret,server_uri=server_uri)
|
//= require quo
//= require hammer
//= require reconnecting-websocket
//= require angular
//= require angular-hammer
//= require app
//= require_tree .
|
'use strict';
const request = require('request');
const debug = require('debug')('flashmob-sms:send-sms');
module.exports = function sendSMS(param, cb) {
debug('Trying to send message...');
param.key = process.env.API_KEY;
param.long = 1;
request
.post('https://api.clockworksms.com/http/send.aspx')
.form(param)
.on('error', (err) => {
debug(err);
cb(err);
})
.on('response', () => {
debug('Sent message to ' + param.to + '.')
cb();
});
}
|
"""
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by
the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it
loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
"""
__author__ = 'Daniel'
class Solution:
def isHappy(self, n):
"""
Start with several simple cases and find the pattern.
:param n:
:rtype: bool
"""
nxt = 0
appeared = set()
while True:
nxt += (n%10)*(n%10)
n /= 10
if n == 0:
if nxt == 1:
return True
if nxt in appeared:
return False
appeared.add(nxt)
n = nxt
nxt = 0
|
/*
* Copyright (c) Dominick Baier, Brock Allen. All rights reserved.
* see license.txt
*/
using System.Web.Mvc;
using Thinktecture.IdentityModel.Authorization.Mvc;
namespace Thinktecture.AuthorizationServer.WebHost.Areas.Admin.Controllers
{
[ClaimsAuthorize(Constants.Actions.Configure, Constants.Resources.Server)]
public class ApplicationController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Manage()
{
return View();
}
public ActionResult Scopes()
{
return View();
}
public ActionResult Scope()
{
return View();
}
}
}
|
from multiprocessing import Process, Event
import time
import pygame
from pygame.locals import *
import math
from random import randint, randrange
import sys
sys.argv = ['openvibe']
class OVProcess(Process):
def __init__(self):
Process.__init__(self)
self.initialized = Event()
self.stop_asked = Event()
def initialize(self):
pass
def process(self):
pass
def uninitialize(self):
pass
def stop(self):
self.stop_asked.set()
def run(self):
self.initialize()
self.initialized.set()
while not self.stop_asked.is_set():
self.process()
self.uninitialize()
class StarField(OVProcess):
def __init__(self, num_stars, max_depth):
OVProcess.__init__(self)
self.pygame_is_running = False
self.screen = None
self.clock = None
self.num_stars = num_stars
self.max_depth = max_depth
self.stars = []
for i in range(self.num_stars):
star = [randrange(-25,25), randrange(-25,25), randrange(1, self.max_depth)]
self.stars.append(star)
def initialize(self):
pygame.init()
self.pygame_is_running = True
self.screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("3D Starfield Simulation")
self.clock = pygame.time.Clock()
def move_and_draw_stars(self):
origin_x = self.screen.get_width() / 2
origin_y = self.screen.get_height() / 2
for star in self.stars:
star[2] -= 0.19
if star[2] <= 0:
star[0] = randrange(-25,25)
star[1] = randrange(-25,25)
star[2] = self.max_depth
k = 128.0 / star[2]
x = int(star[0] * k + origin_x)
y = int(star[1] * k + origin_y)
if 0 <= x < self.screen.get_width() and 0 <= y < self.screen.get_height():
size = (1 - float(star[2]) / self.max_depth) * 5
shade = (1 - float(star[2]) / self.max_depth) * 255
self.screen.fill((shade,shade,shade),(x,y,size,size))
def process(self):
if self.pygame_is_running:
self.clock.tick(50)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
self.pygame_is_running = False
return
self.screen.fill((0,0,0))
self.move_and_draw_stars()
pygame.display.flip()
def uninitialize(self):
if self.pygame_is_running:
pygame.quit()
self.pygame_is_running = False
class MyOVBox(OVBox):
def __init__(self):
OVBox.__init__(self)
self.p = None
def initialize(self):
self.p = StarField(512, 32)
self.p.start()
def process(self):
pass
def uninitialize(self):
self.p.stop()
self.p.join()
if __name__ == '__main__':
box = MyOVBox()
|
#!/usr/bin/env python2
#
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# 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 os
import sys
from oslo.db.sqlalchemy import utils as db_utils
from subunit2sql.db import api
from subunit2sql.db import models
from subunit2sql import shell
from subunit2sql import write_subunit
DB_URI = 'mysql+pymysql://query:[email protected]/subunit2sql'
if len(sys.argv) == 2:
TEMPEST_PATH = sys.argv[1]
elif len(sys.argv) > 2:
TEMPEST_PATH = sys.argv[1]
DB_URI = sys.argv[2]
else:
TEMPEST_PATH = '/opt/stack/new/tempest'
def get_run_ids(session):
# TODO(mtreinish): Move this function into the subunit2sql db api
results = db_utils.model_query(models.Run, session).order_by(
models.Run.run_at.desc()).filter_by(fails=0).limit(10).all()
return map(lambda x: x.id, results)
def main():
shell.parse_args([])
shell.CONF.set_override('connection', DB_URI, group='database')
session = api.get_session()
run_ids = get_run_ids(session)
session.close()
preseed_path = os.path.join(TEMPEST_PATH, 'preseed-streams')
os.mkdir(preseed_path)
for run in run_ids:
with open(os.path.join(preseed_path, run + '.subunit'), 'w') as fd:
write_subunit.sql2subunit(run, fd)
if __name__ == '__main__':
main()
|
<?php
defined('ABSPATH') or die();
global $post,$dt_revealData, $detheme_config;
$thumb_size=$post->grid_thumb_size;
$attachment_id=get_post_thumbnail_id($post->id);
if ( is_string($thumb_size) ) {
preg_match_all('/\d+/', $thumb_size, $thumb_matches);
if(isset($thumb_matches[0])) {
$thumb_size = array();
if(count($thumb_matches[0]) > 1) {
$thumb_size[] = $thumb_matches[0][0]; // width
$thumb_size[] = $thumb_matches[0][1]; // height
} elseif(count($thumb_matches[0]) > 0 && count($thumb_matches[0]) < 2) {
$thumb_size[] = $thumb_matches[0][0]; // width
$thumb_size[] = $thumb_matches[0][0]; // height
} else {
$thumb_size = false;
}
}
}
if($thumb_size){
$p_img = wpb_resize($attachment_id, null, $thumb_size[0], $thumb_size[0], true);
$post->thumbnail = '<img src="'.$p_img['url'].'" class="img-responsive" alt="" />';
}
else{
$post->thumbnail = wp_get_attachment_image( $attachment_id, 'large', false, array('class' => 'img-responsive') );
}
$modal_effect = (empty($detheme_config['dt-select-modal-effects'])) ? 'md-effect-15' : $detheme_config['dt-select-modal-effects'];
$modalcontent = '<div id="modal_post_'.$post->id.'" class="md-modal '.$modal_effect.'">
<div class="md-content"><img src="#" rel="'.$post->thumbnail_data['p_img_large'][0].'" class="img-responsive" alt=""/>
<div class="md-description secondary_color_bg">'.$post->title.'</div>
<button class="md-close secondary_color_button"><i class="icon-cancel"></i></button>
</div>
</div>';
array_push($dt_revealData,$modalcontent);
?>
<div class="post-image-container">
<?php
if(!empty($post->thumbnail)):;?>
<div class="post-image">
<?php print $post->thumbnail;?>
</div>
<?php endif;?>
<div class="imgcontrol tertier_color_bg_transparent">
<div class="imgbuttons">
<a class="md-trigger btn icon-zoom-in secondary_color_button skin-light" data-modal="modal_post_<?php echo $post->id; ?>" onclick="return false;" href="<?php print $post->link; ?>"></a>
<a class="btn icon-link secondary_color_button skin-light" target="<?php echo $post->link_target;?>" href="<?php print $post->link; ?>"></a>
</div>
</div>
</div>
|
import os
import json
from src.models.entries.entry import Entry
from src.models.categories.category import Category
from src.models.categories.constants import CATEGORIES
def update_json(json_data_fullpath, entries=[]):
if not isinstance(entries, list):
raise Exception("Expecting a list as input")
if len(entries) == 0:
raise Exception("Entries list is empty")
if not isinstance(entries[0], Entry):
raise Exception("Expecting a list of Entry")
data = [e.json() for e in entries]
if os.path.exists(json_data_fullpath):
with open(json_data_fullpath, 'r') as f:
old_data = json.loads(f.read())
data.append(old_data)
open(json_data_fullpath, 'w').write(json.dumps(data, indent=2))
def parse_cvs(cvs_fullpath,
amount_col,
description_col,
date_col,
outcome_col,
category_col):
categories = [Category(name, keywords) for name, keywords in
CATEGORIES.items()]
lines = open(cvs_fullpath).readlines()
entries = []
for line in lines:
sign = 1
line = line.replace('\n', '')
data = line.split(',')
nominal_category = data[category_col]
best_ratio = 0.0
best_category = Category('Unknown')
for category in categories:
ratio = category.similarity(nominal_category)
if ratio > best_ratio:
best_ratio = ratio
best_category = category.name
if outcome_col >= 0:
if data[outcome_col].lower() == 'outcome':
sign = -1
entry = Entry(amount=data[amount_col],
category=best_category,
description=data[description_col],
date=data[date_col],
sign=sign)
entries.append(entry)
return entries
|
from django.db import models
import uuid as uuid
__author__ = 'jkonieczny'
class Genre(models.Model):
name = models.CharField(max_length=32)
def __str__(self):
return self.name
class Publisher(models.Model):
name = models.CharField(max_length=128)
def __str__(self):
return self.name
class Pricing(models.Model):
name = models.CharField(max_length=32)
initial = models.DecimalField(max_digits=5, decimal_places=2)
per_week = models.DecimalField(max_digits=5, decimal_places=2)
added = models.DateTimeField(auto_now_add=True)
closed = models.DateTimeField(null=True, blank=True)
@property
def enabled(self):
return self.closed is not None
def __str__(self):
return self.name
class Author(models.Model):
name = models.CharField(max_length=256)
born = models.DateField()
def __str__(self):
return self.name
class BookTitleManager(models.Manager):
def get_queryset(self):
return super(BookTitleManager, self).get_queryset()\
.extra(select={
'free_entities': "SELECT count(*) FROM books_bookentity "
"WHERE books_bookentity.title_id = books_booktitle.id and books_bookentity.quality > 0"
"and (SELECT count(*) FROM user_loan where book_id = books_bookentity.id) = 0",
'available_entities': "SELECT count(*) FROM books_bookentity "
"WHERE books_bookentity.title_id = books_booktitle.id and books_bookentity.quality > 0"
})
class BookTitle(models.Model):
objects = models.Manager()
data = BookTitleManager()
release = models.DateTimeField()
title = models.CharField(max_length=256)
genre = models.ManyToManyField('Genre')
author = models.ManyToManyField('Author')
def __str__(self):
return self.title
class BookEditionManager(models.Manager):
def get_queryset(self):
return super(BookEditionManager, self).select_related('title')
class BookEditionManager(models.Manager):
def get_queryset(self):
return super(BookEditionManager, self).get_queryset()\
.extra(select={
'free_entities': "SELECT count(*) FROM books_bookentity "
"WHERE books_bookentity.book_id = books_bookedition.id and books_bookentity.quality > 0"
"and (SELECT count(*) FROM user_loan where book_id = books_bookentity.id) = 0",
'available_entities': "SELECT count(*) FROM books_bookentity "
"WHERE books_bookentity.book_id = books_bookedition.id and books_bookentity.quality > 0"
})
class BookEdition(models.Model):
objects = BookEditionManager()
title = models.ForeignKey('BookTitle', null=False, related_name='publications')
publisher = models.ForeignKey('Publisher')
release = models.DateTimeField()
isbn = models.CharField(max_length=18)
pricing = models.ForeignKey('Pricing', null=True, blank=True)
def __str__(self):
return "[{0}] {1}".format(self.publisher.name, self.title.title)
class BookEntityManager(models.Manager):
def get_queryset(self):
return super(BookEntityManager, self).select_related('book', 'title')
class BookEntity(models.Model):
#objects = BookEntityManager()
book = models.ForeignKey('BookEdition', related_name='entities')
uuid = models.CharField(max_length=40)
title = models.ForeignKey('BookTitle')
quality = models.IntegerField()
|
var systemObject = {
run : function() {
this.content($('#navigation ul li a'));
this.pop();
this.runTimer(1);
},
content : function(obj) {
obj.live('click', function(e) {
var thisUrl = $(this).attr('href');
var thisTitle = $(this).attr('title');
systemObject.load(thisUrl);
window.history.pushState(null, thisTitle, thisUrl);
e.preventDefault();
});
},
pop : function() {
window.onpopstate = function() {
systemObject.load(location.pathname);
};
},
load : function(url) {
url = url === '/' ? '/ygwyg' : url;
jQuery.getJSON(url, { ajax : 1 }, function(data) {
jQuery.each(data, function(k, v) {
$('#' + k + ' section').fadeOut(200, function() {
$(this).replaceWith($(v).hide().fadeIn(200));
});
});
});
},
timer : function(n) {
setTimeout(function() {
$('#timer').html(n);
systemObject.runTimer(n);
}, 1000);
},
runTimer : function(n) {
var thisNumber = parseInt(n, 10) + 1;
systemObject.timer(thisNumber);
}
};
$(function() {
systemObject.run();
});
|
# -*- coding: utf-8 -*-
################################################################################
# Copyright (C) 2009 Johan Liebert, Mantycore, Hedger, Rusanon #
# < [email protected] ; http://orphereus.anoma.ch > #
# #
# This file is part of Orphereus, an imageboard engine. #
# #
# 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. #
################################################################################
from Orphereus.lib.base import *
from Orphereus.lib.miscUtils import *
from Orphereus.lib.constantValues import *
from Orphereus.lib.fileHolder import AngryFileHolder
from Orphereus.model import *
import cgi
import shutil
import base64, hashlib
import logging
log = logging.getLogger(__name__)
def processFile(file, thumbSize = 250, baseEncoded = False):
#log.debug('got file %s, dict: %s, test: %s' %(file, file.__dict__, isinstance(file, FieldStorageLike)))
if isinstance(file, cgi.FieldStorage) or isinstance(file, FieldStorageLike):
name = str(long(time.time() * 10 ** 7))
ext = file.filename.rsplit('.', 1)[:0:-1]
#ret: [FileHolder, PicInfo, Picture, Error]
# We should check whether we got this file already or not
# If we dont have it, we add it
if ext:
ext = ext[0].lstrip(os.sep).lower()
else: # Panic, no extention found
ext = ''
return [False, False, False, _("Can't post files without extension")]
# Make sure its something we want to have
extParams = Extension.getExtension(ext)
if not extParams or not extParams.enabled:
return [False, False, False, _(u'Extension "%s" is disallowed') % ext]
relativeFilePath = h.expandName('%s.%s' % (name, ext))
localFilePath = os.path.join(meta.globj.OPT.uploadPath, relativeFilePath)
targetDir = os.path.dirname(localFilePath)
#log.debug(localFilePath)
#log.debug(targetDir)
if not os.path.exists(targetDir):
os.makedirs(targetDir)
localFile = open(localFilePath, 'w+b')
if not baseEncoded:
shutil.copyfileobj(file.file, localFile)
else:
base64.decode(file.file, localFile)
localFile.seek(0)
md5 = hashlib.md5(localFile.read()).hexdigest()
file.file.close()
localFile.close()
fileSize = os.stat(localFilePath)[6]
picInfo = empty()
picInfo.localFilePath = localFilePath
picInfo.relativeFilePath = relativeFilePath
picInfo.fileSize = fileSize
picInfo.md5 = md5
picInfo.sizes = []
picInfo.extension = extParams
picInfo.animPath = None
picInfo.relationInfo = None
pic = Picture.getByMd5(md5)
if pic:
os.unlink(localFilePath)
picInfo.sizes = [pic.width, pic.height, pic.thwidth, pic.thheight]
picInfo.thumbFilePath = pic.thumpath
picInfo.relativeFilePath = pic.path
picInfo.localFilePath = os.path.join(meta.globj.OPT.uploadPath, picInfo.relativeFilePath)
return [False, picInfo, pic, False]
thumbFilePath = False
localThumbPath = False
try:
#log.debug('Testing: %s' %extParams.type)
if not extParams.type in ('image', 'image-jpg'):
# log.debug('Not an image')
thumbFilePath = extParams.path
picInfo.sizes = [None, None, extParams.thwidth, extParams.thheight]
elif extParams.type == 'image':
thumbFilePath = h.expandName('%ss.%s' % (name, ext))
else:
thumbFilePath = h.expandName('%ss.jpg' % (name))
localThumbPath = os.path.join(meta.globj.OPT.uploadPath, thumbFilePath)
picInfo.thumbFilePath = thumbFilePath
if not picInfo.sizes:
picInfo.sizes = Picture.makeThumbnail(localFilePath, localThumbPath, (thumbSize, thumbSize))
except:
os.unlink(localFilePath)
return [False, False, False, _(u"Broken picture. Maybe it is interlaced PNG?")]
return [AngryFileHolder((localFilePath, localThumbPath)), picInfo, False, False]
else:
return False
|
# ===============================================================================
# Copyright 2019 ross
#
# 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 requests
access_token_cookie = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1NTEyMDk0ODgsIm5iZiI6MTU1MTIwOTQ4OCwianRpI' \
'joiMjE2OWJlZWUtMmIwYy00NjEwLTk2NTgtY2U5OGNiM2YxY2Y3IiwiZXhwIjoxNTUzODAxNDg4LCJpZGVudGl0eSI' \
'6Impyb3NzIiwiZnJlc2giOmZhbHNlLCJ0eXBlIjoiYWNjZXNzIn0.y4Hx7PVEWUvam9_rYLU0TB5Bg7myWDw10EK7z' \
'hwvyZY'
def get_samples():
url = 'http://localhost:5002/api/v1/sample?all=True'
response = requests.get(url, cookies={'access_token_cookie': access_token_cookie})
if response.status_code == 200:
return response.json()
if __name__ == '__main__':
print(get_samples())
# ============= EOF =============================================
|
declare module 'image-size' {
export interface ISize {
width: number | undefined;
height: number | undefined;
orientation?: number;
type?: string;
}
export interface ISizeCalculationResult extends ISize {
images?: ISize[];
}
export function imageSize(input: Buffer | string): ISizeCalculationResult;
}
|
import click
import logging
import boto.dynamodb2
import boto.kms
from collections import defaultdict
from flotilla.cli.options import *
from flotilla.db import DynamoDbTables
from flotilla.client import FlotillaClientDynamo
logger = logging.getLogger('flotilla')
ELB_SCHEMES = ('internal', 'internet-facing')
HEALTH_CHECK_PROTOS = ('TCP', 'HTTP', 'HTTPS', 'SSL')
def validate_health_check(ctx, param, value):
if value is None:
return
if ':' not in value:
raise click.BadParameter('Must be PROTO:PORT (TCP:80, HTTP:80/)')
proto, port = value.split(':')
if proto not in HEALTH_CHECK_PROTOS:
raise click.BadParameter(
'Invalid proto: %s, valid options are %s' % (
proto, ', '.join(HEALTH_CHECK_PROTOS)))
if 'HTTP' in proto and '/' not in port:
raise click.BadParameter('HTTP check must include a path')
return value
@click.group()
def service_cmd(): # pragma: no cover
pass
@service_cmd.command(help='Configure a service.')
@click.option('--environment', type=click.STRING, envvar='FLOTILLA_ENV',
default=DEFAULT_ENVIRONMENT, help='Environment name.')
@click.option('--region', '-r', multiple=True, type=click.Choice(REGIONS),
envvar='FLOTILLA_REGION', default=DEFAULT_REGIONS,
help='Regions (multiple allowed).')
@click.option('--name', type=click.STRING, help='Service name.')
@click.option('--elb-scheme', type=click.Choice(ELB_SCHEMES),
help='ELB scheme.')
@click.option('--dns-name', type=click.STRING,
help='Custom DNS entry for service')
@click.option('--health-check', type=click.STRING,
callback=validate_health_check,
help='ELB health check target, http://goo.gl/6ue44c .')
@click.option('--instance-type', type=click.Choice(INSTANCE_TYPES),
help='Worker instance type.')
@click.option('--provision/--no-provision', default=None,
help='Disable automatic provisioning.')
@click.option('--instance-min', type=click.INT,
help='Minimum worker count.')
@click.option('--instance-max', type=click.INT,
help='Maximum worker count.')
@click.option('--kms-key', type=click.STRING,
help='KMS key for encrypting environment variables.')
@click.option('--coreos-channel', type=click.Choice(COREOS_CHANNELS),
help='Worker CoreOS channel.')
@click.option('--coreos-version', type=click.STRING,
help='Worker CoreOS version.')
@click.option('--public-ports', type=click.STRING, multiple=True,
help='Public ports, exposed by ELB. e.g. 80-http, 6379-tcp', )
@click.option('--private-ports', type=click.STRING, multiple=True,
help='Private ports, exposed to peers. e.g. 9300-tcp, 9200-tcp')
def service(environment, region, name, elb_scheme, dns_name, health_check,
instance_type, provision, instance_min, instance_max, kms_key,
coreos_channel, coreos_version, public_ports,
private_ports): # pragma: no cover
if not name:
logger.warn('Service not specified')
return
updates = get_updates(elb_scheme, dns_name, health_check, instance_type,
provision, instance_min, instance_max, kms_key,
coreos_channel, coreos_version, public_ports,
private_ports)
if not updates:
logger.warn('No updates to do!')
return
configure_service(environment, region, name, updates)
logger.info('Service %s updated in: %s', name, ', '.join(region))
def get_updates(elb_scheme, dns, health_check, instance_type, provision,
instance_min, instance_max, kms_key, coreos_channel,
coreos_version, public_ports, private_ports):
updates = {}
if elb_scheme:
updates['elb_scheme'] = elb_scheme
if dns:
updates['dns_name'] = dns
if health_check:
updates['health_check'] = health_check
if instance_type:
updates['instance_type'] = instance_type
if provision is not None:
updates['provision'] = provision
if instance_min is not None:
updates['instance_min'] = instance_min
if instance_max is not None:
updates['instance_max'] = instance_max
if kms_key:
updates['kms_key'] = kms_key
if coreos_channel:
updates['coreos_channel'] = coreos_channel
if coreos_version:
updates['coreos_version'] = coreos_version
if public_ports:
parsed_ports = {}
for public_port in public_ports:
try:
port, proto = public_port.split('-')
parsed_ports[int(port)] = proto.upper()
except:
continue
if parsed_ports:
updates['public_ports'] = parsed_ports
if private_ports:
parsed_ports = defaultdict(list)
for private_port in private_ports:
try:
port, proto = private_port.split('-')
parsed_ports[int(port)].append(proto.upper())
except:
continue
if parsed_ports:
updates['private_ports'] = dict(parsed_ports)
return updates
def configure_service(environment, regions, service_name, updates):
for region in regions:
dynamo = boto.dynamodb2.connect_to_region(region)
kms = boto.kms.connect_to_region(region)
tables = DynamoDbTables(dynamo, environment=environment)
tables.setup(['services'])
db = FlotillaClientDynamo(None, None, None, tables.services, None, None,
kms)
db.configure_service(service_name, updates)
|
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 25 14:30:29 2016
@author: alek
"""
import pickle
import cloudpickle
from tempfile import TemporaryFile
def pickleObj(fileName,obj):
with open(fileName,'w') as f:
cloudpickle.dump(obj,f)
def unpickleObj(fileName):
with open(fileName) as f:
return cloudpickle.load(f)
def pickleObjTemp(job,data):
outfile = TemporaryFile()
cloudpickle.dump([job,data],outfile)
outfile.seek(0)
return outfile
def unpickleObjTemp(outfile):
return cloudpickle.load(outfile)
#functions used to pickle a test_nodeEndpoints pickle
def createPickle(obj):
return cloudpickle.dumps(obj)
def unPickle(data):
return cloudpickle.loads(data)
#######################################
#functions used to create a server pickle
def createPickleServer(obj):
return cloudpickle.dumps(obj).decode('latin1')
def unPickleServer(data):
return cloudpickle.loads(data.encode('latin1'))
def pickleListServer(data_list):
new_list = []
for item in data_list:
new_list.append(item.pickle())
return new_list
def unPickleListServer(data_list):
new_list = []
for item in data_list:
new_list.append(unPickleServer(item))
return new_list
#########################################
def abc():
return 1+2+3+4
if __name__ == '__main__':
a = ('class','method','...',(1,2,3),abc)
fil = createPickle(a)
print ('data(fil): ', fil)
obj = unPickle(fil)
print ('obj: ',obj)
fil2 = createPickleServer(a)
print ('data(fil2) ', fil2)
obj2 = unPickleServer(fil2)
print ('obj: ', obj2)
|
#region License
// -----------------------------------------------------------------------------------------------------------
//
// Name: Todo.cs
//
// Copyright (c) 2016 - 2019 VisualPlus <https://darkbyte7.github.io/VisualPlus/>
// All Rights Reserved.
//
// -----------------------------------------------------------------------------------------------------------
//
// GNU General Public License v3.0 (GPL-3.0)
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
// EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
//
// 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/>.
//
// This file is subject to the terms and conditions defined in the file
// 'LICENSE.md', which should be in the root directory of the source code package.
//
// -----------------------------------------------------------------------------------------------------------
#endregion
#region Namespace
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using VisualPlus.Constants;
using VisualPlus.Utilities.Debugging;
#endregion
namespace VisualPlus.Attributes
{
/// <summary>Represents the <see cref="Todo" /> class for attributes.</summary>
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
[ClassInterface(ClassInterfaceType.None)]
[ComVisible(true)]
[DebuggerDisplay(DefaultConstants.DefaultDebuggerDisplay)]
[Serializable]
public class Todo : VisualAttribute
{
#region Static Fields
/// <summary>
/// Specifies the default value for the <see cref="Todo" />, that represents the current object. This
/// <see langword="static" /> field is read-only.
/// </summary>
public static readonly Todo Default = new Todo();
#endregion
#region Constructors and Destructors
/// <summary>Initializes a new instance of the <see cref="Todo" /> class.</summary>
/// <param name="description">The description text.</param>
public Todo(string description) : base(description)
{
}
/// <summary>Initializes a new instance of the <see cref="Todo" /> class.</summary>
public Todo()
{
}
#endregion
#region Public Methods and Operators
public override bool Equals(object obj)
{
if (obj == this)
{
return true;
}
switch (obj)
{
case Todo testAttribute:
{
bool equal;
// Validate the property's
if (testAttribute.Description.Equals(Description))
{
equal = true;
}
else
{
equal = false;
}
return equal;
}
default:
{
return false;
}
}
}
public override int GetHashCode()
{
return DescriptionValue.GetHashCode();
}
public override bool IsDefaultAttribute()
{
return Equals(Default);
}
public override string ToString()
{
if (Debugger.IsAttached)
{
return this.ToDebug("Description");
}
else
{
return base.ToString();
}
}
#endregion
}
}
|
'use strict';
var taskList = require('../controllers/tasklist'),
_ = require('lodash');
// The Package is passed automatically as first parameter
module.exports = function (Tasklist, app, auth, database) {
app.route('/tasklist').
get(auth.requiresLogin, taskList.all);
app.route('/queryTasklist/:query').
get(auth.requiresLogin, taskList.queryList);
// Create a new task
app.route('/newTask').
post(auth.requiresLogin, taskList.create);
// Retrieve tasks for the current user
app.route('/tasks/user/:userId').
all(auth.requiresLogin).
get(taskList.getTasksByUserId);
// Retrieve tasks for the requested team
app.route('/tasks/team/:teamId').
get(auth.requiresLogin, taskList.getTasksByTeamId);
// Retrieve tasks for this team's graph
app.route('/tasks/team/graph/:teamId').
get(auth.requiresLogin, taskList.getTeamTasksForGraph);
// Delete all tasks for this team
app.route('/tasks/deleteAll/:teamId').
get(auth.requiresLogin, taskList.deleteAllTasks);
// Connection to socket
Tasklist.io.of('/task').on('connection', function (socket) {
//console.log(socket);
if (_.isUndefined(app.get('teams'))) {
return;
}
console.log('joined in tasklist route');
var teamRoom = 'team:' + app.get('teams');
// Join the socket for this team
socket.join(teamRoom);
// Emit the new task to all team members
socket.on('newTask', function(taskData) {
Tasklist.io.of('/task').in(teamRoom).emit('newTask', {
data: taskData.data
}, console.log('after emit'));
});
});
};
|
#!/usr/bin/python
import os
import re
import sys
import traceback
import utils
import hooking
'''
after_vm_destroy:
return the original owner of the usb device
'''
HOOK_HOSTUSB_PATH = '/var/run/vdsm/hooks/hostusb-permissions'
def get_owner(devpath):
uid = pid = -1
content = ''
if not os.path.isfile(HOOK_HOSTUSB_PATH):
return uid, pid
f = file(HOOK_HOSTUSB_PATH, 'r')
for line in f:
if len(line) > 0 and line.split(':')[0] == devpath:
entry = line.split(':')
uid = entry[1]
pid = entry[2]
elif len(line) > 0:
content += line + '\n'
f.close()
if uid != -1:
f = file(HOOK_HOSTUSB_PATH, 'w')
f.writelines(content)
f.close()
return uid, pid
#!TODO:
# merge chown with before_vm_start.py
# maybe put it in hooks.py?
def chown(vendorid, productid):
# remove the 0x from the vendor and product id
devid = vendorid[2:] + ':' + productid[2:]
command = ['lsusb', '-d', devid]
retcode, out, err = utils.execCmd(command, sudo=False, raw=True)
if retcode != 0:
sys.stderr.write('hostusb: cannot find usb device: %s\n' % devid)
sys.exit(2)
devpath = '/dev/bus/usb/' + out[4:7] + '/' + out[15:18]
uid, gid = get_owner(devpath)
if uid == -1:
sys.stderr.write(
'hostusb after_vm_destroy: cannot find devpath: %s in file: %s\n' % (devpath, HOOK_HOSTUSB_PATH))
return
# we don't use os.chown because we need sudo
owner = str(uid) + ':' + str(gid)
command = ['/bin/chown', owner, devpath]
retcode, out, err = utils.execCmd(command, sudo=True, raw=True)
if retcode != 0:
sys.stderr.write('hostusb after_vm_destroy: error chown %s to %s, err = %s\n' % (devpath, owner, err))
sys.exit(2)
if os.environ.has_key('hostusb'):
try:
regex = re.compile('^0x[\d,A-F,a-f]{4}$')
for usb in os.environ['hostusb'].split('&'):
vendorid, productid = usb.split(':')
if len(regex.findall(vendorid)) != 1 or len(regex.findall(productid)) != 1:
sys.stderr.write(
'hostusb after_vm_destroy: bad input, expected 0x0000 format for vendor and product id, '
'input: %s:%s\n' % (
vendorid, productid))
sys.exit(2)
chown(vendorid, productid)
except:
sys.stderr.write('hostusb after_vm_destroy: [unexpected error]: %s\n' % traceback.format_exc())
sys.exit(2)
|
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Safely evaluate Python string literals without using eval()."""
import re
simple_escapes = {"a": "\a",
"b": "\b",
"f": "\f",
"n": "\n",
"r": "\r",
"t": "\t",
"v": "\v",
"'": "'",
'"': '"',
"\\": "\\"}
def escape(m):
all, tail = m.group(0, 1)
assert all.startswith("\\")
esc = simple_escapes.get(tail)
if esc is not None:
return esc
if tail.startswith("x"):
hexes = tail[1:]
if len(hexes) < 2:
raise ValueError("invalid hex string escape ('\\%s')" % tail)
try:
i = int(hexes, 16)
except ValueError:
raise ValueError("invalid hex string escape ('\\%s')" % tail) from None
else:
try:
i = int(tail, 8)
except ValueError:
raise ValueError("invalid octal string escape ('\\%s')" % tail) from None
return chr(i)
def evalString(s):
assert s.startswith("'") or s.startswith('"'), repr(s[:1])
q = s[0]
if s[:3] == q*3:
q = q*3
assert s.endswith(q), repr(s[-len(q):])
assert len(s) >= 2*len(q)
s = s[len(q):-len(q)]
return re.sub(r"\\(\'|\"|\\|[abfnrtv]|x.{0,2}|[0-7]{1,3})", escape, s)
def test():
for i in range(256):
c = chr(i)
s = repr(c)
e = evalString(s)
if e != c:
print(i, c, s, e)
if __name__ == "__main__":
test()
|
using System;
using Premotion.Mansion.Core;
using Premotion.Mansion.Core.Collections;
using Premotion.Mansion.Core.Scripting.TagScript;
using Premotion.Mansion.Core.Templating;
using Premotion.Mansion.Web.Controls.Providers;
namespace Premotion.Mansion.Web.Controls.Grid
{
/// <summary>
/// Implements a <see cref="ColumnFilter"/> using a Selectbox.
/// </summary>
public class SelectboxColumnFilter : ColumnFilter, IDataConsumerControl<DataProvider<Dataset>, Dataset>
{
#region Nested type: SelectboxColumnFilterFactoryTag
/// <summary>
/// Base class for <see cref="Premotion.Mansion.Web.Controls.Grid.SelectboxColumnFilter"/> factories.
/// </summary>
[ScriptTag(Constants.ControlTagNamespaceUri, "selectboxColumnFilter")]
public class SelectboxColumnFilterFactoryTag : ColumnFilterFactoryTag
{
#region Overrides of ScriptTag
/// <summary>
/// Create a <see cref="ColumnFilter"/> instance.
/// </summary>
/// <param name="context">The <see cref="IMansionWebContext"/>.</param>
/// <returns>Returns the created <see cref="ColumnFilter"/>.</returns>
protected override ColumnFilter Create(IMansionWebContext context)
{
return new SelectboxColumnFilter();
}
#endregion
}
#endregion
#region Overrides of ColumnFilter
/// <summary>
/// Renders the header of this column.
/// </summary>
/// <param name="context">The <see cref="IMansionWebContext"/>.</param>
/// <param name="templateService">The <see cref="ITemplateService"/>.</param>
/// <param name="dataset">The <see cref="Dataset"/> rendered in this column.</param>
protected override void DoRenderHeader(IMansionWebContext context, ITemplateService templateService, Dataset dataset)
{
using (templateService.Render(context, "GridControl" + GetType().Name))
{
foreach (var row in Retrieve(context).Rows)
{
using (context.Stack.Push("OptionProperties", row))
templateService.Render(context, "GridControl" + GetType().Name + "Option").Dispose();
}
}
}
#endregion
#region Implementation of IDataConsumerControl<in DataProvider<Dataset>,Dataset>
/// <summary>
/// Sets the <paramref name="dataProvider"/> for this control.
/// </summary>
/// <param name="dataProvider">The <see cref="DataProvider{TDataType}"/> which to set.</param>
public void SetDataProvider(DataProvider<Dataset> dataProvider)
{
// validate arguments
if (dataProvider == null)
throw new ArgumentNullException("dataProvider");
if (provider != null)
throw new InvalidOperationException("The data provider has already been set, cant override it.");
// set the provider
provider = dataProvider;
}
/// <summary>
/// Gets the data bound to this control.
/// </summary>
/// <param name="context">The <see cref="IMansionContext"/>.</param>
/// <returns>Returns the data.</returns>
private Dataset Retrieve(IMansionContext context)
{
// validate arguments
if (context == null)
throw new ArgumentNullException("context");
// check if no provider was set
if (provider == null)
throw new InvalidOperationException("No data provider was set.");
// return the data from the provider
return provider.Retrieve(context);
}
#endregion
#region Private Fields
private DataProvider<Dataset> provider;
#endregion
}
}
|
from __future__ import unicode_literals
from .manager import Manager
from .filesmanager import FilesManager
class Xero(object):
""" An ORM-like interface to the Xero API.
"""
OBJECT_LIST = (
"Attachments",
"Accounts",
"BankTransactions",
"BankTransfers",
"BrandingThemes",
"ContactGroups",
"Contacts",
"CreditNotes",
"Currencies",
"Employees",
"ExpenseClaims",
"Invoices",
"Items",
"Journals",
"ManualJournals",
"Organisations",
"Overpayments",
"Payments",
"Prepayments",
"Receipts",
"RepeatingInvoices",
"Reports",
"TaxRates",
"TrackingCategories",
"Users",
)
def __init__(self, credentials, unit_price_4dps=False):
# Iterate through the list of objects we support, for
# each of them create an attribute on our self that is
# the lower-case name of the object and attach it to an
# instance of a Manager object to operate on it
for name in self.OBJECT_LIST:
setattr(
self, name.lower(),
Manager(name, credentials, unit_price_4dps)
)
setattr(self, "filesAPI", Files(credentials))
class Files(object):
""" An ORM-like interface to the Xero Files API.
"""
OBJECT_LIST = (
"Associations",
"Files",
"Folders",
"Inbox",
)
def __init__(self, credentials):
# Iterate through the list of objects we support, for
# each of them create an attribute on our self that is
# the lower-case name of the object and attach it to an
# instance of a Manager object to operate on it
for name in self.OBJECT_LIST:
setattr(self, name.lower(), FilesManager(name, credentials))
|
#include "./GUI/Simple_window.h"
#include "./GUI/Graph.h"
#include <string>
#include <iostream>
#include <cmath>
using namespace Graph_lib;
int main()
try {
// draw a series of regular polygons from inside out: equilateral triangle,
// square, pentagon, etc.
Point tl {100, 100};
Simple_window win {tl, 600, 400, "Chapter 12 Ex 11"};
// degrees to radians => deg * PI / 180
constexpr double PI = 3.14159265;
const int X = win.x_max() / 2 - 50;
const int Y = win.y_max() / 2 - 50;
// Triangle
Polygon tri;
int alt = sin(60*PI/180) * 100;
tri.add(Point{X, Y + alt});
tri.add(Point{X + 50, Y});
tri.add(Point{X + 100, Y + alt});
tri.set_color(Color::red);
win.attach(tri);
// Square
Rectangle sqr {Point{X, Y}, 100, 100};
sqr.set_color(Color::green);
win.attach(sqr);
// Pentagon
Polygon pent;
int pr = 50 / sin(36*PI/180);
int px = 300;
int py = 200 - pr;
pent.add(Point{px, py});
px += sin(54*PI/180)*100;
py += cos(54*PI/180)*100;
pent.add(Point{px, py});
px -= cos(72*PI/180)*100;
py += sin(72*PI/180)*100;
pent.add(Point{px, py});
px -= 100;
pent.add(Point{px, py});
px -= cos(72*PI/180)*100;
py -= sin(72*PI/180)*100;
pent.add(Point{px, py});
pent.set_color(Color::blue);
win.attach(pent);
// Hexagon
Polygon hex;
int hx = 250;
int hy = 200 - pr;
int hr = cos(30*PI/180)*100;
hex.add(Point{hx, hy});
hex.add(Point{hx + 100, hy});
hex.add(Point{hx + 150, hy + hr});
hex.add(Point{hx + 100, hy + 2*hr});
hex.add(Point{hx, hy + 2*hr});
hex.add(Point{hx - 50, hy + hr});
hex.set_color(Color::black);
win.attach(hex);
// good enough..
win.wait_for_button();
}
catch(exception& e) {
cerr << "exception: " << e.what() << '\n';
return 1;
}
catch(...) {
cerr << "error\n";
return 2;
}
/* Compile command
g++ -w -Wall -std=c++11 GUI/Graph.cpp GUI/Window.cpp GUI/GUI.cpp GUI/Simple_window.cpp ex11_polygons.cpp `fltk-config --ldflags --use-images` -o a.out
*/
|
using UnityEngine;
using System.Collections;
/**
* Instead of detecting a collision between colliders, this shoots a ray and sees if it
* hits anything.
*
* This is useful for fast moving objects, such as bullets.
*/
//TODO add layer mask
public class BulletCollisionEvent : EventComponent {
public float m_Distance; //distance to shoot the ray - usually the speed of the object
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
RaycastHit hit;
if (Physics.Raycast (this.transform.position, this.transform.forward, out hit, m_Distance * Time.deltaTime)) {
TriggerActions(this.actions, hit.collider.gameObject);
this.enabled = false;
}
}
}
|
# -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright (c) 2017 ytdrk1980
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
|
class Solution(object):
def threeSumDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
numDict = {}
for i in xrange(len(nums)):
if numDict.has_key(nums[i]):
numDict[nums[i]].append(i)
else:
numDict[nums[i]] = [i]
# print numDict
result = []
for j in xrange(len(nums)):
for k in xrange(j+1, len(nums)):
complement = 0 - nums[j] - nums[k]
if numDict.has_key(complement):
if len(numDict[complement]) == 1:
if numDict[complement][0] != j and numDict[complement][0] != k:
result.append([nums[j], nums[k], complement])
elif len(numDict[complement]) == 2:
if not (nums[i] == 0 and nums[j] == 0):
result.append([nums[j], nums[k], complement])
else:
result.append([nums[j], nums[k], complement])
return result
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
numsSorted = sorted(nums)
result = []
i = 0
while i < len(numsSorted) - 2:
if i != 0 and numsSorted[i] == numsSorted[i-1]:
i += 1
continue
j, k = i+1, len(numsSorted) - 1
while j < k:
s = numsSorted[i] + numsSorted[j] + numsSorted[k]
if s == 0:
result.append([numsSorted[i], numsSorted[j], numsSorted[k]])
j += 1
k -= 1
while numsSorted[j] == numsSorted[j-1] and j < k:
j += 1
while numsSorted[k] == numsSorted[k+1] and j < k:
k -= 1
elif s < 0:
j += 1
while numsSorted[j] == numsSorted[j-1] and j < k:
j += 1
else:
k -= 1
while numsSorted[k] == numsSorted[k+1] and j < k:
k -= 1
i += 1
return result
if __name__ == '__main__':
nums = [-1,0,1,2,-1,-4]
s = Solution()
print s.threeSum(nums)
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace esdk_fc_v1r5_native_cs.DataType.VmModel
{
/// <summary>
/// 克隆虚拟机请求。
/// </summary>
public class CloneVmReq
{
/// <summary>
/// 【可选】虚拟机别名,长度[0,256]。
/// </summary>
public string name { get; set; }
/// <summary>
/// 【可选】虚拟机描述信息,长度[0,1024]。
/// </summary>
public string description { get; set; }
/// <summary>
/// 【可选】虚拟机组名称,长度为[0,1024],使用原则请参照“创建虚拟机”接口中group字段的描述。
/// </summary>
public string group { get; set; }
/// <summary>
/// <para>【可选】虚拟机所属,可以是集群Urn或主机Urn ,默认同原虚拟机或模板</para>
/// <para>若指定计算节点创建,则且只能在该计算节点上运行,如:“urn:sites:4D9D0815:clusters:79”。</para>
/// </summary>
public string location { get; set; }
/// <summary>
/// <para>【可选】是否与主机绑定;true:与主机绑定,false:不绑定主机</para>
/// <para>当location为hostUrn时有效UsbDevice;</para>
/// <para>若指定主机不位于集群下时系统自动将此属性处理为true;若主机位于集群下时默认为false。</para>
/// </summary>
public bool? isBindingHost { get; set; }
/// <summary>
/// 【可选】虚拟机配置,默认与模板或原虚拟机一致。
/// </summary>
public VmConfig vmConfig { get; set; }
/// <summary>
/// 【可选】操作系统信息。
/// </summary>
public OsOption osOptions { get; set; }
/// <summary>
/// 【可选】部署成VM还是模板,true: 模版,false:虚拟机(默认)。
/// </summary>
public bool? isTemplate { get; set; }
/// <summary>
/// 【可选】是否自动启动,isTemplate为true时,此参数失效,true:自动启动(默认),false:不自动启动。
/// </summary>
public bool? autoBoot { get; set; }
/// <summary>
/// <para>【可选】是否为链接克隆虚拟机</para>
/// <para>和isTemplate不能同时为true,true为创建链接克隆虚拟机,默认为false;</para>
/// <para>如果是链接克隆虚拟机,以传入的第一块磁盘为基础创建链接克隆卷,其他磁盘只创建空卷(不能进行拷贝或创建链接克隆卷,即不处理传入的磁盘参数isDataCopy)。</para>
/// </summary>
public bool? isLinkClone { get; set; }
/// <summary>
/// 【可选】ID盘信息;isLinkClone为true时才需设置,如果不设置当做空字符串处理;长度需在[0,1024]内。
/// </summary>
public string regionInfo { get; set; }
/// <summary>
/// 【可选】虚拟机自定义配置。
/// </summary>
public VmCustomization vmCustomization { get; set; }
/// <summary>
/// 【可选】虚拟机密钥的公钥字符串,只支持linux操作系统。
/// </summary>
public string publickey { get; set; }
/// <summary>
/// 【可选】虚拟机自定义数据,fileName有值时生效,长度 [0,1024]。
/// </summary>
public string vmData { get; set; }
/// <summary>
/// 【可选】自定义数据存放的文件名,长度[1,64]。
/// </summary>
public string fileName { get; set; }
/// <summary>
/// 【可选】VNC设置,目前仅支持设置vncPassword。
/// </summary>
public VncAccessInfo vncAccessInfo { get; set; }
/// <summary>
/// 【可选】是否为file模式(预留字段,不建议填写)。
/// </summary>
public bool? fileMode { get; set; }
/// <summary>
/// 【可选】创建容灾演练虚拟机必选。
/// 1:使用最新数据创建容灾演练虚拟机;
/// 2:使用最新快照创建容灾演练虚拟机;
/// </summary>
public int? drDrillOption { get; set; }
/// <summary>
/// 【可选】创建容灾演练虚拟机必选(对应占位虚拟机的UUID)。
/// </summary>
public string uuid { get; set; }
/// <summary>
/// 【可选】是否开启磁盘加速,默认false。
/// </summary>
public bool? isMultiDiskSpeedup { get; set; }
/// <summary>
/// 定义数据存放的文件名列表,预留字段。
/// </summary>
public List<string> fileNames { get; set; }
/// <summary>
/// 虚拟机自定义数据列表,fileNames有值时生效,预留字段。
/// </summary>
public List<string> vmDatas { get; set; }
}
}
|
#pragma once
void test_source_file(void);
|
# -*- coding: utf-8 -*-
import json
import scrapy
class LocalhostSpider(scrapy.Spider):
name = "localhost"
allowed_domains = ["localhost"]
start_urls = (
'http://localhost:5600/tutorial/',
)
def login(self, response):
names = ['csrfmiddlewaretoken', 'next']
login_info = {}
for i in names:
value = response.xpath(
'//input[@name="%s"]/@value' % (i)).extract()[0]
login_info[i] = value
login_info['username'] = "admin"
login_info['password'] = "admin"
self.logger.error(login_info)
return scrapy.FormRequest.from_response(
response, formdata=login_info, callback=self.after_login
)
def after_login(self, response):
if "accounts/login" in response.url:
self.logger.error("fail")
return
for url in response.css('a::attr(href)').extract():
yield scrapy.Request(response.urljoin(url), self.parse_item)
def parse(self, response):
if "accounts/login" in response.url:
return self.login(response)
def parse_item(self, response):
return json.loads(response.body)
|
#!/usr/bin/env python
"""
Copyright (C) 2017, California Institute of Technology
This file is part of addm_toolbox.
addm_toolbox 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.
addm_toolbox 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 addm_toolbox. If not, see <http://www.gnu.org/licenses/>.
---
Module: addm_toolbox_tests.py
Author: Gabriela Tavares, [email protected]
Tests all scripts in the addm_toolbox.
"""
from .addm_mla_test import main as addm_mla_test_main
from .addm_pta_map import main as addm_pta_map_main
from .addm_pta_mle import main as addm_pta_mle_main
from .addm_pta_test import main as addm_pta_test_main
from .basinhopping_optimize import main as basinhopping_main
from .cis_trans_fitting import main as cis_trans_fit_main
from .ddm_mla_test import main as ddm_mla_test_main
from .ddm_pta_test import main as ddm_pta_test_main
from .demo import main as demo_main
from .genetic_algorithm_optimize import main as genetic_algorithm_main
from .simulate_addm_true_distributions import main as simul_true_dists_main
def main():
print("\n----------Testing demo.py----------")
demo_main()
print("\n----------Testing ddm_pta_test.py----------")
ddm_pta_test_main(d=0.006, sigma=0.07, rangeD=[0.006, 0.007],
rangeSigma=[0.07, 0.08], trialsPerCondition=1,
verbose=True)
print("\n----------Testing addm_pta_test.py----------")
addm_pta_test_main(d=0.006, sigma=0.07, theta=0.4, trialsPerCondition=1,
rangeD=[0.006, 0.007], rangeSigma=[0.07, 0.08],
rangeTheta=[0.4, 0.5], verbose=True)
addm_pta_test_main(d=0.006, sigma=0.07, theta=0.4, subjectIds=[15],
trialsPerCondition=1, rangeD=[0.006, 0.007],
rangeSigma=[0.07, 0.08], rangeTheta=[0.4, 0.5],
verbose=True)
print("\n----------Testing addm_pta_mle.py----------")
addm_pta_mle_main(trialsPerSubject=1, simulationsPerCondition=1,
rangeD=[0.006, 0.007], rangeSigma=[0.07, 0.08],
rangeTheta=[0.4, 0.5], verbose=True)
addm_pta_mle_main(subjectIds=[15], trialsPerSubject=1,
simulationsPerCondition=1, rangeD=[0.006, 0.007],
rangeSigma=[0.07, 0.08], rangeTheta=[0.4, 0.5],
verbose=True)
print("\n----------Testing addm_pta_map.py----------")
addm_pta_map_main(trialsPerSubject=1, numSamples=10, numSimulations=1,
rangeD=[0.006, 0.007], rangeSigma=[0.07, 0.08],
rangeTheta=[0.4, 0.5], verbose=True)
addm_pta_map_main(subjectIds=[15], trialsPerSubject=1, numSamples=10,
numSimulations=1, rangeD=[0.006, 0.007],
rangeSigma=[0.07, 0.08], rangeTheta=[0.4, 0.5],
verbose=True)
print("\n----------Testing ddm_mla_test.py----------")
ddm_mla_test_main(d=0.006, sigma=0.07, rangeD=[0.006, 0.007],
rangeSigma=[0.07, 0.08], numTrials=100,
numSimulations=100, verbose=True)
print("\n----------Testing addm_mla_test.py----------")
addm_mla_test_main(d=0.006, sigma=0.07, theta=0.4, rangeD=[0.006, 0.007],
rangeSigma=[0.07, 0.08], rangeTheta=[0.4, 0.5],
numTrials=100, numSimulations=100, verbose=True)
print("\n----------Testing basinhopping_optimize.py----------")
basinhopping_main(initialD=0.01, initialSigma=0.1, initialTheta=0.5,
trialsPerSubject=1, numIterations=1, stepSize=0.005,
verbose=True)
print("\n----------Testing genetic_algorithm_optimize.py----------")
genetic_algorithm_main(trialsPerSubject=1, popSize=5, numGenerations=2,
verbose=True)
print("\n----------Testing simulate_addm_true_distributions.py----------")
simul_true_dists_main(d=0.006, sigma=0.07, theta=0.4, numIterations=2,
simulationsPerCondition=1, verbose=True)
print("\n----------Testing cis_trans_fitting.py for cis trials----------")
cis_trans_fit_main(trialsPerSubject=1, simulationsPerCondition=1,
rangeD=[0.006, 0.007], rangeSigma=[0.07, 0.08],
rangeTheta=[0.4, 0.5], useCisTrials=True,
useTransTrials=False, verbose=True)
print("\n---------Testing cis_trans_fitting.py for trans trials---------")
cis_trans_fit_main(trialsPerSubject=1, simulationsPerCondition=1,
rangeD=[0.006, 0.007], rangeSigma=[0.07, 0.08],
rangeTheta=[0.4, 0.5], useCisTrials=False,
useTransTrials=True, verbose=True)
|
<DIV NAME="detail" ID="detail" xmlns="http://www.w3.org/TR/REC-html40"><H3><A NAME='detail_CreateFile'></A>TestComplete DDDriverFileCommands::<BIG>CreateFile</BIG>
</H3> <TABLE><TR>
<TD class="borderStyle"><SPAN CLASS='Support' TITLE='SAFS TID Commands'>TID</SPAN></TD>
<TD class="borderStyle"><SPAN CLASS='Support' TITLE='SAFS Driver Commands'>SDC</SPAN></TD>
</TR></TABLE>
<DIV NAME="list" ID="short_desc"><short_desc xmlns="">
Open a new file with the filename, mode and access provided.<BR><b>TID Note: </b>Three ways to create a file:
<ol>
<li>Mode=Input, Access=Read</li>
<li>Mode=Output, Access=Write</li>
<li>Mode=Append, Access=Write</li>
</ol></short_desc></DIV>
<BR/>
<DIV NAME="list" ID="detail_desc"/>
<BR/>
<DIV NAME="list" ID="other">
<p><B>Fields: </B><SMALL>[ ]=Optional with Default Value</SMALL></p>
<code class="safs">
<OL start="3" ><LI>
<B>FileName</B>
<BR/>
<DIV NAME="list" ID="short_desc"><short_desc xmlns="">
The full path file name of the file to be opened.
</short_desc></DIV>
<BR/>
<DIV NAME="list" ID="detail_desc"/>
</LI>
<LI>
<B>Mode</B>
<BR/>
<DIV NAME="list" ID="short_desc"><short_desc xmlns="">
Mode to be used to create and open the file, Input, Output or Append. Random and Binary not supported
</short_desc></DIV>
<BR/>
<DIV NAME="list" ID="detail_desc"/>
</LI>
<LI>
<B>Access</B>
<BR/>
<DIV NAME="list" ID="short_desc"><short_desc xmlns="">
Access to be used to create and open the file. Read, Write or Read Write.
</short_desc></DIV>
<BR/>
<DIV NAME="list" ID="detail_desc"/>
</LI>
<LI>
<B>FileNumberVariable</B>
<BR/>
<DIV NAME="list" ID="short_desc"><short_desc xmlns="">
DDE Variable name of the variable to store the file number.
</short_desc></DIV>
<BR/>
<DIV NAME="list" ID="detail_desc"/>
</LI>
<LI>[ <B>FileNumber</B> = ]<BR/>
<DIV NAME="list" ID="short_desc"><short_desc xmlns="">
Optional File number to be used to open the file Otherwise next available file number is used
</short_desc></DIV>
<BR/>
<DIV NAME="list" ID="detail_desc"/>
</LI></OL ></code>
<br/>
<p><B>Examples:</B></p>
<code class="safs"><UL>
<LI>
<B><usage xmlns="">
C, CreateFile, "C:\Test\FileTest.txt", "Output", "Write","^test_filenum"
</usage></B>
<BR/><DIV NAME="list" ID="short_desc"><short_desc xmlns="">
CreateFile a new file FileTest.txt for Output and writing and store the file number in DDE variable ^test_filenum
</short_desc></DIV>
<BR/>
<DIV NAME="list" ID="detail_desc"/>
</LI>
<LI>
<B><usage xmlns="">
C, CreateFile, "C:\Test\FileTest.txt", "Output", "Write","^test_filenum", 8
</usage></B>
<BR/><DIV NAME="list" ID="short_desc"><short_desc xmlns="">
CreateFile a new file FileTest.txt for Output and Writing with the file number 8 and store the file number 8 in DDE variable ^test_filenum
</short_desc></DIV>
<BR/>
<DIV NAME="list" ID="detail_desc"/>
</LI>
</UL>
</code>
<br/>
<A href="SAFSReferenceKey.htm" alt="Reference Legend or Key">
<SMALL><B>[How To Read This Reference]</B></SMALL>
</A>
<HR/>
</DIV>
</DIV>
|
import os, sys, subprocess, assemblies_meta
# This script is just a quick and dirty tool to extract the assemblies
# evaluated in the DETONATE paper, for use by this regression test suite.
#
# This script is not intended for end-user use.
print("Do you really want to run this?")
sys.exit(1)
def vcc(cmd):
print(cmd)
subprocess.check_call(cmd)
indir = "/tier2/deweylab/scratch/nathanae"
outdir = "/scratch/nathanae/detonate_assemblies"
for reads_id in ["oases_mouse_real", "ensembl_sim_oases", "real", "trinity_yeast_real"]:
vcc(["mkdir", "-p", os.path.join(outdir, reads_id)])
vcc(["mkdir", "-p", os.path.join(outdir, reads_id, "cc")])
vcc(["cp", "-p",
os.path.join(indir, reads_id, "cc", "cc_0.fa"),
os.path.join(outdir, reads_id, "cc", "cc_0.fa")])
vcc(["cp", "-p",
os.path.join(indir, reads_id, "cc", "cc_0_expression/expression.isoforms.results"),
os.path.join(outdir, reads_id, "cc", "cc_0_expression.isoforms.results")])
if reads_id in ["real", "trinity_yeast_real"]:
assemblies = assemblies_meta.ss_assemblies_meta(reads_id)
else:
assemblies = assemblies_meta.all_assemblies_meta(reads_id)
for m in assemblies:
vcc(["mkdir", "-p", os.path.join(outdir, reads_id, m.assembler_id)])
vcc(["cp", "-p",
os.path.join(indir, reads_id, m.assembler_id, m.assembly_id + ".fa"),
os.path.join(outdir, reads_id, m.assembler_id, m.assembly_id + ".fa")])
vcc(["cp", "-p",
os.path.join(indir, reads_id, m.assembler_id, m.assembly_id + "_to_cc_0.psl"),
os.path.join(outdir, reads_id, m.assembler_id, m.assembly_id + "_to_cc_0.psl")])
vcc(["cp", "-p",
os.path.join(indir, reads_id, m.assembler_id, "cc_0_to_" + m.assembly_id + ".psl"),
os.path.join(outdir, reads_id, m.assembler_id, "cc_0_to_" + m.assembly_id + ".psl")])
vcc(["cp", "-p",
os.path.join(indir, reads_id, m.assembler_id, m.assembly_id + "_expression/expression.isoforms.results"),
os.path.join(outdir, reads_id, m.assembler_id, m.assembly_id + "_expression.isoforms.results")])
|
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.IntStream;
public class Controller {
public static Board board;
public static boolean whoseTurn;
public static boolean gameOver;
public static ArrayList<Integer> diceRoll;
public static Random rng;
public static void newGame() {
board = new Board();
board.populatePoints();
getStartingPlayer();
rng = new Random();
}
public static void getUserInput() {
if (board.isEndstate() == 0) {
System.out.println("Game over. Player 1 wins by bearing off all their checkers.");
gameOver = true;
} else if (board.isEndstate() == 1) {
System.out.println("Game over. Player 2 wins by bearing off all their checkers.");
gameOver = true;
} else {
if (whoseTurn)
System.out.println("It is white's turn");
else
System.out.println("It is black's turn");
System.out.println("What action will you take? (QUIT or MOVE)");
String initialInput = EasyIn.getString();
while (!(initialInput.equalsIgnoreCase("QUIT")) && !(initialInput.equalsIgnoreCase("MOVE"))) {
System.out.println("Invalid input. Must be QUIT or MOVE (case-insensitive).");
initialInput = EasyIn.getString();
}
if (initialInput.equalsIgnoreCase("QUIT")) {
if (whoseTurn) {
System.out.println("Game over. Black wins by white's resignation.");
gameOver = true;
} else {
System.out.println("Game over. White wins by black's resignation.");
gameOver = true;
}
} else if ((initialInput.equals("MOVE")) || initialInput.equals("move")) {
try {
System.out.println("What piece are you moving (e.g. 5 or 13)? Input anything else to cancel move.");
String moveOrigin = EasyIn.getString();
Point originPoint = board.points[Integer.parseInt(moveOrigin)];
System.out.println("Where are you moving the piece to? Input anything else to cancel move.");
String moveEndpoint = EasyIn.getString();
Point endPoint = board.points[Integer.parseInt(moveEndpoint)];
if (diceRoll.contains(Math.abs(Integer.parseInt(moveOrigin) - Integer.parseInt(moveEndpoint)))) {
originPoint.movePiece(Integer.parseInt(moveOrigin) - Integer.parseInt(moveEndpoint));
whoseTurn = !whoseTurn;
rollDice();
} else {
System.out.println("Did not enter point allowable by dice roll. Re-prompting user.");
}
} catch (NumberFormatException e) {
System.out.println("Did not enter valid point. Re-prompting user. nfe");
} catch (NullPointerException e) {
System.out.println("Did not enter valid point. Re-prompting user. npe");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Did not enter valid point. Re-prompting user. aioobe");
} catch (Point.InvalidDestinationException e) {
System.out.println("Cannot move to target point as it is against the rules.");
} catch (Point.NonexistentPieceException e) {
System.out.println("Cannot move piece as it is does not exist.");
}
}
}
}
public static void main(String[] args) {
newGame();
while (!gameOver) {
getUserInput();
}
}
public static void getStartingPlayer() {
boolean winner = false;
rollDice();
while (!winner) {
if (diceRoll.get(0) > diceRoll.get(1)) {
winner = true;
whoseTurn = true;
} else if (diceRoll.get(1) > diceRoll.get(0)) {
winner = true;
whoseTurn = false;
} else rollDice();
}
}
public static void rollDice() {
diceRoll = new ArrayList<Integer>();
diceRoll.add(rng.nextInt(6) + 1);
diceRoll.add(rng.nextInt(6) + 1);
System.out.println("Rolled: " + diceRoll.get(0) + " and " + diceRoll.get(1));
}
}
|
# -*- coding: utf-8 -*-
# © 2013-2015 Akretion - Alexis de Lattre <[email protected]>
# © 2014 Serv. Tecnol. Avanzados - Pedro M. Baeza
# © 2016 Antiun Ingenieria S.L. - Antonio Espinosa
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': 'Account Banking PAIN Base Module',
'summary': 'Base module for PAIN file generation',
'version': '8.0.0.4.0',
'license': 'AGPL-3',
'author': "Akretion, "
"Noviat, "
"Serv. Tecnol. Avanzados - Pedro M. Baeza, "
"Antiun Ingeniería S.L., "
"Odoo Community Association (OCA)",
'website': 'https://github.com/OCA/bank-payment',
'contributors': ['Pedro M. Baeza <[email protected]>'],
'category': 'Hidden',
'depends': ['account_banking_payment_export'],
'external_dependencies': {
'python': ['unidecode', 'lxml'],
},
'data': [
'views/payment_line_view.xml',
'views/bank_payment_line_view.xml',
'views/payment_mode_view.xml',
'views/res_company_view.xml',
],
'post_init_hook': 'set_default_initiating_party',
'installable': True,
}
|
from twitchcancer.utils.timesplitter import TimeSplitter
# use LeaderboardBuilder to create instances
class Leaderboard:
def __init__(self, horizon, metric, interval):
self.horizon = horizon
self.metric = metric
self.interval = interval
def __str__(self):
return ".".join([self.horizon, self.metric, self.interval])
def __eq__(self, other):
return self.horizon == other.horizon \
and self.metric == other.metric \
and self.interval == other.interval
def __neq__(self, other):
return self.horizon != other.horizon \
or self.metric != other.metric \
or self.interval != other.interval
def __hash__(self):
return hash(str(self))
# return the first date that should be in this leaderboard
def start_date(self):
if self.horizon == "monthly":
return TimeSplitter.month(TimeSplitter.now())
elif self.horizon == "daily":
return TimeSplitter.day(TimeSplitter.now())
else:
return None
class LeaderboardBuilder:
_horizons = [
'daily',
'monthly',
'all',
]
_metrics = [
'cancer',
'messages',
'cpm',
]
_intervals = [
'minute',
'total',
'average',
]
# builds a list of existing leaderboards
@classmethod
def build(cls, horizon=None, metric=None, interval=None):
# limit horizons
horizons = cls._default_values(horizon, cls._horizons)
# limit metrics
metrics = cls._default_values(metric, cls._metrics)
# limit intervals
intervals = cls._default_values(interval, cls._intervals)
result = set()
for horizon in horizons:
for metric in metrics:
for interval in intervals:
# never build a cpm average
if metric == "cpm" and interval == "average":
continue
result.add(Leaderboard(horizon=horizon, metric=metric, interval=interval))
return result
# builds a leaderboard from its name
@classmethod
def from_name(cls, name):
if not cls._is_valid(name):
return None
(horizon, metric, interval) = name.split(".")
return Leaderboard(horizon, metric, interval)
# checks that a leaderboard exists
@classmethod
def _is_valid(cls, name):
try:
(horizon, metric, interval) = name.split(".")
# check the horizon
if horizon not in cls._horizons:
return False
# check the metric
if metric not in cls._metrics:
return False
# check the interval
if interval not in cls._intervals:
return False
# we don't do cpm average
if metric == "cpm" and interval == "average":
return False
except KeyError:
return False
except TypeError:
return False
except ValueError:
return False
except AttributeError:
return False
return True
# returns
@classmethod
def _default_values(cls, value, source):
if value is not None:
# return a single value if its valid
if value in source:
return [value]
# stop everything if the value is invalid
else:
return []
else:
# default to the full list of possible values
return source
|
using System.Reflection;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("MockAllTheThings.Core")]
[assembly: AssemblyDescription("Core assembly for Mock All The Things.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Phillip Wong")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("Phillip Wong")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("0.2.1.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
|
#!/usr/bin/python
# encoding: utf-8
from __future__ import unicode_literals
import re
import sys
import imp
import os.path
import subprocess
HOME = os.path.expanduser("~")
LIB_PATH = os.path.join(HOME, "Library/Application Support/Alfred 2/" \
"Workflow Data/alfred.bundler-aries/assets/python/")
def as_run(ascript):
"""Run the given AppleScript and return the standard output and error."""
osa = subprocess.Popen(['osascript', '-'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
return osa.communicate(ascript)[0].strip()
def _pip_install():
"""If `pip` isn't installed, install it"""
try: # Check if `pip` installed
imp.find_module('pip')
return True
except ImportError: # If not installed, install it
get_pip = """do shell script "python '{0}/get-pip.py'" """.format(
LIB_PATH)
return as_run(get_pip)
def _get_version(_path):
"""Return version number of package"""
egg_file = [v for v in os.listdir(_path) if v.endswith('.egg-info')][0]
_egg = os.path.join(_path, egg_file)
_info = os.path.join(_egg, 'PKG-INFO')
with open(_info, 'r') as _file:
data = _file.read()
_file.close()
try:
_version = re.search(r"^Version:\s(.*?)$", data, re.M).group(1)
except TypeError:
_version = '0.0'
return _version
def _pkg_exists(_pkg, _version=None):
"""Check if `pkg` in bundler"""
if _pkg in os.listdir(LIB_PATH):
pkg_path = os.path.join(LIB_PATH, _pkg)
if _version == None:
_versions = [v for v in os.listdir(pkg_path) if v != '.DS_Store']
if len(_versions) == 1: # return only version
return os.path.join(pkg_path, _versions[0])
elif len(_versions) > 1: # return highest version
return os.path.join(pkg_path, max(_versions))
elif len(_versions) == 0: # return package path
return pkg_path
else:
_versions = [v for v in os.listdir(pkg_path) if v == _version]
if len(_versions) == 1:
return os.path.join(pkg_path, _versions[0])
elif len(_versions) == 0:
return True
else:
return True
def _pkg_path(_pkg, sub_dir):
"""Return full path to `pkg`'s sub directory"""
sub_dir = os.path.join(_pkg, sub_dir)
return os.path.join(LIB_PATH, sub_dir)
def __load(_pkg, _version=None):
"""Load `pkg` in bundler"""
# ensure `pip` is installed
_pip_install()
# is `package` installed?
_status = _pkg_exists(_pkg, _version)
if _status != True: # if `pkg` in bundler, return path
return _status
else: # else, install `pkg`
if _version == None:
install_path = _pkg_path(_pkg, 'tmp')
install_scpt = """
do shell script "sudo pip install --target='{path}' {pkg}" \
with administrator privileges
""".format(
path=install_path,
pkg=_pkg
)
as_run(install_scpt)
_version = _get_version(install_path)
new_path = _pkg_path(_pkg, _version)
rename_scpt = """
do shell script "sudo mv '{old}' '{new}'" \
with administrator privileges
""".format(
old=install_path,
new=new_path
)
as_run(rename_scpt)
return new_path
else:
install_path = _pkg_path(_pkg, _version)
install_scpt = """
do shell script "sudo pip install --target='{path}' {pkg}=={vers}" \
with administrator privileges
""".format(
path=install_path,
pkg=_pkg,
vers=_version
)
as_run(install_scpt)
return install_path
def main():
"""Test case"""
pkg_path = __load('html2text')
sys.path.insert(0, pkg_path)
import html2text
print html2text
if __name__ == '__main__':
main()
|
import os
import sys
from shutil import rmtree
from setuptools import setup, find_packages
exclude = ["forms_builder/example_project/dev.db",
"forms_builder/example_project/local_settings.py"]
exclude = dict([(e, None) for e in exclude])
for e in exclude:
if e.endswith(".py"):
try:
os.remove("%sc" % e)
except:
pass
try:
with open(e, "r") as f:
exclude[e] = (f.read(), os.stat(e))
os.remove(e)
except Exception:
pass
if sys.argv[:2] == ["setup.py", "bdist_wheel"]:
# Remove previous build dir when creating a wheel build,
# since if files have been removed from the project,
# they'll still be cached in the build dir and end up
# as part of the build, which is unexpected.
try:
rmtree("build")
except:
pass
try:
setup(
name = "django-forms-builder",
version = __import__("forms_builder").__version__,
author = "Stephen McDonald",
author_email = "[email protected]",
description = ("A Django reusable app providing the ability for "
"admin users to create their own forms and report "
"on their collected data."),
long_description = open("README.rst").read(),
url = "http://github.com/stephenmcd/django-forms-builder",
zip_safe = False,
include_package_data = True,
packages = find_packages(),
install_requires = [
"sphinx-me >= 0.1.2",
"unidecode",
"django-email-extras >= 0.2",
"future == 0.9.0",
],
classifiers = [
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"Framework :: Django",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
"Topic :: Internet :: WWW/HTTP :: Site Management",
]
)
finally:
for e in exclude:
if exclude[e] is not None:
data, stat = exclude[e]
try:
with open(e, "w") as f:
f.write(data)
os.chown(e, stat.st_uid, stat.st_gid)
os.chmod(e, stat.st_mode)
except:
pass
|
/**
* @file Math Utils
* @author Alexander Rose <[email protected]>
* @private
*/
export function degToRad (deg: number) {
return deg * 0.01745 // deg * Math.PI / 180
}
export function radToDeg (rad: number) {
return rad * 57.29578 // rad * 180 / Math.PI
}
// http://www.broofa.com/Tools/Math.uuid.htm
const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
const uuid = new Array(36)
export function generateUUID () {
let rnd = 0
let r
for (let i = 0; i < 36; i++) {
if (i === 8 || i === 13 || i === 18 || i === 23) {
uuid[ i ] = '-'
} else if (i === 14) {
uuid[ i ] = '4'
} else {
if (rnd <= 0x02) rnd = 0x2000000 + (Math.random() * 0x1000000) | 0
r = rnd & 0xf
rnd = rnd >> 4
uuid[ i ] = chars[ (i === 19) ? (r & 0x3) | 0x8 : r ]
}
}
return uuid.join('')
}
export function countSetBits (i: number) {
i = i - ((i >> 1) & 0x55555555)
i = (i & 0x33333333) + ((i >> 2) & 0x33333333)
return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24
}
export function normalize (value: number, min: number, max: number) {
return (value - min) / (max - min)
}
export function clamp (value: number, min: number, max: number) {
return Math.max(min, Math.min(max, value))
}
export function pclamp (value: number) {
return clamp(value, 0, 100)
}
export function saturate (value: number) {
return clamp(value, 0, 1)
}
export function lerp (start: number, stop: number, alpha: number) {
return start + (stop - start) * alpha
}
export function spline (p0: number, p1: number, p2: number, p3: number, t: number, tension: number) {
const v0 = (p2 - p0) * tension
const v1 = (p3 - p1) * tension
const t2 = t * t
const t3 = t * t2
return (2 * p1 - 2 * p2 + v0 + v1) * t3 +
(-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 +
v0 * t + p1
}
export function smoothstep (min: number, max: number, x: number) {
x = saturate(normalize(x, min, max))
return x * x * (3 - 2 * x)
}
export function smootherstep (min: number, max: number, x: number) {
x = saturate(normalize(x, min, max))
return x * x * x * (x * (x * 6 - 15) + 10)
}
export function smootheststep (min: number, max: number, x: number) {
x = saturate(normalize(x, min, max))
return (
-20 * Math.pow(x, 7) +
70 * Math.pow(x, 6) -
84 * Math.pow(x, 5) +
35 * Math.pow(x, 4)
)
}
export function almostIdentity (value: number, start: number, stop: number) {
if (value > start) return value
const a = 2 * stop - start
const b = 2 * start - 3 * stop
const t = value / start
return (a * t + b) * t * t + stop
}
|
ORDER_KEY = "DE6A6E24F046FB24094E9208C66FEFE7"
CREATE_PAYMENT_RESPONSE = """<?xml version='1.0' encoding='UTF-8'?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<createResponse ddpXsdVersion="1.3.14" xmlns="http://www.docdatapayments.com/services/paymentservice/1_3/">
<createSuccess>
<success code="SUCCESS">Operation successful.</success>
<key>{}</key>
</createSuccess>
</createResponse>
</S:Body>
</S:Envelope>
""".format(ORDER_KEY)
CANCELLED_PAYMENT_RESPONSE = """<?xml version='1.0' encoding='UTF-8'?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<cancelResponse ddpXsdVersion="1.3.14" xmlns="http://www.docdatapayments.com/services/paymentservice/1_3/">
<cancelSuccess>
<success code="SUCCESS">Operation successful.</success>
<result>NO_PAYMENTS</result>
</cancelSuccess>
</cancelResponse>
</S:Body>
</S:Envelope>
"""
STATUS_SUCCESS_RESPONSE = """<?xml version='1.0' encoding='UTF-8'?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<statusResponse ddpXsdVersion="1.3.14" xmlns="http://www.docdatapayments.com/services/paymentservice/1_3/">
<statusSuccess>
<success code="SUCCESS">Operation successful.</success>
<report>
<approximateTotals exchangeRateDate="2019-02-10 16:52:52" exchangedTo="EUR">
<totalRegistered>299</totalRegistered>
<totalShopperPending>0</totalShopperPending>
<totalAcquirerPending>0</totalAcquirerPending>
<totalAcquirerApproved>299</totalAcquirerApproved>
<totalCaptured>299</totalCaptured>
<totalRefunded>0</totalRefunded>
<totalChargedback>0</totalChargedback>
<totalReversed>0</totalReversed>
</approximateTotals>
<payment>
<id>4910079745</id>
<paymentMethod>IDEAL</paymentMethod>
<authorization>
<status>AUTHORIZED</status>
<amount currency="EUR">299</amount>
<confidenceLevel>ACQUIRER_APPROVED</confidenceLevel>
<capture>
<status>CAPTURED</status>
<amount currency="EUR">299</amount>
</capture>
</authorization>
</payment>
<consideredSafe>
<value>true</value>
<level>SAFE</level>
<date>2019-02-10T16:51:43.446+01:00</date>
<reason>EXACT_MATCH</reason>
</consideredSafe>
<apiInformation conversionApplied="false">
<originalVersion>1.3</originalVersion>
</apiInformation>
</report>
</statusSuccess>
</statusResponse>
</S:Body>
</S:Envelope>
"""
STATUS_CANCELLED_RESPONSE = """<?xml version='1.0' encoding='UTF-8'?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<statusResponse xmlns="http://www.docdatapayments.com/services/paymentservice/1_3/">
<statusSuccess>
<success code="SUCCESS">Operation successful.</success>
<report>
<approximateTotals exchangeRateDate="2019-02-04 11:11:07" exchangedTo="EUR">
<totalRegistered>0</totalRegistered>
<totalShopperPending>0</totalShopperPending>
<totalAcquirerPending>0</totalAcquirerPending>
<totalAcquirerApproved>0</totalAcquirerApproved>
<totalCaptured>0</totalCaptured>
<totalRefunded>0</totalRefunded>
<totalChargedback>0</totalChargedback>
</approximateTotals>
</report>
</statusSuccess>
</statusResponse>
</S:Body>
</S:Envelope>
"""
|
from os import execv
class RunCommand(object):
"""
Builder for a docker run command.
"""
def __init__(self, inspection, command=None):
"""
:param inspection: docker inspect output for a container.
:param command: command to execute at runtime (optional).
"""
self.inspection = inspection
self.command = command
self.args = ["docker", "run", "--rm", "-it"]
def add_volumes(self):
for container_path, host_path in self.inspection["Volumes"].items():
self.args.append("--volume={}:{}".format(host_path, container_path))
return self
def add_ports(self):
for port, bindings in self.inspection["HostConfig"]["PortBindings"].items():
for binding in bindings:
self.args.append("--publish={}:{}".format(binding["HostPort"], port))
return self
def add_image(self):
self.args.append(self.inspection["Config"]["Image"])
return self
def add_command(self):
if self.command:
self.args.append(self.command)
return self
@classmethod
def build(cls, docker_client, args, extra=None):
"""
Build the docker run command arguments for the given container name or ID.
"""
container = args.container
command = args.command
inspection = docker_client.inspect_container(container)
return (cls(inspection, command)
.add_volumes()
.add_ports()
.add_image()
.add_command())
def execute(self):
"""
Execute the command.
"""
print "DOCKER-DEBUG:", " ".join(self.args)
execv("/usr/bin/docker", self.args)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Generate .h file for TCG code generation.
"""
__author__ = "Lluís Vilanova <[email protected]>"
__copyright__ = "Copyright 2012-2014, Lluís Vilanova <[email protected]>"
__license__ = "GPL version 2 or (at your option) any later version"
__maintainer__ = "Stefan Hajnoczi"
__email__ = "[email protected]"
from tracetool import out
def generate(events, backend):
out('/* This file is autogenerated by tracetool, do not edit. */',
'/* You must include this file after the inclusion of helper.h */',
'',
'#ifndef TRACE__GENERATED_TCG_TRACERS_H',
'#define TRACE__GENERATED_TCG_TRACERS_H',
'',
'#include <stdint.h>',
'',
'#include "trace.h"',
'#include "exec/helper-proto.h"',
'',
)
for e in events:
# just keep one of them
if "tcg-trans" not in e.properties:
continue
# get the original event definition
e = e.original.original
out('static inline void %(name_tcg)s(%(args)s)',
'{',
name_tcg=e.api(e.QEMU_TRACE_TCG),
args=e.args)
if "disable" not in e.properties:
out(' %(name_trans)s(%(argnames_trans)s);',
' gen_helper_%(name_exec)s(%(argnames_exec)s);',
name_trans=e.event_trans.api(e.QEMU_TRACE),
name_exec=e.event_exec.api(e.QEMU_TRACE),
argnames_trans=", ".join(e.event_trans.args.names()),
argnames_exec=", ".join(e.event_exec.args.names()))
out('}')
out('',
'#endif /* TRACE__GENERATED_TCG_TRACERS_H */')
|
/**************************************************************************
* Otter Browser: Web browser controlled by the user, not vice-versa.
* Copyright (C) 2015 - 2019 Michal Dutkiewicz aka Emdek <[email protected]>
* Copyright (C) 2016 Piotr Wójcik <[email protected]>
*
* 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/>.
*
**************************************************************************/
#ifndef OTTER_CERTIFICATEDIALOG_H
#define OTTER_CERTIFICATEDIALOG_H
#include "Dialog.h"
#include <QtGui/QStandardItem>
#include <QtNetwork/QSslCertificate>
namespace Otter
{
namespace Ui
{
class CertificateDialog;
}
class CertificateDialog final : public Dialog
{
Q_OBJECT
public:
enum CertificateField
{
VersionField = 0,
SerialNumberField,
SignatureAlgorithmField,
IssuerField,
ValidityField,
ValidityNotBeforeField,
ValidityNotAfterField,
SubjectField,
PublicKeyField,
PublicKeyAlgorithmField,
PublicKeyValueField,
ExtensionsField,
ExtensionField,
DigestField,
DigestSha1Field,
DigestSha256Field
};
enum DataRole
{
CertificateFieldRole = Qt::UserRole,
CertificateIndexRole,
ExtensionIndexRole,
ExtensionNameRole
};
explicit CertificateDialog(QVector<QSslCertificate> certificates, QWidget *parent = nullptr);
~CertificateDialog();
protected:
void changeEvent(QEvent *event) override;
QStandardItem* createField(CertificateField field, QStandardItem *parent = nullptr, const QMap<int, QVariant> &metaData = {});
static QString formatHex(const QString &source, QChar separator = QLatin1Char(' '));
protected slots:
void exportCertificate();
void updateCertificate();
void updateValue();
private:
QVector<QSslCertificate> m_certificates;
Ui::CertificateDialog *m_ui;
};
}
#endif
|
import sublime
from sublime_plugin import WindowCommand
from ..git_command import GitCommand
from ..constants import MERGE_CONFLICT_PORCELAIN_STATUSES
from ...common import util
class GsMergeCommand(WindowCommand, GitCommand):
"""
Display a list of branches available to merge against the active branch.
When selected, perform merge with specified branch.
"""
def run(self):
sublime.set_timeout_async(lambda: self.run_async(), 1)
def run_async(self):
self._branches = tuple(branch for branch in self.get_branches() if not branch.active)
self._entries = tuple(self._generate_entry(branch) for branch in self._branches)
self.window.show_quick_panel(
self._entries,
self.on_selection
)
@staticmethod
def _generate_entry(branch):
entry = branch.name_with_remote
addl_info = []
if branch.tracking:
addl_info.append("tracking remote " + branch.tracking)
if branch.tracking_status:
addl_info.append(branch.tracking_status)
if addl_info:
entry += " (" + " - ".join(addl_info) + ")"
return entry
def on_selection(self, index):
if index == -1:
return
branch = self._branches[index]
try:
self.git("merge", "--log", branch.name_with_remote)
finally:
util.view.refresh_gitsavvy(self.window.active_view())
class GsAbortMergeCommand(WindowCommand, GitCommand):
"""
Reset all files to pre-merge conditions, and abort the merge.
"""
def run(self):
sublime.set_timeout_async(self.run_async, 0)
def run_async(self):
self.git("reset", "--merge")
util.view.refresh_gitsavvy(self.window.active_view())
class GsRestartMergeForFileCommand(WindowCommand, GitCommand):
"""
Reset a single file to pre-merge condition, but do not abort the merge.
"""
def run(self):
sublime.set_timeout_async(self.run_async, 0)
def run_async(self):
self._conflicts = tuple(
f.path for f in self.get_status()
if (f.index_status, f.working_status) in MERGE_CONFLICT_PORCELAIN_STATUSES
)
self.window.show_quick_panel(
self._conflicts,
self.on_selection
)
def on_selection(self, index):
if index == -1:
return
fpath = self._conflicts[index]
self.git("checkout", "--conflict=merge", "--", fpath)
util.view.refresh_gitsavvy(self.window.active_view())
|
import RecentSearchesRoot from '~/filtered_search/recent_searches_root';
import * as vueSrc from 'vue';
describe('RecentSearchesRoot', () => {
describe('render', () => {
let recentSearchesRoot;
let data;
let template;
beforeEach(() => {
recentSearchesRoot = {
store: {
state: 'state',
},
};
spyOn(vueSrc, 'default').and.callFake((options) => {
data = options.data;
template = options.template;
});
RecentSearchesRoot.prototype.render.call(recentSearchesRoot);
});
it('should instantiate Vue', () => {
expect(vueSrc.default).toHaveBeenCalled();
expect(data()).toBe(recentSearchesRoot.store.state);
expect(template).toContain(':is-local-storage-available="isLocalStorageAvailable"');
});
});
});
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtGui 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 The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/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 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QOPENGL_P_H
#define QOPENGL_P_H
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists purely as an
// implementation detail. This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//
#include <QtGui/private/qtguiglobal_p.h>
#include <qopengl.h>
#include <private/qopenglcontext_p.h>
#include <QtCore/qset.h>
#include <QtCore/qstring.h>
#include <QtCore/qversionnumber.h>
QT_BEGIN_NAMESPACE
class QJsonDocument;
class Q_GUI_EXPORT QOpenGLExtensionMatcher
{
public:
QOpenGLExtensionMatcher();
bool match(const QByteArray &extension) const
{
return m_extensions.contains(extension);
}
QSet<QByteArray> extensions() const { return m_extensions; }
private:
QSet<QByteArray> m_extensions;
};
class Q_GUI_EXPORT QOpenGLConfig
{
public:
struct Q_GUI_EXPORT Gpu {
Gpu() : vendorId(0), deviceId(0) {}
bool isValid() const { return deviceId || !glVendor.isEmpty(); }
bool equals(const Gpu &other) const {
return vendorId == other.vendorId && deviceId == other.deviceId && driverVersion == other.driverVersion
&& driverDescription == other.driverDescription && glVendor == other.glVendor;
}
uint vendorId;
uint deviceId;
QVersionNumber driverVersion;
QByteArray driverDescription;
QByteArray glVendor;
static Gpu fromDevice(uint vendorId, uint deviceId, QVersionNumber driverVersion, const QByteArray &driverDescription) {
Gpu gpu;
gpu.vendorId = vendorId;
gpu.deviceId = deviceId;
gpu.driverVersion = driverVersion;
gpu.driverDescription = driverDescription;
return gpu;
}
static Gpu fromGLVendor(const QByteArray &glVendor) {
Gpu gpu;
gpu.glVendor = glVendor;
return gpu;
}
static Gpu fromContext();
};
static QSet<QString> gpuFeatures(const Gpu &gpu,
const QString &osName, const QVersionNumber &kernelVersion, const QString &osVersion,
const QJsonDocument &doc);
static QSet<QString> gpuFeatures(const Gpu &gpu,
const QString &osName, const QVersionNumber &kernelVersion, const QString &osVersion,
const QString &fileName);
static QSet<QString> gpuFeatures(const Gpu &gpu, const QJsonDocument &doc);
static QSet<QString> gpuFeatures(const Gpu &gpu, const QString &fileName);
};
inline bool operator==(const QOpenGLConfig::Gpu &a, const QOpenGLConfig::Gpu &b)
{
return a.equals(b);
}
inline bool operator!=(const QOpenGLConfig::Gpu &a, const QOpenGLConfig::Gpu &b)
{
return !a.equals(b);
}
inline uint qHash(const QOpenGLConfig::Gpu &gpu)
{
return qHash(gpu.vendorId) + qHash(gpu.deviceId) + qHash(gpu.driverVersion);
}
QT_END_NAMESPACE
#endif // QOPENGL_H
|
"""Approaches for calculating haplotype phasing of variants.
"""
import os
from bcbio import broad
from bcbio.utils import file_exists
from bcbio.distributed.transaction import file_transaction
from bcbio.pipeline import shared
from bcbio.variation import bamprep
def has_variants(vcf_file):
with open(vcf_file) as in_handle:
for line in in_handle:
if not line.startswith("#"):
return True
return False
def read_backed_phasing(vcf_file, bam_files, genome_file, region, config):
"""Phase variants using GATK's read-backed phasing.
http://www.broadinstitute.org/gatk/gatkdocs/
org_broadinstitute_sting_gatk_walkers_phasing_ReadBackedPhasing.html
"""
if has_variants(vcf_file):
broad_runner = broad.runner_from_config(config)
out_file = "%s-phased%s" % os.path.splitext(vcf_file)
if not file_exists(out_file):
with file_transaction(config, out_file) as tx_out_file:
params = ["-T", "ReadBackedPhasing",
"-R", genome_file,
"--variant", vcf_file,
"--out", tx_out_file,
"--downsample_to_coverage", "250",
"--downsampling_type", "BY_SAMPLE"]
for bam_file in bam_files:
params += ["-I", bam_file]
variant_regions = config["algorithm"].get("variant_regions", None)
region = shared.subset_variant_regions(variant_regions, region, out_file)
if region:
params += ["-L", bamprep.region_to_gatk(region),
"--interval_set_rule", "INTERSECTION"]
broad_runner.run_gatk(params)
return out_file
else:
return vcf_file
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Models;
namespace MindstormController
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private Context ctx;
private BackgroundWorker bw = new BackgroundWorker();
/// <summary>
/// Constructor
/// </summary>
public MainWindow()
{
InitializeComponent();
SetLanguageDictionary(Thread.CurrentThread.CurrentCulture.ToString());
ctx = new Context();
Database.SetInitializer<Models.Context>(new Models.Initializer());
// Database first connection is a bit slow (from 1 to 3 seconds),
// so we do in a thread a query in order to start the database
// connection in background
bw.DoWork += new DoWorkEventHandler(checkDatabase);
bw.RunWorkerAsync();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (!isDatabaseUp())
return;
string name = this.username.Text;
string password = this.password.Password;
errormsg.Visibility = System.Windows.Visibility.Hidden;
if (String.IsNullOrEmpty(name) || String.IsNullOrEmpty(password))
{
errormsg.Text = "Error: Campo Vacío";
errormsg.Visibility = System.Windows.Visibility.Visible;
return;
}
string hash = User.GenerateHash(password);
if (ctx.Users.Any(u => u.name == name && u.password == hash))
{
HomeWindow home = new HomeWindow();
HomeWindow.username = name;
App.Current.MainWindow = home;
home.Resources.MergedDictionaries.Clear();
home.Resources.MergedDictionaries.Add(this.Resources.MergedDictionaries.First());
this.Close();
home.Show();
}
else
{
if (ctx.Users.Any(u => u.name == name))
errormsg.Text = "Error: Contrseña errónea";
else
errormsg.Text = "Error: El usuario no existe ";
errormsg.Visibility = System.Windows.Visibility.Visible;
return;
}
}
private void NewUser_Click(object sender, RoutedEventArgs e)
{
if (!isDatabaseUp())
return;
RegisterWindow register = new RegisterWindow();
App.Current.MainWindow = register;
register.Resources.MergedDictionaries.Clear();
register.Resources.MergedDictionaries.Add(this.Resources.MergedDictionaries.First());
this.Close();
register.Show();
}
public void checkDatabase(object sender, DoWorkEventArgs e)
{
if (!isDatabaseUp())
{
this.Dispatcher.Invoke((Action)(() =>
{
this.errormsg.Text = "Error: No se ha podido conectar con la base de datos";
this.errormsg.Visibility = Visibility.Visible;
}));
}
}
public bool isDatabaseUp()
{
try
{
ctx.Users.Count();
return true;
}
catch
{
return false;
}
}
private void English_Click(object sender, RoutedEventArgs e)
{
SetLanguageDictionary("en-US");
}
private void Spanish_Click(object sender, RoutedEventArgs e)
{
SetLanguageDictionary("es-ES");
}
private void SetLanguageDictionary(String code)
{
ResourceDictionary dict = new ResourceDictionary();
switch (code)
{
case "en-US":
dict.Source = new Uri("pack://application:,,,/Resources/StringResources.xaml");
TitleImg.Source = new BitmapImage(new Uri("pack://application:,,,/Resources/img/titleMindstorm1EN.jpg"));
HomeWindow.language = Models.Language.English;
break;
case "es-ES":
dict.Source = new Uri("pack://application:,,,/Resources/StringResources.es-ES.xaml");
TitleImg.Source = new BitmapImage(new Uri("..\\Resources\\img\\titleMindstorm1.jpg", UriKind.Relative));
HomeWindow.language = Models.Language.Spanish;
break;
default:
dict.Source = new Uri("pack://application:,,,/Resources/StringResources.xaml");
TitleImg.Source = new BitmapImage(new Uri("pack://application:,,,/Resources/img/titleMindstorm1EN.jpg"));
HomeWindow.language = Models.Language.English;
break;
}
this.Resources.MergedDictionaries.Clear();
this.Resources.MergedDictionaries.Add(dict);
}
private void Exit_Click(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
}
}
}
|
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import { setVisibilityFilter } from '../../actions/todo';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
import IconButton from 'material-ui/IconButton/IconButton';
import ContentFilter from 'material-ui/svg-icons/content/filter-list';
class Filter extends Component {
constructor(props) {
super(props)
};
render(){
const {messages , visibilityFilter, setVisibilityFilter } = this.props;
function handleChangeSingle (event, value) {
setVisibilityFilter(value);
};
return (
<IconMenu
iconButtonElement={<IconButton><ContentFilter color={'white'}/></IconButton>}
onChange={handleChangeSingle}
value={visibilityFilter}
multiple={false}
>
<MenuItem value="SHOW_ALL" primaryText={messages.all||'all'} />
<MenuItem value="SHOW_COMPLETED" primaryText={messages.completed||'completed'} />
<MenuItem value="SHOW_ACTIVE" primaryText={messages.active||'active'} />
</IconMenu>
)
}
}
Filter.propTypes = {
messages: PropTypes.object.isRequired,
setVisibilityFilter: PropTypes.func.isRequired,
visibilityFilter:PropTypes.string.isRequired,
}
function mapStateToProps(state) {
const { intl, visibilityFilter} = state;
return {
messages: intl.messages,
visibilityFilter: visibilityFilter,
};
}
const mapDispatchToProps = (dispatch) => {
return {
setVisibilityFilter:(filter)=>{
dispatch(setVisibilityFilter(filter));
},
}
}
export default connect(mapStateToProps,mapDispatchToProps)(Filter);
|
//>>built
define("dojox/drawing/manager/Mouse",["dojo","../util/oo","../defaults"],function(_1,oo,_2){
return oo.declare(function(_3){
this.util=_3.util;
this.keys=_3.keys;
this.id=_3.id||this.util.uid("mouse");
this.currentNodeId="";
this.registered={};
},{doublClickSpeed:400,_lastx:0,_lasty:0,__reg:0,_downOnCanvas:false,init:function(_4){
this.container=_4;
this.setCanvas();
var c;
var _5=false;
_1.connect(this.container,"rightclick",this,function(_6){
console.warn("RIGHTCLICK");
});
_1.connect(document.body,"mousedown",this,function(_7){
});
_1.connect(this.container,"mousedown",this,function(_8){
this.down(_8);
if(_8.button!=_1.mouseButtons.RIGHT){
_5=true;
c=_1.connect(document,"mousemove",this,"drag");
}
});
_1.connect(document,"mouseup",this,function(_9){
_1.disconnect(c);
_5=false;
this.up(_9);
});
_1.connect(document,"mousemove",this,function(_a){
if(!_5){
this.move(_a);
}
});
_1.connect(this.keys,"onEsc",this,function(_b){
this._dragged=false;
});
},setCanvas:function(){
var _c=_1.coords(this.container.parentNode);
this.origin=_1.clone(_c);
},scrollOffset:function(){
return {top:this.container.parentNode.scrollTop,left:this.container.parentNode.scrollLeft};
},resize:function(_d,_e){
if(this.origin){
this.origin.w=_d;
this.origin.h=_e;
}
},register:function(_f){
var _10=_f.id||"reg_"+(this.__reg++);
if(!this.registered[_10]){
this.registered[_10]=_f;
}
return _10;
},unregister:function(_11){
if(!this.registered[_11]){
return;
}
delete this.registered[_11];
},_broadcastEvent:function(_12,obj){
for(var nm in this.registered){
if(this.registered[nm][_12]){
this.registered[nm][_12](obj);
}
}
},onDown:function(obj){
this._broadcastEvent(this.eventName("down"),obj);
},onDrag:function(obj){
var nm=this.eventName("drag");
if(this._selected&&nm=="onDrag"){
nm="onStencilDrag";
}
this._broadcastEvent(nm,obj);
},onMove:function(obj){
this._broadcastEvent("onMove",obj);
},overName:function(obj,evt){
var nm=obj.id.split(".");
evt=evt.charAt(0).toUpperCase()+evt.substring(1);
if(nm[0]=="dojox"&&(_2.clickable||!_2.clickMode)){
return "onStencil"+evt;
}else{
return "on"+evt;
}
},onOver:function(obj){
this._broadcastEvent(this.overName(obj,"over"),obj);
},onOut:function(obj){
this._broadcastEvent(this.overName(obj,"out"),obj);
},onUp:function(obj){
var nm=this.eventName("up");
if(nm=="onStencilUp"){
this._selected=true;
}else{
if(this._selected&&nm=="onUp"){
nm="onStencilUp";
this._selected=false;
}
}
this._broadcastEvent(nm,obj);
if(dojox.gfx.renderer=="silverlight"){
return;
}
this._clickTime=new Date().getTime();
if(this._lastClickTime){
if(this._clickTime-this._lastClickTime<this.doublClickSpeed){
var dnm=this.eventName("doubleClick");
console.warn("DOUBLE CLICK",dnm,obj);
this._broadcastEvent(dnm,obj);
}else{
}
}
this._lastClickTime=this._clickTime;
},zoom:1,setZoom:function(_13){
this.zoom=1/_13;
},setEventMode:function(_14){
this.mode=_14?"on"+_14.charAt(0).toUpperCase()+_14.substring(1):"";
},eventName:function(_15){
_15=_15.charAt(0).toUpperCase()+_15.substring(1);
if(this.mode){
if(this.mode=="onPathEdit"){
return "on"+_15;
}
if(this.mode=="onUI"){
}
return this.mode+_15;
}else{
if(!_2.clickable&&_2.clickMode){
return "on"+_15;
}
var dt=!this.drawingType||this.drawingType=="surface"||this.drawingType=="canvas"?"":this.drawingType;
var t=!dt?"":dt.charAt(0).toUpperCase()+dt.substring(1);
return "on"+t+_15;
}
},up:function(evt){
this.onUp(this.create(evt));
},down:function(evt){
this._downOnCanvas=true;
var sc=this.scrollOffset();
var dim=this._getXY(evt);
this._lastpagex=dim.x;
this._lastpagey=dim.y;
var o=this.origin;
var x=dim.x-o.x+sc.left;
var y=dim.y-o.y+sc.top;
var _16=x>=0&&y>=0&&x<=o.w&&y<=o.h;
x*=this.zoom;
y*=this.zoom;
o.startx=x;
o.starty=y;
this._lastx=x;
this._lasty=y;
this.drawingType=this.util.attr(evt,"drawingType")||"";
var id=this._getId(evt);
if(evt.button==_1.mouseButtons.RIGHT&&this.id=="mse"){
}else{
evt.preventDefault();
_1.stopEvent(evt);
}
this.onDown({mid:this.id,x:x,y:y,pageX:dim.x,pageY:dim.y,withinCanvas:_16,id:id});
},over:function(obj){
this.onOver(obj);
},out:function(obj){
this.onOut(obj);
},move:function(evt){
var obj=this.create(evt);
if(this.id=="MUI"){
}
if(obj.id!=this.currentNodeId){
var _17={};
for(var nm in obj){
_17[nm]=obj[nm];
}
_17.id=this.currentNodeId;
this.currentNodeId&&this.out(_17);
obj.id&&this.over(obj);
this.currentNodeId=obj.id;
}
this.onMove(obj);
},drag:function(evt){
this.onDrag(this.create(evt,true));
},create:function(evt,_18){
var sc=this.scrollOffset();
var dim=this._getXY(evt);
var _19=dim.x;
var _1a=dim.y;
var o=this.origin;
var x=dim.x-o.x+sc.left;
var y=dim.y-o.y+sc.top;
var _1b=x>=0&&y>=0&&x<=o.w&&y<=o.h;
x*=this.zoom;
y*=this.zoom;
var id=_1b?this._getId(evt,_18):"";
var ret={mid:this.id,x:x,y:y,pageX:dim.x,pageY:dim.y,page:{x:dim.x,y:dim.y},orgX:o.x,orgY:o.y,last:{x:this._lastx,y:this._lasty},start:{x:this.origin.startx,y:this.origin.starty},move:{x:_19-this._lastpagex,y:_1a-this._lastpagey},scroll:sc,id:id,withinCanvas:_1b};
this._lastx=x;
this._lasty=y;
this._lastpagex=_19;
this._lastpagey=_1a;
_1.stopEvent(evt);
return ret;
},_getId:function(evt,_1c){
return this.util.attr(evt,"id",null,_1c);
},_getXY:function(evt){
return {x:evt.pageX,y:evt.pageY};
},setCursor:function(_1d,_1e){
if(!_1e){
_1.style(this.container,"cursor",_1d);
}else{
_1.style(_1e,"cursor",_1d);
}
}});
});
|
<?php $tag = $block->subject ? 'section' : 'div'; ?>
<<?php print $tag; ?><?php print $attributes; ?>>
<div class="block-inner clearfix">
<?php print render($title_prefix); ?>
<?php if ($block->subject): ?>
<h2<?php print $title_attributes; ?>><span class="block-title-icon"></span><?php print $block->subject; ?></h2>
<?php endif; ?>
<?php print render($title_suffix); ?>
<div<?php print $content_attributes; ?>>
<?php print $content ?>
</div>
</div>
</<?php print $tag; ?>>
|
#!/usr/bin/python
# -*- encoding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
# Copyright (C) OpenERP Venezuela (<http://openerp.com.ve>).
# All Rights Reserved
###############Credits######################################################
# Coded by: Javier Duran <[email protected]>
# Planified by: Nhomar Hernandez
# Audited by: Vauxoo C.A.
#############################################################################
# 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/>.
################################################################################
import wh_src_report
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'WMS Landed Costs',
'version': '1.1',
'summary': 'Landed Costs',
'description': """
Landed Costs Management
=======================
This module allows you to easily add extra costs on pickings and decide the split of these costs among their stock moves in order to take them into account in your stock valuation.
""",
'website': 'https://www.odoo.com/page/warehouse',
'depends': ['stock_account', 'purchase'],
'category': 'Warehouse Management',
'sequence': 16,
'demo': [
],
'data': [
'security/ir.model.access.csv',
'stock_landed_costs_sequence.xml',
'product_view.xml',
'stock_landed_costs_view.xml',
'stock_landed_costs_data.xml',
],
'test': [
'../account/test/account_minimal_test.xml',
'../stock_account/test/stock_valuation_account.xml',
'test/stock_landed_costs.yml',
'test/stock_landed_costs_rounding.yml',
],
'installable': True,
'auto_install': False,
}
|
"""
This defines a generic session class. All connection instances (both
on Portal and Server side) should inherit from this class.
"""
import time
#------------------------------------------------------------
# Server Session
#------------------------------------------------------------
class Session(object):
"""
This class represents a player's session and is a template for
both portal- and server-side sessions.
Each connection will see two session instances created:
1) A Portal session. This is customized for the respective connection
protocols that Evennia supports, like Telnet, SSH etc. The Portal
session must call init_session() as part of its initialization. The
respective hook methods should be connected to the methods unique
for the respective protocol so that there is a unified interface
to Evennia.
2) A Server session. This is the same for all connected players,
regardless of how they connect.
The Portal and Server have their own respective sessionhandlers. These
are synced whenever new connections happen or the Server restarts etc,
which means much of the same information must be stored in both places
e.g. the portal can re-sync with the server when the server reboots.
"""
# names of attributes that should be affected by syncing.
_attrs_to_sync = ('protocol_key', 'address', 'suid', 'sessid', 'uid',
'uname', 'logged_in', 'puid', 'encoding',
'conn_time', 'cmd_last', 'cmd_last_visible', 'cmd_total',
'protocol_flags', 'server_data', "cmdset_storage_string")
def init_session(self, protocol_key, address, sessionhandler):
"""
Initialize the Session. This should be called by the protocol when
a new session is established.
protocol_key - telnet, ssh, ssl or web
address - client address
sessionhandler - reference to the sessionhandler instance
"""
# This is currently 'telnet', 'ssh', 'ssl' or 'web'
self.protocol_key = protocol_key
# Protocol address tied to this session
self.address = address
# suid is used by some protocols, it's a hex key.
self.suid = None
# unique id for this session
self.sessid = 0 # no sessid yet
# database id for the user connected to this session
self.uid = None
# user name, for easier tracking of sessions
self.uname = None
# if user has authenticated already or not
self.logged_in = False
# database id of puppeted object (if any)
self.puid = None
# session time statistics
self.conn_time = time.time()
self.cmd_last_visible = self.conn_time
self.cmd_last = self.conn_time
self.cmd_total = 0
self.encoding = "utf-8"
self.protocol_flags = {}
self.server_data = {}
# a back-reference to the relevant sessionhandler this
# session is stored in.
self.sessionhandler = sessionhandler
def get_sync_data(self):
"""
Return all data relevant to sync the session
"""
return dict((key, value) for key, value in self.__dict__.items()
if key in self._attrs_to_sync)
def load_sync_data(self, sessdata):
"""
Takes a session dictionary, as created by get_sync_data,
and loads it into the correct properties of the session.
"""
for propname, value in sessdata.items():
setattr(self, propname, value)
def at_sync(self):
"""
Called after a session has been fully synced (including
secondary operations such as setting self.player based
on uid etc).
"""
pass
# access hooks
def disconnect(self, reason=None):
"""
generic hook called from the outside to disconnect this session
should be connected to the protocols actual disconnect mechanism.
"""
pass
def data_out(self, text=None, **kwargs):
"""
generic hook for sending data out through the protocol. Server
protocols can use this right away. Portal sessions
should overload this to format/handle the outgoing data as needed.
"""
pass
def data_in(self, text=None, **kwargs):
"""
hook for protocols to send incoming data to the engine.
"""
pass
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using Neuronic.CollectionModel.Collections.Containers;
using Neuronic.CollectionModel.WeakEventPattern;
namespace Neuronic.CollectionModel.Collections
{
/// <summary>
/// Base class for dynamic transforming collections.
/// </summary>
/// <typeparam name="TSource">The type of the source items.</typeparam>
/// <typeparam name="TTarget">The type of the transformed items.</typeparam>
public abstract class IndexedTransformingReadOnlyObservableListBase<TSource, TTarget> : IndexedReadOnlyObservableListBase<TSource, TTarget>, IWeakEventListener
{
private readonly IEqualityComparer<IndexedItemContainer<TSource, TTarget>> _sourceComparer;
private readonly IEnumerable<TSource> _source;
/// <summary>
/// Initializes a new instance of the <see cref="TransformingReadOnlyObservableList{TSource, TTarget}" /> class.
/// </summary>
/// <param name="source">The source collection.</param>
/// <param name="selector">The transformation to apply to the items in <paramref name="source" />.</param>
/// <param name="onRemove">The callback to execute when an item is removed from the collection.</param>
/// <param name="onChange">The callback to execute when a value changes in the collection.</param>
/// <param name="sourceComparer">
/// A comparer for the list items. This is only used if the source collection is not a list
/// and does not provide index information in its <see cref="NotifyCollectionChangedEventArgs"/> events.
/// </param>
public IndexedTransformingReadOnlyObservableListBase(IEnumerable<TSource> source,
Func<TSource, IObservable<TTarget>> selector, Action<TTarget> onRemove = null,
Action<TTarget, TTarget> onChange = null, IEqualityComparer<TSource> sourceComparer = null)
: base (source, selector, onRemove, onChange)
{
_source = source;
_sourceComparer = new ContainerEqualityComparer<TSource, IndexedItemContainer<TSource, TTarget>>(sourceComparer);
if (_source is INotifyCollectionChanged notifier)
CollectionChangedEventManager.AddListener(notifier, this);
}
bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
{
if (!ReferenceEquals(_source, sender) || managerType != typeof(CollectionChangedEventManager))
return false;
SourceOnCollectionChanged(sender, (NotifyCollectionChangedEventArgs)e);
return true;
}
private void SourceOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
Items.UpdateCollection(_source, e, o => CreateContainer((TSource) o), RemoveContainer, _sourceComparer);
}
}
}
|
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2011-2013 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM 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.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::constIsoSolidTransport
Description
Constant properties Transport package.
Templated into a given thermodynamics package (needed for thermal
conductivity).
SourceFiles
constIsoSolidTransportI.H
constIsoSolidTransport.C
\*---------------------------------------------------------------------------*/
#ifndef constIsoSolidTransport_H
#define constIsoSolidTransport_H
#include "vector.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
template<class Thermo> class constIsoSolidTransport;
template<class Thermo>
inline constIsoSolidTransport<Thermo> operator*
(
const scalar,
const constIsoSolidTransport<Thermo>&
);
template<class Thermo>
Ostream& operator<<
(
Ostream&,
const constIsoSolidTransport<Thermo>&
);
/*---------------------------------------------------------------------------*\
Class constIsoSolidTransport Declaration
\*---------------------------------------------------------------------------*/
template<class Thermo>
class constIsoSolidTransport
:
public Thermo
{
// Private data
//- Constant isotropic thermal conductivity
scalar kappa_;
// Private Member Functions
//- Construct from components
inline constIsoSolidTransport(const Thermo& t, const scalar kappa);
public:
// Constructors
//- Construct as named copy
inline constIsoSolidTransport
(
const word&,
const constIsoSolidTransport&
);
//- Construct from Istream
constIsoSolidTransport(const dictionary& dict);
// Selector from dictionary
inline static autoPtr<constIsoSolidTransport> New
(
const dictionary& dict
);
// Member functions
//- Return the instantiated type name
static word typeName()
{
return "constIso<" + Thermo::typeName() + '>';
}
//- Is the thermal conductivity isotropic
static const bool isotropic = true;
//- Isotropic thermal conductivity [W/mK]
inline scalar kappa(const scalar p, const scalar T) const;
//- Un-isotropic thermal conductivity [W/mK]
inline vector Kappa(const scalar p, const scalar T) const;
//- Dynamic viscosity [kg/ms]
inline scalar mu(const scalar p, const scalar T) const;
//- Thermal diffusivity of enthalpy [kg/ms]
inline scalar alphah(const scalar p, const scalar T) const;
//- Write to Ostream
void write(Ostream& os) const;
// Member operators
inline constIsoSolidTransport& operator=
(
const constIsoSolidTransport&
);
inline void operator+=(const constIsoSolidTransport&);
inline void operator-=(const constIsoSolidTransport&);
// Friend operators
friend constIsoSolidTransport operator* <Thermo>
(
const scalar,
const constIsoSolidTransport&
);
// Ostream Operator
friend Ostream& operator<< <Thermo>
(
Ostream&,
const constIsoSolidTransport&
);
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#include "constIsoSolidTransportI.H"
#ifdef NoRepository
# include "constIsoSolidTransport.C"
#endif
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
|
# Output to File classes.
#
# Author: Just van den Broecke
#
import os
from stetl.output import Output
from stetl.util import Util
from stetl.packet import FORMAT
from stetl.component import Config
log = Util.get_log('fileoutput')
class FileOutput(Output):
"""
Pretty print input to file. Input may be an etree doc or any other stringify-able input.
consumes=FORMAT.any
"""
# Start attribute config meta
@Config(ptype=str, default=None, required=True)
def file_path(self):
"""
Path to file, for MultiFileOutput can be of the form like: gmlcities-%03d.gml
"""
pass
# End attribute config meta
def __init__(self, configdict, section):
Output.__init__(self, configdict, section, consumes=FORMAT.any)
log.info("working dir %s" % os.getcwd())
def write(self, packet):
if packet.data is None:
return packet
return self.write_file(packet, self.file_path)
def write_file(self, packet, file_path):
log.info('writing to file %s' % file_path)
out_file = open(file_path, 'w')
out_file.write(packet.to_string())
out_file.close()
log.info("written to %s" % file_path)
return packet
class MultiFileOutput(FileOutput):
"""
Print to multiple files from subsequent packets like strings or etree docs, file_path must be of a form like: gmlcities-%03d.gml.
consumes=FORMAT.any
"""
def __init__(self, configdict, section):
Output.__init__(self, configdict, section, consumes=FORMAT.any)
self.file_num = 1
def write(self, packet):
if packet.data is None:
return packet
# file_path must be of the form: gmlcities-%03d.gml
file_path = self.file_path % self.file_num
self.file_num += 1
return self.write_file(packet, file_path)
|
#pragma ident "$Id$"
//============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// any later version.
//
// The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Copyright 2009, The University of Texas at Austin
//
//============================================================================
#ifndef XCOMMONTIME_HPP
#define XCOMMONTIME_HPP
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include "CommonTime.hpp"
using namespace std;
class xCommonTime: public CPPUNIT_NS :: TestFixture
{
CPPUNIT_TEST_SUITE (xCommonTime);
CPPUNIT_TEST (setTest);
CPPUNIT_TEST (arithmiticTest);
CPPUNIT_TEST_SUITE_END ();
public:
void setUp (void);
protected:
void setTest (void);
void arithmiticTest (void);
private:
};
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.