code stringlengths 1 199k |
|---|
from FaustBot.Communication.Connection import Connection
from FaustBot.Model.UserProvider import UserProvider
from FaustBot.Modules.JoinObserverPrototype import JoinObserverPrototype
from FaustBot.Modules.ModuleType import ModuleType
from ..Modules.NickChangeObserverPrototype import NickChangeObserverPrototype
from ..M... |
from heapq import heappush, heappop
def heap_sort(heap_iterable):
'''
Heap sort implementation
'''
heap = []
for val in heap_iterable:
heappush(heap, val)
return [heappop(heap) for _ in range(len(heap))]
if __name__ == '__main__':
test_cases = (
[1, 3, 5, 7, 9, 2, 4, 6, 8, 0]... |
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
import argparse
import os
import re
from osgeo import gdal
from osgeo import ogr
from scipy import ndimage
import numpy as np
from threedilib.modeling import progress
from... |
print("empecemos el curso")
"""
Este es un comentario multilinea
creo que entre python y haskell debo empezar a programar seguido
haskell para acostumbrarme a la programación funcional
y python para la inteligencia artificial.
Nota: c++ será el lenguaje de facto para los problemas de programación
"""
esta_es_una_variab... |
import pango
import shutil
import matplotlib.artist as Artist
from matplotlib.lines import Line2D
from matplotlib.figure import Figure
from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg as FigureCanvas
import scipy.optimize as optimize
from PIL import Image
from anmr_common import *
if EXPERTMODE:
hi... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('aklub', '0008_auto_20150902_1242'),
('aklub', '0011_auto_20150803_1731'),
]
operations = [
] |
import logging
from bottle import request
from bottle_utils.i18n import lazy_gettext as _
from .forms import ONDDForm
def read_ondd_setup():
initial_data = request.app.supervisor.exts.setup.get('ondd')
return {} if isinstance(initial_data, bool) else initial_data
def has_invalid_config():
ondd_client = requ... |
from distutils.core import setup
setup(
name="utt_foo", version="1.0", packages=["utt.plugins"],
) |
'''
Author: xswxm
Blog: xswxm.com
This script includes a class, which is responsible for scanning, sniffing, and attacking devices.
It is a key component of the whole scripts.
'''
import sys
sys.path.append("..")
import time, threading
from lib import common
from utils.messager import Messager
from utils import config
... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('curriculum', '0008_auto_20181119_1429'),
]
operations = [
migrations.RemoveField(
model_name='titlelevel',
... |
"""increase test result app_version
Revision ID: e0a6e52a26e4
Revises: bdf99a876c5d
Create Date: 2017-08-10 17:37:46.896672
"""
from alembic import op
import sqlalchemy as sa
revision = 'e0a6e52a26e4'
down_revision = 'bdf99a876c5d'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated ... |
from nose.tools import *
from pillowncase import pncase
import os
import shutil
from datetime import datetime
import random
import hashlib
from tests import helper
from tests import channel_tests
import sys
def setup():
print ("SETUP!")
helper.setup_environment()
def teardown():
print ("TEAR DOWN!")
def tes... |
from django.apps import AppConfig
from actstream import registry
class PhillyorganizeAppConfig(AppConfig):
name = 'phillyorganize'
def ready(self):
super(PhillyorganizeAppConfig, self).ready()
registry.register(self.get_model('Organizer')) |
'''
/**************************************************************************************************************************
SemiAutomaticClassificationPlugin
The Semi-Automatic Classification Plugin for QGIS allows for the supervised classification of remote sensing images,
providing tools for the download, the ... |
import csv, glob, random
from os import path, mkdir
from sys import argv
UPLOAD_DIR = '/home/hduser/workspace/phr_client/enc_files'
WORKLOAD_UNI = 'uniform.csv'
WORKLOAD_DIS = 'dis.csv'
WRITE_POS = 0.5 # write possibility
NUMBER_OPS = 10000
range_userid={'start':1,'end':5000}
range_sysid={'start':0,'end':9}
if len(ar... |
import argparse
import fnmatch
import logging
import os
import re
import sys
from recursemp3_logging import LoggerConfig
from tqdm import tqdm
from mutagen.id3 import ID3, Encoding, ID3NoHeaderError, TPE1, TALB, TCON, TCOM, TPE2, TSOA, TRCK, TPOS, TIT2, TSOT, \
TFLT, TDRL
from CoverFetcher import CoverFetcher
class... |
import matplotlib as mpl
mpl.use('pgf')
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from uncertainties import ufloat
import uncertainties.unumpy as unp
mpl.rcParams.update({
'font.family': 'serif',
'text.usetex': True,
'pgf.rcfonts': False,
'pgf.texsystem': 'l... |
import getopt
import socket
import datetime
import tempfile
from wlstModule import * #@UnusedWildImport
from java.util import LinkedHashSet
def main(options, arguments):
base_dir = os.path.dirname(sys.argv[0])
if base_dir in [".", ""]: base_dir = os.getcwd()
if os.path.isfile(os.path.join(base_dir, "meta... |
from shop.cart import Cart
from drawn import Drawn
from random import choice
Drawn('http://www.wp.pl')
c = Cart()
c.add(Drawn('http://www.amazon.co.uk/Doctor-Who-50th-Anniversary-Special/dp/B00F37VHX4/ref=pd_cp_d_h__0'))
c.add(Drawn('http://www.amazon.co.uk/Star-Wars-Original-Trilogy-Episodes/dp/B00E0NHP6K/ref=br_lf_m_... |
"""Sample that streams audio to the Google Cloud Speech API via GRPC."""
from __future__ import division
import contextlib
import re
import signal
import threading
from google.cloud.speech.v1beta1 import cloud_speech_pb2 as cloud_speech
from google.cloud import credentials
from google.rpc import code_pb2
from grpc.beta... |
"""Module which provides compatibility with older Python versions."""
__all__ = ["namedtuple", "property"]
from operator import itemgetter as _itemgetter
from keyword import iskeyword as _iskeyword
import sys as _sys
try:
from collections import namedtuple
except ImportError:
def namedtuple(typename, field_name... |
"""
oflogviewer.app
~~~~~~~~~~~~~~~
Webアプリケーションのローダ
:copyright: Copyright (c) 2015, National Institute of Information and Communications Technology.All rights reserved.
:license: GPL3, see LICENSE for more details.
"""
import os
import simplejson as json
import logging
from logging.handlers import RotatingFileHandler
f... |
import traceback
import sys
import os
MESSENGERS_LIST = list()
_indent = ''
def register_messenger(messenger):
"""
Append the given messenger to the list of messengers.
Args:
messenger: a method that takes a string
"""
MESSENGERS_LIST.append(messenger)
def set_indent(level=0):
global _in... |
import orjson
import os
from wsgiref.handlers import CGIHandler
from philologic.runtime.DB import DB
from philologic.runtime import kwic_hit_object, page_interval
import sys
sys.path.append("..")
import custom_functions
try:
from custom_functions import WebConfig
except ImportError:
from philologic.runtime impo... |
from colorama import Fore
from modules.const import OK, INFO, NO
from modules.util import *
FULL_LIST = list ()
def check_once (target, verbose=False):
print INFO + 'Checking ' + target + '...'
th = check (target, verbose)
if len (th) > 0:
print OK + 'Bad items were found at url ' + Fore.CYAN + target + Fore.RESET... |
from django.utils import timezone
from django.db import models
import datetime
class Lights(models.Model):
light_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.light_text
def was_published_recently(self):
return se... |
"""Print information about the arguments to a method.
"""
__version__ = "$Id$"
import inspect
import example
arg_spec = inspect.getargspec(example.module_level_function)
print 'NAMES :', arg_spec[0]
print '* :', arg_spec[1]
print '** :', arg_spec[2]
print 'defaults:', arg_spec[3]
args_with_defaults = arg_s... |
from re import search,I
def baidu(headers,content):
_ = False
for header in headers.items():
_ |= search(r'fh1|yunjiasu-nginx',header[1],I) is not None
if _ : break
if _ :
return "Yunjiasu Web Application Firewall (Baidu)" |
import ctypes
import os
from ctypes import POINTER, c_int, c_uint, c_double, c_void_p
AT_H = ctypes.c_int
AT_BOOL = ctypes.c_int
AT_64 = ctypes.c_int64
AT_U8 = ctypes.c_uint8
AT_WC = ctypes.c_wchar
_stdcall_libraries = {}
if os.name in ('nt', 'ce'):
_stdcall_libraries['ATCORE'] = ctypes.WinDLL('atcore')
_stdcal... |
from enum import auto
from enum import StrEnum
import json
class Type(StrEnum):
GRASS = auto()
WATER = auto()
FIRE = auto()
ELECTRIC = auto()
ICE = auto()
FIGHTING = auto()
GROUND = auto()
POISON = auto()
FLYING = auto()
PSYCHIC = auto()
BUG = auto()
ROCK = auto()
GHO... |
import json
import socket
import numpy as np
import pytest
from pysisyphus.calculators.XTB import XTB
@pytest.mark.skip
def test_socketcalc():
host = "localhost"
port = 8080
calc = XTB(pal=2)
funcs = {
"energy": calc.get_energy,
"forces": calc.get_forces,
"hessian": calc.get_hess... |
import time
import iris
import cf_units
import numpy
grid_file='/group_workspaces/jasmin2/ukca/vol1/mkoehler/um/archer/ag542/apm.pp/ag542a.pm1988dec'
emissions_file='/group_workspaces/jasmin2/ukca/vol1/mkoehler/emissions/OXBUDS/0.5x0.5/cmip6_hybrid/v2/CMIP6_hybrid_combined_n-pentane_1960-2020_v2_greg.nc'
species_name='... |
import unittest
from unittest.mock import patch
from tmc import points
from tmc.utils import load, get_out
module_name="src.find_matching"
find_matching = load(module_name, "find_matching")
@points('p01-14.1')
class FindMatching(unittest.TestCase):
def test_first(self):
result = find_matching(["sensitive", ... |
"""@package internal exceptions
Exceções de validações internas.
Este modulo contem classes de controle de exceção
para validações internas
"""
from exceptions import Exception
class ResultadoConsultaNuloError(Exception):
"""docstring for ResultadoConsultaNuloError"""
def __init__(self, message):
""" Initialize mod... |
import os
import imp
import inspect
from functions import ButiaFunctions
import random
ERROR = -1
class Chotox(ButiaFunctions):
def __init__(self, debug=False, get_modules=True, chotox=False):
self._debug_flag = debug
self._hotplug = []
self._openables = []
self._drivers_loaded = {}
... |
"""
Utilities for managing DIRAC configuration:
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
__RCSID__ = "$Id$"
import socket
import six
from DIRAC import gConfig, gLogger, S_OK, S_ERROR
from DIRAC.ConfigurationSystem.Client.Helpers.Path import cfgPa... |
import argparse
import sys
from PyDvi.Font.FontMap import *
from PyDvi.Kpathsea import kpsewhich
parser = argparse.ArgumentParser(description='Test Font Map.')
parser.add_argument('font_map', metavar='FontMap',
help='TeX font map, e.g. pdftex')
args = parser.parse_args()
font_map_file = kpsewhich(ar... |
from django.contrib.sites.models import Site
from django.core import mail
from tao.models import TaoUser
from tao.tests.integration_tests import helper
from tao.tests.support.factories import UserFactory
import os
class AAFTests(helper.LiveServerTest):
def setUp(self):
os.environ['SHIB_auEdupersonSharedToke... |
default_libver = 37
import regex
lvoregx=regex.compile("\([a-zA-Z0-9_]+\)(\([a-zA-Z0-9_,]*\))(\([aAdD0-9,/]*\))")
def fdfile(lib): return "FD:"+lib+"_lib.fd"
def libname(lib): return lib+".library"
def capitalize(str): return chr(ord(str[0])&~32)+str[1:]
def convreg(str):
if str[0]=='d' or str[0]=='D':
return... |
import Queue
import time
import logging
from API import *
class SensorClient:
'''An easy to use sensor client for OpenTSDB'''
def pushToBuffer(self, timestamp, value, tags):
if timestamp == None: timestamp = self.nowMS()
self.__queue.put(PutData(timestamp, value, tags))
self.__queue.task... |
from setuptools import setup, find_packages
from sys import version_info
from gitclonesync import VERSION
if version_info[0] > 2:
print("ERROR: This project requires GitPython, which does not currently support Python3")
raise SystemExit(1)
if version_info[0] == 2 and version_info[1] < 7:
print("ERROR: This ... |
import json
import os
import time
import psutil
from twisted.internet import defer, reactor, threads, task
import txzmq
import zmq
try:
from zmq.auth.thread import ThreadAuthenticator
except ImportError:
pass
from leap.bitmask.backend.api import API, PING_REQUEST
from leap.bitmask.backend.utils import get_backe... |
from translate.storage import poheader
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Max
from django.utils import timezone
from pootle.core.utils import dateformat
from pootle.core.utils.timezone import datetime_min
from pootle.core.utils.version import get_major_minor_version
from ... |
import urlparse
import json
import Cookie
import squeakspace.common.squeak_ex as ex
def json_fun(object):
#return json.dumps(object)
return json.dumps(object, indent=4) + '\n'
def respond(environ, start_response, status, content, response_headers=None):
if response_headers == None:
response_headers ... |
from .moveto import MoveTo
from .lineto import LineTo
from .cubicto import CubicTo
from .close import Close
PATH_COMPONENTS = {
'MoveTo': MoveTo,
'LineTo': LineTo,
'CubicTo': CubicTo,
'Close': Close
} |
from .functions import _tomlquote
from .model import Entry, Function
from .repl import Repl
from .scope import Resource, Scope
from .util import ispy2, NoSuchPathException
from tempfile import NamedTemporaryFile
from unittest import TestCase
import os, sys
class TestFunctions(TestCase):
def test_slash(self):
... |
"""
This module contains implementations of :class:`turses.api.base.ApiAdapter`
using libraries for accessing the Twitter API.
"""
from functools import wraps, partial
from tweepy import API as BaseTweepyApi
from tweepy import OAuthHandler as TweepyOAuthHandler
from turses.config import configuration
from turses.meta i... |
from nbodykit.lab import FFTPower, BigFileCatalog, BigFileMesh
from nbodykit import setup_logging
import numpy
import argparse
import warnings
from mpi4py import MPI
import os
ap = argparse.ArgumentParser()
ap.add_argument("output", help='e.g. power.json (FFTPower.load) or power.txt (numpy.loadtxt)')
ap.add_argument("-... |
"""
Helper functions to build CLI applications
@author: Aurélien Gâteau <aurelien.gateau@free.fr>
@license: GPL v3 or later
"""
import os
import readline
import subprocess
import sys
import tempfile
import time
import locale
import unicodedata
import re
from getpass import getpass
from yokadi.ycli import colors as C
EN... |
from django.core.cache import cache
from django.conf import settings
from tendenci.apps.navs.cache import NAV_PRE_KEY
def update_nav_links(sender, instance, **kwargs):
keys = [settings.CACHE_PRE_KEY, NAV_PRE_KEY, str(instance.id)]
key = '.'.join(keys)
cache.delete(key) |
from encoders.xor import generate as xor |
'''
Reddit Anime Link Bot
Copyright (C) 2014 John Malsky
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.
This program is distri... |
"""
This is an object-oriented plotting library.
A procedural interface is provided by the companion pyplot module,
which may be imported directly, e.g.::
from matplotlib.pyplot import *
To include numpy functions too, use::
from pylab import *
or using ipython::
ipython -pylab
For the most part, direct use... |
import gtk, gobject, os
from ventana import Ventana
from framework import pclases
import utils
class Adjuntos(Ventana):
VENTANA = os.path.join(os.path.dirname(__file__),
"glades", "adjuntos.glade")
def __init__(self, resultado, usuario = None, run = True):
self.resultado = res... |
from flask import render_template, abort, flash, redirect, url_for
from flask.ext.login import login_required, current_user
from .import main
from ..models import User, Role, Permission, Post
from .. import db
from .forms import EditProfileForm, EditProfileAdminForm, PostForm
from ..decorators import admin_required
@ma... |
"""Extract sequences from a fasta file and group them in output files.
Groups of 'number' sequences are formed.
Output file names will begin by 'stub'.
Usage:
%program <input_file> <number> <stub>"""
import sys
import re
try:
from Bio import SeqIO
except:
print("This program requires the Biopython library")... |
from __future__ import absolute_import
from ..backend import KeyringBackend
from ..errors import PasswordDeleteError
from ..errors import PasswordSetError
from ..util import properties
try:
import dbus
except ImportError:
pass
class DBusKeyring(KeyringBackend):
"""KDE KWallet via D-Bus"""
appid = 'Pytho... |
import tensorflow as tf
WEIGHTS_INIT_STDEV = .1
def net(image):
image = image / 255.0
conv1 = _conv_layer(image, 32, 9, 1)
conv2 = _conv_layer(conv1, 64, 3, 2)
conv3 = _conv_layer(conv2, 128, 3, 2)
resid1 = _residual_block(conv3, 3)
resid2 = _residual_block(resid1, 3)
resid3 = _residual_bloc... |
import time
import datetime
from mysql_observer import MysqlObserver, MysqlOb
from mysql import fetchone_sql as fetch_sql
def handler(*args, **kwargs):
print args
class Class1(MysqlObserver):
def __init__(self, key='default1'):
super(Class1, self).__init__()
self.ob = MysqlOb(handler)
se... |
from TwitterAPI import *
from datetime import *
from pymongo import MongoClient
import sys
import json
import os.path
import time
timeout = 60*3
timeout_start = time.time()
consumer_key = "NBL0CtVrn2ajbpaGEWC1GBY2c"
consumer_secret = "2F5Uz5VYg0ONu4xTYYZsWkAGfc3TYXCkXLCsXMJ1eCKOfhBTfS"
access_token = "2345718031-we2K2P... |
from django.views.generic import TemplateView
class InsightsView(TemplateView):
template_name = "insights.html" |
import settingsManager
import spriteManager
import os
import imp
import pygame
import menu
import battle
import sys
import stages.true_arena as stage
import sss
import musicManager
class CSSScreen():
def __init__(self,rules=None):
settings = settingsManager.getSetting().setting
self.rules = rules
... |
"""Module for calling Group related last.fm web services API methods"""
__author__ = "Abhinav Sarkar <abhinav@abhinavsarkar.net>"
__version__ = "0.2"
__license__ = "GNU Lesser General Public License"
__package__ = "lastfm"
from lastfm.base import LastfmBase
from lastfm.mixin import mixin, chartable
from lastfm.decorato... |
from asterisklint.alinttest import ALintTestCase
from asterisklint.defines import WarningDef
from asterisklint.where import DUMMY_WHERE
class MessageTestCase(ALintTestCase):
def test_normal(self):
class W_WARNING1(WarningDef):
message = 'irrelevant'
W_WARNING1(DUMMY_WHERE)
self.a... |
from django.contrib import admin
from caribnode.tools.models import *
class ToolAdmin(admin.ModelAdmin):
list_display = ('id', 'order', 'scale', 'external', 'featured', 'name', 'display_name', 'description', 'url', 'org', 'org_url', 'layers', 'settings')
search_fields = ('name','description', 'org', )
class Ind... |
import logging
import datetime
from bottle import route, request
import models
log = logging.getLogger(__name__)
@route('/api/single/',method='GET')
def single_item():
id = request.GET.get('id')
session = models.DBSession()
bill = session.query(models.Bill).get(id)
data = serialize_bill(bill)
return... |
from .buffers import CircularBuffer
from ..constants import (CHANGING, WARNING, ALARM,
ABSOLUTE, RELATIVE, ABOVE, BELOW, UNDER)
from .feature import _LinacFeature
from PyTango import AttrQuality
__author__ = "Lothar Krause and Sergi Blanch-Torne"
__maintainer__ = "Sergi Blanch-Torne"
__copyrigh... |
import unittest
from ProceedingsFromXMLBuilder import ProceedingsFromXMLBuilder
from ..Task import Task
class TestProceedingsFromXMLBuilder(unittest.TestCase):
"""
Tests for the class ProceedingsFromXMLBuilder
.. moduleauthor:: Albert Heinle <aheinle@uwaterloo.ca>
"""
def setUp(self):
#First... |
from glob import glob
import cjson
import Gnuplot
import tempfile
import os
from collections import defaultdict
import hashlib
from operator import itemgetter
from config import *
class Graph():
def __init__(self, filename, title=None):
self.file = filename
self.title = title if title else self.file... |
import re
import time
import urlparse
from module.PyFile import PyFile
from ..internal.Account import Account
from ..internal.Captcha import Captcha
class ExtmatrixCom(Account):
__name__ = "ExtmatrixCom"
__type__ = "account"
__version__ = "0.01"
__status__ = "testing"
__description__ = """Extmatrix.... |
import sys
from Cream import *
def main():
connection_timeout = 30 # seconds
#
# Set the enable or disable submission by choosing the boolean value...
#
enable = True # or False
creamClient = CreamProxyFactory.make_CreamProxyAcceptNewJobSubmissions(enable, connection_timeout)
#
# [...]
#
# Check the NULLNES... |
"""Add completed status to mod records
Revision ID: 35c29e829e42
Revises: 284495b61141
Create Date: 2014-07-28 23:08:26.708142
"""
revision = '35c29e829e42'
down_revision = '284495b61141'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('mods', sa.Column('completed', sa.Boolean(), nullabl... |
import sys, os
sys.path.append(os.path.abspath('.'))
import re
from operator import attrgetter
import difflib
import pylons.test
import logging
from quanthistling.config.environment import load_environment
from quanthistling.model.meta import Session, metadata
from quanthistling import model
import quanthistling.dictda... |
n,x,y = map(int, input().split())
minut = min(x, y)
x, y = min(x, y), max(x, y)
n -= 1
time_1 = n * x
time_2 = 0
i = 1
while time_1 >= time_2:
time_2 = y * i
time_1 -= x
i += 1
time_1 += x
minut += time_1
print(int(minut)) |
from __future__ import unicode_literals
from registry.reg import _Reg
class Windows2008ServerR2UserReg(_Reg):
def __init__(self, params):
_Reg.__init__(self, params)
_Reg.init_win_vista_and_above(self)
def csv_open_save_mru(self):
super(Windows2008ServerR2UserReg, self)._csv_open_save_mr... |
KEY_UNKNOWN = 0
KEY_SOFT_LEFT = 1
KEY_SOFT_RIGHT = 2
HOME = KEY_HOME = 3
BACK = KEY_BACK = 4
KEY_CALL = 5
KEY_ENDCALL = 6
KEY_0 = 7
KEY_1 = 8
KEY_2 = 9
KEY_3 = 10
KEY_4 = 11
KEY_5 = 12
KEY_6 = 13
KEY_7 = 14
KEY_8 = 15
KEY_9 = 16
KEY_STAR = 17
KEY_POUND = 18
KEY_DPAD_UP = 19
KEY_DPAD_DOWN = 20
KEY_DPAD_LEFT = 21
KEY_DPA... |
from R305 import generateHeader, header, address
identifire = {1:"command packet",
2: "data packet",
7:"acknokedge packet",
8:"end of data packte"}
confirmation_codes = {0:"ready to transfer the following data packet.",
1:"error while reciving packet",
... |
"""
MagPy
GFZ input filter
supports Kp values from the qlyymm.tab
Written by Roman Leonhardt October 2012
- contains test, read and write function for hour data
ToDo: Filter for minute data
"""
from __future__ import print_function
from magpy.stream import *
def isGFZKP(filename):
"""
Checks whether a file is A... |
import urllib.request, os
def writePidFile(scriptdir, name):
pid = str(os.getpid())
f = open(scriptdir+'/'+name+'.pid', 'w')
f.write(pid)
f.close()
def deletePidFile(scriptdir, name):
os.unlink(scriptdir+'/'+name+'.pid')
def error(port, task, message=''):
if message is None or message == '': c =... |
import os
from flask import Flask, render_template, request
from flask_assets import assets, Environment, Bundle
app = Flask(__name__)
env = assets.Environment(app)
env.register(
'css_main',
assets.Bundle(
'main.sass',
filters='sass',
output='css_main.css'
)
)
@app.route("/home")
def... |
"""
"""
import os
import signal
import subprocess
import tempfile
import time
import sys
script = '''#!/bin/sh
echo "Shell script in process $$"
set -x
python signal_child.py
'''
script_file = tempfile.NamedTemporaryFile('wt')
script_file.write(script)
script_file.flush()
proc = subprocess.Popen(['sh', script_file.name... |
from __future__ import print_function
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
import warnings
import abu_local_env
import abupy
from abupy import AbuFactorBuyBreak
from abupy import AbuFactorSellBreak
from abupy import AbuFactorAtrNStop
from abupy import AbuFactorPre... |
class GapStringExtractor:
def extract(self, M, tokens):
"""
Returns a list of gap-string where each element
of the list contains the gap-strings for one of
the strings in m
"""
gapStrings = []
for m in M:
tokenIndices = self._getTokenIndices(m, tok... |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('app', '0026_change_meta_on_share'),
]
operations = [
migrations.RunSQL(
[("GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO sdump_user;")],
... |
"""
This module provides a workaround for people without mpi4py installed
to run BET.
"""
import collections
class comm_for_no_mpi4py(object):
"""
Provides a fake MPI.COMM_WORLD implementation so that the user need not
install mpi4py.
"""
def __init__(self):
"""
Initialization
... |
from keras.callbacks import Callback
import os
class ModelSnapshotRBM(Callback):
def __init__(self, log_folder="LOG", epoch_interval=1, model_name="bla",verbose=True):
self.log_folder = log_folder
self.model_name = model_name
self.epoch_interval = epoch_interval
self.verbose = verbos... |
"""
pyboy.py Telegram adapter for pybot using python-telegram-bot.
Author: Rael Garcia <self@rael.io>
Date: 06/2016
Usage: Export TELEGRAM_TOKEN variable and run the bot.
Tested on: Python 3 / OS X 10.11.5
"""
import logging
import os
import re
from importlib import reload
from su... |
from __future__ import (absolute_import, division, print_function)
import unittest
from mantid import config
from mantid.api import mtd
from mantid.simpleapi import (AddSampleLog, AddTimeSeriesLog, CreateSampleWorkspace,
CropWorkspace, GroupWorkspaces, Rebin)
from testhelpers import (asser... |
import pytest
import random
from pyranda.rodnecislo import RodneCislo
def test_RodneCisloProperties():
""" Otestuj existenci všech položek pro rodné číslo.. """
mcislo = ""
mrok = 0
mmesic = 0
mden = 0
mpohlavi = 0
rodnecislo = RodneCislo()
assert rodnecislo.cislo == mcislo
assert ro... |
"""
BIANA: Biologic Interactions and Network Analysis
Copyright (C) 2009 Javier Garcia-Garcia, Emre Guney, Baldo Oliva
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 versi... |
"""
This example shows how to use the Hydra's phase space Monte Carlo algorithms to
generate events of B0 -> J/psi K pi on fly and evaluate a set of functors.
This example is the python version of Hydra's
https://github.com/AAAlvesJr/Hydra/blob/master/examples/phase_space/phsp_evaluating_functor.cpp
Author: Deepanshu T... |
import sys, os, time, shutil, argparse
import Image
from Yowsup.connectionmanager import YowsupConnectionManager
from Yowsup.Common.debugger import Debugger
USERNAME = '972583340860'
PASSWORD = 'jag6FSF6MicZmp9M8lrsSqoXYo8='.decode('base64')
phase = None
cm = None
signals_interface = None
methods_interface = None
args ... |
num1 = input()[::-1]
num2 = input()[::-1]
newNum1 = ''
newNum2 = ''
count = 0
for n1, n2 in zip(num1, num2):
if n1 > n2:
newNum1 += n1
elif n1 < n2:
newNum2 += n2
else:
newNum1 += n1
newNum2 += n2
count += 1
if count >= len(num1):
newNum2 += num2[count:]
elif count >= len(num2):
newNum1 += num1[count:... |
__license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
'''
Device drivers.
'''
import sys, time, pprint, operator
from functools import partial
from StringIO import StringIO
DAY_MAP = dict(Sun=0, Mon=1, Tue=2, Wed=3, Thu=4, Fri=5, Sat=6)
MONTH_MAP = dict(Jan=1, Feb=2, Mar=3, Apr=4, May... |
"""
tkRAD - tkinter Rapid Application Development library
(c) 2013+ Raphaël SEBAN <motus@laposte.net>
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 Li... |
from __future__ import print_function
from lib.can_actions import CanActions, auto_blacklist
from lib.common import list_to_hex_str, parse_int_dec_or_hex
from datetime import datetime, timedelta
from sys import stdout
import argparse
import time
XCP_ERROR_CODES = {
0x00: ("ERR_CMD_SYNC", "Command processor synchron... |
import gammalib
import matplotlib.pyplot as plt
map = gammalib.GSkyMap("GAL", 1, "RING")
print(map)
plt.figure(1)
for index in range(4,5):
centre = map.inx2dir(index)
proj = map.projection()
dirs = proj.boundaries(gammalib.GSkyPixel(index), 3)
print len(dirs)
print dirs[0], dirs[1], dirs[2], d... |
""" This is an integration test using both the TSCatalog and the FileCatalog plugins
It supposes that the TransformationDB and the FileCatalogDB are present
It supposes the TransformationManager and that DataManagement/FileCatalog services running
The TSCatalog and FileCatalog plugins must be configured
... |
from fabric.api import *
import os
env.host = ['usuario:22']
def download():
run ('sudo rm -rf IV')
run ('sudo git clone https://github.com/jfranguerrero/IV')
def nohup():
with shell_env(api_skyscanner=os.environ['api_skyscanner'], DATABASE_URL=os.environ['DATABASE_URL'], token_vuelabot=os.environ['token_vu... |
import requests
import re
import os
from lxml import html
import datetime
import json
import mtgs_scraper
import xml.dom.minidom
def correct_cards(mtgjson, manual_cards=[], card_corrections=[], delete_cards=[]):
mtgjson2 = []
for card in manual_cards:
if 'manaCost' in card:
card['manaCost'] ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.