code stringlengths 1 199k |
|---|
from ..mathematics.defaults import *
import copy
import xml.dom.minidom
from ..spatial.vectorial.vectorial import *
from ..spatial.vectorial.geodetic import *
class GeoProfilesSet(object):
"""
Represents a set of ProfileElements instances,
stored as a list
"""
def __init__(self, name=""):
""... |
from utilities import execute, isGit, isMercurial, isBazaar
def merge(arguments):
'''
Merge incoming changes with the current branch.
'''
if isGit():
command = ["git", "merge"]
command.extend(arguments)
execute(command)
if isMercurial():
command = ["hg", "merge"]
... |
"""
Serializers for Content, Tags and it's relation
"""
from rest_framework.serializers import (ModelSerializer, SlugRelatedField,
ReadOnlyField, HyperlinkedModelSerializer)
from linkitos.models import Content, Tag, ContentTag
class ContentTagSerializer(HyperlinkedModelSerializer... |
from flask import Blueprint, render_template
mod = Blueprint(
'web',
__name__,
url_prefix="/web",
template_folder="templates",
static_folder="static"
)
import default |
import helper
from skime.macro import Macro, DynamicClosure
from skime.compiler.parser import parse
from skime.types.pair import Pair as pair
from skime.errors import SyntaxError
from nose.tools import assert_raises
def filter_dc(expr):
if isinstance(expr, DynamicClosure):
return filter_dc(expr.expression)
... |
import os
from git import Repo
root_dir = '.'
directories = [ name for name in os.listdir(root_dir) if os.path.isdir(os.path.join(root_dir, name)) ]
for module_dir in directories:
try:
print "name of module -->>", module_dir
current_dir = os.getcwd()
target_dir = current_dir + '/' + module_d... |
__version__ = '2.3.1'
import Type,Opcode,Status,Class
from Base import DnsRequest, DNSError
from Lib import DnsResult
from Base import *
from Lib import *
Error=DNSError
from lazy import *
Request = DnsRequest
Result = DnsResult
from Serialization import Serialize,DeSerialize |
__author__ = """Stephan GEULETTE <stephan.geulette@uvcw.be>"""
__docformat__ = 'plaintext'
try: # New CMF
from Products.CMFCore.permissions import setDefaultRoles
except ImportError: # Old CMF
from Products.CMFCore.CMFCorePermissions import setDefaultRoles
import os
PROJECTNAME = "ZopeRepository"
try:
from ... |
import numpy as np
from scipy.stats import bernoulli
from scipy.linalg import eig
import random
import matplotlib.pyplot as plt
import itertools, math
def generateWignerMatrix(matrix_size, i):
matrix = np.zeros((matrix_size, matrix_size)) #Form a matrix
newSize = (matrix_size*(i+1))/2
bern = bernoulli.rvs(0... |
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
import sys
sys.path.append(".")
print sys.path
import time, run
device = MonkeyRunner.waitForConnection()
while True:
print "=" * 30
start = time.clock()
result = device.takeSnapshot()
end = time.clock()
print "SnapShot Time:", end - st... |
"""
MetPX Copyright (C) 2004-2006 Environment Canada
MetPX comes with ABSOLUTELY NO WARRANTY; For details type see the file
named COPYING in the root of the source directory tree.
"""
import cgi
import cgitb; cgitb.enable()
import sys, os, pwd, time, re, pickle, commands
sys.path.append(sys.path[0] + "/../../lib");
sy... |
"""
Asynchronous web service.
"""
from collections import (
defaultdict,
deque,
namedtuple,
)
from functools import partial
import os.path
import platform
import sys
from PyQt5 import (
QtCore,
QtNetwork,
)
from PyQt5.QtCore import (
QUrl,
QUrlQuery,
)
from PyQt5.QtNetwork import QNetworkReq... |
import unittest
from src.cannon import Cannon
from src.position import Position
class TestCannonGetters(unittest.TestCase):
def setUp(self):
self.cannon_position = Position(25, 23)
self.projectile_position = Position(35, 33)
self.angle = 45
self.initial_speed = 100
self.canno... |
from Bio.Pathway.Rep.HashSet import *
class MultiGraph:
"""A directed multigraph abstraction with labeled edges."""
def __init__(self, nodes = []):
"""Initializes a new MultiGraph object."""
self.__adjacency_list = {} # maps parent -> set of (child, label) pairs
for n in nodes:
... |
'''
manymaya
--------
A fast and light-weight solution to process Autodesk Maya files.
'''
from .api import find, instance, start, log |
from django.conf.urls import include, url
from django.contrib import admin
import settings
urlpatterns = [
url(r'', include('base.urls', namespace='base')),
url(r'^comment/', include('comment.urls', namespace='comment')),
url(r'^exchange/', include('exchange.urls', namespace='exchange')),
url(r'^grade/'... |
import socket
import time, calendar
from optparse import OptionParser
import os
import subprocess as sb
import sys
class flushfile(object):
def __init__(self, f):
self.f = f
def write(self, x):
self.f.write(x)
self.f.flush()
parser = OptionParser();
parser.add_option("-P", "--psr", "--pu... |
from flask.ext.script import Command, Shell
from flask.ext.migrate import MigrateCommand
from manage import app, db
from app import models
def make_shell_context():
bases = {m: getattr(models, m) for m in dir(models) if m[0].isupper()}
return dict(app=app, db=db, models=models, **bases)
class Hello(Command):
... |
process = None
process1 = None
process2 = None
fn = None |
import wave
import sys
w1, w2 = 'helium.wav', 'mercury.wav'
def mixer(w1_name,w2_name):
w1 = wave.open('{0}'.format(w1_name))
w2 = wave.open('{0}'.format(w2_name))
#get samples formatted as a string.
samples1 = w1.readframes(w1.getnframes())
samples2 = w2.readframes(w2.getnframes())
print w1, w2... |
'''
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 ... |
import cv2
from core.hnfTracker import hnfTracker
video_capture = cv2.VideoCapture(-1)
hnftracker = hnfTracker(video_capture.get(cv2.CAP_PROP_FRAME_WIDTH), video_capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
while(True):
# Gets frame from video input
ret, frame = video_capture.read()
# Smoothens image
frame =... |
{
"name" : "account_report_general_ledger_no_journal",
"version" : "1.0",
"author" : "Vauxoo",
"category" : "account",
"description" : """This module """,
"website" : "http://www.vauxoo.com/",
"license" : "AGPL-3",
"depends" : ["account",],
"init_xml" : [],
"demo_xml" : [],
"... |
"""
WebJournal Element - Display admin links
"""
from invenio.config import \
CFG_SITE_URL, \
CFG_SITE_NAME, \
CFG_SITE_NAME_INTL
from invenio.access_control_engine import acc_authorize_action
from invenio.webjournal_utils import \
parse_url_string, \
get_journal_submission_params
def format_el... |
vowel=('a','e','i','o','u')
no={'a':0,'e':0,'i':0,'o':0,'u':0}
def count(string):
cv=0
for letter in string:
if letter in vowel:
cv=cv+1
no[letter]=no[letter]+1
print "The No of Vowels in the String is:",cv
print no.keys()
print no.values()
return
if __name__=="__... |
from django.contrib import admin
from .models import Todo, Item
admin.site.register(Todo)
admin.site.register(Item) |
from django.shortcuts import render, get_object_or_404, render_to_response, redirect
from django.http import HttpResponse, Http404
from django.forms import models, ModelForm, HiddenInput
from do.models import *
from django.db import connection
from django.db.models import Q
from django.contrib.auth.decorators import lo... |
from tools.load import LoadMatrix
from numpy import where
lm=LoadMatrix()
traindat = lm.load_numbers('../data/fm_train_real.dat')
testdat = lm.load_numbers('../data/fm_test_real.dat')
parameter_list=[[traindat,testdat, 1.0],[traindat,testdat, 10.0]]
def kernel_cauchy_modular (fm_train_real=traindat,fm_test_real=testdat... |
import sys, string, re
import math
import grav_util
from grav_data import *
import fileop
from fileop import to_float
def get_aliod_data(dataFile, meterFile, debug=0):
global nr
# open the file and read it
# create file object
file = open(dataFile, "rt")
meterInfo = get_aliod_info(meterFile)
# now read the ... |
from __future__ import absolute_import
from testutil.dott import feature, sh, testtmp # noqa: F401
(
sh % "cat"
<< r"""
[extensions]
amend=
rebase=
[experimental]
evolution = obsolete
[mutation]
enabled=true
record=false
[visibility]
enabled=true
"""
>> "$HGRCPATH"
)
sh % "hg init repo"
sh % "cd repo"
sh %... |
if __name__ == "__main__":
raise Exception("This script is a plugin for xsconsole and cannot run independently")
from XSConsoleStandard import *
class PoolNewMasterDialogue(Dialogue):
def __init__(self):
Dialogue.__init__(self)
self.ChangeState('SELECT')
def BuildPaneSELECT(self):
se... |
import sys
if sys.version_info[0] != 2:
sys.exit("Sorry, UFONet requires Python >= 2.7.9")
from setuptools import setup, find_packages
setup(
name='ufonet',
version='0.8',
license='GPLv3',
author_email='epsylon@riseup.net',
author='psy',
description='DDoS Botnet via Web Abuse',
url='http... |
from pysys.constants import *
from apama.correlator import CorrelatorHelper
from com.jtech.basetest import CycleMonitorTest
class PySysTest(CycleMonitorTest):
def execute(self):
#start server and set stations
self.startHTTPServer(dir=self.input)
#start the application
self.startCorrelator(url='http://localhost... |
import asyncio, logging, urllib
import goslate
import plugins
logger = logging.getLogger(__name__)
gs = goslate.Goslate()
def _initialise():
plugins.register_handler(_handle_message)
def _handle_message(bot, event, command):
language_map = gs.get_languages()
raw_text = event.text.lower()
raw_text = ' '.... |
extensions = [
'sphinx.ext.autodoc',
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'nZEDb'
copyright = u'2016, nZEDb Dev Team'
author = u'nZEDb Dev Team'
version = u'0.x'
release = u'0.x'
language = None
exclude_patterns = []
pygments_style = 'sphinx'
todo_include_todos = ... |
import numpy as np
import scipy.spatial.distance as dist
import pyparticles.measures.measure as me
class KineticEnergy( me.Measure ):
"""
Mesure for computing the total potential energy of the particle system
"""
def __init__( self , pset=None , force=None ):
self.__ke = 0.0
super( Kinet... |
import csv
import os
GENERATE_SQL_DIR = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"generated_files")
def volcar_a_fichero(countries, file_name):
"""
Recorre la lista de cadenas recibida y las vuelca en un fichero de texto.
"""
abs_file_name = os.path.join(GENERATE_SQL_DIR... |
import sgl
from sgl.lib.Sprite import Sprite, RectSprite, Scene, App
import sgl.lib.Time as time
import sgl.lib.Tween as tween
import sgl.lib.Script as script
from sgl.lib.TextSprite import TextSprite
class ScriptTextSprite(TextSprite):
pause_code = 999
def __init__(self):
super(ScriptTextSprite, self).... |
"""
Copyright (C) 2015 Louis Dijkstra
This file is part of somatic-indel-calling
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.... |
from hapi import HAPI, HAPI_AuthFailed, HAPI_Error
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
from django.contrib import messages
from farm_mngr.models import HypUserProfile, Player
class HAPIAuth(ModelBackend):
"""Return user if login to HAPI is successful; None ... |
import requests
import json
if __name__ == "__main__":
test = ''
if test:
print True
else:
print False
test_dict = {('1,0'):"aaaaaa", ('2,0'): "bbbbbbb", ('1,2'):"cccccc"}
print test_dict
key = '1'
for k in test_dict.keys():
k1,k2 = k.split(',')
if k1 == key:
... |
num=2
while num<=100:
print(num)
num=num+2 |
from plugins.Name_PoorlyWrittenWayType import P_Name_PoorlyWrittenWayType
import re
class Name_PoorlyWrittenWayType_fr(P_Name_PoorlyWrittenWayType):
only_for = ["fr"]
def init(self, logger):
P_Name_PoorlyWrittenWayType.init(self, logger, True)
self.ReTests = {}
# Captial at begining alre... |
""" Playing around with basic pg read access, from Python
mainly stuff I copied from: http://www.jmapping.com/getting-started-with-scripted-geo-data-processing-postgresql-postgis-python-and-a-little-ogr/
"""
import psycopg2
import users_and_passwords # Hide the names and passwords in a file not shared as open sourc... |
"""
This moduly mainly provides CLI interface to class MeerkatMon.
"""
from sys import argv
from lib.base import MeerkatMon
if __name__ == "__main__":
if '--help' in argv or '-h' in argv:
print("MeerkatMon - gawky script for monitoring services")
print("")
print("usage: [python3] ./meerkatmon.py [config file]")
... |
import struct
def read_en_file(fname):
f=open(fname,'rb')
length_bytes=f.read(8)
length=struct.unpack('l',length_bytes)
length=length[0]
data=f.read()
f.close()
return length,data
def write_en_file(fname,raw_length,data_encrypted):
f=open(fname,'wb')
f.write(struct.pack('l',raw_length))
f.write(data_encrypted... |
from PyQt5.QtWidgets import QWizardPage, QLabel, QGroupBox, QVBoxLayout, QSpacerItem, QSizePolicy, QHBoxLayout,\
QComboBox, QPushButton, QFileDialog
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtMultimediaWidgets import QCameraViewfinder
from PyQt5.QtMultimedia import QCamera, QCameraInfo, QCame... |
def main(first_div_by):
partitions = [1]
n = 0
while True:
i = 0
curr_pent = 1
partitions.append(0)
while curr_pent <= n:
sign = -1 if i % 4 > 1 else 1
partitions[n] += sign * partitions[n - curr_pent]
partitions[n] %= first_div_by
... |
from settings import *
import unittest
from nltk.corpus import stopwords
import numpy
import os
from networkx import DiGraph
from tethne import Corpus, GraphCollection, HDF5Corpus
from tethne.readers import dfr
from tethne.model.managers import TAPModelManager, MALLETModelManager
from tethne.model import TAPModel
from ... |
x=int(input("Ingrese 1er lado del triángulo: "))
y=int(input("Ingrese 2do lado del triángulo: "))
z=int(input("Ingrese 3er lado del triángulo: "))
if x==y==z:
print("El triángulo es equilatero")
elif x==y!=z or x!=y==z or x==z!=y:
print("El triángulo es isósceles")
else:
print("El triángulo es escaleno") |
__author__="ashe"
__date__ ="$Jun 2, 2011 6:56:43 PM$"
from owade.process import Process
from owade.fileExtraction.getFiles import GetFiles
from owade.fileAnalyze.windowsRegistery import WindowsRegistery
from owade.fileAnalyze.filesStatistics import FilesStatistics
from owade.fileAnalyze.userPassword import UserPasswor... |
"""
NOTICE: THIS IS ONLY REQUIRED IF YOU ARE UPGRADING THE BOT FROM
A VERSION BEFORE 5/19/17 TO THE CURRENT VERSION.
Don't run this otherwise- you're just going to be wasting your time.
********************************************************************
After you run this script, configuration.V5.ini will be written.
... |
__author__ = 'ZHang Chuan'
'''
Models for user, blog, comment.
'''
import time, uuid
from transwarp.db import next_id
from transwarp.orm import Model, StringField, BooleanField, FloatField, TextField
class User(Model):
__table__ = 'users'
id = StringField(primary_key=True, default=next_id, ddl='varchar(50)')
... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
DOCUMENTATION = '''
---
module: nxos_portchannel
version_added: "2.2"
short_description: Manages port-channel interfaces.
description:
- Manages port-channel specific configuration param... |
"""Translating between encodings on the fly.
"""
from codecs_to_hex import to_hex
import codecs
from cStringIO import StringIO
data = u'pi: \u03c0'
utf8 = data.encode('utf-8')
print 'Start as UTF-8 :', to_hex(utf8, 1)
output = StringIO()
encoded_file = codecs.EncodedFile(output, data_encoding='utf-8',
... |
import calendar
from datetime import datetime, timedelta
from time import sleep
from urllib.parse import urlparse, parse_qs
from dateutil import parser
from facebook import GraphAPI
import mysql.connector
from extracao.rsoservices.config import config, fields_posts, fields_tagged
add_message_table0 = ("INSERT INTO extr... |
'''
Exodus Add-on
Copyright (C) 2016 Viper2k4
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 p... |
from django.contrib import admin
from django.utils.safestring import mark_safe
from edc_base.modeladmin_mixins import audit_fieldset_tuple
from ..admin_site import bcpp_subject_admin
from ..forms import HivCareAdherenceForm
from ..models import HivCareAdherence
from .modeladmin_mixins import CrfModelAdminMixin
@admin.r... |
"""
pygments.lexers.web
~~~~~~~~~~~~~~~~~~~
Lexers for web-related languages and markup.
:copyright: 2006-2008 by Georg Brandl, Armin Ronacher,
Tim Hatch <tim@timhatch.com>, Stou Sandalski.
:license: BSD, see LICENSE for more details.
"""
import re
try:
set
except NameError:
... |
"""Tests for the download center module using a local server"""
import os
import shutil
import subprocess
from time import time
from unittest.mock import Mock, call, patch
import umake
from . import DpkgAptSetup
from umake.network.requirements_handler import RequirementsHandler
from umake import tools
class TestRequire... |
"""
Copyright 2012 Free Software Foundation, Inc.
This file is part of GNU Radio
GNU Radio Companion 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 v... |
import socket
import subprocess
import ipaddress
import nmap
import pexpect
from core.flowcontrol import WriteFileFunction
def reportscan(argument, IP):
output = " "
nm = nmap.PortScanner()
nm.scan(hosts=IP, arguments=argument)
output += (nm.command_line())
output += ('Host : %s (%s) \n' % (IP, nm[IP].hostname())... |
"""
Functions is used to group things together, and keep things in logical places.
Functions saves time and keeps the code tidy. Then you can call the function,
and the things inside the function is executed.
"""
def SayHello():
print("Hello!")
print("Is it me you're looking for?")
print("I can see it in your eyes")... |
import subprocess, threading
import os, signal
count_file = "jdart-termination-count.txt"
class Command:
def __init__(self, args):
self.process = None
self.args = args
def run(self):
self.process = subprocess.Popen(args=self.args, shell=True)
self.process.communicate()
class Comm... |
"""
Collection of DIRAC useful network related modules
by default on Error they return None
"""
import socket
import os
import struct
import array
import fcntl
import platform
from urllib import parse
from DIRAC.Core.Utilities.ReturnValues import S_OK, S_ERROR
def discoverInterfaces():
max_possible = 128
... |
"""
Test case for module Memory
"""
from __future__ import absolute_import, print_function
from tests import common
from bleachbit.Memory import *
import unittest
import sys
running_linux = sys.platform.startswith('linux')
class MemoryTestCase(common.BleachbitTestCase):
"""Test case for module Memory"""
@unitte... |
def sort1(A, B, C):
if (A < B):
if (B < C):
return [A, B, C]
else:
if (A < C):
return [A, C, B]
else:
return [C, A, B]
else:
if (B < C):
if (A < C):
return [B, A, C]
else:
return [B, C, A]
else:
return [C, B, A]
def sort2(A, B, C):
if (A < B) and (B < C) : return [A, B, C]
... |
from ..internal.Crypter import Crypter
from ..internal.misc import json
class YoutubeComFolder(Crypter):
__name__ = "YoutubeComFolder"
__type__ = "crypter"
__version__ = "1.11"
__status__ = "testing"
__pattern__ = r'https?://(?:www\.|m\.)?youtube\.com/(?P<TYPE>user|playlist|view_play_list)(/|.*?[?&]... |
from sys import exit as end_program
import threading
from core.node import Node
from pathlib import PurePath
try:
from dbm import open as dbm_open
except ImportError:
dbm_open = object
print('GNU Database Manager not installed.')
print('Please install Gnu DBM for Python3.')
print('Exiting...')
e... |
import json
import urllib2
import re
import configparser
import logging
from bs4 import BeautifulSoup
import pickle
config = configparser.ConfigParser()
config.read('api/biblegateway_api.cfg')
urls = config['URL']
defaults = config['DEFAULT']
EMPTY = defaults['empty_message']
default_version = defaults['version']
def s... |
from cvxmod import *
from cvxmod.atoms import norm1
from cvxmod.sets import probsimp
from cantilever_divingboard import *
w = optvar('w', 1)
l = optvar('l', 1)
t = optvar('t', 1)
def frequency(w, l, t):
return l/(square(t))
p = problem(maximize(l+square(t)), [l <= 5, t <= 5, w <= 5])
p.solve()
print "Optimal proble... |
import os
ossep = os.sep # path delimiter
oslinesep = os.linesep # line break
osname = os.name # operating system name |
import sys
import clutter
import urllib
import identica
class Murmullos:
def __init__(self,service,tag):
self.stage = clutter.Stage()
self.stage.set_color(clutter.color_from_string('Black'))
self.stage.set_size(800,600)
self.stage.set_title("Murmullos")
self.stage.connect('ke... |
import sys, re
if len(sys.argv) != 3:
sys.exit("usage: coref-evaluator.py [gold_file][output_file]")
goldfh = open(sys.argv[1], 'r')
testfh = open(sys.argv[2], 'r')
gold_tag_list = []
test_tag_list = []
emptyline_pattern = re.compile(r'^\s*$')
for gline in goldfh.readlines():
if not emptyline_pattern.match(glin... |
from otree.api import Currency as c, currency_range
from . import pages
from ._builtin import Bot
from .models import Constants
from random import choice
from . import models
class PlayerBot(Bot):
def play_round(self):
if self.subsession.round_number == 1:
yield (pages.Screen2Page)
y... |
from __future__ import unicode_literals
import frappe
from frappe import _
from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
from frappe.model.document import Document
class AssetMovement(Document):
def validate(self):
self.validate_asset()
self.validate_location()
def validate_asset(self):
s... |
import classes.level_controller as lc
import classes.game_driver as gd
import classes.extras as ex
import pygame
import classes.board
import random
import os
class Board(gd.BoardGame):
def __init__(self, mainloop, speaker, config, screen_w, screen_h):
self.level = lc.Level(self,mainloop,1,1)
gd.Boa... |
"""
This file is part of Giswater 3
The 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.
"""
from functools import partial
from qgis.P... |
from distutils.core import setup
import py2exe
setup(windows=["shutdown.pyw"]) |
from rtorrent.common import find_torrent, \
is_valid_port, convert_version_tuple_to_str
from rtorrent.lib.torrentparser import TorrentParser
from rtorrent.lib.xmlrpc.http import HTTPServerProxy
from rtorrent.rpc import Method, BasicAuthTransport
from rtorrent.torrent import Torrent
from rtorrent.group import Group
... |
"""
Created on Sat Jul 18 20:31:14 2015
@author: Jak
"""
import pprint
import sys
import os
import itertools
import json
import requests
import makeHTML
with open("STEAMAPI.txt", "rb") as f:
STEAMKEY = f.read().rstrip("\n").lstrip(" ")
appListRaw = requests.get("http://api.steampowered.com/ISteamApps/GetAppList/v00... |
__author__ = 'Sungho Arai'
__copyright__ = 'Copyright (c) 2014, Sungho Arai'
import copy
import logging
import re
METRICS = re.compile("(.*){(.*)}")
class Error(Exception):
"""General exception of this module."""
pass
class SyntaxError(Error):
"""Syntax Error at parsing."""
pass
class EvaluationError(Error):... |
import pytest
import sys
import os
from jsonschema import ValidationError
import json
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import jsonvalidate
curpath = os.path.dirname(os.path.abspath(__file__))
def test_ok():
"""Test a well formed JSON file"""
jsv = jsonvalidate.Vali... |
import random
def LevelOneReward(money):
RanNum=random.randint(00,101)
if RanNum > 0 and RanNum < 15:
print("You get nothing!")
elif RanNum > 14 and RanNum < 30:
Amount = random.randint(00,7)
print("You got ", Amount, "copper piece(s)!")
money = mo... |
import time
try:
from PyRow import pyrow
except ImportError:
print "Error importing Pyrow"
class ErgStats(object):
distance = 0.0 # distance in m
spm = 0 # Strokes per Minute
pace = 0.0 # pace in seconds (2:15.0 equals 135.0)
avgPace = 0.0 # the average pace for the current s... |
"""This module provides the RatingsAndReviewsAPI class for talking to the
ratings and reviews API, plus a few helper classes.
"""
from urllib import quote_plus
from piston_mini_client import (
PistonAPI,
PistonResponseObject,
PistonSerializable,
returns,
returns_json,
returns_list_of,
)
from... |
import copy
import time
from flask_babel import lazy_gettext
import mycodo.utils.psypy as SI
from mycodo.databases.models import Conversion
from mycodo.databases.models import CustomController
from mycodo.functions.base_function import AbstractFunction
from mycodo.inputs.sensorutils import convert_from_x_to_y_unit
from... |
from argparse import ArgumentParser
from numpy import logspace, array
from matplotlib.pyplot import show
from gridaurora.eFluxGen import maxwellian, fluxgen, writeh5
from gridaurora.plots import plotflux
import seaborn as sns
sns.set_context("paper", font_scale=1.75)
sns.set_style("whitegrid")
def main():
p = Argum... |
"""
"""
import logging
import unittest
from pysolbase.Assert import Assert
from pysolbase.SolBase import SolBase
logger = logging.getLogger(__name__)
class LocalException(Exception):
"""
For test
"""
def __init__(self, message, param1=None):
"""
Test.
:param message: text message... |
import plots
HORZ = 0
VERT = 1
NORM = 2
def scatter_plot(name,
data = None,
errorx = None,
errory = None,
width = 640,
height = 480,
background = "white light_gray",
border = 0,
axi... |
from pysollib.game import Game
from pysollib.gamedb import GI, GameInfo, registerGame
from pysollib.hint import AbstractHint
from pysollib.layout import Layout
from pysollib.stack import \
AbstractFoundationStack, \
InitialDealTalonStack, \
InvisibleStack, \
ReserveStack
from pysollib.ut... |
import random, re
from ..core import command
die_pattern = re.compile(r'(?:(\d+)x)?(?:(\d+)d)?(\d+)?')
die_defaults = (1, 1, 6)
card_suits = ['hearts', 'diamonds', 'clubs', 'spades']
card_ranks = ['ace'] + list(range(2, 11)) + ['jack', 'queen', 'king']
class Random(metaclass=command.Cog):
@command.command()
async def... |
"""
Django settings for deldichoalhecho_site project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
... |
import argparse
import csv
import json
import sys
def validate_content_by(heading, expected):
if not expected:
return # no validation
comparison = expected.split(',')
stripped = heading[0:len(comparison)] # allow extra fields
if stripped != comparison:
raise MergeError('Erroneous content. Expected = ' + expecte... |
'''
This is to try and get the splash screen and levels to work
'''
from __future__ import division
import math
from math import hypot,atan2, degrees, pi
from random import randint
import pygame
import time
from pygame.sprite import Sprite
import csv
SIZE=(600,600) # sets the size of the window
colour = {0:pygame.color... |
"""
This is a basic logging example
NOTES:
- The idea of passing __name__ to the logger
is that you can turn logs on and off from certain modules.
- the first time you create a logger it doesnt have any handlers
and thats why you don't get any output despite the logging level
begin set correctly. if you turn off do_add... |
"""
django-info-panel
~~~~~~~~~~~~~~~~~
:copyleft: 2015 by the django-debug-toolbar-django-info team, see AUTHORS for more details.
:created: 2015 by JensDiemer.de
:license: GNU GPL v3 or above, see LICENSE for more details.
"""
from __future__ import print_function
import os
import sys
import subpr... |
from django.db.models import Q
from django.shortcuts import get_object_or_404
from core import logic
from . import models
class BlogLogic(logic.PageLogic):
def __init__(self, request):
super(BlogLogic, self).__init__(request)
def page(self, page_slug):
return get_object_or_404(models.Page, slug=... |
from __future__ import unicode_literals
import frappe
import urllib
import copy
from frappe.utils import nowdate, cint, cstr
from frappe.utils.nestedset import NestedSet
from frappe.website.website_generator import WebsiteGenerator
from frappe.website.render import clear_cache
from frappe.website.doctype.website_slides... |
"""
Copyright 2013 AKSW Research Group http://aksw.org
This file is part of LODStats.
LODStats 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.