prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
t(ctxt, self.host)
# FIXME volume count for exporting is wrong
LOG.debug("Re-exporting %s volumes" % len(volumes))
try:
self.stats['pools'] = {}
self.stats.update({'allocated_capacity_gb': 0})
for volume in volumes:
# available volume should a... | context,
request_spec,
filter_properties,
snapshot_id=snapshot_id,
image_id=image_id,
source_volid=source_volid,
source_replicaid=source_replicaid,
consistencygroup_id=consistencygroup_id,
... | snapshot_id=cgsnapshot_id)
except Exception:
LOG.exception(_LE("Failed to create manager volume flow"))
raise exception.CinderException(
_("Failed to create manager volume flow."))
if snapshot_id is not None:
# Make sure the snapshot is not deleted un... |
d[1] < 0:
return True
return False
def takeAction(self, sCoord, action):
"""
Receives an action value, performs associated movement.
"""
if action is 0:
return self.up(sCoord)
if action is 1:
return self.down(sCoord)
if action is 2:
return self.left(sCoord)
if action is 3:
return s... | = self.takeAction(currentState, 3)
self.t[state][action][self.coordToScalar(nextState)] = 1.0
if action == 4:
self.t[state][action][state] = 1.0
if action == 5:
currentState = self.scalarToCoord(state)
nextState = sel | f.takeAction(currentState, 5)
self.t[state][action][self.coordToScalar(nextState)] = 1.0
if action == 6:
currentState = self.scalarToCoord(state)
nextState = self.takeAction(currentState, 6)
self.t[state][action][self.coordToScalar(nextState)] = 1.0
if action == 7:
currentState = s... |
import pylab
import string
import matplotlib
matplotlib.rcParams['figure.subplot.hspace']=.45
matplotlib.rcParams['figure.subplot.wspace']=.3
labels=('Step=1','Step=.5','Step=.25','Step=.01')
steps=(1,.5,.25,.01)
pylab.figure(figsize=(8.5,11))
for i,intxt in enumerate(('O_RK1.txt','O_RK_5.txt','O_RK_25.txt','O_RK_... | (0,100)
pylab.xlabel('Time')
pylab.ylabel('Energy')
pylab.suptitle('RK4 Orbit Integration')
pylab.savefig('RK4_orbit_int.pdf')
pylab.close()
pylab.figure(figsize=(8.5,11))
for i,intxt in enumerate(('O_LF1.txt','O_LF_5.txt','O_LF_25.txt','O_LF_1.txt')):
infile=open(intxt,'r')
t=[]
xs=[]
ys=[]
... | nd(float(line[2]))
Es.append(float(line[5]))
pylab.subplot(4,2,2*i+1)
pylab.plot(xs,ys,'-',lw=2)
pylab.ylim(-1,1)
pylab.xlim(-1,1)
pylab.xlabel('X')
pylab.ylabel('Y')
pylab.title('Step=%f'%(steps[i]))
pylab.subplot(4,2,2*i+2)
pylab.plot(t,Es,'-',lw=1)
pylab.xlim(0,100)
... |
estatus
# and the ingress resource actually getting updated is longer than the
# time spent waiting for resources to be ready, so this test will fail (most of the time)
time.sleep(1)
yield Query(self.url(self.name + "/"))
yield Query(self.url(f'need-normaliza... | serviceName: {self.target.path.k8s}-target2
servicePort: 80
path: /{self.name}-target2/
""" + super().manifests()
def queries(self):
if sys.platform != 'darw | in':
text = json.dumps(self.status_update)
update_cmd = [KUBESTATUS_PATH, 'Service', '-n', 'default', '-f', f'metadata.name={self.name.k8s}', '-u', '/dev/fd/0']
subprocess.run(update_cmd, input=text.encode('utf-8'), timeout=10)
# If you run these tests individually, the ... |
"target.restrict.aqd-unittest.ms.com, but ",
cmd)
def test_201_verify_autocreate(self):
cmd = ["search", "dns", "--fullinfo",
"--fqdn", "target.restrict.aqd-unittest.ms.com"]
out = self.commandtest(cmd)
self.matchoutput(out,
... |
self.assertIn("eth0", interfaces)
self.assertEqual(interfaces["eth0"].aliases[0], 'alias0.aqd-unittest.ms.com')
self.assertEqual(interfaces["eth0"].aliases[1], 'alias01.aqd-unittest.ms.com')
self.assertEqual(interfaces["eth0"].ip, str(ip))
self.assertEqual(interfaces["eth0"].fqd... | ittest.ms.com')
command = ["del", "alias", "--fqdn", "alias01.aqd-unittest.ms.com"]
out = self.commandtest(command)
command = ["del", "alias", "--fqdn", "alias0.aqd-unittest.ms.com"]
out = self.commandtest(command)
def test_710_show_alias_host(self):
ip = self.net["zebra_e... |
[u'/rw/', u'5'],
[u'/si/', u'21'],
[u'/sk/', u'875'],
[u'/sl/', u'530'],
[u'/son/', u'1'],
[u'/sq/', u'27'],
[u'/sr-Cyrl/', u'256'],
[u'/sv/', u'1488'],
[u'/ta-LK/', u'13'],
[u'/ta/', u'13'],
[u'/te/', u'6'],
[u'/th/', u'29... | s a pageview.
[u'/en-US/kb/doc-5/discuss', u'1'], # Doesn't count as a pageview
| [u'/en-US/kb/doc-5?param=ab', u'2'], # Counts as a pageview.
[u'/en-US/kb/doc-5?param=cd', u'4']], # Counts as a pageview.
u'containsSampledData': False,
u'columnHeaders': [
{u'dataType': u'STRING',
u'columnType': u'DIMENSION',
u'name': u'ga:pagePath'},
{u'dat... |
# coding: utf-8
import sys
from setuptools import setup, find_packages
NAME = "pollster"
VERSION = "2.0.2"
# To install the library, run the following
#
# python setup.py install
#
# prerequisite: setuptools
# http://pypi.python.org/pypi/setu | ptools
REQUIRES = ["urllib3 >= 1.15", "six >= 1.10", "certifi", "python-dateutil", "pandas >= 0.19.1"]
setup(
name=NAME,
version=VERSION,
description="Pollster API",
author_email="Adam Hooper <adam.hooper@huffingtonpost.com>",
url="https://github.com/huffpostdata/python-pollster",
keywords=["P... | IRES,
packages=find_packages(),
include_package_data=True,
long_description="""Download election-related polling data from Pollster."""
)
|
lepath is {}'.format(filepath))
database.add_results_to_cache(query, user, results, filepath)
base_reference = 'https://www.passivetotal.org/search/whois/email'
# Use our config defined indicator type of whois email objects
crits_indicator_type = it.WHOIS_REGISTRANT_EMAIL_ADDRESS
bucket_list.ap... | not in CRITs, add all the associated indicators
bucket_list = ['whois pivoting', 'pt:found']
for t in args.tags:
bucket_list.append(t)
| new_ind = crits.add_indicator(
value=result['domain'],
itype=it.DOMAIN,
source=config.crits.default_source,
reference=reference,
method='pt_query.py',
bucket_list=bucket_list,
indicator_confidence=confide... |
from __future__ import absolute_import, print_function
from datetime import timedelta
from django.utils import timezone
from freezegun import freeze_time
from sentry.models import CheckInStatus, Monitor, MonitorCheckIn, MonitorStatus, MonitorType
from sentry.testutils import APITestCase
@freeze_time("2019-01-01")
c... | ateMonitorCheckInTest(APITestCase):
def test_passing(self):
user = self.create_user()
org = self.create_organization(owner=user)
team = self.create_team(organization=org, members=[use | r])
project = self.create_project(teams=[team])
monitor = Monitor.objects.create(
organization_id=org.id,
project_id=project.id,
next_checkin=timezone.now() - timedelta(minutes=1),
type=MonitorType.CRON_JOB,
config={"schedule": "* * * * *"},
... |
from dataclasses import asdict, dataclass
from typing import List, Optional
from license_grep.licenses import UnknownLicense, canonicalize_licenses
from lic | ense_grep.utils import unique_in_order
@dataclass
class PackageInfo:
name: str
version: str
type: str
raw_licenses: Optional[List[str]]
location: str
context: Optional[str]
@property
def licenses(self):
for license, canonicalized_license in canonicalize_licenses(self.raw_licen... | ):
yield canonicalized_license
@property
def licenses_string(self):
return ", ".join(
unique_in_order(str(license or "<UNKNOWN>") for license in self.licenses)
)
@property
def spec(self):
return f"{self.name}@{self.version}"
@property
def full_s... |
#!/usr/bin/env python
# Copyright (c) 2012 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.
"""Top level script for running all python unittests in the NaCl SDK.
"""
from __future__ import print_function
import argparse
i... |
'extract']
subprocess.check_call(cmd)
def main(args):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-v', '--verbose', action='store_true')
parser.add_argument('--quick', action='store_tru | e')
options = parser.parse_args(args)
# Some of the unit tests use parts of toolchains. Extract to TOOLCHAIN_OUT.
print('Extracting toolchains...')
ExtractToolchains()
suite = unittest.TestSuite()
modules = TEST_MODULES
if not options.quick:
modules += TEST_MODULES_BIG
for module_name in modules:... |
import unittest
from ncclient.devices.alu import *
from ncclient.xml_ import *
import re
xml = """<rpc-reply xmlns:junos="http://xml.alu.net/alu/12.1x46/alu">
<routing-engin>
<name>reX</name>
<commit-success/>
<!-- This is a comment -->
</routing-engin>
<ok/>
</rpc-reply>"""
class TestAluDevice(unittest.TestCase):
... | uration
expected["show_cli"] = Sh | owCLI
expected["load_configuration"] = LoadConfiguration
self.assertDictEqual(expected, self.obj.add_additional_operations())
def test_transform_reply(self):
expected = re.sub(r'<rpc-reply xmlns:junos="http://xml.alu.net/alu/12.1x46/alu">',
r'<?xml version="1.0... |
"""Commands related to networks are in this module"""
import click
import sys
from hil.cli.client_setup import client
@click.group()
def network():
"""Commands related to network"""
@network.command(name='create', short_help='Create a new network')
@click.argument('network')
@click.argument('owner')
@click.opti... | gument('network')
def network_show(network):
"""Display information about network"""
q = client.network.show(network)
for item in q.items():
sys.stdout.write("%s\t : %s\n" % (item[0], item[1]))
@network.command(name='list')
def network_list():
"""List all networks"""
q = client.network.l... | ))
@network.command('list-attachments')
@click.argument('network')
@click.option('--project', help='Name of project.')
def list_network_attachments(network, project):
"""Lists all the attachments from <project> for <network>
If <project> is `None`, lists all attachments for <network>
"""
print client... |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012 Alex Forencich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this s | oftware 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... | , 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 OTHER... |
# -*- coding: utf-8 -*-
#
# test_pp_psc_delta_stdp.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST 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 ... | abel('time [ms]')
pylab.ylabel('weight [mV]')
pylab.legend(loc='best')
ylims = pylab.ylim() |
pylab.ylim(ylims[0] - 5, ylims[1] + 5)
# pylab.savefig('test_pp_psc_delta_stdp_fig1.png')
nest.raster_plot.from_device(sd)
ylims = pylab.ylim()
pylab.ylim(ylims[0] - .5, ylims[1] + .5)
pylab.show()
# pylab.savefig('test_pp_psc_delta_stdp_fig2.png')
print 'Archiver lengths shall be equal:'
for nrn in [nrn_post1, nrn... |
s calculation from temperature dependences
# to speed up
pass
def _GEOS(self, xi):
"""Definition of parameters of generalized cubic equation of state,
each child class must define in this procedure the values of mixture
a, b, delta, epsilon. The returned values are not dimen... | ai, kiji in zip(Ai, self.kij):
suma = 0
for xj, aj, kij in zip(zi, Ai, kiji):
suma += xj*(1-kij)*(ai*aj)**0.5
aij.append(suma)
tita = []
for bi, aai in zip(Bi, aij):
rhs = bi/B*(Z-1) - log(Z-B) + A/B/(self.u-self.w)*(
... | ing rules to individual parameters to get the mixture
parameters for EoS
Although it possible use any of available mixing rules, for now other
properties calculation as fugacity helmholtz free energy are defined
using the vdW mixing rules.
Parameters
----------
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('taxbrain', '0002_taxoutput_tax_result'),
]
operations = [
migrations.AddF | ield(
model_name='taxsa | veinputs',
name='parameters',
field=models.TextField(default=None),
preserve_default=True,
),
]
|
from __future__ import absolute_import
from rest_framework.response import Response
from sentry import filters
from sentry.api.bases.project import ProjectEndpoint
class ProjectFiltersEndpoint(ProjectEndpoint):
def get(self, request, project):
"""
List a project's filters
Retrieve a lis... | ,
# 'active' will be either a boolean or list for the legacy browser filters
# all other filters will be boolean
'active': filter.is_enabled(),
'description': filter.description,
| 'name': filter.name,
})
results.sort(key=lambda x: x['name'])
return Response(results)
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | y': 'properties.instanceView', 'type': 'VirtualMachineInstanceView'},
'license_type': {'key': 'properties.licenseType', 'type': 'str'},
'vm_id' | : {'key': 'properties.vmId', 'type': 'str'},
'identity': {'key': 'identity', 'type': 'VirtualMachineIdentity'},
'zones': {'key': 'zones', 'type': '[str]'},
}
def __init__(self, **kwargs):
super(VirtualMachineUpdate, self).__init__(**kwargs)
self.plan = kwargs.get('plan', None)
... |
class resonance():
"""
This class represents a resonance.
"""
def __init__(self,cR=1.0,wR=[],w0=1.,r0=.5,phase=0. | ):
self.wR=wR
self.cR=cR
self.w0=w0
self.r0=r0
| self.phase=phase
def toString(self):
"""
Returns a string of the resonance data memebers delimited by newlines.
"""
return "\n".join(["wR="+str(self.wR),"cR="+str(self.cR),"w0="+str(self.w0),"r0="+str(self.r0)]) |
'''
Convert a table from a nested list to a nested dictionary and back.
-----------------------------------------------------------
(c) 2013 Allegra Via and Kristian Rother
Licensed under the conditions of the Python License
This code appears in section 7.4.3 of the book
"Managing Biological Data with Py... | row[0], key[1]: row[1], key[2]: row[2],
key[3]: row[3]}
nested_dict['row'+str(n)] = entry
# Test
# print(table[1:])
print(nested_dict)
nested_list = []
for entry in nested_dict:
key = nested_d | ict[entry]
nested_list.append([key['protein'], key['ext1'], key['ext2'],
key['ext3']])
print(nested_list)
|
error = e
if too_many:
Log.error(
"multiple keys in {{bucket}} with prefix={{prefix|quote}}: {{list}}",
bucket=self.name,
prefix=key,
list=[k.name for k in metas],
)
if not p... | h|comma}})",
file_length=file_length,
string_length=string_length,
)
value.seek(0)
storage.set_contents_from_file(value, headers=headers)
if self.settings.public:
storage.set_acl("public-read")
... | tr(key + ".json.gz"))
if is_binary(value):
value = convert.bytes2zip(value)
key += ".json.gz"
else:
value = convert.bytes2zip(value).encode("utf8")
key += ".json.gz"
headers = {"Content-Type":... |
# -*- encoding: utf-8 -*-
from abjad import *
def test_p | itchtools_PitchClass_is_pitch_class_number_01():
assert pitchtools.PitchClass.is_pitch_class_number(0)
assert pitchtools.PitchClass.is_pitch_class_number(0.5)
assert pitchtools.PitchClass.is_pitch_class_number(11)
assert pitchtools.PitchClass.is_pitch_class_number(11.5)
def test_pitchtools_PitchClass... | itchClass.is_pitch_class_number(12)
assert not pitchtools.PitchClass.is_pitch_class_number(99)
assert not pitchtools.PitchClass.is_pitch_class_number('foo') |
# OpenShot Video Editor is a program that creates, modifies, and edits video files.
# Copyright (C) 2009 Jonathan Thomas
#
# This file is part of OpenShot Video Editor (http://launchpad.net/openshot/).
#
# OpenShot Video Editor is free software: you can redistribute it and/or modify
# it under the terms of the GNU G... | bpy.data.materials["Material.line3"]
material_object.diffuse_color = params["line3_color"]
material_object = | bpy.data.materials["Material.line4"]
material_object.diffuse_color = params["line4_color"]
# Set the render options. It is important that these are set
# to the same values as the current OpenShot project. These
# params are automatically set by OpenShot
bpy.context.scene.render.filepath = params["output_path"]
bpy... |
#!/user/bin/python
'''
This script uses SimpleCV to grab an image from the camera and numpy to find an infrared LED and report its position relative to the camera view centre and whether it is inside the target area.
Attempted stabilisation of the output by tracking a circular object instead and altering exposure of t... | 0
# If the target is in the box, indicate this with the box colour
if deg_y is 0 and deg_x is 0 and found:
box_clr = SimpleCV.Color.GREEN
else:
box_clr | = SimpleCV.Color.RED
#output the data
# not needed if there's no new data to report
if not lossReported:
message = {
't' : millis(),
'findTime': findTime,
'found' : found,
'tar_px' : {'x':... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015 NLPY.ORG
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
import numpy as np
from line_iterator import LineIterator
class FeatureContainer(object):
def __init__(self, path=None, dtype="libsvm", feature_n=-1):
s... | e_n == -1:
max_key = max(feature_map.keys()) if feature_map else 0
else:
max_key = self.feature_n
features = []
for fidx in range(1, max_key + 1):
if fidx in feature_map:
features.append(feature_map[fidx])
... | #
# self.data = np.array(xs)
# self.targets = np.array(ys) |
'''
Task Coach - Your friendly task manager
Copyright (C) 2004-2010 Task Coach developers <developers@taskcoach.org>
Task Coach 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
... |
def testEventIsAllowedWhenDragBeginsWithItem(self):
| event = DummyEvent(self.item)
self.treeCtrl.OnBeginDrag(event)
self.assertEventIsAllowed(event)
def testEventIsAllowedWhenDragBeginWithSelectedItem(self):
self.treeCtrl.SelectItem(self.item)
event = DummyEvent(self.item)
self.treeCtrl.OnBeginDrag(event)
... |
dFile, render
from olympia.bandwagon.models import Collection
from olympia.files.models import File, FileUpload
from olympia.stats.search import get_mappings as get_stats_mappings
from olympia.versions.models import Version
from .decorators import admin_required
from .forms import (
AddonStatusForm, FeaturedCollec... | else:
qs = Addon.search().query(name__text=q.lower())[:100]
if len(qs) == 1: |
return redirect('zadmin.addon_manage', qs[0].id)
ctx['addons'] = qs
return render(request, 'zadmin/addon-search.html', ctx)
@never_cache
@json_view
def general_search(request, app_id, model_id):
if not admin.site.has_permission(request):
raise PermissionDenied
try:
mo... |
xit with 128 + {reiceived SIG}
# 128 - 141 == -13 == -SIGPIPE, sometimes python receives -13 for some subprocesses
raise RuntimeError('Error reading from pipe. Subcommand exited with non-zero exit status %s.' % self._process.returncode)
def close(self):
self._finish()
def __del... | ream)
def write(self, b):
self._stream.write(self._convert(b))
def writelines(self, lines):
self._stream.writelines((self._convert(line) for line in lines))
def _convert(self, b):
if isinstance(b, six.text_type):
b = b.encode(self.encoding)
warnings.warn('W... | :
"""
Interface for format specifications.
"""
@classmethod
def pipe_reader(cls, input_pipe):
raise NotImplementedError()
@classmethod
def pipe_writer(cls, output_pipe):
raise NotImplementedError()
def __rshift__(a, b):
return ChainFormat(a, b)
class ChainFor... |
import unittest
from card import Card
class CardT | est(unittest.TestCase):
def test_create(self):
suit = 'Hearts'
rank = 'Ace'
card1 = Card(suit, rank)
self.assertEqual((suit, rank), card1.get_value())
def test___eq__(self):
card1 = Card('Spades', 'Queen')
card2 = Card('Spades', 'Queen')
self.assertEqual(... | 'Queen')
self.assertNotEqual(card1, card3)
if __name__ == '__main__':
unittest.main(verbosity=2)
|
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask, render_template
from flask_login import LoginManager
from flask_restful import Api
from flask_wtf.csrf import CsrfProtect
from itsdangerous import URLSafeTimedSerializer
from sqlalchemy import create_engine
import AppConfig
from R... | ources.Resources import PostsList, Posts
from services.Services import UserService
from views import Login, Common, Post, Admin
app = Flask(__name__)
CsrfProtect(app)
login_serializer = URLSafeTimedSerializer(AppConfig.APPSECRETKEY)
@app.errorhandler(404)
def not_found(error):
return render_template('404.html... | fig.APPSECRETKEY
def register_mods():
app.register_blueprint(Common.mod)
app.register_blueprint(Login.mod)
app.register_blueprint(Post.mod)
app.register_blueprint(Admin.mod)
def create_db_engine():
return create_engine(AppConfig.CONNECTIONSTRING, pool_recycle=3600, echo=True)
def build_db_engi... |
import pytest
from bughouse.models import (
BLACK,
WHITE,
OVERALL_OVERALL,
)
from bughouse.ratings.engines.overall import (
rate_teams,
rate_players,
)
def test_rate_single_game(factories, models, elo_settings):
game = factories.GameFactory()
r1, r2 = rate_teams(game)
assert r1.ratin... | actories.GameFactory(winning_team=team_a, losing_team=team_b)
factories.GameFactory(winning_team=team_a, losing_team=team_b)
first_rating_initial = team_a.ratings.get(
game=game_b,
).rating
rate_teams(game_b)
first_rating_recomputed = team_a.ratings.get(
game=game_b,
).rating
... | _recomputed
|
# License AGPL-3.0 or late | r (https://www.gnu.org/licenses/agpl).
from . im | port mod123
|
__problem_title__ = "Integer sided triangles for which the area/perimeter ratio is integral"
__problem_url___ = "https://projecteuler.net/problem=283"
__problem_description__ = "Consider the triangle with sides 6, 8 and 10. It can be seen that the " \
"perimeter and the area are both equal t... | l to 2. Find the sum of " \
"the perimeters of all integer | sided triangles for which the " \
"area/perimeter ratios are equal to positive integers not exceeding " \
"1000."
import timeit
class Solution():
@staticmethod
def solution1():
pass
@staticmethod
def time_solutions():
setup = 'from... |
n wrest:
try:
select.append(all_lines.index(iwrest))
except ValueError:
pass
select.sort()
# GUIs
self.vplt_widg.llist['List'] = llist['List']
self.vplt_widg.llist['show_line'] = select
self.vplt_widg.idx_line = 0
se... | #z=2.96916
#lines = [1548.195, 1550.770]
norm = True
spec_fil = '/Users/xavier/Dropbox/CASBAH/jxp_analysis/FBQS0751+2919/fbqs0751_nov2014bin.fits'
z=0.4391
lines = [1215.6701, 1025.7223] * u.AA
| norm = False
# Launch
spec = lsi.readspec(spec_fil)
app = QtGui.QApplication(sys.argv)
app.setApplicationName('AODM')
main = XAODMGui(spec, z, lines, norm=norm)
main.show()
sys.exit(app.exec_())
else: # RUN A GUI
id_gui = i... |
# -*- coding: utf-8 -*-
"""
example1-simpleloop
~~~~~~~~~~~~~~~~~~~
This example shows how to use the loop block backend and frontend.
:copyright: 2015 by Lantz Authors, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
# From lantz, you import a helper function.
from... | ers).
from lantz.drivers.examples.dummydrivers import DummyOsci
# Drivers are instantiated in the usual way.
osci = DummyOsci('COM2')
# You create a function that will be called by the loop
# It requires three parameters
# counter - the iteration number
# iterations - total number of iterations
# overrun - a boolean ... | on
# is longer than the interval.
def measure(counter, iterations, overrun):
print(counter, iterations, overrun)
data = osci.measure()
print(data)
# You instantiate the loop
app = Loop()
# and assign the function to the body of the loop
app.body = measure
# Finally you start the program
start_g... |
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
... | gether': "(('parent', 'name'),)", 'object_name': 'Folder'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'level': ('django.db.models.fields.PositiveInt... | 'modified_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'filer_owned_folders'... |
lat1) * LOCATION_SCAL | ING_FACTOR, (lon2 - lon1) * LOCATION_SCALING_FACTOR * longitude_scale(lat1*1.0e-7))
def add_offset(lat_e7, lon_e7, ofs_north, ofs_east):
'''add offset in meters to a position'''
dlat = int(float(ofs_north) * LOCATION_SCALING_FACTOR_INV)
dlng = int((float(ofs_east) * LOCATION_SCALING_FACTOR_INV) / longitude... |
return (int(lat_e7+dlat), int(lon_e7+dlng))
def east_blocks(lat_e7, lon_e7):
'''work out how many blocks per stride on disk'''
lat2_e7 = lat_e7
lon2_e7 = lon_e7 + 10*1000*1000
# shift another two blocks east to ensure room is available
lat2_e7, lon2_e7 = add_offset(lat2_e7, lon2_e7, 0, 2*GRID... |
import os
class Program:
socke | tColorBoTe = "255 2 | 55 255 255"
socketColorBa = "77 87 152 255"
progColorRareBoTe = "0 0 0 255"
progColorRareBa = "240 220 180 255"
progColorElseBoTe = "77 87 152 255"
progColorElseBa = "0 0 0 255"
def createFile(self):
filepath = os.path.join('~/dest', "filterZZ.filter")
if not os.path.exists('~/d... |
# Generated by Django 2.2.12 on 2020-05-09 06:28
from django.db import migrations
# Can't use fixtures because load_fixtures method is janky with django-tenant-schemas
def load_initial_data(apps, schema_editor):
Grade = apps.get_model('courses', 'Grade')
# add some initial data if none has been created yet
... | ",
value=11
)
Grade.objects.create(
name="12",
value=12
) |
class Migration(migrations.Migration):
dependencies = [
('courses', '0015_auto_20200508_1957'),
]
operations = [
migrations.RunPython(load_initial_data),
]
|
"""A Python module for interacting and consuming responses from Slack."""
import logging
import slack.errors as e
from slack.web.internal_utils import _next_cursor_is_present
class AsyncSlackResponse:
"""An iterable container of response data.
Attributes:
data (dict): The json-encoded content of th... | Returns:
(AsyncSlackResponse)
This method returns it's own object. e.g. 'self'
Raises:
SlackApiError: The request to the Slack API failed.
"""
if self.status_code == 200 and self.data and self.data.get("ok", False):
return self
msg = ... | "
raise e.SlackApiError(message=msg, response=self)
|
"""
Dynamic DNS updates
===================
Ensure a DNS record is present or absent utilizing RFC 2136
type dynamic updates.
:depends: - `dnspython <http://www.dnspython.org/>`_
.. note::
The ``dnspython`` module is required when managing DDNS using a TSIG key.
If you are not using a TSIG key, DDNS is allow... | omment"] = '{} record "{}" will be updated'.format(rdtype, name)
re | turn ret
status = __salt__["ddns.update"](zone, name, ttl, rdtype, data, **kwargs)
if status is None:
ret["result"] = True
ret["comment"] = '{} record "{}" already present with ttl of {}'.format(
rdtype, name, ttl
)
elif status:
ret["result"] = True
ret[... |
"""Launch the interactive command-line interface.
Returns:
The OnRunStartResponse specified by the user using the "run" command.
"""
self._register_this_run_info(self._run_cli)
response = self._run_cli.run_ui(
init_command=self._init_command,
title=self._title,
title... | tensor filter \"%s\" does not exist." %
parsed | .till_filter_pass])
# Raise CommandLineExit exception to cause the CLI to exit.
raise debugger_cli_common.CommandLineExit(exit_token=run_start_response)
def _register_this_run_info(self, curses_cli):
curses_cli.register_command_handler(
"run",
self._run_handler,
self._argparsers[... |
from django.test import TestCase
from store.forms import ReviewForm
from store.models import Review
from .factories import *
class ReviewFormTest(TestCase):
def test_form_validation_for_blank_items(self):
p1 = ProductFactory.create()
form = ReviewForm(
data={'name':'', 'text': '', '... | alid())
self.assertEqual(form.errors['text'],["Please fill in the | review"])
self.assertEqual(form.errors['rating'],["Please leave a valid rating"])
def test_form_validation_for_required_name_field(self):
p1 = ProductFactory.create()
form = ReviewForm(
data={'name':'', 'text': 'Hello', 'rating': 2, 'product':p1.id})
self.assertFalse(f... |
{
"name" : "Add sales team to website | leads (OBSOLETE)",
| "version" : "0.1",
"author" : "IT-Projects LLC, Ivan Yelizariev",
'license': 'GPL-3',
"category" : "Website",
"website" : "https://yelizariev.github.io",
"depends" : ["website_crm"],
#"init_xml" : [],
#"update_xml" : [],
#"active": True,
"installable": True
}
|
#-*- coding: utf-8 -*-
# Author : Jeonghoonkang, github.com/jeonghoonkang
import platform
import sys
import os
import time
import traceb | ack
import requests
import RPi.GPIO as GPIO
from socket import gethostname
hostname = gethostname()
SERVER_ADDR = '211.184.76.80'
GPIO.setwarnings(False)
GPIO.cleanup()
GPIO.setmode(GPIO.BCM)
GPIO.setup(19, | GPIO.OUT) # for LED indicating
GPIO.setup(26, GPIO.OUT) # for LED indicating
def query_last_data_point(bridge_id):
url = 'http://%s/api/raw_bridge_last/?bridge_id=%d' % (SERVER_ADDR, bridge_id)
try:
ret = requests.get(url, timeout=10)
if ret.ok:
ctx = ret.json()
if ctx['code'] == 0:
return ctx['resu... |
import time
import os
import posixpath
import datetime
import math
import re
import logging
from django import template
from django.utils.encoding import smart_unicode
from django.utils.safestring import mark_safe
from forum.models import Question, Answer, QuestionRevision, AnswerRevision, NodeRevision
from django.util... | er(context)
for line in source.splitlines():
m = self.dec_re.search(line)
if m:
clist = list(context)
clist.reverse()
d = {}
d['_'] = _
d['os'] = os
d['html'] = html
d['revers... |
except Exception, e:
logging.error("Error in declare tag, when evaluating: %s" % m.group(3).strip())
raise
return ''
@register.tag(name='declare')
def do_declare(parser, token):
nodelist = parser.parse(('enddeclare',))
parser.delete_first_token()... |
# Copright (C) 2015 Eric Skoglund
#
# 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 t... | 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/gpl-2.0.html
import requests
import sys
class NotSupported(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class PasteSite(object):
def __init__(self, url):
self.url = url
self.pas... |
###########################################################
#
# Copyright (c) 2005, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permi... | d = "12345"
# create an asset
mel('sphere -n sphere1')
mel('circle -n circle1')
mel('group -n |%s |circle1 |sphere1' % asset_code )
# convert node into a maya asset
node = | MayaNode("|%s" % asset_code )
asset_node = MayaAssetNode.add_sid( node, sid )
# checkin the asset
checkin = MayaAssetNodeCheckin(asset_node)
Command.execute_cmd(checkin)
# create a file from this node
asset_node.export()
if __name__ == '__main__':
unittest.ma... |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | extracted.
Returns:
A numpy `ndarray` of the DataFrame's values.
"""
if not isinstance(data, pd.DataFrame):
return data
return data.as_matrix()
def extract_pandas_labels(labels):
"""Extract data from pandas.DataFrame for labels.
Args:
| labels: `pandas.DataFrame` or `pandas.Series` containing one column of
labels to be extracted.
Returns:
A numpy `ndarray` of labels from the DataFrame.
Raises:
ValueError: if more than one column is found or type is not int, float or
bool.
"""
if isinstance(labels,
pd.Data... |
from euler_functions import is_pandigital_set, number_digits
for x in range(9123, 987 | 6): # much smaller range: http://www.mathblog.dk/project-euler-38-pandigital-multiplying-fixed-number/
products = []
n = 1
num_digits_in_products = 0
while num_digits_in_products < 9:
products.append(x * n)
n += 1
num_digits_in_products = 0
for p in products:
num_digits_in_products += number_digits(p... | igital_set(*products):
print products
break
|
iscovery_timeout(), _patch_discovery_interval():
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.SETUP_RETRY
with patch(f"{MODULE}.AsyncBulb", return_value=_mocked_bulb()), _patch_discovery(
n... | ODULE}.AsyncBulb", return_value=mocked_bulb
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert len(mocked_bulb.async_get_properties.mock_calls) == 1
mocked_bulb._async_callback({KEY_CONNECT | ED: False})
await hass.async_block_till_done()
assert hass.states.get("light.test_name").state == STATE_UNAVAILABLE
assert len(mocked_bulb.async_get_properties.mock_calls) == 1
mocked_bulb._async_callback({KEY_CONNECTED: True})
async_fire_time_changed(
hass, dt_util.u... |
numerate(self.important_ops): |
op_types[idx] = self.type_dict[node.op]
# output shape
op_name = node.name
for i, output_prop in enumerate(self.node_properties[op_name]):
if output_prop.shape.__str__() == "<unknown>": |
continue
shape = output_prop.shape
for j, dim in enumerate(shape.dim):
if dim.size >= 0:
if i * self.hparams.max_output_size + j >= output_embed_dim:
break
op_output_shapes[idx,
i * self.hparams.max_output_size + j] ... |
idget=forms.Select(choices=colleges))
number = forms.IntegerField(label=u"الدفعة", widget=forms.Select(choices=[(i, i) for i in range(1, 17)]))
def clean(self):
cleaned_data = super(RegistrationForm, self).clean()
batch_msg = u"الدفعة التي اخترت غير موجودة."
if 'college' in cleaned_data... | ge_url, data=login_data, cookies=cookies)
login_cookies = login_page.history[0].cookies
cookies = {#'oc_username': login_cookies['oc_username'],
#'oc_token': login_cookies['oc_token'],
#'oc_remember_login': login_cookies['oc_remember_login'],
'oc1d6beae686': login_co... | 686'],
}
return cookies
def createuser(user, password, group):
os.environ['OC_PASS'] = password
command = "/usr/local/bin/php70 /home/medcloud/webapps/ownphp70/occ user:add {} --password-from-env -g {} -n".format(user, group)
output = subprocess.call(command, shell=True)
if output ==... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils import timezone
from django.db import models, migrations
def fill_tables(apps, schema_editor):
eventsforbusv2 = apps.get_model('AndroidRequests', 'EventForBusv2')
eventsforbusstop = apps.get_model('AndroidRequests', 'EventForBus... | hhperiod = hhperiods.objects.get(initial_time__lte = creationTime , end_time__gte = creationTime)
ev.halfHourPeriod = hhperiod
ev.save()
class Migration(migrations.Migration):
dependencies = [
('AndroidRequests', '0903_transformation_halfhourperiod'),
]
operations = [
... | ventforbusv2',
name='halfHourPeriod',
field=models.ForeignKey(verbose_name=b'Half Hour Period', to='AndroidRequests.HalfHourPeriod', null=True),
preserve_default=False,
),
migrations.AddField(
model_name='eventforbusstop',
name='halfHourPeriod'... |
import exceptions
# thr | ows by anything which doesn't like what was passed to it
class DataError(exceptions.StandardError):
pass
# thrown by MojoMessage
class MojoMessageError(DataError):
pass
# thrown by DataTypes
class BadFormatError(DataError):
pass
# throws by things which do block reassembly
class ReassemblyErr | or(IOError):
pass
|
from setuptools import setup
setup(
name = "zml",
packages = ["zml"],
ve | rsion = "0.8.1",
description = "zero markup language",
author = "Christof Hagedorn",
author_email = "team@zml.org",
ur | l = "http://www.zml.org/",
download_url = "https://pypi.python.org/pypi/zml",
keywords = ["zml", "zero", "markup", "language", "template", "templating"],
install_requires = ['pyparsing', 'html5lib', 'pyyaml', 'asteval' ],
classifiers = [
"Programming Language :: Python",
"Programming Lan... |
tr
is_implemented: bool # True iff all unions required by the goal are implemented.
consumed_scopes: Tuple[str, ...] # The scopes of subsystems consumed by this goal.
@dataclass(frozen=True)
class TargetFieldHelpInfo:
"""A container for help information for a field in a target type."""
alias: str
... | scope_info.description,
| is_implemented,
consumed_scopes_mapper(scope_info.scope),
)
name_to_target_type_info = {
alias: TargetTypeHelpInfo.create(target_type, union_membership=union_membership)
for alias, target_type in registered_target_types.aliases_to_types.ite... |
""")
expected_meta = {'page_title': ['custom title']}
self.assertEqual(html.strip(), expected_html)
self.assertEqual(str(toc).strip(), expected_toc)
self.assertEqual(meta, expected_meta)
def test_convert_internal_link(self):
md_text = 'An [internal link](internal.... | n_fenced_code_extension(self):
"""
Ensure that the fenced code extension is supported.
"""
html, toc, meta = build.convert_markdown(dedent("""
```
print 'foo'
```
"""))
expected_html = dedent("""
<pre><code>print 'foo'\n</code></pre>
... | at an extension applies when requested in the arguments to
`convert_markdown`.
"""
md_input = "foo__bar__baz"
# Check that the plugin is not active when not requested.
expected_without_smartstrong = "<p>foo<strong>bar</strong>baz</p>"
html_base, _, _ = build.convert_mark... |
def func():
va | lue = "not-none"
# Is none
<caret>if value is None:
print("None")
else:
p | rint("Not none") |
from geojson_rewind import rewind
from geomet import wkt
import decimal
import statistics
def wkt_rewind(x, digits=None):
"""
reverse WKT winding order
:param x: [str] WKT string
:param digits: [int] number of digits after decimal to use for the return string.
by default, we use the mean num... | z = wkt.loads(x)
if digits is None:
coords = z["coordinates"]
nums = __flatten(coords)
dec_n = [decimal.Decimal(str(w)).as_tuple().exponent for w in nums]
digits = abs(statistics.mean(dec_n))
else:
if not isinstance(digits, int):
raise TypeError("'digits' mu... | _to_wkt
# from https://stackoverflow.com/a/12472564/1091766
def __flatten(S):
if S == []:
return S
if isinstance(S[0], list):
return __flatten(S[0]) + __flatten(S[1:])
return S[:1] + __flatten(S[1:])
|
`` None
| ``required:`` False
| ``default:`` None
:param select: The list of attributes to return for each DeviceServiceService. V | alid values are DeviceServiceServiceID, DeviceID, DataSourceID, ParentDeviceServiceID, ChildDeviceServiceID, SvsvFirstSeenTime, SvsvStartTime, SvsvEndTime, SvsvTimestamp, SvsvChangedCols, SvsvUsage, SvsvProvisionData. If empty or omitted, all attributes will be returned.
:type select: Array
| | ``api version min:`` 2.8
| ``api version max:`` None
| ``required:`` False
| ``default:`` None
:param goto_field: The field name for NIOS GOTO that is used for locating a row position of records.
:type goto_field: String
| ``api version m... |
on
except ImportError:
import common
from autotest.client.shared.global_config import global_config
require_atfork = global_config.get_config_value(
'AUTOSERV', 'require_atfork_module', type=bool, default=True)
try:
import atfork
atfork.monkeypatch_os_fork_functions()
import atfork.stdlib_fixe... |
# Server side tests that call shell scripts often depend on $USER being set
# but depending on how you launch your autotest scheduler it may not be set.
os.environ['USER'] = getpass.getuser()
if parser.options.machines:
machines = parser.options.machines.replace(',', ' ').strip().split()
| else:
machines = []
machines_file = parser.options.machines_file
label = parser.options.label
group_name = parser.options.group_name
user = parser.options.user
client = parser.options.client
server = parser.options.server
install_before = parser.options.install_before
install_aft... |
e else reduced_to_budgets
self.scenario = scenario
self.original_runhistory = original_runhistory
self.validated_runhistory = validated_runhistory
self.trajectory = trajectory
self.ta_exec_dir = ta_exec_dir
self.file_format = file_format
self.validation_format = ... | o=True)
msg = "Validation of default and incumbent failed. SMAC (v: {}) does not support vali | dation of budgets+ins"\
"tances yet, if you use budgets but no instances ignore this warning.".format(str(smac_version))
if self.feature_names:
self.logger.warning(msg)
else:
self.logger.debug(msg)
# Set during execution, to share inform... |
from django.contrib import admin
from workflow.model | s import State, StateLog, NextState, Project, Location
from workflow.activities import StateActivity
class NextStateInline(admin.StackedInline):
model = NextState
fk_name = 'current_state'
extra = 0
class StateAdmin | (admin.ModelAdmin):
inlines = [NextStateInline, ]
list_display = ('name', 'is_work_state',)
class StateLogAdmin(admin.ModelAdmin):
readonly_fields = ['start', 'end', 'state', 'user']
list_display = ('user', 'state', 'project', 'location', 'start', 'end',)
admin.site.register(State, StateAdmin)
admin... |
import unittest
import instruction_set
class TestInstructionSet(unittest.TestCase):
def test_generate(self):
self.assertIsInstance(instruction_set.generate(), list)
self.assertEqual(len(instruction_set.generate()), 64)
self.assertEqual(len(instruction_set.generate(32)), 32)
inse... | ssertLess(instruction, 256)
def test_mutate_bytes(self):
inset = instruction_set.generate()
self.assertEqual(len(inset), len(instruction_set.mutate_bytes(inset)))
self.assertEqual(inset, instruction_set.mutate_bytes(inset, mutation_chance=0))
self.assertNotEqual(inset, instruction_... | :
self.assertGreaterEqual(instruction, 0)
self.assertLess(instruction, 256)
def test_mutate_combined(self):
inset = instruction_set.generate()
self.assertEqual(len(inset), len(instruction_set.mutate_combined(inset)))
for instruction in instruction_set.mutate_combin... |
= StringIO(json.dumps(data_dict))
with pytest.raises(VerifyError) as err:
site.content_manager.verifyFile("data/test_include/content.json", data, ignore_same=False)
assert "File not allowed" in str(err)
# Reset
del data_dict["files"]["notallowed.exe"]
del data_dict[... | e.content_manager.verifyFile(inner_path, data, ignore_same=False)
| # Wrong address
data_dict["address"] = "Othersite"
del data_dict["signs"]
data_dict["signs"] = {
"1TeSTvb4w2PWE81S2rEELgmX2GCCExQGT": CryptBitcoin.sign(json.dumps(data_dict, sort_keys=True), self.privatekey)
}
data = StringIO(json.dumps(data_dict))
with... |
# pylint: dis | able=missing-module-docstring, missing-class-docstring
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('rdrhc_calendar', '... | 0171016_1915'),
]
operations = [
migrations.RenameField(
model_name='shift',
old_name='user',
new_name='sb_user',
),
migrations.RenameField(
model_name='shiftcode',
old_name='user',
new_name='sb_user',
),
... |
from sdoc.sdoc1.data_type.DataType import DataType
class StringDataType(DataType):
"""
Class for string data types.
"""
# ------------------------------------------------------------------------------------------------------------------
def __init__(self, value: str):
"""
Object c... | ------------------------------------------------------------
def get_type_id(self) -> int:
"""
Returns the ID of this data type.
"""
return DataType.STRING
# ------------------------------------------------------------------------------------------------------------------
de... | -----------------------------------------------------------------------------------------------------------------
def is_defined(self) -> bool:
"""
Returns True always.
"""
return True
# --------------------------------------------------------------------------------------------... |
import pytest
from mitmproxy.addons import intercept
from mitmproxy import exceptions
from mitmproxy.test import taddons
from mitmproxy.test import tflow
@pytest.mark.asyncio
async def test_simple():
r = intercept.Intercept()
with taddons.context(r) as tctx:
assert not r.filt
tctx.configure(r... | await tctx.cycle(r, f)
asser | t f.intercepted
tctx.configure(r, intercept_active=False)
f = tflow.ttcpflow()
await tctx.cycle(r, f)
assert not f.intercepted
|
"""
==============
Non-linear SVM
==============
Perform binary classification using non-linear SVC
with RBF kernel. The target to predict is a XOR of the
inputs.
The color map illustrates the decision function learned by the SVC.
"""
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from sklearn imp... | yy.ravel()])
Z = Z.reshape(xx.shape)
plt.imshow(Z, interpolation='nearest',
extent=(xx.min(), xx.max(), yy.min(), yy.max()), aspect='auto',
origin='lower', cmap=plt.cm.PuOr_r)
contours = plt.contour(xx, yy, Z, levels=[0], linewidths=2,
linestyles='dashed')
plt.scatter(X[:,... | ], X[:, 1], s=30, c=Y, cmap=plt.cm.Paired,
edgecolors='k')
plt.xticks(())
plt.yticks(())
plt.axis([-3, 3, -3, 3])
plt.show()
|
from geonode.maps.models import MapLayer
return MapLayer.objects.filter(name=self.typename)
@property
def class_name(self):
return self.__class__.__name__
class Layer_Styles(models.Model):
layer = models.ForeignKey(Layer)
style = models.ForeignKey(Style)
class AttributeManag... | arn('Could not get geoserver resource for %s' % instance)
return
gs_resource.title = instance.title
gs_resource.abstract = instance.abstract
gs_resource.name= instance.name
# Get metadata links
metadata_links = []
for link in ins | tance.link_set.metadata():
metadata_links.append((link.name, link.mime, link.url))
gs_resource.metadata_links = metadata_links
#gs_resource should only be called if ogc_server_settings.BACKEND_WRITE_ENABLED == True
if getattr(ogc_server_settings,"BACKEND_WRITE_ENABLED", True):
gs_catalog.sa... |
__author__ = 'tauren'
from flask import abort
from flask_restful import Resource
from flask.ext.restful import fields, marshal, reqparse
from flask_login import current_user
from models import User, db
user_fields = {
'username': fields.String,
'id': | fields.Integer,
'uri': fields.Url('user')
}
class UserApi(Resource): |
def __init__(self):
self.reqparse = reqparse.RequestParser()
self.reqparse.add_argument('username', type=str, required=True,
help='No username provided', location='json')
self.reqparse.add_argument('password', type=str, required=True,
... |
from flask.ext.wtf import Form
from wtforms import StringFie | ld, BooleanField, PasswordField, SelectField, DateTimeField, Tex | tAreaField
|
#!/usr/bin/python
'''
Wrapper for the SRTM module (srtm.py)
It will grab the altitude of a long,lat pair from the SRTM database
Created by Stephen Dade (stephen_dade@hotmail.com)
'''
import os
import sys
import time
import numpy
from MAVProxy.modules.mavproxy_map import srtm
class ElevationModel():
'''Elevation... | 0.001
lon = opts.lon+0.001
t0 = time.time()
alt = EleModel.GetElevation(lat, lon, timeout=10)
t1 = time.time()+.000001
print("Altitude at (%.6f, %.6f) is %u m. Pulled at %.1f FPS" % (lat, lon, alt, 1/(t1-t0)))
lat = opts.la | t-0.001
lon = opts.lon-0.001
t0 = time.time()
alt = EleModel.GetElevation(lat, lon, timeout=10)
t1 = time.time()+.000001
print("Altitude at (%.6f, %.6f) is %u m. Pulled at %.1f FPS" % (lat, lon, alt, 1/(t1-t0)))
|
# Copyright (C) 2016 Nippon Telegraph and Telephone Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | match_info = []
for i, match in enumerate(v['match']):
n = '{0}_match_{1}'.format(k, i)
if match['type'] == 'prefix':
f.write(''.join('ip prefix-list {0} deny {1}\n'.format(n, p) for p in match['value']))
... | prefix-list {0} permit any\n'.format(n))
elif match['type'] == 'as-path':
f.write(''.join('ip as-path access-list {0} deny _{1}_\n'.format(n, p) for p in match['value']))
f.write('ip as-path access-list {0} permit .*\n'.format(n))
... |
#!/usr/bin/env python3
# Copyright (c) 2009-2019 The Bitcoin Core developers
# Copyright (c) 2014-2019 The DigiByte Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Check RPC argument consistency."""
from collect... | file `fname`."""
cmds = []
in_rpcs = False
with open(fname, "r", encoding="utf8") as f:
for line in f:
line = line.rstrip()
if not in_rpcs:
if line == 'static const CRPCConvertParam vRPCConvertParams[] =':
in_rpcs = True
else:
... | in_rpcs = False
elif '{' in line and '"' in line:
m = re.search('{ *("[^"]*"), *([0-9]+) *, *("[^"]*") *},', line)
assert m, 'No match to table expression: %s' % line
name = parse_string(m.group(1))
idx = int(m.grou... |
offset'), and the __heap segment is
# placed after all others.
segment_ptr = {}
ptr = offset
if '__startup' in segment_size:
segment_ptr['__startup'] = ptr
ptr += segment_size['__startup']
for segment in sorted(segment_size):
if segment not i... | hes, the address stored in the
# instruction is replaced with the mapped address.
# For reloc patches, the two addresses are added
#
do_replace = type in (ImportType.CALL, ImportType.LI)
if patch_call:
orig_instr_bytes = seg_data[instr_offset:instr_offset+4]
... |
# address. Make sure it's indeed a CALL
#
opcode = extract_opcode(orig_instr_word)
if opcode != OP_CALL:
self._linker_error("Patching (%s) of '%s': expected CALL, got %d" % (
type, name, opcode))
# CALL destinations are in... |
#!/usr/bin/env python
"""Distutils installer for extras."""
from setuptools import setup
import os.path
import extras
testtools_cmd = extras.try_import('testtools.TestCommand')
def get_version():
"""Return the version of extras that we are building."""
version = '.'.join(
str(component) for componen... | _email='testtools-dev@lists.launchpad.net',
url='https://github.com/testing-cabal/extras',
description=('Useful extra bits for Python - things that shold be '
'in the standard library'),
long_ | description=get_long_description(),
version=get_version(),
classifiers=[
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
... |
it'] == 1000000)
assert('weightlimit' not in tmpl)
assert(tmpl['sigoplimit'] == 20000)
assert(tmpl['transactions'][0]['hash'] == txid)
assert(tmpl['transactions'][0]['sigops'] == 2)
tmpl = self.nodes[0].getblocktemplate({'rules':['segwit']})
assert(tmpl['sizelimit'] == 10... | ))
for i in range(len(segwit_tx_list)):
tx = FromHex(CTransaction(), self.nodes[2].gettransaction(segwit_tx_list[i | ])["hex"])
assert(self.nodes[2].getrawtransaction(segwit_tx_list[i]) != self.nodes[0].getrawtransaction(segwit_tx_list[i]))
assert(self.nodes[1].getrawtransaction(segwit_tx_list[i], 0) == self.nodes[2].getrawtransaction(segwit_tx_list[i]))
assert(self.nodes[0].getrawtransaction(segwi... |
"""Yelp API setup and random business selection function"""
import io
import json
import random
from yelp.client import Client
from yelp.oauth1_authenticator import Oauth1Authenticator
with io.open('config_yelp_secret.json') as cred:
creds = json.load(cred)
auth = Oauth1Authenticator(**creds)
yelp_clien... | cktailbars', 'lounges', 'sportsbars', 'wine_bar',
'poolhalls', 'pianobars', 'karaoke', 'jazzandblues',
'danceclubs']
eat_activity = ['wineries', 'farmersmarket', 'cafes', 'bakeries', ' | bubbletea', 'coffee',
'restaurants','beer_and_wine', 'icecream', 'gourmet', 'juicebars',
'asianfusion', 'japanese', 'seafood', 'breweries']
def yelp_random_pick(event, city):
"""Generate a top business pick for user."""
if event == 'food':
category_filter = random.choic... |
rsion 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"... | he SELECT supports multiple selections.
throws NotImplementedError If the SELECT does not support multiple selections
"""
if not self.is_multiple:
raise NotImplementedError("You may only deselect all options of a multi-select")
for opt in self.options:
self._un... | given "foo" this
would deselect an option like:
<option value="foo">Bar</option>
:Args:
- value - The value to match against
throws NoSuchElementException If there is no option with specisied value in SELECT
"""
if not self.is_multiple:
... |
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..minc import Voliso
def test_Voliso_inputs():
input_map = dict(args=dict(argstr='%s',
),
avgstep=dict(argstr='--avgstep',
),
clobber=dict(argstr='--clobber',
usedefault=True,
),
environ=... |
mandatory=True,
position=-2,
),
maxstep=dict(argstr='--maxstep %s',
),
minstep=dict(argstr='--minstep %s',
),
output_file=dict(argstr='%s',
genfile=True,
hash_files=False,
name_source=['input_file'],
name_template='%s_voliso.mnc',
position=-1,
),
terminal_out... | )
inputs = Voliso.input_spec()
for key, metadata in list(input_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(inputs.traits()[key], metakey) == value
def test_Voliso_outputs():
output_map = dict(output_file=dict(),
)
outputs = Voliso.output_spec()
... |
_source_fields()[0].geography and self.srid == 4326
def convert_value(self, value, expression, connection, context):
if value is None:
return None
geo_field = GeometryField(srid=self.srid) # Fake field to get SRID info
if geo_field.geodetic(connection):
dist_... | ")
return super(Perimeter, self).as_sql(compiler, connection)
class PointOnSurface(OracleToleranceMixin, GeoFunc):
arity = 1
class Reverse(GeoFunc):
arity = 1
class Scale(SQLiteDecimalToFloatMixin, GeoFunc):
def __init__(self, expression, x, y, | z=0.0, **extra):
expressions = [
expression,
self._handle_param(x, 'x', NUMERIC_TYPES),
self._handle_param(y, 'y', NUMERIC_TYPES),
]
if z != 0.0:
expressions.append(self._handle_param(z, 'z', NUMERIC_TYPES))
super(Scale, self).__ini... |
), # New line
(
"rco2r",
lambda data: [0.0] * data["mco2r"],
"path length in cm of radial CO2 density chord",
),
# read(neqdsk, 1040)(dco2r(jj, k), k = 1, mco2r)
(None, None, None), # New line
(
"dco2r",
lambda data: [0.0] * data["mco2r"],
"line aver... | ),
("taudia", 0.0, "diamagnetic energy confinement time in ms"),
(
"qmerci",
0.0,
"Mercier stability criterion on axial q(0), q(0) > QMERCI for | stability",
),
("tavem", 0.0, "average time in ms for magnetic and MSE data"),
# ishot > 91000
# The next section is dependent on the EFIT version
# New version of EFIT on 05/24/97 writes aeqdsk that includes
# data values for parameters nsilop,magpri,nfcoil and nesum.
(None, True, None), #... |
# 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 unittest
from appengine_module.test_results.handlers import redirector
class RedirectorTest(unittest.TestCase):
def test_url | _from_commit_positions(self):
def mock_load_url(url):
if url == 'https://cr-rev.appspot.com/_ah/api/crrev/v1/redirect/1':
git_sha = 'aaaaaaa'
else:
git_sha = 'bbbbbbb'
return '''{
"git_sha": "%s",
"repo": "chromium/src",
"redirect_url": "https://chromium.googlesource.com/chromiu... | v#redirectItem",
"etag": "\\\"vOastG91kaV9uxC3-P-4NolRM6s/U8-bHfeejPZOn0ELRGhed-nrIX4\\\""
}''' % (git_sha, git_sha)
old_load_url = redirector.load_url
try:
redirector.load_url = mock_load_url
expected = ('https://chromium.googlesource.com/chromium/src/+log/'
'aaaaaaa^..bbbbbbb?pretty=ful... |
#!/usr/bin/env python
# -*- coding: utf-8-*-
import getopt
import time
import re
import os,sys
reload(sys)
sys.setdefaultencoding('utf-8')
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from bs4 import BeautifulSoup
import requests
import webbrowser
import subprocess
class Ou... | s://gsnedders.html5.org/outliner/process.py?url=' + source)
return r.text
#soup = BeautifulSoup(r.text)
#for li in soup.find_all('li'):
# print li.text.strip()
'''
r = requests.get(source)
#script = "var data = new Array();"
... |
script = ''
script += "var HTML5Outline = require('h5o');"
script += "var outline = HTML5Outline('<html></html>');"
output = subprocess.check_output('node -p "' + script + '"' , shell=True)
return output
'''
return ''
def main(ar... |
import numpy as np
import matplotlib.pyplot as plt
def bernstein(t, n, i):
cn = 1.0
ci = 1.0
cni = 1.0
for k in range(2, n, 1):
cn = cn * k
for k in range(1, i, 1):
if i == 1:
break
ci = ci * k
for k in range(1, n - i + 1, 1):
if n == i:
... | )
sum1 += cp[i - 1, | 0] * bt
sum2 += cp[i - 1, 1] * bt
r[k, :] = [sum1, sum2]
return np.array(r)
cp = np.array([[0, -2], [1, -3], [2, -2], [3, 2], [4, 2], [5, 0]])
t = np.arange(0, 1 + 0.01, 0.01)
p = bezierplot(t, cp)
plt.figure()
plt.plot(p[:, 0], p[:, 1])
plt.plot(cp[:, 0], cp[:, 1], ls=':', marker='o')
plt.sho... |
from pygraz_website import filters
class TestFilters(object):
def test_url_detection(self):
"""
Test that urls are found correctly.
"""
no_urls_string = '''This is a test without any urls in it.'''
urls_string = '''This string has one link in it: http://pygraz.org . But it a... | allo <a href="http://twitter.com/pygraz">@pygraz</a>.'
assert filters.urlize(string_with_handles, True).matches == {'handles': set(['pygraz'])}
| def test_hashtags(self):
string_with_tags = 'This is a #test for #hashtags'
assert filters.urlize(string_with_tags) == 'This is a <a href="http://twitter.com/search?q=%23test">#test</a> for <a href="http://twitter.com/search?q=%23hashtags">#hashtags</a>'
assert filters.urlize(string_with_tags, T... |
ef __init__(self):
super().__init__()
self.add_from_file("main.glade")
self.connect_signals(self)
self.spin_buttons = (
self.get_object("spinbutton_h"),
self.get_object("spinbutton_min"),
self.get_object("spinbutton_s"),
)
self.css_pr... | verb = "hibernate"
if platform.system() == "Windows":
if self.get_object("standby").get_active():
verb = "standby"
elif self.get_object("shutdown").get_active():
| verb = "exitwin poweroff"
subprocess.check_output("nircmd.exe " + verb)
else:
if self.get_object("standby").get_active():
verb = "suspend"
elif self.get_o... |
#!/usr/bin/env python
"""
Send message to '#gis.lab' IRC chat room.
Requires to run script 'utils/join-gislab-network.py' first to get connection
with server.
USAGE: send-message.py <message>
"""
import os, sys
import re
import socket
try:
message = sys.argv[1]
except IndexError:
print __doc__
sys.exit(0... | islab :%s\r\n" % me | ssage)
s.send("QUIT: End of message.\r\n")
s.recv(4096)
s.close()
print "Done."
# vim: ts=8 sts=4 sw=4 et:
|
#!/usr/bin/python3
import logging
from operator import itemgetter
from timeit import default_timer as timer
import rdflib
from .abstract_instruction_set import AbstractInstructionSet
from readers import rdf
from writers import rule_set, pickler
from samplers import by_definition as sampler
from algorithms.semantic_rul... | www.cidoc-crm.org/cidoc-crm/P53i_is_former_or_current_location_of"),
(rdflib.URIRef("htt | p://www.cidoc-crm.org/cidoc-crm/P89_falls_within"),
rdflib.URIRef("http://pakbon-ld.spider.d2s.labs.vu.nl/ont/SIKB0102S_contexttype")),
(rdflib.URIRef("http://purl.org/crmeh#EHP3i"),
rdflib.URIRef("http://pakbon-ld.spider.d2s.labs.vu.nl/ont/SIKB0102S_kleur")),
... |
meout == '':
timeout = 10
timeout = int(timeout)
print '\n\nStarting the load balancing application...\n\n'
while True:
print '\n\nQuerying for network core interface monitoring triggered events...\n\n'
print '\n... | ow_stat = odl.odl_mpls_push_flow_inst(url_odl, name, password, odl_header, mpls_push_flow, mpls_push_flow_counter, switch_id, dst_add, src_add, in_port, dl_dst, dl_src, protocol, tcp_src_port, tcp_dst_port, udp_src_port, udp_dst_port, vlan_id, vlan_priority, action_mpls_label, action_out_port, table_id, priority)
... | if flow_stat:
flow_name = flow_stat['Flow ID']
mpls_push_flow_stats[flow_name] = flow_stat
basic_connectivity_flow_stats[flow_name] = {'Switch ID': switch_id, 'IP Destination' : dst_add, 'MPLS Label' : l... |
import itert | ools
import numpy
import math
def ncr(n, r):
f = math.factorial
return f(n) // f(r) // f(n-r)
def subset_pairs(s):
for a_size in range(1, len(s)):
for a in itertools.combinations(s, a_size):
remaining = s.difference(a)
for b_size in range(1, len(remaining) + 1):
... | 22, 25]
|
from PyQt5 import QtCore
from src.business.configuration.constants import project as p
from src.ui.commons.verification import cb
class ConfigProject:
def __init__(self):
self._settings = QtCore.QSettings(p.CONFIG_FILE, QtCore.QSettings.IniFormat)
def get_value(self, menu, value):
return sel... | unar)
self._settings.setValue(p.MAX_LUNAR_PHASE, lunarph)
self._settings.setValue(p.MAX_LUNAR_ELEVATION, lunarpos)
self._settings.endGroup()
def save_settings(self):
self._settings.sync()
def get_site_settings(self):
| return self.get_value(p.SITE_TITLE, p.NAME),\
self.get_value(p.SITE_TITLE, p.SITE_ID),\
self.get_value(p.SITE_TITLE, p.IMAGER_ID)
def get_geographic_settings(self):
m = p.GEOGRAPHIC_TITLE
return self.get_value(m, p.LATITUDE),\
self.get_value(m, p.LONG... |
from Scouting2017.model.models2017 import ScoreResult
from django.db.models.aggregates import Avg
from django.db.models.expressions import Case, When
import json
import math
import collections
def get_statistics(regional_code, teams_at_competition, team=0):
'''
The get_statistics function() returns two lists ... | pe_v2 / num_srs)
team_avgs = collections.defaultdict(int)
# This part of the function (above) obtains overall standard deviations for all score results
teams = team if bool(team) else teams_at_c | ompetition
for team in teams:
teams_srs = team.scoreresult_set.filter(competition__code=regional_code)
team_avgs = teams_srs.aggregate(Avg('tele_gears'),
Avg('tele_fuel_high_score'),
Avg('auto_fuel_high_score'),
... |
# Copyright 2010 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
import re
from django import forms
from django.utils.translation import ugettext as _
from identityprovider.widgets import CommaSeparatedWidget
class CommaSeparatedField(forms.M... | '.join(super(CommaSeparatedField, self).clean(value))
class OATHPasswordField(forms.CharField):
"""A string of between 6 or 8 digits."""
widget = forms.widgets.TextInput(attrs={
'autocomplete': 'off',
'autofocus': 'autofocus'
})
SIX = re.compile('[0-9]{6}$')
EIGHT = re.compile('[0-... | Validate otp and detect type"""
# remove any whitespace from the string
if value:
value = value.strip().replace(' ', '')
value = super(OATHPasswordField, self).clean(value)
if self.SIX.match(value):
return value
elif self.EIGHT.match(value):
re... |
from GangaCore.testlib.GangaUnitTest import GangaUnitTest
from GangaGUI.api import internal
# ******************** Test Class ******************** #
# Templates API Tests
class TestGangaGUIInternalTemplatesAPI(GangaUnitTest):
# Setup
def setUp(self, extra_opts=[]):
super(TestGangaGUIInternalTemplat... | self):
res = self.app.delete(f"/internal/templates/1")
self.assertTrue(res.status_code == 400)
# Templates API - DELETE Method, ID is Negative
def test_DELETE_method_id_negative(self):
res = self.app.delete(f"/internal/templates/-1")
self.assertTrue(res.status_code == 404)
... | elf.app.delete(f"/internal/templates/test")
self.assertTrue(res.status_code == 404)
# Templates API - DELETE Method
def test_DELETE_method_templates_list(self):
from GangaCore.GPI import templates, JobTemplate, GenericSplitter, Local
# Clean template repository check
self.asser... |
# CamJam EduKit 3 - Robotics
# Worksheet 7 - Controlling the motors with PWM
import RPi.GPIO as GPIO # Import the GPIO Library
import time # Import the Time library
# Set the GPIO modes
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# Se | t variables for the GPIO motor pins
pinMotorAForwards = 10
pinMotorABackwards = 9
pinMotorBForwards = 8
pinMotorBBackwards = 7
# How ma | ny times to turn the pin on and off each second
Frequency = 20
# How long the pin stays on each cycle, as a percent (here, it's 30%)
DutyCycle = 30
# Setting the duty cycle to 0 means the motors will not turn
Stop = 0
# Set the GPIO Pin mode to be Output
GPIO.setup(pinMotorAForwards, GPIO.OUT)
GPIO.setup(pinMotorABack... |
#!/usr/bin/python
# Script to Check the difference in 2 files
# 1 fevereiro de 2015
# https://github.com/thezakman
file1 = raw_input('[file1:] ')
modified = open(file1,"r").readlines()[0]
file2 = raw_input('[file2:] ')
pi = open(file2, "r").readlines()[0] # [:len(modified)]
result... | int "[Diff | er:]
print '\n-------------------------------------'
print "[file1] -> [file2]", resultado
print '-------------------------------------'
print "[file2] -> [file1]", resultado2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.