content string |
|---|
import random
from browser import doc
def getMousePosition(e):
if e is None:
e=win.event
if e.pageX or e.pageY:
return {'x': e.pageX, 'y': e.pageY}
if e.clientX or e.clientY:
_posx=e.clientX + doc.body.scrollLeft + doc.documentElement.scrollLeft;
_posy=e.clientY + doc.body.scr... |
import cgi
import json
import os
import traceback
import urllib
import urlparse
from constants import content_types
from pipes import Pipeline, template
from ranges import RangeParser
from request import Authentication
from response import MultipartContent
from utils import HTTPException
__all__ = ["file_handler", "p... |
import project_timesheet
import report
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
from __future__ import unicode_literals
from datetime import datetime, timedelta
from unittest import skipIf, skipUnless
from django.db import connection
from django.db.models import CharField, TextField, Value as V
from django.db.models.expressions import RawSQL
from django.db.models.functions import (
Coalesce,... |
"""
Attitude indicator widget.
"""
import sys
from PyQt4 import QtGui, QtCore
__author__ = 'Bitcraze AB'
__all__ = ['AttitudeIndicator']
class AttitudeIndicator(QtGui.QWidget):
"""Widget for showing attitude"""
def __init__(self):
super(AttitudeIndicator, self).__init__()
self.roll = 0
... |
from django import VERSION as djangoVersion
if djangoVersion[:2] >= (1, 8):
from django.db.backends.base.introspection import BaseDatabaseIntrospection, TableInfo
else:
from django.db.backends import BaseDatabaseIntrospection
from sqlanydb import ProgrammingError, OperationalError
import re
import sqlanydb
cl... |
import sys
from m5.defines import buildEnv
from m5.params import *
from m5.proxy import *
from Bus import CoherentBus
from InstTracer import InstTracer
from ExeTracer import ExeTracer
from MemObject import MemObject
from ClockDomain import *
default_tracer = ExeTracer()
if buildEnv['TARGET_ISA'] == 'alpha':
fro... |
#encoding=utf-8
'''
@author: wufulin
'''
import os
import sys
sys.path.append("..")
from util.Tool import *
####################################
#SongManager
#歌曲列表管理类
####################################
class SongManager(object):
'''
播放列表管理器
'''
def __init__(self):
self.__SongList ... |
"""
Unit tests for stub XQueue implementation.
"""
import mock
import unittest
import json
import requests
import time
import copy
from ..xqueue import StubXQueueService, StubXQueueHandler
class FakeTimer(object):
"""
Fake timer implementation that executes immediately.
"""
def __init__(self, delay, ... |
from test_framework.mininode import *
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from test_framework.comptool import wait_until
import time
'''
Test behavior of -maxuploadtarget.
* Verify that getdata requests for old blocks (>1week) are dropped
if uploadtarget ha... |
from __future__ import print_function
import glob
import io
import os
import platform
import subprocess
import sys
from distutils.command.build_ext import build_ext
from shutil import copytree, copy, rmtree
from setuptools import setup, Extension
if sys.version_info < (3, 5):
print("Python versions prior to 3.5 ... |
"""Tests for stream_slice."""
import string
import six
import unittest2
from apitools.base.py import exceptions
from apitools.base.py import stream_slice
class StreamSliceTest(unittest2.TestCase):
def setUp(self):
self.stream = six.StringIO(string.ascii_letters)
self.value = self.stream.getval... |
from .charsetprober import CharSetProber
from .constants import eNotMe, eDetecting
from .compat import wrap_ord
# This prober doesn't actually recognize a language or a charset.
# It is a helper prober for the use of the Hebrew model probers
### General ideas of the Hebrew charset recognition ###
#
# Four main charse... |
from __future__ import division
import requests
import random
import time
import threading
import rethinkdb as r
import math
import numpy as np
import cv2
import matplotlib
from matplotlib import pyplot as plt
import matplotlib.patches as patches
from scipy.misc import imread
import os
plt.scatter([0,5],[0,5])
plt.io... |
__all__ = ['Process', 'current_process', 'active_children']
#
# Imports
#
import os
import sys
import signal
import itertools
from _weakrefset import WeakSet
#for brython
from _multiprocessing import Process
#
#
#
try:
ORIGINAL_DIR = os.path.abspath(os.getcwd())
except OSError:
ORIGINAL_DIR = None
#
# Publ... |
"""Wraps the body of a converted function with auxiliary constructs."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gast
from tensorflow.python.autograph.core import converter
from tensorflow.python.autograph.pyct import anno
from tensorflow.pyt... |
import string
import sys
from xml.dom.minidom import parseString
from xml.sax import SAXParseException
class ParseException(Exception):
pass
# Generic class to represent items (like channel families)
class Item:
# Name to be displayed by repr()
pretty_name = None
# Attribute name in the parent clas... |
from io import BytesIO
from twisted.python import log as txlog, failure
from twisted.trial import unittest
from scrapy import log
from scrapy.spider import Spider
from scrapy.settings import default_settings
from scrapy.utils.test import get_crawler
class LogTest(unittest.TestCase):
def test_get_log_level(self)... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import re
import time
import glob
from ansible.plugins.action.iosxr import ActionModule as _ActionModule
from ansible.module_utils._text import to_text, to_bytes
from ansible.module_utils.six.moves.urllib.parse import ur... |
"""A Julia set computing workflow: https://en.wikipedia.org/wiki/Julia_set.
This example has in the juliaset/ folder all the code needed to execute the
workflow. It is organized in this way so that it can be packaged as a Python
package and later installed in the VM workers executing the job. The root
directory for th... |
import pytest
from trezorlib import lisk
from trezorlib.tools import parse_path
from .common import TrezorTest
LISK_PATH = parse_path("m/44h/134h/0h/1h")
@pytest.mark.lisk
class TestMsgLiskGetaddress(TrezorTest):
def test_lisk_getaddress(self):
self.setup_mnemonic_nopin_nopassphrase()
assert li... |
"""Queues"""
__all__ = ['Queue', 'PriorityQueue', 'LifoQueue', 'QueueFull', 'QueueEmpty']
import collections
import heapq
from . import events
from . import futures
from . import locks
from .tasks import coroutine
class QueueEmpty(Exception):
"""Exception raised when Queue.get_nowait() is called on a Queue obj... |
from oslo_config import cfg
import datetime
from nova.compute import api as compute_api
from nova.compute import manager as compute_manager
from nova import context
from nova import db
from nova import objects
from nova.tests.functional.v3 import api_sample_base
from nova.tests.functional.v3 import test_servers
from ... |
import os
import subprocess
import re
import threading
from functools import wraps
from concurrent.futures import Future, wait
import time
from ..logger import Logger
class ADB(object):
"""
Wrapper for adb commands.
Import::
from magneto.utils.adb import ADB
:required: Android SDK installe... |
# coding: utf-8
# pylint: disable=invalid-name, protected-access, too-many-arguments, global-statement
"""Symbolic configuration API."""
from __future__ import absolute_import as _abs
import ctypes
import sys
import numpy as _numpy
from ..base import _LIB
from ..base import c_array, c_str, mx_uint, py_str
from ..base... |
"""DB class containing many niceties to retrieve data from SQL"""
import hashlib
import os
import sqlite3
from philologic.Config import Config, db_locals_defaults, db_locals_header
from philologic.runtime import Query
from . import HitList
from . import MetadataQuery
from . import QuerySyntax
from .HitWrapper import... |
#!/usr/bin/env python
'''
@author: David Shaw, <EMAIL>
Inspired by EAS Inspector for Fiddler
https://easinspectorforfiddler.codeplex.com
----- The MIT License (MIT) -----
Filename: ASWBXMLCodePage.py
Copyright (c) 2014, David P. Shaw
Permission is hereby granted, free of charge, to any person obtaining a... |
from mercurial.i18n import _
from mercurial.node import hex
from mercurial import encoding, error, util, obsolete
import errno, os
class bmstore(dict):
"""Storage for bookmarks.
This object should do all bookmark reads and writes, so that it's
fairly simple to replace the storage underlying bookmarks with... |
''' Verifies that builds of the embedded content_shell do not included
unnecessary dependencies.'''
import os
import re
import string
import subprocess
import sys
import optparse
kUndesiredLibraryList = [
'libX11',
'libXau',
'libXcomposite',
'libXcursor',
'libXdamage',
'libXdmcp',
'libXext',
'libXfixe... |
from collections import Mapping, MutableMapping
try:
from threading import RLock
except ImportError: # Platform-specific: No threads available
class RLock:
def __enter__(self):
pass
def __exit__(self, exc_type, exc_value, traceback):
pass
try: # Python 2.7+
from co... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
depends_on = (
("fluent_contents", "0001_initial"),
)
def forwards(self, orm):
# Adding model 'TwitterRecentEntriesItem'
... |
"""
Functions to execute commands via the operating system.
"""
# Copyright (c) 2016 University of Edinburgh.
from __future__ import (nested_scopes, generators, division,
absolute_import, with_statement,
print_function, unicode_literals)
from subprocess import call
fro... |
import os
import sys
import tempfile
import shutil
if sys.version_info[:2] == (2, 6):
import unittest2 as unittest
else:
import unittest
from avocado.core import sysinfo
class SysinfoTest(unittest.TestCase):
def setUp(self):
self.tmpdir = tempfile.mkdtemp(prefix="sysinfo_unittest")
def tes... |
"""
Verifies that postbuild steps work.
"""
import TestGyp
import sys
if sys.platform == 'darwin':
test = TestGyp.TestGyp(formats=['ninja', 'make', 'xcode'])
test.run_gyp('test.gyp', chdir='postbuilds')
test.build('test.gyp', test.ALL, chdir='postbuilds')
# See comment in test/subdirectory/gyptest-subdir-... |
"""
URLconf for registration and activation, using django-registration's
one-step backend.
If the default behavior of these views is acceptable to you, simply
use a line like this in your root URLconf to set up the default URLs
for registration::
(r'^accounts/', include('registration.backends.simple.urls')),
Thi... |
# vim: set fileencoding=utf-8 :
from shirka.responders import Responder
from sympy.parsing.sympy_parser import parse_expr
import exceptions
from shirka.consumers import BaseTestCase
class MathResponder(Responder):
def name(self):
return 'math'
def generate(self, request):
"""
usage: m... |
######################################################################
# This file should be kept compatible with Python 2.3, see PEP 291. #
######################################################################
import sys
from ctypes import *
_array_type = type(c_int * 3)
def _other_endian(typ):
"""Return the t... |
from datetime import datetime, tzinfo
import pytz
from django.template import Library, Node, TemplateSyntaxError
from django.utils import six, timezone
register = Library()
# HACK: datetime is an old-style class, create a new-style equivalent
# so we can define additional attributes.
class datetimeobject(datetime,... |
import workitem
from openerp.workflow.helpers import Session
from openerp.workflow.helpers import Record
from openerp.workflow.workitem import WorkflowItem
class WorkflowInstance(object):
def __init__(self, session, record, values):
assert isinstance(session, Session)
assert isinstance(record, Reco... |
"""
Cached, database-backed sessions.
"""
import logging
from django.contrib.sessions.backends.db import SessionStore as DBStore
from django.core.cache import cache
from django.core.exceptions import SuspiciousOperation
from django.utils import timezone
from django.utils.encoding import force_text
KEY_PREFIX = "djan... |
import logging
import requests
import structlog
import parsel
from random import sample
import re
from django.test import Client
from django.test import RequestFactory
from siteapp.urls import urlpatterns
from django.urls.exceptions import Resolver404 as Resolver404
from siteapp.models import *
from guidedmodules.m... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
from ansible.module_utils.facts.namespace import PrefixFactNamespace
from ansible.module_utils.facts.collector import BaseFactCollector
class OhaiFactCollector(BaseFactCollector):
'''This is a subclass of Facts ... |
"""
from: http://adventofcode.com/2017/day/5
--- Day 5: A Maze of Twisty Trampolines, All Alike ---
An urgent interrupt arrives from the CPU: it's trapped in a maze of jump instructions, and it would
like assistance from any programs with spare cycles to help find the exit.
The message includes a list of the offsets f... |
import glob
import os
# E.g. replace Simon's cat with 'Simon'\''s cat'.
def escape(s):
return "'%s'" % s.replace("'", "'\"'\"'")
def file_glob(given_glob, to, prefix):
dirs = []
files = []
lp = len(prefix)
for f in glob.glob(given_glob):
if os.path.isdir(f):
more_files = file_g... |
#!/usr/bin/python3
# updates repos.gz
import gzip
import os
wwwroot = "/home/packages/www/repos.springrts.com"
prefix = "http://repos.springrts.com/"
streamer = "/home/packages/bin/Streamer"
repos = {
"main": "http://packages.springrts.com"
}
assert(os.path.isfile(streamer))
def SetupStreamer(repodir):
streamerc... |
"""
PRC (Palm resource) parser.
Author: Sebastien Ponce
Creation date: 29 october 2008
"""
from hachoir_parser import Parser
from hachoir_core.field import (FieldSet,
UInt16, UInt32, TimestampMac32,
String, RawBytes)
from hachoir_core.endian import BIG_ENDIAN
class PRCHeader(FieldSet):
static_size = 78*8... |
"""
Utility functions for retrieving and generating forms for the
site-specific user profile model specified in the
``AUTH_PROFILE_MODULE`` setting.
"""
from django import forms
from django.conf import settings
from django.contrib.auth.models import SiteProfileNotAvailable
from django.db.models import get_model
def... |
"""Dealing with all general issues about command line tool set.
And this is command entry point.
"""
import sys
import inspect
import optparse
from robotx.core.base import BaseCommand
from robotx.utils.misc import walk_modules
from robotx.core.exceptions import UsageError
def _iter_command_classes(module_name):
... |
'''
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import pyglet
window = pyglet.window.Window()
label = pyglet.text.Label('Hello, world',
font_name='Times New Roman',
font_size=36,
x=window.width//2, y=window.height//2,
... |
#from out2_sup import *
import out2_sup as model_
rootObj = model_.rootTag(
comments=[
model_.comments(
content_ = [
model_.MixedContainer(1, 0, "", "1. This is a "),
model_.MixedContainer(2, 2, "emp", "foolish"),
model_.MixedContainer(1, 0, "", " comment. ... |
"""
Wraps multiple ways to communicate over SSH.
"""
have_paramiko = False
try:
import paramiko
have_paramiko = True
except ImportError:
pass
# Depending on your version of Paramiko, it may cause a deprecation
# warning on Python 2.6.
# Ref: https://bugs.launchpad.net/paramiko/+bug/392973
import os
impo... |
#
# Emulation of has_key() function for platforms that don't use ncurses
#
import _curses
# Table mapping curses keys to the terminfo capability name
_capability_names = {
_curses.KEY_A1: 'ka1',
_curses.KEY_A3: 'ka3',
_curses.KEY_B2: 'kb2',
_curses.KEY_BACKSPACE: 'kbs',
_curses.KEY_BEG: 'kbeg',
... |
from collections import defaultdict
from operator import itemgetter
from math import log, sqrt
import random as rn
import time
from numpy import * # install numpy
from scipy import * # install scipy
from numpy.linalg import norm
import numpy.linalg as npl
from scipy.sparse import *
import scipy.sparse.linalg as spsl
fr... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
int_or_none,
unified_strdate,
)
from ..compat import compat_urlparse
class DWIE(InfoExtractor):
IE_NAME = 'dw'
_VALID_URL = r'https?://(?:www\.)?dw\.com/(?:[^/]+/)+(?:av|e)-(?P<id>\d+)'
... |
"""Convenience functions to save a model.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=unused-import
from tensorflow.python.saved_model import builder
from tensorflow.python.saved_model import constants
from tensorflow.python.saved... |
from json import loads
from urlparse import urlparse
from flask import current_app as app
from flask import request
def thumbUrl(thumb):
return "https://venturelog.imgix.net/articles/" + thumb + \
"?w=200&h=150&fit=crop&crop=entropy&auto=compress,format"
def html(article):
return '<div><p>' + article... |
#!/usr/bin/env python3
"""
CFE Partition Tag
{
u32 part_id;
u32 part_size;
u16 flags;
char part_name[33];
char part_version[21];
u32 part_crc32;
}
"""
import argparse
import os
import struct
PART_NAME_SIZE = 33
PART_VERSION_SIZE = 21
CRC32_INIT = 0xFFFFFFFF
CRC32_TABLE = [
0x00000000, 0x77073096, 0xEE0E612... |
"""gettext tool
"""
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 The SCons Foundation
#
# 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 with... |
#!/usr/bin/env python
'''
update a wordpress wiki page
Andrew Tridgell
May 2013
See http://codex.wordpress.org/XML-RPC_WordPress_API/Posts
'''
import xmlrpclib, sys
from optparse import OptionParser
parser = OptionParser("update_wiki.py [options] <file>")
parser.add_option("--username", help="Wordpress username", de... |
#!/usr/bin/env python2.6
# vim: ts=4 sw=4 expandtab
""" Parses a script into nodes. """
import bisect
import re
import unittest
import spidermonkey
from spidermonkey import tok, op
from util import JSVersion
_tok_names = dict(zip(
[getattr(tok, prop) for prop in dir(tok)],
['tok.%s' % prop for prop in dir(tok... |
# -*- coding: utf-8 -*-
"""
werkzeug.http
~~~~~~~~~~~~~
Werkzeug comes with a bunch of utilities that help Werkzeug to deal with
HTTP data. Most of the classes and functions provided by this module are
used by the wrappers, but they are useful on their own, too, especially if
the response and ... |
import re
__all__ = ('QueryInfo', 'QueryReadStoreInfo',
'JsonRestStoreInfo', 'JsonQueryRestStoreInfo',)
class QueryInfoFeatures(object):
sorting = True
paging = False
class QueryInfo(object):
'''Usage (is that the right solution?):
info = QueryInfo(request)
info.extract()
... |
# coding=utf-8
from psycopg2.extras import NamedTupleCursor, Json
from tornado.web import Application, HTTPError
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.httpserver import HTTPServer
from tornado.options import parse_command_line
import momoko
import os
from bank import SelectQuestion, get... |
import codecs
from setuptools import setup
with codecs.open('README.rst', encoding='utf-8') as f:
long_description = f.read()
setup(
name="shadowsocks",
version="2.8.2",
license='http://www.apache.org/licenses/LICENSE-2.0',
description="A fast tunnel proxy that help you get through firewalls",
... |
#!/usr/bin/env python
from struct import *
from socket import *
from optparse import OptionParser
UDP_ADDR = "0.0.0.0"
UDP_MULTICAST_ADDR = "239.255.255.100"
UDP_PORT = 7724
BUFFER_SIZE = 65536
#HEADER_KEYS = ['Logger', 'Level', 'Source-File', 'Source-Function', 'Source-Line', 'TimeStamp']
HEADER_KEYS = {
'mini': ... |
"""(Extremely) low-level import machinery bits as used by importlib and imp."""
class __loader__(object):pass
def _fix_co_filename(*args,**kw):
raise NotImplementedError("%s:not implemented" % ('_imp.py:_fix_co_filename'))
def acquire_lock(*args,**kw):
"""acquire_lock() -> None Acquires the interpreter's... |
from datetime import datetime, timedelta
from nose.tools import eq_
from kitsune.announcements.models import Announcement
from kitsune.announcements.tests import announcement
from kitsune.sumo.tests import TestCase
from kitsune.users.tests import user, group, profile
from kitsune.wiki.tests import locale
class Anno... |
"""Support for Vera sensors."""
from datetime import timedelta
import logging
from homeassistant.components.sensor import ENTITY_ID_FORMAT
from homeassistant.const import TEMP_CELSIUS, TEMP_FAHRENHEIT
from homeassistant.helpers.entity import Entity
from homeassistant.util import convert
from . import VERA_CONTROLLER,... |
import os
from ansible import utils
import ansible.utils.template as template
from ansible import errors
from ansible.runner.return_data import ReturnData
## fixes https://github.com/ansible/ansible/issues/3518
# http://mypy.pythonblogs.com/12_mypy/archive/1253_workaround_for_python_bug_ascii_codec_cant_encode_charac... |
import os
import os.path
import shutil
import re
def main():
pam_items = [ 'core', 'data', 'fsize', 'memlock', 'nofile', 'rss', 'stack', 'cpu', 'nproc', 'as', 'maxlogins', 'maxsyslogins', 'priority', 'locks', 'sigpending', 'msgqueue', 'nice', 'rtprio', 'chroot' ]
pam_types = [ 'soft', 'hard', '-' ]
limi... |
{
'name': 'Report Qweb Element Page Visibility',
'version': '8.0.1.0.0',
'author': 'Agile Business Group, Odoo Community Association (OCA)',
'category': 'Tools',
"website": "https://odoo-community.org/",
"license": "AGPL-3",
"application": False,
"installable": True,
'data': [
... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'core',
'version': '1.0'}
DOCUMENTATION = r'''
---
module: win_package
version_added: "1.7"
author: Trond Hindenes
short_description: Installs/Uninstalls an installable package, either from local file system or url
descr... |
"""
Django settings for hoursservice project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ..... |
import json
from datetime import datetime, timedelta
from flask import request, render_template, make_response, current_app
from flask.ext.login import current_user
from flask.ext.oauthlib.provider import OAuth2Provider
from flask.ext.user import login_required, passwords
from werkzeug.security import gen_salt
from b... |
# pylint: disable=C0111
# pylint: disable=W0621
from lettuce import world, step
from lettuce.django import django_url
from course_modes.models import CourseMode
from nose.tools import assert_equal
UPSELL_LINK_CSS = '.message-upsell a.action-upgrade[href*="edx/999/Certificates"]'
def create_cert_course():
world.... |
#!/usr/bin/python -u
#
#
#
#################################################################################
# Start off by implementing a general purpose event loop for anyones use
#################################################################################
import sys
import getopt
import os
import libvirt
impor... |
"""
I hold resource classes and helper classes that deal with CGI scripts.
"""
# System Imports
import string
import os
import urllib
# Twisted Imports
from twisted.web import http
from twisted.internet import reactor, protocol
from twisted.spread import pb
from twisted.python import log, filepath
from twisted.web im... |
import numpy as np
import invesalius.data.coordinates as dco
import invesalius.data.transformations as tr
import invesalius.data.coregistration as dcr
def angle_calculation(ap_axis, coil_axis):
"""
Calculate angle between two given axis (in degrees)
:param ap_axis: anterior posterior axis represe... |
name = 'output'
class State():
def __init__(self):
self.output_setup_called = False
self.output_teardown_called = False
self.output_handler_called = False
state = State()
def setup(config={}):
state.output_setup_called = True
# TODO: This isn't currently called
def teardown():
... |
__author__ = 'Chris HAmm'
#GUI_KeyEvent
#when we press a key on our keyboard, wx.KeyEvent is generated. This event is sent to the widget that currently has focus
#three different key handlers
#wx.EVT_KEY_DOWN
#wx.EVT_KEY_UP
#wx.EVT_CHAR
#common request is to close the application when the ESC key is pressed
import ... |
from unittest import TestCase
import numpy as np
import pandas as pd
from scattertext import LogOddsRatioInformativeDirichletPrior
from scattertext.PriorFactory import PriorFactory
from scattertext.test.test_semioticSquare import get_test_corpus
class TestPriorFactory(TestCase):
def test_all_categories(self):
... |
import os
import os.path
import shutil
import tempfile
import re
# ===========================================
# Support method
def assemble_from_fragments(src_path, delimiter=None, compiled_regexp=None):
''' assemble a file from a directory of fragments '''
tmpfd, temp_path = tempfile.mkstemp()
tmp = os.... |
# -*- coding:utf-8 -*-
import pytest
# node-semver/test/index.js
# import logging
# logging.basicConfig(level=logging.DEBUG, format="%(message)s")
cands = [
['1.2.3', 'major', '2.0.0', False],
['1.2.3', 'minor', '1.3.0', False],
['1.2.3', 'patch', '1.2.4', False],
['1.2.3tag', 'major', '2.0.0', True]... |
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp import netsvc
class workflow(osv.osv):
_name = "workflow"
_table = "wkf"
_order = "name"
_columns = {
'name': fields.char('Name', size=64, required=True),
'osv': fields.char('Resource Object', size=64... |
# -*- coding: utf-8 -*-
"""
pygments.console
~~~~~~~~~~~~~~~~
Format colored console output.
:copyright: Copyright 2006-2012 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
esc = "\x1b["
codes = {}
codes[""] = ""
codes["reset"] = esc + "39;49;00m"
cod... |
### This script calculates the cumulative above and belowground carbon gain in mangrove forest pixels from 2001-2015.
### It multiplies the annual biomass gain rate by the number of years of gain by the biomass-to-carbon conversion.
import utilities
import datetime
import subprocess
import sys
sys.path.append('../')
i... |
"""
An alphabetical list of provinces and territories for use as `choices`
in a formfield., and a mapping of province misspellings/abbreviations to
normalized abbreviations
Source: http://www.canada.gc.ca/othergov/prov_e.html
This exists in this standalone file so that it's only imported into memory
when... |
#Code from https://gist.github.com/craffel/2d727968c3aaebd10359
import matplotlib.pyplot as plt
def draw_neural_net(ax, left, right, bottom, top, layer_sizes, bias=0, draw_edges=False):
'''
Draw a neural network cartoon using matplotilb.
:usage:
>>> fig = plt.figure(figsize=(12, 12))
... |
try:
import pyrax
HAS_PYRAX = True
except ImportError:
HAS_PYRAX = False
def cloud_network(module, state, label, cidr):
changed = False
network = None
networks = []
if not pyrax.cloud_networks:
module.fail_json(msg='Failed to instantiate client. This '
... |
import os
import numpy as np
from neon import logger as neon_logger
from neon.util.argparser import NeonArgparser
from neon.optimizers import Adadelta
from neon.callbacks.callbacks import Callbacks
from network import create_network
from data import make_train_loader, make_test_loader
subm_config = os.path.join(os.pat... |
import cgi
import errno
import mimetypes
import os
import posixpath
import re
import shutil
import stat
import sys
import tempfile
from optparse import make_option
from os import path
import django
from django.template import Template, Context
from django.utils import archive
from django.utils.six.moves.urllib.reques... |
from __future__ import absolute_import
try:
import json
except ImportError, e:
import simplejson as json
import logging
import urllib2
import telnetlib
import urllib
from django.conf import settings
from django.template import loader
from django.http import HttpResponse
from django import forms
from django.c... |
from openerp import models, api
class SaleOrder(models.Model):
_inherit = 'sale.order'
@api.one
def action_button_confirm(self):
procurement_obj = self.env['procurement.order']
procurement_group_obj = self.env['procurement.group']
res = super(SaleOrder, self).action_button_confirm... |
from cloudinary.models import CloudinaryField
from django.contrib.auth.models import User
from django.db import models
from multiselectfield import MultiSelectField
group_permissions = (
('INVITE_MEMBER', 'Send invites'),
('DELETE_MEMBER', 'Remove members'),
('BLOCK_MEMBER', 'Block members'),
('SUSPEND... |
"""Base Manager class.
Managers are responsible for a certain aspect of the system. It is a logical
grouping of code relating to a portion of the system. In general other
components should be using the manager to make changes to the components that
it is responsible for.
For example, other components that need to d... |
import unittest
from openerp.osv.query import Query
class QueryTestCase(unittest.TestCase):
def test_basic_query(self):
query = Query()
query.tables.extend(['"product_product"', '"product_template"'])
query.where_clause.append("product_product.template_id = product_template.id")
q... |
"""NOS NETCONF XML Configuration Command Templates.
Interface Configuration Commands
"""
# Create VLAN (vlan_id)
CREATE_VLAN_INTERFACE = """
<config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0">
<interface-vlan xmlns="urn:brocade.com:mgmt:brocade-interface">
<interface>
<... |
#utilities.py
from SCons.Script import *
from SCons.Environment import Environment
import os
import fnmatch
import json as json
import sys
import os.path
import pic12
import StringIO
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from pymomo.utilities import build
from pymomo.mib.config12 import MIB1... |
#!/usr/bin/env python
import time
#import nose
import logging
l = logging.getLogger("angr_tests.counter")
l.setLevel(logging.INFO)
try:
# pylint: disable=W0611,F0401
import standard_logging
import angr_debug
except ImportError:
pass
addresses_counter = {
'armel': None,
'armhf': None, # addr... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import pytest
from units.modules.utils import set_module_args, exit_json, fail_json, AnsibleExitJson
from ansible.module_utils import basic
from ansible.modules.network.check_point import cp_mgmt_tag_facts
OBJECT = {
"from": 1,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.