content string |
|---|
#
# euc_jis_2004.py: Python Unicode Codec for EUC_JIS_2004
#
# Written by Hye-Shik Chang <<EMAIL>>
#
import _codecs_jp, codecs
import _multibytecodec as mbc
codec = _codecs_jp.getcodec('euc_jis_2004')
class Codec(codecs.Codec):
encode = codec.encode
decode = codec.decode
class IncrementalEncoder(mbc.Multiby... |
{
'name': "Flask middleware connector",
'version': '1.0',
'category': 'Connector',
'description': """Connect to Visiotech flask middleware using Odoo connector""",
'author': 'Comunitea',
'website': 'www.comunitea.com',
"depends": ['base', 'product', 'connector', 'stock', 'custom_partner', 'c... |
DATE_FORMAT = 'j. E Y'
TIME_FORMAT = 'G:i:s'
DATETIME_FORMAT = 'j. E Y G:i:s'
YEAR_MONTH_FORMAT = 'F Y'
MONTH_DAY_FORMAT = 'j. F'
SHORT_DATE_FORMAT = 'd.m.Y'
SHORT_DATETIME_FORMAT = 'd.m.Y G:i:s'
FIRST_DAY_OF_WEEK = 1 # Monday
# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see http://docs.pytho... |
from django.conf.urls import patterns, url
from cyclope.views import ContentDeleteView
urlpatterns = patterns(
'',
url(r'^(?P<content_type>contact)/(?P<slug>[\w-]+)/delete/$', ContentDeleteView.as_view(), {'app': 'contacts'}, name='contacts-delete'),
) |
from theano import shared, tensor
from blocks.bricks import Feedforward
from blocks.bricks.base import application, lazy
from blocks.extras.initialization import PermutationMatrix
from blocks.extras.utils import check_valid_permutation
from blocks.utils import shared_floatx
class FixedPermutation(Feedforward):
""... |
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
def satoshi_round(amount):
return Decimal(amount).quantize(Decimal('0.00000001'), rounding=ROUND_DOWN)
class MempoolPackagesTest(BitcoinTestFramework):
def setup_network(self):
self.nodes = []
se... |
import esp
class FlashBdev:
SEC_SIZE = 4096
START_SEC = esp.flash_user_start() // SEC_SIZE
NUM_BLK = 0x6b
def __init__(self, blocks=NUM_BLK):
self.blocks = blocks
def readblocks(self, n, buf):
#print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf)))
esp.flash_read((n + s... |
'''
Bubble
======
.. versionadded:: 1.1.0
.. image:: images/bubble.jpg
:align: right
The Bubble widget is a form of menu or a small popup where the menu options
are stacked either vertically or horizontally.
The :class:`Bubble` contains an arrow pointing in the direction you
choose.
Simple example
------------... |
import os
import mock
from oslo.config import cfg
from neutron.common import config # noqa
from neutron.tests import base
class ConfigurationTest(base.BaseTestCase):
def setup_config(self):
# don't use default config
pass
def test_defaults(self):
self.assertEqual('0.0.0.0', cfg.CO... |
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import matplotlib.pyplot as plot
import numpy
from numpy.polynomial.polynomial import polyfit,polyadd,Polynomial
import yaml
INCHES_PER_ML = 0.078
VOLTS_PER_ADC_UNIT = 0.0049
def load_numpy_data(path):
with open(path,'r') as fid:
hea... |
from base import BaseService
from shopify_app.models import PlanConfig
from django.conf import settings
from shopify_app.config import DEFAULTS
from datetime import datetime
from shopify_api import APIWrapper
class PlanConfigService(BaseService):
entity = PlanConfig
def _get_charge_common_data(self, shop, p... |
{
'name': 'Turkey - Accounting',
'version': '1.beta',
'category': 'Localization/Account Charts',
'description': """
Türkiye için Tek düzen hesap planı şablonu OpenERP Modülü.
==========================================================
Bu modül kurulduktan sonra, Muhasebe yapılandırma sihirbazı çalışır
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
from ansible.compat.tests.mock import patch
from ansible.modules.network.nxos import nxos_command
from .nxos_module import TestNxosModule, load_fixture, set_module_args
class TestNxosCommandModule(TestNxosModule):
... |
#!/usr/bin/env python
import sys
sys.dont_write_bytecode = True
import glob
import yaml
import json
import os
import sys
import time
import logging
from argparse import ArgumentParser
from slackclient import SlackClient
def dbg(debug_string):
if debug:
logging.info(debug_string)
USER_DICT = {}
class R... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from unv2x import *
from abaqus2x import *
from oofemctrlreader import *
import time
from numpy.core.defchararray import splitlines
if __name__=='__main__':
helpmsg="""
Usage: unv2oofem.py unvfile ctrlfile oofemfile
What it does: read unvfile, create an internal FEM obje... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
# http://binux.me
# Created on 2014-12-04 22:33:43
import re
import six
import time
import json
import sqlalchemy.exc
from sqlalchemy import (create_engine, MetaData, Table, Column, Index,
... |
import re
import fileinput
import sys # for exit
import subprocess
def insert(d):
path = d['Path']
del d['Path']
print "inserting " + path
content = d['Password'] + "\n"
del d['Password']
for k, v in d.iteritems():
content += "%s: %s\n" % (k, v)
del d
cmd = ["pass", "insert", ... |
"""Batch
Batches
=======
Batches allow you to optimize the number of gl calls using pyglets batch
"""
from __future__ import division, print_function, unicode_literals
__docformat__ = 'restructuredtext'
import pyglet
from pyglet.gl import *
from cocos.cocosnode import CocosNode
__all__ = ['BatchNode', 'Batchabl... |
from __future__ import unicode_literals
import unittest
import frappe
test_records = frappe.get_test_records('Bom')
class TestBOM(unittest.TestCase):
def test_get_items(self):
from erpnext.manufacturing.doctype.bom.bom import get_bom_items_as_dict
items_dict = get_bom_items_as_dict(bom="BOM/_Test FG Item 2/001",... |
import os
from ..base import CompilerCommand, CSS_PROPERTY, CSS_STATIC_DIR
class Command(CompilerCommand):
static_dir = CSS_STATIC_DIR
module_property = CSS_PROPERTY
def queue_file(self, fname, module):
return self.test_file_age(fname, ''.join([os.path.splitext(fname)[0], '.css']))
def ... |
import os
import sys
from itertools import product, starmap
import distutils.command.install_lib as orig
class install_lib(orig.install_lib):
"""Don't add compiled flags to filenames of non-Python files"""
def initialize_options(self):
orig.install_lib.initialize_options(self)
self.multiarch ... |
from gnuradio import gr, gru, audio
from gnuradio import eng_notation
from gnuradio.eng_option import eng_option
from gnuradio.wxgui import stdgui2, fftsink2, waterfallsink2, scopesink2, form, slider
from optparse import OptionParser
import wx
import sys
class app_top_block(stdgui2.std_top_block):
def __init__(sel... |
# -*- coding: utf-8 -*-
"""Script to extract documentation from docstrings in *.h files in the DOLFIN
source tree."""
# Copyright (C) 2010 Anders Logg
#
# This file is part of DOLFIN.
#
# DOLFIN is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as pub... |
from __future__ import unicode_literals
from django.test import TestCase
from django.contrib.contenttypes.models import ContentType
from waldur_core.core.models import StateMixin
from waldur_core.cost_tracking import models as cost_tracking_models
from waldur_core.structure import models as structure_models
from wald... |
from oslo_config import cfg
from oslo_db import options
from oslo_log import log
from ec2api import paths
from ec2api import version
CONF = cfg.CONF
_DEFAULT_SQL_CONNECTION = 'sqlite:///' + paths.state_path_def('ec2api.sqlite')
_DEFAULT_LOG_LEVELS = ['amqp=WARN', 'amqplib=WARN', 'boto=WARN',
... |
# Time: O(1) per move
# Space: O(s), s is the current length of the snake.
from collections import deque
class SnakeGame(object):
def __init__(self, width,height,food):
"""
Initialize your data structure here.
@param width - screen width
@param height - screen height
@pa... |
"""Test possibility of patching fftpack with pyfftw.
No module source outside of scipy.fftpack should contain an import of
the form `from scipy.fftpack import ...`, so that a simple replacement
of scipy.fftpack by the corresponding fftw interface completely swaps
the two FFT implementations.
Because this simply inspe... |
import sys
import unittest
from libcloud.utils.py3 import httplib
from libcloud.dns.drivers.godaddy import GoDaddyDNSDriver
from libcloud.test import MockHttp
from libcloud.test.file_fixtures import DNSFileFixtures
from libcloud.test.secrets import DNS_PARAMS_GODADDY
from libcloud.dns.base import Zone, RecordType
cl... |
import random
import numpy as np
from py_paddle import swig_paddle
def doubleEqual(a, b):
return abs(a - b) < 1e-5
def __readFromFile():
for i in xrange(10002):
label = np.random.randint(0, 9)
sample = np.random.rand(784) + 0.1 * label
yield sample, label
def loadMNISTTrainData(ba... |
import numpy as np
import scipy.sparse as sp
from HPOlibConfigSpace.configuration_space import ConfigurationSpace
from HPOlibConfigSpace.conditions import EqualsCondition, InCondition
from HPOlibConfigSpace.hyperparameters import UniformFloatHyperparameter, \
UniformIntegerHyperparameter, CategoricalHyperparameter... |
from django.core.exceptions import ValidationError
from django.utils.six.moves import range
from django.utils.translation import ugettext_lazy as _
def clean_ipv6_address(ip_str, unpack_ipv4=False,
error_message=_("This is not a valid IPv6 address.")):
"""
Cleans an IPv6 address string.
Validity ... |
# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
def example(request):
greek_elections = [
{ 'type': 'Pie3D',
'title': 'Greek Elections 2009',
'data': [43.92, 33.48, 7.54, 5.63, 4.60, 2.53, 2.3],
'labels': 'ΠΑΣΟΚ|ΝΔ|ΚΚΕ|ΛΑΟΣ|ΣΥΡΙΖΑ|Οικολόγοι Πράσι... |
""" Domain classes for handling parameters """
# pylint: enable=E1101
from stoqlib.database.properties import BoolCol, UnicodeCol
from stoqlib.domain.base import Domain
from stoqlib.lib.translation import stoqlib_gettext as _
class ParameterData(Domain):
""" Class to store system parameters.
See also:
... |
"""
Copyright (C) 2016 Richard Schwalk
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 i... |
from enum import Enum
from utils import i, d
Resources = Enum("CASH", "VOTE", "TRUST")
class AbstractTransaction(object):
"""Transaction interface"""
last_id = -1
player_1 = None
player_2 = None
@staticmethod
def next_id():
# @TODO thread safety?
AbstractTransaction.last_id +=... |
#!/usr/bin/python
"""
Implementation of the Hungarian (Munkres) Algorithm using Python and NumPy
References: http://www.ams.jhu.edu/~castello/362/Handouts/hungarian.pdf
http://weber.ucsd.edu/~vcrawfor/hungar.pdf
http://en.wikipedia.org/wiki/Hungarian_algorithm
http://www.public.iastate.edu/~ddot... |
'''
Data structure of the input .npz:
the data is save in python dictionary format with keys: 'acs', 'ep_rets', 'rews', 'obs'
the values of each item is a list storing the expert trajectory sequentially
a transition can be: (data['obs'][t], data['acs'][t], data['obs'][t+1]) and get reward data['rews'][t]
'''
from base... |
import os
from contextlib import contextmanager
from socorro.lib.util import FakeLogger
#--------------------------------------------------------------------------
@contextmanager
def temp_file_context(raw_dump_path, logger=None):
"""this contextmanager implements conditionally deleting a pathname
at the end... |
import os
import settings
from superdesk.factory import get_app as superdesk_app
if os.environ.get('NEW_RELIC_LICENSE_KEY'):
try:
import newrelic.agent
newrelic.agent.initialize(os.path.abspath(os.path.join(os.path.dirname(__file__), 'newrelic.ini')))
except ImportError:
pass
def ge... |
"""Utilities to evaluate models with respect to a variable
"""
#
# License: BSD 3 clause
import warnings
import numpy as np
from .base import is_classifier, clone
from .cross_validation import check_cv
from .externals.joblib import Parallel, delayed
from .cross_validation import _safe_split, _score, _fit_and_score
f... |
from __future__ import absolute_import
import re
import ctypes
import platform
import warnings
def glibc_version_string():
"Returns glibc version string, or None if not using glibc."
# ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen
# manpage says, "If filename is NULL, then the retur... |
from __future__ import print_function
import os, sys; sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
from pattern.server import App, template, threadsafe
from codecs import open
# This example demonstrates a simple wiki served by pattern.server.
# A wiki is a web app where each page can be e... |
# pylint: disable=W0703
def truncate_before(value, srch):
""" Return content of str before the srch parameters. """
before_index = value.find(srch)
if (before_index >= 0):
return value[:before_index]
else:
return value
def _set_to_get(set_cmd, module):
""" Convert set command to... |
from PIL import Image, ImageFile
_handler = None
##
# Install application-specific BUFR image handler.
#
# @param handler Handler object.
def register_handler(handler):
global _handler
_handler = handler
# --------------------------------------------------------------------
# Image adapter
def _accept(pr... |
import numpy as np
from .helpers import SeededTest
from pymc3 import glm, Model, Uniform, Normal, find_MAP, Slice, sample
# Generate data
def generate_data(intercept, slope, size=700):
x = np.linspace(-1, 1, size)
y = intercept + x * slope
return x, y
class TestGLM(SeededTest):
@classmethod
def... |
import sys
import argparse
import json
import base64
import zlib
import time
import subprocess
#
# Construct a basic firmware description
#
def mkdesc():
proto = {}
proto['magic'] = "PX4FWv1"
proto['board_id'] = 0
proto['board_revision'] = 0
proto['version'] = ""
proto['summary'] = ""
proto['description'] = ""... |
from openerp import models, fields, api
from openerp.addons import decimal_precision as dp
class ProductPricelistItem(models.Model):
_inherit = 'product.pricelist.item'
@api.one
@api.depends('product_id', 'product_tmpl_id')
def _get_uop_id(self):
if self.product_id:
self.uop_id = ... |
# -*- coding: utf-8 -*-
import sphinx.roles
import sphinx.environment
from sphinx.writers.html import HTMLTranslator
from docutils.writers.html4css1 import HTMLTranslator as DocutilsTranslator
def patch():
# navify toctree (oh god)
@monkey(sphinx.environment.BuildEnvironment)
def resolve_toctree(old_resolv... |
"""
Base classes for writing management commands (named commands which can
be executed through ``django-admin.py`` or ``manage.py``).
"""
from __future__ import unicode_literals
import os
import sys
from optparse import make_option, OptionParser
import django
from django.core.exceptions import ImproperlyConfigured
... |
import pytest
from pandas.util._validators import validate_args_and_kwargs
_fname = "func"
def test_invalid_total_length_max_length_one():
compat_args = ("foo",)
kwargs = {"foo": "FOO"}
args = ("FoO", "BaZ")
min_fname_arg_count = 0
max_length = len(compat_args) + min_fname_arg_count
actual_... |
"""Test program for the fcntl C module.
"""
import platform
import os
import struct
import sys
import unittest
from test.support import (verbose, TESTFN, unlink, run_unittest, import_module,
cpython_only)
# Skip test if no fcntl module.
fcntl = import_module('fcntl')
# TODO - Write tests fo... |
""".control - Controls."""
from AppKit import *
from Foundation import *
from objc import YES, NO, nil
from mvc.widgets import widgetconst
import wrappermap
from .base import Widget
from .helpers import NotificationForwarder
class SizedControl(Widget):
def set_size(self, size):
if size == widgetconst.SIZ... |
"""Email backend that writes messages to a file."""
import datetime
import os
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.mail.backends.console import \
EmailBackend as ConsoleEmailBackend
from django.utils import six
class EmailBackend(ConsoleEmailB... |
import os.path
from code import Code
import cpp_util
class HGenerator(object):
def Generate(self, features, source_file, namespace):
return _Generator(features, source_file, namespace).Generate()
class _Generator(object):
"""A .cc generator for features.
"""
def __init__(self, features, source_file, na... |
"""Fixer for print.
Change:
'print' into 'print()'
'print ...' into 'print(...)'
'print ... ,' into 'print(..., end=" ")'
'print >>x, ...' into 'print(..., file=x)'
No changes are applied if print_function is imported from __future__
"""
# Local imports
from .. import patcomp
from .... |
#! /usr/bin/env python
"""Test the errno module
Roger E. Masse
"""
import errno
from test import test_support
import unittest
std_c_errors = frozenset(['EDOM', 'ERANGE'])
class ErrnoAttributeTests(unittest.TestCase):
def test_for_improper_attributes(self):
# No unexpected attributes should be on the ... |
# -*- coding: utf-8 -*-
from wxgeometrie.modules.tablatex.tests.tabtestlib import assert_tableau
from wxgeometrie.modules.tablatex.tabsign import tabsign
from pytest import XFAIL
def assert_tabsign(chaine, code_latex, **options):
assert_tableau(tabsign, chaine, code_latex, **options)
def test_mode_manuel():... |
"""
Template file used by the OPF Experiment Generator to generate the actual
description.py file by replacing $XXXXXXXX tokens with desired values.
This description.py file was generated by:
'~/nupic/eng/lib/python2.6/site-packages/nupic/frameworks/opf/expGenerator/ExpGenerator.py'
"""
from nupic.frameworks.opf.expd... |
from sphinx.domains import Domain, ObjType
from sphinx.roles import XRefRole
from sphinx.domains.std import GenericObject, StandardDomain
from sphinx.directives import ObjectDescription
from sphinx.util.nodes import clean_astext, make_refnode
from sphinx.util import ws_re
from sphinx import addnodes
from sphinx.util.do... |
"""Update version of TensorFlow script."""
# pylint: disable=superfluous-parens
import argparse
import fileinput
import os
import re
import subprocess
import time
# File parameters
TF_SRC_DIR = "tensorflow"
VERSION_H = "%s/core/public/version.h" % TF_SRC_DIR
SETUP_PY = "%s/tools/pip_package/setup.py" % TF_SRC_DIR
RE... |
from __future__ import unicode_literals
# mappings for table dumps
# "remember to add indexes!"
data_map = {
"Company": {
"columns": ["name"],
"conditions": ["docstatus < 2"]
},
"Fiscal Year": {
"columns": ["name", "year_start_date", "year_end_date"],
"conditions": ["docstatus < 2"],
},
# Accounts
"Acc... |
"""
Knowledge base model forms
"""
from django.forms import ModelForm, Form, ChoiceField
from models import KnowledgeFolder, KnowledgeItem, KnowledgeCategory
from anaf.core.models import Object
from anaf.core.decorators import preprocess_form
from django.utils.translation import ugettext as _
from django.core.urlresolv... |
""" Attribute and method access on Python objects from C++.
Note: std::cout type operations currently crash python...
Not sure what is up with this...
"""
from __future__ import absolute_import, print_function
import scipy.weave as weave
#----------------------------------------------------------------... |
'''
DDL statements for Elixir.
Entities having the perform_ddl statement, will automatically execute the
given DDL statement, at the given moment: ether before or after the table
creation in SQL.
The 'when' argument can be either 'before-create' or 'after-create'.
The 'statement' argument can be one of:
- a single s... |
import abc
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
import packaging.version
import pkg_resources
import google.auth # type: ignore
import google.api_core # type: ignore
from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # ty... |
from __future__ import unicode_literals
from guessit import base_text_type, Guess
from guessit.patterns import canonical_form
from guessit.textutils import clean_string
import logging
log = logging.getLogger(__name__)
def found_property(node, name, confidence):
node.guess = Guess({name: node.clean_value}, confid... |
from base import *
from papyon.util.async import *
__all__ = ['StoreProfileScenario']
class StoreProfileScenario(BaseScenario):
def __init__(self, storage, callback, errback,
cid, profile_id, expression_profile_id, display_picture_id,
display_name='', personal_message='', displ... |
"""Trains the DeepVariant model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
if 'google' in sys.modules and 'google.protobuf' not in sys.modules:
del sys.modules['google']
import json
import os
from absl import flags
from absl import... |
from copy import deepcopy
from lxml import etree
from openflow.optin_manager.sfa.util.sfalogging import logger
from openflow.optin_manager.sfa.util.xrn import hrn_to_urn, urn_to_hrn
from openflow.optin_manager.sfa.rspecs.version import RSpecVersion
from openflow.optin_manager.sfa.rspecs.elements.element import Element... |
import Screens.InfoBar
from enigma import eServiceReference
from Screens.Screen import Screen
from Components.ServiceScan import ServiceScan as CScan
from Components.ProgressBar import ProgressBar
from Components.Label import Label
from Components.ActionMap import ActionMap
from Components.FIFOList import FIFOList
fro... |
"""Entity tests for mobile_app."""
# pylint: disable=redefined-outer-name,unused-import
import logging
_LOGGER = logging.getLogger(__name__)
async def test_sensor(hass, create_registrations, webhook_client): # noqa: F401, F811, E501
"""Test that sensors can be registered and updated."""
webhook_id = create_... |
#!/usr/bin/python
import os, re, os.path, glob
head = re.compile( r"^(\s*</head>)", re.MULTILINE )
runtest = re.compile( r"runTest\(\s*(\S.*?)\s*\)", re.DOTALL )
scripts = '''
<!-- Polyfill files (NOTE: These are added by auto-generation script) -->
<script src=/encrypted-media/polyfill/chrome-polyfill.js></s... |
import pytest
from itertools import product
from collections import defaultdict
import warnings
from datetime import datetime
import numpy as np
from numpy import nan
import pandas as pd
from pandas.core import common as com
from pandas import DataFrame, MultiIndex, merge, concat, Series, compat
from pandas.util impor... |
from helper import unittest, PillowTestCase
from PIL import Image
class TestFileWebpMetadata(PillowTestCase):
def setUp(self):
try:
from PIL import _webp
except ImportError:
self.skipTest('WebP support not installed')
return
if not _webp.HAVE_WEBPMUX:... |
from StandardDataSets.scripts import JudgeAssistant
# Please feed your node list here:
tagLst = []
attrName = ''
attrVal = ''
dataToCheck = ''
class SimpleJudgingObject:
def __init__(self, _tagLst, _attrName, _attrVal, _data):
self.tagList = _tagLst
self.attrName = _attrName
self.attrVal =... |
import time
from openerp.report import report_sxw
class code_barcode(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(code_barcode, self).__init__(cr, uid, name, context=context)
self.localcontext.update({
'time': time,
})
report_sxw.report_sxw('report.mr... |
import os
import unittest
import mutagen
from . import TestUtil
from .. import util
test_files = "audio_pipeline\\test\\test_files\\audio\\tag_test_files"
class TestAudioFileTags(TestUtil.TestUtilMixin):
def test_artist_name(self):
tag = self.format.album_artist(self.meta)
self.check_af_tag(tag,... |
from numpy.testing import *
import numpy as np
from numpy import ( array, ones, r_, mgrid, unravel_index, zeros, where,
ndenumerate, fill_diagonal, diag_indices,
diag_indices_from, s_, index_exp )
class TestUnravelIndex(TestCase):
def test_basic(self):
assert unravel... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import os
import traceback
GITLAB_IMP_ERR = None
try:
import gitlab
HAS_GITLAB_PACKA... |
import thread
import _jpype
def startJava():
_jpype.startReferenceQueue(1)
def startPython():
def _run() :
_jpype.attachThreadToJVM()
_jpype.startReferenceQueue(0)
thread.start_new_thread(_run, tuple())
def stop():
_jpype.stopReferenceQueue() |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Misc functions related to Bitcoin, but which didn't feel right being
in the main bitcoin funcs
See _doctester.py for examples of most functions below.
'''
import os
import datetime
from binascii import hexlify, unhexlify
try:
ModuleNotFoundError
except:
Mo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
readme = open('README.rst').read()
history = open('HISTORY.rst').read().replace('.. :changelog:', '')
requirements = [
# TODO: put package requirements here
]
test_requi... |
from __future__ import unicode_literals
"""
record of files
naming for same name files: file.gif, file-1.gif, file-2.gif etc
"""
import webnotes, webnotes.utils, os
from webnotes import conf
class DocType():
def __init__(self, d, dl):
self.doc, self.doclist = d, dl
def before_insert(self):
webnotes.local.ro... |
from pyparsing import Literal, CaselessLiteral, Word, Upcase, delimitedList, Optional, \
Combine, Group, alphas, nums, alphanums, ParseException, Forward, oneOf, quotedString, \
ZeroOrMore, restOfLine, Keyword
def test( str ):
print str,"->"
try:
tokens = simpleSQL.parseString( str )
... |
import numpy as np
from nose.tools import assert_equal
from nose.tools import assert_false
from nose.tools import assert_true
from numpy.testing import (assert_almost_equal,
assert_array_almost_equal)
from sklearn.utils.fixes import divide, expit
from sklearn.utils.fixes import astype
def... |
{
'name': 'Belgium - Payroll',
'category': 'Localization',
'author': 'OpenERP SA',
'depends': ['hr_payroll'],
'version': '1.0',
'description': """
Belgian Payroll Rules.
======================
* Employee Details
* Employee Contracts
* Passport based Contract
* Allowances/Deducti... |
import errno
import os
from unittest import mock
import ddt
from oslo_config import cfg
from oslo_utils import importutils
from manila import exception
from manila.share import configuration as config
from manila.share import driver
from manila.share.drivers.glusterfs import layout
from manila import test
from manila... |
import os
import sys
STAGE_USERNAME = 'ffxbld'
STAGE_SSH_KEY = 'ffxbld_dsa'
config = {
#########################################################################
######## WINDOWS GENERIC CONFIG KEYS/VAlUES
# if you are updating this with custom 32 bit keys/values please add them
# below under the '32 b... |
from __future__ import print_function
__author__ = 'Thomas Rueckstiess, <EMAIL>'
from numpy import random
from random import sample
from scipy import isscalar
from pybrain.datasets.dataset import DataSet
from pybrain.utilities import fListToString
class SupervisedDataSet(DataSet):
"""SupervisedDataSets have tw... |
import struct
import datetime
# Operation
CMD_GET_PRODUCT_ID = 0xA0
CMD_GET_UNIQUE_ID = 0xA1
CMD_GET_FIRMWARE_VERSION = 0xA2
CMD_UNLOCK = 0xA8
CMD_UPDATE_FIRMWARE = 0xA9
CMD_GET_FIRMWARE_UPDATE_STATUS = 0xAA
CMD_SOFTWARE_RESET = 0xAF
CMD_SET_POWER_SAVE_MODE = 0xB0
CMD_GET_POWER_SAVE_MODE = 0xB1
UNLOCK_MAGIC_NUMBERS ... |
import base64
from libcloud.common.base import ConnectionUserAndKey, JsonResponse
from libcloud.compute.types import InvalidCredsError
from libcloud.utils.py3 import b
from libcloud.utils.py3 import httplib
try:
import simplejson as json
except ImportError:
import json
class BrightboxResponse(JsonResponse)... |
import os
import subprocess
import sys
import phoenix_utils
phoenix_utils.setPath()
phoenix_jar_path = os.getenv(phoenix_utils.phoenix_class_path, phoenix_utils.phoenix_test_jar_path)
# HBase configuration folder path (where hbase-site.xml reside) for
# HBase/Phoenix client side property override
hbase_library_path ... |
import struct
NETFLOW_V1 = 0x01
NETFLOW_V5 = 0x05
NETFLOW_V6 = 0x06
NETFLOW_V7 = 0x07
NETFLOW_V8 = 0x08
NETFLOW_V9 = 0x09
class NetFlow(object):
_PACK_STR = '!H'
_NETFLOW_VERSIONS = {}
@staticmethod
def register_netflow_version(version):
def _register_netflow_version(cls):
NetFlo... |
"""Test clients and replica set configuration changes, using mocks."""
import sys
sys.path[0:0] = [""]
from pymongo.errors import ConnectionFailure, AutoReconnect
from pymongo import ReadPreference
from test import unittest, client_context, client_knobs, MockClientTest
from test.pymongo_mocks import MockClient
from ... |
from django.core import cache
from django.conf import settings
from django.utils.safestring import mark_safe
from restkit import Resource
import json
from corehq.apps.hqadmin.system_info.utils import human_bytes
from soil import heartbeat
def check_redis():
#redis status
ret = {}
redis_status = ""
red... |
"""Unit tests for abc.py."""
import unittest, weakref
from test import test_support
import abc
from inspect import isabstract
class TestABC(unittest.TestCase):
def test_abstractmethod_basics(self):
@abc.abstractmethod
def foo(self): pass
self.assertTrue(foo.__isabstractmethod__)
... |
"""
BibSword Web Interface.
"""
from invenio.access_control_engine import(
acc_authorize_action
)
import invenio.bibsword_client as sword_client
from invenio.config import(
CFG_SITE_LANG,
CFG_SITE_URL
)
from invenio.messages import(
gettext_set_language
)
from invenio.webinterface_handler import(
w... |
"""Presubmit script for Chromium browser code.
This script currently only checks HTML/CSS/JS files in resources/.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into gcl/git cl, and see
http://www.chromium.org/developers/web-development-style... |
#!/usr/bin/python
"""
Linkfix - a companion to sphinx's linkcheck builder.
Uses the linkcheck's output file to fix links in docs.
Originally created for this issue:
https://github.com/scrapy/scrapy/issues/606
Author: dufferzafar
"""
import re
# Used for remembering the file (and its contents)
# so we don't have ... |
"""
Verifies simple rules when using an explicit build target of 'all'.
"""
import TestGyp
test = TestGyp.TestGyp()
test.run_gyp('actions.gyp', chdir='src')
test.relocate('src', 'relocate/src')
test.build('actions.gyp', chdir='relocate/src')
expect = """\
Hello from program.c
Hello from function1.in
Hello from fu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.