code stringlengths 1 199k |
|---|
import json
__author__ = "elishowk@nonutc.fr"
import unittest
import sys
from uuid import uuid4
import httplib
import urllib
import jsonpickle
import json
import tests
from tinasoft.pytextminer import corpora, corpus, document, ngram
class ServerTest(unittest.TestCase):
def setUp(self):
self.headers = {
... |
import models
import scraper
import cfg
from enums import BoardStatus, BooleanText
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
class Akane():
def __init__(self):
self.db_path = cfg.build_db_path(cfg.DB_MAIN_NAME)
self._engine = create_engine(cfg.build_db_path(cfg.DB_MAIN_NAME))
s... |
import sys
filename = sys.argv[1]
f = open(filename, "rb")
print "uint8_t wspr[162] = {",
for line in f:
print str(int(line[5:6])) + ",",
print "};"
f.close() |
import threading
from threading import Thread
import time
import queue
import tkinter
from tkinter import *
from tkinter import tix
from tkinter import ttk
from tkinter import filedialog
from PIL import Image, ImageTk
import mutagenx.id3
from mutagenx.mp3 import MP3
from mutagenx.easyid3 import EasyID3
from mutagenx.id... |
import asyncio
import orm
from models import Users, next_id
import hashlib
loop = asyncio.get_event_loop()
async def test():
await orm.create_pool(loop=loop, user='lichenxi', password='Lichenxi20000110', db='awesome')
for i in range(20):
user_name = 'Robot%s' % str(i)
user_email = '%s@example.co... |
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse
import json
from .models import Person
def persons_list_get_api(request):
"""
List of persons
:param request:
:return: json list of persons
"""
persons = Person.objects.order_by('firs... |
import xml.etree.ElementTree as ET
from autocut.melt import movie2xml
import argparse
from autocut.parse import parse_input
def main():
parser = argparse.ArgumentParser(description='autocut some video')
parser.add_argument('input', default='input.xml', nargs='?')
parser.add_argument('output', default='editl... |
"""Helpers for an Ubuntu application."""
__all__ = [
'make_window',
]
import os
import gtk,logging
from share import share
def get_builder(builder_file_name):
"""Return a fully-instantiated gtk.Builder instance from specified ui
file
:param builder_file_name: The name of the builder file, without ex... |
import os
import glob
import csv # for the ouptut
import operator # for the sorted()
import datetime
import time
datadir = "/obs/lenses_EPFL/Liverpool/"
decompdir = "/home/epfl/tewes/unsaved/liverdecomp/"
print "HELLO LIVERPOOOOOOOOL !"
globfiles = glob.glob(datadir + "????/????????/*.*")
print "I've found", len(glob... |
nombre = "simón"
apellido = "bolívar"
nombre_completo = nombre + " " + apellido
print(nombre_completo.title())
print("Hola " + nombre_completo.title())
mensaje = "Hola " + nombre_completo.title() + ", es un placer."
print(mensaje) |
from django.test import TestCase
from icons_mimetypes import icons
class IconsTestCase(TestCase):
def test_cache(self):
self.assertIn(("64x64", icons.ICON_FOLDER), icons.ICONS_CACHE)
def test_get_icon(self):
# Folder
self.assertEqual(icons.get_icon(None), "/static/mimetypes/64x64/folder.... |
import re
import sickbeard
import generic
from sickbeard.common import Quality
from sickbeard import logger
from sickbeard import tvcache
from sickbeard import show_name_helpers
from sickbeard.common import Overview
from sickbeard.exceptions import ex
from sickbeard import clients
from lib import requests
from bs4 impo... |
import os.path
from PyQt5 import QtGui, QtWidgets
from ouf import shortcuts
from ouf.filemodel.filemodel import FileModel
class PathView(QtWidgets.QWidget):
ROOT_PATH = FileModel.ROOT_PATH
def __init__(self, path, view, parent=None):
super().__init__(parent)
self._create_actions()
self._... |
import os
from twiggy import log
from lockfile import LockTimeout
from lockfile.pidlockfile import PIDLockFile
from taskw.warrior import TaskWarriorBase
from bugwarrior.config import get_taskrc_path, load_config
from bugwarrior.services import aggregate_issues
from bugwarrior.db import synchronize
def pull():
try:
... |
import json
import os
from urllib.request import urlopen
from threading import Thread
import sys
import pytest
from cryptography.hazmat.primitives.asymmetric import rsa, ec
from cryptography.hazmat.backends import default_backend
parent = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
if os.path.isdir(o... |
from django.shortcuts import render, redirect
from decimal import Decimal
from .models import *
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse_lazy, reverse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from... |
"""
/***************************************************************************
QAD Quantum Aided Design plugin
comando ERASE per cancellare oggetti
-------------------
begin : 2013-08-01
copyright : iiiii
email : hhhhh
... |
"""
:mod:`memristor` -- Basic (nonlinear) memristor
-----------------------------------------------
.. module:: memristor
.. moduleauthor:: Carlos Christoffersen
"""
import numpy as np
from cardoon.globalVars import const, glVar
import cardoon.circuit as cir
import cppaddev as ad
class Device(cir.Element):
r"""
... |
import bookmarks, phases
def _nslist(repo):
n = {}
for k in _namespaces:
n[k] = ""
return n
_namespaces = {"namespaces": (lambda *x: False, _nslist),
"bookmarks": (bookmarks.pushbookmark, bookmarks.listbookmarks),
"phases": (phases.pushphase, phases.listphases),
... |
import sys
def ver2appver(version):
try:
versions = map(int, version.split('.'))
return '%02d.%02d' % tuple(versions[:2])
except ValueError:
return '00.00'
if len(sys.argv) < 2:
version = raw_input("new release version? ")
else:
version = sys.argv[1]
versions = map(int, version.s... |
import click
from multiprocessing import Process
from photomgr.zmqutils.push_client import worker
@click.command()
@click.option('--backend_port', default=5560)
def run_test(backend_port):
number_of_workers = 2
for work_num in range(number_of_workers):
Process(target=worker, args=(work_num, backend_port... |
from graph.graph import Graph_Mat
def top_ord(g):
t_order = []
vertices = g.vertices()
#print(vertices)
while vertices != None:
nwnee = node_with_no_entering_edges(g, vertices)
if nwnee == 0:
break
if nwnee == 404:
return "There is a cycle"
else:
t_order.append(nwnee)
g = free_node(g, nwnee)
... |
COMMUNITY_CHEST = [['Advance to Go (collect $200)', [200, 0]],
['Go to jail – go directly to jail – Do not pass Go, do not collect $200', [0,10]],
['You are assessed for street repairs – $40 per house, $115 per hotel', [40,115]],
['Get out of jail free' , []],
... |
"""Methods for working with MIDI data as bytes.
The MIDI file format specification I used can be found here:
http://www.sonicspot.com/guide/midifiles.html
"""
from __future__ import absolute_import, division
from binascii import a2b_hex
from math import log
from struct import pack
from six.moves import range
from mingu... |
import pygrib
import numpy as np
class DataComparator:
def difference(self, forecast_file, observed_file):
grbs_f = pygrib.open(forecast_file)
grbs_o = pygrib.open(observed_file)
temp15_arr_f = grbs_f.select(name='2 metre temperature')[0]
temp15_arr_o = grbs_o.select(name='2 metre temperature')[0]
... |
from django.conf.urls.defaults import *
urlpatterns = patterns('',
# Example:
# (r'^lha/', include('lha.foo.urls')),
url(r'^authors/(?P<auth_id>[a-zA-Z0-9]*)$', 'collection.views.get_author'),
url(r'^authors/?$', 'collection.views.list_authors'),
url(r'^documents/(?P<doc_id>[a-zA-Z0-9]*)$', 'collect... |
from __future__ import (absolute_import, division, print_function)
from mantid.kernel import *
from mantid.api import (WorkspaceProperty,DataProcessorAlgorithm, AlgorithmFactory,
mtd, Progress)
from mantid.simpleapi import *
import numpy as np
class SwapWidths(DataProcessorAlgorithm):
_input... |
import re
from pathlib import Path
import pytest
from autopilot.setup.setup_autopilot import make_alias
def test_make_alias():
fake_launch_path = '/some/fake/path.sh'
def check_profile(profile_file):
"""check if a bash profile has the autopilot alias"""
with open(profile_file, 'r') as pfile:
... |
import logging
from django.conf import settings
from django.core.cache import cache
from django.utils.crypto import constant_time_compare
from rest_framework.authentication import BaseAuthentication
from rest_framework.permissions import BasePermission
from rest_framework.exceptions import AuthenticationFailed
from moh... |
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import * # noqa
from future.utils import PY2
from binascii import hexlify
from nose.tools import eq_, ok_, raises
from ycmd i... |
__author__= "Luis C. Pérez Tato (LCPT) , Ana Ortega (AO_O) "
__copyright__= "Copyright 2016, LCPT, AO_O"
__license__= "GPL"
__version__= "3.0"
__email__= "l.pereztato@ciccp.es, ana.ortega@ciccp.es "
import xc_base
import geom
import xc
from miscUtils import LogMessages as lmsg
class SectionContainer(object):
def __... |
import serial
import time
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=0)
def leerArduino():
while 1:
try:
entrada = str(ser.readline());
datos = entrada[entrada.index("'")+1: entrada.index("\\")]
print(entrada)
#print(datos)
return datos
... |
import pygame
import os, sys, time, math, random
from random import randint
class Menu():
#def __init__(self, title, menuItems, inputSet, choiceSet):
def __init__(self):
self.menuClock = pygame.time.Clock()
self.displayMenu = True
self.titleFont = pygame.font.SysFont("monospace", 100)
self.menuItemFont = pyga... |
'''
Created on Jul 3, 2013
@author: Devon
Defines various gui widgets
'''
import pygame
from pgu import gui
from pyHopeEngine import engineCommon as ECOM
from pyHopeEngine.utilities.textHelper import createText
class BaseTable(gui.Table):
'''A Base Table used to organize other widgets'''
def __init__(self, **pa... |
import kivy
kivy.require('1.8.0')
from kivy.graphics import Color, Rectangle
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
import calendar
import datetime
import gettext
from strings import TextData
from debug impo... |
from __future__ import absolute_import, print_function
from builtins import super # provides Py3-style super() using python-future
from builtins import str
from builtins import map
from os import path
import re
from psychopy.experiment.components import BaseComponent, Param, _translate
__author__ = 'Jeremy Gray'
thisF... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('light_gallery', '0004_lightgallery_thumbnails'),
]
operations = [
migrations.AddField(
model_name='lightgallery',
name='zoomScale... |
'''
This scripts takes care of postprocessing and reorganizing/correcting
data after Molcas scan...
'''
from collections import namedtuple
from argparse import ArgumentParser
import glob
from itertools import repeat
import multiprocessing
import numpy as np
import os
from shutil import copy2
from quantumpropagator impo... |
import rospy
import roslib
import rosbag
import json
import math
import os
class PathWaypointGenerator():
def __init__(self, topics=['/odom']):
rospy.init_node("capra_ai")
self.topics = topics
self.path = rospy.get_param("~input_bag_file")
self.precision = rospy.get_param("~waypoint_... |
import shutil
import sys
import os.path
import unittest
from variety import Util
sys.path.insert(0, os.path.realpath(os.path.join(os.path.dirname(__file__), "..")))
from variety.ImageFetcher import ImageFetcher
class TestImageFetcher(unittest.TestCase):
def test_fetch(self):
target_folder = '/tmp/variety/Im... |
import matplotlib.pyplot as plt
import torch
from torch import nn
from nupic.torch.modules.k_winners import KWinners
from nupic.torch.modules.sparse_weights import SparseWeights
from util import activity_square, count_parameters, get_grad_printer
def topk_mask(x, k=2):
"""
Simple functional version of KWinnersM... |
import os
import re
import subprocess
outfile = 'po/nautilus-renamer.pot'
pattern = re.compile('^([a-zA-Z_]+)\.po$')
files = ['nautilus-renamer.py', 'nautilus-extension/nautilus-renamer.py']
common_args = ['-o', outfile, '--copyright-holder=Thura Hlaing <trhura@gmail.com>', '--package-name=nautilus-renamer',
'--packag... |
from setuptools import setup, find_packages
with open('./README.md', 'r') as f:
long_description = f.read()
meta_package = {}
with open('./gazouilloire/__version__.py') as f:
exec(f.read(), meta_package)
setup(name='gazouilloire',
version=meta_package['__version__'],
description='Twitter stream & se... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ege', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='ege',
name='type',
field=models.IntegerField... |
from __future__ import absolute_import, unicode_literals
from urllib import urlencode
from urlparse import urlparse
from zope.formlib import form
from Products.CustomUserFolder.interfaces import IGSUserInfo
from Products.Five.browser.pagetemplatefile import \
ZopeTwoPageTemplateFile
from Products.GSProfile.profilea... |
"""installation setup file"""
from setuptools import setup
setup(name='pylang',
description='Multiple language installer',
version='0.1.0',
author='Harsha Srinivas',
author_email='95harsha95@gmail.com',
packages=['pylang'],
entry_points={
'console_scripts': ['pylang=pylang:... |
"""
This file is part of OpenSesame.
OpenSesame 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.
OpenSesame is distributed in the hope that it... |
import gflags
import grpc
import logging
import riotwatcher
import sys
import time
import threading
from concurrent import futures
from powerspikegg.rawdata.public import match_pb2
from powerspikegg.rawdata.public import constants_pb2
from powerspikegg.rawdata.fetcher import cache
from powerspikegg.rawdata.fetcher impo... |
import pytest
from cli_config.tag import tag
from utility.nix_error import NixError
def test_tag_create_no_tag(capsys):
with pytest.raises(SystemExit) as _excinfo:
tag.tag("nixconfig", ["create"])
_out, _err = capsys.readouterr()
assert "2" in str(_excinfo.value), "Exception doesn't contain expected... |
import numpy as np
from io import BytesIO
data = "1, 2, 3\n4, 5, 6"
print(np.genfromtxt(BytesIO(data.encode('utf-8')), delimiter=","))
data = " 1 2 3\n 4 5 67\n890123 4"
print(np.genfromtxt(BytesIO(data.encode('utf-8')), delimiter=3))
data = "123456789\n 4 7 9\n 4567 9"
print(np.genfromtxt(BytesIO(data.encod... |
from lizard_security.models import DataSet
from lizard_area.models import AREA_TYPES
from lizard_area.models import Area, AreaLink
from lizard_area.sync_areas import Synchronizer
import logging
default_logger = logging.getLogger(__name__)
def run_sync_area(options, logger=None):
"""
Synchronise 'aanafvoergieden... |
from dgvm.instruction import MemberInstructionWrapper
__author__ = 'salvia'
from ..constraints import ConstraintCollection
from ..utils import Proxy
class DatamodelStates(object):
NORMAL = 0
USER_CHANGING = 1
ENGINE_CHANGING = 2
DESTROYED = 3
class DatamodelMeta(type):
"""
Metaclass for Data... |
Create({
"ConnectionSettings": Create({
"ConnectionString":
'metadata=res://*/StorageModel.csdl|res://*/StorageModel.ssdl|res://*/StorageModel.msl;provider=System.Data.SqlClient;' +
'provider connection string="Data Source=.;Initial Catalog=MetaTweet;Integrated Security=True;Multiple... |
from collections import Counter, deque, defaultdict
class Solution(object):
def checkInclusion(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
n1 = len(s1)
target = Counter(s1)
current = defaultdict(deque)
count = 0
for ... |
"""
model_c.py
by Ted Morin
contains a function to predict 4-year Incident Hypertension risks using Weibull beta coefficients from:
10.7326/0003-4819-148-2-200801150-00005
2008 A Risk Score for Predicting Near-Term Incidence of Hypertension
Framingham Heart Study
translated and adapted from from FHS online risk calcula... |
__all__ = ['HalfSize']
__docformat__ = 'restructuredtext en'
import numpy
from pyctools.core.config import ConfigBool
from pyctools.core.base import Component
class HalfSize(Component):
"""Half-sizing interlace to sequential converter.
This simply rearranges each interlaced frame into two frames of half
the... |
from tuxostat.tosRelayControl import tosRelayControl
trc = tosRelayControl()
option = 0
while option != 3:
print "0) Show relay state"
print "1) Set Relay ON (True)"
print "2) Set Relay OFF (False)"
print "3) EXIT"
option = raw_input("SELECTION: ")
if option == "0":
# show state
... |
from __future__ import unicode_literals
from django.apps import AppConfig
class HighscoresConfig(AppConfig):
name = 'high_scores' |
from random import choice
import cProfile
def amicable_number(number):
results = [1]
for i in range(2, int(number**(0.5))+1):
if number % i == 0:
results.append(i)
results.append(number // i)
return sum(results)
cProfile.run('nrs_to_check = {x: amicable_number(x) for x in ran... |
import re
import traceback
from bs4 import BeautifulSoup
from sickchill import logger, settings
from sickchill.helper.common import convert_size, try_int
from sickchill.oldbeard import tvcache
from sickchill.providers.torrent.TorrentProvider import TorrentProvider
class Provider(TorrentProvider):
def __init__(self)... |
import gcc
from gccutils import CfgPrettyPrinter, get_src_for_loc, check_isinstance
class StatePrettyPrinter(CfgPrettyPrinter):
"""
Various ways of annotating a CFG with state information
"""
def state_to_dot_label(self, state):
result = '<table cellborder="0" border="0" cellspacing="0">\n'
... |
import numpy as np
import bet.postProcess.plotDomains as pDom
import scipy.io as sio
lam_domain = np.array([[.07, .15], [.1, .2]])
param_min = lam_domain[:, 0]
param_max = lam_domain[:, 1]
station_nums = [0, 5] # 1, 6
mdat = sio.loadmat('Q_2D')
Q = mdat['Q']
Q = Q[:, station_nums]
Q_ref = mdat['Q_true']
Q_ref = Q_ref[1... |
class Solution(object):
def pacificAtlantic(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
if not matrix:
return []
r = len(matrix); c = len(matrix[0])
flag = [[0] * c for i in xrange(r)]
dirs = [(-1,0),(0,1),(... |
""" XVM (c) www.modxvm.com 2013-2015 """
def initialize():
return _contacts.initialize()
def isAvailable():
return _contacts.is_available
def getXvmContactData(uid):
return _contacts.getXvmContactData(uid)
def setXvmContactData(uid, value):
return _contacts.setXvmContactData(uid, value)
from random impo... |
"""
"""
__author__='Xun Li <xunli@asu.edu>'
__all__=[]
from lisa import *
from weights import *
import ctypes
import numpy as np
import os
def call_lisa(data, weight_file, numPermutations):
n = len(data)
# validate data and weight_file
o = open(weight_file)
firstline = o.readline().strip()
if firstl... |
import os
import sys
sys.path.insert(1, os.path.dirname(__file__) + '/../..')
extensions = [
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'cd2cloud'
copyright = u'2014-2015, cd2cloud Devel Team'
cd2cloud_version = "0.0.1"
version = cd2cloud_version.split('-')[0]
release = cd2... |
"""
==================
tao.workflow
==================
Helper that saves a job from form data (in UI Holder). See :class:`tao.ui_modules.UIModulesHolder`
"""
from tao import models, time
from tao.datasets import dataset_get
from tao.xml_util import create_root, find_or_create, child_element, xml_print, NAMESPACE
def sa... |
"""
Created on Wed Nov 16 21:45:07 2016
@author: Rik van der Vlist
"""
from scipy.io import wavfile
import scipy.signal as sg
import matplotlib.pyplot as plt
import numpy as np
filename_ref='clean.wav'
filename_wsola_lpc='wsola speed1 errordomain.wav'
filename_wsola='wsola speed1 WSOLA.wav'
[fs_r, reference] = wavfile.... |
"""
==================
ModEM
==================
"""
import os
import numpy as np
from matplotlib import pyplot as plt, colorbar as mcb
from matplotlib.colors import Normalize
from matplotlib.ticker import MultipleLocator
from mtpy.utils import exceptions as mtex
from mtpy.modeling.modem import Data
from mtpy.modeling.m... |
from glob import glob
NPROCS=4 # number of processors used in 1 SPECFEM3D solve
total_processors = 4 # total number of processors available
number_of_events=len(glob('../input_files/CMTSOLUTION_files/*'))
zero_line = -1.0 # kernels are zeroed-out for z > zero_line (i.e. no model update there)
data_path = '/export/data/... |
"""
Separate surfaces by normal
-
Provided by Honeybee 0.0.57
Args:
_geometry: Brep geometries
_maxUpDecAngle_: Maximum normal declination angle from ZAxis that should be still considerd up
_maxDownDecAngle_: Maximum normal declination angle from ZAxis that should be still considerd down
... |
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
exce... |
"""
test_shipping
Test Shipping Methods
:copyright: © 2011-2013 by Openlabs Technologies & Consulting (P) Limited
:license: GPLv3, see LICENSE for more details.
"""
import os
import sys
import json
from decimal import Decimal
from urllib import urlencode
DIR = os.path.abspath(os.path.normpath(os.path.jo... |
from __future__ import unicode_literals
from io import BytesIO
from flask import jsonify, request, session
from indico.modules.events.timetable.forms import TimetablePDFExportForm
from indico.modules.events.timetable.legacy import TimetableSerializer
from indico.modules.events.timetable.views import WPDisplayTimetable
... |
import xml.parsers.expat
import cStringIO
import gzip as gzipm
try:
import bz2 as bz2m
except ImportError:
pass
from math import floor, atan, sin, cos, pi
import os
import hashlib
try:
# lxml is used for DTD validation
# for server-side applications, it is recommended to install it
# for desktop app... |
from __future__ import print_function, unicode_literals
import datetime
import os
import re
import six
import sickbeard
from sickbeard import helpers, logger
from sickbeard.metadata import generic
from sickrage.helper.common import dateFormat, replace_extension
from sickrage.helper.encoding import ek
from sickrage.help... |
import sys
import os
extensions = []
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'subrosa'
copyright = u'2014, Konrad Wąsowicz'
version = '0.3'
release = '0.3'
exclude_patterns = []
pygments_style = 'sphinx'
html_theme = 'default'
html_static_path = ['_static']
htmlhelp_basena... |
from urllib.request import urlopen # urllib2/3 in python3 is now inside 'urllib.request'
import ujson as json # pip install ujson (Visual C++ 14 Redistributable required)
import os, sys
import os.path as path
import telegram
import time
import urllib.request # We use this module f... |
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django.core.management import call_command
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from dash.models import DashboardSettings, DashboardWorkspace, DashboardE... |
import urllib2
import urllib
url = 'https://webservice.paymentxp.com/wh/webhost.aspx?MerchantID=10012&MerchantKey=c22a63ee-2e7a-4ace-96ac-0958dc8d953f&TransactionType=CreditCardCaptureOnly&TransactionAmount=1.00&AuthCode=123456&CardNumber=4111111111111111&ExpirationDateMMYY=1218'
request = urllib2.Request(url)
response... |
from django.shortcuts import render
def index(request):
return render(request, 'adminlte/index.html', dict())
def show_html(request, path):
return render(request, 'adminlte/' + path, dict()) |
AGO_LIFX_VERSION = '0.0.1'
__author__ = 'Joakim Lindbom'
__copyright__ = 'Copyright 2013-2016, Joakim Lindbom'
__date__ = '2016-11-19'
__credits__ = ['Joakim Lindbom', 'The ago control team']
__license__ = 'GPL Public License Version 3'
__maintainer__ = 'Joakim Lindbom'
__email__ = 'Joakim.Lindbom@gmail.com'
__status__... |
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
stack = dict()
for i in nums:
if i not in stack.keys():
stack[i] = 1
else:
stack[i] += 1
max = 0
... |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
import sys
import traceback
from django.shortcuts import render_to_response
from django.template import RequestContext, loader
from django.http import (HttpResponse, HttpResponseNotFound,
... |
import os
import click
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
from strephit.web_sources_corpus.preprocess_corpus import preprocess_corpus
from strephit.web_sources_corpus import run_all, archive_org
@click.command()
@click.argument('spider-name', nargs=-1, requir... |
class BaseAssemblyError(Exception):
"""
Base class to handle all known exceptions.
Specific exceptions are implemented as sub classes of :py:class:`DBAssemblyError`.
Attributes
* :attr:`message`
Exception message text
"""
def __init__(self, message, *args, **kwargs):
self.mes... |
from __future__ import print_function
import logging
import numba
import numpy as np
import os.path
try:
import Queue
except ImportError:
import queue
import sys
import threading
from multiprocessing import cpu_count
from multiprocessing.dummy import Pool
from numpy.fft import fftshift
from pyem import mrc
from... |
'''
Mepinta
Copyright (c) 2011-2012, Joaquin G. Duo
This file is part of Mepinta.
Mepinta 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.
Mep... |
__all__ = ["asm_to_binary", "dec_to_binary"] |
from functools import wraps
from flask import request
from community_share.authorization import get_requesting_user
from community_share.routes import base_routes
def api_path(path, query_args):
query = '&'.join(['{}={}'.format(name, query_args[name]) for name in query_args])
return '{base_url}rest/{path}/{quer... |
from django.db import models
from django.utils.functional import cached_property
from django.contrib.staticfiles.storage import staticfiles_storage
from japper.monitoring.plugins.models import AlertSinkBase
from japper.monitoring.status import Status
from japper.monitoring.search import build_search_url
from japper.uti... |
"""
Tabulate some simple alignment stats from sam.
"""
import argparse
import sys
import numpy as np
import pandas as pd
import warnings
from collections import OrderedDict
import re
parser = argparse.ArgumentParser(
description="""Summarise output of `stats_from_bam`.""",
formatter_class=argparse.Argum... |
from __future__ import print_function
import base64
import logging
import os
import pytest
import unittest
from six.moves.urllib.parse import urlencode, urlunsplit
from six.moves.urllib.request import Request as BaseRequest
from six.moves.urllib.request import urlopen
from six import binary_type, iteritems
from hyper i... |
"""
Test the Studio help links.
"""
from nose.plugins.attrib import attr
from unittest import skip
from common.test.acceptance.fixtures.course import XBlockFixtureDesc
from common.test.acceptance.tests.studio.base_studio_test import StudioCourseTest, ContainerBase
from common.test.acceptance.pages.studio.index import D... |
from essentia_test import *
import os
def writeFile(str, filename):
resultF = open(filename, 'w')
resultF.write(str)
resultF.close()
class TestYamlInput(TestCase):
def testSingleKeySingleReal(self):
testFile = 'foo: 1.0'
writeFile(testFile, 'testfile')
p = YamlInput(filename='tes... |
from . import event_multiple_registration |
from __future__ import absolute_import, unicode_literals
import json
import pytz
import six
import xml.etree.ElementTree as ET
from datetime import datetime, timedelta
from django.contrib.auth.models import Group
from django.contrib.gis.geos import GEOSGeometry
from django.core.urlresolvers import reverse
from django.d... |
from . import models |
import json
from bson.objectid import ObjectId
class Encoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, ObjectId):
return str(obj)
else:
return obj
def decoder(dct):
for k, v in dct.items():
if '_id' in dct:
try:
dct[... |
'''
Aggregation operator that creates an MOT collection that only contains valid
first use dates. No NULL values. This allows use to accurately calculate the age
of a vehicle.
@author: jdrumgoole
'''
from agg import Agg
def dataCleanse( collection, limit=None ):
#
# Create a collection of clean vehicles with go... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.