code stringlengths 1 199k |
|---|
from nose import SkipTest
import networkx as nx
from networkx.generators.degree_seq import havel_hakimi_graph
class TestSpectrum(object):
numpy=1 # nosetests attribute, use nosetests -a 'not numpy' to skip test
@classmethod
def setupClass(cls):
global numpy
global assert_equal
global... |
from uuid import UUID
from antlr4.atn.ATN import ATN
from antlr4.atn.ATNType import ATNType
from antlr4.atn.ATNState import *
from antlr4.atn.Transition import *
from antlr4.atn.LexerAction import *
from antlr4.atn.ATNDeserializationOptions import ATNDeserializationOptions
BASE_SERIALIZED_UUID = UUID("AADB8D7E-AEEF-441... |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.pr... |
from msrest.pipeline import ClientRawResponse
from .. import models
class IntModelOperations(object):
"""IntModelOperations operations.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An o... |
"""
Bootstrap the app-template. This module disables itself
after execution.
"""
import app_config
import json
import os
import subprocess
import utils
import uuid
import webbrowser
from distutils.spawn import find_executable
from fabric.api import execute, local, prompt, task
from oauth import get_credentials
from tim... |
'''
microcircuit simulation parameters
----------------------------------
Simulation parameters for the microcircuit.
Hendrik Rothe, Hannah Bos, Sacha van Albada; May 2016
'''
import os
sim_dict = {
# Simulation time (in ms).
't_sim': 1000.0,
# Resolution of the simulation (in ms).
'sim_resolution': 0.1... |
from __future__ import unicode_literals
import frappe
def execute():
# update the sales order item in the material request
frappe.reload_doc('stock', 'doctype', 'material_request_item')
frappe.db.sql('''update `tabMaterial Request Item` mri, `tabSales Order Item` soi
set mri.sales_order_item = soi.name
where ifn... |
from openerp import models, fields, api, _
class MrpBomSaleOrder(models.Model):
_name = 'mrp.bom.sale.order'
bom_line = fields.Many2one(comodel_name='mrp.bom.line')
product_id = fields.Many2one(related='bom_line.product_id',
string='Product')
product_uom = fields.Many2on... |
from __future__ import with_statement
import math
import socket
from .exceptions import TreeHashDoesNotMatchError, DownloadArchiveError
from .utils import tree_hash_from_str
class Job(object):
DefaultPartSize = 4 * 1024 * 1024
ResponseDataElements = (('Action', 'action', None),
('Arc... |
"""Adam for TensorFlow."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import resource_var... |
"""SCons.SConf
Autoconf-like configuration support.
"""
__revision__ = "src/engine/SCons/SConf.py 4043 2009/02/23 09:06:45 scons"
import os
import re
import string
import StringIO
import sys
import traceback
import types
import SCons.Action
import SCons.Builder
import SCons.Errors
import SCons.Job
import SCons.Node.FS
... |
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_system_fsso_polling
except ImportError:
... |
from supybot.test import *
class CtcpTestCase(PluginTestCase):
plugins = ('Ctcp',) |
from PIL import ImageFile, ImagePalette, _binary
from PIL._util import isPath
__version__ = "0.1"
try:
import builtins
except ImportError:
import __builtin__
builtins = __builtin__
i16 = _binary.i16be
class GdImageFile(ImageFile.ImageFile):
format = "GD"
format_description = "GD uncompressed images"... |
"""Functional test for GradientDescent."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.op... |
import unittest
import json
from api_list_data_source import APIListDataSource
from extensions_paths import EXTENSIONS
from server_instance import ServerInstance
from test_file_system import TestFileSystem
def _ToTestData(obj):
'''Transforms |obj| into test data by turning a list of files into an object
mapping tha... |
import os
from calibre.ebooks.rtf2xml import copy
from calibre.ptempfile import better_mktemp
class Footnote:
"""
Two public methods are available. The first separates all of the
footnotes from the body and puts them at the bottom of the text, where
they are easier to process. The second joins those foo... |
import matplotlib.pyplot as plt
import numpy as np
from scipy.fftpack import ifft
Ns = 64
hNs = Ns/2
mY = np.zeros(hNs)
pY = np.zeros(hNs)
Y = np.zeros(Ns)
yw = np.zeros(Ns)
Y = np.zeros(Ns, dtype=complex)
k0 = 5
ph0 = 1.5
A0 = .8
mY[k0] = A0 * Ns
pY[k0] = ph0
Y[:hNs] = .5*mY*np.exp(1j*pY)
Y[hNs+1:] = Y[hNs-1:0:-1].con... |
from django.conf import settings
from django.test import TestCase
from django.test.utils import override_settings
import track.tracker as tracker
from track.backends import BaseBackend
SIMPLE_SETTINGS = {
'default': {
'ENGINE': 'track.tests.test_tracker.DummyBackend',
'OPTIONS': {
'flag'... |
from m1 import *
print(m1m1)
from m2 import *
print(m2m1)
from m3 import *
print(m3m1)
from m4 import *
print(m4m1)
from m5 import *
print(m5m1) |
"""Suite of ODE solvers implemented in Python."""
from __future__ import division, print_function, absolute_import
from .ivp import solve_ivp
from .rk import RK23, RK45
from .radau import Radau
from .bdf import BDF
from .lsoda import LSODA
from .common import OdeSolution
from .base import DenseOutput, OdeSolver |
"""
This script converts all python tutorials into python script
and tests whether there is any warning or error.
After running python script, it will also convert markdown files
to notebooks to make sure notebook execution has no error.
"""
import os
import warnings
import imp
import traceback
import n... |
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from avro import ipc
from avro import protocol
MAIL_PROTOCOL_JSON = """\
{"namespace": "example.proto",
"protocol": "Mail",
"types": [
{"name": "Message", "type": "record",
"fields": [
{"name": "to", "type": "string"},
{"na... |
class ModuleDocFragment(object):
# Standard files documentation fragment
DOCUMENTATION = """
options:
host:
description:
- Specifies the DNS host name or address for connecting to the remote
device over the specified transport. The value of host is used as
the destination address fo... |
from m5.params import *
from m5.proxy import *
from m5.SimObject import SimObject
class ReplacementPolicy(SimObject):
type = 'ReplacementPolicy'
cxx_class = 'AbstractReplacementPolicy'
cxx_header = 'mem/ruby/structures/AbstractReplacementPolicy.hh'
block_size = Param.Int(Parent.cache_line_size, "block s... |
from openerp import models, api, exceptions, _
class SaleOrder(models.Model):
_inherit = "sale.order"
@api.multi
def button_draft(self):
# go from canceled state to draft state
for order in self:
if order.state != 'cancel':
raise exceptions.Warning(
... |
"""
Test VCCLCompilerTool EnableEnhancedInstructionSet setting.
"""
import TestGyp
import os
import sys
if sys.platform == 'win32':
print "This test is currently disabled: https://crbug.com/483696."
sys.exit(0)
test = TestGyp.TestGyp()
CHDIR = 'compiler-flags'
test.run_gyp('enable-enhanced-instruction-set.gyp... |
""" Guide renderers for various kinds of axes that can be added to
Bokeh plots
"""
from __future__ import absolute_import
from ..properties import Int, Float, String, Enum, Bool, Datetime, Auto, Instance, Tuple, Either, Include
from ..mixins import LineProps, TextProps
from ..enums import Location
from .renderers impor... |
"""Usage: check_test_times.py seconds inpath [outpath]
Reads test execution result from an output XML file and checks that no test
took longer than given amount of seconds to execute.
Optional `outpath` specifies where to write processed results. If not given,
results are written over the original file.
"""
import sys
... |
"""Utilities to test summaries."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import os
import sqlite3
from tensorflow.core.util import event_pb2
from tensorflow.python.framework import test_util
from tensorflow.python.lib.io import tf_r... |
import test_converter
import test_requests
import test_ui
import test_views |
"this file is needed to make this a package" |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['deprecated'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: cl_license
version_added: "2.1"
author: "Cumulus Networks (@CumulusNetworks)"
short_description: Install licenses fo Cumulus Linux
deprecated: Dep... |
"""
Bootstrap script for IDLE as an application bundle.
"""
import sys, os
os.chdir(os.path.expanduser('~/Documents'))
pyex = os.environ['PYTHONEXECUTABLE']
sys.executable = os.path.join(sys.prefix, 'bin', 'python%d.%d'%(sys.version_info[:2]))
p = pyex.partition('.app')
if p[2].startswith('/Contents/MacOS/Python'):
... |
from azure import (
WindowsAzureError,
MANAGEMENT_HOST,
_str,
_validate_not_none,
)
from azure.servicemanagement import (
AffinityGroups,
AffinityGroup,
AvailabilityResponse,
Certificate,
Certificates,
DataVirtualHardDisk,
Deployment,
Disk,
Disks,
Locations,
... |
"""runpy.py - locating and running Python code using the module namespace
Provides support for locating and running Python scripts using the Python
module namespace instead of the native filesystem.
This allows Python code to play nicely with non-filesystem based PEP 302
importers when locating support scripts as well ... |
def dec(f):
print('decorator')
return f
@dec
async def foo():
print('foo')
coro = foo()
try:
coro.send(None)
except StopIteration:
print('StopIteration') |
from test.json_tests import PyTest, CTest
class JSONTestObject:
pass
class TestRecursion:
def test_listrecursion(self):
x = []
x.append(x)
try:
self.dumps(x)
except ValueError:
pass
else:
self.fail("didn't raise ValueError on list recur... |
from __future__ import unicode_literals
import frappe
def get_workflow_name(doctype):
if getattr(frappe.local, "workflow_names", None) is None:
frappe.local.workflow_names = {}
if doctype not in frappe.local.workflow_names:
workflow_name = frappe.db.get_value("Workflow", {"document_type": doctype,
"is_active":... |
from sympy import ratsimpmodprime, ratsimp, Rational, sqrt, pi, log, erf
from sympy.abc import x, y, z, t, a, b, c, d, e, f, g, h, i, k
def test_ratsimp():
f, g = 1/x + 1/y, (x + y)/(x*y)
assert f != g and ratsimp(f) == g
f, g = 1/(1 + 1/x), 1 - 1/(x + 1)
assert f != g and ratsimp(f) == g
f, g = x/(... |
import importlib
import logging
import types
_logger = logging.getLogger(__name__)
SUPPORTED_DEBUGGER = {'pdb', 'ipdb', 'wdb', 'pudb'}
def post_mortem(config, info):
if config['dev_mode'] and isinstance(info[2], types.TracebackType):
debug = next((opt for opt in config['dev_mode'] if opt in SUPPORTED_DEBUGG... |
"""An example of training and predicting with a TFTS estimator."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import sys
import numpy as np
import tensorflow as tf
try:
import matplotlib # pylint: disable=g-import-not-at-top
matplotl... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.compat.tests import unittest
from ansible.release import __version__
from ansible import cli
class TestCliVersion(unittest.TestCase):
def test_version(self):
ver = cli.CLI.version('ansible-cli-test')
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: os_security_group
short_description: Add/Delete security groups... |
DOCUMENTATION = '''
---
module: ec2_vpc
short_description: configure AWS virtual private clouds
description:
- Create or terminates AWS virtual private clouds. This module has a dependency on python-boto.
version_added: "1.4"
options:
cidr_block:
description:
- "The cidr block representing the VPC, e.g... |
import json
import os
import kunit_parser
from kunit_parser import TestStatus
def get_json_result(test_result, def_config, build_dir, json_path) -> str:
sub_groups = []
# Each test suite is mapped to a KernelCI sub_group
for test_suite in test_result.suites:
sub_group = {
"name": test_suite.name,
"arch": "UM... |
"""FeedParser - An email feed parser.
The feed parser implements an interface for incrementally parsing an email
message, line by line. This has advantages for certain applications, such as
those reading email messages off a socket.
FeedParser.feed() is the primary interface for pushing new data into the
parser. It r... |
"""
German language mappings for language-dependent features of Docutils.
"""
__docformat__ = 'reStructuredText'
labels = {
'author': 'Autor',
'authors': 'Autoren',
'organization': 'Organisation',
'address': 'Adresse',
'contact': 'Kontakt',
'version': 'Version',
'revision': 'Revision',
'... |
data = (
'A', # 0x00
'a', # 0x01
'A', # 0x02
'a', # 0x03
'A', # 0x04
'a', # 0x05
'C', # 0x06
'c', # 0x07
'C', # 0x08
'c', # 0x09
'C', # 0x0a
'c', # 0x0b
'C', # 0x0c
'c', # 0x0d
'D', # 0x0e
'd', # 0x0f
'D', # 0x10
'd', # 0x11
'E', # 0x12
'e', # 0x13
'E', # 0... |
from coqtop import *
def get_goals():
r = goals()
if r is None:
return r
if isinstance(r, Err):
return r
if r.msg is not None:
r.msg
if r.val.val is None:
return "no goals"
gs = r.val.val
return gs
cmd1 = "Theorem plus_0_r : forall n : nat, n + 0 = n."
cmd2 = ... |
import sys
assert all('/usr' not in p for p in sys.path), sys.path
print(sys.path) |
"""SCons.Platform.win32
Platform-specific initialization for Win32 systems.
There normally shouldn't be any need to import this module directly. It
will usually be imported through the generic SCons.Platform.Platform()
selection method.
"""
__revision__ = "src/engine/SCons/Platform/win32.py 4369 2009/09/19 15:58:29 sc... |
"""collection of ring research related tools"""
from collections import namedtuple
import numpy as np
from astropy import units as u
RingSection = namedtuple("RingSection", "name rmin rmax")
D_ring = RingSection("D ring", 66_900*u.km, 74_510*u.km)
C_ring = RingSection("C ring", 74_658*u.km, 92_000*u.km)
B_ring = RingSe... |
"""DHCPv6 Status Codes"""
import pytest
import srv_msg
import srv_control
import references
import misc
@pytest.mark.v6
@pytest.mark.status_code
def test_v6_statuscode_noaddravail_solicit():
misc.test_setup()
srv_control.config_srv_subnet('3000::/64', '3000::1-3000::1')
srv_control.build_and_send_config_fil... |
game = True
price = 1
print 'This is a test \n the objective is waste time. \n How fast can you waste time?'
while game:
print "waste is, "+str(waste)+" tick, tok..."
if waste >= 10:
print "Goodbye, world.."
game = False
elif raw_input("Press Enter. Waste time!")!='Do something else, now.':
... |
from StringIO import StringIO
from PIL import Image
from flask import abort, send_file, request
import processors
MAX_WIDTH, MAX_HEIGHT = 4000, 4000
_processors = {
'contain': processors.process_contain,
'cover': processors.process_cover,
'crop': processors.process_crop
}
def process(type, width, height, pa... |
class EchoService(object):
singleton = None
def __init__(self, console, game_context):
self.console = console
self.game_context = game_context
EchoService.singleton = self
def echo(self, message, context=None):
if context:
replaced_message = context.replace(messag... |
from django.http import HttpRequest
from django.contrib.auth.models import User
import pytest
from fetch.views import user_form, register
from fetch.models import Token
pytestmark = pytest.mark.django_db
def test_user_form(client):
"""Tests user_form is creating Token"""
user = User.objects.create(username='pro... |
import numpy as np
from igakit.nurbs import NURBS
from igakit.transform import transform
from igakit.cad import compat, ruled, bilinear
def coonsInitialize(curves, tol=1.e-3):
[[c1,c3],[c0,c2]] = curves
(c0, c2) = compat(c0, c2)
(c1, c3) = compat(c1, c3)
p, U = c0.degree[0], c0.knots[0]
ub, ue = U[p... |
from dataclasses import dataclass
from dataclasses_json import dataclass_json
from datetime import date
import dataclasses_json
import dataclasses_json.cfg
@dataclass_json
@dataclass
class Person:
name: str
@dataclass_json
@dataclass
class PersonWithBirthday:
name: str
birthday: date
class TestGlobalConfig:... |
from snovault import (
AuditFailure,
audit_checker,
)
@audit_checker('ReferenceEpigenome', frame=['related_datasets',
'related_datasets.replicates',
'related_datasets.replicates.library',
... |
import sys
import CppHeaderParser
import os
def createLUABindings(inputPath, prefix, mainInclude, libSmallName, libName, apiPath, apiClassPath, includePath, sourcePath):
out = ""
sout = ""
lfout = ""
sout += "#include \"%sLUA.h\"\n" % (prefix)
sout += "#include \"%sLUAWrappers.h\"\n\n" % (prefix)
sout += "int lua... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^team/manage/$', views.team_manage, name='team_manage'),
url(r'^team/$', views.team_dashboard, name='team_dashboard'),
url(r'^team/billing/$', views.team_billing, name='team_billing'),
url(r'^team/billing/resign/$', views.team_bi... |
import sys
import pytest
from numpy.testing import assert_allclose
import numpy as np
from keras.backend import theano_backend as KTH
from keras.backend import tensorflow_backend as KTF
from keras.utils.np_utils import convert_kernel
def check_single_tensor_operation(function_name, input_shape, **kwargs):
val = np.... |
"""Local file storage."""
import errno
import hashlib
import os
import shutil
import jinja2
from grow.storage import base_storage
class FileStorage(base_storage.BaseStorage):
@staticmethod
def open(filename, mode=None):
if mode is None:
mode = 'r'
return open(filename, mode=mode)
... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('polls', '0106_question_yesno2_enabled'),
]
operations = [
migrations.AlterField(
model_name='question',
name='ui_number',
... |
"""
Created on Fri Apr 21 00:00:00 2017
@author: JOJO
"""
import cv2
import numpy as np
from collections import namedtuple
from findlanes import find_lanes
from constants import region, gb_kernel, canny_th1, canny_th2
from constants import hl_min_len, hl_max_gap
from constants import white
def roi(image):
mask = np... |
"""
Mock server for Vk.com oAuth authorization
"""
from flask import Flask, request, redirect, jsonify, render_template_string
app = Flask(__name__)
@app.route('/authorize')
def authorize():
if 'client_id' not in request.args:
return jsonify({
"error": "invalid_client",
"error_descri... |
class PyPath:
"""Plugin that allows inline execution of Python expressions and statements."""
def __init__(self):
self.py_buffer = ""
def call(self, pathobj):
cursym = pathobj.prog[pathobj.y][pathobj.x]
if cursym == '@':
result = eval(self.getstr(pathobj), {'pathobj' : pa... |
""" This script contains functions to access various system's info.
Author: Julien Delplanque
"""
import subprocess
from datetime import timedelta
from datetime import datetime
def get_uptime():
""" Return the uptime of the system as a timedelta object.
"""
proc = subprocess.Popen(["cat /proc/uptime"],
... |
import sublime, sublime_plugin
forward_chars = "0123456789.eE"
backward_chars = forward_chars + "-"
class AdjustNumberCommand(sublime_plugin.TextCommand):
def run(self, edit, by = 1):
sel = self.view.sel()
for r in sel:
while self.view.substr(r.a - 1) in backward_chars: r.a -= 1
while self.view.su... |
import os
import re
import string
import requests
import numpy as np
import collections
import random
import pickle
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.python.framework import ops
ops.reset_default_graph()
sess = tf.Session()
min_word_freq = 5 # Trim the less frequent words off
rnn_s... |
import binascii
import json
import pprint
import struct
import logging
logger = logging.getLogger(__name__)
from counterpartylib.lib import config
from counterpartylib.lib import exceptions
from counterpartylib.lib import util
from counterpartylib.lib import log
from counterpartylib.lib import message_type
FORMAT = '>3... |
from sqlalchemy import Column, Integer
from database.main import Base
class LevelXpRequirementSchema(Base):
"""
This table holds information about the necessary XP needed to reach a certain level.
The table's contents are as follows:
level, xp_required(needed to reach the next one)
1, 400 (meani... |
"""
This is CLM2BRY
"""
from datetime import datetime
import numpy as np
from netCDF4 import Dataset, num2date
import IOBry
__author__ = 'Trond Kristiansen'
__email__ = 'me@trondkristiansen.com'
__created__ = datetime(2009, 3, 2)
__modified__ = datetime(2019, 3, 12)
__version__ = "1.5"
__status__ = "Development"
def my... |
print "Building..."
from fabric.api import env
from fabric.operations import run, put, sudo
from fabric.tasks import execute
env.hosts = ['mbjerkness@bjerkness.net']
env.key_filename = "id_rsa"
def copy():
# make sure the directory is there!
sudo('mkdir -p /opt/local/codeflow')
sudo('chown mbjerkness /opt/l... |
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy import String
from sqlalchemy import Integer
from sqlalchemy import ForeignKey
from sqlalchemy import func
from sqlalchemy import FLOAT
from sqlalchemy.orm import backref
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative... |
import sqlite3
import logging
from models import Teacher
def insert_teacher(teacher):
with sqlite3.connect('my-app.db') as conn:
logging.debug('Inserting teacher {}'.format(teacher))
input_cols = [col for col in Teacher.columns if getattr(teacher, col) is not None]
vals = [getattr(teacher, c... |
from sniffer.api import * # import the really small API
import os, termstyle
pass_fg_color = termstyle.green
pass_bg_color = termstyle.bg_default
fail_fg_color = termstyle.red
fail_bg_color = termstyle.bg_default
@file_validator
def py_files(filename):
# dir_name is the full path to the directory of the file that c... |
import pandas as pd
df = pd.read_csv('data/src/sample_pandas_normal.csv')
print(df)
mask = [True, False, True, False, True, False]
df_mask = df[mask]
print(df_mask)
print(df['age'] < 35)
print(~(df['state'] == 'NY'))
print((df['age'] < 35) & ~(df['state'] == 'NY'))
df_and = df[(df['age'] < 35) & ~(df['state'] == 'NY')]... |
import sys
from nltk.tree import Tree
def format_tree():
with open(sys.argv[1]) as np_doc:
for line in np_doc:
np = Tree.fromstring(line)
print_tree(np)
print()
def print_tree(tree):
if tree.height() == 2:
print("{}( {})".format(tree.label(), tree[0]), end="")... |
from invisibleroads_macros_log import get_log
from os.path import expanduser
VIEW_NAMES = [
'text',
'number',
'markdown',
'table',
'image',
'map',
'electricity-network',
'file',
]
DEFAULT_VIEW_NAME = 'text'
PRINT_FORMAT_NAMES = [
'pdf'
]
DEBUG_VARIABLE_DEFINITIONS = [{
'id': 'std... |
"""ILI9486 chip driver"""
from gfxlcd.drawing.area import Area
from gfxlcd.abstract.chip import Chip
class ILI9486(Area, Chip):
"""Class for ILI9486 based LCD"""
rotations = {0: 0x88, 90: 0xf8, 180: 0x48, 270: 0x28}
def __init__(self, width, height, driver):
Chip.__init__(self, width, height, driver... |
r"""
# .---. .-----------
# / \ __ / ------
# / / \( )/ ----- (`-') _ _(`-') <-. (`-')_
# ////// '\/ ` --- ( OO).-/( (OO ).-> .-> \( OO) ) .->
# //// / // : : --- (,------. \ .'_ (`-')----. ,--./ ,--/ ,--.' ,-.
#... |
import argparse
from pathlib import Path
import csv
import setags.data.utils as du
from setags.metrics import confusion_matrix_from_iterables, Example, f1
from setags.utils import cprint
from setags.logging import setup_logger
def compare_files(target_path: Path, prediction_path: Path):
with target_path.open() as t... |
import django
from django.core.files.storage import (
FileSystemStorage, default_storage, get_storage_class)
from .conf import settings
__all__ = [
'spirit_storage',
'spirit_storage_or_none',
'OverwriteFileSystemStorage']
class OverwriteFileSystemStorage(FileSystemStorage):
def get_available_name(se... |
"""
Load pp, plot and save
"""
import os, sys
import matplotlib
matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
from matplotlib import rc
from matplotlib.font_manager import FontProperties
from matplotlib import rcParams
from mpl_toolkits.basemap import Basemap
rc('font', family = 'serif', ... |
import os
import cv2
import numpy as np
import cv2.face
import time
import passwdInput
from sys import exit
status = False
def cut_faces(image,faces_coord):
faces=[]
for (x,y,w,h) in faces_coord:
w_rm=int(0.2*w/2)
faces.append(image[y:y+h,x+w_rm:x+w-w_rm])
return faces
def normalize_intensity(images):
images_no... |
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /var/run/nginx.pid;
include /usr/share/nginx/modules/*.conf;
events {
worker_connections 1024;
}
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_refe... |
import threading
import unittest
import time
from nose.tools import assert_raises, assert_equal, assert_true
from pycassa import ColumnFamily, ConnectionPool, InvalidRequestError,\
NoConnectionAvailable, MaximumRetryException, AllServersUnavailable
from pycassa.logging.pool_stats_logger import Stats... |
from __future__ import absolute_import
import json
import uuid
from datetime import timedelta
from django import forms
from django.conf import settings
from django.contrib.auth.models import AbstractUser, AnonymousUser
from django.contrib.sites.models import Site
from django.core import mail, validators
from django.cor... |
from __future__ import unicode_literals
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, Submit, HTML, Button, Row, Field
from crispy_forms.bootstrap import AppendedText, PrependedText, FormActions
from django.contrib.auth import get_user_model
from django... |
__author__ = "Alexan Mardigian"
__version__ = "0.0.1"
from argparse import ArgumentParser
import certifi
import json
import sys
import urllib3
API_URL = "https://min-api.cryptocompare.com/data/price?fsym=%s&tsyms=%s"
COINFRACTION = float(10**-8) # A satoshi is one hundred millionth (0.00000001) of 1 coin.
clas... |
__all__ = ["GaussianProcess", "Hierogram", "CensoredHierogram"]
__version__ = "0.0.1"
__author__ = "Dan Foreman-Mackey (danfm@nyu.edu)"
__contributors__ = []
__copyright__ = "Copyright 2014 Daniel Foreman-Mackey"
__license__ = "MIT"
from .gp import GaussianProcess
from .hierogram import Hierogram
from . import censored |
import shutil
try:
shutil.rmtree('tmp')
except Exception as e:
pass |
from django.conf import settings
from django.conf.urls import url, include
from django.views.defaults import page_not_found, permission_denied, server_error
from .views import Home, SearchView, LicenseView, UserDocumentationView
urlpatterns = [
url(
regex=r'^$',
view=Home.as_view(),
name='ho... |
from runner.koan import *
class AboutIteration(Koan):
def test_iterators_are_a_type(self):
it = iter(range(1, 6))
fib = 0
for num in it:
fib += num
self.assertEqual(__, fib)
def test_iterating_with_next(self):
stages = iter(['alpha', 'beta', 'gamma'])
... |
from typing import List, Dict, Any # noqa: F401
from vint.ast.traversing import traverse, SKIP_CHILDREN
from vint.ast.plugin.scope_plugin.redir_assignment_parser import (
RedirAssignmentParser,
get_redir_content,
)
from vint.ast.plugin.scope_plugin.call_node_parser import (
CallNodeParser,
get_lambda_s... |
from markovtweet import *
api = create_api('config.json')
trump_mc = Markov_Chain()
for status in tweepy.Cursor(api.user_timeline, id = 'realDonaldTrump').items(5):
print(tokenize(status.text))
trump_mc.train_on_tweets(api,['realDonaldTrump','kanyewest'],500)
print trump_mc.generate_tweet('The') |
import _plotly_utils.basevalidators
class XValidator(_plotly_utils.basevalidators.InfoArrayValidator):
def __init__(self, plotly_name="x", parent_name="treemap.domain", **kwargs):
super(XValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_typ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.