code
stringlengths
1
199k
from setuptools import setup with open("README.rst") as readme_file: long_description = readme_file.read() setup(name="Presser", version="0.1.8", packages=["presser",], license="GNU GPL v3.0", description="Extracts data from vine, in lieu of an API", author="Gemma Hentsch", author_email="con...
""" 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 version. This program is distributed in the hope that it will be ...
'''Player class''' import logging from . import g from . import rnd from . import enum2 as enum log = logging.getLogger(__name__) class HUNGER(enum.Enum): '''Minimum food in stomach before some effect or warning Values represent the last "safe" food amount before the step ''' HUNGRY = 300 # WEAK *...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: citrix_adc_appfw_settings short_description: Manage Citrix ADC ...
""" OwO whats this? """ __author__ = ('Smurphicus') COMMAND = 'owo' from random import choice substitutions = {'r':'w','R':'W','l':'w','L':'W','na':'nya','NA':'NYA','qu':'qw','QU':'QW'} faces = [' OwO', ' owo', ' UwU', ' uwu', ' :3', ' :33', ' :333', ''] def owoify(message): for key in substitutions.keys(): ...
from gi.repository import Gtk, Gdk from lollypop.define import Lp, ArtSize, Type from lollypop.widgets_album import AlbumWidget from lollypop.pop_radio import RadioPopover class RadioWidget(AlbumWidget): """ Widget with radio cover and title """ def __init__(self, name, radios_manager): """ ...
import gettext import locale from obozrenie.global_settings import * current_locale, encoding = locale.getdefaultlocale() t = gettext.translation(APPLICATION_ID, localedir=LOCALE_DIR, languages=[ current_locale], codeset=encoding, fallback=True) _ = t.gettext
from __future__ import print_function import errno import logging import os import pickle import shutil import sys import tempfile import textwrap import six from ipalib.install import certmonger, sysrestore from ipapython import ipautil from ipapython.ipautil import ( format_netloc, ipa_generate_password, run, use...
""" Copyright (C) 2017-2021 Vanessa Sochat. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. """ from django.conf.urls import url from rest_framework_swagger.views import get_s...
from __future__ import unicode_literals from django.conf import settings from django.contrib.auth.models import AnonymousUser from django.http import HttpResponse from django.shortcuts import render from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_exempt from django.vi...
from __future__ import division, absolute_import, with_statement, print_function, unicode_literals import os import sys import subprocess import re from common import list2cmdline from common import sshexec from common import SSH subprocess.list2cmdline = list2cmdline __author__ = "Drew Bonasera" __license__ = "MPL 2.0...
import contextlib import functools import logging import psycopg2.extras from psycopg2 import Error as Psycopg2Error _logger = logging.getLogger(__name__) def retry_on_psycopg2_error(func): """ Decorator that retries 3 times after Postgres error, in particular if the connection was not valid anymore because...
import ujson as json from pprint import pprint import msgpack import logging from cifsdk.constants import PYVERSION import os TRACE = os.environ.get('CIFSDK_CLIENT_MSG_TRACE') logger = logging.getLogger(__name__) logger.setLevel(logging.ERROR) if TRACE: logger.setLevel(logging.DEBUG) MAP = { 1: 'ping', 2: '...
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Document' db.create_table('witness_document', ( ('id', self.gf('django.db.models.fields.AutoField')(primary...
import io import os import sys from atomicwrites import atomic_write from copy import deepcopy from multiprocessing import Pool, cpu_count from six import ensure_text from . import jsonlib from . import vcs from .item import (ConformanceCheckerTest, CrashTest, ManifestItem, ...
import json from datetime import datetime from werkzeug.exceptions import HTTPException, BadRequest from werkzeug.wrappers import Response from ..handler_params import HandlerParams from ..config import Config from ..database import Database from ..logger import Logger class BaseHandler: @staticmethod def raise...
import logging from datetime import datetime import os from flask import request, g, Response, jsonify from openspending.views.api_v4.common import blueprint from openspending.lib.apihelper import DataBrowser_v4, GEO_MAPPING,FORMATOPTS from openspending.lib.jsonexport import to_json from openspending.lib.helpers import...
from odoo.tests.common import SavepointCase class TestStockQuantityChangeReason(SavepointCase): @classmethod def setUpClass(cls): super(TestStockQuantityChangeReason, cls).setUpClass() # MODELS cls.stock_move = cls.env["stock.move"] cls.product_product_model = cls.env["product.pr...
import time from report import report_sxw import netsvc class report_receipt_print(report_sxw.rml_parse): _name = 'report.receipt.print' def __init__(self, cr, uid, name, context): super(report_receipt_print, self).__init__(cr, uid, name, context) self.localcontext.update({ 'time': t...
"""Calculate controller""" from __future__ import division import collections import copy import itertools import os import time from openfisca_core.legislations import ParameterNotFound from .. import conf, contexts, conv, environment, model, wsgihelpers def N_(message): return message def build_output_variables(s...
from ..extensions import celery, redis_store from ..models.taxis import Taxi import time from flask import current_app @celery.task def clean_geoindex(): keys_to_clean = [] cursor = 0 taxi_id = set() cursor = None while cursor != 0: if cursor == None: cursor = 0 cursor, r...
""" WSGI config for credentials. 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.8/howto/deployment/wsgi/ """ import os from os.path import abspath, dirname from sys import path from django.core.wsgi import get_wsg...
""" column 'instances' will be deleted later. Has to be nullable for transition Revision ID: 266658781c00 Revises: 204aae05372a Create Date: 2019-04-15 16:27:22.362244 """ revision = '266658781c00' down_revision = '204aae05372a' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql d...
import sys, urllib2 def main(): if len(sys.argv) < 2: print("Error, usage: {0} <your url>".format(sys.argv[0])) return 1 url = sys.argv[1] print(urllib2.urlopen('http://t34.me/api/?u=' + url).read()) return 0 if __name__ == '__main__': main()
from django.core.urlresolvers import reverse import simplejson as json from utils import test_factories class TestEditor(object): """Simulates the editor widget for unit tests""" def __init__(self, client, video, original_language_code=None, base_language_code=None, mode=None): """Const...
from zou.app.models.search_filter import SearchFilter from .base import BaseModelResource, BaseModelsResource class SearchFiltersResource(BaseModelsResource): def __init__(self): BaseModelsResource.__init__(self, SearchFilter) class SearchFilterResource(BaseModelResource): def __init__(self): Ba...
index_power=lambda a,n:a[n]**n if n<len(a)else-1
from openerp.osv import orm, fields from openerp.tools.translate import _ class product_product(orm.Model): _inherit = "product.product" _columns = { 'product_customer_code_ids': fields.one2many('product.customer.code', 'product_id', ...
from flask_wtf import Form from wtforms import HiddenField, StringField from wtforms.validators import InputRequired, EqualTo from flask_login import current_user, abort, login_required from flask import request, flash, redirect, render_template import random import bcrypt from models.user_model import User from .. imp...
from django.shortcuts import render from rest_framework import generics, serializers from beacon.models import Inquiry, Reply class InquirySerializer(serializers.ModelSerializer): class Meta: model = Inquiry class ReplySerializer(serializers.ModelSerializer): class Meta: model = Reply class Inqu...
import logging import pytz from odoo import models, fields, api _logger = logging.getLogger(__name__) class HrAttendanceDay(models.Model): """ The instances of hr.attendance.day is created either at the first attendance of the day or by the method hr.employee._cron_create_attendance() called by a cron e...
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('scheduler', '0009_auto_20190607_1518'), ] operations = [ migrations.RenameField( model_name='smpost', old_name='post_instagram', new_name='post_newsletter', ...
from . import res_company from . import event from . import event_mail from . import event_type from . import res_config_settings
import os import re import sys import time import redis import datetime sys.path.append(os.path.join(os.environ['AIL_BIN'], 'packages')) import Item import Term sys.path.append(os.path.join(os.environ['AIL_BIN'], 'lib/')) import ConfigLoader def rreplace(s, old, new, occurrence): li = s.rsplit(old, occurrence) ...
PROD = 'prod' LOCAL = 'local' NOPI = 'nopi' ENV = PROD loggingEnabled = True
""" $push is similar to $addToSet. The difference is that rather than accumulating only unique values it aggregates all values into an array. Using an aggregation query, count the number of tweets for each user. In the same $group stage, use $push to accumulate all the tweet texts for each user. Limit your output to th...
import requests import os from optparse import make_option from django.core.exceptions import ImproperlyConfigured from django.core.management.base import BaseCommand, CommandError from django.core.files import File from django.core.files.temp import NamedTemporaryFile from django.core.validators import URLValidator fr...
from django.utils.translation import ugettext_lazy as _ from keops.db import models STATUS = ( ('draft', _('Draft')), ('open', _('In Progress')), ('pending', _('Pending')), ('done', _('Done')), ('cancelled', _('Cancelled')) ) class Category(models.Model): name = models.CharField(null=False, uniq...
from openerp.osv import fields from openerp.osv import osv import lasso import simplejson class auth_saml_provider(osv.osv): """Class defining the configuration values of an Saml2 provider""" _name = 'auth.saml.provider' _description = 'SAML2 provider' _order = 'name' def _get_lasso_for_provider(sel...
""" Forms for the bug tracker app. """ from django import forms from django.utils.translation import ugettext_lazy as _ from apps.txtrender.forms import MarkupCharField from apps.contentreport.forms import ContentReportCreationForm from apps.tools.http_utils import get_client_ip_address from .models import (IssueTicket...
from odoo import models, fields, api from datetime import timedelta from pytz import timezone from odoo.addons import decimal_precision as dp class StockPicking(models.Model): _inherit = 'stock.picking' neutral_document = fields.Boolean('Neutral Document', related='sale_id....
from django.utils.safestring import mark_safe from django.db import models from django.utils.six import python_2_unicode_compatible from mptt.models import MPTTModel from mptt.fields import TreeForeignKey, TreeManyToManyField from datetime import date, timedelta from datetime import datetime from django.utils.translati...
from . import hr_utilization_print
from taiga.base import exceptions as exc from django.apps import apps from django.core import signing from django.utils.translation import ugettext as _ def get_token_for_user(user, scope): """ Generate a new signed token containing a specified user limited for a scope (identified as a string). """ ...
import json import tempfile import os from werkzeug import secure_filename from webant.util import send_attachment_file, routes_collector from flask import request, current_app, url_for, jsonify from archivant import Archivant from archivant.exceptions import NotFoundException from util import ApiError, make_success_re...
""" MIT License Copyright (c) 2017 Hajime Nakagami<nakagami@gmail.com> Copyright (c) 2019 Claude SIMON (https://q37.info/s/rmnmqd49) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restrict...
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Resource' db.create_table('inventory_resource', ( ('id', self.gf('django.db.models.fields.AutoField')(prima...
''' Created on 21 janv. 2016 @author: christian ''' import falcon import os import config import db class Stat(object): ''' Get global statistics ''' def on_get(self, req, resp): '''Return global statistics ''' dbc = db.connect() cur = dbc.cursor() ...
import logging from base64 import b64decode, b64encode from werkzeug.datastructures import FileStorage from odoo import models, fields, _ _logger = logging.getLogger(__name__) try: import magic except ImportError: _logger.warning("Please install magic in order to use Muskathlon module") class OrderMaterialForm(...
from math import pi, atan class ScanSetting(object): """docstring for ScanSetting""" def __init__(self): super(ScanSetting, self).__init__() # for scan self.scan_step = 400 # steps self.theta_a = pi / 6 # radius between center and laser self.img_width = 640 self...
import re, sys from ecmascript.frontend import tree, treeutil def patch(node): patchCount = 0 classDefNodes = list(treeutil.findQxDefineR(node)) for classDefNode in classDefNodes: patchCount += optimize(classDefNode, classDefNodes,) return patchCount def optimize(classDefine, classDefNodes): ...
__name__ = "Remove useless IDENTIFIER column in table MEMBERSHIP_REQUEST" def migrate(cr, version): if not version: return cr.execute('SELECT 1 ' 'FROM pg_class c,pg_attribute a ' 'WHERE c.relname=%s ' 'AND c.oid=a.attrelid ' 'AND a.attname = %...
from django.conf import settings from django.db import models as django_models from django.utils.translation import ugettext_lazy as _ from cms import models as cms_models from djangocms_utils import fields as cms_fields from shop import models as shop_models from shop.util import fields as shop_fields from simple_tran...
from django.conf.urls.defaults import * urlpatterns = patterns('contrib.karma.views', (r'^$', 'index'), (r'index', 'index'), )
from rest_framework import status from rest_framework.decorators import detail_route, list_route from sigma_core.views.sigma_viewset import SigmaViewSet from sigma_core.importer import Sigma, load_ressource User = load_ressource("User") from django.core.mail import send_mail from rest_framework.permissions import Allow...
import sys sys.path.append("./m1") import div sum=div.div(1,200000) print(sum)
from __future__ import unicode_literals from django.db import migrations, models import multiselectfield.db.fields class Migration(migrations.Migration): dependencies = [ ('user', '0018_auto_20160922_1258'), ] operations = [ migrations.AddField( model_name='userprofile', ...
from openerp import fields, models, api class product_product(models.Model): _inherit = 'product.product' is_outlet = fields.Boolean('Is outlet', compute='_is_outlet') normal_product_id = fields.Many2one('product.product', 'normal product') outlet_product_ids = fields.One2many('product.product', ...
''' cloudminingstatus.py @summary: Show selected API data from cloudhasher and miningpool. @author: Andreas Krueger @since: 12 Feb 2017 @contact: https://github.com/drandreaskrueger @copyright: @author @since @license @license: Donationware, see README.md. Plus see LICENSE. @version: v0.1.0 @status: It is...
from .messages import I18nMessages
import logging from osv import osv, fields from tools.translate import _ from datetime import datetime, timedelta _logger = logging.getLogger(__name__) month_list= [('01','January'), ('02','February'), ('03','March'), ('04','April'), ('05','Maj'), ('06','...
import json __author__ = 'Iván Arias León (ivan.ariasleon at telefonica dot com)' import time from lettuce import world from decimal import Decimal from tools import general_utils from tools import http_utils from tools.notification_utils import Notifications from tools.fabric_utils import FabricSupport from tools.cygn...
from . import event_mass_edit
""" Copyright (c) 2015-2017 Alan Yorinks All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 as published by the Free Software Foundation; either or (at your option) any later version. This library is distr...
from essentia_test import * class TestScale(TestCase): def testRegression(self): inputSize = 1024 input = range(inputSize) factor = 0.5 expected = [factor * n for n in input] output = Scale(factor=factor, clipping=False)(input) self.assertEqualVector(output, expected)...
""" Each store has slightly different semantics wrt draft v published. XML doesn't officially recognize draft but does hold it in a subdir. Old mongo has a virtual but not physical draft for every unit in published state. Split mongo has a physical for every unit in every state. Given that, here's a table of semantics ...
from openerp import exceptions from openerp.tools import mute_logger from psycopg2 import IntegrityError from .test_common import TestCommon class TestUnicity(TestCommon): """ This test will prove the next cases to procure the module uniqueness: - Test 1: Can't be created two Serial Numbers with the same name ...
from . import test_stock_location_empty
from .item_status import * # noqa
from __future__ import print_function import re import os import sys import shutil import tempfile import argparse from llnl.util.filesystem import working_dir, mkdirp import spack from spack.util.executable import which description = "runs source code style checks on Spack. requires flake8" section = "developer" level...
""" Resources: http://code.google.com/p/pybluez/ http://lightblue.sourceforge.net/ http://code.google.com/p/python-bluetooth-scanner """ from __future__ import with_statement import select import logging import bluetooth import gobject import util.misc as misc_utils _moduleLogger = logging.getLogger(__name__) class _Bl...
"""": # -*-python-*- bup_python="$(dirname "$0")/bup-python" || exit $? exec "$bup_python" "$0" ${1+"$@"} """ import glob, os, sys, tempfile from bup import options, git, bloom from bup.helpers import (add_error, debug1, handle_ctrl_c, log, progress, qprogress, saved_errors) optspec = """ bup b...
class Foo(object): def set(self, value): self.field = value def get(self): return self.field a = Foo() a.set("hello world") z = a.get() print z z a
from higgins.logger import Loggable class UPnPLogger(Loggable): log_domain = "upnp" logger = UPnPLogger()
from openturns import * TESTPREAMBLE() RandomGenerator().SetSeed(0) try : distribution = LogUniform(1.0, 2.5) size = 10000 sample = distribution.getSample(size) factory = LogUniformFactory covariance = CovarianceMatrix estimatedDistribution = factory.build(sample) print "Distribution ...
''' /******************************************************************************* * * Copyright (c) 2015 Fraunhofer FOKUS, All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Softw...
from __future__ import absolute_import from __future__ import annotations import abc from typing import FrozenSet, Sequence, Union from cbus.common import Application __all__ = ['SAL', 'BaseApplication'] class SAL(abc.ABC): """ Describes an decoder/encoder """ @abc.abstractmethod def encode(self) ->...
"""This demo program uses the interface to SNES solver for variational inequalities to solve a contact mechanics problems in FEniCS. The example considers a heavy hyperelastic circle in a box of the same size""" from dolfin import * if not has_petsc_snes(): print "DOLFIN must be compiled with PETSc version > 3....
from __future__ import unicode_literals from datetime import datetime from dateutil.relativedelta import relativedelta import time from requests.exceptions import ConnectionError, SSLError from weboob.browser.browsers import LoginBrowser, URL, need_login, StatesMixin from weboob.capabilities.base import find_object fro...
"""Funções de conversão usada pelo scraper do Itaú.""" import datetime from dateutil.parser import parse from dateutil.relativedelta import relativedelta from decimal import Decimal def date(s): """Converte strings 'DD/MM' em datetime.date. Leva em consideração ano anterior para meses maiores que o mês corrente...
from pycp2k.inputsection import InputSection from ._each421 import _each421 class _cartesian_eigs1(InputSection): def __init__(self): InputSection.__init__(self) self.Section_parameters = None self.Add_last = None self.Common_iteration_levels = None self.Filename = None ...
from distutils.core import setup setup( name='curie', version='0.1.1', author='Eric Viara', author_email='eric.viara@curie.fr', packages=['curie'], url='http://pypi.python.org/pypi/TowelStuff/', license='LICENSE.txt', description='NaviCell Python Binding', long_description=open('READ...
import random from gevent.pool import Group from base import TestCase, declares_queues from nucleon.amqp import Connection from nucleon.amqp.spec import FrameQueueDeclareOk qname = 'test%s' % (random.random(),) queues = [qname + '.%s' % (i,) for i in xrange(100)] class TestLimits(TestCase): @declares_queues(*queues...
from functools import wraps import logging import time try: from collections import OrderedDict except ImportError: try: # ordereddict available on pypi for Python < 2.7 from ordereddict import OrderedDict except ImportError: # Otherwise fall back on normal dict OrderedDict =...
import RPi.GPIO as GPIO import datetime import time import pandas as pd import logging import logging.handlers import sys logger = logging.getLogger('fridge') handler = logging.StreamHandler() fHandler = logging.FileHandler('fridge.log') formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s", "%Y-%...
from __future__ import unicode_literals from weboob.capabilities.bank import CapBankWealth, AccountNotFound, Account from weboob.capabilities.base import find_object from weboob.capabilities.profile import CapProfile from weboob.tools.backend import Module, BackendConfig from weboob.tools.value import ValueBackendPassw...
from pycp2k.inputsection import InputSection from ._dielectric_cube1 import _dielectric_cube1 from ._dirichlet_bc_cube1 import _dirichlet_bc_cube1 from ._dirichlet_cstr_charge_cube1 import _dirichlet_cstr_charge_cube1 class _implicit_psolver1(InputSection): def __init__(self): InputSection.__init__(self) ...
from distutils.core import setup setup( name='jerboa', packages=['jerboa'], # this must be the same as the name above version='0.2.1-alpha', description='', author='Matt Badger', author_email='foss@lighthouseuk.net', url='https://github.com/LighthouseUK/jerboa', # use the URL to the github...
from saddlebags.HlaSequence import HlaSequence import logging class SubmissionBatch(): def __init__(self, includeInitialSubmission): if(includeInitialSubmission): # Starting with a single empty submission in the batch. self.submissionBatch = [AlleleSubmission()] else: ...
import webapp2 from boilerplate import models from boilerplate import forms from boilerplate.handlers import BaseHandler from google.appengine.datastore.datastore_query import Cursor from google.appengine.ext import ndb from google.appengine.api import users as googleusers from collections import OrderedDict, Counter f...
import json class GithubException(Exception): """ Error handling in PyGithub is done with exceptions. This class is the base of all exceptions raised by PyGithub (but :class:`github.GithubException.BadAttributeException`). Some other types of exceptions might be raised by underlying libraries, for example f...
""" To be used in conjunction with: NR099910-004-10006 - Repeated lowering, OrcaFlex Gumbel Script NR099910-004-10001 - Lifting Analysis Methodology - Probabilistic Approach =============================================================================================== Version 13 Corrected bug in WriteResults()...
import re import os import os.path import sys def main(): already_found = [] url_matcher = re.compile(r'(https?://(www.)?)?((youtu.be|youtube.(com|de|ch|at))/watch\?v=[-_0-9A-Za-z]{11}|youtu.be/[-_0-9A-Za-z]{11})') backup_matcher = re.compile(r'youtu') argc = len(sys.argv) if argc == 1: whol...
from django.apps import AppConfig class CompetencesConfig(AppConfig): name = 'competences' verbose_name = "Компетенции"
import httplib2 from oauth2client.client import SignedJwtAssertionCredentials #included with the Google Apps Directory API from apiclient.discovery import build import csv def downloadUsers(domain, account, customerId): superAdmin = 'is@' + domain serviceAccount = account + '@developer.gserviceaccount.com' ...
from jinja2 import Template as Jinja2Template from atlas.providers import providers class Template(Jinja2Template): def __init__(self, *args, **kwargs): super(Template, self).__init__(*args, **kwargs) for provider in providers: self.globals[provider] = providers[provider]
__author__ = 'canderson' import os import webapp2 import jinja2 from google.appengine.ext import db template_dir = os.path.join(os.path.dirname(__file__), 'templates') env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), autoescape=True) class Handler(webapp2.RequestHandler): ...
def get_resource(filename): import pkg_resources, os return pkg_resources.resource_filename("autobot", os.path.join("data", filename))
"""Test oplog manager methods """ import itertools import re import sys import time import bson import gridfs import pymongo sys.path[0:0] = [""] from mongo_connector.doc_managers.doc_manager_simulator import DocManager from mongo_connector.locking_dict import LockingDict from mongo_connector.namespace_config import Na...
import uuid from motey.models.image import Image from motey.models.service_state import ServiceState class Service(object): """ Model object. Represent a service. A service can have multiple states, action types and service types. """ def __init__(self, service_name, images, id=uuid.uuid4().hex, sta...