text
stringlengths
38
1.54M
import numpy as np from models.mlp import MultilayerPerceptron from models.scn import StructuredControlNet from models.rnn import RecurrentNeuralNetwork from models.rcn import RecurrentControlNet from models.gru import GatedRecurrentUnit from models.lstm import LongShortTermMemory from models.tdnn import TimeDelayNeura...
import random from pico2d import * class Ball: image = None; def __init__(self): self.x, self.y = random.randint(200, 790), 60 if Ball.image == None: Ball.image = load_image('ball21x21.png') def update(self, frame_time): pass def draw(self): self.image.d...
from django.urls import path from . import views urlpatterns = [ path('Action/', views.action ,name='action'), path('Action/<int:detailact_id>/', views.detailact ,name='detailact'), path('Comedy/', views.comedy ,name='comedy'), path('Comedy/<int:detailcom_id>/', views.detailcom ,name='detailcom'), ...
# # Definicao da classe campo # import numpy import ConstantsU import CartorioU import WallU import GlobalsU import UtilsU import ConversionU from random import randrange from copy import copy class Field: def __init__(self, conf): print('Gerando o mapa...') self.nSize = conf.nSize self.mGround = numpy.zer...
import re s = 'abc, acc, adc, aec, afc, ahc' # 匹配 a开头 中间是c或者f 最后是c 的字符 r= re.findall('a[cf]c',s) print(r) # 匹配 a开头 中间不是c或者f 最后是c 的字符 r= re.findall('a[^cf]c',s) print(r) # 匹配 a开头 中间是cdef中的一个 最后是c 的字符 r= re.findall('a[c-f]c',s) print(r)
# 딕셔너리의 키에 접근하고 값 할당하기 lux = {"health": 490, "mana": 334, "melee": 550, "armor": 18.72} print(lux["mana"]) print(lux["melee"]) lux["health"] = 2037 lux["mana"] = 1184 print(lux) lux["mana_regen"] = 3.28 print(lux)
"""getal2 = 10 getal3 = 0.3353333 data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] text = "Hello" print("getal1: {:.2f} getal2: {}".format(getal3, getal2)) """ karakter = input("geef karakter: ") if karakter.isnumeric(): print("Yep")
""" @Time : 2021/4/615:44 @Auth : 周俊贤 @File :embed_replace.py @DESCRIPTION: """ import os import jieba import numpy as np from gensim.models import KeyedVectors, TfidfModel from gensim.corpora import Dictionary from utils.utils import read_samples, write_samples, isChinese from gensim import matutils from itertools i...
from pytorch_trainer.dataset import convert from pytorch_trainer.training.updaters import StandardUpdater class Updater(StandardUpdater): def update_core(self): iterator = self._iterators["main"] batch = iterator.next() in_arrays = convert._call_converter(self.converter, batch, self.device...
''' Created on 2010. 6. 15. @author: user ''' array = [] for x in range(1000): array.append(True) print all(array) print any(array) array[0] = False print all(array) print any(array) for x in range(1000): array[x] = False print all(array) print any(array)
import os import shutil from .lib import paths_management as paths app_paths = paths.App_Paths() db_path = os.path.join(app_paths.base_script_path, 'web_downloader.db') if os.path.isfile(db_path): os.remove(db_path) if os.path.isdir('web_data'): shutil.rmtree('web_data') if os.path.isdir('firefox_driver'): ...
# EX-3 - Faça um programa que leia 4 notas, mostre as notas e a média na tela # lendo as notas nota1 = float(input('Nota da prova1: ')) nota2 = float(input('Nota da prova2: ')) nota3 = float(input('Nota da prova3: ')) nota4 = float(input('Nota da prova4: ')) print() # imprimindo as notas notas = [nota1, nota2, nota3,...
from ...utils.data_from_config import read_config as read_config_default from ..parcellation import RegionMapper def read_config(fn): from white_matter.utils.paths_in_config import path_local_to_cfg_root ret = read_config_default(fn) relevant_section = ret["ProjectionStrength"] relevant_section["cfg_r...
#!/usr/bin/env python3 import contextlib import string import sys import io import ga from brainfuck import BrainfuckInterpreter from character_set import CharacterSetFromString from utils import generate_random_string, breed_strings from timeout import timelimit, ExecutionError MAX_PROGRAM_LEN = 200 PROGRAM_EXEC_TI...
class TestStateValueObject: def __init__(self) -> None: self.voltage = 0.0 self.cpu = 0.0 self.memory = 0.0 self.disk = 0.0
import os w = os.getcwd()+os.sep+"data.yml" import yaml with open(os.getcwd()+os.sep+"data.yaml","r",encoding="utf8") as f: a = [] data = yaml.safe_load(f) print(data,type(data)) print(w) with open(os.getcwd()+os.sep+"data.yml","w",encoding="utf8") as f: data = {'info': {'name': 'l', 'phone': 's'},...
from abc import * from plugins import tools, resources import random class Deck(object): __major = [] __minor = [] def __init__(self, shuffled=False, lang="jp", imageset=resources.tarot_waite, backimage=resources.tarot_back, keywords=resources.load_keywords()): self.__major = [ ...
import sys def startProgress(title): global progress_x sys.stdout.write(title + ": [" + "-"*20 + "]" + chr(8)*21) sys.stdout.flush() progress_x = 0 def progress(x): global progress_x x = int(x * 20 // 100) sys.stdout.write("▒" * (x - progress_x)) sys.stdout.flush() progress_x = x ...
# Fetch a user using raw SQL, also safe. Users.objects.raw("select * from users where email = %s", [email])
import unittest import sys import io from contextlib import contextmanager from models import * from datetime import datetime from console import HBNBCommand @contextmanager def captured_output(): new_out, new_err = io.StringIO(), io.StringIO() old_out, old_err = sys.stdout, sys.stderr try: sys.st...
class Solution: def fourSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[List[int]] """ nums.sort() ln = len(nums) valueDict = {} ans = [] for i in range(ln): for j in range(i): ...
from django.contrib import admin from .models import Station, Status, Department, FaultDetail, StatusFilter, DepartmentFilter, StationFilter from import_export.admin import ImportExportModelAdmin, ExportMixin from import_export import resources, fields from import_export.formats import base_formats # Register your mode...
# -*- coding: utf-8 -*- """ @Time : 2020/6/27 22:12 @Author : QDY @FileName: 189. 旋转数组.py 给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: [1,2,3,4,5,6,7] 和 k = 3 输出: [5,6,7,1,2,3,4] 解释: 向右旋转 1 步: [7,1,2,3,4,5,6] 向右旋转 2 步: [6,7,1,2,3,4,5] 向右旋转 3 步: [5,6,7,1,2,3,4] 示例 2: 输入...
from test_cases import * class TC1(MainTc): """From client side create a file in a share directory. Condition *(rw, sync)""" logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) logger.addHandler(CustomLogger.console) logger.setLevel(logging.DEBUG) logger.addHandler(CustomLogger....
#!/usr/bin/python3 import math import os import random import re import sys # Complete the miniMaxSum function below. def miniMaxSum(arr): sum = 0 arr_sum = [] for i in arr: arr.remove(i) for j in arr: sum +=j arr_sum.append(sum) return arr_sum if __name__ == '__mai...
from rest_framework import serializers from .models import MyChannel class MyChannelSerializer(serializers.ModelSerializer): class Meta: model = MyChannel fields = ['id', 'user', 'name', 'description', 'subscriberCount', 'videoCount']
# from loader import imdb_gen # from keras.layers import Convolution1D, MaxPooling1D, Dense,Flatten,Dropout,LSTM # from keras.models import Sequential # from preprocess import W2VTransformer # # max_words = None # n_features = 100 # total_docs = 25000 # batch_size = 32 # # train_gen = imdb_gen(data='train',max_words=ma...
from bodies.humanoid import HumanoidBody class OrcishBody(HumanoidBody): uid = "orcish" name = "Orcish"
import sys sys.path.insert(0, "../database") from database_methods import * (conn, cur) = connection("client_data.db") def find_years(): ''' Returns a list of years that clients attended a service ''' lst = [] query = "SELECT DISTINCT Year FROM Client_Attends_Service" cur.execute(query) ...
# Generated by Django 3.2.3 on 2021-05-26 04:13 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('gallery', '0002_alter_photos_date'), ] operations = [ migrations.RenameModel( old_name='Photos', new_name='Pics', ),...
# Resolução do exercício utilizando o while: n = int(input('Digite um número para calcular seu Fatorial: ')) f = 1 # fator nulo de multiplicação é 1 (para uma multiplicação limpa, iniciando em 1). print(f'Calculando {n}! = ', end='') while n > 0: # Essas duas linhas de print servem basicamente para mostrar o ...
import random from .value_strategy import ValueStrategy from .incremental_range_strategy import IncrementalRangeStrategy from .ordered_choice_strategy import OrderedChoiceStrategy from .random_choice_strategy import RandomChoiceStrategy from .random_range_strategy import RandomRangeStrategy class StrategyEvaluationF...
from flask import Flask app = Flask(__name__) from app import routes # IMPORTERAR APP I ROUTES ICH I RUN, KÖR INIT 2 GÅNGER
# arr = list(map(int,input().split())) arr = [-1,2,1] N = len(arr) #n:원소의 개수 cnt = 0 for i in range(1 << N) : #1<<n:부분집합의 개수 0에서 2^n전까지 움직임 SUM = 0 sub = [] for j in range(N): #원소의 수만큼 비트를 비교함 #1개의 부분집합들이 계산됨 if i & (1 << j): #i의 j번째 비트가 1이면 j번째 원소 출력 sub.append(arr[j]) ...
""" A setup script for multi-objective c-2-python related functionalities Abdullah Al-Dujaili, 2016 """ import os from os import system from sys import platform as platform # Define the compilation flags if platform == "darwin": # mac os LDFLAGS = " -fPIC -std=c99 -dynamiclib " else: # other systems tested so f...
#! /usr/bin/python # -*- coding: utf-8 -*- import socket from threading import currentThread, Thread import time sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def getMessage(sock, s): s.send(None) while True: data = sock.recv(1024) # print("接收到了服务器端发送过来的数据:{0}".format(bytes(data).de...
import math def distance_between_two_points(p) : "empty function" c=p.w-p.y d=p.x-p.z c=(c**2)+(d**2) c=math.sqrt(c) return c class point(object) : "representation for points" a=input("enter your number") b=input("enter your number") c=input("enter your number") d=input("enter your number") blank=point() ...
from django.forms import ModelForm from .models import customer, proposal, line_item # Customer form class customerForm(ModelForm): class Meta: model = customer fields = '__all__' # Proposal form class proposalForm(ModelForm): class Meta: model = proposal fields = '__all__' #...
# import numpy as np # import torch # import torch.nn as nn # import torch.optim as optim # import torch.nn.functional as F # import torchvision.transforms as T # def transform_obs(obs): # count_grass = 0 # on_grass = False # w,h = len(obs), 84 # dat = np.zeros((w, h), dtype=int) # for i in range(...
#!/usr/bin/env python import scapy.all as scapy import argparse from scapy_http import http def sniff(interface): scapy.sniff(iface=interface, store=False, prn=process_packet) def get_arguments(): parser = argparse.ArgumentParser() parser.add_argument("-i", "--interface", dest="target", help="Specify inte...
import copy from iocbuilder import Device, AutoSubstitution from iocbuilder.arginfo import * from iocbuilder.modules.asyn import Asyn, AsynPort from iocbuilder.modules.ADCore import ADCore, NDPluginBaseTemplate, includesTemplates, makeTemplateInstance class AdPython(Device): '''Library dependencies for adPython'...
def create_incrementer(num): def inc(val): return num + val return inc inc_5 = create_incrementer(5) print(inc_5(10)) # 15 print(inc_5(0)) # 5 inc_7 = create_incrementer(7) print(inc_7(10)) # 17 print(inc_7(0)) # 7
# Generated by Django 3.1.3 on 2020-11-28 11:44 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('weather', '0041_auto_20201128_1343'), ] operations = [ migrations.AlterField( ...
# # This file contains a Google App Engine library for creating XML-RPC # calls. This allows code which runs on App Engine to utilize the # xmlrpclib package in Python and still conform to the rules set # up by the sandbox within App Engine. # # File downloaded from Brian Clapper's blog at: # # http://brizzled.clapp...
def horzbareq(): print "=======================================================" def horzbardash(): print "-------------------------------------------------------" def write_output_header(fname,casetitle,nlag,nelems): from numpy import * from pycdf import * try: f = CDF(fname, NC.WRITE|NC.CREATE|NC.TRUNC) f....
#!/usr/bin/env python # encoding=utf-8 """Dokumentační řetězec""" # importy # třídy # funkce if __name__ == "__main__": # vstupní bod pass
from instabot import Bot import time import numpy as np def get_new_following(bot, old_following): new_following = bot.get_user_following("barneystinson101101") id_to_send_hi = list() if np.array_equal(np.array(new_following).sort(), np.array(old_following).sort()): return [] else: for...
import requests test_url = 'http://0.0.0.0:5000/request_frame' # response = requests.get('http://0.0.0.0:5000/request_frame') response = requests.post(test_url, data=img_encoded.tostring(), headers=headers) print(response.content)
from prediction import schedule_iterator from prediction import ourKey # -*- coding: utf-8 -*- """ Created on Fri Apr 7 18:02:49 2017 @author: ctoou <---- Romeo """ def schedule_generator( course_list ): # sort course_list with ourKey #this is a small optimization sorted_course_list = ourKey.ourKey(course_li...
def solution(l1, l2): """ add the value of l1 and l2 if they are not null create a new node of the sum and check for carry assign the new node to connect with the list iterate to the next node for curr, l1 , l2 final step to check the carry again if carry > 0, then we need to create a new node for the ...
#!/usr/bin/env python """ mp42hV Yeah, this name is kinda shitty. In case you wonder, it means "mp4 to Hidden Volume". This script aims to produce a hybrid file from a mp4 file and a VeraCrypt volume so that both are still readable. """ import sys import array import shutil import logging # Global variables endiann...
# 아래와 같이 자연수로 구성된 수열 k가 있습니다. # 합이 5인 부분 연속 수열의 개수를 구해보세요. k = [1,2,3,2,5] answer = 0 for i in range(len(k)): temp = k[i] j = i+1 while temp <= 5: if temp < 5: temp += k[j] j += 1 elif temp == 5: answer += 1 break print(answer) # 특정한 합을 가지는 부...
# -*- coding: utf-8 -*- """ Created on Sat Feb 29 21:34:31 2020 @author: Janek """ import matplotlib.pyplot as plt import numpy as np import Gauss from openpyxl import load_workbook t0=0 #chwila początkowa #wartosc poczatkowa fi M=1# 2.435 * 10**18 V0 = 8*10**(-11)*M**4 f0=6 ...
import Tile import A_star import Gridlist import Hard import FourPaths import BlockedCells import StartGoalVertex import Tkinter as tk import random import time class Grid(tk.Frame): def __init__(self, root, rows=120, columns=160, size=32, gridList=[]): self.rows = rows self.columns = columns ...
'''Captura de notas por alumnos''' numero_modulos = int(input('¿Cuántos módulos dais? ')) numero_alumnos = int(input('¿Cuántos alumnos hay en clase? ')) def entrada_notas (): lista_total = [] for i in range (numero_alumnos): lista_alumno = [] for j in range(numero_modulos): ...
from setuptools import setup, find_packages import os version = '1.0b1' setup(name='lt.django.company', version=version, description="A Django CMS model for managing company/contact lists", long_description=open(os.path.join("docs", "README")).read() + "\n" + open(os.path.join...
from parsexml.relation import Relation from parsexml.relationtype import RelationType import numpy as np class Closure: def __init__(self, text_obj, relation_type, transitives_of_transitives=False): """If transitives_of_transitives is True we will calculate all possible transitives. Otherwise it will only ...
""" addreq.py Copyright 2015 Andres Riancho This file is part of w3af, http://w3af.org/ . w3af is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation version 2 of the License. w3af is distributed in the hope that it w...
from bs4 import BeautifulSoup import urllib2 import requests import re,math import os from sklearn.feature_extraction.text import CountVectorizer import codecs from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from collections import Counter #This function crawls the hyperlinks fron the list an...
from django.urls import path, include from .views import ItemListView,ItemDetailView,ItemCreateView,ItemEditView urlpatterns = [ path('items/',ItemListView.as_view()), path('items/<int:pk>/',ItemDetailView.as_view()), path('items/add',ItemCreateView.as_view()), path('items/<int:pk>/edit',ItemEditView...
from django.utils.encoding import force_text from rest_framework.authentication import SessionAuthentication, exceptions from rest_framework import status class CSessionValidationError(exceptions.APIException): status_code = status.HTTP_403_FORBIDDEN def __init__(self, detail): self.detail = detail ...
import pandas as pd from sklearn.base import BaseEstimator, TransformerMixin from bikerentals.src.utils.logging import log_transformation class SameLocationRemover(BaseEstimator, TransformerMixin): """ Mark for deletion those records where bikes were rented from and returned to the same bike station. """...
from django import forms from .models import * class Radish_Form(forms.ModelForm): class Meta: model = Radish fields = ['end','lock','bell'] labels = { 'end': ('언제까지 열어두시나요?'), 'lock': ('비밀번호'), 'bell': ('구조대의 가격은?') } widgets = { ...
# Author: Noah Wilson, wilsonn2018@my.fit.edu # Course: CSE 2050, Fall 2019 # Project: Save """Docstring for Save the Manatee Game""" import argparse from urllib.request import urlopen import pygame from pygame.locals import * COQUINAS = list() HYACINTH = list() CLOSED_GATE = list() OPEN_GATE = list() ...
import tensorflow as tf IMAGE_RESIZE = None def saturate(image): saturation = tf.image.random_saturation(image, lower=0.5, upper=1.5) return saturation def random_hue(image): hue = tf.image.random_hue(image, max_delta=0.2) return hue def random_contrast(image): constrast = tf.image.random_cont...
import discord from discord import Embed from discord.ext.commands import command from discord.ext.commands import Cog from discord.ext.commands import Bot from discord.ext.commands.context import Context
# -*- coding: utf-8 -*- """ Created on Wed Sep 7 14:57:17 2016 @author: efron """ """ A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before. For example, 44 → 32 → 13 → 10 → 1 → 1 85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89 Th...
#!/usr/bin/env python from apiclient.discovery import build import httplib2 import logging from oauth2client.client import flow_from_clientsecrets from oauth2client.file import Storage from oauth2client.tools import run_flow import argparse from oauth2client import tools API_VERSION = 'v1' GCE_URL = 'https://www.goo...
#test def get_one_page(url): response = requests.get(url) if response.status_code == 200: return response.text return None def main(): url = 'https://www.consumeraffairs.com/cosmetics/sephora.html' html = get_one_page(url) print(html) main()
from flask import Blueprint, request, Response import json import app.emprestimos.models as md mod = Blueprint('routes', __name__, url_prefix='/') @mod.route('/emprestimos/', methods=['GET', 'POST', 'DELETE']) def emprestimos(): #requests com content-type = application/json if request.method == 'POST': dados = ...
#!/usr/bin/python # Author @nu11secur1ty import os os.system("apt update -y"); os.system("apt upgrade -y"); os.system("apt dist-upgrade -y"); os.system("apt autoremove -y"); os.system("apt --fix-broken install -y"); os.system("cp /etc/apt/sources.list /etc/apt/sources.list_backup"); # You can edit the country (R) is b...
""" Variables used in the division property propagation of SIMECK2n x_i_0,x_i_1,......x_i_n-1, y_i_0,y_i_1,......y_i_n-1 u_i_0,u_i_1,......u_i_n-1, >>>1 & ->> t_i_0,t_i_1,......t_i_n-1 >>>8 v_i_0,v_i_1,......v_i_n-1, w_i_...
# ch12_4.py def hanoi(n, src, aux, dst): global step ''' 河內塔 ''' if n == 1: # 河內塔終止條件 step += 1 # 紀錄步驟 print('{0:2d} : 移動圓盤 {1} 從 {2} 到 {3}'.format(step, n, src, dst)) else: hanoi(n - 1, src, dst, aux) ...
import numpy as np class AnchorGenerator: @property def class_name(self): raise NotImplementedError @property def num_anchors_per_localization(self): raise NotImplementedError def generate(self, feature_map_size): raise NotImplementedError @property def ndim(self...
#!/usr/bin/python # -*- coding: utf-8 -*- import json """ 构建字典可以忽略 """ with open( "THUOCL.json", "r") as f: typed_words0 = json.load(f) data=[] for type0 in typed_words0: data=data+typed_words0[type0] # print("data",len(data)) with open('dict.txt','w') as f: # f.write("\n".join(data)) for word in data...
""" Code Challenge 1 Write a python code to insert records to a mongo/sqlite/MySQL database named db_University for 10 students with fields like Student_Name, Student_Age, Student_Roll_no, Student_Branch. """ import sqlite3 from pandas import DataFrame conn = sqlite3.connect ( 'student.db' ) c = conn.cursor()...
import logging from itertools import chain from django.contrib.postgres.fields import ArrayField from django.db import models from django.db.models import Q from django.utils.translation import gettext_lazy as _ from edd.fields import VarCharField from main import models as edd_models logger = logging.getLogger(__na...
''' *** input *** n : 외벽 수 weak : 약한 외벽 정보 dist : 친구가 갈 수 있는 *** output *** 써야 할 친구 최솟값 *** 신경쓸 조건 *** 한번 출발하면 방향 못바꿈. 원형 : 끝점까지 가도 처음으로 되돌아오는거랑 또이또이 -> 2배를 늘리는 아이디어. for문 중첩이 3개나 ?! -> 정리를 잘 하고 들어가야겠다. 중간중간 큼지막한 경우의 수를 생각하는 것이 팁. 블로그처럼 (https://yabmoons.tistory.com/552) 문제를 풀기 전 이 부분에 적는 주석을 좀 더 늘려야겠다. ''' from i...
from setuptools import setup, find_packages def readme(): with open('readme.md') as f: return f.read() setup( name = 'sink', version = '1.0.2', description = "Sink is a CLI synchronisation app for Google Drive", long_description = readme(), author = 'Yash Thakre', license = 'MIT',...
import unittest import json from route_tienda import Tienda, TiendaById class Test_Productos(unittest.TestCase): def setUp(self): self.tienda = Tienda() self.tiendaById = TiendaById() def test_Get(self): self.assertTrue(self.tienda.get()) self.assertTrue(self.tiendaById.get(...
"""Simple Flask service.""" import os from flask import (Flask, jsonify, render_template, request, make_response, url_for, redirect) import db app = Flask(__name__) app.config['UPLOAD_FOLDER'] = 'uploads/' @app.route('/') def index(): return render_template('index.html') @app.route('/bu...
"""Executes the 'iris' example lane, and checks if the resulting files match what's expected""" import logging import os import subprocess import sys import warnings from filecmp import cmp from shutil import rmtree from tempfile import mkdtemp from unittest import TestCase import sparklanes from sparklanes import Lan...
import calendar import datetime from django import template from django.conf import settings from ...core.utils import get_annual_item_counts from ..models import Account, Album, Artist, Scrobble, Track register = template.Library() def check_top_kwargs(**kwargs): """ Used to check the supplied kwargs for ...
# -*- coding: utf-8 -*- import time # proj_dir = "/data/py/test/SaaSProj" from os import sys, path import os sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) # 获取祖父路径(../SaaSProj), 把项目根目录加入环境变量 base_path = path.dirname(path.dirname(path.abspath(__file__))) proj_dir = base_path # print(proj_dir) # C:\...
# Generated by Django 3.2.5 on 2021-08-01 07:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myapp', '0001_initial'), ] operations = [ migrations.AlterField( model_name='feature', name='details',...
import sys import pymod.mc import pymod.modes import pymod.module import pymod.callback import pymod.modulepath from pymod.error import ModuleNotFoundError def show(name, opts=None, insert_at=None, mode="load"): """Show the commands that would result from loading module given by `name` Parameters -------...
import matplotlib.pyplot as plt import numpy as np def ps29_q7(): x = np.linspace(-5, 5, 1000000) y1 = lambda x: np.sqrt(x) y2 = lambda x: 0.25 * x + 1 fig = plt.figure(figsize=(12, 8)) ax = fig.add_subplot(1, 1, 1) ax.plot(x, y1(x)) ax.plot(x, y2(x)) plt.show() zero_lst = [] ...
class Node(object): def __init__(self, data=None, link=None): self.data = data self.link = link def __repr__(self): return repr(self.data) class Sllist: def __init__(self): self.head = None def __repr__(self): nodes = list() curr = self.head while curr: nodes.append(repr(curr)) curr = curr.li...
""" Task Given an integer, n, perform the following conditional actions: If n is odd, print Weird If n is even and in the inclusive range of 2 to 5, print Not Weird If n is even and in the inclusive range of 6 to 20, print Weird If n is even and greater than 20, print Not Weird Input Format A single line containing a...
""" Classes for connecting to Twitter """ import auth.oauth class TwitterOAuth(auth.oauth.OAuth): """ Provides Twitter's get_uid function. """ def get_uid(self, request, **kwargs): if hasattr(request, 'args'): return request.args.get('screen_name') elif hasattr(request, 'co...
import logging import os import yaml_config as yc from pavilion import arguments from pavilion import plugins from pavilion import result_parsers from pavilion.unittest import PavTestCase LOGGER = logging.getLogger(__name__) class ResultParserTests(PavTestCase): def setUp(self): # This has to run befor...
#imports import pyautogui import time import keyboard ################################################################ #vars IsPressed = False sleep = time.sleep ################################################################ #configs print("Made By Cody666#5618, v1.0.3") print("Enter Amount Of Clicks:") k...
import numpy as np import random import torch from collections import deque, namedtuple device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') class ReplayBuffer: '''Replay buffer to store experience tuples''' def __init__(self, n_action, buffer_size, batch_size, seed=0): ...
# -*- coding: utf-8 -*- import json from SPARQLWrapper import SPARQLWrapper, JSON ''' sparql = SPARQLWrapper("http://dbpedia.org/sparql") sparql.setTimeout(600) sparql.setQuery(""" PREFIX cat: <http://dbpedia.org/resource/Category:> PREFIX dcterms: <http://purl.org/dc/terms/> PRE...
""" Simple U-Net implementation in TensorFlow Credit: https://github.com/kkweon/UNet-in-Tensorflow Objective: detect vehicles y = f(X) X: image (640, 960, 3) y: mask (640, 960, 1) - binary image - background is masked 0 - vehicle is masked 255 Loss function: maximize IOU (intersection of prediction &...
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: d = {} for letter in magazine: if letter not in d: d[letter] = 1 else: d[letter] +=1 for char in ransomNote: if...
from flask import render_template, jsonify, request, redirect, url_for, session from app import app, functions, models import json import pprint as pp @app.route('/', methods=['GET']) @app.route('/index', methods=['GET']) def index(): return render_template('index.html', title='Lanches', lanches=functions.get_all_to...
import graphene from graphene_django.types import DjangoObjectType from ..node import DjangoNode from ...character.models import Character, Favorite class CharacterType(DjangoObjectType): """ Character Object Type Definition """ thumb_url = graphene.String() class Meta: model = Characte...
from py2neo import Graph, Node, Relationship from py2neo.batch import WriteBatch import datanommer.models as m graph_uri = "http://localhost:8182/db/data" class GraphFeed(object): def __init__(self): # m.init(uri= 'postgresql://datanommer:datanommer@localhost/datanommer') m.init('postgresql+psy...
import unittest, sys from ZODB.fsIndex import fsIndex from ZODB.utils import p64 class Test(unittest.TestCase): def testInserts(self): index=fsIndex() for i in range(200): index[p64(i*1000)]=(i*1000L+1) for i in range(0,200): self.assertEqual((i,index[p64(i*1000)...