content stringlengths 4 20k |
|---|
"""
Given three integers x, y, and bound, return a list of all the powerful integers that have a value less than or equal to bound.
An integer is powerful if it can be represented as xi + yj for some integers i >= 0 and j >= 0.
You may return the answer in any order. In your answer, each value should occur at most onc... |
"""Data Retriever
This module handles the CLI for the Data retriever.
"""
import os
import sys
from retriever.engines import engine_list, choose_engine
from retriever.lib.datasets import datasets, dataset_names, license
from retriever.lib.defaults import sample_script, CITATION, SCRIPT_SEARCH_PATHS, LICENSE
from retr... |
"""Test configs for elementwise ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.compat.v1 as tf
from tensorflow.lite.testing.zip_test_utils import create_tensor_data
from tensorflow.lite.testing.zip_test_utils import make_zip_of_tes... |
from scrapy.http import Response
from scrapy.selector import XmlXPathSelector
def xmliter_lxml(obj, nodename, namespace=None):
from lxml import etree
reader = _StreamReader(obj)
tag = '{%s}%s' % (namespace, nodename) if namespace else nodename
iterable = etree.iterparse(reader, tag=tag, encoding=reade... |
#! /usr/bin/env python
# Scan MH folder, display results in window
import os
import sys
import re
import getopt
import string
import mhlib
from Tkinter import *
from dialog import dialog
mailbox = os.environ['HOME'] + '/Mail'
def main():
global root, tk, top, mid, bot
global folderbox, foldermenu, scanbox... |
import sys
from functools import wraps
__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore
if sys.version_info < (3, 6):
raise RuntimeError(
'Python versions prior to 3.6 are not supported for PyFlink [' +
str(sys.version_info) + '].')
def keyword(func):
"""
... |
"""This module is deprecated. Please use `airflow.providers.microsoft.azure.operators.azure_cosmos`."""
import warnings
# pylint: disable=unused-import
from airflow.providers.microsoft.azure.operators.azure_cosmos import AzureCosmosInsertDocumentOperator # noqa
warnings.warn(
"This module is deprecated. Please ... |
"""
BillerBiemann deconvolution algorithm
Provides a class to perform Biller and Biemann deconvolution
"""
#############################################################################
# #
# PyMS software for processing of metabolomic mass... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
# Imports =====================================================================
# Functions & classes =========================================================
def resorted(values):
"""
Sort values, but put numbers after alph... |
# -*- coding: utf-8 -*-
"""
**************
Adjacency List
**************
Read and write NetworkX graphs as adjacency lists.
Adjacency list format is useful for graphs without data associated
with nodes or edges and for nodes that can be meaningfully represented
as strings.
Format
------
The adjacency list format cons... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
import getopt
import cuitweet
import download
### Functions
def check_optlist(optlist):
option = {}
option_keys = {
"-c": "count",
"-s": "since_id",
"-m": "max_id",
"-o": "out_dir",
"-k": "key_... |
#!/usr/bin/env python2
# vim: set fileencoding=utf8
import os
import sys
from getpass import getpass
import requests
import urllib
import json
import re
import time
import argparse
import random
import md5
############################################################
# wget exit status
wget_es = {
0: "No problems ... |
# Code to instruct the computer to generate two user's dice roll values and display output to the screen.
# Input: number, an integer variable
# Output: a vertical list of randomly generated integers in the range specified.
# The above text is commentary. The actual program starts below:
import random # provide... |
"""this module contains exceptions used in the astng library
"""
__doctype__ = "restructuredtext en"
class ASTNGError(Exception):
"""base exception class for all astng related exceptions"""
class ASTNGBuildingException(ASTNGError):
"""exception class when we are unable to build an astng representation"""
c... |
# -*- coding: utf-8 -*
from east import consts
def index(array, key, start=0):
# NOTE(msdubov): No boundary check for optimization purposes.
i = start
while array[i] != key:
i += 1
return i
def match_strings(str1, str2):
"""
Returns the largest index i such that str1[:i] == str2[:i]... |
"""Register a referee's decision on a document (i.e. it is approved or
rejected) in the submission approvals database (sbmAPPROVALS).
"""
__revision__ = "$Id$"
import cgi
import os.path
from invenio.config import CFG_SITE_SUPPORT_EMAIL
from invenio.websubmit_functions.Shared_Functions import ParamFromFile
from inv... |
import pygame
from .viewer import Viewer
from .loader import Loader
class Base(pygame.sprite.Sprite):
images = {}
def __init__(self):
pygame.sprite.Sprite.__init__(self)
def init(self, type):
if not Base.images:
Base.images = {
"WHITE" : Loader.load_pixmap("assets/sprites/base0.png"),
"YELLOW" : L... |
import os, sys
from ctypes import *
up=2
def setlibpath(up):
import sys
path=os.path.normpath(os.path.split(os.path.realpath(__file__))[0]+'\..'*up)
if path not in sys.path:
sys.path.append(path)
setlibpath(up)
from haru import *
from haru.c_func import *
from haru.hpdf_errorcode im... |
import numpy #@UnresolvedImport @UnusedImport
import pyscisoft
exception = Exception
class guibean(dict):
def __init__(self):
pass
class _parameters(object):
_params = []
_str_to_params = dict()
def _register(self, param):
self._params.append(param)
self._str_to_params[str(par... |
import logging
import threading
import time
import psycopg2
import pytz
from datetime import datetime
from dateutil.relativedelta import relativedelta
import odoo
from odoo import api, fields, models, _
from odoo.exceptions import UserError, ValidationError
from odoo.tools.safe_eval import safe_eval
_logger = logging... |
"""Handles all VCS (version control) support"""
import os
import shutil
from pip.backwardcompat import urlparse, urllib
from pip.log import logger
from pip.util import (display_path, backup_dir, find_command,
rmtree, ask_path_exists)
__all__ = ['vcs', 'get_src_requirement']
class VcsSupport(... |
"""This example creates a test network.
You do not need to have a DFP account to run this example, but you do need to
have a Google account (created at http://www.google.com/accounts/newaccount
if you currently don't have one) that is not associated with any other DFP test
networks. Once this network is created, you c... |
'''test pysftp.Connection.chmod - uses py.test'''
from __future__ import print_function
# pylint: disable = W0142
# pylint: disable=E1101
from common import *
import pytest
def test_chmod_not_exist(psftp):
'''verify error if trying to chmod something that isn't there'''
with pytest.raises(IOError):
p... |
from __future__ import unicode_literals
import frappe, os, json
from frappe.modules import get_module_path, scrub_dt_dn
from frappe.utils import get_datetime_str
def import_files(module, dt=None, dn=None, force=False):
if type(module) is list:
out = []
for m in module:
out.append(import_file(m[0], m[1], m[2],... |
"""See :doc:`/specs/addresses`.
.. autosummary::
:toctree:
choicelists
Some unit test cases are
:mod:`lino.projects.min2.tests.test_addresses`.
"""
from lino.api import ad, _
class Plugin(ad.Plugin):
"The descriptor for this plugin. See :class:`lino.core.Plugin`."
verbose_name = _("Addresses")
... |
import unittest
from datetime import datetime
from unittest.mock import Mock
from airflow.models import DAG
from airflow.models.baseoperator import BaseOperator
from airflow.ti_deps.dep_context import DepContext
from airflow.ti_deps.deps.task_concurrency_dep import TaskConcurrencyDep
class TestTaskConcurrencyDep(uni... |
"""
The toplevel modules containing the core Blaze datastructures.
* Indexable
* NDArray
* NDTable
* Table
* Array
"""
import numpy as np
from operator import eq
from blaze.sources.descriptors.byteprovider import ByteProvider
from idx import Space, Subspace, Index
from datashape import DataShape... |
import logging, io
from tornado import gen
from ..requests import requests
from itchatmp.utils import retry, encode_send_dict
from itchatmp.config import SERVER_URL, COROUTINE
from itchatmp.returnvalues import ReturnValue
logger = logging.getLogger('itchatmp')
def create_qrcode(sceneData, expire=2592000, a... |
from consts.district_type import DistrictType
from models.district import District
from models.event import Event
from models.match import Match
from models.team import Team
import tba_config
class ValidationHelper(object):
"""
A collection of methods to validate model ids and return standard
error messag... |
def __getfilesystemencoding():
'''
Note: there's a copy of this method in interpreterInfo.py
'''
import sys
try:
ret = sys.getfilesystemencoding()
if not ret:
raise RuntimeError('Unable to get encoding.')
return ret
except:
try:
#Handle Jyt... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
test_names = []
test_sections = []
sample_types = []
descriptions = []
print_names = []
old_sort = []
uom = []
hand_edit = ['PaCO2','HCO3']
name_file = open('testName.txt','r')
test_section_file = open("testSections.txt",'r')
sample_type_file = open("sampleT... |
import unittest
from ctypes import *
class StructFieldsTestCase(unittest.TestCase):
# Structure/Union classes must get 'finalized' sooner or
# later, when one of these things happen:
#
# 1. _fields_ is set.
# 2. An instance is created.
# 3. The type is used as field of another Structure/Union.
... |
import json
import requests
import unittest
import Utilities
from testLogin import *
from testChat import *
from testBusquedaCandidatos import *
from testPerfil import *
# Precondiciones:
# - La base de datos del servidor no debe contener usuarios.
# - El servidor debe cumplir las especificaciones de la api.#
# - La... |
"""An example functional test
The module-level docstring should include a high-level description of
what the test is doing. It's the first thing people see when they open
the file and should give the reader information about *what* the test
is testing and *how* it's being tested
"""
# Imports should be in PEP8 orderin... |
# -*- coding: utf-8 -*-
import base64
import werkzeug
import werkzeug.urls
from openerp import http, SUPERUSER_ID
from openerp.http import request
from openerp.tools.translate import _
class contactus(http.Controller):
def generate_google_map_url(self, street, city, city_zip, country_name):
url = "http... |
from __future__ import absolute_import
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase
from django.test.utils import override_settings
from django.views.generic.base import View
from django.utils.encoding import force_str
from .models import Author, Artist
class ListViewTest... |
import time
from util import hook, http
commands_modtime = 0
commands = {}
def update_commands(force=False):
global commands_modtime, commands
if force or time.time() - commands_modtime > 60 * 60: # update hourly
h = http.get_html('http://wiki.github.com/nslater/oblique/')
lines = h.xpat... |
"""
### Example HTTP operator and sensor
"""
from airflow import DAG
from airflow.operators import SimpleHttpOperator, HttpSensor
from datetime import datetime, timedelta
import json
seven_days_ago = datetime.combine(datetime.today() - timedelta(7),
datetime.min.time())
default_args ... |
import itertools
from weboob.capabilities.housing import Query
from weboob.tools.test import BackendTest
class SeLogerTest(BackendTest):
MODULE = 'seloger'
def test_seloger(self):
query = Query()
query.area_min = 20
query.cost_max = 1000
query.cities = []
for city in s... |
from unittest import main
import simplejson
from google.protobuf.json_format import MessageToDict
from common.utils.consulhelpers import get_endpoint_from_consul
from tests.itests.test_utils import get_pod_ip, \
run_long_running_command_with_timeout
from tests.itests.voltha.rest_base import RestBase
from voltha.p... |
from django.http import HttpResponse
from django.test import RequestFactory, TestCase
from django.test.utils import override_settings
class SecurityMiddlewareTest(TestCase):
@property
def middleware(self):
from django.middleware.security import SecurityMiddleware
return SecurityMiddleware()
... |
#!/usr/bin/env python
#coding=utf-8
from toughportal.console.libs import pyforms
not_null = pyforms.notnull
is_not_empty = pyforms.regexp('.+', u"不允许为空")
is_date = pyforms.regexp('(\d{4})-(\d{2}-(\d\d))', u"日期格式:yyyy-MM-dd")
is_email = pyforms.regexp('[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$', u"email格式,比如<EMAIL>")
is_ch... |
"""Runs spaceport.io's PerfMarks benchmark."""
import logging
import os
from telemetry import benchmark
from telemetry.core import util
from telemetry.page import page_set
from telemetry.page import page_test
from telemetry.value import list_of_scalar_values
from telemetry.value import scalar
DESCRIPTIONS = {
'c... |
from __future__ import division
from __future__ import print_function
import codecs
import collections
import json
import re
import modeling
import tokenization
import tensorflow as tf
flags = tf.flags
FLAGS = flags.FLAGS
flags.DEFINE_string("input_file", None, "")
flags.DEFINE_string("output_file", None, "")
fl... |
class ModuleDocFragment(object):
# Standard files documentation fragment
DOCUMENTATION = """
options:
authorize:
description:
- B(Deprecated)
- "Starting with Ansible 2.5 we recommend using C(connection: network_cli) and C(become: yes)."
- For more information please see the L(IOS Platf... |
import pytest
from api_tests import utils as api_utils
from framework.auth.core import Auth
from osf.models import PageCounter
from osf_tests.factories import ConferenceFactory, ProjectFactory, AuthUserFactory
@pytest.mark.django_db
class TestMeetingSubmissionsDetail:
@pytest.fixture()
def meeting(self):
... |
"""
SSL with SNI_-support for Python 2. Follow these instructions if you would
like to verify SSL certificates in Python 2. Note, the default libraries do
*not* do certificate checking; you need to do additional work to validate
certificates yourself.
This needs the following packages installed:
* pyOpenSSL (tested w... |
# encoding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from .brightcove import BrightcoveLegacyIE
from .discovery import DiscoveryIE
from ..compat import compat_urlparse
class TlcIE(DiscoveryIE):
IE_NAME = 'tlc.com'
_VALID_URL = r'http://www\.tlc\.com\/[a-zA-Z0-... |
from openerp.osv import fields, osv
from openerp import tools
class sale_report(osv.osv):
_inherit = "sale.report"
_columns = {
'shipped': fields.boolean('Shipped', readonly=True),
'shipped_qty_1': fields.integer('Shipped', readonly=True),
'warehouse_id': fields.many2one('stock.warehous... |
"""Training data conversion for FelixInsert.
Source-target text pairs will be converted to (source) token-level edit
operations and token-level insertions.
"""
from typing import List, Optional, Sequence, Tuple
from felix import felix_constants as constants
from felix import phrase_vocabulary_optimization_utils as p... |
import unittest
import os
import bslint
import bslint.messages.handler as msg_handler
import bslint.messages.error_constants as err_const
from tests.resources.common.test_methods import CommonMethods as Common
from filepaths import BSLINT_COMMAND_CONFIG_PATH
from filepaths import TEST_CONFIG_FILE_PATH
class TestSkipF... |
"""
Tests to cover bulk create and update using serializers.
"""
from __future__ import unicode_literals
from django.test import TestCase
from django.utils import six
from rest_framework import serializers
class BulkCreateSerializerTests(TestCase):
"""
Creating multiple instances using serializers.
"""
... |
"""Utilities for mongo-connector tests. There are no actual tests in here.
"""
import time
def wait_for(condition, max_tries=60):
"""Wait for a condition to be true up to a maximum number of tries
"""
while not condition() and max_tries > 1:
time.sleep(1)
max_tries -= 1
return conditi... |
"""Preview for Zinnia"""
from __future__ import division
from django.utils import six
from django.utils.text import Truncator
from django.utils.html import strip_tags
from django.utils.functional import cached_property
from django.utils.encoding import python_2_unicode_compatible
from bs4 import BeautifulSoup
from z... |
from tempest.api.compute import base
from tempest.common import compute
from tempest.lib import decorators
class MultipleCreateTestJSON(base.BaseV2ComputeTest):
@decorators.idempotent_id('61e03386-89c3-449c-9bb1-a06f423fd9d1')
def test_multiple_create(self):
tenant_network = self.get_tenant_network()... |
PADDING = 10
def get_partner_type(partner):
"""Get partner type for relation.
:param partner: a res.partner either a company or not
:return: 'c' for company or 'p' for person
:rtype: str
"""
return 'c' if partner.is_company else 'p'
from . import res_partner
from . import res_partner_relati... |
"""
The contents of this file are taken from
[Django-admin](https://github.com/niwinz/django-jinja/blob/master/django_jinja/management/commands/makemessages.py)
Jinja2's i18n functionality is not exactly the same as Django's.
In particular, the tags names and their syntax are different:
1. The Django ``trans`` tag ... |
import logging
import os
import shutil
import tempfile
import unittest
from telemetry.core import browser_finder
from telemetry.core import extension_to_load
from telemetry.core.chrome import extension_dict_backend
from telemetry.unittest import options_for_unittests
class ExtensionTest(unittest.TestCase):
def setU... |
"""Neural network support.
See the [Neural network](https://tensorflow.org/api_guides/python/nn) guide.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys as _sys
# pylint: disable=unused-import
from tensorflow.python.ops import ctc_ops as _ctc... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'certified'}
DOCUMENTATION = r'''
---
module: bigip_traffic_selector
short_description: Manage IPSec Traf... |
# -*- coding: utf-8 -*-
import argparse
import re
from . import core
class Command(core.Command):
def call(self, args):
if args.artist:
self.__call_artist(args.artist, args.dry)
elif args.album:
self.__call_album(args.album, args.dry)
elif args.genre:
... |
{
'name': 'Manufacturing Operations',
'version': '1.0',
'category': 'Manufacturing',
'description': """
This module adds state, date_start, date_stop in manufacturing order operation lines (in the 'Work Orders' tab).
=======================================================================================... |
from distutils import core
from distutils import errors
import logging
import os
import sys
import warnings
from pbr import util
if sys.version_info[0] == 3:
string_type = str
integer_types = (int,)
else:
string_type = basestring # flake8: noqa
integer_types = (int, long) # flake8: noqa
def pbr(d... |
import sys
import numpy as np
from agents import CheapAgent, RandomAgent
from Agent_spamu import Agent_spamu #addition
from product import Product
if __name__ == '__main__':
data_path = "./datasets/"
data_group = "dataset1"
# if you like, you can read the data_path and data_group using sys.argv
... |
VERSION = [1, 3, 0]
from .aes import AES, AESModeOfOperationCTR, AESModeOfOperationCBC, AESModeOfOperationCFB, AESModeOfOperationECB, AESModeOfOperationOFB, AESModesOfOperation, Counter
from .blockfeeder import decrypt_stream, Decrypter, encrypt_stream, Encrypter
from .blockfeeder import PADDING_NONE, PADDING_DEFAULT |
import re
from .compat import to_bytes
from .misc import NON_PCT_ENCODED
def normalize_scheme(scheme):
return scheme.lower()
def normalize_authority(authority):
userinfo, host, port = authority
result = ''
if userinfo:
result += normalize_percent_characters(userinfo) + '@'
if host:
... |
import datetime
import requests
from lxml import etree
from cloudbot import hook
# security
parser = etree.XMLParser(resolve_entities=False, no_network=True)
base_url = "http://thetvdb.com/api/"
def get_episodes_for_series(series_name, api_key):
res = {"error": None, "ended": False, "episodes": None, "name": ... |
from browser import html, document, window
import javascript
#memorize/cache?
def _get_value(other):
if isinstance(other, LongInt):
return other.value
return other
class BigInt:
def __init__(self):
pass
def __abs__(self):
return LongInt(self.value.abs())
def __add__(self, other):
... |
from __future__ import unicode_literals
from copy import deepcopy
PLUGIN_INFO = {
"name": "test plugin",
"author": "test author",
"version": "1.0",
"module": "test.TestPlugin",
"media_types": [
"application/x-widget+mashable-application-component",
"application/x-mashup+mashable-application-compo... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
BatchInputSelectionPanel.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
**************... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.template.defaultfilters import truncatechars_html
from django.test import SimpleTestCase
class FunctionTests(SimpleTestCase):
def test_truncate_zero(self):
self.assertEqual(truncatechars_html('<p>one <a href="#">two - three <br>... |
"""
Generate an hourglass graph using the Graphviz generator.
"""
#------------------------------------------------------------------------
#
# python modules
#
#------------------------------------------------------------------------
#------------------------------------------------------------------------
#
# Gprime... |
'''OpenGL extension ARB.texture_rgb10_a2ui
This module customises the behaviour of the
OpenGL.raw.GL.ARB.texture_rgb10_a2ui to provide a more
Python-friendly API
Overview (from the spec)
This extension adds support for the following data format:
A new texturing format for unsigned 10.10.10.2 integer textures.... |
"""Entry point to manage all content of my website.
Mainly base classes to be inherited by website's components.
"""
import logging
from abc import ABC, abstractmethod
from contextlib import AbstractAsyncContextManager
from dataclasses import dataclass
from pathlib import Path, PurePath
from typing import Callable, C... |
import sys
import functools
import ldb
def _recursive_encode(obj):
if isinstance(obj, bytes):
return obj
elif isinstance(obj, str):
return obj.encode('utf-8')
else:
return [_recursive_encode(o) for o in obj]
class _WrapBase(object):
@classmethod
def _wrap(cls, wrapped):... |
from airflow.sensors.base_sensor_operator import BaseSensorOperator
from airflow.utils import timezone
from airflow.utils.decorators import apply_defaults
class TimeDeltaSensor(BaseSensorOperator):
"""
Waits for a timedelta after the task's execution_date + schedule_interval.
In Airflow, the daily task st... |
'''This is a custom layout for the RPi InfoScreen wordclock screen.
Custom layouts can be created for the screen by creating a new file in the
"layouts" folder.
Each layout must have the following variables:
LAYOUT: The grid layout. Must be a single string.
MAP: The mapping required... |
r"""Utilities to compile possibly incomplete Python source code.
This module provides two interfaces, broadly similar to the builtin
function compile(), that take progam text, a filename and a 'mode'
and:
- Return a code object if the command is complete and valid
- Return None if the command is incomplete
- Raise Sy... |
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
import os
import shutil
class MerkleBlockTest(BitcoinTestFramework):
def setup_chain(self):
print("Initializing test directory "+self.options.tmpdir)
initialize_chain_clean(self.options.tmpdir, 4)
... |
"""
Current-flow betweenness centrality measures.
"""
# Copyright (C) 2010-2012 by
# Aric Hagberg <<EMAIL>>
# Dan Schult <<EMAIL>>
# Pieter Swart <<EMAIL>>
# All rights reserved.
# BSD license.
import random
import networkx as nx
from networkx.algorithms.centrality.flow_matrix import *
__author__ = ""... |
# encoding: utf-8
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 field 'Feed.has_page'
db.add_column('feeds', 'has_page', self.gf('django.db.models.fields.Boolean... |
import logging
from airflow.exceptions import AirflowException
from airflow.hooks import HttpsHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class SimpleHttpsOperator(BaseOperator):
"""
Calls an endpoint on an HTTPS system to execute an action
:param htt... |
#!/usr/bin/env python
from __future__ import division
__author__ = "Jai Ram Rideout"
__copyright__ = "Copyright 2012, The QIIME project"
__credits__ = ["Jai Ram Rideout"]
__license__ = "GPL"
__version__ = "1.9.1-dev"
__maintainer__ = "Jai Ram Rideout"
__email__ = "<EMAIL>"
"""Contains functionality to interact with r... |
import markdown
import glob
import os
import re
import sys
class ObjParser(object):
def __init__(self, filename):
self.positions = []
self.normals = []
self.texcoords = []
self.out_positions = []
self.out_normals = []
self.out_texcoords = []
file = open(filename, "r")
lines = file.... |
from __future__ import unicode_literals
from django.contrib.gis.db.models import F, Collect, Count, Extent, Union
from django.contrib.gis.geometry.backend import Geometry
from django.contrib.gis.geos import GEOSGeometry, MultiPoint, Point
from django.db import connection
from django.test import TestCase, ignore_warnin... |
import re
import time
from openerp import tools
from openerp.osv import fields, osv
from openerp.tools import float_round, float_is_zero, float_compare
from openerp.tools.translate import _
CURRENCY_DISPLAY_PATTERN = re.compile(r'(\w+)\s*(?:\((.*)\))?')
class res_currency(osv.osv):
def _current_rate(self, cr, ui... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from os.path import join
import re
from urllib import unquote
from base64 import standard_b64decode
from binascii import unhexlify
from bottle import route, request, HTTPError
from webinterface import PYLOAD, DL_ROOT, JS
try:
from Crypto.Cipher import AES
except:
... |
"""CherryPy is a pythonic, object-oriented HTTP framework.
CherryPy consists of not one, but four separate API layers.
The APPLICATION LAYER is the simplest. CherryPy applications are written as
a tree of classes and methods, where each branch in the tree corresponds to
a branch in the URL path. Each method is a 'pa... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.che... |
#!python
# Retrieving absorbing boundaries.
# P. Galvez (ETH-Zurich, 10.09.2011):
# This function is based on Emmanuele Cassarotti , boundary_definition.py routine.
#
# It returns absorbing_surf,absorbing_surf_xmin,absorbing_surf_xmax,
# absorbing_surf_ymin,absorbing_surf_ymax,absorbing_surf_bottom,top... |
"""Tkinker gui for pylint"""
from __future__ import print_function
import os
import sys
import re
from threading import Thread
import six
from six.moves.tkinter import (
Tk, Frame, Listbox, Entry, Label, Button, Scrollbar,
Checkbutton, Radiobutton, IntVar, StringVar, PanedWindow,
TOP, LEFT, RIGHT, BOTTOM... |
from math import sqrt
@staticmethod
def sim_distance(p1, p2):
"""Returns a distance-based similarity score for p1 and p2"""
# Get the list of shared_items
si = [item for item in p1 if item in p2]
if len(si) != 0:
squares = [pow(p1[item] - p2[item], 2) for item in si]
# Add up the squa... |
from test.test_support import run_unittest, have_unicode
import unittest
import sys
class TestImplementationComparisons(unittest.TestCase):
def test_type_comparisons(self):
self.assertTrue(str < int or str > int)
self.assertTrue(int <= str or int >= str)
self.assertTrue(cmp(int, str) != 0)... |
"""Creates the Bazel source distribution archive."""
import contextlib
import os.path
import sys
import zipfile
from src.create_embedded_tools_lib import copy_tar_to_zip
from src.create_embedded_tools_lib import copy_zip_to_zip
def main():
output_zip = os.path.join(os.getcwd(), sys.argv[1])
input_files = sorted... |
data = (
'ggyeols', # 0x00
'ggyeolt', # 0x01
'ggyeolp', # 0x02
'ggyeolh', # 0x03
'ggyeom', # 0x04
'ggyeob', # 0x05
'ggyeobs', # 0x06
'ggyeos', # 0x07
'ggyeoss', # 0x08
'ggyeong', # 0x09
'ggyeoj', # 0x0a
'ggyeoc', # 0x0b
'ggyeok', # 0x0c
'ggyeot', # 0x0d
'ggyeop', # 0x0e
'ggy... |
import os
import warnings
from collections import Counter, OrderedDict
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils import lru_cache
from django.utils._os import upath
from django.utils.deprecation import RemovedInDjango20Warnin... |
import logging
from formulas import Temperature
from slipnet import slipnet
class CoderackPressure(object):
def __init__(self, name):
self.name = name
def reset(self):
self.unmodifedValues = []
self.values = []
self.codelets = []
def _codelet_index(codelet):
name_indices... |
"""unittest (test_util_test.py) for test_util.py"""
import sys
import os
import tempfile
import unittest as U
from gramps.gen.constfunc import get_env_var
usage_note="""
**************************************************************
Testing (and runing) Gramps requires that PYTHONPATH include
the path to the to... |
# The Python ISAPI package.
# Exceptions thrown by the DLL framework.
class ISAPIError(Exception):
def __init__(self, errno, strerror = None, funcname = None):
# named attributes match IOError etc.
self.errno = errno
self.strerror = strerror
self.funcname = funcname
Exceptio... |
'''
Progress class for modules. Represents where a student is in a module.
Useful things to know:
- Use Progress.to_js_status_str() to convert a progress into a simple
status string to pass to js.
- Use Progress.to_js_detail_str() to convert a progress into a more detailed
string to pass to js.
In particular... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.