content stringlengths 4 20k |
|---|
#! /usr/local/bin/python3
# -*- utf-8 -*-
"""
Total: 33
0~1: 课程材料首次发布、最近发布距今几天
2~6: 用户初次、上次操作此课程据今几天,持续几天,与课程持续时间的比例,初次访问课程材料距离开课时间几天
7~14: 课程的所有用户操作课程持续时间的:平均值、标准差、最大值、最小值,以及与课程持续时间的比例
15~16: month (1-12) of the first, last event in the enrollment
17~32: 用户对课程材料的首次操作时间与课程材料发布时间的日期差的:平均值、标准差、最大值、最小值,
enrollment最... |
"""Additional help about wildcards."""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from gslib.help_provider import HelpProvider
_DETAILED_HELP_TEXT = ("""
<B>DESCRIPTION</B>
gsutil supports URI wildcards. For e... |
from xml_tools import xml_get_text
class StorageVolume(object):
def __init__(self, deltacloud, dom):
self._deltacloud = deltacloud
self.xml = dom.toxml()
self.created = xml_get_text(dom, "created")[0]
self.state = xml_get_text(dom, "state")[0]
self.capacity = xml_get_te... |
"""Tests for certificates views. """
import json
import ddt
from uuid import uuid4
from nose.plugins.attrib import attr
from mock import patch
from django.conf import settings
from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.client impo... |
#!/usr/bin/python
import copy
import datetime
import json
import os
import re
import sys
import urllib
REMOTES = ['gerrit-stream-logger-dfw.stillhq.com',
'gerrit-stream-logger-ord.stillhq.com',
'gerrit-stream-logger-syd.stillhq.com']
one_day = datetime.timedelta(days=1)
day = datetime.datetime... |
"""
Comparing AntEvents to generic asyncio programming.
This is the AntEvents version.
"""
import asyncio
import random
from statistics import median
from antevents.base import DefaultSubscriber, SensorEvent, Scheduler, SensorPub
from antevents.linq.transducer import Transducer
import antevents.linq.combinators
import... |
import os
import platform
from twisted.internet import defer
from .. import data, helper
from p2pool.util import pack
P2P_PREFIX = 'fcd9b7dd'.decode('hex') #stripped from fckbankscoind's main.cpp -> pchMessageStart[4] = { 0xfc, 0xd9, 0xb7, 0xdd };
P2P_PORT = 21779 #fckbankscoind 's p2p port
ADDRESS_VERSION = 36 #lo... |
from openerp.osv import fields, orm
class account_companyweb_wizard(orm.TransientModel):
_name = 'account.companyweb.wizard'
_columns = {
'vat_number': fields.text('VAT number', readonly=True),
'name': fields.text('Name', readonly=True),
'jur_form': fields.text('Juridical Form', reado... |
from neutron.api import extensions
from neutron.api.v2 import attributes as attr
from neutron.common import exceptions as nexception
from neutron.openstack.common import log as logging
LOG = logging.getLogger(__name__)
class FirewallRouterInUse(nexception.InUse):
message = _("Router(s) %(router_ids)s provided al... |
import argparse
import yaml
import finsky.client
# top level parser
parser = argparse.ArgumentParser(description='Google Play Client')
subparsers = parser.add_subparsers(title="Commands")
# download action
parser_download = subparsers.add_parser("download", help="Download APK")
parser_download.add_argument('profile'... |
"""
hiv dataset loader.
"""
import os
import deepchem as dc
from deepchem.molnet.load_function.molnet_loader import TransformerGenerator, _MolnetLoader
from deepchem.data import Dataset
from typing import List, Optional, Tuple, Union
HIV_URL = "https://deepchemdata.s3-us-west-1.amazonaws.com/datasets/HIV.csv"
HIV_TASK... |
# -*- coding: utf-8 -*-
"""
shellstreaming.istream.randsentence
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:synopsis: Generates random sentence sequence.
"""
# standard modules
import time
# my modules
from relshell.record import Record
from relshell.recorddef import RecordDef
from shellstreaming.istream.base im... |
from gui.core.lcd160_gui import Touchable, Aperture, Screen, print_left, dolittle
from gui.core.constants import *
from gui.widgets.listbox import Listbox
class _ListDialog(Aperture):
def __init__(self, location, dropdown, width):
border = 1 # between Aperture border and list
dd = dropdown
... |
"""Spectral operators (e.g. DCT, FFT, RFFT).
@@dct
@@fft
@@ifft
@@fft2d
@@ifft2d
@@fft3d
@@ifft3d
@@rfft
@@irfft
@@rfft2d
@@irfft2d
@@rfft3d
@@irfft3d
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math as _math
from tensorflow.python.framework... |
from django.conf import settings
from django.contrib import messages
from django.http import Http404
from django.shortcuts import render
from django.utils.translation import ugettext as _
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django_facebook impo... |
# -*- coding: utf-8 -*-
"""User forms."""
from flask_wtf import Form
from wtforms import PasswordField, StringField
from wtforms.validators import DataRequired, Email, EqualTo, Length
from .models import User
class RegisterForm(Form):
"""Register form."""
username = StringField('Username',
... |
"""
Tests suite for the admin views of the licenses app.
"""
from django.test import TestCase, Client
from django.core.urlresolvers import reverse
from django.contrib.auth import get_user_model
from django.conf import settings
from django.test.utils import override_settings
from ..models import License
@override_se... |
import StringIO
import sys
from functools import partial
# Twisted Imports
from twisted.trial import unittest
from twisted.spread import banana
from twisted.python import failure
from twisted.internet import protocol, main
from twisted.test.proto_helpers import StringTransport
class MathTests(unittest.TestCase):
... |
"""CNN model class"""
import tensorflow as tf
# import model
import models.rnn
#########################################
# FLAGS
#########################################
FLAGS = tf.app.flags.FLAGS
class RRNN(models.rnn.RNN):
"""recurrent neural network model.
classify web page only based on target html."""
... |
""" Namespace helper module - it contains functions for names
validation and classification """
import re
MESSAGE = re.compile(r"^[A-Z]\d{4}$")
CHECKER = re.compile(r"^[a-z][a-z_0-9]+[a-z0-9]$")
CATEGORY = re.compile(r"^[A-Z][a-zA-Z]+$")
def valid_category_id(name):
""" Validate category name, in case of invalid... |
from typing import Any, List
import numpy as np
AR_LIKE_b: List[bool]
AR_LIKE_i: List[int]
AR_LIKE_f: List[float]
AR_LIKE_U: List[str]
AR_i8: np.ndarray[Any, np.dtype[np.int64]]
reveal_type(np.ndenumerate(AR_i8)) # E: numpy.ndenumerate[{int64}]
reveal_type(np.ndenumerate(AR_LIKE_f)) # E: numpy.ndenumerate[{double}... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Conector for ok.ru
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
# by DrZ3r0
# ------------------------------------------------------------
import re
import urllib
from core import logger
... |
"""
these are systematically testing all of the args to value_counts
with different size combinations. This is to ensure stability of the sorting
and proper parameter handling
"""
from itertools import product
import numpy as np
import pytest
from pandas import (
Categorical,
CategoricalIndex,
DataFrame,... |
import itertools
import tempfile
import StringIO
import cStringIO
import base64
import csv
import codecs
from openerp.osv import orm, fields
from openerp.tools.translate import _
class AccountUnicodeWriter(object):
"""
A CSV writer which will write rows to CSV file "f",
which is encoded in the given en... |
"""
Clopath Rule: Bidirectional connections
-----------------------------------------
This script simulates a small network of ten excitatory and three
inhibitory ``aeif_psc_delta_clopath`` neurons. The neurons are randomly connected
and driven by 500 Poisson generators. The synapses from the Poisson generators
to the... |
import os
import re
from string import Template
from java_class_component import Enum, Field
from java_method import Method
class JavaClassLoader(object):
"""Manager class maintains all loaded java classes."""
def __init__(self, src_path, class_list):
self._src_path = src_path
self._class_list = class_li... |
from __future__ import absolute_import
from django import template
from django.utils.datastructures import SortedDict
from django.utils.translation import ugettext as _
from horizon.base import Horizon
from horizon import conf
register = template.Library()
@register.filter
def has_permissions(user, component):
... |
import logging
import json
import re
import subprocess
from datetime import datetime, timedelta
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from desktop.lib.exceptions_renderable import PopupException
from metadata.workload_analytics_client import WorkfloadAnalyti... |
#!/usr/bin/env python2.7
#coding: utf-8
import os
import threading
import yaml
import savReaderWriter
import signal
from daemon import runner
from lockfile import LockTimeout
import time
import logging
import Queue
readedFile = []
threadLock = threading.Lock()
exitFlag = False
workQueue = Queue.Queue()
class FileRead... |
"""Cloud TPU profiler package."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from setuptools import setup
_VERSION = '1.3.0-a1'
CONSOLE_SCRIPTS = [
'capture_tpu_profile=cloud_tpu_profiler.main:main',
]
REQUIRED_PACKAGES = [
'tensorflow >= 1.... |
import numpy as np
import scipy.sparse as sp
import numbers
from scipy import linalg
from sklearn.decomposition import NMF, non_negative_factorization
from sklearn.decomposition import nmf # For testing internals
from scipy.sparse import csc_matrix
from sklearn.utils.testing import assert_true
from sklearn.utils.te... |
from smart_m3.m3_kp import *
import uuid
import re
import sys
from termcolor import colored
sys.path.append("../")
from sib import SIBLib
import time
import random
import Tkinter
from client_query import *
rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
owl = "http://www.w3.org/2002/07/owl#"
xsd = "http://www.w3.... |
import unittest
import sys
import IECore
class TestIFFHairReader( unittest.TestCase ) :
def testConstruction( self ) :
r = IECore.Reader.create( "test/IECore/data/iffFiles/hairSystem.mchp" )
self.assert_( r.isInstanceOf( "IFFHairReader" ) )
self.assertEqual( type( r ), IECore.IFFHairReader )
self.assertEqua... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
logging.basicConfig()
logger = logging.getLogger("paddle")
logger.setLevel(logging.INFO)
class TaskMode(object):
"""
TaskMode
"""
TRAIN_MODE = 0
TEST_MODE = 1
INFER_MODE = 2
def __init__(self, mode):
"""
:param... |
from .dogma import make_mass_modifier
from .dogma import make_signature_modifier
from .python import PropulsionModuleVelocityBoostModifier
def make_ab_modifiers():
ab_modifiers = (
PropulsionModuleVelocityBoostModifier(),
make_mass_modifier())
return ab_modifiers
def make_mwd_modifiers():
... |
from troveclient import base
class Datastore(base.Resource):
def __repr__(self):
return "<Datastore: %s>" % self.name
class DatastoreVersion(base.Resource):
def __repr__(self):
return "<DatastoreVersion: %s>" % self.name
def update(self, visibility=None):
"""Change something i... |
# -*- encoding: UTF-8 -*-
'''Web crawling with multiprocessing
List of functions:
open_urls
update
'''
# built-in modules
import multiprocessing as mp
import urllib2
import time
#==============================================================================
def open_urls(urls, processes=0, re... |
"custom command to build doc.zip file"
#=============================================================================
# imports
#=============================================================================
# core
import os
from distutils import dir_util
from distutils.cmd import Command
from distutils.errors import *
... |
import pytest
from django.utils import translation
from shoop.front.apps.simple_search.views import (
get_search_product_ids, SearchView
)
from shoop.testing.factories import (
create_product, get_default_product, get_default_shop
)
from shoop.testing.utils import apply_request_middleware
UNLIKELY_STRING = "T... |
from diabeaters.main.models import UserProfile
from django.test import TestCase
from django.contrib.auth.models import User
from django.test.client import Client
from django.core import management
class TrivialViewsTest(TestCase):
def setUp(self):
self.u = User.objects.create(username="testuser")
... |
import os, sys, urllib, xmlrpclib
from xml.dom.minidom import parseString
from xml.dom.minidom import getDOMImplementation
from common import *
class Introspect(object):
def __init__(my):
my.info = TacticInfo.get()
my.app = my.info.get_app()
my.impl = my.info.get_app_implementation()
... |
from selenium.webdriver.common.keys import Keys
from tests.integration.tests.test_splitdatetime import Test as TestSplitDateTime
from . import VisualTest
class Test(VisualTest):
urls = TestSplitDateTime.urls
def test_test_default_usecase(self):
self.driver.get('%s%s' % (self.live_server_url, TestSpl... |
import os
import abc
from scam import pipe
import dropbox
import sys
def _get_filename(context):
"""
Calculates a suitable filename based on the source information in the given context
"""
when = context['SOURCE_DATE'].strftime('%Y-%m-%dT%H %M %S')
return '{} {}{}'.format(when, context['SOURCE_NAM... |
"""I/O function wrappers for the Newick file format.
See: http://evolution.genetics.washington.edu/phylip/newick_doc.html
"""
import re
from Bio._py3k import StringIO
from Bio.Phylo import Newick
class NewickError(Exception):
"""Exception raised when Newick object construction cannot continue."""
pass
to... |
import logging
from collections import defaultdict
import networkx
import claripy
from ..sim_type import SimType, SimTypePointer, SimTypeChar, SimTypeString, SimTypeReg
from ..calling_conventions import DEFAULT_CC
from ..knowledge_base import KnowledgeBase
from ..errors import AngrDirectorError
from . import Explora... |
import sys
sys.path.insert(1,"../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.gbm import H2OGradientBoostingEstimator
def hit_ratio_test():
air_train = h2o.import_file(path=pyunit_utils.locate("smalldata/airlines/AirlinesTrain.csv.zip"))
air_valid = h2o.import_file(path=pyunit_utils.loca... |
"""
WSGI config for djproj project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
"""
import os, sys
# python
sys.path.append('/usr/lib/python2.7/')
sys.path.append('/usr/lib/python2.7... |
# -*- coding: utf-8 -*-
import os
'''
DiceSimulator.py
I don't know if I should say die or dice :()
Author: Alan Richmond, Python3.codes
'''
import pygame
import random
import time
size = 256 # Size of window/dice
spsz = size // 10 # size of spots
m = int(size / 2) ... |
"""
This module is here for string completions. This means mostly stuff where
strings are returned, like `foo = dict(bar=3); foo["ba` would complete to
`"bar"]`.
It however does the same for numbers. The difference between string completions
and other completions is mostly that this module doesn't return defined
names... |
from libsbml import *
# Creates an SBMLNamespaces object with the given SBML level, version
# package name, package version.
#
# (NOTE) By defualt, the name of package (i.e. "layout") will be used
# if the arugment for the prefix is missing or empty. Thus the argument
# for the prefix can be added as follows:
#
# ... |
def getDigits(number):
digits = [0]*4
numOfDigits = 0
while number >= 1:
digits[numOfDigits] = number%10
number /= 10
numOfDigits += 1
return digits
def getLettersSumOfNumber(number):
"""
C_blank = 0 # blank
C_1 = 1 # o... |
import ocl
import camvtk
import time
import vtk
import datetime
import math
def drawPoints(myscreen, clpoints, ccpoints):
c=camvtk.PointCloud( pointlist=clpoints, collist=ccpoints)
c.SetPoints()
myscreen.addActor(c )
def drawFiber(myscreen, f, fibercolor=camvtk.red):
inter = f.getInts()
for i in ... |
import os
import sys
if sys.version_info[0] == 2 and sys.version_info[1] < 7:
#Add a compatibility dir for python versions younger than 2.7
sys.path.append(os.path.join(os.path.split(os.path.realpath(__file__))[0],
'compat'))
from subprocess import call, Popen, PIPE, STDOUT
from os ... |
# -*- coding: utf-8 -*-
# snapshottest: v1 - https://goo.gl/zC4yUc
from __future__ import unicode_literals
from snapshottest import GenericRepr, Snapshot
snapshots = Snapshot()
snapshots['test_schema 1'] = {
'data_path': {
'default': 'data',
'type': 'string'
},
'db_connection_string': {
... |
# -*- coding: utf-8 -*-
import socket, select, threading, time
g_send_list = []
g_recv_list = []
g_fd_map2_cli_sock = {}
send_mutex = threading.Lock()
recv_mutex = threading.Lock()
def send_worker(send_sock):
while True:
if send_mutex.acquire(1):
for index in range(0, len(g_send_list)):
... |
import numpy as np
from numba import vectorize, cuda
from numba.tests.npyufunc.test_vectorize_decor import BaseVectorizeDecor, \
BaseVectorizeNopythonArg, BaseVectorizeUnrecognizedArg
from numba.cuda.testing import skip_on_cudasim, CUDATestCase
import unittest
@skip_on_cudasim('ufunc API unsupported in the simul... |
from odoo import api, fields, models, tools
from odoo.tools import email_re
class MailComposeMessage(models.TransientModel):
_inherit = 'mail.compose.message'
mass_mailing_id = fields.Many2one('mailing.mailing', string='Mass Mailing', ondelete='cascade')
campaign_id = fields.Many2one('utm.campaign', stri... |
"""Functional test for learning rate decay."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
from tensorflow.python.eager import context
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import test_util
from tens... |
import os
import pickle
from typing import List, Tuple
from pathpicker import logger, state_files
from pathpicker.line_format import LineMatch
RED_COLOR = "\033[0;31m"
NO_COLOR = "\033[0m"
INVALID_FILE_WARNING = """
Warning! Some invalid or unresolvable files were detected.
"""
GIT_ABBREVIATION_WARNING = """
It loo... |
#!/usr/bin/env python
# vim:ts=4:sw=4:et:
from __future__ import absolute_import, division, print_function, unicode_literals
import os
try:
from setuptools import setup, Extension
except ImportError:
from distutils.core import setup, Extension
watchman_src_dir = os.environ.get("CMAKE_CURRENT_SOURCE_DIR")
if... |
{
'name': 'Improved reordering rules',
'version': '0.2',
'category': 'Tools',
'description': """
This module allows to improve reordering rules of stock module.
It works forecasting the stock needed per product for n days of sales,
with the next formula:
(( Qty sold in days_stats * (1+f... |
from __future__ import absolute_import, division, print_function
INCLUDES = """
#include <CommonCrypto/CommonCryptor.h>
"""
TYPES = """
enum {
kCCAlgorithmAES128 = 0,
kCCAlgorithmDES,
kCCAlgorithm3DES,
kCCAlgorithmCAST,
kCCAlgorithmRC4,
kCCAlgorithmRC2,
kCCAlgorithmBlowfish
};
typedef uint... |
#!/usr/bin/env python3
# This script removes lines from stubtest whitelists, according to
# an input file. The input file has one entry to remove per line.
# Each line consists of a whitelist filename and an entry, separated
# by a colon.
# This script is used by the workflow to remove unused whitelist entries.
impo... |
import os
from fate_arch.common import file_utils
def get_data_table_count(path):
config_path = os.path.join(path, "config.yaml")
config = file_utils.load_yaml_conf(conf_path=config_path)
count = 0
if config:
if config.get("type") != "vision":
raise Exception(f"can not support thi... |
import time
import unittest
'''
# <start id="simple-string-calls"/>
$ redis-cli #A
redis 127.0.0.1:6379> set hello world #D
OK #E
redis 127.0.0.1:6379> get hello #F
"world" #G
redis 127.0.0.1:... |
from __future__ import division, print_function, absolute_import
import warnings
import threading
import numpy as np
from numpy import array, finfo, arange, eye, all, unique, ones, dot, matrix
import numpy.random as random
from numpy.testing import (TestCase, run_module_suite,
assert_array_almost_equal, asser... |
"""Low-level example of how to spend a P2SH/BIP16 txout"""
import sys
if sys.version_info.major < 3:
sys.stderr.write('Sorry, Python 3.x required by this example.\n')
sys.exit(1)
import hashlib
from bitcoin import SelectParams
from bitcoin.core import b2x, lx, COIN, COutPoint, CMutableTxOut, CMutableTxIn, CM... |
"""
LoginRadius BaseOAuth2 backend, docs at:
https://python-social-auth.readthedocs.io/en/latest/backends/loginradius.html
"""
from .oauth import BaseOAuth2
class LoginRadiusAuth(BaseOAuth2):
"""LoginRadius BaseOAuth2 authentication backend."""
name = 'loginradius'
ID_KEY = 'ID'
ACCESS_TOKEN_URL =... |
import sys, re, time, string
import numpy;
import scipy;
import scipy.special;
import nltk;
from inferencer import compute_dirichlet_expectation;
from inferencer import Inferencer;
class Hybrid(Inferencer):
def __init__(self,
hash_oov_words=False,
number_of_samples=10,
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
from pyFMG.fortimgr import FortiManager
import pytest
try:
from ansible.modules.network.fortimanager import fmgr_secprof_profile_group
except ImportError:
pytest.skip("Could not load required modules ... |
# -*- coding: utf-8 -*-
import os
os_env = os.environ
class Config(object):
SECRET_KEY = os_env["SOLARPI_SECRET"]
APP_DIR = os.path.abspath(os.path.dirname(__file__)) # This directory
PROJECT_ROOT = os.path.abspath(os.path.join(APP_DIR, os.pardir))
BCRYPT_LOG_ROUNDS = 13
ASSETS_DEBUG = False
... |
from __future__ import unicode_literals
import webnotes
from webnotes.utils import flt
def execute(filters=None):
if not filters: filters = {}
columns = get_columns()
last_col = len(columns)
item_list = get_items(filters)
aii_account_map = get_aii_accounts()
if item_list:
item_tax, tax_accounts = get_tax_acc... |
import datetime
import unittest
import sqlite3 as sqlite
class RegressionTests(unittest.TestCase):
def setUp(self):
self.con = sqlite.connect(":memory:")
def tearDown(self):
self.con.close()
def CheckPragmaUserVersion(self):
# This used to crash pysqlite because this p... |
# -*- coding: utf-8 -*-
"""
profile.py
~~~~~~~~~~~~
This module implements some common helper functions for building a server profile
and server profile template in OneView
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_li... |
from .main import TorrentLeech
def start():
return TorrentLeech()
config = [{
'name': 'torrentleech',
'groups': [
{
'tab': 'searcher',
'subtab': 'providers',
'list': 'torrent_providers',
'name': 'TorrentLeech',
'description': 'See <a href... |
import unittest as ut
import importlib_wrapper
def disable_GUI(code):
# integrate without visualizer
breakpoint = "while True:"
assert breakpoint in code
code = code.replace(breakpoint, "for _ in range(100):", 1)
breakpoint = "t = Thread(target=main)"
assert breakpoint in code
code = code.... |
"""
Test the view of the alignemnts in IGV.js.
"""
from tests_functional.test_selenium import *
from selenium.webdriver import ActionChains
import urllib.request, ssl
_is_setup = False
class TestFilters(SeleniumTest):
def setUp(self):
global _is_setup
if not _is_setup:
self.main_page(... |
import re
from Products.DataCollector.plugins.CollectorPlugin import LinuxCommandPlugin
from Products.DataCollector.plugins.DataMaps import MultiArgs
class lsblk(LinuxCommandPlugin):
maptype = "HardDiskMap"
modname = "Products.ZenModel.HardDisk"
relname = "harddisks"
compname = "hw"
command = '''\
... |
#!/usr/bin/env python
# encoding: utf-8
"""
regression.py
Created by Jon Stewart on 2010-05-05.
Copyright (c) 2010 Lightbox Technologies, Inc. All rights reserved.
"""
import sys
import os
import subprocess
import os.path as p
import filecmp
keysDir = './pytest/keys'
docsDir = './pytest/corpora'
resultsDir = './pyte... |
"""
aeneas.cfw is a Python C++ extension to synthesize text with Festival.
The only function provided by this module is:
.. function:: cfw.synthesize_multiple(output_file_path, quit_after, backwards, text)
Synthesize several text fragments into a single WAVE file.
The returned tuple ``(sr, synt, anchors)`` ... |
from django.db import migrations, models
from django.db.backends.postgresql.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
# change emojiset to text if emoji_alt_code is true.
def change_emojiset(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
UserProfile = apps... |
import collections
import contextlib
import heapq
import subprocess
from typing import Dict, Iterable, TextIO, Tuple
from data import data, process_common
SRCS_PATTERN = 'data/corpus/g1m_ngram/googlebooks-eng-1M-1gram-20090715-%s.csv'
AGGREGATED_PATTERN = 'data/corpus/g1m_ngram/aggregated-1gram-20090715-%s.csv'
SORTE... |
from gnuradio import gr, gr_unittest, blocks
class test_repeat (gr_unittest.TestCase):
def setUp (self):
self.tb = gr.top_block ()
def tearDown (self):
self.tb = None
def test_001_float(self):
src_data = [n*1.0 for n in range(100)];
dst_data = []
for n in range(10... |
"""Data generators for LM1B data-set."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import tarfile
from six.moves import range # pylint: disable=redefined-builtin
from tensor2tensor.data_generators import generator_utils
from tensor2tensor.... |
import six
class TokenSanitizer(object):
"""Helper class for cleaning some object from different passwords/tokens.
Simply searches attribute with `look a like` name as one of
the token and replace it value with message.
"""
def __init__(self, tokens=('token', 'pass', 'trustid'),
m... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
"""
Uses the official Khronos-XML specs to generate a
GL/GLES/EGL/GLX/WGL Loader made for your needs. Glad currently supports
the languages C, D and Volt.
Note: this package might be slightly outdated, for always up to date versions
checkout the GitHub repository: https://... |
from __future__ import absolute_import, division, print_function#, unicode_literals
import os.path
import sys
import yaml
import re
import requests
from . import template
CONFIG_FILE = "tile.yml"
HISTORY_FILE = "tile-history.yml"
# The Config object describes exactly what the Tile Generator is going to generate.
# It... |
import numpy as np
def calcGmat(x,y,n,w=1):
deg = np.arange(n+2)
a = np.zeros((len(x),deg.sum()))
cnt = -1
xu = 1
for u in deg:
yv = 1
for v in np.arange(n-u+1):
cnt += 1
a[:,cnt] = w*xu*yv
if v < n-u:
yv *= y
if u < deg[-1]:
xu *= x
r... |
import pandas as pd
import Attack_Calc as atk
def data_input():
# import and fold data
df = pd.read_csv('input_data/units.csv')
# df = df[(df['faction'] == 'scum')]
# df = df[(df['single model health'] >= 5)]
df.sort_values(by=['name'], ascending=[True], inplace=True)
rez_df = pd.D... |
"""Objective function landscape representations"""
import numpy as np
from scipy.optimize import fmin_powell
from lightdock.constants import DEFAULT_STEP_SIZE, DEFAULT_TRANSLATION_STEP, DEFAULT_ROTATION_STEP, \
DEFAULT_NMODES_REC, DEFAULT_NMODES_LIG, DEFAULT_NMODES_STEP
from lightdock.mathutil.cython.quaternion i... |
import logging
import os
import numpy as np
from fairseq.data import (
data_utils,
Dictionary,
AppendTokenDataset,
ConcatDataset,
DenoisingDataset,
PrependTokenDataset,
ResamplingDataset,
SortDataset,
TokenBlockDataset,
)
from .denoising import DenoisingTask
from fairseq.data.encod... |
from keystone import auth
from keystone.common import dependency
from keystone.common import wsgi
from keystone import exception
from keystone.openstack.common import log
from keystone.openstack.common import timeutils
LOG = log.getLogger(__name__)
@dependency.requires('token_provider_api')
class Token(auth.AuthMet... |
from __future__ import absolute_import
from django.core.exceptions import PermissionDenied
from django.db import models
from django.contrib.auth import authenticate
from django.contrib.sites.models import Site
from django.utils.encoding import python_2_unicode_compatible
from django.utils.crypto import get_random_stri... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
try:
import shade
HAS_SHADE = True
except ImportError:
HAS_SHADE = False
from ... |
from bcc import BPF
import os
import sys
from unittest import main, TestCase
class TestKprobeRgx(TestCase):
def setUp(self):
self.b = BPF(text=b"""
typedef struct { int idx; } Key;
typedef struct { u64 val; } Val;
BPF_HASH(stats, Key, Val, 3);
int hello(void *ctx) {
... |
import pyoorb
import numpy
if __name__ == "__main__":
print "starting..."
print "calling oorb_init():"
pyoorb.pyoorb.oorb_init(error_verbosity=5, info_verbosity=5)
#orb is id, 6 elements, epoch_mjd, H, G, element type index
#keplerian appears to be element type index 3
#orbits = numpy.array([0.... |
from unittest import TestCase
from django.core.exceptions import ImproperlyConfigured
from django.test.utils import override_settings
from weblate.utils.classloader import ClassLoader, load_class
class LoadClassTest(TestCase):
def test_correct(self):
cls = load_class("unittest.TestCase", "TEST")
... |
import unittest
import glob
import sys
import os
from IECore import *
class TestYUVImageWriter(unittest.TestCase):
def __makeFloatImage( self, dataWindow, displayWindow, withAlpha = False, dataType = FloatVectorData ) :
img = ImagePrimitive( dataWindow, displayWindow )
w = dataWindow.max.x - dataWindow.min.x +... |
from random import sample
from .. import app, db, auth, jwt_st
from flask import request, jsonify, make_response, g, Blueprint
from ..models import User, Todo, Todo_Ongoing, Todo_Done, Board, Thanks
from ..email import send_email
user = Blueprint('user', __name__)
@user.route('/register/', methods=['POST'])
def regi... |
#!/usr/bin/python
from __future__ import print_function
from pyrad.client import Client
from pyrad.dictionary import Dictionary
import socket
import sys
import pyrad.packet
srv = Client(server="localhost", secret=b"Kah3choteereethiejeimaeziecumi", dict=Dictionary("dictionary"))
req = srv.CreateAuthPacket(code=pyrad.p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.