text stringlengths 38 1.54M |
|---|
import matplotlib.pyplot as plt
import numpy as np
import torch
from brancher.variables import ProbabilisticModel
from brancher.standard_variables import NormalVariable, DeterministicVariable, LogNormalVariable
import brancher.functions as BF
from brancher.visualizations import plot_density
from brancher.transformatio... |
__author__ = '29146'
import sys
def createstack():
stack = []
return stack
def push(item,stack):
stack.append(item)
print stack
def pop(stack):
stack.pop()
print stack
def peek(stack):
print stack[len(stack)-1]
if __name__ == '__main__':
stack = createstack()
push(str(20),stack)... |
import random
import time
import os
class PostIt(object):
def __init__(self, content):
self.content = content
class NoteBook(object):
def __init__(self, book_title):
self.book_title = book_title
self.counter = 0
self.note_dict = {}
def add_post_it(self, page, content):
... |
# _ooOoo_
# o8888888o
# 88" . "88
# (| -_- |)
# O\ = /O
# ____/`---'\____
# . ' \\| |// `.
# / \\||| : |||// \
# / _||||| -:- |||||- \
# | | \\\ - /// | |
# ... |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... |
'''
Problem
A partial permutation is an ordering of only k objects taken from a collection containing n objects (i.e., k<=n).
For example, one partial permutation of three of the first eight positive integers is given by (5,7,2).
The statistic P(n,k) counts the total number of partial permutations of k objects that c... |
import numpy as np
from mnist import MNIST
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.neighbors import NearestNeighbors
from sklearn.preprocessing import normalize
import imageio
# Module display_nerwork help us hiển thị nhiều bức ảnh các chữ số cùng một lúc
from display_network im... |
from django.http.response import HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.db.models import Q
from .models import Category, Post
from comments.models import *
from .forms import *
from comments.forms import *
from FinalBlog.settings import... |
import requests
import hashlib
import re
url = "https://sec-army.ml/fatherphp/fatherphp.php?key1="
s= requests.session()
d = "1"
for d in range(-1000,100):
#print d
r= s.get(url + str(d))
if "secarmy" in r.content:
print r.content
print d
url2 = url + str(d)
# 1e1-2... |
#!/usr/bin/env python3
# coding: utf-8
""" Functions to plot backtest. """
# Built-in packages
# External packages
import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns
# Internal packages
from fynance.features.money_management import iso_vol
from fynance.features.metrics import drawdown, ro... |
#!/usr/bin/env python
from SimpleHTTPServer import SimpleHTTPRequestHandler
from BaseHTTPServer import HTTPServer
from urlparse import urlparse, parse_qs
import cgi
PORT=5003
class TracerHandler(SimpleHTTPRequestHandler):
container={'k':0};
def do_GET(self):
#self.send_response(200)
... |
#!/usr/bin/env python3
def main():
for _ in range(int(input())):
people = []
for _ in range(int(input())):
name, classes, _ = input().split()
classes = [ord(c[0]) for c in classes.split("-")]
people.append((name[:-1], classes[::-1]
+ [109 for _ ... |
import logging
import re
# noinspection PyPackageRequirements
from telegram.ext import (
CommandHandler,
MessageHandler,
ConversationHandler,
Filters
)
from bot import stickersbot
from .packs import create
from .stickers import add
from .conversation_statuses import Status
from .fallback_commands impo... |
'''VoidFinder - Hoyle & Vogeley (2002)'''
################################################################################
#
# IMPORT MODULES
#
################################################################################
from voidfinder import filter_galaxies, find_voids
from astropy.io import fits
from astrop... |
#SudokuPuzzle.py
# Adapted from SudokuData.py
#################
## sudokuPuzzle ##
#################
from select_error import SelectError
from SudokuData import SudokuData
class SudokuPuzzle(SudokuData):
def __init__(self, desc=None, file_name=None, **kwargs):
"""
:description: Description ... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from pylab import *
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import math
def laplace_iteration2_t(f,r,U_t,dr,dtheta,n,m):
n=int(n)
m=int(m)
g=np.zeros((n+1,m));
for j in range(1,int(m-1)): #iteration on the angle
#... |
from data_transfer import DataTransfer
import csv
import psycopg2
def table_list(connect_par):
tbls = []
with psycopg2.connect(connect_par) as con:
with con.cursor() as cur:
# Получаем список таблиц из исходной БД :
cur.execute("""SELECT table_name
... |
def arrayChange(inputArray):
sum1 = 0
for i in range(len(inputArray)):
temp = list()
if i == 0:
continue
else:
if inputArray[i] > inputArray[i-1]:
continue
else:
temp.append(inputArray[i])
inputArray[i] =... |
"""
Project: RadarBook
File: non_coherent_integration.py
Created by: Lee A. Harrison
One: 10/9/2018
Created with: PyCharm
Copyright (C) 2019 Artech House (artech@artechhouse.com)
This file is part of Introduction to Radar Using Python and MATLAB
and can not be copied and/or distributed without the express permission o... |
from numpy import *
drum = {}
drum[0] = '36' #bass drum
drum[1] = '41' #toms
drum[2] = '38' #snares
drum[3] = '49' #cymbals
drum[4] = '42' #Hi-Hat
threshhold = [0.4,0.05,0.25,0.11,0.4]
with open('output.txt') as f:
content = f.readlines()
delimiter = 120
time = 0
random.seed(42)
wr = open('result.txt','w')
for... |
"""
날짜 : 2020/08/11
이름 : 이성진
내용 : 선형회귀 분석 실습하기
"""
a = 0.9767441021911394
b = -102.209288612913
x_data = [170, 155, 150, 175, 165, 180, 182, 173, 190, 188]
#분석모델 정의
def model(x):
y = a * x + b
return y
for x in x_data:
print('%d에 대한 예측값 : %d' % (x, model(x))) |
# 练习一下PPO立杆子,用pytorch重写的,但是train不动...
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import gym
# 超参数
A_LR = 0.0001
C_LR = 0.0002
A_UPDATE_STEPS = 10 # 每次sample完一个minibatch更新多少次actor
C_UPDATE_STEPS = 10 # 每次sample完一个minibatch更新多少次critic
S_DIM, A_DIM = 3, 1 # S: cos(theta), sin(th... |
from django.db import models
from user.models import User
from .constants import COMPANY_TYPES, IntegerRangeField
# Create your models here.
class Company(models.Model):
name = models.CharField(max_length=100, verbose_name='Company Name :')
type = models.CharField(max_length=50, verbose_name='Company Typ... |
# Copyright 2022 Google, LLC.
#
# 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 writing, ... |
from random import randrange, sample, shuffle
from time import sleep
from maze import constants
from maze.tile.passage import Passage
from maze.tile.wall import Wall
from maze.tile.exit import Exit
from maze.tile.tunnel import Tunnel
class MazeGenerator:
"""
Generator object for maze
"""
def __init__... |
# SECTION 5
# 1. Revisiting the Differences between Methods and Functions
mylist = [1,2,3,4]
mylist.pop() # <- Method
print(mylist)
# -> [1,2,3]
mylist = [1,2,3]
max_number = max([1,2,3,4,100,900]) # <- Function
# mylist.max() -> this isn't a thing because max is a function
# error -> unresolved attribute refer... |
import numpy as np
v1 = [np.random.randint(-1,2) for i in range(3)]
v2 = [np.random.randint(-1,2) for i in range(3)]
v = [v1, v2]
def i2pv(N, p):
v = []
i = 0
while p**i < abs(N):
v.append(N % p**i)
i += 1
if len(v) == 0:
v.append(0)
return v
return v
... |
from validators.subsystems import bscode
from datasetrecords import models
from validators.subsystems import checkstatus
from validators.subsystems import checkformat
from validators.subsystems import checkenforcements
from validators.subsystems.datasets import pivalidate
from validators.subsystems.datasets import ibv... |
import os
os.chdir("C:\\Users\\Logan\\Desktop\\simEngine3D")
from pendulum_function import pendulum
import numpy as np
from constraints_in import constraints_in
from simEngine3D_dataload import data_file, DP1_PHI_partials,CD_PHI_partials,DP2_PHI_partials,D_PHI_partials, body
from simEngine3D_functions import build_p, b... |
# https://leetcode.com/problems/merge-intervals/
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
# Algorithm
# Two intervals i1 and i2 can be overlapping if and only if
# * i2.start <= i1.end
# If this is the case two in... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
from scrapy.loader.processors import MapCompose
class ArticlespiderItem(scrapy.Item):
# define the fields for your item here like:
# name = sc... |
from datetime import date, timedelta
from desio.model import users, fixture_helpers as fh
from desio.tests import *
class TestMiddleware(TestController):
form_url = url_for(controller='test', action='rando_form')
exception_url = url_for(controller='test', action='exception')
def test_timer_proxy(self... |
import numpy as np
from PIL import Image
import torch
import torch.nn as nn
from torch.autograd import Variable
# from import *
import torch.nn as nn
# from accuracy import accuracy_check, accuracy_check_for_batch
import scipy.io as sio
import os
from loss import *
from unet1 import *
import matplotlib.pyplot as plt
... |
#!/usr/bin/env python
# encoding: UTF-8
from xml.etree import ElementTree as ET
import os
class XmlHandler:
def __init__(self, xmlfile):
print ("xmlHandler init: " + xmlfile)
self.xmlTree = self.readXml(xmlfile)
def readXml(self, in_path):
if not os.path.exists(in_path):
print ("there is no such file:... |
from django.db import models
from django.contrib.auth.models import User
# модель для создания ДЗ для пользователей
class Homework(models.Model):
homework_name = models.CharField(max_length=100)
description = models.CharField(max_length=300)
def __str__(self):
return self.homework_name
# модель д... |
import numpy as np
n1=np.random.randint(10,50,10)
print(n1)
print(np.std(n1))
print(np.mean(n1))
print(np.median(n1))
|
"""
Copyright (c) 2020 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 writin... |
import numpy as np
import matplotlib.pyplot as plt
import time
import h5py
from ..doublyPeriodic import doublyPeriodicModel
from numpy import pi
class model(doublyPeriodicModel):
def __init__(self, name = None,
# Grid parameters
nx = 128, ny = None, Lx = 2.0*pi, Ly = None,
# ... |
from tkinter import *
from math import ceil
import time
import math
import timeit
class App:
def __init__(self, master):
self.master = master
Grid = mainGrid(self.master, 0, 0)
class mainGrid:
def __init__(self, parent, x, y):
self.parent = parent
self.container = Frame(self.p... |
import os
import csv
import glob
from pathlib import Path
import sqlite3
from collections import defaultdict
def main():
PROJECT_ROOT = Path(__file__).parent.parent
DATABASE = str(Path(Path.home(), 'king-county-assessor.sqlite3'))
with sqlite3.connect(DATABASE) as connection:
connection.execute('... |
# -*- coding: utf-8 -*-
import re
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from hotline.items import HotlineItem
class DongguanSpider(CrawlSpider):
name = 'Dongguan'
allowed_domains = ['wz.sun0769.com']
start_urls = ['http://wz.sun0769.co... |
import pandas as pd
url = "https://raw.githubusercontent.com/justmarkham/DAT8/master/data/u.user"
occupation = pd.read_csv(url, sep = "\t")
occupation.to_csv("Datasets\occupation.csv") |
# Third party import
import pymongo
# Local application imports
from flask import (
_app_ctx_stack,
current_app
)
class MongoConnector(object):
"""Pymongo.MongoClient wrapper
Wraps default MongoClient for proper database
working with flask app context. Also handles
connection with M... |
#!/usr/bin/env python
# encoding: utf-8
import sys
def to_network(filename, outputname):
f = open(filename, "r")
f2 = open(outputname, "w")
convert = {}
a = f.readline()
while (a != '\n'):
k, d = a.split(":")
convert[k] = int(d)
a = f.readline()
text = f.read()
... |
"""Tests the `vlmd_submission_tools.subcommands.base.Subcommand` class"""
import unittest
from utils import captured_output
from vlmd_submission_tools.__main__ import main
from vlmd_submission_tools.subcommands import Subcommand
class TestSubcommand(unittest.TestCase):
class Example(Subcommand):
@classm... |
from django.db.models import Sum, F, Value, DecimalField, ExpressionWrapper, CharField
from .models import *
def summaryTotals(proposalID):
summaryTotals = Security.objects.prefetch_related('relatedDraftHoldings__draftAccount__draftPortfolio__proposal')
summaryTotals = summaryTotals.filter(
relatedDraf... |
'''
Created on Jun 1, 2016
@author: pedrom
'''
import subprocess
from os import listdir, remove
from os.path import isfile, join
def get_captions(youtube_url):
print("Getting captions for " + youtube_url)
ret_dic = {}
argsCapASR = "--write-auto-sub --sub-lang en --skip-download -o cap_asr.tx... |
import discord
from .base import BaseRule
from ..utils import *
import logging
import re
log = logging.getLogger("red.breadcogs.automod")
class MentionSpamRule(BaseRule):
def __init__(
self, config,
):
super().__init__(config)
self.name = "mentionspam"
@staticmethod
async de... |
def getNewCookie(_id: int, _nume: str, _descriere: str, _pret: int, _calorii: int, _in_menu_since: int):
cookie = {
'id': _id,
'nume': _nume,
'descriere': _descriere,
'pret': _pret,
'calorii': _calorii,
'in_menu_since': _in_menu_since
}
return cookie
def g... |
# conding = utf-8
from selenium import webdriver
import time
import json
class DouyuSpider:
def __init__(self):
self.start_url = "https://www.douyu.com/directory/all"
self.driver = webdriver.Chrome(r"F:\chromedriver.exe")
def get_content_list(self):
li_list = self.driver.find_elements... |
from layers.domain_layer.user_aggregate import Regulator
from layers.domain_layer.repositories import UserRepository
def Generate_Regulator():
regulator = Regulator("admin","admin@admin.com","88888888","Mr Regulator","123456")
UserRepository().add(regulator)
return regulator.id
|
import yaml
import os
class YAML:
def __init__(self,filename=None):
self.__filenane=filename
self.__config_path=os.path.join(os.curdir,self.__filenane)
self.__config=self.__load_config()
def __load_config(self):
try:
with open (self.__config_path) as f:
... |
"""
15. 3Sum
Medium
19433
1856
Add to List
Share
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
Example 1:
Input: nums = [-1,0,1,2,-1,-... |
n = int(input())
a = list(map(int, input().split()))
lists = [i for i in range(1, n + 1)]
dicts = {j:i for i, j in zip(lists, a)}
for i in range(1, n + 1):
print(dicts[i], end=' ')
print()
|
"""
This module will query the OWL Ontology based on a user's inputted genre to
select a set of instruments as midi program integers
"""
import owlready2 as owl
from music21 import instrument
def load_ontology():
return owl.get_ontology("root-ontology.owl").load()
def get_genre_map(ontology):
genres = ... |
# Problem 1209. 1, 10, 100, 1000...
# http://acm.timus.ru/problem.aspx?space=1&num=1209
# See the sequence
# 1
# 10
# 100
# 1000
# 10000
# 100000
# We get '1' after a '0' increased
# The sequence of getting '1' is 1,2,4,7,11,16 and so on
# if we multiple a number by 8 and subtrack by 7 and the result
# of the equat... |
__author__ = 'Chaithra'
from listutils import *
#
notes = """
This is to make you familiar with linked list structures usage in python
see the listutils.py module for some helper functions
"""
class Node:
def __init__(self, value=None):
self.value = value
self.next = None
#giv... |
from PyObjCTools.TestSupport import *
import CoreWLAN
class TestCWNetwork (TestCase):
@min_os_level('10.7')
def test_methods10_7(self):
self.assertResultIsBOOL(CoreWLAN.CWNetwork.ibss);
@min_os_level('10.6')
def test_methods10_6(self):
self.assertResultIsBOOL(CoreWLAN.CWNetwork.isEqu... |
from turtle import Turtle,Screen
import random
import turtle as t
# COLORS = [(236, 235, 230), (239, 228, 234), (223, 240, 231), (227, 232, 241), (240, 37, 113), (146, 25, 72), (218, 161, 64), (14, 144, 88), (239, 73, 35), (186, 169, 36), (29, 127, 193), (56, 190, 230), (245, 220, 53), (178, 42, 102), (35, 175, 119), (... |
import numpy as np
import scipy.sparse as sp
import argparse
import random
nodes_map = {
}
def read_dat(path, file_name):
path = path + file_name
data = np.loadtxt(path, delimiter='\t', dtype=np.int)
return data
def gen_nodes_map(path, node_type):
data = read_dat(path=path, file_name="%s.txt" % no... |
def dictionary(openfile):
lines = open(openfile)
word_count_list = {}
for line in lines:
line = line.rstrip()
words = line.split()
for word in words:
word_count_list[word] = word_count_list.get(word, 0) + 1
for word, count in word_count_list.items():
print(... |
print('Part 1')
list=[0]
for line in open('input.txt'):
list.append(int(line.split('\n')[0]))
sortd=sorted(list)
i=0
counter1=1
counter3=1
while i<(len(sortd)-1):
if sortd[i+1]-sortd[i]==1:
counter1=counter1+1
if sortd[i+1]-sortd[i]==3:
counter3=counter3+1
i=i+1
print(counter1*counter3... |
#Import the json library
import json
'''
Two important json methods for json.dump and json.dumps
json.dump ==> to dump a python object into a text file in json format
json.dumps ==> to convert a python object into string representation of the json format.
'''
friend1 = {"Raunaq": [24, "India"]}
friend2 = {"Milony": [... |
def alphabetize(thisString):
newString = ''
newString.join(sorted(thisString))
return newString
def anagram(aString, bString):
if len(aString) != len(bString):
return False
aString = alphabetize(aString)
bString = alphabetize(bString)
if aString == bString:
return True
e... |
import nengo
import numpy as np
import pytest
from nengo.exceptions import BuildError
from nengo_loihi.builder import Model
from nengo_loihi.neurons import nengo_rates
@pytest.mark.parametrize("tau_ref", [0.001, 0.003, 0.005])
def test_lif_response_curves(tau_ref, Simulator, plt):
n = 256
encoders = np.ones(... |
while True:
m = int(input('Введите месяц числом от 1 до 12'))
e = 0
r = 12
if m >= e or m < r:
win = [1, 2, 12]
sprig = [3, 4, 5]
sam = [6, 7, 8]
aut = [9, 10, 11]
if win.count(m) == 1:
print('Зима')
else:
if sprig.count(m) == 1:
... |
class Tracer:
def __init__(self):
self.IsEnabled = True
def __call__(self, f):
def wrap(*args, **kwargs):
if self.IsEnabled:
print('Tracing is happening')
return f(*args, **kwargs)
return wrap
tracer = Tracer()
@tracer
def rotate_list(lst):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Take absolute value. Needed before smooth if amplitudes are negative!
# Implemented by Martin Hardcastle based on clip/flag code
import logging
from operations_lib import *
logging.debug('Loading ABS module.')
def run( step, parset, H ):
import numpy as np
f... |
def multiply(x, y):
return x * y
def subtract(x, y):
return x - y
def divide(x, y):
return x / y
def square(x):
return x**2
def raise_to(x, y):
print("This function raises x to the power y")
return x**y
def add(x, y):
return x + y
|
from engine import get_psql_engine
from jinja2 import Environment
from sql_templates import SIMPLE_SEARCH_TEMPLATE, SEARCH_TEMPLATE, SIMPLE_MATCH_TEMPLATE, MATCH_TEMPLATE
from config import PPM_DIFF,RT_DIFF,WITH_MS2,EXCLUDE_CONTROLS,INT_OVER_CONTROLS,ATTRS
def construct_search(mz,rt,ion_mode,config):
ppm_diff = ... |
# read three numbers
number1 = int(input("Enter the first number: "))
number2 = int(input("Enter the second number: "))
number3 = int(input("Enter the third number: "))
# We temporarily assume that the first number
# is the largest one.
# We will verify this soon.
largest_number = number1
# we check if the... |
import FWCore.ParameterSet.Config as cms
# Silicon Strip Digitizer running with APV Mode Deconvolution
from SimGeneral.MixingModule.stripDigitizer_cfi import *
stripDigitizer.APVpeakmode = False
|
# 1. combo_string
def combo_string(a, b):
if len(a) > len(b):
return b + a + b
else:
return a + b + a
# 2. extra_end
def extra_end(str):
temp = str[-2:]
return temp + temp + temp
# 3. first_half
def first_half(str):
return str[:len(str) // 2]
# 4. first_two
def first_two(str):
... |
for i in range(101):
if( i % 5 == 0 and i % 2 == 0):
print(i, 'zip', 'zap')
elif( i % 2 == 0):
print(i, 'zip')
elif( i % 5 == 0):
print(i, 'zap')
else:
print(i)
#please note that there are many solutions to this problem
# Here is what the output should look like:... |
from django.apps import AppConfig
class ShopifywebhooksConfig(AppConfig):
name = 'shopifywebhooks'
|
import os.path
import os
import subprocess
import distutils.sysconfig
# Set these to None for debugging or subprocess.PIPE to silence compiler
# warnings and errors.
STDOUT = subprocess.PIPE
STDERR = subprocess.PIPE
# STDOUT = None
# STDERR = None
# This is the max length that I want a printed line to be.
MAX_LINE_LE... |
import os
import h5py
import numpy as np
import json
import glob
import pysrt
from tqdm import tqdm
from PIL import Image
from utils import read_json_lines, load_json, save_json
import cv2 as cv
rgb_path = "/home/scw/Downloads/tvqa_new/frames_hq/"
of_path = "/home/scw/CLionProjects/optical_flow/cmake-b... |
# -*- coding: utf-8 -*-
"""
This is the module ``report_defines.py`` for report generation by
simulation in Typhoon HIL API in Python.
Reserved to some value and text definitions for the report used in
``Report_function.py`` module.
Test Name: Modulation performance test
Description... |
class Conta():
def __init__ (self, clientes, numero, saldo = 0, operacoes = []):
self.clientes = clientes
self.numero = numero
self.saldo = saldo
self.operacoes = operacoes
def resumo(self):
print(f"CC Número {self.numero} \nSaldo: {self.saldo}")
def saque(self, qua... |
import struct
import perilib
class RobotisDynamixel2Packet(perilib.StreamPacket):
TYPE_INSTRUCTION = 0
TYPE_STATUS = 1
TYPE_STR = ["instruction", "status"]
TYPE_ARG_CONTEXT = ["outgoing_args", "incoming_args"]
crc_table = [
0x0000, 0x8005, 0x800F, 0x000A, 0x801B, 0x001E, 0x0014, 0x8011,
... |
import numpy as np
import operator
def twodim(mat):
len_mat = len(mat)
if len_mat == 1:
return 'Matriz de 1 elemento'
elif len_mat == 2:
return 'Matriz de 2 elementos'
elif len_mat == 3:
return 'Matriz de 3 elementos'
def twodim_recursivo(mat1):
len_mat1 = len(mat1)
whi... |
import itertools
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tensorflow as tf
from sklearn.ensemble import IsolationForest
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
# CONSTANTS
ITERATIONS = 10000
LABEL = 'Ado... |
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from wheel.signatures import assertTrue
from features.pages.page_selector import LoginPageLocator, OrganizationPopup, HomePageLocator
from selenium.webdriver.support import expected_conditions as EC
def l... |
#!/usr/bin/python3
"""
Start link class to table in database
"""
import sys
from model_state import Base, State
from sqlalchemy import (create_engine)
if __name__ == "__main__":
usr = argv[1]
pwd = argv[2]
db_name = argv[3]
engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'.
... |
# coding: utf-8
# 自分の得意な言語で
# Let's チャレンジ!!
input_line = input()
s = ""
for i in range(int(input_line)):
s += "*"
print(s)
|
import numpy as np
"""task 1"""
m = np.ones((3, 3))
"""task 2"""
m = np.vstack((m, [2, 2, 2]))
m = np.hstack((m, [[3], [3], [3], [3]]))
print(m)
|
a = []
x = input("please input numbers with space between them \n").split()
h = len(x)
y = 0
for i in range(0,h):
a.append(int(x[y]))
y = y + 1
a.sort()
z = len(a) - 1
w = str(a)
w = w.replace("[", "")
w = w.replace("]", "")
w = w.replace(",", "")
print(w)
print("The smallest number among the input is" , a... |
import os
import jieba
def cn_ci(dir_path):
all_text = ""
for file_name in os.listdir(dir_path):
if file_name.find(".txt") != -1:
file_path = "/".join([dir_path, file_name])
with open(file_path, "rb") as f:
all_text = f.read()#.decode("utf-8")
with op... |
x = int(input("Insert number "))
if x % 2 == 0:
print("Number is even")
else:
print("Number is not even")
|
#공통 요인을 위한 슈퍼 클래스 생성
class Employee:
def __init__(self, name):
self.name = name
def doWork( self ):
print( 'Employee {0}는 '.format( self.name ), end = '')
#상속받으려면 괄호 안에 슈퍼클래스명 입력
#파이썬은 단일 상속만 지원 ( 다중 상속은 미지원 )
class RegularEmployee( Employee ):
def __init__( self, name, age)... |
"""
all mixins are defined here
"""
from django.contrib.auth.views import redirect_to_login
from django.contrib.auth.models import Group
from django.http import Http404
class RequireLoginMixin:
"""
Login Required before accessing the view
"""
def dispatch(self, request, *args, **kwargs):
# p... |
from bs4 import BeautifulSoup
import requests
import urllib.request
res= requests.get('https://bing.wallpaper.pics/')
soup= BeautifulSoup(res.text, 'lxml')
imageUrl= soup.find('div', class_='panel').find('img')['src']
urllib.request.urlretrieve(imageUrl , 'bing.jpg') |
from django.forms import ModelForm
from myapp.models import *
# Create the form class.
class MeasurementForm(ModelForm):
class Meta:
model = Measurement
fields = ['msmtType', 'value', ] |
#Uses python3
import sys
import queue
import math
#=============================================
sample_undigraph0 = """
4 5
2 1
4 3
1 4
2 4
3 2
"""
# 1 3 Test Source and Terminus
sample_undigraph1 = """
4 4
1 2
4 1
2 3
3 1
2 4
"""
sample_undigraph2 = """
5 4
5 2
1 3
3 4
1 4
3 5
"""
sample_digraph1 = """
5 8
4 3
... |
from django.test import Client
from django.test import SimpleTestCase
from adminlte2_templates.core import reverse
class ContextTestCase(SimpleTestCase):
def setUp(self):
self.client = Client()
def context_exists(self, context):
# Get view from 'layouts' unit test
response = self.cli... |
from django.db.models.signals import post_save
from django.dispatch import receiver
from onadata.apps.logger.models import MergedXForm
from onadata.libs.permissions import OwnerRole
from onadata.libs.utils.project_utils import set_project_perms_to_xform
@receiver(
post_save,
sender=MergedXForm,
dispatch_... |
"""parallelizer tester
Useful to make sure tests are being parallelized properly, and then reported correctly.
This file is named specially to prevent being picked up by py.test's default collector, and should
not be run during a normal test run.
"""
import random
from time import sleep
import pytest
pytestmark = ... |
class Solution:
def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:
"""DFS.
"""
graph = defaultdict(set)
for a, b in allowedSwaps:
graph[a].add(b)
graph[b].add(a)
visited = set()
res = 0... |
__version__ = "$Id$"
import mac_windowbase
_Toplevel = mac_windowbase._Toplevel
toplevel = _Toplevel()
mac_windowbase.toplevel = toplevel
from mac_windowbase import *
addclosecallback = toplevel.addclosecallback
canceltimer = toplevel.canceltimer
close = toplevel.close
mainloop = toplevel.mainloop
newcmwindow = top... |
import serial
import serial.tools.list_ports_linux as ports
import gi.repository.GLib as gobject
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk as gtk
import pytopo.MapWindow as MapWindow
import pytopo.MapViewer as MapViewer
import gc
import re
class MyMapWindow(MapWindow):
#override in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.