content string |
|---|
"""
=============================
Species distribution modeling
=============================
Modeling species' geographic distributions is an important
problem in conservation biology. In this example we
model the geographic distribution of two south american
mammals given past observations and 14 environmental
varia... |
# -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsCheckableComboBox
.. 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.
"... |
from __future__ import print_function
from builtins import range
from airflow.operators import PythonOperator
from airflow.models import DAG
from datetime import datetime, timedelta
import time
from pprint import pprint
seven_days_ago = datetime.combine(datetime.today() - timedelta(7),
... |
#!/usr/bin/env python
import sys,re,time,argparse
def main(args):
# print >>sys.stdout, "Start analysis: " + time.strftime("%a,%d %b %Y %H:%M:%S")
output_gpd(args.input,args.output,args.length,args.ratio)
# print >>sys.stdout, "Finish analysis: " + time.strftime("%a,%d %b %Y %H:%M:%S")
def extract_exon_length_from_c... |
#!/usr/bin/env python3
########################################################
#
# A simple middleware to submit a scan report
# assessment results
#
# Usage:
# python sar_etl.py <apikey> <sar_service_url> [-s <system_id>] [-d <deployment_uuid>]
#
# Example:
# python sar_etl.py eCXZbZwmBrtD5hgrJ8ptmJfvDA5vlDcc ht... |
from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration
mname = "facebook/wmt19-en-de"
tokenizer = FSMTTokenizer.from_pretrained(mname)
# get the correct vocab sizes, etc. from the master model
config = FSMTConfig.from_pretrained(mname)
config.update(dict(
d_model=4,
encoder_layers=1, d... |
from gnuradio import gr, gr_unittest, blocks
class test_throttle(gr_unittest.TestCase):
def setUp(self):
self.tb = gr.top_block()
def tearDown(self):
self.tb = None
def test_01(self):
# Test that we can make the block
op = blocks.throttle(gr.sizeof_gr_complex, 1)
if __na... |
"""
Tests specific to the CourseRerunState Model and Manager.
"""
from django.test import TestCase
from opaque_keys.edx.locations import CourseLocator
from six import text_type
from course_action_state.managers import CourseRerunUIStateManager
from course_action_state.models import CourseRerunState
from student.test... |
__author__ = "V.A. Sole - ESRF Software Group"
import numpy
try:
from PyMca import StackBrowser
from PyMca.PyMcaSciPy.signal import median
except ImportError:
print("Median2DBrowser importing directly!")
import StackBrowser
from PyMcaSciPy.signal import median
medfilt2d = median.medfilt2d
qt = Stac... |
# encoding: utf-8
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 'Project.repo_type'
db.add_column('projects_project', 'repo_type', self.gf('django.db.models.fields... |
import os
import sys
import pipes
import shutil
import subprocess
"""
This plugin uses glue to sprite images:
http://glue.readthedocs.org/en/latest/quickstart.html
Install:
(Only if you want to sprite jpg too)
brew install libjpeg
sudo easy_install pip
sudo pip uninstall pil
sudo pip install pil
sudo pip install gl... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
import re
import json
from ansible.module_utils.basic import AnsibleModule
from ansible.modu... |
from __future__ import print_function, unicode_literals
import frappe
from frappe.utils import flt, cstr, nowdate, nowtime
from erpnext.stock.utils import update_bin
from erpnext.stock.stock_ledger import update_entries_after
from erpnext.controllers.stock_controller import update_gl_entries_after
def repost(only_actu... |
"""
EXPERIMENTAL CODE!
Here we load a .TTF font file, and display it in
a basic pygame window. It demonstrates several of the
Font object attributes. Nothing exciting in here, but
it makes a great example for basic window, event, and
font management.
"""
import pygame
import math
from pygame.locals import *
from pyg... |
import proto # type: ignore
__protobuf__ = proto.module(
package="google.ads.googleads.v6.enums",
marshal="google.ads.googleads.v6",
manifest={"AppPaymentModelTypeEnum",},
)
class AppPaymentModelTypeEnum(proto.Message):
r"""Represents a criterion for targeting paid apps."""
class AppPaymentMod... |
from bz2 import BZ2File
import gzip
from io import BytesIO
import numpy as np
import os
import shutil
from tempfile import NamedTemporaryFile
from sklearn.externals.six import b
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert... |
from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from django.views import generic
from oscar.core.application import Application
from oscar.core.loading import get_class
class CustomerApplication(Application):
name = 'customer'
summary_view = get_class('customer.view... |
import pilas
from pilas.actores import Actor
class Mapa(Actor):
"""Representa mapas creados a partir de imagenes mas pequeñas.
Este actor te permite crear escenarios tipo ``tiles``, una técnica
de contrucción de escenarios muy popular en los videojuegos.
Puedes crear un actor a partir de una gri... |
#!/usr/bin/python3
import numpy as np
import matplotlib.pyplot as plt
import sys
class Src:
def __init__(self, fname, block_size, navg = 1):
self.offs = 0
self.navg = navg
self.block_size = block_size
self.data = np.fromfile(fname, dtype=np.float32)
l = divmod(len(self.dat... |
from bitlist.models.user import User
from bitlist.models.song import Song
from bitlist.models.playlist import Playlist
import jobs
import json
import player
from pyramid.security import remember
from pyramid.security import forget
from pyramid.view import view_config
from pyramid.view import forbidden_view_config
from ... |
# Created by CubicVirtuoso
# Any problems feel free to drop by #l2j-datapack on irc.freenode.net
import sys
from net.sf.l2j.gameserver.model.quest import State
from net.sf.l2j.gameserver.model.quest import QuestState
from net.sf.l2j.gameserver.model.quest.jython import QuestJython as JQuest
#NPCs
MIRABEL = 7146
ARI... |
from urlparse import urlparse
from threading import Thread
import httplib, sys, multiprocessing
from Queue import Queue
import simplejson
import time
import base64
num_processes = int(sys.argv[1])
num_threads = int(sys.argv[2])
num_requests = int(sys.argv[3])
num_metrics_per_request = int(sys.argv[4])
series_name = sy... |
import win32security,win32api,win32con, win32process
new_privs = ((win32security.LookupPrivilegeValue('',win32security.SE_SECURITY_NAME),win32con.SE_PRIVILEGE_ENABLED),
(win32security.LookupPrivilegeValue('',win32security.SE_TCB_NAME),win32con.SE_PRIVILEGE_ENABLED),
(win32security.LookupPrivil... |
# -*- coding: utf-8 -*-
"""
Acceptance tests for Video.
"""
from .helpers import UniqueCourseTest
from ..pages.lms.video import VideoPage
from ..pages.lms.tab_nav import TabNavPage
from ..pages.studio.auto_auth import AutoAuthPage
from ..pages.lms.course_info import CourseInfoPage
from ..fixtures.course import Course... |
from math import log10
from django.core.exceptions import ObjectDoesNotExist
from elasticsearch_dsl.search import Search as dslSearch
from statsd import statsd
from mkt.constants.base import VALID_STATUSES
class Search(dslSearch):
def execute(self):
with statsd.timer('search.execute'):
res... |
import contextlib
import copy
import itertools
import time
import mock
from oslo.config import cfg
import testtools
from neutron.agent.linux import ovs_lib
from neutron.extensions import securitygroup as ext_sg
from neutron.plugins.nec.agent import nec_neutron_agent
from neutron.tests import base
DAEMON_LOOP_COUNT =... |
from OpenSSL import crypto
TYPE_RSA = crypto.TYPE_RSA
TYPE_DSA = crypto.TYPE_DSA
def retrieve_key_from_file(keyfile):
fo = open(keyfile, 'r')
buf = fo.read()
keypair = crypto.load_privatekey(crypto.FILETYPE_PEM, buf)
return keypair
def retrieve_cert_from_file(certfile):
fo = open(certfile, 'r')
... |
#
# $Id$
#
from sphinxapi import *
import sys, time
if not sys.argv[1:]:
print "Usage: python test.py [OPTIONS] query words\n"
print "Options are:"
print "-h, --host <HOST>\tconnect to searchd at host HOST"
print "-p, --port\t\tconnect to searchd at port PORT"
print "-i, --index <IDX>\tsearch through index(es) s... |
from __future__ import unicode_literals
def get_notification_config():
return { "for_doctype":
{
"Issue": {"status": "Open"},
"Warranty Claim": {"status": "Open"},
"Task": {"status": ("in", ("Open", "Overdue"))},
"Project": {"status": "Open"},
"Item": {"total_projected_qty": ("<", 0)},
"Lead": {"s... |
"""distutils.archive_util
Utility functions for creating archive files (tarballs, zip files,
that sort of thing)."""
# This module should be kept compatible with Python 2.1.
__revision__ = "$Id: archive_util.py,v 1.17 2004/11/10 22:23:13 loewis Exp $"
import os
from distutils.errors import DistutilsExecError
from d... |
import datetime
from operator import attrgetter
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import DEFAULT_DB_ALIAS
from django.test import TestCase
from django.utils import tzinfo
from models import (Worker, Article, Party, Event, Department,
BrokenUnicodeMe... |
# -*- coding: utf-8 -*-
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 model 'SearchableTool'
db.create_table('search_searchabletool', (
('id', self.gf(
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.acme import (
ModuleFailException, ACMEAccount
)
import os
i... |
VERSION = [1, 1, 0]
from .aes import AES, AESModeOfOperationCTR, AESModeOfOperationCBC, AESModeOfOperationCFB, AESModeOfOperationECB, AESModeOfOperationOFB, AESModesOfOperation, Counter
from .blockfeeder import Decrypter, Encrypter |
import json
from tests.factories import (
RequestFactory,
ResponseFactory,
)
def test_path_property():
request = RequestFactory(url='http://www.example.com/blog/25')
assert request.path == '/blog/25'
def test_query_property():
request = RequestFactory(url='http://www.example.com/api/?token=1234... |
from sickbeard import helpers
from sickbeard import logger
meta_session = helpers.make_session()
def getShowImage(url, imgNum=None):
if url is None:
return None
# if they provided a fanart number try to use it instead
if imgNum is not None:
tempURL = url.split('-')[0] + "-" + str(imgNum)... |
#!/usr/bin/env python
import sys
import argparse
from fastavro import writer
parser = argparse.ArgumentParser()
parser.add_argument('output_file', help='Output Avro data file')
parser.add_argument('--num_records', dest='num_records', default=1024, type=int, help='Number of records to generate (default: 1024)')
parser.... |
"""
Google Voice SMS platform for notify component.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/notify.google_voice/
"""
import logging
from homeassistant.components.notify import (
ATTR_TARGET, DOMAIN, BaseNotificationService)
from homeassistant... |
# A 'tree' is a networkx.DiGraph with a single root node (a node without parents)
from operator import itemgetter
from networkx import Graph, DiGraph
from collections import defaultdict
from math import sqrt
from itertools import izip, islice
from catmaid.models import Treenode
def find_root(tree):
""" Search and... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
from ansible.compat.tests.mock import patch
from ansible.modules.network.ovs import openvswitch_bridge
from .ovs_module import TestOpenVSwitchModule, load_fixture, set_module_args
test_name_side_effect_matrix = {
... |
import sqlalchemy as orm
def upgrade(migrate_engine):
meta = orm.MetaData()
meta.bind = migrate_engine
idp_table = orm.Table('identity_provider', meta, autoload=True)
remote_id_table = orm.Table(
'idp_remote_ids',
meta,
orm.Column('idp_id',
orm.String(64),
... |
import pytest
@pytest.mark.parametrize(
"filter_string, expected_result",
[
("h=28 or w=6 or l=2", True),
("r.params.get.param2='2'", True),
("r.headers.response.Location", "https://wfuzz.readthedocs.io/en/latest/"),
("r.headers.response.notthere", {}),
("r.params.get.n... |
import imp
import logging
import os
import sys
from optparse import OptionParser, make_option
from django import VERSION as DJANGO_VERSION
from django.conf import ENVIRONMENT_VARIABLE as SETTINGS_ENVIRONMENT_VARIABLE
from django.core.exceptions import ImproperlyConfigured
from django.core.management import base
from ... |
from __future__ import absolute_import
import itertools
import logging
import time
import click
from populus.compilation import (
compile_project_contracts,
)
from .accounts import (
is_account_locked,
)
from .compile import (
write_compiled_sources,
)
from .contracts import (
verify_contract_byteco... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
################################################################################
# Documentation
################################################################################
ANSIBLE_METADATA = {'metadata_version': '1.1', 'statu... |
import string, random
words = open("Alice's Adventures in Wonderland by Lewis Carroll.txt").read().split('\n')
xwords = open('words.txt').read().split('\n')
emma = open('Emma by Jane Austen.txt').read().split('\n')
def break_book_into_words(book):
#apostrophes are a problem, don't => dont
lower_book = ''
... |
# -*- coding: utf-8 -*-
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 'Artist.spotify_artist_href'
db.add_column(u'history_artist', 'spotify_artist_href',
... |
'''
Steps for problem.feature lettuce tests
'''
# pylint: disable=missing-docstring
# pylint: disable=redefined-outer-name
from lettuce import world, step
from common import i_am_registered_for_the_course, visit_scenario_item
from problems_setup import PROBLEM_DICT, answer_problem, problem_has_answer, add_problem_to_... |
from __future__ import absolute_import
from pychron.core.ui.factory import toolkit_factory
DisplayEditor = toolkit_factory('display_editor', 'DisplayEditor')
LoggerEditor = toolkit_factory('display_editor', 'LoggerEditor')
# ============= EOF ============================================= |
from test_plus.test import TestCase
from ..admin import MyUserCreationForm
class TestMyUserCreationForm(TestCase):
def setUp(self):
self.user = self.make_user()
def test_clean_username_success(self):
# Instantiate the form with a new username
form = MyUserCreationForm({
... |
# * *************************************************************
# *
# * Soft Active Mater on Surfaces (SAMoS)
# *
# * Author: Rastko Sknepnek
# *
# * Division of Physics
# * School of Engineering, Physics and Mathematics
# * University of Dundee
# *
# * (c) 2013, 2014
# *
# * School of Scienc... |
"""
Module simplifying manipulation of XML described at
http://libvirt.org/formatnetwork.html
"""
import logging
from virttest import virsh, xml_utils
from virttest.libvirt_xml import base, xcepts, accessors
class RangeList(list):
"""
A list of start & end address tuples
"""
def __init__(self, iterab... |
from urllib import urlencode
from weboob.deprecated.browser import Browser, BrowserIncorrectPassword
from .pages import HomePage, MessagesPage, LogoutPage, LogoutOkPage, \
AlreadyConnectedPage, ExpiredPage, MovementsPage, RootPage
__all__ = ['LCLEnterpriseBrowser']
class LCLEnterpriseBrowser(Browser):
BAS... |
# -*- coding: utf-8 -*-
"""Word cloud integration tests using mongo modulestore."""
import json
from operator import itemgetter
from . import BaseTestXmodule
from xmodule.x_module import STUDENT_VIEW
class TestWordCloud(BaseTestXmodule):
"""Integration test for word cloud xmodule."""
CATEGORY = "word_cloud"... |
"""Support for Wink lights."""
import pywink
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_COLOR_TEMP,
ATTR_HS_COLOR,
SUPPORT_BRIGHTNESS,
SUPPORT_COLOR,
SUPPORT_COLOR_TEMP,
LightEntity,
)
from homeassistant.util import color as color_util
from homeassistant.util.color i... |
import rospy
from sensor_msgs.msg import Image
from std_msgs.msg import String
from cv_bridge import CvBridge
import cv2
import numpy as np
import tensorflow as tf
import classify_image
class RosTensorFlow():
def __init__(self):
classify_image.maybe_download_and_extract()
self._session = tf.Sessio... |
import operator
import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
from pandas.arrays import BooleanArray
from pandas.tests.extension.base import BaseOpsUtil
class TestLogicalOps(BaseOpsUtil):
def test_numpy_scalars_ok(self, all_logical_operators):
a = pd.array([True, Fals... |
#!/usr/bin/python
"""Test of HTML list presentation."""
from macaroon.playback import *
import utils
sequence = MacroSequence()
#sequence.append(WaitForDocLoad())
sequence.append(PauseAction(5000))
# Work around some new quirk in Gecko that causes this test to fail if
# run via the test harness rather than manuall... |
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
import cyclope.settings as cyc_settings
from django.conf import settings
from models import *
class AnswerInline(admin.StackedInline):
model = Answer
class QuestionAdmin(admin.ModelAdmin):
inlines = [AnswerInline]
li... |
import unittest
import os
import comm
import zipfile
import shutil
from xml.etree import ElementTree
import json
class TestCrosswalkApptoolsFunctions(unittest.TestCase):
def test_create_pkg_basic(self):
comm.setUp()
os.chdir(comm.XwalkPath)
comm.clear("org.xwalk.test")
os.mkdir("o... |
from oslo.config import cfg
from nova.api.openstack import common
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api.openstack import xmlutil
from nova import availability_zones
from nova import db
from nova import servicegroup
CONF = cfg.CONF
authorize_list = extensions.exte... |
#!/usr/bin/python
try:
import setuptools
except ImportError:
import ez_setup
ez_setup.use_setuptools()
from setuptools import setup, find_packages
import sys, os
from cogen import __version__ as version
setup(
name='cogen',
version=version,
description='''
Coroutines... |
"""RSA module
Module for calculating large primes, and RSA encryption, decryption,
signing and verification. Includes generating public and private keys.
WARNING: this implementation does not use random padding, compression of the
cleartext input to prevent repetitions, or other common security improvements.
Use with... |
# workserver.py - simple HTTP server with a do_work / stop_work API
# GET /do_work activates a worker thread which uses CPU
# GET /stop_work signals worker thread to stop
import math
import socket
import threading
import time
from bottle import route, run
hostname = socket.gethostname()
hostport = 9000
keepworking = ... |
#coding: utf-8
import sqlite3
from pkg_resources import parse_version
__version__ = "0.2.1"
__author__ = "Mickael Desfrenes"
__email__ = "<EMAIL>"
# Yen 2013.04.08, 將 Python2 的 .next() 改為 next(), 以便在 Python 3 中使用
class SQLiteWriter(object):
"""
In frozen mode (the default), the writer will not alter db sche... |
import gettext
import httplib
import logging
import socket
from M2Crypto.SSL import SSLError
import rhsm.config
from subscription_manager import injection as inj
from subscription_manager import listing
from subscription_manager import rhelproduct
_ = gettext.gettext
log = logging.getLogger('rhsm-app.' + __name__)... |
"""
test_aggregate
----------------------------------
Functional tests for `shade` aggregate resource.
"""
from openstack.tests.functional import base
class TestAggregate(base.BaseFunctionalTest):
def test_aggregates(self):
aggregate_name = self.getUniqueString()
availability_zone = self.getUni... |
from . import ProtocolHandler
import select, socket
from cStringIO import StringIO
class TCPHandler(ProtocolHandler):
"""
TCPHandler acts as a generic TCP forwarder.
Data will be .log()ed, but not stored any further.
"""
def handle_messages(self):
self.c.establish_server_connection()
... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
proximity.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
*****************************... |
import os, unittest
from ctypes import *
try:
WINFUNCTYPE
except NameError:
# fake to enable this test on Linux
WINFUNCTYPE = CFUNCTYPE
import _ctypes_test
lib = CDLL(_ctypes_test.__file__)
class CFuncPtrTestCase(unittest.TestCase):
def test_basic(self):
X = WINFUNCTYPE(c_int, c... |
import mock
import os
from os import path
import sys
import unittest
from test_inventory import cleanup
from test_inventory import get_inventory
from test_inventory import make_config
INV_DIR = 'inventory'
sys.path.append(path.join(os.getcwd(), INV_DIR))
from osa_toolkit import filesystem as fs
TARGET_DIR = path.j... |
from amqpstorm.compatibility import json
from amqpstorm.compatibility import quote
from amqpstorm.management.base import ManagementHandler
from amqpstorm.message import Message
API_BASIC_PUBLISH = 'exchanges/%s/%s/publish'
API_BASIC_GET_MESSAGE = 'queues/%s/%s/get'
class Basic(ManagementHandler):
def publish(sel... |
from __future__ import unicode_literals, division, absolute_import
import logging
import re
from urllib import quote
from flexget import plugin
from flexget import validator
from flexget.entry import Entry
from flexget.event import event
from flexget.utils.soup import get_soup
from flexget.utils.search import torrent... |
from distutils.version import LooseVersion
from ccmlib.node import NodetoolError
from dtest import Tester
from jmxutils import apply_jmx_authentication
from tools import known_failure, since
@since('3.6')
class TestJMXAuth(Tester):
@known_failure(failure_source='test',
jira_url='https://issu... |
"""Stanford Online Products Dataset."""
import csv
import os
import tensorflow.compat.v2 as tf
import tensorflow_datasets.public_api as tfds
_DOWNLOAD_LINK = "ftp://cs.stanford.edu/cs/cvgl/Stanford_Online_Products.zip"
_SPLITS = {tfds.Split.TRAIN: "Ebay_train", tfds.Split.TEST: "Ebay_test"}
_SUPER_CLASSES = [
"b... |
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
from hashlib import sha1
class PayloadFieldAlreadyDefinedError(Exception): pass
class PayloadFrozenError(Exception): pass
class Payload(object):
"""A mapping fr... |
import requests
import secrets
import os
import datetime
import subprocess
__author__ = 'Jason Yao'
def setup_logging():
log = "logs"
if not os.path.exists(log):
os.makedirs(log)
date = datetime.datetime.now()
log_file_name = "logs/" + date.strftime('%Y-%m-%d') + ".log"
return open(log_... |
#! -*- coding: utf-8 -*-
from __future__ import unicode_literals
import base64
import errno
import hashlib
import json
import os
import shutil
import tempfile as sys_tempfile
import unittest
from django.core.files import temp as tempfile
from django.core.files.uploadedfile import SimpleUploadedFile
from django.http.m... |
#!/usr/bin/env python
from gnuradio import gr, gr_unittest, blocks
import numpy
import time
class add_ff(gr.sync_block):
def __init__(self):
gr.sync_block.__init__(
self,
name = "add_ff",
in_sig = [numpy.float32, numpy.float32],
out_sig = [numpy.float32],
... |
from __future__ import absolute_import
import argparse
import pytest
import os
import sys
is_python2 = sys.version_info[0] == 2
import bokeh.command.subcommands.svg as scsvg
from bokeh.command.bootstrap import main
from bokeh.util.testing import TmpDir, WorkingDir, with_directory_contents
from . import basic_svg_sc... |
"""
This module contains helper functionality for writing CanTherm output files.
"""
import ast
################################################################################
class PrettifyVisitor(ast.NodeVisitor):
"""
A class for traversing an abstract syntax tree to assemble a prettier
version of... |
from __future__ import absolute_import
from copy import deepcopy
from datetime import timedelta
from uuid import uuid4
import pytz
from confluent_kafka import Producer
from dateutil.parser import parse as parse_date
from django.conf import settings
from django.test.utils import override_settings
from exam import fixt... |
"""Coordinator to help multiple threads stop when requested."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import contextlib
import sys
import threading
import time
import six
from tensorflow.python.framework import errors
from tensorflow.python.platf... |
from .VDBTestCase import VDBTestCase
from .MeshToLevelSetTest import MeshToLevelSetTest
from .LevelSetToMeshTest import LevelSetToMeshTest
from .LevelSetOffsetTest import LevelSetOffsetTest
from .PointsGridToPointsTest import PointsGridToPointsTest
from .ModuleTest import ModuleTest
from .SphereLevelSetTest import Sphe... |
"""A daemonize function (for Unices) and daemon mix-in class"""
__docformat__ = "restructuredtext en"
import os
import errno
import signal
import sys
import time
import warnings
def daemonize(pidfile=None, uid=None, umask=077):
"""daemonize a Unix process. Set paranoid umask by default.
Return 1 in the ori... |
# sort three num
count=0
print 'please input three num for sort'
while count <3:
print 'please input num%d'%(count+1)
input=raw_input('num%d='%(count+1))
if input.isdigit()==False:
print 'input error, not a num'
continue
count+=1
if count==1:
num1=input
#print 'num1 is',num1
elif count==2:
num2=input... |
from __future__ import unicode_literals
import datetime
from operator import attrgetter
from django.core.exceptions import ValidationError
from django.db import router
from django.db.models.sql import InsertQuery
from django.test import TestCase, skipUnlessDBFeature
from django.utils import six
from django.utils.time... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import curses
import os
import signal
import sys
import app.curses_util
import app.debug_window
import app.file_manager_window
import app.log
import app.prediction_window
import app.window
class ProgramWindo... |
"""GYP backend that generates Eclipse CDT settings files.
This backend DOES NOT generate Eclipse CDT projects. Instead, it generates XML
files that can be imported into an Eclipse CDT project. The XML file contains a
list of include paths and symbols (i.e. defines).
Because a full .cproject definition is not created ... |
from neutron.openstack.common import log
from neutron.plugins.vmware.common import nsx_utils
LOG = log.getLogger(__name__)
# Protocol number look up for supported protocols
protocol_num_look_up = {'tcp': 6, 'icmp': 1, 'udp': 17}
def _convert_to_nsx_rule(session, cluster, rule, with_id=False):
"""Converts a Neutr... |
from __future__ import unicode_literals
from collections import Counter
import datetime
import inspect
import json
import re
import time
import frappe
import sqlparse
from frappe import _
RECORDER_INTERCEPT_FLAG = "recorder-intercept"
RECORDER_REQUEST_SPARSE_HASH = "recorder-requests-sparse"
RECORDER_REQUEST_HASH = ... |
#!/usr/bin/env python
"""
"**Pycco**" is a Python port of [Docco](http://jashkenas.github.com/docco/):
the original quick-and-dirty, hundred-line-long, literate-programming-style
documentation generator. It produces HTML that displays your comments
alongside your code. Comments are passed through
[Markdown](http://dar... |
from django import forms
from django.conf import settings
from django.contrib.flatpages.models import FlatPage
from django.utils.translation import ugettext, ugettext_lazy as _
class FlatpageForm(forms.ModelForm):
url = forms.RegexField(label=_("URL"), max_length=100, regex=r'^[-\w/\.~]+$',
help_text = _("... |
"""A module to add gyp support to cr."""
import cr
import os
GYP_DEFINE_PREFIX = 'GYP_DEF_'
class GypPrepareOut(cr.PrepareOut):
"""A prepare action that runs gyp whenever you select an output directory."""
ENABLED = cr.Config.From(
GYP_GENERATORS='ninja',
GYP_GENERATOR_FLAGS='output_dir={CR_OUT_BASE... |
from __future__ import absolute_import
from django.test import TestCase
from model_inheritance.models import Title
class InheritanceSameModelNameTests(TestCase):
def setUp(self):
# The Title model has distinct accessors for both
# model_inheritance.Copy and model_inheritance_same_model_name.Cop... |
#!/usr/bin/env python
"""
sort-md-list.py sorts markdown lists
Use this script to prepare sections of the changelog.
this script expects a bulleted markdown list in stdout
for example
./sort-md-list.py - <<EOF
* builder/amazon: Only delete temporary key if we created one. [GH-4850]
* core: Correctly reject config f... |
"""
Model Managers for Course Actions
"""
import traceback
from django.db import models, transaction
class CourseActionStateManager(models.Manager):
"""
An abstract Model Manager class for Course Action State models.
This abstract class expects child classes to define the ACTION (string) field.
"""
... |
import sys
import pysam
from collections import Counter
if len(sys.argv) < 2:
sys.exit("usage: alnstat.py in.bam")
fname = sys.argv[1]
mode = "rb" if fname.endswith(".bam") else "r"
bamfile = pysam.AlignmentFile(fname, mode)
stats = Counter()
for read in bamfile:
stats["total"] += 1
stats['qcfail'] += in... |
"""
Scan for unused datasource queries. Run from web or java with:
../scripts/datasource-query-usage.py **/*_queries.xml
Writes out used_queries and unused_queries files.
Be sure to remove the used_queries and unused_queries files in the directory
before re-running.
"""
import os
import os.path
import sys
impor... |
import json
import falcon
import falcon.testing as testing
def capture_error(ex, req, resp, params):
resp.status = falcon.HTTP_723
resp.body = 'error: %s' % str(ex)
def handle_error_first(ex, req, resp, params):
resp.status = falcon.HTTP_200
resp.body = 'first error handler'
class CustomBaseExcep... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.