prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
#!/usr/bin/env python
# -*- coding: ISO-8859-15 -*-
#
# Copyright (C) 2005-2007 David Guerizec <david@guerizec.net>
#
# Last modified: 2006 Sep 02, 01:40:01 by david
#
# 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... | LAR 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
__plugin_name__ = "Console Extra Comma... | ugin offers several new commands for the console session:
- open user@site
Open a shell session on user@site.
- run user@site cmd args...
Run a command remotely on user@site.
"""
def __init_plugin__():
import commands
|
import sys
import pytest
py3 = sys.v | ersion_info[0] >= 3
class DummyCollector(pytest.collect.File):
def collect(self):
return []
def pytest_pycollect_makemodule(path, parent):
bn = path.basename
if "py3" in bn and not py3 or ("py2" in bn and py3):
return DummyCollector(p | ath, parent=parent)
|
"""
Tests that skipped rows are properly handled during
parsing for all of the parsers defined in parsers.py
"""
from datetime import datetime
from io import StringIO
import numpy as np
import pytest
from pandas.errors import EmptyDataError
from pandas import (
DataFrame,
Index,
)
import pandas._testing as ... | iprows=[6, 8])
condensed_result = parser.read_csv(StringIO(condensed_data))
tm.assert_frame_equal(result, condensed_result)
def test_skip_rows_blank(all_parsers):
# see gh-9832
parser = all_parsers
text = """#foo,a,b,c
#foo,a,b,c
#foo,a,b,c
#foo,a,b,c
1/1/2000,1.,2.,3.
1/2/2000,4,5,6
1/3/2000,7,... | ,9
"""
data = parser.read_csv(
StringIO(text), skiprows=6, header=None, index_col=0, parse_dates=True
)
index = Index(
[datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)], name=0
)
expected = DataFrame(
np.arange(1.0, 10.0).reshape((3, 3)), columns=[1, 2, 3], ... |
#
# Copyright (c) 2012 Citrix Systems, Inc.
#
# 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 dist... | epilog=epilog)
parser.add_argument("user",
metavar="USER",
choices=["sys"] + configuration.USERS,
help="connect to database as: " | +
", ".join(["sys"] + configuration.USERS))
parser.add_argument("script",
metavar="SCRIPT",
help="sqlplus script to run")
parser.set_defaults(func=_run)
parser.set_defaults(need_config=True)
parser.set_defaults(need_metadata... |
#!/usr/bin/env python
#
# Copyright 2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
from gnuradio import gr
import pmt
def make_lengthtags(lengths, offsets, tagname='length', vlen=1):
tags = []
assert(len(offsets) == len(lengths))
f... | g(packet) for packet in packets]
def count_bursts(data, tags, tsb_tag_key, vlen=1):
lengthtags = [t for t in tags
if pmt.symbol_to_string(t.key) == tsb_tag_key]
lengths = {}
for tag in lengthtags:
if tag.offset in lengths:
| raise ValueError(
"More than one tags with key {0} with the same offset={1}."
.format(tsb_tag_key, tag.offset))
lengths[tag.offset] = pmt.to_long(tag.value) * vlen
in_burst = False
in_packet = False
packet_length = None
packet_pos = None
burst_count = 0
f... |
'''
Project: Farnsworth
Author: Karandeep Singh Nagra
'''
from django.contrib.auth.models import User, Group, Permission
from django.core.urlresolvers import reverse
from django.db import models
from base.models import UserProfile
class Thread(models.Model):
'''
The Thread model. Used to group messages.
... | he user who started this thread.",
)
subject = models.CharField(
blank=False,
null=False,
max_length=254,
help_text="Subject of this thread.",
)
start_d | ate = models.DateTimeField(
auto_now_add=True,
help_text="The date this thread was started.",
)
change_date = models.DateTimeField(
auto_now_add=True,
help_text="The last time this thread was modified.",
)
number_of_messages = models.PositiveSmallIntegerField(
... |
set{w}{\mathrm{argmax}}\ln\prod_{i=0}^n\mathbb{P}\{y_i|x_i\}=$$ (исходя из монотонности логарифма, если функция в данной точке имеет максимум, то и её логарифм)$$=\underset{w}{\mathrm{argmax}}\sum_{i=0}^n\ln\mathbb{P}\{y_i|x_i\}=\underset{w}{\mathrm{argmax}}\sum_{i=0}^n\ln\sigma(y_i(wx_i+b))=\underset{w}{\mathrm{argmax... | исходное равенство), получаем следующие зависимости | $Q$ от $M$:
#
# 1) $Q = [y_{pred} \neq y_{true}]=[y\cdot(wx)<0]=[M < 0]$
#
# 2) $Q = ((wx) - y)^{2}=\frac{1}{y^2}((wx\cdot y) - y^2)^2=\frac{1}{y^2}(M - y^2)^2$. Так как $y=\pm 1$, то $Q=(M - 1)^2$.
#
# 3) $Q = max(0, 1 - y\cdot(wx))=max(0,1-M)$
#
# 4) $Q = \ln(1 + e^{-y\cdot(wx)})=\ln(... |
class TriangleMaking:
def maxPerimeter(self, a, b, c):
fir | st = a
second = b
third = c
sides = [first, second, third]
for idx, side in enumerate(sides):
one = (idx + 1) % 3
two = (idx + 2) % 3
total = sides[one] + s | ides[two]
while sides[idx] >= total:
sides[idx] -= 1
return sum(sides)
|
# -*- coding: utf-8 -*-
"""Factories to help in tests."""
from factory import PostGenerationMethodCall, Sequence
from factory.alchemy import SQLAlchemyModelFactory
from chamberlain.database import db
from chamberlain.user.models import User
class BaseFactory(SQLAlchemyModelFactory) | :
"""Base factory."""
class Meta:
"""Factory configuration."""
abstract = True
sqlalchemy_session = db.session
class UserFactory(BaseFactory):
"""User factory."""
username = Sequence(lambda n: 'user{0}'.format(n))
email = Sequence(lambda n: 'user{ | 0}@example.com'.format(n))
password = PostGenerationMethodCall('set_password', 'example')
active = True
class Meta:
"""Factory configuration."""
model = User
|
#!/usr/bin/env python
impo | rt os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "juisapp.settings")
from django.core.management im | port execute_from_command_line
execute_from_command_line(sys.argv)
|
# Copyright 2019 Objectif Libre
#
# 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 agr... | itations
# under the License.
#
import flask
import voluptuous
from werkzeug import exceptions as http_exceptions
from cloudkitty.api.v2 import base
from cloudkitty.api.v2 import utils as api_utils
from cloudkitty.common import policy
from cloudkitty import messaging
from cloudkitty import storage_state
from cloudk... | e):
@classmethod
def reload(cls):
super(ScopeState, cls).reload()
cls._client = messaging.get_client()
cls._storage_state = storage_state.StateManager()
@api_utils.paginated
@api_utils.add_input_schema('query', {
voluptuous.Optional('scope_id', default=[]):
... |
import frrtest
import pytest |
if 'S["SCRIPTING_TRUE"]=""\n' not in open("../config.status").readlines():
class TestFrrlua:
@pytest.mark.skipif(True, reason="Test unsupported")
def test_exit_cleanly(self):
pass
else:
class TestFrrlua(frrtest.TestMultiOut):
program = "./test_frrlua"
TestFrrlua.exit_... | |
# pylint: disable=C0111,R0902,R0904,R0912,R0913,R0915,E1101
# Smartsheet Python SDK.
#
# Copyright 2018 Smartsheet.com, Inc.
#
# 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.... | = None
if base_obj is not None:
self._base = base_obj
self._confirmed = Boolean()
self._emai | l = String()
self._id_ = Number()
if props:
deserialize(self, props)
# requests package Response object
self.request_response = None
self.__initialized = True
def __getattr__(self, key):
if key == 'id':
return self.id_
else:
... |
# Example for script that connects to PV,
# writes a value, then disconnects from the PV.
#
# This is usually a bad ide | a.
# It's better to have widgets connect to PVs,
# 1) More efficient. Widget connects once on start, then remains connected.
# Widget subscribes to PV updates instead of polling its value.
# 2) Widget will reflect the connection and alarm state of the PV
# 3) Widget will properly disconnect
#
# pvs[0]: PV w | ith name of PV to which to connect
# pvs[1]: PV with value that will be written to the PV
from org.csstudio.display.builder.runtime.script import PVUtil, ScriptUtil
pv_name = PVUtil.getString(pvs[0])
value = PVUtil.getDouble(pvs[1])
print("Should write %g to %s" % (value, pv_name))
try:
PVUtil.writePV(pv_name, v... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from os.path import exists as path_exists
from pyscaffold.api import create_project
from pyscaffold.cli import run
from pyscaffold.extensions import travis
def test_create_project_with_travis(tmpfolder):
# Given options with the travis extension,
opts ... |
create_project(opts)
# then travis files should exist
assert path_exists("proj/.travis.yml")
assert path_exists("proj/tests/travis_install.sh")
def test_create_project_without_travis(tmpfolder):
# Given options without the travis extension,
opts = dict(project="proj")
# when the projec | t is created,
create_project(opts)
# then travis files should not exist
assert not path_exists("proj/.travis.yml")
assert not path_exists("proj/tests/travis_install.sh")
def test_cli_with_travis(tmpfolder):
# Given the command line with the travis option,
sys.argv = ["pyscaffold", "--travis",... |
#!/usr/bin/env python
from __future__ import unicode_literals
import io
import optparse
import os
import sys
# Import youtube_dl
ROOT_DIR = os.path.join(os.path.dirname(__file__), '..')
sys.path.insert(0, ROOT_DIR)
import youtube_dl
def main():
parser = optparse.OptionParser(usage='%prog OUTFILE.md')
optio... | yield ie_md
ies = sorted(youtube_dl.gen_extractors(), key=lambda i: i.IE_NAME.lower())
out = '# Supported sites\n' + ''.join(
' - ' + md + '\n'
for md in gen_ies_md(ies))
with io.open(outfile, 'w', encoding='utf-8') as outf:
outf.write(out)
if __name__ == | '__main__':
main()
|
lower')
pu.cut_plot_and_write_alt_layer(st.lower_internal_surface_3, 'triax', label,
bounding_polygon, airfoil='lower')
# upper aft panel 2 -------------------------------------------------------
label = 'upper aft panel 2'
# create the bounding polygon
ap2u = st.lower_aft_panel_2.layer['upper']
sw3br =... | w3bl.left[0][0], -4.5),
(sw3br.ri | ght[0][0], -4.5),
(sw3br.right[0][0], 0.0)
]
bounding_polygon = Polygon(points_asw3)
pu.plot_polygon(bounding_polygon, 'None', '#000000')
# cut the new layer polygons
pu.cut_plot_and_write_alt_layer(st.lower_external_surface, 'triax', label,
bounding_polygon, airfoil='lower')
pu.cut_plot_and_writ... |
#!/usr/bin/env python
import sys
import math
def main():
if len(sys.argv) != 3:
print('USAGE: ' + sys.argv[0] + ' <filename> ' + ' <boundary id of interest>')
return
targetString = 'Moment coefficient for body[' + sys.argv[2]
targetTimestep = ': \n'
filename = sys.argv[1]
t... | ring in line:
'find the last colon and get the string after that which is the numeric value'
| 'of the lift coefficient'
pos = line.rfind(':')
size = len(line)
print(line[pos+1:size]),
continue
if __name__ == '__main__':
main()
|
from django.contrib.localflavor.it.forms import (ITZipCodeField, ITRegionSelect,
ITSocialSecurityNumberField, ITVatNumberField)
from django.test import SimpleTestCase
class ITLocalFlavorTests(SimpleTestCase):
def test_ITRegionSelect(self):
f = ITRegionSelect()
out = u'''<select name="regions"... | ption value="FVG">Friuli-Venezia Giulia</option>
<option value="LAZ">Lazio</option>
<option value="LIG">Liguria</option>
<option value="LOM">Lombardia</option>
<option value="MAR | ">Marche</option>
<option value="MOL">Molise</option>
<option value="PMN" selected="selected">Piemonte</option>
<option value="PUG">Puglia</option>
<option value="SAR">Sardegna</option>
<option value="SIC">Sicilia</option>
<option value="TOS">Toscana</option>
<option value="TAA">Trentino-Alto Adige</option>
<option val... |
is a bit slower than the hardware interface, but it is far more
# clear what is going on, plus the RPi has only one SPI device.
# Connections: RPi GPIO to MCP320x
# CS_bar_pin = CS/SHDN
# CLK_pin = CLK
# MOSI_pin = D_in
# MISO_pin = D_out
#
# Hardware SPI:... | ta rate can be up to 1MHz.
# Connections: RPi pins to MCP320x
# CE0 or CE1 = CS/SHDN (chip select) set CS_bar = 0 or 1
# SCK = CLK set CLK_pin = 1000000 (transfer speed)
# MOSI = D_in set MOSI_pin = | 0
# MISO = D_out set MISO_pin = 0
# The SPI protocol simulated here is MODE=0, CPHA=0, which has a positive polarity clock,
# (the clock is 0 at rest, active at 1) and a positive phase (0 to 1 transition) for reading
# or writing the data. Thus corresponds to the specifications of the MCP320x ch... |
# Th | is fi | le is only necessary for the tests to work |
# -*- coding: utf-8 -*-
# Taboot - Client utility for performing deployments with Func.
# Copyright © 2009, Red Hat, Inc.
#
# 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 th... | e for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from func.minion.modules import func_module
class | Test(func_module.FuncModule):
pass
|
# -*- coding: utf-8 -*-
from pytdx.hq import TdxHq_API
from fooltrader.api import technical
from fooltrader.contract.data_contract import KDATA_COLUMN_SINA
from fooltrader.utils.utils import get_exchange
def get_tdx_kdata(security_item, start, end):
api = TdxHq_API()
with api.con | nect():
# open close high low vol amount date code
# KDATA_COLUMN = ['ti | mestamp', 'code', 'low', 'open', 'close', 'high', 'volume', 'turnover', 'securityId']
df = api.get_k_data(security_item['code'], start, end)
df = df[['date', 'code', 'low', 'open', 'close', 'high', 'vol', 'amount']]
df['securityId'] = df['code'].apply(lambda x: 'stock_{}_{}'.format(get_exchange... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-24 20:36
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependenc | ies = [
]
operations = [
migrations.CreateModel(
name='LineItem',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
| ('description', models.CharField(max_length=255)),
('amount', models.FloatField(default=0)),
],
),
migrations.CreateModel(
name='Quote',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose... |
def extractMkkbunkotoikemenWordpressCom(item):
'''
Parser for 'mkkbun | kotoikemen.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagnam... | in item['tags']:
return _buildReleaseMessage(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False
|
import os
from concourse_common import jsonutil
def post_successful_tests(filepath, payload, sc, total_string):
sc.api_call("chat.postMessage", as_user=True,
channel=jsonutil.get_params_value(payload, "channel"),
attachments=[{"fallback": "Test Results",
... | ,
"color": "danger",
"title": "Failure:",
"fields": [{"value": os.environ["BUILD_JOB_NAME"] + " in version " + open(
os.path.join(filepath, jsonutil.get_params_value(payload, "version"))).read() +... | "short": False}]}]) |
#
# This file is part of HEPData.
# Copyright (C) 2016 CERN.
#
# HEPData 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.
#
# HEPData is... | a; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
#
from flask_webpackext import WebpackBundle
search_js = WebpackBundle(
__name__,
'assets',
entry={
| 'hepdata-search-js': './js/hepdata_search.js',
'hepdata-search-facets-js': './js/hepdata_search_facets.js',
},
dependencies={
"d3": "~3.5.12",
"d3-tip": "~0.6.7",
"typeahead.js": "0.11.1"
}
)
|
# The following parse_* methods are from bitcoin-abe
import base58
def parse_TxIn(vds):
d = {}
d['prevout_hash'] = vds.read_bytes(32)
d['prevout_n'] = vds.read_uint32()
d['scriptSig'] = vds.read_bytes(vds.read_compact_size())
d['sequence'] = vds.read_uint32()
return d
def parse_TxOut(vds):
d = {}
d['... | ut = vds.read_compact_size()
d['txOut'] = []
for i in xrange(n_vout):
d['txOut'].append(parse_TxOut(vds))
d['lockTime'] = vds.read_uint32()
d['tx'] = v | ds.input[start:vds.read_cursor]
return d
def parse_BlockHeader(vds):
d = {}
blk_magic = vds.read_bytes(4)
#if blk_magic != '\xf9\xbe\xb4\xd9':
# if blk_magic != '\xbf\xfa\xda\xb5':
# raise Exception('Bad magic' + str(blk_magic))
# return d
blk_length = vds.read_int32()
header_start = vds.read_curso... |
(planar_graph_node_builder):
b = planar_graph_node_builder
assert b.coord_nodes == [(0,0), (1,1), (5.1,1.2), (2,2), (1,0)]
assert b.edges == [(0,1), (1,2), (0,3), (4,1), (1,3)]
def test_PlanarGraphNodeBuilder_builds(planar_graph_node_builder):
g = planar_graph_node_builder.build()
assert g.ver... | assert dists == {0:0, 1:1, 2:pytest.approx(1+np.sqrt(2)),
3:pytest.approx(2+np.sqrt(2)), 4:pytest.approx(2+2*np.sqrt(2)),
5:pytest.approx(1+np.sqrt(2)), 6:pytest.approx(2+np.sqrt(2)),
7:pytest.appr | ox(3+2*np.sqrt(2))}
assert prevs == {0:0, 1:0, 2:1, 5:1, 3:2, 6:5, 4:3, 7:4}
dists, prevs = network.shortest_paths(graph2, 2)
assert dists == {0:pytest.approx(1+np.sqrt(2)),
1:pytest.approx(np.sqrt(2)), 2:0, 3:1, 5:2,
6:3, 4:pytest.approx(1+np.sqrt(2)), 7:pytest.approx(2+np.sqrt(2))}
ass... |
#!/usr/bin/env python
# - | *- coding: utf-8 -*-
version = (0, "5d")
__tit | le__ = "Elevator"
__author__ = "Oleiade"
__license__ = "MIT"
__version__ = '.'.join(map(str, version))
|
alib.results.SourcePosition import SourcePosition
from coalib.results.SourceRange import SourceRange
def foo():
pass
def foo_bar(n):
def bar():
return n+1
return bar
class TestAdditionalFunctions(unittest.TestCase):
def second(func):
def wrapper():
return func()
... | temp_file.close()
self.assertIsNone(get_hashbang(temp_file.name))
def test_no_bang(self):
with NamedTemporaryFile(mode='w+t', delete=False) as temp_file:
temp_file.write('#bin/bash')
| temp_file.close()
self.assertIsNone(get_hashbang(temp_file.name))
def test_no_hash(self):
with NamedTemporaryFile(mode='w+t', delete=False) as temp_file:
temp_file.write('!bin/bash')
temp_file.close()
self.assertIsNone(get_hashbang(temp_file.name))
... |
"""
timer.py: Request timer statistical tool
Code adapted from Bottle documentation
Copyright 2014-2015, Outernet Inc.
Some rights reserved.
This software is free software licensed under the terms of GPLv3. See COPYING
file that comes with the source code, or http://www.gnu.org/licenses/gpl.txt.
"""
from __future__... |
def _timer(callback):
@wraps(callback)
def wrapper(*args, ** | kwargs):
start = time.time()
res = callback(*args, **kwargs)
delta = time.time() - start
response.headers[t_header] = str(
round(delta * 1000, 4)) + 'ms'
response.headers[m_header] = str(get_mem())
return res
return wrapper
... |
from django.shortcuts import render, resolve_url
from django.contrib.auth.decorators import login_required
from gui.decorators import profile_required
from gui.utils import collect_view_data
from gui.signals import view_faq
from api.decorators import setting_required
@login_required
@profile_required
def api(request... | red
@setting_required('FAQ_ENABLED', check_settings=False) # FAQ must be enabled only in DC
def faq(request):
"""
Frequently Asked Questions view.
"""
dc_settings = request.dc.settings
context = collect_view_data(request, 'faq')
context['support_email'] = dc_settings.SUPPORT_EMAIL
if d | c_settings.SUPPORT_ENABLED:
context['support_section_url'] = resolve_url('add_ticket')
else:
context['support_section_url'] = '#'
view_faq.send(sender='faq', request=request, context=context)
return render(request, 'gui/docs/faq.html', context)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2015-12-30 00:07
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import wagtail.wagtailcore.fields
class Migration(migrations.Migration):
dependencies = [
('wagtailimages', '0010_change... | ecommendation',
name='displayTitle',
field=wagtail.wagtailcore.fields.RichTextField(blank=True),
),
migrations.AddField(
| model_name='recommendation',
name='image',
field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='wagtailimages.Image'),
),
migrations.AddField(
model_name='recommendation',
... |
"""
To use this, create a settings.py file and make these variables:
TOKEN=<oath token for github>
ORG=<your org in github>
DEST=<Path to download to>
"""
from github import Github
from subprocess import call
import os
from settings import TOKEN, ORG, DEST
def download():
"""Quick and Dirty Download all repos funct... | os.chdir(DEST)
print "Downloading to destination: ", os.getcwd()
g = Github( | TOKEN)
repos = []
for repo in g.get_organization(ORG).get_repos():
print "Fetching Repo Name: %s" % repo.name
repos.append("git@github.com:%s/%s.git" % (ORG, repo.name))
total = len(repos)
print "Found %s repos" % total
count = 0
for repo in repos:
count +=1
print "Cloning Repo [%s]/[%s]: %s" % (cou... |
def count_factor(n, factor=0):
for i in range(1, int(n**0.5)+1):
if n % i == 0:
factor += | 2
return factor
def nth_triangular_number(n):
return int(n+(n*(n-1))/2)
def find_triangular_number_over(k, n=0):
while count_factor(nth_triangular_number(n)) <= k:
n += 1
return nth_triangular_number(n)
def main():
print(find_tr | iangular_number_over(500))
if __name__ == "__main__":
main()
|
# Globals | for the directions
# Change the values as you see fit
EAST = None
NORTH = None
WEST = None
SOUTH = None
class Robot:
def __init__(self | , direction=NORTH, x_pos=0, y_pos=0):
pass
|
import _plotly_uti | ls.basevalidators
class ColorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self, plotly_name="color", parent_name="scatter.unselected.textfont", **kwargs
):
super(ColorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | e"),
**kwargs
)
|
"""
Document class definition
"""
class Document(object):
"""Represents a document"""
def __init__(self, id, name, type, path):
if '\n' in name:
raise ValueError('The document name cannot contain newline character!')
if '\n' in type:
raise ValueError('The document type... | me
@property
def type(self):
return self._type
@property
def path(self):
return self._ | path
|
#!/usr/bin/env python
"""
For a given vdi and import file this script will import a VDI on to a XS host.
This script needs to be run whenever you want to restore a VDI to a previous
version.
example: python cbt_import_whole_vdi.py -ip <host address> -u <host username>
-p <host password> -v <vdi uuid> -f <impo... | dd_argument('--as-new-vdi', dest='new_vdi', action='store_const',
const=True, default=False,
help='Create a new VDI for the import')
args = parser.parse_args()
session = XenAPI.Session("https://" + args.ho | st, ignore_ssl=True)
session.login_with_password(args.username, args.password, "0.1",
"CBT example")
try:
vdi_uuid = args.vdi_uuid
if args.new_vdi:
vdi_ref = session.xenapi.VDI.get_by_uuid(args.vdi_uuid)
size = session.xenapi.VDI.g... |
# Copyright 2017 Mycroft AI Inc.
#
# 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 writin... | it__(self, name):
LOG._custom_name = name
@classmethod
def _log(cls, func, *args, **kwargs):
if cls._custom_name is not None:
name = cls._custom_name
cls._custom_name = None
else:
# Stack:
# [0] - _log()
# [1] - debug(), info()... | ecord:
# [0] - frame object
# [1] - filename
# [2] - line number
# [3] - function
# ...
record = stack[2]
mod = inspect.getmodule(record[0])
module_name = mod.__name__ if mod else ''
... |
# 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 may ... | Credential
class WebSiteManagementClientConfiguration(Configuration):
"""Configuration for WebSiteManagementClient.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~... | iption ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000).
:type subscription_id: str
"""
def __init__(
self,
credential: "AsyncTokenCredential",
subscription_id: str,
**kwargs: Any
) -> None:
super(WebSiteManagementClientConfiguratio... |
from docar import Document, Collection
from docar import fields
from docar.backends.http import HttpBackendManager
from libthirty.state import uri, app_ | uri, service_uri, resource_collection_uri
from libthirty.validators import naming, max_25_chars, naming_with_dashes
import os
HttpBackendManager.SSL_CERT = os.p | ath.join(
os.path.dirname(__file__), "ssl", "StartSSL_CA.pem")
class User(Document):
username = fields.StringField(validators=[naming, max_25_chars])
email = fields.StringField()
is_active = fields.BooleanField()
class Account(Document):
name = fields.StringField(validators=[naming, max_25_c... |
import ast
import label
import repository
import os
| class IncludeDef:
"""
Represents build file include definition like
include_defs("//include/path").
"""
def __init__(self, ast_call: ast.Call) -> None:
self.ast_call = ast_call
def get_location(self) -> str:
"""
Returns an include definition location.
For i... | ""
return self.ast_call.args[0].s
def get_label(self) -> label.Label:
"""Returns a label identifying a build extension file."""
return label.from_string(self.get_location())
def get_include_path(self, repo: repository.Repository):
"""Returns a path to a file from which symbols ... |
import relayManager
import dronekit
class ShotManager():
def __init__(self):
# see the shotlist in app/shots/shots.p
| print "init"
def Start(self, vehicle):
self.vehicle = vehicle
# Initialize relayManager
self.relayManager = relayManager.RelayManager(self)
target = 'udp:127.0.0.1:14551' #'tcp:127.0.0.1:5760'
print 'Connecting to ' + | target + '...'
vehicle = dronekit.connect(target, wait_ready=True)
sm = ShotManager()
sm.Start(vehicle)
|
# coding=utf-8
import datetime
import logging
import time
import uuid
from dateutil.relativedelta import relativedelta
from redis.connection import Connection
import listenbrainz.db.user as db_user
from listenbrainz.db.testing import DatabaseTestCase
from listenbrainz import config
from listenbrainz.listen import Li... | )
self.assertEqual(len(recent), RedisListenStore.RECENT_LISTENS_MAX)
self.assertIsInstance(recent[0], Listen)
for i, r in enumerate(recent):
self.assertEqual(r.timestamp, listens[i].timestamp)
recent = self._redis.get_recent_listens(5)
self.assertEqual(len(recent), 5... | datetime.utcnow()
# get without setting any value, should return None
self.assertIsNone(self._redis.get_listen_count_for_day(today))
# set a value to a key that doesn't exists
self._redis.increment_listen_count_for_day(today, 2)
self.assertEqual(2, self._redis.get_listen_count_f... |
]],
long_param_re = "is unknown mode char to me for (?P<channel>.+)",
long_param_values = {"channel":channel})
if expect_ops_needed:
self.get_reply(client, expect_code = replies.ERR_CHANOP | RIVSNEEDED, expect_nick = nick,
expect_nparams = 2, expect_short_params = [channel],
long_param_re = "You're not channel operator")
if nick_mode is not None and expect_not_on_channel:
self.get_reply(client, expect | _code = replies.ERR_USERNOTINCHANNEL, expect_nick = nick,
expect_nparams = 3, expect_short_params = [nick_mode, channel],
long_param_re = "They aren't on that channel")
# Message/reply getters
def get_reply(self, client, expect_co... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
FileSelectionPanel.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
********************... | leNames(self,
self.tr('Select file'), path, '*.' + self.ext)
if filenames:
self.leText.setText(u';'.join(filenames))
settings.setValue('/Processing/LastInputPath',
os.path.dirname(filenam | es[0]))
def getValue(self):
s = self.leText.text()
if isWindows():
s = s.replace('\\', '/')
return s
def setText(self, text):
self.leText.setText(text)
|
import _plotly_utils.basevalidators
class FamilyValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self,
plotly_name="family",
parent_name="scatter3d.marker.colorbar.title.font",
**kwargs
):
super(FamilyValidator, self).__init__(
plotly_n... | parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
no_blank=kwargs.pop("no_blank", True),
strict=kwargs.pop("strict", | True),
**kwargs
)
|
import re
from gourmet.plugin import ExporterPlugin
from gourmet.convert import seconds_to_timestring, float_to_frac
from . import gxml2_exporter
from gettext import gettext as _
GXML = _('Gourmet XML File')
class GourmetExportChecker:
def check_rec (self, rec, file):
self.txt = file.read()
self... | 'Did not find yields value %s %s'%(self.rec.yields,
self.rec.yield_unit)
for att in ['preptime','cooktime']:
if getattr(self.rec,att):
tstr = seconds_to_timestring(getattr(self.rec,att))
... | |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# no... | mplied. See the
# License for the specific language governing permissions and limitations
# under the License.
from django.conf.urls.defaults import patterns
from django.conf.urls.defaults import url
from openstack_dashboard.dashboards.project.instances.views import DetailView
from openstack_dashboard.dashboard... | LaunchInstanceView
from openstack_dashboard.dashboards.project.instances.views import ResizeView
from openstack_dashboard.dashboards.project.instances.views import UpdateView
INSTANCES = r'^(?P<instance_id>[^/]+)/%s$'
VIEW_MOD = 'openstack_dashboard.dashboards.project.instances.views'
urlpatterns = patterns(VIEW_... |
#!/usr/bin/env python
# $Id$
"""
Print detailed information about a process.
"""
import os
import datetime
import socket
import sys
import psutil
from psutil._compat import namedtuple
def convert_bytes(n):
if n == 0:
return '0B'
symbols = ('k', 'M', ' | G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i+1)*10
for s | in reversed(symbols):
if n >= prefix[s]:
value = float(n) / prefix[s]
return '%.1f%s' % (value, s)
def print_(a, b):
if sys.stdout.isatty():
fmt = '\x1b[1;32m%-17s\x1b[0m %s' %(a, b)
else:
fmt = '%-15s %s' %(a, b)
print fmt
def run(pid):
p = psutil.Proc... |
#MenuTitle: Guides through All Selected Nodes
# -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
__doc__="""
Creates guides through all selected nodes.
"""
from Foundation import NSPoint
import math
thisFont = Glyphs.font # frontmost font
selectedLayers = thisFont.selectedLayers... | ction[0])
for i,j in enumerate(range(1,len(currentPointSelection))):
point1 = currentPointSelection[i]
point2 = currentPointSelection[j]
angleBetween | Points = angle(point1,point2)
middlePoint = addPoints(point1,point2)
middlePoint.x *= 0.5
middlePoint.y *= 0.5
# create guide and add it to layer:
if not isThereAlreadyAGuideWithTheseProperties(thisLayer, middlePoint, angleBetweenPoints):
guideBetweenPoints = newGuide(middlePoint, angleBetw... |
"""
Provide basic components for groupby. These definitions
hold the allowlist of methods that are exposed on the
SeriesGroupBy and the DataFrameGroupBy objects.
"""
from __future__ import annotations
import dataclasses
from typing import Hashable
@dataclasses.dataclass(order=True, frozen=True)
class OutputKey:
... | cepts only
# a single quantile value, it's a reduction.
# GH#27526 might change that.
"quantile",
"sem",
"size",
"skew",
"std",
"sum",
"var",
]
)
# List of transformation functions.
# a transformation is a function that, for each group,
# prod... | x",
"cummin",
"cumprod",
"cumsum",
"diff",
"ffill",
"fillna",
"pad",
"pct_change",
"rank",
"shift",
"tshift",
]
)
# these are all the public methods on Grouper which don't belong
# in either of the above lists
groupby_other_met... |
e not in ('', True, False, None):
# Only add the 'value' attribute if a value is non-empty.
final_attrs['value'] = force_unicode(value)
return mark_safe(u'<label class="checkbox"><input%s /> %s</label>' %
(flatatt(final_attrs), self.inline_label))
class Bootstr... | 'endpoint': se | lf.url,
'page_size': self.page_size,
}
)
return mark_safe(output)
class DateRangePickerWidget(Input):
"""SUPPORTS BOOTSTRAP 3 ONLY
Extends the standard input widget to render a Date Range Picker Widget.
Documentation and Demo here: http://www.daterangepicker.com... |
import lassie
from .base import LassieBaseTes | tCase
class LassieOpenGraphTestCase(LassieBas | eTestCase):
def test_open_graph_all_properties(self):
url = 'http://lassie.it/open_graph/all_properties.html'
data = lassie.fetch(url)
self.assertEqual(data['url'], url)
self.assertEqual(data['title'], 'Lassie Open Graph All Properies Test')
self.assertEqual(data['descriptio... |
#!/usr/bin/python3
import sys
import os
# this script allows the loading of palettes from files
# when invoked you must specify a palette
# google-blue.hex
# google-light-blue.hex
# old-blue.rgb
#
# each palette must contain 10 colours for the graduations between 0 and 100 %
# and an 11th colour for ... | lour_ongoing = [''')
for o in colours[10]:
o += " | ,"
lines.append(o)
lines.append("];\n")
# print footer
lines.append(footer)
lines.append("\n")
f.writelines(lines)
if __name__ == "__main__":
args = sys.argv
if len(args) < 2:
print("Error: must specify palette file")
exit(1)
if len(args) > 2:
print("E... |
from PyOM | APIc im | port PyOMAPIc
|
from settings_base import *
PO | RT = 80
SERVER_NAME = 'http://libra.pitomba.org:%s' % PORT
MONGODB_DATABASE_URL = "localhost"
MONGODB_DATABASE_PORT = 27017
MONGODB_DATABASE_USER = "usr_libra"
MONGODB_DATABASE_PWD = "usr_libra"
M | ONGODB_DATABASE_POOL_SIZE = 50
|
def italianhello():
i01.setHandSpeed("left", 0.60, 0.60, 1.0, 1.0, 1.0, 1.0)
i01.setHandSpeed("right", 1.0, 1.0, 1.0, 1.0, 1.0, 1.0)
i01.setArmSpeed("left", 1.0, 1.0, 1.0, 1.0)
i01.setArmSpeed("right", 1.0, 1.0, 1.0, 1.0)
i01.setHeadSpeed(0.65, 0.75)
i01.moveHead(105,78)
i01.moveArm("left",78,48,37,11)
... | sleep(1)
i01.setHandSpeed("left", 0.85, 0.85, 0.85, 0.85, 0.85, 0.85)
i01.setHandSpeed("right", 0.85, 0.85, 0.85, 0.85, 0.85, 0.85)
i01.setArmSpeed("right", 0.75, 0.85, 0.95, 0.85)
i01.setArmSpeed("left", 0.95, 0.65, 0.75, 0.75)
i01.setHeadSpeed(0.75, | 0.75)
i01.moveHead(79,100)
i01.moveArm("left",5,94,28,15)
i01.moveArm("right",5,82,28,15)
i01.moveHand("left",42,58,42,55,71,35)
i01.moveHand("right",81,50,82,60,105,113)
ear.resumeListening()
|
#
# (c) 2017 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible is d... | ations = self.get_device_operations()
self.check_edit_config_capability(operations, candidate, commit, replace, comment)
resp = {}
results = []
requests = []
if replace:
| candidate = 'load replace {0}'.format(replace)
for line in to_list(candidate):
if not isinstance(line, collections.Mapping):
line = {'command': line}
cmd = line['command']
results.append(self.send_command(**line))
requests.append(cmd)
... |
from django.apps import AppConfig
from django.core import checks
from django.utils.translation import ugettext_lazy as _
import xadmin
class XAdminConfig( | AppConfig):
"""Simple AppConfig which does not do automatic discovery."""
name = 'xadmin'
verbose_name = _("Administration")
def ready(self):
self.module.autodiscover()
setattr(xadmin, 'site', xadmi | n.site)
|
#!/usr/bin/env python
from distutils.core import setup
execfile('modlunky/version.py')
with open('requirements.txt') as requirements:
required = requirements.read().splitlines()
kwargs = {
"name": "modlun | ky",
"version": str(__version__),
"packages": ["modlunky"],
"scripts": ["bin/modlunky"],
"description": "Library and Command Line Tool for Spelunky.",
"author": "Gary M. Josack",
"maintainer": "Gary M. Josack",
"author_email": "gary@byoteki.com",
"maintainer_email": "gary@byoteki.com",
... | ogramming Language :: Python",
"Topic :: Software Development",
"Topic :: Software Development :: Libraries",
"Topic :: Software Development :: Libraries :: Python Modules",
]
}
if required:
kwargs["install_requires"] = required
setup(**kwargs)
|
#!/usr/bin/python
############################################################################
# tcp2tcp.py | #
# v0.1 #
# #
# Copyright (C) 2011 by Boyan Tabakov #
# blade@alslayer.net ... | #
# #
# 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,... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Ship()
result.template = "object/ship/p | layer/shared_player_z95.iff"
result.attribute_template_id = -1
result.stfName("space_ship","player_z95")
#### BEGIN | MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
import csv
from django.db.models import Max
from django.utils.translation import ugettext_lazy as _
from urllib2 import URLError
from googlemaps import GoogleMaps, GoogleMapsError
from locations.models import Location
from locations.exceptions import LocationEncodingError
class CsvParseError(csv.Error):
pass
d... |
location.category.add(category | )
location.save()
messages['created'].append(location_row['name'])
else:
# Duplicate, but enforce that it is now active
location.is_active = True
location.save()
messages['skipped'].append(location_row['name'])
messages['errors'] = Fals... |
'''
/*******************************************************************************
*
* Copyright (c) 2015 Fraunhofer FOKUS, All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser Genera | l Public
* License as published by the Free Software Foundation; either
* version 3.0 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, see <http://www.gnu.org/licenses/>.
*
* AUTHORS: Louay Bassbouss (louay.bassbouss@fokus.fraunhofer.de)
*
***... |
init_zero=False,
data_format='channels_last',
name=None):
"""Performs a batch normalization followed by a ReLU.
Args:
inputs: `Tensor` of shape `[batch, channels, ...]`.
is_training_bn: `bool` for whether the model is training.
relu: `bool` if Fal... | batch, height, width, channels]`.
Returns:
A padded `Tensor` of the same `data_format` with size either intact
(if `kernel_size == 1`) or padded (if `kernel_size > 1`).
"""
pad_total = kernel_size - 1
pad_beg = pad_total // 2
pad_end = pad_total - pad_beg
if data_format == 'channels_first':
pad... | .pad(
inputs, [[0, 0], [0, 0], [pad_beg, pad_end], [pad_beg, pad_end]])
else:
padded_inputs = tf.pad(
inputs, [[0, 0], [pad_beg, pad_end], [pad_beg, pad_end], [0, 0]])
return padded_inputs
def conv2d_fixed_padding(inputs,
filters,
kernel_size,... |
#! /usr/bin/env python
# -*- coding: latin-1 -*-
# Copyright (C) 2006 Universitat Pompeu Fabra
#
# Permission is hereby granted to distribute this software for
# non-commercial research purposes, provided that this copyright
# notice is included with any such distribution.
#
# THIS SOFTWARE IS PROVIDED "AS IS" WI... | al (and""" % t,
for i in range(1,n):
print >> problem, """
(less n%d n%d)""" % (i,i+1),
print >> probl | em, """
))
)
"""
|
andle
File to load.
model : model object
The model object (of type :class:`flopy.modflow.mf.Modflow`) to
which this package will be added.
ext_unit_dict : dictionary, optional
If the arrays in the file are specified using EXTERNAL,
or ol... | t_package | ('DIS').laycbd[k] > 0:
if model.verbose:
print ' loading vkcb layer {0:3d}...'.format(k+1)
if 'vkcb' not in par_types:
t = util_2d.load(f, model, (nrow,ncol), np.float32, 'vkcb',
ext_unit_dict)
... |
from flask import Blueprint
log_analyzer = Blue | print('log_analyzer', __name__)
| from . import views
|
s': [{'key': 'k0', 'value': 'v0'},
{'key': 'k1', 'value': 'v1'}]}
out_md = self.driver._format_metadata('fp', in_md)
self.assertTrue('fingerprint' in out_md)
self.assertEqual(out_md['fingerprint'], 'fp')
self.assertTrue('items' in out_md)
self.assertEqu... | ._create_node_req(node_name, size, image,
zone, metadata=md)
self.assertTrue('items' in data['metadata'])
self.assertEqual(len(data['metadata']['items']), 1)
self.assertEqual(data['metadata']['items'][0]['k | ey'], 'k0')
self.assertEqual(data['metadata']['items'][0]['value'], 'v0')
def test_create_node_existing(self):
node_name = 'libcloud-demo-europe-np-node'
image = self.driver.ex_get_image('debian-7')
size = self.driver.ex_get_size('n1-standard-1', zone='europe-west1-a')
self.... |
import os
import sys
import unittest
from logilab.common import testlib
from pylint.testutils import make_tests, LintTestUsingFile, cb_test_gen, linter
import ConfigParser
HERE = os.path.dirname(os.path.abspath(__file__))
PLUGINPATH = os.path.join(HERE, "..")
linter.prepare_import_path(PLUGINPATH)
linter.load_plugin_... | , 'messages')
return make_tests(input_dir, messages_dir, None, callbacks)
def additional_tests():
suites = unittest.TestSuite()
for fn in os.listdir(os.path.dirname(__file__)):
if fn.endswith('.py') and fn not in ('__init__.py', 'fulltest.py'):
name = os.path.splitext(fn)[0]
... | eturn suites
def suite():
default = [unittest.makeSuite(test, suiteClass=testlib.TestSuite) for test in tests()]
default.append(additional_tests())
return testlib.TestSuite(default)
if __name__ == '__main__':
testlib.unittest_main(defaultTest='suite')
|
# code source: https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iv-database
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
v = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
api.downgrade(SQLALCHEMY_DATABASE_UR... | To downgrade in m | ultiple revisions, run script as many as needed. |
example_template = Template({
'A': RsrcDef({}, []),
'B': RsrcDef({ | }, []),
'C': RsrcDef({'a': '4alpha'}, ['A', 'B']),
'D': RsrcDef({'c': GetRes('C')}, []),
'E': RsrcDef({'ca': GetAtt('C', 'a')}, []),
})
engine.create_stack('foo', example_template)
engine.noop(3)
engine.rollback_sta | ck('foo')
engine.noop(6)
engine.call(verify, Template())
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
import os
from mozboot.base import BaseBootstrapper
class OpenBSDBootstrapper(BaseBootstrapper):
def __init__(self... |
self.run_as_root(['pkg_add', '-z',
'mercurial',
'llvm',
'autoconf-2.13',
'yasm',
'gtk+2',
'libIDL',
'gmake',
'gtar',
'wget',
'unzip',
'zip'])
def _update_package_manager(self... | un_as_root(['pkg_add', '-u', 'mercurial'])
|
#!/usr/bin/env python3
"""
The goal of this example is to show you the syntax for IR seeking readings. When using
IR-SEEK with a remote control you get both heading and distance data. The code below
shows the syntax for beacon seeking. Additionally it's good to play with a demo so that
you can see how well or not we... | ue(1)
print("IR Heading = {} Distance = {}".format(current_heading, current_distance))
time.sleep(0.5)
ev3.Sound.speak("Goodbye")
# ----------------------------------------------------------------------
# Calls main to sta | rt the ball rolling.
# ----------------------------------------------------------------------
main()
|
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2014-2015 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser 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 S... | foo bar/foo|bar/foo| bar/
foo bar/foo|bar/ foo| bar/
foo bar /foo|bar/ foo| bar| /
foo bar bla fasel/foo|bar|bla|fasel/foo| bar| bla| fasel/
x y z xxxx/x|y|z|xxxx/x| y| z| xxxx/
\x bar/x|bar/\x| bar/
\ x bar/ x|bar/\ x| bar/
\ bar/ bar/\ bar/
foo \x bar/foo|x|bar/foo| \x|... | |bar|bla/"foo"| bar| "bla"/
"foo" bar bla/foo|bar|bla/"foo"| bar| bla/
foo 'bar' bla/foo|bar|bla/foo| 'bar'| bla/
'foo' 'bar' 'bla'/foo|bar|bla/'foo'| 'bar'| 'bla'/
'foo' bar 'bla'/foo|bar|bla/'foo'| bar| 'bla'/
'foo' bar bla/foo|bar|bla/'foo'| bar| bla/
blurb foo"bar"bar"fasel" baz/blurb|foobarbarfasel|baz/blurb| foo"... |
import re
import sys
class URI():
def __init__( self, root_path ):
super().__init__()
if root_path[-1] != '/' or root_path[0] != '/':
raise ValueError( 'root_path must start and end with "/"' )
self.root_path = root_path
self.uri_regex = re.compile( r'^({0}|/)(([a-zA-Z0-9\-_.!~*<>]+/)*)([a-zA... | ng and leading blank lines:
while trimmed and not trimmed[-1]:
trimmed.pop()
while trimmed and not trim | med[0]:
trimmed.pop( 0 )
# Return a single string:
return '\n'.join( trimmed )
|
# Copyright (C) 2017 Lenovo, Inc.
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansi... | le 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import tempfile
from units.compat import unittest
fro... |
# Copyright 2014 The | Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-st | yle license that can be
# found in the LICENSE file.
from master import gitiles_poller
def Update(config, active_master, c):
master_poller = gitiles_poller.GitilesPoller(
'https://chromium.googlesource.com/external/mojo')
c['change_source'].append(master_poller)
|
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('data', one_hot=True)
mnist_train = mnist.train
mnist_val = mnist.validation
p = 28 * 28
n = 10
h1 = 300
func_act = tf.nn.sigmoid
x_pl = tf.placeholder(dtype=tf.float32, shape=[None, p])
y_pl = tf.pl... | (learning_rate=0.3).minimize(cross_entropy)
batch_size = 50
batch_per_epoch = mnist_train.num_examples // batch_size
epoch = 2
with tf.Session() as sess:
tf.global_variables_initializer().run()
x_val = mnist_val.images
y_val = mnist_val.labels
val_fd = {x_pl: x_val, y_pl: y_val}
for ep in range(epo... | xt_batch(batch_size)
loss_value, _ = sess.run([cross_entropy, train_op], feed_dict={x_pl: xtr, y_pl: ytr})
if sp == 0 or (sp + 1) % 100 == 0:
print(f'Loss: {loss_value:.4f}')
acc = sess.run(accuracy, feed_dict=val_fd)
print(f'Validation Acc: {acc:.4f}')
... |
import _plotly_utils.basevalidators
class TickvalsValidator(_plotly_utils.basevalidators.DataArrayValidator):
def __init__(self, plotly_name="tickvals", parent_name="carpet.ba | xis", **kwargs):
super(TickvalsValidator, self).__init__(
| plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
**kwargs
)
|
from django.contrib import admin
from .models import Grant, AccessToken, RefreshToken, get_application_model
class ApplicationAdmin(admin.ModelAdmin):
list_display = ("name", "user", "client_type", "authorization_grant_type")
list_filter = ("client_type", "authoriza | tion_grant_type", "skip_authorization")
radio_fields = {
"client_type": admin.HORIZONTAL,
"authorization_grant_type": admin.VERTICAL,
}
raw_id_fields = ("user", )
class GrantAdmin(admin.ModelAdmin):
list_display = ("code", "application", "user", "expires")
raw_id_fields | = ("user", )
class AccessTokenAdmin(admin.ModelAdmin):
list_display = ("token", "user", "application", "expires")
raw_id_fields = ("user", )
class RefreshTokenAdmin(admin.ModelAdmin):
list_display = ("token", "user", "application")
raw_id_fields = ("user", "access_token")
Application = get_applic... |
import os
impo | rt sys
# Add parent directory to path to make test aware of other modules
srcfol | der = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', "src"))
if srcfolder not in sys.path:
sys.path.append(srcfolder)
|
import l | ogging
import os
import re
import select
import subprocess
import threading
import | time
__all__ = [
'ExternalService',
'SpawnedService',
]
log = logging.getLogger(__name__)
class ExternalService(object):
def __init__(self, host, port):
log.info("Using already running service at %s:%d", host, port)
self.host = host
self.port = port
def open(self):
... |
from django.conf.urls import patterns, include, url
from service_order import views, data_views
urlpatterns = patterns('',
url(r'^$', views.index),
url(r'^order_state_machine/$', views.order_state_machine),
url(r' | ^make_order/$', views.make_order),
url(r'^make_order2/$', views.make_order2),
url(r'^make_order3/$', views.make_order3),
url(r'^cr | eate_order/$', views.create_order),
url(r'^view_refund_sheet/$', views.view_refund_sheet),
url(r'^data/validate_code/', data_views.validate_code),
)
|
'location': 'Test Cases',
'description': 'We\'re just testing that all day events get setup '
'correctly',
'kind': 'calendar#event',
'created': '2016-06-23T16:37:57.000Z',
'transparency': 'transparent',
'updated': '2016-06-24T01:57:2... | assert cal.name == device_name
assert cal.state == STATE_OFF
assert not cal.offset_reached()
assert cal.device_state_attributes == {
'message': event['summary'],
'all_day': False,
'offset_reached': False,
'start_time': one_hour_from_now.strftim... | cation': '',
'description': '',
}
@patch('homeassistant.components.google.calendar.GoogleCalendarData')
def test_in_progress_event(self, mock_next_event):
"""Test that we can create an event trigger on device."""
middle_of_event = dt_util.now() \
- dt_util.dt.tim... |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from socorro.unittest.cron.setup_configman import (
get_config_manager_for_crontabber,
)
from crontabber.tests impo... | ration tests to participate
fully with the environment variables, commandline arguments, and
| configurations files that the Socorro installation/test system of
Makefiles and shell scripts offers"""
config = get_config_manager_for_crontabber().get_config()
return config
|
raise | Exception("tes | ts where moved to emzed to avoid circular dependencies")
|
import sys
from craystack import cf
if len(sys.argv) < 4:
print "Usage: %s <key> <subkey> <path>" % sys.argv[0]
sys.exit(2)
_, key, subkey, filena | me = sys.argv
with open(filename) as f:
content = f.read()
cf.insert(key, {subkey: content})
print "Uploaded %s to %s/%s (%s bytes)" % (filename, key, su | bkey, len(content))
|
fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]).){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}... | xtra
rectangles on the top to represent antennas. Width will stay the same
though.
"""
old_h = h
h = old_h * self.drawing['antenna_height_ratio']
self.drawing['h_with_ant'] = h
ant_w = self.drawing['w'] * self.drawing['antenna_width_ratio']
self.drawing['... | t so we have enough space for the antennas
h_diff = h - old_h
self.drawing['h_diff'] = h_diff
env.y += h_diff
self.drawing['ant_h'] = h_diff
return w, h
def draw(self, env):
self.draw_base(env)
# Fetch the drawing group from the environment
g = env.... |
modified_1 or modified_2:
print(region, last_modified_1, last_modified_2)
self.handle_region(region)
def handle_region(self, region):
lics = Licence.objects.filter(traffic_area=region)
lics = lics.in_bulk(field_name="licence_number")
lics_to_update = set()
... | on.traffic_area_office_covered_by_area = line['TAO Covered BY Area']
# a registration can have multiple numbers
if registration.service_number:
if line['Service Num | ber'] not in registration.service_number:
registration.service_number = f"{registration.service_number}\n{line['Service Number']}"
else:
registration.service_number = line['Service Number']
# a registration can have multiple types
if registration.... |
from couchpotato import get_session
from couchpotato.core.event import addEvent, fireEvent
from couchpotato.core.helpers.variable import mergeDicts, randomString
from couchpotato.core.logger import CPLog
from couchpotato.core.plugins.base import Plugin
from couchpotato.core.settings.model import Library
import copy
imp... | heckLibrary)
def returnByType(self, results):
new_results = {}
for r in results:
type_name = r.get('type', 'movie') + 's'
if type_name not in new_results:
new_results[type_name] = []
| new_results[type_name].append(r)
# Combine movies, needs a cleaner way..
if 'movies' in new_results:
new_results['movies'] = self.combineOnIMDB(new_results['movies'])
return new_results
def combineOnIMDB(self, results):
temp = {}
order = []
... |
"""Test cltk.prosody."""
__license__ = 'MIT License. See LICENSE.'
from cltk.prosody.latin.scanner import Scansion as ScansionLatin
from cltk.prosody.latin.clausulae_analysis import Clausulae
from cltk.prosody.greek.scanner import Scansion as ScansionGreek
from cltk.prosody.latin.macronizer import Macronizer
import u... | """Test Macronizer().macronize_tags()"""
text = "Quo usque tandem, O Catilina, abutere nostra patientia?"
correct = [('quo', 'd--------', 'quō'), ('usque', 'd--------', 'usque'), ('tandem', 'd--------', 'tandem'), (',', 'u--------', ','), ('o', 'e--------', 'ō'), ('catilina', 'n-s---mb-', 'catilīn... | None, '?')]
current = Macronizer("tag_ngram_123_backoff").macronize_tags(text)
self.assertEqual(current, correct)
def test_macronize_text(self):
"""Test Macronizer().macronize_text()"""
text = "Quo usque tandem, O Catilina, abutere nostra patientia?"
correct = "quō usque ta... |
ly(self):
days = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN']
for day in days:
self._check_generated_range('1/1/2000', 'W-%s' % day)
def test_week_of_month(self):
days = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN']
for day in days:
for i in range(... | 07-01 10:00', '2014-07-01 11:00',
| '2014-07-01 12:00', '2014-07-01 13:00', '2014-07-01 14:00',
'2014-07-01 15:00', '2014-07-01 16:00',
'2014-07-02 09:00', '2014-07-02 10:00', '2014-07-02 11:00'])
self.assertEqual(idx.inferred_freq, 'BH')
idx = DatetimeIndex... |
from OpenGLCffi.GL import params
@params(api='gl' | , prms=['len', 'string'])
d | ef glStringMarkerGREMEDY(len, string):
pass
|
import unittest
from github_person import GithubPerson
class Test_GithubPerson( | unitte | st.TestCase):
def setUp(self):
pass
if __name__ == '__main__':
unittest.main()
|
import shutil
import os
import hashlib
import dockbot
def gen_hash(data):
return hashlib.sha256(data).hexdigest()
class Image(object):
def __init__(self, root, name, path, platform = None, projects = [],
modes = None, slave = False, remote = False):
self.root = root
self.con... | self.context += [
dockbot.get_resource('dockbot/data/master/nginx.conf')]
self.containers.app | end(dockbot.Master(self))
return
# Slave only from here
for mode in modes:
self.containers.append(self.create_slave(mode))
# Slave projects
self.projects = set()
for project in projects:
self.projects.update(self.conf.get_project_deps(project... |
#!/bin/env python
# mainly for sys.argv[], sys.argv[0] is the name of the program
import sys
# mainly for arrays
import numpy as np |
def newtraph(fx, fxprime):
if __name__ == '__main__':
print 'hello'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.