prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
from app import app, grabber, merge, segment
from flask import render_template, request, url_for, jsonify
import cv2
import numpy as np
import os, re
def rm(dir, pattern):
for f in os.listdir(dir):
if re.search(pattern, f):
os.remove(os.path.join(dir, f))
@app.route('/')
@app.route('/index')
d... | time = g.grab(lat, lon, zoom)
# 'smart' means that the image went through the neural net prediction script
smart_contours = segment.predict(time,'app/ma_prediction_400/dg%s.png'%(time), 'app/static/img/nn_dg'+time+'.png')
smart_areas = segment.get_areas(smart_contours.values())
# 'dumb' meanas that th... | .png','app/static/img/dumy_dg'+time+'.png')
dumb_areas = segment.get_areas(dumb_contours.values())
# uses 'smart' locations to pick out contours in the 'dumb' image
buildings = merge.intersect(smart_contours, dumb_contours)
merge.mkimage('app/static/img/dg'+time+'.png','app/static/img/merge_dg'+time+'.... |
import re
import textwrap
__all__ = ['dumps', 'loads']
SPLIT_ITEMS = re.compile(r'\n(?!\s)').split
MATCH_ITEM = re.compile(r'''
(?P<key | >\w+): # key
\s?
(?P<value>.*?)$ # first line
(?P<value2>.+)? # optional continuation line(s)
''', re.MULTILINE | re.DOTALL | re.VERBOSE).match
def dumps(data, comments={}):
s = ''
for k, v in data.items():
comment = comments.get(k, None)
if comment:
s... | ads(serialized):
data = {}
lineno = 0
for item in SPLIT_ITEMS(serialized):
if not item.startswith('#') and item.strip():
m = MATCH_ITEM(item)
if not m:
raise ValueError('syntax error on line {}'.format(lineno + 1))
value = m.group('value')
... |
class MutableValue:
"""
Used to avoid warnings (and in future errors) from aiohttp when the app context is modified.
"""
__slots__ = 'value',
def __init__(self, value=None):
self.value = value
| def change(self, new_value):
self.value = new_value
def __len__(self):
return len(self.value)
def __repr__(self):
return repr(self.value)
def __str__(self):
return str(self.value)
def __bool__(self):
return | bool(self.value)
def __eq__(self, other):
return MutableValue(self.value == other)
def __add__(self, other):
return self.value + other
def __getattr__(self, item):
return getattr(self.value, item)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-06-06 06:33
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations... | ('expense_detail', models.CharField(help_text='Enter expense details', max_length=2 | 00, null=True)),
('expense_amount', models.FloatField(help_text='Enter expense amount', null=True)),
('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
],
),
]
|
random.randrange(1000)
print("a =", a, file=f)
print("b =", b, file=f)
if TESTFN in sys.modules:
del sys.modules[TESTFN]
try:
try:
mod = __import__(TESTFN)
except ImportError as err:
... | st.support, "__file__"))
# import x.y.z as w binds z as w.
import test.support as y
self.assertIs(y, test.support, y.__name__)
def test_import_initless_directory_warning(self):
with check_warnings(('', ImportWarning)):
# Just a | random non-package directory we always expect to be
# somewhere in sys.path...
self.assertRaises(ImportError, __import__, "site-packages")
|
"""nox-poetry c | onfiguration file."""
from calcipy.dev.noxfile import build_check, build_dist, check_safety, coverage, tests # noqa: F401 | |
# encoding: utf-8
#
#
# 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 dist | ributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Contact: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import absolute_import, division, unicode_literals
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.hashes import SHA256, Hash
... | ault_backend())
digest.update(bytes)
return digest.finalize()
|
ved = p['commit_set'] - v['commit_set']
added = v['commit_set'] - p['commit_set']
for c in history.get(v['sha1'], []):
if c['sha1'] in added:
v['commits'].append(dict(c))
v['commits'][-1]['removed'] = False
for c in history.get(p['sha1'], [])[::-1]... | t(create_version(manifest))))
if __name__ == "__main__":
ET.register_namespace('sparkle', 'http://www.andymatuschak.org/xml-namespaces/sparkle')
ET.register_namespace('ce', 'http://catchexception.org/xml-namespaces/ce')
import argparse
parser = argparse.ArgumentParser(description='obs-studio release ... | ', '--key', dest='key')
args = parser.parse_args()
create_update(args. |
Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Lic... | -id'
args = [my_id]
self._test_delete_resource(resource, cmd, my_id, args)
class CLITestV2 | 0V |
# -*- coding: utf-8 -*-
"""Reusable mixins for SQLAlchemy declarative models."""
from __future__ import unicode_literals
import datetime
import sqlalchemy as sa
class Timestamps(object):
created = sa.Column(
sa.DateTime,
default=datetime.datetime.utcnow,
server_default=sa.func.now(),
... | date=datetime.d | atetime.utcnow,
nullable=False,
)
|
#!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
... | tware is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ... | T SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
... |
#!/usr/bin/env python
#
# This is run by Travis-CI before an upgrade to load some data into the
# database. After the upgrade is complete, the data is verified by
# upgrade-after.py to make sure that the upgrade of the database went smoothly.
#
import logging
import unittest
import sys
sys.path.insert(0, '..')
sys.pat... | E FROM ip_net_asn")
def add_prefix(self, prefix, type, description, tags=None):
if tags is None:
tags = []
p = Prefix()
p.prefix = prefix
p.type = type
p.description = description
| p.tags = tags
p.save()
return p
class TestLoad(unittest.TestCase):
""" Load some data into the database
"""
def test_load_data(self):
"""
"""
th = TestHelper()
p1 = th.add_prefix('192.168.0.0/16', 'reservation', 'test')
p2 = th.add_prefix('192... |
ndom)
:arg realtime: Specify whether to perform the operation in realtime or
search mode
:arg refresh: Refresh the shard containing the document before
performing the operation
:arg routing: Specific routing value
"""
_, data = yield self.transport.perform... | ery name, attribute, or wildcard
:arg refresh: Refresh the index after performing the operation
:arg replication: Specific replication type (default: sync)
:arg retry_on_conflict: Specify how many times should the operation be
retried when a conflic | t occurs (default: 0)
:arg routing: Specific routing value
:arg script: The URL-encoded script definition (instead of using
request body)
:arg timeout: Explicit operation timeout
:arg timestamp: Explicit timestamp for the document
:arg ttl: Expiration time for the doc... |
from pulp.bindings import auth, consumer, consumer_groups, repo_groups, repository
from pulp.bindings.actions import ActionsAPI
from pulp.bindings.content import OrphanContentAPI, ContentSourceAPI, ContentCatalogAPI
from pulp.bindings.event_listeners import EventListenerAPI
from pulp.bindings.server_info import ServerI... | groups.ConsumerGroupActionAPI(pulp_connection)
self.consumer_group_bind = consumer_groups.ConsumerGroupBindAPI(pulp_connection)
self.consumer_group_content = consumer_groups.ConsumerG | roupContentAPI(pulp_connection)
self.consumer_history = consumer.ConsumerHistoryAPI(pulp_connection)
self.consumer_search = consumer.ConsumerSearchAPI(pulp_connection)
self.content_orphan = OrphanContentAPI(pulp_connection)
self.content_source = ContentSourceAPI(pulp_connection)
... |
import mock
from django.utils import timezone
from rest_framework.test import APIRequestFactory
from elections.api.next.api_views import BallotViewSet
class TestBallotViewSet:
def test_get_queryset_last_updated_ordered_by_modified(self):
factory = APIRequestFactory()
timestamp = timezone.now().i... | Set(request=request)
view.queryset = mock.MagicMock()
view.get_queryset()
view.queryset.with_last_updated.assert_called_once()
def test_get_queryset_last_updated_not_ordered(self):
factory = APIRequestFactory | ()
request = factory.get("/next/ballots/")
request.query_params = request.GET
view = BallotViewSet(request=request)
view.queryset = mock.MagicMock()
view.get_queryset()
view.queryset.with_last_updated.assert_not_called()
|
import logging
class NullHandler(logging.Handler):
def emit(self, record):
pass
log = logging.getLogger('WebPage')
log.setLevel(logging.ERROR)
log.addHandler(NullHandler())
import os
import web
from viz import Viz
import WebPage
import WebHandler
class WebHandlerDyn(WebHandler.WebHandler):... | username=username)
def getDynPath(self):
elems = WebPage.WebPage.urlStringTolist(web.ctx.path)
for e in elems:
if e.startswith('_'):
return e[1:]
c | lass WebPageDyn(WebPage.WebPage):
def __init__(self,subPageLister=None,
subPageHandler=None,
**fvars):
assert callable(subPageLister)
# store params
self.subPageLister = subPageLister
self.subPageHandler = ... |
# REST API Backend for the Radiocontrol Project
#
# Copyright (C) 2017 Stefan Derkits <stefan@derkits.at>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License... | n 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 Affero General Public License
# along with this program. If n... | ister your models here.
|
# Copyright 2014 OpenStack Foundation
# 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 requ... | eate_share_type_with_empty_name(self):
self.assertRaises(lib_exc.BadRequest, self.create_share_type, '')
@test.attr(type=["gate", "smoke", ])
def test_create_share_type_with_too_big_name(self):
self.assertRaises(lib_exc.BadRequest,
self.create_share_type,
... | def test_get_share_type_by_nonexistent_id(self):
self.assertRaises(lib_exc.NotFound,
self.shares_client.get_share_type,
data_utils.rand_name("fake"))
@test.attr(type=["gate", "smoke", ])
def test_try_delete_share_type_by_nonexistent_id(self):
... |
"""
Tests for CourseData utility class.
"""
from __future__ import absolute_import
import six
from mock import patch
from lms.djangoapps.course_blocks.api import get_course_blocks
from openedx.core.djangoapps.content.block_structure.api import get_course_in_cache
from student.tests.factories import UserFactory
from x... | data we used as input, and c_b_s is input-only
if arg != kwarg and arg != "collected_block_structure":
expected = self.expected_results[arg]
actual = getattr(co | urse_data, arg)
self.assertEqual(expected, actual)
def test_properties(self):
expected_edited_on = getattr(
self.one_true_structure[self.one_true_structure.root_block_usage_key],
'subtree_edited_on',
)
for kwargs in [
dict(course=self... |
# Copyright 2014 Sebastien Maccagnoni-Munch
#
# Th | is file is part of Calaos Web Installer.
#
# Calaos Web Installer is free software: you can redistribute it and/or
# modify it unde | r the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# Calaos Web Installer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty... |
"""
Deployment file to facilitate releases of pymatgen.
Note that this file is meant to be run from the root directory of the pymatgen
repo.
"""
__author__ = "Shyue Ping Ong"
__email__ = "ongsp@ucsd.edu"
__date__ = "Sep 1, 2014"
import glob
import os
import json
import webbrowser
import requests
import re
import subp... | toks.insert(-1, "\n\n" + "\n".join(lines))
with open("CHANGES.rst", "w") as f:
f.write("==========".join(toks))
def log_ver():
filepath = os.path.join(os.environ["HOME"], "Dropbox", "Public",
"pymatgen", ver)
with open(filepath, "w") as f:
f.write("Release")
d... | setver()
if not skip_test:
local("nosetests")
publish()
log_ver()
update_doc()
merge_stable()
release_github()
def open_doc():
pth = os.path.abspath("docs/_build/html/index.html")
webbrowser.open("file://" + pth)
|
v\xedk</option>
<option value="113">113 Reykjav\xedk</option>
<option value="116">116 Kjalarnes</option>
<option value="121">121 Reykjav\xedk</option>
<option value="123">123 Reykjav\xedk</option>
<option value="124">124 Reykjav\xedk</option>
<option value="125">125 Reykjav\xedk</option>
<option value="127">127 Reykjav... | lue="601">601 Akureyri</option>
<option value="602">602 Akureyri</option>
<option value="603">603 Akureyri</option>
<option value="610">610 Greniv\xedk</option>
<option value="611">611 Gr\xedmsey</option>
<option value="620">620 Dalv\xedk</option>
<option value="621">621 Dalv\xedk</option>
<option value="625">625 \xd3l... | </option>
<option value="645">645 Fossh\xf3ll</option>
<option value="650">650 Laugar</option>
<option value="660">660 M\xfdvatn</option>
<option value="670">670 K\xf3pasker</option>
<option value="671">671 K\xf3pasker</option>
<option value="675">675 Raufarh\xf6fn</option>
<option value="680">680 \xde\xf3rsh\xf6fn</op... |
import tkinter as tk
from tkinter.filedialog import askdirectory
from tkinter.messagebox import showwarning, showerror, showinfo
from tkinter import ttk
import logging
import sys
from threading import Thread
from spider_board.client import Browser
from spider_board.utils import time_job, LOG_FILE, get_logger, humansiz... | estroy | ()
def update_units(self):
self.unit_box.delete(0, tk.END)
for unit in self.browser.units:
self.unit_box.insert(tk.END, unit.title)
self.root.after(1000, self.update_units)
def bootstrap_browser(self, browser):
"""
Add in any hooks to the browser so they wi... |
#!/usr/bin/env python
import sys
sys.path.append('/var/www/html/modules/libraries')
import avahi
import dbus
from time import sleep
import mysql.connector
file = open('/var/www/html/config.php', 'r')
for line in file:
if "db_name" in line: MySQL_database = line.split('"')[3]
elif "db_user" in line: MySQL_us... | vahi.DBUS_NAME, avahi.DBUS_PATH_SERVER), avahi.DBUS_INTERFACE_ | SERVER)
group = dbus.Interface(bus.get_object(avahi.DBUS_NAME, server.EntryGroupNew()),
avahi.DBUS_INTERFACE_ENTRY_GROUP)
self._service_name = name
index = 1
while True:
try:
group.AddService(avahi.IF_UNSPEC, avahi.PROTO_INET, 0... |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | 'direction', 'ethertype',
'port/protocol', 'remote'])
def test_neutron_subnet_list(self):
subnet_list = self.parser.listing(self.neutron('subnet-list'))
| self.assertTableStruct(subnet_list, ['id', 'name', 'cidr',
'allocation_pools'])
def test_neutron_firewall_list(self):
firewall_list = self.parser.listing(self.neutron
('firewall-list'))
self.assertTable... |
from OctaHomeCore.OctaFiles.urls.base import *
from OctaHomeTempControl.views import *
class TempControlOctaUrls(OctaUrls):
@classmethod
def getUrls(cls):
return [
url(r'^TempControl/command/(?P<command>\w+)/$', handleTempCommand.as_view(), name='TempControlCommandWithOutDevice'),
url(r'^TempControl/command/... | name='TempControlCommand'),
url(r'^TempControl/command/(?P<command>\w+)/(?P<house>\w+)/(?P<deviceType>\w+)/(?P<deviceId>\d+)/$', handleTempCommand.as_view(), name='TempControlCommand'),
url(r'^TempControl/command/(?P<command>\w+)/(?P<house>\w | +)/(?P<room>\w+)/(?P<deviceType>\w+)/(?P<deviceId>\d+)/$', handleTempCommand.as_view(), name='TempControlCommand'),
url(r'^TempControl/page/(?P<page>\w+)/$', handleTempView.as_view(), name='TempControlPage'),
url(r'^TempControl/page/(?P<page>\w+)/(?P<deviceType>\w+)/(?P<deviceId>\d+)/$', handleTempCommand.as_... |
self.assertEqual(expected_ret, ret, "Not expected return")
def test_rc_send_success(self):
methodname = 'POST'
url = '/controller/dc/esdk/v2.0/test_url'
expected_resp = {'errorCode': u'0', 'reason': None,
'response': 'ok', 'status': 204}
with mock.patch.obje... | 'process_request',
return_value=self._mock_req_re | sp
(requests.codes.no_content)):
ret = ac_rest.RestClient().send(self.host, self.port,
methodname, url,
hex(10),
test_create_network_req)
... |
import unittest
from graph_diff.graph import rnr_graph, lr_node
from graph_diff.graph.graph_with_repetitive_nodes_exceptions import GraphWithRepetitiveNodesKeyError
class GraphWithRepetitiveNodesWithRootTest(unittest.TestCase):
def setUp(self):
self.test_graph = rnr_graph()
def test_add_node(self):
... | n self.test_graph)
self.test_graph.add_edge(lr_node(1, 1), lr_node(1, 2))
self.assertTrue(lr_node(1, 1) in self.test_graph)
self.assertTrue(lr_node(1, 2) in self.test_graph)
def test_add_edge_exp(self):
self.assertFalse(lr_node(1, 1) in self.test_graph)
self.assertFalse(lr_n... | lr_node(1, 1),
lr_node(1, 2))
if __name__ == '__main__':
unittest.main()
|
from setuptools import setup
__version__ = "0.5.0"
# Get the long description by reading the README
try:
readme_content = open("README.md").read()
except:
readme_content = ""
# Create the actual setup method
setup(name='pypred',
version=__version__,
description='A Python library for simple evaluat... | nguage"],
packages=['pypred'],
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating | System :: POSIX",
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Topic :: Software Development :: Libraries"
],
... |
summary_op_util.collect(val, collections, [_ops.GraphKeys.SUMMARIES])
return val
@tf_export(v1=['summary.audio'])
def audio(name, tensor, sample_rate, max_outputs=3, collections=None,
family=None):
# pylint: disable=line-too-long
"""Outputs a `Summary` protocol buffer with audio.
The summary has up... | _util.collect(val, collections, [_ops.GraphKeys.SUMMARIES])
return val
@tf_export(v1=['summary.text'])
def text(name, tensor, collections=None):
"""Summarizes textual data.
Text data summarized via this plugin will be visible in the Text Dashboard
in TensorBoard. The standard TensorBoard Text Dashboard will ... | own
in the strings, and will automatically organize 1d and 2d tensors into tables.
If a tensor with more than 2 dimensions is provided, a 2d subarray will be
displayed along with a warning message. (Note that this behavior is not
intrinsic to the text summary api, but rather to the default TensorBoard text
pl... |
from django import forms
from django.forms.widgets import *
from django.utils.safestring import mark_safe
from madrona.analysistools.widgets import SliderWidget, DualSliderWidget
class AdminFileWidget(forms.FileInput):
"""
A FileField Widget that shows its current value if it has one.
"""
def __init__(... | atBlock
try:
flatblock = str(FlatBlock.objects.get(slug=self.id).content)
except:
flatblock = ""
output = output.replace('\n', ' <img src="/media/marco/img/info.png" id="%s" class="info" /> | \n' %img_id, 1)
output = output.replace('\n', ' <span id="%s" style="display: none;">%s</span>\n' %(span_id, flatblock), 1)
return mark_safe(output)
class DualSliderWidgetWithTooltip(DualSliderWidget):
def __init__(self, param1, param2, min, max, step, id):
super(DualSliderWidgetW... |
from sympy import S, Integral, sin, cos, pi, sqrt, symbols
from sympy.physics.mechanics import (Dyadic, Particle, Point, ReferenceFrame,
RigidBody, Vector)
from sympy.physics.mechanics import (angular_momentum, dynamicsymbols,
inertia, inertia_of... | est_kinetic_energy():
m, M, l1 = symbols('m M l1')
omega = dynamicsymbols('omega')
N = ReferenceFrame('N')
O = Point('O')
O.set_vel(N, 0 * N.x)
Ac = O.locatene | w('Ac', l1 * N.x)
P = Ac.locatenew('P', l1 * N.x)
a = ReferenceFrame('a')
a.set_ang_vel(N, omega * N.z)
Ac.v2pt_theory(O, N, a)
P.v2pt_theory(O, N, a)
Pa = Particle('Pa', P, m)
I = outer(N.z, N.z)
A = RigidBody('A', Ac, a, M, (I, Ac))
assert 0 == kinetic_energy(N, Pa, A) - (M*l1**2*o... |
'''Find valid tags and usernames.
The file will contain things like:
tag:12345:romance
'''
import gzip
import re
import requests
import string
import sys
import time
import random
DEFAULT_HEADERS = {'User-Agent': 'ArchiveTeam'}
class FetchError(Exception):
'''Custom error class when fetching does not me | et our expectation.'''
def main():
# Take the program arguments given to this script
# Normal programs use 'argparse' but this keeps things | simple
start_num = int(sys.argv[1])
end_num = int(sys.argv[2])
output_filename = sys.argv[3] # this should be something like myfile.txt.gz
assert start_num <= end_num
print('Starting', start_num, end_num)
gzip_file = gzip.GzipFile(output_filename, 'wb')
for shortcode in check_range(star... |
"""
Router.py uses bot_packages in this file to setup comma | nd and sensor value routing to the correct bot_role.
"""
settings= {
"bot | _name":"rp4.solalla.ardyh",
"bot_roles":"bot",
"bot_packages":[],
"subscriptions":[],
}
|
from | astropy import units as u
K_kepler = 0.01720209895 # ua^(3/2) m_{sun} d^(−1)
K = 0.01720209908 * u.au ** (3 / 2) / u.d # ua^(3/2) d^(−1)
UA = | 149597870700 * u.m # m
GM1 = 1.32712442099E20 * u.m ** 3 / u.s ** 2 # m^(3) s^(−2)
# m1/m2
Mercury = 6023600
Venus = 408523.719
Earth_Moon = 328900.561400
Mars = 3098703.59
Jupiter = 1047.348644
Saturn = 3497.9018
Uranus = 22902.98
Neptune = 19412.26
Pluto = 136566000
Eris = 119100000
Ceres = 2119000000
Palas = 970... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Adriano Monteiro Marques
#
# Author: Piotrek Wasilewski <wasilewski.piotrek@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Fre | e Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Publi... | this program. If not, see <http://www.gnu.org/licenses/>.
from core import Chart, ChartColumn
CHART_TOOLS_PACKAGES = ['corechart', 'gauge', 'geochart', 'table', \
'treemap', 'annotatedtimeline']
class InvalidChartsPackage(Exception):
pass
class DatatableColumn(ChartColumn):
"""
... |
"""
Get the stem of a word, given a declined form and its gender.
TODO: Check this logic with von Soden's Grundriss der akkadischen Grammatik.
TODO: Deal with j/y issue.
"""
__author__ = ['M. Willis Monroe <willismonroe@gmail.com>']
__license__ = 'MIT License. See LICENSE.'
ENDINGS = {
'm': {
'singular':... | 'accusative': 'tam',
'genitive': | 'tim'
},
'dual': {
'nominative': 'tān',
'oblique': 'tīn'
},
'plural': {
'nominative': ['ātum', 'ētum', 'ītum'],
'oblique': ['ātim', 'ētim', 'ītum']
}
}
}
class Stemmer(object):
"""Stem Akkadian words with a simple algorithm... |
from chil | l import *
source('include.c')
destination('includemodified.c')
procedure('main | ')
loop(0)
original()
print_code()
|
#!/usr/bin/python
from sys import argv
from modules.helpers.wpdetector import WordpressDetector
from modules.net.scan import is_good_response
from modules.const import ERR, NO, OK, INFO
def main ():
if len (argv) > 1:
| print INFO + 'Checking site...'
if not is_good_response (argv [1]):
print ERR + 'Site is unavailable! :('
exit (-1)
print INFO + 'Detecting word | press...'
wpd = WordpressDetector (argv [1])
if wpd.detect_by_pages ():
print OK + 'Wordpress Detected!'
if raw_input ('Try to detect Wordpress version? (y/n): ') == 'y':
print INFO + 'Detecting Wordpress version...'
dec = wpd.detect_version ()
if dec is not None:
print OK + 'Wordpress Versi... |
# Copyright 2015 Google 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 writi... | rt ValidationFailed
from rigour.types import *
from rigour.constraints import length_between
import rigour
import pytest
def test_secrecy_declared_before():
t = String().secret().constrain(length_between(4,6))
with pytest.raises(ValidationFailed) as excinfo:
t.check("xxx")
message = str(excinfo)
assert "x... | t.check("xxx")
message = str(excinfo)
assert "xxx" not in message
|
import pygame
import intro
import game
class Intro2(intro.Intro):
def load_image(self):
self.fondo = pygame.image.load('ima/intro2.png').c | onvert()
def go_to_next(self):
new_scene = game.Game(self.world)
self.world.chang | e_scene(new_scene)
|
#!/usr/bin/env python
# PyQt tutorial 3
|
import sys
from PyQt4 import QtGui
app = QtGui.QAp | plication(sys.argv)
window = QtGui.QWidget()
window.resize(200, 120)
quit = QtGui.QPushButton("Quit", window)
quit.setFont(QtGui.QFont("Times", 18, QtGui.QFont.Bold))
quit.setGeometry(10, 40, 180, 40)
quit.clicked.connect(app.quit)
window.show()
sys.exit(app.exec_())
|
class GameStateInterface(object):
def __init_ | _(self):
self._team_ids_to_names = None
self._service_ids_to_names = None
def _team_id_to_name_map(self):
raise NotImplementedError
def _service_id_to_name_map(self):
raise NotImplementedError
def _scored_events_for_tick(self, tick):
raise NotImplementedError
... | _ids_to_names = self._team_id_to_name_map()
return self._team_ids_to_names
@property
def service_id_to_name_map(self):
if self._service_ids_to_names is None:
self._service_ids_to_names = self._service_id_to_name_map()
return self._service_ids_to_names
def scored_events_... |
"""Test cases that are in common among wemo platform modules.
This is not a test module. These test methods are used by the platform test modules.
"""
import asyncio
import threading
from unittest.mock import patch
from pywemo.ouimeaux_device.api.service import ActionException
from homeassistant.components.homeassis... | ).state == STATE_UNAVAILABLE
# Check that the entity recovers and is available after the update succeeds.
await hass.services.async_call(
HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
{ATTR_ENTITY_ID: [wemo_entity.entity_id]},
blockin | g=True,
)
assert hass.states.get(wemo_entity.entity_id).state == STATE_OFF
|
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 14 14:10:41 2016
@author: sigurdja
"""
from setuptools import setup, find_packages
setup(
name="psse_models",
| version= | "0.1",
packages=find_packages(),
) |
# Thanks to Kurt Othmer for BioExplorer design this is translated from
from flow import *
class Flow(object):
def init(self, context):
ch1 = context.get_channel('Channel 1')
#ch1 = Notch(50, input=ch1)
ch1_dc = DCBlock(ch1).ac
ch1_raw = BandPass(0.0, 40.0, input=ch1_dc)
ch1_theta = BandPass(3.0, 7.0, inpu... | w
def | flow():
return Flow()
|
s://scihub.copernicus.eu/apihub/search?q="
requests.packages.urllib3.disable_warnings()
def calculate_md5(fname):
hasher = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hasher.update(chunk)
return hasher.hexdigest().upper()
def do_query(quer... | "%Y/%j").isoformat()
if len(location) == 2:
location_str = 'footprint:"Intersects(%f, %f)"' % (location[0], location[1])
| elif len(location) == 4:
location_str = 'footprint:"Intersects( POLYGON(( " + \
"%f %f, %f %f, %f %f, %f %f, %f %f) ))"' % (
location[0], location[0],
location[0], location[1],
location[1], location[1],
location[1], location[0],
location[... |
ce': '/tool'}
try:
r = connection.request('POST',
'/dynamic/login',
fields=credentials,
retries=1,
redirect=False)
except (HTTPError, SSLError):
error('Connection to Hub f... | pecified exists and you have access to it.'
error(error_msg)
exit(-1)
# pylint: enable=E1103
| if options.verbose:
log('Data received from the hub')
log('Logging out')
logout(connection, cookie)
return r_data
def write_to_file(options, data, filename=None, output_path=None, force_overwrite=False):
if not filename:
filename = '%s-%s-%s.json' % (options.project, options.t... |
entry = InstructorTask.objects.get(id=task_entry.id)
status = json.loads(entry.task_output)
self.assertEquals(status.get('attempted'), succeeded + failed)
self.assertEquals(status.get('succeeded'), succeeded)
self.assertEquals(status.get('skipped'), skipped)
self.assertEquals(s... | urn_value.send_messages.side_effect = cycle([None])
self._test_run_with_task(send_bulk_course_email, 'emailed', num_emails - 1, num_emails - 1)
def test_disabled_user(self):
# Select number of emails to fit into a single subtask.
num_emails = settings.BULK_EMAIL_EMAILS_PER_TASK
... | e instructor:
students = self._create_students(num_emails - 1)
# mark a student disabled:
student = students[0]
UserStanding.objects.create(user=student, account_status=UserStanding.ACCOUNT_DISABLED, changed_by=student)
with patch('bulk_email.tasks.get_connection', autospec=True)... |
"""
mbed SDK
Copyright (c) 2011-2013 ARM Limited
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wr... | match = self.goanna_parse_line(line)
if match is not None:
self.cc_info(
| match.group('severity').lower(),
match.group('file'),
match.group('line'),
match.group('message')
)
def get_dep_opt(self, dep_path):
return ["--depend", dep_path]
def archive(self, objects, lib_path):
self... |
from monitor import Monitor
try:
from python_libtorrent import get_libtorrent
lt = get_libtorrent()
except Exception, e:
import libtorrent as lt
class Dispatcher(Monitor):
def __init__(self, client):
super(Dispatcher,self).__init__(client)
def do_start(self, th, ses):
self._th = th... | self._ses=ses
self.start()
def run(self):
if not self._ses:
raise Exception('Invalid state, session is not initialized')
while self.running:
a=self._ses.wait_for_alert(1000)
if a:
alerts= self._ses.pop_alerts()
for ... | for cb in self.listeners:
cb(lt.alert.what(alert), alert)
|
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2016, 2018, 2020 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distribu... | "uniqueItems": True,
"items": {"type": "string"},
"default": [],
}
schema["required"] = ["source"]
return schema
def __init__(self, name, options, project):
super().__init__(name, options, project)
self._setup_base_tools()
def _setup_base_tools(... | # Inform Snapcraft of the properties associated with building. If these
# change in the YAML Snapcraft will consider the build step dirty.
return ["configflags"]
def env(self, root):
env = super().env(root)
if self.project.is_cross_compiling:
env.extend(
... |
20,
'other_seed': 'r1'}}
expected_report = """\
remap r1,100,1,10,r2
remap r2,200,2,20,r1
"""
write_remap_counts(writer, counts, 'remap', distance_report)
self.assertEqual(expected_report, report.getvalue())
# noinspection DuplicatedCode
class ConvertPrelim... | expected_seed_counts = {'R1-seed': 2}
seed_counts = convert_prelim(prelim_csv,
self.sam_file,
self.remap_counts_writer,
count_threshold,
self.projects)
se... | ue())
self.assertEqual(expected_seed_counts, seed_counts)
def test_star_region(self):
self.maxDiff = None
prelim_csv = StringIO("""\
qname,flag,rname,pos,mapq,cigar,rnext,pnext,tlen,seq,qual
example1,89,R1-seed,1,0,54M,=,1,0,\
AAACCCTTTAAACCCTTTAAACCCTTTAAACCCTTTAAACCCTTTAAACCCTTT,\
BBBBBBB... |
import re
simple_cmd_match = re.compile(r'\\([^\\]+?)\{(.*?)\}')
graphics_cmd_match = re.compile(r'\\includegraphics\[.*?\]?\{(.*?)\}')
begin_cmd_match = re.compile(r'\\begin{([^}]+?)}(?:(?:\[([^\]]+?)\])|.*)')
newcmd_match = | re.compile(r'\\.+?\{(.*?)\}\{(.*)\}')
# newcmd_match_with_var = re.compile(r'\\[^\\]+?\{(.*?)\}\{(.*?)\}')
vars_match = re.compile(r'\{(.+?)\}')
def get_vars(line):
res = list()
open_braces = 0
one_var = ''
for char in line.strip():
| if char == '}':
open_braces -= 1
if open_braces > 0:
one_var += char
elif open_braces == 0 and one_var:
res.append(one_var)
one_var = ''
if char == '{':
open_braces += 1
return res
class FileIter:
def __init__(self, filename):
... |
ng.getLogger(__name__)
# Import third party libs
HAS_NEUTRON = False
try:
from neutronclient.v2_0 import client
HAS_NEUTRON = True
except ImportError:
pass
__opts__ = {}
def __virtual__():
'''
Only load this module if neutron
is installed on this minion.
'''
if HAS_NEUTRON:
r... | list all networks
CLI Example:
.. code-block:: bash
salt '*' neutron.list_networks
'''
return neutron_interface.list_networks(**kwargs)['networks']
@_autheticate
def list_ports(neutron_interface, **kwargs):
'''
list all ports
CLI Example:
.. code-block:: bash
sal... |
CLI Example:
.. code-block:: bash
salt '*' neutron.list_routers
'''
return neutron_interface.list_routers(**kwargs)['routers']
@_autheticate
def update_floatingip(neutron_interface, fip, port_id=None):
'''
update floating IP. Should be used to associate and disassociate
floating... |
from dj | ango.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf.urls.static import static
from .views import HomeView
# Uncomment the next two lines to enable the admin:
admin.autodiscover()
urlpatterns = (
static(settings.MEDIA_URL, document_root=... | l(r'^admin/', include(admin.site.urls)),
url(r'^social/', include('socialregistration.urls', namespace='socialregistration')),
)
)
|
iguration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
sys.path.insert(0, os.path.abspath('..'))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings')
import cachalot
# This sets up ... | a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xh | tml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'django-cachalotdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt',... |
from sqlalchemy import *
from migrate import *
from migrate.changeset import schema
pre_meta = MetaData()
post_meta = MetaData()
product = Table('product', pre_meta,
Column('id', INTEGER, primary_key=True, nullable=False),
Column('product_name', VARCHAR),
Column('bar_code', INTEGER),
Column('price', N... | lumn('picture_id', Integer),
)
def upgrade(migrate_engine):
# Upgrade operations go here. Don't create your own engine; bind
# migrate_engine to your metadata
pre_meta.bind = migrate_engine
post_meta.bind = migrate_engine
pre_meta.tables['product'].columns['supply'].drop()
post_meta.tables['pr... | te_engine):
# Operations to reverse the above upgrade go here.
pre_meta.bind = migrate_engine
post_meta.bind = migrate_engine
pre_meta.tables['product'].columns['supply'].create()
post_meta.tables['product'].columns['supply_id'].drop()
|
import pytest
import six
from mock import call, patch
from tests import utils
from week_parser.base import parse_row, parse_week, populate_extra_data
from week_parser.main import PrettyPrinter
def test_populate_extra_data_no_days():
"""
If we haven't found any days data, there is not extra data to add
""... | assert week_data == {'mon': {'day': 'mon', 'value': 3}}
assert mock_populate.call_args_list == [call(week_data, '__DESCRIPTION__')]
def test_parse_row_day_range():
"""
If the input row contains a day range, it is outputted
"""
row = {'mon-wed': '3', 'description': '__DESCRIPTION__'}
w | ith patch('week_parser.base.populate_extra_data') as mock_populate:
week_data = parse_row(row)
assert week_data == {
'mon': {'day': 'mon', 'value': 3},
'tue': {'day': 'tue', 'value': 3},
'wed': {'day': 'wed', 'value': 3},
}
assert mock_populate.call_args_list == [call(week_d... |
pedescr = dtype
valid_filemodes = ["r", "c", "r+", "w+"]
writeable_filemodes = ["r+", "w+"]
mode_equivalents = {
"readonly":"r",
"copyonwrite":"c",
"readwrite":"r+",
"write":"w+"
}
@set_module('numpy')
class memmap(ndarray):
"""Create a memory-map to an array stored in a *binary* file on disk... | eading only. | |
+------+-------------------------------------------------------------+
| 'r+' | Open existing file for reading and writing. |
+------+-------------------------------------------------------------+
| 'w+' | Create or overwrite existing file for reading a... |
documentation build configuration file, created by
# sphinx-quickstart on Fri Nov 5 15:13:45 2010.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default... | odule name will be prepended to all description
# unit titles (such as .. function::).
#add_modu | le_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefi... |
def main(request, response):
headers = {
# CORS-safelisted
"content-type": "text/plain",
"c | ache-control": "no cache",
"content-language": "en",
"expires": "Fri, 30 Oct 1998 14:19:41 GMT",
"last-modified": "Tue, 15 Nov 1994 12:45:26 GMT",
"pragma": "no-cache",
| # Non-CORS-safelisted
"x-test": "foobar",
"Access-Control-Allow-Origin": "*"
}
for header in headers:
response.headers.set(header, headers[header])
response.content = "PASS: Cross-domain access allowed."
|
#!/usr/bin/env python
# Copyright 2019 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.
"""
Unit tests for the contents of cpu_temperature.py
"""
# pylint: disable=unused-argument
import logging
import unittest
from devil... | self.assertFalse(c.IsSupported())
class CpuTemperatureLetCpuCoolToTemperatureTest(CpuTemperatureTest):
# Return values for the mock side effect
cooling_down0 = (
[45000
for _ in range(8)] + [43000
for _ in range(8)] + [41000 for _ in range(8)])
@mock.patch('time.sle... | s(self):
self.mock_device.ReadFile = mock.Mock(side_effect=self.cooling_down0)
self.cpu_temp.LetCpuCoolToTemperature(42)
self.mock_device.ReadFile.assert_called()
self.assertEquals(self.mock_device.ReadFile.call_count, 24)
cooling_down1 = [45000 for _ in range(8)] + [41000 for _ in range(16)]
@moc... |
#coding:utf- | 8
#################################
#Copyright(c) 2014 dtysky
#################################
import G2R
class ScSp(G2R.SpSyntax):
def Show(self,Flag,Attrs,US,UT,Tmp,FS):
sw=''
name,Attrs=self.Check(Flag,Attrs,UT,FS)
if Attrs['k']=='Main':
sw+=' $ store.chapter='
sw+="'Chapter."+Attrs['cp']+Attrs['sc... | n"
return sw |
##
# Copyright 2012-2017 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (F... | e 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 v2.
#
# EasyBuild is distributed in the hope that it will b | e 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 EasyBuild. If not, see <http://www.gnu.org/license... |
# Copyright 2016 Twitter. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | integ_const.MAX_EXECUTIONS)
assert isinstance(self.max_executions, int) and self.max_executions > 0
Log.info("Max executions: %d" % self.max_executions)
self.tuples_to_complete = 0
self.user_spout.initialize(config, context)
@staticmethod
def _load_user_spout(pex_file, classpath):
pex_loader.l... | _get_class(pex_file, classpath)
return cls
@property
def is_done(self):
return self.max_executions == 0
def next_tuple(self):
if self.is_done:
return
self.max_executions -= 1
Log.info("max executions: %d" % self.max_executions)
self.user_spout.next_tuple()
if self.is_done:
... |
from django.db import models
from cms.models import CMSPlugin
CLASS_CHOICES = ['container', 'content', 'teaser']
CLASS_CHOICES = tuple((entry, entry) for entry in CLASS_CHOICES)
TAG_CHOICES = [
'div', 'article', 'section', 'header', 'footer', 'aside',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
]
TAG_CHOICES = tuple... | choices=CLASS_CHOICES,
default=CLASS_CHO | ICES[0][0],
blank=True,
max_length=255,
)
additional_classes = models.CharField(
verbose_name='Additional classes',
blank=True,
max_length=255,
)
def __str__(self):
return self.label or self.tag_type or str(self.pk)
def get_short_description(self):
... |
"""
The GeometryColumns and SpatialRefSys models for the PostGIS backend.
"""
from django.db import models
from django.contrib.gis.db.backends.base import SpatialRefSysMixin
class GeometryColumns(models.Model):
"""
The 'geometry_columns' table from the PostGIS. See the PostGIS
documentation at Ch. 4.2.2.
... | field (SRID: %d)" % \
(self.f_table_name, self.f_geometry_column,
| self.coord_dimension, self.type, self.srid)
class SpatialRefSys(models.Model, SpatialRefSysMixin):
"""
The 'spatial_ref_sys' table from PostGIS. See the PostGIS
documentaiton at Ch. 4.2.1.
"""
srid = models.IntegerField(primary_key=True)
auth_name = models.CharField(max_length=256)... |
__source__ = 'https:/ | /leetcode.com/problems/valid-anagram/description/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/valid-anagram.py
# Time: O(n)
# Space: O(1)
#
# Description: Leetcode # 242. Valid Anagram
#
# Given two strings s and t, write a function to
# determi | ne if t is an anagram of s.
#
# For example,
# s = "anagram", t = "nagaram", return true.
# s = "rat", t = "car", return false.
#
# Note:
# You may assume the string contains only lowercase alphabets.
#
# Companies
# Amazon Uber Yelp
# Related Topics
# Hash Table Sort
# Similar Questions
# Group Anagrams Palindrome Per... |
from typing import Dict
from unittest import mock
from conductor.accounts.forms import DeactivateForm, SignupForm
from conductor.tests import TestCase
class TestSignupForm(TestCase):
def test_valid(self) -> None:
product_plan = self.ProductPlanFactory.create()
data = {
"username": "ma... | tal_code(self, stripe_gateway | : mock.MagicMock) -> None:
product_plan = self.ProductPlanFactory.create()
stripe_gateway.create_customer.return_value = "cus_1234"
data = {
"username": "matt",
"email": "matt@test.com",
"password": "asecrettoeverybody",
"stripe_token": "tok_1234",... |
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'pasportaservo',
'USER': 'guillaume',
}
}
LANGUAGE_CODE = 'en'
INSTALLED_APPS = (
'grappelli',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'dja... | .messages',
'django.contrib.staticfiles',
'django_extensions',
'django_countries',
'phonenumber_field',
'bootstrapform',
'leaflet',
'postman',
'hosting',
'pages',
'debug_toolbar',
)
EMAIL_BACKEND = 'django.core.m | ail.backends.console.EmailBackend'
|
#
# Newfies-Dialer License
# http://www.newfies-dialer.org
#
# 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/.
#
# Copyright (C) | 2011-2013 Star2Billing S.L.
#
# The Initial Developer of the Original Code is
# Arezqui Belaid <info@star2billing.com>
#
import newfies
from django.conf import settings
def newfies_version(request):
ret | urn {'newfies_version': newfies.__version__, 'SURVEYDEV': settings.SURVEYDEV}
|
from shutit_module import ShutItModule
import base64
class openshift_airflow(ShutItModule):
def build(self, shutit):
shutit.send('cd /tmp/openshift_vm')
shutit.login(command='vagrant ssh')
shutit.login(command='sudo su -',password='vagrant',note='Become root (there is a problem logging in as admin with the vag... | }
}
},
{
"type": "ConfigChange"
}
],
"replicas": 1,
"selector": {
"name":"airflow"
},
"template": {
"metadata": {
"labels": {
"name": "airflow"
}
},
... | "name": "airflow",
"image": "airflow",
"ports": [
{
"containerPort": 8080,
"protocol": "TCP"
}
],
"resources": {},
"terminationMessagePath": "/dev/termination-log... |
from tkinter import *
from gui import GUI
from reminder import Reminder
import argparse
import time
if __name__ == '__main__':
print("""
Copyright (C) 2016 Logvinov Dima.
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it
under certain cond... | reminder app for ElementaryOS.")
parser.add_argument('--add', help="Add new event.\n"
"$ pyreminder --add 'Event text:Event time hours.minutes.day.month.year'", type=str)
parser.add_argument('--list', help="Print list of eve | nts.", action="store_true")
parser.add_argument('--delete', help="Delete event.\n "
"$ pyreminder --delete event_id ", type=int)
parser.add_argument('--gui', help="Run gui program.", action="store_true")
args = parser.parse_args()
reminder = Reminder()
if a... |
ut (2a): ::
doing a slow thing... done
Output (2b): ::
doing a slow thing... ERROR
<stack trace>
:param quiet: True to skip the message altogether
"""
def __init__(self, msg,
sameline=True,
quiet=False,
file=sys.stderr):
... | ns_output(dpack, predicted, filename):
"""
Write predictions to an output file whose format
is documented in :doc:`../output`
"""
links = {}
for edu1, edu2, label in predicted:
links[(edu1, edu2)] = label
def mk_row(edu1, edu2):
'return a list of columns'
edu1_id = e... | d
edu2_id = edu2.id
row = [edu1_id,
edu2_id,
links.get((edu1_id, edu2_id), UNRELATED)]
return [x.encode('utf-8') for x in row]
with open(filename, 'wb') as fout:
writer = csv.writer(fout, dialect=csv.excel_tab)
# by convention the zeroth edu is ... |
def printMap(the_map,note):
print(note)
for row in the_map:
row_str = ""
for cell in row:
row_str += " {0:3d}".format(cell)
print(row_str)
def pathFinder(x, y, the_map, steps, lastX, lastY, wall):
# count possible moves
debug = False
options ... | print(" looking at ({0:2d},{1:2d}) with value={2:2d} and with steps:{3:3d} {4:6} from ({5:2d},{6:2d})".format(newX,newY,the_map[newY][newX],steps,wall,x,y))
# if statements
if the_map[newY][newX] == 0:
the_map[newY][newX] = steps
if newX != 0 or newY != 0:
... | the_map, steps, lastX, lastY, wall)
elif the_map[newY][newX] > 1 and steps <= the_map[newY][newX]:
the_map[newY][newX] = steps
if newX != 0 or newY != 0:
pathFinder(newX, newY, the_map, steps, lastX, lastY, wall)
elif ( the_map[newY][newX] == 1 or the_map[ne... |
# -*- coding: utf-8 -*-
# Copyright (C) 2010 by RoboLab - University of Extremadura
#
# This file is part of RoboComp
#
# RoboComp 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... | elf.leftPyrList)):
xPos = xPos + (self.wdth/2)/(2**level)
yPos = yPos - self.hght/(2**level)
qimage = QImage(self.leftPyrList[level], self.wdth/(2**level), self.hght/(2**level), QImage.Format_RGB888);
painter.drawImage(QPointF(xPos, yPos), qimage)
qimage = QImage(self.rightPyrList[level], self.wdth/(2**l... | inter = None
|
'find', 'find_one', 'find_one_and_delete',
'find_one_and_replace', 'find_one_and_update',
'update_one', 'update_many', 'replace_one',
'delete_one', 'delete_many',
'create_index', 'create_indexes', 'reindex',
'index_information', 'list_indexes',
'drop', 'drop_ind... | _pre_save(self):
for name, field in self._fields.items():
value = field.pre_save_val(self._data.get(name))
if value:
setattr(self, name, value)
if not field.required and name in self._data \
and self._data[name] is None:
del... | self):
filter_ = {}
if self._ensure_id():
filter_['_id'] = self._data['_id']
for name in self.unique_fields:
value = self._data.get(name)
if value:
filter_[name] = value
return filter_
def _upsert_update(self, filter_, null=False):... |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # The AI Platform services require regional API endpoints.
client_options = {"api_endpoint": api_endpoint}
# Initialize client that will be used to create and send requests.
# This client only needs to be created once, and can be reused for multiple requests.
client = aiplatform.gapic.JobServiceClient(c... | _id
)
response = client.cancel_data_labeling_job(name=name)
print("response:", response)
# [END aiplatform_cancel_data_labeling_job_sample]
|
from pybrain.tools.shortcuts import buildNetwork
from pybrain.datasets import SupervisedDataSet
from pybrain.supervised.trainers import BackpropTrainer
import copy
from PIL import Image
import os
import random
import time
import math
imagesize = (120, 120)
peak = 100
gusti = ["margherita", "crudo", "funghi", "salame"... | print("Training set for gusto: %s (%s)" % (gusto, ",".join(map(str, getSwitchTuple(indice, inputs)))))
for pizzaname in pizzaset:
pizza = "./pizze/" + gusto + "/" + pizzaname
print(" Training with %s" % pizza, end=" ")
ds.addSample(getSwitchTuple(indice, inputs, disturb=ra... | iform(-0.3, 0.3)), processImg(pizza))
print("done")
return ds
def outimage(outtuple, name):
img = Image.new('RGB', imagesize, "white")
pixels = img.load()
for i in range(img.size[0]):
for j in range(img.size[1]):
tup_index = (i*img.size[0] + j) * 3
pixels[i,j... |
from allauth.socialaccount.providers.base import AuthAction, ProviderAccount
from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
class Scope(object):
ACCESS = 'read-only'
clas | s YNABAccount(ProviderAccount):
pass
class YNABProvider(OAuth2Provider):
id = 'ynab'
name = 'YNAB'
account_class = YNABAccount
def get_default_scope(self):
scope = [Scope.ACCESS]
return scope
def get_auth_params(self, request, action):
ret = super(YNABProvider, self).... | return ret
def extract_uid(self, data):
return str(data['data']['user']['id'])
provider_classes = [YNABProvider]
|
import sys
from healthcareai.common.healthcareai_error import HealthcareAIError
def validate_pyodbc_is_loaded(): |
""" Simple check that alerts user if they are do not have pyodbc installed, which is not a requirement. """
if 'pyodbc' not in sys.modules:
raise HealthcareAIError('Using this function requires installation of pyodbc.')
def validate_sqlite3_is_loaded():
""" Simple check that alerts user if they a... | which is not a requirement. """
if 'sqlite3' not in sys.modules:
raise HealthcareAIError('Using this function requires installation of sqlite3.')
|
"""
Test basic DataFrame functionality.
"""
import pandas as pd
import pytest
import weld.grizzly as gr
def get_frames(cls, strings):
"""
Returns two DataFrames for testing binary operators.
The DataFrames have columns of overlapping/different names, types, etc.
"""
df1 = pd.DataFrame({
... | n.
df1 = gr.GrizzlyDataFrame({
'age': [20, 30, 35, 20, 50, 35],
'score': [20.0, 30.0, 35.0, 50 | .0, 35.0, 25.0]
})
df2 = gr.GrizzlyDataFrame({
'age': [20, 30, 35, 20, 50, 35],
'scores': [20.0, 30.0, 35.0, 50.0, 35.0, 25.0]
})
df3 = (df1 + df2) * df2 + df1 / df2
assert not df3.is_value
df3.evaluate()
assert df3.is_value
weld_value = df3.weld_value
df3.eva... |
3 = 1.7
n1 = 2.1
n2 = 1.3
b = DMatrix([n1])
Ai = [ blkdiag([n3,-n3])]
C = blkdiag([n2,-n2])
A = vertcat(Ai)
dsp = DSDPSolver(C.sparsity(),A.sparsity())
dsp.init()
dsp.input("c").set(C)
dsp.input("b").set(b)
dsp.input("a").set(A)
dsp.evaluate()
self.checkarr... |
# x1 >=0
#
# solution: x0=1, x1=0
b = DMatrix([2,3])
Ai = [ blkdiag([1,1,0]), blkdiag([1,0,1])]
C = blkdiag([1,0,0])
A = vertcat(Ai)
dsp = DSDPSolver(C.sparsity(),A.sparsity())
dsp.init()
dsp.input("c").set(C)
dsp.input("b").set(b)
... | rray(dsp.output("primal_cost"),DMatrix(2),digits=5)
self.checkarray(dsp.output("dual_cost"),DMatrix(2),digits=5)
self.checkarray(dsp.output("primal"),DMatrix([1,0]),digits=5)
self.checkarray(dsp.output("p"),DMatrix([[0,0,0],[0,1,0],[0,0,0]]),digits=5)
self.checkarray(dsp.output("dual"),DMatrix([[2,... |
#! /usr/bin/env python
class ParserError(Exception):
pass
class Sentence(object):
def __init__(self, subject, verb, object):
# remember we take ('noun', 'princess') tuples and convert them
self.subject = subject[1]
self.verb = verb[1]
self.object = object[1]
def get_sente... | d_list, 'direction')
else:
raise ParserError("Expected a noun or direction next.")
def parse_sub | ject(word_list, subj):
verb = parse_verb(word_list)
obj = parse_object(word_list)
return Sentence(subj, verb, obj)
def parse_sentence(word_list):
skip(word_list, 'stop')
start = peek(word_list)
if start == 'noun':
subj = match(word_list, 'noun')
return parse_subject(word_lis... |
from grslra import testdata
from grslra.grslra_batch import grslra_batch, slra_by_factorization
from grslra.structures import Hankel
from grslra.scaling import Scaling
import numpy as np
import time
# The goal of this experiment is to identify an LTI system from a noisy outlier-contaminated and subsampled observation ... | ling=scaling)
t_grslra = time | .time() - t_start
if PROFILE:
profile.disable()
profile.dump_stats("grslra.bin")
print "error GRSLRA: ", np.linalg.norm(l_grslra - x_0) / np.linalg.norm(x_0)
print "time GRSLRA: ", t_grslra
if PROFILE:
profile = cProfile.Profile()
profile.enable()
t_start = time.time()
l_slrabyF = slra_by_factorizat... |
"""LaTeX Exporter class"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
from traitlets import Unicode, default
from traitlets.config import Config
from nbconvert.filters.highlight import Highlight2Latex
from nbconvert.filters.filter_links import reso... | for x in super(LatexExporter, self).default_filters():
yield x
yield ('resolve_references', resolve_references)
@property
def default_config(self):
c = Config({
'NbConvertBase': {
'dis | play_data_priority' : ['text/latex', 'application/pdf', 'image/png', 'image/jpeg', 'image/svg+xml', 'text/markdown', 'text/plain']
},
'ExtractOutputPreprocessor': {
'enabled':True
},
'SVG2PDFPreprocessor': {
'enabled':Tru... |
R_ID, 'BGP')
self.ryu_bgp_driver = ryu_driver.RyuBgpDriver(cfg.CONF.BGP)
mock_ryu_speaker_p = mock.patch.object(bgpspeaker, 'BGPSpeaker')
self.mock_ryu_speaker = mock_ryu_speaker_p.start()
def test_add_new_bgp_speaker(self):
self.ryu_bgp_driver.add_bgp_speaker(FAKE_LOCAL_AS1)
... | FAKE_AUTH_TYPE,
FAKE_PEER_PASSWORD)
speaker = self.ryu_bgp_driver.cache.get_bgp_speaker(FAKE_LOCAL_AS1)
speaker.neighbor_add.assert_called_once_with(
address=FAKE_PEER_IP,
... | password=FAKE_PEER_PASSWORD,
connect_mode=CONNECT_MODE_ACTIVE)
def test_remove_bgp_peer(self):
self.ryu_bgp_driver.add_bgp_speaker(FAKE_LOCAL_AS1)
self.assertEqual(1,
self.ryu_bgp_driver.cache.get_hosted... |
els import *
import isisdata.tasks as dtasks
import curation.taskslib.citation_tasks as ctasks
import curation.taskslib.authority_tasks as atasks
from isisdata.filters import CitationFilter
import json
# TODO: refactor these actions to use bulk apply methods and then explicitly
# trigger search indexing (or whatever ... | task.save()
return task.id
class SetRecordStatus(BaseAction):
model = Citation
label = u'Set record status'
default_value_field = forms.ChoiceField
default_value_field_kwargs = {
'choices': CuratedMixin.STATUS_CHOICES,
'label': 'Set record status',
'widget': forms.w... | s': 'action-value'}),
}
def apply(self, user, filter_params_raw, value, **extra):
# We need this to exist first so that we can keep it up to date as the
# group of tasks is executed.
task = AsyncTask.objects.create()
type = extra['object_type'] if extra['object_type'] else Non... |
elf, slave, event_name):
"""Acknowledge a slave's message"""
self.send(slave, 'ack {}'.format(event_name))
def monitor_shutdown(self, slave):
# non-daemon so slaves get every opportunity to shut down cleanly
shutdown_thread = Thread(target=self._monitor_shutdown_t,
... | e = int(poll_num_sec - (time() - start_time))
self.print_message(
'{} still shutting down, '
'will continue polling for {} seconds '
.format(slaveid, remaining_time), blue=True)
| sleep(poll_sleep_time)
# start the poll
for poll in sleep_and_poll():
ec = process.poll()
if ec is None:
continue
else:
if ec == 0:
self.print_message('{} exited'.format(slaveid), green=True)
... |
array=numpy.sqrt(stararray['e1']*stararray['e1']+stararray['e2']*stararray['e2'])
emagautocorr=numpy.zeros((starlen*(starlen-1))/2)
edistautocorr=numpy.zeros((starlen*(starlen-1))/2)
iterator=0
# I'm sure there's a better way to do this.
for i in range(len(emagarray)):
for j in range(i+... | tropy polynomial values for all the objects.
|
bincenters, gamma1vals, binerrs, gamma1errs = \
make_scatter_inputs(gal_g1arr, gal_e1corr, (-0.02,0.03), 10)
bincenters2, gamma2vals, binerrs2, gamma2errs = \
make_scatter_inputs(gal_g2arr, gal_e2corr, (-0.02,0.03), 10)
pylab.subplot(232,axisbg='w')
pylab.errorbar(x=... |
isatty():
RED = "\x1B[31m"
GREEN = "\x1B[32m"
NORM = "\x1B[39m"
else:
RED = ""
GREEN = ""
NORM = ""
class VethNetworkConfig(object):
def __init__(self, portCount):
self.caddr = "127.0.0.1"
self.cport = randomports(1)[0]
self.switchInterfaces = ["veth%d" % (i*2) for i... | AILED'
sys.stdout.write(RED + "FAIL" + NORM + "\n" | )
print "Test logs in %s" % testLogDir
if self.abat:
self.abat.updateTestcase(testName, result)
self.updateResultXml(testName, result, testLogDir)
return result
def updateResultXml(self, testName, result, logDir):
self.results.append((testName, result, log... |
std::string name) [member function]
cls.add_method('LookupByName',
'ns3::TypeId',
[param('std::string', 'name')],
is_static=True)
## type-id.h (module 'core'): ns3::Ptr<ns3::TraceSourceAccessor const> ns3::TypeId::LookupTraceSourceByName(std::string na... | ): ns3::TypeId::TraceSourceInformation::TraceSourceInformation(ns3::TypeId::TraceSourceInformation const & arg0) [copy constructor]
cls.add_constructor([param('ns3::TypeId::TraceSourceInformation const &', 'arg0')])
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::accessor [variable]
cls.a... | tribute('accessor', 'ns3::Ptr< ns3::TraceSourceAccessor const >', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::help [variable]
cls.add_instance_attribute('help', 'std::string', is_const=False)
## type-id.h (module 'core'): ns3::TypeId::TraceSourceInformation::name [vari... |
earDown()
self.post_draft.delete()
self.post_published.delete()
def test_list_published_posts(self):
"""
Test API list all published blog posts
"""
url = reverse('blogpost-list')
response = self.client.get(url, format='json')
self.assertEqual(respons... | th2 as a superuser
" | ""
original_title = Post.objects.get(pk=self.post_published.pk).title
original_content = Pos |
from typing import (
Any,
List,
)
from pcs import resource
from pcs.cli.common.parse_args import InputModifiers
from pcs.cli.common.routing import (
CliCmdInterface,
create_router,
)
def resource_defaults_cmd(parent_cmd: List[str]) -> CliCmdInterface:
def _get_router(
lib: Any, argv: List... | er(lib, argv, modifiers)
return _get_router
def resource_op_defaults_cmd(parent_cmd: List[str]) -> CliCmdInterface:
def _get_router(
lib: Any, argv: List[str], modifiers: InputModifiers
) -> None:
"""
Options:
* -f - CIB file
* --force - allow unknown options
... | command
return resource.resource_op_defaults_legacy_cmd(
lib, argv, modifiers, deprecated_syntax_used=True
)
router = create_router(
{
"config": resource.resource_op_defaults_config_cmd,
"set": create_router(
... |
#### PATTERN | EN ##################################################################################
# Copyright (c) 2010 University of Antwerp, Belgium
# Author: Tom De Smedt <tom@organisms.be>
# License: BSD (see LICENSE.txt for details).
# http://www.clips.ua.ac.be/pages/pattern
####################################... | import \
suggest as spelling
from parser import tokenize, parse, tag
from parser.tree import Text, Sentence, Slice, Chunk, PNPChunk, Chink, Word, table
from parser.tree import SLASH, WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA, AND, OR
from parser.modality import mood, INDICATIVE, IMPERATIVE, C... | r.modality import modality, EPISTEMIC
from parser.modality import negated
from parser.sentiment import sentiment, polarity, subjectivity, positive
from parser.sentiment import NOUN, VERB, ADJECTIVE, ADVERB
import wordnet
import wordlist
def parsetree(s, *args, **kwargs):
""" Returns a parsed Text from the given... |
"""
=============================
OOB Errors for Random Forests
=============================
The ``RandomForestClassifier`` is trained using *bootstrap aggregation*, where
each new tree is fit from a bootstrap sample of the training observations
:math:`z_i = (x_i, y_i)`. The *out-of-bag* (OOB) error is the average er... | _state=RANDOM_STATE)),
("RandomForestClassifier, max_features=None",
RandomForestClassifier(warm_start=True, max_features=None,
oob_score=True,
random_state=RANDOM_STATE))
]
# Map a classifier name to a list of (<n_estimators>, <error rate>) pai... | to explore.
min_estimators = 15
max_estimators = 175
for label, clf in ensemble_clfs:
for i in range(min_estimators, max_estimators + 1):
clf.set_params(n_estimators=i)
clf.fit(X, y)
# Record the OOB error for each `n_estimators=i` setting.
oob_error = 1 - clf.oob_score_
er... |
self.assertEqual(indices, offsets_2)
def test_iter_advanced(self):
"""test that pointers to other mappings are detected"""
matcher = haystack.reverse.matchers.PointerEnumerator(self._memory_handler)
self.pointerEnum1 = haystack.reverse.enumerators.WordAlignedEnumerator(self.mmap, matcher,... | r(self._memory_handler)
finder = self._memory_handler.get_heap_finder()
walkers = finder.list_heap_walkers()
heap_walker = walkers[0]
# create the enumerator on the allocated chunks mapping
enumerator2 = haystack.reverse.enumerators.AllocatedWordAlignedEnumerator(heap_walker, mat... | import cProfile, pstats, StringIO
pr = cProfile.Profile()
pr.enable()
# ... do something ...
heap_enum2 = enumerator2.search()
pr.disable()
s = StringIO.StringIO()
sortby = 'cumulative'
ps = pstats.Stats(pr, stream=s).sor... |
class hheap(dict):
@staticmethod
def _parent(i): # please use bit operation (same below)!
return (i-1)>>1
@staticmethod
def _left(i):
return (i<<1) + 1
@staticmethod
def _right(i):
return (i<<1) + 2
'''
Structure is the following
inside the heap we have a list
[position,value]
which means the dicti... | min = rightChild
else:
min = leftChild
if self.heap[index][1] > self.heap[min][1]:
self._swap(index,min)
if self.heap[index][1] == self.heap[min][1]:
if self.heap[index][2] > self.heap[min][2]:
self._swap(index,min)
return self.heapdown(min)
def _swap(self, i, j):
| """swap the contents b/w indices i and j; update hash accordingly"""
#swap within the heap
self.heap[i][0],self.heap[j][0] = j,i
self.heap[i],self.heap[j] = self.heap[j],self.heap[i]
def pop(self):
# pop root (best)
#display the soon to be popped item
popped = self.heap[0]
#remove from dict and h... |
import importlib
import os
import sys
here = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def get_version() -> str:
"""
Return version.
"""
sys.path.insert(0, here)
return importlib.import_module("a2wsgi").__version__
os.chdir(here)
os.system(f"poetry version {get_version()}")
os... | oml")
os.system(f'git commit -m "v{get_version()}"')
os.system("git push")
os.system("git tag v{0}".format(get_version()))
os.system("git p | ush --tags")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.