code stringlengths 1 199k |
|---|
from django.apps import apps
from guardian.shortcuts import get_objects_for_user
from api.addons.views import AddonSettingsMixin
from api.actions.views import get_actions_queryset
from api.actions.serializers import ActionSerializer
from api.base import permissions as base_permissions
from api.base.exceptions import Co... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('delivery', '0081_auto_20160828_0319'),
]
operations = [
migrations.AddField(
model_name='proxyserver',
name='http_pos',
... |
import os
import networkx as nx
import click
import solar
from solar.core.resource import composer as cr
from solar.core import resource
from solar.dblayer.model import ModelMeta
from solar.events import api as evapi
from fuelclient.objects.environment import Environment
class NailgunSource(object):
def nodes(self,... |
import cli |
__author__ = 'msergeyx'
from model.contact import Contact
from selenium.webdriver.support.ui import Select
import re
class ContactHelper:
def __init__(self, app):
self.app = app
def return_to_homepage(self):
wd = self.app.wd
wd.find_element_by_link_text("home page").click()
def go_ho... |
import yaml
from collections import OrderedDict
def ordered_loader(stream, Loader=yaml.Loader, object_pairs_hook=OrderedDict):
"""Helper function to load Yaml dictionaries into an OrderedDict."""
class OrderedLoader(Loader):
pass
def construct_mapping(loader, node):
loader.flatten_mapping(no... |
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from hsnominal.models import *
from django.db.models import Q
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def about(request):
# Read boxes
retu... |
from flask import render_template
from . import main
@main.app_errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@main.app_errorhandler(500)
def internal_server_error(e):
return render_template('500.html'), 500 |
a = [0] * 1000000; t = 0; modulus = 2 ** 24;
for i in xrange(1000000) :
t = (615949*t + 797807) % modulus
a[i] = t - modulus / 2
for i in (20,100,1000,10000,100000,1000000) :
fname = "sum2tc_%d.txt" % i
f = open(fname,"w")
for j in xrange(i) : f.write("%d\n" % a[j])
f.close() |
from django.contrib import admin
from .models import Article
class PostModelAdmin(admin.ModelAdmin):
list_display = ['title', 'timestamp', 'updated']
list_filter = ['timestamp']
search_fields = ['title', 'content']
class Meta:
model = Article
admin.site.register(Article, PostModelAdmin) |
import numpy as np
from scipy import stats
class ReuseableHoldout:
orig_T = None
tau = None
T_hat = None
budget = None
gaussian_noise = None
def __init__(self, T=0.04, tau=0.01, budget=None, gaussian_noise=True):
self.gaussian_noise = gaussian_noise
self.orig_T = T
self.t... |
import random
import datetime
import os
scriptname = os.path.basename(__file__)
"""
Copyright (c) 1987-2015 by Frank Holger Rothkamm. Forth/Coldfusion/Python
psychostochastics - Classic Csound - humanized random distributions
------------------------------------------------------------------------------
"""
orchestra =... |
"""Tests for prensor.path."""
import pprint
from absl.testing import absltest
from struct2tensor.path import create_path
from struct2tensor.path import from_proto
from struct2tensor.path import parse_map_indexing_step
from struct2tensor.path import Path
class PathTest(absltest.TestCase):
def test_get_child(self):
... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('admins', '0002_availableproject_published_date'),
]
operations = [
migrations.RemoveField(
model_name='availableproject',
name='p... |
import os
import shutil
from urllib.parse import quote
from unit.applications.proto import TestApplicationProto
from unit.option import option
class TestApplicationPython(TestApplicationProto):
application_type = "python"
load_module = "wsgi"
def load(self, script, name=None, module=None, **kwargs):
... |
import synapse.exc as s_exc
import synapse.common as s_common
import synapse.lib.time as s_time
import synapse.tests.utils as s_t_utils
from synapse.tests.utils import alist
class FileTest(s_t_utils.SynTest):
async def test_model_filebytes(self):
async with self.getTestCore() as core:
valu = 'sh... |
import testtools
import shade
from shade.tests.unit import base
from testtools import matchers
RAW_ROLE_ASSIGNMENTS = [
{
"links": {"assignment": "http://example"},
"role": {"id": "123456"},
"scope": {"domain": {"id": "161718"}},
"user": {"id": "313233"}
},
{
"links":... |
"""Support for HomematicIP Cloud switches."""
import logging
from homematicip.aio.device import (
AsyncBrandSwitchMeasuring,
AsyncFullFlushSwitchMeasuring,
AsyncMultiIOBox,
AsyncOpenCollector8Module,
AsyncPlugableSwitch,
AsyncPlugableSwitchMeasuring,
AsyncPrintedCircuitBoardSwitch2,
Asyn... |
"""Replace for Babbage.
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable la... |
"""Text Preprocessor."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
from absl import flags
import numpy as np
import tensorflow as tf
from tf_trainer.common import base_model
from tf_trainer.common import types
from tf_trainer.common.tok... |
import os
import os.path
import sys
def apply_header(source_file, header_file):
source = read_file(source_file)
header = header_map[header_file]
if source.find(header) < 0:
f = open(source_file, 'w')
try:
f.write(header)
f.write(source)
finally:
f.close()
def read_file(file):
f = o... |
"""Train iterative refinement networks (NCSN and DDPM)."""
import os
import time
from absl import app
from absl import flags
from absl import logging
from functools import partial
import jax
import jax.numpy as jnp
import jax.experimental.optimizers
import numpy as np
import tensorflow as tf
import tensorflow_datasets ... |
import numpy as np
import argparse
import ast
import time
import paddle
import paddle.fluid as fluid
from paddle.fluid.dygraph.nn import Linear
from paddle.distributed import fleet
from paddle.fluid.dygraph import nn
from paddle.distributed.fleet.meta_parallel.sharding.sharding_stage3 import ShardingStage3
from paddle.... |
import subprocess
import logging
def run_shell_command(command, decode_output=True):
"""
Runs the given command and returns any output and error
If `decode_output` is True, try to decode output and error message with
UTF-8 encoding, as well as removing any single quote.
"""
process = subprocess.... |
'''
Copyright 2016, EMC, Inc.
Author(s):
George Paulos
'''
import os
import sys
import subprocess
sys.path.append(subprocess.check_output("git rev-parse --show-toplevel", shell=True).rstrip("\n") + "/test/fit_tests/common")
import fit_common
from nose.plugins.attrib import attr
@attr(all=True, regression=True, smoke=Tr... |
from tweepy import OAuthHandler
from django.conf import settings
from django.contrib.auth import authenticate, login, logout
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect
def twitter_login(request):
"""
ログインを行う。
:param request: リクエストオブジェクト
:type ... |
"""
main.py -- Udacity conference server-side Python App Engine
HTTP controller handlers for memcache & task queue access
$Id$
created by wesc on 2014 may 24
"""
__author__ = 'wesc+api@google.com (Wesley Chun)'
import webapp2
from google.appengine.api import app_identity
from google.appengine.api import mail
from c... |
"""
Routines for configuring Octavia Haproxy driver
"""
from oslo_config import cfg
from gbpservice._i18n import _
haproxy_amphora_opts = [
cfg.StrOpt('base_path',
default='/var/lib/octavia',
help=_('Base directory for amphora files.')),
cfg.StrOpt('base_cert_dir',
d... |
import os
from flask import Flask
from flask import render_template as render
from werkzeug.debug import DebuggedApplication
def application():
app = Flask(__name__)
if 'SERVER_SOFTWARE' in os.environ and os.environ['SERVER_SOFTWARE'].startswith('Dev'):
app.debug = True
app.wsgi_app = DebuggedAp... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zabbix_wechat_db', '0002_duty_roster_token'),
]
operations = [
migrations.CreateModel(
name='GROUP',
fields=[
('i... |
IVERSION = (0, 10)
VERSION = ".".join(str(i) for i in IVERSION)
NAME = "netlib"
NAMEVERSION = NAME + " " + VERSION |
import torch
PYTORCH_LOSS_NAMES = {s for s in dir(torch.nn.modules) if s.endswith("Loss")}
PYTORCH_OPTIM_NAMES = {s for s in dir(torch.optim) if any(c.isupper() for c in s)} - {'Optimizer'}
LR_NAME = "lr"
DEFAULT_LR = 1e-3
BATCH_SIZE_NAME = "batch_size"
DEFAULT_BATCH_SIZE = 32
def validate_pytorch_loss(loss):
impor... |
"""
The qiprofile REST data model.
The model field choices are listed in the preferred display order,
most common to least common.
The data capture client has the following responsibility:
* Validate the data upon input as determined by the model
validation documentation.
* Resolve conflicts between data capture and ... |
from rest_framework import serializers
from spa.models.comment import Comment
class CommentSerialiser(serializers.HyperlinkedModelSerializer):
user = serializers.RelatedField(many=False)
avatar_image = serializers.Field(source='avatar_image')
class Meta:
model = Comment
fields = ('comment', ... |
import pytest
import sqlalchemy as sa
from postgresql_audit import (
add_column,
alter_column,
change_column_name,
remove_column,
rename_table
)
from .utils import last_activity
@pytest.mark.usefixtures('activity_cls', 'table_creator')
class TestRenameTable(object):
def test_only_updates_given_t... |
import sys
import os
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
extensions = []
if not on_rtd:
extensions.append('sphinxcontrib.spelling')
spelling_show_suggestions = True
spelling_word_list_filename = 'spelling.txt'
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project =... |
from django.conf import settings
from django.contrib.sites.models import Site
REQUEST_IGNORE_AJAX = getattr(settings, 'REQUEST_IGNORE_AJAX', False)
REQUEST_IGNORE_IP = getattr(settings, 'REQUEST_IGNORE_IP', tuple())
REQUEST_IGNORE_USERNAME = getattr(settings, 'REQUEST_IGNORE_USERNAME', tuple())
REQUEST_USE_HOSTED_MEDIA... |
from django.contrib.auth import get_user_model
from django.db import models
from guardian.conf import settings
from guardian.core import ObjectPermissionChecker
from guardian.ctypes import get_content_type
from guardian.exceptions import WrongAppError
def check_object_support(obj):
"""
Returns ``True`` if given... |
'''Autogenerated by get_gl_extensions script, do not edit!'''
from OpenGL import platform as _p, constants as _cs, arrays
from OpenGL.GL import glget
import ctypes
EXTENSION_NAME = 'GL_ARB_internalformat_query'
def _f( function ):
return _p.createFunction( function,_p.GL,'GL_ARB_internalformat_query',False)
_p.unpa... |
import ldap
from oncall import db
import os
import logging
from oncall.user_sync.ldap_sync import user_exists, import_user, update_user
logger = logging.getLogger(__name__)
class Authenticator:
def __init__(self, config):
if config.get('debug'):
self.authenticate = self.debug_auth
re... |
"""
pygments.lexers.inferno
~~~~~~~~~~~~~~~~~~~~~~~
Lexers for Inferno os and all the related stuff.
:copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, include, bygroups, default
from pygment... |
"""
colors.py
=========
Convert colors between rgb, hsv, and hex, perform arithmetic, blend modes,
and generate random colors within boundaries.
"""
from .base import *
__version__ = '0.2.2'
__author__ = 'Matt Robenolt <matt@ydekproductions.com>'
__license__ = 'BSD' |
from helper import *
Import( 'env' )
def add_dependencies(env):
'''[[[cog
import cogging as c
c.tpl(cog,templateFile,c.a(prefix=configFile))
]]]'''
'''[[[end]]] (checksum: 68b329da9893e34099c7d8ad5cb9c940)'''
AddNetwork(env)
c = {}
c['PROG_NAME'] = 'enet_cnets_osblinnikov_github_com'
c['testFiles'] = ['enet... |
from __future__ import absolute_import
import logging
from os import environ
from conda_wrapper import CondaWrapper
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
with CondaWrapper(
environ["PYTHON_VERSION"], environ["CONDA_HOME"], environ["CONDA_VENV"]
) as conda:
conda.... |
import numpy as np
def Rotate3d(vector, theta_x, theta_y, theta_z):
"""
3-d rotation of a vector around the x-, y- and z-axes.
INPUTS
vector : vector to be rotated
theta_x : rotation angle around x-axis
theta_y : rotation angle around y-axis
theta_z : rotation angle around z-axis
... |
"""import threading
import time
class Mythread(threading.Thread):
def run(self):
print("About to ss")
time.sleep(5)
print("finish")
m = Mythread()
m.start()
print(time.perf_counter())"""
import threading
import PeyeonScript,time
from multiprocessing import Pool , TimeoutError
def serverConnect(ip):
basla2= time... |
import os
import numpy as np
import lsst.afw.image as afwImage
import astropy.coordinates as astroCoords
import astropy.units as u
from astropy.io import fits
from astropy.wcs import WCS
from scipy.ndimage import convolve
from sklearn.cluster import DBSCAN
class searchImage(object):
"""
A class of methods used ... |
import bdf
import header_writer
import argparse
INPUT_FILE_NAME = '../bdf/Helvetica-18.bdf'
OUTPUT_FILE_NAME = '../fonts/helvetica_18.h'
VARIABLE_NAME = 'HELVETICA_18'
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--name', dest='name', help='font name')
name = parser.parse_args().name
... |
"""
Copyright (c) 2009-2010 Marian Tietz
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the followin... |
from collections import namedtuple
from django.db import models
from django.core.exceptions import ValidationError
from django.utils.six import with_metaclass, string_types
Choice = namedtuple('Choice', ('value', 'display', 'slug', 'handler',))
class ChoiceField(with_metaclass(models.SubfieldBase, models.PositiveSmallI... |
import inspect
from contextlib import contextmanager
from attest import statistics
__all__ = ['Loader',
'assert_',
'Assert',
]
class Loader(object):
"""Run tests with Attest via distribute.
.. deprecated:: 0.5
:meth:`~attest.reporters.AbstractReporter.test_loader` is pref... |
"""
Functions used to analyze the trained neural networks.
"""
try:
import cPickle as pickle
except:
import pickle
import glob
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import lasagne
from lasagne import layers
from lasagne import nonlinearities
from nolearn.lasagn... |
from datetime import datetime
__all__ = ("date", )
def date(time):
if not time:
return ""
# calculate "now" in the timezone (if any) of the given time
now = datetime.now(time.tzinfo)
if time > now:
past = False
diff = time - now
else:
past = True
diff = now - ... |
"""
Copyright (c) 2016 Ad Schellevis <ad@opnsense.org>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
th... |
from .contrib import * # noqa
DATABASES = {
'default': {
# Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
# 'ENGINE': 'django.db.backends.postgresql_psycopg2',
'ENGINE': 'django.contrib.gis.db.backends.postgis',
# Or path to database file if using sqlite3.
'NAME'... |
from .test_base import TestBase
class TestUserLogin(TestBase):
def test_any_case_login_ok(self):
username = 'bob'
password = 'bobbob'
# kobocat lo
self._create_user(username, password)
# kobocat login are now case sensitive so you must lowercase BOB
self._login('bob',... |
from ctypes import (cast, CDLL, c_char, c_char_p, c_int, c_int8, c_int16,
c_int32, c_int64, c_size_t, c_ssize_t, c_uint, c_uint8,
c_uint16, c_uint32, c_uint64, c_void_p)
libc = CDLL("libc.so.6")
mmap = libc.mmap64
mmap.argtypes = (c_void_p, c_size_t, c_int, c_int, c_int, c_int64)... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "smirik.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
import tests.periodicities.period_test as per
per.buildModel((7 , 'S' , 50)); |
from celery import Celery
import consumer
app_name = 'consumer' # take the celery app name
app = Celery(app_name, broker=consumer.redis_url)
for i in range(100):
a = 1
b = 2
consumer.consume.delay(a, b) |
from django.conf.urls import patterns, url
from django.views.decorators.cache import never_cache
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .views import SubscriptionView
from .models import Campaign, SubscriptionPlugin,... |
"""SpecfileData object to read data in SPEC_ format
===================================================
.. _SPEC: http://www.certif.com/content/spec
Requirements
------------
- silx (http://www.silx.org/doc/silx/dev/modules/io/specfilewrapper.html)
TODO
----
- _pymca_average() : use faster scipy.interpolate.interp1d
- ... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ugc_manage.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
"""Test import_data."""
import mne
import pytest
import os.path as op
import numpy as np
import scipy.io as sio
import nipype.pipeline.engine as pe
from ephypype.nodes.import_data import ConvertDs2Fif, ImportHdf5, ImportMat
from ephypype.nodes.import_data import Ep2ts, Fif2Array, ImportFieldTripEpochs
from ephypype.imp... |
"""
Tests for grades API
"""
from datetime import timedelta
from unittest.mock import patch, MagicMock
import ddt
from django.core.exceptions import ImproperlyConfigured
from django.db.models.signals import post_save
from django_redis import get_redis_connection
from factory.django import mute_signals
from courses.fact... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from satchless.product.models import ProductAbstract, Variant, ProductAbstractTranslation
class Parrot(ProductAbstract):
latin_name = models.CharField(max_length=20)
class Meta:
app_label = 'product'
class ParrotTransla... |
from __future__ import absolute_import
from sentry.data_export.base import ExportError
from sentry.data_export.processors.discover import DiscoverProcessor
from sentry.testutils import TestCase, SnubaTestCase
class DiscoverProcessorTest(TestCase, SnubaTestCase):
def setUp(self):
super(DiscoverProcessorTest,... |
def extractMjnovelsBlogspotCom(item):
'''
Parser for 'mjnovels.blogspot.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', ... |
from __future__ import unicode_literals
import base64
import re
from django.contrib.messages.storage.base import BaseStorage
from django.http import HttpRequest
from django.template.base import (
COMMENT_TAG_START, COMMENT_TAG_END,
Template,
TemplateSyntaxError,
)
from django.template.context import BaseCon... |
import rospy
from std_msgs.msg import Char
class TransportDriveMotorAPI:
FORWARD_LABEL = 1
BACKWARD_LABEL = 2
CLOCKWISE_LABEL = -1
COUNTERCLOCKWISE_LABEL = 3
def __init__(self):
# Initialize publishers for speed and direction topics.
self.speed_publisher = rospy.Publisher("drive_spee... |
from django.conf.urls import include, url
from django.contrib.staticfiles.views import serve as serve_static
from django.views.decorators.cache import never_cache
from django.conf import settings
from django.contrib import admin
urlpatterns = [
url(r'^api/', include('apps.api.urls', namespace='api')),
url('', i... |
import numpy as np
import scipy.sparse as sp
from fastFM import bpr
from fastFM import utils
def get_test_problem(task='regression'):
X = sp.csc_matrix(np.array([[6, 1],
[2, 3],
[3, 0],
[6, 1],
... |
from unittest import skip
from selenium.webdriver.support.ui import Select
from django.test import override_settings
from .. import models, view_helpers
from .base import FunctionalTest
class ElementHelper(object):
def __init__(self, browser):
self.browser = browser
@property
def done(self):
... |
import unittest
from .test_augmentedYaml import TestAugmentedYaml
if __name__ == '__main__':
unittest.main(verbosity=3) |
from pages.tests.test_pages import *
__test__ = {'pages.tests.TestPages': ['test_pages']} |
from hashlib import md5
from app import db
ROLE_USER = 0
ROLE_ADMIN = 1
followers = db.Table('followers',
db.Column('follower_id', db.Integer, db.ForeignKey('user.id')),
db.Column('followed_id', db.Integer, db.ForeignKey('user.id'))
)
class User(db.Model):
id = db.Column(db.Integer, primary_key = True)
... |
import warnings
from functools import wraps
import cherrypy
from social_core.utils import setting_name, module_member, get_strategy
from social_core.backends.utils import get_backend, user_backends_data
DEFAULTS = {
'STRATEGY': 'social_cherrypy.strategy.CherryPyStrategy',
'STORAGE': 'social_cherrypy.models.Cher... |
"""
raven.handlers.logging
~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import logging
import sys
import traceback
class SentryHandler(logging.Handler):
def __init__(self, client=... |
import qiime2.core.archive.format.v3 as v3
from qiime2.core.cite import Citations
class ArchiveFormat(v3.ArchiveFormat):
# - Adds a transformers section to action.yaml
# - Adds citations via the !cite yaml type which references the
# /provenance/citations.bib file (this is nested like everything else
... |
import sys
import threading
import time
import subprocess
import re
import errno
ntp_interval = 30.0
heartbeat_interval = 60.0
done = False;
def set_done():
global done
done = True
last_heartbeat = time.time()
def heartbeat():
global last_heartbeat
last_heartbeat = time.time()
def check_heartbeat():
... |
from django.conf import settings
from django.conf.urls.defaults import patterns, include
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from .scanner import urls
from funfactory.monkeypatches import patch
patch()
urlpatterns = patterns('',
# Example:
(r'', include(urls)),
# Uncomment th... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Product',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=Fals... |
"""
User interface Controls for the layout.
"""
from __future__ import unicode_literals
from pygments.token import Token
from six import with_metaclass
from abc import ABCMeta, abstractmethod
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import to_cli_filter
from prompt_toolkit.mouse_event... |
"""
sentry.web.feeds
~~~~~~~~~~~~~~~~
:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.utils import feedgenerator
from django.utils.translation import uget... |
import numpy
import math
import copy
from emission.core.wrapper.trip_old import Trip, Coordinate
import emission.storage.decorations.trip_queries as esdtq
import emission.storage.decorations.place_queries as esdpq
"""
This class creates a group of representatives for each cluster
and defines the locations that the user... |
import datetime
from haystack.indexes import *
from haystack import site
from resources.models import Resource
class ResourceIndex(SearchIndex):
text = CharField(document=True, use_template=True) #name, description
def get_queryset(self):
"""Used when the entire index for model is updated."""
re... |
import datetime
from django.utils import timezone
try:
import pytz
except ImportError:
pytz = None
def get_utc_now():
now = datetime.datetime.utcnow()
now = now.replace(microsecond=0, tzinfo=timezone.utc)
return now
def get_default_now():
return get_now_in(timezone.get_default_timezone())
def ge... |
"""Package contenant le paramètre 'dupliquer' de la commande 'rapport'."""
from primaires.interpreteur.masque.parametre import Parametre
class PrmDupliquer(Parametre):
"""Commande 'rapport dupliquer'"""
def __init__(self):
"""Constructeur du paramètre."""
Parametre.__init__(self, "dupliquer", "d... |
from datetime import timedelta
from celery.decorators import periodic_task
from celery.task import Task
from pennyblack import settings
@periodic_task(run_every=timedelta(minutes=settings.BOUNCE_DETECTION_GETMAIL_INTERVAL))
def pennyblack_get_email():
"""get bounced emails from the imap mailbox"""
from pennybla... |
"""Removes code coverage flags from invocations of the Clang C/C++ compiler.
If the GN arg `use_clang_coverage=true`, this script will be invoked by default.
GN will add coverage instrumentation flags to almost all source files.
This script is used to remove instrumentation flags from a subset of the source
files. By d... |
import unittest
from main import Solution
class SolutionTest(unittest.TestCase):
def setUp(self):
self.sol = Solution()
def test_1(self):
l = [1, 2, 3]
self.sol.nextPermutation(l)
self.assertEqual(l, [1, 3, 2])
def test_2(self):
l = [1, 2, 3, 2, 1]
self.sol.ne... |
from pyramid.exceptions import NotFound
from pyramid.renderers import get_renderer
from pyramid.view import view_config
from .webnut import WebNUT
from . import config
class NUTViews(object):
def __init__(self, request):
self.request = request
renderer = get_renderer("templates/layout.pt")
s... |
"""
sentry.utils.samples
~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2013 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import os.path
from sentry.constants import DATA_ROOT, PLATFORM_ROOTS
from sentry.models import Group
from sentry.utils import json
def create_sample_even... |
from distutils.version import LooseVersion
import gc
import os
import os.path as op
from pathlib import Path
import shutil
import sys
import warnings
import pytest
try:
import readline # noqa
except Exception:
pass
import numpy as np
import mne
from mne.datasets import testing
from mne.utils import _pl, _asser... |
import numpy as np
from .line import LineVisual
class XYZAxisVisual(LineVisual):
"""
Simple 3D axis for indicating coordinate system orientation. Axes are
x=red, y=green, z=blue.
"""
def __init__(self, **kwargs):
pos = np.array([[0, 0, 0],
[1, 0, 0],
... |
"""Package contenant la commande 'setquest'"""
from primaires.interpreteur.commande.commande import Commande
class CmdSetQuest(Commande):
"""Commande 'setquest'.
"""
def __init__(self):
"""Constructeur de la commande"""
Commande.__init__(self, "setquest", "setquest")
self.groupe = "a... |
"""
This script will be used by fpm to edit the control file during package
building.
The script will correct all the crazy names defined in the ``PACKAGE_TYPES``
configuration object.
"""
import os
import re
import argparse
import tempfile
from vdt.versionplugin.debianize.config import PACKAGE_TYPES, PACKAGE_TYPE_CHOI... |
from __future__ import division
from PyQt4 import QtCore, QtGui
from vistrails.core.system import get_vistrails_basic_pkg_id
from vistrails.gui.theme import CurrentTheme
from vistrails.gui.modules.utils import get_widget_class
from vistrails.gui.modules.constant_configuration import ConstantWidgetMixin, \
StandardC... |
import os
import unittest
from telemetry import benchmark
from telemetry import story
from telemetry.internal.results import base_test_results_unittest
from telemetry.internal.results import chart_json_output_formatter
from telemetry.internal.results import json_output_formatter
from telemetry.internal.results import p... |
import sys
try:
from django.conf import settings
settings.configure(
DEBUG=True,
USE_TZ=True,
DATABASES={
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
ROOT_URLCONF="nump3.urls",
INSTALLED_APPS=[
"dja... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.