src stringlengths 721 1.04M |
|---|
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='microscan',
version=... |
"""!
@brief Examples of usage and demonstration of abilities of Hysteresis Oscillatory Network.
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2020
@copyright BSD-3-Clause
"""
from pyclustering.nnet.hysteresis import hysteresis_network, hysteresis_visualizer;
from pyclustering.nnet import *;... |
import numpy as np
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from numpy.testing import assert_array_almost_equal
from skgarden.quantile import DecisionTreeQuantileRegressor
from skgarden.quantile import ExtraTreeQuantileRegressor
from skgarden.quantile.utils import w... |
"""
MAP Client, a program to generate detailed musculoskeletal models for OpenSim.
Copyright (C) 2012 University of Auckland
This file is part of MAP Client. (http://launchpad.net/mapclient)
MAP Client is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public Li... |
# coding=utf-8
from __future__ import unicode_literals
import pytest
import re
import capybara
class TestHasText:
def test_is_true_if_the_given_text_is_on_the_page_at_least_once(self, session):
session.visit("/with_html")
assert session.has_text("est")
assert session.has_text("Lorem")
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Maria Isabel Restrepo
# @Date: 2014-01-08 14:34:42
# @Last Modified by: Maria Isabel Restrepo
# @Last Modified time: 2014-01-15 10:20:14
#
# A file to generate rigid transformations
import rotations
import transformations as tf
import numpy as np
for trial... |
# -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2013 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pu... |
from django.shortcuts import render_to_response
from django.shortcuts import render ,redirect
from django.template.context import RequestContext
from corporaciones.models import Corporacion , Sede
from django.contrib.auth.decorators import permission_required
from corporaciones.forms import FormularioRegistroCorporacio... |
"""
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distri... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-07-13 22:59
from __future__ import unicode_literals
import core.models
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('patient', '0001_initi... |
# Functions to preprocess Train_user and Test_user
# Pecoraro Cyril
import pandas as pd
import numpy as np
import os
from IPython.display import Image
from IPython.core.display import HTML
import matplotlib.pyplot as plt
import random
from datetime import datetime
import seaborn as sns
from pandas.tools.plotting im... |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
# Copyright (C) 2014-2017 New York University
# This file is part of ReproZip which is released under the Revised BSD License
# See file LICENSE for full license details.
from __future__ import division, print_function, unicode_literals
from qtpy import QtCore, QtWidgets
import yaml
import reprounzip_qt.reprounzip_i... |
# Copyright 2017 Workonline Communications (Pty) Ltd. All rights reserved.
#
# The contents of this file are licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with the
# License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LIC... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-04-21 23:16
from __future__ import unicode_literals
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
... |
# -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals
from django import forms
... |
# coding: utf-8
""" A script for making figures for the Spitzer proposal """
from __future__ import division, print_function
__author__ = "adrn <adrn@astro.columbia.edu>"
# Standard library
import os, sys
import cPickle as pickle
# Third-party
from astropy.io import ascii
import astropy.units as u
import numpy as ... |
from ..DiffusionModel import DiffusionModel
import numpy as np
import future.utils
__author__ = 'Giulio Rossetti'
__license__ = "BSD-2-Clause"
__email__ = "giulio.rossetti@gmail.com"
class IndependentCascadesModel(DiffusionModel):
"""
Edge Parameters to be specified via ModelConfig
:param thresh... |
"""
FLI.camera.py
Object-oriented interface for handling FLI USB cameras
author: Craig Wm. Versek, Yankee Environmental Systems
author_email: cwv@yesinc.com
"""
__author__ = 'Craig Wm. Versek'
__date__ = '2012-08-08'
import sys, time, warnings, traceback
try:
from collections import OrderedDict
e... |
#!/usr/bin/env python
#
# Copyright 2014 Cosmos.io
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
from math import sqrt
import Slope
class Simulation:
SIM_STEP_SIZE = 0.0001
const_g = -981
def __init__ (self, slope, **kwargs):
self.slope = slope
self.t = [0]
self.x = [Simulation.SIM_STEP_SIZE]
self.mom_inertia_coefficient = 0
for name, value in kwargs.items():
... |
#!/usr/bin/env python
'''
DANGER. THIS WILL WIPE AN ENTIRE ANACONDA.ORG REPOSITORY CHANNEL.
YOU HAVE BEEN WARNED.
'''
import argparse
from subprocess import check_output, STDOUT
def choose(answer):
answer = answer.upper()
if answer == 'Y' or answer == 'YES':
return True
return False
def prompt... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# $Id$
# Last modified Wed Jul 7 20:51:13 2010 on stalker
# update count: 102
#
# subdms - A document management system based on subversion.
# Copyright (C) 2009 Albert Thuswaldner
#
# This program is free software: you can redistribute it and/or modify
# it under the te... |
import cv
import os
from os.path import join
from django.conf import settings
def find_faces( img_url ):
cascade = cv.Load( join(settings.ROOT_DIR,'apps/WebUi/haarcascade_frontalface_alt.xml') )
directory= join(settings.MEDIA_ROOT , 'Uploads/')
target_directory = join( directory, 'Portraits/')
portrait... |
'''
ZMQ handling, takes care of the per-flask-instance initialization, and
provides a highlevel communication API for the app
'''
import zmq
import json
from pprint import pprint
import aegir.config
_ctx = None
_socket_pr = None
def init(app):
app.before_first_request(instance_init)
pass
def instance_init(... |
# -*- coding: utf-8 -*-
#
# ForgeryPy documentation build configuration file, created by
# sphinx-quickstart on Wed Jul 11 20:31:25 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# A... |
from hpp.corbaserver.rbprm.rbprmbuilder import Builder
from hpp.corbaserver.rbprm.rbprmfullbody import FullBody
from hpp.gepetto import Viewer
from tools import *
import walkBauzil_hrp2_pathKino as tp
import time
import omniORB.any
packageName = "hrp2_14_description"
meshPackageName = "hrp2_14_description"
rootJointT... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: wushuiyong
# @Created Time : 日 1/ 1 23:43:12 2017
# @Description:
import time
from datetime import datetime
import os
import pwd
import re
from flask import current_app
from flask_socketio import emit
from walle.model.project import ProjectModel
from walle.mo... |
from functools import wraps
from inspect import signature
from . import utils
@utils.optional_arguments
def simple_instruction(f, multiple_return_items=False):
'''
Wraps an instruction funtion ``f`` to have it take its arguments from
Push stacks and add the return value to the ``exec``.
It requires ... |
import os
import numpy as np
import cv2
# Custom modules
from common import cameraTrigger as ct
from common import constantSource as cs
import cameraRectify as cr
from common import miscellaneous as msc
TOTAL_PICS = cs.getCalibReq()
while True:
q = input("Do you want to perform camera caliberation? (y/n): ")
... |
from ..remote import RemoteModel
class VlanNetworkExplorerSummariesSummaryGridRemote(RemoteModel):
"""
| ``VlanID:`` none
| ``attribute type:`` string
| ``VlanMemberID:`` none
| ``attribute type:`` string
| ``BridgeMemberInd:`` none
| ``attribute type:`` string
| ``RootVla... |
# coding:utf-8
from ..const import *
err_msg = {
ERR_URL_NOT_RECOGNIZED: "网址不够绅士",
ERR_CANT_DOWNLOAD_EXH: "需要登录后才能下载里站",
ERR_ONLY_VISIBLE_EXH: "这个本子只有里站能看到",
ERR_MALFORMED_HATHDL: "hathdl文件有猫饼,解析失败",
ERR_GALLERY_REMOVED: "这个本子被移除了,大概里站能看到",
ERR_KEY_EXPIRED: "下载链接不太正常",
ERR_NO_PAGEURL_FOUND... |
#!/usr/bin/python
# coding: utf-8
'''
File: tiger.py
Author: Oliver Zscheyge
Description:
Access the TIGER corpus with NLTK.
Implementation based on (section "Loading your own Corpus"):
http://nltk.org/book/ch02.html
'''
import os.path as op
from cPickle import dump, load
from lxml import etree
impo... |
"""
Description:
Creates content within an Oracle UCM instance
Author:
A Mancevice
Project Resources:
"webservice" - URL of the UCM Web Service
"user" - username for the UCM Instance
"password" - password for the UCM Instance
"verbose" - toggle logging. If set to True, service calls will
will be... |
# Copyright (c) 2015, MapR Technologies
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
# -*- coding: utf-8 -*-
import uuid
import fauxfactory
import pytest
from utils import error
from cfme.base.credential import Credential
from cfme.common.provider_views import (InfraProviderAddView,
InfraProvidersView,
InfraProvidersDisc... |
"""CLI tests for ``katello-agent``.
:Requirement: Host
:CaseAutomation: Automated
:CaseLevel: Component
:CaseComponent: Katello-agent
:Assignee: gtalreja
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
import time
import pytest
from broker import VMBroker
from robottelo.api.utils import wait_for... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import urllib2
import base64
import json
import urlparse
import time
from datetime import datetime
from argparse import ArgumentParser
def prepareLog():
global logFile
logFilePath = scriptPath + '/gfwlist2dnsmasq.log'
# The maximum log file si... |
from __future__ import absolute_import, print_function
import base64
import logging
import six
import traceback
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.http import HttpResponse, H... |
'''Label
=====
The :class:`Label` widget is for rendering text. It supports ascii and unicode
strings::
# hello world text
l = Label(text='Hello world')
# unicode text; can only display glyphs that are available in the font
l = Label(text=u'Hello world ' + unichr(2764))
# multiline text
l = ... |
'''
md2tex.py
- author: Richard Dong
- description: Convert markdown to latex
'''
from __future__ import print_function
import re
import io
import sys
import argparse
import markdown
class State:
NORMAL = 0
RAW = 1
class Handler:
def __init__(self):
self.vars = dict()
self.state = State.NORMAL
sel... |
import os
import unittest
from collections import OrderedDict
from conans.model.ref import ConanFileReference
from conans.test.utils.tools import (TestClient, TestServer, NO_SETTINGS_PACKAGE_ID, TurboTestClient,
GenConanfile)
from conans.util.files import load
class DownloadTest(... |
import numpy as np
import pytest
import pandas as pd
from pandas import DataFrame, Series, Timestamp
import pandas._testing as tm
class TestDataFrameQuantile:
@pytest.mark.parametrize(
"df,expected",
[
[
DataFrame(
{
0: Serie... |
#!/usr/bin/python
# Copyright (C) 2013 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of c... |
import collections
import sys
from django.conf import settings
from django.core.management.color import color_style
from django.utils.encoding import force_str
from django.utils.itercompat import is_iterable
from django.utils import six
class ModelErrorCollection:
def __init__(self, outfile=sys.stdout):
... |
#!/usr/bin/env python2
##
# autosign
# https://github.com/leosartaj/autosign.git
#
# copyright (c) 2014 sartaj singh
# licensed under the mit license.
##
import unittest
import os, shutil
import helper
from autosign.main import removeSign, isSign
from autosign.exce import UnsignedError
class TestremoveSign(unittest... |
"""Python part of the warnings subsystem."""
# Note: function level imports should *not* be used
# in this module as it may cause import lock deadlock.
# See bug 683658.
import sys, types
import linecache
__all__ = ["warn", "showwarning", "formatwarning", "filterwarnings",
"resetwarnings"]
# filters conta... |
"""Add an address translation to an IPSEC tunnel context."""
# :license: MIT, see LICENSE for more details.
import click
import SoftLayer
from SoftLayer.CLI import environment
# from SoftLayer.CLI.exceptions import ArgumentError
# from SoftLayer.CLI.exceptions import CLIHalt
@click.command()
@click.argument('contex... |
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... |
# These are linting checks used in the chalice codebase itself.
# These are used to enforce specific coding standards and constraints.
from pylint.checkers import BaseChecker
from pylint.interfaces import IAstroidChecker
from astroid.exceptions import InferenceError
import astroid
def register(linter):
linter.reg... |
import sqlite3
import urllib
import re
from urllib.request import urlopen
from bs4 import BeautifulSoup, NavigableString
from phyllo.phyllo_logger import logger
import nltk
from itertools import cycle
nltk.download('punkt')
from nltk import sent_tokenize
def parseRes2(soup, title, url, cur, author, date, collectiont... |
# Copyright 2012 IBM Corp.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
#!/usr/bin/python
# -*- coding: utf-8
import httplib, urllib,time
import requests
import xml.etree.ElementTree as etree
import re
from icelog import *
from my import curdate2my
from datetime import datetime
import dbIceCash as db
ns={\
"c":"http://fsrar.ru/WEGAIS/Common",\
"wbr":"http://fsrar.ru/WEGAIS/TTNInformF2Reg"... |
import math
import nltk
import time
import sys
# Constants to be used by you when you fill the functions
START_SYMBOL = '*'
STOP_SYMBOL = 'STOP'
MINUS_INFINITY_SENTENCE_LOG_PROB = -1000
log2 = lambda x: math.log(x, 2)
# TODO: IMPLEMENT THIS FUNCTION
# Calculates unigram, bigram, and trigram probabilities given a tra... |
import re
import sqlalchemy as sa
from sqlalchemy import cast
from sqlalchemy.dialects.postgresql import ARRAY, ENUM
def sql_enum_to_list(value):
"""
Interprets PostgreSQL's array syntax in terms of a list
Enums come back from SQL as '{val1,val2,val3}'
"""
if value is None:
return []
... |
from flask import Blueprint, request
from .._config import AUTH
from .._query import execute_query, QueryBuilder
from .._validate import check_auth_token, extract_integers, extract_strings, require_all
# first argument is the endpoint name
bp = Blueprint("ght", __name__)
alias = None
@bp.route("/", methods=("GET", ... |
from numpy.matlib import *
from numpy.linalg import *
import numpy as np
import time
class Leader:
def __init__(self, kp, kd, dt, state = array([[0], [0], [0], [0]])):
self.A = array([[-kp+kd/dt, -kd/dt, 0, 0], [1, -1, 0, 0], [0, 0, -kp+kd/dt, -kd/dt], [0, 0, 1, -1]])
self.B = array([[kp, 0], [0, 0], [0, kp], ... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
from copy import copy, deepcopy
lights = []
with open("Day_18.input") as f:
for line in f:
data = line.strip()
light_temp = list(data)
lights.append(light_temp)
def getNeighbours(j, k, lights):
dx = [0, 1, -1]
dy = [0, 1, -1]
neighbours = 0
for x in dx:
for y in dy:
if j+x >= 0 and j+x < len(lights[0]... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import csv
import time
import sys
import subprocess
import codecs
from utils import *
import unicodedata
import argparse
import cPickle as pickle
reload(sys)
sys.setdefaultencoding('utf8')
# pattern for removing redundunt spaces
space_pat = re.compile(u'\s\s+', ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that computes the sentiment for a given text and a given
map with word => (valence, arousal)
"""
from nltk.tokenize import PunktWordTokenizer
from nltk.stem import SnowballStemmer
STEMMER = SnowballStemmer('spanish')
def get_sentiment(sentiment_db, txt... |
from __future__ import unicode_literals
import datetime
import unittest
import uuid
from copy import deepcopy
from django.core.exceptions import FieldError
from django.db import DatabaseError, connection, models, transaction
from django.db.models import TimeField, UUIDField
from django.db.models.aggregates import (
... |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
#!/usr/bin/env python
'''Tool to generate computationally-rarefied graphs kmer spectra'''
import sys
import os
import argparse
import matplotlib as mpl
import numpy as np
import scipy.stats
from ksatools.rare import fract, rich, calc_resampled_fraction, calc_resampled_richness, plotme
from ksatools.ksatools import l... |
# -*- coding: utf-8 -*-
import imp
import ipdb
import logging
from sys import modules, meta_path
from os import mkdir
from os.path import (
isdir,
abspath,
dirname,
exists,
join,
)
import encodings.idna
import requests
from git import Repo
from packyou import find_module_path_in_cloned_repos
from... |
import networkx as nx
import json
import codecs
import numpy as np
import community
import os.path
POPULAR = 4
AVERAGE = 3
UNPOPULAR = 2
DATASET_FNAME = "../Dataset/Output/articles_labeled.json"
# Used in each step of the Girvan-Newman clustering algorithm
# Functionally equivalaent to networkx's edge_betweenness_ce... |
## @file
# This file is used to define class for data type structure
#
# Copyright (c) 2011 - 2018, Intel Corporation. All rights reserved.<BR>
#
# This program and the accompanying materials are licensed and made available
# under the terms and conditions of the BSD License which accompanies this
# distribution... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
import smbus
import time
import os
import RPi.GPIO as GPIO
bus = smbus.SMBus(1)
# Set PPM limit variable to whatever would be an alarm for you
# For Uncalibrated sensors, use your better judgement or get it calibrated (390 is a fresh air outdoor baseline, depending on area).
# Sensor can also be calibrated by immersi... |
# coding: utf-8
from __future__ import unicode_literals
import base64
import datetime
import hashlib
import json
import netrc
import os
import random
import re
import socket
import sys
import time
import math
from ..compat import (
compat_cookiejar,
compat_cookies,
compat_etree_fromstring,
compat_getp... |
# Python 3
import fileinput
import glob
import shutil
import sys
import os
import re
import distutils.dir_util
VERSION_SHORT = "v.31"
VERSION_FULL = VERSION_SHORT + ", released 3 April 2021"
EXEC_UGLIFYJS_WIN = "{2}/lib/uglifyjs.cmd --parse bare_returns --compress --mangle toplevel --mangle-props keep_quoted,reserve... |
# vi: ts=4 expandtab
#
# Copyright (C) 2012 Canonical Ltd.
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P.
# Copyright (C) 2012 Yahoo! Inc.
# Copyright (C) 2014 Amazon.com, Inc. or its affiliates.
#
# Author: Scott Moser <scott.moser@canonical.com>
# Author: Juerg Haefliger <juerg.haefl... |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... |
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2014 Thomas Voegtlin
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at y... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: run-atari.py
# Author: Yuxin Wu <ppwwyyxxc@gmail.com>
import numpy as np
import tensorflow as tf
import os, sys, re, time
import random
import argparse
import six
from tensorpack import *
from tensorpack.RL import *
IMAGE_SIZE = (84, 84)
FRAME_HISTORY = 4
CHANNEL... |
from datetime import datetime
from django.core.urlresolvers import reverse
from django.db.models import Q
from corehq import Domain
from corehq.apps.programs.models import Program
from corehq.apps.reports.commtrack.standard import CommtrackReportMixin
from corehq.apps.reports.filters.dates import DatespanFilter
from co... |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
import numpy as np
from pathlib import Path
import pyro
import pyro.distributions as dist
from pyro.infer import SVI, Trace_ELBO
import torch
import torch.nn as nn
from tqdm import tqdm
class Encoder(nn.Module):
def __init__(self... |
# * coding: utf8 *
#
# This file is part of CERN Analysis Preservation Framework.
# Copyright (C) 2016 CERN.
#
# CERN Analysis Preservation Framework 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 vers... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import logging
import redis
from curl2share import config
class Redis(object):
"""
Interact with redis to insert, retrieve, delete
metadata of file object in/from Redis.
REMEMBER: Redis is a caching layer.
... |
__author__ = 'yinjun'
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param l1: the first list
# @param l2: the second list
# @return: the sum list of l1 and l2
def addLists(self, l1, l2):
... |
# -*- coding: utf-8 -*-
import base64
import pytest
import hashlib
from falcon.testing import TestBase
from falcon import API
from falcon import status_codes
from graceful.resources.base import BaseResource
from graceful import authentication
from graceful import authorization
@authorization.authentication_required... |
from boxbranding import getMachineBrand, getMachineName
from twisted.web import client
from twisted.internet import reactor, defer
from urlparse import urlparse
class HTTPProgressDownloader(client.HTTPDownloader):
def __init__(self, url, outfile, headers=None):
client.HTTPDownloader.__init__(self, url, outfile, h... |
import pytest
from roam.editorwidgets.numberwidget import NumberWidget, DoubleNumberWidget
config = {
"prefix": "test_pre",
"suffix": "test_suf",
"max": 100,
"min": 0
}
def test_should_return_same_value():
widget = NumberWidget().createWidget(None)
wrapper = NumberWidget(widget=widget)
wr... |
"""This module implements the training for lasagne models.
The classes are designed to train a lasagne model on a fixed data set
with different learning rates. The training schedule can be epoch or
iteration based.
The classes print the training and test error to the standard output
every epoch or in a given interval ... |
import pytest
import numpy as np
import pandas as pd
from pandas.util.testing import assert_frame_equal
import fishact
def test_sniffer():
n_header, delimiter, line = fishact.parse._sniff_file_info(
'tests/single_gtype.txt')
assert n_header == 2
assert deli... |
#!/usr/bin/env python
from time import sleep
from time import strftime
import RPi.GPIO as GPIO
import os
import paho.mqtt.publish as publish
import paho.mqtt.client as mqtt
from datetime import datetime
PIR=26
SCREEN_TIMEOUT=300
SCREEN='/sys/class/backlight/rpi_backlight/bl_power'
ON=0
OFF=1
TOPIC="presence/PIR"
GPI... |
import urllib
from django.db.models import Avg, Sum, Count
from django import forms
from django.forms.widgets import Input
from django.shortcuts import render
from colourlens.models import Artwork, Colour
PROM_ATTRS = {'min': '0', 'max': '100', 'step': '5'}
DIST_ATTRS = {'min': '0', 'max': '50', 'step': '1'}
class R... |
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
__license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import sys, os, shutil, plistlib, subprocess, glob, zipfile, tempfile, \
py_compi... |
import asyncio
class StreamConsumedError(Exception):
"""Same name as request error"""
pass
class HttpStream:
"""An asynchronous streaming body for an HTTP response
"""
def __init__(self, response):
self._response = response
self._streamed = False
self._queue = asyncio.Que... |
from django.db import models
from django.contrib.auth.models import User
class Guy(models.Model):
user = models.OneToOneField(User, primary_key=True)
cell = models.CharField(max_length=15)
metroarea_name = models.CharField(max_length=30, default=None, null=True)
metroareaID = models.IntegerField(defau... |
"""
usage: threshold_custom = tb.SimpleTrackbar(img, "ImgThresh")
"""
import cv2
import numpy as np
def empty_function(*arg):
pass
def SimpleTrackbar(img, win_name):
trackbar_name = win_name + "Trackbar"
cv2.namedWindow(win_name)
cv2.createTrackbar(trackbar_name, win_name, 0, 255, empty_function)
... |
"""
Clickjacking Protection Middleware.
This module provides a middleware that implements protection against a
malicious site loading resources from your site in a hidden frame.
"""
from django.conf import settings
class XFrameOptionsMiddleware(object):
"""
Middleware that sets the X-Frame-Optio... |
import os
import re
import codecs
import struct
paths = [p for p in os.listdir(".") if not(p.endswith(".ct"))]
for src in os.listdir("."):
if (src.endswith(".py")):
continue
dest = src.replace(".cpp", ".ct")
with codecs.open(src, "rb") as stream:
data = stream.read()
pattern = re.compile(b"\\s*(0x[0-9A... |
import pickle
import retino
from retino.plot import *
from retino.utils import *
sns.set_style("ticks")
def plot_axon_growth_direction_algorithm(origin, end, target, ax):
a_origin = origin
a_end = end
desired_direction_weight = 1.1
momentum_direction_weight = 1
desired_direction = get_unit_dir... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may... |
# coding: utf-8
"""Source: lookup_www.common.utils.tests.test_utils_test.
"""
from __future__ import absolute_import, print_function, unicode_literals
from django.test import SimpleTestCase, TestCase
from django.utils import six
class FunctionsTest(TestCase): # TODO: change to SimpleTestCase or unittest.TestCase?
... |
# gaf.netlist - gEDA Netlist Extraction and Generation
# Copyright (C) 1998-2010 Ales Hvezda
# Copyright (C) 1998-2010 gEDA Contributors (see ChangeLog for details)
# Copyright (C) 2013-2019 Roland Lutz
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Publ... |
'''
Handle manager: ensure only one handle set is active.
HandleSet's are not in the model.
An active HandleSet is in the scheme and is drawn.
Generally Handle's draw on top of the morphs they handle.
However, it may be drawn invisibly !!!
E.G. points may be hidden by lines they handle.
E.G. style of handles may be ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.