code stringlengths 1 199k |
|---|
import os, sys
sys.path.insert( 0, os.path.dirname( __file__ ) )
from common import delete
try:
assert sys.argv[2]
except IndexError:
print 'usage: %s key url [purge (true/false)] ' % os.path.basename( sys.argv[0] )
sys.exit( 1 )
try:
data = {}
data[ 'purge' ] = sys.argv[3]
except IndexError:
pa... |
import rospy
import time
from collections import deque
class Publisher(object):
def __init__(self):
self.publishers = {}
self.queue = deque()
def add_publisher(self, alias, publisher):
self.publishers[alias] = publisher
def publish(self):
while len(self.queue) > 0:
... |
import os, h5py, numpy
from scipy.sparse import csc_matrix
import ml2h5.task
from ml2h5 import VERSION_MLDATA
from ml2h5.converter import ALLOWED_SEPERATORS
class BaseHandler(object):
"""Base handler class.
It is the base for classes to handle different data formats.
It implicitely handles HDF5.
@cvar s... |
from __future__ import unicode_literals
import re
from hashlib import sha1
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
ExtractorError,
determine_ext,
float_or_none,
int_or_none,
unified_strdate,
)
class ProSiebenSat1BaseIE(InfoExtractor):
def _extract_... |
from random import *
import numpy
import pdb
import cPickle
import bz2
import sys
import pylab
import nupic.bindings.algorithms as algo
from nupic.bindings.math import GetNumpyDataType
type = GetNumpyDataType('NTA_Real')
type = 'float32'
def simple():
print "Simple"
numpy.random.seed(42)
n_dims = 2
n_cl... |
from cantilever_divingboard import *
freq_min = 1e3
freq_max = 1e5
omega_min = 100e3
initial_guess = (50e-6, 1e-6, 1e-6,
30e-6, 1e-6, 1e-6, 500e-9, 5., 1e15)
constraints = ((30e-6, 100e-6), (500e-9, 20e-6), (1e-6, 10e-6),
(2e-6, 100e-6), (500e-9, 5e-6), (500e-9, 20e-6), (30e-9, 10e-6),
... |
"""
Django settings for spa_movies project.
Generated by 'django-admin startproject' using Django 1.9.7.
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
BAS... |
HOST = [ 'nagios', 'nagios1' ]
PORT = 6557 |
from module.plugins.internal.XFSHoster import XFSHoster, create_getInfo
class SendmywayCom(XFSHoster):
__name__ = "SendmywayCom"
__type__ = "hoster"
__version__ = "0.04"
__pattern__ = r'http://(?:www\.)?sendmyway\.com/\w{12}'
__description__ = """SendMyWay hoster plugin"""
__license__ ... |
from __future__ import unicode_literals
from frappe import _
app_name = "erpnext"
app_title = "ERPNext"
app_publisher = "Frappe Technologies Pvt. Ltd."
app_description = """ERP made simple"""
app_icon = "fa fa-th"
app_color = "#e74c3c"
app_email = "info@erpnext.com"
app_license = "GNU General Public License (v3)"
sourc... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pattern', '0014_pattern_editnumber'),
]
operations = [
migrations.AddField(
model_name='pattern',
name='json',
field=... |
import pyarchey.pyarchey as py
def test_slack():
o = py.Output()
assert o.readDistro('./test/slack.test') == ('Slackware', 'Slackware 14.1')
def test_arch():
o = py.Output()
assert o.readDistro('./test/arch.test') == ('Arch Linux', 'Arch Linux')
def test_raspbian():
o = py.Output()
assert o.readDistro('./test/ras... |
"""__Main__."""
import sys
import os
import logging
import argparse
import traceback
import shelve
from datetime import datetime
from CONSTANTS import CONSTANTS
from settings.settings import load_config, load_core, load_remote, load_email
from settings.settings import load_html, load_sms
from core import read_structure... |
import gensim, logging
class SemanticVector:
model = ''
def __init__(self, structure):
self.structure = structure
def model_word2vec(self, min_count=15, window=15, size=100):
print 'preparing sentences list'
sentences = self.structure.prepare_list_of_words_in_sentences()
prin... |
import logging
from scap.model.oval_5 import PE_SUBSYSTEM_ENUMERATION
from scap.model.oval_5.defs.EntityStateType import EntityStateType
logger = logging.getLogger(__name__)
class EntityStatePeSubsystemType(EntityStateType):
MODEL_MAP = {
}
def get_value_enum(self):
return PE_SUBSYSTEM_ENUMERATION |
import numpy
import scipy
import random
from gnuradio import gr, gr_unittest
import blocks_swig as blocks
import digital_swig as digital
import channels_swig as channels
from ofdm_txrx import ofdm_tx, ofdm_rx
from utils import tagged_streams
LOG_DEBUG_INFO=False
class ofdm_tx_fg (gr.top_block):
def __init__(self, ... |
from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, String, UniqueConstraint
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:///challenge.sqlite', echo=False)
Session = sessionmaker(bind=engine)
session = Session()
B... |
"""
Contains code for nicely reporting errors to the user.
"""
import logging
import traceback
from PyQt4 import QtGui
from xVClient import ClientGlobals
mainlog = logging.getLogger("")
FatalError = 1
"""Fatal error, forces termination of application."""
NormalError = 2
"""Normal error, this has impact but does not cra... |
import fs
import numpy as np
import h5py
import pm_setup
file = h5py.File('force_%s.h5' % fs.config_precision(), 'r')
ref_id = file['id'][:]
ref_force = file['f'][:]
file.close()
fs.msg.set_loglevel(0)
particles = pm_setup.force()
particle_id = particles.id
particle_force = particles.force
if fs.comm.this_node() == 0:
... |
__author__ = 'Marko Čibej'
import argparse
from svgmapper import *
from helper import logger
def main(config, resources=None, maps=None, simulate=False):
logger.info('Starting job')
with SvgMapper() as mapper:
mapper.load_config(config, resources)
if maps:
mapper.replace_targets(maps... |
from distutils.core import setup
import os
import sys
def main():
SHARE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"share")
data_files = []
# don't trash the users system icons!!
black_list = ['index.theme', 'index.theme~']
for path, dirs, files in os.walk(SHARE_PATH... |
import numpy as np
import cv2
from scipy import interpolate
from random import randint
import IPython
from alan.rgbd.basic_imaging import cos,sin
from alan.synthetic.synthetic_util import rand_sign
from alan.core.points import Point
"""
generates rope using non-holonomic car model dynamics (moves with turn radius)
gene... |
__author__ = 'nicolas'
from os.path import expanduser
from ordereddict import OrderedDict
from Bio import SwissProt
import time
import MySQLdb as mdb
"""
Fuck!
from ordereddict import OrderedDict
import MySQLdb as mdb
dicc = {}
dictdebug_empty = OrderedDict()
dictdebug = dictdebug_empty
dictdebug['hola'] = 'chau'
print... |
from odoo import models, fields, api, _
from odoo.exceptions import ValidationError, UserError
class AccountInvoiceLine(models.Model):
_inherit = 'account.invoice.line'
start_date = fields.Date('Start Date')
end_date = fields.Date('End Date')
must_have_dates = fields.Boolean(
related='product_id... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('agentex', '0014_remove_decision_datacollect'),
]
operations = [
migrations.AddField(
model_name='datapoint',
name='sorttimestamp'... |
import numpy as np
import struct
import wave
from winsound import PlaySound, SND_FILENAME, SND_ASYNC
import matplotlib.pyplot as plt
CHUNK = 1 << 8
def play(filename):
PlaySound(filename, SND_FILENAME | SND_ASYNC)
fn = r"D:\b.wav"
f = wave.open(fn)
print(f.getparams())
ch = f.getnchannels()
sw = f.getsampwidth()
n ... |
import tensorflow as tf
from tensorflow.python.ops import rnn_cell
from tensorflow.python.ops import seq2seq
import numpy as np
class Model():
def __init__(self, args, infer=False):
self.args = args
if infer:
args.batch_size = 1
args.seq_length = 1
if args.model == 'r... |
import terrariumLogging
logger = terrariumLogging.logging.getLogger(__name__)
from pathlib import Path
import inspect
from importlib import import_module
import sys
import statistics
from hashlib import md5
from time import time, sleep
from operator import itemgetter
from func_timeout import func_timeout, FunctionTimed... |
import os
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
import my_config
path = my_config.ROOT_DIR # Please create your config file
file = my_config.FILE # Please create your config file
import wave
def time_series(file, i_ch = 0):
with wave.open(file,'r') as wav_file:
... |
self.Step (Message = "Receptionist-N ->> Klient-N [genvej: fokus-modtagerliste] (måske)")
self.Step (Message = "Receptionist-N ->> Klient-N [retter modtagerlisten]") |
import re
import scipy.interpolate
import numpy as np
vectors = []
class OmnetVector:
def __init__(self,file_input):
self.vectors = {}
self.dataTime = {}
self.dataValues = {}
self.maxtime = 0
self.attrs = {}
for line in file_input:
m = re.search("([0-9]+)\... |
"""598. Split Divisibilities
https://projecteuler.net/problem=598
Consider the number 48.
There are five pairs of integers $a$ and $b$ ($a \leq b$) such that $a \times
b=48$: (1,48), (2,24), (3,16), (4,12) and (6,8).
It can be seen that both 6 and 8 have 4 divisors.
So of those five pairs one consists of two integers w... |
import pyes
import os
from models import *
from sqlalchemy import select
from downloader import download
import utils
import re
import time
class Search(object):
def __init__(self,host,index,map_name,mapping=None,id_key=None):
self.es = pyes.ES(host)
self.index = index
self.map_name = map_na... |
import requests
from bs4 import BeautifulSoup
def trade_spider(max_pages):
page = 1
while page <= max_pages:
url = "https://thenewboston.com/videos.php?cat=98&video=20144" #+ str(page)
source_code = request.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text)
... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangorest.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is r... |
for i in range(0):
i += 1
for j in range(0, 1, 3):
j += 1
for k in range(9, 1, -9):
k += 1
for n in range(0, 1.1): # Error on this line
n += 1
for m in range(4, 5):
m += 1 |
import datetime
from sqlalchemy import MetaData, Table, Column, String, Integer
from Interface import AbstractDataObject
from utils.String import attributes_repr
def define_event_table(meta: MetaData):
return Table(
'events', meta,
Column('book_id', String, primary_key=True),
Column('reader_... |
import logging
import os
import urllib
from cvmfsreplica.cvmfsreplicaex import PluginConfigurationFailure
from cvmfsreplica.interfaces import RepositoryPluginAcceptanceInterface
import cvmfsreplica.pluginsmanagement as pm
class Updatedserver(RepositoryPluginAcceptanceInterface):
def __init__(self, repository, conf)... |
from django.db import models
class Licensor(models.Model):
name = models.CharField(max_length=255, unique=True)
def __unicode__(self):
return self.name
class Meta:
ordering = ['name'] |
import socket
import sys
import time
server_add = './bob_system_socket'
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
message = sys.argv[1]+" "+sys.argv[2]
if sys.argv[1] == 'set':
message+= " "+sys.argv[3]
else:
message+= " null"
try:
sock.connect(server_add)
except socket.error, msg:
print >>sys.stderr... |
import inspect
from django.utils.translation import activate
class MenuItemMixin:
"""
This mixins injects attributes that start with the 'menu_' prefix into
the context generated by the view it is applied to.
This behavior can be used to highlight an item of a navigation component.
"""
def get_c... |
import xauth
import xtemplate
import xutils
import os
import re
import sys
import platform
import xconfig
from xutils import dateutil
from xutils import fsutil
from xutils import Storage
from xutils import mem_util
try:
import sqlite3
except ImportError:
sqlite3 = None
def get_xnote_version():
return xconfi... |
from bottle import run, get, post, view, request, redirect, route, static_file, template
import bottle
import json
import threading
import requests
import time
import sys
messages = set([])
@bottle.route('/static/<path:path>')
def server_static(path):
return static_file(path, root='static')
@get('/chat')
@view('cha... |
'''
This is a simple example of how to use the dbm.gnu module of the
standard python library
NOTES:
- the attempt to insert None as value throws an exception.
so only strings and bytes are allowed.
'''
import dbm.gnu # for open
d = dbm.gnu.open('/tmp/foo.gdbm', 'c')
d['one'] = 'ehad'
d['two'] = 'shtaim'
d['three'] = ... |
import gc
import os
import argparse
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
from util import generate_features
def get_arguments():
parser = argparse.ArgumentParser(description='Generate features using a previously trained model')
parser.add_argument('data', type=str, help='File containing the input smiles mat... |
"""
Diabicus: A calculator that plays music, lights up, and displays facts.
Copyright (C) 2016 Michael Lipschultz
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
(a... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: aci_bd
short_description: Manage Bridge Domains (BD) on Cisco ... |
print("Hello") |
import sys
import time
from envirophat import light, weather, motion, analog
def write():
try:
p = round(weather.pressure(),2)
c = light.light()
print('{"light": '+str(c)+', "pressure": '+str(p)+' }')
except KeyboardInterrupt:
pass
write() |
class NodeSuperimposeTr(object):
def __call__(self, g, node_uid, aug):
conv = {}
for uid in aug:
if uid == aug.get_root():
g[node_uid] = aug[uid]
conv[uid] = node_uid
else:
conv[uid] = g.add_object(aug[uid])
for uid in a... |
"""
Pitch follower via DFT peak with Tkinter GUI
"""
import sys
from audiolazy import (tostream, AudioIO, freq2str, sHz, chunks,
lowpass, envelope, pi, thub, Stream, maverage)
from numpy.fft import rfft
def limiter(sig, threshold=.1, size=256, env=envelope.rms, cutoff=pi/2048):
sig = thub(sig, ... |
import os
import tempfile
import zipfile
from PyQt5 import QtCore, QtWidgets
import util
from vaults.modvault import utils
FormClass, BaseClass = util.THEME.loadUiType("vaults/modvault/upload.ui")
class UploadModWidget(FormClass, BaseClass):
def __init__(self, parent, modDir, modinfo, *args, **kwargs):
Base... |
from django.shortcuts import render_to_response, get_object_or_404
from django.views.decorators.cache import cache_page
from weblate.trans import appsettings
from django.core.servers.basehttp import FileWrapper
from django.utils.translation import ugettext as _
import django.utils.translation
from django.template impor... |
"""Dummy test.
Pointless dummy test.
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def inc(arg):
"""Return arg incremented by one."""
return arg + 1
def test_answer():
"""Assert 3+1 == 4."""
assert inc(3) == 4 |
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic import View
from .models import \
Course, Registration, Task, TaskSubmission, ScoreProfile
from .forms import TaskSubmissionForm
class CourseLi... |
import hashlib
import re
import os
import pickle
from functools import partial
from externals.lib.misc import file_scan, update_dict
import logging
log = logging.getLogger(__name__)
VERSION = "0.0"
DEFAULT_DESTINATION = './files/'
DEFAULT_CACHE_FILENAME = 'hash_cache.pickle'
DEFAULT_FILE_EXTS = {'mp4', 'avi', 'rm', 'mk... |
from controlscript import *
print "This is a simple control script. It just does nothing and exits successfully."
print "Start parameter is %s, additional parameters are %s" % (start, arguments)
class DoNothing(ControlAction):
""" Control script action for exiting with error 1 on stop """
def __init__(self):
Contro... |
import logging
from django.core.management.base import BaseCommand
from catalog.core.visualization.data_access import visualization_cache
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = '''Build pandas dataframe cache of primary data'''
def handle(self, *args, **options):
visuali... |
"""
Created on Fri Jul 3 13:38:36 2015
@author: madengr
"""
from gnuradio import gr
import osmosdr
from gnuradio import filter as grfilter # Don't redefine Python's filter()
from gnuradio import blocks
from gnuradio import fft
from gnuradio.fft import window
from gnuradio import analog
from gnuradio import audio
impor... |
"""Storage back-end for Mercurial.
This provides efficient delta storage with O(1) retrieve and append
and O(changes) merge between branches.
"""
from node import bin, hex, nullid, nullrev
from i18n import _
import ancestor, mdiff, parsers, error, util, dagutil
import struct, zlib, errno
_pack = struct.pack
_unpack = s... |
from PyQt5 import QtWidgets
from view.analysis_widget import AnalysisWidget
class TemporalAnalysisWidget(AnalysisWidget):
# noinspection PyArgumentList
def __init__(self, mplCanvas):
"""
Construct the Temporal Analysis page in the main window. |br|
A ``ScatterPlot.mplCanvas`` will be sho... |
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '',''))
import numpy as np
from sklearn import svm
from math import sqrt
import sys
from sklearn.metrics import roc_auc_score
if len(sys.argv)<4:
sys.exit("python cross_validation_from_matrix_norm.py inputMatrix.libsvm C outfile")
c=float(... |
import os
import tempfile
import urllib
from glob import glob
import shutil
import time
import gtk
import gobject
gobject.threads_init()
if __name__ == "__main__":
import sys
sys.path.insert(0, "..")
from chirpui import inputdialog, common
try:
import serial
except ImportError,e:
common.log_exception()
... |
__version__ = '0.1.3' |
import os
import sys
from ase import Atoms
from gpaw import GPAW
from gpaw import ConvergenceError
from gpaw.mpi import rank
from gpaw.eigensolvers.rmm_diis_old import RMM_DIIS
from gpaw import setup_paths
if len(sys.argv) == 1:
run = 'A'
else:
run = sys.argv[1]
assert run in ['A', 'B']
setup_paths.insert(0, '.... |
import configparser
import os
import traceback
__version__ = '18.10.16'
class CCParser(object):
def __init__(self, ini_path='', section='', debug=False):
"""
To init CCParser you can enter a path
and a section. If you doesn't know them yet
you can leave them empty.
... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('flocks', '0015_auto_20170624_1312'),
('feeding', '0005_auto_20170625_1129'),
]
operations = [
migrations.CreateM... |
from ptools import *
pdb1f88 = getPDB("1F88")
WritePDB(pdb1f88, "1F88.pdb") |
from node import models
from django.forms import ModelForm
from . import cdmsportalfunc as cpf
from django.core.exceptions import ValidationError
from django import forms
class MoleculeForm(ModelForm):
class Meta:
model = models.Molecules
fields = '__all__'
class SpecieForm(ModelForm):
datearchi... |
"""Clean db
Revision ID: 4f8bd7cac829
Revises: 3f249e0d2769
Create Date: 2014-01-09 14:03:13.997656
"""
revision = '4f8bd7cac829'
down_revision = '3f249e0d2769'
from alembic import op
import sqlalchemy as sa
def upgrade():
''' Drop the columns calendar_multiple_meetings and
calendar_regional_meetings and rename... |
"""
Takes Google's json encoded spreadsheet and prints a python dictionary keyed by
the values in the first column of the SS. ©2017 J. J. Crump, GNU general public
license
"""
import urllib2
from pprint import pprint
import re
import json
ssURL = "https://spreadsheets.google.com/feeds/list/1OPNQC3xBp3iQTpjVfd6cpvvA0BpH... |
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response, RequestContext, render
from membro_profile.forms import MembroForm, MembroProfileForm, EditProfileForm
from django.contrib.auth.decorators import login_... |
class ImproperlyConfigured(Exception):
pass
class TaskHandlingError(Exception):
pass |
from datetime import datetime, timedelta
import json
import csv
import pytz
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist
from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.template.response import TemplateResponse
from django.core.urlresolvers import reverse
from ... |
from datetime import datetime
import uuid
class Torrent(object):
def __init__(self):
self.tracker = None
self.url = None
self.title = None
self.magnet = None
self.seeders = None
self.leechers = None
self.size = None
self.date = None
self.detail... |
import math
import os
import re
import itertools
from types import LambdaType
import pkg_resources
import numpy
from PyQt4 import QtGui, QtCore, QtWebKit
from PyQt4.QtCore import Qt, pyqtSignal as Signal
from PyQt4.QtGui import QCursor, QApplication
import Orange.data
from Orange.widgets.utils import getdeepattr
from O... |
import sys, os
sys.path.insert(0, os.path.abspath('..'))
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.pngmath']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = 'CodeBug Tether'
copyright = '2015, OpenLX'
version... |
'''
Nibblegen: A script to convert LaTex text to html usable in Nibbleblog Forked from the latex2wp project (the licenceing for which is below).
Copyright (C) 2014 Theodore Jones
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as publish... |
import sys
WorkList = None
def SH(i):
"""reformatting .SH"""
global WorkList
string = WorkList[i]
l = len(string) - 2
r = 0
while string[0] == '=' and string[l] == '=':
WorkList[i] = string[1:l]
string = WorkList[i]
l = len(string) - 1
r = r + 1
if r == 2:
... |
try:
from process.sequence import Alignment
from base.plotter import bar_plot, multi_bar_plot
from process.error_handling import KillByUser
except ImportError:
from trifusion.process.sequence import Alignment
from trifusion.base.plotter import bar_plot, multi_bar_plot
from trifusion.process.erro... |
from logger import *
"""
log_functions = [('no_negative_ret', 'no_negatives_log')]
log_function_args = []
def query():
def sqrt_filter(x):
return x[0] < 0
get_log('no_negatives_log').filter(sqrt_filter).print_log()
"""
"""
log_functions = [('add', 'add_log')]
log_function_args = [('mult', 'mult_log')]
d... |
from marshmallow import EXCLUDE, Schema
from ..fields.objectid import ID
class BaseSchema(Schema):
id = ID(description='ID', dump_only=True)
class Meta:
strict = True
ordered = True
unknown = EXCLUDE |
"""
| *** ATTENTION: This is early work in progress. Interfaces are subject to change. ***
| *** DO NOT USE IN PRODUCTION until you know what you are doing ***
|
This library contains the future network classes for SmartHomeNG.
New network functions and utilities are going to be implemented in this library.
This clas... |
"""
Site
====
Site class. Create one for each independent site with its own configuration.
"""
import logging
from .request import normalize, make_request, And, Condition, Or, Not
from .query import QueryFilter, QuerySelect, QueryChain, QueryOrder, QueryRange,\
QueryDistinct, QueryAggregate
from .access_point impor... |
from logging import Logger
from requests.sessions import Session
def getpocket_download(session: Session, _logger: Logger):
"""
This does the heavy lifting
:param session:
:param _logger:
:return:
"""
headers = {
"Origin": "https://app.getpocket.com", # checked that this is needed
... |
from setuptools import setup, find_packages
try: # for pip >= 10
from pip._internal.req import parse_requirements
except ImportError: # for pip <= 9.0.3
from pip.req import parse_requirements
import re, ast
_version_re = re.compile(r'__version__\s+=\s+(.*)')
with open('bench/__init__.py', 'rb') as f:
versio... |
from os import path
from collections import defaultdict
import math
root = path.dirname(path.dirname(path.dirname(__file__)))
result_dir = path.join(root, 'results')
def get_file_name(test):
test = '%s_result' % test
return path.join(result_dir, test)
def mean(l):
return float(sum(l))/len(l) if len(l) > 0 e... |
from decimal import Decimal
import json
class InvalidDimension(ValueError):
"""Raised when a sheet specification has inconsistent dimensions. """
pass
class Specification(object):
"""Specification for a sheet of labels.
All dimensions are given in millimetres. If any of the margins are not
given, th... |
import os.path
import unittest
from unittest.mock import patch
import libpipe
from libpipe.cmds.align import HisatCmd
import logging
log = logging.getLogger(__name__)
class TestHistatCmd(unittest.TestCase):
def setUp(self):
# prevent error logs from occuring during testing
patcher = patch.object(lib... |
import os
import sys
import re
if len(sys.argv)<4:
print "Usage: make-sim-options.py <decay_file> <output_prefix> <event_number>"
exit(1)
HOME_DIR = os.environ['HOME']
JPSIKKROOT_DIR = os.environ['JPSIKKROOT']
SHARE_DIR = os.path.join(JPSIKKROOT_DIR, "share")
TEMPLATE_DIR = os.path.join(JPSIKKROOT_DIR, "share/t... |
'''Defines the Special class for theia.'''
import numpy as np
from ..helpers import geometry, settings
from ..helpers.units import deg, cm, pi
from .optic import Optic
class Special(Optic):
'''
Special class.
This class represents general optics, as their actions on R and T are left
to the user to input... |
import sys, shutil
try:
from gi.repository import Gtk, Gdk, Vte, GLib, Pango, GConf, GdkPixbuf
import json, os, getpass
from pycm.pycm_globals import *
except ImportError as e:
print "Error during importing of necessaries modules.\nError is '%s'" % e
sys.exit()
python_path = "/usr/lib/python2.7/dist... |
"""
Message Queue wrapper
"""
__RCSID__ = "$Id$"
from DIRAC.FrameworkSystem.private.standardLogging.Handler.MessageQueueHandler import MessageQueueHandler
from DIRAC.Resources.LogBackends.AbstractBackend import AbstractBackend
from DIRAC.FrameworkSystem.private.standardLogging.Formatter.JsonFormatter import JsonFormatt... |
import math
import random, datetime
from gettext import gettext as _
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('PangoCairo', '1.0')
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GObject
from gi.repository import Pango
from gi.repository import PangoCairo
impor... |
"""
Created on Thu Jan 31 2018
Unit tests for the Balance game
@author: IvanPopov
"""
import unittest
from game import Game
class GameTest(unittest.TestCase):
def test_game_loads(self):
g=Game()
self.assertEqual(g.c.title(), "Balance") |
import os, sys, re, argparse, time, json, logging
import requests
from glob import glob
from urlparse import urlsplit
from getpass import getpass
from mastodon import Mastodon
from markdown import markdown
from html_text import extract_text
from flask import (Flask, render_template, abort,
request, redirect, jsonif... |
import time
import os
import json
import requests |
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from app import db
import os.path
db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
api.create(SQLALCHEMY_MIGRATE_REPO, 'database_repository')
api.version_control(SQLALCHEMY_DAT... |
from troposphere import Tags,FindInMap, Ref, Template, Parameter,ImportValue, Ref, Output
from troposphere.efs import FileSystem, MountTarget
from troposphere.ec2 import SecurityGroup, SecurityGroupRule, Instance, Subnet
from create import export_ref, import_ref
from create.network import AclFactory, assoc_nacl_subnet
... |
import os
import os.path
import optparse, ConfigParser
import snap
from snap.options import *
from snap.snapshottarget import SnapshotTarget
from snap.exceptions import ArgError
class ConfigOptions:
"""Container holding all the configuration options available
to the Snap system"""
# modes of operation
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.