content stringlengths 5 1.05M |
|---|
#!/usr/bin/python3
from kivy.app import App
from kivy.core.window import Window
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.scrollview import ScrollView
from... |
#
# Copyright (c) 2018 Juniper Networks, Inc. All rights reserved.
#
from vnc_api.gen.resource_common import SflowProfile
from vnc_cfg_api_server.resources._resource_base import ResourceMixin
class SflowProfileServer(ResourceMixin, SflowProfile):
@staticmethod
def is_profile_editable(obj_dict):
is_d... |
import json
from .exceptions import AskhomeException, UnsupportedTargetError, UnsupportedOperationError
from .requests import create_request
from . import logger
class Smarthome(object):
"""Holds information about all appliances and handles routing requests to appliance actions.
Attributes:
applianc... |
from distutils.core import setup
from trombi import version
setup(
name='trombi',
version='.'.join(map(str, version)),
description='CouchDB client for Tornado',
license='MIT',
author='Inoi Oy',
author_email='inoi@inoi.fi',
maintainer='Jyrki Pulliainen',
maintainer_email='jyrki.pulliaine... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals, division
from collections import defaultdict
class SupplyTracker(object):
def add_to_units_alive(self, event, replay):
unit_name = event.unit_type_name
if unit_name in self.unit_name_to_supply:
... |
#!/usr/bin/env vpython3
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Can be used to point environment variable to hermetic Go toolset.
Usage (on linux and mac):
$ eval `./env.py`
$ go version
Or it ... |
from ..views.base import BasePasswordResetConfirmationViewsTestCase
# Create your tests here.
class PasswordResetConfirmationIntegrationTestCase(BasePasswordResetConfirmationViewsTestCase):
# ======================================================================
@classmethod
def setUpTestData(cls):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys, re
class CARPE_FS_Alloc_Info(object):
"""docstring for CARPE_FS_Alloc_Info"""
def __init__(self):
super(CARPE_FS_Alloc_Info, self).__init__()
self._p_id = None
self._unallock_blocks = []
|
import pandas as pd
import streamlit as st
import queries
import utils
import visualization
from constants import STATES, EQUITY_DATA_TABLE, TRANSPORT_DATA_TABLE, LINKS
def census_equity_explorer():
indent = 4
st.title('Equity Explorer')
st.write('''
### Select a Geography
Iden... |
import smtplib
def sendEmail(event_name, to_users, start_date, end_date, url=""):
gmail_user = "webusability.ssd@gmail.com"
gmail_password = "Ea6thorq5FM*jxvJ"
sent_from = str(gmail_user)
to = to_users
# url = "https://www.google.com"
message = """\
Subject: Your usability test has been schedu... |
#!/usr/bin/env python
import os
import sys
import getopt
TESTNAME = "union"
# generate bindings in this folder
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "k", ["keepfiles"])
except getopt.GetoptError as e:
print str(e)
sys.exit(127)
k = False
for o, a in opts:
if o in ["-k", ... |
import numpy as np
import tensorflow as tf
import gym
import random
import sys
import math
import matplotlib.pyplot as plt
import time
# Define Functions
def init_value_function():
with tf.variable_scope('value_function'):
# Defining NN Structure for value function
# Layer 0
state = tf.p... |
# coding=utf-8
"""MSN for Microservice Node define Microservice Node attrs and method"""
|
import unittest
import requests
class HelpTest(unittest.TestCase):
def setUp(self):
self.endpoint = 'http://127.0.0.1:8081/manage'
self.tlf = '+34666349989'
# self.medium = 'https://medium.com/@hackupc/meet-the-team-directors-6eca8b7c9fbb'
self.medium = 'https://medium.com/vantage... |
from .obs_sym_plus import ObsSymPlus
from .policy_sym_plus import PolicySymPlus
|
#!/usr/local/bin
"""
Author: Kelly Sovacool
Email: kellysovacool@uky.edu
28 Sept. 2017
Usage:
count_blast_records_and_hits.py <blast_result_xml>
"""
import Bio.Blast.NCBIXML
import docopt
def main(args):
count_records = 0
count_alignments = 0
count_hits = 0
with open(args['<blast_result_xml>'], ... |
# Generated by Django 2.2.5 on 2019-11-16 01:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shopify', '0019_shopifycollection'),
]
operations = [
migrations.AlterField(
model_name='shopifymetafield',
name='ow... |
class Solution:
# @param grid, a list of lists of integers
# @return an integer
def minPathSum(self, grid):
if not grid: return 0
line = []
M = len(grid)
N = len(grid[0])
for m in range(M):
for n in range(N):
if m == 0:
... |
import pytest
import hgvs.easy
@pytest.fixture(scope="session")
def parser():
return hgvs.easy.parser
@pytest.fixture(scope="session")
def am38():
return hgvs.easy.am38
|
# oop/mro.simple.py
class A:
label = 'a'
class B(A):
label = 'b'
class C(A):
label = 'c'
class D(B, C):
pass
d = D()
print(d.label) # Hypothetically this could be either 'b' or 'c'
print(d.__class__.mro()) # notice another way to get the MRO
# prints:
# [<class '__main__.D'>, <class '__main__.... |
from pyradioconfig.parts.bobcat.calculators.calc_global import Calc_Global_Bobcat
class calc_global_viper(Calc_Global_Bobcat):
pass |
#MenuTitle: New Tab with Locked Components
# -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
__doc__="""
Opens a new Edit tab containing all glyphs that have locked components in them.
"""
def isLayerAffected( l ):
if l.isMasterLayer or l.isSpecialLayer:
for c in l.components... |
# pyflakes: disable-all
from .views import *
from .widget import *
|
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: rastervision/protos/deeplab/train.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf i... |
"""
Class that provides layers from a given SAM template
"""
import logging
import six
from .provider import LayerProvider, Layer
from .sam_base_provider import SamBaseProvider
LOG = logging.getLogger(__name__)
class SamLayerProvider(LayerProvider):
"""
Fetches and returns CFC Layers from a SAM Template. T... |
from torch.utils.data import Dataset
import librosa as lib
import os
import numpy as np
import torch
import train_utils
from torch.utils.data import DataLoader
import random
import torch.nn.functional as F
import torchaudio
def load_wav(path):
signal, _ = torchaudio.load(path)
signal = signal.reshape(-1)
... |
#coding:utf-8
#
# id: bugs.core_4675
# title: Conditions like WHERE <field> = <cursor>.<field> do not use existing index
# decription:
# tracker_id: CORE-4675
# min_versions: ['3.0']
# versions: 3.0
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
# ver... |
#! /usr/bin/env python
# System imports
from distutils.core import *
from distutils import sysconfig
# Third-party modules - we depend on numpy for everything
import numpy
# Obtain the numpy include directory. This logic works across numpy versions.
try:
numpy_include = numpy.get_include()
except Attribute... |
import sys
import random
"""
Generates test and result files for given fasta file
"""
if len(sys.argv) != 5:
print "Invalid number of arguments. Example usage: python testCommandGenerator.py randIntervalSize fastaFile testOutput resultOutputs"
print "\t\tpython testFileGenerator.py 20 fasta.txt test.txt re... |
import torch
import numpy as np
from transformers import BertTokenizer, BertForSequenceClassification
class BERT:
def set_device(self):
"""
Sets device as 'GPU' or 'CPU'
"""
# if there's a GPU available...
if torch.cuda.is_available():
# tell PyTorch to use the ... |
# -*- encoding: utf-8 -*-
import os
from getpass import getpass
from pkg_resources import resource_string
from paramiko.client import (
SSHClient,
MissingHostKeyPolicy,
)
class ConfigurationGenerator(MissingHostKeyPolicy):
"""
Generates a config file from given input.
"""
def __init__(self... |
import decimal
from datetime import datetime, date, time, timedelta
from fractions import Fraction
from ipaddress import (
IPv4Address, IPv6Address,
IPv4Network, IPv6Network,
IPv4Interface, IPv6Interface,
)
from operator import attrgetter
from pathlib import Path
from typing import Type, Dict, Any, Generic,... |
XXXXXXXXXXXXXXXXXX
XXXXXXX XXXX XXXXX
XXXXXXXXXXXXXXXXXX
XX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXX XXXXXXX XXXXXX XXXXXXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX
XXXXX XXX XXXXXXXXXX XXXXXXXXX XXXXX XXX XXXXXXXXXX XXXXX
XX XXXXXX
XXXX XX XXX XXXXXXXX XX XXXX XXXX XXXXXX XXXX XX XXXXXXXXXXX XXXXX XXX ... |
"""
Subset of repo2docker functionality focused on primarily Python projects.
Supports the following files from repo2docker:
1. environment.yml
2. requirements.txt
3. runtime.txt
4. postBuild
5. start
We try to re-use code from repo2docker wherever possible
"""
from traitlets.config import LoggingConfigurable, Appli... |
"""Test estimate the cost of a job."""
from nameko_sqlalchemy.database_session import Session
from tests.utils import get_configured_job_service, get_random_user
class TestEstimateJob:
"""Test the estimate method for a job."""
def test_default_estimates(self, db_session: Session) -> None:
"""Check t... |
import re
import textwrap
from collections import defaultdict
EMOJI_LINE = re.compile(r'"([^"]+)": +"([^"]+)", +# (.+)', flags=re.UNICODE)
HEADING_LINE = re.compile(r'([A-Z_]+)\s+=\s+{', flags=re.UNICODE)
def main():
blocks = defaultdict(list)
current_heading = ""
with open("emojizones/lookup.py", "r") as... |
import sqlite3
from contextlib import contextmanager
import re
import os
import time
import random
import json
from bs4 import BeautifulSoup as Soup
import requests
import click
from colorama.ansi import Fore, Back, Style, clear_line, Cursor, clear_screen, set_title
URL_TEMPLATE = "https://open.spotify.com/artist/{}... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:
from easyai.base_name.block_name import NormalizationType, ActivationType
from easyai.model.base_block.utility.base_block import *
from easyai.model.base_block.utility.utility_block import ActivationConvBNBlock
from easyai.model.base_block.utility.separable_conv_b... |
from .sensorpack import SensorPack as SensorDict
from .sensorpack import SensorPack
|
#!usr/bin/env -python
import re
import os
import base64
import argparse
import datetime
import subprocess
import ConfigParser
import gdata
import gdata.docs.service
import gdata.spreadsheet.service
from scilifelab.google import get_credentials
from scilifelab.google.google_docs import SpreadSheet
## declaring argumen... |
"""
Single-threaded web application service framework designed as an alternative to
ordinary desktop application development. See http://github.com/kjosib/kali
HTTP is essentially a request/respond protocol:
The server proceeds by first building a request object (based on whatever the
browser transmits) and then route... |
import os
import pytest
from firepit.exceptions import IncompatibleType
from firepit.exceptions import InvalidAttr
from firepit.exceptions import InvalidStixPath
from firepit.exceptions import InvalidViewname
from firepit.exceptions import StixPatternError
from .helpers import tmp_storage
@pytest.fixture
def invali... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
def wind_turbine_model(x):
# cut-in pseed vs cut-out speed
if x<4.5 or x>21.5:
return 0
# standard operability
return 376.936 - 195.8161*x + 33.75734*x**2 - 2.212492*x**3 + 0.06309095*x**4 - 0.0006533647*x**5
# load dat... |
from __future__ import print_function, division
from values import NIL, LispType, LispValue, Symbol, Value, Pair
from parse import parse_token_prompt, parse_program
from operator import mul
import random
random.seed()
import os.path
# overwritten in the executible
PERMISSIVE = False
class LispRuntimeError(BaseEx... |
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
import logging
def _p_shape(tensor,msg):
if (FLAGS.debug):
return tf.Print(tensor, [tf.shape(tensor)], msg,summarize= 100)
else:
return tensor
def _p(tensor,msg):
if (FLAGS.debug):
return tf.Print(tensor, [tensor], msg,summarize= 1... |
import simpy
from gacoan import config
from gacoan.roles import Role
class Cashier(Role):
"""
Role in charge of handling orders and payments.
"""
def __init__(self, env: simpy.Environment) -> None:
super().__init__(env, config.CASHIER_CAPACITY, config.CASHIER_TIME)
|
from django.contrib.auth import get_user_model
from django.core.management import call_command
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Generate superusers, users and app data"
def handle(self, *args, **options):
call_command("makemigrations")
ca... |
''' Gaussian Noise Component
This module contains the class for Gaussian Noise
Author: Bennet Meyers
'''
import cvxpy as cvx
import numpy as np
from osd.components.component import Component
class MeanSquareSmall(Component):
def __init__(self, size=1, **kwargs):
super().__init__(**kwargs)
self.... |
from .client import MonzoClient |
from django.apps import AppConfig
class AutovcConfig(AppConfig):
name = 'autovc'
|
import simplegui
import random
import math
class Grid():
def __init__(self):
self.grid = []
for n in range(4):
newrow = []
for d in range(4):
newrow.append(0)
self.grid.append(newrow)
def get_grid(self):... |
import tensorflow as tf
def slide_window(image, window_width, window_stride):
"""
Takes (image_height, image_width, 1) input,
Returns (num_windows, image_height, window_width, 1) output, where
num_windows is floor((image_width - window_width) / window_stride) + 1
"""
kernel = [1, 1, window_wid... |
from keras.layers.core import Dropout
from keras.layers.core import Flatten
from keras.layers.core import Dense
class FCHeadNet:
def build(baseModel, classes, D):
headModel = baseModel.output
headModel = Flatten(name="flatten")(headModel)
headModel = Dense(D, activation="relu")(headModel)
headModel = Dropout(... |
# coding: utf-8
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^check_token/$', views.check_token),
url(r'^check_login_password/$', views.check_login_password),
url(r'^check_perm/$', views.check_perm),
url(r'^api_token_auth/$', views.obtain_auth_token),
]
|
import socket, random, time
import GeneralAttribute
# Create a datagram socket
UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
def StartSending():
# Bind to address and ip
UDPServerSocket.bind((GeneralAttribute.localIP, GeneralAttribute.localPort))
print("Thread Sender Start... |
"""168. Excel Sheet Column Title"""
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
# Practice:
capitals = [chr(x) for x in range(ord("A"), ord("Z")+1)]
res = ''
while n != 0:
res = str(capitals[(n-1)%... |
from flask import request
from flask.ext.cors import cross_origin
from voteit.core import app, motions, vote_events, issues
from voteit.util import jsonify, paginate_cursor, obj_or_404
from werkzeug.exceptions import BadRequest
from bson.objectid import ObjectId
#------
# Issues API
#-------
# HERE BE DRAGONS!
# ... |
#!/usr/bin/env python3
"""
Utilities used internally by climopy.
"""
def _first_unique(args):
"""
Return first unique argument.
"""
seen = set()
for arg in args:
if arg not in seen:
yield arg
seen.add(arg)
def _make_logger(name, /, level='error'):
"""
Return a... |
# python standard library
import re
# this package
from apetools.baseclass import BaseClass
from apetools.commons.errors import CommandError
from apetools.parsers import oatbran
NEWLINE = "\n"
class WmicEnumeration(object):
__slots__ = ()
code = "code"
# class WmicEnumeration
class WmicWin32NetworkAdapter(... |
import unittest
from tyckiting_client.ai.strategies.triangleShot import TriangleShot
from tyckiting_client.messages import Pos, Bot, Event
class TriangleShotTest(unittest.TestCase):
def setUp(self):
self.triShot = TriangleShot()
self.bots = [
Bot(0, 'bot1', 1, True, {"x":-13,"y":5}, 10),
Bot(1, 'bot2', 1,... |
from app.utilities.schema import load_schema_from_name
from tests.app.app_context_test_case import AppContextTestCase
class SchemaLoaderTest(AppContextTestCase):
def test_load_schema_from_name(self):
self.assertIsNotNone(load_schema_from_name("test_checkbox"))
def test_load_schema_with_different_sche... |
import numpy as np
import net.utilities
class TestEncoder:
def test_encoding(self):
labels = ["A", "B", "C", "D"]
encoder = net.utilities.Encoder(labels)
assert np.all(np.array([0, 1, 0, 0]).reshape(4, 1) == encoder.encode("B"))
assert np.all(np.array([0, 0, 0, 1]).reshape(4, 1)... |
import logging
from django.contrib.auth import get_user_model
from django.http import HttpRequest
from . import settings
from .models import MagicLink, MagicLinkError
User = get_user_model()
log = logging.getLogger(__name__)
class MagicLinkBackend():
def authenticate(
self,
request: HttpReques... |
from pytest_django.asserts import assertTemplateUsed
import pytest
@pytest.mark.django_db
class TestMessagesViews:
def test_direct_message_main_view_without_authentication(self, client, persist_user):
client.force_login(persist_user)
client.logout()
response = client.get('/direct/')
... |
import logging
import os
from .helper import build_zip_for_object, subject_for_object
from .settings import PKI_ENABLE_EMAIL
if PKI_ENABLE_EMAIL is True:
try:
from django.core.mail import EmailMessage
# import zipfile
except ImportError as e:
raise Exception(
"Library impo... |
import asyncio
import logging
from tracardi.config import tracardi
from tracardi.exceptions.log_handler import log_handler
from tracardi.service.postpone_cache_multi_threaded import PostponeCache, InstanceCache
logger = logging.getLogger(__name__)
logger.setLevel(tracardi.logging_level)
logger.addHandler(log_handler)... |
import glob
from sentinel import jp2_to_cog
import os
import rasterio
import subprocess
def perform_atmospheric_corrections(product):
sentinel_product_dir = product['filename']
date = product['filename'][11:19]
tile = product['filename'][39:44]
corrected_images = glob.glob(f"*2A_{date}*_T{tile}_*.SAFE/... |
# -*- coding: utf-8 -*-
# Resource object code
#
# Created by: The Resource Compiler for PyQt5 (Qt v5.15.1)
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore
qt_resource_data = b"\
\x00\x00\x01\x46\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x18\x... |
#!/usr/bin/env python
#######################################################
# Copyright (c) 2015, ArrayFire
# All rights reserved.
#
# This file is distributed under 3-clause BSD license.
# The complete license agreement can be obtained at:
# http://arrayfire.com/licenses/BSD-3-Clause
###############################... |
import pytest
import sys
import os
from unittest import mock
from requests import exceptions
import aiohttp
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from fake_useragent import aio_main, main, errors, settings
def test_main_fetch():
assert main.fetch("https://i3wm.org") is no... |
from overrides import overrides
from typing import List
from allennlp.common.util import JsonDict
from allennlp.data import DatasetReader, Instance
from allennlp.data.tokenizers.word_splitter import JustSpacesWordSplitter
from allennlp.models import Model
from allennlp.predictors.predictor import Predictor
from allennl... |
from nova.exception import NovaException
from nova.i18n import _
class ServiceGroupUnavailable(NovaException):
msg_fmt = _("The service from servicegroup driver %(driver)s is "
"temporarily unavailable.") |
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import AbstractUser
class Account(AbstractUser):
"""Extend django's user model with added fields."""
tagline = models.TextField(max_length=250)
created_at = models.DateTimeField(auto_now_add=True)
up... |
import unittest
from unittest.mock import Mock, MagicMock, patch
import json
import datetime
from ses_client import SesClient
from meetup_client import MeetupClient
from app import App
GROUP_URLNAME = 'Group-Urlname'
NOW = datetime.datetime.now()
DEFAULT_EVENT_START_TIME_HOURS_FROM_NOW = 48
DEFAULT_NOTIFY_PERIOD_HOURS... |
import unittest
import balance
class TestBalance(unittest.TestCase):
def test_balance(self):
result = balance.get_holder_balance(56, '0x7EC1EdCB89343A8DF4329Ad94C174458225105aE', '0x68E596b8122Ac6F4Ddc2C897CFf816C31E309eB3')
self.assertIsNotNone(result)
self.assertGreater(float(result), 0... |
import lenstronomy.Util.constants as const
import numpy as np
__all__ = ['Cosmo']
class Cosmo(object):
"""
cosmological quantities
"""
def __init__(self, d_d, d_s, d_ds):
"""
:param d_d: angular diameter distance to the deflector
:param d_s: angular diameter distance to the s... |
"""
Django settings for musicbrainz project.
Generated by 'django-admin startproject' using Django 2.1.4.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import o... |
# Copyright 2017 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
import functools as ft
import inspect
import json
import typing
from collections import defaultdict
from types import SimpleNamespace
from typing import Any, Callable, Collection, Dict, Optional, Type
import multidict
import pydantic
from aiohttp import web
def extract_annotations(
func: Callable,
bo... |
import unittest
from typing import List
# this adds the 'src' folder to the path. Needed to get the src imports to work in unit tests.
import config
import inputHelper
import src.day06 as puzzle
_DAY = 6
class Day06(unittest.TestCase):
"""
Day 6: Universal Orbit Map
https://adventofcode.... |
#Copyright 2013 Pieter Rautenbach
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
import argparse
def InputParser():
parser=argparse.ArgumentParser(description="Vision Transformers for Tomography Data")
parser.add_argument('--dataset',default='zeiss',help="Defines the tomography image dataset")
parser.add_argument('--class',default='pores',help="Defines fault type to be identified in... |
import os
from venv import create
# force numpy to use only a single processor, by changing the environment of the underlying libraries
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
os.environ["OMP_NUM_THREADS"] = "1"
import numpy as np
import time
import random
import tqdm
def chunkify(... |
# Generated by Django 2.2.8 on 2020-01-21 14:44
import django.contrib.gis.db.models.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('boundaries', '0014_country'),
]
operations = [
migrations.AddField(
model_name='country',
... |
'''
Blink
Turns on an on-board LED on for one second, then off for one second repeatedly.
Most Arduinos have an on-board LED you can control. On the Uno and Leonardo,
it is attached to digital pin 13. If you're unsure what pin the on-board LED
is connected to on your Arduino model, check the doc at http://arduino.cc
... |
import unittest
import json
from apiaiWebhookSerializer import Response
class TestReponse(unittest.TestCase):
speech = "I love cupcake"
displayText = "Cupcake ipsum dolor sit amet jelly-o danish marshmallow oat cake. \
Oat cake caramels caramels croissant topping icing carrot cake. \
... |
# For better print formatting
from __future__ import print_function
# Imports
from pycompss.api.task import task
from pycompss.api.parameter import *
FILE_NAME="dummy_file.txt"
CONTENT="Content"
RENAMED_SUFFIX=".IT"
@task(filename={Type:FILE_OUT, Keep_rename:True})
def write_file_kr(filename, text):
print("Fil... |
import struct, time
from usb.core import USBError
from pyftdi.ftdi import FtdiError
from array import array
from enum import Enum, auto
from pydispatch import dispatcher
from base import ECU
class ECUSTATE(Enum):
OFF = auto()
UNKNOWN = auto()
OK = auto()
FLASH = auto()
SECURE = auto()
RECOVER_O... |
#!/usr/bin/env python
import vtk
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# Interpolate onto a volume
# Parameters for debugging
NPts = 1000000
math = vtk.vtkMath()
math.RandomSeed(31415)
# create pipeline
#
points = vtk.vtkBoundedPointSource()
points.SetNumberOfPoints(NPts)
points.P... |
# Time: O(n * glogg), g is the max length of a string in input.
# Space: O(n * g)
#
# Given an array of strings, return all groups of strings that are anagrams.
#
# Note: All inputs will be in lower-case.
#
import collections
class Solution(object):
def groupAnagrams_noSort(self, strs): # USE THIS: better O(n *... |
# pyxpcconnection: OS X XPC Bindings for Python
#
# Copyright (c) 2015 Matthew Else
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# U... |
from nn.nn import NeuralNetwork
D=[[[0,0],[0]],[[1,0],[1]],[[0,1],[1]],[[1,1],[0]]]
nn=NeuralNetwork(2,[2,2],1,lr=0.0075)
while (nn.test(D,log=False)<95):
nn.train_multiple(D,5000,log=False)
print("Accuracy: "+str(nn.test(D,log=False)))
a=nn.test(D)
print("="*40+"\nACCURACY: "+str(a)+"\n"+"="*40) |
from flask import Blueprint
from flask.views import MethodView
from flask import (request, jsonify)
from apps.students.models import Student
from apps.students import tools
from apps import utils
from apps import config
students_bp = Blueprint('students', __name__)
def student_retrieve(sid):
ret = {
'co... |
import time
import os.path
import logging
import hashlib
import fnmatch
import datetime
from colorama import Fore
from piecrust import CACHE_DIR
from piecrust.baking.baker import Baker
from piecrust.baking.records import (
BakeRecord, BakeRecordEntry, SubPageBakeInfo)
from piecrust.chefutil import format_timed
... |
from tornado.web import RequestHandler
class BaseHandler(RequestHandler):
"""A handler class is defined by its main possible requests
and other necessary functions.
"""
def initialize(self, **kwargs):
"""It serves as the basic initializer of every incoming request.
"""
# De... |
"""
Module with hooks saving the trained model under certain criteria.
"""
import logging
import numpy as np
from . import AbstractHook, EveryNEpoch
from ..models import AbstractModel
from ..types import EpochData
class SaveEvery(EveryNEpoch):
"""
Save the model every ``n_epochs`` epoch.
.. code-block:... |
import unidecode, json, re
text = "{'gender': 'masculino','pageName': 'Index','ET': 'cmspage','brandName':'','pageCategorySubcategoryBrand': '','pageType': '','skuTop3' : ['','',''],'wt_cc1':'','wt_cc2':'','wt_cc3':'','wt_cc4':'','wt_cc5':'','wt_cc6':'','keyword' : '','googleRemarketingLabel' : 'UWWxCIyIlAIQ5NyG1gM'}"... |
#
# (c) PySimiam Team 2013
#
# Contact person: Tim Fuchs <typograph@elec.ru>
#
# This class was implemented as a weekly programming excercise
# of the 'Control of Mobile Robots' course by Magnus Egerstedt.
#
from controllers.pid_controller import PIDController
import math
import numpy
from pose import Pose
class Avoid... |
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from website.models import Contest, User, Exam, Mathlete, Team, Problem
from django.utils import timezone
from website.tasks import init_all_tasks, check_finished_games_real, final_ai_grading
from website.utils import update_c... |
import graphene
from .person import schema as person_schema
from .events.birth import schema as birth_schema
class Query(
person_schema.Query,
birth_schema.Query,
graphene.ObjectType,
):
pass
class Mutation(
person_schema.Mutation,
birth_schema.Mutation,
graphene.ObjectType,
):
pass... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.