code stringlengths 1 199k |
|---|
from openerp import models, fields, api
class SaleOrder(models.Model):
_inherit = "sale.order"
period_ack = fields.Char(string='ACK Period', size=6, required=True)
#@api.one
def action_button_confirm(self, cr, uid, ids, context=None):
return super(SaleOrder, self).action_button_confirm(cr, uid, ... |
import unicodedata
import re
class PathExtension:
"""
Enables readable url path names instead of ids for object traversal.
Names are stored as meta.pool_filename and generated from
title by default. Automatic generation can be disabled by setting
*meta.customfilename* to False for each object.
E... |
import sys
import os
import mock
MOCK_MODULES = ['numpy','six','six.moves','matplotlib','_csphi']
for mod in MOCK_MODULES:
sys.modules[mod] = mock.Mock()
import sphinx_bootstrap_theme
sys.path.insert(0, os.path.abspath('../../'))
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext... |
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.utils.translation import ugettext
from django.contrib.auth.decorators import login_required
from django.contrib.admin.views.dec... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('carts', '0007_auto_20161221_1337'),
]
operations = [
migrations.AddField(
model_name='cart',
name='tax_percentage',
f... |
from transH import TransH
import pickle
import numpy as np
import sys
def main():
if len(sys.argv) != 3:
print '[Usage] python train.py train_data validation_data'
exit(0)
train_data, valid_data = sys.argv[1:]
X, E, R = loadData(train_data)
V = loadData(valid_data, E=E, R=R, mode='valid')
# parameters
gamma =... |
"""
Tools to put to good use INE data
""" |
from pylab import *
dt = 0.001
t = arange(0.0, 10.0, dt)
r = exp(-t[:1000]/0.05) # impulse response
x = randn(len(t))
s = convolve(x,r)[:len(x)]*dt # colored noise
plot(t, s)
plt.xticks( range(5), ('', '', '', '','', '', '', '','2', '', '', '','3', '', '', '','4', '', '', '',) )
plt.yticks( range(1), (''... |
import glob
import sys
import serial
def serial_ports():
""" Lists serial port names
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list of the serial ports available on the system
"""
if sys.platform.startswith('win'):
ports = ['COM... |
"""
Methods to calculate ECP values (Endogenous Competition Potential)
"""
from cellery import exceptions
from itertools import product
from multiprocessing import Queue,Process
from numpy import array,empty,float32,float64,nan,zeros
from clcECP import rtrnECP,rtrnECPMskd,rtrnECPDnsty,rtrnECPDnstyMskd
import os
import ... |
import logging
import pandas as pd
from catalog.core.search_indexes import PublicationDocSearch
from ..data_access import data_cache, IncludedStatistics
from query import Query
logger = logging.getLogger(__name__)
def _create_count_dataframe(df):
return df.groupby(['year_published']) \
.agg(dict(title='coun... |
import numpy as np
import astropy.io.fits as fits
__all__ = ["RMF", "ARF"]
class RMF(object):
def __init__(self, filename):
self._load_rmf(filename)
pass
def _load_rmf(self, filename):
"""
Load an RMF from a FITS file.
Parameters
----------
filename : str
... |
import numpy as np
import unittest
import logging
class _BaseTest(unittest.TestCase):
def grad_t(self, x):
log= logging.getLogger( "BaseTest.grad_t" )
e, g = self.pot.getEnergyGradient(x)
e1 = self.pot.getEnergy(x)
numerical_g = self.pot.NumericalDerivative(x)
log.debug( "g= ... |
__author__ = "Wren J. R. (uberfastman)"
__email__ = "wrenjr@yahoo.com"
import datetime
import logging
from pathlib import Path
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from report.logger import get_logger
from utils.app_config_parser import AppConfigParser
logger = get_logger(__name__, ... |
"""rds-create-cpu-alarms
Script used to create CPUUtilization alarms in AWS CloudWatch
for all RDS instances.
A upper-limit threshold needs to be defined.
Usage:
rds-create-cpu-alarms [options] <threshold> <sns_topic_arn> <region>
rds-create-cpu-alarms -h | --help
Options:
-h --help Show this screen.
... |
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_ChooseFormatDeviceDialog(object):
def setupUi(self, ChooseFormatDeviceDialog):
ChooseFormatDeviceDialog.setObjectName(_fromUtf8("ChooseFormatDeviceDialog"))
Choose... |
"""
PHCpy --- a package for Polynomial Homotopy Continuation
========================================================
PHCpy is a collection of Python modules to compute solutions
of polynomial systems using PHCpack.
A homotopy defines the deformation of a start system
(system with known solutions) into the target syste... |
import time
import RPi.GPIO as GPIO
from flask import Flask, render_template
class WaterLevelSensor:
# how high the sensor is above the top of the fish tank
offset = 0
def __init__(self, echo, trig):
self.echo_pin = echo
self.trig_pin = trig
GPIO.setup(self.trig_pin, GPIO.OUT, initia... |
import random
import Globals
def updateAlphas(newAlphas, oldTargetList):
for i in range(0, len(newAlphas)):
found = False
for j in range(0, len(Globals.ALPHAS)):
if newAlphas[i]['replica'] == Globals.ALPHAS[j]['replica']:
Globals.ALPHAS[j]['alphaTarget'] = newAlphas[i]['alphaTarget']
... |
import numpy as np
import matplotlib.pyplot as plt
plt.style.use("seaborn-colorblind")
import galore
import galore.plot
vasprun = './test/MgO/vasprun.xml.gz'
xmin, xmax = (-10, 2)
fig = plt.figure()
for i, l in enumerate(np.arange(0.05, 0.50, 0.05)):
ax = fig.add_subplot(3, 3, i + 1)
ax.set_title("$\gamma = {0:... |
import os
import re
from contextlib import contextmanager
from unittest import mock
from celery import task
from pyvirtualdisplay import Display
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.firefox.webdriver import WebDrive... |
from lokp.models import DBSession
from lokp.protocols.activity_protocol import ActivityProtocol
from lokp.review.review import BaseReview
class ActivityReview(BaseReview):
def __init__(self, request):
super(ActivityReview, self).__init__(request)
self.protocol = ActivityProtocol(DBSession) |
import sys
import re
import numpy as np
import matplotlib.pyplot as plt
import argparse
remove_comments = re.compile("(?!\#)", re.VERBOSE)
parser = argparse.ArgumentParser()
parser.add_argument("-f", nargs=1, default=None)
parser.add_argument("files", nargs='*')
args = parser.parse_args()
if len(args.files) < 1:
pa... |
import re
import datetime
import logging
from urlparse import parse_qsl
from mamchecker.model import depth_1st, problemCtxObjs, keysOmit, table_entry, ctxkey
from mamchecker.hlp import datefmt, last
from mamchecker.util import PageBase
from google.appengine.ext import ndb
def prepare(
qs # url query_string (af... |
from wazo_auth.interfaces import (
BaseAuthenticationBackend,
BaseMetadata,
DEFAULT_XIVO_UUID,
)
__all__ = [
'BaseAuthenticationBackend',
'BaseMetadata',
'DEFAULT_XIVO_UUID',
] |
from __future__ import absolute_import, unicode_literals
import logging
from django import forms
from django.contrib import messages
from django.http import Http404
from django.utils.encoding import smart_str
from easy_maps.models import Address
from . import lib
log = logging.getLogger(__name__)
class AddressForm(form... |
"""
Created on Sun Aug 09 13:15:13 2015
@author: Vedran
Fetching a schedule from Google Docs, extracting information, converting to
pdf and sending via e-mail.
Copyright (C) 2015 Vedran Vukovic <wilheru@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General... |
"""
Almost all test cases covers both tag calling and template using.
"""
from __future__ import print_function, unicode_literals
from django.conf import settings as django_settings
from django.contrib.contenttypes.models import ContentType
from django.http import HttpRequest
from django.utils.six import assertCountEqu... |
import sys
import math
import time
import random
from bzrc import BZRC, Command
class dumb_agent(object):
"""Class handles all command and control logic for a teams tanks."""
new_angles = []
running_time = []
shooting_time = 2
ENEMY_TANK_MIN_DISTANCE = 1
ENEMY_TANK_MAX_DISTANCE = 5
OBSTACLE_... |
from ..base import ComponentAPI
class CollectionsJOB(object):
"""Collections of JOB APIS"""
def __init__(self, client):
self.client = client
self.execute_task = ComponentAPI(
client=self.client, method='POST', path='/api/c/compapi/job/execute_task/',
description=u'根据作业模板I... |
from datetime import datetime
from django.contrib.auth.models import User
from django.db import models
from uccaApp.models import Layers, Users, Constants
class Projects(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50)
description = models.CharField(max_length=Co... |
import os
import webapp2
from app import routes
webapp2_config = {'webapp2_extras.sessions':
{'secret_key': 'hfgskahjfgd736987qygukr3279rtigu',
'webapp2_extras.jinja2': {'template_path': os.path.join(os.path.abspath(os.path.dirname(__file__)), 'templates')}}}
application = webapp2.WSGIApplication(debug=True, config... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0004_auto_20161129_0947'),
]
operations = [
migrations.AlterField(
model_name='pokemon',
name='qr_code',
fiel... |
"""
HipparchiaBuilder: compile a database of Greek and Latin texts
Copyright: E Gunderson 2016-21
License: GNU GENERAL PUBLIC LICENSE 3
(see LICENSE in the top level directory of the distribution)
"""
import re
from string import punctuation
try:
from builder.dbinteraction.connection import setconnection
except:
... |
"""Calculate driving times and driving delays for database Erniesoft.
The following type codes are used in the driving times algorithm. The
description of each type code is described in the table below::
typecode | description
----------+---------------------------------------------------
... |
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import numpy as np
import pandas as pd
import xgboost as xgb
import gc
import sklearn
print('Loading data ...')
train = pd.read_csv('data/train_2016.csv')
prop = pd.read_csv('data/properties_2016.csv')
for c, dtyp... |
import re
def get_abstracts(filename):
output = []
abstract_buffer = []
notes_buffer = []
last_abstract_no = 0
last_pmid = 0
last_biviewid = 0
with open(filename, 'rb') as f:
for line in f: # fast forward to abstract 1
m = re.match("Abstract 1 of [1-9][0-9]*", line)
... |
import asterisk.manager
import sys,os,time
import simplejson as json
from stompy.simple import Client
import ConfigParser
from sqlobject import *
from handlers.command_handler_factory import CommandHandlerFactory
from handlers.command_constants import Protocol
import logging
logging.basicConfig(level=logging.INFO,
... |
DOXYFILE_ENCODING = UTF-8
PROJECT_NAME =
PROJECT_NUMBER =
PROJECT_BRIEF =
PROJECT_LOGO =
OUTPUT_DIRECTORY =
CREATE_SUBDIRS = NO
OUTPUT_LANGUAGE = English
BRIEF_MEMBER_DESC = YES
REPEAT_BRIEF = YES
ABBREVIATE_BRIEF =
ALWAYS_DETAILED_SEC ... |
import os
import rospy
import rospkg
from python_qt_binding import QT_BINDING
from rqt_gui_py.plugin import Plugin
from python_qt_binding import loadUi
from python_qt_binding.QtCore import QTimer
try:
from python_qt_binding.QtGui import QWidget
except ImportError:
from python_qt_binding.QtWidgets import QWidget... |
"""Solver object"""
class Solver():
"""Solver object
This object solves sudokus. It can be used with tools to create sudoku
solver application or combined with Runner object to make life easier.
See Runner object in sudoku.runner for more information about it.
"""
def __init__(self, sudoku):
... |
from pexpect import *
import os, sys
import getpass
import time
class ssh_session:
"Session with extra state including the password to be used."
def __init__(self, user, host, password=None, verbose=0):
self.user = user
self.host = host
self.verbose = verbose
self.password = pass... |
from .models import *
from django.db.models import Count, F, Max, Sum
def get_median_points(game_id):
return median_value(Team.objects.filter(play__game__id=game_id) \
.exclude(play__team__points__isnull=True),
'play__team__points')
def get_play_count(game_id):
re... |
import sys
import smtplib
def output((code, msg)):
sys.stdout.write('%s %s\n' % (code, msg))
sys.stdout.flush()
smtp = smtplib.SMTP('localhost', 2500)
output(smtp.ehlo('moon.localdomain'))
print smtp.esmtp_features
output(smtp.mail('Damien Churchill <damoxc@gmail.com>'))
output(smtp.rcpt('Damien Churchill <damo... |
from indico.core.db import DBMgr
from MaKaC import user
from MaKaC.common.indexes import IndexesHolder
"""
Generates a file with all the avatars that are not well indexed by name.
"""
DBMgr.getInstance().startRequest()
error = False
ah = user.AvatarHolder()
ni=IndexesHolder()._getIdx()["name"]
log = file('names_ids.txt... |
import os.path
import sickbeard
from sickbeard import helpers, logger
from sickbeard.metadata.generic import GenericMetadata
from sickrage.helper.encoding import ek
from sickrage.helper.exceptions import ShowDirectoryNotFoundException
from hachoir_parser import createParser
from hachoir_metadata import extractMetadata
... |
#------------------------------------------------------------
import urlparse,urllib2,urllib
import time
import os
import config
import logger
import re
import downloadtools
import socket
logger.info("[scrapertools.py] init")
DEBUG_LEVEL = True
CACHE_ACTIVA = "0" # Automatica
CACHE_SIEMPRE = "1" # Cachear todo
CACHE_... |
from pypwrctrl.pypwrctrl import Plug, PlugDevice, PlugMaster |
import logging
import re
from datetime import datetime
from typing import List, Any, Dict, Union, Pattern
from pastehunter.common import base62_decode, base62_encode
from pastehunter.inputs.base_input import BasePasteSite
logger = logging.getLogger('pastehunter')
class IxDotIoSite(BasePasteSite):
# Yeah, yeah, I kn... |
"""
WSGI config for pyday2016 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.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTING... |
"""
Script: Forest, a simple Python forum script.
Author: Andrew Nelis (andrew.nelis@gmail.com)
OnTheWeb: http://www.triv.org.uk/~nelis/forest
Date: Jun 2010
Version: 1.0.3
A Python CGI script for a basic flat-file based forum.
Getting Started:
* Set up your web server/place forest.py so that it is executed as a CGI sc... |
import numpy as np
class MovieBase():
def read_from_csv(self, file_path):
f = open(file_path, 'r')
self.matrix = np.loadtxt(f, delimiter=',')
self.shape = self.matrix.shape
f.close()
def get_user_unseen_films(self, user_idx):
if user_idx >= self.shape[1]:
rais... |
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_SearchWidget(object):
def setupUi(self, SearchWidget):
SearchWidget.setObjectName("SearchWidget")
SearchWidget.resize(973, 25)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Preferred)
... |
from django.test import TestCase, RequestFactory
from main.models import *
from main.views import *
from bs4 import BeautifulSoup
from .base import *
import datetime
from feedback.models import IndividualFeedback
class StatusCheckTest(TestCase):
"""Testing the decorator test functions"""
def test_user_teacher_t... |
from logging import getLogger
from abstract_step import AbstractStep
import os
logger = getLogger('uap_logger')
class GffreadExtractTranscripts(AbstractStep):
'''
extract transcripts from gtf
http://ccb.jhu.edu/software/stringtie/gff.shtml
write a fasta file with spliced exons for each GFF transcript
... |
import re
import sys
import socket
from src.config import *
class IRC:
def __init__(self, queue):
self.queue = queue
def end_connection(self):
"""Send a goodbye message through irc and close the socket."""
try:
self.send_custom_message('goodbye')
channel = get_cha... |
"""
Utilities for extracting text from generated classes.
"""
def is_string(txt):
if isinstance(txt, str):
return True
try:
if isinstance(txt, str):
return True
except NameError:
pass
return False
def description(obj):
if obj is None:
return None
retur... |
import numpy as np
def analytical_gradients(network, X, Y):
print("Calculating analytical gradients...")
print("Forward pass:", end=" ")
preds = network.predict(X)
print("done! Backward pass:", end=" ")
delta = network.cost.derivative(preds, Y)
network.backpropagate(delta)
print("done!")
... |
import os
from datetime import date
from gi.repository import Gtk, Gdk
class GuiHelper(object):
(DIALOG_TYPE_ERROR,
DIALOG_TYPE_WARNING,
DIALOG_TYPE_INFO) = range(3)
@staticmethod
def enable_item(widget, enable=True):
widget.set_sensitive(enable)
@staticmethod
def calendar_get_date... |
from django.contrib.sitemaps import Sitemap
from .models import BlogEntry
class BlogEntrySitemap(Sitemap):
changefreq = "yearly"
priority = 0.6
protocol = 'https'
def items(self):
return BlogEntry.on_site.filter(is_visible=True)
def lastmod(self, item):
return item.modification |
from test.support import verbose, run_unittest, gc_collect, bigmemtest, _2G, \
cpython_only
import io
import re
from re import Scanner
import sys
import string
import traceback
from weakref import proxy
import unittest
class ReTests(unittest.TestCase):
def test_keep_buffer(self):
# See bug 14212
... |
import sys
from argparse import ArgumentParser
from DatabaseLogin import DatabaseLogin
from GlobalInstaller import GlobalInstaller
from PyQt5 import QtWidgets
from Ui_MainWindow import Ui_MainWindow
from PyQt5 import QtCore, QtGui
import cx_Oracle
import json
import base64
import urllib
from Crypto.Cipher import AES
fr... |
import re
import heapq
from sql import Null
from sql.aggregate import Max
from sql.conditionals import Case
from collections import defaultdict
try:
import simplejson as json
except ImportError:
import json
from ..model import ModelView, ModelSQL, fields, Unique
from ..report import Report
from ..wizard import ... |
"""
Partition Helper Script: MRBPR USER-USER relations
"""
import os
import csv
import random
import argparse
import itertools
from collections import defaultdict
def generate_relation(data_dir, input_filename, output_filename, relation_id, max_members):
""" Generate the weight files """
dict_network_users = de... |
import logging
import warnings
from collections import namedtuple
logger = logging.getLogger(__name__)
Field = namedtuple('Field', ('name', 'type_', 'default', 'desc', 'warn'))
class Config:
"""配置模块
用户可以在 rc 文件中配置各个选项的值
"""
def __init__(self):
object.__setattr__(self, '_fields', {})
def __ge... |
"""
Shannon's entropy equation (latex format):
H=-\sum_{i=1}^{M} P_i\,log_2\,P_i
Entropy is a measure of the uncertainty of a probability distribution (p1, ..... , pM)
https://stepic.org/lesson/Scoring-Motifs-157/step/7?course=Bioinformatics-Algorithms&unit=436
Where, Pi is the fraction of nuleotide bas... |
from __future__ import with_statement
from pynamite import *
from pynamite.actor import TextBox
def scene1():
# define some actors
x = TextBox("Pynamite")
y = TextBox("Rocks!!!")
# tell the first actor to enter
enter(x)
# wait for a keypress to continue
pause()
# fade out one actor while... |
from test_support import *
prove_all(no_fail=True, steps = 400) |
"""
Main controller.
"""
import json
from Server.Importer import ImportFromModule
class ControllerMain(ImportFromModule("Server.ControllerBase", "ControllerBase")):
"""
Main controller.
"""
def ShowPage(self, uriParameters, postedParameters):
"""
Shows the home page.
"""
... |
from platform import system
import os
from os.path import sep, expanduser, join as join_path
from collections import defaultdict
import pygame as pg
import settings
from util import ir, dd, split
class Conf (object):
IDENT = 'wvoas'
USE_SAVEDATA = True
USE_FONTS = False
# save data
SAVE = ('CURRENT_... |
import htmlPy
import socket
import json
import os
sock = socket.socket()
sock.connect(('localhost', 5002))
sock.send(b'')
sock.recv(1024)
sock.recv(1024)
sock.recv(1024)
app = htmlPy.AppGUI(title=u"Python Best Ever", maximized=True)
app.template_path = os.path.abspath("./html")
app.static_path = os.path.abspath("./html... |
import getopt
import sys
class SlopeOrientation:
def __init__(self, dem, out_layer):
print "Entering SlopeOrientation"
#ALGORITHM: Aspect
# INPUT <ParameterRaster>
# BAND <ParameterNumber>
# COMPUTE_EDGES <ParameterBoolean>
# ZEVENBERGEN <ParameterBool... |
from django.utils.translation import ugettext_lazy as _
from crystal_dashboard.dashboards.crystal import dashboard
import horizon
class Controllers(horizon.Panel):
name = _("Controllers")
slug = 'controllers'
dashboard.CrystalController.register(Controllers) |
import codecs
import escpos
from datetime import datetime
import textwrap
import output
class OutputPrn(output.Output):
def output(self):
articles = self._articles
for f in articles:
prn = escpos.Escpos('%s.prn' % f.replace('/', '_'))
for a in articles[f]:
tit... |
__version__='0.5.1' |
DEBUG = True
observer = None
ser_port = None
s = 0
ser = None
import signal
import sys
import os
def signal_handler(signal, frame):
global s, ser
print '\nYou pressed Ctrl+C!'
if s > 18:
print "MTK_Finalize"
serialPost(ser, "B7".decode("hex"))
time.sleep(0.1)
if ser.isOp... |
import numpy as np
from assorted.GraphInput import GraphInput
from model.component.component_model import ComponentModel
class CsvInput(ComponentModel):
name = "CsvInput"
default_out_sockets = [{'position': [0, -20],
'name': 'Output'}]
default_attributes = {'path': '<argument>',
... |
from rest_framework import serializers
from .models import Community, Objective, SocialNetwork, Sector
class ObjectiveSerializer(serializers.ModelSerializer):
class Meta:
model = Objective
class CommunitySerializer(serializers.ModelSerializer):
objectives = ObjectiveSerializer(many=True)
class Meta:... |
from .operation import Operation
from ..operands import Register, Operand2, Opcodes, Zero
class LedOperation(Operation):
opcodes = {"but": "1111100"}
structure = [Opcodes(opcodes), Zero(21), Register]
class ButOperation(Operation):
opcodes = {"led": "1111101"}
structure = [Opcodes(opcodes), Operand2(25)... |
from mstm_studio.contributions import MieLognormSpheres
from mstm_studio.alloy_AuAg import AlloyAuAg
import numpy as np
mie = MieLognormSpheres(name='mie', wavelengths=np.linspace(300,800,51))
mie.set_material(AlloyAuAg(x_Au=1), 1.5) # golden sphere in glass
values = [1, 1.5, 0.5] # scale, mu, sigma
fig, _ = mie.plot... |
"""Some useful path functions."""
import os
from django.conf import settings
def __path_join(base, *args):
"""
Join multiple paths after 'base' and ensure the result is still
under 'base'.
"""
base = os.path.normpath(base)
directory = os.path.normpath(os.path.join(base, *args))
if directory.... |
import os
import asyncio
import struct
from .logger import get_logger
from .protocol import PeerStreamIterator
from .message import (MessageID,
InterestedMessage,
HandshakeMessage,
BitFieldMessage,
NotInterestedMessage,
... |
import logging
import time
import zlib
from collections import defaultdict
from datetime import datetime
from hashlib import sha1
from operator import itemgetter
import simplejson as json
from _mysql_exceptions import IntegrityError
from django.conf import settings
from django.core.cache import cache
from django.core.e... |
import torch
def get_data(params):
batch_size = params["batch_size"]
M, N, K = params["problem"]["size"]
flop = (2.0 * M * N * K)
params["problem"]["flop_estimated"] = flop * params["nb_epoch"] * batch_size
m = params["problem"]["size"][0]
n = params["problem"]["size"][1]
k = params["problem... |
reddit_client_id = ""
reddit_client_secret = ""
reddit_user = ""
reddit_pass = ""
discord_key = ""
module_names = (
"default",
)
config_version = 2 |
from textwrap import dedent
from bedrock.mozorg.tests import TestCase
from bedrock.sitemaps.models import NO_LOCALE, SitemapURL
class TestSitemapView(TestCase):
def setUp(self):
data = [
{
'path': '/firefox/all/',
'locale': 'de',
'lastmod': '2020-0... |
'''ioriodb CLI client to interact with the api from the command line'''
from __future__ import print_function
import time
import json
import argparse
import iorio
def get_arg_parser():
'''build the cli arg parser'''
parser = argparse.ArgumentParser(description='Iorio DB CLI')
parser.add_argument('--verbose'... |
class Ob(object):
def __init__(self, *args, **kwds):
for i in args:
self.__dict__.update(args)
self.__dict__.update(kwds)
def __getattr__(self, name):
return self.__dict__.get(name, '')
def __setattr__(self, name, value):
if value is not None:
self.__d... |
import subprocess
def main():
error = True
while error:
error = False
try:
subprocess.check_call("./asteroids -hostAt=\":10034\" &> /dev/null", shell=True)
except subprocess.CalledProcessError:
error = True
if __name__ == "__main__":
main() |
"""
Test models, managers, and validators.
"""
from __future__ import absolute_import, division, unicode_literals
import six
from completion import models, waffle
from completion.test_utils import CompletionWaffleTestMixin, submit_completions_for_testing
from django.core.exceptions import ValidationError
from django.te... |
"""Functional tests for XPI file format"""
__metaclass__ = type
import re
import unittest
from zope.component import getUtility
from lp.app.interfaces.launchpad import ILaunchpadCelebrities
from lp.registry.interfaces.person import IPersonSet
from lp.registry.interfaces.product import IProductSet
from lp.testing.layers... |
"""
Unit tests for django-registration.
These tests assume that you've completed all the prerequisites for
getting django-registration running in the default setup, to wit:
1. You have ``registration`` in your ``INSTALLED_APPS`` setting.
2. You have created all of the templates mentioned in this
application's docume... |
import os
import time
import mechanize
CKAN = os.environ.get('CKAN', 'http://data.england.nhs.uk/')
class Transaction(object):
def __init__(self):
self.custom_timers = {}
def run(self):
# create a Browser instance
br = mechanize.Browser()
# don't bother with robots.txt
br... |
from rest_framework import renderers
from django.utils.xmlutils import SimplerXMLGenerator
from django.utils.six.moves import StringIO
from django.utils.encoding import smart_text
from rest_framework.compat import six
from rest_framework import negotiation
import json
"""
@author: Jon Nordling
@date: 06/19/2016
XFormLi... |
{'name': 'Magento Connector - Pricing',
'version': '2.0.0',
'category': 'Connector',
'depends': ['magentoerpconnect',
],
'author': "MagentoERPconnect Core Editors,Odoo Community Association (OCA)",
'license': 'AGPL-3',
'website': 'http://www.odoo-magento-connector.com',
'description': """
Magento Co... |
import ckan.controllers.package as package
import ckan.lib.dictization.model_dictize as model_dictize
import ckan.model as model
from ckan.common import c
class MapactionPackageController(package.PackageController):
def groups(self, id):
q = model.Session.query(model.Group) \
.filter(model.Group... |
from openerp.osv import osv, fields
class AccountInvoiceMultipartner(osv.osv):
''' Add more than one reference partner in account invoice
(only in report document, not in journal entry)
'''
_inherit = 'account.invoice'
# on change function:
def onchange_extra_address(self, cr, uid, ids, extr... |
import time
import random
import os
import os.path
import logging
import urlparse
import functools
import lms.lib.comment_client as cc
import django_comment_client.utils as utils
import django_comment_client.settings as cc_settings
from django.core import exceptions
from django.contrib.auth.decorators import login_requ... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("events", "0004_create_basic_calendars")]
operations = [
migrations.AlterField(
model_name="event",
name="name",
field=models.CharF... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('explorer', '0006_auto_20181004_1159'),
]
operations = [
migrations.AddField(
model_name='fieldvalue',
name='column_name',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.