code stringlengths 1 199k |
|---|
"""Integration test for breakpad in content shell.
This test checks that content shell and breakpad are correctly hooked up, as
well as that the tools can symbolize a stack trace."""
import glob
import optparse
import os
import shutil
import subprocess
import sys
import tempfile
CONCURRENT_TASKS=4
def main():
parser ... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = """
---
module: ce_vxlan_gateway
version_added: "2.4"
short_description: Manages gateway for the VXLAN network on HUAWEI CloudEngine devices.
description:
- Conf... |
"""
Django admin page for Site Configuration models
"""
from django.contrib import admin
from .models import SiteConfiguration, SiteConfigurationHistory
class SiteConfigurationAdmin(admin.ModelAdmin):
"""
Admin interface for the SiteConfiguration object.
"""
list_display = ('site', 'enabled', 'values')
... |
"""Model script to test TF-TensorRT integration."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.compiler.tensorrt.test import tf_trt_integration_test_base as trt_test
from tensorflow.python.framework import consta... |
"""
Tests for various parts of L{twisted.web}.
"""
import os
import zlib
from zope.interface import implementer
from zope.interface.verify import verifyObject
from twisted.python.compat import _PY3, networkString
from twisted.python.filepath import FilePath
from twisted.trial import unittest
from twisted.internet impor... |
"""
cclib (http://cclib.sf.net) is (c) 2006, the cclib development team
and licensed under the LGPL (http://www.gnu.org/copyleft/lgpl.html).
"""
__revision__ = "$Revision: 861 $"
import numpy
import logfileparser
import utils
class ADF(logfileparser.Logfile):
"""An ADF log file"""
def __init__(self, *args, **kw... |
"""Tests for the AdbWrapper class."""
import os
import socket
import tempfile
import time
import unittest
import adb_wrapper
class TestAdbWrapper(unittest.TestCase):
def setUp(self):
devices = adb_wrapper.AdbWrapper.GetDevices()
assert devices, 'A device must be attached'
self._adb = devices[0]
self._... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = """
---
module: ce_vxlan_arp
version_added: "2.4"
short_description: Manages ARP attributes of VXLAN on HUAWEI CloudEngine devices.
description:
- Manages ARP at... |
from oscar.core.loading import is_model_registered
from oscar.apps.customer import abstract_models
__all__ = []
if not is_model_registered('customer', 'Email'):
class Email(abstract_models.AbstractEmail):
pass
__all__.append('Email')
if not is_model_registered('customer', 'CommunicationEventType'):
... |
from __future__ import unicode_literals
import os.path
import re
from .common import InfoExtractor
from ..compat import (
compat_urllib_parse,
compat_urllib_request,
)
class MonikerIE(InfoExtractor):
IE_DESC = 'allmyvideos.net and vidspot.net'
_VALID_URL = r'https?://(?:www\.)?(?:allmyvideos|vidspot)\.n... |
__author__ = "Thomas Rueckstiess, Frank Sehnke"
from pybrain.tools.example_tools import ExTools
from pybrain.tools.shortcuts import buildNetwork
from pybrain.rl.environments.cartpole import CartPoleEnvironment, BalanceTask
from pybrain.rl.agents import LearningAgent
from pybrain.rl.learners import ENAC
from pybrain.rl.... |
__author__ = 'Cosmo Harrigan'
from flask import abort, jsonify
from flask.ext.restful import Resource, reqparse
import socket
from flask_restful_swagger import swagger
COGSERVER_PORT = 17001
class ShellAPI(Resource):
"""
Defines a barebones resource for sending shell commands to the CogServer
"""
# This... |
import hashlib
import re
from livestreamer.plugin import Plugin
from livestreamer.plugin.api import http
from livestreamer.stream import HDSStream
TOKEN_SECRET = '9b673b13fa4682ed14c3cfa5af5310274b514c4133e9b3a81e6e3aba009l2564'
_url_re = re.compile("http(s)?://(\w+\.)?wat.tv/")
_video_id_re = re.compile("href=\"http:/... |
"""==============
Array indexing
==============
Array indexing refers to any use of the square brackets ([]) to index
array values. There are many options to indexing, which give numpy
indexing great power, but with power comes some complexity and the
potential for confusion. This section is just an overview of the
var... |
kwargs = {'foo': 'bar'}
class Foo(object):
@classmethod
def test(cls):
cls(**kwargs, <error descr="Python versions < 3.5 do not allow keyword arguments after **expression">foo=1</error>) |
"""
set_default_site.py
"""
import socket
from optparse import make_option
from django.core.management.base import NoArgsCommand, CommandError
from django_extensions.management.utils import signalcommand
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--name', dest='si... |
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers
import pybindgen.settings
import warnings
class ErrorHandler(pybindgen.settings.ErrorHandler):
def handle_error(self, wrapper, exception, traceback_):
warnings.warn("exception %r in wrapper %s" % (exception, wrapper))
... |
class A:
def __getitem__(self, idx):
print(idx.start, idx.stop, idx.step)
try:
t = A()[1:2]
except:
print("SKIP")
raise SystemExit
A()[1:2:3]
class B:
def __getitem__(self, idx):
try:
idx.start = 0
except AttributeError:
print('AttributeError')
B()[:] |
import psycopg2
import logging
from openerp.osv import orm
from openerp.tools.float_utils import float_compare
_logger = logging.getLogger(__name__)
def _format_inserts_values(vals):
cols = vals.keys()
if 'line_id' in cols:
cols.remove('line_id')
return (', '.join(cols), ', '.join(['%%(%s)s' % i for... |
import re
class pp_ss:
def __init__(self, val):
self.val = val
def to_string(self):
return "a=<" + str(self.val["a"]) + "> b=<" + str(self.val["b"]) + ">"
def lookup_function (val):
"Look-up and return a pretty-printer that can print val."
# Get the type.
type = val.type
# If it ... |
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
import xmodule_django.models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... |
from bokeh.plotting import figure, output_file, show
from bokeh.models import HoverTool, BoxSelectTool
output_file("toolbar.html")
TOOLS = [BoxSelectTool(), HoverTool()]
p = figure(plot_width=400, plot_height=400, title=None, tools=TOOLS)
p.circle([1, 2, 3, 4, 5], [2, 5, 8, 2, 7], size=10)
show(p) |
from django.conf import settings
processor_name = settings.CC_PROCESSOR.keys()[0]
module = __import__('shoppingcart.processors.' + processor_name,
fromlist=['render_purchase_form_html'
'process_postpay_callback',
])
def render_purchase_form... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'curated'}
DOCUMENTATION = '''
---
module: azure_rm_virtualnetwork
version_added: "2.1"
short_description: Manage Azure virtual networks.
description:
- Create, update or delete a virtual ne... |
"""
Twisted Python Roots: an abstract hierarchy representation for Twisted.
Maintainer: Glyph Lefkowitz
"""
import types
from twisted.python import reflect
class NotSupportedError(NotImplementedError):
"""
An exception meaning that the tree-manipulation operation
you're attempting to perform is not supporte... |
from __future__ import absolute_import
import logging
__all__ = [
'ExtraLogFormatter'
]
class ExtraLogFormatter(logging.Formatter):
"""
Custom log formatter which attaches all the attributes from the "extra"
dictionary which start with an underscore to the end of the log message.
For example:
ex... |
"""
webapp2_extras.appengine.sessions_memcache
==========================================
Extended sessions stored in memcache.
:copyright: 2011 by tipfy.org.
:license: Apache Sotware License, see LICENSE for details.
"""
from google.appengine.api import memcache
from webapp2_extras import sessions
... |
import re
import sys
import string
from optparse import OptionParser
asflicense='''
<!---
-->
'''
def docstrip(key,string):
string=re.sub("^## @%s " % key ,"",string)
string=string.lstrip()
string=string.rstrip()
return string
def toc(list):
tocout=[]
header=()
for i in list:
if header != i.getinter()... |
import sys
import shutil
import os
import stat
import re
import posixpath
import zipfile
import tarfile
import subprocess
import textwrap
from pip.exceptions import InstallationError, BadCommand, PipError
from pip.backwardcompat import(WindowsError, string_types, raw_input,
console_to_st... |
'''expand keywords in tracked files
This extension expands RCS/CVS-like or self-customized $Keywords$ in
tracked text files selected by your configuration.
Keywords are only expanded in local repositories and not stored in the
change history. The mechanism can be regarded as a convenience for the
current user or for ar... |
from i18n import _
import util, match
import re
_commentre = None
def ignorepats(lines):
'''parse lines (iterable) of .hgignore text, returning a tuple of
(patterns, parse errors). These patterns should be given to compile()
to be validated and converted into a match function.'''
syntaxes = {'re': 'relr... |
from django.contrib import auth
from django import db
from django.utils.encoding import force_bytes
def check_password(environ, username, password):
"""
Authenticates against Django's auth database
mod_wsgi docs specify None, True, False as return value depending
on whether the user exists and authentic... |
"""
Make sure the base address setting is extracted properly.
"""
import TestGyp
import re
import sys
if sys.platform == 'win32':
test = TestGyp.TestGyp(formats=['msvs', 'ninja'])
CHDIR = 'linker-flags'
test.run_gyp('base-address.gyp', chdir=CHDIR)
test.build('base-address.gyp', test.ALL, chdir=CHDIR)
def Get... |
import unittest
from test import test_support
import base64
class LegacyBase64TestCase(unittest.TestCase):
def test_encodestring(self):
eq = self.assertEqual
eq(base64.encodestring("www.python.org"), "d3d3LnB5dGhvbi5vcmc=\n")
eq(base64.encodestring("a"), "YQ==\n")
eq(base64.encodestr... |
import time
from openerp.osv import fields, osv
class account_analytic_balance(osv.osv_memory):
_name = 'account.analytic.balance'
_description = 'Account Analytic Balance'
_columns = {
'date1': fields.date('Start of period', required=True),
'date2': fields.date('End of period', required=Tru... |
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
parse_duration,
int_or_none,
)
class ChirbitIE(InfoExtractor):
IE_NAME = 'chirbit'
_VALID_URL = r'https?://(?:www\.)?chirb\.it/(?:(?:wp|pl)/|fb_chirbit_player\.swf\?key=)?(?P<id>[\da-zA-Z]+)'
_TESTS = [{
... |
from subcmds.sync import Sync
class Smartsync(Sync):
common = True
helpSummary = "Update working tree to the latest known good revision"
helpUsage = """
%prog [<project>...]
"""
helpDescription = """
The '%prog' command is a shortcut for sync -s.
"""
def _Options(self, p):
Sync._Options(self, p, show_smar... |
from .cassconnect import create_test_db, remove_test_db
setUp = create_test_db
tearDown = remove_test_db |
cpp_examples = [
("wifi-example-sim", "True", "True"),
]
python_examples = [] |
import sys
from root import get_root, get_focus
from dialogs import Dialog
from theme import ThemeProperty
from pygame import Rect, draw
class MenuItem(object):
keyname = ""
keycode = None
shift = False
alt = False
enabled = False
if sys.platform.startswith('darwin') or sys.platform.startswith('... |
import os
import sys
import time
NUM_EVENT_QUEUES = 10
mountpoint = sys.argv[1]
if not os.path.exists( mountpoint ):
print >> sys.stderr, "Usage: %s MOUNTPOINT" % sys.argv[0]
sys.exit(1)
for i in xrange(0, NUM_EVENT_QUEUES):
print "event queue: tmp/test-%s" % i
os.mkdir( "tmp/test-%s" % i )
print "Waiti... |
import math
import sensors.pycomms.mpu6050 as mpu6050
mpu = mpu6050.MPU6050(channel=1)
mpu.dmpInitialize()
mpu.setDMPEnabled(True)
packetSize = mpu.dmpGetFIFOPacketSize()
offset = None
while True:
# Get INT_STATUS byte
mpuIntStatus = mpu.getIntStatus()
if mpuIntStatus >= 2: # check for DMP data ready interr... |
import json
from datetime import date
from textwrap import dedent
import pytest
import responses
from flask_forecaster.tracker import Tracker, models
@pytest.fixture
def api():
return Tracker('hello')
class TestTokenValidation:
@responses.activate
def test_token_valid(self):
projects = ['foo', 'bar'... |
from distutils.core import setup
setup(
name='nasbkp',
version='0.1',
packages=['nasbkp', 'nasbkp.tests', 'nasbkp.common', 'nasbkp.storage'],
url='',
license='ISC',
author='Alexandre Vaissière',
author_email='avaiss@fmiw.org',
description='Automated backup for zfs volume'
) |
from __future__ import print_function
from bytecode import *
if __name__ == '__main__':
import sys
if len(sys.argv) > 1:
try:
sys.stdout.write(write_bytecode(collect(refine(optimize(convert(sys.argv[1], flatten(parse(sys.argv[1]))))))))
except DejaSyntaxError as e:
print(e, file=sys.stderr) |
import numpy as np
def make_isocosahedron():
g = (1. + np.sqrt(5)) / 2. # the golden ratio
# looking outside the isocosahedron in to the origin
# the vertices go in an anticlockwise direction around each face
# and the faces touch each other sequentially
v = np.array([
[ 0, 1, g],
[... |
import os
import unittest
from subprocess import CalledProcessError
from latexbuild.subprocess_extension import check_output_cwd
PATH_FILE = os.path.abspath(__file__)
PATH_TEST = os.path.dirname(PATH_FILE)
PATH_MAIN = os.path.dirname(PATH_TEST)
NAME_FILE = os.path.basename(PATH_FILE)
def ls_and_split(directory):
st... |
"""
This package provides extensions of the RX used in the app.
"""
import sensomatic.rxutils.from_iterable_with_interval |
import os
from pythonz.commands import Command
from pythonz.define import PATH_PYTHONS
from pythonz.installer.pythoninstaller import CPythonInstaller, StacklessInstaller, PyPyInstaller, JythonInstaller
from pythonz.log import logger
class ListCommand(Command):
name = "list"
usage = "%prog [options]"
summary... |
from __future__ import print_function
import unittest
import discretize
from SimPEG import utils
import numpy as np
from SimPEG.electromagnetics import resistivity as dc
from SimPEG.electromagnetics import analytics
try:
from pymatsolver import Pardiso as Solver
except ImportError:
from SimPEG import SolverLU a... |
from textwrap import dedent
import icalendar
import pytest
import vdirsyncer.utils.vobject as vobject
from .. import BARE_EVENT_TEMPLATE, EVENT_TEMPLATE, VCARD_TEMPLATE, \
normalize_item
_simple_split = [
VCARD_TEMPLATE.format(r=123, uid=123),
VCARD_TEMPLATE.format(r=345, uid=345),
VCARD_TEMPLATE.format... |
import network
import numpy
training_data = [
(numpy.array([[0], [0]]), numpy.array([[0]])),
(numpy.array([[0], [1]]), numpy.array([[1]])),
(numpy.array([[1], [0]]), numpy.array([[1]])),
(numpy.array([[1], [1]]), numpy.array([[0]])),
]
net = network.Network([2, 3, 1])
net.SGD(training_data, 5000, 4, 1.0... |
'''
Created by auto_sdk on 2015.06.23
'''
from aliyun.api.base import RestApi
class Ecs20140526AllocateEipAddressRequest(RestApi):
def __init__(self,domain='ecs.aliyuncs.com',port=80):
RestApi.__init__(self,domain, port)
self.Bandwidth = None
self.InternetChargeType = None
self.RegionId = None
def getapiname(... |
import botlog
from bbot.Data import *
from bbot.Utils import *
class PrimeProjection:
def __init__(self, answer=None, confidence=None):
self.answer = answer
self.confidence = confidence
def is_low_confidence(self):
return self.confidence is None or self.confidence < 0.5
def is_high_c... |
"""
audfprint_analyze.py
Class to do the analysis of wave files into hash constellations.
2014-09-20 Dan Ellis dpwe@ee.columbia.edu
"""
from __future__ import print_function
import os
import numpy as np
import scipy.signal
import struct
import glob
import time
import hash_table
import librosa
import audio_read
PRECOMPE... |
import superimport
import numpy as np
import scipy.sparse
import matplotlib.pyplot as plt
import pyprobml_utils as pml
from matplotlib import colors as mcolors
def demo(priorVar, plot_num):
np.random.seed(1)
colors = dict(mcolors.BASE_COLORS, **mcolors.CSS4_COLORS)
N = 10 # number of interior observed poin... |
import urllib
class RecaptchaMixin(object):
"""RecaptchaMixin
You must define some options for this mixin. All information
can be found at http://www.google.com/recaptcha
A basic example::
from tornado.options import define
from tornado.web import RequestHandler, asynchronous
def... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
from statusupdater import views
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^login', views.login),
url(r'^get_cod... |
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='gateway',
version='0.0.1',
description='gateway',
long_descrip... |
from hyperstream import TimeInterval, MIN_DATE
from hyperstream.tool import MultiOutputTool
from hyperstream.stream import StreamMetaInstance, AssetStream
import logging
from copy import deepcopy
class SplitterFromStream(MultiOutputTool):
"""
This version of the splitter assumes that the mapping exists as the l... |
from kombu import Connection
from kombu import Exchange, Queue, pools
from microservices.utils import get_logger
from microservices.helpers.logs import InstanceLogger
import six
_logger = get_logger(__file__)
class _exchange(object):
"""Exchange helper"""
def __init__(self, client, name, routing_key=None, logge... |
'''
The four adjacent digits in the 1000-digit number that
have the greatest product are 9 × 9 × 8 × 9 = 5832.
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896... |
import logging
try:
from urlparse import urlparse
except ImportError:
# python 3
from urllib.parse import urlparse
from django.conf import settings
from django.views.decorators.cache import never_cache
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_protect... |
from django.conf import settings
from django.core.management.base import NoArgsCommand
from django_cas.models import SessionServiceTicket
class Command(NoArgsCommand):
help = "Purges CAS session - service ticket mappings not matching any session."
def handle_noargs(self, **options):
"""Purges Session Se... |
"""
A simple GEGL snippet with the Gobject automatic introspection method.
This inverts the colors of a PNG file.
BUG: GEGL has been built without introspection on Debian 8.
See https://github.com/jsbueno/python-gegl/issues/2
See: http://linuxfr.org/news/gegl-0-3-0-et-babl-0-1-12-sont-de-sortie
http://gegl.or... |
import sys
import traceback
import unittest
from cutoff import CutoffTest
from mfcc import MFCCTest
import signal_comparison
from sound_file import SoundFileTest
def run_tests():
unittest.main()
if __name__ == "__main__":
try:
file_names = ["recordings//" + str + ".wav" for str in
... |
import os, re, os.path, shutil
from behave import *
def get_stream(context, stream):
assert stream in ['stderr', 'stdout'], "Unknown output stream {}".format(stream)
return getattr(context.output, stream)
def get_env_path(context, file_):
return os.path.join(context.env.cwd, file_)
def get_data_file_path(fi... |
from flask import Flask, render_template, request
import trafficlights.controller as controller
import trafficlights.poller as poller
from trafficlights.updaters.teamcity_updater import TeamCityUpdater
from trafficlights.updaters.flash_updater import FlashUpdater
import os
import pwd
import logging
from logging.handler... |
import traceback
import json
from rq.timeouts import JobTimeoutException
import smtplib
import quopri
from email.parser import Parser
import frappe
from frappe import _, safe_encode, task
from frappe.model.document import Document
from frappe.email.queue import get_unsubcribed_url
from frappe.email.email_body import ad... |
"""
Package for magical effects
"""
from .damage import DamageEffect
from .damagemodifier import DamageModifier
from .effectscollection import EffectsCollection
from .effect import Effect, EffectHandle
from .heal import Heal
from .movementmode import MovementModeModifier
from .poison import Poison |
from pyramid.config import Configurator
from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from sqlalchemy import engine_from_config
from .models import (
DBSession,
Base,
)
import os
def main(global_config, **settings):
""" This funct... |
class TinydealPipeline(object):
def process_item(self, item, spider):
return item |
c = open('commons.py')
b = open('blabla.py')
o = open('commons2.py', 'w')
u = [line.strip('\n') for line in c]
lo = [line for line in b]
for x, y in zip(u, lo):
o.write(x + y) |
import csv as csvreader
import pdb as pdb
import time as time
import sys as sys
import logging as logging
""" SERP_mat_conditioner is a simple python script that takes in a comma delimited input
file which contains parameters and options and outputs the appropriate material
composition in atomic percent inside ... |
from __future__ import division, print_function, unicode_literals
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
testinfo = "s, q"
tags = "TmxObjectLayer, get_in_region"
import pyglet
from pyglet.window import key
pyglet.resource.path.append(pyglet.resource.get_script_home())
pyg... |
import subprocess, os
from conans.errors import ConanException
from conans.util.runners import check_output_runner
class PkgConfig(object):
@staticmethod
def _cmd_output(command):
return check_output_runner(command).strip()
def __init__(self, library, pkg_config_executable=None, static=False, msvc_s... |
from app.repositories.nn_training_result_repository import fetch_from_patch
class NnTrainingResultService:
def __init__(self, patch):
self._patch = patch
def get_nn_performance(self):
return fetch_from_patch(self._patch) |
class Solution(object):
def solveSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
cols = [[False] * 9 for _ in range(9)]
rows = [[False] * 9 for _ in range(9)]
blocks = [[False] * 9 f... |
from __future__ import unicode_literals
from django.db import migrations, models
import web_client.models
class Migration(migrations.Migration):
initial = True
dependencies = [
('web_client', '0002_delete_siteconfiguration'),
]
operations = [
migrations.CreateModel(
name='Sit... |
import logging
from flask import Blueprint, redirect, url_for, session, request, jsonify
from flask_oauthlib.client import OAuth
import requests
google_oauth_provider = Blueprint('google_oauth_provider', __name__)
from app import app
from . import user_access
from config.config import BaseConfig
logging.basicConfig(lev... |
from .mgrslib import * |
import os, sys
from goldensixpacks import app
app.run(host='0.0.0.0') |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "happyteams.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is r... |
import utils
class plugin_singleton:
def __init__(self, parent, content, position, arguments):
[pos, class_name] = utils.getClassName(content, position)
self.__content = """
private:
%%classname%%();
%%classname%%(%%classname%% const&);
voi... |
"""
<DefineSource>
@Date : Fri Nov 14 13:20:38 2014 \n
@Author : Erwan Ledoux \n\n
</DefineSource>
A Brianer
"""
import ShareYourSystem as SYS
BaseModuleStr="ShareYourSystem.Standards.Recorders.Simulater"
DecorationModuleStr="ShareYourSystem.Standards.Classors.Classer"
SYS.setSubModule(globals())
from ShareYourSystem.S... |
from math import sqrt
class Position:
def __init__(self, x, y):
self.x = x
self.y = y
def length(self):
return sqrt(self.x**2 + self.y**2)
def substract(self, vector):
return Position(self.x - vector.x, self.y - vector.y)
def multiply(self, magnitude):
return Posi... |
from dp_tornado.engine.controller import Controller
class FlushallController(Controller):
def get(self):
self.model.tests.model_test.cache_test.flushall_redis()
self.finish('done') |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "SudokuSolver.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Article',
fields=[
... |
from django.conf.urls import patterns, url
urlpatterns = patterns(
'stores.views',
url(r'^(?P<slug>[\w-]+)/$', 'store', name='store'),
url(r'^(?P<store_slug>[\w-]+)/(?P<slug>[\w-]+)/$',
'product', name='product'),
url(r'^(?P<store_slug>[\w-]+)/(?P<slug>[\w-]+)/add/$',
'add_to_cart', name... |
from __future__ import with_statement
from fabric.api import run, cd
from journeyman.buildrunner.registry import registry
def fetch_pip_dependencies(build_runner, **kwargs):
# Move into the source/repo directory
with cd(build_runner.build_src):
# Get files from config
files = kwargs.get('lines',... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
import tensorflow as tf
from resnet.data import cifar_input
class CIFAR100Dataset():
def __init__(self,
folder,
split,
num_fold=10,
... |
import socket
import argparse
import traceback
import configuration
import tuner
import sys
class streamJit:
def __init__(self, port):
self.port = port
self.program = "streamApp"
def listen(self):
try:
print 'listening for client at local prot %d'%self.port
server_socket = socket.socket(socket.AF_INET, so... |
import re
import unicodedata
from flask_sqlalchemy.model import camel_to_snake_case
from .decorators import was_decorated_without_parenthesis
from .mail import send_mail
def slugify(string):
string = re.sub(r'[^\w\s-]', '',
unicodedata.normalize('NFKD', string.strip()))
return re.sub(r'[-\s]... |
from __future__ import annotations
import argparse
import os.path
import re
from typing import Sequence
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*')
parser.add_argument(
'--django', default=False, action='store_tru... |
from django.db import models, migrations
import django.utils.timezone
import uuid
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Event',
fields=[
('created', models.DateTimeField(auto_now_add=True, editab... |
import sys, os, time
from shutil import copyfile
from docutils.core import publish_parts
sys.path.insert(0, os.path.abspath('..'))
sys.path.append(os.path.abspath('.'))
sys.path.append(os.path.abspath('html'))
def rst2html(input, output):
"""
Create html file from rst file.
:param input: Path to rst source ... |
import sys
import traceback
if sys.version_info[0] == 3:
def B(value):
return value.encode('ascii')
else:
def B(value):
return value
kAEInternetSuite=B('gurl')
kAEISGetURL=B('gurl')
kCoreEventClass=B('aevt')
kAEOpenApplication=B('oapp')
kAEOpenDocuments=B('odoc')
keyDirectObject=B('----')
typeAE... |
import bleach
from django.contrib.contenttypes.models import ContentType
from django.core import urlresolvers
from django.db import models
from django.utils.formats import date_format
from django.utils.translation import ugettext as _
from django.utils import timezone
from django_countries.fields import CountryField
cl... |
import os
import sys
use_verbose_logging = 'verbose' in sys.argv
def sh(cmd):
if use_verbose_logging:
print(cmd)
return os.system(cmd)
def compile_test(test):
sh('gcc -std=gnu99 -Wall -Wextra -I../include -ffreestanding -nostdlib -c {test}.c -o {test}.o'.format(test=test))
def link_test(test):
sh('ld main.o {test... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.