text stringlengths 8 6.05M |
|---|
import sys
from datetime import datetime
# Shared data
# keg data dictionary
# value is list( volume in liters, empty weight in kg )
keg_data = {
'half_bbl': (58.6, 13.6),
'tall_qtr_bbl': (29.3, 10),
'short_qtr_bbl': (29.3, 10),
'sixth_bbl': (19.5, 7.5),
'corny': (18.9, 4),
}
# CO2 tank data dict... |
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('first', 'second', 'third', 'nickname')
nation_name = forms.CharField(max_length=100,) |
#import glob
import os
#import sys
#import pandas
#import numpy
#import math
#import tensorflow as tf
#import matplotlib.pyplot as plt
class Config:
def __init__(self):
self.ROOT_PATH = os.path.abspath(__file__ + "/../../")
self.LIBRARY_PATH = os.path.join(self.ROOT_PATH, 'K3S')
self.DATA_PATH = os.path.join... |
#!/usr/bin/env python
import mattermost
from threading import Lock
from flask import request
from flask import Flask, jsonify
app = Flask(__name__)
import configparser
import sys
import time
import random
import shelve
import datetime
from insults import list_of_insults
GAME_MUTEX = Lock()
# Read in the config
co... |
def testData():
otest = open('./21/test.txt', 'r')
test = otest.readlines()
oanswer = open('./21/answer.txt', 'r')
answer = oanswer.readline()
status = False
print("Runs test data")
result = runCode(test)
if result == int(answer): #not always int
status = True
prin... |
# a121_catch_a_turtle.py
#-----import statements-----
import turtle as trtl
import random
#-----game configuration----
t=trtl.Turtle()
score_writer=trtl.Turtle()
t.speed(0)
spot_color = "pink"
score=0
score_writer.speed(0)
#-----initialize turtle-----
t.shape("circle")
t.shapesize(2)
t.fillcolor("black")
... |
from django.test import TestCase
from pulp import *
import random
from .models import Nb_creneaux
from .models import plne
class plne_test(TestCase):
def test_1(self):
n = random.randint(0,Nb_creneaux-1)
index = []
for i in range(Nb_creneaux):
index.append(i)
... |
# -*- coding: utf-8 -*-
"""Points models."""
from tour.database import Column, Model, db
categories = ['Park', 'Museum', 'Restaurant']
class Point(Model):
"""A point model of the app."""
__tablename__ = 'points'
id = db.Column(db.Integer, primary_key=True)
name = Column(db.String(80), nullable=False... |
import time
import random
# 带参数的装饰器
def get_exec_time(func):
def wrapper(a, b):
begin_time = time.time()
func(a, b)
end_time = time.time()
use_time = end_time-begin_time
print(use_time)
return wrapper
@get_exec_time
def func1(a, b):
sleep_time = random.randint(a, ... |
class SentenceAnalyser:
def __init__(self):
self.sentence={"Clauses":0 , "Complete sentences":0 , "Questions":0}
def __str__(self):
string = ""
for i in self.sentence:
string += i + ":" + str(self.sentence[i]) + '\n'
return string
def analyse_sentences(self, dec... |
#!/usr/bin/env
# encoding: utf-8
"""
Created by John DiBaggio on 2017-06-22
Prints a message like the following:
417929742755482295 rabbit pairs after 86 months with 1 pairs produced per litter from rabbits of age 2+ months and
rabbits dying after 18 months. Calculated in 0.000448942184448 seconds
"""
__author__ = 'j... |
# Removing the duplicate values in a sequence,
# but preserve the order of the remaining items.
# Solution for hashable sequence
def dedupe(items):
seen = set()
for item in items:
if item not in seen:
yield item
seen.add(item)
# Solution for unhashable types (such as dicts)
d... |
"""Write a function that takes as input an English sentence (a string) and prints the total
number of vowels and the total number of consonants in the sentence. The function
returns nothing. Note that the sentence could have special characters like dots, dashes,
and so on"""
import string
def eliminate_bad_characters... |
"""
==============
Risk Observers
==============
This module contains tools for observing risk exposure during the simulation.
"""
from collections import Counter
from typing import Dict
import pandas as pd
from vivarium.framework.engine import Builder
from vivarium.framework.event import Event
from vivarium_publi... |
# coding=utf-8
import os
import sys
sys.path.append(os.environ.get('PY_DEV_HOME'))
from webTest_pro.common.preInit import preinit
# from webTest_pro.common.logger import logger
if __name__ == '__main__':
preinit()
|
"""empty message
Revision ID: fd0fb00bfd08
Revises: 19c4b18cd911
Create Date: 2019-05-29 00:41:00.880720
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = 'fd0fb00bfd08'
down_revision = '19c4b18cd911'
branch_labels = None... |
import unittest
from katas.kyu_7.count_the_ones import hamming_weight
class CountTheOnesTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(hamming_weight(10), 2)
def test_equal_2(self):
self.assertEqual(hamming_weight(21), 3)
def test_equal_3(self):
self.asser... |
from EmpNode import MyNode
class LinkedList(MyNode):
def __init__(self,head = None):
self.__head = head
def isEmpty(self):
return self.__head == None
def AddNew(self,data):
myNode = MyNode(data)
if self.isEmpty() == True:
self.__hea... |
import tensorflow as tf
import numpy as np
from dps.utils import Parameterized, Param
from dps.utils.tf import build_gradient_train_op
class Optimizer(Parameterized):
def __init__(self, agents):
self.agents = agents
def trainable_variables(self, for_opt):
return [v for agent in self.agents f... |
import numpy as np
import pandas as pd
from sklearn.svm import SVR
from sklearn.model_selection import KFold
import optuna
class SVRCV(object):
model_cls = SVR
def __init__(self, n_trials=100):
self.n_trials = n_trials
def fit(self, X, y):
if isinstance(X, np.ndarray):
X = p... |
#!/usr/bin/env python3
import logging
import os, re;
from datetime import datetime
from threading import Thread, Lock, Event
from urllib.request import urlopen
from urllib.parse import urljoin, urlsplit
from bs4 import BeautifulSoup as BS;
import signal
maxAttempt = 3;
outDir = '/Volumes/flood3/RSS'
bs4FMT = 'l... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import datetime
import re
import time
from pathlib import Path
import pytest
from freezegun import freeze_time
from pants.base.build_environment import get_buildroot
from pants.base.exit... |
from fastapi import APIRouter
from . import user
from . import todo_list
api = APIRouter(prefix='/api')
api.include_router(user.api)
api.include_router(todo_list.api)
|
#this program is used to do the sorting of values by merge sort
from util import utility
try:
lst = [int(x) for x in input("enter the number with space ").split()]
print(utility.merge_sort(lst)) # calls the method nad prints the output
except ValueError:
print("ENTER THE INT VALUES") |
city0 = "Karachi"
city1 = "Lahore"
city2 = "Islamabad"
city3 = "Quetta"
city4 = "Peshawar"
print("Welcome to city " + city3)
cities = ["Karachi","Lahore","Islamabad","Quetta","Pehawar"]
print("Welcomw to city " + cities[4]) |
#!/usr/bin/env /data/mta/Script/Python3.8/envs/ska3-shiny/bin/python
#####################################################################################
# #
# run_iru_gyro_bias.py: update iru gyro bias database ... |
import numpy as np
import scipy.spatial.distance as dist
from permaviss.sample_point_clouds.examples import torus3D, take_sample
from permaviss.spectral_sequence.MV_spectral_seq import create_MV_ss
from permaviss.spectral_sequence.local_chains_class import local_chains
from permaviss.simplicial_complexes.vietoris_rip... |
#!/usr/bin/env python
"""
"""
import sys
from collections import defaultdict
GTF_HEADER = ['seqname', 'source', 'feature', 'start', 'end', 'score',
'strand', 'frame']
gff_in_fn = sys.argv[1]
with open(gff_in_fn) as fh:
counter = 1
trans_in_dict = {}
for line in fh:
if line.startsw... |
shopping_list={
"warzywniak":["marchew", "ogórek", "sałata"],
"zoologiczny":["jedzenie dla kota", 'jedzenie dla psa'],
"piekarnia":["chleb", "ciasto"],
"mięsny":["szynka", "kurczak"],
"komputerowy":['pendrive']
}
product_list=[]
for store in shopping_list:
products=str(shopping_list[store])
... |
# -*- coding:utf-8 -*-
from django import forms
from .models import UserProfile
DEPT_CHOICES = (
('HWL', '核物理研究室'),
('WSW', '物理生物学研究室'),
('SKX', '水科学研究室'),
('JSQ', '加速器物理与射频技术部'),
('FEL', '自由电子激光技术部'),
('SLK', '束流测量与控制技术部'),
('JXG', '机械工程技术部'),
('DYJ', '... |
#========================================
# author: Changlong.Zang
# mail: zclongpop123@163.com
# time: Tue Sep 19 14:40:48 2017
#========================================
import pymel.core as pm
import maya.OpenMaya as OpenMaya
#--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+... |
# -*- coding: utf-8 -*-
"""
**Introducción a Redes Complejas en Biología de Sistemas**
Trabajo Computacional 2 - Estructura a Gran Escala
Entrega 14/05
Grupo: Camila Sanz, Matías Zanini.
"""
################################################################################
# ... |
import urllib
def read_text():
quotes = open(src, "r")
contents_file = quotes.read()
print contents_file
quotes.close()
profanity_check(contents_file)
def profanity_check(text_check)
connection = urllib.urlopen("http://www.wdyl.com/profanity?q=" + text_check)
output = connection.read()
print output
connecti... |
from django.contrib import admin
from .models import Checklistdocument
# Register your models here.
admin.site.register(Checklistdocument) |
class Print_options:
def display_float_question(self, question):
while True:
try:
awnser = float(input(question))
except ValueError:
print("Sorry, dat begreep ik niet, probeer het opnieuw")
continue
else:
br... |
__author__ = 'aoboturov'
from sklearn.cross_validation import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import roc_auc_score
from competition_tutorial import prepare_data_features, FEATURES
RANDOM_STATE = 42
train, target_with_features = prepare_data_features(lambda df: train_test_split(df,... |
while True:
x = int(input())
if x == 0:
break
for n in range(1, x+1):
if n == x:
print(n)
else:
print(n, end=' ') |
if __name__ == '__main__':
student_list =[]
for _ in range(int(input())):
name = input()
score = float(input())
student = [name, score]
student_list.append( student )
number_list = sorted(list(set(map(lambda x : x[1], student_list))))
# print (number_list)
secon... |
# Generated by Django 2.1.2 on 2019-01-07 10:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('products', '0033_auto_20190102_1033'),
]
operations = [
migrations.RenameField(
model_name='category',
old_name='dir... |
def take_umbrella(weather, rain_chance):
if weather=='rainy':
return True
if weather=='sunny' and rain_chance>0.50:
return True
elif weather=='cloudy'and rain_chance>0.20:
return True
else:
return False
'''
Write a function take_umbrella() that takes two arguments: a str... |
from MarbleManager import marbleManager
commands = [
"**help:** you just used it",
"**ping:** pong",
"**register:** register and recieve a random amount of marbles from 20 to 40",
"**collection:** shows your current marble amount"
]
async def processCommand(message, commandPrefix):
command =... |
import sys
sys.path.append('../500_common')
import lib
import lib_ss
if False:
images = lib.get_images("data/result.html")
else:
soup = lib_ss.main("/Users/nakamurasatoru/git/d_genji/genji_curation/src/500_common/Chrome3post", "Profile 3", 60)
images = lib.get_images_by_soup(soup)
manifest = "https://kote... |
# Generated by Django 2.2.6 on 2019-11-06 18:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('work', '0023_dprqty'),
]
operations = [
migrations.RemoveField(
model_name='dprinfra',
name='site',
),
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# from django.contrib.gis.db import models
from django.utils import timezone
class FeatureType(models.Model):
feature_name = models.CharField(max_length=200)
def __str__(self):
return "{}".format(self.featur... |
class Building:
graph = None
floors = None
def __init__(self, graph, floors):
self.graph = graph
self.floors = floors
class Graph:
points = []
connections = []
def __init__(self, points, connections):
self.points = points
self.connections = connections
... |
# Problem description: http://www.geeksforgeeks.org/partition-a-set-into-two-subsets-such-that-the-difference-of-subset-sums-is-minimum/
def find_minimum_partition(array, set1, total_sum):
# construct all possible values for set 1 from array
if not array:
sum_set1 = sum(set1)
sum_set2 = total... |
# -*- coding: utf-8 -*-
class Solution:
def calculateMinimumHP(self, dungeon):
result = [float("inf") for _ in range(len(dungeon[0]))]
result[-1] = 1
for i in reversed(range(len(dungeon))):
result[-1] = max(result[-1] - dungeon[i][-1], 1)
for j in reversed(range(le... |
from django.http import HttpResponse
from django.contrib.auth import authenticate,login,get_user_model
from django.shortcuts import render,redirect
from .forms import ContactForm,LoginForm,RegisterForm
# Create your views here.
def home_page(request):
context = {
"title":"Hello world!",
"con... |
from django.db import models
from multiselectfield import MultiSelectField
from datetime import datetime, date
# Create your models here.
class Task(models.Model):
name = models.CharField(max_length=255)
genre_choice = [
("Drama", "Drama"),
("Romance", "Romance"),
("Action", "Action"),
... |
#coding:utf-8
#!/usr/bin/env python
from gclib.json import json
from game.models.account import account
from game.models.user import user
from game.routine.gift import gift as giftR
def request(request):
"""
请求加好友
"""
usr = request.user
friendid = request.GET['friend_id']
friendid = int(friendid)
if friendid ... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as pat
import math
class Ellipsoid:
def __init__(self, a, b, c, p, xc):
self.a = a
self.b = b
self.c = c
self.p = p
self.xc = xc
self.w = c
fig = plt.figure()
# Draw constr... |
'''5206.删除字符串中的所有相邻重复项'''
s = "deeedbbcccbdaa"
k = 3
i=0
n=len(s)
while(i+k<=n):
'''if s[i:i+k]==s[i]*k:
#1.采用切片结合字符串的乘法来进行对比处理
#2.或者将字符逐个对比,累计相同字符的个数然后与k对比
#3.或者将字符逐个添加到一个list中,进行set处理,看
#处理之后长度是否为1
#后面两种方法花费时间比第一种方法更长
s=s[:i]+s[i+k:]
n=n-k
... |
import binary
import flipMove
# encode -> binary <- decode
# decode/encode
def language():
language = input('binary, flipMove: ')
if 'binary'.startswith(language.lower()):
if binary.question():
print('done')
if 'flipMove'.startswith(language.lower()):
flipMove()
language()
|
import torchvision.transforms as transforms
import config as cf
from autoaugment import DogBreedPolicy
def transform_training():
transform_train = transforms.Compose([
transforms.Resize(227),
#transforms.RandomCrop(32, padding=4),
# transforms.RandomHorizontalFlip(),
#DogBreedPoli... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-03-24 02:47
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('treatment_sheets', '0005_auto_20160323_0547'),
]
operations = [
migrations.A... |
import argparse
import os
import shutil
import time
from pathlib import Path
from PIL import Image
import cv2
import torch
import torch.backends.cudnn as cudnn
from numpy import random
import numpy as np
import math
from models.experimental import attempt_load
from utils.datasets import LoadStreams, Lo... |
import WH
conn = WH.WH()
conn.connect()
r = conn.add_allowed_host(40466,"https","nunahealth.com")
print r.text
|
#!/usr/bin/env python
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any
# means.
#
# I... |
import sys
import rosbag
if __name__ == '__main__':
inputfile = sys.argv[1]
if len(sys.argv) == 3:
outputfile = sys.argv[2]
else:
outputfile = inputfile[:-4] + '-converted.bag'
with rosbag.Bag(outputfile, 'w') as outbag:
for topic, msg, t in rosbag.Bag(inputfile).read_messages(... |
#Batch export of orthophotos based on individual cameras or user selected cameras
#creates custom menu item
#compatibility Agisoft PhotoScan Pro 1.1.0
#no arguments required
import os
import time
import random
import PhotoScan
from PySide import QtCore, QtGui
def intersect(p0, pn, l0, l):
d = ((p0 - l0) * pn) / (... |
from django.shortcuts import render, reverse
from .forms import CommentForm
from django.core import serializers
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect, JsonResponse
from posts.models import Post
def comment_create_view(request, post_id , *args, **kwargs):
posts =... |
class BuiltinFunctionDemo:
"""
内置函数Demo
"""
def __init__(self):
self._name = None
"""
def get_name(self):
return self._name
def set_name(self, value):
self._name = value
def del_name(self):
del self._name
name = property(get_name, set_name, del_na... |
# django_file_system_searcher/serializers.py
from rest_framework import serializers
from .models import LightroomImageFileInfo, LightroomCatalog, ImageToFileInfo
class LightroomImageFileInfoSerializer(serializers.ModelSerializer):
class Meta:
model = LightroomImageFileInfo
fields = [
"... |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import tensorflow as tf
import numpy as np
def to_tensor(array, dtype=tf.float32):
#return tf.convert_to_tensor(array, dtype=dtype)
if 'tensorflow.python.framework.ops.Tensor' not in str(type(array)):... |
w = 64
w_ave = 71.9
w_sd = 10.61
cv = w_sd/w_ave
print(cv)
print(1.2)
coefficient1 = w/(w_ave + 2*w_sd)
print(coefficient1)
coefficient2 = w_ave/(w_ave + 2*w_sd)
print(coefficient2)
|
import datetime
import random
class SimpleScheduler(object):
def __init__(self, setting_dict, right_now=None):
self.frequency = setting_dict.get('check_freq', 1) # how often the action occurs (Never, Daily, Weekly, Monthly)
self.specific_time = setting_dict.get('check_time', 0) # whether the action sh... |
import math, random
import pygame as pg
from pygame.sprite import *
from utils import Bullet, media_path
TRANSPARENT = (0, 0, 0, 0)
class Player(Sprite):
def __init__(self, pos, size):
Sprite.__init__(self)
# Create Player Image
self.original_img = self.make_image(size)
... |
#coding=utf-8
# dict = {'Alice': 2341, 'Beth': 9102, 'Cecil': 3258}
# dict = sorted(dict.items(),key=lambda item:item[1],reverse=1)
# for i in range(0,2):
# print(dict[i])
|
from django.shortcuts import render
from django.http import HttpResponse
from .models import TodoList, Item
# Create your views here.
def home(request, id):
todo_list = TodoList.objects.get(id=id)
item_list = todo_list.item_set.all()
context = {
'todo_list': todo_list,
'item_list': item_li... |
"""
Exercício 3: Elefantes
Este exercício tem duas partes:
Implemente a função incomodam(n) que devolve uma string contendo "incomodam " (a palavra seguida de um espaço) n vezes. Se n não for um inteiro estritamente positivo, a função deve devolver uma string vazia. Essa função deve ser implementada utilizando recursã... |
''' This file contains the script to run the Random Forest Classifier.
'''
import Utils
import numpy
from sklearn import cross_validation
from sklearn.ensemble import RandomForestClassifier
print("Loading test data...")
class_names, y, X = Utils.load_training_data()
# Instantiate a random forest classifier
my_random... |
from rest_framework import generics, serializers
from .models import Match
from .serializers import MatchSerializer
class MatchListApi(generics.ListAPIView):
"""
match queryset/list API
"""
model = Match
serializer_class = MatchSerializer
def get_queryset(self):
queryset = self.mode... |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 9 18:36:43 2020
@author: Barmando
"""
import flask
import base64
import hashlib
import hmac
import json
import sys
import xmltodict
from flask import request
from flask import Response
from Modules.GUI.GUI2 import Ui_MainWindow
from PyQt5 import QtWidgets
from constan... |
from multiprocessing import Pool
import numpy as np
import torch
from torchtext import data
"""
Example (a colleciton of text is one)
"""
class Example(data.Example):
@classmethod
def fromlist(cls, data, fields, step=None, noise_generators=None):
ex = super().fromlist(data, fields)
if noise_g... |
from django.conf.urls.defaults import patterns
urlpatterns = patterns('bluenotepad.public.views',
(r'^dataset/(?P<filename>.+)$', 'dataset'),
)
|
import math
from MyQueue import Queue
class PriorityQueue(Queue):
def __init__(self, _sortFunction = None, _ascending = True, _initialElements = []):
super().__init__()
self.ascending = _ascending
setattr(PriorityQueue, "sortFunction", _sortFunction)
if(_sortFunction is None):
... |
from dronekit import connect, VehicleMode, LocationGlobalRelative, APIException, Command
import time
import socket
import exceptions
import math
import argparse #To import some values from command line and use it on our python script
from pymavlink import mavutil
#####################functions####
def conne... |
import sys
from .cmd_main import run_vvc_command
sys.exit(run_vvc_command(sys.argv[1:]))
|
from pico2d import *
import random
import game_framework
import game_world
from game_object import GameObject
class Missile(GameObject):
# image = None
RUN_SPEED_PPS = 200
def __init__(self, x, y, dx, dy, size):
super(Missile, self).__init__()
self.x, self.y = x, y
self.dx, self.dy ... |
n = int(input("Enter size of pyramid: "))
for i in range(n,0,-1):
for j in range(i):
print("*",end=' ')
print('\r') |
import os
import sys
from pathlib import Path
import shlex
import sc2
portconfig = sc2.portconfig.Portconfig()
gameid = os.environ["sc2_match_id"]
# Ensure SC2 gid and write permission
os.chown("/replays", -1, 1500)
os.chmod("/replays", 0o775)
commands = [
[
"cd" # home directory
], [
"cd"... |
import uuid
import base64
from cookies import Cookies
from google.appengine.api import memcache
def authenticate(handler):
return check_cookie(handler)
def process_auth(handler, userId):
return check_cookie(handler, userId)
def check_cookie(handler, userId=None):
cookies = Cookies(handler)
if co... |
from django.conf.urls import url
from django.urls import include, path
from . import views
app_name='notes_app'
urlpatterns = [
url(r'^$',views.all_notes , name='all_notes'),
path("analysis", views.algorithm_analysis, name='algorithm_analysis'),
path("render_pdf", views.render_pdf, name='render_pdf' )
]... |
#concatnate all the features together.
#'note_pairs_wnsimilarity.csv' # wordnet::similarity package
features_path='/Users/gary/Documents/2020Fall/IntroNLP/project/'
feature_files=['OntoNotes_SensesPairs.csv','note_pairs_wnsimilarity.csv','OntoNotes_SensesPairs_WNFeatures.csv',
'WN21mapWn16_topic_similari... |
from _beatbox import _tPartnerNS, _tSObjectNS
from _beatbox import Client as BaseClient
from marshall import marshall
from types import TupleType, ListType
from xmltramp import Namespace
import copy
import re
_tSchemaInstanceNS = Namespace('http://www.w3.org/2001/XMLSchema-instance')
_tSchemaNS = Namespace('http://www... |
from ft232.wrapper import FT232
import logging
import time
from ft232.dll_h import *
class UART(FT232):
def __init__(self, description, BaudRate, Parity, ByteSize, Stopbits):
FT232.__init__(self, description)
self.BaudRate = BaudRate
self.Parity = Parity
self.ByteSize ... |
import numpy as np
from sklearn.base import clone
from ._utils_boot import boot_manual, draw_weights
from ._utils import fit_predict, fit_predict_proba, tune_grid_search
def fit_irm(y, x, d,
learner_g, learner_m, all_smpls, dml_procedure, score,
n_rep=1, g0_params=None, g1_params=None, m_para... |
#coding:utf-8
import paramiko
from time import sleep
print '-------------------------------------------------------------'
# 设置 host,username,password
while(True):
environment = raw_input('please entry environment. (eg: "98 or 99"):')
if environment != '' and environment != 'exit':
break
else:
exi... |
import sys
cycle_length = {}
def get_cycle_length(n):
length = 1
numbers = {}
while n != 1:
if n in cycle_length:
length = length + cycle_length[n] - 1
break
numbers[n] = length
n = (n / 2) if (n % 2) == 0 else (3 * n + 1)
length += 1
for i in numbers:
cycle_length[i] = length + 1 - numbers[i]
re... |
# Voorbeeld
def increment(x):
return x + 1
def square(x):
# Vervang onderstaande lijn door de vertaling van de Java-code
raise NotImplementedError()
def are_ordered(x, y, z):
raise NotImplementedError()
# is_divisible_by
|
class Node:
def __init__(self, info):
self.info = info
self.left = None
self.right = None
self.level = None
def __str__(self):
return str(self.info)
class BinarySearchTree:
def __init__(self):
self.root = None
def create(self, val):
i... |
from django.db import models
# Create your models here.
class User(models.Model):
username = models.CharField(max_length=15)
email = models.CharField(max_length=30)
dob = models.CharField(max_length=15)
password = models.CharField(max_length=30)
# auto add these timestamps
created_at = models.... |
def sumofint(n):
sum = 0
while n != 0:
sum += (n%10)
n = int(n/10)
return sum
n = int(input())
for j in range(20):
if |
__author__ = 'tonyxufaker'
|
import numpy as np
import matplotlib.pyplot as plt
u=np.linspace(-2,2,3)
v=np.linspace(-1,1,5)
X,Y=np.meshgrid(u,v)
z=X**2/25+Y**2/4
print(X)
print(Y)
print('z:\n',z)
plt.set_cmap('gray')
plt.pcolor(z)
plt.show()
y=np.array([[1,2,3], [4,5,6]])
print('z:\n',z)
plt.pcolor(y)
plt.show()
|
# -*- coding: utf-8 -*-
''' 测试可调用方法__call__()'''
class SalaryAccount:
'''工资计算类'''
def __call__(self, salary):
print("开始计算工资")
yearSalary = salary*12
daySalary = salary//22.5
hourSalary = daySalary//8
return dict(yearSalary = yearSalary, monthSalary = salary, daySalary ... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This temporary script file is located here:
/home/peterb/.spyder2/.temp.py
"""
import numpy as np
import serial
import alsaaudio
import websocket
import json
volFactor=0.1
m=alsaaudio.Mixer()
ws=websocket.create_connection('ws://192.168.13.30:80/mopidy/ws/',timeout=1)
#ser... |
from .Action import Action
class Select(Action):
def __init__(self, objects, exclusive):
Action.__init__(self)
self.objects = objects
self.exclusive = exclusive
if exclusive:
self.previousSelections = list(base.selectionMgr.selectedObjects)
def do(self):
if... |
# coding: utf-8
# In[3]:
import os
os.environ["CUDA_VISIBLE_DEVICES"]="1"
import csv
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import math
from datetime import datetime
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.callbacks import EarlyStopping
impor... |
import pytest
from bromine.utils.wait import Wait
from .. import Mock
@pytest.mark.parametrize('bool_seq,iterations', (
([False, True, False, True], 2),
([False, False, True], 3),
([True, True], 1)
))
def test_wait_until_returns_as_soon_as_condition_is_true(bool_seq, iterations):
condition = Mock(si... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.