code stringlengths 1 199k |
|---|
from pyload.utils import json_loads
from pyload.plugin.internal.MultiHoster import MultiHoster
from pyload.utils import parse_size
class OverLoadMe(MultiHoster):
__name = "OverLoadMe"
__type = "hoster"
__version = "0.11"
__pattern = r'https?://.*overload\.me/.+'
__config = [("use_premium", "b... |
import sys
import requests
REVIEW_URL = "http://www.goodreads.com/book/review_counts.json"
def insert_ratings(books):
print "\b.",
sys.stdout.flush()
isbn_str = ",".join([book["isbn"] for book in books])
result = {}
for book in requests.get(REVIEW_URL + "?isbns=" + isbn_str).json()["books"]:
... |
import csv
import os
from sys import argv
print "Converting " + argv[1] + " to " + argv[2]
conversations = []
with open(argv[1]) as inputFile:
reader = csv.reader(inputFile, quoting=csv.QUOTE_NONE)
for conversation in reader: # each row is a list
formatted_conversation = []
for statement in con... |
from __future__ import absolute_import
option_list = {}
from . import ( # noqa
caffe,
gpu_list,
jobs_dir,
log_file,
torch,
server_name,
store_option,
tensorflow,
url_prefix,
)
def config_value(option):
"""
Return the current configuration value for the given option
"""
... |
from dimensioning import *
from dimensioning import __dir__
import previewDimension
from centerLines import _centerLineSVG
import dimensionSvgConstructor
import numpy
from numpy import pi, sin, cos, arctan2, arcsin, arccos, dot
from numpy.linalg import norm
dotProduct = numpy.dot
crossProduct = numpy.cross
d = Dimensio... |
""" Base object for database tables """
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base() |
"""A subclass of Cheetah.Template for use in CGI scripts.
Usage in a template:
#extends Cheetah.Tools.CGITemplate
#implements respond
$cgiHeaders#slurp
Usage in a template inheriting a Python class:
1. The template
#extends MyPythonClass
#implements respond
$cgiHeaders#slurp
2. The Python class
... |
import threading
class read_stdout_thread(threading.Thread):
def __init__(self, dictionary):
threading.Thread.__init__(self)
self.daemon = True
self.dictionary = dictionary
def run(self):
while True:
chat_proc_dict = self.dictionary.copy()
for key, value i... |
import init_location
import requests
from sample_data.data_API import *
import unittest
import json
import re
from Nodes import *
URL = "http://secure-springs-85403.herokuapp.com/"
firstTime = True
"""
CS stands for Client-Server
"""
COOKIE_NAMES = ["cookie_cmput404_author_id","cookie_cmput404_session_id","cookie_cmput... |
from module.plugins.internal.DeadHoster import DeadHoster, create_getInfo
class WuploadCom(DeadHoster):
__name__ = "WuploadCom"
__type__ = "hoster"
__version__ = "0.23"
__pattern__ = r'http://(?:www\.)?wupload\..+?/file/((\w+/)?\d+)(/.*)?'
__config__ = [] #@TODO: Remove in 0.4.10
__descr... |
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from datetime import datetime
from dateutil.tz import tzoffset
from calibre.constants imp... |
def do_something():
print("something") |
import os
from django import setup
from django.conf import settings
import logging
logging.getLogger("factory").setLevel(logging.WARN)
def pytest_configure():
if not settings.configured:
from pootle import syspath_override # Needed for monkey-patching
syspath_override
os.environ['DJANGO_SET... |
import pygame
import numpy as np
from pygame.locals import *
pygame.init()
class Squares:
def __init__(self, N, cor=0.5, cor_wall=0.5, max_speed=1000, L=20):
self.pos = np.empty((N, 2), dtype=float)
self.pos[:, 0] = np.random.uniform(100, 700, size=N)
self.pos[:, 1] = np.random.uniform(100, ... |
import tkinter as tk
window = tk.Tk()
def buttonClick():
button.config(text="Clicked")
button = tk.Button(window, text="Click me!",
command = buttonClick)
button.pack()
window.mainloop() |
import random
import string
import django.contrib.auth.models
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm
from django.core.exceptions import FieldDoesNotExist
from django.db.models.fields import CharField
from django.db.models.fields imp... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("delft3dworker", "0054_auto_20160826_0747"),
]
operations = [
migrations.AddField(
model_name="container",
name="docker_log",
... |
import sys
import os
import math
from collections import namedtuple
from pylatex import Document, LongTabu, NoEscape
from pylatex.utils import bold
from enum import Enum, auto
sys.path.insert(0, '/latticeQCD/raid6/ahanlon/git/research/lattice_qcd/QCD_scripts/sigmond')
import util
IRREP_MAP = {
'A1g': r'$A_{1g}$',
... |
from django.core.files.storage import Storage
from django.core.files import File
from django.core.urlresolvers import reverse
from oioioi.filetracker.client import get_client
from oioioi.filetracker.utils import FileInFiletracker
from oioioi.filetracker.filename import FiletrackerFilename
import os
import os.path
impor... |
from __future__ import unicode_literals
AUTHOR = 'Mike & Zoey'
SITENAME = 'Mike & Zoey'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'America/Boise'
DEFAULT_LANG = 'en'
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None
LINKS = (('Pelican', 'http://get... |
from __future__ import absolute_import
import unittest
from ptbtest import UserGenerator
class TestUserGenerator(unittest.TestCase):
def setUp(self):
self.ug = UserGenerator()
def test_no_specification(self):
u = self.ug.get_user()
self.assertIsInstance(u.id, int)
self.assertTrue... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.contrib.auth.models
import django.utils.timezone
import django.core.validators
import jsonfield.fields
class Migration(migrations.Migration):
dependencies = [
('auth', '0006_require_contenttypes_0002'),
]
... |
__author__ = 'student'
import matplotlib.pyplot as plt
from random import random
I=open('float_data.txt')
data = list(map(float, I.read().split()))
plt.hist(data, bins=20)
plt.show() |
import os
import sys
import shlex
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.mathjax',
'sphinx.ext.githubpages',
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = 'Virtual Railways Tools'
copyright = '2017, Roberto Ceccarelli - CasaSoft'
author = 'Roberto Ceccarelli ... |
"""
"""
__author__='Xun Li <xunli@asu.edu>'
__all__=["StarsArtProvider"]
import wx
from toolbarimages import *
class StarsArtProvider(wx.ArtProvider):
def __init__(self):
wx.ArtProvider.__init__(self)
def CreateBitmap(self, artid, client, size):
bmp = wx.NullBitmap
if artid == "ToolBarBi... |
""" This is a test of the chain
ReqClient -> ReqManagerHandler -> ReqDB
It supposes that the DB is present, and that the service is running
"""
from DIRAC.Core.Base.Script import parseCommandLine
parseCommandLine()
import unittest
from DIRAC import gLogger
from DIRAC.Core.Security.ProxyInfo import getProxyInfo
... |
import os, sys
import csv
from BaseObject import BaseObject
class Path(BaseObject):
'''Path is a set of coordinates along which a route follows.
This translates into a shape in GTFS data.'''
paths = []
path_id = 0
def __init__(self, name, coords = None):
BaseObject.__init__(self)
sel... |
import discord
from discord.ext import commands
from __main__ import send_cmd_help
class Wikipedia:
"""Wikipedia search for the Red-DiscordBot"""
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True, no_pm=True)
async def wikipedia(self, ctx, *text):
"""Wikipedia s... |
import mmap
import struct
import socket
MAX_IPV4_RANGE = 4294967295
class IP2Location:
""" IP2Location country database """
def __init__(self, filename):
with open(filename, 'rb') as db1:
try:
self._f = mmap.mmap(db1.fileno(), 0, prot=mmap.PROT_READ)
except Attrib... |
import logging
from functools import partial
import requests
import gpodder
import soco
_ = gpodder.gettext
logger = logging.getLogger(__name__)
__title__ = _('Stream to Sonos')
__description__ = _('Stream podcasts to Sonos speakers')
__authors__ = 'Stefan Kögl <stefan@skoegl.net>'
__category__ = 'interface'
__only_for... |
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummyhead = ListNode(0)
dummyhead.next = head
cur = dummyhead
# Loop when next two nodes
while cur.next and cur.next.next:
n1, n2 = cur... |
import os
import sys
from jinja2 import Environment, FileSystemLoader
import yaml
with open(sys.argv[1], 'r') as f:
data = yaml.load(f)
env = Environment(
block_start_string = '((*',
block_end_string = '*))',
variable_start_string = '(((',
variable_end_string = ')))',
loader = FileSystemLoader('... |
"""
File:
Description:
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from builtins import object
import datetime
import nose
from io import StringIO
import tecs.rinex.v3.o as obs_v3
NAME = 'test_obs3'
RINEX = """ ... |
import random
from soma import aims, aimsalgo
import subprocess
from optparse import OptionParser
from scipy.stats import mode
import sys, glob, os, os.path, subprocess, sys, time, timeit
import numpy as np
import highres_cortex.od_cutOutRois
from soma.aims import volumetools
import matplotlib.pyplot as plt
import math... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import django.db.models.manager
import mptt.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='P... |
import functions
import cartographie
import donnees
import histogramme
def main(annee_crash):
"""
Fonction principale permettant l'appel des autres fonctions
:param annee_crash: année rentrée par l'utilisateur
:return:
"""
# Sécurité pour éviter les erreurs
try:
if annee_crash == "0"... |
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 'CodeLicense'
db.create_table('metadata_codelicense', (
('id', self.gf('django.db.models.fields.AutoField')(... |
"""
$Id: EMCToolExporter.py 629 2010-08-23 16:53:06Z sumpfralle $
Copyright 2010 Lars Kruse <devel@sumpfralle.de>
This file is part of PyCAM.
PyCAM 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 3 ... |
import pafy # pip install pafy (for downloading YouTube videos)
from pydub import AudioSegment # pip install pydub ('libavtools' and 'ffmpeg' requiered. Check "https://github.com/jiaaro/pydub#installation" for getting assistance)
import os
import os.path as path
import threading
from database import read_database... |
import glob
import subprocess
import sys
import gettext
from gettext import gettext as _
gettext.textdomain('quickly')
from quickly import configurationhandler, templatetools
def usage():
templatetools.print_usage('quickly design')
def help():
print _("""Opens Glade UI editor so that you can edit the UI for dia... |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import * # noqa
from future import standard_library
from future.utils import native
standard_library.install_aliases()
from ycmd.utils import ToBytes, Proce... |
import sys
import os
import logging
import logging.config
from datetime import datetime
from paste.deploy.converters import asbool, asint, aslist
from alerts import config_from_file, config, template_loader
from alerts.lib.mailer import Mailer, make_mailer
from alerts.lib import Message, CheckContext
from alerts.lib.lo... |
from __future__ import division, print_function, absolute_import
import warnings
import numpy.testing as npt
import numpy as np
from scipy import stats
from test_continuous_basic import distcont
DECIMAL = 5
@npt.dec.slow
def test_cont_extra():
for distname, arg in distcont[:]:
distfn = getattr(stats, distna... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Patient.age'
db.alter_column('core_patient', 'age', self.gf('django.db.models.fields.IntegerField')(null=True))
... |
import sys, time
from PyQt4 import QtCore, QtGui
import pyqtgraph
import numpy
import serial
import sys
import re
class DCF77DebugApp(QtGui.QWidget):
# DCF77_Demodulator
DCF77_Demodulator_Phase_Value = 0
DCF77_Demodulator_Tick_Value = 0
DCF77_Demodulator_MaxIndex_Value = 0
DCF77_Demodulator_Bins_Val... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('oppia', '0031_auto_20210511_1909'),
]
operations = [
migrations.AlterField(
model_name='award',
name='certificate_pdf',
field=models.FileField(default=None,
... |
import mercurial.node
CFN = '.veh.conf'
def warn_changes(ui, repo, hooktype, **kwargs):
"""hg hook to monitor changes of .veh.conf in pull and update.
install in hgrc:
[hooks]
changegroup.veh=python:veh.hooks.warn_changes
preupdate.veh=python:veh.hooks.warn_changes
"""
try:
if hookty... |
'''Item 23 from Effective Python'''
''' sort a list of names based on their lengths by providing a lambda
expression as the key hook '''
print('Example 1:\n==========')
names = ['Socrates', 'Archimedes', 'Plato', 'Aristotle']
names.sort(key=lambda x: len(x))
print (names)
''' define a hook that logs each time a key is ... |
from JDI.web.selenium.elements.composite.web_page import WebPage
class SupportPage(WebPage):
def __init__(self, url, title):
super(SupportPage, self).__init__(url=url, title=title) |
"""
Integrates bootstrap-datepicker nicely into web2py.
"""
__author__ = 'Leonel Câmara'
__email__ = 'leonel.camara@i-am.pt leonelcamara@gmail.com'
__copyright__ = 'Copyright(c) 2014 Leonel Câmara'
__license__ = 'BEER-WARE'
__version__ = '0.11'
__status__ = 'Development' # possible options: Prototype, Development, Pro... |
from ert_gui.models import Observable
class AbstractMethodError(NotImplementedError):
def __init__(self, obj, function_name):
super(AbstractMethodError, self).__init__("Class %s has not implemented support for %s()" % (obj.__class__.__name__, function_name))
class ModelMixin(object):
def __init__(self, ... |
import sys, csv, re
import util_conf
sys.path = [ util_conf.APP_PATH ] + sys.path
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ocemr.settings")
import django
django.setup()
from django.conf import settings
from ocemr.models import LabType
import datetime
reader = csv.reader(open("%s/source_data/%s/EngeyeE... |
from .planet import PlanetBuilder |
from paramecio.citoplasma.mtemplates import PTemplate, env_theme
from paramecio.citoplasma.urls import make_url
from paramecio.wsgiapp import app
from settings import config
from bottle import request
env=env_theme(__file__)
t=PTemplate(env)
@app.route('/welcome')
def home():
return t.render_template('welcome.html'... |
import argparse
import glob
import sys
from collections import Counter, defaultdict
import matplotlib.pyplot as plt
from ucca.ioutil import file2passage
desc = """Parses XML files in UCCA standard format, and creates a histogram for the number of parents per unit.
"""
def plot_histogram(counter, label, plot=None):
... |
"""A test for the main process of the HiSPARC monitor.
This process creates other objects and threads.
"""
import re
import logging
import logging.handlers
import sys
sys.path.append("..")
from EConfigParser import EConfigParser
import BufferListener
from Interpreter import Interpreter
from CheckScheduler import CheckS... |
import pymysql.cursors
HOST = 'localhost'
USER = 'root'
PASSWORD = ''
DB = ''
SELECT_EXCLUIDOS = "SELECT %s FROM %s WHERE ind_excluido = 1 ORDER BY %s"
REGISTROS_INCONSISTENTES = "DELETE FROM %s WHERE %s "
"in (%s) AND ind_excluido = 0 "
EXCLUI_REGISTRO = "DELETE FROM %s WHERE ind_excluido=1"
NORMA_DEP = "DELETE FROM v... |
import os
import shlex
import sys
from mock import Mock as MagicMock
class Mock(MagicMock):
"""
from http://read-the-docs.readthedocs.org/en/latest/faq.html#i-get-import-errors-on-libraries-that-depend-on-c-modules
"""
@classmethod
def __getattr__(cls, name):
return Mock()
MOCK_MODULES =... |
"""
/***************************************************************************
QAD Quantum Aided Design plugin
classe base per un comando
-------------------
begin : 2013-05-22
copyright : iiiii
email : hhhhh
deve... |
"""
Created on Wed May 17 16:30:01 2017
@author: Shabaka
"""
from bokeh.plotting import figure
from bokeh.io import output_file, show
from bokeh.plotting import ColumnDataSource
from bokeh.models import HoverTool
from bokeh.layouts import gridplot
from bokeh.models.widgets import Panel
from bokeh.models.widgets import ... |
import cubit
try:
cubit.init([""])
except:
pass
cfg='fullpath_myparameterfile.cfg'
o='fullpath_specfem3d_meshfiles_outputdir'
o1='fullpath_cubit_meshfiles_outputdir'
from geocubitlib import volumes, mesh_volume, exportlib
volumes.volumes(cfg)
mesh_volume.mesh(cfg)
exportlib.collect(outdir=o1)
exportlib.e2SEM(ou... |
'''
@license: GPLv3
Created on May, 2014
@author: Léonard Gérard leonard.gerard@sri.com
Generate one ROS .msg file per topic and struct type.
If a struct as a EXTERNAL_ROS_DEF field, it is used instead of generating
a new one.
'''
from radler import instrumentation
from radler.astutils.tools import write_file
from radl... |
from indico.core.logger import Logger
class NoPluginMetadataException(Exception):
pass
def processPluginMetadata(obj):
_defaults = {
'name': '',
'description': '',
'type': '',
'ignore': False,
'visible': True,
'testPlugin': False,
'requires': []
}
... |
"""
Copyright 2013 Steven Diamond
This file is part of CVXPY.
CVXPY 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 3 of the License, or
(at your option) any later version.
CVXPY is distributed in t... |
import struct
class NMBError(Exception): pass
class NotConnectedError(NMBError):
"""
Raisd when the underlying NMB connection has been disconnected or not connected yet
"""
pass
class NMBSessionMessage:
HEADER_STRUCT_FORMAT = '>BBH'
HEADER_STRUCT_SIZE = struct.calcsize(HEADER_STRUCT_FORMAT)
... |
from __future__ import unicode_literals
from django.db import migrations, models
def fixTransactionAmount(apps, schema_editor):
tranModel = apps.get_model('cashier', 'transaction')
trans = tranModel.objects.all()
for tran in trans:
if tran.typeOfTransaction == 'dept':
tran.amount *= -1
... |
from django import forms
from django.db.models import Q
from .ativos_passivos_select import tipos_códigos
from .models import Item
class ItemForm(forms.ModelForm):
class Meta:
model = Item
fields = [
'título',
'código',
'tipo',
]
def clean(self):
... |
import os
import sys
from platform import system
from setuptools import setup, find_packages
py_version = sys.version_info[:2]
PY35_OR_GREATER = py_version >= (3, 5)
ON_WINDOWS = system() == 'Windows'
if py_version < (3, 4):
raise RuntimeError('Errbot requires Python 3.4 or later')
VERSION_FILE = os.path.join('errb... |
import uuid
from django import forms
from django.db.models import Field, SubfieldBase
from django.utils.encoding import smart_unicode
try:
# psycopg2 needs us to register the uuid type
#import psycopg2
#psycopg2.extras.register_uuid()
pass #TODO!
except (ImportError, AttributeError):
pass
class Stri... |
import sys
import os
sys.path.insert(0, os.path.abspath('../../'))
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.viewcode',
'sphinxcontrib.napoleon',
]
templates_path = ['_templates']
source_suffix = '.rst'
source_encoding = 'utf-8'
master_doc = 'index'
project = u'WAPT'
copyright ... |
from cwrap import BaseCEnum
class RealizationStateEnum(BaseCEnum):
TYPE_NAME = "realisation_state_enum"
STATE_UNDEFINED = None
STATE_INITIALIZED = None
STATE_HAS_DATA = None
STATE_LOAD_FAILURE = None
STATE_PARENT_FAILURE = None
RealizationStateEnum.addEnum("STATE_UNDEFINED", 1)
RealizationStateE... |
__all__ = ["printAtomsXYZ", "PrintEvent"]
def printAtomsXYZ(fout, coords, line2="", atom_type=["LA"]):
"""
print atomic coordinate in vmd xyz format:
natoms
line2 ...could be anything, e.g. box lengths...
atom_type x[0] y[0] z[0]
atom_type x[1] y[1] z[1]
atom_type x[2] y[2] z[2]
...
... |
import copy, numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
def sigmoid(x):
output = 1/(1+np.exp(-x))
return output
def sigmoid_output_to_derivative(output):
return output*(1-output)
int2binary = {}
binary_dim = 8
largest_number = pow(2,binary_dim)
binary = np.unpackbits(
np.array([range(... |
import HTMLParser
from BeautifulSoup import BeautifulSoup as soupify
import requests
from requests import async
class Story(object):
def __init__(self, id):
self.url = "http://www.literotica.com/s/%s" %(id)
# first page, full of useful stuff yo
self.fp = ""
self.author = ""
s... |
from distutils.core import setup
long_description = """
The `pytcptunnel` is the TCP request forwarding server, in theory it can handle
the almost every TCP-based protocol like `HTTP`, `HTTPS`, even in `ssh`.
"""
setup(
name="pytcptunnel",
version="0.1",
description="TCP request forwarding server",
long... |
from sklearn.datasets import fetch_20newsgroups
categories = ['alt.atheism', 'soc.religion.christian', 'comp.graphics', 'sci.med']
twenty_train = fetch_20newsgroups(subset='train', categories=categories, shuffle=True, random_state=42)
print twenty_train |
from simplicial import *
import collections
import matplotlib as mpl
import matplotlib.pyplot as plt
def draw_complex( c, em, ax = None, color = None, color_simplex = None, node_size = 0.02 ):
"""Draw a simplicial complex embedded in space.
At present we only deal with simplices of order 2 and less.
:param ... |
from __future__ import division
from __future__ import unicode_literals
from mo_json_config import URL
from pyLibrary import convert
from active_data.app import OVERVIEW
from mo_threads import Till
from pyLibrary.env import http
from tests.test_jx import BaseTestCase, TEST_TABLE
class TestBasicRequests(BaseTestCase):
... |
import os
import time
from flask import Blueprint, Response, jsonify, render_template, request
from everyclass.server.utils.config import get_config
main_blueprint = Blueprint('main', __name__)
@main_blueprint.route('/')
def main():
"""首页"""
return render_template('common/index.html')
@main_blueprint.route('/ti... |
'''
Script to generate Themed*.java source files for Fennec.
This script runs the preprocessor on a input template and writes
updated files into the source directory.
To update the themed views, update the input template
(ThemedView.java.frag) and run the script. Use version control to
examine the differences, and don... |
from unittest import mock
import pytest
from stripe.error import InvalidRequestError
from kuma.users.models import User
@mock.patch("kuma.users.signal_handlers.cancel_stripe_customer_subscriptions")
def test_unsubscribe_payments_on_user_delete(mock_cancel, stripe_user):
"""A stripe subscription is cancelled when th... |
a = 1
b = [a, 2]
c = {a: b[0]}
d = (a, b, c)
e = {a}
f = (a & 2 * 3) - 33 / 2
g = b + [1]
h = ~a
i = a if a else h
k = b[1:2]
l = [(x, x * 2) for x in b]
m = {x : y for x in b for y in e}
n, o, p = 1, "st", True
nn = n
oo = o
pp = p |
import pytest
from datetime import datetime
from anyblok.tests.conftest import init_registry_with_bloks, reset_db
from anyblok import Declarations
from anyblok_furetui import exposed_method
from anyblok.column import (
Boolean, Json, String, BigInteger, Text, Selection,
Date, DateTime, Time, Interval, Decimal, ... |
from unittest import TestCase
from unittest.mock import patch
from nose.tools import eq_, ok_
from recommendation.tests.memcached import mock_memcached
from recommendation.tasks.task_recommend import make_key
KEY = 'query_key'
QUERY = 'frend'
RESULTS = {
'hello': 'frend'
}
@patch('recommendation.tasks.task_recommen... |
{
'repo_type' : 'git',
'url' : 'https://bitbucket.org/multicoreware/x265_git',
'folder_name': 'x265_git',
'depth_git': 0,
'source_subfolder' : '_build',
'configure_options' :
'../source {cmake_prefix_options} '
'-DCMAKE_AR={cross_prefix_full}ar '
'-DENABLE_SHARED=OFF '
'-DENABLE_ASSEMBLY=ON '
'-DEXTRA_L... |
import json
import logging
from copy import deepcopy
from datetime import datetime, timedelta
from email.utils import formatdate
from functools import wraps
from hashlib import sha256
from time import mktime, time
from urllib.parse import urlencode
from django.conf import settings
from django.core.cache import cache, c... |
from mozsvc.middlewares import _resolve_name
class ResolveException(Exception):
pass
def _get_group(group_name, dictionary):
"""
Get a sub-group from a configuration dictionary
@param group_name sub-group name to get
@param dictionary configuration dictionary
"""
if group_name is None:
... |
import re
import codecs
import os
try:
import multiprocessing
except ImportError:
pass
from setuptools import setup
def read(*parts):
return codecs.open(os.path.join(os.path.dirname(__file__), *parts)).read()
def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r... |
import structlog
from flask import current_app
from relengapi.blueprints.tokenauth import tables
from relengapi.lib import badpenny
logger = structlog.get_logger()
@badpenny.periodic_task(3600)
def monitor_users(job_status):
# for every user token, examine the token's permission map and the user's
# permissions... |
"""
Convert numbers from base 10 integers to base X strings and back again.
Sample usage:
>>> base20 = BaseConverter('0123456789abcdefghij')
>>> base20.from_decimal(1234)
'31e'
>>> base20.to_decimal('31e')
1234
"""
class BaseConverter(object):
decimal_digits = "0123456789"
def __init__(self, digits):
se... |
""" Updates the database """
import pymongo
from frontend.base import get_database
from frontend.custom.courses import FrontendCourse
def update_database():
db_version = get_database().db_version.find_one({})
if db_version is None:
db_version = 0
else:
db_version = db_version['db_version']
... |
"""djangoapp URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-ba... |
from abc import ABCMeta, abstractmethod
class OpenRosaFormListInterface(metaclass=ABCMeta):
"""
This interface defines required properties and methods of objects expected
by `kpi.serializers.v2.open_rosa.FormListSerializer`
"""
@property
@abstractmethod
def description(self):
pass
... |
from django.db import IntegrityError
from django.db.models import Exists, OuterRef
from django.utils.functional import cached_property
from glom import glom, T, Coalesce
from agir.authentication.models import Role
from agir.notifications.models import Announcement, Notification
def add_announcements(person):
announ... |
def eatEggs(eggnum):
print(str(eggnum)+' eggs') |
from shinken.webui.bottle import redirect
app = None
def get_page():
# First we look for the user sid
# so we bail out if it's a false one
user = app.get_user_auth()
if not user:
redirect("/user/login")
return
# we return values for the template (view). But beware, theses values are ... |
"""
Unit tests for getting the list of courses and the course outline.
"""
import datetime
import json
import ddt
import lxml
import mock
import pytz
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.test.utils import override_settings
from django.utils.translation import ... |
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from easy_thumbnails.fields import ThumbnailerImageField
from django_rea.valueaccounting.models import *
MEMBERSHIP_TYPE_CHOICES = (
#('participant', _('project participant (no membership... |
from Queue import Queue
import threading
import md5
import string
import os
import Cheetah.Template
import smtplib
import cherrypy
from evecentral import display
from evecentral import evec_func
from evecentral.userlib import User
from evecentral import cache
from evecentral import stats
class BackgroundStatThread(thre... |
from __future__ import absolute_import
from django.core.mail import mail_admins
from celery import shared_task
from publish.models import EmailSubscriber
from comics.models import Comic, Blog
@shared_task
def tidy_subscribers():
deleted_subscribers = []
for subscriber in EmailSubscriber.tidy():
deleted_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.