code stringlengths 1 199k |
|---|
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
int_or_none,
unescapeHTML,
ExtractorError,
xpath_text,
)
class BiliBiliIE(InfoExtractor):
_VALID_URL = r'http://www\.bilibili\.(?:tv|com)/video/av(?P<id>\d+)(?:/i... |
{% if cookiecutter.use_celery == "y" %}
from __future__ import absolute_import
import os
from celery import Celery
from django.apps import AppConfig
from django.conf import settings
if not settings.configured:
# set the default Django settings module for the 'celery' program.
os.environ.setdefault("DJANGO_SETTI... |
from __future__ import print_function
import mxnet as mx
import numpy as np
from timeit import default_timer as timer
from dataset.testdb import TestDB
from dataset.iterator import DetIter
class Detector(object):
"""
SSD detector which hold a detection network and wraps detection API
Parameters:
-------... |
import os
import shutil
import stat
import tempfile
import threading
import time
import unittest
from collections import namedtuple
from pyspark import SparkConf, SparkFiles, SparkContext
from pyspark.testing.utils import ReusedPySparkTestCase, PySparkTestCase, QuietTest, SPARK_HOME
class CheckpointTests(ReusedPySparkT... |
import os, sys
from django.core.management import execute_manager
sys.path.insert(0, os.path.abspath('./../../'))
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears y... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import re
import json
from itertools import chain
from ansible.module_utils._text import to_bytes, to_text
from ansible.module_utils.network.common.utils import to_list
from ansible.plugins.cliconf import CliconfBase, enable_mode
cl... |
import sys
import platform
import twisted
import scrapy
from scrapy.command import ScrapyCommand
class Command(ScrapyCommand):
def syntax(self):
return "[-v]"
def short_desc(self):
return "Print Scrapy version"
def add_options(self, parser):
ScrapyCommand.add_options(self, parser)
... |
from __future__ import absolute_import, unicode_literals
import collections
import sys
import unittest
from build_swift import shell
import six
from six import StringIO
from .. import utils
try:
# Python 3.4
from pathlib import Path
except ImportError:
pass
try:
# Python 3.3
from unittest import moc... |
{
'name': 'Account Journal Always Check Date',
'version': '0.1',
'category': 'Accounting & Finance',
'license': 'AGPL-3',
'summary': 'Option Check Date in Period always active on journals',
'description': """
Check Date in Period always active on Account Journals
================================... |
"""
***************************************************************************
rasterize_over.py
---------------------
Date : September 2013
Copyright : (C) 2013 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
*********************************... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = """
---
module: cp_mgmt_address_range_facts
short_description: Get address-ra... |
from itertools import chain
from pyprint.ClosableObject import ClosableObject
from coalib.parsing.StringProcessing import escape
from coalib.settings.Section import Section
class ConfWriter(ClosableObject):
def __init__(self,
file_name,
key_value_delimiters=('=',),
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: azure_rm_keyvaultsecret
version_added: 2.5
short_description: U... |
import htmlentitydefs
import re, string, sys
import mimetools, StringIO
import ElementTree
AUTOCLOSE = "p", "li", "tr", "th", "td", "head", "body"
IGNOREEND = "img", "hr", "meta", "link", "br"
if sys.version[:3] == "1.5":
is_not_ascii = re.compile(r"[\x80-\xff]").search # 1.5.2
else:
is_not_ascii = re.compile(e... |
"""
pygments.lexers.rdf
~~~~~~~~~~~~~~~~~~~
Lexers for semantic web and RDF query languages and markup.
:copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, bygroups, default
from pygments.toke... |
from boto.regioninfo import RegionInfo, get_regions
from boto.regioninfo import connect
def regions():
"""
Get all available regions for the AWS CloudHSM service.
:rtype: list
:return: A list of :class:`boto.regioninfo.RegionInfo`
"""
from boto.cloudhsm.layer1 import CloudHSMConnection
retur... |
{
'name' : 'Account Tax Cash Basis',
'version' : '1.1',
'author' : 'OpenERP SA',
'summary': 'Allow to have cash basis on tax',
'sequence': 4,
'description': """
Add an option on tax to allow them to be cash based, meaning that during reconciliation, if there is a tax with
cash basis invo... |
from django.contrib.gis.db.models import GeometryField
from django.contrib.gis.db.models.functions import Distance
from django.contrib.gis.measure import (
Area as AreaMeasure, Distance as DistanceMeasure,
)
from django.db.utils import NotSupportedError
from django.utils.functional import cached_property
class Base... |
import logging
import urllib
import urllib2
from google.appengine.api import urlfetch
from django.conf import settings
from common import exception
from common.protocol import base
class _DevRpc(object):
def get_result(self):
pass
class PshbConnection(base.Connection):
def __init__(self, endpoint):
self.end... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['deprecated'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: kubernetes
version_added: "2.1"
deprecated:
removed_in: "2... |
from __future__ import absolute_import |
from LogAnalyzer import Test,TestResult
import DataflashLog
from VehicleType import VehicleType
import collections
class TestPitchRollCoupling(Test):
'''test for divergence between input and output pitch/roll, i.e. mechanical failure or bad PID tuning'''
# TODO: currently we're only checking for roll/pitch outs... |
"""
Nontransitive dice in Google CP Solver.
From
http://en.wikipedia.org/wiki/Nontransitive_dice
'''
A set of nontransitive dice is a set of dice for which the relation
'is more likely to roll a higher number' is not transitive. See also
intransitivity.
This situation is similar to that in the game Rock... |
"""Tests for tf.GrpcServer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.client import session
from tensorflow.python.framework import errors_impl
from tensorflow.python.framework import test_util
from tensorflow.python.ops import... |
import logging
__author__ = 'rolandh'
from pymongo import Connection
import time
from datetime import datetime
from saml2 import time_util
from saml2.cache import ToOld
from saml2.time_util import TIME_FORMAT
logger = logging.getLogger(__name__)
class Cache(object):
def __init__(self, server=None, debug=0, db=None)... |
import json
from wtforms.fields import TextAreaField
from shapely.geometry import shape, mapping
from .widgets import LeafletWidget
from sqlalchemy import func
import geoalchemy2
class JSONField(TextAreaField):
def _value(self):
if self.raw_data:
return self.raw_data[0]
if self.data:
... |
xkcd_rgb = {'acid green': '#8ffe09',
'adobe': '#bd6c48',
'algae': '#54ac68',
'algae green': '#21c36f',
'almost black': '#070d0d',
'amber': '#feb308',
'amethyst': '#9b5fc0',
'apple': '#6ecb3c',
'apple green': '#76cd26',
... |
from __future__ import division, absolute_import, print_function
__all__ = ['logspace', 'linspace']
from . import numeric as _nx
from .numeric import result_type, NaN
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None):
"""
Return evenly spaced numbers over a specified interval.
Retu... |
from django.urls import path, re_path
from . import views
urlpatterns = [
path('noslash', views.empty_view),
path('slash/', views.empty_view),
path('needsquoting#/', views.empty_view),
# Accepts paths with two leading slashes.
re_path(r'^(.+)/security/$', views.empty_view),
] |
from __future__ import unicode_literals
import cgi
import codecs
import logging
import sys
from io import BytesIO
from threading import Lock
import warnings
from django import http
from django.conf import settings
from django.core import signals
from django.core.handlers import base
from django.core.urlresolvers import... |
nplurals=2 # Afrikaans language has 2 forms:
# 1 singular and 1 plural
get_plural_id = lambda n: int(n != 1) |
"""Python 2/3 compatibility definitions.
These are used by the rest of Elpy to keep compatibility definitions
in one place.
"""
import sys
if sys.version_info >= (3, 0):
PYTHON3 = True
from io import StringIO
def ensure_not_unicode(obj):
return obj
else:
PYTHON3 = False
from StringIO import ... |
import errno
from http import client
import io
import os
import array
import socket
import unittest
TestCase = unittest.TestCase
from test import support
here = os.path.dirname(__file__)
CERT_localhost = os.path.join(here, 'keycert.pem')
CERT_fakehostname = os.path.join(here, 'keycert2.pem')
CACERT_svn_python_org = os.... |
import sys
import unittest
from libcloud.utils.py3 import httplib
from libcloud.loadbalancer.base import Member, Algorithm
from libcloud.loadbalancer.drivers.brightbox import BrightboxLBDriver
from libcloud.loadbalancer.types import State
from libcloud.test import MockHttpTestCase
from libcloud.test.secrets import LB_B... |
import sqlalchemy as sa
from sqlalchemy import orm
from neutron.db import model_base
class RouterRule(model_base.BASEV2):
id = sa.Column(sa.Integer, primary_key=True)
source = sa.Column(sa.String(64), nullable=False)
destination = sa.Column(sa.String(64), nullable=False)
nexthops = orm.relationship('Nex... |
from geopy.point import Point
class Location(object):
def __init__(self, name="", point=None, attributes=None, **kwargs):
self.name = name
if point is not None:
self.point = Point(point)
if attributes is None:
attributes = {}
self.attributes = dict(attributes,... |
from openerp import tools
from openerp.osv import fields,osv
class report_lunch_order(osv.osv):
_name = "report.lunch.order.line"
_description = "Lunch Orders Statistics"
_auto = False
_rec_name = 'date'
_columns = {
'date': fields.date('Date Order', readonly=True, select=True),
'yea... |
"""Execute shell commands via os.popen() and return status, output.
Interface summary:
import commands
outtext = commands.getoutput(cmd)
(exitstatus, outtext) = commands.getstatusoutput(cmd)
outtext = commands.getstatus(file) # returns output of "ls -ld file"
A trailing newline is removed f... |
def build_models(payment_class):
return [] |
from matplotlib.numerix import which
if which[0] == "numarray":
from numarray.linear_algebra.mlab import *
elif which[0] == "numeric":
from MLab import *
elif which[0] == "numpy":
try:
from numpy.oldnumeric.mlab import *
except ImportError:
from numpy.lib.mlab import *
else:
raise Runt... |
from __future__ import (absolute_import, division)
__metaclass__ = type
import json
import os
import shutil
import tempfile
import pytest
from units.compat.mock import patch, MagicMock
from ansible.module_utils._text import to_bytes
from ansible.module_utils import basic
class TestAnsibleModuleTmpDir:
DATA = (
... |
from __future__ import unicode_literals
from django.db import router
from .base import Operation
class SeparateDatabaseAndState(Operation):
"""
Takes two lists of operations - ones that will be used for the database,
and ones that will be used for the state change. This allows operations
that don't supp... |
xs = 1<caret>, 2 |
from __future__ import unicode_literals
import datetime
import unittest
from django.apps.registry import Apps
from django.core.exceptions import ValidationError
from django.db import models
from django.test import TestCase
from .models import (
CustomPKModel, FlexibleDatePost, ModelToValidate, Post, UniqueErrorsMod... |
try:
1 // 0
except ZeroDivisionError:
print("ZeroDivisionError")
try:
1 % 0
except ZeroDivisionError:
print("ZeroDivisionError") |
class <caret>A(B
pass |
def foo(bar):
""" @param """ |
class Foo:
@property
def bar(self):
import warnings
warnings.warn("this is deprecated", DeprecationWarning, 2)
foo = Foo()
foo.<warning descr="this is deprecated">bar</warning> |
""" Python Character Mapping Codec iso8859_5 generated from 'MAPPINGS/ISO8859/8859-5.TXT' with gencodec.py.
"""#"
import codecs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_table)
def decode(self,input,errors='strict'):
ret... |
DATE_FORMAT = 'j. E Y.'
TIME_FORMAT = 'H:i:s'
DATETIME_FORMAT = 'j. E Y. H:i'
YEAR_MONTH_FORMAT = 'F Y.'
MONTH_DAY_FORMAT = 'j. F'
SHORT_DATE_FORMAT = 'j.m.Y.'
SHORT_DATETIME_FORMAT = 'j.m.Y. H:i'
FIRST_DAY_OF_WEEK = 1
DATE_INPUT_FORMATS = (
'%Y-%m-%d', # '2006-10-25'
'%d.%m.%Y.', '%d.%m.%y.... |
"""
Views and functions for serving static files. These are only to be used
during development, and SHOULD NOT be used in a production setting.
"""
from __future__ import unicode_literals
import mimetypes
import os
import stat
import posixpath
import re
try:
from urllib.parse import unquote
except ImportError: ... |
"""
Iterator based sre token scanner
"""
import sre_parse, sre_compile, sre_constants
from sre_constants import BRANCH, SUBPATTERN
from re import VERBOSE, MULTILINE, DOTALL
import re
__all__ = ['Scanner', 'pattern']
FLAGS = (VERBOSE | MULTILINE | DOTALL)
class Scanner(object):
def __init__(self, lexicon, flags=FLAG... |
"""
Check that all of the certs on all service endpoints validate.
"""
import unittest
from tests.integration import ServiceCertVerificationTest
import boto.swf
class SWFCertVerificationTest(unittest.TestCase, ServiceCertVerificationTest):
swf = True
regions = boto.swf.regions()
def sample_service_call(self... |
"""Tk user interface implementation for namebench."""
__author__ = 'tstromberg@google.com (Thomas Stromberg)'
import datetime
import os
import Queue
import sys
import threading
import tkFont
from Tkinter import *
import tkMessageBox
import traceback
import addr_util
import base_ui
import conn_quality
import nameserver_... |
data = (
'Yao ', # 0x00
'Yu ', # 0x01
'Chong ', # 0x02
'Xi ', # 0x03
'Xi ', # 0x04
'Jiu ', # 0x05
'Yu ', # 0x06
'Yu ', # 0x07
'Xing ', # 0x08
'Ju ', # 0x09
'Jiu ', # 0x0a
'Xin ', # 0x0b
'She ', # 0x0c
'She ', # 0x0d
'Yadoru ', # 0x0e
'Jiu ', # 0x0f
'Shi ', # 0x10
'Tan ... |
from eforge import plugins
from eforge.models import Project
from eforge.decorators import project_page, has_project_perm, user_page, group_page
from django.shortcuts import get_object_or_404, render_to_response, redirect
from django.http import HttpResponse
from django.template import RequestContext
@project_page
def ... |
"""Host Reservation DHCPv6"""
import pytest
import misc
import srv_msg
import srv_control
@pytest.mark.v6
@pytest.mark.host_reservation
@pytest.mark.kea_only
@pytest.mark.pgsql
def test_v6_host_reservation_duplicate_reservation_duid():
misc.test_setup()
srv_control.config_srv_subnet('3000::/30', '3000::1-3000::... |
import textwrap
from unittest import mock
from unittest.mock import call
import pytest
from flask_forecaster.config import Config, ConfigError, parse_vcap, require
@mock.patch('flask_forecaster.config.os.getenv')
def test_require_success(getenv):
getenv.return_value = 'world'
assert require('hello') == 'world'
... |
"""
Collection of astronomy-related functions and utilities
"""
__version__ = '0.1.1' |
from collections import defaultdict
from operator import itemgetter
import re
def isRealRoom(name, checksum):
if len(checksum) != 5:
raise Exception
totals = defaultdict(int)
for c in name:
if c != '-':
totals[c] += 1
pairs = zip(totals.keys(), totals.values())
alphaPairs... |
from typing import List
class Solution:
def arrayStringsAreEqualV1(self, word1: List[str], word2: List[str]) -> bool:
return "".join(word1) == "".join(word2)
def arrayStringsAreEqualV2(self, word1: List[str], word2: List[str]) -> bool:
def generator(word: List[str]):
for s in word:
... |
import math
from pyb import DAC, micros, elapsed_micros
def tone1(freq):
t0 = micros()
dac = DAC(1)
while True:
theta = 2*math.pi*float(elapsed_micros(t0))*freq/1e6
fv = math.sin(theta)
v = int(126.0 * fv) + 127
#print("Theta %f, sin %f, scaled %d" % (theta, fv, v))
#... |
import sys
import math
import datetime
def readline():
return sys.stdin.readline().strip()
def main():
while True:
n_readings = int(readline())
if n_readings == 0:
break
meter_readings = []
for i in range(n_readings):
reading = [int(x) for x in readline().... |
import DeepFried2 as df
from .. import dfext
def mknet(mkbn=lambda chan: df.BatchNormalization(chan, 0.95)):
kw = dict(mkbn=mkbn)
net = df.Sequential(
# -> 128x48
df.SpatialConvolutionCUDNN(3, 64, (7,7), border='same', bias=None),
dfext.resblock(64, **kw),
df.PoolingCUDNN((2,2)),... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ..proto.summary_pb2 import Summary
from ..proto.summary_pb2 import SummaryMetadata
from ..proto.tensor_pb2 import TensorProto
from ..proto.tensor_shape_pb2 import TensorShapeProto
import os
import time
impo... |
def addition(x,y):
return int(x)+int(y)
def subtraction (x,y) :
return int(x) -int(y)
def multiplication (x,y) :
return int(x) *int(y)
def module (x,y) :
return int(x) %int(y)
a=raw_input("Enter variable a: ")
b=raw_input("Enter variable b: ")
print addition (a,b)
print subtraction (a,b)
print multiplic... |
from datetime import datetime
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models, tools
_INTERVALS = {
"hours": lambda interval: relativedelta(hours=interval),
"days": lambda interval: relativedelta(days=interval),
"weeks": lambda interval: relativedelta(days=7 * interval)... |
import sys # For getting generic exception info
import datetime # For getting time deltas for timeouts
import time # For sleep
import json # For packing ros message properties
import random # For picking robot responses and shuffling answer options
import logging # Log messages
import Queue # for queuing messages for t... |
import tornado.web
import forms
import config
import io
class Index(tornado.web.RequestHandler):
"""
Returns the index page.
"""
def get(self):
form = forms.RecomputeForm()
recomputations_count = io.get_recomputations_count()
latest_recomputations = io.load_all_recomputations(con... |
from __future__ import unicode_literals
import pytest
from hyputils.memex.util import markdown
class TestRender(object):
def test_it_renders_markdown(self):
actual = markdown.render("_emphasis_ **bold**")
assert "<p><em>emphasis</em> <strong>bold</strong></p>\n" == actual
def test_it_ignores_mat... |
import typing as t
import contextlib
import pytest
import diana
State = t.NewType("State", dict)
AsyncState = t.NewType("AsyncState", dict)
async def no_op():
pass
@pytest.fixture
def module():
class ContextModule(diana.Module):
def __init__(self):
self.state: State = {"count": 0}
@d... |
from django.db import models
from django_hstore import hstore
class Place(models.Model):
osm_type = models.CharField(max_length=1)
osm_id = models.IntegerField(primary_key=True)
class_field = models.TextField(db_column='class') # Field renamed because it was a Python reserved word.
type = models.TextFie... |
from rest_framework.decorators import api_view
from django.shortcuts import get_object_or_404
from rest_framework.response import Response
from rest_framework import status
from .models import Person
from .serializers import PersonSerializer
@api_view(['GET', 'DELETE', 'PUT'])
def get_delete_update_person(request, fstn... |
from django.conf import settings
""" Your GSE API key """
GOOGLE_SEARCH_API_KEY = getattr(settings, 'GOOGLE_SEARCH_API_KEY', None)
""" The ID of the Google Custom Search Engine """
GOOGLE_SEARCH_ENGINE_ID = getattr(settings, 'GOOGLE_SEARCH_ENGINE_ID', None)
""" The API version. Defaults to 'v1' """
GOOGLE_SEARCH_API_VE... |
'''
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the word list
For example,
Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot... |
""" generator.py: Contains the Generator class. """
import random
import copy
import graphics
from helpers import *
counts = {1: 1, 2: 1, 3: 2, 4: 7, 5: 18, 6: 60}
class Generator:
""" A class for generating polyominoes. Call the generate function with the
polyomino order wanted. Please Note: This class has not... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import io
import unittest
from prov.model import *
from prov.dot import prov_to_dot
from prov.serializers import Registry
from prov.tests.examples import primer_example, primer_example_alternate
EX_NS = Namespac... |
"""
sphinx.ext.napoleon.docstring
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Classes for docstring parsing and formatting.
:copyright: Copyright 2007-2017 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import collections
import inspect
import re
from .iterators import modify_iter
im... |
from pygame.sprite import DirtySprite
from pygame import draw
class BaseWidget(DirtySprite):
"""clase base para todos los widgets"""
focusable = True
# si no es focusable, no se le llaman focusin y focusout
# (por ejemplo, un contenedor, una etiqueta de texto)
hasFocus = False
# indica si el wid... |
"""
Utilities related to bgp data types and models.
"""
import logging
import socket
from ryu.lib.packet.bgp import (
BGPUpdate,
RF_IPv4_UC,
RF_IPv6_UC,
RF_IPv4_VPN,
RF_IPv6_VPN,
RF_L2_EVPN,
RF_RTC_UC,
RouteTargetMembershipNLRI,
BGP_ATTR_TYPE_MULTI_EXIT_DISC,
BGPPathAttributeMul... |
from mattermost_bot.bot import Bot, PluginsManager
from mattermost_bot.mattermost import MattermostClient
from mattermost_bot.dispatcher import MessageDispatcher
import bot_settings
class LocalBot(Bot):
def __init__(self):
self._client = MattermostClient(
bot_settings.BOT_URL, bot_settings.BOT_T... |
import numpy as np
import cv2
import cv2.cv as cv
im = cv2.imread('pic.png')
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
invert = 255 - imgray
cv2.imwrite('/Users/asafvaladarsky/Documents/pic1.png', invert)
contours, hierarchy = cv2.findContours(invert,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for i in range(0, len(conto... |
"""
moveit_attached_object_demo.py - Version 0.1 2014-01-14
Attach an object to the end-effector and then move the arm to test collision avoidance.
Created for the Pi Robot Project: http://www.pirobot.org
Copyright (c) 2014 Patrick Goebel. All rights reserved.
This program is free software; you can... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from os import listdir
files = listdir('./data/plots/')
colorarray = np.random.random_sample((10000, 3))
for f in files:
size = int(f.split('-')[0])
x, y, c = np.loadtxt('./data/plots/' + f, unpack=True)
fig = plt.figure... |
from pypermissions.permission import PermissionSet
def _prepare_runtime_permission(self, perm=None, runkw=None, args=None, kwargs=None):
"""This function parses the provided string arguments to decorators into the actual values for use when the
decorator is being evaluated. This allows for permissions to be cre... |
import sys
import os
import subprocess
import time
filename = sys.argv[1]
print("extracting " + filename)
p = subprocess.Popen(["unzip", filename, "-dintro"], stdout=subprocess.PIPE)
p.communicate()
p = subprocess.Popen(["php","-f","uploadtodb.php","intro/courses.csv","courses"],stdout=subprocess.PIPE, universal_newlin... |
'''
http://projecteuler.net/problem=1
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
'''
from projecteuler import calctime
n, a, b = 100000, 3, 5
def v1():
summ = 0
for i in... |
"""
file: cas_manager.py
authors: Christoffer Rosen <cbr4830@rit.edu>
date: Jan. 2014
description: This module contains the CAS_manager class, which is a thread that continously checks if there
is work that needs to be done. Also contains supporting classes of Worker and ThreadPool used by
the CAS_Manager.
"""
... |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
MAIL_SERVER = os.environ.get('MAIL_SERVER', 'smtp.googlemail.com')
MAIL_PORT = int(os.environ.get('MAIL_PORT', '587'))
MAIL_USE_TLS = os.environ.get('MAIL_USE_... |
import csv
from datetime import datetime
from matplotlib import pyplot as plt
filename = 'sitka_weather_2017.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
dates, highs, lows = [], [], []
for row in reader:
current_date = datetime.strptime(row[0], "%Y-%m-%d")
... |
"""
The MIT License
Copyright (c) 2010 Olle Johansson
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, publi... |
import sys
import click
from boadata import __version__
from boadata.cli import try_load, try_apply_sql, qt_app
@click.command()
@click.version_option(__version__)
@click.argument("uri")
@click.option("-s", "--sql", required=False, help="SQL to run on the object.")
@click.option("-t", "--type", default=None, help="What... |
r"""Functions for Higgs signal strengths."""
import flavio
from . import production
from . import decay
from . import width
prod_modes = {
'ggF': {
'desc': 'gluon fusion production',
'tex': 'gg',
'str': 'gg',
},
'hw': {
'desc': '$W$ boson associated production',
'tex'... |
import numpy as np
import cv2
from math import pi
def points2mapa(landmarks,pos_rob,mapa,P, delete_countdown): #mapa = (x,y, Px,Py, updt)
new_points2add = []
landmarks = np.array(landmarks)
for i in range(0,landmarks.shape[0]):
x_mapa = pos_rob[0] + landmarks[i,1]*np.cos((pos_rob[2])*pi/180+landmarks[i,0])
y_m... |
import collections
from client.constants import FieldKeyword
from metadata import Metadata
class FileUrlMetadata(Metadata):
def get_title(self, soup):
image_url = self.prop_map[FieldKeyword.URL]
return image_url.split('/')[-1]
def get_files_list(self, response):
file_list = collections.O... |
from __future__ import unicode_literals
import random
import itertools
import gym
import numpy as np
class Sarsa(object):
def __init__(self, allStates, allActions):
"""
Sarsa performs in discrete action space and requires the
action state value function table to be initialized arbitrarily
... |
import binascii
from x509 import ASN1_Node
def a2b_base64(s):
try:
b = bytearray(binascii.a2b_base64(s))
except Exception as e:
raise SyntaxError("base64 error: %s" % e)
return b
def b2a_base64(b):
return binascii.b2a_base64(b)
def dePem(s, name):
"""Decode a PEM string into a bytear... |
import _plotly_utils.basevalidators
class ColorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self, plotly_name="color", parent_name="surface.hoverlabel.font", **kwargs
):
super(ColorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=pa... |
''' Controller for the application '''
import logging
import sys
import traceback
import forms
from models import Settings
from flask import Flask, render_template
from google.appengine.api import app_identity # pylint: disable=E0401
from google.appengine.api import mail # pylint: disable=E0401
from google.appengine.ap... |
import os
from fuel import config
from fuel.datasets import H5PYDataset
from fuel.transformers.defaults import uint8_pixels_to_floatX
class SVHN(H5PYDataset):
"""The Street View House Numbers (SVHN) dataset.
SVHN [SVHN] is a real-world image dataset for developing machine
learning and object recognition alg... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.