code stringlengths 1 199k |
|---|
import os
import struct
import sys
import gzip
from appenv import env, log
from errors import NotFoundError, InvalidDictError
class cls_worditem(object):
def __init__(self, word, offset, size):
self.word = word
self.offset = offset
self.size = size
def __str__(self):
return '%s, ... |
import logging
from collections import defaultdict
from errno import ENOENT
from stat import S_IFDIR, S_IFLNK, S_IFREG
from sys import argv, exit
from time import time
from fuse import FUSE, FuseOSError, Operations, LoggingMixIn
if not hasattr(__builtins__, 'bytes'):
bytes = str
class Entyty(object):
def __init... |
from yowsup.layers import YowParallelLayer
import time, logging, random
from yowsup.layers import YowLayer
from yowsup.layers.noise.layer import YowNoiseLayer
from yowsup.layers.noise.layer_noise_segments import YowNoiseSegmentsLayer
from yowsup.layers.auth import YowAuthenticationProtocolLayer
f... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import sys
from nose.plugins.skip import SkipTest
if sys.version_info < (2, 7):
raise SkipTest("F5 Ansible modules require Python >= 2.7")
from ansible.module_utils.basic import AnsibleModule
try:
from ... |
"""DBUS interface module."""
import logging
import warnings
import dbus.service
from dbus import DBusException
from xml.etree import ElementTree
from twisted.internet import defer
from twisted.python.failure import Failure
from ubuntuone.syncdaemon.interfaces import IMarker
from ubuntuone.platform.credentials.linux imp... |
import os
from tempfile import mkdtemp, mkstemp, NamedTemporaryFile
from shutil import rmtree
from urlparse import urlparse
from urllib2 import URLError
import urllib2
from numpy.testing import *
from numpy.compat import asbytes
import numpy.lib._datasource as datasource
def urlopen_stub(url, data=None):
'''Stub to... |
from __future__ import division, print_function
import numpy as np
from linguineglobals import *
class Telescope(object):
def __init__(self,
efl_m,
T=273.15
):
self.T = T
self.tau = 1.0 # initialise the throughput to 1 as it is determined by the telescope's mirrors.
self.efl_m = efl_m
self.efl_mm = efl_m... |
"""Traverse a family SQLite database file for all descendants of given people.
"""
from argparse import ArgumentParser
import os
import sqlite3 as lite
class Trawler:
"""Simple object to wrap our db logic
"""
def __init__(self, input):
"""Create new trawler given some db input filepath
"""
... |
import logging
import logging.config
import os
import click
import json
from json.decoder import JSONDecodeError
import tornado.ioloop
import tornado.web
from tornado.web import url, HTTPError
from checkQC.app import App
from checkQC.config import ConfigFactory
from checkQC.exceptions import *
log = logging.getLogger(_... |
from django.db import models
from django.utils import timezone
from django.utils.functional import cached_property
from django_extensions.db import fields
from urllib import parse
class News(models.Model):
slug = fields.RandomCharField(
length=12,
unique=True,
include_alpha=False,
db... |
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from walicxe2d_utils import *
path = '/Users/esquivel/Desktop/diable/data/esquivel/Walixce-2D/LE-JET/'
runs = ['Tau40AD','Tau40ISO','Tau40DMC','Tau40AD-2']
nproc = 16
nx = 32
ny = 32
nlevs = 7
neqs = 5
xmax = 4.#6e17
ymax = 1.#1.5e17
nbx =... |
"""Tests for QGIS functionality.
.. 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__ = 'tim@... |
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class QRadioButtonGroup(QGroupBox):
#
# public
#
selectItemChanged = pyqtSignal(int, QWidget)
def selectedItem(self):
return self.group.checkedId()
def buddie(self, index):
item = self.group.button(index)
return item.bu... |
def do_twice(f,val):
f(val)
f(val)
def print_twice(msg):
do_twice(print,msg)
def do_four(f,val):
do_twice(f,val)
do_twice(f,val)
do_twice(print_twice,'spam')
print()
do_four(print,'spam') |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('backend', '0005_auto_20170411_1425'),
]
operations = [
migrations.AddField(
model_name='project',
... |
import logging
import structlog
from django.utils.functional import cached_property
from structlog import get_logger
from django.db import models, transaction
from django.utils import timezone
from django.conf import settings
from jsonfield import JSONField
from copy import deepcopy
from collections import OrderedDict
... |
from PyQt5.QtCore import pyqtSignal, pyqtSlot
from PyQt5.QtWidgets import QListWidgetItem, QDialog, QDialogButtonBox
from .qtdesigner.ui_QStrChooser import Ui_QStrChooser
class StrChooser(QDialog):
"""
This dialog shows a list of strings. Can filter them and select multiple of
them. On accept dialog emits *... |
from abstract import Provider
from datetime import timedelta, datetime
class ViennaAt(Provider):
provider_name = 'vienna.at'
update_intervall = timedelta(minutes=30)
last_updated = None
url = 'http://apps.vienna.at/tools/schwarzkappler/'
info = {}
@classmethod
def fetch(cls):
p = cls... |
__version__ = '2.0.3' |
from feature import Feature
from layer import (FeatureGenerator, FeatureLayer, buffer, copy_layer,
difference, erase, identity, intersection, union, update) |
import configparser
import glob
import locale
import os
import pwd
import stat
from collections import (
namedtuple,
OrderedDict,
defaultdict)
from itertools import (
chain,
accumulate)
from locale import gettext as _
from gi.repository import (
GdkPixbuf,
GLib,
GObject,
Gtk,
Pan... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('MetaGet', '0003_image_datetimedigitized'),
]
operations = [
migrations.AddField(
model_name='image',
name='ExifImageHeight',
... |
from django.db import models
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
class MailingListSignup(models.Model):
# Cosmetic bits
button_text = models.CharField(_('button text'), max_length=50,)
form_url = models.URLField(_('form url'),)
head... |
"""
Database connection with logging.
Overrides MonetDB connection object.
"""
import monetdb.sql as db
from src.unifiedConnection import UnifiedConnection
from monetdb.mapi import logger as mapi_logger
import logging
class MonetConnection(UnifiedConnection):
"""
Connection with logging.
Overrides MonetDB c... |
"""pkg_usbguard command.
@author: Tobias Hunger <tobias.hunger@gmail.com>
"""
from cleanroom.command import Command
from cleanroom.helper.file import create_file, makedirs, remove, move
from cleanroom.location import Location
from cleanroom.systemcontext import SystemContext
import textwrap
import typing
class PkgAvahi... |
"""
Fixtures for testing Control classes.
"""
import pytest
from z2pack._control import (
AbstractControl, IterationControl, DataControl, StatefulControl,
ConvergenceControl
)
@pytest.fixture
def test_ctrl_base():
"""
Test that a control class is a subclass of the right abstract classes.
"""
def... |
import PyQt4.pyqtconfig
import os
pyqtcfg = PyQt4.pyqtconfig.Configuration()
print("pyqt_version:%06.0x" % pyqtcfg.pyqt_version)
print("pyqt_version_num:%d" % pyqtcfg.pyqt_version)
print("pyqt_version_str:%s" % pyqtcfg.pyqt_version_str)
pyqt_version_tag = ""
in_t = False
for item in pyqtcfg.pyqt_sip_flags.split(' '):
... |
__all__ = ['admin', 'forms']
from cinemania.admin.forms import *
from cinemania.admin.admin import * |
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if not needle:
return 0
start, l1, l2 = 0, len(haystack), len(needle)
while start < l1:
if start < l1 and star... |
import pandas as pd
df1 = pd.DataFrame( {
"Name" : ["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"] ,
"City" : ["Seattle", "Seattle", "Portland", "Seattle", "Seattle", "Portland"],
"score" : [4, 2, 3, 5, 6, 8] } )
df1 = df1.sort_values(['Name', 'City'], ascending=[1, 0])
g1 = df1.groupby(["City"]).... |
import numpy as np
import matplotlib.pyplot as plt
X, Y = np.meshgrid(np.linspace(-2, 2, 100), np.linspace(-2, 2, 100))
phi = (X - 1.2)**2 * (X + 1.2)**2 + Y**2 - 3
dt = .1
epsilon = 0.001
for i in range(30):
gx, gy = np.gradient(phi)
gradnorm = np.sqrt(gx**2 + gy**2)
phi = phi - dt * np.sign(phi) * (gradno... |
"""quatloo URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/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-bas... |
'''
This decoder stacks on top of the 'i2c' PD and decodes the
Microchip ATSHA204A CryptoAuthentication protocol.
'''
from .pd import Decoder |
"""Define the PV database of a single BPM and its enum types."""
from copy import deepcopy as _dcopy
import numpy as _np
from ... import csdev as _csdev
class ETypes(_csdev.ETypes):
"""Local enumerate types."""
TRIGDIR = ('trn', 'rcv')
TRIGDIRPOL = ('same', 'rev')
TRIGSRC = ('ext', 'int')
TRIGEXTERN... |
from __future__ import unicode_literals
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.db import transaction
from django.shortcuts import get_object_or_404, redirect
from django.urls import reverse
from django.utils.translation import ugettext a... |
source_root_dir = "/home/wildan/PASSION/src"
whitelisted_packages = "".split(';') if "" != "" else []
blacklisted_packages = "".split(';') if "" != "" else []
underlay_workspaces = "/opt/ros/indigo".split(';') if "/opt/ros/indigo" != "" else [] |
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
tree = ttk.Treeview(root)
tree.pack(fill=tk.BOTH,expand=True)
testdict = {"Main": ["Stuff1", "Stuff2"]}
tree.insert("", index="end",iid="Main", text="main branch")
tree.insert("Main", index="end", text="Stuff 1")
tree.insert("Main", index="end", text="Stuff 2"... |
from __future__ import division
import os
import sys
from math import sqrt
import copy
import uuid
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QItemDelegate, QTextEdit, QLineEdit, QDoubleSpinBox, QMessageBox
abs_path = os.path.dirname(__file__)
sys.path.insert(0, abs_path)
import pa... |
"""Authentication module for MyGamePlan."""
import base64
import binascii
import datetime
import functools
import hashlib
import json
import logging
import os
import random
import re
import time
import typing
from typing import Any, Callable, Dict, List, NoReturn, Optional, Tuple, TypedDict
from urllib import parse
imp... |
class Solution:
"""
@param: n: The number of queens
@return: All distinct solutions
"""
def solveNQueens(self, n):
# write your code here
def _dfs(candidate):
dep = len(candidate)
if dep > n: return
if dep == n:
res.append(candidate... |
import pandas as pd
import unittest
import warnings
import nose
import numpy as np
import sys
from pandas import Series
from pandas.util.testing import (
assert_almost_equal, assertRaisesRegexp, raise_with_traceback, assert_series_equal
)
class TestAssertAlmostEqual(unittest.TestCase):
_multiprocess_can_split_ ... |
from __future__ import unicode_literals
import os
from weblate.addons.base import BaseAddon
from weblate.utils.render import render_template
class BaseScriptAddon(BaseAddon):
"""Base class for script executing addons."""
icon = 'file-code-o'
script = None
add_file = None
alert = 'AddonScriptError'
... |
"""Tables inside the database"""
import os
import unittest
import subprocess
from fields import String, Number, Enum, Set, Record, Store
from rbtree import RBDict
from read import scan_file, reading
from server import Server
class Step(Record):
"""Period for the automatic invoicing"""
__slots__ = 'step', 'type'... |
"""This file contains backported functionality from future versions of libraries.
Mostly done with monkey-patching.
"""
def block_diag(*arrs):
import numpy as np
from numpy import atleast_1d, atleast_2d, array
if arrs == ():
arrs = ([],)
arrs = [np.atleast_2d(a) for a in arrs]
bad_args = [k ... |
import pprint
import sys, os
import random
import time
import math
import numpy
from Task import Task
from SimParams import SimParams
from MPEG2FrameTask import MPEG2FrameTask
class MPEG2FrameTask_InterRelatedGOP(MPEG2FrameTask):
# static array
PARALLEL_TASK_GOP_IX = [2,3,4, 5,6,7, 8,9,10,11]
PARALLEL_TAS... |
import os, locale
from .. import Module, Phpclass, Phpmethod, Xmlnode, StaticFile, Snippet, SnippetParam, utils, Readme
class ConfigurationTypeSnippet(Snippet):
snippet_label = 'Configuration Type'
def add(self, config_name, node_name, field_name, extra_params=None):
config_class_name = ''.join(utils.upperfirst(w) ... |
JobRetry = -2
JobError = -1
JobHold = 0
JobScheduled = 1
JobProducing = 2
JobProduced = 3
def jobState2String(jobstate):
if jobstate == JobRetry:
return "%d (JobRetry)" % jobstate
elif jobstate == JobError:
return "%d (JobError)" % jobstate
elif jobstate == JobHold:
return "%d (JobHo... |
"""Project Euler Problem 2
>>> answer()
4613732
"""
def answer():
result = 0
a,b = 1,0
FOUR_MILLION = 4 * 1000 * 1000
while(a <= FOUR_MILLION):
if a % 2 == 0:
result += a
a,b = b+a, a
return result
if __name__ == "__main__":
print( answer() ) |
import cv
import cv2
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
def get_mouse(event, x, y, flags, param):
param.mx = x
param.my = y
do_print = True
if event == cv2.EVENT_MOUSEMOVE:
do_print = False
elif event == cv2.EVENT_LBUTTONDOWN:
if not param.l_butto... |
"""
Copyright (C) <2010> Autin L.
This file ePMV_git/pmv_dev/strutsCommands.py is part of ePMV.
ePMV 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... |
def main():
"""
Excerpt from the user manual of phcpy.
"""
p = ['x^2 + y - 3;', 'x + 0.125*y^2 - 1.5;']
print 'constructing a total degree start system ...'
from phcpy.solver import total_degree_start_system as tds
q, qsols = tds(p)
print 'number of start solutions :', len(qsols)
fro... |
import sys, datetime
DEF = -50 # isn't really needed
INF = 1000000 # wrong number, should be removed or set to correct value
class ParseParamError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
def tab_read_line(lines, n, c):
tab ... |
from django.utils.translation import ugettext_lazy as _
from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.contrib import messages
from apps.models import forms
from django.views.generic.edit ... |
import re
from urllib.parse import urljoin
from requests.utils import dict_from_cookiejar
from sickchill import logger
from sickchill.helper.common import try_int
from sickchill.oldbeard import tvcache
from sickchill.providers.torrent.TorrentProvider import TorrentProvider
class Provider(TorrentProvider):
def __ini... |
import re
import sys
from django.core.management.base import NoArgsCommand
from django.conf import settings as django_settings
from django.db import transaction
from django.utils import translation
from askbot import const
from askbot import models
from askbot import forms
from askbot.utils import console
from askbot.u... |
''' CSHelpers
Module containing functions interacting with the CS and useful for the RSS
modules.
'''
from DIRAC import gConfig, gLogger, S_OK, S_ERROR
from DIRAC.Core.Utilities.SitesDIRACGOCDBmapping import getGOCSiteName
from DIRAC.ResourceStatusSystem.Utilities import... |
if not request.env.web2py_runtime_gae:
## if NOT running on Google App Engine use SQLite or other DB
db = DAL('sqlite://storage.sqlite')
else:
## connect to Google BigTable (optional 'google:datastore://namespace')
db = DAL('google:datastore')
## store sessions and tickets there
session.connect(... |
"""
Warnings
--------
.. deprecated:: 3.2.0
Use :mod:`gensim.models.fasttext` instead.
Python wrapper around word representation learning from FastText, a library for efficient learning
of word representations and sentence classification [1].
This module allows training a word embedding from a training corpus with t... |
import os
import datetime
from GangaCore.Core.exceptions import GangaException
from GangaCore.GPIDev.Schema import Schema, Version, SimpleItem, ComponentItem
from GangaCore.GPIDev.Base import GangaObject
from GangaCore.GPIDev.Base.Proxy import isType, stripProxy, addProxy
from GangaCore.GPIDev.Credentials import requir... |
class replayInfos(object):
def __init__(self) :
self.description = ''
self.size = 0
self.map = ''
self.cheats = False
self.teamLock = False
self.score = True
self.victory = 'demoralization'
self.civilian = 'enemy'
self.Timeouts = -1
se... |
import imdb
import Levenshtein
import unicodedata
from operator import itemgetter
"""
The min Levenshtein distance to consitute a match
"""
minLevenshtein = 0.79
class movieNameRecognition:
def __init__(self):
self.ia = imdb.IMDb() # by default access the web.
def isMatch(self,possibleTitle, title):
isMatch = Fal... |
"""Formula Helpers for reading dimacs
Copyright (C) 2012-2021 Massimo Lauria <massimo.lauria@uniroma1.it>
https://massimolauria.net/cnfgen/
"""
import argparse
from cnfgen.formula.cnf import CNF
from cnfgen.clitools import interactive_msg
from cnfgen.clitools import msg_prefix
from cnfgen.clihelpers.formula_helpers imp... |
"""
A rhythmbox plugin for playing music from baidu music.
Copyright (C) 2013 pandasunny <pandasunny@gmail.com>
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 ... |
from ..visitors import DefaultVisitor
from ..msg import log, warn
from ..ast import *
import sys
class CheckVisitor(DefaultVisitor):
def err(self, msg, context = None):
log('error: %s' % msg, context)
self.has_errors = True
def __init__(self, *args, **kwargs):
super(CheckVisitor, self)._... |
source("../../shared/qtcreator.py")
inputDialog = "{type='QDialog' unnamed='1' visible='1' windowTitle='Extract Function Refactoring'}"
def revertMainCpp():
invokeMenuItem('File', 'Revert "main.cpp" to Saved')
waitFor("object.exists(':Revert to Saved_QMessageBox')", 1000)
clickButton(waitForObject(":Revert ... |
from django.contrib.auth.models import User
from django.db import models
from django import forms
from django.forms import ModelForm, TextInput
import datetime
class Equipo(models.Model):
nombre = models.CharField(max_length=200,verbose_name='Nombre del equipo',unique=True)
def __unicode__(self):
return self.nombre... |
from rest_framework import permissions
class IsOwner(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to edit it.
"""
def has_object_permission(self, request, view, obj):
return obj.owner == request.user |
'''
pyOpt_history
Holds the Python Design Optimization History Class.
Copyright (c) 2008-2013 by pyOpt Developers
All rights reserved.
Revision: 1.0 $Date: 11/12/2009 21:00$
Developers:
-----------
- Dr. Ruben E. Perez (RP)
- Mr. Peter W. Jansen (PJ)
History
-------
v. 1.0 - Initial Class Creation (PJ,RP 2009)
'''
... |
import unittest
from random import random
from timelinelib.drawing.utils import darken_color, lighten_color
class drawing_utils(unittest.TestCase):
def test_darken_color_good_factor(self):
randColor = self.random_color()
randFactor = random()
newColor = darken_color(randColor, randFactor)
... |
from os import path
from codecs import open # To use a consistent encoding
import glob
from setuptools import setup, find_packages
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='atn-tools',
version='0.0.1a... |
from LogAnalyzer import Test,TestResult
import math
class TestNaN(Test):
'''test for NaNs present in log'''
def __init__(self):
Test.__init__(self)
self.name = "NaNs"
def run(self, logdata, verbose):
self.result = TestResult()
self.result.status = TestResult.StatusType.GOOD
... |
from django.db import models
from django.forms import ModelForm
from django import forms
class ficheros_audio(models.Model):
nombre = models.CharField(max_length=80)
descripcion = models.TextField(max_length=200)
# En settings.py --> MEDIA_ROOT = '/home/asterisk-bee/asteriskbee'
fichero_audio = models.FileField(upl... |
from . import report_slae_summury |
import typing as t
from temci.utils.settings import Settings
from temci.utils.typecheck import *
import base64
import hashlib
import os
HOME_DIR = os.path.expanduser("~") # type: str
""" Home directory of the current user """
def hashed_name_of_file(filename: str, block_size: int = 2**20) -> str:
"""
Generates... |
from collections import Counter
def palindrome_rearranging(s):
c = Counter(s)
odd = 0
possible = True
for v in c.values():
if v % 2 != 0:
odd += 1
if odd > 1:
possible = False
break
return possible |
import cv2
import os
import time
from PIL import Image,ImageDraw
i=0
true_num=0
def detectFaces(image_name,Type="Haar"):
img = cv2.imread(image_name)
h,w,z=img.shape
cascadeType={"Haar":"./cascade.xml","LBP":"../LBP/cascade.xml"}
for ih in range(0,h):
for iw in range(0,w/2):
img[ih][... |
from logging import Filter
class MaxLevelFilter(Filter):
"""
Custom logging filter to show multiple logging levels
:param:
:return:
"""
def __init__(self, level):
self.level = level
def filter(self, record):
return record.levelno < self.level |
from django.shortcuts import render, get_object_or_404
from dashboard.models import FunctionalUseCategory
def functional_use_category_list(
request, template_name="functional_use_category/functional_use_category_list.html"
):
categories = FunctionalUseCategory.objects.all().values(
"id", "title", "descr... |
from .exceptions import DownloadFailedError
from .services import ServiceConfig
from .tasks import DownloadTask, ListTask
from .utils import get_keywords
from .videos import Episode, Movie, scan
from collections import defaultdict
from itertools import groupby
import bs4
import guessit
import logging
__all__ = ['SERVIC... |
from intersect import *
def test_slope():
point1 = Point(2.,2.)
point2 = Point(1.,1.)
assert slope(point1, point2) == 1
point3 = Point(0,3.)
point4 = Point(0,1.)
assert slope(point3, point4) == "vert"
p1 = Point(-2.,2.)
p2 = Point(2.,0.)
assert slope(p1,p2) == (-1./2.)
def test_b():
... |
import cuon.TypeDefs
from cuon.Databases.dumps import dumps
from cuon.Logging.logs import logs
import time
from xmlrpclib import ServerProxy
class myXmlRpc(dumps, logs):
"""
@author: Jürgen Hamel
@organization: Cyrus-Computer GmbH, D-32584 Löhne
@copyright: by Jürgen Hamel
@license: GPL ( GNU GENERA... |
from __future__ import absolute_import, unicode_literals
import json
from functools import wraps
from django.core.urlresolvers import reverse
from django.http import (HttpResponse, HttpResponseForbidden,
HttpResponseNotFound, HttpResponseRedirect)
from django.shortcuts import get_object_or_404,... |
import sqlite3
from sdl2.ext import Resources
from utils import dict_factory
DB = Resources(__file__, 'resources', 'db')
class DataBase:
def __init__(self):
self.db_path = DB.get_path('database.sqlite')
def get_all_npc(self):
with sqlite3.connect(self.db_path) as conn:
conn.row_facto... |
from errno import EACCES
import os
import re
try:
from jinja2.exceptions import UndefinedError as JUndefinedError
except ImportError:
# No jinja2 dependency
JUndefinedError = Exception
from cloudinit import handlers
from cloudinit import log as logging
from cloudinit.sources import INSTANCE_JSON_FILE
from c... |
from ._baseclass import ArtBaseClass
from .utils.shrapnel import Shrapnel
from math import sqrt
class Art(ArtBaseClass):
description = "Bubbling pixels"
def __init__(self, matrix, config):
self.pieces = int(sqrt(matrix.numpix))
cycles = int(sqrt(matrix.numpix)*2)
self.shrapnel = [Shrapne... |
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from slugify import slugify
class Event(models.Model):
name = models.CharField(max_length=60)
code = models.CharField(max_length=60, blank=True)
date =... |
from spam_proof_commands.say import SayCommand
from events import Event
from filters.players import PlayerIter
from listeners.tick import Delay
from controlled_cvars.handlers import bool_handler, float_handler
from ..resource.strings import build_module_strings
from .players import player_manager, tell
from .teams impo... |
try:
from plugins.TreesAreMemory3.Constituent import Constituent
from plugins.TreesAreMemory3.operations import Add, Comp, Spec, Adj, Done, Fail
from plugins.TreesAreMemory3.route_utils import get_uid, get_label
except ImportError:
from Constituent import Constituent
from operations import Add, Comp... |
from django.contrib import admin
from .models import Channel
class ChannelAdmin(admin.ModelAdmin):
"""docstring for ChannelAdmin"""
list_display = ('name', 'description')
search_fields = ('name',)
list_filter = ('name',)
admin.site.register(Channel, ChannelAdmin) |
from unittest import TestCase
import os
import sys
import ConfigParser
import cStringIO
import tempfile
import shutil
import debops
__author__ = "Hartmut Goebel <h.goebel@crazy-compilers.com>"
__copyright__ = "Copyright 2014-2015 by Hartmut Goebel "
"<h.goebel@crazy-compilers.com>"
__licence__ = "GNU General Public Lic... |
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
... |
from glob import glob
from sys import stdout
from os import getcwd
def fixHeader(fil, fixln):
stor = []
with open(fil,'r') as info:
for line in info:
stor.append(line)
if len(stor) >= 1:
if len(stor[0]) >= 2:
if stor[0][:2] == "#!":
print("Fixing " + f... |
class AnalysisMethod :
"""
Analysis methods for DUO data.
"""
def __init__(self) :
"""
Initializes necessary variables for this class
"""
def TwoMatrixOperation(self, start_object_1, start_object_2, formula):
"""
Macro for 2D matrix manipulation
Argume... |
import logging
from scap.model.xhtml import *
from scap.model.xhtml.FlowType import FlowType
logger = logging.getLogger(__name__)
class InsTag(FlowType):
MODEL_MAP = {
'attributes': {
'cite': {'type': 'UriType'},
'datetime': {'type': 'DateTimeType'},
},
}
MODEL_MAP['a... |
"""Basic example for a bot that can receive payment from user.
This program is dedicated to the public domain under the CC0 license.
"""
from telegram import (LabeledPrice, ShippingOption)
from telegram.ext import (Updater, CommandHandler, MessageHandler,
Filters, PreCheckoutQueryHandler, Ship... |
from lofar.parameterset import parameterset
from lofar.messagebus.protocols import TaskFeedbackDataproducts
parset = parameterset()
parset.add("foo", "bar")
msg = TaskFeedbackDataproducts(
"from",
"forUser",
"summary",
1,
2,
parset)
from lofar.messagebus.protocols import TaskFeedbackProcessing
parset = para... |
import daqcs_pi_pb2 as daqcs_pi
device = daqcs_pi.Data(id=0)
tempSensor1 = device.tempSensors.add(id=0)
tempSensor2 = device.tempSensors.add(id=1)
tempSensor1.value = 1.125;
tempSensor2.value = -2.25;
pressureSensor = device.pressureSensors.add(id=0)
pressureSensor.value = 0.1875
serialized = device.SerializeToString()... |
"""
Detector options for reduction
"""
from __future__ import (absolute_import, division, print_function)
import xml.dom.minidom
from reduction_gui.reduction.scripter import BaseScriptElement
try:
import mantidplot # noqa
IS_IN_MANTIDPLOT = True
except(ImportError, ImportWarning):
IS_IN_MANTIDPLOT = Fal... |
from gi.repository import Gtk
import sys
import time
import unittest
from mock import Mock
sys.path.insert(0,"../..")
sys.path.insert(0,"..")
import softwarecenter.paths
import softwarecenter.utils
softwarecenter.paths.datadir = "../data"
from softwarecenter.enums import ActionButtons, TransactionTypes
from softwarecen... |
from django.contrib import admin
from .models import Plan
admin.site.register(Plan) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.