code stringlengths 1 199k |
|---|
import os
import operator
PRODUCTION = os.environ.get('SERVER_SOFTWARE', '').startswith('Google App Eng')
DEBUG = DEVELOPMENT = not PRODUCTION
try:
# This part is surrounded in try/except because the config.py file is
# also used in the run.py script which is used to compile/minify the client
# side files (*.less... |
from django.core.management.base import BaseCommand, CommandError
from monitor.node_updates import update_nodes
class Command(BaseCommand):
help = 'Updates the database with information from nodes'
def handle(self, *args, **options):
update_nodes() |
from future import standard_library
standard_library.install_aliases()
from builtins import str
import click
import hashlib
from io import StringIO
import logging
import os
import urllib.request, urllib.parse, urllib.error
from cargoport.utils import yield_packages, package_name, PACKAGE_SERVER, get_url
logging.basicCo... |
"""Tests for Google-style docstring routines."""
import typing as T
import pytest
from docstring_parser.common import ParseError, RenderingStyle
from docstring_parser.google import (
GoogleParser,
Section,
SectionType,
compose,
parse,
)
def test_google_parser_unknown_section() -> None:
"""Test p... |
sort_transform = lambda arr: (lambda conv = lambda ls: ''.join(map(chr, ls[:2] + ls[-2:])): '-'.join([conv(arr), conv(sorted(arr)), conv(sorted(arr, reverse = True)), conv(sorted(arr))]))() |
def exclude_keys(d, keys):
"""Return a new dictionary excluding all `keys`."""
return {k: v for k, v in d.items() if k not in keys} |
import os
from keras import backend as K
from keras import objectives
from keras.layers import Conv2D, MaxPooling2D, UpSampling2D, Dense, GlobalAveragePooling2D
from keras.layers import Input
from keras.layers.advanced_activations import LeakyReLU
from keras.layers.core import Activation, Flatten
from keras.layers.merg... |
from django.contrib import admin
from .models import Employee, Role, Category
class RoleAdmin(admin.ModelAdmin):
list_display = ("name",)
class CategoryAdmin(admin.ModelAdmin):
list_display = ("name", "weight",)
class EmployeeAdmin(admin.ModelAdmin):
list_display = ("username", "first_name", "last_name", "e... |
from ..common.factory import MapleFactory
from .protocol import WorldProtocol
from ..common.mixins import CharacterCacheMixin
class WorldFactory(CharacterCacheMixin, MapleFactory):
protocol = WorldProtocol
def __init__(self, worlds, *args, **kwargs):
self.worlds = worlds
return super(WorldFactor... |
import matplotlib.pyplot as plt
import networkx as nx
def plot_graph(G, N, time_point, posi):
#setting up for graph plotting
#setting the positions for all nodes
pos = {}
for ii in range(N):
pos[ii] = posi[ii]
elarge=[(u,v) for (u,v,d) in G[time_point].edges(data=True) if d['weight'] >0.5]
... |
from __future__ import unicode_literals
from django.db import migrations
import kobra.db_fields
class Migration(migrations.Migration):
dependencies = [
('kobra', '0006_auto_20180111_1901'),
]
operations = [
migrations.AlterField(
model_name='discount',
name='amount',
... |
from django.forms import ModelForm, Form, Textarea, CharField, ModelChoiceField, ChoiceField
from mblog.models import BloggerProfile, Visitor, Thematic, Post, Comment
from django.contrib.auth.models import User
class VisitorForm(ModelForm):
class Meta:
model = Visitor
fields = ['username']
class Com... |
import uuid
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
from .. import models
class LoadBalancerFrontendIPConfigurationsOperations(object):
"""LoadBalancerFrontendIPConfigurationsOperations operations.
:param client: Client for service requests.
:param c... |
"""
ORCID Member
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: Latest
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class MonthV30(object):
... |
import numpy
import pytest
from formulaic.transforms.poly import poly
class TestPoly:
@pytest.fixture(scope="session")
def data(self):
return numpy.linspace(0, 1, 21)
def test_basic(self, data):
state = {}
V = poly(data, _state=state)
assert V.shape[1] == 1
# Comparis... |
from __future__ import unicode_literals
from django.db import models, migrations
import timer.models
class Migration(migrations.Migration):
dependencies = [("timer", "0002_only_1_running_constraint_20150127_1512")]
operations = [
migrations.AlterField(
model_name="timer",
name="c... |
import platform
import textwrap
import pytest
from conans.test.assets.cmake import gen_cmakelists
from conans.test.assets.sources import gen_function_cpp
from conans.test.utils.tools import TestClient
from conans.util.files import save
@pytest.fixture
def client():
c = TestClient()
save(c.cache.new_config_path,... |
import os
import pickle
import unittest
from os.path import join
from pyfluka.utils import ureg
from pyfluka.reader import _dh
from pyfluka.utils import PhysicsQuantities as PQ
_basedir = os.path.dirname(__file__)
class TestDataHandle(unittest.TestCase):
def setUp(self):
fLE = open(join(_basedir, "../pyfluk... |
import whrandom, pygame, math
class Star:
""" Star is a crippled particle class - it can draw itself, keep track
of its speed, position and direction, color and size. """
def __init__(self, position_x, position_y, distance, angle, speed, size,
color):
self.position_x = position_x
... |
import time
import lib.settings as settings
import lib.logger
log = lib.logger.get_logger('DB_Sqlite')
import sqlite3
class DB_Sqlite():
def __init__(self):
log.debug("Connecting to DB")
self.dbh = sqlite3.connect(settings.DB_SQLITE_FILE)
self.dbc = self.dbh.cursor()
def updateStats(self,averageOverTime):
l... |
"""JKS/JCEKS file format decoder. Use in conjunction with PyOpenSSL
to translate to PEM, or load private key and certs directly into
openssl structs and wrap sockets.
Notes on Python2/3 compatibility:
Whereever possible, we rely on the 'natural' byte string
representation of each Python version, i.e. 'str' in Python2 a... |
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based... |
import unittest
from uirapuru import utils
class TestUtils(unittest.TestCase):
def test_flatten(self):
a = [[1, 2, 3], [4, 5]]
self.assertEqual(utils.flatten(a), [1, 2, 3, 4, 5])
def test_split_by_tempo(self):
result = utils.split_by_tempo(2.3)
self.assertEqual(result[0:2], [1.0,... |
"""Base Models"""
from django.db import models
from django.utils import timezone
from django.urls import reverse, NoReverseMatch
class FrontEndModel(models.Model):
"""Contains default methods for urls"""
class Meta(object):
abstract = True
# OVERKILL: allows us to immediately get add url for stuff t... |
import numpy as np
import matplotlib.pyplot as plt
from astropy.io import fits
from astropy import units as u, constants as c, table as t
import extinction
from scipy.interpolate import interp1d
from scipy.signal import medfilt
import os, sys
from copy import copy
import utils as ut
import indices
from spectrophot impo... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Leevee.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
import sys
import numpy
import seqdict
from shogun.Classifier import LibSVM
from shogun.Features import StringCharFeatures,DNA
from shogun.Kernel import WeightedDegreeStringKernel
from shogun.Library import DynamicIntArray
class svm_splice_model(object):
def __init__(self, order, traindat, alphas, b, (window_left,offs... |
from __future__ import division
try:
import boost.python
except Exception:
ext = None
else:
ext = boost.python.import_ext("fable_ext", optional=True)
def py_fem_utils_unsigned_integer_scan(code, start=0, stop=-1):
i = start
while (i < stop):
c = code[i]
if (not c.isdigit()): break
i += 1
if (i =... |
import types
import logging
from functools import wraps
if 'logger' not in globals():
logger = logging.getLogger('Main')
logger.setLevel(logging.DEBUG)
logger.propagate = False
if not logger.handlers:
hdlr = logging.StreamHandler()
hdlr.setLevel(logging.DEBUG)
formatter = logging... |
import six
from six.moves import reduce
def rgetattr(obj, attr, allow_null=True):
attrs = attr.split('__')
def _get_attr(o, a):
try:
return getattr(o, a)
except AttributeError as e:
if not allow_null:
raise e
return reduce(_get_attr, [obj] + attrs)
def... |
from util import hexdump, inttime
import datetime
import struct
import sys
import time
try:
import serial
except ImportError:
print >> sys.stderr, "Missing serial module"
sys.exit(1)
class KeymazePort(object):
"""Interface w/ the Keymaze device, through a serial stream which is itself
encapsulated i... |
"""
Django settings for ruhive project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
from django.core.urlresolvers import reverse_lazy
from os.path import dirname,... |
__author__ = 'sibirrer'
from astrofunc.LensingProfiles.spp import SPP
from astrofunc.LensingProfiles.spemd_smooth import SPEMD_SMOOTH
class SPEMD(object):
"""
class for smooth power law ellipse mass density profile
"""
def __init__(self):
self.s2 = 0.00000001
self.spp = SPP()
sel... |
from __future__ import unicode_literals
from django.db import migrations
def forwards_func(apps, schema_editor):
"""Old models with provider_data='' are being fetched as str instead of json."""
Integration = apps.get_model('integrations', 'Integration')
Integration.objects.filter(
provider_data='',
... |
"""
module description
"""
from functools import wraps
def rate_limit(limit, period):
"""
Limits the amount of times the decorated function may be called within
a given time period.
As an example or first iteration the period is assumed to be second, minute,
hour, day, or month. Ultimately we will ... |
import json
from sqlalchemy import inspect
from wtforms import RadioField, SelectField
from indico.core import signals
from indico.core.db.sqlalchemy.util.session import no_autoflush
from indico.core.errors import UserValueError
from indico.modules.events.layout import theme_settings
from indico.modules.events.models.p... |
import os
import sys
from test_package import return_hi, hey
from hello import return_hello
from yo import return_yo
from hola import return_hola
from pow import return_pow
def test_imports_worked():
assert "hi" == return_hi()
assert "hey" == hey.return_hey()
assert "hello" == return_hello()
assert "yo"... |
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from tkinter import filedialog
import PyPDF2
class PDFCombiner:
def __init__(self, master):
master.title('PDF Combiner')
master.resizable(False, False)
self.chooseButtons = {}
self.chooseLabelVars = {}
... |
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'UserMessages.reply_to'
db.add_column(u'user_management_usermessages', 'reply_to',
... |
from django.db import models
class Publisher(models.Model):
name = models.CharField(max_length = 30)
address = models.CharField(max_length = 50)
city = models.CharField(max_length = 60)
state_province = models.CharField(max_length = 30)
country = models.CharField(max_length = 50)
website = model... |
from __future__ import print_function
import os, sys, subprocess
from glob import glob
from cStringIO import StringIO
_dotnetConfiguration = "Release"
_dotnetFramework = "netcoreapp1.1"
_dotnetRuntime = "portable"
def execute(args):
popen = subprocess.Popen(args, stdout=subprocess.PIPE, universal_newlines=True)
... |
import logging
__all__ = ['logger']
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
COLORS = {
'WARNING': YELLOW,
'INFO': WHITE,
'DEBUG': BLUE,
'CRITICAL': RED,
'ERROR': RED
}
RESET_SEQ = "\033[0m"
def color_string(text, color):
return '\033[1;3{0}m{1}{2}'.format(color, text, RE... |
import helpers
def plot():
from matplotlib import pyplot as plt
import numpy as np
def f(t):
s1 = np.cos(2*np.pi*t)
e1 = np.exp(-t)
return np.multiply(s1, e1)
fig = plt.figure()
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
t3 = np.arange(0.0, 2.0, 0.01... |
import sys
import win32cred as Cred
import win32ts as Ts
import win32wts as Wts
def GetUsername(id):
server = Ts.WTS_CURRENT_SERVER_HANDLE
for session in Ts.WTSEnumerateSessions(server):
if session["SessionId"] == id:
user = Ts.WTSQuerySessionInformation(server, id, Ts.WTSUserName)
domain = Ts.WTSQuerySession... |
""" This file contains code for performing static code analysis on APK files. """
try:
import mallodroid
except:
print("error: could not find Mallodroid, make sure you have downloaded it and set your python path.")
exit(1)
def analyze(apps, filename, app):
""" Performs a static code analysis on an app.
Arguments:... |
import numpy as np
import loaddata
import params as p
import value
import forecast
def NL2016Draft():
db = loaddata.LahmanDB()
nl2015db = loaddata.LahmanNL2015()
db.connect()
nl2015db.connect()
lr = forecast.LinRegForecaster(db, p.minYear, p.maxYear, value.LinearValues)
#B = nl_batter_vorp2016()... |
from ezdxf.math import (
Vec3,
estimate_tangents,
local_cubic_bspline_interpolation,
)
from ezdxf.math.bspline import local_cubic_bspline_interpolation_from_tangents
POINTS1 = [(1, 1), (2, 4), (4, 1), (7, 6)]
POINTS2 = [(1, 1), (2, 4), (4, 1), (7, 6), (5, 8), (3, 3), (1, 7)]
def test_estimate_tangents_3p():... |
from .common import SeaBreezeError, get_pyseabreeze_decorator
from .eeprom import EEPromFeature
from .communication import USBCommOBP
import struct
convert_exceptions = get_pyseabreeze_decorator('interfaces.nonlinearity')
class NonlinearityCoefficientsEEPromFeature(EEPromFeature):
def has_nonlinearity_coeffs_featur... |
from office365.runtime.client_value import ClientValue
class TeamMessagingSettings(ClientValue):
"""Settings to configure messaging and mentions in the team."""
def __init__(self, allow_user_edit_messages=True,
allow_user_delete_messages=True,
allow_owner_delete_messages=True,
... |
from itertools import groupby
def scramble(s1,s2):
for key, group in groupby(sorted(s2)):
if len(list(group)) > s1.count(key):
return False
return True |
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from builtins import str, zip, map, range
__author__ = 'Zhengtao Xiao'
from .test_func import wilcoxon_greater,combine_pvals
from .prepare_transcripts import *
from .translate_dna import translation
from .orf_fi... |
from neo.VM.Mixins import InteropMixin
class StorageContext(InteropMixin):
ScriptHash = None
def __init__(self, script_hash):
self.ScriptHash = script_hash
def ToArray(self):
# hmmm... script hashes are already a byte array at the moment, i think?
# return self.ScriptHash.ToArray()
... |
from rest_framework.test import APITestCase
import unittest
from . import settings
class WQTestCase(APITestCase):
@unittest.skipUnless(settings.WITH_WQDB, "requires wq.db")
def test_config(self):
config = self.client.get("/config.json").data
for name, conf in config["pages"].items():
... |
from nose.tools import raises
import unittest
from victor.exceptions import (
FieldValidationException,
FieldTypeConversionError,
FieldRequiredError,
VectorInputTypeError
)
from victor.vector import (
Vector,
CharField,
StringField,
ListField,
IntField,
FloatField
)
class VectorT... |
import os
import shutil
import re
import glob
import subprocess
import json
import sys
try:
import pil
import logger
import helpers
from constants import Constants
except ImportError:
from . import pil
from . import logger
from . import helpers
from .constants import Constants
"""
The co... |
__author__ = 'Eshin Kunishima'
__license__ = 'MIT'
from enum import Enum
from copy import deepcopy
from random import randint, random
from field import Field
from neighbor import Neighbor
def clamp(num, min_num, max_num):
return max(min(max_num, num), min_num)
class Season(Enum):
spring = 0
summer = 1
a... |
"""
Script used to train the models.
"""
import argparse
import audiosegment
import numpy as np
import os
import sys
import senses.dataproviders.dataprovider as dp
import senses.dataproviders.featureprovider as fp
import senses.dataproviders.sequence as seq
import senses.voice_detector.voice_detector as vd
script_path ... |
"""Record module signals."""
from __future__ import absolute_import, print_function
from blinker import Namespace
_signals = Namespace()
record_viewed = _signals.signal('record-viewed')
"""Signal sent when a record is viewed on any endpoint.
Parameters:
- ``sender`` - a Flask application object.
- ``pid`` - a persisten... |
import Error
import re
from src.Circuito import Circuito
class GranPremio(object):
puntuaciones = {1: 25, 2: 18, 3: 15, 4: 12, 5: 10, 6: 8, 7: 6, 8: 4, 9: 2, 10: 1}
def __init__(self, nombre, circuito, escuderias, pais, fecha):
"""
Clase GranPremio
Esta clase contiene el circuito, escude... |
import urllib.parse
import socket
import re
from selectors import *
seen_urls = set('/')
urls_todo = set('/')
selector = DefaultSelector()
stopped = False
class Fetcher():
def __init__(self,url):
self.url = url
self.response = b''
self.sock = None
def fetch(self):
self.sock = socket... |
from django.apps import AppConfig
class ListingsConfig(AppConfig):
name = 'listings'
verbose_name = "User Listings" |
"""
FILE: sample_batch_client_async.py
DESCRIPTION:
This sample demonstrates how to upload, merge, or delete documents using SearchIndexingBufferedSender.
USAGE:
python sample_batch_client_async.py
Set the environment variables with your own values before running the sample:
1) AZURE_SEARCH_SERVICE_ENDP... |
import numpy as np
def compare(first,second):
if float(first[-2])>float(second[-2]):
return 1
elif float(first[-2])<float(second[-2]):
return -1
else:
return 0
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
f=open(os.path.join(BASE_D... |
import sublime_plugin
import os
from .command_base import AdvancedNewFileBase
from ..anf_util import *
class AdvancedNewFileNew(AdvancedNewFileBase, sublime_plugin.WindowCommand):
def __init__(self, window):
super(AdvancedNewFileNew, self).__init__(window)
def run(self, is_python=False, initial_path=Non... |
from __future__ import print_function
import argparse
from os import path, mkdir
import json
import parse as parse
def get_contents(name, input_file, out_dir):
with open(input_file) as data_file:
data = json.load(data_file)
for rev in data:
revid = rev['revid']
data = parse.get_content(n... |
import unittest
from asq._portability import is_callable
from asq.selectors import k_, a_, m_, identity
from asq.test.test_queryable import TracingGenerator, infinite
__author__ = "Sixty North"
class TestKeySelector(unittest.TestCase):
def test_k_result_is_callable(self):
foo_selector = k_('foo')
se... |
from .base import BaseCoin
from ..transaction import SIGHASH_ALL, SIGHASH_FORKID
from ..explorers import blockdozer
class BitcoinCash(BaseCoin):
coin_symbol = "bcc"
display_name = "Bitcoin Cash"
segwit_supported = False
magicbyte = 0
script_magicbyte = 5
wif_prefix = 0x80
hd_path = 145
e... |
from rest_framework import routers
from . import viewsets
router = routers.DefaultRouter()
router.register(r'thoughts', viewsets.ThoughtViewSet, base_name='thoughts') |
import logging
class MockLoggingHandler(logging.Handler):
debug = []
warning = []
info = []
error = []
def emit(self, record):
getattr(self.__class__, record.levelname.lower()).append(record.getMessage())
@classmethod
def reset(cls):
for attr in dir(cls):
if isins... |
"""
homeassistant.components.demo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sets up a demo environment that mimics interaction with devices
"""
import random
import homeassistant as ha
import homeassistant.components.group as group
from homeassistant.components import (SERVICE_TURN_ON, SERVICE_TURN_OFF,
... |
"""
@Author: Well
@Date: 2014 - 07 - 05
"""
'''
SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。
python的smtplib提供了一种很方便的途径发送电子邮件。它对smtp协议进行了简单的封装。
Python创建 SMTP 对象语法如下:
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
参数说明:
host: SMTP 服务器主机。 你可以指定主机的ip地址或者域名如:... |
import argparse
import logging
import os
import sys
import appdirs
import config
import parser
from client import JIRAClient, ClientError
from parser import ParseError
def main():
"""The program's main entry point"""
try:
_configure_logging()
parsed_args = _cli_parse()
subtasks = _parse_... |
from .analysis_helper_functions import load_alignment_algorithm, load_substitution_matrix
class SequenceAlignment:
"""
Sequence alignment with two chain objects
"""
def __init__(self, target, collection, algorithm, substitution_matrix):
"""
:param chain_1:
:param collection:
... |
import Adafruit_BBIO.UART as UART
import serial
import struct
import sensorState
class EncoderController(sensorState.Sensor):
def __init__(self, inName, inDefaultPriority=3, baudrate = 38400, **kwargs):
# boilerplate bookkeeping
sensorState.Sensor.__init__(self, inName, inSensorThreadProc=self.__threadProc,
... |
f = open('mobil.in.txt')
[n] = map(int, f.readline().split())
free_minutes, free_sms, price_minute, price_sms = map(float, f.readline().split())
free_seconds = free_minutes * 60
sms = 0
all_calls_seconds = 0
for i in range(0, n):
s = f.readline().split()[2]
if s == 'SMS':
sms += 1
else:
call... |
class DataFormat:
def __init__(self, mode_name, mode, unit,
number_of_bytes, number_of_datasets):
self.mode_name = mode_name
self.mode = mode
self.unit = unit
self.dataset_size = number_of_bytes
self.dataset_count = number_of_datasets
def create(mode_name... |
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from .models import Profile
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
... |
import pandas as pd
import numpy as np
from pandas import ExcelWriter
from pandas import ExcelFile
import tensorflow as tf
import matplotlib.pylab as plt
import matplotlib.animation as animation
from scipy.interpolate import interp1d
from scipy import signal
def qhull(sample):
link = lambda a,b: np.concatenate((a,b... |
import time
import pytest
import redis
from limits import RateLimitItemPerMinute, RateLimitItemPerSecond
from limits.storage import RedisStorage, storage_from_string
from limits.strategies import FixedWindowRateLimiter, MovingWindowRateLimiter
class SharedRedisTests(object):
def test_fixed_window(self):
lim... |
import argparse
import os
import tempfile
import unittest
import mock
from cliez import parser
mock_input = 'builtins.input'
class InitComponentTestCase(unittest.TestCase):
def setUp(self):
from cliez import main
_ = main
pass
def test_ok(self):
dp = tempfile.TemporaryDirectory()... |
print("""
1. Name mangling is not applied
2. Left untouched by the Python interpreter
3. Reserved for special use in the Python language
4. Stay away from using names that start and end with __
""") |
Number = (int, float) |
__author__ = 'pawel'
import SimpleHTTPServer
import SocketServer
import logging
import cgi
import sys
PORT = 8080
class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
logging.error(self.headers)
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
def do_POST(self)... |
"""
Simple classes to get info from the ip system utility
"""
from subprocess import check_output as sub
import re
__all__ = ['Devices', 'Routes']
class Devices(object):
""" Network devices from IP """
def __init__(self):
self.ips = {}
self.states = {}
# Get states
for i in sub([... |
class Quiz():
def __init__(self,name,num_questions):
self.name = name
self.num_questions = num_questions
self.questions = []
def __str__(self):
s = self.name
s += ' with ' + str(self.num_questions) + ' questions.' + '\n'
for i in range(self.num_questions):
... |
from pyspark.sql import SparkSession
from pyspark.sql import functions
if __name__ == "__main__":
spark = SparkSession.builder.appName("SparkQuery").getOrCreate()
# Convert data to Spark Dataset
salesDataset = spark.read.option("header","true").csv("hdfs:////user/maria_dev/tp-data/data_dump.csv")
# Coun... |
"""
A minimal front end to the Docutils Publisher, producing (X)HTML.
The output conforms to XHTML 1.0 transitional
and almost to HTML 4.01 transitional (except for closing empty tags).
"""
try:
import locale
locale.setlocale(locale.LC_ALL, '')
except:
pass
from docutils.core import publish_cmdline, default... |
'''
seg_evaluater.py
==============================
Evaluation module for semantic segmentation task.
'''
import numpy as np
def _verify(class_map, label_map, n_classes):
assert class_map.ndim == label_map.ndim == 2 # height and width
assert class_map.shape == label_map.shape
assert np.max(class_map) < n_c... |
import tornado.websocket
import tornado.ioloop
from Room import Room
class WebClientServer(tornado.websocket.WebSocketHandler):
def initialize(self, web_client_list=set(), battle_ai_list=dict(), player_server=None):
self.web_client_list = web_client_list # set()
self.battle_ai_list = battle_ai_list... |
import random,khmer,sys, mmh3, math
class HyperLogLog:
def __init__(self, log2m):
self.log2m = log2m
self.m = 1 << log2m
self.data = [0]*self.m
self.alphaMM = (0.7213 / (1 + 1.079 / self.m)) * self.m * self.m
def add(self, o,k):
x=mmh3.hash(str(0),0)
a, b = 32-sel... |
import asyncio
from asyncexec.workers.generator_worker import GeneratorWorker
from asyncexec.workers.inout_worker import InOutWorker, InOutManyWorker
from asyncexec.workers.sink_worker import SinkWorker
from asyncexec.workers import Communicator
from asyncexec.channels import PublisherFactory, ListenerFactory
from conc... |
""" Livre des stratégies. """
from .HumanControl import HumanControl
from .SimpleDefense import SimpleDefense
from .TestAstarStrategy import TestAstarStrategy
from .SimpleOffense import SimpleOffense
from .DoNothing import DoNothing
from .WeirdmovementStrategy import WeirdmovementStrategy
from ai.STA.Strategy.TestTrans... |
from mamba import description, context, it, before
from expects import expect, equal, contain, raise_error
from doublex_expects import have_been_called_with
from doublex import Spy, when
from simpledatamigrate import migrator, collector, repositories
NO_SCHEMA = None
VER1 = '001'
VER2 = '002'
VER3 = '003'
VER4 = '004'
... |
import numpy as np #scintific computing
import pandas as pd #DA library
import tensorflow as tf #ML lib
import tqdm #Progress bar
import helper
import glob
from tensorflow.python.ops import control_flow_ops
import msgpack
def get_songs(path):
files = glob.glob('{}/*.mid*'.format(path))
songs = []
for f in t... |
import pprint
def test_id(product_version):
assert product_version.id == 783
def test_name(product_version):
assert product_version.name == 'RHEL-7-RHCEPH-3.1'
def test_description(product_version):
expected = 'Red Hat Ceph Storage 3.1'
assert product_version.description == expected
def test_released_bu... |
<<<<<<< HEAD
<<<<<<< HEAD
from test import support
import unittest
import dummy_threading as _threading
import time
class DummyThreadingTestCase(unittest.TestCase):
class TestThread(_threading.Thread):
def run(self):
global running
global sema
global mutex
# U... |
import random
class Substituicao:
def cifra(self, string, chave):
newData = ""
for c in string:
newData += chr(chave[ord(c)])
return newData
def decifra(self, string, chave):
newData = ""
for c in string:
val = ord(c)
for key, value in chave.items():
if val == value:
... |
import numpy as np
import tensorflow as tf
import h5py
import time
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import sys
def init_weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1, dtype=tf.float32)
return tf.Variable(initial)
def init_bias_variable(shape):
initial ... |
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Kunlun_M.settings')
import django
django.setup()
from core.engine import scan
from core.engine import init_match_rule
from Kunlun_M.settings import EXAMPLES_PATH
from utils.log import logger
from phply import phpast as php
def test_scan():
logger.info('Exam... |
import datetime
import inspect
from .base import BaseObject
from ..exceptions import AttributeNotFoundException, InvalidSizeException
class UserObject(BaseObject):
simple_properties = {
'first_name': None, 'last_name': None, 'username': None,
'time_zone': None, 'gender': None, 'location': None,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.