code stringlengths 1 199k |
|---|
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
l=len(height)
maxheight=[0 for i in range(l)]
leftmax=0
rightmax=0
res=0
for i in range(l):
if height[i]>leftmax:
le... |
import unittest
"""826. Most Profit Assigning Work
https://leetcode.com/problems/most-profit-assigning-work/description/
We have jobs: `difficulty[i]` is the difficulty of the `i`th job, and
`profit[i]` is the profit of the `i`th job.
Now we have some workers. `worker[i]` is the ability of the `i`th worker,
which means... |
from homevent.reactor import ShutdownHandler
from homevent.module import load_module
from homevent.statement import main_words
from test import run
input = """\
block:
if exists path "..":
log DEBUG Yes
else:
log DEBUG No1
if exists path "...":
log DEBUG No2
else:
log DEBUG Yes
if exists directory "..":
... |
from __future__ import unicode_literals
from django.db import models, migrations
def fix_notes_field (apps, schema_editor):
Question = apps.get_model("checklist", "Question")
for question in Question.objects.all():
question.notes = ""
question.save()
class Migration(migrations.Migration):
de... |
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_setup(object):
def setupUi(self, setup):
setup.setObjectName("setup")
setup.resize(510, 607)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('event', '0015_auto_20170408_1815'),
]
operations = [
migrations.AddField(
model_name='subscription',
name='team',
fie... |
SCRIPT_NAME = "confversion"
SCRIPT_AUTHOR = "drubin <drubin at smartcube.co.za>"
SCRIPT_VERSION = "0.2"
SCRIPT_LICENSE = "GPL3"
SCRIPT_DESC = "Stores version controlled history of your configuration files"
import_ok = True
import subprocess
try:
import weechat
except ImportError:
print "This script must ... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_HTTPError
from ..utils import (
float_or_none,
parse_iso8601,
str_or_none,
try_get,
unescapeHTML,
url_or_none,
ExtractorError,
)
class RteBaseIE(InfoExtractor):
def _real_extract(self, url):
item_id... |
"""Simulation launch services.
Simulation launch services provide the following functionality:
- generating simulation id based on local date and time;
- generating simulation directory name;
- loading names of simulation directories from a text file;
- creating directory structure for simulation;
- normalizing the for... |
from io import StringIO
import re
import httpretty
from django.core.management import call_command
from oppia.test import OppiaTestCase
from settings import constants
from settings.models import SettingProperties
from tests.utils import get_file_contents
class CartoDBUpdateTest(OppiaTestCase):
fixtures = ['tests/te... |
import sqlite3
from sys import version_info
if version_info >= (3, 0, 0):
def listkey(dicts):
return list(dicts.keys())[0]
else:
def listkey(dicts):
return dicts.keys()[0]
class sqlitei:
'''Encapsulation sql.'''
def __init__(self, path):
self.db = sqlite3.connect(path)
se... |
import re
test = '用户输入的字符串'
if re.match(r'用户', test):
print('ok')
else:
print('failed')
print('a b c'.split(' '))
print(re.split(r'\s*', 'a b c'))
print(re.split(r'[\s\,\;]+', 'a,b;; c d'))
m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345')
print(m.group(1))
m = re.match(r'^(\S+)@(\S+.com)$', 'cysuncn@126.c... |
def __load():
import imp, os, sys
ext = 'pygame/display.so'
for path in sys.path:
if not path.endswith('lib-dynload'):
continue
ext_path = os.path.join(path, ext)
if os.path.exists(ext_path):
mod = imp.load_dynamic(__name__, ext_path)
break
els... |
gplheader = """Harmon Instruments CORDIC generator
Copyright (C) 2014 Harmon Instruments, LLC
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any l... |
import os
import sys
import numpy as np
import math
def findBinIndexFor(aFloatValue, binsList):
#print "findBinIndexFor: %s" % aFloatValue
returnIndex = -1
for i in range(len(binsList)):
thisBin = binsList[i]
if (aFloatValue >= thisBin[0]) and (aFloatValue < thisBin[1]):
returnIndex = i
break
return retur... |
import Amarok
from Amarok import Commands
from Core.MyObjects import *
import Taggers
import FileUtils as fu
from Core import Universals as uni
from Core import Dialogs
from Core import Records
from Core import ReportBug
def getDirectoriesAndValues(_filter=""):
db = Amarok.checkAndGetDB()
if db is not None:
... |
"""
Example usage:
python3 testf0seqnrcalculation.py 548659 \
../testdata/sample_data_548659/L548659.parset \
../testdata/sample_data_548659/file-sizes.txt \
../testdata/sample_data_548659/f0seqnr-sizes.txt
"""
import os
import sys
sys.path.append("../scripts")
import create_html
def test_main(i... |
import aiohttp
import discord
import random
from config import GoogleAPIKey
from config import GoogleCSECX
async def google(cmd, message, args):
if not args:
await message.channel.send(cmd.help())
return
else:
search = ' '.join(args)
url = 'https://www.googleapis.com/customsearc... |
from setuptools import setup, find_packages
setup(
name='plumber',
version='0.0.1-alpha',
description='simple, mundane script to build and publish containers to marathon/mesos',
author='Giuseppe Lavagetto',
author_email='glavagetto@wikimedia.org',
url='https://github.com/lavagetto/plumber',
... |
from .hether import hether
__all__ = ["hether"] |
import numpy;
fibonaccirecursion = lambda n: 1 if n <=2 else fibonaccirecursion(n-2) + fibonaccirecursion(n-1);
def fibonaccidualrecursion(n):
if n >= 3:
a, b = fibonaccidualrecursion(n-1);
# F(n-2) = a, F(n-1) = b, F(n) = a+b.
return b, a+b;
elif n == 2:
return 1, 1;
elif n == 1:
# F(0) = 0.
... |
"""Routines for bubble format validation"""
import os
import itertools as it
from collections import Counter
from bubbletools.bbltree import BubbleTree
from bubbletools import utils
def validate(bbllines:iter, *, profiling=False):
"""Yield lines of warnings and errors about input bbl lines.
profiling -- yield a... |
"""
import time
import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
RST = None
DC = 23
SPI_PORT = 0
SPI_DEVICE = 0
disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST, i2c_bus=2)
disp.begin()
disp.clear()
disp.display()
width = disp.width
height =... |
import sys
import random
from linked_list_prototype import ListNode
from reverse_linked_list_iterative import reverse_linked_list
def zipping_linked_list(L):
if not L or not L.next:
return L
# Finds the second half of L.
slow = fast = L
while fast and fast.next:
slow, fast = slow.next, f... |
"""
Module implementing a dialog to enter the connection parameters.
"""
from __future__ import unicode_literals
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QDialog, QDialogButtonBox
from PyQt5.QtSql import QSqlDatabase
from E5Gui.E5Completers import E5FileCompleter
from E5Gui import E5FileDialog
from... |
from __future__ import division
import logging
from collections import namedtuple, defaultdict
from functools import partial
from itertools import chain
from operator import attrgetter
import pygame
from core import tools, state
from core.components.locale import translator
from core.components.pyganim import PygAnimat... |
from jroc.tasks.tokenizers.TokenizerTask import SentenceTokenizerTask, WordTokenizerTask |
from django.forms import *
from django.forms.formsets import BaseFormSet
from django.utils.translation import ugettext_lazy as _
from django.contrib.sites.models import Site
from tradeschool.models import *
class DefaultBranchForm(Form):
def __init__(self, user, redirect_to, *args, **kwargs):
super(DefaultB... |
from BaseCreation import BaseCreation
from MLC.db.mlc_repository import MLCRepository
class IndividualSelection(BaseCreation):
"""
Fill a Population with fixed Individuals.
selected_individuals: dictionary containing {Individual: positions inside
the first population}
fill_creator: creator used to f... |
"""
WSGI config for school_registry 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.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SE... |
import card
from card import Card
from player import Player
from hand import Hand
from prompt import Prompt, IntegerPrompt, SetPrompt
import pprint
class Setup:
def run(self, game):
self.game = game
self.cards_accounted_for = 0
self.setup_conviction()
self.initialize_cards()
... |
"""
Utility Serializers
"""
from rest_framework.serializers import HyperlinkedModelSerializer
class HybridModelSerializer(HyperlinkedModelSerializer):
"""
ModelSerializer which provides both a `url` and `id` field
"""
def get_pk_field(self, model_field):
return self.get_field(model_field) |
"""Request handler for authentication."""
from __future__ import unicode_literals
import logging
import random
import string
import time
from builtins import range
import jwt
from medusa import app, helpers, notifiers
from medusa.logger.adapters.style import BraceAdapter
from medusa.server.api.v2.base import BaseReques... |
from collections import OrderedDict
from django import forms
from django.conf import settings
from django.db import transaction
from django.utils.translation import ugettext_lazy as _
from oioioi.base.utils.input_with_generate import TextInputWithGenerate
from oioioi.base.utils.inputs import narrow_input_field
from oio... |
import __main__
import glob
import os
import re
import shutil
import sys
import optparse
import time
localedir = '@localedir@'
try:
import gettext
t = gettext.translation ('lilypond', localedir)
_ = t.ugettext
except:
def _ (s):
return s
underscore = _
reload (sys)
sys.setdefaultencoding ('utf-8... |
from __future__ import division
import socket, MySQLdb
from PIL import Image
from random import randint, randrange
from ConfigParser import SafeConfigParser
parser = SafeConfigParser()
parser.read('../analogy_config.ini')
db = MySQLdb.connect(
host = parser.get('database','host'),
user = parser.get('database','... |
from hyperiontests import hyperion
from hyperiontests import settings
class TestGrafana(hyperion.HyperionTestCase):
def setUp(self):
super(TestGrafana, self).setUp()
self._host = "http://%s:%s" % (settings.HYPERION_HOST,
settings.HYPERION_WEB)
def test_can_... |
'''Java bytecode implementation'''
import logging
from pyjvm.bytecode import bytecode
from pyjvm.frame import Frame
from pyjvm.jassert import jassert_ref
from pyjvm.natives import exec_native
from pyjvm.thread import SkipThreadCycle
from pyjvm.utils import args_count
from pyjvm.vmo import vm_obj_call
logger = logging.g... |
"""
Bootstrapping script that create a basic Pimlico setup, either for an existing config file, or for a new project.
Distribute this with your Pimlico project code. You don't need to distribute Pimlico itself
with your project, since it can be downloaded later. Just distribute a directory tree containing your config f... |
import numpy as np
import sys
try:
t1 = int(sys.argv[1])
except:
print "usage:", sys.argv[0], "n (number of years)"
sys.exit(1)
t0 = 1750
u0 = 2
t = np.linspace(t0, t0 + t1 + .5, t1)
u = np.zeros(t1 + 1)
a = 0.0218
u[0] = u0
for i in range(len(u) - 1):
u[i+1] = (1 + a)*u[i]
print "Expected population in... |
"""
script to build the latest binaries for each vehicle type, ready to upload
Peter Barker, August 2017
based on build_binaries.sh by Andrew Tridgell, March 2013
"""
from __future__ import print_function
import datetime
import optparse
import os
import re
import shutil
import time
import subprocess
import sys
import z... |
import config_speller_8
import config_robot_8
class Config(object):
def __init__(self):
self.number_of_decisions = 8
speller = config_speller_8.Config()
robot = config_robot_8.Config()
self.state = []
self.actions = []
self.letters = []
#MENU
menu_stat... |
import numpy as np
import time
import matplotlib.pyplot as plt
from AndorSpectrometer import Spectrometer
spec = Spectrometer(start_cooler=False,init_shutter=True)
spec.SetCentreWavelength(650)
spec.SetSlitWidth(100)
spec.SetSingleTrack()
spec.SetExposureTime(5.0)
d = spec.TakeSingleTrack()
spec.SetExposureTime(1)
d2 =... |
from __future__ import unicode_literals
import os
import unittest
import doctest
from lxml import etree
from lxml import doctestcompare
from corpustools import analyser
from corpustools import parallelize
from corpustools import util
here = os.path.dirname(__file__)
class TestAnalyser(unittest.TestCase):
def setUp(... |
from pyglet.window.key import user_key
from pyglet.window.mouse import LEFT as MOUSE_LEFT, RIGHT as MOUSE_RIGHT
from mmfparser.player.common import PlayerChild
from mmfparser.player.eventdispatcher import EventDispatcher
DIRECTIONAL_CONTROLS = ('Up', 'Down', 'Left', 'Right')
KEY_LIST = ('Up', 'Down', 'Left', 'Right', '... |
import os
import logging.config
class MyLogger(object):
# set logging to both file and screen
def __init__(self):
logging.config.fileConfig('../config/logging.conf')
self.logger = logging.getLogger('scrapeforum')
self.logger.addHandler(logging.StreamHandler())
self.errorIndicated... |
"""
:copyright: Copyright 2013-2014 by Łukasz Mierzwa
:contact: l.mierzwa@gmail.com
"""
from __future__ import unicode_literals
from setuptools import setup, find_packages
try:
from pip.req import parse_requirements
from pip.download import PipSession
required = {'install_requires': [str(r.req) for ... |
from .. import NogginConstants
from . import PBConstants
from . import Formations
def sReady(team, workingPlay):
workingPlay.setStrategy(PBConstants.S_READY)
Formations.fReady(team, workingPlay)
def sNoFieldPlayers(team, workingPlay):
workingPlay.setStrategy(PBConstants.S_NO_FIELD_PLAYERS)
Formations.fN... |
"""
Helcio Macedo
Checksum Verifier v1.0
https://github.com/neomacedo/ScriptsUteis
-----------------------------------------------------------
Script used to compare if local file its the same as remote.
"""
import hashlib
import urllib2
import optparse
remote_url = 'https://raw.githubusercontent.com/neomacedo/Area51/m... |
import logging
import logging.handlers
import os
import shutil
import signal
import sys
import traceback
from typing import Callable, Optional
from PyQt5.QtCore import (pyqtSlot, QCommandLineOption, QCommandLineParser, QDir, QFileInfo, QProcess,
QProcessEnvironment, QSettings, QSize, QStandard... |
from __future__ import division
def f():
a = noise(3)
b = 8 + noise(2)
return a, b, a + b, a /b, a*a, a*b, b*b
def go():
for x in v: print x
for x in v: print E(x)
print
for i in xrange(len(r)):
for j in xrange(len(r)):
print "%6.01f" % cov(r[i], r[j]),
print
from... |
from django.conf import settings
from django.contrib.auth import authenticate
from django.http import HttpResponseRedirect, Http404, HttpResponse, JsonResponse
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.csrf import csrf_exempt
from django.contrib import messages
from oppia.api.... |
import urlparse,urllib2,urllib,re
import os, sys
from core import logger
from core import config
from core import scrapertools
from core.item import Item
from core import servertools
from core import httptools
host='http://www.seodiv.com'
def mainlist(item):
logger.info()
itemlist = []
itemlist.append( Item... |
import numpy as np
class BaseFeature():
def __init__(self, text, textName="", args=[], debug=True):
self.text = text.lower()
self.args = args
self.debug = debug
self.textName = textName
#Features, not yet calculated
self.f = np.array([])
def debugStart(self):
... |
"""
A JSON-based API.
Most rules would look like::
@jsonify.when("isinstance(obj, YourClass)")
def jsonify_yourclass(obj):
return [obj.val1, obj.val2]
@jsonify can convert your objects to following types: lists, dicts, numbers and
strings.
"""
__author__ = 'Ross Light'
__date__ = 'March 30, 2008'
__docf... |
import mt, os, mimetypes
from time import strftime
class HTTPOut():
class mtEntry():
def __init__(self):
self.html = False
self.css = False
self.js = False
self.data = ""
self.target = ""
def __init__(self, session = None):
self.session... |
import math
import matplotlib.pyplot as plt
from matplotlib.dates import MONDAY
from matplotlib.dates import MonthLocator, WeekdayLocator, DateFormatter
from TimeSheetAnalyser.utils.misc import time_to_float_time, normalise_number,\
average_sequence
def daily_attendance_plot_pres... |
from __future__ import absolute_import
import six.moves.SimpleHTTPServer
from six.moves.BaseHTTPServer import HTTPServer
from six.moves.socketserver import ForkingMixIn
import six.moves.urllib.request, six.moves.urllib.parse, six.moves.urllib.error
import six.moves.urllib.parse
import sys
import os
import os.path
impor... |
from sqlalchemy.schema import CreateTable
from community_share import store, config, setup
from community_share.models.user import UserReview
config.load_from_environment()
table_sql = CreateTable(UserReview.__table__).compile(store.engine)
print(table_sql) |
"""
Tests for the submit_group.py script.
"""
import random
import sys
from crc_nd.utils.test_io import WritesOutputFiles
from django.test import LiveServerTestCase
from mock import patch
from path import path
from vecnet.simulation import ExecutionRequest, sim_model, Simulation, SimulationGroup as SimGroup, submission... |
"""HTML Processors."""
from .processor import Processor
from .text import TextProcessor
import logging
import os
import xmltodict
import json
from xml.parsers.expat import ExpatError
from .html import HTMLProcessor
class XmlProcessor(HTMLProcessor):
"""Processor for XMLdocuments.
When processing, converts docum... |
"""
Usage:
import_localities < Localities.csv
"""
from django.contrib.gis.geos import GEOSGeometry
from django.utils.text import slugify
from ..import_from_csv import ImportFromCSVCommand
from ...utils import parse_nptg_datetime
from ...models import Locality
class Command(ImportFromCSVCommand):
"""
Imports... |
import sqlalchemy as sa
from relengapi.blueprints.tokenauth import types
from relengapi.lib import db
from relengapi.lib.permissions import p
class Token(db.declarative_base('relengapi')):
__tablename__ = 'auth_tokens'
def __init__(self, permissions=None, **kwargs):
if permissions is not None:
... |
"""
Django settings for cadasta project.
Generated by 'django-admin startproject' using Django 1.8.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
import os
from d... |
def main():
PEOPLE = insert_people()
sum_salary_all(PEOPLE)
list_people_by_city(PEOPLE)
def insert_people():
PEOPLE = []
while True:
NAMES = {}
NAMES["name"] = name = raw_input("Inserisci nome ")
NAMES["city"] = city = raw_input("Inseriscci citta ")
NAMES["salary"] = ... |
class Breadcrumb:
def __init__(self, text, url):
self.text = text
self.url = url |
from locust import HttpLocust, TaskSet, task
class UserBehavior(TaskSet):
def on_start(self):
""" on_start is called when a Locust start before any task is scheduled """
self.login()
def login(self):
# do a login here
# self.client.post("/login", {"username":"ellen_key", "passwor... |
import nose
import ckanext.dcatapit.harvesters.utils as utils
eq_ = nose.tools.eq_
ok_ = nose.tools.ok_
csw_harvester_config = {
'dataset_themes': 'OP_DATPRO',
'dataset_places': 'ITA_BZO',
'dataset_languages': '{ITA,DEU}',
'frequency': 'UNKNOWN',
'agents': {
'publisher': {
'code'... |
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import (login as _login, logout as _logout,
authenticate)
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
from django.db import IntegrityError
from django.fo... |
from __future__ import absolute_import, print_function, division
import os
import math
import string
import collections
import codecs
import json
import gzip
import cPickle as pickle
import itertools
from operator import itemgetter
from redis import Redis
Redis = Redis()
from flask import Flask, g
import reaper
from ba... |
from openerp import models, fields, api
class Category(models.Model):
_name = 'cl_todo.task.category'
name = fields.Char('Category', required=True, size=128, translate=True)
parent_id = fields.Many2one('cl_todo.task.category', 'Parent Category', select=True, ondelete='restrict')
code = fields.Char('Code... |
__author__ = "John Doe <johndoe@mailcatch.com>"
__version__ = "1.0"
import argparse
import json
import re
import sys
import urllib2
import osrframework.utils.browser as browser
from osrframework.utils.platforms import Platform
class Bebee(Platform):
"""
A <Platform> object for Bebee.
"""
def __init_... |
from datetime import datetime, timedelta
from odoo.exceptions import AccessError, ValidationError
from odoo.tests import common
class TestStockCycleCount(common.TransactionCase):
def setUp(self):
super(TestStockCycleCount, self).setUp()
self.res_users_model = self.env["res.users"]
self.cycle... |
import logging
from datetime import datetime
from datetime import timedelta
from openerp import http
from openerp.http import request
from openerp.addons.connector.queue.job import job
from openerp.addons.connector.session import ConnectorSession
from werkzeug.wrappers import Response
from werkzeug.datastructures impor... |
from odoo import api, fields, models
from odoo.osv import expression
class ResCountryZone(models.Model):
_name = "res.country.zone"
_description = "Country Zones"
@api.model
def _name_search(
self, name, args=None, operator="ilike", limit=100, name_get_uid=None
):
args = args or []
... |
from django.core.management.base import BaseCommand
from lachambre.utils import dump_db
class Command(BaseCommand):
def handle(self, *args, **options):
dump_db() |
import sys
import re
import types
import random
import lxml
from lxml import etree
from copy import deepcopy
def usage():
print "Usage: %s countryfile regionname valuefile clubfile1 [clubfile2...]" % sys.argv[0]
print " countryfile: XML file of the country"
print " regionname: stadium... |
from datetime import date
from akvo.rsr.tests.base import BaseTestCase
from akvo.rsr.tests.utils import ProjectFixtureBuilder
from akvo.rsr.usecases import change_project_parent as command
class ChangeProjectParentTestCase(BaseTestCase):
def test_change_parent_to_sibling(self):
# Given
root = Projec... |
from __future__ import unicode_literals
import pytest
from tests.factories import UniprotFactory
@pytest.fixture
def uniprot_egfr_human():
return UniprotFactory(
uniprot_acc='P00533',
uniprot_id='EGFR_HUMAN',
description='Epidermal growth factor receptor EC=2.7.10.1'
) |
{
'name': 'Membership Management - POS Membership',
'version': '8.0.1.0.2',
'category': 'Generic Modules',
'depends': [
'account_membership_balance',
'point_of_sale',
'account_accountant',
'account_voucher',
],
'author': 'Elico Corp',
'license': 'AGPL-3',
... |
"""
Unit tests for the Mixed Modulestore, with DDT for the various stores (Split, Draft, XML)
"""
import datetime
import itertools
import logging
import mimetypes
from collections import namedtuple
from contextlib import contextmanager
from shutil import rmtree
from tempfile import mkdtemp
from uuid import uuid4
import... |
from openerp import fields, models
class ProductTemplate(models.Model):
_inherit = "product.template"
default_code = fields.Char(related='product_variant_ids.default_code', string='Internal Reference', store=True) |
extensions = ['sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.imgmath',
'sphinx.ext.ifconfig',
'sphinx.ext.githubpages']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = 'AppTalk'
copyright = '2017, Thomas Lee'
author = 'Thomas Lee... |
import os
import pytest
from skylines.lib import files
from skylines.lib.types import is_unicode
from skylines.model import User, IGCFile
from tests.data import users, igcs
def test_user_delete_deletes_user(db_session):
john = users.john()
db_session.add(john)
db_session.commit()
john_id = john.id
a... |
from __future__ import absolute_import, unicode_literals
import time
from datetime import timedelta
from djcelery_transactions import task
from django.utils import timezone
from redis_cache import get_redis_connection
from .models import CreditAlert, Invitation, Org, TopUpCredits
@task(track_started=True, name='send_in... |
from . import test_remote_printer
from . import test_printer |
{
'name': 'Frontend Shop',
'version': 'beta',
'author': 'cgstudiomap',
'maintainer': 'cgstudiomap',
'license': 'AGPL-3',
'category': 'Web',
'summary': 'Shop Modules',
'depends': [
'website',
'website_menu_by_user_status',
],
'data': [
'templates/template_s... |
from flask_wtf import FlaskForm
from saylua.utils.form import sl_validators
from saylua.utils.form.fields import SlField, SlTextAreaField
class ForumThreadForm(FlaskForm):
title = SlField('Thread Title', [
sl_validators.Required(),
sl_validators.NotBlank(),
sl_validators.Min(3)])
body = ... |
from django import template
register = template.Library()
@register.filter
def username(user):
return ("%s %s" % (user.first_name, user.last_name)).lstrip() or user.username |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('members', '0005_trainingrecordtype'),
]
operations = [
migrations.AlterField(
model_name='volunteer',
name='portrait',
... |
import os
import shutil
from hashlib import md5
from io import StringIO
from PIL import Image
from photonix.photos.models import LibraryPath
from photonix.photos.utils.db import record_photo
from photonix.photos.utils.fs import (determine_destination,
find_new_file_name, mkdir_p)
f... |
from django.apps import apps
from django.dispatch import receiver
from django.db.models.signals import post_migrate
@receiver(post_migrate, sender=apps.get_app_config('autodidact'))
def create_homepage(sender, **kwargs):
'''Receiver function that populates the database with a homepage in case it doesn't exist'''
... |
import requests
from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
@csrf_exempt
@require_http_methods(["POST"])
def post_service_request(request):
payload = r... |
"""
Module exports :class:`ESHM20Craton`
"""
import numpy as np
from openquake.hazardlib.gsim.base import GMPE, CoeffsTable
from openquake.hazardlib.imt import PGA, SA
from openquake.hazardlib import const
from openquake.hazardlib.gsim.nga_east import (
get_tau_at_quantile, get_phi_ss_at_quantile, TAU_EXECUTION, TA... |
import datetime
import re
import urllib
from lxml import builder
from lxml import etree
from lxml.html import builder as E
from lxml.html import tostring
import oauth2
import simplejson
from vidscraper.decorators import provide_shortmem, parse_url, returns_unicode
from vidscraper import util
from vidscraper.errors impo... |
import openerp.addons.website.tests.test_ui as test_ui
def load_tests(loader, base, _):
base.addTest(test_ui.WebsiteUiSuite(test_ui.full_path(__file__,'website_sale-add_product-test.js'),
{'redirect': '/page/website.homepage'}))
base.addTest(test_ui.WebsiteUiSuite(test_ui.full_path(__file__,'website_sal... |
from __future__ import print_function
from __future__ import unicode_literals
from django.contrib import admin
from .models import Conference
from .models import Paper
from .models import Author
from .models import Attachment
from .actions import paper_actions
class AttachInline(admin.TabularInline):
model = Attach... |
import anki.lang
import aqt
from aqt import AnkiQt
from aqt.profiles import RecordingDriver, VideoDriver
from aqt.qt import *
from aqt.utils import (
TR,
HelpPage,
disable_help_button,
openHelp,
showInfo,
showWarning,
tr,
)
def video_driver_name_for_platform(driver: VideoDriver) -> str:
... |
from odoo import api, models
class AccountPaymentOrder(models.Model):
_inherit = 'account.payment.order'
@api.multi
def open2generated(self):
"""
Replace action to propose upload SEPA file to FDS.
:return: window action
"""
action = super(AccountPaymentOrder, self).op... |
""" Encode any known changes to the database here
to help the matching process
"""
renamed_modules = {
'base_calendar': 'calendar',
'mrp_jit': 'procurement_jit',
'project_mrp': 'sale_service',
# OCA/account-invoicing
'invoice_validation_wkfl': 'account_invoice_validation_workflow',
'account_invo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.