code stringlengths 1 199k |
|---|
from __future__ import absolute_import, unicode_literals, print_function
import cProfile
from datetime import datetime
import re
import os
import codecs
import timeit
import pymorphy
from pymorphy.contrib.tokenizers import extract_words
DICT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__),
... |
import calendar
import datetime
import platform
import time
import os
import ssl
import socket
import urllib
import urlparse
import warnings
import shippo
from shippo import error, http_client, version, util, certificate_blacklist
def _encode_datetime(dttime):
if dttime.tzinfo and dttime.tzinfo.utcoffset(dttime) is... |
import functools
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
fr... |
from src.settings import Colors
def league_color(league: str) -> Colors:
if league in [
]:
return Colors.GREEN
if league in [
'1 CFL (Montenegro)',
'A Lyga (Lithuania)',
'Bikar (Iceland)',
'Coupe de la Ligue (France)',
'EURO Qualifiers (Europe)',
'FA C... |
import platform
from .clipboard import Clipboard
__version__ = '1.0.0'
def get_clipboard(handle=None):
system = platform.system().lower()
if 'windows' == system:
from . import win_clipboard
clip = win_clipboard.WinClipboard(handle)
elif 'darwin' == system:
raise NotImplementedError("... |
from collections import namedtuple
from cairo import LINE_JOIN_ROUND
from zorro.di import di, dependency, has_dependencies
from tilenol.groups import GroupManager
from tilenol.commands import CommandDispatcher
from .base import Widget
from tilenol.theme import Theme
from tilenol.window import Window
GroupState = namedt... |
"""
Trabalho T2 da disciplina Teoria dos Grafos, ministrada em 2014/02
'All Hail Gabe Newell'
Alunos:
Daniel Nobusada 344443
Thales Eduardo Adair Menato 407976
Jorge Augusto Bernardo 407844
"""
import networkx as nx
import numpy as... |
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRe... |
from .test_mocks import *
from .cpython.testmock import *
from .cpython.testwith import * |
import torch
from torch.distributions.kl import kl_divergence
from ..distributions import Delta, MultivariateNormal
from ..lazy import MatmulLazyTensor, SumLazyTensor
from ..utils.errors import CachingError
from ..utils.memoize import pop_from_cache_ignore_args
from .delta_variational_distribution import DeltaVariation... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Bien',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, ... |
from flask.ext.restful import Resource, reqparse
class Test(Resource):
def __init__(self):
self.parser = reqparse.RequestParser()
self.parser.add_argument('id', type=int)
super(AccountAPI, self).__init__()
def get(self):
return {'id': id}
def post(self):
pass
def ... |
"""
Helper functions used in views.
"""
from json import dumps
from functools import wraps
from flask import Response
def jsonify(function):
"""
Creates a response with the JSON representation of wrapped function result.
"""
@wraps(function)
def inner(*args, **kwargs):
return Response(dumps(... |
"""Unit tests for Pool and PoolSpecifier"""
import sys
try:
import unittest2 as unittest
except ImportError:
import unittest
try:
from unittest import mock
except ImportError:
import mock
from batchapps.pool import (
Pool,
PoolSpecifier)
from batchapps.api import (
BatchAppsApi,
Response... |
def AND(x1, x2):
w1, w2, theta = 0.5, 0.5, 0.7
tmp = x1 * w1 + x2 * w2
if tmp <= theta:
print(0)
elif tmp > theta:
print(1)
AND(0, 0)
AND(1, 0)
AND(0, 1)
AND(1, 1) |
def get_plist_text(cf_bundler_identifier, cf_bundle_name=None,
docset_platform_family=None):
"""TODO"""
cf_bundle_name = cf_bundle_name or cf_bundler_identifier.upper()
docset_platform_family = docset_platform_family or cf_bundle_name.upper()
return """
<?xml version="1.0" encoding="UTF-8"?>
... |
"""
test_envcheckr
----------------------------------
Tests for `envcheckr` module.
"""
import pytest
from envcheckr import envcheckr
def test_parse_lines():
lines_a = envcheckr.parse_lines('tests/env')
assert len(lines_a) == 3
lines_b = envcheckr.parse_lines('tests/env.example')
assert len(lines_b) == ... |
from django.template import Library
from django.conf import settings
if "django.contrib.sites" in settings.INSTALLED_APPS:
from django.contrib.sites.models import Site
current_domain = lambda: Site.objects.get_current().domain
elif getattr(settings, "SITE_DOMAIN", None):
current_domain = lambda: settings.SI... |
from django.db import models
class Salary(models.Model):
id = models.AutoField(primary_key = True)
bh = models.CharField(max_length = 10)
xm = models.CharField(max_length = 12)
status = models.CharField(max_length = 8)
class Meta:
db_table = 'swan_salary'
def __str__(self):
retur... |
import pyaudiogame
from pyaudiogame import storage
spk = pyaudiogame.speak
MyApp = pyaudiogame.App("Pizza Please")
storage.screen = ["start"]
storage.toppings = ["cheese", "olives", "mushrooms", "Pepperoni", "french fries"]
storage.your_toppings = ["cheese"]
storage.did_run = False
def is_number(number, topping_list):
... |
from exterminate.Utilities import builtins
_range = range
def alt_range(start, stop, step=1):
return _range(start-2, stop+2, max(1, int(step/2)))
builtins.range = alt_range |
from collections import OrderedDict
class DataSet(object):
__slots__ = (
'events', # List of all events in this data set
'group', # Iterable containing groups of events
)
def __init__(self, query, group_function):
self.events = query.all()
if group_function is None:
... |
import logging
from datetime import datetime
from core import app
from sqlalchemy import inspect
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
class Show(db.Model):
show_id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
link = db.Column(db.String(255))
count... |
import unittest
from .connected_graph import Node
class TestConnectedGraph(unittest.TestCase):
def test_acyclic_graph(self):
"""Example graph from https://upload.wikimedia.org/wikipedia/commons/0/03/Directed_acyclic_graph_2.svg"""
n9 = Node(9)
n10 = Node(10)
n8 = Node(8, [n9])
... |
import _plotly_utils.basevalidators
class LocationssrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(self, plotly_name="locationssrc", parent_name="choropleth", **kwargs):
super(LocationssrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_nam... |
"""
Test for: command line arguments
"""
from nose.tools import eq_, assert_raises
from m2bk import app, config, const
import os
def _get_arg_cfg_file_name(arg, filename):
try:
app.init_parsecmdline([arg, filename])
except FileNotFoundError:
pass
return config.get_config_file_name()
def test... |
import subprocess
import threading
import time
class OpenVPN():
def __init__(self, config_file=None, auth_file=None, timeout=10):
self.started = False
self.stopped = False
self.error = False
self.notifications = ""
self.auth_file = auth_file
self.config_file = config_... |
from cocosCairo.cocosCairo import * # Convenience module to import all other modules
from splash import *
BACKGROUND_COLOR = Color(0.1, 0.3, 0.7)
MAZE_PATHS = ["maze01.maze", "maze02.maze", "maze03.maze"] # an ordered list of the maze files
PATH_INDEX = 0 # the index of the next maze file to load
class MazeScene(Scene)... |
import re, csv, sys
from urlparse import urlparse
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.text import TextCollection
if len(sys.argv) < 2:
print "ERROR: arg1: must specify the input file"
print " arg2: specify -t to generate test ARFF"
sys.exit(1)
test... |
from typing import List
from django.utils.html import format_html, mark_safe
from haystack import indexes
from projects.models import Project, Nomination, Claim
class ProjectIndex(indexes.SearchIndex, indexes.Indexable):
"""Django-haystack index of Project model."""
name = indexes.CharField(model_attr='name', i... |
import math
import time
global x
x = time.clock() # seed for the PRNG
def prng():
global x
x = math.fmod((x + math.pi) ** 2.0, 1.0)
return x
def c(n, k):
if k == 0: return 1
if n == 0: return 0
return c(n - 1, k - 1) + c(n - 1, k)
n = 20 # number of bits in each trial
print 'Test in progress...'... |
from datetime import date
from . import GenericCalendarTest
from ..america import (
Argentina, Barbados, Chile, Colombia, Mexico, Panama, Paraguay
)
class ArgentinaTest(GenericCalendarTest):
cal_class = Argentina
def test_holidays_2018(self):
holidays = self.cal.holidays_set(2018)
# 1. Año N... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('deals', '0002_advertiser_logo'),
]
operations = [
migrations.RemoveField(
model_name='advertiser',
name='logo',
),
] |
from networkx import DiGraph
from networkx.readwrite import json_graph
import cantera as ct
import numpy as np
import json
import os
__author__ = 'Xiang Gao'
""" ----------------------------------------------
construction of the element flux graph
-----------------------------------------------"""
def build_flux_grap... |
import argparse
import datetime
import pathlib
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from mushroom_rl.algorithms.value import AveragedDQN, CategoricalDQN, DQN,\
DoubleDQN, MaxminDQN, DuelingDQN, NoisyDQN, Rainbow
from mushroom_rl.approximat... |
"""
WSGI config for django-example project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICAT... |
"""
@package ssw_wrap
@brief Simple python wrapper for SSW align library
To use the dynamic library libssw.so you may need to modify the LD_LIBRARY_PATH environment
variable to include the library directory (export LD_LIBRARY_PATH=$PWD) or for definitive
inclusion of the lib edit /etc/ld.so.conf and add the path or the... |
import os
import re
import string
from itertools import chain
from .detector_morse import Detector
from .detector_morse import slurp
import nlup
from pug.nlp.constant import DATA_PATH
from pug.nlp.util import generate_files
from pug.nlp.regex import CRE_TOKEN, RE_NONWORD
def list_ngrams(token_list, n=1, join=' '):
... |
from .base import *
SECRET_KEY = '!i%7s@1+v&293zcy*kljuke=_l176nqpj2-3dtms()pw^et!we'
DEBUG = True
ALLOWED_HOSTS = []
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
} |
""" """
from __future__ import unicode_literals, division, print_function, absolute_import
import argparse
import codecs
import sys
from sqlalchemy.engine import create_engine
from sqlalchemy.schema import MetaData
from sqlacodegen.codegen import CodeGenerator
import sqlacodegen
def main():
parser = argparse.Argume... |
import re
import string
import sys
sys.path.append('/Users/exu/PlayGround/readinglists/')
from key.keys import *
from amazon.api import AmazonAPI
from html2text import html2text
pattern = re.compile("https?://.*amazon.com/gp/product/([0-9]+)/.*")
amazon = AmazonAPI(AMAZON_ACCESS_KEY_ID, AMAZON_SECRET_ACCESS_KEY, AMAZON... |
from PyQt4 import QtCore
from PyQt4 import QtGui
from Action import Speech
from UI.ActionPushButton import ActionPushButton
class BaseStudy(QtGui.QWidget):
def __init__(self):
super(BaseStudy, self).__init__()
self._actionQueue = None
self._nao = None
self._widgets = None
sel... |
class CodeBlock:
"""Code fragment for the readable format.
"""
def __init__(self, head, codes):
self._head = '' if head == '' else head + ' '
self._codes = codes
def _to_str_list(self, indent_width=0):
codes = []
codes.append(' ' * indent_width + self._head + '{')
... |
import redis
from app.config import get_config_obj
from app.util.httputil import Http_util
class Component_access_token():
def __init__(self):
self.component_appid = get_config_obj().component_appid
self.component_appsecret = get_config_obj().component_secret
self.r = redis.Redis(host='local... |
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 'Reference.year'
db.add_column(u'citations_reference', 'year',
self.gf('django.db.models.fields.In... |
from selenium import webdriver
from time import sleep
driver = webdriver.Firefox()
driver.get("https://www.baidu.com/")
driver.find_element_by_xpath("//input[@id='kw']").send_keys("51zxw")
driver.find_element_by_xpath("//input[@name='wd']").send_keys("51zxw")
driver.find_element_by_xpath("//*[@class='s_ipt']").send_key... |
import unittest
from datetime import date
from binder.col import *
from binder.table import Table, SqlCondition, SqlSort, AND, OR
from bindertest.tabledefs import Foo, Bar
class TableTest(unittest.TestCase):
def test_init_2_AutoIdCols(self):
# Table can have only 1 AutoIdCol
try:
Table("... |
""":mod:`cliche.celery` --- Celery_-backed task queue worker
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sometimes web app should provide time-consuming features that cannot
immediately respond to user (and we define "immediately" as "shorter than
a second or two seconds" in here). Such things should ... |
from __future__ import absolute_import
from sqlalchemy import *
from migrate import *
meta = MetaData()
vieworderings = Table('vieworderings', meta,
Column('id', Integer, primary_key=True),
Column('tagset', Text()),
Column('timestamp', Float, index=True),
)
def upgrade(migrate_engine):
... |
import _plotly_utils.basevalidators
class ShowexponentValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self, plotly_name="showexponent", parent_name="parcats.line.colorbar", **kwargs
):
super(ShowexponentValidator, self).__init__(
plotly_name=plotly_name,
... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0002_auto_20141029_1945'),
]
operations = [
migrations.CreateModel(
name='Tag',
fields=[
('id', models.Au... |
from distutils.core import setup
setup(
name='flashback',
packages=['flashback'],
version='0.4',
description='The handiest Flashback scraper in the game',
author='Robin Linderborg',
author_email='robin.linderborg@gmail.com',
install_requires=[
'beautifulsoup4==4.4.1',
'reques... |
from ..gitpub import gitpub
def sort_repos(repo_list):
"""
Sort the repo_list using quicksort
Parameters
----------------------------------
repo_list : [gitpub.Repository()]
Array of friends (loaded from the input file)
=================================================
Returns:
-... |
ACCESS_KEY = 'twitter_access_token'
REQUEST_KEY = 'twitter_request_token'
SUCCESS_URL_KEY = 'twitter_success_url'
USERINFO_KEY = 'twitter_user_info' |
import platform
import asyncio
import json
from base.logger import LOG
def singleton(cls, *args, **kw):
instances = {}
def _singleton(*args, **kw):
if cls not in instances:
instances[cls] = cls(*args, **kw)
return instances[cls]
return _singleton
def func_coroutine(func):
"""... |
from optparse import make_option
from django.core.management.base import BaseCommand
import path
from frog.models import Gallery, Image, Video, Piece, VideoQueue
class Command(BaseCommand):
help = 'Generated thumbnails'
def add_arguments(self, parser):
parser.add_argument(
'guids',
... |
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pip... |
"""dryorm URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/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-base... |
import json
from feature_ramp import redis
class Feature(object):
"""
A class to control ramping features to a percentage of users
without needing to deploy to change the ramp.
Usage:
Feature("on_off_toggled").activate()
Feature("on_off_toggled").is_active
Feature("on_off_toggled").deactivat... |
from unittest import TestCase
import json
import re
from grab import Grab, GrabMisuseError
from test.util import TMP_FILE, GRAB_TRANSPORT, get_temp_file
from test.server import SERVER
from grab.proxy import ProxyList
DEFAULT_PLIST_DATA = \
'1.1.1.1:8080\n'\
'1.1.1.2:8080\n'
class GrabProxyTestCase(TestCase):
... |
from string import Template
from datetime import date
bitcoinDir = "./";
inFile = bitcoinDir+"/share/qt/Info.plist"
outFile = "Nichts-Qt.app/Contents/Info.plist"
version = "unknown";
fileForGrabbingVersion = bitcoinDir+"bitcoin-qt.pro"
for line in open(fileForGrabbingVersion):
lineArr = line.replace(" ", "")... |
def RadixSort(A):
RADIX = 10
maxLength = False
tmp , placement = -1, 1
while not maxLength:
maxLength = True
buckets = [list() for _ in range(RADIX)]
for i in A:
tmp = i / placement
buckets[tmp % RADIX].append(i)
if maxLength and tmp > 0:
maxLength = False
a = 0
for b in range(RADIX... |
import pygame
class GameOfLife:
# still
BLOCK_0 = set([(0, 0), (0, 1), (1, 0), (1, 1)])
BLOCK_1 = BLOCK_0
# oscillators
THREE_0 = set([(0, 1), (0, 0), (0, 2)])
THREE_1 = set([(0, 1), (-1, 1), (1, 1)])
# spaceships (moves)
GLIDER_0 = set([(0, 1), (1, 2), (0, 0), (0, 2), (2, 1)])
GLIDE... |
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
def coefficient(slipValue, extremumValue, extremumSlip, asymptoteValue, asymptoteSlip):
coefficient = asymptoteValue;
absoluteSlip ... |
import os
import logging
from dotenv import find_dotenv, load_dotenv
from constants import *
import json
from utils import json_from_file, merge_json
import shutil
from settings import *
def prepare_train_data():
""" Runs data processing scripts to turn traning raw data from (../raw) into
interim data to be... |
"""
Utilities and functions for the mailstat package
""" |
import unittest
from .layer import *
class L(Layer):
L1 = LayerSpec("l1", "layer-1")
L2 = LayerSpec("l2", "layer-2", [L1])
class TestLayer(unittest.TestCase):
def testFromId(self):
self.assertEqual(L.FromId(L.L1.id_), L.L1)
self.assertEqual(L.FromId(L.L2.id_), L.L2)
def testFromName(self):
self.asse... |
import OOMP
newPart = OOMP.oompItem(9439)
newPart.addTag("oompType", "RESE")
newPart.addTag("oompSize", "0805")
newPart.addTag("oompColor", "X")
newPart.addTag("oompDesc", "O202")
newPart.addTag("oompIndex", "01")
OOMP.parts.append(newPart) |
def circle(cx, cy, diameter):
radius = diameter / 2
oval(cx - radius, cy - radius, diameter, diameter)
circle(420, 532, 254)
circle(728, 414, 154)
circle(510, 258, 306) |
def countup(n):
if n >= 10:
print "Blastoff!"
else:
print n
countup(n+1)
def main():
countup(1)
main()
def countdown_from_to(start,stop):
if start == stop:
print "Blastoff!"
elif start <= stop:
print "Invalid pair"
else:
print start
countdown_from_to(start - 1,stop)
def main():
countdown_from_to(89... |
import pygame
import parameters
from filemanager import filemanager
from pygame.locals import *
from pygame import *
from pygame.mixer import *
pigmusic = None
currentStdMusic=None
currentMenuMusic=None
currentType = None
def initmusic():
global pigmusic
#Init pygame mixer and music
print "music init GO"
... |
"""Basic simplified data test functions - NOT FOR XML """
from invenio.bibworkflow_config import CFG_OBJECT_STATUS
def task_a(a):
def _task_a(obj, eng):
"""Function task_a docstring"""
eng.log.info("executing task a " + str(a))
obj.data += a
return _task_a
def task_b(obj, eng):
"""Fu... |
from pik.flights import Flight
import csv
import sys
reader = csv.reader(sys.stdin)
for flight in Flight.generate_from_csv(reader):
print flight |
from __future__ import unicode_literals
from layman.utils import path
from layman.overlays.source import OverlaySource
class StubOverlay(OverlaySource):
''' Handles overlays with missing modules. '''
type = 'N/A'
type_key = 'n/a'
def __init__(self, parent, config, _location, ignore = 0... |
import os
from flask import Flask
from flask import request
import requests
import random
import codecs
bot_id = ''
app = Flask(__name__)
def stripped(text):
text = text.lower()
return text.encode('ascii','replace_spc')
def send(text):
message = {
'text' : text,
'bot_id' : bot_id
}
r = requests.post("https://a... |
from django.conf.urls import patterns, url
from django.contrib import admin
import views
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^$', views.HomeView.as_view(), name="home"),
url(r'^clues/$', views.CluesView.as_view(), name="clues"),
url(r'^test$', views.TestView.as_view(), name="test"),
... |
"""\
Rotamer library handling
========================
:mod:`rotamers.library` contains the data (:data:`LIBRARIES`) to load
a rotamer library, represented by a :class:`RotamerLibrary`.
"""
from __future__ import absolute_import, division, print_function
import MDAnalysis, MDAnalysis.lib.util
import logging
logger = lo... |
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response
from omeroweb.webgateway.views import getBlitzConnection, _session_logout
from omeroweb.webgateway import views as webgateway_views
import settings
import logging
impor... |
from netfilterqueue import NetfilterQueue
from dpkt import ip, icmp, tcp, udp
from scapy.all import *
import socket
def print_and_accept(pkt):
data=pkt.get_payload()
res = ip.IP(data)
res2 = IP(data)
i = ICMP(data)
t = TCP(data)
u = UDP(data)
print "SOURCE IP: %s\tDESTINATION IP: %s" % (sock... |
import steps.interface
from steps.model import *
from steps.geom import *
from steps.rng import *
from steps.sim import *
from steps.saving import *
from steps.visual import *
import time
mdl = Model()
r = ReactionManager()
with mdl:
X = Species.Create()
vsys = VolumeSystem.Create()
with vsys:
dif_X... |
from django.contrib.auth import authenticate, login, get_user_model
from mailin import Mailin
from string import punctuation
def authorize(request):
email = request.POST.get('Email')
password = request.POST.get('Password')
if len(email) < 6 or len(password) < 10:
return {'ERROR' : 'Too short'}
else:
user = auth... |
FUDGE_AMOUNT = 3
FUDGE_AMOUNT_2 = 6
from gamera.core import Rect, Point, Dim
def Fudge(o, amount=FUDGE_AMOUNT):
# For rectangles, just return a new rectangle that is slightly larger
if isinstance(o, Rect):
return Rect(Point(int(o.ul_x - amount), int(o.ul_y - amount)), Dim(int(o.ncols + amount * 2), int(... |
from tictactoe import game, player
import unittest
from unittest import mock
class GameTest(unittest.TestCase):
def setUp(self):
self.num_of_players = 2
self.width = 3
self.height = 3
self.game = game.Game(2, 3, 3)
def test_init(self):
self.assertEqual(self.game.board, No... |
from django.template import RequestContext
from django.shortcuts import render_to_response, HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.contrib import messages
from django.core.urlresolvers import reverse
i... |
userDb = "userDb"
passDb = "passDb"
mail = "*********@gmail.com"
passMail = "passMail"
nameDb = "domotics_db"
urlDb = "urlDb"
serverPort = 8080
updateCode = "UPDATE device SET code = '%s' WHERE id = '%s' AND (code = '%s' OR connectionStatus = 0)"
updateCodeRemote = "UPDATE device SET code = '%s' WHERE idDevice = '%s'"
... |
from sys import exit
from random import randint
class Scene(object):
def enter(self):
print "This scene is not yet configured. Subclass it and implement enrer()."
exit(1)
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
current_s... |
import rospy
import actionlib
from actionlib_msgs.msg import *
from geometry_msgs.msg import PoseStampted
import yaml
import os
import os.path
class GetLocals:
def __init__(self):
rospy.Subscriber('move_base_simple/goal', PoseStampted, self.goal_callback)
print('\nPLEASE, SEND A GOAL WITH NAV 2D GOAL USING GRAPHIC... |
from ventana import Ventana
from formularios import utils
import re
import pygtk
pygtk.require('2.0')
import gtk
from framework import pclases
from utils import _float as float
try:
from psycopg import ProgrammingError as psycopg_ProgrammingError
except ImportError:
from psycopg2 import ProgrammingError as psyc... |
from __future__ import division
import csv
import os
import sys
import matplotlib.pyplot as plt
import collections
import argparse
import shutil
import numpy
import time
import config
csv_file_handle = {}
value = dict()
def plot(files, pstyle = 'ggplot', output=None, seq=None, xkcd=False):
global csv_file_handle
... |
import os
from twisted.python.compat import iteritems
from landscape.lib.fs import read_text_file
from landscape.constants import APT_PREFERENCES_SIZE_LIMIT
from landscape.client.monitor.plugin import DataWatcher
class AptPreferences(DataWatcher):
"""
Report the system APT preferences configuration.
"""
... |
from __future__ import unicode_literals
from argparse import ArgumentParser
from .core import Core
def getopt(argv):
parser = ArgumentParser(description='Another webui for youtube-dl')
parser.add_argument('-c', '--config', metavar="CONFIG_FILE", help="config file")
parser.add_argument('--host', metavar="ADD... |
import apt
from datetime import datetime
import decimal
import json
import os
import Queue
import random
import socket
import subprocess
import sys
import traceback
import xbmc
import xbmcaddon
import xbmcgui
__libpath__ = xbmc.translatePath(os.path.join(xbmcaddon.Addon().getAddonInfo('path'), 'resources','lib'))
sys.p... |
import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), "scripts"))
from Util import runTests
runTests() |
'''
Created on Jun 9, 2015
@author: dwalker
@change: 2016/02/10 roy Added sys.path.append for being able to unit test this
file as well as with the test harness.
@change: 2016/04/06 eball Updated name to ConfigureProfileManagement
@change: 2016/11/02 eball Updated name to ConfigurePasswordPolicy... |
import pymysql
import json
class MysqlHelper:
"""mysql 帮助类"""
@staticmethod
def insert(word,asymbol,esymbol,explain,cizu,liju,xiangguancihui,aspoken,espoken):
db=pymysql.connect(host="192.168.180.187",user="root",password="123456",db="lytest",charset="utf8")
cursor=db.cursor()
print(... |
"Fully test this module's functionality through the use of fixtures."
from megacosm.generators import Govt, Country, City
import unittest2 as unittest
import fakeredis
import fixtures
from config import TestConfiguration
class TestGovt(unittest.TestCase):
def setUp(self):
""" """
self.redis = faker... |
"""Writers test.
.. 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 the License, or
(at your option) any later version.
"""
__author__ = 'riccardo.klinger@geo... |
"""Dumper module
Test module which outputs any input values in a file.
"""
import fw_modules.module_template
from fw_modules.module_exceptions import *
import time
class DumperClass(fw_modules.module_template.ModuleClass):
"""DumperClass
Receives messages and dumps them into file.
"""
def __init__(self,... |
import netifaces
from avocado import Test
from avocado.utils.software_manager import SoftwareManager
from avocado.utils.ssh import Session
from avocado.utils import process
from avocado.utils import distro
from avocado.utils.network.interfaces import NetworkInterface
from avocado.utils.network.hosts import LocalHost
cl... |
import subprocess
import smtplib
import socket
from email.mime.text import MIMEText
import datetime
to = 'rk.ryan.king@gmail.com'
gmail_user = 'rk.ryan.king@gmail.com'
gmail_password = 'nzwaahcmdzjchxsz'
smtpserver = smtplib.SMTP('smtp.gmail.com', 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.