content string |
|---|
import simuPOP as sim
pop = sim.Population([500]*2)
pop.evolve(
preOps=[
sim.ResizeSubPops(proportions=(1.5, 2), at=3),
sim.Stat(popSize=True),
sim.PyEval(r'"Gen %d:\t%s\n" % (gen, subPopSize)')
],
matingScheme=sim.RandomSelection(),
gen = 5
) |
import argparse
import logging
import os
import sys
from concurrent import futures
import PIL
import PIL.Image
from tqdm import tqdm
def process_options():
kwargs = {
'format': '[%(levelname)s] %(message)s',
}
parser = argparse.ArgumentParser(
description='Thumbnail generator',
... |
#!/usr/bin/env python3
import glob
import os
import os.path
import sys
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
PROJECT_BEAR_DIR = os.path.abspath(os.path.join(PROJECT_DIR, 'bears'))
def main():
args = sys.argv[1:]
d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Approximately model an atomic absorption line in a stellar spectrum. """
__author__ = "Andy Casey <<EMAIL>>"
import logging
import numpy as np
import scipy.optimize as op
from oracle import photospheres, synthesis
logger = logging.getLogger("fireworks")
def appro... |
import os
import sys
# Add the AstroImage class
import astroimage as ai
# This script will allow you to simply select a range of images and change the
# "OBJECT" keyword in their header to match the appropriate group name. Simply
# change the start and end file numbers for each grup in the dictionary.
# This is the ... |
__author__ = 'casey'
"""
@package coverage_model.util.numpy_utils
@file coverage_model/util/numpy_utils.py
@author Casey Bryant
@brief Common numpy array manipulation routines.
"""
import numpy as np
import random
import string
class NumpyUtils(object):
@classmethod
def sort_flat_arrays(cls, np_dict, sort_... |
from memoryops import MemoryOp
class Pad:
VOL_INDEX = 0
AMB_INDEX = 2
PATCH_INDEX = 4
PATCH_INTERNAL_INDEX = 8
PITCH_INDEX = 12
MUFFLING_INDEX = 16
PAN_INDEX = 18
COLOR_INDEX = 23
MFX_ASSIGN_INDEX = 25
SWEEP_INDEX = 27
MIDI_INDEX = 33
MIDI_GATE_INDEX = 34
SEND_ALL_P... |
import uuid
import collections
def _flatten(d, parent_key='', sep='_'):
# http://stackoverflow.com/a/6027615/519385
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if isinstance(v, collections.MutableMapping):
items.extend(_flatten(v, new_k... |
'''
Communication with Vivado processes monitoring FPGAs over redis.
Using redis was an awful idea. It should be done over sockets.
'''
import redis
import datetime
import logging
from pyvivado import config
logger = logging.getLogger(__name__)
r = redis.StrictRedis(host='localhost', port=6379, db=0)
def get_har... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
import json
import requests
import sys
import linot.config as config
import linot.logger
logger = linot.logger.get().getLogger(__name__)
class TwitchRequests: # pragma: no cover
TWITCH_API_BASE = 'https://api.twitch.tv/kraken/'
... |
#Standard libraries import
import socket
import sys
from thread import *
#Local modules import
import Device
#Modbus TCP Server class
class ModbusTCPServer():
port = 502 ##Modbus port
device_name = '' ##Device name
diagnostic = False ##Diagnostics enable
MAX_CONNECTIONS = 10 ... |
import libnacl
import libnacl.dual
import libnacl.sign
from ...keyvault.keys import PrivateKey
from ...keyvault.public.libnaclkey import LibNaCLPK
class LibNaCLSK(PrivateKey, LibNaCLPK):
"""
A LibNaCL implementation of a secret key.
"""
def __init__(self, binarykey=""):
"""
Create a ... |
import datetime
from django.db import models
from pastryio.models import managers
from pastryio.utils import int_to_b64
class ArchiveMixin(models.Model):
"""
A model that is only marked as deleted when the .delete() method is
called, instead of actually deleted.
Calling .delete() on this object will ... |
"""
===================================================================
Compute cross-talk functions (CTFs) for labels for MNE/dSPM/sLORETA
===================================================================
CTFs are computed for four labels in the MNE sample data set
for linear inverse operators (MNE, dSPM, sLORETA).... |
from sqlalchemy.orm import relationship
from sqlalchemy.schema import Column, ForeignKey
from sqlalchemy.types import BigInteger, Boolean, Float, Integer, String
from tangled.decorators import cached_property
from bycycle.core.geometry import DEFAULT_SRID, length_in_meters
from bycycle.core.geometry.sqltypes import L... |
r"""
*************************************
**espressopp.interaction.SoftCosine**
*************************************
This class provides methods to compute forces and energies ofthe SoftCosine potential.
.. math::
V(r) = A \left[ 1.0 + cos \left( \frac{\pi r}{r_c} \right) \right]
.. function:: espressopp.inter... |
from __future__ import print_function
import h5py
import unittest
import random
import os
from annoy import AnnoyIndex
try:
from urllib import urlretrieve
except ImportError:
from urllib.request import urlretrieve # Python 3
import gzip
from nose.plugins.attrib import attr
class AccuracyTest(unittest.TestCase... |
import click
from regparser.commands.dependency_resolver import DependencyResolver
from regparser.history import annual
from regparser.index import dependency, entry
@click.command()
@click.argument('cfr_title', type=int)
@click.argument('cfr_part', type=int)
@click.argument('year', type=int)
def fetch_annual_editio... |
from supriya.system.SupriyaObject import SupriyaObject
class OscCallback(SupriyaObject):
"""
An OSC callback.
::
>>> import supriya.osc
>>> callback = supriya.osc.OscCallback(
... address_pattern='/*',
... procedure=lambda x: print('GOT:', x),
... )
... |
import attr
from osis_common.ddd import interface
@attr.s(frozen=True, slots=True)
class SearchLanguagesCommand(interface.CommandRequest):
pass # Filters can ba added later when it's needed
@attr.s(frozen=True, slots=True)
class GetLanguageCommand(interface.CommandRequest):
code_iso = attr.ib(type=str) |
# vim:fileencoding=utf-8:nomodified
# $Id$
# Test of the dao module
import json
from radiomate.dao import *
from radiomate.mate import *
import sys
import MySQLdb
# connection parameters
DBHOST="127.0.0.1"
DBUSER="mate"
DBPASSWORD="radi0"
DATABASE="radiomate0"
def roledaotest():
r = Role()
r.rolename = "testrole... |
import os
import gtk
import pango
from otrverwaltung.constants import Cut_action
from otrverwaltung.gui.config_bindings import EntryBinding, FileChooserFolderBinding, CheckButtonBinding, ComboBoxEntryBinding, RadioButtonsBinding
from otrverwaltung import path
class PreferencesWindow(gtk.Window, gtk.Buildable):
_... |
import rospy
import humanoid_league_msgs.msg
from dynamic_stack_decider.abstract_action_element import AbstractActionElement
class AbstractPlayAnimation(AbstractActionElement):
"""
Abstract class to create actions for playing animations
"""
def __init__(self, blackboard, dsd, parameters=None):
... |
# 1mm localization and total power in dreampy
# 2015, 2016 LLB
import numpy
import matplotlib
import shutil
# matplotlib.use('agg')
from matplotlib import pylab, mlab, pyplot
import os
np = numpy
plt = pyplot
# plt.ion()
from argparse import Namespace
from glob import glob
import scipy.io
from scipy.signal import butt... |
from functools import wraps
from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured
from django.db.models.loading import get_apps, get_app, get_models, get_model, register_models
from django.db.models.query import Q
from django.db.models.expressions import F
from django.db.models.manager import Man... |
#! /usr/bin/env python
"""
Sample script that monitors smartcard insertion/removal and select
DF_TELECOM on inserted cards
__author__ = "http://www.gemalto.com"
Copyright 2001-2010 gemalto
Author: Jean-Daniel Aussel, mailto:<EMAIL>
This file is part of pyscard.
pyscard is free software; you can redistribute it and/... |
from PyQt5.QtWidgets import QAction
from formlayout import fedit
from praatkatili.resources import Array, FileResource
from pyAudioAnalysis import audioFeatureExtraction
global main_widget
def transform_array(resource, main_win):
datalist = [("Alias for result", "{}_transformed".format(resource.alias)),
... |
from pygame import display, font, image, init, time, event
from pygame.locals import *
from random import randrange
from GameObject import Bird, Pipe
SCORE_COLOR = (255, 255, 0)
HIGHSCORE_COLOR = (255, 165, 0)
DISPLAY_WIDTH = 320
DISPLAY_HEIGHT = 480
FONT = None
FONT_SIZE = 22
HOLE_SIZE = 50
PIPE_FREQUENCY = 50
PIP... |
import argparse
import csv
import os
import sys
import matplotlib.pyplot as plt
import numpy
from experiments.capacity import data_utils
_OVERLAPS_FILE_NAME = "/overlaps.csv"
def main(inputPath, csvOutputPath, imgOutputPath):
# remove existing /overlaps.csv if present
if os.path.exists(csvOutputPath + _OVER... |
import socket
import sys
import time
import re
class Client(object):
"""Client class
Attributes:
sock: The socket
"""
def __init__(self, sock=None):
# Create a TCP/IP socket
try:
if sock is None:
self.sock = socket.socket(socket.AF_I... |
from .request import content_request
from ..common import util
from ..common import xml_dom_parser as xdp
CONF_ENDPOINT = "%s/servicesNS/%s/%s/configs/conf-%s"
def _conf_endpoint_ns(uri, owner, app, conf_name):
return CONF_ENDPOINT % (uri, owner, app, conf_name)
def reload_conf(splunkd_uri, session_key, app_na... |
from distutils.core import setup
os_files = [
# XDG application description
('share/applications', ['xdg/pyexiftoolgui.desktop']),
# XDG application icon
('share/pixmaps', ['logo/pyexiftoolgui.png']),
]
# main distutils setup (command)
dist = setup(name = "pyexiftoolgui",
version = "0.5",
des... |
"""Dynamic Protobuf class creator."""
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict #PY26
import hashlib
import os
from google.protobuf import descriptor_pb2
from google.protobuf import message_factory
def _GetMessageFromFactory(factory, full_name):
"""G... |
"""
The client end point of the events mechanism.
Clients are the communicating parties of the events mechanism. They
communicate by sending messages to a server, which in turn redistributes
messages to other clients.
When a client registers a callback for a given signal, it also tells the
server that it wants to be ... |
#! /usr/bin/env python
"""
"PYSTONE" Benchmark Program
Version: Python/1.1 (corresponds to C/1.1 plus 2 Pystone fixes)
Author: Reinhold P. Weicker, CACM Vol 27, No 10, 10/84 pg. 1013.
Translated from ADA to C by Rick Richardson.
Every method to preserve ADA-likeness h... |
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
from adhocracy4.dashboard import ProjectFormComponent
from adhocracy4.dashboard import components
from . import forms
from . import views
class ExternalProjectComponent(ProjectFormComponent):
identifier = 'external'
weig... |
import Tkinter as tk
def main():
"""Main function"""
root = tk.Tk()
root.title("Hello")
root.mainloop()
if __name__ == '__main__':
main() |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import tensorflow as tf
import utils
class PTBModel():
def __init__(self, is_training, config, input_):
self._input = input_
batch_size = input_.batch_size
num_steps = input_.num_steps
size = config.hidden_size
vocab_size... |
""" CLI tests for gramps """
import os
import unittest
import re
from .test import test_util as tu
pdir = tu.path_append_parent()
ddir = tu.make_subdir( "cli_test_data")
test_ged = """0 HEAD
1 SOUR min1r.ged min 1-rec
1 SUBM @SUBM1@
1 GEDC
2 VERS 5.5
2 FORM LINEAGE-LINKED
1 CHAR ASCII
0 @I1@ INDI
0 TRLR
"""
min1r =... |
import time
import sys
import re
import logging
from abc import ABCMeta, abstractmethod # abstract base class support
import threading
import Queue
from ... import scriptHelper
from ..cashState import CashStorage, CashState
import pickle
import base64
class CashServer:
__metaclass__ = ABCMeta
MAXIMUM_DISPENS... |
#!/usr/bin/env python2
from __future__ import print_function
import ast
import binascii
import csv
import os
import re
import subprocess
from collections import namedtuple
from glob import glob
from ansible.module_utils.basic import AnsibleModule
ARG_SPECS = {
'display': dict(default=":0", type='str', required=Fa... |
import json
from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render
from django.views.generic import CreateView, ListView, DetailView
from django.views.generic import DeleteView, UpdateView
from .models import TemplateModel
from snappy.utils import log
from nlg... |
#!/usr/bin/env python3
import csv
import http.client
import logging
import logging.handlers
import time
#spaceCode,spaceNo,spaceContent,spaceUsed,spaceType,isBook,devCode,lastSpaceCode,issave,parkCode
def httppost(ip, cmd, body, headers):
global logger
conn = http.client.HTTPConnection(ip, 80, timeout=4)
... |
import unittest
from hecuba import Config
from hecuba.hdict import StorageDict
class StorageDict_Tests(unittest.TestCase):
def test_init(self):
pass
def inmemory_contains_test(self):
pd = StorageDict(None,
[('pk1', 'int')],
[('val1', 'text')... |
#!/usr/bin/env python
#
# wtimegui - Working time class with GUI
#
import sys
import time
try:
from Tkinter import *
import ttk
import tkMessageBox
from threading import *
except ModuleNotFoundError:
from tkinter import *
from tkinter import ttk
from threading import *
from tkinter impor... |
"""Support for monitoring OctoPrint binary sensors."""
import logging
import requests
from homeassistant.components.binary_sensor import BinarySensorDevice
from . import BINARY_SENSOR_TYPES, DOMAIN as COMPONENT_DOMAIN
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_entities, discovery_i... |
from django.db import models
from sorl.thumbnail import ImageField
from django.contrib.auth.models import User
class Sites(models.Model):
id_sites = models.AutoField(primary_key=True)
titulo = models.CharField(max_length=150, db_index=True)
descricao = models.TextField()
link = models.URLField(db_in... |
"""
Provides an APIView class that is the base of all views in REST framework.
"""
from __future__ import unicode_literals
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.db import models
from django.http import Http404
from django.http.response import HttpResponseBase
... |
#!/usr/bin/env python
import paho.mqtt.client as mqtt
import json
from gpiozero import DigitalOutputDevice
from time import sleep
from uuid import getnode as get_mac
class Payload(object):
def __init__(self, json_def):
s = json.loads(json_def)
self.id = None if 'id' not in s else s['id']
se... |
from __future__ import absolute_import
from django.conf import settings
if False:
from zerver.models import UserProfile
from typing import Text
from zerver.lib.avatar_hash import gravatar_hash, user_avatar_hash
from zerver.lib.upload import upload_backend, MEDIUM_AVATAR_SIZE
def avatar_url(user_profile, medium=... |
'''
The Intercom lets Controllers and Minions talk to each other.
'''
import zmq
class Intercom:
def __init__(self):
self.reset()
def reset(self):
context = zmq.Context(1)
# Socket facing clients
self.frontend = context.socket(zmq.REP)
self.frontend.bind("tcp://*:555... |
"""This file should be updated as files/classes/functions are deprecated."""
import pytest
from praw import Reddit
from praw.exceptions import APIException, WebSocketException
from praw.models.reddit.user_subreddit import UserSubreddit
from . import UnitTest
@pytest.mark.filterwarnings("error", category=Deprecatio... |
from scipy import *
import sys,pipes,struct,os,glob,fnmatch,pickle
from pylab import *
from scipy.stats import nanmean, nanstd
from mpl_toolkits.basemap import Basemap
from polar_projection import *
import scipy.io as io
from mpl_toolkits.basemap import Basemap
import Nio
from sattools import *
from gmttools import *
f... |
import logging; logging.basicConfig()
# Import JIT features
from pymothoa.jit import default_module, function
# Import constructs for the Pymothoa dialect
from pymothoa.dialect import *
# Import the Pymothoa types
from pymothoa.types import *
import numpy as np
from ctypes import c_float
from matrixmul import matr... |
from sqlalchemy import Column, ForeignKey, Integer, String, create_engine
from sqlalchemy.orm import Session, relationship, backref,\
joinedload_all
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm.collections import attribute_mapped_collection
from sqlalchemy.... |
#!/usr/bin/env python
"""
Solving Heat Equation using pseudospectral methods with Backwards Euler:
u_t= \alpha*u_xx
BC = u(0)=0 and u(2*pi)=0 (Periodic)
IC=sin(x)
"""
import math
import numpy
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import... |
from __future__ import absolute_import, unicode_literals
from future.builtins import chr, int, str
try:
from html.parser import HTMLParser
from html.entities import name2codepoint
try:
from html.parser import HTMLParseError
except ImportError: # Python 3.5+
class HTMLParseError(Excepti... |
"""Utilities for Science Metadata."""
import d1_scimeta.util
import d1_scimeta.validate
import d1_common.types
import d1_common.types.exceptions
import django.conf
import d1_gmn.app.sciobj_store
def assert_valid(sysmeta_pyxb, pid):
"""Validate file at {sciobj_path} against schema selected via formatId and rais... |
def printMap(the_map,note):
print(note)
for row in the_map:
row_str = ""
for cell in row:
row_str += " {0:3d}".format(cell)
print(row_str)
def pathFinder(x, y, m, steps, lastX, lastY):
# count possible moves
options = []
if x-1 >= 0: # East
op... |
from JumpScale import j
import os
from watchdog.observers.polling import PollingObserver as Observer
from watchdog.events import FileSystemEventHandler
addedspaces = []
class SpaceWatcher():
def __init__(self, contentdir=''):
"""
@param contentDirs are the dirs where we will load wiki files fro... |
"""
Container set for groups and parameters
"""
from ..utils.datastructures import SortedDict
class Parameter(object):
allowed_keys = ('CONF_NAME', 'CMD_OPTION', 'USAGE', 'PROMPT',
'PROCESSORS', 'VALIDATORS', 'LOOSE_VALIDATION',
'DEFAULT_VALUE', 'USE_DEFAULT', 'OPTION_LIST... |
from openerp.osv import fields, osv
class ple_3_5 (osv.Model):
_name = "l10n_pe.ple_3_5"
_inherit = "l10n_pe.ple"
_columns= {
'lines_ids': fields.one2many ('l10n_pe.ple_line_3_5', 'ple_3_5_id', 'Lines', readonly=True, states={'draft':[('readonly',False)],}),
}
def action_reload (self, cr,... |
from splinter.meta import InheritedDocs
class CookieManagerAPI(InheritedDocs("_CookieManagerAPI", (object,), {})):
"""
An API that specifies how a splinter driver deals with cookies.
You can add cookies using the :meth:`add <CookieManagerAPI.add>` method,
and remove one or all cookies using
the :... |
class ConfigFileNotFoundException(Exception):
pass
class ConfigFileInvalidException(Exception):
pass
def get_config_defaults():
"""Get the default configuration values."""
config = {}
# Supress console output
config['quiet'] = False
# Run in daemon mode
config['daemon-mode'] = Fal... |
# Create your views here.
from django.utils import timezone
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.views.generic.list import ListView
from django.utils import timezone
from django import forms
from light_state import get_lig... |
# -*- coding: utf-8 -*-
"""
Admin site configuration for third party authentication
"""
from django import forms
from django.contrib import admin
from config_models.admin import ConfigurationModelAdmin, KeyedConfigurationModelAdmin
from .models import (
OAuth2ProviderConfig,
SAMLProviderConfig,
SAMLConfig... |
"""Module to facilitate quantum chemical computations on chemical
databases. Contains Molecule class and physical constants from psi4 suite.
"""
__version__ = '0.1'
__author__ = 'Lori A. Burns'
# Load Python modules
from molecule import *
from dbproc import *
# Load items that are useful to access from an input file... |
"""A VariantCaller producing DeepVariantCall and gVCF records."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import collections
import itertools
import math
import operator
import numpy as np
from deeptrio.python import variant_calling_d... |
from db.versions.v0_9_1.persistence import DAOList |
from netforce.model import Model, fields, get_model
from datetime import *
from dateutil.relativedelta import *
from netforce import database
from netforce.access import get_active_company
class ReportAccountSum(Model):
_name = "report.account.sum"
_transient = True
_fields = {
"account_id": field... |
# -*- coding: utf-8 -*-
"""----------------------------------------------------------------------------
Author:
Huang Quanyong (wo1fSea)
<EMAIL>
Date:
2016/10/19
Description:
ImageRect.py
----------------------------------------------------------------------------"""
from PIL import Image
from .Rect i... |
import arrow
import superdesk
from flask import json
from bson import ObjectId
from bson.errors import InvalidId
from eve.utils import str_to_date
from eve.io.mongo import MongoJSONEncoder
from eve_elastic import ElasticJSONSerializer
class SuperdeskJSONEncoder(MongoJSONEncoder, ElasticJSONSerializer):
"""Custom... |
"""Basic TensorBoard functional tests using WebDriver."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import os
import subprocess
import unittest
import tempfile
from selenium.webdriver.common import by
from selenium.webdriver.support... |
from tapiriik.services import *
from .service_record import ServiceRecord
from tapiriik.database import db, cachedb
from bson.objectid import ObjectId
# Really don't know why I didn't make most of this part of the ServiceBase.
class Service:
# These options are used as the back for all service record's configurat... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
colors_hex = {
"black": "#000000",
"navy": "#000080",
"darkblue": "#00008b",
"mediumblue": "#0000cd",
"blue": "#0000ff",
"darkgreen": "#006400",
"green": "#008000",
"teal": "#008080",
"darkcyan": "#008b8b",
"deepskyblue": "#00bfff",
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
**********************************************************
*
* libpirc
* version: 20200209a
*
* By: Nicola Ferralis <<EMAIL>>
*
***********************************************************
'''
import RPi.GPIO as GPIO
from time import sleep, time
import sys
import rando... |
"""A simple script to generate a CSV with sine data."""
import csv
import math
ROWS = 3000
def run(filename="sine.csv"):
print "Generating sine data into %s" % filename
fileHandle = open(filename,"w")
writer = csv.writer(fileHandle)
writer.writerow(["angle","sine"])
writer.writerow(["float","float"])
wr... |
import os.path
from setuptools import setup
about = {}
version_path = os.path.join(os.path.dirname(__file__), 'staticconf', 'version.py')
with open(version_path) as f:
exec(f.read(), about)
setup(
name="PyStaticConfiguration",
version=about['version'],
provides=["staticconf"],
author="Daniel Nephi... |
from autobahn.twisted.component import Component, run
from autobahn.wamp.types import RegisterOptions
from autobahn.wamp.exception import ApplicationError
from twisted.internet.defer import inlineCallbacks
@inlineCallbacks
def main(reactor, session):
print("Client session={}".format(session))
try:
re... |
import unittest
class TestBinarySearch(unittest.TestCase):
def test_binary_search(self):
self.assertEqual(-1,binary_search([1,2,3],0))
self.assertEqual(0,binary_search([1,2,3],1))
self.assertEqual(2,binary_search([1,2,3],3))
self.assertEqual(2,binary_search([1,2,2,2,3],2))
def test_binary_se... |
# jsb/plugs/irc.py
#
#
""" irc related commands. """
## gozerbot imports
from jsb.lib.callbacks import callbacks
from jsb.lib.socklib.partyline import partyline
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.lib.fleet import getfleet
import jsb.lib.threads as thr
## basic imports
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# real time bus information
# source
#route -> http://data.taipei/bus/ROUTE
#bus -> http://data.taipei/bus/BUSDATA
import gzip
<<<<<<< HEAD
import requests
=======
import gzip
import requests
import json
>>>>>>> b5a1599dc4edb8dd7e3b2d7f95231de91fce0070
def buildRTBuses():
... |
from spack import *
import glob
class Chombo(MakefilePackage):
"""The Chombo package provides a set of tools for implementing finite
difference and finite-volume methods for the solution of partial
differential equations on block-structured adaptively refined
logically rectangular (i.e. Carte... |
from __future__ import absolute_import
# Copyright (c) 2010-2017 openpyxl
from .strings import (
basestring,
unicode,
bytes,
file,
tempfile,
safe_string,
safe_repr,
)
from .numbers import long, NUMERIC_TYPES
# Python 2.6
try:
from collections import OrderedDict
except ImportError:... |
#generate all the plots for the market project
from optparse import OptionParser
import matplotlib.pyplot as plt
__author__ = 'mattdyer'
# add labels to a plot
# @param points The plot object
# @param axis The axis object
def autolabel(points, axis, data):
# attach some text labels
for i, point in enumerate... |
# -*- coding: utf-8 -*-
"""Micro tidy.
Usage::
>>> print utidy('''
... <form name="FirmaForm" id="FirmaForm" method="POST" autocomplete="off"
... action="." class="fForm"><input type="hidden" name="__cmd"
... value="FirmaForm"></form>hello
... ''')
...
<form action=... |
from __future__ import unicode_literals
__author__ = 'luissaguas'
import frappe
from frappe.utils import get_site_base_path
import os, json
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import subprocess
#import fluorine
import fluorine.utils
import pprint
#import fluorine.... |
from cornice import Service
from pyramid.exceptions import HTTPNotFound
from pyramid.httpexceptions import HTTPFound
from sqlalchemy import func, distinct
from sqlalchemy.sql import or_
import math
from bodhi.models import (
Group,
Package,
Update,
User,
)
import bodhi.schemas
import bodhi.security
im... |
from django.db import models
from django.contrib.auth.models import User
from django.contrib import messages
from apps.hypervisor.models import Hypervisor
from utils import node
import persistent_messages
import time
import os
class InstallationDisk(models.Model):
name = models.CharField(max_length=100)
hypervisor... |
"""Implementation of a Queue."""
from datetime import datetime as dt
class Queue(object):
"""Queue object constructor.
Initialize a queue with no values Queue(),
or pass values into queue Queue(1, 2, 3, 4).
Add value to end of queue:
.enqueue(value)
Removes the top of the queue and returns... |
from bs4 import BeautifulSoup
import time
import numpy as np
import logging
from collections import defaultdict
from tasks.core.base import SiteTask, OrchestrateTask
import urllib2
from porc import Client
class ANNRatingOrchestrate(OrchestrateTask):
@property
def id(self):
return 3
def __init__(self):
logg... |
"""Search blueprint in order for template and static files to be loaded."""
from __future__ import absolute_import, print_function
import json
import six
from flask import Blueprint, current_app, jsonify, request, render_template
from invenio_search.api import RecordsSearch
blueprint = Blueprint('inspirehep_search... |
import simplesorting
import mergesort
import sortquickly
import unittest
import random
import time
import radixal
def sorttestframework(sortfunction):
answer = sortfunction([])
assert answer == []
answer = sortfunction([0])
assert answer == [0]
answer = sortfunction([0, 1])
assert answer == [0,... |
########################################################################
# File : EndpointFactory.py
########################################################################
""" The Cloud Endpoint Factory has one method that instantiates a given Cloud Endpoint
"""
from DIRAC import S_... |
from collections import Counter
# open the reals
reals = []
priors = [0] * 4
with open('realresults.txt') as f:
for line in f:
words = line.split()
num = int(words[0])
reals.append(num)
priors[num] += 1
for index, prior in enumerate(priors):
priors[index] /= len(reals)
# indiv... |
# -*- coding: utf-8 -*-
from ifplus.vfs.models.file import FileObject
#
#
# class PlanVersion(object):
# pass
#
#
# class PlanArchive(object):
# pass
#
#
# class Scenario(object):
# pass
#
#
# class Baseline(object):
# pass
#
#
#
#
#
# class Programme(Initiative):
# pass
#
#
# class Project(Initiati... |
from __future__ import absolute_import, division, print_function
import os
import sys
import tensorflow.compat.v1 as tfv1
from attrdict import AttrDict
from xdg import BaseDirectory as xdg
from src.flags import FLAGS
from .gpu import get_available_gpus
from .logging import log_error
from .text import Alphabet, UTF8A... |
"""Test RPCs related to blockchainstate.
Test the following RPCs:
- getblockchaininfo
- gettxoutsetinfo
- getdifficulty
- getbestblockhash
- getblockhash
- getblockheader
- getchaintxstats
- getnetworkhashps
- verifychain
Tests correspond to code in rpc/blockchain.cpp.
"""
from de... |
""" Interface for Data Ingestion.
"""
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2... |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('rois_manager', '0012_auto_20170208_0933'),
]
operations = [
migrations.AlterUniqueTogether(
name='core',
unique_together=set([('labe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.