code
stringlengths
1
199k
""" InaSAFE Disaster risk assessment tool developed by AusAid and World Bank - **Impact function Test Cases.** .. note:: 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 t...
import sys from os.path import abspath, join, dirname def main(): port = int(sys.argv[1]) py_ver = sys.version_info[0] lib_name = abspath(join(dirname(__file__), 'subp-py%d' % py_ver)) sys.path.insert(0, lib_name) from dreampielib.subprocess import main as subprocess_main del sys.path[0] if ...
import csv from dateutil.parser import parse from adoptarbol.tree.models import Tree def load(filename): with open(filename, encoding='utf-8') as f: reader = csv.reader(f) header = next(reader) def pos_for(field): return header.index(field) def float_or_none(string): ...
""" * Partial implementation of standard atmospheric model as described in * GOST 4401-81 useful for processing of data from meteorological balloon * sensors. * * Supported modelling of temperature and pressure over the altitude span from * 0 up to 51km. * * algorithm by Oleg Kochetov <ok@noiselab.ru> """ from...
from gi.repository import Gtk, GLib, Gio, Pango try: from gi.repository import Secret except: Secret = None from gettext import gettext as _ from _thread import start_new_thread from lollypop.define import Lp, Type, SecretSchema, SecretAttributes from lollypop.utils import use_csd class Settings(Gio.Settings): ...
import urllib2 url = "http://ifolderlinks.ru/404" req = urllib2.Request(url) response = urllib2.urlopen(req,timeout=3) print response.info()
import gui gui.main()
import pytest import numpy as np import astropy.units as u from astropy.time import Time from .. import vdif from .. import mark4 from .. import mark5b from .. import dada from ..base.encoding import EIGHT_BIT_1_SIGMA from ..data import (SAMPLE_MARK4 as SAMPLE_M4, SAMPLE_MARK5B as SAMPLE_M5B, SAMPLE...
import pytest import httpretty import logging class callcounted(object): """Decorator to determine number of calls for a method""" def __init__(self,method): self.method=method self.counter=0 def __call__(self,*args,**kwargs): self.counter+=1 return self.method(*args,**kwargs...
"""Translation GUI $Id: translate.py 26889 2004-08-04 04:00:36Z pruggera $ """ __docformat__ = 'restructuredtext' from zope.app.i18n.browser import BaseView class Translate(BaseView): def getMessages(self): """Get messages""" filter = self.request.get('filter', '%') messages = [] for...
import read, edit, faulty, group, composed, optional
from numpy.distutils.core import setup, Extension setup( name = "Infer", version = "1.0", description='Python version of MCMC, plus other inference codes under development', author='Neale Gibson', author_email='ngibson@eso.org', packages=['Infer'], package_dir={'Infer':'src'}, #and extension package for s...
from __future__ import absolute_import import re class RegexLib(object): """ A class containing all regular expressions used throughout the DataHound application. """ # Class Members # Potentially better email regex # "([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})" # http://www.webmo...
""" Use this component to change the schedules of your HBZones. - Provided by Honeybee 0.0.57 Args: _HBZones: HBZones for which you want to change shcedules. occupancySchedule_: A text string representing the occupancy shceudle that you want to use. This can be either a shcedule from the schedule l...
import json from ansible.module_utils._text import to_text from ansible.module_utils.basic import env_fallback, return_values from ansible.module_utils.network.common.utils import to_list, ComplexList from ansible.module_utils.connection import Connection, ConnectionError _DEVICE_CONFIGS = {} ios_provider_spec = { ...
''' Created on 26/09/2014 @author: javgar119 ''' cluster_list =([Cluster(set([]), 0, 0, 1, 0), Cluster(set([]), 1, 0, 1, 0)]) cluster_list2 = ([Cluster(set([]), 0, 0, 1, 0), Cluster(set([]), 1, 0, 1, 0), Cluster(set([]), 2, 0, 1, 0), ...
from .util.deb import deb from .util.nrange import nrange from .cell import Cell from .grid import spoint CURSOR_POS=None def gcp(): #get cursor position global CURSOR_POS deb('gcp',CURSOR_POS) return CURSOR_POS def scp(x,y): deb('scp',gcp(),x,y) cxc=0 #todo, normalize in cursor... global CURSOR_POS CURSOR_POS=(...
""" Copyright 2013 Giacomo Antolini <giacomo.antolini@gmail.com>. This file is part of flocca_dot_com. flocca_dot_com 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 Lic...
""" Program do gry w Blackjack (a.k.a. Oczko) w języku Python przy użyciu biblioteki PyGame Projekt zaliczeniowy - Języki Skryptowe, Informatyka i Ekonometria, rok 1, WZ, AGH Autorzy: Joanna Jeziorek, Mateusz Koziestański, Katarzyna Maciocha III 2016 """ import random as rd import os import sys import pygame from pygam...
from chiplotle.geometry.core.path import Path from chiplotle.geometry.core.coordinate import Coordinate from chiplotle.core import errors from py.test import raises def test_path_add_01( ): '''A Path and an int cannot be added.''' assert raises(TypeError, 'Path([(1, 2), (3, 4)]) + 3') def test_path_add_02( ): ...
__author__ = 'hkar' import Vault.Crypto import Vault.Key from test_helpers import * import os def test_aes(tmpdir): # make tmp text files f = create_test_file(tmpdir) text = str(f.read()) # define file names file_in = str(f) file_out = file_in + ".enc" # generate random secret secret = g...
import datetime import thread, time, ast, sys, re import socket, traceback import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, Gdk, GObject, cairo from decimal import Decimal from electrum.util import print_error, InvalidPassword from electrum.bitcoin import is_valid, COIN from electrum.wallet imp...
from PIL import Image class Channel: def __init__(self, channelLabel, size): self.channelLabel = channelLabel self.channel = Image.new("CMYK", (size[0], size[1]), "black") self.pixelMap = self.channel.load() def save(self, filename): self.channel.save(filename)
from gi.repository import GObject from gi.repository import GLib from coverart_widgets import AbstractView class ListShowingPolicy(GObject.Object): ''' Policy that mostly takes care of how and when things should be showed on the view that makes use of the `AlbumsModel`. ''' def __init__(self, list_v...
import tempfile import unittest from list import TodoTxtList class TestTodoTxtList(unittest.TestCase): def test_init_from_text(self): todo_text = "(A) Item one\n(Z) Item two\nx Item three\n\n \n" test_list = TodoTxtList(None, todo_text) self.assertEqual(3, test_list.num_items()) self...
def sort_by_length(arr): return sorted(arr, key=len)
from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('article', '0006_article_owner'), ] operations = [ migrations.RenameField( model_name='article', old_name='owner', new_name='o...
import time from tentacle_pi.AM2315 import AM2315 am = AM2315(0x5c, "/dev/i2c-1") for x in range(10): temperature, humidity, crc_check = am.sense() print "Temperature: %s" % temperature print "Humidity: %s" % humidity print "CRC: %s" % crc_check time.sleep(2)
from __future__ import unicode_literals import os from io import BytesIO from flask import flash, redirect, request, session from PIL import Image from werkzeug.exceptions import NotFound from indico.core.db import db from indico.modules.events.layout import layout_settings, logger from indico.modules.events.layout.for...
import numpy as np import pyparticles.pset.boundary as bd class ReboundBoundary( bd.Boundary ): def __init__( self , bound=(-1,1) , dim=3 ): self.set_boundary( bound , dim ) self.set_normals() def set_normals( self ): self.__N = np.zeros( ( 2*self.dim , self.dim ) ) #print( self....
import frappe, os, json from frappe.utils import cstr from unidecode import unidecode from six import iteritems def create_charts(company, chart_template=None, existing_company=None): chart = get_chart(chart_template, existing_company) if chart: accounts = [] def _import_accounts(children, parent, root_type, root...
import datetime from collections import namedtuple import os import tempfile import time import uuid import random import stat from textwrap import dedent import pytest from GangaCore.Utility.logging import getLogger from GangaDirac.Lib.Utilities.DiracUtilities import execute from GangaCore.testlib.mark import external...
from __future__ import absolute_import import datetime from django.db import models from django.db.models import get_model from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import User from django.conf import settings from django.u...
import cgi, json argsDict = cgi.FieldStorage() EMPTY_DICT = {} def getState (init = False): dataDict = getDataDict () if dataDict is None \ and init is True: (key, uri) = generateTOTP () generateQR (key, uri) dataDict = newDataDict (key, uri) setDataDict (dataDict) devDic...
from common import common_global from common import common_pagination_bootstrap from sanic import Blueprint blueprint_user_metadata_game_system = Blueprint('name_blueprint_user_metadata_game_system', url_prefix='/user') @blueprint_user_metadata_game_system.route('/user_me...
import sys, os import time extensions = ['sphinx.ext.autodoc', 'sphinx.ext.mathjax', 'sphinx.ext.viewcode', 'sphinx.ext.autosummary', 'sphinx.ext.intersphinx', 'sphinx.ext.extlinks', 'matplotlib.sphinxext.plot_directive',] templates_pat...
from vsg.token import primary_unit_declaration as token from vsg.vhdlFile import utils def detect(iToken, lObjects): ''' primary_unit_declaration ::= identifier; ''' return classify(iToken, lObjects) def classify(iToken, lObjects): iCurrent = iToken while not utils.is_next_token(';', iCurrent, l...
import urlparse def uc2utf8(input): ## argh! this feels wrong, but seems to be needed. if type(input) == unicode: return input.encode('utf-8') else: return input class URL: """ This class is for wrapping URLs into objects. It's used internally in the library, end users should n...
"""Test class for Subscriptions :Requirement: Subscription :CaseAutomation: Automated :CaseLevel: Acceptance :CaseComponent: CLI :TestType: Functional :CaseImportance: High :Upstream: No """ import tempfile import csv import os from robottelo import manifests from robottelo.cli.activationkey import ActivationKey from r...
import logging from time import strftime def closed(): logging.info('Headlights process stopped') def criterr(errortext): logging.critical('A fatal error occured :: ' + errortext) exit() def err(errortext): logging.error('An error occured :: ' + errortext) def warn(errortext): logging.warning(errort...
""" Display a simple window with a message. """ import os import sys from _common import gettext as _ from gi.repository import Gtk class MessageWindow(Gtk.Window): """Display a simple window with a message.""" def __init__(self, text, title="Epoptes", markup=True, icon_name="dialog-information...
""" $Id: test_adapter.py 67630 2006-04-27 00:54:03Z jim $ """ import unittest from zope.testing.doctestunit import DocTestSuite def test_suite(): return unittest.TestSuite(( DocTestSuite('zope.security.adapter'), )) if __name__ == '__main__': unittest.main(defaultTest='test_suite')
class Recombination_Parameters(object): # Change these two values to the folders you prefer - use an absolute path e.g. /Users/Harry/fastq-data and # /Users/Harry/csv-data or a path relative to the tools directory. # You may use the same folder for input and output. input_folder = "data" output_fold...
import unittest as ut import espressomd import numpy as np from espressomd.magnetostatics import * from tests_common import * class MagnetostaticsInteractionsTests(ut.TestCase): # Handle to espresso system system = espressomd.System() def setUp(self): self.system.box_l = 10, 10, 10 if not se...
from __future__ import unicode_literals import frappe, copy import os import json from frappe.utils import cstr, flt, getdate from frappe import _ from frappe.utils.file_manager import save_file from .default_website import website_maker import install_fixtures from .sample_data import make_sample_data from erpnext.acc...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = """ --- module: cron short_description: Manage cron.d and crontab entries descr...
import unittest from ..temp import * __author__ = 'Christopher Blunck' __email__ = 'chris@wxnet.org' __revision__ = '$Revision: 1.6 $' __doc__ = ''' Unit tests the temp module. ''' __usage__ = ''' python $0 ''' def usage(): print(__usage__) sys.exit(1) class TestCase(unittest.TestCase): def setUp(self): p...
from enum import Enum from Adafruit_MotorHAT import Adafruit_MotorHAT, Adafruit_DCMotor import time import atexit Direction = Enum('Forward','Reverse','Spin','Left','Right','None') class Wheels: def __init__(self): self.lc = 100 #Loop count self.ld = .02 #Loop delay self.mh = Adafruit_MotorH...
""" project and subproject adding """ from Acquisition import aq_inner from Products.CMFCore.utils import getToolByName from Products.Five.browser.pagetemplatefile import ZopeTwoPageTemplateFile from opencore.browser.formhandler import OctopoLite, action from opencore.i18n import _ from opencore.interfaces import IHome...
import os import sys from distutils.core import setup from distutils.command.install import install VERSION_NUMBER = "1.6.3" class CustomInstall(install): def run(self): install.run(self) for script in self.distribution.scripts: script_path = os.path.join(self.install_scripts, ...
import Adafruit_BBIO.PWM as PWM class Servo: def __init__(self, pin): self.servo_pin = pin self.duty_min = 3 self.duty_max = 14.5 self.duty_span = self.duty_max - self.duty_min def StartServo(self): print("Starting servo") print(self.servo_pin) PWM.start(self.servo_pin, (100 - self.duty_min), 60.0, 1) ...
"""A utility that tries saved genetic tests and removes those failing""" import asyncio import yaml from pathlib import Path from logzero import logger from rizza import entity_tester from rizza import genetic_tester def genetic_prune(conf, entity='All'): """Check all saved genetic_tester tests for an entity, prune...
DD_SAVE_DIR = 'home/pi/' DD_TIME_FORMAT = '%H:%S-%d-%m-%Y' MOUNT_DIR = '/mnt' FC_SAVE_DIR = '/home/pi/' FC_TIME_FORMAT = '%S:%H-%d-%m-%Y' POP_INDEX = 1 DEBUG = 0 PLANT_LOAD_DIR = '/home/pi/pruebas/' PLANT_SAVE_DIR = '/'
from setuptools import setup setup( name='geovalidation.server', version='0.5', long_description="Flask-based server to validate GIS datasets (with prepair and val3dity).", packages=['geovalidation'], include_package_data=True, zip_safe=False, install_requires=[ 'Flask>=1.1' ,'Jinja2>=...
import os import sys import urllib from gi.repository import Clutter, ClutterX11, Mx, Lomo, GObject, GLib class Cover(Clutter.Box): __gtype_name__ = 'GlosseCover' # # Member, setter and getter for the 'lomo' property # def _get_lomo_player_prop(self): return self._lomo_player_prop def _set_lomo_player_prop(self...
""" DragonPy - base memory info ~~~~~~~~~~~~~~~~~~~~~~~~~~~ :created: 2013 by Jens Diemer - www.jensdiemer.de :copyleft: 2013 by the MC6809 team, see AUTHORS for more details. :license: GNU GPL v3 or above, see LICENSE for more details. """ import sys class BaseMemoryInfo: def __init__(self, out...
"""Test class for Medium CLI""" from ddt import ddt from fauxfactory import gen_string, gen_alphanumeric from robottelo.cli.factory import CLIFactoryError from robottelo.test import CLITestCase from robottelo.common.decorators import data, run_only_on from robottelo.cli.factory import make_medium, make_os from robotte...
import os import json import re from BeautifulSoup import BeautifulSoup from psrd.rules import write_rules from psrd.files import char_replace from psrd.universal import parse_universal, print_struct from psrd.sections import ability_pass, is_anonymous_section, has_subsections, entity_pass, quote_pass def core_structur...
import numpy as np import matplotlib.pyplot as plt performance = [10.3882388499416,1,10.3212281215746] variance = [0.790435196936213,0,0.827207394592818] scripts = ['string_subst_1.py', 'string_subst_2.py', 'string_subst_3.py'] x_pos = np.arange(len(scripts)) plt.bar(x_pos, performance, yerr=variance, align='center', a...
"""Bootstrap a buildout-based project Simply run this script in a directory containing a buildout.cfg. The script accepts buildout command-line options, so you can use the -c option to specify an alternate configuration file. """ import os, shutil, sys, tempfile, urllib, urllib2, subprocess from optparse import OptionP...
from __future__ import absolute_import from django.utils.translation import ugettext_lazy as _ from documents.permissions import PERMISSION_DOCUMENT_TYPE_EDIT from .permissions import (PERMISSION_METADATA_DOCUMENT_EDIT, PERMISSION_METADATA_DOCUMENT_ADD, PERMISSION_METADATA_DOCUMENT_REMOVE, PERMISSION_METADATA_D...
r""" ================================================== Feature computation for univariate time series ================================================== This sub-module provides routines for computing features on univariate time series. Many functions are improved version of PyEEG [PYEEG]_ functions. Be careful, some ...
""" pytest fixtures """ import pytest from django.contrib.auth.models import User from orb.models import Category, Tag, UserProfile from orb.peers.models import Peer from orb.resources.tests.factory import resource_factory pytestmark = pytest.mark.django_db @pytest.fixture def testing_user(): user, _ = User.objects...
execfile('curves.py') x = variety() x0,x1,x2 = sp.var('x0,x1,x2') x.varlist = [x0,x1,x2] x.func = x0*x0 + x1*x2 - x1*x0 x.points = [[1,1,0], [2,1,-2]] cnumcurve(x) x.points = [[1,1,0], [2,1,-2], [0,0,0]] cnumcurve(x) x.points = [[1,1,0], [2,1,-2], [1,1,1]] cnumcurve(x) execfile('surfaces.py') x = variety() x0,x1,x2,x3 ...
""" leap/email/imap/tests/__init__.py ---------------------------------- Module intialization file for leap.mx.tests, a module containing unittesting code, using twisted.trial, for testing leap_mx. @authors: Kali Kaneko, <kali@leap.se> @license: GPLv3, see included LICENSE file @copyright: © 2013 Kali Kaneko, see COPYL...
class Solution(object): def distributeCandies(self, candies): """ :type candies: List[int] :rtype: int """ result = 0 kind = list(set(candies)) if len(kind) > len(candies)/2: result = len(candies)/2 else: result = len(kind) ...
"""Utility modules used throughout the rest of the codebase. Note that these modules should in general not depend (at compile time) on any other modules, to avoid cyclic dependencies. They could be imported (at the top level) into any other module so should not have any top-level imports from other modules. """
import operator class Targets: ALL_TARGETS = map(lambda x: 2 ** x , range(7)) (DESKTOP_474_GCC, DESKTOP_480_DEFAULT, SIMULATOR, EMBEDDED_LINUX, DESKTOP_521_DEFAULT, DESKTOP_531_DEFAULT, DESKTOP_541_GCC) = ALL_TARGETS @staticmethod def desktopTargetClasses(): desktop...
class Information: def __init__(self, objectid, cvid, information_type_id, description): self.objectid = objectid self.cvid = cvid self.information_type_id = information_type_id self.description = description self.deleted = 0
import argparse import sys from soma import aims import highres_cortex.cortex_topo def fix_cortex_topology_files(input_filename, output_filename, filling_size, fclosing): """Call highres_cortex.cortex_topo.fix_cortex_topology on files.""" input_volume = aims.read(input_filename) ...
import os import struct def makeTag(text): if len(text) != 4: raise Exception('Invalid text size {0}'.format(len(text))) return struct.unpack('>L', text)[0] def tagToString(tag): return struct.pack('>L', tag) class Stream: def readByte(self): return struct.unpack('B', self.read(1))[0] def readSByte(self): re...
""" ================================================= Draw a Quantile-Quantile Plot and Confidence Band ================================================= This is an example of drawing a quantile-quantile plot with a confidence level (CL) band. """ print __doc__ import ROOT from rootpy.interactive import wait from rootp...
import os root_name = __path__[0] csadmin_dirs = ['/csadmin/local', '/csadmin/common'] script_get_os = 'scripts/get_compat_os.share' get_os = None for d in csadmin_dirs: aux_get_os = os.path.join(d, script_get_os) if os.path.exists(aux_get_os): get_os = aux_get_os break if get_os is not None: compat_plat ...
"""54. Poker hands https://projecteuler.net/problem=54 In the card game poker, a hand consists of five cards and are ranked, from lowest to highest, in the following way: * **High Card** : Highest value card. * **One Pair** : Two cards of the same value. * **Two Pairs** : Two different pairs. * **Three of a Kin...
import sys def gcd(a, b): if b== 0: return a return gcd(b, a%b) def lcm(a, b): return (a* (b/gcd(a, b))) def load(): while(1): line = next(sys.stdin).split() line = [int(x) for x in line] line.pop(-1) if len(line) == 0: break yield(line) for (sequence) in load(): n = len(sequence) diff = list() fo...
from WellBehavedPython.api import * from WellBehavedPython.Engine.TestCase import TestCase from WellBehavedPython.Discovery.ModuleExaminer import ModuleExaminer class ModuleExaminerTests(TestCase): def test_examiner_can_find__only_class_in_simple_module(self): # Where examiner = ModuleExaminer('Well...
""" @file VelocityOverTime.py @author Sascha Krieg @author Daniel Krajzewicz @author Michael Behrisch @date 2008-05-29 Shows the velocityCurve of the chosen taxi for all available sources, thereby the time duration per Edge is apparent. SUMO, Simulation of Urban MObility; see http://sumo.sourceforge.net/ Copyr...
import abc from typing import Optional, Callable from math import fabs import itertools from copy import copy import numbers from array import array from .space2d import Point2D, Segment2D from ...orientations.orientations import * from ...mathematics.statistics import * from ...mathematics.quaternions import * from .....
import gtk from gtk import gdk import gobject from draw import draw_text from color import alpha_color_hex_to_cairo class NoteBook(gtk.Container): def __init__(self): gtk.Container.__init__(self) self.__init_values() def __init_values(self): self.add_events(gtk.gdk.ALL_EVENTS_MASK) ...
class AgendaWizardDialogResources(object): RID_AGENDAWIZARDDIALOG_START = 5000 RID_AGENDAWIZARDROADMAP_START = 5049 RID_COMMON_START = 500 SECTION_ITEMS = "AGENDA_ITEMS" SECTION_TOPICS = "AGENDA_TOPICS" SECTION_MINUTES_ALL = "MINUTES_ALL" SECTION_MINUTES = "MINUTES" def __init__(self, oW...
__author__ = "Rajiv Mayani" from time import localtime, strftime from sqlalchemy.orm.exc import NoResultFound from Pegasus.tools import utils from Pegasus.plots_stats import utils as stats_utils from Pegasus.db.workflow import stampede_statistics from Pegasus.service.dashboard import queries class NoWorkflowsFoundError...
import selenium from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities import time import urlparse,urllib2,urllib,re,xbmcplugin,xbmcgui,xbmcaddon,xbmc import os, sys from core import logger from core import config from core import scrapertools from core.item import...
import sys, os import locale import getopt import codecs import zipfile from cStringIO import StringIO import xml.sax import shutil import traceback def get_filename(authors_list, sequence_name, sequence_number, title): '''Форматы: 1 - "полные имена авторов, разделенные запятой - название (серия #номер)" 2 ...
''' Created on 01.12.2016 @author: michael ''' from alex_test_utils import MODE_SIMPLE from alexandriabase import baseinjectorkeys from alexandriabase.domain import Event, AlexDateRange, AlexDate, Document, \ DocumentType from alexpresenters.MessageBroker import REQ_SAVE_CURRENT_EVENT, \ REQ_SAVE_CURRENT_DOCUME...
from django import template import sys register = template.Library() @register.filter def get(dictionary, key): return dictionary.get(key) @register.filter def pertinent_values(dictionary, key): limit = '10' if ',' in key: key, limit = key.split(',') keys = dictionary.keys() total = reduce(l...
class LazyProxy(object): def __init__(self, original_module, original_class, init_args): self._original_module = original_module self._original_class = original_class self._original_init_args = init_args self._instance = None def __getattr__(self, name): if self._instance...
def boolean(value): return isinstance(value, bool) def integer(value): return isinstance(value, int) def module_id(value): return True
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: openbsd_pkg author: "Patrik Lundin (@eest)" version_added: "1.1...
from scrapelib import HTTPError from openstates.utils import LXMLMixin from pupa.scrape import Person, Scraper class UTPersonScraper(Scraper, LXMLMixin): def scrape(self): PARTIES = {"R": "Republican", "D": "Democratic"} representative_url = "http://house.utah.gov/rep/{}" senator_url = "http...
from django.conf.urls import url from . import views urlpatterns = [ # Captures special abbreviations and redirects to UOS websites url(r"^(?P<site>bb|udc|ms|uos)/?$", views.redirect_to_uos), # All website related requests link to views.layout # as the layout loads other dependencies as per request ...
from NfaBuilder import NfaBuilder def enum(**enums): return type('Enum', (), enums) nodeTypes = enum(CHARACTER = 1, STAR = 2, QUESTION = 3, ALTER = 4, CONCAT = 5, PLUS = 6) specialTransitions = enum(EPSILON = -1) class ParseError( Exception ): pass class ParseNode(): """ Represents a node in the resulted bi...
import os, sys, platform import subprocess, shlex, shutil import commands import locale import pwd, grp from gi.repository import Gtk import ConfigParser class cssi(): def __init__(self, user=None): self.user = user self.win = None self.grid = None self.CalendarDir="/usr/local/...
""" Plugins allow flexible modification and execution of OpenNFT without touching the core codebase. Plugins can access data, process them in a specific way, and they can be switched on and off according to the user's need. Each plugin has to be a subclass of *Process class specified in pyniexp.mlplugins. It has to con...
import urllib2 import logger log = logger.get_logger() def send_query(json_blurb, api_key): """ Send HTTP POST request containing the JSON-formatted Atlas query. If successful, Atlas' API should return the JSON-formatted measurement ID. """ url = "https://atlas.ripe.net/api/v1/measurement/?key=" + a...
import copy import logging import threading import time from xml.etree import ElementTree from PyQt5 import QtWidgets import gremlin import gremlin.ui.common import gremlin.ui.input_item class DoubleTapContainerWidget(gremlin.ui.input_item.AbstractContainerWidget): """DoubleTap container for actions for double or s...
from gi.repository import Gtk import os import shutil import gettext from cloudsn.core import config, provider, account, indicator, keyring from cloudsn import logger import cloudsn.core.utils as coreutils STOP_RESPONSE = 1 class MainWindow: __default = None def __init__ (self): if MainWindow.__default:...
""" This progam (as part of SHEAR) searches adapter sequences and generates an adapter file for use with SHEAR/Scythe. """ import sys import os import argparse import re import gzip _LICENSE = """ SHEAR: Simple Handler for Error and Adapter Removal James B. Pease http://www.github.com/jbpease/shear This file is part of...
""" Set-up script to install PyFAST locally """ from setuptools import setup setup(name='pyfast', version='0.1', description='Tools for working with wind turbine simulator FAST', url='https://github.com/jennirinker/PyFAST.git', author='Jenni Rinker', author_email='jennifer.m.rinker@gmail.c...
""" This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ...
import unittest """993. Cousins in Binary Tree https://leetcode.com/problems/cousins-in-binary-tree/description/ In a binary tree, the root node is at depth `0`, and children of each depth `k` node are at depth `k+1`. Two nodes of a binary tree are _cousins_ if they have the same depth, but have **different parents**. ...