code stringlengths 1 199k |
|---|
d = np.load('spectralCube_2stars_1626spectra.npy')[()]
print(d.keys())
print(d['spectral'])
print(d['temporal'])
print(d['squares'])
print(d['cubes']) |
from twisted.protocols import tls
from twisted.internet import interfaces
from zope.interface import implements
class SSLWrapClientEndpoint(object):
implements(interfaces.IStreamClientEndpoint)
def __init__(self, contextFactory, wrappedEndpoint):
self.contextFactory = contextFactory
self.wrapped... |
"""
"""
from twisted.internet import defer
from twisted.internet.protocol import Factory
from ..machine import Machine, Property, ui
from ..protocol.basic import QueuedLineReceiver
from ..util import now
__all__ = ["MultiValve"]
class LineReceiver (QueuedLineReceiver):
timeoutDuration = 4.5
delimiter = b"\r"
class Mu... |
import frappe
def execute():
frappe.reload_doc("core", "doctype", "docfield", force=True)
frappe.reload_doc("custom", "doctype", "custom_field", force=True)
frappe.reload_doc("custom", "doctype", "customize_form_field", force=True)
frappe.reload_doc("custom", "doctype", "property_setter", force=True)
frappe.db.sql... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('ringapp', '0021_auto_20150121_1848'),
]
operations = [
migrations.AlterModelTable(
name='metaproperty',
table='metaproperty',
... |
from django.shortcuts import render
from rest_framework import mixins
from rest_framework import generics
from customers.models import Customer
from customers.serializers import CustomerSerializer
class CustomerList(generics.ListCreateAPIView):
queryset = Customer.objects.all()
serializer_class = CustomerSerial... |
import time, sys, os, helper, config, data
from comodit_client.api import Client
from comodit_client.api.exceptions import PythonApiException
from comodit_client.api.collection import EntityNotFoundException
from comodit_client.rest.exceptions import ApiException
from comodit_client.api.host import Host
from helper imp... |
import configparser
from os import path
from sys import argv
from lib.Parser2Feed import OneRSSFile, RSSFilePerParser, RSSFilePerURL
class Main:
def __init__(self):
self.__config = configparser.ConfigParser()
working_path = path.dirname(argv[0])
default_config = path.join(working_path, "conf... |
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('transcript', '0010_transcript_statistics'),
]
operations = [
migrations.AddField(
model_name='tra... |
version_info = (7, 0, 0, 'final', 0)
_specifier_ = {'alpha': 'a', 'beta': 'b', 'candidate': 'rc', 'final': ''}
__version__ = '%s.%s.%s%s'%(version_info[0], version_info[1], version_info[2],
'' if version_info[3]=='final' else _specifier_[version_info[3]]+str(version_info[4]))
__protocol_version__ = '2.0.0'
__jupyter_... |
from .base import * # noqa
DEBUG = True
INTERNAL_IPS = ["127.0.0.1"]
SECRET_KEY = "secret"
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'development.sqlite3',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
},
}
CACHES = {
"d... |
import sys
def main(args):
data = [int(s.strip()) for s in sys.stdin]
total = 0
for x in data:
total += (x // 3) - 2
print(total)
if __name__ == '__main__':
sys.exit(main(sys.argv)) |
from unittest import TestCase
from ..fixtures.csv import CsvToFixtureFactory as Factory
from ..fixtures.parseargs import parse_args
import os
class ParseArgsTests(TestCase):
def test_no_args_return_cwd(self):
args = []
cwd = os.getcwd()
args = parse_args(args)
self.assertEqual(args.p... |
"""Test the bumpfee RPC.
Verifies that the bumpfee RPC creates replacement transactions successfully when
its preconditions are met, and returns appropriate errors in other cases.
This module consists of around a dozen individual test cases implemented in the
top-level functions named as test_<test_case_description>. T... |
from vsm.spatial import angle_sparse
from vsm.exceptions import *
from wrappers import *
__all__ = ['TfIdfViewer']
class TfIdfViewer(object):
"""
A class for viewing Term frequency-Inverse document Frequency model.
"""
def __init__(self, corpus, model):
"""
Initialize TfIdfViewer.
... |
from mrjob.job import MRJob
import json as simplejson
from mrjob.protocol import RawValueProtocol
from datetime import datetime, timedelta
import ujson
class MRRetweetRate(MRJob):
OUTPUT_PROTOCOL = RawValueProtocol
PARTITION_SECS = 20 # bin things in five minutes
NUM_PARTITIONS = 60*60/PARTITION_SECS # reco... |
"""hug/directives.py
Defines the directives built into hug. Directives allow attaching behaviour to an API handler based simply
on an argument it takes and that arguments default value. The directive gets called with the default supplied,
ther request data, and api_version. The result of running the directive method is... |
"""
Utilities for working with SCIP: http://scip.zib.de/
"""
import numpy as np
import pyllars.utils as utils
import toolz.dicttoolz
def _parse_status_line(l):
# SCIP Status : problem is solved [optimal solution found]
was_solved = l.find("problem is solved") > -1
time_out = l.find("time limit reache... |
from datetime import datetime, timedelta
from flask import Flask, current_app, make_response, request
from markdown import markdown
import pyjade
from pyjade.ext.jinja import PyJadeExtension
from server_global import config, db, rds
from service import dns_cname, is_muh_domain, url_builder_manager
from service.app impo... |
from org.xdi.oxauth.security import Identity
from org.xdi.model.custom.script.type.auth import PersonAuthenticationType
from org.xdi.oxauth.service import UserService
from org.xdi.util import StringHelper
from org.xdi.service.cdi.util import CdiUtil
import java
class PersonAuthentication(PersonAuthenticationType):
... |
from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups') |
"""
mygraph.py, modified from demo python script by Eli Bendersky (eliben@gmail.com), is real time plotting with wxPython Phoenix
"""
import os
import random
import sys
import wx
import matplotlib
matplotlib.use('WXAgg')
import matplotlib.pyplot as plt
from matplotlib import gridspec
from matplotlib.backends.backend_wx... |
from distutils.core import setup
setup(name = "MarkdownPP",
version = "1.0",
description = "Markdown",
author = "John Reese",
author_email = "john@noswap.com",
url = "https://github.com/jreese/markdown-pp.git",
data_files = [('/usr/local/bin', ['markdown-pp.py'])],
packages = [... |
import numpy as np
import uncertainties.unumpy as unp
from uncertainties import ufloat
import math
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
import scipy.constants as const
fallzeit_kleine_kugel, fallzeit_große_kugel = np.genfromtxt('fallzeit_raumtemp.txt',unpack=True)
temperatur, fallzeit_k... |
from __future__ import division
import sys
sys.dont_write_bytecode = True
import math
from prime_gen import gen_4n3
__author__ = 'Saifuddin Abdullah'
"""
Primelookup - packed in a single portable object
"""
class primelookup(object):
"""
init
"""
def __init__(self, docs):
#first 26 primes of the... |
import random as rand
node_count = 20
soft_max = 5
data = {}
for i in range(node_count):
data[i] = []
for key, value in data.items():
for i in range(rand.randint(1, soft_max)):
node = rand.randint(0, node_count - 1)
if node != key and node not in value:
value.append(node)
... |
YEAR = 0
MONTH = 1
DAY = 2
HOUR = 3
MINUTE = 4
SECOND = 5
MILLISECOND = 6
class BaseLocale():
def __init__(self):
pass
def relative(self, target, number):
pass
def past(self, time):
pass
def future(self, time):
pass |
import csv
import datetime
from bill_search import count_matches, words, title_phrases
from wordsearch import count_phrase_for_legislator
CSV_FILE = 'bills.csv'
TODAY = datetime.date.today().isoformat()
def main():
with open(CSV_FILE) as data_file:
i = 0
reader = csv.reader(data_file, quotechar='|')... |
import traceback
import sys
import os.path
from lxml import etree as et
from profiles.quickbird_parser import load_as_xml
from profiles.quickbird import ProfileQuickBird
XML_OPTS = {'pretty_print': True, 'xml_declaration': True, 'encoding': 'utf-8'}
def main(fname):
profile = ProfileQuickBird
xml = load_as_xml(... |
project = "Project"
runVers = "Run"
makePlot = "spectrum"
specSynMode = False
teff = 5777.0 #, K
logg = 4.44 #, cgs
log10ZScale = 0.0 # [A/H]
massStar = 1.0 #, solar masses
xiT = 1.0 #, km/s
logHeFe = 0.0 #, [He/Fe]
logCO = 0.0 #, [C/O]
logAlphaFe = 0.0 #, [alpha-elements/Fe]
lambdaSt... |
import csv
import re
class Arquivo:
def __init__(self, path):
rp = re.compile("^ *(\d+) +(\d+)\n?$")
self.alturas = []
self.duracoes = []
linecount = 1
with open(path) as f:
for line in f:
match = rp.match(line)
if match:
... |
from hamcrest import assert_that, is_
class GoPayMock:
def __init__(self, config=None):
self.request = ()
self.config = config if config is not None else {}
self.response = 'irrelevant browser response'
def given_response(self, has_succeed=False, json=None):
self.response = Respo... |
from .exceptions import SprinterException
EXAMPLE = """
packages:
sprinter:
updated_date: 2015-12-10T02:59:43Z
user_input: {}
config: {}
""".strip()
class StateException(SprinterException):
pass
class SprinterState(object):
def __init__(self, config):
self._validate(config)
@staticmeth... |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0002_fixture_os'),
]
operations = [
migrations.RenameModel(
old_name='InstallerFiles',
new_name='CoreInstaller',
),
] |
from __future__ import print_function, unicode_literals, division # Python2.7
import sqlite3 as sqlite
import sys
import os
import locale
import csv
import datetime
import io
import codecs
import shlex # Simple lexical analysis
try: # We are Python 3.3+
from tkinter import *
from tkinter import font, ttk, fi... |
from kivy.app import App
from kivy.factory import Factory
from kivy.properties import ObjectProperty
from kivy.lang import Builder
Builder.load_string('''
<LabelDialog@Popup>
id: popup
title: ''
size_hint: 0.8, 0.3
pos_hint: {'top':0.9}
BoxLayout:
orientation: 'vertical'
Widget:
... |
from fuzzywuzzy import fuzz
import lib.notationToEmoji as notationToEmoji
def move_Compare_Main(chara_Move, characterMoves_json, is_case_sensitive, chara_Name):
chara_Move = move_Input_Standardizer(chara_Move)
if is_case_sensitive:
move = list(filter(lambda x: (move_Input_Standardizer(x['Command']) == c... |
class MacApiError(Exception):
"""An error status code was returned when querying the HTTP API"""
pass
class MacAuthError(MacApiError):
"""An 401 Unauthorized status code was returned when querying the API"""
pass
class MacParamValidationError(MacApiError):
"""There is an error when validating params... |
"""
Collects JMX metrics from the Jolokia Agent. Jolokia is an HTTP bridge that
provides access to JMX MBeans without the need to write Java code. See the
[Reference Guide](http://www.jolokia.org/reference/html/index.html) for more
information.
By default, all MBeans will be queried for metrics. All numerical values w... |
import os
from osim.env import Arm2DEnv
import pprint
import numpy as np
env = Arm2DEnv()
if __name__ == '__main__':
observation = env.reset()
env.osim_model.list_elements()
for i in range(3000):
action = env.action_space.sample()
observation, reward, done, info = env.step(action)
pr... |
import os
from slackclient import SlackClient
"""
Returns the id of the movie slackbot
"""
SLACK_BOT_TOKEN = os.environ.get('SLACK_BOT_TOKEN')
BOT_NAME = 'filmybot'
bot_found = False
try:
slack_client = SlackClient(SLACK_BOT_TOKEN)
except:
print "Connection error"
#calling the api to get a list of all users in your ... |
"""Utility file contains attack algorithm for SVM"""
import numpy as np
def min_dist_calc(x, clf):
"""
Find the class that <x> is closest to its hyperplane and calculate that
distance
"""
x_ini = x.reshape(1, -1)
ini_class = clf.predict(x_ini)
w = clf.coef_[int(ini_class[0]), :]
d_list =... |
import json
import urllib
import urllib.request
from pyfiglet import Figlet
async def harambe(message, client):
data = json.loads(urllib.request.urlopen("http://api.giphy.com/v1/gifs/random?tag=silverback+gorilla&api_key=dc6zaTOxFJmzC").read().decode('utf-8'))
data = json.loads(json.dumps(data['data']))
awa... |
from __future__ import absolute_import
from adblockparser import AdblockRules, AdblockRule, AdblockParsingError
import pytest
try:
import re2
USE_RE2 = [True, False, 'auto']
except Exception:
USE_RE2 = ['auto']
DOCUMENTED_TESTS = {
"/banner/*/img^": {
"blocks": [
"http://example.com/... |
from django.test import TestCase
from django import forms
from freezegun import freeze_time
from formidable import json_version
from formidable.constants import REQUIRED
from formidable.forms import (
FormidableForm, fields, get_dynamic_form_class_from_schema
)
from formidable.forms import field_builder, widgets
fr... |
import flask
import base64
import importlib
from flask.ext.classy import FlaskView, route, request
from annotator_supreme.controllers.plugins_controller import PluginsController
from annotator_supreme.controllers.image_controller import ImageController
from annotator_supreme.controllers.dataset_controller import Datase... |
from __future__ import print_function, unicode_literals
from collections import OrderedDict
import six
from django import forms
from django.core.urlresolvers import Resolver404, resolve
from django.core.validators import URLValidator
from django.http import QueryDict
from .utils import Base64
class NextUrlField(forms.C... |
from shiji.webapi import APIError
class SampleNormalError(APIError):
error_code = 100
exception_class = "SampleNormalError"
exception_text = "A sample normal error that doesn't take arguments except for 'request'."
class SampleAdvancedError(APIError):
error_code = 101
exception_class = "SampleAdvanc... |
from twython import Twython, TwythonAuthError, TwythonRateLimitError
import json
import config
import time
def file_to_list(filename):
f = open(filename, 'r')
return [line.strip('\n') for line in f.readlines()]
def get_oauth_tokens():
return file_to_list('oauth_token.txt')
OAUTH_TOKEN, OAUTH_TOKEN_SECRET = ... |
from numpy import cos, sin, pi, arctan2, sqrt,\
square, int, linspace, any, all, floor, round, ceil
from numpy.random import random as random
import numpy as np
import cairo
from time import time as time
from operator import itemgetter
from numpy.random import normal as normal
from collections import ... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('social', '0002_auto_20180212_1637'),
]
operations = [
migrations.AlterField(
model_name='socialmediaqueue',
name='date',
... |
from random import randrange
from myhdl import Signal
from myhdl import intbv
from myhdl import traceSignals
from myhdl import Simulation
from myhdl import bin
from myhdl import delay, instance, always, always_seq, always_comb
from myhdl import toVerilog, toVHDL
def register_sync(q, d, ce, clk):
"""
register --... |
from ..error import ClientError
from .response_handler import ResponseHandler
class ErrorHandler():
@staticmethod
def check_error(response, *args, **kwargs):
code = response.status_code
typ = response.headers.get('content-type')
if code in range(500, 600):
raise ClientError('Error ' + str(code), code)
elif... |
from setuptools import setup, find_packages
version = '1.2.0'
setup(
name='tag-hub',
version=version,
description="Task distribution and result aggregation",
long_description="TAG hub distributes tasks to DetectionModules and aggregates results.",
classifiers=[],
keywords='',
author='PSR',
... |
from django.contrib import admin
from .models import Challenge, CompletedChallenge
admin.site.register(Challenge)
admin.site.register(CompletedChallenge) |
"""Code to implement graphics output for ANI analyses."""
from math import floor, log10
import warnings
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
import scipy.cluster.hierarchy as sch
import scipy.spatial.distance as distance
import... |
"""
Table of command codes is in Section 4.1, page 58.
"""
import re
from decimal import Decimal
def parse_command(s):
if s[0] == '%':
# Extended commands, identify by first 3 chars
code = s[1:3]
cls = extended_commands[code]
return cls.from_string(s)
else:
# For normal c... |
from hwt.hdl.constants import Time
from hwt.pyUtils.arrayQuery import take, iter_with_last
from hwt.simulator.simTestCase import SimTestCase, \
simpleRandomizationProcess
from hwtLib.amba.axis_comp.fifoMeasuring import AxiS_fifoMeasuring
from pyMathBitPrecise.bit_utils import mask, mask_bytes
from hwtSimApi.constan... |
import sys
from twitter_bot import BotRunner, Settings
if __name__ == '__main__':
if len(sys.argv) != 2:
print("You must specify a single command, either 'post_message' or 'reply_to_mentions'")
result = 1
else:
result = BotRunner().go(Settings(), sys.argv[1])
sys.exit(result) |
"""
WSGI config for polyclinic project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTING... |
'''pyglet is a cross-platform games and multimedia package.
Detailed documentation is available at http://www.pyglet.org
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
import os
import sys
_is_epydoc = hasattr(sys, 'is_epydoc') and sys.is_epydoc
version = '1.2.4'
compat_platform = sys.platform
if "bsd" in ... |
r'''We consider two diseases that cooperate in the sense that if an individual has
recovered from one disease, then if it is infected with the other disease it
transmits with higher rate and it remains infectious longer. This is a bit
unrealistic, but could correspond to an individual having a more mild infection
resu... |
"""Stores a class that manages flags generation using cmake.
Attributes:
log (logging.Log): Current logger.
"""
from .flags_source import FlagsSource
from .compilation_db import CompilationDb
from ..tools import File
from ..tools import Tools
from ..tools import SearchScope
from ..tools import singleton
from os imp... |
from __future__ import division
import logging
import time
from quant import config
from quant.common import constant
from .basicbot import BasicBot
from quant.brokers import broker_factory
class T_Kkex_BCH(BasicBot):
"""
kkex
python -m quant.cli -mBitfinex_BCH_USD,Kkex_BCC_BTC,Bitfinex_BTC_USD -o=T_Kkex_BC... |
import _plotly_utils.basevalidators
class LatValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(self, plotly_name="lat", parent_name="layout.geo.center", **kwargs):
super(LatValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
ed... |
from __future__ import absolute_import, division, with_statement
import sys
import logging
import token
import basicParser
logging.basicConfig(level=logging.DEBUG)
parse_file = open('simple.ps', 'r')
lexer = token.Lexer(parse_file)
def lexer_runner():
res = lexer.read()
while not res.is_EOF():
print("==... |
from __future__ import absolute_import
from __future__ import print_function
import sys
import os.path
from pyth.plugins.rtf15.reader import Rtf15Reader
from pyth.plugins.xhtml.writer import XHTMLWriter, write_html_file
numargs = len(sys.argv) - 1
if numargs not in [1, 2]:
print("usage: rtf15 inputfile.rtf [outputd... |
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRe... |
"""
Copyright (C) 2012 Alan J Lockett
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, ... |
import os
import re
import sys
import json
import time
import struct
import pprint
import logging
import requests
import argparse
import getpass
import csv
import time
from tkinter import ttk
import tkinter as tk
from collections import OrderedDict
from pokemondata import PokemonData
from pokeivwindow import PokeIVWind... |
try:
from .metrics_post_body_schema_parameters_py3 import MetricsPostBodySchemaParameters
from .metrics_post_body_schema_py3 import MetricsPostBodySchema
from .metrics_segment_info_py3 import MetricsSegmentInfo
from .metrics_result_info_py3 import MetricsResultInfo
from .metrics_result_py3 import Me... |
"""Classes and functions used to construct graphs."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import contextlib
import copy
import linecache
import re
import sys
import threading
import weakref
import six
from tensorflow.core.framew... |
import functools
from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import Pipe... |
import json
import copy
history = []
class ConnectMore:
TURNS_PER_PLAYER = 18
WIDTHS = [6, 9, 9, 10, 12]
HEIGHTS = [6, 6, 8, 9, 9]
#initiate the value of each chain length with length 3=1, 4=2,
#and everything else upto max dimensions as a 'fibonacci-ish' sequence
CHAIN_LENGTH_SCORE = [0, 0, 0, ... |
import logging
import time
from quant import config
class Market(object):
"""
eth_btc
base_currency :btc
quote_currency:eth
"""
def __init__(self, base_currency, market_currency, pair_code, fee_rate):
self._name = None
self.base_currency = base_currency
self.marke... |
import unittest
import os, shutil, glob, re
from scipy.misc import imread
from ptv1 import py_start_proc_c, py_init_proc_c
from ptv1 import py_sequence_init, py_sequence_loop, py_set_img
from ptv1 import py_trackcorr_init, py_trackcorr_loop, py_trackcorr_finish
from ptv1 import py_trackback_c
def compare_directories(di... |
from {{cookiecutter.app_name}}.auth import views
__all__ = ["views"] |
__author__ = 'Milinda Perera'
from charm.toolbox.integergroup import random, integer
from pkenc_paillier import Paillier
from utils_poly import poly_eval_horner, poly_from_roots
class PSI3RoundPaillier(object):
"""
Implements the 3-round PSI protocol based on Paillier cryptosystem
"""
def __init__(self,... |
import hashlib
import hmac
import struct
import scrypt
if bytes == str:
def check_bytes(byte_array):
return True
def get_byte(c):
'Converts a 1-byte string to a byte'
return ord(c)
def chars_to_bytes(array):
'Converts an array of integers to an array of bytes.'
return... |
'''Provide some text utilities.
This small module is just used to contain simple text utilities that
might be used to cleanup text strings or to generate random text.
Most utilities are just functions.
Functions included:
- sanitize_name:
Classes included:
- Chomsky: This is and adaptatiion of the Chomsky utility b... |
from __future__ import unicode_literals, division, absolute_import
from builtins import * # pylint: disable=unused-import, redefined-builtin
import pytest
@pytest.mark.online
class TestMyEpisodes(object):
"""Uses test account at MyEpisodes, username and password are 'flexget'"""
config = """
tasks:
... |
from __future__ import division, print_function, absolute_import
import os.path
import warnings
import numpy as np
import scipy.ndimage as ndimage
from numpy.testing import (assert_, assert_array_almost_equal, assert_equal,
assert_almost_equal, assert_array_equal,
a... |
"""
DocuSign REST API
The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. # noqa: E501
OpenAPI spec version: v2.1
Contact: devcenter@docusign.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint... |
import os
import tensorflow as tf
import numpy as np
from tensorflow.contrib.rnn import LSTMCell
from q_learning.q_network import MentorAgent, ExperienceBuffer, update_target_graph, perform_update, process_capture
import gym
import universe
tf.reset_default_graph()
env = gym.make('Pong-v0')
FILTER_DIMS = [[8, 8], [4, 4... |
"""
Command Line tool to split a csv file
Takes carguments from the command line. For argument help use: python file_fragmenter.py --help
Script will bring source CSV into Pandas Dataframe and use DF to ouput to smaller files
Arguments include the ability to control how many rows are in the output ... |
import glob
import os
import re
import sys
if len(sys.argv) != 3:
sys.exit("Usage: %s $QTDIR/translations $BITCOINDIR/src/qt/locale"%sys.argv[0])
d1 = sys.argv[1]
d2 = sys.argv[2]
l1 = set([ re.search(r'qt_(.*).qm', f).group(1) for f in glob.glob(os.path.join(d1, 'qt_*.qm')) ])
l2 = set([ re.search(r'bitcoin_(.*).qm'... |
import os
import tempfile
import requests
from requests_toolbelt import MultipartEncoder
from moviesapp.models import Record
from .mixins import VkAjaxView
class UploadPosterToWallView(VkAjaxView):
tmp_file = None
def _get_filepath(self, record_id):
movie = Record.objects.get(pk=record_id).movie
... |
VERSION = (0, 2, 2)
def get_version():
return '.'.join((str(number) for number in VERSION))
__version__ = get_version()
default_app_config = 'email_confirm_la.apps.ECLAAppConf' |
'''
SAMPLE: Freitag, 13.09.13, 17:26
'''
SAMPLE = '01011001101010100100101100101111010011001010110010110010000'
WEEKDAYS = ('Sonntag', 'Montag', 'Dienstag', 'Mittwoch',
'Donnerstag', 'Freitag', 'Samstag', 'Sonntag')
def decode(bits):
assert bits[0] == '0' and bits[20] == '1'
minutes, hours, day_of_m... |
from nose.tools import raises
from sprox.validators import UniqueValue
from sprox.test.base import *
from formencode import Invalid
from sprox.sa.provider import SAORMProvider
session = None
engine = None
connection = None
trans = None
def setup():
global session, engine, connect, trans
session, engine, connect... |
import unittest
"""
Construct tree from given inorder and preorder traversals.
Input:
Inorder: D B E A F C
Preorder: A B D E C F
In a preorder sequence, leftmost element is root of tree. So, we know 'A' is root from given preorder sequence.
By searching 'A' in inorder sequence, we can find out all elements on left side... |
import logging,os,re,sys
def main(color,threshold):
current_dir = os.path.dirname(os.path.realpath(__file__))
input_file = current_dir+"/../aa_vocab_min_count_2"
output_file = current_dir+"/./"+color+"_adv.out.txt"
valid_line = re.compile('^(\w+)\/(\w+)\/(\w+)\/(\w+)\/(\w+)\/(\w+)\/(\w+)\/(\w+)\s\d+$')
suffix = ' ... |
from setuptools import setup
setup(
name= 'CAVA',
version = '1.2.3',
description = 'CAVA (Clinical Annotation of VAriants)',
url = 'https://github.com/RahmanTeam/CAVA',
author = 'RahmanTeam',
author_email = 'rahmanlab@icr.ac.uk',
license = 'MIT',
packages=['cava_', 'ensembldb'],
scri... |
import os
import sys
import uuid
from .compat import iteritems, to_unicode
from .. import exceptions
SAFE_UID_CHARS = ('abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
'0123456789_.-+')
_missing = object()
def expand_path(p):
p = os.path.expanduser(p)
p = os.path.nor... |
"""
WSGI config for hiplyst project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` s... |
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as f:
readme = f.read()
requires = [
'pelican',
]
setup(
name='pelican-link-bugs',
version='0.2',
description='Automati... |
"""TEMPORARY DEBUG/DEVELOPMENT SCRIPT.
It's here only for our (developers) convenience.
Please ignore it (or take as a simple usage example).
"""
from mangopaysdk.mangopayapi import MangoPayApi
from mangopaysdk.types.pagination import Pagination
api = MangoPayApi()
api.Config.ClientID = 'example'
api.Config.ClientPassw... |
n = 100 # List length
N = range(n) # List from 0 to (n-1)
for i in N:
N[i] += 1 # Add 1 to each list element to get 1 to n
fb = (N[i]/3.0,N[i]/5.0)
N[i] = str('') # Needs to be string to append Fizz or Buzz
if fb[0] == flo... |
from ansiblelint import AnsibleLintRule
class ShellAltChmod(AnsibleLintRule):
id = 'E501'
shortdesc = 'Use chmod module'
description = ''
tags = ['shell']
def matchtask(self, file, task):
if task['action']['__ansible_module__'] not in ['shell', 'command']:
return False
if... |
from .models.post import Post
from .models.vote import Vote
from .models.user import User
from .models.comment import Comment
from .models.related_link import RelatedLink
from .models.user_details import UserDetails
from .models.notification import Notification
def parse_notifications(notifications):
return [
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.