content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import sys
sys.path.append("/Users/zhouxuerong/projects/autotest/autotest/autotest")
from django.test import TestCase
from apitest.views import Login
from django.http import HttpRequest
class titlePageTest(TestCase):
def test_loginPage(self):
request = HttpRequest()
Response = Login(request)
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
def main():
s = input()
if s == 'Sunny':
print('Cloudy')
elif s == 'Cloudy':
print('Rainy')
else:
print('Sunny')
if __name__ == '__main__':
main()
| nilq/baby-python | python |
from sqlalchemy import MetaData
from sqlalchemy.ext.declarative import declarative_base
metadata = MetaData()
Base = declarative_base(metadata=metadata)
from . import Assignment, Driver, DriverAssignment, Location, LocationPair, MergeAddress, RevenueRate, Trip | nilq/baby-python | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Copyright (c) 2012 Michael Hull.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are m... | nilq/baby-python | python |
import utils
from symbolic.symbolic_types.symbolic_int import SymbolicInteger
from symbolic.symbolic_types.symbolic_type import SymbolicType
from z3 import *
class Z3Expression(object):
def __init__(self):
self.z3_vars = {}
def toZ3(self,solver,asserts,query):
self.z3_vars = {}
solver.assert_exprs([self.pred... | nilq/baby-python | python |
import xgboost as xgb
# read in data
dtrain = xgb.DMatrix('../../data/data_20170722_01/train_data.txt')
dtest = xgb.DMatrix('../../data/data_20170722_01/test_data.txt')
# specify parameters via map, definition are same as c++ version
param = {'max_depth':22, 'eta':0.1, 'silent':0, 'objective':'binary:logistic','min_c... | nilq/baby-python | python |
N = int(input())
N = str(N)
if len(N)==1:
print(1)
elif len(N)==2:
print(2)
elif len(N)==3:
print(3)
elif len(N)>3:
print("More than 3 digits") | nilq/baby-python | python |
from passlib.context import CryptContext
PWD_CONTEXT = CryptContext(schemes=["bcrypt"], deprecated="auto")
def verify_password(plain_password: str, hashed_password: str) -> bool:
return PWD_CONTEXT.verify(plain_password, hashed_password)
def get_password_hash(password: str) -> str:
return PWD_CONTEXT.hash(... | nilq/baby-python | python |
from .simple_ga import SimpleGA
from .simple_es import SimpleES
from .cma_es import CMA_ES
from .de import DE
from .pso import PSO
from .open_es import OpenES
from .pgpe import PGPE
from .pbt import PBT
from .persistent_es import PersistentES
from .xnes import xNES
from .ars import ARS
from .sep_cma_es import Sep_CMA_E... | nilq/baby-python | python |
import random
from model import Actor, Critic
from ounoise import OUNoise
import torch
import torch.optim as optim
GAMMA = 0.99 # discount factor
TAU = 0.01 # for soft update of target parameters
LR_ACTOR = 0.001 # learning rate of the actor
LR_CRITIC = 0.001 # learning rate of the critic
class Agent():
def ... | nilq/baby-python | python |
from __future__ import print_function
from sublime import Region, load_settings
from sublime_plugin import TextCommand
from collections import Iterable
DEBUG = False
def dbg(*msg):
if DEBUG:
print(' '.join(map(str, msg)))
class MyCommand(TextCommand):
def set_cursor_to(self, pos):
""" Set... | nilq/baby-python | python |
import sys
sys.path.append('C:\Python27\Lib\site-packages')
import cv2
import numpy as np
import os
import pytesseract
from PIL import Image
from ConnectedAnalysis import ConnectedAnalysis
import post_process as pp
input_folder = r"C:\Users\SRIDHAR\Documents\python\final\seg_new";
output_folder= "temp";
d... | nilq/baby-python | python |
from pymongo import MongoClient
import os
class Mongo:
def __init__(self):
self.__client = MongoClient(os.environ['MONGODB_CONNECTIONSTRING'])
self.__db = self.__client.WebScrapingStocks
def insert_quotes(self, quotes):
dict_quotes = []
for quote in quotes:
dict_q... | nilq/baby-python | python |
class DubboError(RuntimeError):
def __init__(self, status, msg):
self.status = status
self.message = msg
| nilq/baby-python | python |
test_issue_data = """
#### Advanced Settings Modified? (Yes or No)
## What is your overall Commons Configuration strategy?
{overall_strategy}
### [FORK MY PROPOSAL]() (link)
# Module 1: Token Freeze and Token Thaw
- **Token Freeze** is set to **{token_freeze_period} weeks**, meaning that 100% of TEC tokens minted ... | nilq/baby-python | python |
import unittest
from rooms.room import Room
from rooms.position import Position
from rooms.vector import build_vector
from rooms.actor import Actor
from rooms.vision import Vision
from rooms.geography.basic_geography import BasicGeography
class SimpleVisionTest(unittest.TestCase):
def setUp(self):
self.... | nilq/baby-python | python |
# coding: utf-8
import sys, os
sys.path.append(os.pardir)
import numpy as np
from common.layers import *
from common.gradient import numerical_gradient
from collections import OrderedDict
from dataset.mnist import load_mnist
class SGD:
def __init__(self, lr=0.01):
self.lr = lr
def update(self, param... | nilq/baby-python | python |
# Generated by Django 3.0.7 on 2020-08-04 09:56
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('contr_clienti', '0010_contractscan_actaditional'),
]
operations = [
migrations.AlterField(
mode... | nilq/baby-python | python |
#!/usr/bin/python
import requests, json, fire, os
slack_webhook_url = os.environ['XKCD_SLACK_WEBHOOK_URL']
slack_headers={'Content-Type': 'application/json'}
def slack_post(content):
_slack_post = requests.post(slack_webhook_url, data=json.dumps(content), headers=slack_headers)
return(_slack_post.text)
def ... | nilq/baby-python | python |
import pytest
import torch
from nnrl.nn.actor import (
Alpha,
DeterministicPolicy,
MLPContinuousPolicy,
MLPDeterministicPolicy,
)
from nnrl.nn.critic import ActionValueCritic, MLPVValue
from nnrl.nn.model import EnsembleSpec, build_ensemble, build_single
from ray.rllib import SampleBatch
from raylab.ut... | nilq/baby-python | python |
_base_ = './fcn_r50-d8_512x512_20k_voc12aug.py'
model = dict(pretrained='open-mmlab://resnet101_v1c',
backbone=dict(depth=101),
decode_head=dict(num_classes=2),
auxiliary_head=dict(num_classes=2)
)
dataset_type = 'PLDUDataset' # Dataset type, this will be used to de... | nilq/baby-python | python |
import sys
import os
import argparse
def make_streams_binary():
sys.stdin = sys.stdin.detach()
sys.stdout = sys.stdout.detach()
parser = argparse.ArgumentParser(description='generate random data.')
parser.add_argument('--octets', metavar='N', dest='octets',
type=int, nargs='?', default=2048... | nilq/baby-python | python |
# pvtrace is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# pvtrace is distributed in the hope that it will be useful,
# but WITHOUT... | nilq/baby-python | python |
import numpy as np
import math
import Graphics
from typing import List
import json
from scipy.optimize import fmin_powell
Vector = List[float]
import time
class Node (object):
"""A object that defines a position"""
def __init__(self, name: str, pos, constraint_x=0, constraint_y=0):
"""Node: has a name,... | nilq/baby-python | python |
"""
This commander shell will be a implementation of the PX4 'commander' CLI (https://docs.px4.io/v1.9.0/en/flight_modes/).
Here you can switch modes on the go. Will require root access for safety reasons.
"""
from cmd import Cmd
import logger
import rospy
from mavros_msgs.srv import CommandBool
banner = """
... | nilq/baby-python | python |
from data.scraper import DataScraper
from PIL import Image,ImageFont,ImageDraw
import time
class GenerateTiles:
def __init__(self,FONT,FONT_SIZE,FONT_COLOR,TILE_SIZE,TILE_BG_COLOR):
self.FONT = FONT
self.FONT_COLOR = FONT_COLOR
self.FONT_SIZE = FONT_SIZE
self.TILE_SIZE = TILE_SIZE
self.TILE_BG_COLOR = TILE_... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 2 14:56:30 2020
@author: sanja
"""
import numpy as np
from matplotlib import pyplot as plt
import cv2
import binascii
img = cv2.imread('4119.png')
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY ) # Converting RGB to gray
#height, width = fi ... | nilq/baby-python | python |
from ConexionSQL import ConexionSQL
def clean_api_count():
conSql = ConexionSQL()
conn = conSql.getConexion()
cur = conSql.getCursor()
query = """DELETE FROM tokens_count WHERE tiempo < (current_timestamp - interval \'15 minutes\');"""
cur.execute(query)
conn.commit()
query = 'VACUUM FUL... | nilq/baby-python | python |
def get_knockout_options(model_class, form):
knockout_options = {
'knockout_exclude': [],
'knockout_fields': [],
'knockout_field_names': [],
'click_checked': True,
}
for item in (model_class, form):
if not item:
continue
has_fields_and_exclude =... | nilq/baby-python | python |
# from coursesical.course import *
from course import *
def test0():
t = TimeTable([("08:00", "10:10")])
s = Semester("2021-03-01", t)
r = RawCourse(
name="通用魔法理论基础(2)",
group="(下课派:DD23333;疼逊会议)",
teacher="伊蕾娜",
zc="1-16(周)",
classroom="王立瑟雷斯特利亚",
weekday=0... | nilq/baby-python | python |
from django.conf.urls import url
from bluebottle.funding_flutterwave.views import FlutterwavePaymentList, FlutterwaveWebhookView, \
FlutterwaveBankAccountAccountList, FlutterwaveBankAccountAccountDetail
urlpatterns = [
url(r'^/payments/$',
FlutterwavePaymentList.as_view(),
name='flutterwave-pa... | nilq/baby-python | python |
"""
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related docu... | nilq/baby-python | python |
from django.urls import path
from .views import encuesta
urlpatterns = [
path('', encuesta, name='encuesta'),
]
| nilq/baby-python | python |
#
# PySNMP MIB module REDSTONE-TC (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/REDSTONE-TC
# Produced by pysmi-0.3.4 at Mon Apr 29 20:46:57 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... | nilq/baby-python | python |
import asyncio
import aiohttp
import time
import sys
from aiohttp.client_exceptions import ClientConnectorError
try:
from aiohttp import ClientError
except:
from aiohttp import ClientProxyConnectionError as ProxyConnectionError
from proxypool.db import RedisClient
from proxypool.setting import *
class Tester... | nilq/baby-python | python |
import sys
sys.path.append("..")
import cv2
from CORE.streamServerDependency.camera import Camera
c = Camera()
cv2.namedWindow("test")
while True:
cv2.imshow("test", c.image)
cv2.waitKey(1) | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import image_cropping.fields
class Migration(migrations.Migration):
dependencies = [
('artwork', '0006_auto_20151010_2243'),
]
operations = [
migrations.AlterField(
model... | nilq/baby-python | python |
import image2ascii.boot
import image2ascii.lib
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--filename', required=True, type=str)
parser.add_argument('-W', '--width', type=int)
parser.add_argument('-H', '--height', type=int)
parser.add_argument('-greysav... | nilq/baby-python | python |
import itertools
from intcode import Computer
def run(data):
code = [int(c) for c in data.split(',')]
return find_max_thrust(code)[-1], find_max_thrust_feedback(code)[-1]
def find_max_thrust(code):
max_thrust = 0
for phases in itertools.permutations(range(5), 5):
val = 0
for phase i... | nilq/baby-python | python |
'''
Development Test Module
'''
# import os
import argparse
from dotenv import load_dotenv
#from pyspreader.client import SpreadClient, MSSQLSpreadClient
from pyspreader.worker import SpreadWorker
load_dotenv(verbose=True)
if __name__ == '__main__':
# cli = MSSQLSpreadClient(connection_string=os.environ.get('SPREA... | nilq/baby-python | python |
"""
Django settings for ac_mediator 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/
"""
impor... | nilq/baby-python | python |
import time
import aiohttp
import asyncio
import statistics
runs = []
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main(loop):
for i in range(3):
latencies = []
expected_response = ','.join(['OK']*100)
async ... | nilq/baby-python | python |
import logging
import torch.nn
from torch_scatter import scatter
from nequip.data import AtomicDataDict
from nequip.utils import instantiate_from_cls_name
class SimpleLoss:
"""wrapper to compute weighted loss function
if atomic_weight_on is True, the loss function will search for
AtomicDataDict.WEIGHTS_... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
# Copyright 2017 ROBOTIS CO., LTD.
#
# 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 cop... | nilq/baby-python | python |
import pandas as pd
import S3Api
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer, ENGLISH_STOP_WORDS
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
from sklearn import metrics
from sklearn.decomposition import PCA
import numpy as np
import plotly.express as px
from sklea... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 15 17:35:51 2018
@author: Dr Kaustav Das (kaustav.das@monash.edu)
"""
# import numpy as np
import copy as cp
from math import sqrt, exp, log
from collections import deque
from scipy.stats import norm
# Computes the usual Black Scholes Put/Call formula (not PutBS) for... | nilq/baby-python | python |
import xml.etree.ElementTree as ET
import traceback
def build_crafting_lookup():
# TODO: Keep working on this, I think only one ingredient is in the list currently.
"""
Returns a crafting lookup table
:return:
"""
crafting_dict = {}
itemtree = ET.parse('libs/game_data/items.xml')
item... | nilq/baby-python | python |
def main():
for a in range(1,int(1000/3)+1):
for b in range(a+1, int(500-a/2)+1): # b < c <=> b < 1000-(a+b) <=> b < 500 - a/2
if chkVal(a, b):
print(a * b * (1000-(a+b)))
def chkVal(a, b):
left_term = a**2 + b**2
right_term = (1000 - (a + b))**2
return left_term ==... | nilq/baby-python | python |
import time
from hyades.inventory.inventory import InventoryManager
inventory = InventoryManager('inventory.yml')
connectors_result = {}
for device in inventory.filter(mode='sync'):
connector = device.connection_manager.registry_name
print(f'\nStart collecting {device.name} with {connector}')
connectors_... | nilq/baby-python | python |
from yourproduct.config import Config
CONFIG: Config = Config()
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import print_function
from ._version import get_versions
__author__ = 'Juan Ortiz'
__email__ = 'ortizub41@gmail.com'
__version__ = get_versions()['version']
del get_versions
def hello_world():
print('Hello, world!')
return True
| nilq/baby-python | python |
#!/usr/bin/env python
import json
import time
try:
import requests
except ImportError:
print "Install requests python module. pip install requests"
exit(1)
GREEN = '\033[92m'
RED = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
def check_file(value):
try:
f = open(value)
return f.read()... | nilq/baby-python | python |
"""Tests for provide_url_scheme function."""
from url_normalize.url_normalize import provide_url_scheme
EXPECTED_DATA = {
"": "",
"-": "-",
"/file/path": "/file/path",
"//site/path": "https://site/path",
"ftp://site/": "ftp://site/",
"site/page": "https://site/page",
}
def test_provide_url_sc... | nilq/baby-python | python |
import sys
import os
from datetime import datetime
import unittest
import xlwings as xw
from xlwings.constants import RgbColor
from .common import TestBase, this_dir
# Mac imports
if sys.platform.startswith('darwin'):
from appscript import k as kw
class TestRangeInstantiation(TestBase):
def test_range1(self... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pylab
import numpy
import Image # PIL
from supreme.lib import pywt
im = Image.open("data/aero.png").convert('L')
arr = numpy.fromstring(im.tostring(), numpy.uint8)
arr.shape = (im.size[1], im.size[0])
pylab.imshow(arr, interpolation="nearest", cmap=pylab.cm.gray)
... | nilq/baby-python | python |
import sys
import math
def count_digit(p1, p2):
l1 = len(str(p1))
l2 = len(str(p2))
count = 0
for i in range(l1, l2+1):
if i == l1:
st = p1
else:
st = 10**(i-1)
if i == l2:
ed = p2
else:
ed = 10**i - 1
count += (ed... | nilq/baby-python | python |
from utils import pandaman, handyman
from feature_extraction import data_loader
from feature_extraction import feature_preprocessor
import numpy as np
import pandas as pd
import os
import matplotlib.pyplot as plt
plt.style.use('ggplot')
if __name__ == '__main__':
train_data, test_data = data_loader.create_flat_int... | nilq/baby-python | python |
import numpy as np
import pandas as pd
import pytest
from dku_timeseries import IntervalRestrictor
from recipe_config_loading import get_interval_restriction_params
@pytest.fixture
def datetime_column():
return "Date"
@pytest.fixture
def df(datetime_column):
co2 = [315.58, 316.39, 316.79, 316.2]
countr... | nilq/baby-python | python |
# Dan Thayer
# PID control servo motor and distance sensor.. just messing around
from range_sensor import measure_distance
# gains
k_p = 1.0
k_d = 1.0
k_i = 0.001
def run(target_dist, debug=False):
"""
Sense distance and drive motor towards a given target
:param target_dist: distance in cm
:return:
... | nilq/baby-python | python |
# Copyright 2011 Justin Santa Barbara
#
# 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 l... | nilq/baby-python | python |
from urlparse import urlparse, urlunparse
import re
from bs4 import BeautifulSoup
from .base import BaseCrawler
from ...models import Author, AuthorType
class CitizenCrawler(BaseCrawler):
TL_RE = re.compile('(www\.)?citizen.co.za')
def offer(self, url):
""" Can this crawler process this URL? """
... | nilq/baby-python | python |
import sys
sys.path.insert(1, "../")
import pickle
from story_environment_neuro import *
from decode_redo_pipeline_top_p_multi import Decoder
import numpy as np
from data_utils import *
import argparse
from memoryGraph_scifi2 import MemoryGraph
import datetime
from semantic_fillIn_class_offloaded_vn34 import FillIn
fro... | nilq/baby-python | python |
usrLvl = int(input("What level are you right now (1-50)?"))
usrXP = int(input("What is your XP count right now?"))
usrPrs = int(input("What prestige are you right now (0-10)?"))
usr20 = str(input("Are you a Kamado (write \"y\" or \"n\")?"))
usr10 = str(input("Are you a Tokito or Ubuyashiki (write \"y\" or \"n\")?"))
xp... | nilq/baby-python | python |
import math
import os
import pytest
import torch
from tests import _PATH_DATA
@pytest.mark.skipif(not os.path.exists(_PATH_DATA), reason="Data files not found")
def test_load_traindata():
dataset = torch.load(f"{_PATH_DATA}/processed/train.pt")
assert len(dataset) == math.ceil(25000 / 64)
@pytest.mark.ski... | nilq/baby-python | python |
"""
====================
Fetching Evaluations
====================
Evalutions contain a concise summary of the results of all runs made. Each evaluation
provides information on the dataset used, the flow applied, the setup used, the metric
evaluated, and the result obtained on the metric, for each such run made. These... | nilq/baby-python | python |
#!/usr/bin/python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import argparse
def plot_err_cdf(data1, data2):
"""draw cdf to see the error between without/with freeze"""
err_data = []
for x, y in zip(data1, data2):
err_data.append(abs(x-y))
sorted_err_data = np.sort(er... | nilq/baby-python | python |
from datetime import timedelta
from django.test import TestCase
from django.core.exceptions import ValidationError
from django.utils import timezone
from url_shortener.links.models import Link
class LinkTest(TestCase):
def create_link(self, expires_at=None, short_url="asdf", full_url="https://google.com"):
... | nilq/baby-python | python |
import configparser
from datetime import datetime
import os
import sys
from pyspark.sql import SparkSession
from pyspark.sql.functions import count
from pyspark.sql.types import DateType
def create_spark_session():
spark = SparkSession \
.builder \
.config("spark.jars.packages", "org.apache.hadoop... | nilq/baby-python | python |
from src.loader.interface import ILoader
from src.loader.impl import DataLoader | nilq/baby-python | python |
#!/usr/bin/python
import sys, re
import fabric.docs
import fabric, simplejson, inspect, pprint
from lib import fabfile
action_dir = "./"
def generate_meta(fabfile):
for i in dir(fabfile):
action_meta = {}
fabtask = getattr(fabfile,i)
if isinstance(fabtask,fabric.tasks.WrappedCallableTask):
print "%s is a ... | nilq/baby-python | python |
from spike import PrimeHub
hub = PrimeHub()
while True:
if hub.left_button.was_pressed():
print("Left button was Pressed")
elif hub.right_button.was_pressed():
print("Right button was Pressed")
| nilq/baby-python | python |
from distutils.core import setup
import glob, os
from osg_configure.version import __version__
def get_data_files():
"""
Generates a list of data files for packaging and locations where
they should be placed
"""
# create a list of test files
fileList = []
for root, subFolders, files in os... | nilq/baby-python | python |
import socket
from tkinter import*
#Python socket client by Jeferson Oliveira
#ESSE É O CLIENTE ESSE CÓDIGO DEVER SER ADAPTADO NO PROJETO
HOST = 'ip' #DEFINE O IP DO SERVIDOR
PORT = 11000
tela = Tk()
def LerComando(comando):
if comando == "b1":
botao['text'] = "1"
def de(): #ESSA FUN... | nilq/baby-python | python |
import asyncio
import copy
import logging
import time
from collections import defaultdict
from decimal import Decimal
from typing import Any, Dict, List, Mapping, Optional
from bidict import bidict, ValueDuplicationError
import hummingbot.connector.derivative.binance_perpetual.binance_perpetual_utils as utils
import ... | nilq/baby-python | python |
from sys import *
import csv
def locase(s): return s[:1].lower() + s[1:]
reader = csv.DictReader(stdin, delimiter=',')
for item in reader:
itemstr = item.get('item')
itemid = itemstr[itemstr.rfind('/')+1:]
lang = item.get('itemLabel_lang')
str1 = locase(item.get('str1'))
str2 = locase(item.get('st... | nilq/baby-python | python |
expected_results = {
"K64F": {
"desc": "error when bootloader not found",
"exception_msg": "not found"
}
}
| nilq/baby-python | python |
import random
import json
import torch
from model import NeuralNetwork
from nltk_utils import tokenize,extract_stop_words,stem,bag_of_words
import os
import time
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
with open('intents.json',encoding='UTF-8') as f:
intents = json.load(f)
DATA_FILE... | nilq/baby-python | python |
import time, pytest, inspect
from utils import *
from PIL import Image
def test_mixer_from_config(run_brave, create_config_file):
subtest_start_brave_with_mixers(run_brave, create_config_file)
subtest_assert_two_mixers(mixer_0_props={'width': 160, 'height': 90, 'pattern': 6})
subtest_change_mixer_pattern(... | nilq/baby-python | python |
print 'Welcome to the Pig Latin Translator!'
# Start coding here!
original = raw_input('TELL ME a word in ENGRIXH:').lower()
| nilq/baby-python | python |
from behave import given, when, then
import time
import os
@when("you navigate to CSW homepage")
def step(context):
url = os.environ["CSW_URL"]
context.browser.get(url)
@when('you navigate to CSW page "{path}"')
def step(context, path):
url = os.environ["CSW_URL"] + path
print(url)
context.brows... | nilq/baby-python | python |
from django.contrib import admin
from models import Participant, Exchange
class ParticipantAdmin(admin.ModelAdmin):
pass
class ExchangeAdmin(admin.ModelAdmin):
pass
admin.site.register(Participant)
admin.site.register(Exchange) | nilq/baby-python | python |
import torch
import torch.nn as nn
import torch.nn.functional as F
class CrowdCounter(nn.Module):
def __init__(self, model_name):
super(CrowdCounter, self).__init__()
if model_name == 'AlexNet'.lower():
from .counters.AlexNet import AlexNet as net
elif model_nam... | nilq/baby-python | python |
"""
The file defines the training process.
@Author: Yang Lu
@Github: https://github.com/luyanger1799
@Project: https://github.com/luyanger1799/amazing-semantic-segmentation
"""
from utils.data_generator import ImageDataGenerator
from utils.helpers import get_dataset_info, check_related_path
from utils.callbacks impor... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: gxs
@license: (C) Copyright 2016-2019, Light2Cloud (Beijing) Web Service Co., LTD
@contact: dingjianfeng@light2cloud.com
@software: AWS-DJF
@file: delete_s3_upload_data.py
@ide: PyCharm
@time: 2020/4/16 11:18
@desc:
"""
import base64
import csv
import fnmatch
... | nilq/baby-python | python |
"""
Author: Fritz Alder
Copyright:
Secure Systems Group, Aalto University
https://ssg.aalto.fi/
This code is released under Apache 2.0 license
http://www.apache.org/licenses/LICENSE-2.0
"""
import cppimport
#This will pause for a moment to compile the module
cppimport.set_quiet(False)
m = cppimport.imp("minionn")
#... | nilq/baby-python | python |
import csv
def savetoCSV(data, filename):
# specifying the fields for csv file
fields = ['Term', 'Poem', 'Part of Speech', 'Definition', 'Tags']
# writing to csv file
with open(filename, 'w') as csvfile:
# creating a csv dict writer object
writer = csv.DictWriter(cs... | nilq/baby-python | python |
"""plugins.py contains the main type and base class used by the analyzis plugins.
It also contains the work functions used to load the plugins both from disc and
from the resources."""
from act.scio import plugins
import addict
from importlib import import_module
from importlib.machinery import ModuleSpec
from import... | nilq/baby-python | python |
from pathlib import Path
import pytest
from pytest_mock.plugin import MockerFixture
from dotmodules.renderer import ColorAdapter, Colors
@pytest.fixture
def colors() -> Colors:
return Colors()
@pytest.fixture
def color_adapter() -> ColorAdapter:
return ColorAdapter()
class TestColorTagRecognitionCases:
... | nilq/baby-python | python |
# Copyright 2017 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Driver for Parade PS8742 USB mux.."""
import hw_driver
import i2c_reg
class Ps8742Error(hw_driver.HwDriverError):
"""Error occurred accessing ps874... | nilq/baby-python | python |
import jwt
import datetime
import tornado.testing
import tornado.httpserver
import tornado.httpclient
import tornado.gen
import tornado.websocket
from app import Application
APP = Application()
JWT_TOKEN_EXPIRE = datetime.timedelta(seconds=5)
class ChatAuthHandler(tornado.testing.AsyncTestCase):
def setUp(self)... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
(베타) PyTorch를 사용한 Channels Last 메모리 형식
*******************************************************
**Author**: `Vitaly Fedyunin <https://github.com/VitalyFedyunin>`_
**번역**: `Choi Yoonjeong <https://github.com/potatochips178>`_
Channels last가 무엇인가요
----------------------------
Channels last 메모... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import sys
import codecs
import os.path
from youtubeAPICrawler.database import *
#sys.stdout = codecs.getwriter('utf8')(sys.stdout)
db = YTDatabase()
data_dir = '../../../data/'
studio71 = 'network_channel_id_studio71.json'
maker = 'network_channel_id_maker.json'
broadtv = 'network_channel... | nilq/baby-python | python |
import glob, os
from random import shuffle
import numpy as np
from PIL import Image
import pycuda.driver as cuda
import tensorrt as trt
import labels
import calibrator
MEAN = (71.60167789, 82.09696889, 72.30508881)
MODEL_DIR = 'data/fcn8s/'
CITYSCAPES_DIR = '/data/shared/Cityscapes/'
TEST_IMAGE = CITYSCAPES_DIR + 'l... | nilq/baby-python | python |
import numpy as np
import os, errno
from PyQt4 import QtGui,QtCore
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg
from saltgui import MplCanvas
class FpParallWidget (QtGui.QWidget):
def __init__(self,parent=None):
super(FpParallWidget,self).__init__(... | nilq/baby-python | python |
from logging import NullHandler
from ast import literal_eval
import io
class RequestCountHandler(NullHandler):
def __init__(self,queue):
NullHandler.__init__(self)
self.queue = queue
def handle(self, record):
if False and "request" in record.msg:
print("adding")
... | nilq/baby-python | python |
from .network import launch_in_thread
from . import ui
import argparse
from ..logs import logger
def main(capture_file=None):
ui.init(launch_in_thread, capture_file)
ui.async_start()
if __name__ == "__main__":
logger.debug("Starting sniffer as __main__")
parser = argparse.ArgumentParser(
d... | nilq/baby-python | python |
import os
import sqlite3
try:
from psycopg2cffi import compat
compat.register()
except ImportError:
pass
from sqlalchemy import Column, Integer, String, ForeignKey, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
import pytest
@pytest.fixtur... | nilq/baby-python | python |
import time
from django.contrib.auth.models import User
from django.urls import reverse
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium.webdriver.firefox.webdriver import WebDriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support.ui import Se... | nilq/baby-python | python |
#!/usr/bin/env python3
import datetime
import logging
import os.path
import rescale.client
# Remember to set RESCALE_API_KEY env variable to your Rescale API key
# on platform.rescale.com (in Settings->API)
SHORT_TEST_ARCHIVE = 'inputs/all_short_tests.tar.gz'
LONG_TEST_FORMAT = 'inputs/long_test_{i}.tar.gz'
LONG_TES... | nilq/baby-python | python |
#!/usr/bin/env pybricks-micropython
from pybricks.hubs import EV3Brick
from pybricks.ev3devices import InfraredSensor
from pybricks.parameters import Port, Button
from pybricks.tools import wait
from pybricks.media.ev3dev import SoundFile, Font
# Create the brick connection.
ev3 = EV3Brick()
# Set Font.
print_font = ... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.