code stringlengths 1 199k |
|---|
from models.notifications.notification import Notification
class AwardsNotification(Notification):
def __init__(self, event):
self.event = event
@classmethod
def _type(cls):
from consts.notification_type import NotificationType
return NotificationType.AWARDS
@property
def fcm... |
import re
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='pennathletics',
version='0.0.1',
description='Python SDK for Penn Athletics.',
author='Penn Labs',
author_email='admin@pennlabs.org',
url='http://github.com/pennlabs/pennathletic... |
from django import template
from django.template.defaultfilters import stringfilter
import base64
register = template.Library()
@register.filter
@stringfilter
def base64_encode(value):
"""Encode the value in base64"""
return base64.b64encode(value)
@register.filter
@stringfilter
def base64_decode(value):
""... |
"""
Integration tests for singletask vector feature models.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
__author__ = "Bharath Ramsundar"
__copyright__ = "Copyright 2016, Stanford University"
__license__ = "MIT"
import os
import unittest
import tempfi... |
"""
referee.py:
The Referee class for processing a post and emitting
a decision string to the handler.
* Author: Mitchell Bowden <mitchellbowden AT gmail DOT com>
* License: MIT License: http://creativecommons.org/licenses/MIT/
"""
from google.appengine.ext import db
import random
import logging
import lib.p... |
"""
Created on Tue Dec 17 14:55:58 2013
@author: kyle
"""
import os.path
import os, cherrypy
import time
from lxml import etree
from lxml.builder import E
import urllib2
import mysql.connector
def setup_glams():
''' 1) check if config.txt is created. If it isn't, display a webpage to create one.'''
print('Sett... |
import serial
import time
BAUDRATE = 115200
PORT = 'COM3'
def zerocrossed_up(prev, curr):
return (prev < 100) and (curr > 200)
def zerocrossed_down(prev, curr):
return (prev > 200) and (curr < 100)
def zero_crossed(prev, curr):
return zerocrossed_up(prev, curr) or zerocrossed_down(prev, curr)
def port_open(... |
from . import SampleResource |
import unittest
from django.conf import settings
from django.db import models
from django.http import HttpRequest
from django.template import Template, Context, RequestContext
from django.test import TestCase
from django.urls import reverse
class DummyModel(models.Model):
"""
Dummy model for testing below
"... |
import csv
import numpy as np
import pickle
with open('data (2).csv','r') as f:
csv = csv.reader(f)
csvlist = []
for i in csv:
csvlist.append(i)
mas = []
for i in range(364):
i+=6
a = 0
b = 0
c = 0
date = csvlist[i][0]
weather = csvlist[i][1]
if date[0:10] == "2016/11/1 "... |
"""
Unit tests for Python ICE-CASCADE hillslope & uplift example case
"""
import os
import unittest
import py_ice_cascade.examples
class hill_uplift_TestCase(unittest.TestCase):
def test_run_successfully(self):
"""Confirm the example runs without error"""
file_name = py_ice_cascade.examples.hill_upl... |
import theano
import numpy as np
from theano import tensor as T
from utils.fftconv import cufft, cuifft
from utils.theano_complex_extension import apply_complex_mat_to_kronecker
NP_FLOAT = np.float64
INT_STR = 'int64'
FLOAT_STR = 'float64'
def initialize_data_nodes(loss_function, input_type, out_every_t):
x = T.ten... |
import argparse
import math
import sys
import fpdf
def main():
# Command line options
parser = argparse.ArgumentParser()
parser.add_argument('--dt', dest='Dt', type=float, required=True,
help='diameter of the glass top rim (inches)', metavar='IN')
parser.add_argument('--hg', dest... |
from crispy_forms import layout
from csat.acquisition import forms
from . import models
class ConfigForm(forms.CollectorConfigForm):
class Meta(forms.CollectorConfigForm.Meta):
model = models.Config
def get_basic_layout(self):
return layout.Layout(
layout.Field('repo_url'),
... |
import mimetypes
import os
import re
import sys
from shutil import copyfile
def main(args):
if type(args) is not list:
raise TypeError("Args were not of type list.")
args_len = len(args)
if args_len == 3 or args_len == 5:
run_type = args[0]
source = args[1]
target = args[2]
... |
"""
A wrapper around a 32-bit FORTRAN library, :ref:`example_fortran_lib32
<example-fortran-lib32>`, using :class:`ctypes.CDLL`.
Example of a server that loads a 32-bit FORTRAN library, :ref:`example_fortran_lib32
<example-fortran-lib32>`, in a 32-bit Python interpreter to host the library.
The corresponding :mod:`~.fo... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("spectator_events", "0002_event_slug"),
]
operations = [
migrations.AddField(
model_name="classicalwork",
name="slug",
... |
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
import os
import os.path
import sys
setup(name="dicomparser",
packages = find_packages(),
include_package_data = True,
version="0.2",
zip_safe = False, # want users to be able to see included... |
minmaxdiff([4, 2, 1, 6, 7])
[7, 6, 8, 5]
def minmaxdiff(nums):
# could define smallest/largest with temp values, but that seems sloppier
if len(nums) <= 2:
# latter part looks awkward! but it returns an answer if length is 1
return abs(nums[0] - nums[-1])
else:
smallest = min(nums[0]... |
import fractions as fr
def main():
out = []
ans = 1
num_prod = 1
deno_prod = 1
for num in range(10,100):
for deno in range(10,100):
arr = []
arr_val = []
if(num < deno):
if(len(list(set(list(str(num)))&set(list(str(deno))))) == 1):
... |
"""
WSGI config for makerAuth 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_SETTING... |
import numpy as np
from bayesnet.tensor.constant import Constant
from bayesnet.tensor.tensor import Tensor
from bayesnet.function import Function
class Sum(Function):
"""
summation along given axis
y = sum_i=1^N x_i
"""
def __init__(self, axis=None, keepdims=False):
if isinstance(axis, int):... |
from __future__ import unicode_literals
from django.apps import AppConfig
import watson
class KutimeConfig(AppConfig):
name = 'kutime'
def ready(self):
Lecture = self.get_model('Lecture')
watson.register(Lecture) |
import os
PLUGINS = [
# Built-ins
"will.plugins.admin",
"will.plugins.chat_room",
"will.plugins.devops",
"will.plugins.friendly",
"will.plugins.fun",
"will.plugins.help",
"will.plugins.productivity",
"will.plugins.web",
# All plugins in your project.
"plugins",
]
PLUGIN_BLACK... |
from mxm.midifile.src.data_type_converters import readBew, readVar, varLen
import os, os.path, sys
class RawInstreamFile:
"""
RawInstreamFile parses and reads data from an input file. It takes care of big
endianess, and keeps track of the cursor position. The midi parser
only reads from this object. Nev... |
"""This module contains Language Server Protocol types
https://microsoft.github.io/language-server-protocol/specification
-- Language Features - Type Definition --
Class attributes are named with camel-case notation because client is expecting
that.
"""
from typing import Optional
from pygls.lsp.types.basic_structures ... |
"""
Status and feature management commands
"""
STATUS = 'status'
FEATURE_GET = 'feature_get'
FEATURE_SET = 'feature_set'
"""
Feature names
"""
FEATURE_NAME_BREAKPOINT_LANGUAGES = 'breakpoint_languages'
FEATURE_NAME_BREAKPOINT_TYPES = 'breakpoint_types'
FEATURE_NAME_DATA_ENCODING = 'data_encoding'
FEATURE_NAME_ENCODING ... |
from __future__ import absolute_import, unicode_literals
from base import GAETestCase
from datetime import datetime, date
from decimal import Decimal
from category_app.category_model import Category
from routes.categorys.edit import index, save
from mommygae import mommy
from tekton.gae.middleware.redirect import Redir... |
from __future__ import print_function
import shutil
import os
import unittest
import numpy
import nifty
import nifty.graph.rag as nrag
class TestRagBase(unittest.TestCase):
def setUp(self):
self.tmp = './tmp'
if not os.path.exists(self.tmp):
os.mkdir(self.tmp)
self.path = os.path... |
# -*- coding: utf-8 -*-
r"""
Beamline optics
---------------
The images below are produced by the scripts in
``\examples\withRaycing\02_Balder_BL\``.
The examples show the scans of various optical elements at Balder@MaxIV
beamline. The source is a multipole conventional wiggler.
Diamond filter of varying thickness
~~~... |
import csv as csv
import numpy as np
csv_file_object = csv.reader(open('data/train.csv', 'rb'))
header = csv_file_object.next() #The next() command just skips the
#first line which is a header
data=[] #Create a variable called 'data'
for row in csv_file_object:... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from . import validators, forms
class CIDRNetworkField(models.Field):
description = _("CIDR network; assumes /32 by default")
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 18
self.default_validator... |
import json
from pathlib import Path
import ptt_core
l = ptt_core.l
_PREPROCESSED_DIR_PATH = Path('preprocessed/')
if not _PREPROCESSED_DIR_PATH.exists():
_PREPROCESSED_DIR_PATH.mkdir()
def preprocess_to_json_file(html_path):
l.info('Preprocessing {} ...'.format(html_path))
json_path = _PREPROCESSED_DIR_PAT... |
import sys
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
class RawTransactionsTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 4
self.extra_args = [['-usehd=1']] * self.num_nodes
s... |
import copy
class MediaFile(object):
"""
A media file
"""
def __init__(self):
self._filename = None
self._videoStreams = list()
self._audioStreams = list()
self._imageStreams = list()
self._containerType = None
self._description = ""
def getFileName(se... |
import logging
logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO)
log = logging.getLogger('rhcephcompose')
logging.getLogger('requests').setLevel(logging.WARNING)
logging.getLogger('urllib3').setLevel(logging.WARNING) |
""" Utilities
@requires: U{B{I{gluon}} <http://web2py.com>}
@copyright: (c) 2010-2013 Sahana Software Foundation
@license: MIT
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 Softwar... |
from setuptools import setup, Extension
setup(
# Name of this package
name="pairwise",
# Package version
version=0.1,
# This tells setup how to find our unit tests.
test_suite = "test.pairwise_unittest",
# Describes how to build the actual extension module from C source files.
ext_module... |
import os
from fab_deploy2.base import nginx as base_nginx
from fab_deploy2.tasks import task_method
from fab_deploy2 import functions
from fabric.api import run, sudo, env, local
from fabric.tasks import Task
class Nginx(base_nginx.Nginx):
"""
Install nginx
"""
def _install_package(self):
funct... |
import os
import pytest
from molecule import util
from molecule.provisioner import ansible_playbooks
@pytest.fixture
def _provisioner_section_data():
return {
'provisioner': {
'name': 'ansible',
'options': {},
'lint': {
'name': 'ansible-lint',
... |
import pandas as pd
import numpy as np
from os.path import dirname, abspath, exists
datadir = dirname(abspath(__file__))+'/'
def table1():
""" read table 1 from Box and Decker: Greenland marine-terminating glacier area changes
"""
data = pd.DataFrame.from_csv(datadir+'table1.txt',sep=' ')
# format indi... |
"""
Please install futu-api before use.
"""
from copy import copy
from datetime import datetime
from threading import Thread
from time import sleep
from futu import (
ModifyOrderOp,
TrdSide,
TrdEnv,
OpenHKTradeContext,
OpenQuoteContext,
OpenUSTradeContext,
OrderBookHandlerBase,
OrderStat... |
import sys
sys.path.append('lib')
from game import tictactoe
a = tictactoe()
a.update() |
'''
This is intended to be a plot interface w/
1)filenumber/filename text string filter (allowing update of current Augerfile)
2) adjustable charging energy value,
3) comparison of data with plotted line energies (including shift),
entry for element list?
'''
import tkinter as tk
from matplotlib.figure import Figure
fr... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
db.rename_table('hero_slider_slideritemtitle', 'hero_slider_slideritem_translation')
try:
db.drop_foreign_key('hero_slider_... |
import os
import cherrypy
import simplejson as json
class Extract():
exposed = True
def __init__(self, classifier):
self._classifier = classifier
def getRequestContent(self):
request = cherrypy.request
if request.headers['content-type'] == 'application/x-www-form-urlencoded':
... |
class CannotAddToTreeException(BaseException):
'''error in tree addition!'''
class CannotFindInTreeException(BaseException):
'''error! can't find element'''
def BackwardSearch(cls_type, node, index, depth=0, start_index=0):
'''
Helper method which backwards-recursively searches for objects
:param cl... |
__author__ = 'wuxiaoyu'
from dynrigbuilder import main
reload(main)
def show():
main.show() |
rst_header = '''\
.. _%(mod_name)s:
.. raw:: html
<script>ODSA.SETTINGS.DISP_MOD_COMP = %(dispModComp)s;ODSA.SETTINGS.MODULE_NAME = "%(mod_name)s";ODSA.SETTINGS.MODULE_LONG_NAME = "%(long_name)s";ODSA.SETTINGS.MODULE_CHAPTER = "%(mod_chapter)s"; ODSA.SETTINGS.BUILD_DATE = "%(mod_date)s"; ODSA.SETTINGS.BUILD_CMAP = %... |
from direct.directnotify import DirectNotifyGlobal
from direct.interval.IntervalGlobal import *
from direct.fsm import State
from pandac.PandaModules import *
from toontown.building import Elevator
from toontown.coghq import CogHQExterior
from toontown.safezone import Train
class CashbotHQExterior(CogHQExterior.CogHQEx... |
import numpy as np
from scipy.optimize import linear_sum_assignment
def search_assignment(matrix,
row_assignment=False,
maximize=True,
inplace=False):
r"""Solve the linear sum assignment problem.
This function can also solve a generalization of the c... |
from ctypes import c_size_t, c_int, c_void_p, c_ubyte, c_char_p, c_char, c_bool
from ctypes import create_string_buffer, cast, POINTER, byref, cdll, sizeof, memmove, Structure
from abc import ABCMeta, abstractmethod
from warnings import warn
from itertools import product
import os
import sys
__all__ = ["CompressionForm... |
from django.contrib import admin
from amanda.faq.models import Topic
class TopicAdmin(admin.ModelAdmin):
list_display = ('created_at', 'question', 'email', 'user', 'name', 'hidden')
search_fields = ('name', 'email', 'question', 'answer')
date_hierarchy = 'created_at'
list_filter = ('user', 'hidden', 'cr... |
"""
The Python parts of the Jedi library for VIM. It is mostly about communicating
with VIM.
"""
import traceback # for exception output
import re
import os
import sys
from shlex import split as shsplit
try:
from itertools import zip_longest
except ImportError:
from itertools import izip_longest as zip_longest... |
import os
import sys
import codecs
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
tests_require = [ # We require these packages when running tests.
'coverage', # Capture code execution coverage.
'pytest', # The main test runner.
'pytest-cov', # Coverage reporting... |
from fractions import Fraction
ex = [Fraction(0, 1)] * 1001
def expansion(n):
if ex[n] > 0: return ex[n]
if n == 0: ex[n] = Fraction(1, 1)
else: ex[n] = 1 + 1 / (1 + expansion(n-1))
return ex[n]
def valid(n):
f = expansion(n)
return len(str(f.numerator)) > len(str(f.denominator))
print len(filter(valid, ran... |
from setuptools import setup
__version__ = '0.7.1'
__description__ = 'A Flask based web analytics app'
setup(name='crumby',
version=__version__,
author='bmweiner',
author_email='bmweiner@users.noreply.github.com',
url='https://github.com/bmweiner/crumby',
description=__description__,
... |
QUERY_ISSUE_RESULT = {'Ticket(val.Id == obj.Id)':
[
{
'Id': '12652', 'Key': 'VIK-3', 'Summary': 'JiraTestMohitM', 'Status': 'To Do', 'Assignee': 'null(null)',
'Creator': 'jon doe(email)', 'Priority': 'High', 'ProjectName': 'VikTest', 'DueDate': None,
'Created': '2019-05-0... |
from __future__ import absolute_import
import numpy as np
import pandas as pd
from .Ranker import *
from .Table import Table
def borda_count_merge(rankings):
"""Merge rankings by using Borda count.
Parameters
----------
rankings: list of rankings returned by rank of rankers.
Returns
-------
... |
"""
WSGI config for tally project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` set... |
import ezodf as od
import numpy as np
import time
import datetime
import os
results_root = "/mnt/data/Fer/diplomski/training_currennt/results/"
def save_score(strid, netname, results):
#print("save_score called")
# initialize empty table
results_file = results_root + "results.ods"
if os.path.isfile(results_file):
... |
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import UserQAProfile
@receiver(post_save, sender=User)
def ensure_profile_exists(sender, **kwargs):
if kwargs.get('created', False):
UserQAProfile.objects.get_or_creat... |
import sys
from distutils.version import LooseVersion
try:
from setuptools import setup, find_packages
except ImportError:
print('setuptools is required.')
sys.exit()
if sys.version_info.major == 2:
print('python >= 3.6 is required.')
sys.exit()
elif sys.version_info.major == 3 and sys.version_info ... |
"""Unit test utilities for Google C++ Testing Framework."""
__author__ = 'wan@google.com (Zhanyong Wan)'
import atexit
import os
import shutil
import sys
import tempfile
import unittest
_test_module = unittest
try:
import subprocess
_SUBPROCESS_MODULE_AVAILABLE = True
except:
import popen2
_SUBPROCESS_MODULE_AV... |
"""
tkSidViewer class implements a graphical user interface for SID based on tkinter
2017/09/01: add vertical lines on the plot for each monitored station
"""
from __future__ import print_function
import matplotlib
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg as FigureCanvas, NavigationToolbar2Tk
fro... |
import sys
import numpy as np
import ast
import json
def find_correlation(movie_list, movie_for_correlation):
'''
Input:
movie_list - List of movies
movie_for_correlation: The movie to calculate the correlation for
Return:
Dictionary of correlation for movie_for_correlation
'''
correlate... |
import myhdl
import pihdf
from pihdf import Testable
import os, sys
sys.path.append(os.path.dirname(__file__) + "/../..")
from HandShakeData.HandShakeData import HandShakeData
class t_HandShakeData(Testable):
'''|
| Automatically generated. Do not modify this file.
|________'''
pihdf.head("T E S T S")
... |
import MySQLdb
con = MySQLdb.connect(host='localhost', user='root', passwd='', db='test', port=3306, charset='utf8')
cur = con.cursor()
cur.execute(' CREATE TABLE person (id int not null auto_increment primary key,name varchar(20),age int)')
data="'qiye',20"
cur.execute(' INSERT INTO person (name,age) VALUES (%s)'%data... |
""" Functions and utilities for calculating the rarity-weighted richness score.
Module can be used alone or as part of Snakemake workflow.
"""
import click
import glob
import logging
import numpy as np
import numpy.ma as ma
import pdb
import rasterio
import time
from importlib.machinery import SourceFileLoader
from sci... |
from __future__ import division, print_function
from ... import moves
from .test_proposal import _test_normal, _test_uniform
__all__ = ["test_normal_de_snooker", "test_uniform_de_snooker"]
def test_normal_de_snooker(**kwargs):
_test_normal(moves.DESnookerMove(), **kwargs)
def test_uniform_de_snooker(**kwargs):
... |
"""
Memcache decorator for Google App Engine.
Maciej Żok, 2014 MIT License
"""
from functools import wraps
import logging
from google.appengine.api import memcache
class memcached(object):
'''
Sets/gets value from memcache.
Args:
key (str): Name of cache object
time (datetime, optional): Exp... |
"""pycounter: Project COUNTER/NISO SUSHI statistics."""
from pycounter import exceptions, report, sushi
from pycounter.version import __version__
__all__ = ("__version__", "report", "sushi", "exceptions") |
import math
from random import choice, randint
import numpy as np
__all__ = ('make_reber', 'is_valid_by_reber', 'make_reber_classification')
avaliable_letters = 'TVPXS'
reber_rules = {
0: [('T', 1), ('V', 2)],
1: [('P', 1), ('T', 3)],
2: [('X', 2), ('V', 4)],
3: [('X', 2), ('S', None)],
4: [('P', 3)... |
import math
from . import cartesian3d as c3d
class BoundingSphere(object):
def __init__(self, *args, **kwargs):
MAX = float('infinity')
MIN = float('-infinity')
self.center = kwargs.get('center', [])
self.radius = kwargs.get('radius', 0)
self.minPointX = [MAX, MAX, MAX]
... |
from ast import literal_eval
import parser
import tokenize
import token
import StringIO
__all__ = [
"getval", "select", "groupby", "calc", "where", "each", "limit", "reverse",
"orderby"]
from django import template
register = template.Library()
def getval(obj, keys, default=None):
"""Try to get value from o... |
import argparse
import multiprocessing
import os
import subprocess
import sys
def setup():
global args, workdir
programs = ['ruby', 'git', 'apt-cacher-ng', 'make', 'wget']
if args.kvm:
programs += ['python-vm-builder', 'qemu-kvm', 'qemu-utils']
elif args.docker:
dockers = ['docker.io', '... |
import os
import sys
import argparse
import datetime
import requests
import pickle
from tendo import singleton
from bs4 import BeautifulSoup
import gi
gi.require_version('Notify', '0.7')
from gi.repository import Notify
from pyshorteners import Shortener
shortener = Shortener('Google', api_key='AIzaSyCo3t8difUtcZl4EFHU... |
import vx
import argparse
parser = argparse.ArgumentParser(description='edit files')
parser.add_argument('files', metavar='FILE', type=str, nargs='*',
help='Files to edit')
parser.add_argument('-l', '--log', dest='log', action='store_true',
help='Log to \'log\' file')
vx.parsed_a... |
import sys
for i in range(13)[1::]:
print(''.join(['%4d' % (i * j) for j in range(13)[1::]]).strip()) |
from index import index_files
from index import enhance_repo
import logging
import os
import time
import requests
import json
try:
from elasticsearch import Elasticsearch
except ImportError:
logging.error("Elasticsearch is required to run this script")
exit(1)
es_config = {}
bb_config = {}
execfile("elastic... |
from ConnectFour import ConnectFour
class ConnectFourText(ConnectFour):
def current(self):
print(self.players[self.first_player])
def drop(self, column):
ConnectFour.drop(self, column)
print(self)
if self.game_over != False:
print('Game has ended.')
return
... |
from app import db
class Category():
@staticmethod
def get_all(include_none=False):
query = ("SELECT name FROM category")
cnx = db.get_connection()
with cnx.cursor() as cursor:
cursor.execute(query)
all_data = list(cursor.fetchall())
if include_none:
... |
/**
*
* The MIT License (MIT)
*
* Copyright (c) 2013 Shrey Malhotra
*
* 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 witho... |
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from os import path, popen
from subprocess import call
class Watcher:
WATCH = '/path'
OUTPUT = '/path'
def __init__(self):
self.observer = Observer()
def run(self):
event_handler = Hand... |
from __future__ import absolute_import
from builtins import object
from math import *
from proteus import *
from proteus.default_p import *
try:
from .multiphase import *
except:
from multiphase import *
from proteus.mprans import Pres
name = "pressure"
LevelModelType = Pres.LevelModel
coefficients=Pres.Coeffic... |
import asyncio
import signal
import engineio
loop = asyncio.get_event_loop()
eio = engineio.AsyncClient()
exit_event = asyncio.Event()
original_signal_handler = None
async def send_hello():
message = 'Hello from client side!'
while not exit_event.is_set():
print('sending: ' + 'Hello from client side!')
... |
from __future__ import print_function
from google.protobuf import text_format
from cStringIO import StringIO
from PIL import Image
import scipy.ndimage as nd
import numpy as np
import caffe
import os
class BatCountry:
def __init__(self, base_path, deploy_path, model_path,
patch_model="./tmp.prototxt", mean=(104.0, 1... |
import copy
from gitlint.tests.base import BaseTestCase
from gitlint.config import LintConfig, LintConfigBuilder, LintConfigError
from gitlint import rules
class LintConfigBuilderTests(BaseTestCase):
def test_set_option(self):
config_builder = LintConfigBuilder()
config = config_builder.build()
... |
import os
import glob
import fileinput
root_dir = os.path.expanduser('~/scrimmage/gtri-tactics')
src_dir = root_dir + '/src'
include_dir = root_dir + '/include'
for root, dirs, files in os.walk(src_dir):
for file in files:
if file.endswith(".cpp"):
#print(os.path.join(root, file))
fi... |
import logging
from .ast_object import ASTObject
from .channel.ast_channel import ASTChannel
from .channel.fits_channel import *
from .mapping.frame.frame import *
from .mapping.frame.frame_set import *
from .mapping.frame.sky_frame import *
from .mapping.frame.time_frame import *
from .mapping.frame.compound_frame imp... |
import sys
def is_nice(string):
return has_three_vowels_or_more(string) and has_a_double(string) and not has_nasty_sequence(string)
def has_three_vowels_or_more(string):
vowels = "aeiou"
return len(list(filter(lambda x: x in vowels, string))) >= 3
def has_a_double(string):
return any(map(lambda x: x * 2... |
from mashery_api import *
from axeda_api import *
class Node():
"""
A node indicates a machine or whatever connected to cloud.
Its role may be client, server or whatever.
"""
def __init__(self, name, config):
if not name:
assert(False)
if not config:
assert(False)
self.config = config
if name == "Mas... |
from readthedocs.builds.storage import BuildMediaFileSystemStorage
class BuildMediaFileSystemStorageTest(BuildMediaFileSystemStorage):
def exists(self, *args, **kargs):
return True |
from lxml import html
import urllib
import requests
from time import sleep
webpage = "http://makeameme.org"
added_url = "/media/templates"
page = requests.get(webpage)
tree = html.fromstring(page.text)
image_url_list = []
image_url_list = tree.xpath('//img[@class="th creates css-thumbs"]/@rel')
i = 0
for image in image... |
"""
Django settings for ldapsample project.
Generated by 'django-admin startproject' using Django 1.10.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
... |
import _plotly_utils.basevalidators
class BaxisValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="baxis", parent_name="carpet", **kwargs):
super(BaxisValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_... |
import functools
from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.trans... |
import torch
from torch.utils.data import DataLoader, TensorDataset
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
from torch.optim.lr_scheduler import StepLR
import os
import os.path as osp
from tqdm import tqdm
import argparse
import time
import numpy as ... |
"""
This script is intended to be used with Google Appengine. It contains
a number of demos that illustrate the Tropo Web API for Python.
"""
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import cgi
import logging
import tropo
import GoogleS3
from xml.dom import minidom
from googl... |
import pytest
def test_document_0_upgrade(upgrader, document_0, publication):
value = upgrader.upgrade('document', document_0, target_version='2')
assert value['schema_version'] == '2'
assert value['references'] == [publication['identifiers'][0]]
def test_document_upgrade_status(upgrader, document_1):
v... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.