code stringlengths 1 199k |
|---|
import functools
import itertools
from ..backend_object import BackendObject
def normalize_types(f):
@functools.wraps(f)
def normalizer(self, region, o):
'''
Convert any object to an object that we can process.
'''
if isinstance(o, IfProxy):
return NotImplemented
... |
import matplotlib.pyplot as plt
import numpy as np
import os
import time
import yaml
from sklearn.learning_curve import learning_curve
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
from keras.models import Sequential, model_from_yaml
from keras.wrappers.scikit_learn im... |
from JumpScale import j
import unittest
import JumpScale.portal
descr = """
test jpackages over rest to portal (appserver)
"""
organization = "jumpscale"
author = "kristof@incubaid.com"
license = "bsd"
version = "1.0"
category = "appserver.jpackages.rest,portal"
enable=True
priority=5
class TEST(unittest.TestCase):
... |
try:
import simplejson as json
except ImportError:
import json
import functools
from cgi import parse_header
def wrap_json(func=None, *, encoder=json.JSONEncoder, preserve_raw_body=False):
"""
A middleware that parses the body of json requests and
encodes the json responses.
NOTE: this middlewar... |
from __future__ import absolute_import
import re, os, sys
from clay import app
import clay.config
from flask import make_response, request, redirect, render_template, url_for
from epubber.fimfic_epubgen import FimFictionEPubGenerator
site_epub_classes = [
FimFictionEPubGenerator
]
accesslog = clay.config.get_logger... |
"""
PyLTI is module that implements IMS LTI in python
The API uses decorators to wrap function with LTI functionality.
"""
VERSION = "0.3.2" # pragma: no cover |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import matplotlib as mpl
import matplotlib.pyplot as plt
from .theme import theme_base
class theme_xkcd(theme_base):
"""
xkcd theme
The theme internaly uses the settings from pyplot.xkcd().
"""
... |
correct = [[1,2,3],
[2,3,1],
[3,1,2]]
incorrect = [[1,2,3,4],
[2,3,1,3],
[3,1,2,3],
[4,4,4,4]]
incorrect2 = [[1,2,3,4],
[2,3,1,4],
[4,1,2,3],
[3,4,1,2]]
incorrect3 = [[1,2,3,4,5],
[2,3,1,5,6],
... |
from django import template
from django.forms.forms import BoundField
register = template.Library()
class NamelessField(BoundField):
def __init__(self, field):
self.__dict__ = field.__dict__
def as_widget(self, widget=None, attrs=None, only_initial=False):
"""
Renders the field by render... |
import time
def Rank(self, parts, fromloc, overriderank, server=None):
username = parts[2].lower()
year = time.strftime("%Y")
month = time.strftime("%m")
if username == "099":
if not (int(year) > 2012 and int(month) > 3):
return "099 may not be ranked until April 1st 2013."
if se... |
from numba import njit, prange
import numpy as np
import argparse
import time
def kde(X):
b = 0.5
points = np.array([-1.0, 2.0, 5.0])
N = points.shape[0]
n = X.shape[0]
exps = 0
# "prange" in a normal function is identical to "range"
for i in prange(n):
p = X[i]
d = (-(p-poin... |
from django.db.models import Q
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.utils.timezone import now
from django.conf import settings
from django import template # import Template,Context
from django.contrib.contenttypes.m... |
from __future__ import unicode_literals
from builtins import str
import six
import datetime
from django.db import models
from django.db.models import Q
from django.conf import settings
from django.core.validators import MaxValueValidator
from django.core.validators import MinValueValidator
from django.core.exceptions i... |
"""
Benchmark how long it takes to set 10,000 keys in the database.
"""
from __future__ import print_function
import trollius as asyncio
from trollius import From
import logging
import trollius_redis
import time
from six.moves import range
if __name__ == '__main__':
loop = asyncio.get_event_loop()
# Enable logg... |
import os
import unittest
from math import pi
import numpy
from kiva import agg
def save_path(filename):
return filename
def draw_arcs(gc, x2, y2, radiusstep=25.0):
gc.set_stroke_color((0.2,0.2,0.2)) # lightgray
gc.move_to(0, 0)
gc.line_to(100, 0)
gc.line_to(x2, y2)
gc.stroke_path()
gc.set... |
import os
import time
import shutil
import traceback
import signal
from collections import OrderedDict
import re
import flask
import gevent
import gevent.event
import gevent.queue
from config import config_value
from . import utils
from status import Status
from job import Job
from dataset import DatasetJob
from model ... |
"Run the keyword-names example pipeline, which has keyword-style inputs."
import kiveapi
import example_tools
session = kiveapi.KiveAPI("http://localhost:8000")
session.login('kive', 'kive')
names_dataset = session.find_datasets(name="example_names.csv")[0]
salutations_dataset = session.find_datasets(name="salutations.... |
__all__ = ['Kane']
from sympy import Symbol, zeros, Matrix, diff, solve_linear_system_LU, eye
from sympy.utilities import default_sort_key
from sympy.physics.mechanics.essential import ReferenceFrame, dynamicsymbols
from sympy.physics.mechanics.particle import Particle
from sympy.physics.mechanics.point import Point
fr... |
import csv
from io import TextIOWrapper
import six
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from django.db import transaction
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from djan... |
import math
import numpy
import numpy.random
import scipy.stats
import functools
from collections import defaultdict
from nose import SkipTest
from nose.tools import assert_greater
from nose.tools import assert_in
from nose.tools import assert_is_instance
from nose.tools import assert_not_equal
from nose.tools import a... |
import HTMLParser
import json
from xml.etree import ElementTree
from django.conf import settings
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse, HttpResponseBadRequest, Http404
from django.shortcuts import get_object_or_404
fro... |
import aggdraw as agg
from ginga import colors
class AggContext(object):
def __init__(self, canvas):
self.canvas = canvas
def set_canvas(self, canvas):
self.canvas = canvas
def get_color(self, color):
if isinstance(color, str):
r, g, b = colors.lookup_color(color)
... |
"""
"""
from __future__ import print_function, absolute_import, division, unicode_literals
import numpy as np
import os, sys
import matplotlib.pyplot as plt
import glob
from PyQt4 import QtGui
from PyQt4 import QtCore
from matplotlib import mpl
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureC... |
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
import os.path
import subprocess
import sys
libpg_query = os.path.join('.', 'libpg_query')
class PSqlParseBuildExt(build_ext):
def run(self):
return_code = subprocess.call(['make', '-C', libpg_query, 'build'])
... |
import pulsar as psr
def load_ref_system():
""" Returns l-arginine as found in the IQMol fragment library.
All credit to https://github.com/nutjunkie/IQmol
"""
return psr.make_system("""
N 0.8592 -2.9103 -0.8578
C 1.3352 -1.5376 -1.1529
C 2.8596... |
from unittest import mock
from olympia.amo.cron import gc
from olympia.amo.tests import TestCase
from olympia.files.models import FileUpload
@mock.patch('olympia.amo.cron.storage')
class TestGC(TestCase):
def test_file_uploads_deletion(self, storage_mock):
fu_new = FileUpload.objects.create(path='/tmp/new',... |
from gurtel.util import Url
class TestUrl(object):
def equal(self, one, two):
"""
For this test, want to ensure that compare-equal implies hash-equal.
"""
return (one == two) and (hash(one) == hash(two))
def test_no_qs(self):
assert self.equal(
Url("http://fak... |
"""Repository of clusterPy's main class "Layer"
"""
__author__ = "Juan C. Duque, Alejandro Betancourt"
__credits__ = "Copyright (c) 2009-10 Juan C. Duque"
__license__ = "New BSD License"
__version__ = "1.0.0"
__maintainer__ = "RiSE Group"
__email__ = "contacto@rise-group.org"
__all__ = ['Layer']
import copy
import cPic... |
from __future__ import division, print_function, unicode_literals, \
absolute_import
import unittest
import os
import json
import numpy as np
import pandas as pd
from pymatgen import Structure
from veidt.describer.general import FuncGenerator, MultiDescriber
from veidt.describer.structural_describer import Distinct... |
from webargs import fields
from ..api.validators import Email, password
user_args = {
'email': fields.Str(validate=Email, required=True),
'password': fields.Str(validate=password, required=True)
}
role_args = {
'name': fields.Str(required=True),
'description': fields.Str(required=True)
} |
"""
Utilities for generating the version string for Astropy (or an affiliated
package) and the version.py module, which contains version info for the
package.
Within the generated astropy.version module, the `major`, `minor`, and `bugfix`
variables hold the respective parts of the version number (bugfix is '0' if
absen... |
import json
import logging
import time
from datetime import datetime, timedelta
from itertools import chain
from django.conf import settings
from django.http import (
HttpResponse, HttpResponseBadRequest, HttpResponseRedirect)
from django.shortcuts import render
from django.utils.html import escape
from django.util... |
"""Unittest for reflection.py, which also indirectly tests the output of the
pure-Python protocol compiler.
"""
__author__ = 'robinson@google.com (Will Robinson)'
import copy
import gc
import operator
import struct
from google.apputils import basetest
from google.protobuf import unittest_import_pb2
from google.protobuf... |
from mission.constants.config import PIPE_SEARCH_DEPTH
from mission.framework.combinators import *
from mission.framework.primitive import *
from mission.framework.position import *
from mission.framework.movement import *
from mission.framework.task import *
from mission.framework.timing import *
from mission.framewor... |
from gevent import monkey
monkey.patch_all()
import pytest
import gevent
import marshmallow
from channelstream.server_state import get_state
from channelstream.channel import Channel
@pytest.mark.usefixtures("cleanup_globals", "pyramid_config")
class TestConnectViews(object):
def test_bad_json(self, dummy_request, ... |
import wx
import wx.glcanvas
import pyglet
import pyglet.gl as gl
import pyglet.gl
import motmot.wxvideo.wxvideo as wxvideo
NewImageReadyEvent = wx.NewEventType() # use to trigger GUI thread action from grab thread
class PygWxContext:
_gl_begin = False
_workaround_unpack_row_length = False
def __init__(self... |
import logging
from django.contrib import messages
from django.contrib.auth.decorators import user_passes_test
from django.contrib.admin.utils import NestedObjects
from django.urls import reverse
from django.db import DEFAULT_DB_ALIAS
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts impo... |
import logging
from django.conf import settings
from django.db import models
from mkt.site.mail import send_mail
from mkt.site.models import ModelBase
from mkt.users.models import UserProfile
from mkt.webapps.models import Webapp
from mkt.websites.models import Website
log = logging.getLogger('z.abuse')
class AbuseRepo... |
from itertools import product
from inspect import signature
import warnings
from textwrap import dedent
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
from ._core import VectorPlotter, variable_type, categorical_order
from . import utils
from .utils import _check_argumen... |
from PIL import Image
from maskgen import exif
import numpy as np
import PIL
"""
Save the image as PDF. If the image has a orientation and 'Image Rotated', rotate the image according to the EXIF.
"""
def transform(img,source,target, **kwargs):
if 'resolution' in kwargs:
res = float(int(kwargs['resolution'])... |
"""
Kay preparse management command.
:Copyright: (c) 2009 Accense Technology, Inc.
Takashi Matsuo <tmatsuo@candit.jp>,
All rights reserved.
:license: BSD, see LICENSE for more details.
"""
import os
import sys
from os import listdir, path, mkdir
from werkzeug.utils import impor... |
"""Deglitch utilities
=====================
"""
import numpy as np
import logging
_logger = logging.getLogger("sloth.math.deglitch")
def remove_spikes_medfilt1d(y_spiky, backend="silx", kernel_size=3, threshold=0.1):
"""Remove spikes in a 1D array using medfilt from silx.math
Parameters
----------
y_spi... |
__all__ = ['pdb']
__version__ = '0.9.0'
import sys
from fairseq.logging import meters, metrics, progress_bar # noqa
sys.modules['fairseq.meters'] = meters
sys.modules['fairseq.metrics'] = metrics
sys.modules['fairseq.progress_bar'] = progress_bar
import fairseq.criterions # noqa
import fairseq.models # noqa
import f... |
from spectrum.datasets import *
def test_marple_data():
d = marple_data
assert len(d) == 64
def test_timeseries():
data = data_cosine(N=1024, A=0.1, sampling=1024, freq=200)
ts = TimeSeries(data, sampling=1)
#assert ts.N == 1024
#assert ts.sampling == 1024
ts.plot()
def test_data_cosine():
... |
"""
"""
from collections import namedtuple
from minghu6.internet.proxy_ip import proxy_ip
from minghu6.text.seq_enh import filter_invalid_char
URL_LIST_FILE_PATH = 'URList-{username:s}.txt'
UrlNameTuple = namedtuple('UrlNameTuple', ['url', 'title']) |
"""Test segzify.""" |
'''
Copyright (c) 2013, LastSeal S.A.
Copyright (c) 2011-2012, Joaquin G. Duo
All rights reserved.
This code is distributed under BSD 3-clause License.
For details check the LICENSE file in the root of the project.
'''
class context_singleton(object):
'''
Singleton pattern decorator.
It provides a singl... |
from django.db.models import Prefetch, prefetch_related_objects
from django.test import TestCase
from .models import Author, Book, Reader
class PrefetchRelatedObjectsTests(TestCase):
"""
Since prefetch_related_objects() is just the inner part of
prefetch_related(), only do basic tests to ensure its API hasn... |
VERSION = (1, 4) |
from zeit.cms.i18n import MessageFactory as _
from zope.cachedescriptors.property import Lazy as cachedproperty
import os.path
import zeit.cms.browser.view
import zeit.cms.content.interfaces
import zeit.cms.interfaces
import zeit.content.image.interfaces
import zeit.content.video.interfaces
import zeit.edit.browser.for... |
import re
_BISECT_CONFIG_SCHEMA = {
'command': {'type': 'string', 'required': True},
'good_revision': {'type': 'revision', 'required': True},
'bad_revision': {'type': 'revision', 'required': True},
'bisect_bot': {'type': 'string'},
'metric': {'type': 'string'},
'bug_id': {'type': 'integer'},
... |
def print_from_queue(q):
"""
prints values read from queue q to
standard out.
"""
while True:
v = q.get()
if v is None:
# exit loop
return
else:
print (str(v))
class queue_to_file(object):
"""
self.actuate(a) puts values from a queu... |
from __future__ import absolute_import
from exam import fixture
from six.moves.urllib.parse import parse_qs, urlparse
from sentry.models import ApiApplication, ApiAuthorization, ApiGrant, ApiToken
from sentry.testutils import TestCase
class OAuthAuthorizeCodeTest(TestCase):
@fixture
def path(self):
retu... |
import os
import tempfile
import shutil
from django.conf import settings
from django.core.files.storage import default_storage as storage
from django.test.client import RequestFactory
from mock import patch
from olympia import amo, core
from olympia.addons import forms
from olympia.addons.models import Addon, Category
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from keras.optimizers import SGD
from keras.optimizers import Adam
from keras.optimizers import adadelta
from keras.optimizers import rmsprop
from keras.layers import Layer
from keras import backend as K
K.set_i... |
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import Co... |
import os
from setuptools import setup
from setuptools import find_packages
version = '0.1'
shortdesc = "Klarna Payment for bda.plone.shop"
setup(
name='bda.plone.klarnapayment',
version=version,
description=shortdesc,
classifiers=[
'Environment :: Web Environment',
'License :: OSI Appro... |
import importlib
import inspect
from celery import task
from django.conf import settings
from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk as es7_bulk
from elasticsearch.helpers.errors import BulkIndexError
from elasticsearch_dsl import Document, UpdateByQuery, analyzer, char_filter, token_... |
import os
DEBUG = True
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
SITE_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'post... |
help_txt = """
:help, show this help menu. :help [command] for detail
:dict [word], only find translation on dict.cn
:google [sentence], only find translation on google api
:lan2lan [sentence], translate from one language to another language
:add [word], add new word to your library
:del [word], delete word from your l... |
'''
TODO:
optimize adds, multiplies, 'or' and 'and' as they can accept more than two values
validate type info on specific functions
'''
from .matching import AstHandler, ParseError, DateTimeFunc
class AggregationParser(AstHandler):
FUNC_TO_ARGS = {'concat': '+', # more than 1
'strcasecmp': 2,
... |
from __future__ import absolute_import, division, print_function
import pytest
import numpy as np
from ...extern import six
from ..data_info import dtype_info_name
STRING_TYPE_NAMES = {(False, 'S'): 'str', # PY2
(False, 'U'): 'unicode',
(True, 'S'): 'bytes', # not PY2
... |
from __future__ import division, print_function
from os.path import join, split, dirname
import os
import sys
from distutils.dep_util import newer
from distutils.msvccompiler import get_build_version as get_msvc_build_version
def needs_mingw_ftime_workaround():
# We need the mingw workaround for _ftime if the msvc ... |
"""Watch for changes in a collection of source files. If changes, run
the specified test runner (nosetests, by default).
"""
from argparse import ArgumentParser
import ConfigParser
import glob
import os
import stat
import subprocess
import sys
import time
class Nosy(object):
"""Watch for changes in all source files... |
from magicbot.state_machine import (
default_state,
state,
timed_state,
AutonomousStateMachine,
StateMachine,
IllegalCallError,
NoFirstStateError,
MultipleFirstStatesError,
MultipleDefaultStatesError,
InvalidStateName,
)
from magicbot.magic_tunable import setup_tunables
import py... |
from mod_python import apache
from mod_python import util
import os.path
import urllib
import logging
debug = True
def handler(req):
"""
This is called by Apache and maps the request to the resource class.
Process of maping:
1. Try import a python script which handles this resource.
The... |
def extractWwwTccedwardsCom(item):
'''
Parser for 'www.tccedwards.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', 'Loite... |
import unittest
from restkiss.preparers import Preparer, FieldsPreparer
class InstaObj(object):
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
class LookupDataTestCase(unittest.TestCase):
def setUp(self):
super(LookupDataTestCase, self).setUp()
... |
import sys
from arrowhead.core import Step
from arrowhead.core import ErrorArrow
from arrowhead.core import NormalArrow
from arrowhead.core import ValueArrow
def print_flow_state(flow, active_step_name=None, file=sys.stdout):
"""
Display the state of a given flow.
:param flow:
A Flow, instance or cl... |
from __future__ import absolute_import
from mayavi.core.api import * |
__author__ = 'michael'
from django import template
from unobase import models as unobase_models
register = template.Library()
@register.inclusion_tag('blog/widgets/tag_cloud.html')
def tag_cloud(blog_slug):
tags = unobase_models.TagModel.get_distinct_tags('blogentry')
#set(unobase_models.TagModel.get_tags('blog... |
"""
Google Code Wiki translator.
Syntax defined by http://code.google.com/p/support/wiki/WikiSyntax
Here called gwiki to make the dialect clear (g for google).
"""
import re, os, commands, sys
from common import default_movie, plain_exercise, insert_code_and_tex, \
fix_ref_section_chapter
from plaintext import pla... |
import os
import shutil
import addSubproject
import option
import utility
import grapeGit as git
import grapeConfig
import grapeMenu
import checkout
class UpdateView(option.Option):
"""
grape uv - Updates your active submodules and ensures you are on a consistent branch throughout your project.
Usage: gra... |
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import sy, sy.path
setup(
name='sy',
version=sy.__version__,
url='http://sy.afajl.com',
license='BSD',
author='Paul Diaconescu',
author_email='p@afajl.com',
description='Simple tools for ... |
"""
WSGI config for goska project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "goska.settings")
from django.core.wsgi impo... |
from enable.api import ColorTrait
from .base_patch_stylus import BasePatchStylus
class RectangleStylus(BasePatchStylus):
""" A Flyweight object for drawing filled rectangles.
"""
edge_color = ColorTrait('black')
fill_color = ColorTrait('yellow')
def draw(self, gc, rect):
with gc:
... |
'''
Created on 14.07.2015
@author: Aaron Klein
'''
import numpy as np
from robo.task.base_task import BaseTask
class Hartmann6(BaseTask):
def __init__(self):
X_lower = np.array([0, 0, 0, 0, 0, 0])
X_upper = np.array([1, 1, 1, 1, 1, 1])
opt = np.array([[0.20169, 0.150011, 0.476874, 0.275332, ... |
"""Common settings and globals."""
from os.path import abspath, basename, dirname, join, normpath
from sys import path
DJANGO_ROOT = dirname(dirname(abspath(__file__)))
SITE_ROOT = dirname(DJANGO_ROOT)
SITE_NAME = basename(DJANGO_ROOT)
path.append(DJANGO_ROOT)
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Your ... |
"""Bridge for using cclib data in PyQuante (http://pyquante.sourceforge.net)."""
from __future__ import print_function
import sys
try:
from PyQuante.Molecule import Molecule
except ImportError:
# Fail silently for now.
pass
def makepyquante(atomcoords, atomnos, charge=0, mult=1):
"""Create a PyQuante Mo... |
"""
Documents metadata tools.
"""
from __future__ import absolute_import, print_function, unicode_literals
import yaml
DELIMITER = '---'
def stripped(stream):
"""
Read stream to strip YAML header, returns stripped data.
"""
data = []
meta_started = False
meta_ended = False
# TODO: cleaner im... |
from canvas.exceptions import ServiceError, ValidationError
from canvas.economy import InvalidPurchase
from drawquest import knobs
from drawquest.apps.palettes.models import get_palette_by_name, all_palettes
from drawquest.signals import balance_changed
def balance(user):
return int(user.kv.stickers.currency.get() ... |
import sys
import os.path
import re
import operator
import digits
from digits import utils
from digits.utils import subclass, override
from digits.task import Task
PICKLE_VERSION = 3
@subclass
class CreateDbTask(Task):
"""Creates a database"""
def __init__(self, input_file, db_name, backend, image_dims, **kwarg... |
from django.shortcuts import get_object_or_404
from apps.canvas_auth.models import User
from canvas.api_decorators import api_decorator
from canvas.metrics import Metrics
from canvas.models import Comment
from canvas.view_guards import require_user
urlpatterns = []
api = api_decorator(urlpatterns)
@api('hide_comment')
... |
'''
Show how to access glyph outline description.
'''
from freetype import *
if __name__ == '__main__':
import numpy
import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches
face = Face(b'./Vera.ttf')
face.set_char_size( 48*64 )
face.load_char('S'... |
from __future__ import absolute_import, division, print_function, unicode_literals
from django.core.management import call_command
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Completely rebuilds the search index by removing the old data and then updating."
def add_arg... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('latest_tweets', '0010_photo_unique'),
]
operations = [
migrations.AddField(
model_name='photo',
name='image_file',
fi... |
"""Fichier contenant des fonctions utiles à la manipulation de masques."""
def chaine_vers_liste(chaine):
"""Convertit une chaîne en sa liste de caractères"""
return list(chaine)
def liste_vers_chaine(liste):
"""Convertit une lsite de caractères en une chaîne"""
return "".join(liste)
def lstrip(liste):
... |
from __future__ import absolute_import, division, print_function
import numpy as np
from matplotlib.colors import Normalize
from matplotlib.collections import LineCollection
from mpl_scatter_density import ScatterDensityArtist
from astropy.visualization import (ImageNormalize, LinearStretch, SqrtStretch,
... |
import os
in_dir = "D:/Projects/CrashRpt/valid_reports"
out_file = "stats.txt"
f = open(out_file, "w")
def get_txt_file_count(dirname):
count = 0
for root, dirs, files in os.walk(dirname, True):
for file in files:
if file[-4:] != ".txt":
continue;
count += 1
break;
return ... |
import json
from datetime import datetime
from dojo.models import Finding
class MeterianParser(object):
def get_scan_types(self):
return ["Meterian Scan"]
def get_label_for_scan_types(self, scan_type):
return scan_type
def get_description_for_scan_types(self, scan_type):
return "Mete... |
import sys
import time
output = sys.argv[1]
persistoutput = "%s.persist" % sys.argv[1]
count = 0
try:
count = open(persistoutput, 'r').read()
except:
pass
count = int(count) + 1
if len(sys.argv) > 2:
max_count = int(sys.argv[2])
if count > max_count:
count = max_count
oldcount = 0
try:
oldcount = open(out... |
from setuptools import setup, find_packages
import os
import cms
CLASSIFIERS = [
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independen... |
import os
import numpy as np
import hftools.dataset.arrayobj as aobj
import hftools.networks.spar_functions as spfun
from hftools.testing import TestCase
basepath = os.path.split(__file__)[0]
def make_array(a):
dims = (aobj.DimSweep("f", len(a)),
aobj.DimMatrix_i("i", 2),
aobj.DimMatrix_j("j... |
import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "django-pressroom",
version = "0.4.2.1",
url = 'https://github.com/petry/django-pressroom',
license = 'BSD',
description = "A pressroom applicat... |
import getopt
try:
import pyclamd
HAVE_CLAMD = True
except ImportError:
HAVE_CLAMD = False
from viper.common.out import *
from viper.common.abstracts import Module
from viper.core.session import __sessions__
class ClamAV(Module):
cmd = 'clamav'
description = 'Scan file from local ClamAV daemon'
... |
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
from sentry.utils.query import RangeQuerySetWrapperWithProgressBar
class Migration(DataMigration):
# Flag to indicate if this migration is too risky
# to run online and need... |
from evernote.api.client import EvernoteClient
import evernote.edam.notestore.ttypes as NoteStoreTypes
access_token = "insert dev or oauth token here"
client = EvernoteClient(token = access_token, sandbox = True)
note_store = client.get_note_store()
note_filter = NoteStoreTypes.NoteFilter()
note_filter.words = "created... |
import datetime
import re
from django.http import HttpResponse
from django.utils.http import urlencode
import smsgateway
from smsgateway.models import SMS
from smsgateway.backends.base import SMSBackend
from smsgateway.utils import check_cell_phone_number
class MobileWebBackend(SMSBackend):
def get_send_url(self, s... |
"""Fichier contenant l'ordre Virer."""
from secondaires.navigation.equipage.signaux import *
from ..ordre import *
class Virer(Ordre):
"""Ordre virer.
Cet ordre demande au matelot de faire virer le navire sur bâbord
ou tribord en fonction du besoin, jusqu'à ce qu'il soit dans une certaine
direction. Le ... |
'''Handling of the <message> element.
'''
from __future__ import print_function
import re
import six
from grit.node import base
from grit import clique
from grit import exception
from grit import lazy_re
from grit import tclib
from grit import util
_ELLIPSIS_PATTERN = lazy_re.compile(r'(?<!\.)\.\.\.(?=$|\s)')
_ELLIPSIS... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.