code stringlengths 1 199k |
|---|
"""Pre-computation and code generation for all sorts of moments"""
from horton import get_cartesian_powers, get_ncart
def write_cart_poly_code(f):
cps = get_cartesian_powers(7)
cps = [tuple(row) for row in cps[1:]] # chop of the s function
print(" // Shell l=0", file=f)
print(" if (lmax <= 0) retu... |
from django.conf.urls import url
from . import views
app_name = 'contact'
urlpatterns = [
url(r'^$', views.ContactView.as_view(), name='contact'),
url(r'^thanks/$', views.ThanksView.as_view(), name='thanks'),
] |
import argparse
from libsudoku.register import Register, discover
from libsudoku.parsers import ParsingError
from libsudoku.solvers import SolvingError
def parse_arguments(*args) -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Sudoku solver")
parser.add_argument(
'-v', '--verbo... |
from sapl.compilacao import models as compilacao
from sapl.norma import models as norma
from sapl.rules import SAPL_GROUP_NORMA, __base__, __perms_publicas__
rules_group_norma = {
'group': SAPL_GROUP_NORMA,
'rules': [
(norma.NormaJuridica, __base__, __perms_publicas__),
(norma.NormaRelacionada, ... |
from Scientific.IO import NetCDF
from numpy import *
from meteo import *
from sciproc import *
from ncdfextra import *
from matplotlib import rc
from matplotlib.pyplot import *
from matplotlib.dates import *
from datetime import *
from pytz import *
from numpy import *
ncmean = NetCDF.NetCDFFile('/home/hendrik/data/par... |
from strava_uploader import main
main.main() |
import sys
import os
import glob
def process_file(fname):
func_name = None
with open(fname) as f:
l = f.readline()
if not l.startswith("; Entry point: "):
return
l = l.strip()
head, func_name = l.rsplit(None, 1)
assert func_name
print("Processing:", fname)
... |
class ClusterGroup(object):
def __init__(self, cluster_name):
self.cluster_name = cluster_name
self.clusters = {}
self.connects = {
'input': [],
'output': []
}
self.back_channels = {
}
def parse(self):
snapshot = {
'type... |
import numpy as np
from pele.transition_states import InterpolatedPathDensity
__all__ = ["smoothPath"]
def smoothPath(path, mindist, density=5., interpolator=None):
"""return a smooth (interpolated) path
usefull for making movies. Especially for min-ts-min pathways
returned by DoubleEndedConnect.
Param... |
""" DIRAC Basic MySQL Class
It provides access to the basic MySQL methods in a multithread-safe mode
keeping used connections in a python Queue for further reuse.
These are the coded methods:
__init__( host, user, passwd, name, [maxConnsInQueue=10] )
Initializes the Queue and tries to connect to the... |
"""Module for the handler of the About window"""
import gtk
from constants import VERSION
class AboutHandler(object):
"""About window handler"""
def __init__(self, mainhandler):
self._mainhandler = mainhandler
self._wtree = gtk.Builder()
self._wtree.add_from_file("view/about.glade")
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: postgresql_user
short_description: Add or remove a user (role) from a PostgreSQL... |
from sigelib import Environment
EXTRA_HOUR_ALERT = '[Hora Extra] {} ja esta trabalhando a {}! - Jornada de {}'
INTERJOURNEY_ALERT = ('[Interjornada Divergente] Empregado: {} tirou {}H de '
'interjornada!')
REST_ALERT = '[Intervalo Divergente] {} tirou intervalo de: {} H'
FIRST_JOURNEY_EXTRAPOLATED... |
import sys
import os
sys.path.insert(0, os.path.abspath('../'))
sys.path.insert(0, os.path.abspath('../totalopenstation'))
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.napoleon',
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = 'Total Open Station'
copyright = '2015-20... |
'''
$ python3 merging_strings.py
Please input the first string: ab
Please input the second string: cd
Please input the third string: abcd
The third string can be obtained by merging the other two.
$ python3 merging_strings.py
Please input the first string: ab
Please input the second string: cdab
Please input the third ... |
import sublime
import sublime_plugin
import subprocess
import tempfile
class MysqlCommand(sublime_plugin.TextCommand):
settings = sublime.load_settings("SublimeMysql.sublime-settings")
def run(self, edit):
view = self.view
if self.settings.get('dbname') is None:
view.run_command('sho... |
'''
Created on 17 de fev de 2017
@author: nicoli
'''
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
class ResultNetsPlotting():
def read_data_set(self, filename):
return pd.read_csv(filename, sep=r',', index_col=0).round(5)
def plotanomaly(self, type, dataset, month, time_gap)... |
from drawing import Drawing
from factory import PickerFactory
from randomPicker import RandomPicker
if __name__ == "__main__":
d = {"picksPerDrawing": 5, "altReds": False}
# Test creating pickers
# Test factory
pf = PickerFactory()
print(pf)
rp = pf.CreatePicker("RandomPicker", **d)
print(rp... |
from multiprocessingloghandler import ChildMultiProcessingLogHandler
import logging
import queue
import os
class FedStream(object):
def __init__(self, source, log_queue, log_level):
# Create a thread-safe buffer of audio data
self._buff = source
self.closed = False
self._log_queue = ... |
"""
A distutils script to make a standalone .app of the MASSIVE Launcher for
Mac OS X. You can get py2app from http://undefined.org/python/py2app.
Use this command to build the .app and collect the other needed files:
python create_mac_bundle.py py2app
Traditionally, this script would be named setup.py
"""
from set... |
import math
import pyglet
import string
import wrappers
from pyglet.gl import *
def getCapVertexCount(segment_count):
return segment_count*2 + 3
def getCapIndexCount(segment_count):
return segment_count * (3 * 3)
def setVertex(vb, vi, x, y, z, color, alpha):
vb.vertices[vi*3:vi*3+3] = [x, y, z]
vb.color... |
import os
import argparse
import numpy as np
import time
import datetime
DESCRIPTION = "Python pipe to build Freesurfer template surface. $SUBJECT_DIR and $TM_ADDONS must be declared (e.g., export SUBJECT_DIR=/path/to/freesurfer/subjects)"
def getArgumentParser(parser = argparse.ArgumentParser(description = DESCRIPTION... |
from __future__ import unicode_literals
import array
import logging
import re
import struct
from io import open, StringIO
from unitex import UnitexException, UnitexConstants
from unitex.io import UnitexFile
from unitex.utils.fsa import FSAConstants, Automaton
from unitex.utils.types import BRACKETED_ENTRY, Tag, Entry
_... |
from django.apps import AppConfig
class BarbadoswebConfig(AppConfig):
name = 'barbadosweb' |
from django.conf.urls.defaults import *
from abcast.views import StationListView, StationDetailView
urlpatterns = patterns('',
url(r'^$', StationListView.as_view(), name='abcast-station-list'),
url(r'^(?P<slug>[-\w]+)/$', StationDetailView.as_view(), name='abcast-station-detail'),
) |
'''
Copyright 2013 Joel Whitcomb
This file is part of Sudoku Solver.
Sudoku Solver 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 ver... |
from oct2py import octave
import numpy as np
def cumulative_losses(state_1, state_2, time, ideal_losses):
"""
Cumulative losses during generator ramping are calculated. Units in MW*min.
:param state_1: Solved Matpower case with initial generation schedule
:param state_2: Solved Matpower case with final ... |
LEADERBOARD_HOMEPAGE_RESULTS_PER_PAGE = 10
LEADERBOARD_TABLE_RESULTS_PER_PAGE = 25
ACTIVITY_GRAPH_DEFAULT_NO_DAYS = 31
STR_DATE_DISPLAY_FORMAT = "%d %b %Y"
STR_DATE_DISPLAY_FORMAT_MONTH = "%b %Y"
STR_DATE_FORMAT = "%Y-%m-%d"
STR_DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S" |
import MySQLdb
import pandas
from grimoirelib.data_handler.scr import SCR
class SCRData(object):
""" Basic class to deal with SCR data
"""
def _connect(self):
user = "root"
password = ""
host = "localhost"
db = "wikimedia_gerrit_20150621"
try:
db = MySQLdb... |
import re
import requests
from lxml import html
from cloudbot import hook
from cloudbot.util import formatting, web
search_url = "https://search.atomz.com/search/?sp_a=00062d45-sp00000000"
@hook.command
def snopes(text):
"""<topic> - Searches snopes for an urban legend about <topic>."""
try:
params = {'... |
from GangaCore.testlib.GangaUnitTest import GangaUnitTest
import os
class TestSavannah19123(GangaUnitTest):
def test_Savannah19123(self):
from GangaCore.GPI import Job, Local
from GangaTest.Framework.utils import sleep_until_state
# check if stdout and stderr exists or not, flag indicates if... |
from __future__ import print_function
import espressomd
import numpy as np
import unittest as ut
@ut.skipIf(not espressomd.has_features(["BOND_ANGLE"]),
"Features not available, skipping test!")
class InteractionsNonBondedTest(ut.TestCase):
system = espressomd.System(box_l=[10.0, 10.0, 10.0])
box_l =... |
from core import httptools
from platformcode import logger
import sys
PY3 = False
if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int
if not PY3: from lib import alfaresolver
else: from lib import alfaresolver_py3 as alfaresolver
def test_video_exists(page_url):
global data
logger.i... |
"""
========
ctang, a map of geba stations in southern africa
========
"""
import math
import pdb
from scipy import stats
import datetime
import pandas as pd
import numpy as np
import matplotlib as mpl
from textwrap import wrap
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap , addcyclic
from ma... |
from __future__ import unicode_literals
from django.db import models
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation im... |
import pickle
from unittest import TestCase
from unittest.mock import Mock
from tempfile import TemporaryFile
from pynetics.stop import StepsNum, FitnessBound
class StepsNumTestCase(TestCase):
""" Test for the stop condition based on number of iterations. """
def test_class_is_pickeable(self):
""" Check... |
import os
import RPi.GPIO as GPIO
import signal
import subprocess
import sys
import time
import string
import datetime
from time import strftime
import shutil
import atexit
import traceback
from radio_daemon import Daemon
from radio_class import Radio
from lcd_i2c_class import lcd_i2c
from log_class import Log
from rss... |
import os
from typing import Dict
import requests
from collections import defaultdict
from dateutil import tz, parser
from ..Api import Api
from xml.etree import ElementTree
from datetime import datetime
from stations import Station
SBB_API_KEY = os.environ.get('SBB_API_KEY')
TIMEZONE = tz.gettz('Europe/Zurich')
class ... |
from time import *
import serial
from serial import *
class MySerial:
serial = Serial(
port = '/dev/ttyUSB0',
#port = '/dev/serial/by-path/pci-0000:00:14.0-usb-0:5:1.0-port0',
baudrate = 9600,
parity = PARITY_NONE, # Check this
stopbits = STOPBITS_ONE, # Check this
... |
'''class to interpolate position information given a time'''
import sys, os, time, math, datetime, re
import fractions
from MAVProxy.modules.mavproxy_map import mp_elevation
from pymavlink import mavutil
from cuav.lib import cuav_util
EleModel = mp_elevation.ElevationModel()
class MavInterpolatorException(Exception):
... |
from socket import *
from string import Formatter
from datetime import datetime, date
from optparse import OptionParser
import sys
import json
def get_options_parser():
parser = OptionParser(add_help_option=False)
parser.add_option('-?',"--help",action="help",\
help="Show this message and exit.")
pa... |
import asyncio
import logging
import socket
import unittest
from hpfeeds.asyncio import ClientSession
from hpfeeds.broker import prometheus
from hpfeeds.broker.auth.memory import AsyncAuthenticator, Authenticator
from hpfeeds.broker.server import Server
class TestAsyncioClientIntegration(unittest.TestCase):
log = l... |
"""
Command-line utility for administrative tasks.
"""
import os
import sys
if __name__ == "__main__":
os.environ.setdefault(
"DJANGO_SETTINGS_MODULE",
"TinyILS.settings"
)
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
from urllib import unquote, urlencode
from sys import exit
current_crs = str(iface.mapCanvas().mapRenderer().destinationCrs().authid())
ems_url_in_v2_public_1 = (
" crs='EPSG:4326' format='PNG32' layer='0' url='http://noisy.hq.isogeo.fr:6081/arcgis/rest/services/LimitesAdministrativesFR/EPCI/MapServer' table="
... |
"""
ZetCode PyQt4 tutorial
This example shows a QtGui.QProgressBar widget.
author: Jan Bodnar
website: zetcode.com
last edited: September 2011
"""
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI... |
import pyCHNadm1 as CHN
import numpy as np
import pandas as pd
import seaborn as sns
from scipy import stats
import matplotlib as mpl
mpl.rcParams["axes.labelsize"] = 18.0
mpl.rcParams["axes.grid"] = True
mpl.rcParams["font.size"] = 14.0#
mpl.rcParams["axes.edgecolor"] = "black"
mpl.rcParams["axes.labelcolor"] = "black... |
import unittest
import mock
import accurev.transaction
class TestAccuRevTransaction(unittest.TestCase):
def test_transaction_from_cpkhist(self):
xml = """<?xml version="1.0" encoding="utf-8"?>
<acResponse>
<transaction
id="50"
type="dispatch"
... |
from urllib.parse import urlparse
from django.core.exceptions import PermissionDenied
from django.utils.decorators import available_attrs
from django.utils.six import wraps
from djangle import settings
def user_passes_test_with_403(test_func):
"""
Decorator for views that checks that the user passes the given t... |
import os
import sys
import os.path as op
import mtpy.core.edi as MTedi
def main():
fn = sys.argv[1]
if not op.isfile(fn):
print('\n\tFile does not exist: {0}\n'.format(fn))
sys.exit()
saveplot = False
if len(sys.argv) > 2:
arg2 = sys.argv[2]
if 's' in arg2.lower():
... |
import commands
import pykolab
from pykolab.imap import IMAP
from pykolab.translate import _
log = pykolab.getLogger('pykolab.cli')
conf = pykolab.getConf()
def __init__():
commands.register('list_deleted_mailboxes', execute)
def execute(*args, **kw):
"""
List deleted mailboxes
"""
imap = IMAP()... |
import os
from autosemver.packaging import get_changelog, get_current_version, get_releasenotes
if not os.path.exists("_build/html/_static"):
os.makedirs("_build/html/_static")
URL = "https://github.com/david-caro/python-autosemver"
BUGTRACKER_URL = URL + "/issues/"
with open("_build/html/_static/RELEASE_NOTES.txt"... |
"""
Plots cells over time
Copyright (C) 2012 Ahmet Ay, Jack Holland, Adriana Sperlea
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 later vers... |
'''
Mepinta
Copyright (c) 2011-2012, Joaquin G. Duo
This file is part of Mepinta.
Mepinta 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.
Mep... |
import numpy as np
from scipy import interpolate
from collections import namedtuple
from oceansar import constants as const
def orbit_to_vel(orbit_alt, ground=False,
r_planet=const.r_earth,
m_planet=const.m_earth):
""" Calculates orbital/ground velocity assuming circular orbit
... |
from positive_test_suite import PositiveTestSuite
from negative_test_suite import NegativeTestSuite
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
from query_models import PhraseMatch
class TestPhraseMatchPositiveTestSuite(PositiveTestSuite):
def query_tests(self):
... |
from django.conf.urls import patterns, url, include
from rest_framework.routers import DefaultRouter
import views
router = DefaultRouter()
router.register(r'snippets', views.SnippetView)
urlpatterns = patterns('',
url(r'^', include(router.urls)),
url(r'^host/$', views.host_register, name='host'),
url(r'^cho... |
from pathlib import Path
from django.template import TemplateDoesNotExist
from django.test import RequestFactory
from django_jinja.backend import Jinja2
from mock import ANY, Mock, patch
from bedrock.mozorg.tests import TestCase
from lib.l10n_utils import render
ROOT_PATH = Path(__file__).with_name("test_files")
ROOT =... |
def main(request, response):
headers = [("Content-Type", "text/plain")]
stashed_data = {'control_request_headers': "", 'preflight': "0", 'preflight_referrer': ""}
token = None
if "token" in request.GET:
token = request.GET.first("token")
if "origin" in request.GET:
for origin in requ... |
from datetime import timedelta
from django.test import TestCase
from django.utils.timezone import now
from nucleus.rna.models import Release
class TestReleaseQueries(TestCase):
def setUp(self):
one_week_ago = now() - timedelta(days=7)
two_weeks_ago = now() - timedelta(days=14)
self.r1 = Rele... |
import argparse
import json
import os
import re
import math
import sys
import shutil
import tempfile
import timeit
import subprocess
import pkg_resources
import itertools
import numpy as np
from functools import partial
from nanonet import decoding, nn, cl
from nanonet.fast5 import Fast5, iterate_fast5, short_names
fro... |
{
'repo_type' : 'git',
'url' : 'https://chromium.googlesource.com/webm/libwebp',
'branch': 'main',
'source_subfolder': '_build',
'conf_system' : 'cmake',
'configure_options' : '.. {cmake_prefix_options} '
'-DCMAKE_INSTALL_PREFIX={target_prefix} -DBUILD_SHARED_LIBS=OFF -DWEBP_BUILD_EXTRAS=OFF'
'-DWEBP_ENABLE_S... |
import mozinfo
import mozunit
import os
import pprint
import re
import shutil
import sys
import tempfile
import unittest
from StringIO import StringIO
from mozlog import structured
from mozbuild.base import MozbuildObject
os.environ.pop('MOZ_OBJDIR', None)
build_obj = MozbuildObject.from_environment()
from runxpcshellt... |
from odoo import api, exceptions, fields, models, _
from io import BytesIO
import logging
import base64
_logger = logging.getLogger(__name__)
try:
import openpyxl
except ImportError:
_logger.debug('Can not import openpyxl')
class SqlExport(models.Model):
_inherit = 'sql.export'
file_format = fields.Sele... |
import logging
from . import abstract_test
_logger = logging.getLogger(__name__)
class AbstractTestForeignCurrency(abstract_test.AbstractTest):
"""Common technical tests for all reports."""
def _chart_template_create(self):
super(AbstractTestForeignCurrency, self)._chart_template_create()
# Acco... |
import os
import sys
import openerp.netsvc
import logging
from openerp.osv import osv, orm, fields
from datetime import datetime, timedelta
from openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT, DATETIME_FORMATS_MAP, float_compare
import openerp.addons.decimal_precision as dp
from openerp... |
"""
Database models for the LTI provider feature.
This app uses migrations. If you make changes to this model, be sure to create
an appropriate migration file and check it in at the same time as your model
changes. To do that,
1. Go to the edx-platform dir
2. ./manage.py lms schemamigration lti_provider --auto "descrip... |
from web.settings.base import *
DEBUG = False
ALLOWED_HOSTS = ['localhost']
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': [
'memcached1:11211',
'memcached2:11211',
]
}
}
DATABASES = {
'default': {
... |
import pytest
from adhocracy4.categories.dashboard import ModuleCategoriesComponent
@pytest.mark.django_db
def test_module_categories_settings(phase_factory):
# Note: this test depends on tests.project.settings.A4_CATEGORIZABLE
phase = phase_factory(type='a4test_questions:ask')
component = ModuleCategoriesC... |
import sys
import traceback
import logging
import psycopg2
import psycopg2.extras
from datetime import datetime
from managers.manager import Manager
from services.cursor import Cursor
from orm.common import *
from tools.translations import trlocal as _
_logger = logging.getLogger('listener.' + __name__)
class db_except... |
import fix_path # noqa
import datetime
import httplib2
import logging
import random
import string
import time
from apiclient import discovery
from apiclient.errors import HttpError
from google.appengine.api import app_identity, memcache, lib_config
from google.appengine.ext import ndb
from oauth2client.appengine impor... |
import re,cgi,cgitb,sys
import os
import urllib
import meowaux as mew
import Cookie
cgitb.enable()
cookie = Cookie.SimpleCookie()
cookie_hash = mew.getCookieHash( os.environ )
if ( ("userId" not in cookie_hash) or ("sessionId" not in cookie_hash) or
(mew.authenticateSession( cookie_hash["userId"], cookie_hash["se... |
import optparse
import re
import time
from sys import exit
def start_scann(module):
# Open and read file
method_list = []
with open("../../ipol_demo/modules/{}/{}.py".format(module, module)) as f:
lines = f.readlines()
for line_index in range(len(lines)):
method = ""
if "@cherryp... |
"""
This class is an interface for Reactionner and Poller daemons
A Reactionner listens to a port for the configuration from the Arbiter
The conf contains the schedulers where actionners will gather actions.
The Reactionner keeps on listening to the Arbiter
(one a timeout)
If Arbiter wants it to have a new conf, the sa... |
import logging
import requests
import threading
from queue import Empty
from cachetools import LFUCache
from timeit import default_timer
from .utils import get_async_requests_session
log = logging.getLogger(__name__)
wh_lock = threading.Lock()
def send_to_webhooks(args, session, message_frame):
if not args.webhooks... |
from __future__ import print_function
try:
from tkinter import Tk, Label
except ImportError:
from Tkinter import Tk, Label
from PIL import Image, ImageTk
class UI(Label):
def __init__(self, master, im):
if im.mode == "1":
# bitmap image
self.image = ImageTk.BitmapImage(im, fo... |
"""OCitySMap 2.
OCitySMap is a Mapnik-based map rendering engine from OpenStreetMap.org data.
It is architectured around the concept of Renderers, in charge of rendering the
map and all the visual features that go along with it (scale, grid, legend,
index, etc.) on the given paper size using a provided Mapnik styleshee... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting model 'TaskExecutorLog'
db.delete_table('admin_task_executor_log')
# Adding field 'EmailTask.user'
db.add_co... |
import pandas as pd
import pyedna.ezdna as dna
tag = "TESTSITE.TESTSERVICE.TESTPNT1" # format site.service.tag
start = "12/01/16 01:01:01" # format mm/dd/yy hh:mm:ss
end = "01/03/17 01:01:01" # format mm/dd/yy hh:mm:ss
period = "00:00:30" # format hh:mm:ss
... |
from django.contrib import admin
from .models import Group, Patrol, Technique, Test
@admin.register(Group)
class GroupAdmin(admin.ModelAdmin):
list_display = ('name',)
@admin.register(Technique)
class TechniqueAdmin(admin.ModelAdmin):
list_display = (
'name',
'staff',
'person_name',
... |
import os
from flask import Flask
import pandas as pd
from io import StringIO
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from skl... |
from __future__ import absolute_import, division, print_function
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
impo... |
from astrobin_apps_equipment.api.filters.filter_filter import FilterFilter
from astrobin_apps_equipment.api.serializers.filter_image_serializer import FilterImageSerializer
from astrobin_apps_equipment.api.serializers.filter_serializer import FilterSerializer
from rest_framework.decorators import action
from rest_frame... |
from openerp import fields, models, api
class HrEmployee(models.Model):
_inherit = 'hr.employee'
external_code = fields.Char()
attendance_count = fields.Integer(string='# of Attendances', compute='_count_attendances', readonly=True)
def _count_attendances(self):
for rec in self:
rec.... |
from __future__ import unicode_literals
import errno
from django.test import TestCase
from mock import Mock, patch, DEFAULT
import six
from wirecloud.catalogue.utils import add_packaged_resource, update_resource_catalogue_cache
from wirecloud.commons.utils.template import TemplateParseException
from wirecloud.commons.u... |
from .dev import *
from .cms.dev import *
import json
with open(ENV_ROOT / "env.json") as env_file:
ENV_TOKENS = json.load(env_file)
THEME_NAME=ENV_TOKENS.get('THEME_NAME')
enable_theme(THEME_NAME)
FAVICON_PATH = 'themes/%s/images/favicon.ico' % THEME_NAME
LOGIN_URL = '/login'
INSTALLED_APPS += ('wind','cvn_lms', '... |
from __future__ import unicode_literals
from django.contrib import admin |
from __future__ import absolute_import
from vulture.whitelist_utils import Whitelist
view_whitelilst = Whitelist() |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalogue', '0029_auto_20201102_1315'),
]
operations = [
migrations.AddField(
model_name='collection',
name='notes',
field=models.TextField(blank=True, verbo... |
"""This module provides the components needed to build your own __import__
function. Undocumented functions are obsolete.
In most cases it is preferred you consider using the importlib module's
functionality over this module.
Taken from CPython 3.7.0 and vendored to still have it when it gets
completely removed.
Licen... |
import datetime
from os.path import join as path_join
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.utils import translation
from reportlab.lib import colors
from reportlab.lib.colors import HexColor
from reportlab.lib.styles import (
ParagraphStyle,
StyleShe... |
import partner_address
import res_company |
longdesc = '''
This is a library for Freifunk. fflib includes several modules to
interact with Meshviewer informations, gateways, the Freifunk network
and even nodes directly.
Required packages:
paramiko
netifaces
Please read <https://github.com/Real-Instruments/fflib> for more
informations.
'''
try:
from s... |
{
'name': 'Intervention report - Calendar meeting sync',
'version': '0.2',
'category': 'Intervention / Calendar',
'description': """
Add a sync to calendar event for Intervent
""",
'author': 'Micronaet s.r.l.',
'website': 'http://www.micronaet.it',
'license': 'AGPL-3',
'depen... |
import openerp.addons.web.http as openerpweb
from openerp.addons.web.controllers.main import View
import urllib2
import simplejson
import base64
import time
import zlib
import cPickle
import hashlib
FILE_TOKENS ={}
def content_disposition(filename, req):
filename = filename.encode('utf8')
escaped = urllib2.quot... |
{
'name': 'Track Employees Equipment',
'version': '1.0',
'sequence': 125,
'description': """
Track employees' equipment and manage its allocation """,
'author': 'Odoo S.A.',
'depends': ['hr'],
'data': [
'security/hr_equipment.xml',
'security/ir.model.access.csv',
... |
from openerp.osv import osv,fields
class res_partner(osv.Model):
_name = "res.partner"
_inherit = "res.partner"
_columns = {
'is_instructor': fields.boolean('Instructor'),
'session_ids' : fields.one2many('openacademy.session','instructor_id',string='Sessions'),
} |
import logging
from ckan.common import request, c
from ckan.lib.base import BaseController
from ckan.model import Session, Package
from ckan.lib.helpers import url_for
from pylons import config, response
from pylons.decorators.cache import beaker_cache
import ckan.model as model
import ckan.lib.helpers as h
import ti... |
from . import website
from . import models |
import os.path
import logging
import getpass
import diaspy
import bs4
def get_connection():
c = diaspy.connection.Connection(**_get_login())
c.login()
return c
def _get_login():
login_file = os.path.expanduser('~/.diaspora')
if os.path.exists(login_file):
with open(login_file) as f:
... |
from haystack import indexes
from parliament.models import Member, Keyword, MemberActivity, Term
class MemberIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, model_attr='name', use_template=False)
autosuggest = indexes.EdgeNgramField(model_attr='name')
time = indexes.Da... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.