code stringlengths 1 199k |
|---|
"""Calibration of predicted probabilities."""
from __future__ import division
import warnings
from math import log
import numpy as np
from scipy.optimize import fmin_bfgs
from sklearn.preprocessing import LabelEncoder
from .base import BaseEstimator, ClassifierMixin, RegressorMixin, clone
from .preprocessing import lab... |
from argparse import ArgumentParser, ArgumentError, SUPPRESS
from argparse import OPTIONAL, ZERO_OR_MORE, ONE_OR_MORE, REMAINDER, PARSER
from argparse import _get_action_name, _
def action_is_satisfied(action):
''' Returns False if the parse would raise an error if no more arguments are given to this action, True o... |
from openerp import tools
from openerp.osv import osv
from openerp.osv import fields
from openerp.tools.translate import _
class invite_wizard(osv.osv_memory):
""" Wizard to invite partners and make them followers. """
_name = 'mail.wizard.invite'
_description = 'Invite wizard'
def default_get(self, cr,... |
"""Add areas in stop points
Revision ID: 29fc422c56cb
Revises: 23dd34bfaeaf
Create Date: 2015-04-13 17:07:36.827493
"""
revision = '29fc422c56cb'
down_revision = '23dd34bfaeaf'
from alembic import op
import sqlalchemy as sa
import geoalchemy2 as ga
def upgrade():
op.add_column('stop_point', sa.Column('is_zonal', sa... |
"""Tests for distutils.dist."""
import os
import io
import sys
import unittest
import warnings
import textwrap
from unittest import mock
from distutils.dist import Distribution, fix_help_options, DistributionMetadata
from distutils.cmd import Command
from test.support import TESTFN, captured_stdout, run_unittest
from d... |
from __future__ import generators
r"""A fast and complete Python implementation of Markdown.
[from http://daringfireball.net/projects/markdown/]
> Markdown is a text-to-HTML filter; it translates an easy-to-read /
> easy-to-write structured text format into HTML. Markdown's text
> format is most similar to that of pla... |
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
Ovh = get_driver(Provider.OVH)
driver = Ovh('yourAppKey', 'yourAppSecret', 'yourProjectId', 'yourConsumerKey')
location = [l for l in driver.list_locations() if l.id == 'SBG1'][0]
image = [i for i in driver.list_images() if 'D... |
s = f'{f"""{42:{"'"}}"""}' |
"""
API for corpus readers.
"""
import os
import re
from collections import defaultdict
from nltk.data import PathPointer, FileSystemPathPointer, ZipFilePathPointer
from nltk.sourcedstring import SourcedStringStream
from util import *
class CorpusReader(object):
"""
A base class for "corpus reader" classes, eac... |
from msrest.serialization import Model
class GenericUrl(Model):
"""The Generic URL.
:param generic_value: Generic URL value.
:type generic_value: str
"""
_attribute_map = {
'generic_value': {'key': 'generic_value', 'type': 'str'},
}
def __init__(self, generic_value=None):
sel... |
from sympy.core.backend import symbols, Matrix, atan, zeros
from sympy import simplify
from sympy.physics.mechanics import (dynamicsymbols, Particle, Point,
ReferenceFrame, SymbolicSystem)
from sympy.utilities.pytest import raises
x, y, u, v, lam = dynamicsymbols('x y u v lambda')
m... |
""" Modified version of build_ext that handles fortran source files.
"""
import os
import sys
from glob import glob
from distutils.dep_util import newer_group
from distutils.command.build_ext import build_ext as old_build_ext
from distutils.errors import DistutilsFileError, DistutilsSetupError,\
DistutilsError
fro... |
from nose.tools import *
from networkx import *
from networkx.convert import *
from networkx.algorithms.operators import *
from networkx.generators.classic import barbell_graph,cycle_graph
from networkx.testing import *
class TestRelabel():
def test_convert_node_labels_to_integers(self):
# test that empty g... |
k0 = lambda x: besselk(0,x)
k1 = lambda x: besselk(1,x)
k2 = lambda x: besselk(2,x)
k3 = lambda x: besselk(3,x)
plot([k0,k1,k2,k3],[0,8],[0,5]) |
from shinken_test import *
class TestConfig(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_host_extented_info.cfg')
def test_dummy(self):
#
# Config is not correct because of a wrong relative path
# in the main config file
#
print "Get the hosts ... |
"""SCons.Tool.CVS.py
Tool-specific initialization for CVS.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
__revision__ = "src/engine/SCons/Tool/CVS.py 4043 2009/02/23 09:06:45 scons"
import SCons.Action
import ... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
import sys
if sys.version_info < (2, 7):
pytestmark = pytest.mark.skip("F5 Ansible modules require Python >= 2.7")
from ansible.module_utils.basic import AnsibleModule
try:
from library.mo... |
from django.contrib.auth.models import User
from django.http import HttpRequest
from django.test import TestCase
from tastypie.bundle import Bundle
from tastypie.fields import ToOneField, ToManyField
from tastypie.resources import ModelResource
from basic.api.resources import SlugBasedNoteResource
from basic.models imp... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
from mock import ANY
from ansible.module_utils.network.fortios.fortios import FortiOSHandler
try:
from ansible.modules.network.fortios import fortios_spamfilter_fortishield
except ImportError:... |
from __future__ import print_function
import sys, six
from w3lib.url import is_url
from scrapy.commands import ScrapyCommand
from scrapy.http import Request
from scrapy.exceptions import UsageError
from scrapy.utils.datatypes import SequenceExclude
from scrapy.utils.spider import spidercls_for_request, DefaultSpider
cl... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: win_audit_rule
short_description: Adds an audit rule to files, folders, or registry keys
description:
- Used to apply audit rules to files, folder... |
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__) |
import logging
from twisted.internet import task
from scrapy.exceptions import NotConfigured
from scrapy import signals
logger = logging.getLogger(__name__)
class LogStats(object):
"""Log basic scraping stats periodically"""
def __init__(self, stats, interval=60.0):
self.stats = stats
self.inter... |
def main(request, response):
response.headers.update([("Access-Control-Allow-Origin", request.headers["host"]),
("Access-Control-Max-Age", 30000),
("Access-Control-Allow-Credentials", "false"),
("Access-Control-Allow-Headers", "M... |
import os
import sys
from textwrap import dedent
import _pytest._code
import pytest
from _pytest.main import EXIT_NOTESTSCOLLECTED
from _pytest.nodes import Collector
ignore_parametrized_marks = pytest.mark.filterwarnings(
"ignore:Applying marks directly to parameters"
)
class TestModule(object):
def test_faili... |
import os
import signal
import sys
from telemetry.core import exceptions
from telemetry.core import util
from telemetry.core.platform import profiler
util.AddDirToPythonPath(util.GetChromiumSrcDir(), 'third_party', 'pexpect')
try:
import pexpect # pylint: disable=F0401
except ImportError:
pass
class _SingleProcess... |
from __future__ import (absolute_import, division)
__metaclass__ = type
import pytest
from ansible import context
class FakeOptions:
pass
def test_set_global_context():
options = FakeOptions()
options.tags = [u'production', u'webservers']
options.check_mode = True
options.start_at_task = u'Start wit... |
from oslo_log import log as logging
from tempest import config
import tempest.test
CONF = config.CONF
LOG = logging.getLogger(__name__)
class BaseDatabaseTest(tempest.test.BaseTestCase):
"""Base test case class for all Database API tests."""
credentials = ['primary']
@classmethod
def skip_checks(cls):
... |
"""
====================================
Outlier detection on a real data set
====================================
This example illustrates the need for robust covariance estimation
on a real data set. It is useful both for outlier detection and for
a better understanding of the data structure.
We selected two sets of ... |
import json
import warnings
from calendar import timegm
from collections import Mapping
from datetime import datetime, timedelta
from .api_jws import PyJWS
from .algorithms import Algorithm, get_default_algorithms # NOQA
from .compat import string_types, timedelta_total_seconds
from .exceptions import (
DecodeErro... |
import imp
import os.path
import sys
import unittest
def _GetDirAbove(dirname):
"""Returns the directory "above" this file containing |dirname| (which must
also be "above" this file)."""
path = os.path.abspath(__file__)
while True:
path, tail = os.path.split(path)
assert tail
if tail == dirname:
... |
import os
import unittest
from telemetry.page import page
from telemetry.page import page_set
class TestPage(unittest.TestCase):
def assertPathEqual(self, path1, path2):
self.assertEqual(os.path.normpath(path1), os.path.normpath(path2))
def testFilePathRelative(self):
apage = page.Page('file://somedir/other... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
name: jsonfile
short_description: JSON formatted files.
description:
- This cache uses JSON formatted, per host, files saved to the filesystem.
version_added: "1.9"
author: Ansible Cor... |
import time
from openerp.osv import fields, osv
class product_product(osv.osv):
_inherit = "product.product"
def _product_margin(self, cr, uid, ids, field_names, arg, context=None):
res = {}
if context is None:
context = {}
for val in self.browse(cr, uid, ids, context=context... |
"""Profiler tools for CherryPy.
CherryPy users
==============
You can profile any of your pages as follows::
from cherrypy.lib import profiler
class Root:
p = profile.Profiler("/path/to/profile/dir")
def index(self):
self.p.run(self._index)
index.exposed = True
def _i... |
import os
from ROOT import TFile,TH1D,TList,TObject
from base.MonteCarloFileHandler import MonteCarloFileHandler
class BinContent(object):
def __init__(self):
self.__MCtruth = None
self.__triggers = {}
def SetMCtruth(self, mctruth):
self.__MCtruth = mctruth
def AddTrigger(self, trigg... |
"""
***************************************************************************
sql_dictionary.py
---------------------
Date : April 2012
Copyright : (C) 2012 by Giuseppe Sucameli
Email : brush dot tyler at gmail dot com
*************************************... |
from __future__ import print_function
import codecs
import os
import platform
import sys
import unicodedata
__bold__ = "\033[1m"
__normal__ = "\033[0;0m"
DEFAULT_TERMINAL_SIZE = (80, 25)
def __get_size_windows__():
res = None
try:
from ctypes import windll, create_string_buffer
handler = windll.kernel32.GetStdH... |
from test_framework.mininode import *
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
import time
from test_framework.blocktools import create_block, create_coinbase
'''
Test version bits' warning system.
Generate chains with block versions that appear to be signalling u... |
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Person(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
birthday = models.DateField()... |
"""
Tests for L{twisted.protocols.amp}.
"""
import datetime
import decimal
from zope.interface.verify import verifyObject
from twisted.python.util import setIDFunction
from twisted.python import filepath
from twisted.python.failure import Failure
from twisted.protocols import amp
from twisted.trial import unittest
from... |
from django.core.management.base import BaseCommand
def module_to_dict(module, omittable=lambda k: k.startswith('_')):
"""Converts a module namespace to a Python dictionary."""
return {k: repr(v) for k, v in module.__dict__.items() if not omittable(k)}
class Command(BaseCommand):
help = """Displays differen... |
from zope.interface import directlyProvides
from twisted.mail.pop3 import AdvancedPOP3Client as POP3Client
from twisted.mail.pop3 import InsecureAuthenticationDisallowed
from twisted.mail.pop3 import ServerErrorResponse
from twisted.protocols import loopback
from twisted.internet import reactor, defer, error, protocol,... |
"""
Takes as arguments:
1. the path to a JSON file (such as an IPython notebook).
2. the path to output file
If 'metadata' dict in the JSON file contains 'include_in_docs': true,
then copies the file to output file, appending the 'metadata' property
as YAML front-matter, adding the field 'category' with value 'notebook... |
if (A and
B and
C):
pass
if <weak_warning descr="Remove redundant parentheses">("\n")</weak_warning>:
pass |
import unittest
import builtins
import warnings
from test.support import run_unittest
import os
from platform import system as platform_system
class ExceptionClassTests(unittest.TestCase):
"""Tests for anything relating to exception objects themselves (e.g.,
inheritance hierarchy)"""
def test_builtins_new_s... |
from unittest import TestCase
from django import get_version
from django.utils import six
class VersionTests(TestCase):
def test_development(self):
ver_tuple = (1, 4, 0, 'alpha', 0)
# This will return a different result when it's run within or outside
# of a git clone: 1.4.devYYYYMMDDHHMMSS ... |
"""Base and helper classes for Google RESTful APIs."""
__all__ = ['add_sync_methods']
import httplib
import random
import time
from . import api_utils
try:
from google.appengine.api import app_identity
from google.appengine.ext import ndb
except ImportError:
from google.appengine.api import app_identity
from go... |
import builder
import os
import sys
def create_builder(args):
usage = """\
Usage:
main.py cfg_msvc [-h|--help] [-t|--target TARGET] [cfg_site]
Arguments:
cfg_site: site configuration module. If not specified, "cfg_site"
is implied
-t,--target TARGET: Visual Studio build conf... |
def dis(src):
return __BRYTHON__.JSObject(__BRYTHON__.py2js(src)).to_js() |
"""Test the binascii C module."""
from test import test_support
import unittest
import binascii
import array
b2a_functions = ['b2a_base64', 'b2a_hex', 'b2a_hqx', 'b2a_qp', 'b2a_uu',
'hexlify', 'rlecode_hqx']
a2b_functions = ['a2b_base64', 'a2b_hex', 'a2b_hqx', 'a2b_qp', 'a2b_uu',
'unhe... |
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 'CourseMode.description'
db.add_column('course_modes_coursemode', 'description',
self.gf('django.d... |
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class SyndicationConfig(AppConfig):
name = 'django.contrib.syndication'
verbose_name = _("Syndication") |
Latin7_CharToOrderMap = (
255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10
253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20
252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30
253, 82,10... |
import os
from colorsys import hsv_to_rgb
from datetime import datetime
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.s... |
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, Http404
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from dashboard.models import *
from dashboard.util import force_url... |
__cmdname__ = 'rename_graphs'
import json
import re
import sys
import circonusapi
import log
import util
class Module(object):
def __init__(self, api, account):
self.api = api
self.account = account
def command(self, opts, pattern, replacement):
"""Rename multiple graphs at once
... |
import sys
import os
from recommonmark.parser import CommonMarkParser
needs_sphinx = '1.0'
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.ifconfig',
'sphinx.ext.githubpages',
]
templates_path = ['_templates']
source_parsers = ... |
from typing import Union
from django.contrib.auth import get_user_model
from django.contrib.auth.models import User
from jwt.exceptions import PyJWKClientError
from .base import BaseUserRepository, BasePublicKeyRepository
from ..tokens import UntrustedToken, Token
from .. import models
class DjangoUserRepository(BaseUs... |
print("\n#############################")
print("##### Strings VS. Bytes #####")
print("#############################\n")
print("by = b'abcd\x65'")
by = b'abcd\x65'
print("by = {0}".format(by))
print("type(by) = {0}".format(type(by)))
print("len(by) = {0}".format(len(by)))
print("by += b'\xff'")
by += b'\xff'
print("by ... |
from django.contrib import admin
from django.utils.html import format_html
from todoapi.models import Priority, Todo
admin.site.register(Priority)
class TodoAdmin(admin.ModelAdmin):
list_display = 'user', 'formattedTitle', 'dueTo', 'priority',
def formattedTitle(self, todo):
if todo.completed:
... |
"""
WSGI config for gluefun project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` s... |
"""
Author : A. Emerick
Date : May 2016
Purpose:
"""
__author__ = "aemerick <emerick@astro.columbia.edu>"
import numpy as np
from collections import OrderedDict
import pickle
import imf as imf
import star as star
import config as config
from constants import CONST as const
class Zone:
"""
Zone Cl... |
import numpy as np
class one2many(dict):
def reverse_lookup(self, x):
if not hasattr(self, 'reverse'):
reverse = dict()
for k, v in self.items():
for code in v.split():
reverse[code] = k
self.reverse = reverse
return np.unique([... |
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='pyMech',
version='0.1.0a',
description='Roloff / Matek brought to ... |
import unittest
from uuid import uuid4
from bidon.db.access import transaction, autocommit, DataAccess, Upsert
from tests import get_data_access, CONFIG
__all__ = ["DbAccessDataAccessTestCase"]
def rand():
return str(uuid4())
class DbAccessDataAccessTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
... |
import os
import numpy as np
import pytest
from natural_bm.datasets.common import threshold_data
from natural_bm.datasets import mnist, svhn, fast
import natural_bm.backend as B
def test_treshold_data():
datasets = {'train.data': 0.6*np.ones((100, 10))}
datasets = threshold_data(datasets, threshold=None)
as... |
from naospeech import NaoMic, NaoSpeech |
from __future__ import absolute_import, print_function
__author__ = 'katharine'
import atexit
import logging
import math
import os
import sys
import threading
import time
import requests
from pebble_tool.version import __version__
from pebble_tool.sdk import sdk_manager
from pebble_tool.util.config import config
from p... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import copy
from scipy.spatial import distance
import base64
from IPython.display import HTML
def mcl_update(particle_list, msg, target_particles=300,
new_particles_per_round=0, resample=True):
... |
import os
import re
re_pid = re.compile('^[0-9]+')
re_map = re.compile('^Size')
def pids():
dirs = os.listdir('/proc/')
dirs2 = []
for d in dirs:
if re_pid.match(d):
dirs2.append(d)
return dirs2
def mapsizes(pid):
sizes = [] # region sizes
pname = '/proc/' + pid + '/smaps'
... |
"""Simple example demonstrating categorizing messages to coroutines.
"""
import sys, random
import asyncoro
def client_proc(server, coro=None):
for i in range(12):
asyncoro.logger.debug('sending "%s"' % i)
server.send(i)
yield coro.sleep(random.uniform(0, 2))
server.send('done')
def serv... |
from ansible.module_utils.hashivault import hashivault_argspec
from ansible.module_utils.hashivault import hashivault_auth_client
from ansible.module_utils.hashivault import hashivault_init
from ansible.module_utils.hashivault import hashiwrapper
ANSIBLE_METADATA = {'status': ['stableinterface'], 'supported_by': 'commu... |
import vim
import webbrowser
import os
import platform
import mistune
def markdown(text, escape=True):
html = mistune.markdown(text, escape)
return html
def markdownPreviewWithDefaultCodeStyle():
cssName = vim.eval("a:args1")
currentpath = os.getcwd()
content = getHead(cssName)
content += getBuf... |
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
class Migration(migrations.Migration):
dependencies = [
('donors', '0004_auto_20141108_1110'),
]
operations = [
migrations.CreateModel(
name='Donation',
fields=[
... |
import os
import gameboard
import move
import getch
def clear_terminal():
"""Clears the terminal"""
os.system("cls" if os.name == "nt" else "clear")
if __name__ == "__main__":
# if game is started as a program - start game loop
# load all levels
levels = gameboard.sokoban_load_levels("sokoban_levels... |
'''Kivy Language
=============
The Kivy language is a language dedicated to describing user interface and
interactions. You could compare this language to Qt's QML
(http://qt.nokia.com), but we included new concepts such as rule definitions
(which are somewhat akin to what you may know from CSS), templating and so on.
... |
from snakemake import snakemake
from .utils import *
from datasuper.utils import parsers as dsparsers
from .result_schema import ResultSchema
import json
import sys
import datasuper as ds
from .snakemake_rule_builder import SnakemakeRuleBuilder
from time import time
from .pipeline_instance_utils import *
from .pipeline... |
import json
import requests
from pprint import pprint
all_data = list()
category_dict = {'1': '音樂類',
'2': '戲劇類',
'3': '舞蹈類',
'6': '展覽類',
'7': '講座類',
'8': '電影類',
'17': '演唱會'}
def insert_data(req_data):
for art_json ... |
class Colors:
### This is the line that you want to edit
### Replace False with True to enable colors!
def __init__(self, falfo = False):
if falfo:
self.red = "\033[01;31m{0}\033[00m"
self.green = "\033[1;36m{0}\033[00m"
self.blue = "\033[1;34m{0}\033[00m"
... |
from fabkit import task, parallel
from fablib.openstack import Ironic
@task
@parallel
def setup():
ironic = Ironic()
ironic.setup()
return {'status': 1} |
import os
DEBUG = True
TEMPLATE_DEBUG = True
SECRET_KEY = 'km4eHMibwT6Axr'
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'sample_db.sqlite3'),
}
}
SOCIAL_AUTH_GITHUB_KEY = 'km4eHMibwT6Axr'
S... |
import random, pylab
nsamples = 100000
x_list, y_list = [], []
for sample in range(nsamples):
x_list.append(random.gauss(0.0, 1.0))
y_list.append(random.gauss(0.0, 1.0))
pylab.plot(x_list, y_list, marker='.', linestyle='')
pylab.title('Samples from the 2D Gaussian distribution')
pylab.xlabel('$x$', fontsize=14)... |
"Base definitions for transports based on IP networking."
import os
import socket
import logging
from thespian.actors import ActorAddress
_localAddresses = set(['', '127.0.0.1', 'localhost', None])
def _probeAddrInfo(usage, useAddr, af, socktype, proto):
try:
return socket.getaddrinfo(useAddr, 0, af, sockty... |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('bunq_bot', '0002_auto_20170620_1430'),
]
operations = [
migrations.RenameModel(
old_name='BotInfo',
new_name='ChatInfo',
),
... |
from typing import Callable
from typing import List
import pytest
from py_algorithms.dynamic_connectivity import dynamic_connectivity_brute_force
from py_algorithms.dynamic_connectivity import dynamic_connectivity_quick_union
from py_algorithms.dynamic_connectivity import dynamic_connectivity_weighted_quick_union
from ... |
"""blankscript.py - Do nothing
But do it neatly.
Version 2012-12-12
Usage:
blankscript.py <arg1> <arg2>
"""
import os, sys, getopt
import Image
def blankscript(arg1, arg2):
pass
class Usage(Exception):
def __init__(self, msg):
self.msg = msg
def main(argv=None):
if argv is None:
... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^initiate-payment/(?<payment_id>)/$', login_required(views.InitiatePaymentView.as_view(), login_url=reverse_lazy('accounts:signup')), name='initiate_payment'),
] |
"""Handles converting FLAC files to MP3.""" |
"""
@file diff3.py
@brief Three-way file comparison algorithm.
This is a line-by-line translation of the Text::Diff3 Perl module version
0.10 written by MIZUTANI Tociyuki <tociyuki@gmail.com>.
The Text::Diff3 Perl module in turn was based on the diff3 program:
Three way file comparison program ... |
import traceback
from typing import Any, Dict
import demistomock as demisto # noqa: F401
import urllib3
from CommonServerPython import * # noqa: F401
urllib3.disable_warnings()
''' CONSTANTS '''
''' CLIENT CLASS '''
class Client(BaseClient):
"""Client class to interact with the service API"""
def get_lists(se... |
"""
"""
from zircon.external.komodo.komodo_py import *
from zircon.transceivers.base import BaseTransceiver
import sys
class KomodoTransceiver(BaseTransceiver):
MAX_PKT_SIZE = 8
NUM_GPIOS = 8
def __init__(self, channel):
# A, B, or AB
self.channel = channel
if self.channel == 'A':
... |
"""
一个重要的事.py:
当我们可以 参 数 -1 来 定 出图像的深度 数据类型 与原图像保持一致
但是我们在代 码中使用的却是 cv2.CV_64F。 是为什么呢 ?
想象一下一个从黑到白的边界的导数是整数,而一个从白到黑的边界点导数却是负数。
如果原图像的深度是 np.int8 时 所有的负值 会 截断变成 0
换句话就是把边界丢失掉。
所以如果 两种边界你 想检测到
最好的的办法就是将输出的数据类型 设置的更高
比如 cv2.CV_16S cv2.CV_64F 等。
取绝对值然后再把它 回 到 cv2.CV_8U。
下 的示例演示了输出图片的深度不同造成的不同效果。
"""
import cv2
impo... |
import logging
from typing import Any, Dict, Iterable, List, Mapping, Optional, Tuple, Union, cast
from graphql import (
IDLE,
REMOVE,
DocumentNode,
FieldNode,
FragmentDefinitionNode,
FragmentSpreadNode,
GraphQLError,
GraphQLInterfaceType,
GraphQLList,
GraphQLNonNull,
GraphQL... |
import datetime
import re
import sys
import time
import argparse
import json
import mechanize
from bs4 import BeautifulSoup
def select_form(browser, form_id):
'''With a mechanize browser, selects a form based on id'''
for form in browser.forms():
if form.attrs.get('id') == form_id:
browser.f... |
import requests
from pymongo import MongoClient
import time
from redis import StrictRedis
import traceback
from parsel import Selector
import urlparse
import json
import re
from multiprocessing import Pool
from collections import Counter
redis_setting = {
'dev': {
'host': 'localhost',
'port': 6379,
... |
"""Test logic for skipping signature validation on old blocks.
Test logic for skipping signature validation on blocks which we've assumed
valid (https://github.com/sarielsaz/sarielsaz/pull/9484)
We build a chain that includes and invalid signature for one of the
transactions:
0: genesis block
1: b... |
from scrapy.utils.project import get_project_settings
import scrapy
import json
from scrapy.crawler import CrawlerProcess
from lfcs_scraping.items import Grant2Item
from lfcs_scraping.spiders.grants import Grant2
class JsonWriterPipeline(object):
def __init__(self):
self.file = open('items.json', 'wb')
... |
import httplib2
import os
import random
import sys
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow
CLIENT_SECRETS_FILE = "client_secrets.json"
MIS... |
from __future__ import annotations
import warnings
from contextlib import closing
import django
from django.db import connection
from pytest_django.plugin import _blocking_manager
def pytest_report_header(config):
dot_version = ".".join(str(x) for x in django.VERSION)
header = "Django version: " + dot_version
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.