content string |
|---|
import sys, os, site, logging, optparse
server_options_parser = optparse.OptionParser()
server_options_parser.add_option("-d", "--debug", dest="debug", default=False, action="store_true")
server_options_parser.add_option("--pygments", dest="pygments", default=False, action="store_true")
server_options_parser.add_optio... |
"""
taylor
==========
"""
import numpy as np
import matplotlib.pyplot as plt
class TaylorDiagram(object):
"""Taylor diagram.
Plot model standard deviation and correlation to reference (data)
sample in a single-quadrant polar plot, with r=stddev and
theta=arccos(correlation).
"""
def __init_... |
# !/usr/bin/env python
import os
import logging
from utils import Singleton
from config import Config
CONFIG_FILE = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) + '/mysqldump.cfg'
# application
class App(object):
__metaclass__ = Singleton
def __init__(self):
# parse configurations
... |
import sys
import numpy as np
import numpy.random as rn
import math
# User defined package
import kflib
import SIR_ensemble_lib
###################################################################
###################################################################
# MAIN CODE ... |
"""Runner objects execute a Pipeline.
This package defines runners, which are used to execute a pipeline.
"""
from apache_beam.runners.direct.direct_runner import DirectRunner
from apache_beam.runners.runner import PipelineRunner
from apache_beam.runners.runner import PipelineState
from apache_beam.runners.runner imp... |
from common.api.serializers import MembershipSerializer
from common.models import Interest, Language, Position, Region
from players.models import Player
from teams.models import Team
from rest_framework import serializers
class TeamPlayerSerializer(serializers.ModelSerializer):
"""Serializer for nesting a Player ... |
import graphene
from gqlclans.logic import get_clan_info, search_clan
class Member(graphene.ObjectType):
name = graphene.String()
account_id = graphene.ID()
role = graphene.String()
class Message(graphene.ObjectType):
body = graphene.String()
class AddMessage(graphene.Mutation):
class Argument... |
# vim:sw=8:ts=8:et:nowrap
import sys
import re
import os
import string
import mx.DateTime
from miscfuncs import ApplyFixSubstitutions
from splitheadingsspeakers import StampUrl
from contextexception import ContextException
regcolcore = '[^:<]*:\s*column\s*\d+(?:WS)?'
regcolumnum1 = '<br> <br>\s*%s\s*<br> ... |
import mock
from sahara.service import networks
from sahara.tests.unit import base
class TestNetworks(base.SaharaTestCase):
@mock.patch('sahara.service.networks.conductor.instance_update')
@mock.patch('sahara.utils.openstack.nova.get_instance_info')
def test_init_instances_ips_with_floating(self, nova, ... |
import sys
import argparse
from math import log
import itertools
import os
from fasta import *
from fastq import *
def read_clustalw(filename):
sequences = []
with open(filename) as inp:
for line in inp:
words = line.split()
if words:
sequences.append(words[1])
return sequences
def read_fasta_align... |
from logging import *
import os, sys
#LEVEL = DEBUG
LEVEL = WARNING
def get_log_file():
LOG_DIR = os.path.join(os.path.expanduser("~"), '.FLIKA', 'log')
MAX_LOG_IDX = 99
if not os.path.exists(LOG_DIR):
os.makedirs(LOG_DIR)
existing_files = os.listdir(LOG_DIR)
existing_files = [f for f in... |
"""Count and Say
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer ... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
CalculatorModelerAlgorithm.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
************... |
from lib import solution
import re
class Solution(solution.Solution):
def __init__(self, nr):
super().__init__(nr)
self.match_outside = re.compile(r'([^[\]]+)(?:$|\[)')
self.match_inside = re.compile(r'\[(.*?)\]')
self.match_abba = re.compile(r'.*(.)(?!\1)(.)\2\1.*')
self.m... |
"""
"""
# Created on 2014.06.27
#
#
# Copyright 2014, 2015, 2016, 2017 Giovanni Cannata
#
# This file is part of ldap3.
#
# ldap3 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... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'selezionegeo.ui'
#
# by: PyQt4 UI code generator 4.8.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda... |
from extract_image_features.video_utils import *
import numpy as np
from extract_image_features.keras_pretrained_models.imagenet_utils import preprocess_input
from keras.models import Model
from keras.preprocessing import image
from extract_image_features.keras_pretrained_models.vgg19 import VGG19
# file saving and lo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
* Copyright © 2015 Uncharted Software Inc.
*
* Property of Uncharted™, formerly Oculus Info Inc.
* http://uncharted.software/
*
* Released under the MIT License.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this softwa... |
from scipy import *
import matplotlib.pyplot as plt
from scipy.linalg import logm, expm
import sys
## System
psi_up = 0.7
psi_down = sqrt(1.0 - abs(psi_up)**2)
psi_s = array([psi_up, psi_down], dtype=complex)
## Environment
N = 100
psi_e = randn(N)+1j*randn(N) # Random state
psi_e = psi_e / sqrt(sum(abs(psi_e)**2))
... |
#!/usr/bin/env python
import os
from nose.tools import eq_
import mapnik
from .utilities import execution_path, run_all
try:
import itertools.izip as zip
except ImportError:
pass
def setup():
# All of the paths used are relative, if we run the tests
# from another directory we need to chdir()
... |
from scap.model.xnl_2_0.PersonNameType import PersonNameType
import logging
logger = logging.getLogger(__name__)
class PersonNameElement(PersonNameType):
MODEL_MAP = {
'tag_name': 'PersonName',
'elements': [
{'tag_name': 'FormerName', 'list': 'former_names', 'class': 'FormerNameElement'... |
import pandas as pd
df = pd.DataFrame({'A': [11, 21, 31],
'B': [12, 22, 32],
'C': [13, 23, 33]},
index=['ONE', 'TWO', 'THREE'])
print(df)
# A B C
# ONE 11 12 13
# TWO 21 22 23
# THREE 31 32 33
df_new = df.rename(columns={'A': 'Col_1'}, ... |
# third party
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options
# Django
from django.contrib.staticfiles.testing impor... |
"""Event-based IRC Class"""
import random
import re
import time
import urllib
from pyhole import irclib
from pyhole import plugin
class IRC(irclib.SimpleIRCClient):
"""An IRC connection"""
def __init__(self, config, network, log, version, conf_file):
irclib.SimpleIRCClient.__init__(self)
s... |
from vispy import io
import os
from time import time
import numpy as np
from sub8_misc_tools import download_and_unzip
def load_and_cache_mesh(file_path, url=None):
'''Load and save a binary-cached version of a mesh'''
vertices, faces, normals, texcoords = io.read_mesh(file_path)
if url is None:
n... |
import os
from ..util import global_variables
from . import PackageFile
from . import RegisterFile
from . import BaseCMakeFiles
from . import CMakeListsFile
from ..code_files import CppExampleFile
class CMakeFiles():
"""Class for all CMake files"""
def __init__(self, pkg_object, this_dir, verbose=False):
... |
"""Core admin."""
# Copyright 2015 Solinea, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
"""
Module used to interact with relational databases.
"""
import logging
import sqlalchemy
from sqlalchemy.orm import sessionmaker
from api_etl.utils_secrets import get_secret
from api_etl.data_models import RdbModel
from api_etl.utils_misc import build_uri
logger = logging.getLogger(__name__)
RDB_USER = get_secre... |
# -*- coding: utf-8 -*-
# List of SysTray elements - Global Plugin for NVDA
# Authors:
# Rui Fontes <<EMAIL>>
# Rui Batista <<EMAIL>>
# Shortcut: NVDA+f11
import ctypes
import gettext
import languageHandler
import os.path
import wx
import globalPluginHandler,IAccessibleHandler
import globalVars
import scriptHandler
im... |
import netaddr
from neutron_lib import constants as n_const
from os_ken.lib.packet import ipv4
from os_ken.lib.packet import ipv6
from os_ken.lib.packet import packet
from os_ken.ofproto import ether
from oslo_log import log
from dragonflow.controller.apps import l3_base
from dragonflow.controller.common import const... |
"""Test utilities"""
import sys
import six
import enum
try:
import collections.abc as collections_abc # python 3.3+
except ImportError:
import collections as collections_abc
# Local imports
from . import DevState, GreenMode
from .server import Device
from .test_context import MultiDeviceTestContext, DeviceTe... |
"""
Jawbone OAuth2 backend, docs at:
http://psa.matiasaguirre.net/docs/backends/jawbone.html
"""
from requests import HTTPError
from social.backends.oauth import BaseOAuth2
from social.exceptions import AuthCanceled, AuthUnknownError
class JawboneOAuth2(BaseOAuth2):
name = 'jawbone'
AUTHORIZATION_URL = 'h... |
"""Tests for module model_performance_analysis.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from os import path
import textwrap
from absl import flags
from absl.testing import absltest
from absl.testing import parameterized
import pandas as pd
imp... |
"""
ROS message source code generation for rospy.
Converts ROS .srv files into Python source code implementations.
"""
import roslib; roslib.load_manifest('rospy')
import sys, os
import roslib.genpy
import roslib.gentools
import roslib.srvs
import genmsg_py, genutil
REQUEST ='Request'
RESPONSE='Response'
class S... |
import sim, sim_items, main
from util import *
import random
class FeatherlightPrefix(sim_items.Prefix):
def __init__(self):
super(FeatherlightPrefix, self).__init__(
"featherlight", # name
"Certain armor-smiths have mastered the art of using foreign "
"light weight cure... |
"""LAMB (Layer-wise Adaptive Moments) optimizer as TF1 tf.train.Optimizer.
See paper [Large Batch Optimization for Deep Learning: Training BERT in 76
minutes](https://arxiv.org/abs/1904.00962).
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
... |
import subprocess
import sys
import os
import math
# This code is meant to manage running multiple instances of my KMCLib codes at the same time,
# in the name of time efficiency
numLambda = 256
numStepsEquilib = 16000000
numStepsAnal = 16000
numStepsSnapshot = 1000
numStepsReq = 320000
sysWidth = 16
sysLength = 16
an... |
import sys
import tkinter as tk
from PIL import ImageTk
from Sheet import Sheet
import settings
def resize_layout(event=[]):
global sheet
pixelX=tk_root.winfo_width()
pixelY=tk_root.winfo_height()
sheet.resize()
def graphics_init():
tk_root.title("MindMap")
tk_root.geometry("{}x{}+{}+{}"... |
#!/usr/bin/env python2.6
import textwrap
import pytest
import time
from tests.test_registrar_name.test_request_json import initialize_simulation
def test_validate_domain_candidates_none(session, log_file, capsys):
response = '{"result":{"code":100,"message":"Command Successful"},"bar":["baz", null, 1.0, 2]}'
... |
from PyQt4.QtCore import QTimer
from OTPApplication import OTPApplication
from Util import listToString
class PilotInfo(object):
__info = {}
def __init__(self):
object.__init__(self)
self._name = None
self._teamName = None
self._state = None
self._reason = None
... |
from mangopaysdk.entities.entitybase import EntityBase
from mangopaysdk.types.money import Money
class Transaction (EntityBase):
"""Transaction entity.
Base class for: PayIn, PayOut, Transfer.
"""
def __init__(self, id = None):
self.AuthorId = None
self.CreditedUserId = None
#... |
import IMP
import IMP.test
import IMP.domino
import IMP.core
import IMP.algebra
import random
class LogRestraint(IMP.Restraint):
def __init__(self, m, ps):
IMP.Restraint.__init__(self, m, "LogRestraint%1%")
self.count = 0
self.ps = ps
def unprotected_evaluate(self, da):
self.... |
bot=None
import modules
import modules.eliza as eliza
import os,time
from BeautifulSoup import BeautifulSoup
from modules.chatterbotapi import ChatterBotFactory, ChatterBotType
factory = ChatterBotFactory()
bot1 = factory.create(ChatterBotType.PANDORABOTS, 'b0dafd24ee35a477')
#bot1session = bot1.create_session()
bots... |
from __future__ import absolute_import
import sys
import gevent
import gevent.event
import gevent.queue
from pykka import Timeout
from pykka.actor import Actor
from pykka.future import Future
__all__ = [
'GeventActor',
'GeventFuture',
]
class GeventFuture(Future):
"""
:class:`GeventFuture` imple... |
import base64
import os
import quopri
import re
import socket
import string
import threading
import unittest
from trac.config import ConfigurationError
from trac.notification import SendmailEmailSender, SmtpEmailSender
from trac.test import EnvironmentStub
LF = '\n'
CR = '\r'
SMTP_TEST_PORT = 7000 + os.getpid() % 100... |
#!/usr/bin/env python
""" MultiQC module to parse output from QUAST """
from __future__ import print_function
from collections import OrderedDict
import logging
import re
from multiqc import config
from multiqc.plots import table, bargraph
from multiqc.modules.base_module import BaseMultiqcModule
# Initialise the l... |
import datetime
from django.test import TestCase
from django.utils import timezone
from schedule.models import Calendar, CalendarRelation, Event, Rule
class TestCalendar(TestCase):
def __create_event(self, start, end):
data = {
'title': 'Recent Event',
'start': start,
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 16 17:21:58 2017
「ctrl」+「s」で保存。その他、コピー、ペースト、全選択のショートカットは通常通り。
全実行は「F5」
1行実行は「F9」
「#%%」でセルを作成
セルの実行は「ctrl」と「enter」同時押し。
セルを実行して次のセルに移動は「shift」と「enter」同時押し。
右下のiPython consoleに直接コードを書いて実行することもできる。
右上のVariable explorerでデータの中身を見ることができる。
1行コメントアウトは「ctrl」と「1」を同時押し。コメントアウト解除も同様。... |
import numpy
import os
import matplotlib.pyplot as plt
from scipy.sparse import lil_matrix
from pyxpe.recon.injection import analyze_run
if __name__ == '__main__':
import argparse
formatter = argparse.ArgumentDefaultsHelpFormatter
parser = argparse.ArgumentParser(formatter_class=formatter)
parser.add_... |
from txdav.caldav.datastore.scheduling.work import ScheduleWork
"""
SQL backend for CalDAV storage when resources are external.
"""
from twisted.internet.defer import inlineCallbacks, returnValue
from twext.python.log import Logger
from txdav.caldav.datastore.scheduling.imip.token import iMIPTokenRecord
from txdav.c... |
from datetime import datetime
from datetime import timedelta
from pyspark import SparkConf, SparkContext
conf = (SparkConf()
.setMaster("local[*]")
.setAppName("My app")
.set("spark.executor.memory", "8g")
.set("spark.executor.cores", "8"))
sc = SparkContext(conf = conf)
#test = sc.te... |
"""Code transformation exceptions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.autograph.utils import ag_logging
class AutoGraphError(Exception):
pass
class InternalError(AutoGraphError):
"""Raised when AutoGraph finds ... |
from __future__ import unicode_literals
import frappe
from frappe.model.naming import set_name_by_naming_series
from frappe import _, msgprint, throw
import frappe.defaults
from frappe.utils import flt, cint, cstr, today
from frappe.desk.reportview import build_match_conditions, get_filters_cond
from erpnext.utilities.... |
from setuptools import find_packages, setup
setup(
name='oyente',
version='0.2.7',
author='Loi Luu',
# author_email='',
url='https://github.com/melonport/oyente',
description='An analysis tool for smart contracts',
long_description=open('README.md').read(),
license='GPL',
keywords='... |
import numpy as np
import h5py as h5
from utilities_functions import *
from healpy_functions import *
from functools import reduce
def read_from_data(filename,pol,npairs=None):
"""
Read a hdf5 file of one Constant Elevation Scan preprocessed by the AnalysisBackend
of the Polarbear Collaboration.
**... |
from __future__ import print_function
from random import shuffle
from myhdl import *
class FIFO(object):
"""
FIFO interface and model.
"""
def __init__(self, depth=16, width=16, clock_read=None, clock_write=None):
self.depth = depth
self.clock_write = clock_write
self.clock_re... |
import sys
import datetime
def my_weekdatescalendar(cal, date):
weeks = cal.monthdatescalendar(date.year, date.month)
for weekno, week in enumerate(weeks):
# Hide all days that are not part of the current week.
if date in week:
return week
raise Exception('No such week')
def ... |
#
# Provides a single class, OWLOntologyBuilder, that implements methods for
# parsing descriptions of ontology classes (e.g., from CSV files) and
# converting them into classes in an OWL ontology.
#
# Python imports.
import re
import logging
from obohelper import termIRIToOboID, oboIDToIRI
from ontology import Ontolo... |
"""API for manipulating libraries."""
from datetime import datetime, timedelta
from functools import partial
from dateutil import parser
from dateutil.rrule import FREQNAMES, rrule
from invenio_search.api import RecordsSearch
from .models import LibraryIdentifier
from ..api import IlsRecord
from ..fetchers import id... |
# -*- coding: utf-8 -*-
'''
This os an example of spider for forum working with scrapy lib.
'''
__author__ = "YO_N"
__license__= "MIT"
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from scrapy.selector import Selector
from aks.items import AkusherstvoItem
... |
# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------... |
"""Tests for ssd resnet v1 FPN feature extractors."""
import tensorflow as tf
from object_detection.models import ssd_resnet_v1_fpn_feature_extractor
from object_detection.models import ssd_resnet_v1_fpn_feature_extractor_testbase
class SSDResnet50V1FeatureExtractorTest(
ssd_resnet_v1_fpn_feature_extractor_testb... |
import sys
import nltk
from lexicon import Lexicon
from stemming.porter2 import stem
class HpSubj:
"""
High precision subjective sentence classifier which uses an annotated
lexicon of words as features. It classifies a sentence as subjective
if it contains two or more of the strong subjec... |
"""Module for testing constraints in commands involving domain."""
import os
import unittest
if __name__ == "__main__":
import utils
utils.import_depends()
from brokertest import TestBrokerCommand
class TestDomainConstraints(TestBrokerCommand):
def testdelsandboxwithhost(self):
command = "del ... |
#! /usr/bin/env python
###############################################################################
import nose
import sys
import io
import random
import os
import glob
import pdb
import subprocess
import numpy.testing
from mann import agent
here = os.path.abspath(os.path.dirname(__file__))
######################... |
#!/usr/bin/env python
import json
import logging
import os
import re
import signal
from pathlib import Path
from pprint import pformat
from zipfile import ZipFile, is_zipfile
import yaml
from requests_oauthlib import OAuth1Session
def print_user_info(zip_path):
"""Print user details in a ZIP archive
"""
... |
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.test import APITestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from drfpasswordless.settings import api_settings, DEFAULTS
from drfpasswordless.utils import CallbackToken
Use... |
class Solution:
# @param A, a list of integers
# @param target, an integer to be searched
# @return an integer
def search(self, A, target):
left, right = 0, len(A)-1
while left + 1 < right :
mid = (left+right)/2
if A[mid] >= A[left] :
if A[mid] >= ... |
# -*- coding: utf-8 -*-
import pkg_resources
from plone.app.dexterity.browser import fields
from plone.schemaeditor.browser.schema.listing import ReadOnlySchemaListing
from zope.event import notify
from z3c.form.events import DataExtractedEvent
class EnhancedSchemaListing(fields.EnhancedSchemaListing):
def extra... |
#!/usr/bin/env python
import fileinput, string, sys, subprocess
#####################################################################################
#Thanks to John Nielsen
#http://code.activestate.com/recipes/408859-socketrecv-three-ways-to-turn-it-into-recvall/
#####################################################... |
class progressBar:
""" Creates a text-based progress bar. Call the object with the `print'
command to see the progress bar, which looks something like this:
[=======> 22% ]
You may specify the progress bar's width, min and max values on init.
"""
def __init... |
# -*- coding: utf-8 -*-
import os
import subprocess
from base64 import b32encode
from Crypto.Random import random
import gnupg
import scrypt
import config
import store
# to fix gpg error #78 on production
os.environ['USERNAME'] = 'www-data'
GPG_KEY_TYPE = "RSA"
if os.environ.get('SECUREDROP_ENV') == 'test':
# O... |
import sys
import time
from twisted.internet import defer
import p2pool
from p2pool.bitcoin import data as bitcoin_data
from p2pool.util import deferral, jsonrpc
@deferral.retry('Error while checking the daemon connection:', 1)
@defer.inlineCallbacks
def check(daemon, net):
if not (yield net.PARENT.RPC_CHECK(dae... |
all__ = (
"PublicanUtilityTest",
)
import unittest
import sys, os
import json
sys.path.insert(0, os.path.abspath(__file__+"/../.."))
from zanataclient.publicanutil import PublicanUtility
class PublicanUtilityTest(unittest.TestCase):
def setUp(self):
self.publican = PublicanUtility()
... |
#!/usr/bin/python
# ex:set fileencoding=utf-8:
from django.conf import settings
from django.contrib.auth.models import User
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.timezone import now
fr... |
import csv, sys
#sys.path.insert(0, '..')
#from views import lis
#print lis
f = open('../some.csv')
sp = csv.reader(f, delimiter=' ')
for i in sp:
data = i
stories=int(data[0]) #Number of stories
dep_of_foun=float(data[1]) #Depth of Foundation
plinth_lev=float(data[2... |
VERSION = 20140315
DEVICE_TYPE_IOS = 'ios'
DEVICE_TYPE_ANDROID = 'android' |
from django.contrib import admin
from .models import Link
class LinkAdmin(admin.ModelAdmin):
def get_changeform_initial_data(self, request):
return {'owner': request.user}
def get_fields(self, request, obj=None):
if request.user.is_superuser:
return ['name', 'target', 'owner']
... |
# -*- coding: utf-8 -*-
"""
zine.upgrades.webapp
~~~~~~~~~~~~~~~~~~~~
This package implements a simple web application that will be responsible
for upgrading Zine to the latest schema changes.
:copyright: (c) 2010 by the Zine Team, see AUTHORS for more details.
:license: BSD, see LICENSE for m... |
from opus_core.variables.variable import Variable
from variable_functions import my_attribute_label
from urbansim.functions import attribute_label
from numpy import zeros
class is_in_plan_type_group_SSS(Variable):
"""Returns a boolean indicating whether this gridcell's plan type group is
of given name... |
import py
from rpython.translator.translator import TranslationContext
from rpython.translator.backendopt import inline
from rpython.translator.backendopt.all import backend_optimizations
from rpython.translator.translator import TranslationContext, graphof
from rpython.rtyper.llinterp import LLInterpreter
from rpython... |
"""
Helper methods to provide utility for student_certifications application.
"""
from datetime import datetime
from importlib import import_module
from io import BytesIO
from logging import getLogger
import img2pdf
import requests
from boto import connect_s3
from boto.s3.key import Key
from django.conf import setting... |
from __future__ import unicode_literals
import warnings
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
try:
ANONYMOUS_USER_NAME = settings.ANONYMOUS_USER_NAME
except AttributeError:
try:
ANONYMOUS_USER_NAME = settings.ANONYMOUS_DEFAULT_USERNAME_VALUE
wa... |
"""
Module for code that should run during LMS startup
"""
import django
from django.conf import settings
# Force settings to run so that the python path is modified
settings.INSTALLED_APPS # pylint: disable=pointless-statement
from openedx.core.lib.django_startup import autostartup
import logging
import analytics... |
#!/usr/bin/python
#encoding:utf-8
import os
import sys
import subprocess
import json
import re
import StringIO
import math
import shutil
import time
from collections import OrderedDict
from hashlib import md5
# 用装饰器实现单例
def singleton(cls, *args, **kw):
instances = {}
def _singleton():
if cls not in instances:
... |
from plugins.Plugin import Plugin
class TagRemove_FR(Plugin):
only_for = ["FR", "NC"]
def init(self, logger):
Plugin.init(self, logger)
self.errors[41001] = { "item": 4100, "level": 3, "tag": ["tag", "fix:chair"], "desc": T_(u"Misused tag in this country") }
def node(self, data, tags):
... |
import logging
import os
from celery import Celery
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "agir.api.settings")
app = Celery("agir.api")
# - namespace='CELERY' means all celery-related configuration keys
# should have a `CELERY_` prefix.
app.config_from_object("django.conf:settings", namespace="CELERY")
... |
from tornado.web import url
import tornado.web
from handlers.index import (
IndexHandler,
ManhuaHandler,
TianhuodadaoHandler,
QuanwenyueduHandler,
XujiHandler,
ZhoubianHandler,
JueshitangmenHandler,
JiushenHandler,
)
from handlers.abc import (
AHandler,
BHandler,
CHandler,
... |
"""
Utilities for the Indivo admin tool
"""
from django.http import HttpResponseNotAllowed
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.models import User
from django.forms.util import ErrorList
# taken from pointy-stick.com with some modification... |
import unittest
import os
from tests.TestProject import TestProject
from tests.ReloadedTestCase import ReloadedTestCase
class TravisTest(ReloadedTestCase):
def test_travis_module_not_works_if_envvar_Travis_is_not_yes(self):
self.assertFalse(os.environ.get("TRAVIS")=="true")
os.environ["TRAVIS_BRAN... |
"""Commands for starting daemons."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import pprint
import confpy.api
import confpy.core.option
from .. import messages
cfg = confpy.api.Configuration... |
from __future__ import absolute_import
import json
MOLECULE_START = '-OEChem-'
MOLECULE_END = '$$$$'
MDF_SECTION = 'MDF'
SECTION_PREFIX = '<PUBCHEM_'
def parse_molecules(raw_lines):
"""Generator that yields raw molecules."""
molecule = None
section = None
for raw_line in raw_lines:
if isinstance(raw_line... |
"""
Change your nautilus directories icons easily
Author : Bilal Elmoussaoui (<EMAIL>)
Website : https://github.com/bilelmoussaoui/nautilus-folder-icons
Licence : GPL-3.0
nautilus-folder-icons is free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License as published
by t... |
"""Contains the :code:`Address` class, representing a collection of reverse
geocoding results. Primarily, this functions as a container for a set of
:code:`errorgeopy.Location` objects after a successful reverse geocode, and
exposes methods that operate on this set of results, including:
- de-duplication
- extracting ... |
import Tkinter
import time
from ConfigParser import SafeConfigParser
import visual_recognition
from PIL import Image
from PIL import ImageTk
import zipfile
class Application:
def __init__(self, api_key, classifier_id):
self.camera = visual_recognition.Camera()
self.watson = visual_recognition.Wat... |
# -*- coding: utf-8 -*-
# pylint: disable=R0904,C0103
# - Too many public methods
# - Invalid name XXX (should match YYY)
import unittest
import email
import datetime
from storm.exceptions import IntegrityError
from mailman.email.message import Message
from kittystore.storm import get_storm_store
from kittystore.sto... |
import time
import sys
import os
import vim
class Options:
instance = None
def __init__(self):
self.refresh_key = vim.eval('do#get("do_refresh_key")')
self.update_time = int(vim.eval("do#get('do_update_time')"))
self.new_process_window_command = vim.eval('do#get("do_new_process_window_... |
"""Helper code for dealing with protobuf messages."""
import binascii
from pyatv import const
from pyatv.mrp import protobuf
from pyatv.support import hap_tlv8
def create(message_type, error_code=0, identifier=None):
"""Create a ProtocolMessage."""
message = protobuf.ProtocolMessage()
message.type = mes... |
import re
import sys
import os
from datetime import datetime
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.core import mail
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium... |
"""BSDDB BTree-based Shelve OID Storage"""
import bsddb, shelve, traceback, sys
from twistedsnmp import oidstore, errors, pysnmpproto
import struct, weakref
OID = pysnmpproto.oid.OID
if pysnmpproto.USE_STRING_OIDS:
def oidToSortable( oid ):
"""Convert a dotted-format OID to a sortable string"""
return "".join([
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.