content stringlengths 4 20k |
|---|
import re
def slugify(s):
# FIXME: This is Polish-language-specific.
STOPLIST = ['i', 'a', 'z', 'w', '', 'o',
'jak', 'sie', 'do',
'na', 'to', 'quot', 'gt',
]
if type(s) != str:
s = str(s, 'utf-8')
s = s.lower()
# FIXME: This is Polish-languag... |
# pylint: disable=C0301
# the mountinfo data lines are too long
import os
import stat
import yaml
from mocker import MockerTestCase
from unittest import TestCase
from cloudinit import importer
from cloudinit import util
class FakeSelinux(object):
def __init__(self, match_what):
self.match_what = match_... |
from rpython.rlib import rgc, jit
from rpython.rlib.objectmodel import enforceargs
from rpython.rlib.rarithmetic import ovfcheck, r_uint, intmask
from rpython.rlib.debug import ll_assert
from rpython.rlib.unroll import unrolling_iterable
from rpython.rtyper.rptr import PtrRepr
from rpython.rtyper.lltypesystem import ll... |
import os
import sys
import shutil
import urllib2
import argparse
import tempfile
from zipfile import ZipFile
from StringIO import StringIO
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), ".."))
import lib.cuckoo.common.colors as colors
from lib.cuckoo.common.constants import CUCKOO_ROOT
URL... |
# -*- coding: UTF-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
import io
import logging
import os.path
import shutil
import mock
import pytest
from pre_commit.staged_files_only import staged_files_only
from pre_commit.util import cmd_output
from pre_commit.util import cwd
from... |
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
from six.moves import range
import argparse
import norm_nn as nn
import os
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from datetime import datetime
from math import s... |
import re
''' -- imports from installed packages -- '''
from django.shortcuts import render_to_response
from django.template import RequestContext
# from django.core.urlresolvers import reverse
from mongokit import paginator
try:
from bson import ObjectId
except ImportError: # old pymongo
from pymongo.objectid i... |
from __future__ import print_function
import sys
import os
import subprocess
from offload_error import OffloadError
from _misc import _debug as debug
from _misc import _config as config
from _pymicimpl import _pymic_impl_load_library
from _pymicimpl import _pymic_impl_unload_library
from _pymicimpl import _pymic_imp... |
"""Invenio user management and authentication."""
import os
import sys
from setuptools import find_packages, setup
from setuptools.command.test import test as TestCommand
readme = open('README.rst').read()
history = open('CHANGES.rst').read()
tests_require = [
'check-manifest>=0.25',
'coverage>=4.0',
'i... |
__author__ = 'lorenzo'
import json
import unittest
from scripts.factory import SubSystem
from scripts.datagenerator.constraints import tech_constrains
from config.config import _TEMP_SECRET
class BasicComponentCreation(unittest.TestCase):
kind = 'communication'
c = SubSystem.generate_py_instance(kind, tech... |
"""
Exporter classes : Exporting data to file
Class BaseTextExporter is used as a template for exporting data to
differents file
Class CSVExporter export Metada and Data to csv file
Class AvivExporter export Metada and Data to aviv file
Class GraphicExporter export Metada and Data to png file
"""
from StringIO ... |
from odoo import api, fields, models
from datetime import timedelta, date
class ResPartner(models.Model):
_inherit = "res.partner"
blocked_sales = fields.Boolean('Sales blocked?', copy=False)
defaulter = fields.Boolean()
never_block = fields.Boolean("Never block sales in this partner")
... |
import iutil, shlex
from flags import flags
from pyanaconda.constants import ROOT_PATH
from pykickstart.constants import *
import logging
log = logging.getLogger("anaconda")
selinux_states = { SELINUX_DISABLED: "disabled",
SELINUX_ENFORCING: "enforcing",
SELINUX_PERMISSIVE: "perm... |
#!/usr/bin/python
import json, sys, unicodedata
dataEn = json.loads(open('../webapp/locales/en_US.json').read())
dataPt = json.loads(open('../webapp/locales/pt_BR.json').read())
dataEs = json.loads(open('../webapp/locales/es_ES.json').read())
dataFr = json.loads(open('../webapp/locales/fr_FR.json').read())
ptItens =... |
from __future__ import print_function
import sys
import os
import logging
import io
import argparse
import yaml
from suricata.update import config
from suricata.update import net
from suricata.update import util
from suricata.update import loghandler
from suricata.update.data.index import index as bundled_index
log... |
import platform
import datetime
import time
from .. import scope_client
from .. import scope_job_runner
from ..config import scope_configuration
def main():
runner = scope_job_runner.JobRunner()
jobs = runner.jobs.get_jobs()
to_email = set()
for job in jobs:
if job.status == scope_job_runner.S... |
''' Implement and provide message protocols for communication between Bokeh
Servers and clients.
'''
from __future__ import absolute_import
from tornado.escape import json_decode
from ..exceptions import ProtocolError
from . import messages
from . import versions
class Protocol(object):
''' Provide a message fa... |
import cv2
import numpy as np
####### training part ###############
samples = np.loadtxt('generalsamples.data',np.float32)
responses = np.loadtxt('generalresponses.data',np.float32)
responses = responses.reshape((responses.size,1))
model = cv2.KNearest()
model.train(samples,responses)
#########################... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'EmbededMedia'
db.create_table('multimedia_embededmedia', (
('id', self.gf('dja... |
import asyncio
from datetime import datetime
import discord
from discord.activity import ActivityType
from discord.ext.commands import BucketType
from bot.bot import command, cooldown
from cogs.cog import Cog
from utils.utilities import (get_avatar, seconds2str, bool_check, is_false,
basi... |
import re
import tempfile
import subprocess
import shutil
import os.path
import pandas
# Label translation function - LimeSurvey to SRI/old REDCap style
def label_to_sri( prefix, ls_label ):
return "%s_%s" % (prefix, re.sub( '_$', '', re.sub( '[_\W]+', '_', re.sub( 'subjid', 'subject_id', ls_label.lower() ) ) ) )
... |
# -*- coding: utf-8 -*-
import datetime
from django.utils.translation import ugettext as _
from django.conf import settings
from cms.models import Page, PageModeratorState, PageModerator, CMSPlugin, Title
from cms.utils import timezone
I_APPROVE = 100 # current user should approve page
I_APPROVE_DELETE = 200
def page... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 11 15:21:02 2016
@author: edarin
"""
import pandas as pd
import numpy as np
from generation import generate_population
from tools import (distance_to_reference, get_proba, get_classes_age,
ajout_effectif_reference,
from_unique_value_reference_to_standard_referenc... |
import abc
from six import with_metaclass
from rqalpha.const import SIDE
from rqalpha.utils.exception import patch_user_exc
from rqalpha.utils.i18n import gettext as _
class BaseSlippage(with_metaclass(abc.ABCMeta)):
@abc.abstractmethod
def get_trade_price(self, order, price):
raise NotImplementedEr... |
from KineticsKit import *
import visual
import math, string, time
width = 50
height = 10
writepov = 1
inifile = """\
[%(w)sx%(h)s, AA]
Width=%(w)s
Height=%(h)s
Antialias=On
Sampling_Method=2 ; adaptive and recursive super-sampling method
Antialias_Depth=3
Antialias_Threshold=0.1
""" % {'w':width, 'h':height}
f = ope... |
"""
Terminal Escape Sequences for input and display
"""
import re
try:
from urwid import str_util
except ImportError:
from urwid import old_str_util as str_util
from urwid.compat import bytes, bytes3
within_double_byte = str_util.within_double_byte
SO = "\x0e"
SI = "\x0f"
IBMPC_ON = "\x1b[11m"
IBMPC_OFF = ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import model_utils.fields
import django.utils.timezone
from django.conf import settings
from opaque_keys.edx.django.models import (
BlockTypeKeyField, CourseKeyField, UsageKeyField
)
class Migration(migration... |
"""
Extract CIFAR-100 feature from AutoEncoder
"""
import cPickle as pickle;
import numpy as np;
import theano;
import theano.tensor as T;
import matplotlib.pyplot as plt;
import telauges.utils as utils;
from telauges.hidden_layer import AutoEncoder;
n_epochs=100;
training_portion=1;
batch_size=100;
rng=np.random.R... |
import logging
import os
import sys
from lib.database import Database
from lib.utils import emojify
class Command(object):
def __init__(self, bot, config):
self.bot = bot
self._config = config
self._logger = logging.getLogger('pyper.command.' + self.name)
self.name = self.__get_n... |
import sys, os
from fatools.lib.utils import cout, cerr
from fatools.lib.sqlmodels.handler_interface import base_sqlhandler
from fatools.lib.sqlmodels import schema
class SQLHandler(base_sqlhandler):
Panel = schema.Panel
Marker = schema.Marker
Batch = schema.Batch
Sample = schema.Sample
Assay = s... |
#!/usr/bin/env python
# [SublimeLinter pep8-max-line-length:150]
# -*- coding: utf-8 -*-
"""
black_rhino is a multi-agent simulator for financial network analysis
Copyright (C) 2016 Co-Pierre Georg (<EMAIL>)
Pawel Fiedor (<EMAIL>)
This program is free software: you can redistribute it and/or modify
it under the terms... |
# -*- coding: UTF-8 -*-
__revision__ = '$Id: macutils.py 1519 2011-02-05 15:32:36Z iznogoud $'
# Copyright (c) 2005-2011 Vasco Nunes, Piotr Ożarowski
#
# 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 Foun... |
"""OpenStackClient plugin for Governance service."""
from oslo_log import log as logging
from congressclient.common import utils
LOG = logging.getLogger(__name__)
DEFAULT_POLICY_API_VERSION = '1'
API_VERSION_OPTION = 'os_policy_api_version'
API_NAME = 'congressclient'
API_VERSIONS = {
'1': 'congressclient.v1.cl... |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.core.urlresolvers import reverse
from django.test import TestCase
from . import models
from django.contrib.auth import get... |
from __future__ import absolute_import
from __future__ import unicode_literals
import os
from compose.config.config import ConfigDetails
from compose.config.config import ConfigFile
from compose.config.config import load
def build_config(contents, **kwargs):
return load(build_config_details(contents, **kwargs))... |
import os
import anyconfig
from molecule import interpolation
from molecule import logger
from molecule import platforms
from molecule import scenario
from molecule import state
from molecule import util
from molecule.dependency import ansible_galaxy
from molecule.dependency import gilt
from molecule.driver import do... |
from gen import *
##########
# shared #
##########
flow_var[0] = """
(declare-fun tau () Real)
"""
flow_dec[0] = """
(define-ode flow_1 ((= d/dt[tau] 1)))
"""
state_dec[0] = """
(declare-fun time_{0} () Real)
(declare-fun tau_{0}_0 () Real)
(declare-fun tau_{0}_t () Real)
"""
state_val[0] = """
(assert (<= 0 t... |
from bbschema import Publication, PublicationType
from check_helper_functions import *
from entity_testing import EntityTests
from sample_data_helper_functions import *
class TestPublication(EntityTests):
"""Class that gathers tests for Publication entities
See class_diagram.png to see how it is related to ... |
async def f11(x):
y = {await<error descr="Expression expected"> </error>for await<error descr="Expression expected"> </error>in []} # fail
await x
def f12(x):
y = {await for await in []}
return x
async def f21(x):
y = {mapper(await<error descr="Expression expected">)</error> for await<error des... |
#!/bin/env python
# Automatically translated python version of
# OpenSceneGraph example program "osgpagedlod"
# !!! This program will need manual tuning before it will work. !!!
import sys
from osgpypp import osg
from osgpypp import osgDB
from osgpypp import osgUtil
# Translated from file 'osgpagedlod.cpp'
# Ope... |
# coding: utf-8
import re
from gettext import gettext as _, ngettext as n_
import datetime
class FieldError(Exception):
def __init__(self, field, val, msg):
self.field = field
self.val = val
self.msg = msg
def __str__(self):
cls = self.field.__class__.__name__
return '%s\n%s: %s' % (self.msg,... |
"""
:created: 11.03.2018 by Jens Diemer, www.jensdiemer.de
:copyleft: 2018 by the bootstrap_env team, see AUTHORS for more details.
:license: GNU General Public License v3 or later (GPLv3+), see LICENSE for more details.
"""
import contextlib
import io
import os
import unittest
from pathlib import Path
# B... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the VFS back-end CLI arguments helper."""
import argparse
import unittest
from plaso.cli import tools
from plaso.cli.helpers import vfs_backend
from plaso.lib import errors
from tests.cli import test_lib as cli_test_lib
class VFSBackEndArgumentsHelperTest... |
"""
SALTS XBMC Addon
Copyright (C) 2014 tknorris
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 your option) any later version.
T... |
"""HITAP Birleştirme Sorgula
Hitap üzerinden personelin hizmet birleştirme bilgilerinin sorgulamasını yapar.
"""
from ulakbus.services.personel.hitap.hitap_sorgula import HITAPSorgula
class HizmetBirlestirmeGetir(HITAPSorgula):
"""
HITAP Sorgulama servisinden kalıtılmış
Hizmet Birleştirme Bilgisi Sorgu... |
"""
Copyright (C) 2014, 申瑞珉 (Ruimin Shen)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed i... |
#http://doc.aldebaran.com/2-5/naoqi/core/altabletservice-api.html
import qi
import argparse
import sys
import os
import time
import conditions
from conditions import set_condition
# function called when the signal onTouchDown is triggered
def onTouched(x, y):
global memory_service
print "coordinates are x: "... |
from django.db import models
from brand.models import Brand
# Create your models here.
class ItemManager(models.Manager):
def get_item(self, item_pk):
try:
item = Item.objects.get(pk=item_pk)
except Item.DoesNotExist:
item = None
return item
class Item(models.Mo... |
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon.utils import memoized
from openstack_dashboard import api
from openstack_dashboard.dashboards.admin.routers.extensions.extraroutes\
import form... |
"""TF-Agents Experimental Modules.
These utilities, libraries, and tools have not been rigorously tested for
production use. For example, experimental examples may not have associated
nightly regression tests.
"""
# Aliasing the already moved `tf_agent.train` module from its new location here
# for backward compatibi... |
# -*- coding: utf-8 -*-
import config
import numpy as np
# 统计一下问题的平均vote/ans/bestans,以及相互的比重,并把三个值得dict保存
def question_numerical(back=True):
q2vote = {}
q2ans = {}
q2bestans = {}
vote_count, ans_count, bestans_count = {}, {}, {}
avg_vote, avg_ans, avg_bestans = 0, 0, 0
avg_ans2vote, avg_bestans2vote, avg_best... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('globenocturneapp', '0010_auto_20150623_1622'),
]
operations = [
migrations.CreateModel(
name='WorldCountrySOL',
... |
from django.db import models
from django.contrib import auth
from django.forms import ModelForm
from django.template.defaultfilters import slugify
from datetime import datetime
import re
import string
class Post(models.Model):
"""
Post data class represents a Blog Post
"""
title = models.CharField(max... |
# -*- coding: utf-8 -*-
from couchpotato.core.event import addEvent, fireEvent
from couchpotato.core.helpers.encoding import ss
from couchpotato.core.helpers.variable import tryFloat, mergeDicts, md5, \
possibleTitles, getTitle
from couchpotato.core.logger import CPLog
from couchpotato.core.plugins.base import Plug... |
import sys
import rlp
from rlp.sedes import CountableList, binary
from rlp.utils import decode_hex, encode_hex, ascii_chr, str_to_bytes
from ethereum import opcodes
from ethereum import utils
from ethereum import specials
from ethereum import bloom
from ethereum import vm as vm
from ethereum.exceptions import *
from et... |
# src/nmapps/injection.py
import logging
from nmapps.utils import UserException
LOGGER = logging.getLogger("nmapps.injection")
class DependencyException(UserException):
pass
class DependencyManager(object):
def __str__(self):
return "%s()" % (type(self).__name__, )
def set(key, value, *... |
""" The base class for all actions. """
# Enthought library imports.
from traits.api import Bool, Callable, Enum, HasTraits, Instance, Str
from traits.api import Unicode
from traitsui.ui_traits import Image
class Action(HasTraits):
""" The base class for all actions.
An action is the non-UI side of a comma... |
import platform as py_platform
from spack.architecture import OperatingSystem
from spack.version import Version
from spack.util.executable import Executable
# FIXME: store versions inside OperatingSystem as a Version instead of string
def macos_version():
"""temporary workaround to return a macOS version as a Ve... |
# ElGamal Cryptanalysis Module.
# Contributor: Sushant Dinesh [:sushant94]
# Read Multiple signatures (r, s, m) from a JSON file.
# Check if the private factor is vulnerable due to re-use of 'r'
'''
JSON Input Format:
====================
{
"generator": ... , "safeprime": ... , "pubkey": ... ,
"sigs": [
... |
"""Profile controller module"""
from tg import expose, redirect, abort, url
from depot.manager import DepotManager
from mozzarella.lib.base import BaseController
from mozzarella.model import DBSession, User
from mozzarella.lib.card import Card, CardTypes
__all__ = ['UsersController']
def card_about_me(user):
i... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
fillnodata.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
****************************... |
import json
from typing import Any, Dict, cast
from unittest import mock
import requests
from zerver.lib.avatar import get_gravatar_url
from zerver.lib.message import MessageDict
from zerver.lib.outgoing_webhook import get_service_interface_class, process_success_response
from zerver.lib.test_classes import ZulipTest... |
import numpy as np
import pp
from pp.components.bezier import bezier
from pp.container import container
@container
def package_optical2x2(component, port_spacing=20.0, bend_length=None):
"""returns component with port_spacing"""
component = pp.call_if_func(component)
component.y = 0
if bend_length i... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
class Defaults(object):
DEBUG = False
TESTING = False
LANGUAGES = {
'en': 'English',
'fr': 'Français',
'es': 'Español',
}
DEFAULT_LANGUAGE = 'en'
SECRET_KEY = 'Default uData secret key'
MONGODB_HOST = ... |
from __future__ import absolute_import
from django.conf import settings
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext_lazy as _
from sentry import roles
from sentry.models import Team, TeamSta... |
"""Schedule for dense operator"""
from __future__ import absolute_import as _abs
import tvm
from .. import tag
from .. import generic
@generic.schedule_dense.register(["opengl"])
def schedule_dense(outs):
"""Schedule for dense operator.
Parameters
----------
outs: Array of Tensor
The computati... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
lastile.py
---------------------
Date : September 2013
Copyright : (C) 2013 by Martin Isenburg
Email : martin near rapidlasso point com
*****************... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from . import Indicator, And
class NonZeroDifference(Indicator):
'''
Keeps track of the difference between two data inputs skipping, memorizing
the last non zero value if the current difference is... |
import numpy as np
import math
import sys
import os
import time
#Rotate x and z by theta.
def rotate(x0,z0,theta):
x = x0*np.cos(theta) - z0*np.sin(theta)
z = x0*np.sin(theta) + z0*np.cos(theta)
return x,z
#Find converging amplitude for damping source term.
def finalAmplitude(L,w):
T... |
# -*- encoding: utf-8 -*-
"""
stonemason.tilecache.tilecache
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A do nothing tile cache.
"""
__author__ = 'kotaimen'
__date__ = '1/6/15'
from stonemason.pyramid import Tile
class TileCacheError(Exception):
pass
class TileNotFound(TileCacheError):
pass
class TileC... |
"""
Copyright (C) 2004-2015 Pivotal Software, Inc. All rights reserved.
This program and the accompanying materials are made available under
the terms of the 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
... |
import yt
import numpy as np
from galaxy_analysis.plot.plot_styles import *
fsize = 22
import matplotlib.pyplot as plt
from collections import Iterable, OrderedDict
import glob
import os
import h5py
import deepdish as dd
# parallel
from multiprocessing import Pool
from contextlib import closing
import itertools
# ... |
__all__ = ['EasyDict', 'args_indexes', 'class_name', 'dummy_context_mgr', 'get_local_devices', 'ilog2', 'local_kwargs',
'map_to_device', 'multi_host_barrier', 'override_args_kwargs', 'positional_args_names', 'Renamer',
're_sign', 'repr_function', 'to_interpolate', 'to_padding', 'to_tuple']
import... |
from django import forms
from django.utils.translation import ugettext_lazy as _
from .models import Page
from ._markups import get_all_markups
from .settings import WALIKI_CODEMIRROR_SETTINGS as CM_SETTINGS, get_slug
from .acl import check_perms
class DeleteForm(forms.Form):
what = forms.ChoiceField(label=_('Wha... |
from publica import settings
from datetime import datetime
from publica.core.portal import Portal
from publica.utils.json import encode, decode
from publica.utils.decorators import dbconnectionapp, serialize, jsoncallback
class Public(object):
"""
public class of methods of this content
"""
def ... |
import unittest
import rawdatx.read_TOA5 as read_raw_data
import rawdatx.process_XML as process_XML
import glob, sys, os, hashlib, zipfile
try: import ConfigParser as configparser # Python 2
except ImportError: import configparser # Python 3
cfg="""
[RawData]
raw_data_path = ./raw_data/
mask = ... |
import asposepdfcloud
from asposepdfcloud.PdfApi import PdfApi
from asposepdfcloud.PdfApi import ApiException
from asposepdfcloud.models import AppendDocument
import asposestoragecloud
from asposestoragecloud.StorageApi import StorageApi
from asposestoragecloud.StorageApi import ResponseMessage
apiKey = "XXXXX" #sepc... |
import os
import re
import yaml
import logging
import markdown
import devsiteHelper
from google.appengine.ext.webapp.template import render
SOURCE_PATH = os.path.join(os.path.dirname(__file__), 'src/content/')
UNSUPPORTED_TAGS = [
r'{% link_sample_button .+%}',
r'{% include_code (.+)%}'
]
def getPage(requestPath,... |
"""System information."""
__all__ = [
'ISystem',
]
from zope.interface import Interface, Attribute
class ISystem(Interface):
"""Information about the Mailman system."""
mailman_version = Attribute('The GNU Mailman version.')
python_version = Attribute('The Python version.') |
from troposphere import Ref, Template, Parameter
from troposphere.constants import STRING
import troposphere.ssm as ssm
t = Template()
t.add_description("2012-09-09")
rhel_patch_group_name = t.add_parameter(Parameter(
"RHELPatchGroupName",
Type=STRING,
Description="The value of the RHEL patch group tag "
... |
"""Local node REST api.
"""
import logging
import os
# pylint: disable=E0611,F0401
import flask
import flask_restplus as restplus
from treadmill import webutils
_LOGGER = logging.getLogger(__name__)
# pylint: disable=W0232,R0912
def init(api, cors, impl):
"""Configures REST handlers for allocation resource.""... |
"""
Django settings for Episodes project.
Generated by 'django-admin startproject' using Django 1.9.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Request'
db.create_table('spf_request', (
('id', self.gf('django.db.models.field... |
# -*- coding: utf-8 -*-
#------------------------------------------------------------
# seriesly - XBMC Plugin
# Conector para videomega
# http://blog.tvalacarta.info/plugin-xbmc/seriesly/
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os
from core import scrape... |
import base64
from keystone.common import pemutils
from keystone import tests
from six import moves
# List of 2-tuples, (pem_type, pem_header)
headers = pemutils.PEM_TYPE_TO_HEADER.items()
def make_data(size, offset=0):
return ''.join([chr(x % 255) for x in moves.range(offset, size + offset)])
def make_base64... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from httpie.plugins import FormatterPlugin
from ohoh.clients import DebuggerCliClient
class Formatter(DebuggerCliClient, FormatterPlugin):
name = DebuggerCliClient.intro
def __init__(self, env, **kwargs):
self.enabled = True
sel... |
import unittest
import numpy
import chainer
from chainer import backend
from chainer.backends import cuda
from chainer import links
from chainer import testing
from chainer.testing import attr
class TestInceptionBNBase(unittest.TestCase):
in_channels = 3
out1, proj3, out3, proj33, out33, proj_pool = 3, 2, ... |
#!/usr/bin/env python
"""Train model to predict lightning using a simple convnet.
Copyright Google Inc.
2018 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.... |
import os
import mutagen
from quodlibet.compat import cBytesIO
from tests import TestCase, get_data_path
from quodlibet.formats.mp4 import MP4File
from quodlibet.formats._image import EmbeddedImage
import mutagen.mp4
from .helper import get_temp_copy
class TMP4File(TestCase):
def setUp(self):
self.f =... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Generate word clouds based on termvectors for random sets of documents.
"""
import logging
from django.core.management.base import BaseCommand
from collections import Counter
import time
import requests
import json
from services.es import _es
from services.models impo... |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012-2016 Alex Forencich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the... |
# creates: transport_setup.png
import numpy as np
from ase import Atoms
from ase.structure import molecule
from ase.io import write
a = 3.92 # Experimental lattice constant
sqrt = np.sqrt
cell = np.array([[a / sqrt(3), 0., 0.],
[ 0., a / sqrt(2), 0.],
... |
import subprocess
import RPi.GPIO as GPIO
import time
def main():
unlock_bolt()
locked = unlock_bolt()
while 1 == 1:
if check_usb():
locked = unlock_bolt() if locked else lock_bolt()
time.sleep(2)
def unlock_bolt():
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(33, GPIO... |
"""Thermalblock demo.
Usage:
thermalblock.py [-ehp] [--estimator-norm=NORM] [--extension-alg=ALG] [--grid=NI] [--help]
[--pickle=PREFIX] [--plot-solutions] [--plot-error-sequence] [--reductor=RED]
[--test=COUNT]
XBLOCKS YBLOCKS SNAPSHOTS RBSIZE
Arguments:
XBL... |
"""Tests for yapf.split_penalty."""
import sys
import textwrap
import unittest
from lib2to3 import pytree
from yapf.yapflib import pytree_utils
from yapf.yapflib import pytree_visitor
from yapf.yapflib import split_penalty
UNBREAKABLE = split_penalty.UNBREAKABLE
STRONGLY_CONNECTED = split_penalty.STRONGLY_CONNECTED... |
class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
s = set()
for i in range(1,10):
s.add(chr(ord('0') + i))
for i in range(9):
temp1 = set(s)
temp2 = set(s)
... |
# -*- encoding:utf-8 -*-
from __future__ import unicode_literals
MESSAGES = {
"%d min remaining to read": "Залишилось читати %d хвилин",
"(active)": "(активне)",
"Also available in:": "Іншою мовою:",
"Archive": "Архів",
"Authors": "Автори",
"Categories": "Категорії",
"Comments": "Коментарі"... |
import tacticenv
from pyasm.security import Batch
from pyasm.search import Search
from pyasm.common import SPTDate
from pyasm.command import Command
from dateutil import parser
from dateutil.relativedelta import relativedelta
import sys
class FixDay(Command):
'''Fix the work hours getting offset issue by bringi... |
""" Invoke various functionality for imageio docs.
"""
import os
import sys
import imageio
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
DOC_DIR = os.path.dirname(THIS_DIR)
files_to_remove = []
def setup(app):
init()
app.connect('build-finished', clean)
def init():
print('Special prepa... |
# python standard library
from contextlib import nested
# third-party
from behave import given, when, then
from hamcrest import assert_that, is_, equal_to, contains
from mock import MagicMock, patch, call
# this package
from theape.plugins.apeplugin import OperatorConfigurationConstants, OperatorConfiguration
from th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.