text stringlengths 12 6.59M |
|---|
# websocket_server -- WebSocket/HTTP server/client library
# https://github.com/CylonicRaider/websocket-server
"""
Support for "sessions" spanning multiple WebSocket connections.
In some (or many) cases, multiple WebSocket connections to the same URL are
(mostly) interchangeable. This module caters for that case by p... |
# websocket_server -- WebSocket/HTTP server/client library
# https://github.com/CylonicRaider/websocket-server
"""
Support for "sessions" spanning multiple WebSocket connections.
In some (or many) cases, multiple WebSocket connections to the same URL are
(mostly) interchangeable. This module caters for that case by p... |
#!/usr/bin/env python
from __future__ import division, print_function
import logging
FORMAT = '[%(asctime)s] %(name)-15s %(message)s'
DATEFMT = "%H:%M:%S"
logging.basicConfig(format=FORMAT, datefmt=DATEFMT, level=logging.INFO)
import ipdb
import theano
import theano.tensor as T
from argparse import ArgumentParser
... |
# devicefactory.py
# Creation of devices based on a top-down specification.
#
# Copyright (C) 2012, 2013 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your op... |
#!/usr/bin/python
import sys
import csv
import re
import yaml
import os.path
from pysvg.shape import *
from pysvg.structure import *
from pysvg.style import *
from pysvg.text import *
from pysvg.builders import StyleBuilder
# Default configuration
config = {
# Y value scaling. 1 is one vertical pixel per second.... |
#!/usr/bin/env python
import os #, signal
import sys
import traceback
import time
import thread
from os.path import *
from getopt import getopt
try:
from spade import spade_backend
# from spade import SpadeConfigParser
from spade import colors
#from xmppd.filters import acc
except ImportError, e:
print "Could no... |
# coding:utf-8
from nose.core import run
if __name__ == "__main__":
args = ['', '--cover-package=pagarme', '--with-coverage']
run(argv=args)
|
import os
import sys
import shutil
real_path = os.path.realpath(__file__)
real_path = real_path[:real_path.find('install.py')]
RESET_PATH = real_path
def check_os():
'''Check operating system'''
if sys.platform.lower() == 'darwin':
return 'macos'
elif sys.platform.lower() == 'win32':
retur... |
#!/usr/bin/python
import gettext
import logging
import unittest
import doctest
import sys
from optparse import OptionParser
from minimock import Mock
from pprint import pprint
from pysettings.modules import get_module
gettext.install('firmant')
def safe_displayhook(s):
if s is not None:
if isinstance(... |
#!/usr/bin/python
import re
import glob
import sys
import os
import argparse
import time
run_time = time.strftime("%Y-%m-%d_%H-%M-%S")
ces_dir = '/install/community-edition-setup'
parser = argparse.ArgumentParser(description="This script extracts community-edition-setup package and runs setup.py without arguments")
... |
#!/usr/bin/env python
from __future__ import print_function
import atexit
import base64
import os
import sys
import re
import gc
import heapq
import locale
import shutil
import time
import unittest
import doctest
import operator
import subprocess
import tempfile
import traceback
import warnings
import zlib
import glo... |
#!/usr/bin/env python
# dotfiles
# Kashev Dalmia | @kashev | kashev.dalmia@gmail.com
# README.md
import argparse
import getpass
import os
HOME_DIR = os.path.join("/home", getpass.getuser())
DOT_INSTALL_FOLDERS = ["git"]
def delete_and_link(source, dest, force=False):
"""Delete the destination file if it exists... |
#!/usr/bin/env python
from django.conf import settings, global_settings as default_settings
from django.core.management import call_command
from os.path import dirname, realpath
import django
import sys
import os
TESTABLE_APPS = ['bulbs.content', 'bulbs.images']
# Give feedback on used versions
sys.stderr.write('Usin... |
#!/usr/bin/env python2
import os
import shutil
import stat
import sys
try:
import config
except ImportError:
print 'Created personal config.py for your customizations'
shutil.copyfile('config.py.dist', 'config.py')
import config
TEMPLATE_FILE = 'shline.py.tpl'
OUTPUT_FILE = 'shline.py'
SEGMENTS_DIR =... |
#!/usr/bin/python
import os
import sys
import re
import gc
import codecs
import shutil
import unittest
import doctest
import operator
import tempfile
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
try:
import cPickle as pickle
except ImportError:
import pickle
WITH_CY... |
print("Taichi Installer v0.1")
import os
import pwd
import sys
import platform
import argparse
from os import environ
# Utils
def get_shell_name():
return environ['SHELL'].split('/')[-1]
def get_shell_rc_name():
shell = get_shell_name()
if shell == 'bash':
return '~/.bashrc'
elif shell == 'zsh':
ret... |
# -*- coding: utf-8 -*-
# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any ... |
from browbeat_run import browbeat_run
from dtree_classifier import classify_value
import numpy
import sqlite3
import cPickle
from sklearn.svm import SVC
from sklearn.svm import LinearSVC
from sklearn.svm import NuSVC
from sklearn.tree import DecisionTreeClassifier
import json
def longest_test_name(config):
val =... |
#!/usr/bin/python
import os
import sys
import re
import codecs
import shutil
import unittest
import doctest
import operator
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
try:
import cPickle as pickle
except ImportError:
import pickle
WITH_CYTHON = True
from distutil... |
#!/usr/bin/python3
import os
import sys
import subprocess
PARENT = os.path.abspath(os.path.dirname(__file__))
def install_file(name, dest_dir = os.path.expanduser('~'), dot = True):
if not os.path.isdir(dest_dir):
os.makedirs(dest_dir)
if dot:
dest = os.path.join(dest_dir, '.' + name)
else:
dest = ... |
import time
import logging
from bndl.util.lifecycle import Lifecycle
from bndl.execute.worker import current_worker
logger = logging.getLogger(__name__)
class ExecutionContext(Lifecycle):
def __init__(self, driver, conf=None):
super().__init__()
self._driver = driver
self._node = driver... |
#! /usr/bin/env python
sources = """
eNrsvWuTI0eSIDZ3km51kPYlnVaPu5WSKPVmJhuFrmpyHosjOOI0u3d7l482dvcsz4olMAtIVOUU
kInOTHRV7SzH9E/0J+4/yGSmb/eH5K94ZiSAapIzKzMV2VVAZjw8PDw83D083P+Pf/ndm58kr/9s
czeerarL8WxWlEU7m735F6//bjgcRvDssigvo09ePI+SeFNXi+08r5s4yspFFM+rstmu6Tt8LPN5
my+it0UWXed3N1W9aNIIGhkM3vzL13+EPTTt4s1/9ur//Bc/+Um... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys
import platform
import subprocess
from indexer import index_browser_history
def setup():
# Identify the type of operating system for install packages
OS = platform.dist()[0].lower()
if OS == "fedora" or OS == "redhat":
install = "sudo yu... |
import time
import logging
from bndl.util.lifecycle import Lifecycle
from bndl.execute.worker import current_worker
logger = logging.getLogger(__name__)
class ExecutionContext(Lifecycle):
def __init__(self, driver, conf=None):
super().__init__()
self._driver = driver
self._node = driver... |
#!/usr/bin/env python
import sys
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
INSTALLED_APPS=(
... |
#!/usr/bin/env python2.7
import errno
import re
import os
import optparse
import os.path
import platform
import sys
from itertools import product
from contextlib import contextmanager
from subprocess import Popen, PIPE
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
... |
#!/usr/bin/env python
import atexit
import os
import sys
import re
import gc
import locale
import shutil
import time
import unittest
import doctest
import operator
import subprocess
import tempfile
import traceback
import warnings
try:
import platform
IS_PYPY = platform.python_implementation() == 'PyPy'
I... |
#!/usr/bin/env python
import os, socket, sys
# Creates directories for temporary application files.
def make_cache_dirs():
cache_dir = os.path.expanduser("~/.cache")
app_names = ["gdb", "less", "stoken", "zsh"]
for app_name in app_names:
app_cache_dir = os.path.join(cache_dir, app_name)
os.makedirs(app... |
"""
Base implementation of the Page Object pattern.
See https://code.google.com/p/selenium/wiki/PageObjects
"""
from abc import ABCMeta, abstractmethod, abstractproperty
from collections import defaultdict, namedtuple
from functools import wraps
from contextlib import contextmanager
import json
import logging
import os... |
# Copyright (c) 2006-2007 Open Source Applications Foundation
#
# 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 require... |
# Copyright (c) 2006-2007 Open Source Applications Foundation
#
# 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 require... |
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
#
# Copyright 2011 Aaron Steele, John Wieczorek, Gaurav Vaidya
#
# 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.... |
#!/usr/bin/env python
#
# Copyright 2011 Aaron Steele, John Wieczorek, Gaurav Vaidya
#
# 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
#
# Unl... |
"""
mbed SDK
Copyright (c) 2011-2014 ARM Limited
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 agreed to in wr... |
#!/usr/bin/env python
import argparse
import glob
import keystoneclient.v2_0.client
import novaclient.client
import neutronclient.v2_0.client
import glanceclient
import requests
import re
import os
import sys
import urllib
import urlparse
import ConfigParser
__author__ = 'sshnaidm'
env_re = re.compile("export (OS_[A-... |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... |
# -*- coding: utf-8 -*-
import sys
import time
import json
import Queue
import subprocess
import util
class Message(object):
def __init__(self, name, channel=None, **kwargs):
self.name = name
self.channel = channel
self.args = util.AttrDict(kwargs)
def dumps(self):
return ... |
#!/usr/bin/python
import os
import smtplib
import urllib
class Ip_check:
def send_email(self, message):
# Credentials for the email
username = 'username'
password = 'password'
fromaddr = 'username@gmail.com'
toaddrs = 'dst_addr@gmail.com'
subject = 'New IP!'
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
import re
try:
from BeautifulSoup import BeautifulSoup
from PyQt4.QtCore import QObject, pyqtSlot
from PyQt4.QtGui import (QApplication, QDialog, QDialogButtonBox,
QHBoxLayout, QLabel, QLineEdit)
f... |
import re
class APIError(Exception):
"""
If description is passed, messages would be ignored
"""
def __init__(self, messages=None, description=None, code=None, status_code=None):
self.messages = messages
self.description = str(description)
self.code = code
self.status_c... |
__author__ = 'Victor Cabezas'
import argparse
from __future__ import print_function
from past.builtins import basestring
from .Solver import Solver
from .Solver import Beginner
from .Solver import CFOP
from .Solver import Kociemba
from .NaiveCube import NaiveCube
from .Cubie import Cube
from .Printer import TtyPrinter
... |
import struct
import socket
import logging
import zlib
try:
from cPickle import loads, dumps
except ImportError:
from Pickle import loads, dumps
__all__ = ['Client']
logger = logging.getLogger('bmemcached')
class Client(object):
def __init__(self, servers, username=None, password=None):
self.use... |
# -*- coding: utf-8 -*-
"""
Simple IRC bot library.
This module contains a single-server IRC bot class that can be used to
write simpler bots.
"""
from __future__ import absolute_import
import sys
import irc.client
import irc.modes
from .dict import IRCDict
class ServerSpec(object):
"""
An IRC server spec... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def _previsit(v, previsit_d, clock):
clock[0] += 1
previsit_d[v] = clock[0]
def _postvisit(v, postvisit_d, clock):
clock[0] += 1
postvisit_d[v] = clock[0]
def _dfs_recur_visit(v, graph_adj_... |
# Copyright 2022 Google LLC.
#
# 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 agreed to in writing, s... |
#!/usr/local/bin/python
import pygtk
pygtk.require('2.0')
import gtk
class window:
def delete_event(self,widget,event,data=None):
"Quit window"
dialog = gtk.MessageDialog(self.window,gtk.DIALOG_MODAL |gtk.DIALOG_DESTROY_WITH_PARENT,gtk.MESSAGE_WARNING,gtk.BUTTONS_YES_NO,"Save before quit ?")
dialog.set_title("... |
#!/usr/bin/env python
__author__ = "Eric Allen Youngson"
__email__ = "eric@successionecological.com"
__copyright__ = "Copyright 2015, Succession Ecological Services"
__license__ = "GNU Affero (GPLv3)"
""" This module provides functions for requesting results from the DeltaMeter
Services API * deltameterservic... |
#!/usr/bin/env python
__author__ = "Eric Allen Youngson"
__email__ = "eric@scneco.com"
__copyright__ = "Copyright 2015, Succession Ecological Services"
__license__ = "GNU Affero (GPLv3)"
""" This module provides functions for requesting results from the DeltaMeter
Services API * deltameterservices.com * """
... |
import webapp2
import webapp2_extras.routes
from .centralclient import CentralClient
from .download import Download
from .handlers.collectionshandler import CollectionsHandler
from .handlers.confighandler import Config, Version
from .handlers.containerhandler import ContainerHan... |
#!/usr/bin/python
import os
import json
import boto3
import botocore
from chalice import Chalice
from chalice import BadRequestError
from chalice import UnauthorizedError
from chalicelib import credential
#key compromise plugins
from chalicelib.aws_ir.aws_ir.plugins import revokests_key
from chalicelib.aws_ir.aws_ir.... |
from flask import Flask
from twilio_client import client
# config test app
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////Users/thomas/PersonalProjects/soda-twilio-service/test.db'
db = SQLAlchemy(app)
@app.route('/',methods=['GET','POST'])
def index():
message = client.messages.creat... |
# ApplePy - an Apple ][ emulator in Python
# James Tauber / http://jtauber.com/
# originally written 2001, updated 2011
import curses
def signed(x):
if x > 0x7F:
x = x - 0x100
return x
class Memory:
def __init__(self, size):
self.__mem = [0x00] * size
def load(self, filename, o... |
# ApplePy - an Apple ][ emulator in Python
# James Tauber / http://jtauber.com/
# originally written 2001, updated 2011
import pygame
import colorsys
def signed(x):
if x > 0x7F:
x = x - 0x100
return x
class Display:
characters = [
[0b00000, 0b01110, 0b10001, 0b10101, 0b10111, 0b101... |
"""
Description : Simple Python implementation of the Apriori Algorithm
Usage:
$python apriori.py -f DATASET.csv -s minSupport -c minConfidence
$python apriori.py -f DATASET.csv -s 0.15 -c 0.6
"""
import sys
from itertools import chain, combinations
from collections import defaultdict
from optparse imp... |
import sys
import os.path
import csv
import math
import types
from collections import defaultdict, Iterable
import itertools
class Apriori:
def __init__(self, data, minSup, minConf):
self.dataset = data
self.transList = defaultdict(list)
self.freqList = defaultdict(int)
self.itemse... |
#!/usr/bin/env python3
try:
from systemd import journal
systemd = True
except:
systemd = False
from urllib.request import urlopen
from geojson import Feature, Point, FeatureCollection, dumps
try:
from geojsonio import to_geojsonio
except:
print("""==> Warning: You need to 'pip install github3.py' a... |
import numpy as np
import numpy.ma as ma
from numpy import linalg as LA
import itertools
import collections
from scipy import stats
def tsToAutoregressiveForm(Y, p):
'''
Y is a matrix of observations, where columns are the variables and rows
are time points
p is the max order
Returns: Yf, the obse... |
import math
import random
from functools import wraps
# Note: unable to import Gallery from model specifically because model imports arrange too
import model
DEFAULT_MARGIN = 2
# Decorator for instance methods of workspace
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
def adjust_for_wa... |
import discord
from discord.ext import commands
import json
bot = commands.Bot(command_prefix=commands.when_mentioned_or('?'), description="Artemis: Rhiba's life organiser.")
with open('creds.json') as data:
creds = json.load(data)
token = creds["token"]
@bot.event
async def on_ready():
print('Logged in as:')
... |
# -*- coding: utf-8 -*-
import base64
import hmac
from hashlib import sha1 as sha
py3k = False
try:
from urlparse import urlparse
except:
py3k = True
from urllib.parse import urlparse
from email.utils import formatdate
from requests.auth import AuthBase
class S3Auth(AuthBase):
"""Attaches AWS Authe... |
import json
import textwrap
import six
from jirafs import constants, utils
from jirafs.plugin import CommandPlugin
class Command(CommandPlugin):
""" Fetch remote changes """
TRY_SUBFOLDERS = True
MIN_VERSION = '1.0a1'
MAX_VERSION = '1.99.99'
def handle(self, folder, **kwargs):
return se... |
import os
import os.path
import fnmatch
import logging
import ycm_core
BASE_FLAGS = [
'-Wall',
'-Wextra',
'-Werror',
'-Wc++98-compat',
'-Wno-long-long',
'-Wno-variadic-macros',
'-fexceptions',
'-ferror-limit=10000',
'-DNDEBUG',
'-std=c++98',
'-xc++',
'-I/usr/lib/'
'-... |
import os
def page():
page_id = request.args[0]
check_page_id(page_id)
page = get_page(page_id)
boxes_on_pages = page.boxes.select()
extra_box_info = {}
child_boxes = []
for box in boxes_on_pages:
extra_box_info[box.id] = box_content_info(box)
if box.content_type == 'box':
child_boxes.append(box.content_... |
import os
import time
import json
import requests
from oti_search import OTISearch
from ConfigParser import SafeConfigParser
import urllib2
import sys
import traceback
import api_utils
@request.restful()
def v1():
"The OpenTree API v1"
response.view = 'generic.json'
oti_base_url = api_utils.get_oti_base_u... |
from __future__ import absolute_import
from __future__ import division
import base64
import collections
import datetime
import hashlib
import logging
import json
import re
import time
import pytz
import requests
import slumber.exceptions
import xmlrpc2.client
from conveyor.utils import DictDiffer
_normalize_regex ... |
"""
Django settings for coop project.
Generated by 'django-admin startproject' using Django 1.10.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
#... |
###############################################################################
#
# ChartScatter - A class for writing the Excel XLSX Scatter charts.
#
# Copyright 2013-2015, John McNamara, jmcnamara@cpan.org
#
from . import chart
class ChartScatter(chart.Chart):
"""
A class for writing the Excel XLSX Scatte... |
from django.conf.urls import *
from django.conf import settings
from django.contrib.auth.decorators import login_required, permission_required
import signbank.registration.forms
from django.conf.urls.static import static
from django.views.generic import TemplateView
#These are needed for the urls below
import signbank... |
# Copyright (c) 2015 Presslabs SRL
#
# 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 agreed to in writ... |
#!/usr/bin/python
import os
if __name__ == '__main__':
print ('Reseting Swift......')
os.system('resetswift')
print ('Done')
#start proxy-server
print ('Starting Proxy Server......')
os.system('/home/mjwtom/PycharmProjects/swift/bin/swift-proxy-server /etc/swift/proxy-server.conf &')
print ... |
"""
Helper functions to run with OpenMM, these function could be methods of the
MDSimulation class however because of limitations imposed by the
multiprocessing they need to be functions
"""
from __future__ import absolute_import, division, print_function
import os
import sys
import time
import functools
import traceb... |
from __future__ import print_function, division
import numpy as np
from numpy import dot
from sisl.messages import warn
from sisl.utils.ranges import array_arange
import sisl._array as _a
import sisl.linalg as lin
__all__ = ['SelfEnergy', 'SemiInfinite']
__all__ += ['RecursiveSI']
class SelfEnergy(object):
""... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# region Description
"""
network_conflict_creator.py: Network conflict creator script
Author: Vladimir Ivanov
License: MIT
Copyright 2019, Raw-packet Project
"""
# endregion
# region Import
# region Add path with Raw-packet modules
from sys import path
from os.path impor... |
from __future__ import unicode_literals
import json
import os
import shutil
import sys
import tempfile
import traceback
import zipfile
from glob import iglob
from io import BytesIO
from cumulusci.core.config import FAILED_TO_CREATE_SCRATCH_ORG, FlowConfig
from cumulusci.core.exceptions import (
ApexTestException,... |
#! /usr/bin/python -u
# Note -u forces stdout to be unbuffered.
import argparse
import subprocess
import traceback
import sys
import time
from operator import itemgetter
from biokbase.workspace.client import Workspace
from biokbase.workspaceService.Client import workspaceService as oldWorkspace
from biokbase.fbaModel... |
from datetime import date, timedelta
from collections import namedtuple
class Week(namedtuple('Week', ('year', 'week'))):
"""A Week represents a period of 7 days starting with a Monday.
"""
__slots__ = ()
def __new__(cls, year, week):
if week < 1 or week > 52:
return cls(year, 1) +... |
#######################################################################
#
# Dumper Implementations
#
#######################################################################
from __future__ import with_statement
def mapForms():
return "Normal,Compact"
def mapCompact(format, keyType, valueType):
if format ==... |
# Django settings for miilibrary project.
from .utils import relative
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'ora... |
"""Copyright (c) 2010-2012 David Rio Vierra
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WA... |
# Monica Powell
# May, 25th, 2016
# Homework 2
# 1) Make a list of the following numbers: 22, 90, 0, -10, 3, 22, and 48
numbers = [22, 90, 0, -10, 3, 22, 48 ]
# 1) Display the number of elements in the list
print("number of elements on list", len(numbers))
# 2) Display the 4th element of this list.
print("fourth ele... |
import os
import time
import sys
import math
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from vmmaster.core.utils.init import home_dir
from vmmaster.core.config import setup_config, config
setup_config('%s/config.py' % home_dir())
from vmmaster.core.db import Session, VmmasterLogStep,... |
# -*- coding: UTF-8 -*-
"""
Usage:
leadbutt [options]
Options:
-h --help Show this screen.
-c FILE --config-file=FILE Path to a YAML configuration file [default: config.yaml].
-p INT --period INT Period length, in minutes (default: 1)
-n INT Number of data poin... |
from glob import iglob
import ROOT
import rootpy
from rootpy.tree import Cut
from root_numpy import tree2rec
def expander(
dtype='cf',
tree='rrqDir/calibzip1',
base='/tera2/data3/cdmsbatsProd/R133/dataReleases/Prodv5-3_June2013/merged/',
data='all',
productions=['all'],
... |
from bocca_objects import *
from subprocess import Popen, PIPE
class Error (Exception):
pass
class RunError (Error):
def __init__ (self, status, stderr):
self.status = status
self.stderr = stderr
class ProjectExistsError (RunError):
def __init__ (self, status, stderr):
self.status = status
self... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
import re
import frappe
from frappe import _, scrub
from frappe.rate_limiter import rate_limit
from frappe.utils.html_utils import clean_html
from frappe.website.doctype.blog_settings.blog_settings import get_comment_limit... |
# -*- coding: utf-8 -*-
u"""
.. _qook:
xrtQook -- a GUI for creating a beamline
----------------------------------------
The main interface to xrt is through a python script. Many examples of such
scripts can be found in the supplied folder ‘examples’. The script imports the
modules of xrt, instantiates beamline par... |
"""
Methods to characterize image textures.
"""
import math
import numpy as np
from scipy import ndimage
from ._greycomatrix import _glcm_loop
def greycomatrix(image, distances, angles, levels=256, symmetric=False,
normed=False):
"""Calculate the grey-level co-occurrence matrix.
A grey lev... |
from __future__ import unicode_literals
from django.conf.urls import patterns, url
from mezzanine.conf import settings
urlpatterns = []
if "django.contrib.admin" in settings.INSTALLED_APPS:
from django import VERSION
if VERSION < (1, 6):
reset_pattern = "^reset/(?P<uidb36>[-\w]+)/(?P<token>[-\w]+)/... |
# coding=utf-8
from common.exception import ConfigNotExist
from flask import current_app
import redis
__author__ = 'GaoJie'
redis_map = {}
def get(name='default'):
connect_name = '%s_%s' % (current_app.import_name, name)
if connect_name in redis_map:
return redis_map[connect_name]
config_map = c... |
#
# Copyright (c) 2010 rPath, Inc.
#
# This program is distributed under the terms of the Common Public License,
# version 1.0. A copy of this license should have been distributed with this
# source file in a file called LICENSE. If it is not present, the license
# is always available at http://www.rpath.com/permanent/... |
#!/usr/bin/env python
import sys
from hbasetable import HBaseTable
class UidTable(HBaseTable):
def table(self):
return "uid"
def create(self):
return """
{NAME => 'name', VERSIONS => 1,COMPRESSION => 'NONE'},
{NAME => 'id', VERSIONS => 1,COMPRESSION => 'NONE'}
"""
def validate(self, schema):
ret... |
import theano.tensor as T
def gaussianKL(dumb, y_pred):
dim = y_pred.shape[-1] / 2
mean = y_pred[:, :dim]
logsigma = y_pred[:, dim:]
kl = -.5 - logsigma + .5 * (mean**2 + T.exp(2 * logsigma))
return kl + 0 * dumb.sum()
|
# Author: Ian Burke
# Module: Emerging Technologies
# Date: September, 2017
# Problem Sheet: https://emerging-technologies.github.io/problems/python-fundamentals.html
import math
def factorial(n):
fact = math.factorial(n) # importing a function that calculates the factorial of n
print("Factorial of ", n... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
u"""
===============================
Shimehari.core.manager
~~~~~~~~~~~~~~~~~~~~~~
マネージメント
===============================
"""
import os
import sys
from optparse import OptionParser
from .AbstractCommand import AbstractCommand, CreatableCommand
from shimehari... |
# Copyright (C) 2011 Nippon Telegraph and Telephone Corporation.
#
# 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 appli... |
# backend.py
# openeventdatabase
from datetime import datetime
import json
import os
import falcon
import psycopg2
import psycopg2.extras
def db_connect():
return psycopg2.connect(
dbname=os.getenv("DB_NAME", "oedb"),
host=os.getenv("DB_HOST", None),
password=os.getenv("POSTGRES_PASSWORD... |
#!/usr/bin/env python
import os
import re
import glob
from copy import copy
import multiprocessing
import numpy as np
from numpy.core.defchararray import add as char_add
import fitsio
from astropy.table import Table
from bokpipe import bokpl,bokobsdb
from bokpipe import __version__ as pipeVersion
def set_rm_defaults... |
#!/usr/bin/env python
"""@package letsacme
################ letsacme ###################
This script automates the process of getting a signed TLS/SSL certificate
from Let's Encrypt using the ACME protocol. It will need to be run on your
server and have access to your private account key.
It gets both the certificate a... |
import os
from glob import glob
import re
import logging
import shutil
import time
import pyfits
import numpy as np
import numpy.ma as ma
import argparse
import collections
import Ska.DBI
import Ska.arc5gl
from Chandra.Time import DateTime
import Ska.File
logger = logging.getLogger('aca0 fetch')
logger.setLevel(logg... |
import logging
import sys
def get_dev_logger(name='dev.radosgw_agent'):
"""
A simple utility to be able to log things that are meant for developer-eyes
and not for user facing.
All developer logs must be prepended with `dev` so this utility ensures
that is the case. To use it::
dev_log =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.