code
stringlengths
1
199k
""" batch.py Batch simulation for M1 model using NetPyNE """ from netpyne.batch import Batch import numpy as np def runBatch(b, label, setup='mpi_bulletin'): b.batchLabel = label b.saveFolder = 'data/'+b.batchLabel b.method = 'grid' if setup == 'mpi_bulletin': b.runCfg = {'type': 'mpi_bulletin',...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Company', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=Fals...
from diary import DiaryDB, Event import unittest import sqlite3 import os.path class TestDiaryDB(unittest.TestCase): TEMP_DB_PATH = os.path.join(os.path.dirname(__file__), 'testing_dir', 'temp.db') SIMPLE_EVENT = Event("INFO", "LEVEL") def setUp(self): self.logdb = D...
import os import textwrap import glob from os.path import join, curdir, pardir import pytest from pip.utils import appdirs, rmtree from tests.lib import (pyversion, pyversion_tuple, _create_test_package, _create_svn_repo, path_to_url) from tests.lib.local_repos import local_checkout from tests.li...
from .ppo import PPOAgent
import click import matplotlib import matplotlib.pyplot as plt from matplotlib import rc import numpy as np import pandas as pd prop1range = [0.0, 1.0] # VF prop2range = [0.0, 800.0] # ML num_ch4_a3 = 2.69015E-05 # from methane-comparison.xlsx fsl = fs = 8 rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']...
from drf_yasg import openapi organization_params_in_header = openapi.Parameter( "org", openapi.IN_HEADER, required=True, type=openapi.TYPE_INTEGER ) organization_params = [ organization_params_in_header, ] opportunity_list_get_params = [ organization_params_in_header, openapi.Parameter("name", openapi.I...
""" WSGI config for Pjs 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.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODU...
from datetime import datetime class PanoplyException(Exception): def __init__(self, args=None, retryable=True): super(PanoplyException, self).__init__(args) self.retryable = retryable class IncorrectParamError(Exception): def __init__(self, msg: str = "Incorrect input parametr"): super()...
import numpy import os import sys import sjson if __name__ == "__main__": if sys.version_info < (3, 4): print('Python 3.4 or higher needed to run this script') sys.exit(1) if len(sys.argv) != 2: print('Usage: python gen_bit_rate_stats.py <path/to/input_file.sjson>') sys.exit(1) input_sjson_file = sys.argv[1]...
""" GpuCorrMM-based convolutional layers """ import theano from .. import init from .. import nonlinearities from .base import Layer from .conv import conv_output_length from theano.sandbox.cuda.basic_ops import gpu_contiguous from theano.sandbox.cuda.blas import GpuCorrMM __all__ = [ "MMLayer", "Conv2DMMLayer"...
""" handlers for transactional messaging service """ import json from tornado.queues import Queue from tornado import websocket, gen, web from settings import DEBUG class messaging_server(web.Application): """listener application class""" def __init__(self, q): """listener builder method""" #def...
import sys import os import shlex sys.path.insert(0, os.path.abspath('..')) extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode', 'sphinx.ext.napoleon' ] templates_path = ['_templates'] source_suffix = '.rst' master_doc = ...
from courtesy import courtesy_reply from log_decorator import error_logging @error_logging('na') def response(com, answer, **kwargs): return courtesy_reply(('na',), **kwargs)
import pytest import re import capybara from capybara.exceptions import ElementNotFound class TestAssertAllOfSelectors: @pytest.fixture(autouse=True) def setup_session(self, session): session.visit("/with_html") def test_does_not_raise_if_the_given_selectors_are_on_the_page(self, session): s...
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding unique constraint on 'Category', fields ['name'] db.create_unique(u'website_category', ['name']) def backwards(self, orm):...
import glob import os import numpy as np def load_emebeddings(folder): files = [filename for filename in glob.iglob(folder + '**', recursive=True) if not os.path.isdir(filename)] w2v = {} for file in files: with open(file, "r", encoding='utf8') as lines: for line in lines: ...
import urllib2 from lxml import etree class Scraper(object): # subclass must override this property url = None def scrape(self): stream = self.get_stream() doc = self.get_document(stream) return self.do_scrape(doc) def get_document(self, stream): doc = etree.parse(stream,...
import argparse import os import os.path import sqlite3 import sys import work_recorder COLUMN_MONTH = u'month' COLUMN_HOURS = u'hours' TIME_KEY_MONTH = COLUMN_MONTH TIME_KEY_PROJECT = work_recorder.COLUMN_PROJECT TIME_KEY_HOURS = COLUMN_HOURS def aggregate_work_time(start_day, end_day, conn): u""" Aggregate wo...
from .analyzer import Pep8Analyzer from .issues_data import issues_data analyzers = { 'pep8' : { 'title' : 'Pep-8', 'class' : Pep8Analyzer, 'language' : 'python', 'issues_data' : issues_data, }, }
try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages with open('readme.rst') as reader: long_description = reader.read() setup(name='theape', long_description=long_description, ...
import pygame from ui.utils.interpolator import Interpolator class LcarsWidget(pygame.sprite.DirtySprite): """Base class for all widgets""" def __init__(self, color, pos, size, handler=None): pygame.sprite.DirtySprite.__init__(self) if self.image == None: self.image = pygame.Surface(...
a = (1, 2) b = (1, 3, 5, 7, 8, 11) print a[0] x1 = a[0] y1 = a[1] x1, y1 = a b1, b2, b3, b4, b5, b6 = b print b4 a = 1, 2, 3 print a def f(): return 1, 3 a = f() x, y = f() x = f()[0]
__author__ = 'Varun Nayyar' from Utils.MFCCArrayGen import emotions, speakers, getCorpus from MCMC import MCMCRun from emailAlerter import alertMe def main2(numRuns = 100000, numMixtures = 8, speakerIndex = 6): import time for emotion in emotions: start = time.ctime() Xpoints = getCorpus(emotion...
import sys import os.path import datetime import subprocess import time """ Run snapstream reader script for several files and out a table of match counts. Example: $ python run_on_dates.py eg01china.c 2014-01-01 2014-07-01 """ def validate(date_string): try: datetime.datetime.strptime(date_string,"%Y-%m-%d...
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Address', fields=[ ('id'...
from django.conf import settings from django.forms import SelectMultiple import django_filters from pdc.apps.common.filters import MultiValueFilter, NullableCharFilter from . import models class RPMFilter(django_filters.FilterSet): name = MultiValueFilter() version = MultiValueFilter() epoch ...
from __future__ import ( unicode_literals, absolute_import, print_function, division, ) import socket import pytest import mock from lars import dns def test_from_address(): with mock.patch('tests.test_dns.dns.socket.getnameinfo') as getnameinfo: getnameinfo.return_value = ('9.0.0.0', 0)...
''' mcbd.py - Saves and loads pieces of text from/to the clipboard to/from a shelf type file. Usage: python3 mcbd.py save <keyword> - saves clipboard for keyword. python3 mcbd.py <keyword> - loads to clipboard for keyword. python3 mcbd.py list - loads all keywords to clipboard. python3 mc...
from msrest.pipeline import ClientRawResponse from .. import models class HttpRetry(object): """HttpRetry operations. :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An objec model deseria...
import os import sys sys.path.insert(0, os.path.abspath('../..')) extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.viewcode', ] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = 'tritonschedule' copyright = '2016, tritonschedule' author = 'tritonschedul...
from django.conf.urls import url from .views import ObservationListView, AddObservationView, UploadObservationsView app_name = "observations" urlpatterns = [ url(r"^$", ObservationListView.as_view(), name="observation_list"), url( r"^(?P<observer_id>\d+)/$", ObservationListView.as_view(), ...
import numpy as np from numpy.testing import assert_array_equal from nose.tools import (assert_equal, assert_raises, raises, assert_true, assert_false) try: from nose.tools import assert_is except ImportError: from landlab.testing.tools import assert_is from landlab import RasterModelGri...
resultado = 0 contador = 0 numero = int(input('Digite um numero: ')) while resultado < numero: resultado = (contador -2) * (contador -1) * contador if resultado == numero: print('O numero %d e triangular. %d x %d x %d = %d' % (numero, (contador -2), (contador - 1), contador, numero)) break c...
<<<<<<< HEAD <<<<<<< HEAD """Configuration file parser. A configuration file consists of sections, lead by a "[section]" header, and followed by "name: value" entries, with continuations and such in the style of RFC 822. Intrinsic defaults can be specified by passing them into the ConfigParser constructor as a dictiona...
from typing import Dict, List from service.ws_re.register._base import Register from service.ws_re.register.author import Author from service.ws_re.register.authors import Authors from service.ws_re.register.lemma import Lemma from service.ws_re.register.register_types.volume import VolumeRegister class PublicDomainReg...
from setuptools import setup, find_packages setup( name='bftest_cli', version='0.1a', description='A wrapper to manage docker instances', url='https://github.com/wnormandin/bftest_cli', author='wnormandin', author_email='bill@pokeybill.us', license='MIT', classifiers=[ 'Developme...
from stt_watson.SttWatsonAbstractListener import SttWatsonAbstractListener class SttWatsonLogListener(SttWatsonAbstractListener): def __init__(self): pass def listenHypothesis(self, hypothesis): print "Hypothesis: {0}".format(hypothesis) def listenPayload(self, payload): print(u"Text...
from __future__ import annotations from ..typecheck import * from ..import ui from ..import dap from . import css from .breakpoints_panel import BreakpointsPanel from .input_list_view import InputListView if TYPE_CHECKING: from ..debugger import Debugger class DebuggerPanel(ui.div): on_settings: Callable[[], Any] on...
import time from acris import resource_pool as rp from acris import threaded import queue from datetime import datetime from acris import traced_method traced=traced_method(print, True) class MyResource1(rp.Resource): pass class MyResource2(rp.Resource): pass rp1=rp.ResourcePool('RP1', resource_cls=MyResource1, policy=...
from kaleidoscope.globals import SecType class OrderLeg(object): def __init__(self, quantity, contract): """ This class is an abstraction of an order leg of an option strategy. It holds the information for a single order leg as part of an entire option strategy. """ self.quan...
import pytest from apispec import yaml_utils def test_load_yaml_from_docstring(): def f(): """ Foo bar baz quux --- herp: 1 derp: 2 """ result = yaml_utils.load_yaml_from_docstring(f.__doc__) assert result == {"herp": 1, "derp": 2} @pyt...
import unittest import os os.environ['MIAMI_ENV'] = 'test' import simplejson as json from miami.models import Team, User, Task class ModelsTest(unittest.TestCase): def test_team_toJSON(self): team = Team('Log') team.id = 1 self.assertEquals({'id':1, 'name': 'Log', 'color': '2a33d8'}, team.to...
""" Global Settings """ settings = {} # conf = __import__("django.conf") # settings = conf.conf.settings # settings = {} BROKER_URL = getattr(settings, "BROKER_URL", "amqp://guest@127.0.0.1//") CELERY_TRACKER_STORAGE = getattr(settings, "CELERY_TRACKER_STORAGE", "") CELERY_TRACKER_LOG_LEVEL = getattr(settin...
my_file = open("/tmp/my_file", "w") my_file.write("Test string") my_file.close() my_file = open("/tmp/my_file", "r") content = my_file.read() my_file.close() if (content == "Test string"): print("OK") else: print("KO")
"""Second module, imported as inspect_recursive.a, with no contents""" import inspect_recursive.first as a import sys if sys.version_info >= (3, 7): # For some reason 3.6 says second doesn't exist yet. I get that, it's a # cyclic reference, but that works in 3.7. import inspect_recursive.second as b from in...
from azure.core.exceptions import HttpResponseError, ServiceRequestError import pytest from azure.core.rest import HttpRequest from azure.core.exceptions import StreamClosedError, StreamConsumedError, ResponseNotReadError @pytest.mark.asyncio async def test_iter_raw(client): request = HttpRequest("GET", "/streams/b...
from string import Template from datetime import date bitcoinDir = "./"; inFile = bitcoinDir+"/share/qt/Info.plist" outFile = "KombatKoin-Qt.app/Contents/Info.plist" version = "unknown"; fileForGrabbingVersion = bitcoinDir+"bitcoin-qt.pro" for line in open(fileForGrabbingVersion): lineArr = line.replace(" ",...
import logging import os from django.conf import settings from django.core.management import BaseCommand from django.apps import apps from django.core.management import CommandError from django.template.defaultfilters import slugify from django.template.loader import get_template from django.db import models logger = l...
import urllib.request import pickle import sys import ast try: import variables as v except: class var(): def __init__(self): self.screen = None v = var() import pygame as py class textLabel(py.sprite.Sprite): def __init__(self, text, pos, colour, font, size, variable = False, centre...
from test_framework.test_framework import ComparisonTestFramework from test_framework.util import * from test_framework.mininode import CTransaction, NetworkThread from test_framework.blocktools import create_coinbase, create_block from test_framework.comptool import TestInstance, TestManager from test_framework.script...
from yapsy.IPlugin import IPlugin from manager.message import Message import protocol.control as control import schedule class Time(IPlugin, Message): def __init__(self): IPlugin.__init__(self) Message.__init__(self) self.text = control.SPEED_1 + '\x0B9 \x0B8' + control.NEW_LINE + control.CA...
from django import forms from django.db import models class Births(models.Model): year = models.IntegerField("Year") county = models.CharField("County",max_length=20) mothersAge = models.IntegerField("Mother's Age") mothersEdu = models.CharField("Mother's Education",max_length=50) source = models.UR...
from subprocess import check_output from charmhelpers.core.hookenv import ( config, log, ERROR, ) from charmhelpers.contrib.openstack.utils import os_release def headers_package(): """Ensures correct linux-headers for running kernel are installed, for building DKMS package""" kver = check_output...
""" This TinyMCE widget was copied and extended from this code by John D'Agostino: http://code.djangoproject.com/wiki/CustomWidgetsTinyMCE """ from django import forms from django.conf import settings from django.contrib.admin import widgets as admin_widgets from django.core.urlresolvers import reverse from django.form...
from canvas_sdk import client, utils def make_account_admin(request_ctx, account_id, user_id, role=None, role_id=None, send_confirmation=None, **request_kwargs): """ Flag an existing user as an admin within the account. :param request_ctx: The request context :type request_ctx: :class:RequestCon...
import setuptools from setuptools.command.develop import develop from setuptools.command.install import install class DevelopScript(develop): def run(self): develop.run(self) ntlk_install_packages() class InstallScript(install): def run(self): install.run(self) ntlk_install_packa...
import os, sys; sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) import pytest from lasio import read test_dir = os.path.dirname(__file__) egfn = lambda fn: os.path.join(os.path.dirname(__file__), "examples", fn) def test_open_url(): l = read("https://raw.githubusercontent.com/kinverarity1/" ...
from __future__ import unicode_literals from django.db import models, migrations import django.core.validators class Migration(migrations.Migration): dependencies = [ ('taskmanager', '0001_initial'), ] operations = [ migrations.CreateModel( name='Project', fields=[ ...
import sys import os import argparse base_dir = os.path.dirname(os.path.abspath(__file__)) script_dir = os.path.join(base_dir, 'Common') sys.path.insert(0, script_dir) drop_formant = True import common from polyglotdb.utils import ensure_local_database_running from polyglotdb import CorpusConfig if __name__ == '__main_...
from .base import ItemCollector class BaseProbabilityCollector(ItemCollector): # result_dependencies = (*CountCollector, *FrequencyCollector) def __init__(self, previous_collector_set): super().__init__(previous_collector_set) self.__cached_result = None def get_result(self, collector_set): if self.__cached_re...
import RPi.GPIO as GPIO import time led = 11 GPIO.setmode(GPIO.BOARD) GPIO.setup(led,GPIO.OUT) GPIO.output(led,True) time.sleep(0.5) GPIO.output(led,False) time.sleep(0.5) GPIO.output(led,True) time.sleep(0.5) GPIO.output(led,False) time.sleep(0.5) GPIO.output(led,True) time.sleep(0.2) GPIO.output(led,False) time.sleep...
import os from HTMLParser import HTMLParser from ConfigParser import NoOptionError import nltk from sentence import Sentence from resources import Resources from wordnet_cache import WordnetCache as Wordnet class ReadAndEnrich(object): def __init__(self, conf): self.conf = conf self.enricher = Enric...
""" couchbasekit.fields ~~~~~~~~~~~~~~~~~~~ :website: http://github.com/kirpit/couchbasekit :copyright: Copyright 2013, Roy Enjoy <kirpit *at* gmail.com>, see AUTHORS.txt. :license: MIT, see LICENSE.txt for details. * :class:`couchbasekit.fields.CustomField` * :class:`couchbasekit.fields.ChoiceField` * :class:`couchbas...
from ..base import HaravanResource class ShippingLine(HaravanResource): pass
from gscripts import qtools import sys, os if not os.path.exists("fastqc/"): os.mkdir("fastqc") cmds = [] Sub = qtools.Submitter() for fileName in sys.argv[1:]: fastqc_command = "fastqc -o fastqc %s" %fileName cmds.append(fastqc_command) Sub.job(command_list=cmds, sh_file="runFastqc.sh", job_name="Fastqc", ...
import csv import os import gzip class File: def read(self, path, **kwargs): path = os.path.join(kwargs.get('root_path', ''), path) content_type = kwargs.get('content_type', 'txt') if content_type == 'txt': with file(path, 'r') as f: content = f.read() ...
import json from django.core.serializers.json import DjangoJSONEncoder from instanotifier.fetcher.rss.fetcher import fetch_rss_feed def fetch_rss_url(url): result = fetch_rss_feed(url) return result def write_to_file(filename, data): json_data = json.dumps(data, cls=DjangoJSONEncoder) with open(filename...
''' Work of Cameron Palk ''' import sys import pandas as pd def main( argv ): try: csv_filepath = argv[ 0 ] output_filepath = argv[ 1 ] except IndexError: print( "Error, usage: \"python3 coord_bounds.py <CSV> <output_file>\"" ) return training_data = pd.read_csv( csv_filepath ) training_data[ 'clean_Latitu...
import my_data_file d = my_data_file.my_data print "Hello my name is %s and i am %d years of age and my coolnes is %d " % (d [ 'naam' ], d [ 'age' ], d ['coolheid'])
''' Support for WM_TOUCH messages (Windows platform) ================================================ ''' __all__ = ('WM_MotionEventProvider', 'WM_MotionEvent') import os from kivy.input.providers.wm_common import WNDPROC, \ SetWindowLong_WndProc_wrapper, RECT, POINT, WM_TABLET_QUERYSYSTEMGESTURE, \ QUERYSYSTEM...
from dr import app if __name__ == '__main__': app.run()
def fib_recursive(n): """[summary] Computes the n-th fibonacci number recursive. Problem: This implementation is very slow. approximate O(2^n) Arguments: n {[int]} -- [description] Returns: [int] -- [description] """ # precondition assert n >= 0, 'n must be a positive...
''' spawn º¯Êý»¹¿ÉÓÃÓÚÔÚºǫ́ÔËÐÐÒ»¸ö³ÌÐò. ÏÂÀýÖÐ ¸ø run º¯ÊýÌí¼ÓÁËÒ»¸ö¿ÉÑ¡µÄ mode ²ÎÊý; µ±ÉèÖÃΪ os.P_NOWAIT ʱ, Õâ¸ö½Å±¾²»»áµÈ´ý×Ó³ÌÐò½áÊø, ĬÈÏÖµ os.P_WAIT ʱ spawn »áµÈ´ý×Ó½ø³Ì½áÊø. ÆäËüµÄ±êÖ¾³£Á¿»¹ÓÐ os.P_OVERLAY ,ËüʹµÃ spawn µÄÐÐΪºÍ exec ÀàËÆ, ÒÔ¼° os.P_DETACH , ËüÔÚºǫ́ÔËÐÐ×Ó½ø³Ì, Ó뵱ǰ¿ØÖÆÌ¨ºÍ¼üÅ̽¹µã¸ôÀë. ''...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('exdb', '0005_swap_type_subtype'), ] operations = [ migrations.AddField( model_name='experience', name='temp_subtypes', ...
import uasyncio as asyncio from machine import Pin, I2C import asi2c import ujson i2c = I2C(scl=Pin(0),sda=Pin(2)) # software I2C syn = Pin(5) ack = Pin(4) chan = asi2c.Responder(i2c, syn, ack) async def receiver(): sreader = asyncio.StreamReader(chan) await chan.ready() print('started') for _ in range...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('type_page', '0004_auto_20170711_1241'), ] operations = [ migrations.AddField( model_name='footballtype', name='comments', ...
''' Created on May 20, 2012 @author: Jason Huang ''' if __name__ == '__main__': pass
""" Extend suppliers table with new fields (to be initially populated from declaration data) Revision ID: 940 Revises: 930 Create Date: 2017-08-16 16:39:00.000000 """ revision = '940' down_revision = '930' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column(u'suppliers', sa.Column('registere...
from chainer.iterators import multiprocess_iterator from chainer.iterators import serial_iterator MultiprocessIterator = multiprocess_iterator.MultiprocessIterator SerialIterator = serial_iterator.SerialIterator
from RPSOM import Model from RPSOM.transition_graph import output_graph if __name__=='__main__': alpha_max = [0.1, 0.5, 0.7] alpha_min = [0.01, 0.1, 0.2] sigma_max = [5, 7, 10] sigma_min = [1, 2, 3] epochs = 10 rpsom=Model.RPSOM(epochs, 15, 20, input_file="animal.csv", alpha_max=alpha_max, alpha_min=alpha_min, si...
""" Provide log related functions. You need to Initialize the logger and use the logger to make logs. Example: >>> logger = Initialize() Use logger.level(\*msg) to log like: >>> logger.error("Pickle data writing Failed.") >>> logger.info("Pickle data of ", foo, " written successfully.") The log will be stored into LogF...
import json from collections import abc class ToDictMixin(object): def to_dict(self): """Return a dictionary representation of this object""" return self._traverse('none', self.__dict__) def _traverse(self, key, obj): """Return a dictionary representation of this obj""" if isinst...
from __future__ import print_function from __future__ import absolute_import import re from pyingest.config.utils import u2asc from .default import DefaultParser from .author_names import AuthorNames from .entity_convert import EntityConverter head_dict = {'TITLE:': 'journal', 'NUMBER:': 'volume', 'SUBJECT:': 'title', ...
from __future__ import absolute_import, unicode_literals from config.template_middleware import TemplateResponse from gaecookie.decorator import no_csrf from gaepermission.decorator import login_required from pytz import common_timezones import settings from tekton import router from tekton.gae.middleware.redirect impo...
"Pythonic simple SOAP Client implementation" __author__ = "Mariano Reingart (reingart@gmail.com)" __copyright__ = "Copyright (C) 2008 Mariano Reingart" __license__ = "LGPL 3.0" __version__ = "1.07a" TIMEOUT = 60 import cPickle as pickle import hashlib import logging import os import tempfile import urllib2 from urlpars...
from setuptools import setup, find_packages setup(name='MODEL1310110042', version=20140916, description='MODEL1310110042 from BioModels', url='http://www.ebi.ac.uk/biomodels-main/MODEL1310110042', maintainer='Stanley Gu', maintainer_url='stanleygu@gmail.com', packages=find_packages()...
import json from pprint import pprint import re import urllib import time from geopy import geocoders import Image import os class TwitterJsonParser(): # parser useful fields from file of json tweet objects def get_data_from_tweets(self, input_data): g = geocoders.GoogleV3() tweet_data = [] processed_tweets = [...
from app import mongo_utils from bson import json_util from flask import Blueprint, render_template, request, Response,session import json import time from datetime import datetime from operator import itemgetter mod_main = Blueprint('main', __name__) @mod_main.route('/', methods=['GET']) def index(): project_enabl...
print("In Python, what do you call a 'box' used to store data?") answer = input() if answer == "variable": print(" :) ") else: print(" :( ") print("Thank you for playing!") print(''' Q1 - In Python, what do you call a 'box' used to store data? a - text b - variable c - a shoe box ''') answer = input().lower() if answ...
from scapy.all import * import plotly from datetime import datetime import pandas as pd packets=rdpcap('mypcap.pcap') pktBytes=[] pktTimes=[] for pkt in packets: if IP in pkt: try: pktBytes.append(pkt[IP].len) pktTime=datetime.fromtimestamp(pkt.time) pktTimes.append(pktTime.strftime("%Y-%m-%d %H:%M:%S.%f"))...
import zmq ctx = zmq.Context.instance() server = ctx.socket(zmq.PUSH) server.bind('inproc://foo') clients = [ctx.socket(zmq.PULL) for i in range(10)] poller = zmq.Poller() for client in clients: client.connect('inproc://foo') poller.register(client, zmq.POLLIN) for client in clients: server.send(b'DATA') fo...
""" NPR 2017-01-22 www.npr.org/2017/01/22/511046359/youve-got-to-comb-together-to-solve-this-one The numbers 5,000, 8,000, and 9,000 share a property that only five integers altogether have. Identify the property and the two other integers that have it. """ def is_supervocalic(w): ''' Determine if a word has on...
from datetime import datetime import threading import time from collections import deque import logging logger = logging.getLogger(__name__) class MonitorThread(threading.Thread): """executes a function f with sleep_time intervals in between """ def __init__(self, sleep_time, callback): threading.Th...
""" This script produces quality plots to check that the LFs are fine compared to simumlations. """ import sys import os from os.path import join data_dir = os.environ['DATA_DIR'] import glob from lib_plot import * SNlim = 5 plotDir="/home/comparat/database/Simulations/galform-lightcone/products/emissionLineLuminosityF...
import ast from python_minifier.rename.binding import NameBinding from python_minifier.rename.name_generator import name_filter from python_minifier.rename.util import is_namespace def all_bindings(node): """ All bindings in a module :param node: The module to get bindings in :type node: :class:`ast.AST...
from novaprinter import prettyPrinter from helpers import retrieve_url, download_file from HTMLParser import HTMLParser from urllib import urlencode class torrentz(object): # mandatory properties url = 'https://torrentz.eu' name = 'Torrentz' supported_categories = {'all': ''} trackers_list = ['udp:...
from ._StabData import * from ._AccelData import * from ._MotorData import * from ._GyroData import *
import os, sys import logging from .lib.xmlUtils import XMLParser from .gui.windowextensions import WindowExtensions class Extension: def __init__(self, data_path = None, parent = None): self.data_path=data_path self.parent = parent self.pytrainer_main = parent def getActiveExtensions(self): retorno = [] fo...
''' Created on Dec 31, 2011 @author: fli ''' import logging import base64 import urllib import simplejson from urllib2 import urlopen, URLError, Request from weibonews.utils.decorators import perf_logging _LOGGER = logging.getLogger('weibonews.external') _ACCESS_URL_FORMAT = "http://%s/image/%s/%s" _INFO_URL_FORMAT = "...