text
stringlengths 2
6.14k
|
|---|
//https://angular.io/docs/ts/latest/tutorial/toh-pt6.html
import { Injectable } from '@angular/core';
import { Headers, Http, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/Rx';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class HttpService {
private apiBaseUrl = "http://localhost:58551/api";
private options: RequestOptions;
constructor(private http: Http) {
}
private configure() {
let token = localStorage.getItem('token');
let headers = new Headers();
headers = new Headers({
'Content-Type': 'application/json'
});
this.options = new RequestOptions({ headers: headers });
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
search(url): Observable<any> {
url = `${this.apiBaseUrl}/${url}`;
this.configure();
return this.http
.get(url, this.options)
.map((r: Response) => r.json());
}
get(url): Promise<any> {
url = `${this.apiBaseUrl}/${url}`;
this.configure();
return this.http.get(url, this.options)
.toPromise()
.then(response => response.json() )
.catch(this.handleError);
}
post(url, data): Promise<any> {
url = `${this.apiBaseUrl}/${url}`;
this.configure();
return this.http
.post(url, JSON.stringify(data), this.options)
.toPromise()
.then(res => res.json())
.catch(this.handleError);
}
delete(url): Promise<void> {
url = `${this.apiBaseUrl}/${url}`;
this.configure();
return this.http.delete(url, this.options)
.toPromise()
.then(() => null)
.catch(this.handleError);
}
}
|
from StringIO import StringIO
import sys
from django.core import management
from waffle import Switch, Flag, Sample
from publicweb.tests.open_consent_test_case import EconsensusFixtureTestCase
class WaffleCommandTest(EconsensusFixtureTestCase):
fixtures = ['default_waffles.json']
def setUp(self):
self.output = StringIO()
self.saved_output = sys.stdout
sys.stdout = self.output
def tearDown(self):
self.output.close()
sys.stdout = self.saved_output
def _delete_waffles(self):
"""Delete all waffles"""
for switch in Switch.objects.all():
switch.delete()
for flag in Flag.objects.all():
flag.delete()
for sample in Sample.objects.all():
sample.delete()
def _requires_initializing(self):
"""Returns true if waffles need initializing, False if not."""
management.call_command('waffles_need_initializing')
output = self.output.getvalue()
return int(output.strip()) == 1
def test_having_no_waffles_requires_initializing(self):
self._delete_waffles()
self.assertTrue(self._requires_initializing())
def test_if_switch_is_present_no_initialization_is_required(self):
self._delete_waffles()
switch = Switch(name='test')
switch.save()
self.assertFalse(self._requires_initializing())
def test_if_flag_is_present_no_initialization_is_required(self):
self._delete_waffles()
flag = Flag(name='test')
flag.save()
self.assertFalse(self._requires_initializing())
def test_if_sample_is_present_no_initialization_is_required(self):
self._delete_waffles()
sample = Sample(name='test', percent=0)
sample.save()
self.assertFalse(self._requires_initializing())
|
# -*- coding: utf-8 -*-
# Licensed under the Apache-2.0 License, see LICENSE for details.
"""This module extract the RS_API_VERSION to which pyrealsense is binded and wraps several enums
from rs.h into classes with the same name."""
import pycparser
import io
# Platform dependent
import os
import sys
from os import environ, path
## construct path to librealsense/rs.h
if 'PYRS_INCLUDES' in environ:
rs_h_filename = path.join(environ['PYRS_INCLUDES'], 'rs.h')
## for docs, use locally stored
elif os.environ.get('READTHEDOCS') == 'True':
rs_h_filename = './rs.h'
elif sys.platform == 'win32':
raise Exception('PYRS_INCLUDES must be set to the location of the librealsense headers!')
else:
rs_h_filename = '/usr/local/include/librealsense/rs.h'
## if not found, exit
if not path.exists(rs_h_filename):
raise Exception('librealsense/rs.h header not found at {}'.format(rs_h_filename))
# Dynamically extract API version
api_version = 0
with io.open(rs_h_filename, encoding='latin') as rs_h_file:
for l in rs_h_file.readlines():
if 'RS_API' in l:
key, val = l.split()[1:]
globals()[key] = val
api_version = api_version * 100 + int(val)
if api_version >= 10000:
break
globals()['RS_API_VERSION'] = api_version
def _get_enumlist(obj):
for _, cc in obj.children():
if type(cc) is pycparser.c_ast.EnumeratorList:
return cc
else:
return _get_enumlist(cc)
# Dynamically generate classes
ast = pycparser.parse_file(rs_h_filename, use_cpp=True)
for c in ast.ext:
if c.name in ['rs_capabilities',
'rs_stream',
'rs_format',
'rs_distortion',
'rs_ivcam_preset',
'rs_option']:
e = _get_enumlist(c)
class_name = c.name
class_dict = {}
for i, (_, child) in enumerate(e.children()):
class_dict[child.name] = i
name_for_value = {}
for key, val in class_dict.items():
name_for_value[val] = key
class_dict['name_for_value'] = name_for_value
# Generate the class and add to global scope
class_gen = type(class_name, (object,), class_dict)
globals()[class_name] = class_gen
del class_gen
|
# This file is part of Invenio.
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 CERN.
#
# Invenio 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.
#
# Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""
invenio.modules.search.washers
------------------------------
Implements search washers.
"""
from invenio.base.globals import cfg
from invenio.utils.datastructures import LazyDict
def get_search_results_default_urlargd():
"""Returns default config for search results arguments."""
return {
'cc': (str, cfg['CFG_SITE_NAME']),
'c': (list, []),
'p': (str, ""), 'f': (str, ""),
'rg': (int, cfg['CFG_WEBSEARCH_DEF_RECORDS_IN_GROUPS']),
'sf': (str, ""),
'so': (str, "d"),
'sp': (str, ""),
'rm': (str, ""),
'of': (str, "hb"),
'ot': (list, []),
'em': (str,""),
'aas': (int, cfg['CFG_WEBSEARCH_DEFAULT_SEARCH_INTERFACE']),
'as': (int, cfg['CFG_WEBSEARCH_DEFAULT_SEARCH_INTERFACE']),
'p1': (str, ""), 'f1': (str, ""), 'm1': (str, ""), 'op1':(str, ""),
'p2': (str, ""), 'f2': (str, ""), 'm2': (str, ""), 'op2':(str, ""),
'p3': (str, ""), 'f3': (str, ""), 'm3': (str, ""),
'sc': (int, 0),
'jrec': (int, 0),
'recid': (int, -1), 'recidb': (int, -1), 'sysno': (str, ""),
'id': (int, -1), 'idb': (int, -1), 'sysnb': (str, ""),
'action': (str, "search"),
'action_search': (str, ""),
'action_browse': (str, ""),
'd1': (str, ""),
'd1y': (int, 0), 'd1m': (int, 0), 'd1d': (int, 0),
'd2': (str, ""),
'd2y': (int, 0), 'd2m': (int, 0), 'd2d': (int, 0),
'dt': (str, ""),
'ap': (int, 1),
'verbose': (int, 0),
'ec': (list, []),
'wl': (int, cfg['CFG_WEBSEARCH_WILDCARD_LIMIT']),
}
search_results_default_urlargd = LazyDict(get_search_results_default_urlargd)
def wash_search_urlargd(form):
"""
Create canonical search arguments from those passed via web form.
"""
from invenio.ext.legacy.handler import wash_urlargd
argd = wash_urlargd(form, search_results_default_urlargd)
if 'as' in argd:
argd['aas'] = argd['as']
del argd['as']
if argd.get('aas', cfg['CFG_WEBSEARCH_DEFAULT_SEARCH_INTERFACE']) \
not in cfg['CFG_WEBSEARCH_ENABLED_SEARCH_INTERFACES']:
argd['aas'] = cfg['CFG_WEBSEARCH_DEFAULT_SEARCH_INTERFACE']
# Sometimes, users pass ot=245,700 instead of
# ot=245&ot=700. Normalize that.
ots = []
for ot in argd['ot']:
ots += ot.split(',')
argd['ot'] = ots
# We can either get the mode of function as
# action=<browse|search>, or by setting action_browse or
# action_search.
if argd['action_browse']:
argd['action'] = 'browse'
elif argd['action_search']:
argd['action'] = 'search'
else:
if argd['action'] not in ('browse', 'search'):
argd['action'] = 'search'
del argd['action_browse']
del argd['action_search']
if argd['em'] != "":
argd['em'] = argd['em'].split(",")
return argd
|
<?php
/**
* Copyright (c) 2011 Fernando Ribeiro
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the names of the copyright holders nor the names of the
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package Netcrash
* @subpackage Groupon
* @author Fernando Andre <netriver+GrouponApi at gmail dit com>
* @copyright 2011 Fernando Ribeiro http://netcrash.wordpress.com
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @link
* @version @@PACKAGE_VERSION@@
*/
namespace Netcrash\Groupon\DataObject;
/**
* The data information of the Division
*
* for details about the properties please see the api documentation
* for divisions.
*
* @author andref
*
*/
class Division extends Basic
{
private $IsRewardEnabled;
public function setIsRewardEnabled($val)
{
$this->IsRewardEnabled = $val;
}
public function getIsRewardEnabled()
{
return $this->IsRewardEnabled;
}
private $Timezone;
public function setTimezone($val)
{
$this->Timezone = $val;
}
public function getTimezone()
{
return $this->Timezone;
}
private $IsNowMerchantEnabled;
public function setIsNowMerchantEnabled($val)
{
$this->IsNowMerchantEnabled = $val;
}
public function getIsNowMerchantEnabled()
{
return $this->IsNowMerchantEnabled;
}
private $Name;
public function setName($val)
{
$this->Name = $val;
}
public function getName()
{
return $this->Name;
}
private $Id;
public function setId($val)
{
$this->Id = $val;
}
public function getId()
{
return $this->Id;
}
private $Areas;
public function setAreas($val)
{
$this->Areas = $val;
}
public function getAreas()
{
return $this->Areas;
}
private $IsNowCustomerEnabled;
public function setIsNowCustomerEnabled($val)
{
$this->IsNowCustomerEnabled = $val;
}
public function getIsNowCustomerEnabled()
{
return $this->IsNowCustomerEnabled;
}
private $TimezoneOffsetInSeconds;
public function setTimezoneOffsetInSeconds($val)
{
$this->TimezoneOffsetInSeconds = $val;
}
public function getTimezoneOffsetInSeconds(){
return $this->TimezoneOffsetInSeconds;
}
private $Country;
public function setCountry($val) {
$this->Country = $val;
}
public function getCountry(){
return $this->Country;
}
public function __toString()
{
return $this->getId();
}
}
|
import {Injectable, Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'todosFilter'
})
@Injectable()
export class TodosFilterPipe implements PipeTransform {
transform(items: any[], status: string): any {
if (!status) {
return items;
}
return items.filter(item => item.status === status);
}
}
|
import functools
import glib
from gi.repository import Gtk
from kupfer import version, config
def idle_call(func):
@functools.wraps(func)
def idle_wrapper(*args):
glib.idle_add(func, *args)
return idle_wrapper
_HEADER_MARKUP = '<span weight="bold" size="larger">%s</span>'
class ProgressDialogController (object):
def __init__(self, title, header=None, max_value=100):
"""Create a new progress dialog
@header: first line of dialog
The methods show, hide and update are all wrapped to be
safe to call from any thread.
"""
self.aborted = False
self.max_value = float(max_value)
ui_file = config.get_data_file("progress_dialog.ui")
self._construct_dialog(ui_file, title, header)
@idle_call
def _construct_dialog(self, ui_file, title, header):
builder = Gtk.Builder()
builder.set_translation_domain(version.PACKAGE_NAME)
builder.add_from_file(ui_file)
builder.connect_signals(self)
self.window = builder.get_object("window_progress")
self.button_abort = builder.get_object('button_abort')
self.progressbar = builder.get_object('progressbar')
self.label_info = builder.get_object('label_info')
self.label_header = builder.get_object('label_header')
self.window.set_title(title)
if header:
self.label_header.set_markup(_HEADER_MARKUP %
glib.markup_escape_text(header))
else:
self.label_header.hide()
self.update(0, '', '')
def on_button_abort_clicked(self, widget):
self.aborted = True
self.button_abort.set_sensitive(False)
@idle_call
def show(self):
self.window.present()
@idle_call
def hide(self):
self.window.hide()
@idle_call
def update(self, value, label, text):
""" Update dialog information.
@value: value to set for progress bar
@label: current action (displayed in emphasized style)
@text: current information (normal style)
"""
self.progressbar.set_fraction(min(value/self.max_value, 1.0))
self.label_info.set_markup("<b>%s</b> %s" %
(
glib.markup_escape_text(label),
glib.markup_escape_text(text),
))
return self.aborted
|
import os
import tempfile
import shutil
import unittest
import tables
from simphony.cuds.particles import Particles
from simphony.io.h5_cuds import H5CUDS
from simphony.io.h5_particles import H5Particles
from simphony.io.data_container_description import SUPPORTED_CUBA
from simphony.testing.abc_check_particles import (
CheckManipulatingBonds, CheckAddingParticles,
CheckAddingBonds, CheckManipulatingParticles)
class TestH5ContainerAddParticles(CheckAddingParticles, unittest.TestCase):
def container_factory(self, name):
self.handle.add_dataset(Particles(name=name))
return self.handle.get_dataset(name)
def supported_cuba(self):
return SUPPORTED_CUBA
def setUp(self):
self.temp_dir = tempfile.mkdtemp()
self.filename = os.path.join(self.temp_dir, 'test_file.cuds')
self.addCleanup(self.cleanup)
self.handle = H5CUDS.open(self.filename)
CheckAddingParticles.setUp(self)
def cleanup(self):
if os.path.exists(self.filename):
self.handle.close()
shutil.rmtree(self.temp_dir)
class TestH5ContainerManipulatingParticles(
CheckManipulatingParticles, unittest.TestCase):
def container_factory(self, name):
self.handle.add_dataset(Particles(name=name))
return self.handle.get_dataset(name)
def supported_cuba(self):
return SUPPORTED_CUBA
def setUp(self):
self.temp_dir = tempfile.mkdtemp()
self.filename = os.path.join(self.temp_dir, 'test_file.cuds')
self.addCleanup(self.cleanup)
self.handle = H5CUDS.open(self.filename)
CheckManipulatingParticles.setUp(self)
def cleanup(self):
if os.path.exists(self.filename):
self.handle.close()
shutil.rmtree(self.temp_dir)
class TestH5ContainerAddBonds(CheckAddingBonds, unittest.TestCase):
def container_factory(self, name):
self.handle.add_dataset(Particles(name=name))
return self.handle.get_dataset(name)
def supported_cuba(self):
return SUPPORTED_CUBA
def setUp(self):
self.temp_dir = tempfile.mkdtemp()
self.filename = os.path.join(self.temp_dir, 'test_file.cuds')
self.addCleanup(self.cleanup)
self.handle = H5CUDS.open(self.filename)
CheckAddingBonds.setUp(self)
def cleanup(self):
if os.path.exists(self.filename):
self.handle.close()
shutil.rmtree(self.temp_dir)
class TestH5ContainerManipulatingBonds(
CheckManipulatingBonds, unittest.TestCase):
def container_factory(self, name):
self.handle.add_dataset(Particles(name=name))
return self.handle.get_dataset(name)
def supported_cuba(self):
return SUPPORTED_CUBA
def setUp(self):
self.temp_dir = tempfile.mkdtemp()
self.filename = os.path.join(self.temp_dir, 'test_file.cuds')
self.addCleanup(self.cleanup)
self.handle = H5CUDS.open(self.filename)
CheckManipulatingBonds.setUp(self)
def cleanup(self):
if os.path.exists(self.filename):
self.handle.close()
shutil.rmtree(self.temp_dir)
class TestH5ParticlesVersions(unittest.TestCase):
def setUp(self):
self.temp_dir = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.temp_dir)
def test_version(self):
filename = os.path.join(self.temp_dir, 'test_file.cuds')
group_name = "dummy_component_name"
with tables.open_file(filename, 'w') as handle:
group = handle.create_group(handle.root, group_name)
# given/when
H5Particles(group)
# then
self.assertTrue(isinstance(group._v_attrs.cuds_version, int))
# when
with tables.open_file(filename, 'a') as handle:
handle.get_node("/" + group_name)._v_attrs.cuds_version = -1
# then
with tables.open_file(filename, 'a') as handle:
with self.assertRaises(ValueError):
H5Particles(handle.get_node("/" + group_name))
if __name__ == '__main__':
unittest.main()
|
const {Component, EventEmitter, Inject, Input, Output} = require("../../export-switch");
const template = process.env.NG2 ? require("./templates/ng2.html") : require("./templates/ng1.html");
@Component({
selector: "child-app",
template
})
export class ChildAppComponent {
@Output() onAdd = new EventEmitter();
@Output() onRemove = new EventEmitter();
add() {
this.onAdd.emit("Added " + Math.random());
}
remove() {
this.onRemove.emit();
}
}
|
<?php
/**
* PhpThumb Library Example File
*
* This file contains example usage for the PHP Thumb Library
*
* PHP Version 5 with GD 2.0+
* PhpThumb : PHP Thumb Library <http://phpthumb.gxdlabs.com>
* Copyright (c) 2009, Ian Selby/Gen X Design
*
* Author(s): Ian Selby <[email protected]>
*
* Licensed under the MIT License
* Redistributions of files must retain the above copyright notice.
*
* @author Ian Selby <[email protected]>
* @copyright Copyright (c) 2009 Gen X Design
* @link http://phpthumb.gxdlabs.com
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
* @version 3.0
* @package PhpThumb
* @subpackage Examples
* @filesource
*/
require_once '../ThumbLib.inc.php';
$thumb = PhpThumbFactory::create('test.jpg');
$thumb->adaptiveResize(300, 300);
$thumb->save('test.png', 'png');
?>
|
package com.ganxin.codebase.utils.sharedpreferences;
import android.content.Context;
import com.ganxin.codebase.application.ConstantValues;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Description : 设置管理类 <br/>
* author : WangGanxin <br/>
* date : 2016/12/16 <br/>
* email : [email protected] <br/>
*/
public class SettingManager implements OnSharedataCommitListener {
private SettingManager() {
}
private static class SettingManagerHolder{
private static final SettingManager INSTANCE=new SettingManager();
}
public static SettingManager getInstance() {
return SettingManagerHolder.INSTANCE;
}
private HashMap<String, List<OnSettingsChangedListenr>> listeners = new HashMap<>();
/**
* 添加设置监听
* @param listener 监听对象
* @param type 类型
* <li>{@link ConstantValues#SETTING_TYPE_ONE} 设置的类型
*/
public void addSettingsChangedListener(OnSettingsChangedListenr listener,
String... type) {
if (listener == null || type == null)
return;
for (int i = 0; i < type.length; i++) {
List<OnSettingsChangedListenr> list = listeners.get(type[i]);
if (list == null) {
list = new ArrayList<>();
}
list.add(listener);
listeners.put(type[i], list);
}
}
/**
* 解除设置监听
* @param type 类型
* <li>{@link ConstantValues#SETTING_TYPE_ONE} 设置的类型
*/
public void removeSettingsChangedListener(String... type) {
if(listeners!=null&&listeners.size()>0){
for (int i = 0; i < type.length; i++) {
listeners.remove(type[i]);
}
}
}
private void notifySettingsChanged(String type, Object newVal) {
List<OnSettingsChangedListenr> list = listeners.get(type);
if (list != null) {
for (OnSettingsChangedListenr scl : list) {
scl.settingsChanged(type, newVal);
}
}
}
@Override
public void onSharedataCommit(String configKey, Object configValue) {
notifySettingsChanged(configKey, configValue);
}
/**
* @param context
* @param value
*/
public void setStatus(Context context, boolean value) {
SharedPreferencesAccessor.setConfig(context, ConstantValues.SHARPREFER_FILENAME,
ConstantValues.SETTING_TYPE_ONE, value, this);
}
/**
* @param context
* @return
*/
public boolean getStatus(Context context) {
return SharedPreferencesAccessor.getBooleanConfig(context, ConstantValues.SHARPREFER_FILENAME,
ConstantValues.SETTING_TYPE_ONE, false);
}
}
|
# Simple servo control device
# author: ulno
# created: 2017-06-05
#
# based off: https://bitbucket.org/thesheep/micropython-servo/src/f562a6abeaf0e83b752838df7cd31d88ea10b2c7/servo.py?at=default&fileviewer=file-view-default
import time
from machine import PWM
from uiot.device import Device
class Servo(Device):
# Handle output devices
def __init__(self, name, pin,
ignore_case=True, on_change=None,
report_change=False,
turn_time_ms=700,
freq=50, min_us=600, max_us=2400, angle=180):
self.min_us = min_us
self.max_us = max_us
self.us = 0
self.freq = freq
self.angle = angle
self.angle_list = None
self.turn_time_ms = turn_time_ms
self.turn_start = None
Device.__init__(self, name, PWM(pin, freq=self.freq, duty=0),
setters={"set": self.turn}, ignore_case=ignore_case,
on_change=on_change, report_change=report_change)
self._init()
def _init(self):
self.port.init()
def _trigger_next_turn(self):
self.turn_start = time.ticks_ms()
if len(self.angle_list) > 0:
self.write_angle(self.angle_list[0])
del self.angle_list[0]
def turn(self, msg):
if type(msg) in [str, int]:
self.angle_list = [int(msg)] # TODO: accept floats?
else: # should be a list
self.angle_list = msg[:]
self._trigger_next_turn()
def write_us(self, us):
if us == 0:
self.port.duty(0)
return
us = min(self.max_us, max(self.min_us, us))
duty = us * 1024 * self.freq // 1000000
self.port.duty(duty)
def write_angle(self, degrees=None):
degrees = degrees % 360
total_range = self.max_us - self.min_us
us = self.min_us + total_range * degrees // self.angle
self.write_us(us)
def measure(self):
if self.turn_start is not None: # turn in process
current = time.ticks_ms()
if time.ticks_diff(current, self.turn_start) >= self.turn_time_ms:
if len(self.angle_list) > 0:
self._trigger_next_turn()
else:
self._release()
return self.angle_list
def _release(self):
self.turn_start = None
self.port.deinit()
|
/*
* Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/**
* 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 com.sun.org.apache.xml.internal.security.signature;
/**
* Raised if verifying a {@link Reference} fails
* because of an uninitialized {@link XMLSignatureInput}
*
* @author Christian Geuer-Pollmann
*/
public class ReferenceNotInitializedException extends XMLSignatureException {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Constructor ReferenceNotInitializedException
*
*/
public ReferenceNotInitializedException() {
super();
}
/**
* Constructor ReferenceNotInitializedException
*
* @param msgID
*/
public ReferenceNotInitializedException(String msgID) {
super(msgID);
}
/**
* Constructor ReferenceNotInitializedException
*
* @param msgID
* @param exArgs
*/
public ReferenceNotInitializedException(String msgID, Object exArgs[]) {
super(msgID, exArgs);
}
/**
* Constructor ReferenceNotInitializedException
*
* @param msgID
* @param originalException
*/
public ReferenceNotInitializedException(String msgID, Exception originalException) {
super(msgID, originalException);
}
/**
* Constructor ReferenceNotInitializedException
*
* @param msgID
* @param exArgs
* @param originalException
*/
public ReferenceNotInitializedException(String msgID, Object exArgs[], Exception originalException) {
super(msgID, exArgs, originalException);
}
}
|
/*
* @BEGIN LICENSE
*
* Psi4: an open-source quantum chemistry software package
*
* Copyright (c) 2007-2019 The Psi4 Developers.
*
* The copyrights for code used from other parties are included in
* the corresponding files.
*
* This file is part of Psi4.
*
* Psi4 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, version 3.
*
* Psi4 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 Psi4; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* @END LICENSE
*/
/*! \file
\ingroup DPD
\brief Enter brief description of file here
*/
#include <cstdio>
#include "psi4/libqt/qt.h"
#include "dpd.h"
namespace psi {
/* buf4_axpbycz(): Evaluates the standard operation aX + bY -> cZ for
** dpdbuf4's.
**
** Arguments:
** dpdbuf4 *FileA: A pointer to the leftmost dpdbuf4.
** dpdbuf4 *FileB: A pointer to the rightmost summand dpdbuf4.
** dpdbuf4 *FileC: A pointer to the target dpdbuf4.
** double a, b, c, scalar prefactors
*/
int DPD::buf4_axpbycz(dpdbuf4 *FileA, dpdbuf4 *FileB, dpdbuf4 *FileC, double a, double b, double c) {
buf4_scm(FileC, c);
buf4_axpy(FileB, FileC, b);
buf4_axpy(FileA, FileC, a);
return 0;
}
} // namespace psi
|
//The MIT License(MIT)
//copyright(c) 2016 Greg Dennis & Alberto Rodríguez
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.
using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using LiveCharts.Helpers;
namespace LiveCharts.Wpf.Converters
{
/// <summary>
///
/// </summary>
/// <seealso cref="System.ComponentModel.TypeConverter" />
public class StringCollectionConverter : TypeConverter
{
/// <summary>
/// Returns whether this converter can convert an object of the given type to the type of this converter, using the specified context.
/// </summary>
/// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext" /> that provides a format context.</param>
/// <param name="sourceType">A <see cref="T:System.Type" /> that represents the type you want to convert from.</param>
/// <returns>
/// true if this converter can perform the conversion; otherwise, false.
/// </returns>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof (string) || base.CanConvertFrom(context, sourceType);
}
/// <summary>
/// Converts the given object to the type of this converter, using the specified context and culture information.
/// </summary>
/// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext" /> that provides a format context.</param>
/// <param name="culture">The <see cref="T:System.Globalization.CultureInfo" /> to use as the current culture.</param>
/// <param name="value">The <see cref="T:System.Object" /> to convert.</param>
/// <returns>
/// An <see cref="T:System.Object" /> that represents the converted value.
/// </returns>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
var valueString = value as string;
if (valueString != null)
{
return valueString.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Trim())
.ToArray();
}
return base.ConvertFrom(context, culture, value);
}
}
/// <summary>
///
/// </summary>
/// <seealso cref="System.ComponentModel.TypeConverter" />
public class NumericChartValuesConverter : TypeConverter
{
/// <summary>
/// Returns whether this converter can convert an object of the given type to the type of this converter, using the specified context.
/// </summary>
/// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext" /> that provides a format context.</param>
/// <param name="sourceType">A <see cref="T:System.Type" /> that represents the type you want to convert from.</param>
/// <returns>
/// true if this converter can perform the conversion; otherwise, false.
/// </returns>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
}
/// <summary>
/// Converts the given object to the type of this converter, using the specified context and culture information.
/// </summary>
/// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext" /> that provides a format context.</param>
/// <param name="culture">The <see cref="T:System.Globalization.CultureInfo" /> to use as the current culture.</param>
/// <param name="value">The <see cref="T:System.Object" /> to convert.</param>
/// <returns>
/// An <see cref="T:System.Object" /> that represents the converted value.
/// </returns>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
var valueString = value as string;
if (valueString != null)
{
return valueString.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
.Select(d => double.Parse(d, CultureInfo.InvariantCulture))
.AsChartValues();
}
return base.ConvertFrom(context, culture, value);
}
}
}
|
/*
* Copyright (C) 2003 Dizzy
*
* 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.
*/
#include "common/setup_before.h"
#ifndef HAVE_MMAP
#include <cstdlib>
#ifdef HAVE_SYS_TYPES_H
# include <sys/types.h>
#endif
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#include "common/xalloc.h"
#include "mmap.h"
#ifdef WIN32
# include <windows.h>
# include <io.h>
#endif
#include "common/setup_after.h"
namespace pvpgn
{
extern void * pmmap(void *addr, unsigned len, int prot, int flags, int fd, unsigned offset)
{
void *mem;
#ifdef WIN32
HANDLE hFile, hMapping;
/* under win32 we only support readonly mappings, the only ones used in pvpgn now :) */
if (prot != PROT_READ) return NULL;
hFile = (HANDLE) _get_osfhandle(fd);
if (hFile == (HANDLE) - 1) return MAP_FAILED;
hMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
if (!hMapping) return MAP_FAILED;
mem = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0 ,0);
#else /* systems without mmap or win32 */
unsigned pos;
int res;
mem = xmalloc(len);
pos = 0;
while(pos < len) {
res = read(fd, (char *)mem + pos, len - pos);
if (res < 0) {
xfree(mem);
return MAP_FAILED;
}
pos += res;
}
#endif
return mem;
}
extern int pmunmap(void *addr, unsigned len)
{
#ifdef WIN32
UnmapViewOfFile(addr);
#else
xfree(addr);
#endif
return 0;
}
}
#else
typedef int filenotempty; /* make ISO standard happy */
#endif
|
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test a node with the -disablewallet option.
- Test that validateaddress RPC works when running with -disablewallet
- Test that it is not possible to mine to an invalid address.
"""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
class DisableWalletTest (BitcoinTestFramework):
def __init__(self):
super().__init__()
self.setup_clean_chain = True
self.num_nodes = 1
def setup_network(self, split=False):
self.nodes = start_nodes(self.num_nodes, self.options.tmpdir, [['-disablewallet']])
self.is_network_split = False
self.sync_all()
def run_test (self):
# Check regression: https://github.com/bitcoin/bitcoin/issues/6963#issuecomment-154548880
x = self.nodes[0].validateaddress('7TSBtVu959hGEGPKyHjJz9k55RpWrPffXz')
assert(x['isvalid'] == False)
x = self.nodes[0].validateaddress('ycwedq2f3sz2Yf9JqZsBCQPxp18WU3Hp4J')
assert(x['isvalid'] == True)
# Checking mining to an address without a wallet
try:
self.nodes[0].generatetoaddress(1, 'ycwedq2f3sz2Yf9JqZsBCQPxp18WU3Hp4J')
except JSONRPCException as e:
assert("Invalid address" not in e.error['message'])
assert("ProcessNewBlock, block not accepted" not in e.error['message'])
assert("Couldn't create new block" not in e.error['message'])
try:
self.nodes[0].generatetoaddress(1, '7TSBtVu959hGEGPKyHjJz9k55RpWrPffXz')
raise AssertionError("Must not mine to invalid address!")
except JSONRPCException as e:
assert("Invalid address" in e.error['message'])
if __name__ == '__main__':
DisableWalletTest ().main ()
|
/* Copyright © Richard Kettlewell.
*
* 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/>.
*/
#include "mmui.h"
#include "MainMenu.h"
#include "GenericWindow.h"
#include "ControlPanel.h"
#include <gdk/gdkkeysyms.h>
#include <gtkmm/frame.h>
#include <gtkmm/box.h>
namespace mmui {
GenericWindow::GenericWindow(): view(NULL), controls(NULL) {}
void GenericWindow::Initialize(View *view_) {
view = view_;
controls = new ControlPanel(view);
view->SetControlPanel(controls);
add_events(Gdk::KEY_RELEASE_MASK);
Gtk::Frame *frame = manage(new Gtk::Frame());
frame->add(*controls);
Gtk::VBox *vbox = Gtk::manage(new Gtk::VBox(false, 0));
vbox->pack_start(*manage(new Menubar()), false, false, 1);
vbox->pack_start(*frame, false, false, 1);
vbox->pack_end(*view, true, true, 0);
add(*vbox);
}
bool GenericWindow::on_key_release_event(GdkEventKey *event) {
if((event->state & (Gdk::SHIFT_MASK | Gdk::CONTROL_MASK)) == Gdk::CONTROL_MASK) {
switch(event->keyval) {
case GDK_equal:
case GDK_minus:
case GDK_KP_Add:
case GDK_KP_Subtract: {
int w, h;
view->get_window()->get_size(w, h);
if(event->keyval == GDK_equal || event->keyval == GDK_KP_Add)
view->Zoom(w / 2.0, h / 2.0, M_SQRT1_2);
else
view->Zoom(w / 2.0, h / 2.0, M_SQRT2);
controls->UpdateDisplay();
view->NewLocation(w / 2, h / 2);
return true;
}
}
}
return false;
}
bool GenericWindow::on_delete_event(GdkEventAny *) {
return close();
}
} // namespace mmui
/*
Local Variables:
mode:c++
c-basic-offset:2
comment-column:40
fill-column:79
indent-tabs-mode:nil
End:
*/
|
#!/usr/bin/env python
import argparse
import sys
from wemo.environment import Environment
from wemo.utils import matcher
from wemo.signals import receiver, statechange, devicefound
def mainloop(name):
matches = matcher(name)
@receiver(devicefound)
def found(sender, **kwargs):
if matches(sender.name):
print("Found device:", sender.name)
@receiver(statechange)
def motion(sender, **kwargs):
if matches(sender.name):
print("{} state is {state}".format(
sender.name, state="on" if kwargs.get('state') else "off"))
env = Environment()
try:
env.start()
env.discover(10)
env.wait()
except (KeyboardInterrupt, SystemExit):
print("Goodbye!")
sys.exit(0)
if __name__ == "__main__":
parser = argparse.ArgumentParser("Motion notifier")
parser.add_argument("name", metavar="NAME",
help="Name (fuzzy matchable)"
" of the Motion to detect")
args = parser.parse_args()
mainloop(args.name)
|
from __future__ import unicode_literals
from django.core.exceptions import ImproperlyConfigured
from django.core.servers.basehttp import get_internal_wsgi_application
from django.core.signals import request_started
from django.core.wsgi import get_wsgi_application
from django.db import close_old_connections
from django.test import SimpleTestCase, override_settings
from django.test.client import RequestFactory
@override_settings(ROOT_URLCONF='wsgi.urls')
class WSGITest(SimpleTestCase):
def setUp(self):
request_started.disconnect(close_old_connections)
def tearDown(self):
request_started.connect(close_old_connections)
def test_get_wsgi_application(self):
"""
Verify that ``get_wsgi_application`` returns a functioning WSGI
callable.
"""
application = get_wsgi_application()
environ = RequestFactory()._base_environ(
PATH_INFO="/",
CONTENT_TYPE="text/html; charset=utf-8",
REQUEST_METHOD="GET"
)
response_data = {}
def start_response(status, headers):
response_data["status"] = status
response_data["headers"] = headers
response = application(environ, start_response)
self.assertEqual(response_data["status"], "200 OK")
self.assertEqual(
set(response_data["headers"]),
{('Content-Length', '12'), ('Content-Type', 'text/html; charset=utf-8')})
self.assertIn(bytes(response), [
b"Content-Length: 12\r\nContent-Type: text/html; charset=utf-8\r\n\r\nHello World!",
b"Content-Type: text/html; charset=utf-8\r\nContent-Length: 12\r\n\r\nHello World!"
])
def test_file_wrapper(self):
"""
Verify that FileResponse uses wsgi.file_wrapper.
"""
class FileWrapper(object):
def __init__(self, filelike, blksize=8192):
filelike.close()
application = get_wsgi_application()
environ = RequestFactory()._base_environ(
PATH_INFO='/file/',
REQUEST_METHOD='GET',
**{'wsgi.file_wrapper': FileWrapper}
)
response_data = {}
def start_response(status, headers):
response_data['status'] = status
response_data['headers'] = headers
response = application(environ, start_response)
self.assertEqual(response_data['status'], '200 OK')
self.assertIsInstance(response, FileWrapper)
class GetInternalWSGIApplicationTest(SimpleTestCase):
@override_settings(WSGI_APPLICATION="wsgi.wsgi.application")
def test_success(self):
"""
If ``WSGI_APPLICATION`` is a dotted path, the referenced object is
returned.
"""
app = get_internal_wsgi_application()
from .wsgi import application
self.assertIs(app, application)
@override_settings(WSGI_APPLICATION=None)
def test_default(self):
"""
If ``WSGI_APPLICATION`` is ``None``, the return value of
``get_wsgi_application`` is returned.
"""
# Mock out get_wsgi_application so we know its return value is used
fake_app = object()
def mock_get_wsgi_app():
return fake_app
from django.core.servers import basehttp
_orig_get_wsgi_app = basehttp.get_wsgi_application
basehttp.get_wsgi_application = mock_get_wsgi_app
try:
app = get_internal_wsgi_application()
self.assertIs(app, fake_app)
finally:
basehttp.get_wsgi_application = _orig_get_wsgi_app
@override_settings(WSGI_APPLICATION="wsgi.noexist.app")
def test_bad_module(self):
msg = "WSGI application 'wsgi.noexist.app' could not be loaded; Error importing"
with self.assertRaisesMessage(ImproperlyConfigured, msg):
get_internal_wsgi_application()
@override_settings(WSGI_APPLICATION="wsgi.wsgi.noexist")
def test_bad_name(self):
msg = "WSGI application 'wsgi.wsgi.noexist' could not be loaded; Error importing"
with self.assertRaisesMessage(ImproperlyConfigured, msg):
get_internal_wsgi_application()
|
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'iframe', 'th', {
border: 'Show frame border', // MISSING
noUrl: 'Please type the iframe URL', // MISSING
scrolling: 'Enable scrollbars', // MISSING
title: 'IFrame Properties', // MISSING
toolbar: 'IFrame'
} );
|
# -*- coding: utf-8 -*-
"""
xccdf.models.status includes the class Status
to create or import a <xccdf:status> element.
This module is part of the xccdf library.
Author: Rodrigo Núñez <[email protected]>
"""
# Python stdlib
from datetime import date
# lxml
from lxml import etree
# XCCDF
from xccdf.exceptions import InvalidValueException
from xccdf.models.element import Element
from xccdf.constants.status import STATUS_VALUE_CHOICES
from xccdf.constants import NSMAP
class Status(Element):
"""
Class to implement <xccdf:status> element.
"""
def __init__(self, xml_element=None, state=None):
"""
Initializes the attrs attribute to serialize the attributes.
:param lxml.etree._Element xml_element: XML element to load_xml_attrs.
:param str state: State string of this status
:raises ValueError: If no parameter is given.
:raises InvalidValueException: If the imported state string is not
one of the valid state strings.
"""
if xml_element is None and state is None:
raise ValueError('either xml_element or state are required')
self.text = state
tag_name = 'status' if xml_element is None else None
super(Status, self).__init__(xml_element, tag_name)
if self.text not in STATUS_VALUE_CHOICES:
val = '{val} is not valid. Must '\
'be one of this: {choices}'.format(
val=self.text, choices=repr(STATUS_VALUE_CHOICES))
raise InvalidValueException(val)
def __str__(self):
"""
String representation of Status object.
:returns: Status object as a string.
:rtype: str
"""
string_value = 'status {state}'.format(state=self.text)
if hasattr(self, 'date'):
string_value += ' ({date})'.format(date=self.date)
return string_value
def str_to_date(self):
"""
Returns the date attribute as a date object.
:returns: Date of the status if it exists.
:rtype: date or NoneType
"""
if hasattr(self, 'date'):
return date(*list(map(int, self.date.split('-'))))
else:
return None
def update_xml_element(self):
"""
Updates the xml element contents to matches the instance contents.
:returns: Updated XML element.
:rtype: lxml.etree._Element
"""
if not hasattr(self, 'xml_element'):
self.xml_element = etree.Element(self.name, nsmap=NSMAP)
if hasattr(self, 'date'):
self.xml_element.set('date', self.date)
self.xml_element.text = self.text
return self.xml_element
def to_xml_string(self):
"""
Exports the element in XML format.
:returns: element in XML format.
:rtype: str
"""
self.update_xml_element()
xml = self.xml_element
return etree.tostring(xml, pretty_print=True).decode('utf-8')
|
#!/usr/bin/env python3
import os,sys
from ftplib import FTP
from tempfile import mkdtemp
from shutil import rmtree
from http.client import HTTPConnection
from urllib.parse import urlsplit
def get_temp_dir(work_dir,prefix='temp'):
'''
This function returns a temporary directory
'''
try:
temp_dir=mkdtemp(prefix=prefix,dir=work_dir)
return temp_dir
except Exception as e:
print('Error: %s' % e)
def clean_temp_dir(temp_dir):
'''
This function delete a directory and all its contents
'''
if os.path.isdir(temp_dir):
try :
rmtree(temp_dir)
except Exception as e:
print('couldn\'t remove %s' % temp_dir)
else:
print('removed %s' % temp_dir)
def get_ftp_index(ftp_url='ftp.debian.org', dir='debian',index='README'):
'''
This function connect to a FTP server and retrieve a file
'''
with FTP(ftp_url) as ftp:
ftp.login()
ftp.cwd(dir)
ftp.retrbinary('RETR '+index, open(index,'wb').write)
ftp.quit()
def read_index_file(infile, f_header=[]):
'''
Read an index file and a list of fields (optional)
Returns a list of dictionary
'''
if len(f_header) == 0:
f_header=['EXPERIMENT_ID','FILE_TYPE','SAMPLE_NAME','EXPERIMENT_TYPE','FILE','LIBRARY_STRATEGY']
infile=os.path.abspath(infile)
if os.path.exists(infile) == False:
print('%s not found' % infile)
sys.exit(2)
with open(infile, 'r') as f:
header=[]
file_list=[]
for i in f:
row=i.split("\t")
if(header):
filtered_dict=dict((k,v) for k,v in dict(zip(header,row)).items() if k in header)
file_list.append(filtered_dict)
else:
header=row
return file_list
def check_ftp_url(full_url):
'''
This function checks if an url is accessible and returns its http response code
'''
url=urlsplit(full_url)
conn = HTTPConnection(url.netloc)
conn.request("HEAD",url.path)
res = conn.getresponse()
return res.status
if __name__=='__main__':
url='http://ftp.ebi.ac.uk/pub/databases/blueprint/data/homo_sapiens/GRCh38/Cell_Line/BL-2/Sporadic_Burkitt_lymphoma/ChIP-Seq/NCMLS/BL-2_c01.ERX297411.H3K4me1.bwa.GRCh38.20150528.bw'
code=check_ftp_url(url)
print(code)
|
#! /usr/bin/env python
# This file is part of the dvbobjects library.
#
# Copyright 2000-2001, GMD, Sankt Augustin
# -- German National Research Center for Information Technology
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
import string
import pprint
######################################################################
def CDR(s, alignment = 4, gap_byte = 0xFF):
"""If necessary, append to 's' a trailing NUL byte
and fill with 'gap_byte' until properly aligned.
"""
if len(s) % alignment == 0 and s[-1] in ("\x00", "\xFF"):
return s
s = s + "\x00"
while len(s) % alignment:
s = s + chr(gap_byte)
return s
######################################################################
class DVBobject:
"""The base class for many protocol data units.
Basically it provides functionality similar to a C-struct.
Members are set via keyword arguments either in the constructor
or via the set() method. Other (rather static) attributes
can be defined as (sub-)class attributes.
Subclasses must implement a 'pack()' method which returns
the properly packed byte string.
Attributes may come from the following sources:
1. (Static) class attributes;
2. Keyword arguments given in the constructor;
3. Keyword arguments given in the 'set()' method;
4. Direct assignment to instance attributes (NOT recommended).
"""
#
# Default attribute value.
# Subclasses can do that, too!
#
ISO_639_language_code = "deu"
def __init__(self, **kwargs):
"""Initialize instance attributes from keyword arguments.
"""
apply(self.set, (), kwargs)
def set(self, **kwargs):
"""Add (more) instance attributes from keyword arguments.
"""
for k, v in kwargs.items():
setattr(self, k, v)
def __repr__(self):
"""Used for debugging."""
def hilite(s):
return "### %s ###" % s
return pprint.pformat(
(hilite(self.__class__.__name__),
self.__dict__))
def dump(self):
"""Print a simple hexdump of this object to stdout.
"""
BYTES_PER_LINE = 16
bytes = self.pack()
i = 0
for byte in bytes:
if i % BYTES_PER_LINE == 0:
if i: print # start on a fresh line...
print "%04x " % i,
print "%02X" % ord(byte),
i = i+1
print # dump is done => NL
def test(self):
"""Used for debugging."""
if not self.__dict__:
self.sample()
self.dump()
print self
|
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** 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 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 General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** 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-3.0.html.
**
****************************************************************************/
#pragma once
#include <texteditor/textmark.h>
#include <QPersistentModelIndex>
namespace Autotest {
namespace Internal {
class TestEditorMark : public TextEditor::TextMark
{
public:
TestEditorMark(QPersistentModelIndex item, const Utils::FileName &file, int line);
bool isClickable() const override { return true; }
void clicked() override;
private:
QPersistentModelIndex m_item;
};
} // namespace Internal
} // namespace Autotest
|
jQuery(document).ready(function($) {
var t_test = $('input:radio[name=socialize_twitterWidget]:checked').val();
$(".socialize-twitter-select").hide();
$("#socialize-twitter-"+t_test).show();
var f_test = $('input:radio[name=socialize_fbWidget]:checked').val();
$(".socialize-facebook-select").hide();
$("#socialize-facebook-"+f_test).show();
var d_test = $("input[name=socialize_button_display]:checked").val();
if(d_test == 'in')
$("input[name=socialize_out_margin]").attr("disabled", "disabled");
else
$("input[name=socialize_out_margin]").removeAttr("disabled");
$("input[name=socialize_twitterWidget]").change(function() {
var t_test = $(this).val();
$(".socialize-twitter-select").hide();
$("#socialize-twitter-"+t_test).show();
});
$("input[name=socialize_fbWidget]").change(function() {
var f_test = $(this).val();
$(".socialize-facebook-select").hide();
$("#socialize-facebook-"+f_test).show();
});
$("input[name=socialize_button_display]").change(function() {
var d_test = $(this).val();
if(d_test == 'in')
$("input[name=socialize_out_margin]").attr("disabled", "disabled");
else
$("input[name=socialize_out_margin]").removeAttr("disabled");
});
});
|
from JumpScale.clients.racktivity.energyswitch.common import convert
from JumpScale.clients.racktivity.energyswitch.common.GUIDTable import Value
from JumpScale.clients.racktivity.energyswitch.modelfactory.models.RTF0037.Master_0_1_2_41 import Model as Master
class Model(Master):
def __init__(self, parent):
super(Model, self).__init__(parent)
self._guidTable.update({
# added only those that are needed for snmp configuration, others
# omitted
# SNMPTrapUser
10212: Value(u"type='TYPE_UNSIGNED_NUMBER'\nsize=1\nlength=1\nunit=''\nscale=0"),
# SNMPTrapEnable
10222: Value(u"type='TYPE_ENUM'\nsize=1\nlength=1\nunit=''\nscale=0")
})
def getSNMPTrapUser(self, portnumber):
guid = 10212
moduleID = 'M1'
length = 1
valDef = self._guidTable[guid]
data = self._parent.client.getAttribute(
moduleID, guid, portnumber, length)
return self._parent.getObjectFromData(data, valDef, count=length)
def setSNMPTrapUser(self, value, portnumber):
guid = 10212
moduleID = 'M1'
valDef = self._guidTable[guid]
data = self._parent.client.setAttribute(
moduleID, guid, convert.value2bin(value, valDef), portnumber)
return self._parent.getObjectFromData(data, valDef, setter=True)
def getSNMPTrapEnable(self, portnumber=1):
guid = 10222
moduleID = 'M1'
length = 1
valDef = self._guidTable[guid]
data = self._parent.client.getAttribute(
moduleID, guid, portnumber, length)
return self._parent.getObjectFromData(data, valDef, count=length)
def setSNMPTrapEnable(self, value, portnumber=1):
guid = 10222
moduleID = 'M1'
valDef = self._guidTable[guid]
data = self._parent.client.setAttribute(
moduleID, guid, convert.value2bin(value, valDef), portnumber)
return self._parent.getObjectFromData(data, valDef, setter=True)
|
package ru.stqa.pft.rest;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import org.apache.http.client.fluent.Request;
import org.apache.http.message.BasicNameValuePair;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.Set;
import static org.testng.Assert.assertEquals;
/**
* Created by Sasha on 08.06.2016.
*/
public class RestTests extends TestBase{
@Test
public void testCreateIssue() throws IOException {
skipIfNotFixed(1);
Set<Issue> oldIssues = getIssues();
Issue newIssue = new Issue().withSubject("Test issue").withDescription("New test issue");
int issueId = createIssue(newIssue);
Set<Issue> newIssues = getIssues();
oldIssues.add(newIssue.withId(issueId));
assertEquals(newIssues, oldIssues);
}
private Set<Issue> getIssues() throws IOException {
String json = getExecutor().execute(Request.Get("http://demo.bugify.com/api/issues.json")).returnContent().asString();
JsonElement parsed = new JsonParser().parse(json);
JsonElement issues = parsed.getAsJsonObject().get("issues");
return new Gson().fromJson(issues, new TypeToken<Set<Issue>>() {}.getType());
}
private int createIssue(Issue newIssue) throws IOException {
String json = getExecutor().execute(Request.Post("http://demo.bugify.com/api/issues.json").bodyForm(
new BasicNameValuePair("subject", newIssue.getSubject()), new BasicNameValuePair("description",
newIssue.getDescription()))).returnContent().asString();
JsonElement parsed = new JsonParser().parse(json);
return parsed.getAsJsonObject().get("issue_id").getAsInt();
}
}
|
# -*- coding: utf-8 -*-
from datetime import timedelta
from django.utils import timezone
from nose.tools import * # noqa
from tests.base import OsfTestCase
from osf_tests.factories import RegistrationFactory, UserFactory
from scripts.approve_registrations import main
class TestApproveRegistrations(OsfTestCase):
def setUp(self):
super(TestApproveRegistrations, self).setUp()
self.user = UserFactory()
self.registration = RegistrationFactory(creator=self.user)
self.registration.is_public = True
self.registration.require_approval(self.user)
def test_new_registration_should_not_be_approved(self):
assert_true(self.registration.is_pending_registration)
main(dry_run=False)
assert_false(self.registration.is_registration_approved)
def test_should_not_approve_pending_registration_less_than_48_hours_old(self):
# RegistrationApproval#iniation_date is read only
self.registration.registration_approval.initiation_date = timezone.now() - timedelta(hours=47)
self.registration.registration_approval.save()
assert_false(self.registration.is_registration_approved)
main(dry_run=False)
assert_false(self.registration.is_registration_approved)
def test_should_approve_pending_registration_that_is_48_hours_old(self):
assert_true(self.registration.registration_approval.state) # sanity check
# RegistrationApproval#iniation_date is read only
self.registration.registration_approval.initiation_date = timezone.now() - timedelta(hours=48)
self.registration.registration_approval.save()
assert_false(self.registration.is_registration_approved)
main(dry_run=False)
self.registration.registration_approval.reload()
assert_true(self.registration.is_registration_approved)
def test_should_approve_pending_registration_more_than_48_hours_old(self):
# RegistrationApproval#iniation_date is read only
self.registration.registration_approval.initiation_date = timezone.now() - timedelta(days=365)
self.registration.registration_approval.save()
assert_false(self.registration.is_registration_approved)
main(dry_run=False)
self.registration.registration_approval.reload()
assert_true(self.registration.is_registration_approved)
def test_registration_adds_to_parent_projects_log(self):
initial_project_logs = self.registration.registered_from.logs.count()
# RegistrationApproval#iniation_date is read only
self.registration.registration_approval.initiation_date=timezone.now() - timedelta(days=365)
self.registration.registration_approval.save()
assert_false(self.registration.is_registration_approved)
main(dry_run=False)
self.registration.registration_approval.reload()
assert_true(self.registration.is_registration_approved)
assert_true(self.registration.is_public)
# Logs: Created, approval initiated, approval initiated, registered, registration complete
assert_equal(self.registration.registered_from.logs.count(), initial_project_logs + 2)
|
#!/usr/bin/env python2.6
# -*- coding: utf-8 -*-
#
# mean_std.py
# Copyright 2010 arpagon <[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 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
__version__ = "0.0.1"
__license__ = """The GNU General Public License (GPL-2.0)"""
__author__ = "Sebastian Rojo <http://www.sapian.com.co> [email protected]"
__contributors__ = []
_debug = 0
import collections
from weakref import proxy
class Link(object):
'''
The proper use of __slots__ is to save space in objects.
'''
__slots__ = 'prev', 'next', 'key', '__weakref__'
class LinkedList(collections.MutableSet):
'''
LinkedLink
Set the remembers the order elements were added
'''
def __init__(self, iterable=None):
'''
Init
'''
self.__root = root = Link()
root.prev = root.next = root
self.__map = {} # key --> link
if iterable is not None:
self |= iterable
def __len__(self):
'''
Length for the LinkedList
'''
return len(self.__map)
def __contains__(self, key):
'''
Return Content of LinkedList
'''
return key in self.__map
def add(self, key):
'''
Add Node
Store new key in a new link at the end of the linked list
'''
if key not in self.__map:
'''
Not Element Eq in the list
'''
self.__map[key] = link = Link()
root = self.__root
last = root.prev
link.prev, link.next, link.key = last, root, key
last.next = root.prev = proxy(link)
def head(self):
'''
Return Head
'''
return list(self)[0],list(self)[-1]
def discard(self, key):
'''
Remove an existing item using self.__map to find the link which is
then removed by updating the links in the predecessor and successors.
'''
if key in self.__map:
link = self.__map.pop(key)
link.prev.next = link.next
link.next.prev = link.prev
def __iter__(self):
'''
iteration for the Next Method
'''
root = self.__root
curr = root.next
while curr is not root:
yield curr.key
curr = curr.next
def __reversed__(self):
'''
iteration in reverse mode Method
'''
root = self.__root
curr = root.prev
while curr is not root:
yield curr.key
curr = curr.prev
def pop(self, last=True):
'''
pop key
'''
if not self:
raise KeyError('set is empty')
key = next(reversed(self)) if last else next(iter(self))
self.discard(key)
return key
def __repr__(self):
'''
String Conversion representation of object LinkeList repr()
'''
if not self:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, list(self))
def __eq__(self, other):
'''
Method for de Equal comparation.
'''
if isinstance(other, LinkedList):
return len(self) == len(other) and list(self) == list(other)
return not self.isdisjoint(other)
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MFinance extends CI_Model{
public function __construct() {
parent::__construct();
}
function add_finance($data) {
$query = $this->db->insert('finance', $data);
return $this->db->affected_rows();
}
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:1c4eecafd284728bdbaeb8243eafed57b8973f9fcf6271044573a4abc3dcb843
size 10749
|
// Copyright (C) 1999,2000 Bruce Guenter <[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 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
#include <config.h>
#include "vdomain.h"
static bool validate_field(mystring str, const char* bad_chars)
{
if(!str)
return false;
if(str.find_first_of(bad_chars) >= 0)
return false;
return true;
}
bool vdomain::validate_username(mystring user) const
{
return validate_field(user, "/:\n\r\t ");
}
bool vdomain::validate_password(mystring pass) const
{
return validate_field(pass, ":\n\r\t ");
}
response vdomain::validate_forward(mystring forward)
{
int atchar = forward.find_first('@');
if(atchar < 0) {
if(!exists(forward))
RETURN(err, "User '" + forward + "' does not exist");
}
else if(forward.find_first('@', atchar+1) >= 0)
RETURN(err, "Address '" + forward + "' is invalid: "
" Address contains more than one at (@) symbol");
RETURN(ok, "");
}
|
/**
* @file
*
* @date 22.06.2012
* @author Anton Bondarev
*/
#ifndef MIPS_LINKAGE_H_
#define MIPS_LINKAGE_H_
#include <asm/asm.h>
#ifdef __ASSEMBLER__
#define C_ENTRY(name) .globl name; .align 2; name
/*
* LEAF - declare leaf routine
*/
#define LEAF(symbol) \
.globl symbol; \
.align 2; \
.type symbol, @function; \
.ent symbol, 0; \
symbol: .frame $sp, 0, $ra
/*
* NESTED - declare nested routine entry point
*/
#define NESTED(symbol, framesize, rpc) \
.globl symbol; \
.align 2; \
.type symbol, @function; \
.ent symbol, 0; \
symbol: .frame $sp, framesize, rpc
/*
* END - mark end of function
*/
#define END(function) \
.end function; \
.size function, .-function
#endif /* __ASEEMBLER__ */
#endif /* MIPS_LINKAGE_H_ */
|
# -*- coding: utf-8 -*-
# Copyright (C) 2014 Osmo Salomaa
#
# 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/>.
"""
Routing using MapQuest Open.
http://open.mapquestapi.com/directions/
"""
import copy
import poor
import urllib.parse
CONF_DEFAULTS = {
"avoids": [],
"language": poor.util.get_default_language("en_US"),
"type": "fastest",
}
ICONS = {
0: "continue",
1: "turn-slight-right",
2: "turn-right",
3: "turn-sharp-right",
4: "flag",
5: "turn-sharp-left",
6: "turn-left",
7: "turn-slight-left",
8: "uturn",
9: "uturn",
10: "merge-slight-left",
11: "merge-slight-right",
12: "off-ramp-slight-right",
13: "off-ramp-slight-left",
14: "off-ramp-slight-right",
15: "off-ramp-slight-left",
16: "fork-slight-right",
17: "fork-slight-left",
18: "fork-straight",
}
SUPPORTED_LOCALES = [
"en_US",
"en_GB",
"fr_CA",
"fr_FR",
"de_DE",
"es_ES",
"es_MX",
"ru_RU",
]
URL = ("http://open.mapquestapi.com/directions/v2/route"
"?key=Fmjtd|luur2quy2h,bn=o5-9aasg4"
"&ambiguities=ignore"
"&from={fm}"
"&to={to}"
"&unit=k"
"&routeType={type}"
"&doReverseGeocode=false"
"&shapeFormat=cmp"
"&generalize=5"
"&manMaps=false"
"&locale={locale}")
cache = {}
def prepare_endpoint(point):
"""Return `point` as a string ready to be passed on to the router."""
if isinstance(point, (list, tuple)):
return "{:.5f},{:.5f}".format(point[1], point[0])
geocoder = poor.Geocoder("default")
results = geocoder.geocode(point, dict(limit=1))
return prepare_endpoint((results[0]["x"], results[0]["y"]))
def route(fm, to, heading, params):
"""Find route and return its properties as a dictionary."""
fm, to = map(prepare_endpoint, (fm, to))
type = poor.conf.routers.mapquest_open.type
locale = poor.conf.routers.mapquest_open.language
locale = (locale if locale in SUPPORTED_LOCALES else "en_US")
url = URL.format(**locals())
if type == "fastest":
# Assume all avoids are related to cars.
for avoid in poor.conf.routers.mapquest_open.avoids:
url += "&avoids={}".format(urllib.parse.quote_plus(avoid))
with poor.util.silent(KeyError):
return copy.deepcopy(cache[url])
result = poor.http.get_json(url)
result = poor.AttrDict(result)
x, y = poor.util.decode_epl(result.route.shape.shapePoints)
maneuvers = []
for leg in result.route.legs:
maneuvers.extend(leg.maneuvers)
maneuvers = [dict(
x=float(maneuver.startPoint.lng),
y=float(maneuver.startPoint.lat),
icon=ICONS.get(maneuver.turnType, "flag"),
narrative=maneuver.narrative,
duration=float(maneuver.time),
) for maneuver in maneuvers]
if len(maneuvers) > 1:
maneuvers[ 0]["icon"] = "depart"
maneuvers[-1]["icon"] = "arrive"
route = dict(x=x, y=y, maneuvers=maneuvers, mode="car")
route["attribution"] = poor.util.get_routing_attribution("MapQuest")
route["language"] = locale
if route and route["x"]:
cache[url] = copy.deepcopy(route)
return route
|
from django import template
from django.conf import settings
from django.contrib.flatpages.models import FlatPage
from django.contrib.sites.shortcuts import get_current_site
register = template.Library()
class FlatpageNode(template.Node):
def __init__(self, context_name, starts_with=None, user=None):
self.context_name = context_name
if starts_with:
self.starts_with = template.Variable(starts_with)
else:
self.starts_with = None
if user:
self.user = template.Variable(user)
else:
self.user = None
def render(self, context):
if 'request' in context:
site_pk = get_current_site(context['request']).pk
else:
site_pk = settings.SITE_ID
flatpages = FlatPage.objects.filter(sites__id=site_pk)
# If a prefix was specified, add a filter
if self.starts_with:
flatpages = flatpages.filter(
url__startswith=self.starts_with.resolve(context))
# If the provided user is not authenticated, or no user
# was provided, filter the list to only public flatpages.
if self.user:
user = self.user.resolve(context)
if not user.is_authenticated:
flatpages = flatpages.filter(registration_required=False)
else:
flatpages = flatpages.filter(registration_required=False)
context[self.context_name] = flatpages
return ''
@register.tag
def get_flatpages(parser, token):
"""
Retrieve all flatpage objects available for the current site and
visible to the specific user (or visible to all users if no user is
specified). Populate the template context with them in a variable
whose name is defined by the ``as`` clause.
An optional ``for`` clause controls the user whose permissions are used in
determining which flatpages are visible.
An optional argument, ``starts_with``, limits the returned flatpages to
those beginning with a particular base URL. This argument can be a variable
or a string, as it resolves from the template context.
Syntax::
{% get_flatpages ['url_starts_with'] [for user] as context_name %}
Example usage::
{% get_flatpages as flatpages %}
{% get_flatpages for someuser as flatpages %}
{% get_flatpages '/about/' as about_pages %}
{% get_flatpages prefix as about_pages %}
{% get_flatpages '/about/' for someuser as about_pages %}
"""
bits = token.split_contents()
syntax_message = ("%(tag_name)s expects a syntax of %(tag_name)s "
"['url_starts_with'] [for user] as context_name" %
{'tag_name': bits[0]})
# Must have at 3-6 bits in the tag
if 3 <= len(bits) <= 6:
# If there's an even number of bits, there's no prefix
if len(bits) % 2 == 0:
prefix = bits[1]
else:
prefix = None
# The very last bit must be the context name
if bits[-2] != 'as':
raise template.TemplateSyntaxError(syntax_message)
context_name = bits[-1]
# If there are 5 or 6 bits, there is a user defined
if len(bits) >= 5:
if bits[-4] != 'for':
raise template.TemplateSyntaxError(syntax_message)
user = bits[-3]
else:
user = None
return FlatpageNode(context_name, starts_with=prefix, user=user)
else:
raise template.TemplateSyntaxError(syntax_message)
|
import sys
import numpy as np
import matplotlib
import matplotlib.pylab as pylab
import matplotlib.pyplot as plt
def get_timestamp(filename, ch=0):
f = open(filename, 'rb')
ftype = np.dtype([
('flags', '>u1'),
('timestamp', '>u4')
])
a = np.fromfile(f, dtype=ftype)
flags = a['flags']
timestamp = a['timestamp']
# Filter events containing channel ch
timestamp = timestamp[flags & (1<<ch) != 0]
return timestamp
if len(sys.argv) not in (3,4) or (len(sys.argv) == 4 and sys.argv[3] not in ('time', 'hist')):
print('usage: %s acq_file channel [hist|time]' % sys.argv[0])
sys.exit(1)
filename = sys.argv[1]
channel = int(sys.argv[2])
plottype = 'hist' if len(sys.argv) == 3 else sys.argv[3]
chunksize = int(1e7)
isi = np.array(np.diff(get_timestamp(filename, channel)), dtype=np.float64)
print(repr(('mean', isi.mean(), 'std', isi.std())))
plt.rc('text', usetex=True)
plt.rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
if plottype == 'time':
for i in xrange(0, len(isi), chunksize):
print('start @chunk %d' % i)
window = isi[i:i+chunksize]
plt.plot(1.e-6*window.cumsum(), window, 'k.')
plt.ylabel(r'$\Delta t$ ($\mu$s)')
plt.xlabel(r'$t$ (s)')
dim = plt.axis()
plt.axis(dim[:2] + (dim[2]-2, dim[3]+2))
ax = plt.gca()
y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
ax.yaxis.set_major_formatter(y_formatter)
plt.tight_layout()
plt.show()
elif plottype == 'hist':
y, x, _ = plt.hist(isi, color='#888888', log=True)
plt.ylabel(r'Number of occurrences')
plt.xlabel(r'$\Delta t$ ($\mu$s)')
ax = plt.gca()
x_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
ax.xaxis.set_major_formatter(x_formatter)
plt.xticks(np.round(x[pylab.find(y>0)]))
plt.tight_layout()
plt.show()
|
//
// GMKeyboardHandler.h
// MobileWorkbenchPhone
//
// Created by Mike Bobiney on 2/2/13.
// Copyright (c) 2013 General Motors. All rights reserved.
//
#import <Foundation/Foundation.h>
@protocol TTAKeyboardHandlerDelegate
- (void)keyboardSizeChanged:(CGSize)delta;
@end
@interface TTAKeyboardHandler : NSObject
@property(nonatomic, weak) id<TTAKeyboardHandlerDelegate> delegate;
@property(nonatomic) CGRect frame;
@end
|
import chalk from "chalk";
import figures from "figures";
import checkWhen from "../utils/checkWhen";
import processText from "../utils/processText";
/**
* Notify the user of an error (if any), otherwise log out
* the success message for the command.
*
* @param {Error} err
* @param {Object} ctx
*/
export default function (err, ctx) {
if (err) printError(err);
else printSuccess(ctx);
}
/**
* Handles the formatting for displaying errors.
*/
function printError (err) {
process.stdout.write(`\n\n
${chalk.bold.bgRed("Failure! Error! Sadness!")}\n
Oh man, this is embarrassing but we weren't able to complete the operation.\n\n
${chalk.bold("Why?")}\n
${chalk.red(err.message)}
`);
process.exit(1);
}
/**
* Handles the formatting for displaying the success message.
*/
function printSuccess (ctx) {
process.stdout.write(`\n\n
${chalk.bold.green(figures.tick + " Success!")}\n
We successfully added the chosen template contents to your current directory.\n\n`);
if (
ctx.manifest.done
&& typeof ctx.manifest.done.message === "string"
&& checkWhen(ctx, ctx.manifest.done.when)
) {
var output = processText(ctx, ctx.manifest.done.message);
process.stdout.write("And now a word from the author:\n");
process.stdout.write(output + "\n\n");
}
}
|
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import internal_alerts
import json
import random
import string
import unittest
import webtest
from google.appengine.api import memcache
from google.appengine.ext import testbed
class InternalAlertsTest(unittest.TestCase):
def setUp(self):
self.testbed = testbed.Testbed()
self.testbed.activate()
self.testbed.init_user_stub()
self.testbed.init_memcache_stub()
self.testapp = webtest.TestApp(internal_alerts.app)
def tearDown(self):
self.testbed.deactivate()
def user_helper(self, email, uid):
self.testbed.setup_env(
USER_EMAIL=email,
USER_ID=uid,
USER_IS_ADMIN='0',
overwrite=True)
def check_json_headers(self, res):
self.user_helper('[email protected]', '123')
self.assertEqual(res.content_type, 'application/json')
# This is necessary for cross-site tools to retrieve internal alerts.
self.assertEqual(res.headers['access-control-allow-origin'], '*')
def test_get_no_data_cached(self):
self.user_helper('[email protected]', '123')
res = self.testapp.get('/internal-alerts')
self.check_json_headers(res)
self.assertEqual(res.body, '')
def test_happy_path(self):
self.user_helper('[email protected]', '123')
# Set it.
params = {'content': '{"alerts": ["hello", "world"]}'}
self.testapp.post('/internal-alerts', params)
# Get it.
res = self.testapp.get('/internal-alerts')
self.check_json_headers(res)
internal_alerts = json.loads(res.body)
# The server should have stuck a 'date' on there.
self.assertTrue('date' in internal_alerts)
self.assertEqual(type(internal_alerts['date']), int)
self.assertEqual(internal_alerts['alerts'], ['hello', 'world'])
def test_post_invalid_data_not_reflected(self):
self.user_helper('[email protected]', '123')
params = {'content': '[{"this is not valid JSON'}
self.testapp.post('/internal-alerts', params, status=400)
res = self.testapp.get('/internal-alerts')
self.assertEqual(res.body, '')
def test_post_invalid_data_does_not_overwrite_valid_data(self):
self.user_helper('[email protected]', '123')
# Populate the cache with something valid
params = {'content': '{"alerts": "everything is OK"}'}
self.testapp.post('/internal-alerts', params)
self.testapp.post('/internal-alerts', {'content': 'woozlwuzl'},
status=400)
res = self.testapp.get('/internal-alerts')
self.check_json_headers(res)
internal_alerts = json.loads(res.body)
self.assertEqual(internal_alerts['alerts'], 'everything is OK')
def test_large_number_of_internal_alerts(self):
self.user_helper('[email protected]', '123')
# This generates ~2.5MB of JSON that compresses to ~750K. Real
# data compresses about 6x better.
random.seed(0xf00f00)
put_internal_alerts = self.generate_fake_internal_alerts(4000)
params = {'content': json.dumps(put_internal_alerts)}
self.testapp.post('/internal-alerts', params)
res = self.testapp.get('/internal-alerts')
got_internal_alerts = json.loads(res.body)
self.assertEquals(got_internal_alerts['alerts'],
put_internal_alerts['alerts'])
def test_no_user(self):
# Get it.
res = self.testapp.get('/internal-alerts')
self.check_json_headers(res)
internal_alerts = json.loads(res.body)
# The server should have stuck a 'date' on there.
self.assertTrue('date' in internal_alerts)
self.assertEqual(type(internal_alerts['date']), int)
self.assertTrue('redirect-url' in internal_alerts)
self.assertEqual(type(internal_alerts['redirect-url']), unicode)
def test_invalid_user(self):
self.user_helper('[email protected]', '123')
# Get it.
res = self.testapp.get('/internal-alerts', status=403)
def generate_fake_internal_alerts(self, n):
self.user_helper('[email protected]', '123')
return {'alerts': [self.generate_fake_alert() for _ in range(n)]}
def generate_fake_alert(self):
# fake labels
labels = [['', 'last_', 'latest_', 'failing_', 'passing_'],
['build', 'builder', 'revision'],
['', 's', '_url', '_reason', '_name']]
def label():
return string.join(map(random.choice, labels), '')
# fake values
def time():
return random.randint(1407976107614, 1408076107614) / 101.0
def build():
return random.randint(2737, 2894)
def revision():
return random.randint(288849, 289415)
tests = [['Activity', 'Async', 'Browser', 'Content', 'Input'],
['Manager', 'Card', 'Sandbox', 'Container'],
['Test.'],
['', 'Basic', 'Empty', 'More'],
['Mouse', 'App', 'Selection', 'Network', 'Grab'],
['Input', 'Click', 'Failure', 'Capture']]
def test():
return string.join(map(random.choice, tests), '')
def literal_array():
generator = random.choice([time, build, revision])
return [generator() for _ in range(random.randint(0, 10))]
def literal_map():
generators = [build, revision, test, literal_array]
obj = {}
for _ in range(random.randint(3, 9)):
obj[label()] = random.choice(generators)()
return obj
def value():
generators = [time, build, revision, test, literal_array,
literal_map]
return random.choice(generators)()
alert = {}
for _ in range(random.randint(6, 9)):
alert[label()] = value()
return alert
|
# http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Bridge_Pattern#Python
# ConcreteImplementor 1/2
class DrawingAPI1:
def drawCircle(self, x, y, radius):
print('API1.circle at {}:{} radius {}'.format(x, y, radius))
# ConcreteImplementor 2/2
class DrawingAPI2:
def drawCircle(self, x, y, radius):
print('API2.circle at {}:{} radius {}'.format(x, y, radius))
# Refined Abstraction
class CircleShape:
def __init__(self, x, y, radius, drawingAPI):
self.__x = x
self.__y = y
self.__radius = radius
self.__drawingAPI = drawingAPI
# low-level i.e. Implementation specific
def draw(self):
self.__drawingAPI.drawCircle(self.__x, self.__y, self.__radius)
# high-level i.e. Abstraction specific
def resizeByPercentage(self, pct):
self.__radius *= pct
def main():
shapes = (
CircleShape(1, 2, 3, DrawingAPI1()),
CircleShape(5, 7, 11, DrawingAPI2())
)
for shape in shapes:
shape.resizeByPercentage(2.5)
shape.draw()
if __name__ == "__main__":
main()
|
/**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2011 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*
* WARNING: This is generated code. Modify at your own risk and without support.
*/
// A good bit of this code was derived from the Three20 project
// and was customized to work inside spfc_me
//
// All modifications by spfc_me are licensed under
// the Apache License, Version 2.0
//
//
// Copyright 2009 Facebook
//
// 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.
//
#ifdef USE_TI_UIDASHBOARDVIEW
#import <UIKit/UIKit.h>
@class LauncherButton;
@class LauncherItem;
@protocol LauncherViewDelegate;
@interface LauncherView : UIView<UIScrollViewDelegate> {
@private
id<LauncherViewDelegate> delegate;
UIScrollView *scrollView;
UIPageControl *pager;
NSMutableArray *pages;
NSMutableArray *buttons;
NSInteger columnCount;
NSInteger rowCount;
LauncherButton *dragButton;
NSTimer* editHoldTimer;
NSTimer* springLoadTimer;
UITouch* dragTouch;
NSInteger positionOrigin;
CGPoint dragOrigin;
CGPoint touchOrigin;
BOOL editing;
BOOL springing;
BOOL editable;
}
@property(nonatomic) NSInteger columnCount;
@property(nonatomic) NSInteger rowCount;
@property(nonatomic) NSInteger currentPageIndex;
@property(nonatomic,assign) id<LauncherViewDelegate> delegate;
@property(nonatomic,readonly) BOOL editing;
@property(nonatomic,assign) BOOL editable;
- (void)addItem:(LauncherItem*)item animated:(BOOL)animated;
- (void)removeItem:(LauncherItem*)item animated:(BOOL)animated;
- (void)beginEditing;
- (void)endEditing;
- (LauncherItem*)itemForIndex:(NSInteger)index;
- (NSArray*)items;
@end
@protocol LauncherViewDelegate <NSObject>
@optional
- (void)launcherView:(LauncherView*)launcher didAddItem:(LauncherItem*)item;
- (void)launcherView:(LauncherView*)launcher didRemoveItem:(LauncherItem*)item;
- (void)launcherView:(LauncherView*)launcher willDragItem:(LauncherItem*)item;
- (void)launcherView:(LauncherView*)launcher didDragItem:(LauncherItem*)item;
- (void)launcherView:(LauncherView*)launcher didMoveItem:(LauncherItem*)item;
- (void)launcherView:(LauncherView*)launcher didSelectItem:(LauncherItem*)item;
- (void)launcherViewDidBeginEditing:(LauncherView*)launcher;
- (void)launcherViewDidEndEditing:(LauncherView*)launcher;
- (BOOL)launcherViewShouldWobble:(LauncherView*)launcher;
@end
#endif
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Odoo - Sentry connector
# Copyright (C) 2014 Mohammed Barsi.
#
# 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 traceback
import logging
import sys
import openerp.service.wsgi_server
import openerp.addons.web.controllers.main
import openerp.addons.report.controllers.main
import openerp.http
import openerp.tools.config as config
import openerp.osv.osv
import openerp.exceptions
from openerp.http import request
from raven import Client
from raven.handlers.logging import SentryHandler
from raven.middleware import Sentry
from raven.conf import setup_logging, EXCLUDE_LOGGER_DEFAULTS
_logger = logging.getLogger(__name__)
CLIENT_DSN = config.get('sentry_client_dsn', '').strip()
ENABLE_LOGGING = config.get('sentry_enable_logging', False)
ALLOW_ORM_WARNING = config.get('sentry_allow_orm_warning', False)
INCLUDE_USER_CONTEXT = config.get('sentry_include_context', False)
AUTO_LOG_STACKS = config.get('auto_log_stacks', False)
def get_user_context():
'''
get the current user context, if possible
'''
cxt = {}
try:
session = getattr(request, 'session', {})
except RuntimeError, e:
return cxt
cxt.update({
'session': {
'context': session.get('context', {}),
'db': session.get('db', None),
'login': session.get('login', None),
'password': session.get('uid', None),
},
})
return cxt
def serialize_exception(e):
'''
overrides `openerp.http.serialize_exception`
in order to log orm exceptions.
'''
if isinstance(e, (
openerp.osv.osv.except_osv,
openerp.exceptions.Warning,
openerp.exceptions.AccessError,
openerp.exceptions.AccessDenied,
)):
if INCLUDE_USER_CONTEXT:
client.extra_context(get_user_context())
client.captureException(sys.exc_info())
return openerp.http.serialize_exception(e)
elif isinstance(e, Exception):
if INCLUDE_USER_CONTEXT:
client.extra_context(get_user_context())
client.captureException(sys.exc_info())
return openerp.http.serialize_exception(e)
class ContextSentryHandler(SentryHandler):
'''
extends SentryHandler, to capture logs only if
`sentry_enable_logging` config options set to true
'''
def emit(self, rec):
if INCLUDE_USER_CONTEXT:
client.extra_context(get_user_context())
super(ContextSentryHandler, self).emit(rec)
client = Client(CLIENT_DSN, auto_log_stacks=AUTO_LOG_STACKS)
if ENABLE_LOGGING:
# future enhancement: add exclude loggers option
EXCLUDE_LOGGER_DEFAULTS += ('werkzeug', )
handler = ContextSentryHandler(client)
setup_logging(handler, exclude=EXCLUDE_LOGGER_DEFAULTS)
if ALLOW_ORM_WARNING:
openerp.addons.web.controllers.main._serialize_exception = serialize_exception
openerp.addons.report.controllers.main._serialize_exception = serialize_exception
# wrap the main wsgi app
openerp.service.wsgi_server.application = Sentry(
openerp.service.wsgi_server.application, client=client
)
if INCLUDE_USER_CONTEXT:
client.extra_context(get_user_context())
# fire the first message
client.captureMessage('Starting Odoo Server')
|
#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. 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.
import datetime
from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django.contrib.auth.forms import AuthenticationForm as AuthAuthenticationForm, UserCreationForm as AuthUserCreationForm
from django.forms import CharField, TextInput, PasswordInput, ChoiceField, ValidationError
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _t, ugettext as _
from desktop import conf
from useradmin.password_policy import get_password_validators
def get_server_choices():
if conf.LDAP.LDAP_SERVERS.get():
return [(ldap_server_record_key, ldap_server_record_key) for ldap_server_record_key in conf.LDAP.LDAP_SERVERS.get()]
else:
return [('LDAP', 'LDAP')]
class AuthenticationForm(AuthAuthenticationForm):
"""
Adds appropriate classes to authentication form
"""
error_messages = {
'invalid_login': _t("Invalid username or password."),
'inactive': _t("Account deactivated. Please contact an administrator."),
}
username = CharField(label=_t("Username"), max_length=30, widget=TextInput(attrs={'maxlength': 30, 'placeholder': _t("Username"), "autofocus": "autofocus"}))
password = CharField(label=_t("Password"), widget=PasswordInput(attrs={'placeholder': _t("Password"), 'autocomplete': 'off'}))
def authenticate(self):
return super(AuthenticationForm, self).clean()
def clean(self):
if conf.AUTH.EXPIRES_AFTER.get() > -1:
try:
user = User.objects.get(username=self.cleaned_data.get('username'))
expires_delta = datetime.timedelta(seconds=conf.AUTH.EXPIRES_AFTER.get())
if user.is_active and user.last_login + expires_delta < datetime.datetime.now():
if user.is_superuser:
if conf.AUTH.EXPIRE_SUPERUSERS.get():
user.is_active = False
user.save()
else:
user.is_active = False
user.save()
if not user.is_active:
if settings.ADMINS:
raise ValidationError(mark_safe(_("Account deactivated. Please contact an <a href=\"mailto:%s\">administrator</a>.") % settings.ADMINS[0][1]))
else:
raise ValidationError(self.error_messages['inactive'])
except User.DoesNotExist:
# Skip because we couldn't find a user for that username.
# This means the user managed to get their username wrong.
pass
return self.authenticate()
class LdapAuthenticationForm(AuthenticationForm):
"""
Adds NT_DOMAINS selector.
"""
def __init__(self, *args, **kwargs):
super(LdapAuthenticationForm, self).__init__(*args, **kwargs)
self.fields['server'] = ChoiceField(choices=get_server_choices())
def authenticate(self):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
server = self.cleaned_data.get('server')
if username and password:
self.user_cache = authenticate(username=username,
password=password,
server=server)
if self.user_cache is None:
raise ValidationError(
self.error_messages['invalid_login'])
elif not self.user_cache.is_active:
raise ValidationError(self.error_messages['inactive'])
self.check_for_test_cookie()
return self.cleaned_data
class UserCreationForm(AuthUserCreationForm):
"""
Accepts one password field and populates the others.
password fields with the value of that password field
Adds appropriate classes to authentication form.
"""
password = CharField(label=_t("Password"),
widget=PasswordInput(attrs={'class': 'input-large'}),
validators=get_password_validators())
def __init__(self, data=None, *args, **kwargs):
if data and 'password' in data:
data = data.copy()
data['password1'] = data['password']
data['password2'] = data['password']
super(UserCreationForm, self).__init__(data=data, *args, **kwargs)
class LdapUserCreationForm(UserCreationForm):
def __init__(self, *args, **kwargs):
super(LdapUserCreationForm, self).__init__(*args, **kwargs)
self.fields['server'] = ChoiceField(choices=get_server_choices())
|
describe('ngNuxeoClient module', function () {
'use strict';
var httpBackend, nuxeo, nuxeoUser, dataDocuments, dataUser, dataWorkspace;
beforeEach(module('ngNuxeoClient', 'data/documents.json', 'data/user.json', 'data/workspace.json'));
beforeEach(inject(function ($httpBackend, _nuxeo_, _nuxeoUser_, _dataDocuments_, _dataUser_, _dataWorkspace_) {
httpBackend = $httpBackend;
nuxeo = _nuxeo_;
nuxeoUser = _nuxeoUser_;
dataDocuments = _dataDocuments_;
dataUser = _dataUser_;
dataWorkspace = _dataWorkspace_;
}));
describe('nuxeo.Document object', function () {
it('is valid when instantiated with no argument', function () {
expect(nuxeo.Document.name === 'Document').toBe(true);
var doc = new nuxeo.Document();
expect(typeof doc === 'object').toBe(true);
expect(doc instanceof nuxeo.Document).toBe(true);
expect(doc.constructor === nuxeo.Document).toBe(true);
expect(nuxeo.Document.prototype instanceof nuxeo.Automation).toBe(true);
expect(doc.isDeletable).toBeFalsy();
expect(doc.isPublishable).toBeFalsy();
});
it('is valid when instantiated argument', function () {
var doc = new nuxeo.Document(dataDocuments.entries[0]);
expect(typeof doc === 'object').toBe(true);
expect(doc instanceof nuxeo.Document).toBe(true);
expect(doc.constructor === nuxeo.Document).toBe(true);
expect(nuxeo.Document.prototype instanceof nuxeo.Automation).toBe(true);
expect(doc.isDeletable).toBeDefined();
expect(doc.isPublishable).toBeDefined();
});
it('has parameters passed in instantiation', function () {
var doc = new nuxeo.Document({name: 'myDocument', type: 'Picture'});
expect(doc.name).toEqual('myDocument');
expect(doc.type).toEqual('Picture');
});
});
describe('nuxeo.Document', function () {
it('should create a Document when requested', function () {
httpBackend.whenGET('https://demo.nuxeo.com/nuxeo/api/v1/user/Administrator').respond(dataUser);
httpBackend.whenGET('https://demo.nuxeo.com/nuxeo/api/v1/path/default-domain/UserWorkspaces/fmaturel-github-com'
).respond(dataWorkspace);
httpBackend.whenPOST('https://demo.nuxeo.com/nuxeo/site/automation/Document.Create').respond('{\"type": \"Document\"}');
nuxeo.Document.create('webbanner', '/default-domain/sections', function (result) {
expect(result).toBeDefined();
expect(result.type).toEqual('Document');
});
nuxeoUser.login('Administrator', 'Administrator');
httpBackend.flush();
});
});
});
|
<?php
/*
* This file is part of the Claroline Connect package.
*
* (c) Claroline Consortium <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Claroline\CoreBundle\Entity\Theme;
use Claroline\CoreBundle\Entity\Plugin;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
* @ORM\Table(name="claro_theme")
*/
class Theme
{
/**
* @var integer
*
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column()
*/
private $name;
/**
* @var string
*
* @ORM\Column(nullable=true)
*/
private $path;
/**
* @ORM\ManyToOne(targetEntity="Claroline\CoreBundle\Entity\Plugin")
* @ORM\JoinColumn(onDelete="CASCADE")
*/
protected $plugin;
public function __construct($name = null, $path = null)
{
$this->setName($name);
$this->setPath($path);
}
public function get($variable)
{
if (isset($this->$variable)) {
return $this->$variable;
}
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
* @return Theme
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set path
*
* @param string $path
* @return Theme
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* Get path
*
* @return string
*/
public function getPath()
{
return $this->path;
}
public function setPlugin(Plugin $plugin)
{
$this->plugin = $plugin;
}
public function getPlugin()
{
return $this->plugin;
}
}
|
#!/usr/bin/python
from distutils.core import setup, Extension
from distutils.sysconfig import get_python_lib, get_python_version
import os
if os.path.isfile("MANIFEST"):
os.unlink("MANIFEST")
# You may have to change these
PYLIBS = ["python"+get_python_version(), "pthread", "util"]
PYLIBDIR = [get_python_lib(standard_lib=True)+"/config"]
LUALIBS = ["lua", "lualib"]
LUALIBDIR = []
setup(name="lunatic-python",
version = "1.0",
description = "Two-way bridge between Python and Lua",
author = "Gustavo Niemeyer",
author_email = "[email protected]",
url = "http://labix.org/lunatic-python",
license = "LGPL",
long_description =
"""\
Lunatic Python is a two-way bridge between Python and Lua, allowing these
languages to intercommunicate. Being two-way means that it allows Lua inside
Python, Python inside Lua, Lua inside Python inside Lua, Python inside Lua
inside Python, and so on.
""",
ext_modules = [
Extension("lua-python",
["src/pythoninlua.c", "src/luainpython.c"],
library_dirs=PYLIBDIR,
libraries=PYLIBS,
extra_compile_args=["-rdynamic"],
extra_link_args=["-rdynamic"]),
Extension("lua",
["src/pythoninlua.c", "src/luainpython.c"],
library_dirs=LUALIBDIR,
libraries=LUALIBS,
extra_compile_args=["-rdynamic"],
extra_link_args=["-rdynamic"]),
],
)
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JSDoc: Global</title>
<script src="scripts/prettify/prettify.js"> </script>
<script src="scripts/prettify/lang-css.js"> </script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>
<body>
<div id="main">
<h1 class="page-title">Global</h1>
<section>
<header>
<h2>
</h2>
</header>
<article>
<div class="container-overview">
<dl class="details">
</dl>
</div>
<h3 class="subsection-title">Members</h3>
<dl>
<dt>
<h4 class="name" id="NAV2D"><span class="type-signature"></span>NAV2D<span class="type-signature"></span></h4>
</dt>
<dd>
<dl class="details">
<dt class="tag-author">Author:</dt>
<dd class="tag-author">
<ul>
<li>Russell Toris - [email protected]</li>
<li>Lars Kunze - [email protected]</li>
</ul>
</dd>
<dt class="tag-source">Source:</dt>
<dd class="tag-source"><ul class="dummy"><li>
<a href="Nav2D.js.html">Nav2D.js</a>, line 6
</li></ul></dd>
</dl>
</dd>
</dl>
</article>
</section>
</div>
<nav>
<h2><a href="index.html">Index</a></h2><h3>Classes</h3><ul><li><a href="NAV2D.ImageMapClientNav.html">ImageMapClientNav</a></li><li><a href="NAV2D.Navigator.html">Navigator</a></li><li><a href="NAV2D.OccupancyGridClientNav.html">OccupancyGridClientNav</a></li></ul><h3>Global</h3><ul><li><a href="global.html#NAV2D">NAV2D</a></li></ul>
</nav>
<br clear="both">
<footer>
Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.2.0-dev</a> on Fri Aug 08 2014 09:02:22 GMT-0400 (EDT)
</footer>
<script> prettyPrint(); </script>
</body>
</html>
|
import ply.lex as lex
ident = r"(-)?([a-z_]|[^\0-\177]|\\[0-9a-f]{1,6}(\r\n|[ \n\r\t\f])?|\\[^\n\r\f0-9a-f])([a-z0-9_\-]|[^\0-\177]|\\[0-9a-f]{1,6}(\r\n|[ \n\r\t\f])?|\\[^\n\r\f0-9a-f])*"
name = r"([a-z0-9_\-]|[^\0-\177]|\\[0-9a-f]{1,6}(\r\n|[ \n\r\t\f])?|\\[^\n\r\f0-9a-f])+"
num = r"[0-9]+|[0-9]*\.[0-9]+"
string1 = r"\"([^\n\r\f\\\"]|\\(\n|\r\n|\r|\f)|[^\0-\177]|\\[0-9a-f]{1,6}(\r\n|[ \n\r\t\f])?|\\[^\n\r\f0-9a-f])*\""
string2 = r"\'([^\n\r\f\\\']|\\(\n|\r\n|\r|\f)|[^\0-\177]|\\[0-9a-f]{1,6}(\r\n|[ \n\r\t\f])?|\\[^\n\r\f0-9a-f])*\'"
string = string1 + r"|" + string2
invalid1 = r"\"([^\n\r\f\\\"]|\\(\n|\r\n|\r|\f)|[^\0-\177]|\\[0-9a-f]{1,6}(\r\n|[ \n\r\t\f])?|\\[^\n\r\f0-9a-f])*"
invalid2 = r"\'([^\n\r\f\\\']|\\(\n|\r\n|\r|\f)|[^\0-\177]|\\[0-9a-f]{1,6}(\r\n|[ \n\r\t\f])?|\\[^\n\r\f0-9a-f])*"
invalid = invalid1 + r"|" + invalid2
w = r"[ \t\r\n\f]*"
# D d|\\0{0,4}(44|64)(\r\n|[ \t\r\n\f])?
# E e|\\0{0,4}(45|65)(\r\n|[ \t\r\n\f])?
# N n|\\0{0,4}(4e|6e)(\r\n|[ \t\r\n\f])?|\\n
# O o|\\0{0,4}(4f|6f)(\r\n|[ \t\r\n\f])?|\\o
# T t|\\0{0,4}(54|74)(\r\n|[ \t\r\n\f])?|\\t
# V v|\\0{0,4}(58|78)(\r\n|[ \t\r\n\f])?|\\v
# %%
tokens = [
"S",
"INCLUDES",
"DASHMATCH",
"PREFIXMATCH",
"SUFFIXMATCH",
"SUBSTRINGMATCH",
"IDENT",
"STRING",
"FUNCTION",
"NUMBER",
"HASH",
"PLUS",
"GREATER",
"COMMA",
"TILDE",
"NOT",
"ATKEYWORD",
"INVALID",
"PERCENTAGE",
"DIMENSION",
"CDO",
"CDC",
]
literals = "*|.[=]:)"
t_S = r"[ \t\r\n\f]+"
t_INCLUDES = r"~="
t_DASHMATCH = r"\|="
t_PREFIXMATCH = r"\^="
t_SUFFIXMATCH = r"\$="
t_SUBSTRINGMATCH = r"\*="
t_IDENT = ident
@lex.TOKEN(string)
def t_STRING(t):
t.value = t.value[1:-1]
return t
t_FUNCTION = ident + r"\("
t_NUMBER = num
t_HASH = r"\#" + name
t_PLUS = w + r"\+" + w
t_GREATER = w + r">" + w
t_COMMA = w + r","
# t_TILDE = w + r"~"
t_NOT = r":not\("
t_ATKEYWORD = r"@" + ident
t_INVALID = invalid
t_PERCENTAGE = num + r"%"
t_DIMENSION = num + ident
t_CDO = r"<!--"
t_CDC = r"-->"
# Error handling rule
def t_error(t):
print "Illegal character '%s'" % t.value[0]
t.lexer.skip(1)
lexer = lex.lex()
# %%
# \/\*[^*]*\*+([^/*][^*]*\*+)*\/ /* ignore comments */
|
<html>
<head>
<script type="text/javascript">
var dojoConfig= {
async:!!location.search
};
</script>
<script type="text/javascript" src="../../../dojo/dojo.js"></script>
<script type="text/javascript">
require(["dojox/gfx", "dojo/domReady!"], function(gfx){
console.log(gfx);
});
require(["dojo", "dojo/domReady!"], function(dojo){
dojo.byId("status").innerHTML= "OK";
});
</script>
</head>
<body>
<div id="status">loading</div>
</body>
|
#!/usr/bin/env python
# Author: Pawel Foremski <[email protected]>
# Copyright (C) 2012-2014 IITiS PAN <http://www.iitis.pl/>
# Licensed under GNU GPL v3
import re
### <yuck!>
import sys
from os import path
sys.path.insert(0, path.dirname(__file__))
### </yuck!>
import tldextract
import params as P
def do_segment(word):
if len(word) > 0:
return [word]
else:
return []
###########
# (from segment import segment)
ret = []
if P.tok.seg > 0 and len(word) > P.tok.seg:
for token in segment(word):
if len(token) > 1: ret.append(token)
elif len(word) > 0:
ret.append(word)
return ret
###########
def get_flow_features(domain):
ret = []
text = domain.strip()
i = text.rfind(':')
if i > 0:
s = text[i:]
j = s.find('/')
if j > 0:
ret.append(s[:j]) # port
ret.append(s[j:]) # proto
else:
ret.append(s[:j]) # port
return ret
def tokenizer(domain):
ret = []
text = domain.lower().strip()
# parse the domain
r = tldextract.extract(text)
# subdomain: only letters
if len(r.subdomain):
# change digits to 'N'
sd = re.sub('[0-9]', 'N', r.subdomain)
sd = re.sub('(N+)', '\\1.', sd)
for word in re.split("[^a-zN]+", sd):
if len(word) == 0:
continue
elif word.isdigit():
ret.append("N" * len(word))
else:
ret.extend(do_segment(word))
# domain: no dashes
for word in r.domain.split("-"):
ret.extend(do_segment(word))
# TLD: no dots
if P.tok.tlds:
for token in r.tld.split("."):
if len(token) > 0: ret.append(token)
# flow features
if P.tok.flow:
ret.extend(get_flow_features(domain))
if P.tok.max > 0:
ret = ret[-P.tok.max:]
#print "%s -> %s" % (domain.strip(), ret)
return ret
|
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.RecaptchaEnterprise.V1.Snippets
{
// [START recaptchaenterprise_v1_generated_RecaptchaEnterpriseService_DeleteKey_async]
using Google.Cloud.RecaptchaEnterprise.V1;
using System.Threading.Tasks;
public sealed partial class GeneratedRecaptchaEnterpriseServiceClientSnippets
{
/// <summary>Snippet for DeleteKeyAsync</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public async Task DeleteKeyRequestObjectAsync()
{
// Create client
RecaptchaEnterpriseServiceClient recaptchaEnterpriseServiceClient = await RecaptchaEnterpriseServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteKeyRequest request = new DeleteKeyRequest
{
KeyName = KeyName.FromProjectKey("[PROJECT]", "[KEY]"),
};
// Make the request
await recaptchaEnterpriseServiceClient.DeleteKeyAsync(request);
}
}
// [END recaptchaenterprise_v1_generated_RecaptchaEnterpriseService_DeleteKey_async]
}
|
# -*- coding: utf-8 -*-
import string
import getpass
def to_bool(val, default=False, yes_choices=None, no_choices=None):
if not isinstance(val, basestring):
return bool(val)
yes_choices = yes_choices or ('y', 'yes', '1', 'on', 'true', 't')
no_choices = no_choices or ('n', 'no', '0', 'off', 'false', 'f')
if val.lower() in yes_choices:
return True
elif val.lower() in no_choices:
return False
return default
def prompt(name, default=None):
"""
Grab user input from command line.
:param name: prompt text
:param default: default value if no input provided.
"""
prompt = name + (' [%s]' % default if default else '')
prompt += ' ' if name.endswith('?') else ': '
while True:
rv = raw_input(prompt)
if rv:
return rv
if default is not None:
return default
def prompt_pass(name, default=None):
"""
Grabs hidden (password) input from command line.
:param name: prompt text
:param default: default value if no input provided.
"""
prompt = name + (default and ' [%s]' % default or '')
prompt += name.endswith('?') and ' ' or ': '
while True:
rv = getpass.getpass(prompt)
if rv:
return rv
if default is not None:
return default
def prompt_bool(name, default=False, yes_choices= ('y', 'yes', '1', 'on', 'true', 't'), no_choices=('n', 'no', '0', 'off', 'false', 'f')):
"""
Grabs user input from command line and converts to boolean
value.
:param name: prompt text
:param default: default value if no input provided.
:param yes_choices: default 'y', 'yes', '1', 'on', 'true', 't'
:param no_choices: default 'n', 'no', '0', 'off', 'false', 'f'
"""
while True:
rv = prompt(name + '?', yes_choices[0] if default else no_choices[0])
if not rv:
return default
rv = to_bool(rv, default=None, yes_choices=yes_choices, no_choices=no_choices)
if rv is not None:
return rv
def prompt_choices(name, choices, default=None, resolve=string.lower,
no_choice=('none',)):
"""
Grabs user input from command line from set of provided choices.
:param name: prompt text
:param choices: list or tuple of available choices. Choices may be
single strings or (key, value) tuples.
:param default: default value if no input provided.
:param no_choice: acceptable list of strings for "null choice"
"""
_choices = []
options = []
for choice in choices:
if isinstance(choice, basestring):
options.append(choice)
else:
options.append("[%s] %s" % (choice[0], choice[1]))
choice = choice[0]
_choices.append(choice)
while True:
rv = prompt(name + '? - %s' % '\n'.join(options), default)
if not rv:
return default
rv = resolve(rv)
if rv in no_choice:
return None
if rv in _choices:
return rv
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
from dhis2 import Api, setup_logger, logger
THRESHOLD = 1
ORDER_FORWARD = 'FEkGksxhOpH'
OVERALL_SCORE = 'Y8Nmpp7RhXw'
def parse_args():
usage = "hnqis-scan-mismatches [-s] [-u] [-p] -x" \
"\n\n\033[1mExample:\033[0m " \
"\nhnqis-scan-mismatches -s=data.psi-mis.org -u=admin -p=district -x"
parser = argparse.ArgumentParser(
description="Scan mismatches of Scores > 1 value", usage=usage)
parser.add_argument('-s', dest='server', action='store',
help="DHIS2 server URL without /api/ e.g. -s=play.dhis2.org/demo")
parser.add_argument('-x', dest='fix_values', action='store_true', default=False, required=False,
help="Fix events by overwriting _Overall Score with 0CS-100 score + resetting _Order Forward to 9999")
parser.add_argument('-u', dest='username', action='store', help="DHIS2 username")
parser.add_argument('-p', dest='password', action='store', help="DHIS2 password")
parser.add_argument('-d', dest='debug', action='store_true', default=False, required=False,
help="Writes more info in log file")
return parser.parse_args()
def fix_event(event, root_compscores):
"""Adjust data values: overwrite _Overall Score with 0CS-100 value and set order forward to be 9999"""
datavalues = event['dataValues']
for i in range(len(datavalues)):
if datavalues[i]['dataElement'] == ORDER_FORWARD:
event['dataValues'][i]['value'] = '9999'
if datavalues[i]['dataElement'] == OVERALL_SCORE:
event['dataValues'][i]['value'] = [x['value'] for x in datavalues if x['dataElement'] in root_compscores][0]
return event
def analyze_event(program, event, root_compscores):
"""Analyze if event needs to be fixed"""
x = [dv['value'] for dv in event['dataValues'] if dv['dataElement'] == OVERALL_SCORE]
y = [dv['value'] for dv in event['dataValues'] if dv['dataElement'] in root_compscores]
if x and y:
n1 = float(x[0])
n2 = float(y[0])
diff = abs(n1-n2)
if diff > THRESHOLD:
print(u"{},{},{},{},{},{},{}".format(event['eventDate'], program['id'], program['name'], event['event'], n1, n2, diff))
return event['event']
def main():
args = parse_args()
setup_logger()
api = Api(server=args.server, username=args.username, password=args.password)
p = {
'paging': False,
'filter': 'name:like:HNQIS',
'fields': 'id,name'
}
programs = api.get('programs', params=p)
print("event_date,program,name,event,_OverallScore,0CS-100,diff")
fix_them = []
csparams = {
'filter': ['shortName:like:.0CS-100', 'name:!ilike:_DEL'],
'paging': False,
'fields': 'id'
}
root_compscores = [x['id'] for x in api.get('dataElements', params=csparams).json()['dataElements']]
for p in programs['programs']:
params = {
'program': p['id'],
'skipPaging': True,
'fields': '[*]'
}
events = api.get('events', params=params).json()
for event in events['events']:
if analyze_event(p, event, root_compscores):
fix_them.append(event)
if fix_them and args.fix_values:
logger.info(u"Fixing those events and resetting _Order Forward...")
for i, e in enumerate(fix_them, 1):
fixed = fix_event(e, root_compscores)
logger.info(u"[{}/{}] Pushing event {}...".format(i, len(fix_them), e['event']))
api.put('events/{}'.format(e['event']), data=fixed)
else:
logger.warn(u"Not fixing events")
if __name__ == '__main__':
main()
|
/***************************************************************************
qgsrasterrange.h
--------------------------------------
Date : Oct 9, 2012
Copyright : (C) 2012 by Radim Blazek
email : radim dot blazek at gmail dot com
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#ifndef QGSRASTERRANGE_H
#define QGSRASTERRANGE_H
#include <QList>
class QgsRasterRange;
typedef QList<QgsRasterRange> QgsRasterRangeList;
/** \ingroup core
* Raster values range container. Represents range of values between min and max
* including min and max value.
*/
class CORE_EXPORT QgsRasterRange
{
public:
/** \brief Constructor.
*/
QgsRasterRange();
/** \brief Constructor
* @param theMin minimum value
* @param theMax max value
*/
QgsRasterRange( double theMin, double theMax );
double min() const { return mMin; }
double max() const { return mMax; }
double setMin( double theMin ) { return mMin = theMin; }
double setMax( double theMax ) { return mMax = theMax; }
inline bool operator==( QgsRasterRange o ) const
{
return qgsDoubleNear( mMin, o.mMin ) && qgsDoubleNear( mMax, o.mMax );
}
/** \brief Test if value is within the list of ranges
* @param value value
* @param rangeList list of ranges
* @return true if value is in at least one of ranges
* @note not available in python bindings
*/
static bool contains( double value, const QgsRasterRangeList &rangeList );
private:
double mMin;
double mMax;
};
#endif
|
#ifndef BOOST_SMART_PTR_MAKE_LOCAL_SHARED_OBJECT_HPP_INCLUDED
#define BOOST_SMART_PTR_MAKE_LOCAL_SHARED_OBJECT_HPP_INCLUDED
// make_local_shared_object.hpp
//
// Copyright 2017 Peter Dimov
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
// See http://www.boost.org/libs/smart_ptr/ for documentation.
#include <boost/smart_ptr/local_shared_ptr.hpp>
#include <boost/smart_ptr/make_shared.hpp>
#include <boost/config.hpp>
#include <utility>
#include <cstddef>
namespace boost
{
namespace detail
{
// lsp_if_not_array
template<class T> struct lsp_if_not_array
{
typedef boost::local_shared_ptr<T> type;
};
template<class T> struct lsp_if_not_array<T[]>
{
};
template<class T, std::size_t N> struct lsp_if_not_array<T[N]>
{
};
// lsp_ms_deleter
template<class T, class A> class lsp_ms_deleter: public local_counted_impl_em
{
private:
typedef typename sp_aligned_storage<sizeof(T), ::boost::alignment_of<T>::value>::type storage_type;
storage_type storage_;
A a_;
bool initialized_;
private:
void destroy() BOOST_SP_NOEXCEPT
{
if( initialized_ )
{
T * p = reinterpret_cast< T* >( storage_.data_ );
#if !defined( BOOST_NO_CXX11_ALLOCATOR )
std::allocator_traits<A>::destroy( a_, p );
#else
p->~T();
#endif
initialized_ = false;
}
}
public:
explicit lsp_ms_deleter( A const & a ) BOOST_SP_NOEXCEPT : a_( a ), initialized_( false )
{
}
// optimization: do not copy storage_
lsp_ms_deleter( lsp_ms_deleter const & r ) BOOST_SP_NOEXCEPT : a_( r.a_), initialized_( false )
{
}
~lsp_ms_deleter() BOOST_SP_NOEXCEPT
{
destroy();
}
void operator()( T * ) BOOST_SP_NOEXCEPT
{
destroy();
}
static void operator_fn( T* ) BOOST_SP_NOEXCEPT // operator() can't be static
{
}
void * address() BOOST_SP_NOEXCEPT
{
return storage_.data_;
}
void set_initialized() BOOST_SP_NOEXCEPT
{
initialized_ = true;
}
};
} // namespace detail
template<class T, class A, class... Args> typename boost::detail::lsp_if_not_array<T>::type allocate_local_shared( A const & a, Args&&... args )
{
#if !defined( BOOST_NO_CXX11_ALLOCATOR )
typedef typename std::allocator_traits<A>::template rebind_alloc<T> A2;
#else
typedef typename A::template rebind<T>::other A2;
#endif
A2 a2( a );
typedef boost::detail::lsp_ms_deleter<T, A2> D;
boost::shared_ptr<T> pt( static_cast< T* >( 0 ), boost::detail::sp_inplace_tag<D>(), a2 );
D * pd = static_cast< D* >( pt._internal_get_untyped_deleter() );
void * pv = pd->address();
#if !defined( BOOST_NO_CXX11_ALLOCATOR )
std::allocator_traits<A2>::construct( a2, static_cast< T* >( pv ), std::forward<Args>( args )... );
#else
::new( pv ) T( std::forward<Args>( args )... );
#endif
pd->set_initialized();
T * pt2 = static_cast< T* >( pv );
boost::detail::sp_enable_shared_from_this( &pt, pt2, pt2 );
pd->pn_ = pt._internal_count();
return boost::local_shared_ptr<T>( boost::detail::lsp_internal_constructor_tag(), pt2, pd );
}
template<class T, class A> typename boost::detail::lsp_if_not_array<T>::type allocate_local_shared_noinit( A const & a )
{
#if !defined( BOOST_NO_CXX11_ALLOCATOR )
typedef typename std::allocator_traits<A>::template rebind_alloc<T> A2;
#else
typedef typename A::template rebind<T>::other A2;
#endif
A2 a2( a );
typedef boost::detail::lsp_ms_deleter< T, std::allocator<T> > D;
boost::shared_ptr<T> pt( static_cast< T* >( 0 ), boost::detail::sp_inplace_tag<D>(), a2 );
D * pd = static_cast< D* >( pt._internal_get_untyped_deleter() );
void * pv = pd->address();
::new( pv ) T;
pd->set_initialized();
T * pt2 = static_cast< T* >( pv );
boost::detail::sp_enable_shared_from_this( &pt, pt2, pt2 );
pd->pn_ = pt._internal_count();
return boost::local_shared_ptr<T>( boost::detail::lsp_internal_constructor_tag(), pt2, pd );
}
template<class T, class... Args> typename boost::detail::lsp_if_not_array<T>::type make_local_shared( Args&&... args )
{
return boost::allocate_local_shared<T>( std::allocator<T>(), std::forward<Args>(args)... );
}
template<class T> typename boost::detail::lsp_if_not_array<T>::type make_local_shared_noinit()
{
return boost::allocate_shared_noinit<T>( std::allocator<T>() );
}
} // namespace boost
#endif // #ifndef BOOST_SMART_PTR_MAKE_SHARED_OBJECT_HPP_INCLUDED
|
from os import path
from werkzeug import BaseRequest, BaseResponse, Template
from werkzeug.routing import NotFound, RequestRedirect
from werkzeug.exceptions import HTTPException, NotFound
from i18nurls.urls import map
TEMPLATES = path.join(path.dirname(__file__), 'templates')
views = {}
def expose(name):
"""Register the function as view."""
def wrapped(f):
views[name] = f
return f
return wrapped
class Request(BaseRequest):
def __init__(self, environ, urls):
super(Request, self).__init__(environ)
self.urls = urls
self.matched_url = None
def url_for(self, endpoint, **args):
if not 'lang_code' in args:
args['lang_code'] = self.language
if endpoint == 'this':
endpoint = self.matched_url[0]
tmp = self.matched_url[1].copy()
tmp.update(args)
args = tmp
return self.urls.build(endpoint, args)
class Response(BaseResponse):
pass
class TemplateResponse(Response):
def __init__(self, template_name, **values):
self.template_name = template_name
self.template_values = values
Response.__init__(self, mimetype='text/html')
def __call__(self, environ, start_response):
req = environ['werkzeug.request']
values = self.template_values.copy()
values['req'] = req
values['body'] = self.render_template(self.template_name, values)
self.write(self.render_template('layout.html', values))
return Response.__call__(self, environ, start_response)
def render_template(self, name, values):
return Template.from_file(path.join(TEMPLATES, name)).render(values)
class Application(object):
def __init__(self):
from i18nurls import views
self.not_found = views.page_not_found
def __call__(self, environ, start_response):
urls = map.bind_to_environ(environ)
req = Request(environ, urls)
try:
endpoint, args = urls.match(req.path)
req.matched_url = (endpoint, args)
if endpoint == '#language_select':
lng = req.accept_languages.best
lng = lng and lng.split('-')[0].lower() or 'en'
index_url = urls.build('index', {'lang_code': lng})
resp = Response('Moved to %s' % index_url, status=302)
resp.headers['Location'] = index_url
else:
req.language = args.pop('lang_code', None)
resp = views[endpoint](req, **args)
except NotFound:
resp = self.not_found(req)
except (RequestRedirect, HTTPException), e:
resp = e
return resp(environ, start_response)
|
/* NewIndiController */
#import <Cocoa/Cocoa.h>
#import "GCFile.h"
#import "GenXUtil.h"
@interface EditIndiController : NSObject
{
IBOutlet NSWindow* new_indi_window;
IBOutlet NSMatrix* sex_matrix;
IBOutlet NSTextField* first_name;
IBOutlet NSTextField* last_name;
IBOutlet NSTextField* name_suffix;
IBOutlet NSPopUpButton* birth_day;
IBOutlet NSPopUpButton* birth_month;
IBOutlet NSTextField* birth_year;
IBOutlet NSTextField* birth_place;
IBOutlet NSPopUpButton* death_day;
IBOutlet NSPopUpButton* death_month;
IBOutlet NSTextField* death_year;
IBOutlet NSTextField* death_place;
IBOutlet NSTextField* mother_text;
IBOutlet NSTextField* father_text;
IBOutlet NSTextField* source_text;
NSModalSession modal_session;
GCFile* ged;
INDI* field;
}
+ (EditIndiController*) sharedNewIndi;
- (EditIndiController*) initNib;
- (void) prepForDisplay: (id) my_ged: (id) my_field;
- (BOOL) process;
- (void) handleOk: (id) sender;
- (void) handleCancel: (id) sender;
- (NSWindow*) window;
@end
|
# -*- coding: utf-8 -*-
"""
The Pygments Markdown Preprocessor
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This fragment is a Markdown_ preprocessor that renders source code
to HTML via Pygments. To use it, invoke Markdown like so::
import markdown
html = markdown.markdown(someText, extensions=[CodeBlockExtension()])
This uses CSS classes by default, so use
``pygmentize -S <some style> -f html > pygments.css``
to create a stylesheet to be added to the website.
You can then highlight source code in your markdown markup::
[sourcecode:lexer]
some code
[/sourcecode]
.. _Markdown: https://pypi.python.org/pypi/Markdown
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
# Options
# ~~~~~~~
# Set to True if you want inline CSS styles instead of classes
INLINESTYLES = False
import re
from markdown.preprocessors import Preprocessor
from markdown.extensions import Extension
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import get_lexer_by_name, TextLexer
class CodeBlockPreprocessor(Preprocessor):
pattern = re.compile(r'\[sourcecode:(.+?)\](.+?)\[/sourcecode\]', re.S)
formatter = HtmlFormatter(noclasses=INLINESTYLES)
def run(self, lines):
def repl(m):
try:
lexer = get_lexer_by_name(m.group(1))
except ValueError:
lexer = TextLexer()
code = highlight(m.group(2), lexer, self.formatter)
code = code.replace('\n\n', '\n \n').replace('\n', '<br />')
return '\n\n<div class="code">%s</div>\n\n' % code
joined_lines = "\n".join(lines)
joined_lines = self.pattern.sub(repl, joined_lines)
return joined_lines.split("\n")
class CodeBlockExtension(Extension):
def extendMarkdown(self, md, md_globals):
md.preprocessors.add('CodeBlockPreprocessor', CodeBlockPreprocessor(), '_begin')
|
<?php
return [
'adminEmail' => '[email protected]',
'supportEmail' => '[email protected]',
'user.passwordResetTokenExpire' => 3600,
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
'' => '',
];
|
//This file is automatically rebuilt by the Cesium build process.
/*global define*/
define(function() {
"use strict";
return "uniform vec4 fadeInColor;\n\
uniform vec4 fadeOutColor;\n\
uniform float maximumDistance;\n\
uniform bool repeat;\n\
uniform vec2 fadeDirection;\n\
uniform vec2 time;\n\
\n\
float getTime(float t, float coord)\n\
{\n\
float scalar = 1.0 / maximumDistance;\n\
float q = distance(t, coord) * scalar;\n\
if (repeat)\n\
{\n\
float r = distance(t, coord + 1.0) * scalar;\n\
float s = distance(t, coord - 1.0) * scalar;\n\
q = min(min(r, s), q);\n\
}\n\
return clamp(q, 0.0, 1.0);\n\
}\n\
\n\
czm_material czm_getMaterial(czm_materialInput materialInput)\n\
{\n\
czm_material material = czm_getDefaultMaterial(materialInput);\n\
\n\
vec2 st = materialInput.st;\n\
float s = getTime(time.x, st.s) * fadeDirection.s;\n\
float t = getTime(time.y, st.t) * fadeDirection.t;\n\
\n\
float u = length(vec2(s, t));\n\
vec4 color = mix(fadeInColor, fadeOutColor, u);\n\
\n\
material.emission = color.rgb;\n\
material.alpha = color.a;\n\
\n\
return material;\n\
}\n\
";
});
|
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xml:base="http://machines.plannedobsolescence.net/51-2008" xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>
<title>intro to digital media studies - web 2.0</title>
<link>http://machines.plannedobsolescence.net/51-2008/taxonomy/term/12/0</link>
<description></description>
<language>en</language>
<item>
<title>I hate buzz words</title>
<link>http://machines.plannedobsolescence.net/51-2008/node/7</link>
<description><p>I don't see a difference between web 1.0 and web 2.0. Dare to disagree with me.</p>
</description>
<comments>http://machines.plannedobsolescence.net/51-2008/node/7#comments</comments>
<category domain="http://machines.plannedobsolescence.net/51-2008/taxonomy/term/12">web 2.0</category>
<pubDate>Fri, 25 Jan 2008 18:28:47 +0000</pubDate>
<dc:creator>student01</dc:creator>
<guid isPermaLink="false">7 at http://machines.plannedobsolescence.net/51-2008</guid>
</item>
</channel>
</rss>
|
"""
DWF Python Example
Author: Digilent, Inc.
Revision: 2018-07-19
Requires:
Python 2.7, 3
"""
from ctypes import *
from dwfconstants import *
import math
import time
import matplotlib.pyplot as plt
import sys
import numpy
import wave
import datetime
import os
buffersize = 4096; # samples / buffer
samplerate = 8000; # samples / second
signalgenhz = 80;
if sys.platform.startswith("win"):
dwf = cdll.dwf
elif sys.platform.startswith("darwin"):
dwf = cdll.LoadLibrary("/Library/Frameworks/dwf.framework/dwf")
else:
dwf = cdll.LoadLibrary("libdwf.so")
#declare ctype variables
hdwf = c_int()
sts = c_byte()
rgdSamples = (c_double*buffersize)()
version = create_string_buffer(16)
dwf.FDwfGetVersion(version)
print("DWF Version: "+str(version.value))
#open device
print("Opening first device")
dwf.FDwfDeviceOpen(c_int(-1), byref(hdwf))
if hdwf.value == hdwfNone.value:
szerr = create_string_buffer(512)
dwf.FDwfGetLastErrorMsg(szerr)
print(szerr.value)
print("failed to open device")
quit()
cBufMax = c_int()
dwf.FDwfAnalogInBufferSizeInfo(hdwf, 0, byref(cBufMax))
print("Device buffer size: "+str(cBufMax.value)+" samples")
#set up acquisition
dwf.FDwfAnalogInFrequencySet(hdwf, c_double(samplerate))
dwf.FDwfAnalogInBufferSizeSet(hdwf, c_int(buffersize))
dwf.FDwfAnalogInChannelEnableSet(hdwf, c_int(0), c_bool(True))
dwf.FDwfAnalogInChannelRangeSet(hdwf, c_int(0), c_double(5))
# set up signal generation
channel = c_int(0) # use W1
dwf.FDwfAnalogOutNodeEnableSet(hdwf, channel, AnalogOutNodeCarrier, c_bool(True))
dwf.FDwfAnalogOutNodeFunctionSet(hdwf, channel, AnalogOutNodeCarrier, funcTriangle) # ! this looks like a square wave
dwf.FDwfAnalogOutNodeFrequencySet(hdwf, channel, AnalogOutNodeCarrier, c_double(signalgenhz))
dwf.FDwfAnalogOutNodeAmplitudeSet(hdwf, channel, AnalogOutNodeCarrier, c_double(1.41)) # ! this doesn't really do anything
dwf.FDwfAnalogOutNodeOffsetSet(hdwf, channel, AnalogOutNodeCarrier, c_double(1.41))
print("Generating sine wave @"+str(signalgenhz)+"Hz...")
dwf.FDwfAnalogOutConfigure(hdwf, channel, c_bool(True))
#wait at least 2 seconds for the offset to stabilize
time.sleep(2)
#get the proper file name
starttime = datetime.datetime.now();
startfilename = "AD2_" + "{:04d}".format(starttime.year) + "{:02d}".format(starttime.month) + "{:02d}".format(starttime.day) + "_" + "{:02d}".format(starttime.hour) + "{:02d}".format(starttime.minute) + "{:02d}".format(starttime.second) + ".wav";
#open WAV file
print("Opening WAV file '" + startfilename + "'");
waveWrite = wave.open(startfilename, "wb");
waveWrite.setnchannels(2); # 2 channels for the testing (1 channel would be enough if FDwfAnalogInStatusData returned only 1 channel's data
waveWrite.setsampwidth(4); # 32 bit / sample
waveWrite.setframerate(samplerate);
waveWrite.setcomptype("NONE","No compression");
#start aquisition
print("Starting oscilloscope")
dwf.FDwfAnalogInConfigure(hdwf, c_bool(False), c_bool(True))
print("Recording data @"+str(samplerate)+"Hz, press Ctrl+C to stop...");
bufferCounter = 0;
try:
while True:
while True:
dwf.FDwfAnalogInStatus(hdwf, c_int(1), byref(sts))
if sts.value == DwfStateDone.value :
break
time.sleep(0.1)
dwf.FDwfAnalogInStatusData(hdwf, 0, rgdSamples, buffersize) # get channel 1 data CH1 - ! it looks like 2 channels get read here and only the second is the data of CH1
#dwf.FDwfAnalogInStatusData(hdwf, 1, rgdSamples, buffersize) # get channel 2 data CH2
waveWrite.writeframes(rgdSamples);
bufferCounter += 1;
if ((bufferCounter % 1) == 0):
print(str(waveWrite.tell() * 4) + " bytes were written");
except KeyboardInterrupt:
pass
print("Acquisition done")
print("Closing WAV file")
waveWrite.close();
dwf.FDwfDeviceCloseAll()
#rename the file so that we know both the start and end times from the filename
endtime = datetime.datetime.now();
endfilename = "AD2_" + "{:04d}".format(starttime.year) + "{:02d}".format(starttime.month) + "{:02d}".format(starttime.day) + "_" + "{:02d}".format(starttime.hour) + "{:02d}".format(starttime.minute) + "{:02d}".format(starttime.second) + "-" + "{:02d}".format(endtime.hour) + "{:02d}".format(endtime.minute) + "{:02d}".format(endtime.second) + ".wav";
print("Renaming file from '" + startfilename + "' to '" + endfilename + "'");
os.rename(startfilename, endfilename);
#plot window
#dc = sum(rgdSamples)/len(rgdSamples)
#print("DC: "+str(dc)+"V")
#plt.plot(numpy.fromiter(rgdSamples, dtype = numpy.float))
#plt.show()
|
<?php
namespace src\DesignPatterns\Bridge;
use src\DesignPatterns\Bridge\Assemble;
use src\DesignPatterns\Bridge\Produce;
/**
* 抽象
*/
abstract class Vehicle
{
protected $workShop1;
protected $workShop2;
protected function __construct()
{
$this->workShop1 = new Assemble();
$this->workShop2 = new Produce();
}
abstract function manufacture();
}
|
using Sandbox.Common.ObjectBuilders.Definitions;
namespace SEModAPI.API.Definitions
{
public class GlobalEventsDefinition : ObjectOverLayerDefinition<MyObjectBuilder_GlobalEventDefinition>
{
#region "Constructors and Initializers"
public GlobalEventsDefinition(MyObjectBuilder_GlobalEventDefinition definition): base(definition)
{}
#endregion
#region "Properties"
public MyGlobalEventTypeEnum EventType
{
get { return MyGlobalEventTypeEnum.InvalidEventType; }
set
{
//if (m_baseDefinition.EventType == value) return;
//m_baseDefinition.EventType = value;
Changed = true;
}
}
public string DisplayName
{
get { return m_baseDefinition.DisplayName; }
set
{
if (m_baseDefinition.DisplayName == value) return;
m_baseDefinition.DisplayName = value;
Changed = true;
}
}
public long MinActivation
{
get { return m_baseDefinition.MinActivationTimeMs.GetValueOrDefault(0); }
set
{
if (m_baseDefinition.MinActivationTimeMs == value) return;
m_baseDefinition.MinActivationTimeMs = value;
Changed = true;
}
}
public long MaxActivation
{
get { return m_baseDefinition.MaxActivationTimeMs.GetValueOrDefault(0); }
set
{
if (m_baseDefinition.MaxActivationTimeMs == value) return;
m_baseDefinition.MaxActivationTimeMs = value;
Changed = true;
}
}
public long FirstActivation
{
get { return m_baseDefinition.FirstActivationTimeMs.GetValueOrDefault(0); }
set
{
if (m_baseDefinition.FirstActivationTimeMs == value) return;
m_baseDefinition.FirstActivationTimeMs = value;
Changed = true;
}
}
#endregion
#region "Methods"
protected override string GetNameFrom(MyObjectBuilder_GlobalEventDefinition definition)
{
return definition.DisplayName;
}
#endregion
}
public class GlobalEventsDefinitionsManager : SerializableDefinitionsManager<MyObjectBuilder_GlobalEventDefinition, GlobalEventsDefinition>
{
}
}
|
package com.lichader.alfred.metroapi.v3.model;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Created by lichader on 14/6/17.
*/
public class DisruptionDirection {
@JsonProperty("route_direction_id")
public int RouteDirectionId;
@JsonProperty("direction_id")
public int DirectionId;
@JsonProperty("direction_name")
public String DirectionName;
@JsonProperty("service_time")
public String ServiceTime;
}
|
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">Search 2</h4>
</div>
<div class="panel-body">
<div class="navbar navbar-{{ skin }}">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">Brand</a>
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#collapse-search-2{{ id }}">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="navbar-collapse collapse" id="collapse-search-2{{ id }}">
<!-- Search -->
<form class="navbar-form navbar-left">
{% include "lib/navbar/html/_search_2.html" { btnClass: "btn-inverse" } %}
</form>
<!-- // END search -->
</div>
</div>
</div>
</div>
</div>
|
import cv2
import numpy as np
from faster_rcnn import network
from faster_rcnn.faster_rcnn import FasterRCNN
from faster_rcnn.utils.timer import Timer
def test():
import os
im_file = 'demo/000001.jpg'
# im_file = 'data/VOCdevkit2007/VOC2007/JPEGImages/009036.jpg'
# im_file = '/media/longc/Data/data/2DMOT2015/test/ETH-Crossing/img1/000100.jpg'
image = cv2.imread(im_file)
model_file = 'VGGnet_fast_rcnn_iter_70000.h5'
# model_file = '/media/longc/Data/models/faster_rcnn_pytorch3/faster_rcnn_100000.h5'
# model_file = '/media/longc/Data/models/faster_rcnn_pytorch2/faster_rcnn_2000.h5'
detector = FasterRCNN()
network.load_net(model_file, detector)
detector.cuda()
detector.eval()
print('load model successfully!')
# network.save_net(r'/media/longc/Data/models/VGGnet_fast_rcnn_iter_70000.h5', detector)
# print('save model succ')
t = Timer()
t.tic()
# image = np.zeros(shape=[600, 800, 3], dtype=np.uint8) + 255
# dets, scores, classes, inds, all_scores = detector.detect(image, 0.05)
dets, scores, classes = detector.detect(image, 0.05)
# all_prob_dist = all_scores[inds, :]
# print(all_prob_dist)
runtime = t.toc()
print('total spend: {}s'.format(runtime))
im2show = np.copy(image)
for i, det in enumerate(dets):
det = tuple(int(x) for x in det)
cv2.rectangle(im2show, det[0:2], det[2:4], (255, 205, 51), 2)
cv2.putText(im2show, '%s: %.3f' % (classes[i], scores[i]), (det[0], det[1] + 15), cv2.FONT_HERSHEY_PLAIN,
1.0, (0, 0, 255), thickness=1)
cv2.imwrite(os.path.join('demo', 'out.jpg'), im2show)
cv2.imshow('demo', im2show)
cv2.waitKey(0)
if __name__ == '__main__':
test()
|
# -*- coding: utf-8 -*-
from flask import Flask
from flask_login import LoginManager
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_moment import Moment
from flask_mail import Mail
from config import config
from flask_migrate import Migrate
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'
bootstrap = Bootstrap()
db = SQLAlchemy()
moment = Moment()
mail = Mail()
migrate = Migrate()
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
login_manager.init_app(app)
bootstrap.init_app(app)
db.init_app(app)
moment.init_app(app)
mail.init_app(app)
migrate.init_app(app, db)
from main import main as main_blueprint
app.register_blueprint(main_blueprint)
from auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint)
from moderate import moderate as moderate_blueprint
app.register_blueprint(moderate_blueprint)
return app
|
// Copyright 2007-2008 The Apache Software Foundation.
//
// 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.
namespace MassTransit.Tests.Transports
{
using System;
using Messages;
using NUnit.Framework;
using TestConsumers;
using TextFixtures;
[TestFixture]
public class When_publishing_a_message_via_multicast :
MulticastUdpTestFixture
{
private readonly TimeSpan _timeout = TimeSpan.FromSeconds(2);
[Test, Ignore]
public void It_should_be_received()
{
PingMessage message = new PingMessage();
var consumer = new TestCorrelatedConsumer<PingMessage, Guid>(message.CorrelationId);
RemoteBus.Subscribe(consumer);
LocalBus.Publish(message);
LocalBus.Publish(message);
consumer.ShouldHaveReceivedMessage(message, _timeout);
}
[Test, Explicit]
public void It_should_be_received_by_both_receivers()
{
PingMessage message = new PingMessage();
var remoteConsumer = new TestCorrelatedConsumer<PingMessage, Guid>(message.CorrelationId);
RemoteBus.Subscribe(remoteConsumer);
var localConsumer = new TestCorrelatedConsumer<PingMessage, Guid>(message.CorrelationId);
LocalBus.Subscribe(localConsumer);
// okay so a shared endpoint results in only one service bus in the process getting the message
LocalBus.Publish(message);
LocalBus.Publish(message);
remoteConsumer.ShouldHaveReceivedMessage(message, _timeout);
localConsumer.ShouldHaveReceivedMessage(message, _timeout);
}
}
}
|
export * from './Dialog';
export * from './DialogFooter';
export * from './Dialog.Props';
|
from Components.Console import Console
from os import listdir as os_listdir, path as os_path
from re import compile as re_compile
from enigma import eEnv
class Keyboard:
def __init__(self):
self.keyboardmaps = []
self.readKeyboardMapFiles()
def readKeyboardMapFiles(self):
for keymapfile in os_listdir(eEnv.resolve('${datadir}/keymaps/')):
if (keymapfile.endswith(".info")):
f = open(eEnv.resolve('${datadir}/keymaps/') + keymapfile)
mapfile = None
mapname = None
for line in f:
m = re_compile('^\s*(\w+)\s*=\s*(.*)\s*$').match(line)
if m:
key, val = m.groups()
if key == 'kmap':
mapfile = val
if key == 'name':
mapname = val
if (mapfile is not None) and (mapname is not None):
self.keyboardmaps.append(( mapfile,mapname))
f.close()
if len(self.keyboardmaps) == 0:
self.keyboardmaps = [('dream-de.kmap', 'Box Keyboard Deutsch'), ('eng.kmap', 'Keyboard English')]
def activateKeyboardMap(self, index):
try:
keymap = self.keyboardmaps[index]
print "Activating keymap:",keymap[1]
keymappath = eEnv.resolve('${datadir}/keymaps/') + keymap[0]
if os_path.exists(keymappath):
Console().ePopen(("loadkmap < " + str(keymappath)))
except:
print "Selected keymap does not exist!"
def getKeyboardMaplist(self):
return self.keyboardmaps
def getDefaultKeyboardMap(self):
return 'eng.kmap'
keyboard = Keyboard()
|
import math
import numpy as np
import numba
def run_far_jump():
gt_as_str = 'float32'
R_EARTH = 6371.0 # km
@numba.roc.jit(device=True)
def deg2rad(deg):
return math.pi * deg / 180.0
sig = '%s(%s, %s, %s, %s)' % ((gt_as_str,) * 5)
@numba.vectorize(sig, target='roc')
def gpu_great_circle_distance(lat1, lng1, lat2, lng2):
'''Return the great-circle distance in km between (lat1, lng1) and (lat2, lng2)
on the surface of the Earth.'''
lat1, lng1 = deg2rad(lat1), deg2rad(lng1)
lat2, lng2 = deg2rad(lat2), deg2rad(lng2)
sin_lat1, cos_lat1 = math.sin(lat1), math.cos(lat1)
sin_lat2, cos_lat2 = math.sin(lat2), math.cos(lat2)
delta = lng1 - lng2
sin_delta, cos_delta = math.sin(delta), math.cos(delta)
numerator = math.sqrt((cos_lat1 * sin_delta)**2 +
(cos_lat1 * sin_lat2 - sin_lat1 * cos_lat2 * cos_delta)**2)
denominator = sin_lat1 * sin_lat2 + cos_lat1 * cos_lat2 * cos_delta
return R_EARTH * math.atan2(numerator, denominator)
arr = np.random.random(10).astype(np.float32)
gpu_great_circle_distance(arr, arr, arr, arr)
if __name__ == '__main__':
run_far_jump()
|
using System;
using System.ComponentModel;
namespace SatSolver.Objects.Gates
{
[Serializable]
public enum GateType
{
[Description("INV")] [Gate("inv", 1)] Inv,
[Description("OR")] [Gate("or", 2)] Or,
[Description("AND")] [Gate("and", 2)] And,
[Description("XOR")] [Gate("xor", 2)] Xor,
[Description("ONE")] [Gate("one", 1)] One,
[Description("ZERO")] [Gate("one", 1)] Zero
}
}
|
const assert = require('assert');
const helpers = require('../helpers');
describe('MetaData Array Modification', ()=>{
describe("Wrapper", ()=>{
it("Shuld return a JSON object instead of an Array", function(){
const res = helpers.wrap([{url: "localhost:3000"}])
assert.equal(res.Crawls.length, 1)
});
});
})
|
# Copyright (C) 2006-2013 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia 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 (FSF), 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 Affero GNU General Public License
# version 3 along with this program. If not, see http://www.gnu.org/licenses/
#! /usr/bin/env python
import sys, os
import essentia, essentia.standard, essentia.streaming
from essentia.streaming import *
namespace = 'lowlevel'
panningFrameSize = 8192
panningHopSize = 2048
analysisSampleRate = 44100.0
class PanningExtractor(essentia.streaming.CompositeBase):
def __init__(self, frameSize=panningFrameSize, hopSize=panningHopSize,
sampleRate=analysisSampleRate):
super(PanningExtractor, self).__init__()
demuxer = StereoDemuxer()
fc_left = FrameCutter(frameSize=frameSize,
hopSize=hopSize,
startFromZero=False,
silentFrames='noise')
fc_right = FrameCutter(frameSize=frameSize,
hopSize=hopSize,
startFromZero=False,
silentFrames='noise')
w_left = Windowing(type='hann',
size=frameSize,
zeroPadding=frameSize)
w_right = Windowing(type='hann',
size=frameSize,
zeroPadding=frameSize)
spec_left = Spectrum()
spec_right = Spectrum()
pan = Panning(sampleRate=sampleRate,
averageFrames=43, # 2 seconds*sr/hopsize
panningBins=512,
numCoeffs=20,
numBands=1,
warpedPanorama=True)
# left channel:
demuxer.left >> fc_left.signal
fc_left.frame >> w_left.frame >> spec_left.frame
spec_left.spectrum >> pan.spectrumLeft
# right channel:
demuxer.right >> fc_right.signal
fc_right.frame >> w_right.frame >> spec_right.frame
spec_right.spectrum >> pan.spectrumRight
# define inputs:
self.inputs['signal'] = demuxer.audio
# define outputs:
self.outputs['panning_coefficients'] = pan.panningCoeffs
def computePanning(filename, pool, startTime, endTime, namespace=''):
'''4th pass: panning'''
if namespace:
llspace = namespace + '.lowlevel.'
else:
llspace = 'lowlevel.'
rgain, analysisSampleRate, downmix = getAnalysisMetadata(pool)
loader = streaming.AudioLoader(filename=filename)
trimmer = streaming.Trimmer(startTime=startTime, endTime=endTime)
panning = PanningExtractor(sampleRate=analysisSampleRate)
loader.audio >> panning.signal
loader.sampleRate >> None
loader.numberChannels >> None
panning.panning_coefficients >> (pool,'panning_coefficients')
run(loader)
usage = 'panning.py [options] <inputfilename> <outputfilename>'
def parse_args():
import numpy
essentia_version = '%s\n'\
'python version: %s\n'\
'numpy version: %s' % (essentia.__version__, # full version
sys.version.split()[0], # python major version
numpy.__version__) # numpy version
from optparse import OptionParser
parser = OptionParser(usage=usage, version=essentia_version)
parser.add_option("-c","--cpp", action="store_true", dest="generate_cpp",
help="generate cpp code from CompositeBase algorithm")
parser.add_option("-d", "--dot", action="store_true", dest="generate_dot",
help="generate dot and cpp code from CompositeBase algorithm")
(options, args) = parser.parse_args()
return options, args
if __name__ == '__main__':
opts, args = parse_args()
if len(args) != 2:
cmd = './'+os.path.basename(sys.argv[0])+ ' -h'
os.system(cmd)
sys.exit(1)
if opts.generate_dot:
essentia.translate(PanningExtractor, 'streaming_extractorpanning', dot_graph=True)
elif opts.generate_cpp:
essentia.translate(PanningExtractor, 'streaming_extractorpanning', dot_graph=False)
pool = essentia.Pool()
loader = AudioLoader(filename=args[0])
panExtractor = PanningExtractor()
loader.audio >> panExtractor.signal
loader.numberChannels >> None
loader.sampleRate >> None
panExtractor.panning_coefficients >> (pool, namespace + '.panning_coefficients')
essentia.run(loader)
essentia.standard.YamlOutput(filename=args[1])(pool)
|
using System;
using ColossalFramework.UI;
using UnityEngine;
namespace RSSChirp
{
public class RSSSettingsButton : UIButton
{
public override void Start () {
text = "RSS";
width = 40;
height = 30;
normalBgSprite = "ButtonMenu";
disabledBgSprite = "ButtonMenuDisabled";
hoveredBgSprite = "ButtonMenuHovered";
focusedBgSprite = "ButtonMenuFocused";
pressedBgSprite = "ButtonMenuPressed";
textColor = new Color32 (255, 255, 255, 255);
disabledTextColor = new Color32 (7, 7, 7, 255);
hoveredTextColor = new Color32 (7, 132, 255, 255);
focusedTextColor = new Color32 (255, 255, 255, 255);
pressedTextColor = new Color32 (30, 30, 44, 255);
playAudioEvents = true;
transformPosition = new Vector3 (0.95f, 0.95f);
}
}
}
|
#Error Messaging
import os
##############################
#attackctrl.py
def notification_attackctrl(type):
if type == "init":
os.system("python /usr/share/subterfuge/utilities/notification.py 'Starting' 'Subterfuge attack initializing...' '' 'hidden'")
elif type == "arpwatch-no-rmac":
os.system("python /usr/share/subterfuge/utilities/notification.py 'Startup Error!' 'Encountered an error configuring arpwatch: Router MAC Address Unknown.'")
elif type == "autoconfig-error":
os.system("python /usr/share/subterfuge/utilities/notification.py 'Startup Error!' 'Encountered an error configuring attack: Invalid Arguments in autoconfiguration.'")
elif type == "no-single-target":
os.system("python /usr/share/subterfuge/utilities/notification.py 'Startup Error!' 'Could not poison single target: no target found!.'")
##############################
#scan.py
def notification_scan(type):
if type == "path":
os.system("python /usr/share/subterfuge/utilities/notification.py 'Scan Error!' 'Error executing nmap scan. Is it in your PATH?'")
##############################
#main/views.py
def notification_main(type):
if type == "init":
os.system("python /usr/share/subterfuge/utilities/notification.py 'Starting' 'Subterfuge attack initializing...' '' 'hidden'")
|
// 设置图片合并的最小间隔
fis.config.set('settings.spriter.csssprites.margin', 20);
//对js、css、png图片引用添加md5
fis.match('*.{png,js,css}',{
useHash:true
});
//启用fis-spriter-csssprites插件
fis.match('::package',{
spriter:fis.plugin('csssprites')
});
fis.match('*.css',{
useSprites:true
});
// 对js、css、图片、html进行压缩
fis.match('*.js', {
optimizer: fis.plugin('uglify-js')
});
fis.match('*.css', {
optimizer: fis.plugin('clean-css')
});
fis.match('*.png', {
optimizer: fis.plugin('png-compressor')
});
fis.match('*.html', {
optimizer: fis.plugin('html-minifier')
});
// 开启simple插件
fis.config.set('modules.postpackager', 'simple');
// 设置打包规则
fis.config.set('pack', {
'/pkg/lib.js': [
'js/lib/jquery.js',
'js/lib/html5.js'
],
'/pkg/aio.css': '**.css'
});
//开启simple对零散资源的自动合并
fis.config.set('settings.postpackager.simple.autoCombine', true);
|
# Copyright (c) 2010 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2010, Eucalyptus Systems, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing 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 MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import xml.sax
import utils
class XmlHandler(xml.sax.ContentHandler):
def __init__(self, root_node, connection):
self.connection = connection
self.nodes = [('root', root_node)]
self.current_text = ''
def startElement(self, name, attrs):
self.current_text = ''
t = self.nodes[-1][1].startElement(name, attrs, self.connection)
if t != None:
if isinstance(t, tuple):
self.nodes.append(t)
else:
self.nodes.append((name, t))
def endElement(self, name):
self.nodes[-1][1].endElement(name, self.current_text, self.connection)
if self.nodes[-1][0] == name:
self.nodes.pop()
self.current_text = ''
def characters(self, content):
self.current_text += content
def parse(self, s):
xml.sax.parseString(s, self)
class Element(dict):
def __init__(self, connection=None, element_name=None,
stack=None, parent=None, list_marker=('Set',),
item_marker=('member', 'item'),
pythonize_name=False):
dict.__init__(self)
self.connection = connection
self.element_name = element_name
self.list_marker = utils.mklist(list_marker)
self.item_marker = utils.mklist(item_marker)
if stack is None:
self.stack = []
else:
self.stack = stack
self.pythonize_name = pythonize_name
self.parent = parent
def __getattr__(self, key):
if key in self:
return self[key]
for k in self:
e = self[k]
if isinstance(e, Element):
try:
return getattr(e, key)
except AttributeError:
pass
raise AttributeError
def get_name(self, name):
if self.pythonize_name:
name = utils.pythonize_name(name)
return name
def startElement(self, name, attrs, connection):
self.stack.append(name)
for lm in self.list_marker:
if name.endswith(lm):
l = ListElement(self.connection, name, self.list_marker,
self.item_marker, self.pythonize_name)
self[self.get_name(name)] = l
return l
if len(self.stack) > 0:
element_name = self.stack[-1]
e = Element(self.connection, element_name, self.stack, self,
self.list_marker, self.item_marker,
self.pythonize_name)
self[self.get_name(element_name)] = e
return (element_name, e)
else:
return None
def endElement(self, name, value, connection):
if len(self.stack) > 0:
self.stack.pop()
value = value.strip()
if value:
if isinstance(self.parent, Element):
self.parent[self.get_name(name)] = value
elif isinstance(self.parent, ListElement):
self.parent.append(value)
class ListElement(list):
def __init__(self, connection=None, element_name=None,
list_marker=['Set'], item_marker=('member', 'item'),
pythonize_name=False):
list.__init__(self)
self.connection = connection
self.element_name = element_name
self.list_marker = list_marker
self.item_marker = item_marker
self.pythonize_name = pythonize_name
def get_name(self, name):
if self.pythonize_name:
name = utils.pythonize_name(name)
return name
def startElement(self, name, attrs, connection):
for lm in self.list_marker:
if name.endswith(lm):
l = ListElement(self.connection, name,
self.list_marker, self.item_marker,
self.pythonize_name)
setattr(self, self.get_name(name), l)
return l
if name in self.item_marker:
e = Element(self.connection, name, parent=self,
list_marker=self.list_marker,
item_marker=self.item_marker,
pythonize_name=self.pythonize_name)
self.append(e)
return e
else:
return None
def endElement(self, name, value, connection):
if name == self.element_name:
if len(self) > 0:
empty = []
for e in self:
if isinstance(e, Element):
if len(e) == 0:
empty.append(e)
for e in empty:
self.remove(e)
else:
setattr(self, self.get_name(name), value)
|
#include <stdbool.h>
#include <stdint.h>
#define BUFFER_SIZE 8192 // that is (2^13)
/* A circular read buffer */
struct read_buffer {
char buffer[BUFFER_SIZE];
uint16_t read_position;
uint16_t write_position;
#ifdef DEBUG_BUILD
uint16_t write_remaining;
#endif
};
void rbuf_debug_check(struct read_buffer* buffer);
/*
Initialize the read and write position of a read_buffer
*/
void rbuf_init(struct read_buffer* buf);
/*
Copy n bytes from the buffer,
returns the number of bytes copied.
*/
int rbuf_copyn(struct read_buffer* buffer, char* dest, int n);
/*
Compare n bytes from the buffer from the read position,
returns the comparison result
*/
int rbuf_cmpn(struct read_buffer* buffer, const char* with, int n);
/*
Extract integer from character stream (ASCII)
Only process up to a maximum number of bytes (-1 for entire stream)
*/
bool rbuf_strntol(struct read_buffer* buffer, int* output, int max);
/*
Get the number of bytes remaining to read
*/
int rbuf_read_remaining(struct read_buffer* buffer);
/*
Get the number of contiguous bytes remaining to be read
until the end (highest index)
*/
int rbuf_read_to_end(struct read_buffer* buffer);
/*
Get the number of bytes that can be written until maximum
capacity.
*/
int rbuf_write_remaining(struct read_buffer* buffer);
/*
Get the number of contiguous bytes that can be written
*/
uint16_t rbuf_write_to_end(struct read_buffer* buffer);
void rbuf_debug_read_check(struct read_buffer* buffer, int by);
void rbuf_debug_write_incr(struct read_buffer* buffer, int by);
/*
Get a pointer to the buffer at the current read position
*/
#define RBUF_READ(x) &(x.buffer)[x.read_position & (BUFFER_SIZE-1)]
/*
Get a pointer to the buffer at the start (idx:0)
*/
#define RBUF_START(x) x.buffer
/*
Get a pointer to the buffer at the current write offset
*/
#define RBUF_WRITE(x) &(x.buffer)[x.write_position & (BUFFER_SIZE-1)]
/*
Move the read offset
*/
#define RBUF_READMOVE(x, by) rbuf_debug_read_check(&x, by); x.read_position+=by; rbuf_debug_check(&x);
/*
Move the write offset
*/
#define RBUF_WRITEMOVE(x, by) rbuf_debug_write_incr(&x, by); x.write_position+=by; rbuf_debug_check(&x);
#define RBUF_EMPTY(x) x->write_position == x->read_position
#define RBUF_READLEN(x) ((decltype( x.write_position ))(( x.write_position ) - ( x.read_position )))
#define RBUF_WRITELEN(x) BUFFER_SIZE - RBUF_READLEN(x)
#define RBUF_FULL(x) RBUF_LEN(x) == BUFFER_SIZE
/*
Get a pointer to the buffer at the current read position
*/
#define RBUF_READPTR(x) &(x->buffer)[x->read_position & (BUFFER_SIZE-1)]
/*
Get a pointer to the buffer at the start (idx:0)
*/
#define RBUF_STARTPTR(x) x->buffer
/*
Get a pointer to the buffer at the current write offset
*/
#define RBUF_WRITEPTR(x) &(x->buffer)[x->write_position & (BUFFER_SIZE-1)]
/*
Move the read offset
*/
#define RBUF_READMOVEPTR(x, by) rbuf_debug_read_check(x, by); x->read_position+=by; rbuf_debug_check(&x);
/*
Move the write offset
*/
#define RBUF_WRITEMOVEPTR(x, by) rbuf_debug_write_incr(x, by); x->write_position+=by; rbuf_debug_check(x);
#define RBUF_READLENPTR(x) ((decltype( x->write_position ))(( x->write_position ) - ( x->read_position )))
#define RBUF_WRITELENPTR(x) BUFFER_SIZE - RBUF_READLENPTR(x)
/*
Helper to Iterate over circular buffer
*/
#define RBUF_ITERATE(rb,n,buffer,end,ret,inner) do { \
end = rbuf_read_to_end(&rb); \
n = 0; \
if (end != 0){ \
buffer = RBUF_READ(rb); \
for (; ret == continue_processing && n < rbuf_read_remaining(&rb); n++){ \
if (end == n) { \
buffer = RBUF_START(rb); \
} \
ret = inner; \
buffer++; \
} \
} \
if (ret == continue_processing){ \
ret = needs_more; \
} \
} while (0);
|
/* mbed Microcontroller Library
* Copyright (c) 2018 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "NFCEEPROMDriver.h"
using namespace mbed;
using namespace mbed::nfc;
NFCEEPROMDriver::NFCEEPROMDriver() : _delegate(NULL), _event_queue(NULL)
{
}
NFCEEPROMDriver::~NFCEEPROMDriver()
{
}
void NFCEEPROMDriver::set_delegate(Delegate *delegate)
{
_delegate = delegate;
}
void NFCEEPROMDriver::set_event_queue(events::EventQueue *queue)
{
_event_queue = queue;
}
NFCEEPROMDriver::Delegate *NFCEEPROMDriver::delegate()
{
return _delegate;
}
events::EventQueue *NFCEEPROMDriver::event_queue()
{
return _event_queue;
}
|
#!/usr/bin/python
''' This file handles a database connection. It can simply be deleted if not needed.
The example given is for a PostgreSQL database, but can be modified for any other.
'''
from __future__ import print_function
from __future__ import division
from marvin.db.DatabaseConnection import DatabaseConnection
from pgpasslib import getpass
from marvin import config
import yaml
import os
# Read in the db connection configuration
dbconfigfile = 'dbconfig.ini'
dbconfigfile = os.path.join(os.path.dirname(os.path.abspath(__file__)), dbconfigfile)
try:
rawfile = open(dbconfigfile, 'r').read()
except IOError as e:
raise RuntimeError('IOError: Could not open dbconfigfile {0}:{1}'.format(dbconfigfile, e))
dbdict = yaml.load(rawfile)
# select the appropriate configuration from config
if config.db:
db_info = dbdict[config.db]
try:
if 'password' not in db_info:
db_info['password'] = getpass(db_info['host'], db_info['port'], db_info['database'], db_info['user'])
except KeyError:
raise RuntimeError('ERROR: invalid server configuration')
else:
raise RuntimeError('Error: could not determine db to connect to: {0}'.format(config.db))
# this format is only usable with PostgreSQL 9.2+
# dsn = "postgresql://{user}:{password}@{host}:{port}/{database}".format(**db_info)
# database_connection_string = 'postgresql+psycopg2://%s:%s@%s:%s/%s' % (db_info["user"], db_info["password"], db_info["host"], db_info["port"], db_info["database"])
# Build the database connection string
if db_info["host"] == 'localhost':
database_connection_string = 'postgresql+psycopg2:///%(database)s' % db_info
else:
database_connection_string = 'postgresql+psycopg2://%(user)s:%(password)s@%(host)s:%(port)i/%(database)s' % db_info
# Make a database connection
try:
db = DatabaseConnection()
except AssertionError as e:
db = DatabaseConnection(database_connection_string=database_connection_string)
engine = db.engine
metadata = db.metadata
Session = db.Session
Base = db.Base
except KeyError as e:
print("Necessary configuration value not defined.")
raise RuntimeError('KeyError: Necessary configuration value not defined: {0}'.format(e))
|
import os
import pytest
from mfr.core.provider import ProviderMetadata
from mfr.core.exceptions import RendererError
from mfr.extensions.jamovi import JamoviRenderer
BASE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'files')
@pytest.fixture
def metadata():
return ProviderMetadata('jamovi', '.omv', 'application/octet-stream', '1337',
'http://wb.osf.io/file/jamovi.omv?token=1337')
@pytest.fixture
def ok_path():
return os.path.join(BASE_PATH, 'ok.omv')
@pytest.fixture
def not_a_zip_file_path():
return os.path.join(BASE_PATH, 'not-a-zip-file.omv')
@pytest.fixture
def no_manifest_path():
return os.path.join(BASE_PATH, 'no-manifest.omv')
@pytest.fixture
def no_archive_version_in_manifest_path():
return os.path.join(BASE_PATH, 'no-data-archive-version-in-manifest.omv')
@pytest.fixture
def archive_version_is_too_old_path():
return os.path.join(BASE_PATH, 'data-archive-version-is-too-old.omv')
@pytest.fixture
def no_index_html_path():
return os.path.join(BASE_PATH, 'no-index_html.omv')
@pytest.fixture
def contains_malicious_script_path():
return os.path.join(BASE_PATH, 'contains-malicious-script.omv')
@pytest.fixture
def url():
return 'http://wb.osf.io/file/jamovi.omv'
@pytest.fixture
def assets_url():
return 'http://mfr.osf.io/assets'
@pytest.fixture
def export_url():
return 'http://mfr.osf.io/export?url=' + url()
@pytest.fixture
def extension():
return '.omv'
@pytest.fixture
def renderer(metadata, ok_path, url, assets_url, export_url):
return JamoviRenderer(metadata, ok_path, url, assets_url, export_url)
class TestCodeJamoviRenderer:
def test_render_jamovi(self, renderer):
body = renderer.render()
assert '<div style="word-wrap: break-word; overflow: auto;" class="mfrViewer">' in body
def test_render_jamovi_not_a_zip_file(self, metadata, not_a_zip_file_path, url, assets_url,
export_url):
try:
renderer = JamoviRenderer(metadata, not_a_zip_file_path, url, assets_url, export_url)
renderer.render()
except RendererError:
return
assert False # should not get here
def test_render_jamovi_no_manifest(self, metadata, no_manifest_path, url, assets_url,
export_url):
try:
renderer = JamoviRenderer(metadata, no_manifest_path, url, assets_url, export_url)
renderer.render()
except RendererError:
return
assert False # should not get here
def test_render_jamovi_no_archive_version_in_manifest(self, metadata,
no_archive_version_in_manifest_path,
url, assets_url, export_url):
try:
renderer = JamoviRenderer(metadata, no_archive_version_in_manifest_path, url,
assets_url, export_url)
renderer.render()
except RendererError:
return
assert False # should not get here
def test_render_jamovi_archive_is_too_old(self, metadata, archive_version_is_too_old_path, url,
assets_url, export_url):
try:
renderer = JamoviRenderer(metadata, archive_version_is_too_old_path, url, assets_url,
export_url)
renderer.render()
except RendererError:
return
assert False # should not get here
def test_render_jamovi_no_index_html(self, metadata, no_index_html_path, url, assets_url,
export_url):
try:
renderer = JamoviRenderer(metadata, no_index_html_path, url, assets_url, export_url)
renderer.render()
except RendererError:
return
assert False # should not get here
def test_render_jamovi_contains_malicious_script(self, metadata, contains_malicious_script_path,
url, assets_url, export_url):
renderer = JamoviRenderer(metadata, contains_malicious_script_path, url, assets_url,
export_url)
body = renderer.render()
assert '<script>' not in body
assert ' onclick="' not in body
def test_render_jamovi_file_required(self, renderer):
assert renderer.file_required is True
def test_render_jamovi_cache_result(self, renderer):
assert renderer.cache_result is True
|
from bs4 import BeautifulSoup
from couchpotato.core.helpers.encoding import toUnicode, tryUrlencode
from couchpotato.core.helpers.variable import tryInt
from couchpotato.core.logger import CPLog
from couchpotato.core.providers.torrent.base import TorrentProvider
import re
import traceback
log = CPLog(__name__)
class ILoveTorrents(TorrentProvider):
urls = {
'download': 'http://www.ilovetorrents.me/%s',
'detail': 'http://www.ilovetorrents.me/%s',
'search': 'http://www.ilovetorrents.me/browse.php?search=%s&page=%s&cat=%s',
'test' : 'http://www.ilovetorrents.me/',
'login' : 'http://www.ilovetorrents.me/takelogin.php',
'login_check' : 'http://www.ilovetorrents.me'
}
cat_ids = [
(['41'], ['720p', '1080p', 'brrip']),
(['19'], ['cam', 'ts', 'dvdrip', 'tc', 'r5', 'scr']),
(['20'], ['dvdr'])
]
cat_backup_id = 200
disable_provider = False
http_time_between_calls = 1
def _searchOnTitle(self, title, movie, quality, results):
page = 0
total_pages = 1
cats = self.getCatId(quality['identifier'])
while page < total_pages:
movieTitle = tryUrlencode('"%s" %s' % (title, movie['library']['year']))
search_url = self.urls['search'] % (movieTitle, page, cats[0])
page += 1
data = self.getHTMLData(search_url)
if data:
try:
soup = BeautifulSoup(data)
results_table = soup.find('table', attrs = {'class': 'koptekst'})
if not results_table:
return
try:
pagelinks = soup.findAll(href = re.compile('page'))
pageNumbers = [int(re.search('page=(?P<pageNumber>.+'')', i['href']).group('pageNumber')) for i in pagelinks]
total_pages = max(pageNumbers)
except:
pass
entries = results_table.find_all('tr')
for result in entries[1:]:
prelink = result.find(href = re.compile('details.php'))
link = prelink['href']
download = result.find('a', href = re.compile('download.php'))['href']
if link and download:
def extra_score(item):
trusted = (0, 10)[result.find('img', alt = re.compile('Trusted')) is not None]
vip = (0, 20)[result.find('img', alt = re.compile('VIP')) is not None]
confirmed = (0, 30)[result.find('img', alt = re.compile('Helpers')) is not None]
moderated = (0, 50)[result.find('img', alt = re.compile('Moderator')) is not None]
return confirmed + trusted + vip + moderated
id = re.search('id=(?P<id>\d+)&', link).group('id')
url = self.urls['download'] % (download)
fileSize = self.parseSize(result.select('td.rowhead')[5].text)
results.append({
'id': id,
'name': toUnicode(prelink.find('b').text),
'url': url,
'detail_url': self.urls['detail'] % link,
'size': fileSize,
'seeders': tryInt(result.find_all('td')[2].string),
'leechers': tryInt(result.find_all('td')[3].string),
'extra_score': extra_score,
'get_more_info': self.getMoreInfo
})
except:
log.error('Failed getting results from %s: %s', (self.getName(), traceback.format_exc()))
def getLoginParams(self):
return {
'username': self.conf('username'),
'password': self.conf('password'),
'submit': 'Welcome to ILT',
}
def getMoreInfo(self, item):
cache_key = 'ilt.%s' % item['id']
description = self.getCache(cache_key)
if not description:
try:
full_description = self.getHTMLData(item['detail_url'])
html = BeautifulSoup(full_description)
nfo_pre = html.find('td', attrs = {'class':'main'}).findAll('table')[1]
description = toUnicode(nfo_pre.text) if nfo_pre else ''
except:
log.error('Failed getting more info for %s', item['name'])
description = ''
self.setCache(cache_key, description, timeout = 25920000)
item['description'] = description
return item
def loginSuccess(self, output):
return 'logout.php' in output.lower()
loginCheckSuccess = loginSuccess
|
/**
* NativeFmodEx Project
*
* Want to use FMOD Ex API (www.fmod.org) in the Java language ? NativeFmodEx is made for you.
* Copyright © 2005-2008 Jérôme JOUVIE (Jouvieje)
*
* Created on 23 feb. 2005
* @version file v1.0.0
* @author Jérôme JOUVIE (Jouvieje)
*
*
* WANT TO CONTACT ME ?
* E-mail :
* [email protected]
* My web sites :
* http://jerome.jouvie.free.fr/
*
*
* INTRODUCTION
* FMOD Ex is an API (Application Programming Interface) that allow you to use music
* and creating sound effects with a lot of sort of musics.
* FMOD is at :
* http://www.fmod.org/
* The reason of this project is that FMOD Ex can't be used direcly with Java, so I've created
* this project to do this.
*
*
* GNU LESSER GENERAL PUBLIC LICENSE
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1 of the License,
* or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the
* Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*/
package org.jouvieje.FmodEx.Callbacks;
import org.jouvieje.FmodEx.*;
import org.jouvieje.FmodEx.Exceptions.*;
import org.jouvieje.FmodEx.Callbacks.*;
import org.jouvieje.FmodEx.*;
import org.jouvieje.FmodEx.Defines.*;
import org.jouvieje.FmodEx.Enumerations.*;
import org.jouvieje.FmodEx.Structures.*;
import java.nio.*;
import org.jouvieje.FmodEx.Misc.*;
import org.jouvieje.FmodEx.System;
public interface FMOD_MEMORY_REALLOCCALLBACK
{
/**
*/
public ByteBuffer FMOD_MEMORY_REALLOCCALLBACK(ByteBuffer ptr, int size, int type);
}
|
package teamOD.armourReborn.common.modifiers;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.World;
public class TraitFireResistant extends AbstractTrait {
public TraitFireResistant () {
super ("fire retardant", TextFormatting.RED) ;
}
@Override
public void onArmorTick(World world, EntityPlayer player, ItemStack itemStack) {
if (player.isBurning()) {
player.extinguish() ;
}
}
}
|
# -*- coding: utf-8 -*-
"""
Copyright (c) 2013-2019 Matic Kukovec.
Released under the GNU GPL3 license.
For more information check the 'LICENSE.txt' file.
For complete license information of the dependencies, check the 'additional_licenses' directory.
"""
import os
import sip
import os.path
import collections
import traceback
import ast
import inspect
import math
import functools
import textwrap
import difflib
import re
import time
import settings
import functions
import data
import components
import themes
"""
-----------------------------------------------------------------------------------
ExCo Information Widget for displaying the license, used languages and libraries, ...
-----------------------------------------------------------------------------------
"""
class ExCoInfo(data.QDialog):
#Class variables
name = "Ex.Co. Info"
savable = data.CanSave.NO
#Class functions(methods)
def __init__(self, parent, app_dir=""):
"""Initialization routine"""
#Initialize superclass, from which the current class is inherited,
#THIS MUST BE DONE SO THAT THE SUPERCLASS EXECUTES ITS __init__ !!!!!!
super().__init__()
#Setup the window
self.setWindowTitle("About Ex.Co.")
self.setWindowFlags(data.Qt.WindowStaysOnTopHint)
#Setup the picture
exco_picture = data.QPixmap(data.about_image)
self.picture = data.QLabel(self)
self.picture.setPixmap(exco_picture)
self.picture.setGeometry(self.frameGeometry())
self.picture.setScaledContents(True)
#Assign events
self.picture.mousePressEvent = self._close
self.picture.mouseDoubleClickEvent = self._close
#Initialize layout
self.layout = data.QGridLayout()
self.layout.addWidget(self.picture)
self.layout.setSpacing(0)
self.layout.setContentsMargins(
data.QMargins(0,0,0,0)
)
self.setLayout(self.layout)
#Set the log window icon
if os.path.isfile(data.application_icon) == True:
self.setWindowIcon(data.QIcon(data.application_icon))
#Save the info window geometry, the values were gotten by showing a dialog with the label containing
#the ExCo info image with the size set to (50, 50), so it would automatically resize to the label image size
my_width = 610
my_height = 620
#Set the info window position
parent_left = parent.geometry().left()
parent_top = parent.geometry().top()
parent_width = parent.geometry().width()
parent_height = parent.geometry().height()
my_left = parent_left + (parent_width/2) - (my_width/2)
my_top = parent_top + (parent_height/2) - (my_height/2)
self.setGeometry(data.QRect(my_left, my_top, my_width, my_height))
self.setFixedSize(my_width, my_height)
# self.setStyleSheet("background-color:transparent;")
# self.setWindowFlags(data.Qt.WindowStaysOnTopHint | data.Qt.Dialog | data.Qt.FramelessWindowHint)
# self.setAttribute(data.Qt.WA_TranslucentBackground)
def _close(self, event):
"""Close the widget"""
self.picture.setParent(None)
self.picture = None
self.layout = None
self.close()
|
'use strict';
/**
* Module dependencies.
*/
var should = require('should'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
Messages = mongoose.model('Messages');
/**
* Globals
*/
var user, messages, user2;
/**
* Unit tests
*/
describe('Messages Model Unit Tests:', function() {
beforeEach(function(done) {
user = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: '[email protected]',
username: 'username',
password: 'password'
});
user2 = new User({
firstName: 'Full2',
lastName: 'Name2',
displayName: 'Full2 Name2',
email: '[email protected]',
username: 'username2',
password: 'password2'
});
user2.save(function() {});
user.save(function() {
messages = new Messages({
userTo: user.username,
userFrom: user2.username,
messageSubject: 'hi',
messageBody: 'hi world'
});
done();
});
});
describe('Method Save', function() {
it('should be able to save without problems', function(done) {
return messages.save(function(err) {
should.not.exist(err);
done();
});
});
it('should be able to show an error when try to save with no userTo', function(done) {
messages.userTo = '';
return messages.save(function(err) {
should.exist(err);
done();
});
});
});
afterEach(function(done) {
Messages.remove().exec();
User.remove().exec();
done();
});
});
|
# Django settings for example project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Christopher Glass', '[email protected]'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'test.sqlite', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'Europe/Zurich'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'h2%uf!luks79rw^4!5%q#v2znc87g_)@^jf1og!04@&&tsf7*9'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = [
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
]
import django
if django.VERSION[0] < 1 or django.VERSION[1] <3:
MIDDLEWARE_CLASSES.append('cbv.middleware.DeferredRenderingMiddleware')
ROOT_URLCONF = 'testapp.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
'django.contrib.admindocs',
'shop', # The django SHOP application
'project', # the test project application
)
# The shop settings:
SHOP_CART_MODIFIERS= ['shop.cart.modifiers.rebate_modifiers.BulkRebateModifier']
SHOP_SHIPPING_BACKENDS=['shop.shipping.backends.flat_rate.FlatRateShipping']
# Shop module settings
SHOP_SHIPPING_FLAT_RATE = '10' # That's just for the flat rate shipping backend
|
#ifndef ATCMPROGRESSBARTASKMENU_H
#define ATCMPROGRESSBARTASKMENU_H
#include <QDesignerTaskMenuExtension>
#include <QExtensionFactory>
class QAction;
class QExtensionManager;
class ATCMprogressbar;
class atcmprogressbarTaskMenu : public QObject, public QDesignerTaskMenuExtension
{
Q_OBJECT
Q_INTERFACES(QDesignerTaskMenuExtension)
public:
atcmprogressbarTaskMenu(ATCMprogressbar *anim, QObject *parent);
QAction *preferredEditAction() const;
QList<QAction *> taskActions() const;
private slots:
void editState();
private:
QAction *editStateAction;
ATCMprogressbar *progressbar;
};
class atcmprogressbarTaskMenuFactory : public QExtensionFactory
{
Q_OBJECT
public:
atcmprogressbarTaskMenuFactory(QExtensionManager *parent = 0);
protected:
QObject *createExtension(QObject *object, const QString &iid, QObject *parent) const;
};
//Q_DECLARE_METATYPE(atcmprogressbarTaskMenu);
#endif
|
import { generateUtilityClass, generateUtilityClasses } from '@mui/base';
export interface SpeedDialActionClasses {
/** Styles applied to the Fab component. */
fab: string;
/** Styles applied to the Fab component if `open={false}`. */
fabClosed: string;
/** Styles applied to the root element if `tooltipOpen={true}`. */
staticTooltip: string;
/** Styles applied to the root element if `tooltipOpen={true}` and `open={false}`. */
staticTooltipClosed: string;
/** Styles applied to the static tooltip label if `tooltipOpen={true}`. */
staticTooltipLabel: string;
/** Styles applied to the root element if `tooltipOpen={true}` and `tooltipPlacement="left"`` */
tooltipPlacementLeft: string;
/** Styles applied to the root element if `tooltipOpen={true}` and `tooltipPlacement="right"`` */
tooltipPlacementRight: string;
}
export type SpeedDialActionClassKey = keyof SpeedDialActionClasses;
export function getSpeedDialActionUtilityClass(slot: string): string {
return generateUtilityClass('MuiSpeedDialAction', slot);
}
const speedDialActionClasses: SpeedDialActionClasses = generateUtilityClasses(
'MuiSpeedDialAction',
[
'fab',
'fabClosed',
'staticTooltip',
'staticTooltipClosed',
'staticTooltipLabel',
'tooltipPlacementLeft',
'tooltipPlacementRight',
],
);
export default speedDialActionClasses;
|
/* include/config.h. Generated automatically by configure. */
/* include/config.h.in. Generated automatically from configure.in by autoheader. */
/* Define as the return type of signal handlers (int or void). */
#define RETSIGTYPE void
#define HAVE_STDARG_H 1
/* host guessing */
#define CONFIG_HOST_TYPE ""
/* Define if snprintf is broken */
#define BROKEN_SNPRINTF 1
/* Define to to use pthreads instead of fork or clone for htxf */
/* #undef CONFIG_HTXF_PTHREAD */
/* Define to to use clone instead of fork for htxf */
/* #undef CONFIG_HTXF_CLONE */
/* Define to use fork instead of clone for htxf */
#define CONFIG_HTXF_FORK 1
/* Define to compile image preview code */
/* #undef CONFIG_HTXF_PREVIEW */
/* Define to enable HFS */
#define CONFIG_HFS 1
/* Define to compile megahal */
/* #undef CONFIG_HAL */
/* Define to compile HOPE */
/* #undef CONFIG_HOPE */
/* Define to compile cipher */
/* #undef CONFIG_CIPHER */
/* Define to compile compress */
/* #undef CONFIG_COMPRESS */
/* Define if you have the strcasestr function */
#define HAVE_STRCASESTR 1
/* Define if you have the basename function */
#define HAVE_BASENAME 1
/* Define if you have the realpath function */
/* #undef HAVE_REALPATH */
/* Define if you have the strptime function */
/* #undef HAVE_STRPTIME */
/* Path to tr */
#define PATH_TR "/usr/bin/tr"
/* Default sound player */
#define DEFAULT_SND_PLAYER "play"
/* Define to compile trackname command */
/* #undef CONFIG_XMMS */
/* Define to dull the icon of a user when the user is away */
/* #undef CONFIG_DULLED */
/* Enable IPv6 Support */
/* #undef CONFIG_IPV6 */
/* apple constants */
/* #undef HOST_DARWIN */
/* #undef CORESERVICES */
/* The number of bytes in a int. */
#define SIZEOF_INT 4
/* The number of bytes in a long. */
#define SIZEOF_LONG 8
/* The number of bytes in a void *. */
#define SIZEOF_VOID_P 8
/* Define if you have the getdtablesize function. */
#define HAVE_GETDTABLESIZE 1
/* Define if you have the gethostname function. */
#define HAVE_GETHOSTNAME 1
/* Define if you have the getrlimit function. */
#define HAVE_GETRLIMIT 1
/* Define if you have the hstrerror function. */
#define HAVE_HSTRERROR 1
/* Define if you have the inet_aton function. */
#define HAVE_INET_ATON 1
/* Define if you have the inet_ntoa_r function. */
/* #undef HAVE_INET_NTOA_R */
/* Define if you have the localtime_r function. */
#define HAVE_LOCALTIME_R 1
/* Define if you have the putenv function. */
#define HAVE_PUTENV 1
/* Define if you have the snprintf function. */
#define HAVE_SNPRINTF 1
/* Define if you have the tcgetattr function. */
#define HAVE_TCGETATTR 1
/* Define if you have the tcsetattr function. */
#define HAVE_TCSETATTR 1
/* Define if you have the vsnprintf function. */
#define HAVE_VSNPRINTF 1
/* Define if you have the <openssl/rand.h> header file. */
/* #undef HAVE_OPENSSL_RAND_H */
/* Define if you have the <pthread.h> header file. */
/* #undef HAVE_PTHREAD_H */
/* Define if you have the <stdarg.h> header file. */
/* #undef HAVE_STDARG_H */
/* Define if you have the <sys/select.h> header file. */
/* #undef HAVE_SYS_SELECT_H */
/* Define if you have the <termcap.h> header file. */
/* #undef HAVE_TERMCAP_H */
/* Define if you have the 44bsd library (-l44bsd). */
/* #undef HAVE_LIB44BSD */
/* Define if you have the m library (-lm). */
/* #undef HAVE_LIBM */
/* Define if you have the nsl library (-lnsl). */
/* #undef HAVE_LIBNSL */
/* Define if you have the pthread library (-lpthread). */
/* #undef HAVE_LIBPTHREAD */
/* Define if you have the resolv library (-lresolv). */
/* #undef HAVE_LIBRESOLV */
/* Define if you have the socket library (-lsocket). */
/* #undef HAVE_LIBSOCKET */
|
/*
* DEFINE POPOVER TO HELP TEXT
* ---------------------------
*
* This is a configuration to enable popover to elements
* with "help" class.
*/
setTimeout(function() {
$('.help').popover({ trigger: "hover" });
}, 2000);
/*
* DEFINE MASK TO INPUTS
* ---------------------------
*
* This is a configuration to enable mask to
* inputs.
*/
setTimeout(function() {
$(":input").inputmask();
$(".cep").inputmask("99999-999");
$(".phone").inputmask("(99) 9{4,5}-9999");
$(".birth").inputmask("99/99/9999");
$(".cpf").inputmask("999.999.999-99");
}, 2000);
|
import asciinema
import sys
from setuptools import setup
if sys.version_info.major < 3:
sys.exit('Python < 3 is unsupported.')
url_template = 'https://github.com/asciinema/asciinema/archive/v%s.tar.gz'
requirements = []
test_requirements = ['nose']
with open('README.md', encoding='utf8') as file:
long_description = file.read()
setup(
name='asciinema',
version=asciinema.__version__,
packages=['asciinema', 'asciinema.commands', 'asciinema.asciicast'],
license='GNU GPLv3',
description='Terminal session recorder',
long_description=long_description,
long_description_content_type='text/markdown',
author=asciinema.__author__,
author_email='[email protected]',
url='https://asciinema.org',
download_url=(url_template % asciinema.__version__),
entry_points={
'console_scripts': [
'asciinema = asciinema.__main__:main',
],
},
package_data={'asciinema': ['data/*.png']},
data_files=[('share/doc/asciinema', ['CHANGELOG.md',
'CODE_OF_CONDUCT.md',
'CONTRIBUTING.md',
'README.md',
'doc/asciicast-v1.md',
'doc/asciicast-v2.md']),
('share/man/man1', ['man/asciinema.1'])],
install_requires=requirements,
tests_require=test_requirements,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Topic :: System :: Shells',
'Topic :: Terminals',
'Topic :: Utilities'
],
)
|
#!/usr/bin/env python
# coding=utf-8
"""
The MIT License (MIT)
Copyright (c) 2010-2015, Ryan Fan <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import os
from django.core.management.base import BaseCommand, CommandError
from web.core.management.commands._baseproject import LEGACY_MODE,BaseProject
class ProducerProject(BaseProject):
def __init__(self, name, dir):
self.type = "producer"
self.name = name
self.dir = dir
super(ProducerProject, self).__init__()
class Command(BaseCommand):
"""
If Django version <1.8, it use option_list to add additional options
If Django version >=1.8, it use add_parse() function to add additional options
"""
args = '[name] [optional destination directory]'
help = "Create wcmb producer project"
if LEGACY_MODE:
from optparse import make_option
option_list = BaseCommand.option_list + (
#make_option(),
)
# only useful for Django version >= 1.8
def add_arguments(self, parser):
# Positional arguments
# parser.add_argument('id', nargs='+', type=int)
# Named (optional) arguments
parser.add_argument(
'-h',
'--help',
action='store_true',
dest='help_producer',
default=False,
help='Help how to create celery producer'
)
def handle(self, name="producer", dir=None, **options):
"""
To be compatible with Django>=1.8,
It is encouraged to exclusively use **options for new commands.
"""
# by default, project_dir is project_name
if dir is None:
top_dir = os.path.join(os.getcwd(), name)
else:
top_dir = os.path.abspath(os.path.expanduser(dir))
if not os.path.exists(top_dir):
raise CommandError("Destination directory '%s' does not "
"exist, please create it first." % top_dir)
#self.build_fs_structure(top_dir)
# new consumer project
proj = ProducerProject(name, top_dir)
proj.config()
|
import os
# We don't want to run metrics for unittests, automatically-generated C files,
# external libraries or git leftovers.
EXCLUDE_SOURCE_DIRS = {"src/test/", "src/trunnel/", "src/rust/",
"src/ext/" }
EXCLUDE_FILES = {"orconfig.h"}
def _norm(p):
return os.path.normcase(os.path.normpath(p))
def get_tor_c_files(tor_topdir, include_dirs=None):
"""
Return a list with the .c and .h filenames we want to get metrics of.
"""
files_list = []
exclude_dirs = { _norm(os.path.join(tor_topdir, p)) for p in EXCLUDE_SOURCE_DIRS }
if include_dirs is None:
topdirs = [ tor_topdir ]
else:
topdirs = [ os.path.join(tor_topdir, inc) for inc in include_dirs ]
for topdir in topdirs:
for root, directories, filenames in os.walk(topdir):
# Remove all the directories that are excluded.
directories[:] = [ d for d in directories
if _norm(os.path.join(root,d)) not in exclude_dirs ]
directories.sort()
filenames.sort()
for filename in filenames:
# We only care about .c and .h files
if not (filename.endswith(".c") or filename.endswith(".h")):
continue
if filename in EXCLUDE_FILES:
continue
full_path = os.path.join(root,filename)
files_list.append(full_path)
return files_list
class NullFile:
"""A file-like object that we can us to suppress output."""
def __init__(self):
pass
def write(self, s):
pass
|
import mongoose from 'mongoose';
const { Schema } = mongoose;
const wishSchema = new Schema({
release: { type: Schema.Types.ObjectId, ref: 'Release' },
dateAdded: { type: Date },
user: { type: Schema.Types.ObjectId, ref: 'User' }
});
wishSchema.index({ user: 1, release: 1 }, { unique: true });
const Wish = mongoose.model('Wish', wishSchema, 'wishlist');
export default Wish;
|
/*
This file is part of the QRPG project
Copyright (C) 2015 Marco Willems
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, see <http://www.gnu.org/licenses/>.
*/
#include "qrpgscene.h"
#include <QPainter>
#include <QDebug>
QRPG::QRPGScene::QRPGScene(QObject *parent) : QObject(parent)
{
}
QRPG::QRPGScene::~QRPGScene()
{
}
void QRPG::QRPGScene::render(QPixmap *screen, const QPointF &pos)
{
// QMutexLocker locker(&renderMutex);
QRectF screenRect(pos.x(), pos.y(), screen->rect().width(), screen->rect().height());
if (!screen->isNull()) {
QPainter painter(screen);
painter.fillRect(screen->rect(), Qt::black);
foreach (QSet<GraphicsItem *> layerItems, itemsPerLayer.values()) {
foreach (GraphicsItem *item, layerItems) {
// if (itemIsInRect(screen->rect(), item)) {
if (itemIsInRect(screenRect, item)) {
painter.drawPixmap(item->pos() - pos, *(item->pixmap()), item->boundingRect());
}
}
}
painter.end();
}
}
bool QRPG::QRPGScene::addGraphicsItem(GraphicsItem *item, int layer)
{
bool exists = false;
foreach (QSet<GraphicsItem *> set, itemsPerLayer) {
if (set.contains(item)) {
exists = true;
}
}
if (!exists) {
itemsPerLayer[layer].insert(item);
}
return !exists;
}
bool QRPG::QRPGScene::deleteGraphicsItem(QRPG::GraphicsItem *item)
{
bool exists = false;
foreach (QSet<GraphicsItem *> set, itemsPerLayer) {
if (set.contains(item)) {
exists = true;
set.remove(item);
}
}
return exists;
}
void QRPG::QRPGScene::doTick()
{
foreach (QSet<GraphicsItem *> set, itemsPerLayer) {
foreach (GraphicsItem *item, set) {
item->doTick();
}
}
}
bool QRPG::QRPGScene::itemIsInRect(const QRectF &rect, const GraphicsItem *item) const
{
QRectF itemRect(item->pos(), QSizeF(item->boundingRect().width(), item->boundingRect().height()));
return rect.intersects(itemRect);
}
|
##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, [email protected], All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# 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 terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class Launchmon(Package):
"""Software infrastructure that enables HPC run-time tools to
co-locate tool daemons with a parallel job."""
homepage = "https://github.com/LLNL/LaunchMON"
url = "https://github.com/LLNL/LaunchMON/releases/download/v1.0.2/launchmon-v1.0.2.tar.gz"
version('1.0.2', '8d6ba77a0ec2eff2fde2c5cc8fa7ff7a')
depends_on('autoconf', type='build')
depends_on('automake', type='build')
depends_on('libtool', type='build')
depends_on('libgcrypt')
depends_on('libgpg-error')
depends_on("elf", type='link')
depends_on("boost")
depends_on("spectrum-mpi", when='arch=ppc64le')
def install(self, spec, prefix):
configure(
"--prefix=" + prefix,
"--with-bootfabric=cobo",
"--with-rm=slurm")
make()
make("install")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.