content string |
|---|
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
"""
Normalize data
Outputs:
data normalized so that when plotted 0 will be midlevel grey
Args:
data: np.ndarray
"""
def normalize_data(data):
if np.max(np.abs(data)) > 0:
norm_data = (data / np.max(np.abs(data))).squeeze()
else:... |
from .utils import serialize, unserialize, dict_set_path, dict_filter, create_filter
from .watcher import ZkFarmJoiner, ZkFarmExporter, ZkFarmImporter
from kazoo.client import OPEN_ACL_UNSAFE
from kazoo.exceptions import NoNodeError, BadVersionError
class ZkFarmer(object):
STATUS_OK = 0
STATUS_WARNING = 1
... |
from os_brick import initiator
from os_brick.initiator import connector
import nova.conf
from nova import utils
from nova.virt.libvirt.volume import volume as libvirt_volume
CONF = nova.conf.CONF
class LibvirtHGSTVolumeDriver(libvirt_volume.LibvirtBaseVolumeDriver):
"""Driver to attach HGST volumes to libvirt.... |
# 'Data Science from Scratch' Chapter 1 exampl
# Create list of users
userNames = ["Hero", "Dunn", "Sue", "Chi", "Thor", "Clive", "Hicks", "Devin", "Kate", "Klein"]
users = []
for ind, name in enumerate( userNames ):
users.append( {"id": ind, "name": name})
# Helper function to get id
get_id = lambda userlist... |
__source__ = 'https://leetcode.com/problems/move-zeroes/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/move-zeroes.py
# Time: O(n)
# Space: O(1)
#
# Description: Leetcode # 283. Move Zeroes
#
# Given an array nums, write a function to move all 0's
# to the end of it while maintaining the relative order
# ... |
"""Implementation of the VGG-16 network.
In this specific implementation, max-pooling operations are replaced with
average-pooling operations.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import tensorflow as tf
slim = tf.contrib.slim
f... |
import socket
import re
import logging as log
from time import sleep
from select import select
from threading import Thread
from StringIO import StringIO
from httplib import HTTPResponse
class StringySocket(StringIO):
def makefile(self, *args, **kw):
"""
Used to mock set 'rb' flags etc...
... |
import os
import subprocess
import numpy as np
import warnings
import rasterio
from s2p import common
from s2p import rpc_model
from s2p import rpc_utils
from s2p.config import cfg
# silent rasterio NotGeoreferencedWarning
warnings.filterwarnings("ignore",
category=rasterio.errors.NotGeorefere... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import re
import socket
import sys
import urllib
import urllib2
import urlparse
class BingSearch(object):
url = 'http://www.bing.com/search?q={0}&first={1}&go=&qs=n&FORM=PORE'
headers = {
'User-Agent': 'Mozilla/5.0 (X... |
"""
A module defining pytest fixtures for testing with MultiDeviceTestContext
Requires pytest and pytest-mock
"""
from collections import defaultdict
import pytest
import socket
import tango
from tango.test_context import MultiDeviceTestContext, get_host_ip
@pytest.fixture(scope="module")
def devices_info(request):
... |
nodetype = 'dl160g6'
scalapack = True
compiler = 'gcc'
libraries =[
'gfortran',
'scalapack',
'mpiblacs',
'mpiblacsCinit',
'openblaso',
'hdf5',
'xc',
'mpi',
'mpi_f77',
]
library_dirs =[
'/home/opt/el6/' + nodetype + '/openmpi-1.6.3-' + nodetype + '-tm-gfortran-1/lib',
'/ho... |
"""
Base group class, from the project one, as a placeholder to build more than
one project from a single one
"""
from .base_project import Project, GVSBUILD_GROUP
class Group(Project):
def __init__(self, name, **kwargs):
Project.__init__(self, name, **kwargs)
def unpack(self):
# ... |
# coding: utf-8
"""
39. Testing using the Test Client
The test client is a class that can act like a simple
browser for testing purposes.
It allows the user to compose GET and POST requests, and
obtain the response that the server gave to those requests.
The server Response objects are annotated with the details
of t... |
#!/usr/bin/env python
import os
import sys
import json
import locale
import math
from optparse import OptionParser
from clint.textui import indent, puts, puts_err
import cache
locale.setlocale(locale.LC_ALL, '')
def pretty(x):
return locale.format("%d", x, grouping=True)
def humanize_bytes(bytes, precision=1):... |
from __future__ import unicode_literals
import frappe
import frappe.utils
import json
from frappe.utils.jinja import validate_template
from frappe.model.document import Document
class PrintFormat(Document):
def validate(self):
if (self.standard=="Yes"
and not frappe.local.conf.get("developer_mode")
and not (... |
# -*- coding: utf-8 -*
from setuptools.command.install import install
from setuptools import find_packages
from setuptools import setup
import subprocess
import codecs
import faketime
import sys
import os
class CustomInstall(install):
def run(self):
"""Compile libfaketime."""
if sys.platform == "l... |
from array import array
from gimpfu import *
gettext.install("gimp20-python", gimp.locale_directory, unicode=True)
def zxspectrum(img, layer, hbedge, rgbsat, halftone):
# Store the GIMP's settings so they can be restored when we're finished
gimp.context_push()
# Make all the operations in this filter un... |
"""Tests for object_detection.core.matcher."""
import numpy as np
import tensorflow as tf
from object_detection.core import matcher
class MatchTest(tf.test.TestCase):
def test_get_correct_matched_columnIndices(self):
match_results = tf.constant([3, 1, -1, 0, -1, 5, -2])
match = matcher.Match(match_results... |
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'sudo'
SITENAME = u'Criticón '
HIDE_SITENAME = True
SITEURL = ''
SITELOGO = 'images/logo-criticon-sm.png'
PATH = 'content'
OUTPUT_PATH = '../docs'
TIMEZONE = 'America/Bogota'
DEFAULT_LANG = u'es'
# Feed generation is us... |
from PyQt5.QtCore import pyqtSignal, pyqtSlot
from PyQt5.QtWidgets import QListWidgetItem, QDialog, QDialogButtonBox
from .qtdesigner.ui_QStrChooser import Ui_QStrChooser
class StrChooser(QDialog):
"""
This dialog shows a list of strings. Can filter them and select multiple of
them. On accept dialog emit... |
import pyglet
from pyglet.gl import *
# Imports peng3d (obvious)
import peng3d
langs=["en","de","__"]
def createGUI():
# Adds a Resource Category for later use
# Required to store Images for use in ImageButton, ImageWidgetLayer etc.
# This creates a pyglet TextureBin internally, to bundle multiple images... |
import pytest
from django.db.models import Q
from jx_base.expressions import NULL
from jx_mysql.mysql import MySQL
from jx_mysql.mysql_snowflake_extractor import MySqlSnowflakeExtractor
from mo_files import File
from mo_future import text
from mo_sql import SQL
from mo_testing.fuzzytestcase import assertAlmostEqual
fro... |
import re
from model.contact import Contact
class ContactHelper:
def __init__(self, app):
self.app = app
def fill_form(self, contact):
wd = self.app.wd
self.app.update_text_field("firstname", contact.fname)
self.app.update_text_field("middlename", contact.mname)
self.... |
#Create File Geodatabase
#06/21/2017
#A. Stephens
import arcpy
import os
from arcpy import env
arcpy.env.overwriteOutput = True
out_folder = arcpy.GetParameterAsText (0)#Output Folder, Workspace, Required
inprname = arcpy.GetParameterAsText (1)#Input Project Name, String, Required
incoord = arcpy.GetPa... |
from __future__ import print_function
import argparse
from bcc import BPF, USDT, utils
from time import sleep
import os
# C needs to be the last language.
languages = ["c", "java", "ruby", "tcl"]
examples = """examples:
./uobjnew -l java 145 # summarize Java allocations in process 145
./uobjnew -l c 2... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as 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 'Boostrap3ButtonPlugin.icon_left'
db.add_column(u'aldryn_b... |
"""Send Wake On LAN packets to given MAC addresses.
This is somewhat hard-coded to a Ubuntu installation, and assumes that the SUID
bit has been set on the etherwake binary.
"""
__author__ = 'Robert Pufky'
import cgi
import re
import subprocess
COMPUTERS = {
'Media Center': 'FF:FF:FF:FF:FF:FF',
'Mac Desktop': 'FF... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from tree import Tree
import itertools
"""
Types: Constants defined for each type:
S-expression
├── list -------------> quote ()
└── number -----------> 0
"""
type_tree = Tree.from_tuple(('S-expression',
... |
import pyblish.api
class CollectMindbenderImageSequences(pyblish.api.ContextPlugin):
"""Gather image sequnences from working directory"""
order = pyblish.api.CollectorOrder
hosts = ["shell"]
label = "Image Sequences"
def process(self, context):
import os
import json
from ... |
"""Ce fichier définit la classe Logger, détaillée plus bas."""
import os
import time
from primaires.log.message import Message
# Constantes prédéfinies
# Niveaux d'erreur
DBG = DEBUG = 0
INFO = 1
WARN = WARNING = 2
FATAL = ERROR = EXCEPTION = 3
# Dictionnaire des niveaux
NIVEAUX = {
INFO: "info",
WARNING: "... |
from ventana import Ventana
from formularios import utils
import pygtk
pygtk.require('2.0')
import gtk
from framework import pclases
import mx.DateTime
class VencimientosPendientesPorCliente(Ventana):
def __init__(self, objeto = None, usuario = None):
"""
Constructor. objeto puede ser un objet... |
from itertools import tee
import pytest
import iteration_utilities
def test_ipartition_with_none_predicate():
f, t = iteration_utilities.ipartition([0, 1, 0, 1], pred=None)
assert list(f) == [0, 0]
assert list(t) == [1, 1]
def test_exceptions():
# Random product doesn't work with empty iterables
... |
from ex import *
import ex.pp.mr as mr
def usage():
print('''
map files using specified handler
python reduce_files.py --module={module path string} --input=input_files(wildcard) [--output={output directory}] [--poolsize={number of parallel processes}]
--module: the processing module. this module should contain ... |
"""Get data."""
import functools
import tensorflow as tf
from non_semantic_speech_benchmark import file_utils
def get_data(
file_pattern,
reader,
samples_key,
min_length,
label_key,
label_list,
batch_size,
loop_forever,
shuffle,
shuffle_buffer_size=10000,
label_type=tf.int... |
from collections import OrderedDict
from knack.log import get_logger
logger = get_logger(__name__)
def registry_output_format(result):
return _output_format(result, _registry_format_group)
def usage_output_format(result):
return _output_format(result, _usage_format_group)
def policy_output_format(result... |
import os
from ase.structure import molecule
from ase.io import read, write
from ase.parallel import rank
from gpaw import GPAW, restart
import warnings
# cmr calls all available methods in ase.atoms detected by the module inspect.
# Therefore also deprecated methods are called - and we choose to silence those warni... |
import os, sys, string, gettext, wx
from TextPanel import *
from londonlaw.common.config import *
class HistoryWindow(wx.ScrolledWindow):
def __init__(self, parent):
wx.ScrolledWindow.__init__(self, parent)
# load in the ticket images
self.ticketImages = []
for i in range(5):
filen... |
"""This module contains mainloop wrappers.
Currently only glib main loops are supported."""
from __future__ import absolute_import
__all__ = ("MainLoop", "set_type")
class MainLoop(object):
"""An abstract main loop wrapper class and factory.
Use MainLoop() to get a main loop wrapper object for a main loop... |
import operator # itemgetter
try:
from weakref import WeakSet
except ImportError:
# for py2k
from weakref import ref
class WeakSet(object):
"""Simple weak set implementation.
>>> import gc
>>> ws = WeakSet()
>>> class Test(object):
... pass
>>> x = ... |
"""
Some parts are copied from rest_framework.exceptions, which is licensed under the BSD license:
*******************************************************************************
Copyright (c) 2011-2016, Tom Christie
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, ... |
'Test of DMA load and store'
import numpy as np
from videocore.assembler import qpu
from videocore.driver import Driver
#=================================== 32 bit ===================================
@qpu
def horizontal_32bit_load(asm):
mov(ra0, uniform)
ldi(rb0, 4*16*16)
for i in range(4):
setu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Munch is a subclass of dict with attribute-style access.
>>> b = Munch()
>>> b.hello = 'world'
>>> b.hello
'world'
>>> b['hello'] += "!"
>>> b.hello
'world!'
>>> b.foo = Munch(lol=True)
>>> b.foo.lol
True
>>> b.foo is b['foo'... |
"""
Rotate an array in place
"""
def rotate_to_new_list(l, k):
"""
Return a new list that is the reult of rotating the original list
to the right by k steps.
"""
if l is None:
return None
if len(l) <= 1:
return l
n = len(l)
k = k % n
result = [None] * n
for i in ... |
""" Crops a selected component from a SANS."""
from __future__ import (absolute_import, division, print_function)
from mantid.kernel import (Direction, StringListValidator)
from mantid.api import (DistributedDataProcessorAlgorithm, MatrixWorkspaceProperty, AlgorithmFactory, PropertyMode, Progress)
from sans.common.co... |
from trove.common.db import models
from trove.common.i18n import _
class MongoDBSchema(models.DatastoreSchema):
"""Represents a MongoDB database and its associated properties."""
@property
def _max_schema_name_length(self):
return 64
def _is_valid_schema_name(self, value):
# check ag... |
import json
import pytest
from indy import crypto, error
@pytest.mark.asyncio
async def test_auth_decrypt_works(wallet_handle, identity_steward1, identity_trustee1, message):
(_, my_verkey) = identity_steward1
(_, their_verkey) = identity_trustee1
encrypted_msg = await crypto.auth_crypt(wallet_handle, m... |
# Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: copy
import types
import weakref
from copy_reg import dispatch_table
class Error(Exception):
pass
error = Error
try:
from org.python.core import PyStringMap
except ImportError:
PyStringMap = None
__all__ = ['Error', 'copy', 'deepc... |
import os
import json
import shutil
from urlparse import urlparse
import click
from dsl_parser.parser import parse_from_path
from dsl_parser.exceptions import DSLParsingException
from .. import local
from .. import utils
from ..cli import cfy
from .. import blueprint
from .. import exceptions
from ..config import co... |
import importlib
class IBenchmark:
def __init__(self, params, remaining_args):
self.get_kernel(params, remaining_args)
def measure_power_and_run(self):
results = self.run()
# self.post_process() # TODO
return results
def load_data(self):
params = self.params
... |
# Python import
import sys
# Twisted import
from twisted.internet import reactor, protocol, task
from twisted.python import log
log.startLogging(sys.stdout)
# My import
from pybgp.bgp import message
from pybgp.bgp import State
class BGP(protocol.Protocol):
def __init__(self, asn, hold_time, router_id):
... |
from django.contrib.auth.decorators import login_required
from django.conf.urls import patterns, url
from general.decorators import ajax_only
from .views import CreateStoryView, StoryListView, StoryListAjaxView, \
StoryDetailView, ReadStoryView, BookmarksView, AuthorListView, AuthorListAjaxView,\
ChapterDetailA... |
""" A single or set of synchronous machines for converting mechanical power into alternating-current power. For example, individual machines within a set may be defined for scheduling purposes while a single control signal is derived for the set. In this case there would be a GeneratingUnit for each member of the set a... |
from gettext import gettext as _
import tempfile
import urllib.parse
import os
import logging
from gi.repository import Gio
from gi.repository import Gtk
from sugar3.graphics.palette import Palette
from sugar3.graphics.menuitem import MenuItem
from sugar3.graphics.icon import Icon
from sugar3.graphics import style
fr... |
import unittest
import numpy as np
from op_test import OpTest
class TestSumOp(OpTest):
def setUp(self):
self.op_type = "reduce_sum"
self.inputs = {'X': np.random.random((5, 6, 10)).astype("float64")}
self.outputs = {'Out': self.inputs['X'].sum(axis=0)}
def test_check_output(self):
... |
"""
URL routing for blogs, entries and feeds
"""
from django.conf.urls.defaults import patterns, url
from django.conf import settings
from feeds import LatestEntriesByBlog, LatestEntries #, EntryComments
from models import Blog
from views import generic_blog_entry_view, blog_detail
from viewpoint.settings import USE_C... |
#!/usr/bin/env python
import logging
import os
import re
import subprocess
import time
from osx_browser_driver import OSXBrowserDriver
from webkitpy.benchmark_runner.utils import force_remove
_log = logging.getLogger(__name__)
class OSXSafariDriver(OSXBrowserDriver):
process_name = 'Safari'
browser_name =... |
#!/usr/bin/env python
from .graph_node import SemGraphNode
KNOWN_FLAGS = frozenset(['hidden', 'sibling_higher', 'extinct'])
class TaxonConceptSemNode(SemGraphNode):
def __init__(self, sem_graph, foreign_id):
d = {'class_tag': 'tc', 'context_id': foreign_id}
super(TaxonConceptSemNode, self).__init... |
from hdgwas.hdregression import HASE, A_covariates, A_tests, B_covariates, C_matrix, A_inverse,B4
from hdgwas.tools import study_indexes, Timer
import numpy as np
import os
import time
def merge_PD(path, max_node, study_name):
print ('Merging PD...')
while True:
time.sleep(10)
if np.sum( [ os.p... |
from conans import ConanFile, CMake
import os
# This easily allows to copy the package in other user or channel
channel = os.getenv("CONAN_CHANNEL", "testing")
username = os.getenv("CONAN_USERNAME", "demo")
class HelloReuseConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
requires = ("hello/... |
"""
File: /src/Events.py
Project: Subversion Dump Editor
By: Tim Oram [<EMAIL>]
Website: http://www.mitmaro.ca/projects/svneditor/
http://code.google.com/p/svndumpeditor/
Email: <EMAIL>
Created: September 11, 2009; Updated October 13, 2009
Purpose: Custom events used by the custom wid... |
import hmac
from werkzeug import urls
from odoo import models
from odoo.addons.http_routing.models.ir_http import slug
class MailGroup(models.Model):
_inherit = 'mail.channel'
def _notify_email_header_dict(self):
headers = super(MailGroup, self)._notify_email_header_dict()
base_url = self.e... |
from trytond.model import ModelView
from trytond.wizard import Wizard, StateTransition, StateAction, StateView, Button
from trytond.transaction import Transaction
from trytond.pool import Pool
from trytond.pyson import PYSONEncoder
__all__ = ['CreateAppointmentEvaluation']
class CreateAppointmentEvaluation(Wizard):
... |
from msrest.serialization import Model
class AuthenticationTokenSettings(Model):
"""The settings for an authentication token that the task can use to perform
Batch service operations.
:param access: The Batch resources to which the token grants access. The
authentication token grants access to a lim... |
from .core import Filter
from c7n.exceptions import PolicyValidationError
from c7n.loader import PolicyLoader
from c7n.utils import type_schema
class Missing(Filter):
"""Assert the absence of a particular resource.
Intended for use at a logical account/subscription/project level
This works as an effect... |
import os
import subprocess
import sys
import tempfile
import time
m_dbus = m_polkit = m_aptd = None
def start_dummy_backend():
global m_dbus, m_polkit, m_aptd
# start private dbus
m_dbus = subprocess.Popen(["dbus-daemon",
"--session",
"--nof... |
if False:
mldb_wrapper = None
from mldb import mldb, MldbUnitTest, ResponseException
class RowNumberBuiltinFctTest(MldbUnitTest): # noqa
@classmethod
def setUpClass(cls):
ds = mldb.create_dataset({'id' : 'ds', 'type' : 'sparse.mutable'})
for i in range(4):
ds.record_row(i, [[... |
import re
from typing import Any, Dict, Mapping, Optional
from pathlib import Path
from .filter import Filter
# not supported: .gif, .jpg, .mp3, .ogg, .png, .tiff, .wav
SUPPORTED_EXTENSIONS = (
".csv .doc .docx .eml .epub .json .html .msg .odt .pdf .pptx .ps .rtf .txt .xlsx .xls"
).split()
class FileContent(F... |
from pyanaconda.modules.payloads.constants import PayloadType, SourceType
from pyanaconda.modules.payloads.payload.payload_base import PayloadBase
from pyanaconda.modules.payloads.payload.live_image.live_image_interface import \
LiveImageInterface
from pyanaconda.modules.payloads.source.factory import SourceFactory... |
"""project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-ba... |
from django.db import models
from ckeditor.fields import RichTextField
import datetime
import platform
##ckeditor,现在还没用上
class Blog(models.Model):
title = models.CharField(max_length = 50, verbose_name = "标题")
content = RichTextField(blank = True, null = True, verbose_name = "内容")
def __unicode__(sel... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
##################################################
# GNU Radio Python Flow Graph
# Title: Mpsk Stage6
# Generated: Tue Jun 20 15:21:39 2017
##################################################
if __name__ == '__main__':
import ctypes
import sys
if sys.platform.s... |
import unittest
import email
from pixelated.maintenance import delete_all_mails, load_mails
from pixelated.bitmask_libraries.session import LeapSession
from leap.mail.imap.account import SoledadBackedAccount
from leap.mail.imap.fields import WithMsgFields
from leap.soledad.client import Soledad
from leap.soledad.commo... |
import asyncio
import os
import signal
import threading
import traceback
import sys
import cloudbot
if cloudbot.dev_mode.get("pympler", False):
try:
import pympler
import pympler.muppy
import pympler.summary
import pympler.tracker
except ImportError:
pympler = None
else... |
from kubernetes_py.models.v1.PersistentVolumeSpec import PersistentVolumeSpec
from kubernetes_py.models.v1.ResourceRequirements import ResourceRequirements
from kubernetes_py.models.v1beta1.LabelSelector import LabelSelector
from kubernetes_py.utils import is_valid_list, is_valid_string
class PersistentVolumeClaimSpe... |
"""Creates a line item creative association for a creative set.
To create creative sets, run create_creative_set.py. To create creatives, run
create_creatives.py. To determine which LICAs exist, run get_all_licas.py.
The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By def... |
"""Injection stage filter."""
from itertools import filterfalse
class InjectionStageFilter:
"""Filter records by "injection_stage" property.
Args:
records: A list of records to filter.
keywords: Filter keywords.
For multiple keywords put them in a list.
Attributes:
... |
"""Windows can't run .sh files, so this is a Python implementation of
update.sh. This script should replace update.sh on all platforms eventually."""
import os
import re
import shutil
import subprocess
import sys
# Do NOT CHANGE this if you don't know what you're doing -- see
# https://code.google.com/p/chromium/wiki... |
#-*- encoding: utf-8 -*-
from django.shortcuts import render_to_response
from django import forms
import os
from django.http.response import HttpResponse, HttpResponseRedirect
from django.template.loader import get_template
from tarfile import pwd
from clouddesktop.util import load_data
from django.core.files.uploadedf... |
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (built by setup.py sdist) and build
# directories (produced by setup.py build) will contain a much shorter file
# that just contains th... |
# -*- coding: utf-8 -*-
"""Click commands."""
import os
from glob import glob
from subprocess import call
import click
from flask import current_app
from flask.cli import with_appcontext
from werkzeug.exceptions import MethodNotAllowed, NotFound
from api.extensions import db
HERE = os.path.abspath(os.path.dirname(__... |
from matplotlib.backend_bases import FigureCanvasBase
from matplotlib.backend_bases import RendererBase
from matplotlib.testing.decorators import image_comparison
import matplotlib.pyplot as plt
import matplotlib.transforms as transforms
import matplotlib.path as path
import numpy as np
import os
import shutil
import... |
"""Add grating_couplers to a component."""
from typing import Callable, List, Tuple
from phidl.device_layout import Label
import pp
from pp.cell import cell
from pp.component import Component
from pp.components.grating_coupler.elliptical_trenches import (
grating_coupler_te,
grating_coupler_tm,
)
from pp.rout... |
# coding=utf-8
__author__ = "AstroPrint Product Team <<EMAIL>>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2017-2019 3DaGoGo, Inc - Released under terms of the AGPLv3 License"
from . import PluginService
from octoprint.server import UI_API_KE... |
"""
Data Preprocessing
"""
__author__ = ["Carlos Eduardo Cancino Cha\'on"]
__email__ = "<EMAIL>"
__version__ = "11503.03"
import numpy as np
from scipy import linalg
class DataPreprocessing():
def fit(self,input_array):
self.x = np.asarray(input_array)
self.mean = np.mean(input_array, ax... |
# encoding: utf-8
"""
@version: python3.6
@author: ‘sj‘
@contact: <EMAIL>
@file: boll-trend-3.1.py
@time: 12/14/17 1:29 PM
"""
from backtest.core.backteststrategy_test import *
from backtest.optimizer.optimizer import *
from backtest.tools.ta import *
from datetime import datetime as dtL
class BollStrategyTrend(Ba... |
from cvxopt import matrix,spmatrix,sparse,exp
from cvxopt.blas import dot,dotu
from cvxopt.solvers import qp
import numpy as np
import pylab as pl
class Kernel:
def __init__(self):
pass
@staticmethod
def get_kernel(X, Y, type='linear', param=1.0):
"""Calculates a kernel given the data X and Y (dims x exms)"""... |
import logging
import unittest
logging.basicConfig(level=logging.DEBUG)
from pymothoa.jit import JITModule, function
from pymothoa.compiler_errors import *
from pymothoa.types import *
from pymothoa.dialect import *
dummy = JITModule('testerror')
@dummy.function(ret=Int, later=True)
def test_no_ret():
pass
@dumm... |
"""RAM-based database"""
import datetime
import logging
import sys
from biryani import strings
import pymongo
import threading2
from . import conf
from .ramindexes import *
categories_slug_by_tag_slug = {}
categories_slug_by_word = {}
category_by_slug = {}
category_slug_by_pivot_code = {}
icon_classes_by_schema_n... |
import logging
from optparse import make_option
from django.core.management import BaseCommand
from corehq.apps.app_manager.models import Application
from dimagi.utils.couch.database import iter_docs
logger = logging.getLogger('app_migration')
logger.setLevel('DEBUG')
def get_all_app_ids(include_builds=False):
k... |
import _cffi_backend
ffi = _cffi_backend.FFI(b"manual2",
_version = 0x2601,
_types = b'\x00\x00\x01\x0D\x00\x00\x07\x01\x00\x00\x00\x0F\x00\x00\x00\x09\x00\x00\x00\x0B\x00\x00\x01\x03',
_globals = (b'\xff\xff\xff\x0bAA',0,b'\xff\xff\xff\x0bBB',-1,b'\xff\xff\xff\x0bCC',2,b'\xff\xff\xff\x1fFOO',0x999999... |
"""Test mongo using the synchronizer, i.e. as it would be used by an
user
"""
import time
import unittest
import os
import sys
import inspect
import socket
sys.path[0:0] = [""]
try:
from pymongo import MongoClient as Connection
except ImportError:
from pymongo import Connection
from tests.setup_cluste... |
#!/usr/bin/python
import sys
import os
if len(sys.argv) >= 4:
pos_filename = sys.argv[1]
neg_filename = sys.argv[2]
FDR = float(sys.argv[3])
input_filename = sys.argv[4]
output_filename = sys.argv[5]
else:
print("usage: ./ROC.py pos_filename neg_filename FDR output_filename")
print("or ")
... |
'''
Copyright (C) 2016 Fin Christensen
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 2
of the License, or (at your option) any later version.
This program is distributed in the hop... |
import os, sys, string, socket, errno
from StringIO import StringIO
import cgi
import codecs
#sys.stdout = codecs.getwriter("utf-8")(sys.stdout)
#sys.stderr = codecs.getwriter("utf-8")(sys.stderr)
#---------------------------------------------------------------------------
# Set various FastCGI constants
# Max... |
"""changes to allow biweekly digest
Revision ID: 8ac7c042469
Revises: 2303f398cc0e
Create Date: 2015-09-14 14:53:27.438500
"""
# revision identifiers, used by Alembic.
revision = '8ac7c042469'
down_revision = '2303f398cc0e'
from alembic import op
import sqlalchemy as sa
from purchasing.opportunities.models import ... |
from django.core.exceptions import ObjectDoesNotExist
from rest_framework import test
from waldur_core.core import utils as core_utils
from waldur_mastermind.marketplace import models as marketplace_models
from waldur_mastermind.marketplace import tasks as marketplace_tasks
from waldur_mastermind.marketplace.plugins i... |
'''
Factory object
==============
The factory can be used to automatically import any class from a module,
by specifying the module to import instead of the class instance.
The class list and available modules are automatically generated by setup.py.
Example for registering a class/module::
>>> from kivy.factor... |
"""TensorBoard server handler logic.
TensorboardHandler contains all the logic for serving static files off of disk
and for handling the API calls to endpoints like /tags that require information
about loaded events.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import pri... |
"""
"""
__author__ = "Xun Li <<EMAIL>>"
__all__ = ['DynamicMapWidget','DynamicPlotMapWidget']
import os
import wx
from wx import xrc
import numpy as np
import stars
from MapWidget import MapWidget
from AbstractCanvas import AbstractCanvas
from AbstractWidget import AbstractWidget
from utils import *... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible import errors
try:
import netaddr
except ImportError:
# in this case, we'll make the filter return an error message (see bottom)
netaddr = None
class FilterModule(object):
''' IP addresses within IP ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.