code stringlengths 1 199k |
|---|
from datetime import timedelta
import unittest
import mock
from django.test import TestCase
from django.core.urlresolvers import reverse
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group, Permission
from django.core import mail
from django.core.paginator import Paginator
from d... |
def get_file_extension(filename):
return filename.split(".")[-1] |
import pytest
import numpy as np
from numpy.testing import assert_allclose
from .....extern.six.moves import range
from ..mle import design_matrix, periodic_fit
@pytest.fixture
def t():
rand = np.random.RandomState(42)
return 10 * rand.rand(10)
@pytest.mark.parametrize('freq', [1.0, 2])
@pytest.mark.parametrize... |
"""The WaveBlocks Project
IOM plugin providing functions for handling various
overlap matrices of linear combinations of general
wavepackets.
@author: R. Bourquin
@copyright: Copyright (C) 2013 R. Bourquin
@license: Modified BSD License
"""
import numpy as np
def add_overlaplcwp(self, parameters, timeslots=None, matrix... |
"""
__init__.py
.. moduleauthor:: Russell Sim <russell.sim@monash.edu>
"""
import logging
from django.conf import settings
from django.utils.importlib import import_module
from django.core.exceptions import ImproperlyConfigured
from django.db.models.signals import post_save
from django.core.exceptions import Middleware... |
from __future__ import absolute_import
from envisage.ui.single_project.action.configure_action import * |
from __future__ import unicode_literals
import channels.models
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("channels", "0... |
import os
import shutil
import glob
import time
import sys
import subprocess
from optparse import OptionParser, make_option
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PARAMETERS = None
ADB_CMD = "adb"
def doCMD(cmd):
# Do not need handle timeout in this short script, let tool do it
print "-->> \"%s... |
"""
Author
------
Bo Zhang
Email
-----
bozhang@nao.cas.cn
Created on
----------
- Sat Sep 03 12:00:00 2016
Modifications
-------------
- Sat Sep 03 12:00:00 2016
Aims
----
- normalization
Notes
-----
This is migrated from **SLAM** package
"""
from __future__ import division
import numpy as np
from joblib import Paralle... |
from clock import kTicksPerQuarter, quantize_tick_up
class Metronome(object):
"""Plays a steady click every beat.
"""
def __init__(self, sched, synth, channel = 0, patch=(128, 0), pitch = 60):
super(Metronome, self).__init__()
self.sched = sched
self.synth = synth
self.channe... |
from django.core import mail
from django.test import TestCase
from users.default_roles import DefaultGroups
from users.models import Invitation, Membership, OCUser
from communities.tests.common import create_sample_community
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as ... |
"""
gatefilter.py
Driver function that creates an ARTView display and initiates Gatefilter.
"""
import os
import sys
from ..core import Variable, QtGui, QtCore
from ..components import RadarDisplay, Menu
from ._common import _add_all_advanced_tools, _parse_dir, _parse_field
from ..plugins import GateFilter
def run(DirI... |
import logging
def same_ocr_mrz(mrz_data, zones):
last_name_is_valid = mrz_data["last_name"][:25] == zones["last_name"]["value"][:25]
logging.debug(
"MRZ last name: {}; OCR last name: {}; matching {}".format(
mrz_data["last_name"], zones["last_name"]["value"], last_name_is_valid
)
... |
import predict
import sklearn.metrics
import argparse, sys
import os
import numpy as np
import glob
import re
import matplotlib.pyplot as plt
def calc_auc(predictions):
y_true =[]
y_score=[]
for line in predictions:
values= line.split(" ")
y_true.append(float(values[1]))
y_score.append(float(values[0]))
auc =... |
import re
from crispy_forms import layout
from django import forms
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from django.http import HttpResponseRedirect, Http404
from django.utils.translation import gettext_lazy
from cradmin_le... |
"""Git implementation of _version.py."""
import errno
import os
import re
import subprocess
import sys
def get_keywords():
"""Get the keywords needed to look up the version information."""
# these strings will be replaced by git during git-archive.
# setup.py/versioneer.py will grep for the variable names, ... |
"""An example of a python script which can be executed by the task queue
"""
import sys
def execute():
"""Simply write the python executable
"""
sys.stdout.write(sys.executable)
if __name__ == '__main__':
execute() |
from django.conf import settings
from django.db import models
from django.template.context import Context
from django.template.loader import get_template_from_string
from django.utils import timezone
import swapper
class BaseLogEntry(models.Model):
"""
A base class that implements the interface necessary to log... |
from django.conf.urls.defaults import patterns, include
from ietf.wginfo import views, edit, milestones
from django.views.generic.simple import redirect_to
urlpatterns = patterns('',
(r'^$', views.wg_dir),
(r'^summary.txt', redirect_to, { 'url':'/wg/1wg-summary.txt' }),
(r'^summary-by-area.txt', redirect... |
"""Package contenant la commande 'recettes' et ses sous-commandes.
Dans ce fichier se trouve la commande même.
"""
from primaires.interpreteur.commande.commande import Commande
from .editer import PrmEditer
from .lister import PrmLister
from .supprimer import PrmSupprimer
class CmdRecettes(Commande):
"""Commande 'r... |
import urllib2, httplib, threading, os, binascii, urlparse
POST="""\
--%(boundary)s
Content-Disposition: form-data; name="secret"
%(secret)s
--%(boundary)s
Content-Disposition: form-data; name="path"
%(path)s
--%(boundary)s
Content-Disposition: form-data; name="file"; filename="%(path)s"
Content-Type: application/octet... |
from __future__ import unicode_literals
import time
from django.conf import settings
from django.test import TestCase
from django.test.client import FakePayload, Client
from django.utils.encoding import force_text
from tastefulpy.serializers import Serializer
try:
from urllib.parse import urlparse
except ImportErro... |
import fcntl
import inspect
import logging
import os
import psutil
import textwrap
from devil import base_error
from devil import devil_env
from devil.android import device_errors
from devil.android.constants import file_system
from devil.android.sdk import adb_wrapper
from devil.android.valgrind_tools import base_tool... |
"""Presubmit script for Chromium browser resources.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into gcl/git cl, and see
http://www.chromium.org/developers/web-development-style-guide for the rules
we're checking against here.
"""
import os
... |
"""
lit - LLVM Integrated Tester.
See lit.pod for more information.
"""
from __future__ import absolute_import
import math, os, platform, random, re, sys, time
import lit.ProgressBar
import lit.LitConfig
import lit.Test
import lit.run
import lit.util
import lit.discovery
class TestingProgressDisplay(object):
def __... |
from django.template.defaultfilters import rjust
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe
from ..utils import setup
class RjustTests(SimpleTestCase):
@setup({'rjust01': '{% autoescape off %}.{{ a|rjust:"5" }}. .{{ b|rjust:"5" }}.{% endautoescape %}'})
def test_rjust01... |
from sklearn2sql_heroku.tests.classification import generic as class_gen
class_gen.test_model("LogisticRegression" , "BinaryClass_10" , "db2") |
"""An extensible ASCII table reader and writer.
basic.py:
Basic table read / write functionality for simple character
delimited files with various options for column header definition.
:Copyright: Smithsonian Astrophysical Observatory (2011)
:Author: Tom Aldcroft (aldcroft@head.cfa.harvard.edu)
"""
from __future__ ... |
from __future__ import division
import re
from includes.functions import *
class fileserve_com:
def init( self ):
self.url_pattern = re.compile( r'(http://www\.fileserve\.com/file/([A-Za-z0-9]+))', re.I )
self.result_pattern = re.compile( r'<td>(http://www\.fileserve\.com/file/([A-Za-z0-9]+))</td><td>--</td>', re.... |
from django.conf import settings
from django.contrib.auth.decorators import user_passes_test
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse
from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from django.template i... |
"""Ce fichier définit un objet 'importeur', chargé de contrôler le mécanisme
d'importation, initialisation, configuration, déroulement et arrêt
des modules primaires et secondaires.
On parcourt les sous-dossiers définis dans les variables :
- REP_PRIMAIRES : répertoire des modules primaires
- REP_SECONDAIRES : répertoi... |
input_name = '../examples/diffusion/poisson.py'
output_name = 'test_poisson.vtk'
from testsBasic import TestInput
class Test( TestInput ):
pass |
"""
XStatic resource package
See package 'XStatic' for documentation and basic tools.
"""
DISPLAY_NAME = 'Angular-lrdragndrop'
PACKAGE_NAME = 'XStatic-%s' % DISPLAY_NAME
NAME = __name__.split('.')[-1] # package name (e.g. 'foo' or 'foo_bar')
# please use a all-lowercase valid python
... |
from pathlib import Path
import pandas as pd
import lightgbm as lgb
if lgb.compat.MATPLOTLIB_INSTALLED:
import matplotlib.pyplot as plt
else:
raise ImportError('You need to install matplotlib and restart your session for plot_example.py.')
print('Loading data...')
regression_example_dir = Path(__file__).absolut... |
from .sql import *
__all__ = ['DBAdapter', 'get_db_adapter', 'async_atomic', 'async_atomic_func', 'get_db_settings'] |
from __future__ import absolute_import, division, print_function
ANSIBLE_METADATA = {
'status': ['preview'],
'supported_by': 'community',
'metadata_version': '1.1'
}
DOCUMENTATION = '''
---
module: grafana_dashboard
author:
- Thierry Sallé (@seuf)
version_added: "2.5"
short_description: Manage Grafana das... |
from __future__ import division
Symbol = str # A Lisp Symbol is implemented as a Python str
List = list # A Lisp List is implemented as a Python list
Number = (int, float) # A Lisp Number is implemented as a Python int or float
def parse(program):
"Read a Scheme expression from a string."
ret... |
"""Test node disconnect and ban behavior"""
import time
from test_framework.test_framework import GuldenTestFramework
from test_framework.util import (
assert_equal,
assert_raises_rpc_error,
connect_nodes_bi,
wait_until,
)
class DisconnectBanTest(GuldenTestFramework):
def set_test_params(self):
... |
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/loot/collectible/collectible_parts/shared_sculpture_structure_04.iff"
result.attribute_template_id = -1
result.stfName("collectible_loot_items_n","sculpture_structure_04")
#### BEGIN MODIFICATIONS ####
#### END ... |
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import cstr
from frappe.model.document import Document
class LDAPSettings(Document):
def validate(self):
if not self.flags.ignore_mandatory:
self.validate_ldap_credentails()
def validate_ldap_credentails(self):
try:
... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param num, a list of integers
# @return a tree node
def sortedArrayToBST(self, num):
if not num: return None
ln = len(num)
if ln == 1: return TreeNode... |
from PyQt5.QtCore import QObject, pyqtSlot, pyqtSignal
from PyQt5.Qt import QSystemTrayIcon, QIcon
class TrayIcon(QSystemTrayIcon):
ActivationReason = ['Unknown', 'Context', 'DoubleClick', 'Trigger', 'MiddleClick']
onactivate = pyqtSignal(int, str)
onmessageclick = pyqtSignal()
def __init__(self, parent, toolTip... |
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/ship/crafted/reactor/shared_base_reactor_subcomponent_mk5.iff"
result.attribute_template_id = 8
result.stfName("space_crafting_n","base_reactor_subcomponent_mk5")
#### BEGIN MODIFICATIONS ####
#### END MODIFICAT... |
from collections import defaultdict
import pprint
import re
_re_num = re.compile('\s(?P<num>\d+)\s+(?P<name>(RPL|ERR)_\w+)\s*(?P<_>.*)')
_re_mask = re.compile('^\s{24,25}(?P<_>("(<|:).*|\S.*"$))')
def main():
print('Parsing rfc file...')
item = None
items = []
out = open('irc3/_rfc.py', 'w')
with op... |
from sha3 import sha3_256
from ethereum.utils import big_endian_to_int
def sha3(seed):
return sha3_256(bytes(seed)).digest()
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def DEBUG(*args, **kargs):
print(FAIL + repr(args) + repr(kargs) + ENDC)
colors = ['\033[9%dm' % i for i in range... |
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_shaupaut.iff"
result.attribute_template_id = 9
result.stfName("monster_name","shaupaut")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
"""Main view for geo locator application"""
from django.shortcuts import render
def index(request):
if request.location:
location = request.location
else:
location = None
return render(request, "homepage.html", {'location': location}) |
from thrift.Thrift import TType, TMessageType, TException, TApplicationException
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol, TProtocol
try:
from thrift.protocol import fastbinary
except:
fastbinary = None
class ServiceException(TException):
"""
Attributes:
- message: ... |
from flask_login import LoginManager, UserMixin, login_user, logout_user, current_user, login_required
from werkzeug.security import generate_password_hash, check_password_hash
import ctf
class User(UserMixin, ctf.db.Model):
__tablename__ = 'users'
id = ctf.db.Column(ctf.db.Integer, primary_key=True)
userna... |
import sys
import yaml
def fetch_table_data(table_path):
data_dict = {}
with open(table_path) as table_to_load:
# load headers
headers = table_to_load.readline().strip('\n').split('\t')
row_id = 0
for line in table_to_load.readlines():
# print(line)
line_d... |
import unittest
from datetime import datetime
from wechatpy import parse_message
class EventsTestCase(unittest.TestCase):
def test_scan_code_push_event(self):
from wechatpy.events import ScanCodePushEvent
xml = """<xml>
<ToUserName><![CDATA[gh_e136c6e50636]]></ToUserName>
<FromUserNa... |
r"""Module doctest -- a framework for running examples in docstrings.
In simplest use, end each module M to be tested with:
def _test():
import doctest
doctest.testmod()
if __name__ == "__main__":
_test()
Then running the module as a script will cause the examples in the
docstrings to get executed and verif... |
'''
Created on Mar 19, 2014
@author: Simon
'''
from engine.engine_job import EngineJob
class ValidationJob(EngineJob):
'''
M/R job for validating a trained model.
'''
def mapper(self, key, values):
data_processor = self.get_data_processor()
data_processor.set_data(values)
data_pr... |
"""Functionality to query and extract information from aligned BAM files.
"""
import collections
import contextlib
import os
import itertools
import signal
import subprocess
import numpy
import pysam
import toolz as tz
from bcbio import utils
from bcbio.bam import ref
from bcbio.distributed import objectstore
from bcbi... |
import os
import pytest
from som.vm.current import current_universe
@pytest.mark.parametrize(
"test_name",
[
"Array",
"Block",
"ClassLoading",
"ClassStructure",
"Closure",
"Coercion",
"CompilerReturn",
"DoesNotUnderstand",
"Double",
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import time
import numpy as np
import tensorflow as tf
from tensorboard.plugins.beholder import im_util
from tensorboard.plugins.beholder.file_system_tools import read_pickle,\
write_pickle, write_fi... |
import csv
import re
from io import TextIOWrapper
from django.conf import settings
from django.core.cache import cache
from django.utils.termcolors import colorize
if settings.DEBUG:
from clog.clog import clog
else:
def clog(*args, **kwargs):
pass
def pop_first(data, key):
"""Pop the given key from ... |
from __future__ import absolute_import
from .nihts_xcam import XenicsCamera |
import re
from django.db import migrations
def add_project_member(apps, schema_editor):
# Using historical versions as recommended for RunPython
PublicDataAccess = apps.get_model("public_data", "PublicDataAccess")
DataRequestProjectMember = apps.get_model(
"private_sharing", "DataRequestProjectMembe... |
import os, json, frappe
from frappe.utils.momentjs import get_all_timezones
def get_country_info(country=None):
data = get_all()
data = frappe._dict(data.get(country, {}))
if 'date_format' not in data:
data.date_format = "dd-mm-yyyy"
if 'time_format' not in data:
data.time_format = "HH:mm:ss"
return data
def g... |
import csv
import math
import sys
data = []
with open(sys.argv[1], 'rb') as f:
reader = csv.DictReader(f)
for row in reader:
if row['year'] != '2015':
continue
if row['birthdate'] and row['gender']:
data.append({
'age': 2016 - int(math.floor(float(row['bir... |
from .stop_words import STOP_WORDS
from .lex_attrs import LEX_ATTRS
from .punctuation import TOKENIZER_SUFFIXES
from ...language import Language, BaseDefaults
class UrduDefaults(BaseDefaults):
suffixes = TOKENIZER_SUFFIXES
lex_attr_getters = LEX_ATTRS
stop_words = STOP_WORDS
writing_system = {"direction... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Control',
fields=[
('id', models.AutoField(auto_created=T... |
try:
import Blender
try:
from Blender import Mesh
from Blender import Lamp
except Exception, detail:
print detail
except ImportError:
pass
import md5, random, binascii, cStringIO, copy, Image, math, struct, StringIO, os, os.path, pickle
from prp_Types import *
from prp_DXTConv im... |
"""
***************************************************************************
MultipleExternalInputDialog.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
(C) 2013 by CS Systemes d'information (CS SI)
Email ... |
"""QGIS Unit tests for QgsLayoutView.
.. 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__ = 'Nyall Dawson'
... |
'''
Created on 25 April 2014
@author: Kimon Tsitsikas
Copyright © 2013-2014 Kimon Tsitsikas, Delmic
This file is part of Odemis.
Odemis is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License version 2 as published by the Free Software
Foundation.
Odemis is distribut... |
import k3d
import testing
setup = testing.setup_mesh_modifier_test("PolyGrid", "ExtrudeFaces")
setup.source.rows = 3
setup.source.columns = 3
selection = k3d.geometry.selection.create(0)
face_selection = k3d.geometry.primitive_selection.create(selection, k3d.selection.type.FACE)
k3d.geometry.primitive_selection.append(... |
"""
Support for buildsets in the database
"""
import sqlalchemy as sa
from buildbot.db import base
from buildbot.util import datetime2epoch
from buildbot.util import epoch2datetime
from buildbot.util import json
from twisted.internet import reactor
class BsDict(dict):
pass
class BuildsetsConnectorComponent(base.DBC... |
"""
***************************************************************************
EditScriptDialog.py
---------------------
Date : December 2012
Copyright : (C) 2012 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
********************************... |
import os
from optparse import OptionParser,OptionGroup
import sys
import cStringIO
from bio_pieces import fasta
from bio_pieces.fasta import UnknownIdentifierLineException
class SequenceConcat:
_fasta_file_path = None
_strip_chars = ""
_parsed_fasta = None
def __init__( self, fasta_file, file_type = 'g... |
import os, re, sys
if len(sys.argv) < 2:
print "usage: %s <recordfile>" % sys.argv[0]
sys.exit(1)
filename = sys.argv[1]
fd = file(filename)
record = fd.read()
fd.close()
newrecord = []
lbreak = "\r\n"
for line in record.splitlines():
if line.startswith('# Revision:'):
rev = int(line.split(':')[1]) ... |
"""
HDL Testing Platform
REST API for HDL TP # noqa: E501
OpenAPI spec version: 1.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import swagger_client
from swagger_client.models.task import Task # noqa: E501
from swagger_cl... |
from __future__ import print_function
from sqlalchemy import create_engine
from sqlalchemy.pool import NullPool
import sqlalchemy
import sys
SCHEMA_VERSION = 1
engine = None
def init_db_engine(connect_str):
global engine
engine = create_engine(connect_str, poolclass=NullPool)
def run_sql_script(sql_file_path):
... |
from opus_core.configuration import Configuration
class JobsEventModelConfigurationCreator(object):
_model_name = 'agent_event_model'
def __init__(self,
location_set = 'gridcell',
agent_set = 'job',
agent_event_set = 'jobs_event'):
self.location_set = loca... |
import os.path
import gtk
import logging
import pango
from gtk import gdk
from locale import strcoll
from translate.lang import factory as lang_factory
from translate.storage import factory as store_factory
from virtaal.common.pan_app import ui_language
from virtaal.views.baseview import BaseView
from virtaal.views imp... |
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Campaign.photo'
db.delete_column(u'campaign_campaign', 'photo')
# Adding f... |
"""
Motion correction of image sequences by 'efficient subpixel image registration
by cross correlation'. A reference image is iteratively computed by aligning
and averaging a subset of images/frames.
2015 Lloyd Russell, Christoph Schmidt-Hieber
**************************************************************************... |
import GemRB
import GUIClasses
import GUICommon
import GUICommonWindows
import CommonWindow
import GUIWORLD
from GameCheck import MAX_PARTY_SIZE
from GUIDefines import *
MessageWindow = 0
ActionsWindow = 0
PortraitWindow = 0
OptionsWindow = 0
MessageTA = 0
def OnLoad():
global MessageWindow, ActionsWindow, PortraitWin... |
""" PyroScope - Controller "torrent".
Copyright (c) 2009 The PyroScope Project <pyroscope.project@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 2 of the Lic... |
from Queue import Empty
from multiprocessing import Process, Queue
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import widgets
from scipy import interpolate
from labrad.units import Unit
V, mV, us, GHz, rad = [Unit(s) for s in ('V', 'mV', 'us', 'GHz', 'rad')]
from pyle.dataking import utilMultilev... |
__author__ = 'leviwright'
from mainbot.commands import Command
class NickServLogin(Command):
arguments = []
permissionLevel = 3
permitExtraArgs = False
manArgCheck = False
defaultArgs = []
callName = "login"
def on_call(self, event, *args):
self.bot.connection.privmsg("NickServ", "id... |
import os
import re
from avocado import Test
from avocado.utils import archive
from avocado.utils import build
from avocado.utils import distro
from avocado.utils import process
from avocado.utils.software_manager import SoftwareManager
class GDB(Test):
def setUp(self):
sm = SoftwareManager()
dist =... |
"""Test permissions of user account REST API."""
import json
from invenio_db import db
from flask import url_for
from invenio_accounts.models import User
from invenio_oauth2server.models import Token
from invenio_oauth2server import current_oauth2server
from b2share_unit_tests.helpers import create_user
def test_accoun... |
from distutils.core import setup
from spacewalk.common.rhnConfig import CFG, initCFG
initCFG('web')
setup(name = "rhnclient",
version = "5.5.9",
description = CFG.PRODUCT_NAME + " Client Utilities and Libraries",
long_description = CFG.PRODUCT_NAME + """\
Client Utilities
Includes: rhn_check, action ... |
import hashlib
import itertools
import sqlalchemy as sa
from buildbot.util import unicode2bytes
class DBConnectorComponent:
# A fixed component of the DBConnector, handling one particular aspect of
# the database. Instances of subclasses are assigned to attributes of the
# DBConnector object, so that they ... |
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework.views import APIView
class IndexView(APIView):
def get(self, request, *args, **kwargs):
"""List API resources."""
return Response({
'projects': reverse('api-project-list', request=... |
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from osgeo import ogr
from ui_widgetGrid import Ui_GdalToolsWidget as Ui_Widget
from widgetPluginBase import GdalToolsBasePluginWidget as BasePluginWidget
import GdalTools_utils as Utils
class GdalToolsDialog(QWidget, Ui... |
import sys, re
mnemonics="mov,and,or,xor,add,adc,sto,ld,ror,jsr,sub,sbc,inc,lsr,dec,asr,halt,bswp,putpsr,getpsr,rti,not,out,in,push,pop,cmp,cmpc".split(",")
op = dict([(opcode,mnemonics.index(opcode)) for opcode in mnemonics])
dis = dict([(mnemonics.index(opcode),opcode) for opcode in mnemonics])
pred_dict = {0:"",1:"0... |
"""test building messages with streamsession"""
import os
import uuid
from datetime import datetime
import zmq
from zmq.tests import BaseZMQTestCase
from zmq.eventloop.zmqstream import ZMQStream
from IPython.kernel.zmq import session as ss
from IPython.testing.decorators import skipif, module_not_available
from IPython... |
import getopt
import os
import sys
import shutil
from math import asin, cos, radians, sin, sqrt
from PIL import Image
from lib.exif_pil import PILExifReader
class GPSDirectionDuplicateFinder:
"""Finds duplicates based on the direction the camera is pointing.
This supports the case where a panorama is being made."... |
"""Manifest clonning tools.."""
import json
import requests
import six
import time
import uuid
import zipfile
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
from nailgun import entiti... |
import re
from module.plugins.Hoster import Hoster
class VeehdCom(Hoster):
__name__ = 'VeehdCom'
__type__ = 'hoster'
__pattern__ = r'http://veehd\.com/video/\d+_\S+'
__config__ = [
('filename_spaces', 'bool', "Allow spaces in filename", 'False'),
('replacement_char', 'str', "Filename rep... |
import math
def is_palindrome(n):
s = str(n)
return s == s[::-1]
def is_prime(n):
if n <= 1:
return False
if n % 2 == 0 and n != 2:
return False
if n == 2:
return True
root = math.sqrt(n)
i = 3
while i <= root:
if n % i == 0:
return False
... |
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import flt
from frappe.model.document import Document
from erpnext.stock.doctype.serial_no.serial_no import get_serial_nos
class LandedCostVoucher(Document):
def get_items_from_purchase_receipts(self):
self.set("items", [])
... |
"""
PILKit image processors.
A processor accepts an image, does some stuff, and returns the result.
Processors can do anything with the image you want, but their responsibilities
should be limited to image manipulations--they should be completely decoupled
from the filesystem.
"""
from .base import *
from .crop import ... |
JvR_links = (
("http://www.endgame.nl/match.htm", "http://www.endgame.nl/MATCHPGN.ZIP"),
("http://www.endgame.nl/bad1870.htm", "http://www.endgame.nl/bad1870.pgn"),
("http://www.endgame.nl/wfairs.htm", "http://www.endgame.nl/wfairs.pgn"),
("http://www.endgame.nl/russia.html", "http://www.endgame.nl/Russ... |
class HfstException:
## A message describing the error in more detail.
def what():
pass
class HfstTransducerTypeMismatchException(HfstException):
pass
class ImplementationTypeNotAvailableException(HfstException):
pass
class FunctionNotImplementedException(HfstException):
pass
class FlagDiacr... |
import qa
import re
import numpy
have_use = re.compile("^\s{1,12}use\s")
remove_warn = re.compile('''(?!.*QA_WARN .+)''', re.VERBOSE)
unwanted = re.compile("(\s|&|\n)", re.VERBOSE)
def do_magic(files, options):
name = files[0]
glob = []
temp = []
for f in files[2:]:
lines = open(f, 'r').readline... |
KEY = 'miclaveparafirmarurls';
def index():
"""
Pantalla de bienvenida estatica,
sólo muestra un enlace hacia el manejador
"""
return dict()
@auth.requires_login()
def manager():
"""
Permite crear eventos nuevos, ver/copiar los creados por otros
y editar los que se fueron creados por el usuario a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.