text stringlengths 8 6.05M |
|---|
from sklearn.model_selection import train_test_split
import utils
from DL4.GAN_model import GAN
import tensorflow as tf
SEED = 42
# Data handling:
# German credit dataset:
german_credit_data = utils.load_data("german_credit.arff")
german_credit_preprocessed_data, german_credit_target = utils.preprocessing_data(germa... |
import pytest
def add(a,b):
return a+b
def test_plan():
output=add(2,3)
assert output==5
|
import os
import json
from lxml import etree as et
from collections import OrderedDict
def ensure_dirs(path):
dirname = os.path.dirname(path)
if dirname and not os.path.exists(dirname):
os.makedirs(dirname)
def load_json(input_path):
with open(input_path, "r", encoding="utf-8") as fin:
... |
from __future__ import print_function, unicode_literals
import re
from django import template
from django.conf import settings
from django.core.urlresolvers import reverse, NoReverseMatch
from ..static_version import STATIC_VERSION
register = template.Library()
def get_asset_url(name, prefix, outside):
is_abs ... |
# -*- coding: utf-8 -*-
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.cache = OrderedDict()
self.capacity = capacity
def get(self, key):
if key not in self.cache:
return -1
value = self.cache[key]
del self.cache[key... |
# Register your models here.
from django.contrib import admin
from mezzanine.core.admin import TabularDynamicInlineAdmin
from mezzanine.pages.admin import PageAdmin
from .models import HomePage, IconBlurb, MapPlace
# TabularDynamicInlineAdmin for the Slide and IconBlurb
# NB the dynamic just gives some js to "add ano... |
def min_value(digits):
return int(''.join(str(e) for e in sorted(set(digits))))
'''
Given a list of digits, return the smallest number that could be formed from
these digits, using the digits only once (= ignore duplicates).
Note: Only positive integers will be passed to the function
(> 0 ), no negatives or zeros... |
#!/usr/bin/python3
import requests
import webbrowser
import pyautogui
import time
import random
import tkinter as tk
import tkinter.messagebox
def request_words():
""" Request dictionary of words for the world wide web.
"""
url = 'http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/p... |
from flask import request, jsonify
from auth.model.user import User
from werkzeug.security import generate_password_hash, check_password_hash
from exception import MyException
from extensions.extensions import db, jwt
from auth.model.token_revoked import RevokedToken
from flask_jwt_extended import create_access_token, ... |
# -*- coding: utf-8 -*-
import uuid
import pytz
from model.systems.assistance.date import Date
class Issue:
'''
' Obtener los hijos de un issue en base a su id
'''
def getChildsId(self, con, id):
cur = con.cursor()
cur.execute('''
SELECT r.id
FROM issues.request ... |
from typing import List
from django.urls import reverse
from colossus.apps.accounts.models import User
from colossus.apps.templates.models import EmailTemplate
from colossus.apps.templates.tests.factories import EmailTemplateFactory
from colossus.test.factories import UserFactory
from colossus.test.testcases import T... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
import heapq
self... |
#!/usr/bin/env python
import sys
import fileinput
import re
number=re.compile("^[0-9]")
for line in fileinput.input():
tokens=line.strip().split('\t')
if len(tokens)>4:
tokens[2]=tokens[2].strip().replace("\n","").replace("\r","")
m=number.search(tokens[3].strip())
if m is None:
m=number.search(... |
import numpy as np
import random
import tfim
import itertools as it
import argparse
import networkx as nx
from line_profiler import LineProfiler
import json
from itertools import groupby
import sys, os
from itertools import combinations
def main():
parser = argparse.ArgumentParser()
parser.add_argument('yhe... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
admin.autodiscover()
# The order is important
urlpatterns = patterns('',
url(r'^$', 'interview.views.home'),
url(r'^ad... |
class Solution(object):
def numPairsDivisibleBy60(self, time):
c = 0
n = [0] * 60
for i in time:
n[i%60]+=1
for i in range(0, 31):
if n[i] == 0:
continue
if (i == 0 or i == 30):
if n[i] > 1:
c+=... |
import re
import os
from .. import root_dir
# constant and path variables
labels = ["0", "1", "2", "3", "4", "5", "6",
"7", "8", "9", "character"]
darknet_dir = root_dir.darknet_path()
crop_char_img_dir = os.path.join(root_dir.data_path(), "crop_char_img")
os.makedirs(crop_char_img_dir, exist_ok = True)
ch... |
import unittest
class Testing(unittest.TestCase):
def test_string(self):
a = 'some'
b = 'some'
self.assertEqual(a, b)
def test_boolean(self):
a = True
b = True
self.assertEqual(a, b)
# pytest only needs from here...
def test_string_pytest():
a = 'some'
... |
class Call(object):
def __init__(self, idnum, name, phone, time, reason):
# Call Setup
self.idnum = idnum
self.name = name
self.phone = phone
self.time = time
self.reason = reason
def displayAll(self):
# Displays all of my caller's information
... |
import functools
from django.core.exceptions import ValidationError
from django.views.defaults import permission_denied, page_not_found
from django.views.generic import TemplateView, FormView
from django.shortcuts import redirect, get_object_or_404
# from django.urls import reverse
from django.db.models import Count
fr... |
def pointless(*args):
return "Rick Astley"
|
class View:
def __init__(self):
pass
def json(self, action):
return action
def html(self, action):
return action
def xml(self, action):
return action
|
# Dependencies
import pymongo
import datetime
# The default port used by MongoDB is 27017
# https://docs.mongodb.com/manual/reference/default-mongodb-port/
conn = 'mongodb://localhost:27017'
client = pymongo.MongoClient(conn)
# Declare the database
db = client.fruits_db
# Declare the collection
collection = d... |
from selenium import webdriver
import time
import random
letters = ["a", "b","c", "d","e", "f","g", "h","i", "j","k", "l","m", "n",
"o", "p","q", "r","s", "t","u", "v","w", "x","y", "z",]
while True:
random1 = random.choice(letters)+random.choice(letters)+random.choice(letters)+random.choice(letters)
... |
for i in range(0, 7):
if (i <= 3):
for j in range(0, i+1):
print("* ", end="")
print("\r")
else:
for x in range(i-1,6):
print("* ", end="")
print("\r")
|
import sys
import gitlab
from functions import show_vars, show_vars_for_all, add_variable, change_variable, delete_variable
from support import parse_file_variable, parse_single_variable
from namespace_definer import namespace
if "-a" in sys.argv:
masked = False
if "-m" in sys.argv:
masked = True
... |
import requests
r = requests.get("http://www.cyclonemfg.com/")
print(r.status_code)
print(r.ok)
|
# alphabet = {0:'A',1:'B',2:'C',3:'D',4:'E',5:'F',6:'G',7:'H',8:'I',9:'J',10:'K',11:'L',12:'M',\
# 13:'N',14:'O',15:'P',16:'Q',17:'R',18:'S',19:'T',20:'U',21:'V',22:'W',23:'X',24:'Y',25:'Z'}
# userInput = input('Enter a string: ').lower()
# vowels = ['a', 'e', 'i', 'o', 'u']
# counter = 0
# for letter in use... |
import web
class WayPoint:
def GET(self):
return render.waypoint()
|
#Escribir un programa que le diga al usuario que ingrese una cadena.
# El programa tiene que evaluar la cadena y decir cuantas letras mayúsculas tiene.
def conytarMayus(cadena:str):
mayusculas="ABCDEFGHIJKLMNÑOPQRSTUVWXYZ"
contaMyus = 1
for i in mayusculas:
if i in cadena:
contaMyus +=... |
import random
from concurrent.futures import ThreadPoolExecutor
from functools import partial
import graphviz
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from matplotlib.axes import Axes
from pandarallel import pandarallel
from pandas import DataFrame
from sklearn import tree
from sklea... |
from django.urls import re_path
from .views import (
OrganisationDetailView,
OrganisationsFilterView,
SupportedOrganisationsView,
)
urlpatterns = [
re_path(
r"^$", SupportedOrganisationsView.as_view(), name="organisations_view"
),
# canonical URL for a single organisation record
re... |
def countFreq(arr,num):
count = 0
if(len(arr)==0):
return 0
mid = len(arr)//2
if(arr[mid]==num):
count = count+1
count = count+countFreq(arr[mid+1:],num)
count = count+countFreq(arr[:mid],num)
return count
arr = [1,2,3,4,4,4,5,6,6,7]
print(countFreq(arr,6)) |
import os
import sys
import pandas as pd
import numpy as np
import scipy.stats as stats
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['pdf.fonttype'] = 42
import statsmodels.stats.multitest as multitest
##################################################################... |
from collections import namedtuple
import math
import random
Point = namedtuple("Point","x,y")
def distance(p1,p2):
return math.sqrt( math.pow((p2.x - p1.x),2) + math.pow((p2.y - p1.y),2))
def merge_sort(alist):
if len(alist) <= 1:
return alist
else:
mid = len(alist)//2
left = merg... |
from typing import List, Union
from dataclasses import dataclass
from torch.tensor import Tensor
@dataclass
class EncodedSentence:
x_inputs: Tensor
x_attention: Tensor
y_inputs: Tensor
y_attention: Tensor |
#!/usr/bin/python
"""
Test the performance of several inter-process transfer methods on a large dictionary.
"""
import os
import sys
import time
import socket
import random
import string
from pathlib import Path
import multiprocessing as mp
import subprocess as sp
from uuid import uuid4
sys.path.append("/home/mot... |
# do not need to specify the variable type
# declare a variable and it's type by given it a value
# example with integers and floats
def test_1():
a = 12
b = 21
d = 21.0
c = a + b
e = a + d
print(c)
print(e)
# strings
# use single or double quotes
def test_2():
print("hello")
print... |
#test generic_language.py
from dotenv import load_dotenv, find_dotenv
from pathlib import Path
import json
import os
import pymysql
import traceback
import time
import sys
import re
import subprocess
path = os.path.dirname(os.path.abspath(__file__))
sys.path.append(path + "/..")
from languagefactory import LanguageFa... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 25 13:33:29 2020
@author: Joe
UKBiobank data loading utilities
"""
import wx
from ukbiobank.gui.load_frame import LoadFrame
# Open GUI
def open():
app = wx.App()
LoadFrame()
app.MainLoop()
return
|
# Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.
# Comments Section:
# - This exercice can be easily done by hand.
# Gonna make 1 by hand so you can understand what's going on:
# 7*1 + 3 = 10
# 7*4 + 2 = 3*10
# 7*2 + 6 = 2*10
# 7*8 + 4 = 6*10
# 7*5 + 5 = 4*1... |
"""
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
"""
def print_links(links):
stack = []
while links:
stack.append(links.val)
links = links.next
while stack:
print(stack.pop())
# def print_link_recursion(links):
# if links:
# print_link_recursi... |
def additionwithoutplus(a,b):
if(b==0):
#print a
return a
sum=a^b
carry=a&b
return additionwithoutplus(sum,carry<<1)
k=additionwithoutplus(10,15)
print ("The sum is ",k)
|
from math import e, factorial
def poison_distribution(k,l):
return round(((l**k)*(e**(-l)))/factorial(k), 3)
print(poison_distribution(3,2))
|
import math
import csv
import sys
def sigmoid(x):
return 1 / (1 + math.exp(-x))
def main():
test_pred = csv.reader(open(sys.argv[1]), delimiter=" ")
print "PhraseId,Sentiment"
for (phrase_id, pred0, pred1, pred2, pred3, pred4) in test_pred:
prob = [sigmoid(float(pred0)), sigmoid(float(pred1... |
import math
from django.db import models
from django.utils import timezone
from datetime import timedelta, datetime
from numpy import mean
class Cinema(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
def roomQuantity(self):
return Room.objects.f... |
def read_essid(interface):
'''Read the name of the network a Wireless device is
attached to.
ARGS:
@interface -- The interface inquired about. Ex wlan0
RETURNS:
@essid -- The name of the wireless network the device
is configured on.
'''
from parse_iwconfig import parse_iwconfig
interfaces = pa... |
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# 162 ms
class Solution(object):
def addTwoNumbers(self, l1, l2):
head = ListNode(0);
current = head
carry = 0
while True:
a = l1.val if l1 is not None else 0
... |
import pytest
import responses
import pyyoutube.models as mds
from .base import BaseTestCase
from pyyoutube.error import PyYouTubeException
class TestSubscriptionsResource(BaseTestCase):
RESOURCE = "subscriptions"
def test_list(self, helpers, key_cli, authed_cli):
with pytest.raises(PyYouTubeExcepti... |
# -*- coding: utf-8 -*-
"""
Created on 2017/3/19
@author: will4906
"""
# 处理item_group函数
def handle_item_group(item_group):
AND = ' AND '
OR = ' OR '
NOT = ' NOT '
exp_str = ""
keyand = item_group.__getattribute__('And')
keyor = item_group.__getattribute__('Or')
keynot = item_group.__getat... |
# coding: utf-8
# # VQE Screening 2
# In[1]:
scaffold_codeBell = """
// Ref[1] https://arxiv.org/pdf/1907.13623.pdf
const double alpha0 = 3.14159265359;
module initialRotations(qbit reg[2]) {
Rx(reg[0], alpha0);
CNOT(reg[0], reg[1]);
H(reg[0]);
}
module entangler(qbit reg[2]) {
H(reg[0]);
CNOT(reg[0... |
#터틀 그래픽을 활용하여 원점을 중심으로 가로 세로 200크기의 사각형을 그린다
#마우스 이벤트를 사용하여 사각형 내부를 클릭하면 클릭한 지점에 파랑색 원,외부를 클릭하면 빨강색 원을 그린다
#원의 크기는 5입니다.
import turtle as t
import math
t.shape('turtle')
#사각형 그리기
t.penup()
t.goto(100,100)
t.pendown()
for i in range(4):
t.right(90)
t.forward(200)
def decision(x,y):
t.penup()
t.goto(x... |
import unittest
import operator
from copy import copy
from pyconc import Empty
from pyconc import Singleton
from pyconc import Concat
from pyconc import identity
from pyconc import SingleThreadedMultiplexor
class ConcTests(unittest.TestCase):
def setUp(self):
self.empty = Empty()
self.single =... |
#!/usr/bin/env python
from distutils.core import setup
setup(packages=['gridmetrics'])
|
celsius=float(input("Enter temperature in celsius : "))
fahrenheit = (celsius * 1.8) + 32
print("The temperature in fahrenheit is :",fahrenheit)
|
import math
import tensorflow as tf
import matplotlib.pyplot as plt
def sin():
while True:
x = tf.random.normal((32, 10), math.pi, 1.5)
y = tf.math.sin(x)
yield (x, y)
def build_model(layers):
x = inputs = tf.keras.Input((10, ))
for _ in range(layers):
x = tf.keras.layer... |
# In-place O(logN)
def quick_sort(x):
def partition(low, high):
pivot = x[(low + high) // 2]
while low <= high: # mid에서 만나면 탈출(즉, low == mid인 경우 탈출)
while x[low] < pivot:
low += 1
while x[high] > pivot:
high -= 1
if low <= high:
... |
#/usr/bin/env python
from astropy.units import u
from ...ast_object import ASTObject
import starlink.Ast as Ast
__all__ = ['ASTTimeFrame']
class ASTTimeFrame(ASTObject):
'''
self.astObject is of type TimeFrame.
'''
def __init__(self, ast_object=None):
raise NotImplementedError() |
# Generated by Django 2.0.4 on 2018-05-12 20:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('music', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='music',
name='href',
field=... |
import cv2
import numpy as np
from cv2 import VideoWriter, VideoWriter_fourcc
import os
import glob
import pandas as pd
import json
from PIL import Image, ImageDraw
from saveGIF import*
"""
Author: CS6670 Group
Code structure inspired from carpedm20/DCGAN-tensorflow, GV1028/videogan
"""
def clear_prior_generated_cont... |
# -*- coding: utf-8 -*-
"""
# @file name : dataset.py
# @author : yts3221@126.com
# @date : 2019-08-21 10:08:00
# @brief : 各数据集的Dataset定义
"""
import numpy as np
import torch
import os
import random
from PIL import Image
from torch.utils.data import Dataset
random.seed(1)
rmb_label = {"1": 0, "100": 1}
... |
import os
while True:
i = 1 #곱해주는 수를 항상 1로 초기화
num = int(input("몇 단?(0을 입력 시 종료) : "))
if num == 0:
print("구구단 프로그램을 종료합니다.")
break
while i < 10:
print("%d x %d = %d"%(num, i, num * i))
i += 1
os.system("pause")
os.system("cls")
|
#! /usr/bin/env python
#
# Copyright 2016 ARTED developers
#
# 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 b... |
import mcpi.minecraft as minecraft
import mcpi.block as block
import time
import anyio.seg7 as display
import RPi.GPIO as GPIO
BUTTON = 4
LED_PINS = [10,22,25,8,7,9,11,12]
GPIO.setmode(GPIO.BCM)
GPIO.setup(BUTTON, GPIO.IN)
ON = False
display.setup(GPIO, LED_PINS, ON)
mc = minecraft.Minecraft.create()
def bomb(x,y,z... |
from flask import Blueprint, request, render_template, redirect, url_for
from application.database.models import Product, db
from application.forms.product import CreateProductForm, UpdateProductForm, DeleteProductForm, SearchProductForm, FilterProductForm
product_bp = Blueprint('product_bp', __name__, url_prefix="/... |
def collatz(number):
if (number % 2 == 0):
print(number // 2)
valor = number // 2
return valor
else:
print(3 * number + 1)
valor = 3 * number +1
return valor
try:
valor = int(input('Informe um número: '))
while valor != 1:
... |
# USAGE
# python search.py --tree vptree.pickle --hashes hashes.pickle --query queries\accordion.jpg
from pyimagesearch.parallel_hashing import *
import argparse
import pickle
import time
import cv2
# construct argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument('-t', '--tr... |
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn
import threading
import urllib2
import time
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.end_headers()
message = threading.currentThread().get... |
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import dataclasses
import logging
import os
from dataclasses import dataclass
from os import PathLike
from pathlib import Path, PurePath
from typing imp... |
#!/usr/bin/env python2
##############################################################################
# Copyright (c) 2012, GeoData Institute (www.geodata.soton.ac.uk)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following... |
print(str(input()).upper()) |
# os module
import os
# 查看目录与切换目录
print(os.getcwd()) # 查看当前目录,D:\pythonPro\function
os.chdir("D:\pythonPro\day01") # 切换目录
print(os.getcwd()) # 再次查看, D:\pythonPro\变量-print
print("-"*30)
print(os.curdir) # 打印当前路径.
print(os.pardir) # 打印上级路径..
os.chdir(os.pardir) # 切换到上次目录
print(os.getcwd()) # 切换到上级目录后,打印当... |
# HW1 for Computer Vision
import cv2
import numpy as np
from matplotlib import pyplot as plt
import math
# Asserts to test that the values are correct
# assert np.abs(np.sum(psi)) < 1e-8
# assert np.abs(np.sum(np.abs(psi) ** 2) - 1) < 1e-8
# Tutorial stuff to get used to cv2's API
# Loads an image
# grayscale image... |
# config/filesystem.py
# Copyright (C) 2011-2014 Andrew Svetlov
# andrew.svetlov@gmail.com
#
# This module is part of BloggerTool and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import codecs
import os
from bloggertool.exceptions import FileNotFoundError, FileOutOfProject
... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param A : list of linked list
# @return the head node in the linked list
def mergeKLists(self, A):
nodes = []
for node in A:
c... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 7 20:18:34 2018
@author: user
字串加總
"""
val=input()
val=val.split(" ")
vl=list(map(eval,val))
print("Total = {:}".format(sum(vl)))
print("Average = {:}".format(sum(vl)/len(vl))) |
g2=map(int,input().split())
print(max(g2))
|
# https://stackoverflow.com/questions/70797/user-input-and-command-line-arguments
# https://docs.python.org/2.0/lib/module-binascii.html
# import sys
import binascii
# def hexTo64(input_hex):
# binary = binascii.a2b_hex(input_hex)
# output_64 = binascii.b2a_base64(binary)
# return output_64
# hexTo64(sys... |
import unittest
from nab.files import File
from nab.show import Show
# fields: ext, group, tags
# episode, season
# title, eptitle
file_tests = [
('[gg]_C_The_Money_of_Soul_and_Possibility_Control_-_01_[7B880013].mkv',
{'entry': ('C: The Money of Soul and Possibility Control', 1, 1),
'e... |
#coding:utf-8
def script(s, player=None):
from NaoQuest.objective import Objective
from NaoCreator.setting import Setting
import NaoCreator.Tool.facebookor as FC
if not player:
Setting.error("Error in execution of pre_script of objective \"result\": ... |
def sumSquareDif(num):
sumOfSquare, squareOfSum = 0, 0
for i in range(1, num + 1):
sumOfSquare += i * i
squareOfSum += i
squareOfSum *= squareOfSum
result = squareOfSum - sumOfSquare
return result
print(sumSquareDif(100))
|
#coding: utf-8
from __future__ import print_function, absolute_import
import logging
import re
import json
import requests
import uuid
import time
import os
import argparse
import uuid
import datetime
import socket
import apache_beam as beam
from apache_beam.io import ReadFromText
from apache_beam.io import WriteToT... |
def interweave(s1, s2):
output = ''
for x in range(len(s1)):
if not s1[x].isdigit():
output += s1[x]
if x < len(s2) and not s2[x].isdigit():
output += s2[x]
return output
'''
Your friend Rick is trying to send you a message, but he is concerned that it
would get in... |
import os
import pickle
import argparse
import matplotlib.pyplot as plt
import numpy as np
from numpy.linalg import norm
from sklearn.model_selection import train_test_split
import utils
import logReg
from logReg import logRegL2, kernelLogRegL2
from pca import PCA, AlternativePCA, RobustPCA
def load_dataset(filename)... |
__author__ = 'Magnus'
from Spiller import Spiller
from Aksjon import Aksjon
import random
class SpillerHistoriker(Spiller):
def __init__(self, husk):
assert(isinstance(husk, int))
self._husk = husk
self._historie = list()
def velg_aksjon(self):
mestsannsynlig = self.finnMestS... |
#!/usr/bin/python
# Yume Tower Defense
import yume.core
raise SystemExit(yume.core.main())
|
# coding:utf-8
import sys
import traceback
import dill
import easyquotation
import datetime
ACCOUNT_OBJECT_FILE = 'account.session'
class StrategyTemplate:
name = 'DefaultStrategyTemplate'
def __init__(self, log_handler, main_engine,stocks=[],additional_stocks=['000002'],except_stocks=['600556','000001']):
... |
import cv2
import numpy as np
from matplotlib import pyplot as plt
def hex_to_rgb(v):
v = v.lstrip('#')
lv = len(v)
return list(int(v[i:i+lv//3], 16) for i in range(0, lv, lv//3))
def count_pixels(img, value):
np_img = np.fromstring(img, np.uint8)
jpg = cv2.imdecode(np_img, ... |
from PyQt5.QtWidgets import *
from PyQt5 import QtCore
import os
class CheckableDirModel(QDirModel):
def __init__(self, parent=None):
QDirModel.__init__(self, None)
self.checks = {}
self.rootDir = None
def data(self, index, role=QtCore.Qt.DisplayRole):
if role == QtCore.Qt.Che... |
import unittest
from katas.kyu_6.binding_within_the_list_monad import bind
class BindTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(bind([1, 2, 3], lambda a: [a]), [1, 2, 3])
def test_equals_2(self):
self.assertEqual(bind([7, 8, 9], lambda a: [[a]]), [[7], [8], [9]])
... |
import mx
import mx_sdk
_suite = mx.suite("mozart-graal")
mx_sdk.register_graalvm_component(mx_sdk.GraalVmLanguage(
suite=_suite,
name="Mozart-Graal",
short_name="moz",
dir_name="oz",
license_files=["LICENSE_MOZART_GRAAL.txt"],
third_party_license_files=[],
truffle_jars=[
"mozart-g... |
from unittest import TestCase
from phiml.math import tensor, batch, is_finite
from phi.field import *
class TestNoise(TestCase):
def test_multi_k(self):
grid = CenteredGrid(Noise(vector='x,y', scale=tensor([1, 2], batch('batch'))), x=8, y=8)
self.assertTrue(is_finite(grid.values).all)
|
from flask import Flask, render_template
from iceke.worm import Worm
import json
from iceke.util import Util
app = Flask(__name__)
flint_url = 'http://11.11.0.64:8099/'
flint_stage_url = 'http://11.11.0.64:4041/stages/'
spark_url = 'http://11.11.0.55:8090/'
spark_stage_url = 'http://11.11.0.55:4040/stages/'
@app.ro... |
import socket
ss=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ss.connect(('www.baidu.com',80))
data = "GET {} HTTP/1.1\r\n" \
"Host:{}\r\n" \
"Connection:close\r\n" \
"User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/... |
import cv2
import numpy as np
def find_rect_of_target_color(image):
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV_FULL)
h = hsv[:, :, 0]
s = hsv[:, :, 1]
mask = np.zeros(h.shape, dtype=np.uint8)
mask[((h < 20) | (h > 200)) & (s < 80)] = 255
contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX... |
from collections.abc import Collection
from .card import Card, CardSuit, CardRank
class BaseDeck(Collection):
cards = []
# TODO Deck should implement the collection interface
"""This class represents a deck of cards"""
def __init__(self, cards):
if cards is None:
self.cards = []
... |
import sys
sys.path.append('..')
from run_command import run_command
from batman_socket import BatmanSocket
from BatmanServerSocket import BatmanServerSocket
class BatmanClientServerSocket(BatmanServerSocket):
'''CLASS: Representing a BATMAN-Advanced node capable of listening, interpreting
actions, and tra... |
from django.conf.urls import include, url, patterns
from django.contrib import admin
from tastypie.api import Api
from quotes import views
from quotes.api import QuoteResource
v1_api = Api(api_name='v1')
v1_api.register(QuoteResource())
urlpatterns = patterns(
'',
url(r'^$', views.manager, name='home'),
url(... |
from flask import request, g, Blueprint, json, Response
from ..models.RouteModel import RouteModel, RouteSchema
route_api = Blueprint('route_api', __name__)
route_schema = RouteSchema()
@route_api.route('/', methods=['POST'])
def create():
req_data = request.get_json()
data, error = route_schema.load(req_dat... |
# making a tornado figure in graph
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
mpl.rcParams['legend.fontsize'] = 10
fig = plt.figure()
ax = fig.gca(projection='3d')
theta = np.linspace(0 * np.pi, 10 * np.pi, 200)
z = np.linspace(0, 10, 200)
r = z ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.