content stringlengths 4 20k |
|---|
from captcha.conf import settings
from captcha.helpers import captcha_image_url, captcha_audio_url
from captcha.models import CaptchaStore
from django.http import HttpResponse, Http404
from django.core.exceptions import ImproperlyConfigured
from ranged_response import RangedFileResponse
import random
import tempfile
im... |
import os
from flask import Flask
from flask import render_template
from flask import url_for
from flask import request
from twilio import twiml
from twilio.util import TwilioCapability
# Declare and configure application
app = Flask(__name__, static_url_path='/static')
app.config.from_pyfile('local_settings.py')
... |
from portality import models
batch_size = 1000
total=0
batch = []
suggestion_iterator = models.Suggestion.iterall(page_size=10000)
for s in suggestion_iterator:
update_deposit_policies = {
'Héloïse': 'Héloïse',
'Diadorum': 'Diadorim'
}
changed = False
for old, new in update_deposit_p... |
"""
Introduce some basic refactoring functions to |jedi|. This module is still in a
very early development stage and needs much testing and improvement.
.. warning:: I won't do too much here, but if anyone wants to step in, please
do. Refactoring is none of my priorities
It uses the |jedi| `API <plugin-a... |
# -*- coding: utf-8 -*-
"""
Permette di spostarsi tra le coordinate della stessa area o in aree differenti
da quella in cui si trova l'amministratore del Mud.
"""
#= IMPORT ======================================================================
from src.command import get_command_syntax
from src.config import co... |
import string
def generate_starts(prefix, words):
starts = []
for w in words:
if w.startswith(prefix):
starts.append(w)
return starts
def generate_ends(sufix, words):
ends = []
for w in words:
if w.endswith(sufix):
ends.append(w)
return ends
def gene... |
from oocs.io import Config, message_add, quote
class Packages(object):
module_name = 'packages'
def __init__(self, verbose=False):
self.verbose = verbose
self.scan = {
'module' : self.module_name,
'checks' : {},
'status' : {}
}
try:
... |
import sys
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtWebKit import *
class Browser:
def run(self):
self.web = QWebView()
self.web.load(QUrl("http://gabrielecirulli.github.io/2048/"))
self.web.page().frameCreated.connect(self.onInit)
self.web.show()
d... |
"""
The module implements page downloading. done
Authors: songyue02(<EMAIL>)
Date: 2016/06/04
"""
import re
import logging
import requests
# get log singleton
log = logging.getLogger('Spider.crawler')
def make_url_good(raw_value):
"""
Deal with the http header of url
Args:
... |
from ....const import GRAMPS_LOCALE as glocale
_ = glocale.get_translation().gettext
#-------------------------------------------------------------------------
#
# GRAMPS modules
#
#-------------------------------------------------------------------------
from .._regexpidbase import RegExpIdBase
#--------------------... |
from __future__ import print_function
import pytest
from SumList import sum_value
'''Arguments as lists'''
only_numbers = [1, 2, 3, 4]
numbers_as_string = ['1', '2', '3', '4']
combined_string_numbers = ['1', 2, 3, '4']
fail_not_number = ['d', '1', 3]
empty_list = []
with_floats_to_int = ['1.0', '2.0', 3, '4']
with_fl... |
"""Benchmark for Keras text vectorization preprocessing layer's adapt method."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import numpy as np
from tensorflow.python import keras
from tensorflow.python.compat import v2_compat
from tensorfl... |
import sys
import socket
import unittest
import test_utils
sys.path.insert(1, sys.path[0]+'/../../../python')
from pysandesh.sandesh_base import *
from gen_py.msg_test.ttypes import *
class SandeshTraceTest(unittest.TestCase):
def setUp(self):
self._sandesh = Sandesh()
http_port = test_utils.get_... |
import os
from rbuild_test import rbuildhelp
from testutils import mock
from conary.lib import util
from conary import state
from rbuild import errors
from rpath_proddef import api1 as proddef
from rbuild.productstore import abstract
from rbuild.facade import conaryfacade
from rbuild_test.unit_test.facadetest impo... |
"""Tests for tfx.orchestration.google.beam_dag_runner."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import unittest
from unittest import mock
import tensorflow as tf
from tfx import types
from tfx.dsl.components.base import base_component
... |
from django import http
from django.db.transaction import non_atomic_requests
from django.shortcuts import get_object_or_404
import commonware.log
import mkt
from mkt.access import acl
from mkt.files.models import File
from mkt.site.decorators import allow_cross_site_request
from mkt.site.utils import get_file_respon... |
"""Generate fixtures."""
import os
import json
import numpy as np
from scipy.special import sici
# Get the file path:
FILE = os.path.realpath(__file__)
# Extract the directory in which this file resides:
DIR = os.path.dirname(FILE)
def gen(x, name):
"""Generate fixture data and writes them to file.
# Argu... |
"""Support for Telldus Live."""
import asyncio
import logging
from functools import partial
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant import config_entries
from homeassistant.const import CONF_SCAN_INTERVAL
from homeassistant.helpers.dispatcher import async_dispa... |
# -*- coding: utf-8 -*-
"""Definition and configuration of the Flask application."""
import flask.ext.restless as rest
from flask import Flask, render_template
from flask.ext.assets import Environment, Bundle
from flask.ext.triangle import Triangle
from readme.model import Recommendation
from readme.db import sessi... |
import os
from utils import make_dir, INSTANCE_FOLDER_PATH, PROJECT_ROOT
class BaseConfig(object):
"""base config object"""
PROJECT = "refstack"
# The app root path, also can use flask.root_path.
PROJECT_ROOT = PROJECT_ROOT
DEBUG = False
TESTING = False
ADMINS = ['<EMAIL>']
# http... |
"""
Sandbox Panel Estimators
References
-----------
Baltagi, Badi H. `Econometric Analysis of Panel Data.` 4th ed. Wiley, 2008.
"""
from scikits.statsmodels.tools.tools import categorical
from scikits.statsmodels.regression.linear_model import GLS, WLS
import numpy as np
__all__ = ["PanelModel"]
try:
from pand... |
import json
from django.test import TestCase
from accounts.models import ROLE_PARTNER
from accounts.tests.factories import CtsUserFactory
from accounts.utils import bootstrap_permissions
class BaseAPITest(TestCase):
def call_api(self, url, token=None):
"""
Call API with auth and return the respo... |
from collections import defaultdict
def flake8wrapper(f):
f.name = __name__
f.version = '0.0.1'
f.skip_on_py3 = False
f.off_by_default = False
return f
@flake8wrapper
def one_import_per_line(logical_line, tokens, filename, noqa):
# Check if QA has to be skipped
if noqa:
return
... |
# Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.minigame.IceGameGlobals
from panda3d.core import Point3
import math
from toontown.toonbase import ToontownGlobals
InputTimeout = 15
TireMovieTimeout = 120
MinWall = (-20.0, -15.0)
MaxWall = (20.0, 15.0)
TireRadius = 1.5
WallMargin = 1 + TireRa... |
import os, sys, re
path = [ ".", "..", "../..", "../../..", "../../../..", "../../../../..", "../../../../../..",
"../../../../../../..", "../../../../../../../..", "../../../../../../../../.." ]
head = os.path.dirname(sys.argv[0])
if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.... |
from __future__ import division
import re
import numpy as np
import sklearn.metrics as grading_metrics
import properties
if __name__=="__main__":
string = open(properties.test_tagged_output_file).readlines()
new_string = ""
for line in string:
class_label = line[0]
new_string = new_string ... |
from gnuradio import gr
import sys
def graph (args):
nargs = len (args)
if nargs == 1:
infile = args[0]
else:
sys.stderr.write('usage: interp.py input_file\n')
sys.exit (1)
sampling_freq = 6400000
fg = gr.flow_graph ()
src0 = gr.file_source (gr.sizeof_gr_complex,infile)
src1 = gr.sig... |
version_str = '0.7'
"""
The current version string.
""" |
#from .chx_libs import *
from .chx_libs import db, get_images, get_table, get_events, get_fields, np, plt , LogNorm
from .chx_generic_functions import show_img
def get_frames_from_dscan( hdr, detector = 'eiger4m_single_image' ):
ev = get_events(hdr, [detector])
length = int( hdr['start']['plan_args']['num'... |
# -*- coding: utf-8 -*-
"""
gspread.client
~~~~~~~~~~~~~~
This module contains Client class responsible for communicating with
Google Data API.
"""
import re
import warnings
from xml.etree import ElementTree
from . import __version__
from . import urlencode
from .ns import _ns
from .httpsession import HTTPSession,... |
import sys
import os
import csv
import time
import numpy as np
from crow.utils import *
def load_csv(filename, delimiter=','):
# loads csv file into array of rows (arrays)
csv.field_size_limit(sys.maxsize)
fp = open(filename)
if not fp:
print "Error: Cannot open file: %s" % filename
re... |
# testDictionary.py
#
import sys
import win32com.server.util
import win32com.test.util
import win32com.client
import traceback
import pythoncom
import pywintypes
import winerror
import unittest
error = "dictionary test error"
def MakeTestDictionary():
return win32com.client.Dispatch("Python.Dictionary")
def Tes... |
import copy
from tempest.lib.api_schema.response.compute.v2_71 import servers as servers271
###########################################################################
#
# 2.73:
#
# The locked_reason parameter is now returned in the response body of the
# following calls:
#
# - POST /servers/{server_id}/action (wher... |
#set($hashtags = '##############################################################################')
${hashtags}
# ${PRODUCT_NAME}
# -*- coding: utf-8 -*-
"""
${PROJECT_NAME}
${NAME} updated on ${DATE} at ${TIME}
${hashtags}
Input:
Output:
Description:
${hashtags}
@author: ${USER}
"""
${hashtags}
# Librar... |
from datetime import date
# Main section
# ------------
title = 'Millainen on Hämeentien tulevaisuus?'
slug = 'hameentie'
main_image = {
'filename': 'images/hameentie/main_image.jpg',
'caption': (
'Liikenne nykyisin Hämeentiellä. '
'(Helsingin kaupungin aineistopankki / Seppo Laakso)'
)... |
import parse
from errors import *
edit_cmds = {}
def edit_func(name):
def _edit_func(f):
edit_cmds.setdefault(name, f)
return f
return _edit_func
@edit_func('target-rev')
def target_rev(command, args):
rev = int(args[0])
command.target_rev(rev)
@edit_func('open-root')
def open_... |
import os
import time
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from account.models import Businesses,Privileges,UserProfiles
from groups.models import Groups,Hosts
from states_config.m... |
import sys
import csv
import warnings
from gridsim.decorators import accepts, returns
class Reader(object):
def __init__(self):
"""
__init__(self)
This class is the based class of all readers/loaders.
"""
super(Reader, self).__init__()
def clear(self):
"""
... |
import gtk
import pango
from umit.pm.core.logger import log
from umit.pm.gui.core.app import PMApp
from umit.pm.gui.plugins.engine import Plugin
from umit.pm.gui.sessions import SessionType
from umit.pm.gui.pages.base import Perspective
from umit.pm.core.errors import PMErrorException
class Explorer(Perspective):
... |
# -*- coding: utf-8 -*-
import time
import re
from cStringIO import StringIO
from Sycamore import wikiutil
from Sycamore import config
from Sycamore import wikidb
from Sycamore import user
from Sycamore.Page import Page
def execute(macro, args, formatter=None):
if not formatter:
formatter = macro.format... |
from oslo_log import log as logging
from oslo_utils import uuidutils
from sqlalchemy.orm import exc
from baremetal_network_provisioning.db import bm_nw_provision_models as models
from neutron._i18n import _LE
from neutron._i18n import _LI
from neutron.db import models_v2
LOG = logging.getLogger(__name__)
def get_... |
"""ORCID util tests."""
from __future__ import absolute_import, division, print_function
import pytest
from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound
from inspire_dojson.utils import get_record_ref
from inspire_schemas.api import validate
from inspirehep.modules.records.api import InspireRecord
f... |
import ssl
from urllib.parse import urlparse
from flask import current_app
from ldap3 import Connection, Server, Tls
from app.utils.onelogin.saml2.auth import OneLogin_Saml2_Auth
from app.utils.onelogin.saml2.utils import OneLogin_Saml2_Utils
def ldap_authentication(email, password):
"""
Authenticate the pro... |
from weboob.capabilities.recipe import ICapRecipe, Recipe
from weboob.tools.backend import BaseBackend
from .browser import SevenFiftyGramsBrowser
import unicodedata
def strip_accents(s):
return ''.join(c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn')
__all__ = ['SevenFiftyGramsBac... |
"""
Tests for vertical module.
"""
from fs.memoryfs import MemoryFS
from xmodule.tests import get_test_system
from xmodule.tests.xml import XModuleXmlImportTest
from xmodule.tests.xml import factories as xml
class BaseVerticalModuleTest(XModuleXmlImportTest):
test_html_1 = 'Test HTML 1'
test_html_2 = 'Test H... |
from cloudify_rest_client.responses import ListResponse
class Execution(dict):
"""Cloudify workflow execution."""
TERMINATED = 'terminated'
FAILED = 'failed'
CANCELLED = 'cancelled'
PENDING = 'pending'
STARTED = 'started'
CANCELLING = 'cancelling'
FORCE_CANCELLING = 'force_cancelling'
... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
'''Pychemqt, Chemical Engineering Process simulator
Copyright (C) 2009-2017, Juan José Gómez Romera <<EMAIL>>
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 Foundatio... |
"""
Unpack beacon advertising packets
"""
# pkt[0] = Packet Type (Filter ensures we only get 0x04) Is packet type?
# pkt[1] = HCI event type (We only interested in 0x3e?) LE Meta Event
# pkt[2] = Length of packet
# pkt[3] = LE Meta Event sub event (see LE_META_EVENT_LOOKUP)
# pkt[4] = Number of reports in packet
# pkt[... |
import unittest
import numpy as np
from op_test import OpTest
class TestFlattenOp(OpTest):
def setUp(self):
self.op_type = "flatten"
self.init_test_case()
self.inputs = {"X": np.random.random(self.in_shape).astype("float32")}
self.init_attrs()
self.outputs = {"Out": self.i... |
from odoo import models, api
class MassReconcileSimple(models.AbstractModel):
_name = 'mass.reconcile.simple'
_inherit = 'mass.reconcile.base'
# has to be subclassed
# field name used as key for matching the move lines
_key_field = None
@api.multi
def rec_auto_lines_simple(self, lines):
... |
"""
Mixins for fixing the time zones support in the
class based generic views for archives.
This module must be removed in Django 1.5.
https://code.djangoproject.com/ticket/18217
"""
import datetime
from django.conf import settings
from django.utils import timezone
from django.views.generic.dates import _date_from_s... |
config_extension_def = """
[EventLoop]
enable=1
active=False
toolkit=TK
[EventLoop_cfgBindings]
eventloop-toggle=<Key-F7>
"""
INTERVAL = 100 # milliseconds
INSTALL_DELAY = 250 # milliseconds
from idlelib.configHandler import idleConf
import sys
if sys.version < '3':
from Tkinter import *
else:
... |
import hashlib
import unittest
import os
import numpy as np
import time
import sys
import random
import functools
import contextlib
from PIL import Image
import math
from paddle.dataset.common import download
import tarfile
import StringIO
random.seed(0)
np.random.seed(0)
DATA_DIM = 224
SIZE_FLOAT32 = 4
SIZE_INT64 = ... |
import sublime
import sublime_plugin
import os
import fnmatch
import threading
import json
from base64 import standard_b64encode
try:
from urllib.request import Request, urlopen
from urllib.error import HTTPError
except ImportError:
from urllib2 import Request, HTTPError, urlopen
TINYPNG_URL = 'http://api... |
"""Tests for :mod:`gwdetchar.utils`
"""
import pytest
import numpy
from gwpy.segments import (
DataQualityFlag,
DataQualityDict,
)
from gwpy.table import EventTable
from gwpy.testing.utils import assert_table_equal
from .. import utils
@pytest.mark.parametrize('in_, out', [
([1, 2, 3], [1, 2, 3]),
... |
from fluous.gobject import connect
from gi.repository import Gtk, GLib, GObject
from nete.components.info_bar import ConnectedInfoBar
from nete.components.note_text_view import ConnectedNoteTextView
from nete.components.toolbar import ConnectedToolbar
class NoteView(Gtk.Bin):
is_note_selected = GObject.Property(... |
# PROBLEM: We scraped our table, but there's actually information on the detail page
# we want to have in our result.
#
# HOW WE'RE GOING TO DEAL WITH IT:
# - Do everything we did before: fetch a page, navigate it and output to csv
# - Refine our script to dip into the detail page for each reactor
# - Use pattern... |
import pytest
from shoop.notify import Context
from shoop_tests.notify.fixtures import get_initialized_test_event
@pytest.mark.django_db
def test_log_entries():
event = get_initialized_test_event()
ctx = Context.from_event(event)
order = ctx.get("order")
n_log_entries = ctx.log_entry_queryset.count()... |
# Toy example
#
# Source: http://nbviewer.ipython.org/github/craffel/theano-tutorial/blob/master/Theano%20Tutorial.ipynb
#
# We'll train our neural network to classify two Gaussian-distributed clusters
# in 2d space.
#
# Defining a multilayer perceptron is out of the scope of this tutorial;
# please see here for backgr... |
#!/usr/bin/env python
'''This runs Apache Status on the remote host and returns the number of requests per second.
./astat.py [-s server_hostname] [-u username] [-p password]
-s : hostname of the remote server to login to.
-u : username to user for login.
-p : Password to user for login.
Example:
Thi... |
import numpy
import chainer
from chainer.functions.activation import sigmoid
from chainer.functions.activation import tanh
from chainer.functions.array import concat
from chainer.functions.math import linear_interpolate
from chainer import link
from chainer.links.connection import linear
class MGUBase(link.Chain):
... |
'''Sana mDS(mobile Dispatch Server)
The mDS API is designed takes a RESTful approach to data packetization using a
CRUD implementation based on the Django-piston API.
The API declares the following objects:
Binary - a binary blob
Client - something that talks to the server
Encounter - an instance of dat... |
from copy import deepcopy
import sqlalchemy as sa
from jsonschema import ValidationError, validate
from jsonschema.validators import Draft4Validator, create
from myreco.engine_strategies.filters.filters import BooleanFilterBy
from myreco.item_types._store_items_model_meta import _StoreItemsModelBaseMeta
from myreco.ut... |
"""Version."""
# (major, minor, micro, release type, pre-release build, post-release build)
version_info = (4, 5, 1, 'final', 0, 0)
def _version():
"""
Get the version (PEP 440).
Version structure
(major, minor, micro, release type, pre-release build, post-release build)
Release names are na... |
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
config = {
'description': 'BioMAJ',
'author': 'Olivier Sallou',
'url': 'http://biomaj.genouest.org',
'download_url': 'http://biomaj.genouest.org',
'author_email': '<EMAIL>',
'version': ... |
import os
from .base import BASE_DIR
# Python Social auth
AUTHENTICATION_BACKENDS = (
# Facebook Social auth
'social.backends.facebook.FacebookOAuth2',
# Kakao talk Social auth
'social.backends.kakao.KakaoOAuth2',
# django defualt
'django.contrib.auth.backends.ModelBac... |
from unittest import TestCase, mock
from test.util import Anything
from mycroft.util import (play_ogg, play_mp3, play_wav, play_audio_file,
record)
from mycroft.util.file_utils import get_temp_path
test_config = {
'play_wav_cmdline': 'mock_wav %1',
'play_mp3_cmdline': 'mock_mp3 %1',
... |
import argparse
import os
import cdpybio as cpb
def main():
parser = argparse.ArgumentParser(
description=('Count number of reads supporting each base for different '
'genomic positions. You can provide a VCF file or a bed '
'file to specifiy the positions to coun... |
import inspect
from werkzeug.exceptions import Forbidden
# These have to be imported for the permission system to work
import account # NOQA
import dataset # NOQA
from flask import abort
from functools import wraps
from flask.ext.login import current_user
from openspending.auth.perms import is_authenticated, is_mod... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('products', '0006_productfeatured'),
]... |
import functools
import hashlib
import logging
import os
import re
import sys
try:
import csscompressor
except ImportError:
logging.critical('Cannot import the third-party Python package csscompressor')
sys.exit(1)
try:
import jsmin
except ImportError:
logging.critical('Cannot import the third-party Python ... |
# coding=utf-8
"""Reclassify a raster layer."""
from os.path import isfile
import numpy as np
from osgeo import gdal
from qgis.core import QgsRasterLayer
from safe.common.exceptions import (
FileNotFoundError, InvalidKeywordsForProcessingAlgorithm)
from safe.common.utilities import unique_filename, temp_dir
fro... |
from numpy import pi as _pi
def sphere(target, pore_diameter='pore.diameter'):
r"""
Calculate cross-sectional area assuming the pore body is a sphere
Parameters
----------
target : OpenPNM Geometry Object
The Geometry object which this model is associated with. This controls
the l... |
"""
.. module: cloudaux.gcp.gcs
:platform: Unix
:copyright: (c) 2016 by Google Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Tom Melendez (@supertom) <<EMAIL>>
"""
from cloudaux.gcp.decorators import gcp_conn
@gcp_conn('gcs')
def list_buckets(client=None, **kw... |
import unittest
import numpy
import chainer
from chainer import cuda
from chainer import functions
from chainer import testing
from chainer.testing import attr
def _to_gpu(x, device_id):
if device_id >= 0:
return cuda.to_gpu(x, device_id)
else:
return x
class Copy(unittest.TestCase):
... |
__author__ = 'chris'
from zope.interface.verify import verifyObject
from txrudp.rudp import ConnectionMultiplexer
from txrudp.connection import HandlerFactory, Handler, State
from txrudp.crypto_connection import CryptoConnectionFactory
from twisted.internet.task import LoopingCall
from twisted.internet import task, rea... |
import os
import pipes
import stat
import subprocess
try:
import MySQLdb
except ImportError:
mysqldb_found = False
else:
mysqldb_found = True
# ===========================================
# MySQL module specific support methods.
#
def db_exists(cursor, db):
res = cursor.execute("SHOW DATABASES LIKE %... |
"""
created 2017 by Jens Diemer <<EMAIL>>
"""
import logging
from django.core.urlresolvers import NoReverseMatch, reverse
from django.utils.translation import ugettext_lazy as _
from cms.toolbar_base import CMSToolbar
from cms.toolbar_pool import toolbar_pool
from cms.utils.urlutils import admin_reverse
fro... |
from less.settings import LESS_MTIME_DELAY
from django.core.cache import cache
from django.utils.encoding import smart_str
from hashlib import md5
import os.path
import socket
def get_hexdigest(plaintext, length=None):
digest = md5(smart_str(plaintext)).hexdigest()
if length:
return digest[:length]
... |
from . import TestCase, unittest
from contextlib import nested
import os
import mock
import juicer.config
# When the config file is read in and parsed it will turn into a dict
# like this
serialized_config = {
"qa": {
"ca_path": "/home/testuser/certs/pulp.crt",
"cert_filename": "/home/testuser/cer... |
import os
import time
import requests
import core
from core.nzbToMediaSceneExceptions import process_all_exceptions
from core.nzbToMediaUtil import convert_to_ascii, rmDir, find_imdbid, find_download, listMediaFiles, remoteDir, import_subs, server_responding, reportNzb
from core import logger
from core.transcoder impo... |
# -*- coding: utf-8 -*-
"""
Author: Bernhard Scheirle
"""
from __future__ import unicode_literals
import logging
import os
import hashlib
import urllib.parse
import urllib.request
logger = logging.getLogger(__name__)
_log = "pelican_comment_system: avatars: "
try:
from . identicon import identicon
_identic... |
"""
Calculate New conditions given a new and an old MAS rate
Use condition name specifically calculate that parameter,
i.e. if you only want to run a subset
Arguments:
-n New MAS Rate
-o Old MAS Rate
Specify Conditions to calculate:
HC
HN
NCA
NCO
NC (both NCA and NCO)
"""
ret=u"\u000D"
spc=u"\u0020"
import sys
fro... |
# encoding: UTF-8
# 重载sys模块,设置默认字符串编码方式为utf8
import sys
try:
reload(sys) # Python 2
sys.setdefaultencoding('utf8')
except NameError:
pass # Python 3
from time import sleep
# vn.trader模块
from vnpy.event import EventEngine
from vnpy.trader.vtEngine import MainEngine, LogEngine
from vnpy.trader.uiQ... |
"""Unit tests for `biggus._init.NewAxesArray`."""
import unittest
import numpy as np
from numpy.testing import assert_array_equal
from biggus._init import NewAxesArray, ConstantArray, NumpyArrayAdapter
class Test___init__(unittest.TestCase):
def test_too_few_axes(self):
in_arr = ConstantArray([3, 2])
... |
"""Reference implementation for Blech32 and segwit addresses."""
CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
def blech32_polymod(values):
"""Internal function that computes the blech32 checksum."""
generator = [0x7d52fba40bd886, 0x5e8dbf1a03950c, 0x1c3a3c74072a18, 0x385d72fa0e5139, 0x7093e5a608865b] # new g... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from distutils.core import setup
setup(
name='Pafy',
py_modules=['pafy'],
version='0.3.23',
description="Python API for YouTube, query and download YouTube content",
keywords=["Pafy", "API", "YouTube", "youtube", "download", "video"],
author="nagev... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Bed and VCF files should be sorted. Bed should have no header.
# Bed should be gziped. VCH should be bgzip and indexed with tabix.
#
import gzip
import vcf
import collections
import sys
import argparse
def main():
# Args
args = parse_arguments()
# Initia... |
import logging
from django.conf import settings
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import messages
from openstack_dashboard import api
LOG = logging.getLogger(__name__)
VNIC_TYPES... |
import functions
import sklearnClassify
import random
def learnfunction(path, pathTweet, numberUsedAll, numberUnlabeled, algorithm, removeWords):
numberForTraining = int (0.8 * numberUsedAll)
numberForTesting = int (0.2 * numberUsedAll)
input_list, input_score = functions.readTestComment(path, numberUsedA... |
from sys import argv
tablacodon = {
'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',
'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K',
'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L',
'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
'CAC':'H', '... |
from functools import partial
from pcs.lib import reports
from pcs.lib.cib import sections
from pcs.lib.cib.nvpair import arrange_first_meta_attributes
from pcs.lib.cib.tools import IdProvider
def _set_any_defaults(section_name, env, options):
"""
string section_name -- determine the section of defaults
... |
from django.conf.urls import url
import bdo_main_app.views as views
import service_builder.views as sb_views
urlpatterns = [
# home & signup
url('^$', views.home, name='home'),
url('^bdo/$', views.dataset_search, name='bdo'),
url('^search/$', views.search, name='search'),
url('^exploretools/$', vi... |
from sqlalchemy import case, func
import airflow
from airflow.ti_deps.deps.base_ti_dep import BaseTIDep
from airflow.utils.db import provide_session
from airflow.utils.state import State
class TriggerRuleDep(BaseTIDep):
"""
Determines if a task's upstream tasks are in a state that allows a given task instanc... |
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.views.decorators.cache import cache_page
from django.views.i18n import javascript_catalog
from localeurl.sitemaps import LocaleurlSitemap
from localeurl.templatetags.localeurl_tags import chlocale
from rando.flatpages.mod... |
import unittest
import os
import logging
import shutil
import setup_logging
class TestCentralLogger(unittest.TestCase):
def setUp(self):
# Remove 'logs' directory.
self.logs_dir = setup_logging.get_log_path()
shutil.rmtree(self.logs_dir, ignore_errors=True)
# Stan... |
"""
do the unit tests!
"""
import os
import re
import sys
import unittest
from optparse import OptionParser
import ssh
import threading
sys.path.append('tests')
from test_message import MessageTest
from test_file import BufferedFileTest
from test_buffered_pipe import BufferedPipeTest
from test_util import UtilTest
f... |
"""
Serializer for video outline
"""
from edxval.api import ValInternalError, get_video_info_for_course_and_profiles
from rest_framework.reverse import reverse
from courseware.access import has_access
from courseware.courses import get_course_by_id
from courseware.model_data import FieldDataCache
from courseware.modul... |
#!/usr/bin/env python
"""
This script is used to map fastq files to the genome. The input is a comma
separated list of fastq[.gz] files (or two lists if the input is paired-end).
The output are bam files with the mapped reads, a table containing the number
of reads mapped to each gene and a wiggle file with the covera... |
from setuptools import setup, find_packages
from src import mx
MAJOR_VERSION = '0'
MINOR_VERSION = '2'
MICRO_VERSION = '18'
VERSION = '{}.{}.{}'.format(MAJOR_VERSION, MINOR_VERSION, MICRO_VERSION)
setup(
name='rafi.mx',
version=VERSION,
description='Workspace/project-oriented tmux/git personal assistant.'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.