code stringlengths 1 199k |
|---|
from tests import util
class Tests(util.TestCase):
def test_import(self):
objid = self.load_fixture('/klassifikation/klasse',
'klasse_opret.json')
expected = {
"note": "Ny klasse",
"attributter": {
"klasseegenskaber": [
... |
import numpy as np
import yaml
from scipy.interpolate import SmoothBivariateSpline
from scipy.optimize import minimize
from scipy.special import gamma
from .threshold import fit_give
def to_eqPonA(width, length):
perimeter = (
np.pi / 2 *
(3*(width + length) - np.sqrt((3*width + length)*(3*length + ... |
"""
Show known Shuup settings and their values.
"""
from optparse import make_option
from django.core.management.base import BaseCommand
import shuup.utils.settings_doc
class Command(BaseCommand):
help = __doc__.strip()
option_list = BaseCommand.option_list + (
make_option(
'--only-changed',... |
from pyramid.view import view_config
from ..models import GameServer
from ..models import Game
@view_config(route_name='games',
renderer='games.mako',
permission='view')
def viewGames(request):
games = Game.getAll()
info = {'games': games}
return info
@view_config(route_name='game... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0015_eventsettings'),
]
operations = [
migrations.AddField(
model_name='eventsettings',
name='report_footer',
... |
import traceback
from django.core.management.base import BaseCommand
from editorsnotes.main.models import Note, Document, Topic
from ... import cendari_index
class Command(BaseCommand):
help = 'Rebuild elasticsearch index'
def handle(self, *args, **kwargs):
for model in [ Note, Document, Topic ]:
... |
'''**********************************************************************
Publite2 is a process manager which launches multiple Freeciv-web servers.
Copyright (C) 2009-2017 The Freeciv-web project
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero Gen... |
"""heck_site URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-ba... |
from bika.lims.content.analysis import Analysis
from bika.lims.testing import BIKA_FUNCTIONAL_TESTING
from bika.lims.tests.base import BikaFunctionalTestCase
from bika.lims.utils import tmpID
from bika.lims.utils.analysisrequest import create_analysisrequest
from bika.lims.workflow import doActionFor
from plone.app.tes... |
from SPARQLWrapper import SPARQLWrapper
q = """PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX opmv: <http://purl.org/net/opmv/ns#>
PREFIX prov: <http://www.w3.org/ns/prov#>
PREFIX dcterms: <http://purl.org/dc/terms/>
CONSTRUCT {
?e prov:wasGenerat... |
from __future__ import absolute_import
import datetime
import json
import re
from _sha512 import sha512
from collections import defaultdict
from io import StringIO
from urllib.parse import urlencode
from django.db import models
from dashboard.models.user import EPOCH
from dashboard.util import itertools
from dashboard.... |
from tastypie.serializers import Serializer
from tastypie.utils import format_datetime, make_naive
import datetime
class UTCSerializer(Serializer):
def format_datetime(self, data):
"""
A hook to control how datetimes are formatted.
Can be overridden at the ``Serializer`` level (``datetime_formatting``)
or glob... |
{
'name': 'Website Sale Product Sort',
'summary': 'Allow to define default sort criteria for e-commerce',
'version': '12.0.1.0.0',
'development_status': 'Beta',
'category': 'Website',
'website': 'https://github.com/OCA/e-commerce',
'author': 'Tecnativa, Odoo Community Association (OCA)',
... |
from __future__ import unicode_literals
from flask import current_app
from udata.forms import ModelForm, fields, validators
from udata.i18n import lazy_gettext as _
from udata.models import User
from .models import AVATAR_SIZES
__all__ = (
'UserProfileForm', 'UserSettingsForm', 'UserAPIKeyForm',
'UserNotificati... |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('catalog', '0018_merge_20171022_1608'),
]
operations = [
migrations.RemoveField(
model_name='design',
name='price',
),
] |
from odoo import models, api, fields
from odoo.tools.translate import _
from odoo.exceptions import UserError
from odoo.addons.l10n_it_fatturapa.bindings import fatturapa
def get_invoice_obj(fatturapa_attachment):
xml_string = fatturapa_attachment.get_xml_string()
return fatturapa.CreateFromDocument(xml_string)... |
import pytest
import rtorshlib.rtorsh
import os
@pytest.fixture
def shell():
myshell = rtorshlib.rtorsh.RtorrentShell(os.environ['RTORRENT_URL'], os.environ['RTORRENT_USER'],
os.environ['RTORRENT_PASSWORD'])
return myshell
def test_check_hash_len_short():
with pytest.raise... |
from django.conf import settings
from datetime import datetime
if getattr(settings, 'DATA_ARCHIVE_ENABLED', False):
# Only do this if data archival is enabled
import pymongo
# Ensure there is a connection to MongoDB
connection = pymongo.Connection(
settings.DATA_ARCHIVE_HOST,
settings.DATA_ARCHIVE_PORT
... |
{
'name': 'Prices Visible Discounts',
'version': '1.0',
'author': 'OpenERP SA',
'category': 'Sales Management',
'website': 'https://www.tunierp.com',
'description': """
This module lets you calculate discounts on Sale Order lines and Invoice lines base on the partner's pricelist.
===============... |
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
urlpatterns = patterns(
'application.views',
url(r'^start/$', 'account.login', name='apply-start'),
url(r'^login/$', 'account.login', name='apply-login'),
url(r'^logout/$', 'account.logout', name='apply-lo... |
import re
from coalib.bears.LocalBear import LocalBear
from coalib.results.Diff import Diff
from coalib.results.Result import Result
from coalib.results.RESULT_SEVERITY import RESULT_SEVERITY
class MatlabIndentationBear(LocalBear):
LANGUAGES = {"Matlab", "Octave"}
AUTHORS = {'The coala developers'}
AUTHORS_... |
from . import course
from . import attendee
from . import session |
from random import shuffle
import sys, os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir, 'common')))
import memcached_workload_common
from vcoptparse import *
op = memcached_workload_common.option_parser_for_memcache()
del op["mclib"] # No longer optional; we only work with me... |
import os
import re
import sys
import json
import subprocess as sp
def norm_ts(ts):
m = re.match(r'^(\d+)\/(\d+)\/(\d+) (\d+):(\d+):(\d+)', ts)
if not m:
return ts
ye = int(m.group(3))
mo = int(m.group(1))
da = int(m.group(2))
HO = int(m.group(4))
MI = int(m.group(5))
SE = int(m.group(6))
v = "{:0... |
from odoo import api, fields, models
class MedicalPharmacy(models.Model):
_inherit = 'medical.pharmacy'
is_verified = fields.Boolean(
help='Check this to indicate that this doctor is a verified entity',
)
verified_by_id = fields.Many2one(
string='Verified By',
comodel_name='res.u... |
{
"name": "Missing Operation",
"version": "8.0.1.1.0",
"author": "PT. Simetri Sinergi Indonesia,OpenSynergy Indonesia",
"website": "https://simetri-sinergi.id",
"category": "Stock Management",
"depends": [
"stock_warehouse_technical_information",
"stock_operation_type_location",
... |
from .symbtr import SymbTrReader
class MusicXMLReader(SymbTrReader):
@classmethod
def read(cls, score_file, symbtr_name=None):
"""
Reader method for the SymbTr-MusicXML scores. This method is not
implemented yet.
Parameters
----------
score_file : str
... |
from archetypes.schemaextender.interfaces import IOrderableSchemaExtender
from archetypes.schemaextender.interfaces import ISchemaModifier
from bika.wine import bikaMessageFactory as _
from bika.lims.fields import *
from bika.lims.browser.widgets import DateTimeWidget as bikaDateTimeWidget
from bika.lims.browser.widget... |
from .image_coding import ImageCodingXBlock |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0009_auto_20210512_0217'),
]
operations = [
migrations.AddField(
model_name='savedimage',
name='external_id',
field=models.UUIDField(default=None, un... |
import re
EDX_TRACK_EVENT_LOG = '/Users/leducni/Documents/DATA/COURS/logs-anon.txt'
DEST_DIR = '/Users/leducni/Documents/DATA/COURS/MOOCDB/'
MIN_DURATION_SECONDS = 10
MAX_DURATION_SECONDS = 3600
DEFAULT_DURATION_SECONDS = 100
INPUT_SOURCE = 'json'
QUOTECHAR = "'"
TIMESTAMP_FORMAT = '%Y-%m-%dT%H:%M:%S.%f'
RESOURCE_HIERA... |
"""
main.py - Main Program to :
1. get from outbox,
2. sent sms via modem
3. insert to sentitems
"""
import smsweb
sw = smsweb.SmsWeb()
sw.opendb()
sw.openser()
sw.moveInboxtodb()
dt=sw.getInbox()
while dt:
text = dt["text"].split('#')
if (len(text) > 1) and (len(text[0]) < 20):
sw.insertCommands(dt["number"],dt["t... |
import unittest
import epidb_client
from epidb_client import EpiDBClient
from epidb_client.tests import config
class LiveProfileUpdateTestCase(unittest.TestCase):
def setUp(self):
self.client = EpiDBClient(config.api_key)
self.client.server = config.server
self.data = {'user_id': config.user... |
from django.apps import AppConfig
from django.db.models.signals import pre_migrate, post_migrate
from .utils import create_index_table, reindex_content
def create_index(sender, **kwargs):
if (kwargs['using'] == 'transient' and isinstance(sender, SearchConfig)):
create_index_table(force=True)
def reindex(sen... |
import logging
import superdesk
from datetime import timedelta
from superdesk.utc import utcnow
from superdesk.notification import push_notification
from superdesk.errors import ProviderError
from superdesk.stats import stats
logger = logging.getLogger(__name__)
class RemoveExpiredContent(superdesk.Command):
"""Rem... |
from openerp.osv import fields, osv
class clv_medicament_dispensation_mng(osv.osv):
_inherit = 'clv_medicament_dispensation_mng'
_columns = {
'prescriber_id': fields.many2one('clv_professional',
string='Prescriber', ),
} |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Submission.marks'
db.add_column(u'wtem_submission', 'marks',
self.gf('jsonfield.fields.JSONField'... |
"""
Copyright 2012-2015 OpenBroadcaster, Inc.
This file is part of OpenBroadcaster Player.
OpenBroadcaster Player is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your... |
import logging
from constants import exceptions
from objects import glob
class channel:
def __init__(self, name, description, publicRead, publicWrite, temp, hidden):
"""
Create a new chat channel object
:param name: channel name
:param description: channel description
:param publicRead: if True, this channel... |
from . import ir_actions
from . import ir_attachment
from . import ir_http
from . import ir_qweb
from . import website
from . import ir_ui_view
from . import res_company
from . import res_partner
from . import res_config_settings
from . import ir_model_fields
from . import ir_model
from . import res_users |
from essentia_test import *
class TestMinToTotal(TestCase):
def testEmpty(self):
self.assertComputeFails(MinToTotal(), [])
def testFlat(self):
self.assertAlmostEquals(MinToTotal()([1]*100), 0)
def testSingle(self):
self.assertAlmostEquals(MinToTotal()([1]), 0)
def testSimple(self... |
"""
This config file runs the simplest dev environment using sqlite, and db-based
sessions. Assumes structure:
/envroot/
/db # This is where it'll write the database file
/edx-platform # The location of this repo
/log # Where we're going to write log files
"""
from .common import *
import os... |
from . import sale |
import json
import logging
import sys
from functools import partial
from django.conf import settings
from django.contrib.auth.models import User
from django.core.cache import cache
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.http import Http404
from djang... |
from openerp import models, fields
class AccountPayment(models.Model):
_inherit = 'account.payment'
fiscal = fields.Selection([
('fiscal', 'Fiscal'),
('no_fiscal', 'No Fiscal')],
help='Marca de cheque no fiscal',
default='fiscal'
)
def create_check(self, check_type, opera... |
from cassandra_tests.porting import *
def testStaticColumns(cql, test_keyspace):
for force_flush in [True, False]:
with create_table(cql, test_keyspace, "(k int, p int, s int static, v int, PRIMARY KEY (k, p))") as table:
execute(cql, table, "INSERT INTO %s(k, s) VALUES (0, 42)")
if ... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('workshops', '0007_auto_20160502_1210'),
]
operations = [
migrations.AddField(
model_name='workshop',
name='requirements',
... |
"""test deprecated module
"""
__revision__ = 0
if __revision__:
import Bastion
print(Bastion)
# false positive (#10061)
import stringfile
print(stringfile) |
import wx
from wx import xrc
from .base import ModuleBase, bind
class PayloadModule(ModuleBase):
def __init__(self, system):
self._system = system
self.title = 'Payload'
self.grid_pos = (0, 3)
self.grid_span = (1, 2)
def load(self, res, parent):
self._panel = res.LoadPane... |
"""Account info tests."""
from magicicadaprotocol import request
from twisted.internet import defer
from magicicada.filesync import services
from magicicada.filesync.models import StorageUser
from magicicada.server.testing.testcase import TestWithDatabase
class QuotaTest(TestWithDatabase):
"""Test account and quota... |
from openerp import models, api, fields
class ResCompany(models.Model):
_inherit = 'res.company'
code = fields.Char(string=u'公司代號', help='') |
from django.core.management.base import BaseCommand
from moderation_queue.models import QueuedImage
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
"--delete",
action="store_true",
help=("Delete moderation queue items with no image"),
... |
def post_init_hook(cr, registry):
""" Fill unrevisioned name of all existent purchases """
query = """
UPDATE purchase_order SET unrevisioned_name=name
WHERE unrevisioned_name IS NULL;
"""
cr.execute(query) |
{
'!langcode!': 'fr',
'!langname!': 'Français',
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" est une expression optionnelle comme "champ1=\'nouvellevaleur\'". Vous ne pouvez mettre à jour ou supprimer les résultats d\'un JOIN',
'%s %%{row}... |
class SaHpiError(Exception):
"""This class represents an SA HPI error."""
def __init__(self, errno, error):
self.errno = errno
self.error = error
def __str__(self):
return '%s: %s' % (self.__class__.__name__, self.error)
def __repr__(self):
return '%s(%d,"%s")' % (self.__... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('machine', '0008_job_mcdrambw'),
]
operations = [
migrations.AddField(
model_name='job',
name='BlockAveBW',
field=mode... |
"""
/***************************************************************************
Name : create a mesh
Description : This plugin allows the user to create a mesh from a shapefile and view it in QGIS
Date : 11/Jul/12
copyright : (C) 2012 by Varun Verma
email : vv311... |
import sys, os, stat, fnmatch
from bup import options, git, shquote, vfs, ls
from bup.helpers import *
handle_ctrl_c()
class OptionError(Exception):
pass
def do_ls(cmd_args):
try:
ls.do_ls(cmd_args, pwd, onabort=OptionError)
except OptionError, e:
return
def write_to_file(inf, outf):
for... |
"""
Metadata about languages used by our model training code for our
SingleByteCharSetProbers. Could be used for other things in the future.
This code is based on the language metadata from the uchardet project.
"""
from string import ascii_letters
class Language:
"""Metadata about a language useful for training m... |
"""The diagram package contains items (to be drawn on the diagram), tools (used
for interacting with the diagram) and interfaces (used for adapting the
diagram).""" |
"""
Sample for python PCSC wrapper module: send a Control Code to a card or
reader
__author__ = "Ludovic Rousseau"
Copyright 2007-2010 Ludovic Rousseau
Author: Ludovic Rousseau, mailto:ludovic.rousseau@free.fr
This file is part of pyscard.
pyscard is free software; you can redistribute it and/or modify
it under the ter... |
"""JSON backend for Orca settings"""
__id__ = "$Id$"
__version__ = "$Revision$"
__date__ = "$Date$"
__copyright__ = "Copyright (c) 2010-2011 Consorcio Fernando de los Rios."
__license__ = "LGPL"
from json import load, dump
import os
from orca import settings, acss
class Backend:
def __init__(self, p... |
"""Feature test ensuring that MC deals correctly with EnsureChannel returning
a channel that has already been dispatched to a handler.
"""
import dbus
import dbus.service
from servicetest import (EventPattern, tp_name_prefix, tp_path_prefix,
call_async, assertContains, assertLength, assertEquals)
from mctest im... |
"""
Unit tests for the :func:`iris._cube_coord_common.get_valid_standard_name`.
"""
import iris.tests as tests
from iris._cube_coord_common import get_valid_standard_name
class Test(tests.IrisTest):
def setUp(self):
self.emsg = "'{}' is not a valid standard_name"
def test_valid_standard_name(self):
... |
import shutil
import theano, numpy
from ActivationFunction import Tanh
from Configs import Configs
from descentDirectionRule.Antigradient import Antigradient
from descentDirectionRule.CheckedDirection import CheckedDirection
from descentDirectionRule.CombinedGradients import CombinedGradients
from initialization.Consta... |
from .emol import EMOLRead
from .erxn import ERXNRead
from .ewrite import EMDLWrite
from .mol import MOLRead, common_isotopes
from .parser import CGRRead, parse_error
from .rxn import RXNRead
from .stereo import MDLStereo
from .rw import MDLRead
from .write import MDLWrite |
import gc
import sys
from UM.Job import Job
from UM.Application import Application
from UM.Mesh.MeshData import MeshData
from UM.View.GL.OpenGLContext import OpenGLContext
from UM.Message import Message
from UM.i18n import i18nCatalog
from UM.Logger import Logger
from UM.Math.Vector import Vector
from cura.Scene.BuildP... |
"""
The I{sxbuiltin} module provides classes that represent
XSD I{builtin} schema objects.
"""
from logging import getLogger
from suds import *
from suds.xsd import *
from suds.sax.date import *
from suds.xsd.sxbase import XBuiltin
import datetime as dt
log = getLogger(__name__)
class XString(XBuiltin):
"""
Rep... |
from paraview.simple import *
import glob
import re
opacityBaffles=0.6
opacityImpeller=1.0
opacityTank=0.2
liste = glob.glob('./post/VTK/mixer_*.vtk')
listeImpl = glob.glob('./post/VTK/impeller_*.stl')
listeTank = glob.glob('/home/bruno/doctorat/mesh/PBT_Manon/tank.stl')
listeBafflesB = glob.glob('/home/bruno/doctorat/... |
from . import main_model |
class DecoratorException(Exception):
pass
class ElementMappingException(Exception):
pass
class ReferenceException(Exception):
pass
class RequiredAttributeException(Exception):
pass
class ProhibitedAttributeException(Exception):
pass
class UnknownAttributeException(Exception):
pass
class UnknownE... |
import argparse
import sys
from ..io import import_from_yaml
from .wrappers import execute_bdd
def cli(args=None) -> int:
parser = argparse.ArgumentParser(
prog='sismic-bdd',
description='Command-line utility to execute Gherkin feature files using Behave.\n'
'Extra parameters will be passed ... |
"""
->PART OF PROJECT CODEX<-
Contains data for Spell classes and their methods.
"""
from constants import *
import pygame
import math
from object_classes import *
from soundC import *
class Spell(object): #Parent class
spells_casted = []
def __init__(self):
self.name = "Undefined_spell"
self.x, self.y = None, No... |
from openerp import SUPERUSER_ID, fields
from openerp.addons.web import http
from openerp.addons.web.http import request
import werkzeug
import time
from openerp.tools.translate import _
class WebsiteProposal(http.Controller):
def request_info(self):
wsgienv = request.httprequest.environ
return '<em... |
from unittest.mock import MagicMock, AsyncMock
import snappy
from sqlalchemy.sql.dml import Insert, Update
from ai.backend.manager.registry import AgentRegistry
from ai.backend.manager.models import AgentStatus
from ai.backend.common import msgpack
from ai.backend.common.types import ResourceSlot
async def test_handle_... |
"""New: added function that calculates concordance"""
def importTable(input_file_name, a_directory, lines_skip):
import os
# Set directory
old_dir = os.getcwd()
os.chdir(a_directory)
# Read data from input file and place in table
f = open(input_file_name, 'r')
# BACKUP f = open('test.txt', 'r')
f.readline() # r... |
import io
def image_to_bytesio(img):
"""Converts PIL.Image to io.BytesIO of a PNG."""
bytes_output = io.BytesIO()
img.save(bytes_output, format='PNG')
bytes_output = bytes_output.getvalue()
return bytes_output |
import os
import httplib2
import pprint
import datetime
import time
import logging
import watchdog
import watchdog.events
import sys
import webbrowser
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler
from watchdog.events import FileSystemEventHandler
from apiclient.discovery impor... |
from bitmovin.resources.models import BroadcastTsMuxing as BroadcastTsMuxingResource
from .generic_muxing_service import GenericMuxingService
class BroadcastTsMuxing(GenericMuxingService):
def __init__(self, http_client):
super().__init__(http_client=http_client, type_url='broadcast-ts', resource_class=Broa... |
from imagekit.specs import ImageSpec
from imagekit import processors
class ResizeThumb(processors.Resize):
width = 100
height = 75
crop = True
class ResizeDisplay(processors.Resize):
width = 600
class EnchanceThumb(processors.Adjustment):
contrast = 1.2
sharpness = 1.1
class Thumbnail(ImageSpec)... |
""" This application demonstrates the encryption and decryption of texts via using Vigenere cipher. """
class Cipher:
""" Uses Vigenere cipher with specified alphabet to convert text data into encrypted string and vice versa. """
def __init__(self, alphabet, key):
""" Constructs the Cipher instance with... |
from bitmovin.utils import Serializable
from . import AbstractInfrastructure
class KubernetesInfrastructure(AbstractInfrastructure, Serializable):
def __init__(self, name, description=None, online=None, connected=None, agent_deployment_download_url=None, id_=None, custom_data=None):
super().__init__(id_=id_... |
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=255, unique=True, db_index=True)
def __str__(self):
return self.name
class Concept(models.Model):
name = models.CharField(max_length=255, db_index=True)
def __str__(self):
return self.name
class... |
"""
Base exceptions.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
class AvaError(Exception):
"""
Raised when error is framework-related but no specific error exists.
"""
def __init__(self, *args, **kwargs):
super(AvaError, self).__init__(args, kwargs)
cl... |
def test_example(app, json_user):
user = json_user
app.login_admin()
app.get("http://localhost/litecart/admin/?app=settings&doc=security")
app.switch_captcha()
app.get("http://localhost/litecart/en/create_account")
app.litecard_helper.add_new(user)
app.litecard_helper.login(user) |
import os.path
import ssl
import tornado.ioloop
from tornado.options import define, options
import tornado.web
import router
define("port", default=8019, help="run on the given port", type=int)
define("debug", default=True, help="run in debug mode")
def main():
# router_ajax放在列表前面,保证优先获取规则
app = tornado.web.App... |
"""
Device for Zigbee Home Automation.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/zha/
"""
import asyncio
from datetime import timedelta
from enum import Enum
import logging
import time
from homeassistant.core import callback
from homeassistant.helpe... |
from threading import Timer
import pyupm_grove as grove
import pyupm_i2clcd as lcd
import pyupm_ttp223 as ttp
import spp as spp
PILL_BUTTON = 2
EMERGENCY_BUTTON = 3
ALERT_LED = 4
PILL_TIMER_LIMIT = 5 # in seconds
LCD_BACKGROUND_COLOR = (50, 50, 100) # in RGB decimal values
LCD_BACKGROUND_ALERT_COLOR = (255, 0, 0) ... |
import sys
def main ():
#Setting abs_min as minus infinity
abs_min= -float("inf")
#Setting abs_max as plus infinity
abs_max=float("inf")
#Uncomment to run as examples:
#tree_value="((4 (7 9 8) 8) (((3 6 4) 2 6) ((9 2 9) 4 7 (6 4 5))))"
#tree_value= "(((1 4) (3 (5 2 8 0) 7 (5 7 1)) (8 3)) (((3 6 4) 2 (9 3 0)) ((8... |
from google.cloud import domains_v1
async def sample_configure_management_settings():
# Create a client
client = domains_v1.DomainsAsyncClient()
# Initialize request argument(s)
request = domains_v1.ConfigureManagementSettingsRequest(
registration="registration_value",
)
# Make the reque... |
'''
Pickler test file
'''
import pickle
def main():
favourite_number = raw_input("Please enter your favourite number: ")
print 'Pickling to file /tmp/number.pickle'
pickle.dump(favourite_number, open("/tmp/number.pickle", "wb"))
print 'Extracting number from file'
unpickled_number = pickle.load(open... |
import pygame
from buffalo import utils
from buffalo.button import Button
from buffalo.label import Label
from buffalo.option import Option
from buffalo.scene import Scene
class MainMenu(Scene):
def __init__(self):
Scene.__init__(self)
self.labels.add(
Label(
(5, 5),
... |
__author__ = 'douglas'
from tkinter import *
from time import localtime
class Horas:
def __init__(self,raiz):
self.canvas=Canvas(raiz, width=200, height=100)
self.canvas.pack()
self.frame=Frame(raiz)
self.frame.pack()
self.altura = 100 # Altura do canvas
# Desenho do ... |
"""
sphinx.search.es
~~~~~~~~~~~~~~~~
Spanish search language: includes the JS Spanish stemmer.
:copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from typing import Dict
import snowballstemmer
from sphinx.search import SearchLanguage, parse_... |
import os
import sys
import socket
from pandajedi.jedicore import Interaction
from pandajedi.jedicore import JediCoreUtils
from pandajedi.jediconfig import jedi_config
from .WatchDogBase import WatchDogBase
class TypicalWatchDogBase(WatchDogBase):
# pre-action
def pre_action(self, tmpLog, vo, prodSourceLabel, p... |
class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[Interval]
"""
out = []
for i in sorted(intervals, key=lambda i: i... |
from . import benchmark
from . import schema
import logging
import os
_logger = logging.getLogger(__name__)
cmakeIndent = " "
def generateCMakeDecls(benchmarkObjs, sourceRootDir, supportedArchitecture):
"""
Returns a string containing CMake declarations
that declare the benchmarks in the list ``benchmarkObjs... |
from robot.libraries.BuiltIn import BuiltIn
try:
unicode = unicode
except NameError:
basestring = (str,bytes)
try:
basestring
except NameError:
basestring = str
class CustomLocator(object):
def __init__(self, name, finder):
self.name = name
self.finder = finder
def find(self, *ar... |
def f(x):
if x is None or not isinstance(x, int):
raise ValueError()
if x < 0:
raise ValueError()
if x < 10:
return x
total = 0
num = x
while True:
a, b = divmod(num, 10)
total += b
if a == 0:
break
else:
num = a
... |
import Leap, sys
from evdev import UInput, ecodes as e
class TestListener(Leap.Listener):
hand_id = 0
spread_win = False
curtime = 0
ui = None
def on_init(self, controller):
self.ui = UInput()
print "Initialized"
def on_connect(self, controller):
print "Connected"
def... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.