content
stringlengths
4
20k
#!/usr/bin/env python3 import binascii import logging import time import uuid import socket from pykms_Structure import Structure from pykms_DB2Dict import kmsDB2Dict from pykms_PidGenerator import epidGenerator from pykms_Filetimes import filetime_to_dt from pykms_Sql import sql_initialize, sql_update, sql_update_ep...
""" Include Bokeh plots in Sphinx HTML documentation. For other output types, the placeholder text ``[graph]`` will be generated. Usage ----- The ``bokeh-plot`` directive can be used by either supplying: 1. **A path to a source file** as the argument to the directive:: .. bokeh-plot:: path/to/plot.py 2. **In...
""" Django settings for DjangoHerokuIn15 project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR...
"""Tests common to all coder implementations.""" import logging import unittest from pyflink.testing.test_case_utils import PyFlinkTestCase try: from pyflink.fn_execution import coder_impl_fast from pyflink.fn_execution.beam import beam_coder_impl_slow as coder_impl have_cython = True except ImportError:...
import sys; import re file = sys.argv[1] fileout = sys.argv[2] reader = open(file, 'r') writer = open(fileout, 'w') empty_line = '^[\s\t]*$' start_sen = '^<s' end_sen = '^</s' curr_sent = None; curr_cont = [] curr_par = None par_cont = [] for line in reader.readlines(): line = line.strip() if line.startswith('<t...
#!/usr/bin/env python3 import sys import urwid from urwid import MetaSignals from state import State class MainWindow(object): __metaclass__ = MetaSignals signals = ["keypress", "quit"] _palette = [ ('divider', 'black', 'light gray'), ('text', 'white', 'default'), ('number', 'da...
""" Module implementing the debug thread. """ import bdb import os import sys from DebugBase import * class DebugThread(DebugBase): """ Class implementing a debug thread. It represents a thread in the python interpreter that we are tracing. Provides simple wrapper methods around bdb for the 'ow...
from __future__ import unicode_literals import locale import time import curses import random from collections import namedtuple import sys PYTHON2 = sys.version_info.major < 3 locale.setlocale(locale.LC_ALL, '') encoding = locale.getpreferredencoding() #################################################################...
# pylint: disable=E1103, E1101 import copy import logging import re from datetime import datetime from pytz import UTC from django.conf import settings from django.utils.translation import ugettext as _ from django.core.urlresolvers import reverse from django_comment_common.models import assign_default_role from djan...
import os import sys import shutil import tempfile import traceback from .util import ( initialize_chain, assert_equal, start_nodes, connect_nodes_bi, sync_blocks, sync_mempools, stop_nodes, wait_flurbods, enable_coverage, check_json_precision, initialize_chain_clean, ) fro...
import array import struct import binascii import ctypes import socket import time import os from Message import Message __author__ = "Alexandre Magno" __version__ = "0.1" __date__ = "2016-dec-08" class Aeronave(object): def __init__(self): # endereco icao # ------------------------------...
import datetime import functools from passlib.context import CryptContext from sqlalchemy.orm.exc import NoResultFound from zope.interface import implementer from warehouse.accounts.interfaces import IUserService from warehouse.accounts.models import Email, User @implementer(IUserService) class DatabaseUserService:...
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import podium_api from podium_api.types.lap import get_lap_from_json from podium_api.laps import make_lap_get, make_laps_get from podium_api.types.token import PodiumToken from mock import patch, Mock try: from urllib.parse import urlencode exc...
# -*- coding: utf-8 -*- """aggdb related functions""" # Copyright 2013 Sergej Alikov # This file is part of IPhistdb. # IPhistdb 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 Lice...
from gnuradio import gr from gnuradio import modulation_utils from math import pi import numpy from pprint import pprint import inspect # default values (used in __init__ and add_options) _def_samples_per_symbol = 2 _def_bits_per_symbol = 1 _def_h_numerator = 1 _def_h_denominator = 2 _def_cpm_type = 0 # 0=CPFSK, 1=GMS...
# -*- coding: utf-8 -*- from pytest import raises # The parametrize function is generated, so this doesn't work: # # from pytest.mark import parametrize # import pytest parametrize = pytest.mark.parametrize from plexfix import metadata from plexfix.main import main class TestMain(object): @parametrize('help...
from FdfParserLite import FdfParser from Table.TableFdf import TableFdf from CommonDataClass.DataClass import MODEL_FILE_FDF, MODEL_PCD, MODEL_META_DATA_COMPONENT from String import NormPath ## FdfObject # # This class defined basic Fdf object which is used by inheriting # # @param object: Inherited fr...
import numpy as np import pandas as pd import tensorflow as tf import os import skimage.io as imageio import skimage.color as color import skimage.transform as trf import collections imageio.use_plugin('matplotlib') from ipywidgets import FloatProgress from IPython.display import display import time import sqlalchem...
#!/usr/bin/env python import argparse import subprocess import sys import rospy from sensor_msgs.msg import Joy from geometry_msgs.msg import TwistStamped from uav_abstraction_layer.srv import TakeOff, GoToWaypoint, Land import time class StateMachine: def __init__(self): rospy.init_node('joy_control') ...
import re # # MARKDOWN TO HTML # try: import misaka misakaExt = misaka.EXT_AUTOLINK | misaka.EXT_NO_INTRA_EMPHASIS | misaka.EXT_FENCED_CODE misakaRender = misaka.HTML_SKIP_STYLE | misaka.HTML_SMARTYPANTS supportsMarkdown = True except: supportsMarkdown = False def markdownToHtml(markdownStr): ...
from .logger import log from .htcondor_object_base import HTCondorObjectBase from .exceptions import CircularDependency class Node(object): """ """ def __init__(self, job, parents=None, children=None, pre_script=None, pre_script_args=N...
""" Utility functions. @package bridgecut @author Aaron Zampaglione <<EMAIL>> @copyright 2011 Aaron Zampaglione @license MIT """ def combinations(iterable, r): # combinations('ABCD', 2) --> AB AC AD BC BD CD # combinations(range(4), 3) --> 012 013 023 123 pool = tuple(iterable) n = len(pool) if r >...
#!/usr/bin/python """ The drivel server program. This program contains the drivel server class. It also contains a certain amount of cowpath paving for running a drivel server. """ from __future__ import with_statement from collections import defaultdict import gc import logging import os import mimetypes import pp...
# encoding: utf-8 """ error.py Created by Thomas Mangin on 2013-07-11. Copyright (c) 2013-2015 Exa Networks. All rights reserved. """ import errno class error: block = set(( errno.EINPROGRESS, errno.EALREADY, errno.EAGAIN, errno.EWOULDBLOCK, errno.EINTR, errno.EDEADLK, errno.EBUSY, errno.ENOBUFS, errno.E...
from __future__ import division, print_function # Python 3 compatibility import numpy as np import pandas as pd from osgeo import gdal from .miscellaneous import progress_bar, makeblock # Accuracy_indices def accuracy_indices(pred, obs): """Compute accuracy indices. Compute the Overall Accuracy, the Figure ...
# creates a polygonoal buffer in geojson format given ... # xin,yin = centre point # radius = buffer radius # npoints = number of points (e.g. 3 for triangle, 6 for hex, Inf. for circle, etc.) import math import matplotlib.pyplot as plt def buffer(xin,yin,radius,npoints): x = [] y = [] coords = [] a...
import six import inspect import pecan import pecan.rest import pecan.routing from designate import exceptions from designate import api from designate.openstack.common import log as logging from designate.openstack.common.gettextutils import _ LOG = logging.getLogger(__name__) class RestController(pecan.rest.RestCo...
""" Dailymotion OAuth2 support. This adds support for Dailymotion OAuth service. An application must be registered first on dailymotion and the settings DAILYMOTION_CONSUMER_KEY and DAILYMOTION_CONSUMER_SECRET must be defined with the corresponding values. User screen name is used to generate username. By default ac...
""" Support for Vera switches. Configuration: To use the Vera lights you will need to add something like the following to your config/configuration.yaml switch: platform: vera vera_controller_url: http://YOUR_VERA_IP:3480/ device_data: 12: name: My awesome switch exclude: t...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Usage: Install py2exe: http://sourceforge.net/projects/py2exe/files/ Copy script to the web2py directory c:\bin\python26\python build_windows_exe.py py2exe Adapted from http://bazaar.launchpad.net/~flavour/sahana-eden/trunk/view/head:/static/scrip...
from openerp import models, fields, api, tools, _ import openerp.addons.decimal_precision as dp class PricelistOffer(models.Model): _name = 'product.pricelist.item.offer' name = fields.Char(string='Offer Name') paid_qty = fields.Integer(string='Paid quantity') free_qty = fields.Integer(string='Free q...
#!/usr/bin/env python2.7 """ This script runs a small number of unit tests. """ # Copyright 2015 Mayer Analytics Ltd. # # This file is part of pySX127x. # # pySX127x is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public # License as published by the Free Software ...
from unittest import TestCase from twisted.test import proto_helpers from twistedlilypad.protocol import LilypadProtocol from twistedlilypad.packets import * try: from unittest.mock import Mock except ImportError: from mock import Mock KEEP_ALIVE_PACKET = PacketKeepAlive(1239812) KEEP_ALIVE_STRING = b'\x05\x...
character_data = { 'player_name': 'Test Player', 'character_name': 'Test Character', 'background': "A Character's background", 'race': 'Human', 'alignment': 'TN', 'experience_points': 500, 'max_hit_points': 10, 'current_hit_points': 8, 'temporary_hit_points': 6, 'armor_class': 12...
""" Exposes regular REST commands as services. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/hassio/ """ import asyncio import logging import os import aiohttp import async_timeout from homeassistant.components.http import ( CONF_API_PASSWORD, CON...
"""find-fix.py: produce a find/fix report for Subversion's IZ database For simple text summary: find-fix.py query-set-1.tsv YYYY-MM-DD YYYY-MM-DD Statistics will be printed for bugs found or fixed within the time frame. For gnuplot presentation: find-fix.py query-set-1.tsv outfile Gnuplot provides its o...
import unittest import numpy import chainer from chainer import cuda from chainer import gradient_check from chainer import links from chainer import testing from chainer.testing import attr def _sigmoid(x): xp = cuda.get_array_module(x) half = x.dtype.type(0.5) return xp.tanh(x * half) * half + half ...
from annotators.conf import TITLE_TO_ID, ENDPOINTS from utils.html import check_json_response, post_request from utils.text import remove_illegal_chars from utils.store import get_wiki_store from utils.logger import get_logger logger = get_logger() wiki_id_db = get_wiki_store(TITLE_TO_ID["spotlight"]) def get_entit...
__author__ = 'Serge Poltavski' from unittest import TestCase, expectedFailure from pddoc.pd.pdexporter import * from pddoc.pd.parser import * import difflib class TestPdExporter(TestCase): def setUp(self): self._exp = PdExporter() self._parser = Parser() c = Canvas(0, 0, 100, 100) ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import wagtail.wagtailimages.utils.validators import wagtail.wagtailimages.models import taggit.managers from django.conf import settings import wagtail.wagtailadmin.taggable class Migration(migrations.Migration)...
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import csv from datetime import date, timedelta from django.core.paginator import Paginator, InvalidPage, EmptyPage from django.http import HttpResponse, HttpResponseNotAllowed, HttpResponseServerError, HttpResponseRedirect from django.template import RequestContext f...
""" Unit tests for TEM calculator. """ import unittest import numpy as np import pandas as pd import plotly.graph_objs as go from pymatgen.analysis.diffraction.tem import TEMCalculator from pymatgen.core.lattice import Lattice from pymatgen.core.structure import Structure from pymatgen.util.testing import PymatgenTe...
import time import cotyledon from oslo_config import cfg from oslo_log import log import oslo_messaging from stevedore import named from ceilometer.i18n import _ from ceilometer import messaging LOG = log.getLogger(__name__) OPTS = [ cfg.BoolOpt('ack_on_event_error', default=True, ...
#!/usr/bin/python2 import Tkinter from Tkinter import * import tkMessageBox import random import numpy class matrix: def __init__( self, data=None ): if data : self.data = data self.obj = numpy.matrix( self.data ) #self.rank = numpy.linalg.matrix_rank( self.obj.getA ) #self.det = numpy.linal...
import argparse from em import BANGPATH_OPT from em import Hook import sys from ros_buildfarm.argument import add_argument_arch from ros_buildfarm.argument import add_argument_build_name from ros_buildfarm.argument import add_argument_config_url from ros_buildfarm.argument import add_argument_os_code_name from ros_bui...
""" Solve a SAT problem by truth-table enumeration with pruning and unit propagation. """ ## solve([]) #. {} ## solve([[]]) ## solve([[1]]) #. {1: True} ## solve([[1,-2], [2,-3], [1,3]]) #. {1: True, 2: False, 3: False} import sat from sat import assign def solve(problem): "Return a satisfying assignment for pro...
"""Tests for cache_util.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # Dependency imports from absl.testing import parameterized import tensorflow.compat.v2 as tf from tensorflow_probability.python.internal import cache_util from tensorflow_probabi...
from __future__ import print_function, unicode_literals from sickbeard import logger, tvcache from sickbeard.bs4_parser import BS4Parser from sickrage.helper.common import try_int from sickrage.providers.torrent.TorrentProvider import TorrentProvider class HorribleSubsProvider(TorrentProvider): # pylint: disable=t...
import edi def test_command_line_interface_setup(empty_config_file): parser = edi._setup_command_line_interface() assert 'embedded development infrastructure' in parser.description args = parser.parse_args(['-v', 'lxc', 'configure', 'some-container', empty_config_file]) assert args.command_name == 'lx...
""" 26. Remove Duplicates from Sorted Array Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this in place with constant memory. For example, Given input array nums = [1,1,2], Your func...
""" Convert a set of reactions to a list of roles """ import os import sys import argparse import PyFBA from PyFBA import log_and_message def convert_reactions_to_roles(): """ Parse the arguments and start the gapfilling. """ orgtypes = ['gramnegative', 'grampositive', 'microbial', 'mycobacteria', ...
import json from django.contrib.auth.decorators import login_required from django.utils import timezone from approver.forms import QuestionForm from approver.workflows import project_crud, approve_workflow import approver.utils as utils @login_required def approve(request, project_id=None): context = { ...
import sqlalchemy from heat.db.sqlalchemy import types as heat_db_types def upgrade(migrate_engine): meta = sqlalchemy.MetaData() meta.bind = migrate_engine resources = sqlalchemy.Table('resource', meta, autoload=True) properties_data = sqlalchemy.Column('properties_data', heat_db_types.Json) pr...
# -*- coding:UTF-8 -*- # !/usr/bin/env python ######################################################################### # File Name: train_classifier3d.py # mail: <EMAIL> # Created Time: 2017年04月26日 星期三 10时27分23秒 ######################################################################### import numpy as np import cv2 i...
"""cal_heatmap_metric_to_metrics Revision ID: bf706ae5eb46 Revises: f231d82b9b26 Create Date: 2018-04-10 11:19:47.621878 """ import json from alembic import op from sqlalchemy import Column, Integer, String, Text from sqlalchemy.ext.declarative import declarative_base from superset import db Base = declarative_bas...
from robot.errors import DataError from .htmlwriter import LibdocHtmlWriter from .xmlwriter import LibdocXmlWriter def LibdocWriter(format=None): format = (format or 'HTML').upper() if format == 'HTML': return LibdocHtmlWriter() if format == 'XML': return LibdocXmlWriter() raise DataE...
from flask import render_template, flash, redirect, request, send_from_directory from app import app from .forms import sendForm, appForm import mail import json from content import render_content import requests def render_services(name, path, template): form = sendForm() service = 'null' if name: ...
import sys import util from nltk.corpus.reader.util import * from nltk.corpus.reader.api import * class ChasenCorpusReader(CorpusReader): def __init__(self, root, fileids, encoding=None, sent_splitter=None): self._sent_splitter = sent_splitter CorpusReader.__init__(self, root, fileids, encoding)...
from __future__ import unicode_literals from datetime import datetime from django.conf import settings from django.contrib import admin from django.contrib.admin import helpers from django.contrib.admin.utils import (display_for_field, flatten_fieldsets, label_for_field, lookup_field, NestedObjects) from django.c...
#!/usr/bin/env python from os.path import join, dirname from setuptools import setup directory = dirname(__file__) # Get version with open(join(directory,'semiautocount','__init__.py'),'rU') as f: exec f.readline() setup( name='semiautocount', version=VERSION, description='Count types of cell in a ...
""" Logarithmic market scoring rule market maker General cost function: C = B * ln(e^(q1/B)+e^(q2/B)) q1 is the number of outstanding BUYERS q2 is the number of outstanding SELLERS B_FACTOR is related to the market-maker's max loss for each 24-hour period. SPREAD is a constant that represents t...
"""Add flat position column Revision ID: d21933db9ad8 Revises: 8155b83242eb Create Date: 2021-02-08 16:26:37.190842 """ from alembic import op import sqlalchemy as sa import sqlalchemy.types as types import json class StringyJSON(types.TypeDecorator): """ Stores and retrieves JSON as TEXT for SQLite. F...
import spack.compiler class Nag(spack.compiler.Compiler): # Subclasses use possible names of C compiler cc_names = [] # Subclasses use possible names of C++ compiler cxx_names = [] # Subclasses use possible names of Fortran 77 compiler f77_names = ['nagfor'] # Subclasses use possible na...
import os import websocket import json import requests import logging import time logging.basicConfig(level=logging.INFO) UAA_ISSUER_URL = os.getenv('UAA_ISSUER_URL', 'https://ff2359d6-05b4-4a0f-9001-2533c77cfe9d.predix-uaa.run.aws-usw02-pr.ice.predix.io') UAA_CLIENT_ID = os.getenv('UAA_CLIENT_ID', 'ts-client1') UAA_...
# -*- coding: utf-8 -*- ''' Created on 2014��12��15�� @author: stm ''' import DebugLog import time from BaseCheck import BaseCheck from ErrorHandler import WrongOSTarget_Exception, WrongOSTargetVersion_Exception,\ TemplateNotMounted_Exception, PowerDirectorNotInstalled_Exception,\ DiskSizeNotEnoug...
from datetime import datetime from django.http import Http404 from mock import Mock, patch from nose.tools import eq_ from oneanddone.base.tests import TestCase from oneanddone.users import views from oneanddone.users.tests import UserFactory, UserProfileFactory class CreateProfileViewTests(TestCase): def setU...
""" Module misc Various things are defined here that did not fit nicely in any other module. This module is also meant to be imported by many other visvis modules, and therefore should not depend on other visvis modules. """ import sys, os import numpy as np from visvis import ssdf import OpenGL.GL as gl ## For ...
from __future__ import absolute_import, division, print_function, \ with_statement from ctypes import c_char_p, c_int, c_ulonglong, byref, \ create_string_buffer, c_void_p from miserable.crypto import util __all__ = ['ciphers'] libsodium = None loaded = False buf_size = 2048 # for salsa20 and chacha20 BLO...
#!/usr/bin/env python # The Python version of qwt-*/examples/cpuplot import os, sys from qt import * from Qwt4.Qwt import * from Qwt4.anynumpy import * class CpuStat: User = 0 Nice = 1 System = 2 Idle = 3 counter = 0 dummyValues = ( ( 103726, 0, 23484, 819556 ), ( 103783, 0, ...
import re from monty.io import zopen from pymatgen.core.lattice import Lattice from pymatgen.core.structure import Structure """ This module provides input and output from the CSSR file format. """ __author__ = "Shyue Ping Ong" __copyright__ = "Copyright 2012, The Materials Project" __version__ = "0.1" __maintainer...
from lib.secureheaders.xss import XXssProtection from lib.secureheaders.csp import ContentSecurityPolicy from lib.secureheaders.pkp import PublicKeyPins from lib.secureheaders.sts import StrictTransportSecurity from lib.secureheaders.xfo import XFrameOptions from lib.secureheaders.xcto import XContentTypeOptions from l...
from random import randint from time import sleep reward_table = [[-1 for x in range(16)] for x in range(16)] q_matrix = [[0 for x in range(16)] for x in range(16)] def set_up_reward_table(): reward_table[0][1] = 0 reward_table[0][4] = 0 reward_table[1][0] = 0 reward_table[2][3] = 0 r...
import datetime from google.cloud import storage import numpy as np import pandas as pd import torch from torch.utils.data import Dataset from torch.utils.data import DataLoader from torch.utils.data import random_split class SonarDataset(Dataset): def __init__(self, csv_file): self.dataframe = pd.read_cs...
from collections.abc import Mapping, Sequence from operator import attrgetter import typing from .logging import logger class FieldSelector: def __init__( self, tohu_items_cls: type, fields: typing.Union[typing.Sequence[str], typing.Mapping[str, str], None] = None ): self.tohu_items_cls = toh...
#!/usr/bin/env python import os import sys import simdna import simdna.simdnautil.util as util import simdna.synthetic as synthetic import simdna.simdnautil.pwm as pwm generationSettings = util.enum( allBackground="allBackground" ,singleMotif1="singleMotif1" #embeds first motif ,singleMotif2="singleMotif2...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('testreport', '0022_auto_20141218_0830'), ] operations = [ migrations.CreateModel( name='Bug', fields...
from datetime import date import unittest import os from ...workbook import Workbook from ..helperfunctions import _compare_xlsx_files class TestCompareXLSXFiles(unittest.TestCase): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.maxDiff = None ...
import copy import mock from oslo_config import cfg # XXX: actionsensor import depends on config being setup. import st2tests.config as tests_config tests_config.parse_args() import st2common.bootstrap.runnersregistrar as runners_registrar from st2actions.runners import ActionRunner from st2actions.runners.localrun...
import collections import json import logging import os import uuid import weakref from werkzeug.exceptions import NotFound from werkzeug.routing import Map, Rule from werkzeug.serving import run_simple from werkzeug.wrappers import Request, Response from werkzeug.wsgi import SharedDataMiddleware __all__ = ("Field", ...
from memorised.decorators import memorise from memorised.utils import uncache import unittest import memcache import uuid def unique(): return str(uuid.uuid4()) class TestModel: c = None d = None def __init__(self): self.a = None self.b = None ...
"""Module tests.""" from __future__ import absolute_import, print_function from click.testing import CliRunner from invenio_accounts.cli import roles_add, roles_create, roles_remove, \ users_activate, users_create, users_deactivate def test_cli_createuser(script_info): """Test create user CLI.""" runne...
import itertools from math import cos, sin from involute import CreateExternalGear, rotate def makeGear(m, Z, angle): w = SVGWireBuilder() CreateExternalGear(w, m, Z, angle) return '\n'.join(w.svg) class SVGWireBuilder(object): def __init__(self): self.theta = 0.0 self.pos = None ...
from argparse import ArgumentParser # argparse by default will exit when there is an error. when spacecmd # is in an interactive shell, we don't want to exit. instead, just # raise an exception that will printed for the user to read. class SpacecmdArgumentParser(ArgumentParser): def error(self, message): ...
""" Tests For Hyper-V driver """ import random from nova import context from nova import db from nova import test from nova.virt import hyperv class HyperVTestCase(test.TestCase): """Test cases for the Hyper-V driver""" def setUp(self): super(HyperVTestCase, self).setUp() self.user_id = 'fak...
import mock import six from openstack import exceptions from openstack.orchestration.v1 import _proxy from openstack.orchestration.v1 import resource from openstack.orchestration.v1 import stack from openstack.tests.unit import test_proxy_base class TestOrchestrationProxy(test_proxy_base.TestProxyBase): def setU...
import logging import os import re import signal import subprocess import sys import tempfile from pylib.device import device_errors # pylint: disable=F0401 from telemetry.core import platform from telemetry.core.platform import profiler from telemetry.core.platform.profiler import android_profiling_helper from tele...
from . import php import regex def _x(default, lookup): return default class DefaultWordpressFilters(object): def __init__(self, shortcodes): super(DefaultWordpressFilters, self).__init__() self.wp_cockneyreplace = None self.__wptexturize_setup() self.__convert_chars_setup()...
import logging import os import re from packstack.installer.exceptions import PuppetError # TODO: Fill logger name when logging system will be refactored logger = logging.getLogger() re_color = re.compile('\x1b.*?\d\dm') re_error = re.compile( 'err:|Syntax error at|^Duplicate definition:|^Invalid tag|' '^No...
import requests import json import hashlib import time from dateutil.parser import parse from datetime import timedelta, datetime from elasticsearch import Elasticsearch es = Elasticsearch() class LastFmRequestor: def __init__(self, api_key = "", user = ""): self.api_key = api_key self.host = ...
"""Leetcode 247. Strobogrammatic Number II Medium URL: https://leetcode.com/problems/strobogrammatic-number-ii/ A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Find all strobogrammatic numbers that are of length = n. Example: Input: n = 2 Output: ["11","69...
from __future__ import annotations import asyncio import logging import json from typing import ( Any, AsyncIterator, Final, Iterable, Mapping, Set, Tuple, Union, TYPE_CHECKING, ) from aiohttp import web import aiohttp_cors from aiohttp_sse import sse_response from aiotools import ...
import re def _create_forwarder(cls, old_method, new_method): # The code for instance and class methods is identical, with # self replaced by class (not to be confused with cls argument above) def fn(self): # call e.g. setUp on all parents of the adjusted base getattr(super(cls, self), old_...
######################################################################################### # Condor.py # 10.11.2014 ######################################################################################### """ Condor.py is a DIRAC independent class representing Condor batch system. Condor objects are used as backen...
test = { 'name': 'remove', 'points': 1, 'suites': [ { 'cases': [ { 'code': r""" scm> (remove 3 nil) () """, 'hidden': False, 'locked': False }, { 'code': r""" scm> (remove 2 '(1 3 2)) (1 3) ...
#!/usr/bin/python # -*- coding: UTF-8 -*- # # Should ideally beexcluded from contributing to coverage. # import codecs import os import py_crunchCSVData as Crunch import py_makeMappings as Mappings import py_filenames as Filenames import py_prepUpload as Prep import py_listscraper as Listscraper import shutil import u...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import readthedocs.core.validators from urlparse import urlparse def migrate_url(apps, schema_editor): Domain = apps.get_model("projects", "Domain") Domain.objects.filter(count=0).delete() for domain...
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib import animation from scipy import constants def rotation_transform(axis, angle, ax = None): if ax is None: ax = plt.gca() t_scale = ax.transData t_rotate = mpl.transforms.Affine2D().rotate_deg_around(axis[0], axis[...
from odoo import api, models class ChildLifecycle(models.Model): """ Send Communication when Child Lifecycle Event is received. """ _inherit = 'compassion.child.ble' @api.model def process_commkit(self, commkit_data): ids = super(ChildLifecycle, self).process_commkit(commkit_data) for...
"""Construct variants of solvers and support code that use cupy instead of numpy""" from __future__ import absolute_import import sys import re from functools import reduce try: import importlib.util except ImportError: sys.stderr.write('The sporco.cupy subpackage is not supported under ' ...
from __future__ import division, absolute_import, print_function import copy import logging logger = logging.getLogger() class UnknownTypeException(Exception): pass class QueryParseExcpetion(Exception): pass class TermNotFoundExcpetion(Exception): pass def isString(v): return isinstance(v, str) ...