text stringlengths 8 6.05M |
|---|
from keras.models import Sequential
from keras.callbacks import EarlyStopping
from keras.layers import Dense, Dropout, BatchNormalization
import numpy
import tensorflow as tf
#시드값 생성
seed = 0
numpy.random.seed(seed)
tf.set_random_seed(seed)
#데이터 로드
dataset = numpy.loadtxt('./data/pima-indians-diabetes.csv', delimiter... |
from models import Category, Subcategory
def categories(request):
categories = Category.objects.all()
subcategories = {}
for cat in categories:
subcategories[cat.name] = cat.subcategory_set.all()
return {'categories':categories, 'subcategories':subcategories}
|
from selenium import webdriver
import time
driver = webdriver.Chrome(executable_path="C:/Users/ABHAY/Selenium/chromedriver.exe")
driver.implicitly_wait(10)
driver.maximize_window()
driver.get("http://the-internet.herokuapp.com/infinite_scroll")
time.sleep(2)
n = 4
for i in range(0,4):
driver.execut... |
import os
import xlrd
from tqdm import tqdm
def all_files_path(rootDir):
f1 = open('dir.txt', 'a', encoding='utf-8')
filepaths = []
for root, dirs, files in os.walk(rootDir):
for file in files:
file_path = os.path.join(root, file)
filepaths.append(file_path)
for file... |
import SimpleHTTPServer
import SocketServer
PORT = 8008
class MyHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def end_headers(self):
self.send_my_headers()
SimpleHTTPServer.SimpleHTTPRequestHandler.end_headers(self)
def send_my_headers(self):
self.send_header("Cache-Control", "no-ca... |
import unittest
from katas.kyu_8.days_in_the_year import year_days
class YearDaysTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(year_days(0), '0 has 366 days')
def test_equals_2(self):
self.assertEqual(year_days(-64), '-64 has 366 days')
def test_equals_3(self):
... |
'''
|Задание 1| Дан список из чисел. Напишите программу, которая удаляет
все четные числа из списка и выводит список через print()
nums = [14, 21, 565, 18, 33, 20, 102, 108, 167, 891, 400]
|Задание 2| Дан список слов. Напишите программу, которая находит
слова длиннее 4 букв и записывает их в другой список.
sentence = ... |
import argparse
import json
import joblib
from pathlib import Path
import rlkit.torch.pytorch_util as ptu
from rlkit.core.eval_util import get_generic_path_information
from rlkit.torch.tdm.sampling import multitask_rollout
from rlkit.core import logger
if __name__ == "__main__":
parser = argparse.ArgumentParser(... |
height = float(input('type the height the wall'))
widht = float(input('Type the widht the wall'))
area = height * widht
paint = area / 2
print('The total area the wall is {} you need {} buckets of ink'.format(area,paint)) |
import lists,scraper,parsing,objects
import veggieTransformer
import healthyTransformer
import cuisineTransformer
cuisineTypes = ['indian','mexican','chinese']
def main():
lists.ingredientDB = parsing.readIngredientsFromFile('FOOD_DATA/FOOD_DES.txt')
lists.updateNameDB()
debug = True
#Welcome message
... |
class Polynomial(object):
def __init__(self, coeffs):
if (type(coeffs) is list) and all(isinstance(x,(int, float)) for x in coeffs):
i=0
n=len(coeffs)-1
while i<n and coeffs[i]==0:
i=i+1
self.coeffs = coeffs[i:(n+1)]
self.n=len(self... |
# -*- encoding:utf-8 -*-
from __future__ import print_function
import os
import random
import shutil
import pandas as pd
from Decorator import warnings_filter
'''
cPickle是C语言写的,速度快,pickle是纯Python写的,速度慢
'''
try:
import cPickle as pickle
except ImportError:
import pickle
def write_chr(f, ch):
f.write(ch... |
from django import forms
from .models import Purchase
class MakePaymentForm(forms.Form):
MONTH_CHOICES = [(i, i) for i in range(1, 12)]
YEAR_CHOICES = [(i, i) for i in range(2018, 2036)]
credit_card_number = forms.CharField(label='Card Number', required=False)
cvv = forms.CharField(label="Security... |
'''
Problem: You have 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, you visit every door and toggle the door (if the door is closed, you open it; if it is open, you close it). The second time you only visit every 2nd door (door #2, #4, #6, ...). The third ti... |
from flask import Flask, jsonify, flash, request, redirect, render_template
import pandas as pd
from transformers import load_transformers
import pickle
import os
localhost = '0.0.0.0'
ALLOWED_EXTENSIONS = set(['csv'])
app = Flask(__name__)
# flask uploader folder
app.config['UPLOAD_FOLDER'] = 'download/'
# loadin... |
# -*- coding: utf-8 -*-
"""Amazon boto interface."""
from __future__ import absolute_import, unicode_literals
try:
import boto
except ImportError: # pragma: no cover
boto = get_regions = ResultSet = RegionInfo = XmlHandler = None
class _void(object):
pass
AWSAuthConnection = AWSQueryConnectio... |
import os
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# raw folder
TRAIN_FEATURES = os.path.join(ROOT_DIR,'input','raw','train_features.csv')
TRAIN_TARGET_SCORED = os.path.join(ROOT_DIR,'input','raw','train_targets_scored.csv')
# processed folder
TRAIN_TRAGET_FOLDS = os.path.join(ROOT_DIR,... |
import time
def Convert_Height(feet,inch):
feet_cm=30.48*feet
inch_cm=2.54*inch
print("Converting units ...")
time.sleep(1)
print(feet,"feet is equal to :",feet_cm,"cm")
print(inch,"inch is equal to :",inch_cm,"cm")
Convert_Height(20,20) |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def bstFromPreorder(self, preorder):
"""
Construct a Binary search tree from pre order traversal
"""
if not pr... |
from urllib.parse import urlencode
from urllib.request import urlopen
from amath.DataTypes.Function2 import Function
from amath.Errors import Failure
def formulaLookup(x):
"""Lookup formulas"""
def wolfram_cloud_call(**args):
arguments = dict([(key, arg) for key, arg in args.items()])
try:
... |
#!/usr/bin/python3
import sys
from datetime import datetime
import timeit
# Global variables
instructions = []
registers = dict()
result01 = 0
result02 = 0
# Functions
def part01():
global registers
global instructions
global result01
sum = 0
for instruction in instructions:
# create regis... |
#!/usr/bin/env python
""" Tools which enable feature generation
for sources in the StarVars project.
*** TODO parse the LINEAR file into a string for below
*** parse raw LINEAR ts files (as string):
tutor_database_project_insert.py:parse_asas_ts_data_str(ts_str)
*** The aperture is chosen and the cooresp... |
import imaging
import servo
import time
def main():
cam_ctrl = imaging.CameraControl()
servo_ctrl = servo.ServoControl()
cam_ctrl.set_exposure(100)
cam_ctrl.set_focus(20)
cam_ctrl.start_camera()
SERVO_DUTY_CYCLE = 30
TOTAL_IMAGES = 100
#servo_ctrl.start(SERVO_DUTY_CYCLE)
for i in... |
import random as r
import os
minscore = 0 #최고점수
while True:
print("☆☆☆☆☆UPDOWN게임☆☆☆☆☆")
print("1.게임시작\n2.게임전적\n3.게임종료")
select = int(input(">>> "))
if select == 1:
computer = r.randint(1, 100)
count = 0 #시도한 횟수
os.system("cls")
while True:
print(co... |
from abc import ABCMeta, abstractmethod
import os
class PackageAnalyzer(object):
"""
Abstract base class for plug-ins seeking to implement package analysis.
"""
__metaclass__ = ABCMeta
def __init__(self, settings):
"""
Creates a new instance of a package-analyzer class.
:p... |
from django.conf.urls import include, url
from django.contrib import admin
from rest_framework.authtoken import views
from windows.views import api_root
urlpatterns = [
url(r'^api/token/', views.obtain_auth_token, name='api-token'),
url(r'^api/$', api_root),
url(r'^api/', include('rest_framework.urls', na... |
# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth import login, logout, get_user_model
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urls... |
#!/usr/bin/env python3
import subprocess, os, csv, time, sys
my_dir = os.path.abspath(os.path.dirname(sys.argv[0]))
os.chdir(my_dir)
subprocess.check_call(["dune", "build", "--profile=release", "carsales", "catrank", "eval"])
bin_dir = os.path.join(my_dir, '../../_build/default/src/benchmark')
switch = subprocess.che... |
'''
This is a python wrapper around Peng's mRMR algorithm.
mRMR is the min redundancy max relevance feature selection algorithm by
Hanchuan Peng. See http://penglab.janelia.org/proj/mRMR for more details about
the code and its author, as well as the sources and the license.
Author: Brice Rebsamen
Version: 0.1
Release... |
import random
import time
from selenium.webdriver.common.by import By
from selenium_ui.base_page import BasePage
from selenium_ui.conftest import print_timing
from selenium_ui.jira.pages.pages import Login
from util.conf import JIRA_SETTINGS
def app_specific_action(webdriver, datasets):
page = BasePage(webdrive... |
from django.urls import path
from yandex_bs.imports import views as import_views
urlpatterns = [
path("imports", import_views.create_import, name="create_import"),
path("imports/<int:import_id>/citizens", import_views.retrieve_import, name="retrieve_import"),
path("imports/<int:import_id>/citizens/<int:ci... |
import os
from __setup import TestCase
from __setup import DATA_DIR
def join(path):
return os.path.join(DATA_DIR, path)
class TestLogger(TestCase):
def test_setup_storage_variables(self):
from graphitequery import settings
settings.setup_storage_variables(DATA_DIR)
self.assertEqual(se... |
from .shapenet import shapenet
__all__ = ('shapenet','modelnet40','SHREC2016')
__all__ = ('point_cloud') |
from .ObjectProperty import ObjectProperty
class EntitySpawnflags(ObjectProperty):
def __init__(self, listOfFlags, mapObject):
ObjectProperty.__init__(self, mapObject)
self.flagList = listOfFlags
self.name = "spawnflags"
self.valueType = "flags"
self.defaultValue = 0
... |
from keras.layers import Flatten, Dense, Conv2D ,Dropout, MaxPooling2D, AveragePooling2D
from keras.layers.advanced_activations import LeakyReLU, PReLU
from keras.optimizers import Adam
from keras.models import Sequential, Model
from keras.layers.normalization import BatchNormalization
from keras.applications.vgg16 imp... |
from redis import Redis
redis_connection = Redis(decode_responses=True)
key = "some-key"
value = 55
key2 = "some-key2"
value2 = 123
redis_connection.set(key, value)
redis_connection.set(key2, value2)
print(redis_connection.get(key))
print(redis_connection.incr(key, 50))
print(redis_connection.decr(key, 23)) |
'''
Module to manage Zenny
'''
from __future__ import absolute_import
# Import salt libs
import salt.utils
import logging
log = logging.getLogger(__name__)
try:
import RPi.GPIO as GPIO
from gtts import gTTS
from tempfile import TemporaryFile
import pyttsx
HAS_LIBS = True
except ImportError:
... |
#!/usr/local/bin/python2.7
# -*- coding: utf-8 -*-
__author__ = 'https://github.com/password123456/'
import random
import numpy as np
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import requests
import urllib
import urllib2
import json
import datetime
import time
class bcolors:
HEADER = '\033[95m'
... |
from twython import Twython
import time
import os
# This file is not included (my secrets!)
from my_keys import app_key, app_secret, oauth_token, oauth_token_secret
__author__ = 'mpolensek'
# Documentation is like sex.
# When it's good, it's very good.
# When it's bad, it's better than nothing.
# When it lies to you,... |
import sys
print("Welcome. This program will calculate the minimum of three numbers you enter.")
try:
num1=int(input("First number please:"))
num2=int(input("Second number please:"))
num3=int(input("Third number please:"))
L=[]
L.append(num1)
L.append(num2)
L.append(num3)
print("The mini... |
#! /usr/bin/env python
"""
Given a databag and a video, generate crops of interesting particles.
CHANGELOG:
USING:
As a command line utility:
$ Cropper.py input_video input_bag output_dir [-p particle_id -pad padding]
As a module:
import Cropper fro... |
from Jumpscale import j
class web_interface(j.baseclasses.object):
__jslocation__ = "j.tools.packages.webinterface"
def test(self, port=None, prefix="", scheme="http"):
"""
kosmos `j.tools.packages.webinterface.test()'
:return:
"""
base_url = "0.0.0.0"
if port:... |
"""App related signal handlers."""
import redis
from django.conf import settings
from django.db.models import signals
from django.dispatch import receiver
from modoboa.admin import models as admin_models
from . import constants
def set_message_limit(instance, key):
"""Store message limit in Redis."""
old_... |
#from matrix_tracker import lattice
import copy
import multiprocessing
from pcaspy import Driver, SimpleServer
import time
from epics import caget, PV
import numpy as np
import random
from MakeModel import SurrogateModel
import json
class SimDriver(Driver):
def __init__(self,input_pv_state,output_pv_state,noise_p... |
# Generated by Django 3.0.1 on 2020-01-04 21:58
from django.db import migrations, models
import django.db.models.deletion
import django.utils.crypto
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name=... |
# -*- coding:utf-8 -*-
import os
import dlib
import glob
import cv2
from PIL import Image
import gc
import threading
import time
import queue
try:
import face_recognition_models
# 加载检测模型文件
detector = dlib.get_frontal_face_detector()
# predictor_68_point_model = face_recognition_models.pose_predictor... |
import socket
import sys
data = sys.argv
data = [data[1], data[2]]
sock = socket.socket()
sock.connect(('localhost', 9090))
sock.send(', '.join(data))
#print data |
from __future__ import unicode_literals
from tinymce.models import HTMLField
from django.db import models
class faculty_data(models.Model):
faculty_id=models.CharField(primary_key=True,max_length=20,blank=False,null=False)
name=models.CharField(max_length=300,blank=True,null=True)
# designation_choice=(
# ("Prof... |
import unittest
from katas.kyu_7.find_the_volume_of_a_cone import volume
class ConeVolumeTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(volume(7, 3), 153)
def test_equal_2(self):
self.assertEqual(volume(56, 30), 98520)
def test_equal_3(self):
self.assertEq... |
"""
Retrieve and store all new tweets from the user home timeline.
"""
import traceback
import db
import log
import twitter
def main():
""" Retrieve and store all new tweets from the user home timeline.
"""
# Logger
logger = log.file_console_log()
# Connect to the MongoDB database
stored_twe... |
import turtle
trt=turtle.Turtle()
scr=turtle.Screen()
turtle.listen(xdummy=None, ydummy=None)
scr.bgcolor("black")
trt.color("white")
def w():
trt.seth(90)
trt.forward(10)
scr.onkeypress(w, "w")
scr.onkey(w, "w")
def s():
trt.seth(270)
trt.forward(10)
scr.onkeypress(s, "s")
scr.onkey(s, "s")
def ... |
#! /usr/bin/env python3
"""Example map generator: Woodbox (Block)
This script demonstrates vmflib by generating a map (consisting of a large
empty room) and writing it to "woodbox_block.vmf". You can open the resulting
file using the Valve Hammer Editor and compile it for use in-game.
This example shows off the tools... |
#coding: utf-8
import os
from celery.decorators import task
from django.conf import settings
from Corretor.base import CorretorException
from Corretor.base import CompiladorException
from Corretor.chamada_sistema import ChamadaSistema
@task
def run_corretor(*args,**kwargs):
"""roda o corretor usando uma task do... |
import torch
from torch import nn as nn
from transformers import BertConfig
from transformers import BertModel
from transformers import BertPreTrainedModel
from spert import sampling
from spert import util
def get_token(h: torch.tensor, x: torch.tensor, token: int):
""" Get specific token embedding (e.g. [CLS]) ... |
from .celery import hello_world
def require_channel(slack_event_json):
"""
Require a channel be present in the JSON from the Events API
:params dict slack_event_json: The JSON from the events API
:rtype: bool (False) or str
"""
# Get the channel, else false so we
# don't reply to mention... |
# coding: utf-8
# https://github.com/usnistgov/yabadaba
from yabadaba.tools import ModuleManager
databasemanager = ModuleManager('Database')
#from yabadaba import databasemanager as coredatabasemanager
# Local imports
from .reset_orphans import reset_orphans
from .prepare import prepare
from .master_prepare import ma... |
import os
import ray
import logging
import hydra
from hydra.utils import get_original_cwd
import numpy as np
import torch
from torchvision import datasets, transforms
from torchfly.training.trainer import Trainer
from model import get_model
from dataloader import get_data_loader
logger = logging.getLogger(__name__)... |
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
row, col = 0, len(matrix[0])-1
right = len(matrix[0])
left = right - 1
# number of row
down = len(matrix)-1
up = down - 1
... |
# Alvin Radoncic
# CS-110-A
# Quiz Two Part Two
# I pledge my Honor that I have abided by the Stevens Honor System
def addition(x, y):
return x + y
def subtraction(x, y):
return x - y
def multiplication(x, y):
return x * y
def division(x, y):
return x / y
def vowels(z):
lowercased = z.lower... |
from ..FeatureExtractor import FeatureExtractor
from common_functions.Example_Methods import Example_Methods
class example_extractor(FeatureExtractor,Example_Methods):
""" Just an example extractor skeleton. For full example, see:
http://lyra.berkeley.edu/dokuwiki/doku.php?id=tcp:feature_testing
"""
internal_us... |
# This is the main testing script that we should be able to run to grade
# your model training for the assignment.
# You can create whatever additional modules and helper scripts you need,
# as long as all the training functionality can be reached from this script.
import matplotlib
matplotlib.use('Agg')
from matplotli... |
import random
import re
from flask import Flask, request
import telegram
from telebot.credentials import bot_token, bot_user_name,URL
global bot
global TOKEN
TOKEN = bot_token
bot = telegram.Bot(token=TOKEN)
def is_number_regex(s):
""" Returns True is string is a number. """
if re.match("^\d+?\.\d+?$", s) is ... |
from pydash import map_, find
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.common.exceptions import N... |
T = int(input())
for t in range(T):
N = int(input())
ss = {}
for n in range(N):
s = list(input().split())
ss[s[0]] = int(s[1])
print(max(ss.keys(), key=ss.get))
|
def expower(powr,num):
if powr <1:
return 1
else :
return num*expower(powr-1,num)
print(expower(3,5))
print()
print()
mylist = [-4, -6, -5, -1, 2, 3, 7, 9, 88]
print(mylist)
for i in mylist:
x = lambda a: print(a) if a > 0 else None
x(i)
|
from django.apps import AppConfig
class MobileWsConfig(AppConfig):
name = 'Mobile_WS'
|
from sqlalchemy import (
Column,
String,
Boolean
)
from db.database import Base
class User(Base):
__tablename__ = 'users'
username = Column(String, primary_key=True, index=True)
hashed_password = Column(String, nullable=False)
is_admin = Column(Boolean, nullable=False)
|
import pytest
from torchvision._utils import sequence_to_str
@pytest.mark.parametrize(
("seq", "separate_last", "expected"),
[
([], "", ""),
(["foo"], "", "'foo'"),
(["foo", "bar"], "", "'foo', 'bar'"),
(["foo", "bar"], "and ", "'foo' and 'bar'"),
(["foo", "bar", "baz"]... |
T = int(input())
childs = [[] for _ in range(T+1)]
for i in range(2, T+1):
par = int(input())
childs[par].append(i)
def dfs(x:int):
ret = 0
for item in childs[x]:
temp = dfs(item) + len(childs[x])
ret = max(ret, temp)
return ret
print(dfs(1))
|
# --------------------------------------------------------
# Tensorflow VCL
# Licensed under The MIT License [see LICENSE for details]
# Written by Zhi Hou, based on code from Transferable-Interactiveness-Network, Chen Gao, Zheqi he and Xinlei Chen
# --------------------------------------------------------
from __futu... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from textwrap import dedent
from pants.testutil.pants_integration_test import run_pants, setup_tmpdir
def test_synthesized_python_is_included_in_packa... |
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from KNN import KNN
data = pd.read_csv('Social_Network_Ads.csv')
# print(data)
data = data.drop(['User ID'], axis=1)
data['Gender'] = data['Gender'].map({'Male': 0, 'Female': 1}... |
from pathlib import Path
class Dirs:
root = Path(__file__).parent.parent
data = root / 'data'
data_tools = root / 'data_tools'
class Data:
min_input_length = 3
max_input_length = 128
train_prob = 0.8 # probability that utterance is assigned to train split
special_symbols = ['[PAD]', '[U... |
import json
import os
import re
from pymongo import MongoClient
### Load Mongo Connection String from environment on PROD
### Otherwise load it from local file
MONGO_CONNECTION_URI = os.environ.get('MONGO_CONNECTION_URI')
if MONGO_CONNECTION_URI is None:
env_config = json.loads(open('dev.json', 'r').read())
... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.file_upload, name="file_upload"),
path('delete/<int:pk>/',views.remove_upload, name='remove_upload'),
path('download/', views.file_download, name='file_download')
] |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
# Ciência de Dados e Inteligência Artificial
# Passo 1: Entendimento do Desafio
# Passo 2: Entendimento da Área/Empresa
# Passo 3: Extração/Obtenção de Dados
# Passo 4: Ajuste de Dados (Tratamento/Limpeza)
# Passo 5: Análise Exploratória
# Passo 6: Modelagem + Alg... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 25 22:53:28 2019
@author: HP
"""
import math
DP=[None for i in range(100001)]
DP[1]=1
def sum_odd(n):
res=1
t=n
while t%2==0:
t=int(t/2)
if DP[t]!=None:
DP[n]=DP[t]
return
else:
for i in range(3,int(math.sqrt(t)+1),2):
... |
#
# Copyright The NOMAD Authors.
#
# This file is part of NOMAD. See https://nomad-lab.eu for further info.
#
# 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/licen... |
###Exercises for Chapter 3
#Ex. 3.1
hours = float(raw_input('Enter Hours Worked: '))
rate = float(raw_input('Enter Rate: '))
if (hours > 40):
ot = hours - 40
otpay = ot * (1.5 * rate)
pay = (40 * rate) + otpay
print 'Your pay = ' + str(pay)
else:
pay = int(hours) * float(rate)
print 'Your pay ... |
#Function One - Sum array
def sum_array(array):
'''Return sum of all items in array'''
if len(array)==1:
return array[0]
else:
return array[0] + sum_array(array[1:])
#Function Two - Find nth fibonacci number
def fibonacci(n):
'''Return nth term in fibonacci sequence'''
if n < 0:
... |
#taking arguments
def sumAll(*args):
sum = 0
for i in args:
sum += i
return sum
print("Sum :", sumAll(1,2,3,4,5))
|
from .point import point_trans, gray, xy2index |
# Copyright (c) Members of the EGEE Collaboration. 2004.
# See http://www.eu-egee.org/partners/ for details on the copyright
# holders.
#
# 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
#... |
import os
import logging
import signal
import sys
import json
from time import sleep
import os
import subprocess
import time
import paho.mqtt.client as mqtt
import threading
import hashlib
import database
from config import MQT
# Initialize Logging
logging.basicConfig(level=logging.WARNING) # Global ... |
"""
Override `error` method of `argparse.ArgumentParser`
in order to print the complete help on error.
"""
import argparse
import sys
SUPPRESS = argparse.SUPPRESS
class HelpParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write('error: %s\n' % message)
self.print_help()
... |
import numpy as np
import math
import matplotlib.pyplot as plt
#plt.switch_backend('Qt4Agg')
# read in MSD and plot
data = np.loadtxt("msd.txt", skiprows=2)
fig, ax = plt.subplots()
ax.plot(data[:,0], data[:,4], "r")
# compare to power law
x = np.arange(100, 500, step=100)
ax.plot(x, 0.00007* x**2, "b--")
ax.text(10... |
# -*- coding: utf-8 -*-
import scrapy
import json,re
from lxml import etree
from loguru import logger
from scrapy.utils.project import get_project_settings
from ProxyIP.items import FreeProxyIPItem
class Ip3366FreeSpider(scrapy.Spider):
name = 'ip3366_free'
settings = get_project_settings()
spider_page_s... |
class UserSignalUIParameters:
# ACCELERATION TIME
AccelerationTimeMin = 0.1
AccelerationTimeMax = 600.0
AccelerationTimeLineEditAccuracy = 2
AccelerationTimeCalcConstant = 100 # Раз 100, значит цифры с точностью до 10**2
AccelerationTimeSliderMin = AccelerationTimeMin * AccelerationTimeCalcC... |
from test.helper import TestHelper
from beetsplug.plexupdate import get_music_section, update_plex
import unittest
import responses
class PlexUpdateTest(unittest.TestCase, TestHelper):
def add_response_get_music_section(self, section_name='Music'):
"""Create response for mocking the get_music_section func... |
from django.contrib.auth.views import LoginView, LogoutView
from django.urls import path
from contest import views
app_name = 'contest'
urlpatterns = [
path('', views.contest.Index.as_view(), name='index'),
path('login', LoginView.as_view(), name='login'),
path('logout', LogoutView.as_view(), name='logo... |
#
# This file is part of LUNA.
#
# Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com>
# SPDX-License-Identifier: BSD-3-Clause
""" Pre-made gateware that implements an ILA connection serial. """
from amaranth import Elaboratable, Module, Signal, Cat
from ...debug.ila ... |
from ryu.base import app_manager
from ryu.controller.handler import set_ev_cls
from ryu.controller.handler import MAIN_DISPATCHER, CONFIG_DISPATCHER
from ryu.controller import ofp_event
from ryu.lib.packet import packet, ether_types, ethernet, arp
# ofproto 在这个目录下,基本分为两类文件,一类是协议的数据结构定义,另一类是协议解析,也即数据包处理函数文件。
# Its lik... |
# -*- coding: utf-8 -*-
kim = input('Kim?\n')
kiminle = input('Kiminle?\n')
nerede = input('Nerede?\n')
neYapiyor = input('Ne yapıyor?\n')
print(kim, kiminle, nerede, neYapiyor) |
# Generated by Django 2.0.7 on 2018-09-13 16:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ProductDT', '0003_auto_20180913_1509'),
]
operations = [
migrations.AlterField(
model_name='hotelmsg',
name='id',
... |
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from .models import Player
from . import makeTeam
def index(request):
return HttpResponse("Test")
def player(request):
context = {
"players": Player.objects.all(),
}
return render(request, "team/player.html", co... |
import unittest
from katas.kyu_6.your_ride_is_here import ride
class RideTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(ride('COMETQ', 'HVNGAT'), 'GO')
def test_equals_2(self):
self.assertEqual(ride('STARAB', 'USACO'), 'STAY')
|
import math
from typing import List, Optional
import numpy as np
from pypm import DataPoints
from pypm.icp import ICP, Penalty
from picp.util.geometry import generate_tf_mat, extract_xyt_from_tf_mat, make_homogeneous
from picp.util.pose import Pose
def icp_with_random_perturbation(icp: ICP, read: DataPoints, ref: D... |
# -*- coding: utf-8 -*-
from django.utils.functional import cached_property
__all__ = [
'FetchIssueByNumber',
'UpdateIssueCacheTemplate',
'AskForUpdateIssuesCacheTemplate',
'IssuePRBranchDeleteJob',
'IssueCreateJob',
'IssueEditStateJob',
'IssueEditTitleJob',
'IssueEditBodyJob',
'Iss... |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 8 18:23:28 2021
@author: gabri
"""
lista=[]
file=open('devices.txt')
for a in file:
a=a.strip()
lista.append(a)
print(a)
file.close()
print(lista) |
import json
from flask import request
class PeopleViews(object):
def __init__(self, service, router):
self.service = service
self.router = router
self._create_routes()
def _create_routes(self):
@self.router.route('/', methods=['GET'])
def home():
return ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.