text stringlengths 38 1.54M |
|---|
import math
from tkinter import *
from tkinter import messagebox
screen =Tk()
screen.title('myclaculator')
screen.maxsize(width=450,height=450)
screen.minsize(width=365,height=450)
screen.configure(bg='blue')
def click(number):
global operator
operator+=str(number)
tex.set(operator)
def clean(... |
#!/usr/bin/env python3
""" function to add two arrays elements-wise"""
def add_arrays(arr1, arr2):
""" adding two arrays element wise
Args:
arr1, arr2: Given arrays
Return:
the sum of arrays: new matrix
"""
if len(arr1) != len(arr2):
return None
else:
return [su... |
#Script Require to edit proxychains config file
dirs = input('Input Directory of ip/port list')
try:
ip = open('{}/ip.txt'.format(dirs))
port = open('{}/ports.txt'.format(dirs))
f = open('/etc/proxychains.conf','a')
ipl = ip.readlines()
portl = port.readlines()
except Exception as e:
print(e)
ips = []
ports = []
... |
import mqtt_remote_method_calls as com
import robot_controller as robo
import ev3dev.ev3 as ev3
import time
""""This is the Ev3 portion of the final project"""
""""These are the list of imports that allow mqtt communication,
robot control, ev3 access, and time."""
class MyDelegate(object):
""""The MyDelegate cl... |
import main
def do_a_trick():
print('here\'s magic trick')
def list_compreshension():
#naive way to create 0 to 9 array
ar = []
for i in range(10):
ar.append(i)
print(ar)
# brackes mean its an array
# theres a for loop inside.
# the i on the outside is what you are putting int... |
"""
======================COPYRIGHT/LICENSE START==========================
BackupProject.py: Part of the CcpNmr Analysis program
Copyright (C) 2003-2010 Wayne Boucher and Tim Stevens (University of Cambridge)
=======================================================================
The CCPN license can be found in ... |
#!/usr/bin/env python3
a0,a1,a2=input().strip().split(' ')
a0,a1,a2=int(a0),int(a1),int(a2)
b0,b1,b2=input().strip().split(' ')
b0,b1,b2=int(b0),int(b1),int(b2)
a,b=0,0
if a0<b0:
b+=1
elif a0>b0:
a+=1
else:
pass
if a1<b1:
b+=1
elif a1>b1:
a+=1
else:
pass
if a2<b2:
b+=1
elif a2>b2:
a+=1... |
"""
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
NOTE: Do not count spaces or hyphens. For example, 342 (th... |
#!/Users/thedrub/anaconda3/bin/python
# ----------------------------------------------------------------------
# Libraries
# ----------------------------------------------------------------------
import pandas as pd
import sys
import csv
import os
from optparse import OptionParser
from pathlib import Path
# ---------... |
H,W = map(int,input().split())
print("#" * (W + 2))
for _ in range(H):
a = input()
print("#"+a+"#")
print("#" * (W + 2))
|
"""
This is the most preferable method to work with file
'with' keyword is used in this system
no need to use finally step as because 'with' helps to close file automatically.
"""
with open('02.new_method.txt', 'w') as file:
file.write('New file method introduced.')
with open('02.new_method.txt', 'a', encod... |
#initializing the dictionary
dic = {'first':[2,1],'second':[2,3],'third':[3,4]}
#a
temp = dic['first']
dic['first'] = dic['third']
dic['third'] = temp
#b
dic['third'].sort()
#c
dic['fourth'] = dic['second']
#d
dic.pop('second')
print dic |
x="MISSISSIPPI"
list1=list(x)
list2=[]
dic={}
for i in range(len(list1)):
if list1[i] not in list2:
list2.append(list1[i])
for j in range (len(list2)):
count=0
for j in range(len(list1)):
if list2[i]==list1[j]:
count=count+1
dic[list2[i]]=count
print(dic) |
#
# StageController.py
# EyeTrackerStageDriver
#
# Created by David Cox on 5/25/08.
# Copyright (c) 2008 __MyCompanyName__. All rights reserved.
#
from Foundation import *
from AppKit import *
import objc
from objc import IBAction, IBOutlet
import time
import httplib
from TrackerMeasurementController import *
fr... |
import unittest
from solution9 import *
class MyTest(unittest.TestCase):
def test_block_equal_to_n(self):
self.assertEqual(pad_to("YELLOW SUBMARINE", 16), ['YELLOW SUBMARINE'])
# FIXME: Fix failing tests, looks like they are returning other test results
# def test_block_less_than_n(self):
# ... |
import tensorflow as tf
import numpy as np
from pysc2.lib import actions
import common.utils as U
class Py_A2C:
def __init__(self, msize, ssize, lr, feature_transform, model, regular_str, minibatch, epoch, isa2c=False, training=True):
self.lr = lr
self.model = model
self.reg_str = regula... |
import pickle, random
t = open("test.info", "wb")
t.truncate(0)
dic = {}
for x in range(0, 10):
randomnum = random.randint(0, 100)
print(randomnum)
dic[randomnum] = bool(input("1/0 big "))
pickle.dump(dic, t)
t.close()
|
# Chapter 7: Requesting and Retrieving Information
# Recipe 2: Searching text with a FindReplaceDialog
#
import wx
import fileEditor as FE # previous recipe module
# extend the art map
FE.ArtMap[wx.ID_FIND] = wx.ART_FIND
FE.ArtMap[wx.ID_REPLACE] = wx.ART_FIND_AND_REPLACE
class TextEditorWithFind(FE.FileEdit... |
import pandas as pd
import requests as req
import json
import os
from datetime import datetime
from google.cloud import storage
from google.cloud import bigquery
api_key = 'ESTE NO SE COMPARTE'
PROJECT_ID = "chemackana-project"
BUCKET_NAME = "face_recog_bd"
REGION = "us-central1"
url = "https://api.polygon.io/v1/hist... |
# -*- coding: utf-8 -*-
from .cve import async_cve_update, async_cve_update_status
from .scan import start_scan_all_devices_async, scan_all_devices_async_status
from .analysis import async_analysis_start, async_analysis_status
|
import json
import os
import numpy as np
import csv
import cv2
from tqdm import tqdm
datasets = ['./adas/route1', './adas/route2', './adas/route3', './adas/route4', './adas/route5', './adas/route6', './adas/route7', './adas/route8']
seg_anns = []
classes = [
"parking_side",
"parking_marked"
]
for da... |
import boto3
import json
import datetime
import smart_open
import pymysql.cursors
import uuid
def lambda_handler(event, context):
# TODO implement
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}
def get_activity_level(json_object):
return "LOW"
def write_to_database(json_object):
json_... |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 22 11:33:18 2021
@author: darsh
"""
import openslide
import numpy as np
from getMaskFromXml import getMaskFromXml
from skimage.transform import rescale,resize
import os
from skimage.measure import label,regionprops
import cv2
import matplotlib.pyplot as plt
... |
import numpy as np
import scipy.stats as ss
import statsmodels.api as sm
import pandas as pd
import matplotlib.pyplot as plt
class Heston_process():
"""
Class for the Heston process:
r = risk free constant rate
rho = correlation between stock noise and variance noise
theta = long term mean of the ... |
from flask import Flask, render_template, jsonify, request
from pymongo import MongoClient # pymongo를 임포트 하기(패키지 인스톨 먼저 해야겠죠?)
import requests
from bs4 import BeautifulSoup
app = Flask(__name__)
client = MongoClient('localhost', 27017) # mongoDB는 27017 포트로 돌아갑니다.
db = client.baking # 'dbsparta'라는 이름의 db를 만듭니다.... |
"""Abstract model of a representation the monster group
Let R_p be the 196884-dimensional representation 196884x of the monster
group modulo a small odd number p as described in [Seys19]. Class
AbstractMmRepSpace is an abstract class for modelling representation
R_p. A small odd modulus p < 256 is passed to the const... |
import numpy as np
import pdb
def im2col(X, pad, patchH, patchW):
assert patchH==patchW
assert 1==(patchH%2)
assert 1==(patchW%2)
X_pad = np.pad(X, ((0,0),(0,0),(pad,pad),(pad,pad)), 'constant') # batch,channel,height,width
batch,chn,height,width = X_pad.shape
outH = height - patchH + 1
o... |
from BibliotekaV1 import BibliotekaV1
from BibliotekaV2 import BibliotekaV2
from Okrag import Okrag
from Prostokat import Prostokat
BG1 = BibliotekaV1()
BG2 = BibliotekaV2()
okrag = Okrag(BG1)
okrag2 = Okrag(BG2)
prostokat = Prostokat(BG1)
prostokat2 = Prostokat(BG2)
print('Rysuje okrag:')
okrag.rysuj()
print('\nRys... |
from numpy import*
glicose=array(eval(input("digite o numero:")))
a=0
i=0
while(i<size(glicose)):
if(glicose[i]>99):
print(i)
a=a+1
else:
a=a+0
i=i+1
print(a)
|
#lambda expression
mynums2 = [1,2,3,4,5,6,7,8]
square2 = lambda num: num ** 2
lambdaList = list(map(lambda num:num**2, mynums2))
print(lambdaList)
#filter
mynums = [1,2,3,4,5,6,7,8]
def check_even(num):
return num % 2 == 0
filtered = filter(check_even, mynums)
print(filtered)
# map
def square(num):
return... |
import sys
import socket
import select
import binascii
from p2p import parseReceivedMessage, createMessage
MSG_PING = 0x00
MSG_PONG = 0x01
MSG_BYE = 0x02
MSG_JOIN = 0x03
MSG_QUERY = 0x80
MSG_QHIT = 0x81
# =============================================================================
# Simple console program that make... |
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
import LatticeDefinitions as ld
import GeometryFunctions as gf
import GeneralLattice as gl
import LAMMPSDump as LD
from scipy import stats
import os
strPMFile = 'data/60and30.eamPM... |
import pandas as pd
import argparse
import sys
def convert_data(file, output_format):
input_format = file.split('.')[-1]
if input_format == 'csv':
data = pd.read_csv(file)
elif input_format == 'tsv':
data = pd.read_csv(file, sep = '\t')
elif input_format == 'json':
data = pd.read_json(file, orient = 'recor... |
from django.db import models
from django.contrib.auth.models import User
from SellerUI.models import *
from BrokerUI.models import *
# Create your models here.
class VehiclesBought(models.Model):
buyer = models.ForeignKey('BrokerUI.Profile', on_delete = models.CASCADE)
vehicle = models.ForeignKey('SellerUI.Ve... |
#---------GRADING GUI---------#
import os
from tkinter import *
import tkinter.messagebox as msgbox
import tkinter.simpledialog as sd
#---List Init--#
#--Entry Boxes--#
section_entry=[]
lab_entry=[]
score_entry=[]
comment_entry=[]
check_box=[]
check_box_var=[]
#---Functions--#
def sub_input():
# Initialization
... |
import pandas as pd
import numpy as np
from keras import models
from sklearn.preprocessing import StandardScaler
from keras import optimizers
from keras import layers
df = pd.read_csv('data/data_adult_clean_1.csv')
x_train = df.iloc[:,:7].join(df.iloc[:,8:])
y_train = df.iloc[:,7]
x_test = x_train.iloc[20000:,:]
... |
#!/usr/bin/env python3
from charms.reactive import when, when_not, set_flag, endpoint_from_name
from charms import layer
@when_not("charm.status.is-set")
def set_status():
layer.status.active("")
set_flag("charm.status.is-set")
@when("endpoint.lb-consumers.requests_changed")
def get_lb():
layer.status.... |
import tft_ir_api as IR
gid = 0
x = IR.RealVE("x", gid, 0.01, 100.0)
gid += 1
y = IR.RealVE("y", gid, 0.01, 100.0)
gid += 1
x2 = IR.BE("*", gid, x, x)
gid += 1
y2 = IR.BE("*", gid, y, y)
gid += 1
x2y2 = IR.BE("+", gid, x2, y2)
gid += 1
sqrt_x2y2 = IR.UE("sqrt", gid, x2y2)
gid += 1
sqrt_x = IR.BE("+", gid, sqr... |
from PyObjCTools.TestSupport import TestCase
import Quartz
class TestPDFActionResetForm(TestCase):
def testMethods(self):
self.assertResultIsBOOL(Quartz.PDFActionResetForm.fieldsIncludedAreCleared)
self.assertArgIsBOOL(Quartz.PDFActionResetForm.setFieldsIncludedAreCleared_, 0)
|
# Copyright 2018 The Google AI Language Team Authors and
# The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. 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 Lice... |
# coding: utf-8
'''This is the main module the core of dotapatch.'''
from __future__ import print_function, absolute_import
import os.path as path
from collections import defaultdict
from logging import getLogger as get_logger
from dotapatch.model import Html
from dotapatch.data import HeropediaData
ERROR = -1
SUCCES... |
'''This example demonstrates the use of Convolution1D for text classification.
Gets to 0.89 test accuracy after 2 epochs.
90s/epoch on Intel i5 2.4Ghz CPU.
10s/epoch on Tesla K40 GPU.
'''
from __future__ import print_function
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.laye... |
from django.db import models
class productoModelo(models.Model):
codigo = models.IntegerField(primary_key=True)
nombre = models.CharField(max_length=50)
detalle = models.CharField(max_length=50)
precio = models.IntegerField()
fecha_ingreso = models.DateField()
stock = models.IntegerField()
def... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class ClassProp(object):
def __init__(self, decl):
self.tp = decl[0].replace("*", "_ptr")
self.name = decl[1]
self.readonly = True
if "/RW" in decl[3]:
self.readonly = False
|
#!/usr/bin/python
from color import *
from netaddr import EUI
from scapy.all import *
from dnslib import DNSRecord # for mdns/bonjour name parsing
from django.utils import timezone
from django.core.exceptions import *
from datetime import datetime #for utcfromtimestamp
from iSniff_GPS.models import Client, AP, Locat... |
#052.py
a = [3, 5, 2, 1, 4]
b = [8, 10, 7, 6, 9]
print("sorted(a)")
print(sorted(a))
print("a")
print(a)
print("")
b.sort()
print("b.sort()")
print(b)
|
# Greatest Common Divisor
# Problem Description
# Given 2 non negative integers A and B, find gcd(A, B) GCD of 2 integers A and B is defined as
# the greatest integer g such that g is a divisor of both A and B. Both A and B fit in a 32 bit
# signed integer. Note: DO NOT USE LIBRARY FUNCTIONS.
# Problem Constraints
#... |
import requests
import time
from cache import Cache
BASE_URL = 'https://api.discogs.com'
class DiscogsClient:
def __init__(self, user_agent, key, secret):
self.session = requests.Session()
self.session.headers.update(
{
'User-Agent': f'{user_agent}',
... |
import MySQLdb
from setting import hostData, userData, passData, dbData
class post(object):
def __init__(self, naglowek, data, zawartosc):
self.data=data
self.naglowek=naglowek
self.zawartosc=zawartosc
def getInformationPosts():
db = MySQLdb.connect(host=hostData, user=userData, passwd... |
from PIL import Image
import os
path = './images/'
import shutil
if not os.path.exists('./deleted'):
os.makedirs('./deleted')
print(len(os.listdir(path)))
counter = 0
with open('delete.txt', 'w+') as f:
for file in os.listdir(path):
extension = file.split('.')[-1]
if extens... |
import collections
import sqlite3
class SqliteSerializable:
def __conform__(self, protocol):
if protocol is sqlite3.PrepareProtocol:
return ';'.join(str(i) for i in self)
class Point(collections.namedtuple('Point', 'x y'), SqliteSerializable):
pass
con = sqlite3.connect(":memory:")
cur = con.cursor()
p = Poi... |
# import os
# from celery import Celery
# import requests,json
# import time
# import baostock as bs
# import pandas as pd
# from cpblog.extensions import db
# from cpblog.models import QuantPost
# CELERY_BROKER_URL = 'redis://:'+os.getenv('redis_password')+'@127.0.0.1:6379/0'
# CELERY_RESULT_BACKEND = 'redis://:'+o... |
#3
import socket
def find_service(port_no,protocol_name):
service_name = socket.getservbyport(port_no,protocol_name);
print("service name:",service_name)
n = int(input("Enter port no\n"))
s = input("Enter protocol name\n")
find_service(n,s)
|
class MyCockTailSort:
def __init__(self, input_array):
self.array = input_array
def cock_tail_sort(self):
for i in range(len(self.array)-1):
is_sorted = True
for j in range(i, len(self.array)-i-1):
if self.array[j] > self.array[j+1]:
... |
"""
Created by PyCharm
~~~~~~~~~~~
:author: ilhamarrouf
:date: 18/04/20
:time: 08.29
"""
from app import app
from app.jobs import example_job
from app.utils.response import respond_json
from flask import Blueprint, request, url_for
mod = Blueprint("homepage_controller", __name__)
@mod.route("/",... |
import sys
import time
import timeit
import numpy as np
import pandas as pd
from pybuga.tests.utils.test_helpers import Tee
# https://stackoverflow.com/a/24812460/365408
# set timeit to return the value
from pybuga.tests.utils.test_helpers import Tee
def _template_func(setup, func):
"""Create a timer function. ... |
"""
@COMPANY WHALE
@AUTHOR ChenZhou
@DESC This is the realization of Geographical Info Extractor using AMap API.
@DATE 2019/09
"""
import geo_extractor as ge
import poi_searcher as ps
import file_reader as fr
import logging
from string import digits
logging.basicConfig(format='%(asctime)s-[%(levelname)s]: %(message)s... |
#!/usr/bin/env python3
import time
import asyncio
import sys
import random
from telethon import TelegramClient, events, utils, Button
api_id = 1529569
api_hash = '4a079214fc8f272f6d82fa70b4fc983f'
sesi_file = 'malingvio'
hasil = '/homesx'
bot = 'KampungMaifamX4Bot' #bot mepam yang digunakan
wit... |
# SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD
# SPDX-License-Identifier: Unlicense OR CC0-1.0
import http.server
import multiprocessing
import os
import socket
import ssl
from typing import Callable
import pexpect
import pytest
from pytest_embedded import Dut
from RangeHTTPServer import RangeReque... |
# coding=utf-8
from tkinter import *
class InputForm():
def __init__(self):
self.main_form = Tk()
self.main_form.title('你好')
self.main_form.geometry('800x600+600+600')
self.frame1 = Frame(self.main_form)
self.frame1.pack(fill=X)
Label(self.frame1, text="这是一个无聊的问题").... |
from __future__ import print_function
import cx_Oracle
import sampleenv
import urllib
import urllib.request
import json
import uuid
def insertrows(insertlist):
#print('start insert-----')
connection = cx_Oracle.connect(sampleenv.INSERT_MAIN_STRING)
cursor = connection.cursor()
try:
cursor.exe... |
import math
from typing import TYPE_CHECKING
class Ponto2D:
def __init__(self,x=0.0, y=0.0):
self.x = x
self.y = y
class Retangulo:
def __init__(self,esq_sup, dir_inf):
self.__esq_sup = esq_sup
self.__dir_inf = dir_inf
def calcularArea(s... |
from matplotlib.pylab import *
import numpy as np
y = np.array([0.5,2.0,1.0,1.5,7.5])
x = np.arange(0,5)
e = np.zeros(len(y))
def error_calc(a,b,x,y):
error = 0
for i in range(0,len(y)):
e[i] = (a*x[i] + b - y[i]) ** 2
error += e[i]
return error
#print(error_calc(a,b,x,y))
def optimize(x,y):
... |
from . import admin_views as VW
from django.urls import path
urlpatterns = [
path('authenticate', VW.Authentication.as_view(), name = 'authenticate'),
]
#path('', VW.test, name = 'test'), |
import re
# r="helloo3"
# x="\w{6}"
# match=re.fullmatch(x,r)
# if match is not None:
# print("valid")
# else:
# print("invalid")
r="56kg"
x="\d{2}[kg]"
match=re.fullmatch(x,r)
if match is not None:
print("valid")
else:
print("invalid")
|
import numpy as np
from scipy.stats import ttest_ind, pearsonr
from sklearn.model_selection import StratifiedKFold
class CounterbalancedStratifiedSplit(object):
def __init__(self, X, y, c, n_splits=5,
c_type='categorical', metric='corr', use_pval=False,
threshold=0.05, verbose=F... |
delim='&'
a=open(raw_input('infile: '))
cols=int(raw_input('cols: '))
rows=int(raw_input('rows: '))
dump=[]
for line in a:
dump.append(line[:-1])
a.close()
d=len(dump)
num=int(d/(cols*rows))+1
got=False
s=0
for n in range(num):
print ''
for i in range(rows):
st=''
for j in range(cols):
... |
class Application:
### Constructor from application class
def __init__(self):
self.appid = 0
self.name = ''
self.type = 'BATCH'
self.image = ''
self.min_memory = -1
self.num_cores = 1
self.comments = ''
### Function to verify an equality of two applicati... |
# Tabla.py
# Autor: Eilen Estefania Esquivel Camacho
# Fecha de creación: 16/09/2019
# La función input() permite obtener texto escrito por teclado.
# Al llegar a la función,
# el programa se detiene esperando que se escriba algo y se pulse la tecla Intro.
# Convertir a entero la funcion int () a un número.
# Es un... |
import asyncio
from dffml import Definition, DataFlow, Input, op
from dffml.noasync import run
OBJ = Definition(name="obj", primitive="mapping")
LOCKED_OBJ = Definition(name="locked_obj", primitive="mapping", lock=True)
SLEEP_TIME = Definition(name="sleep_time", primitive="int")
INTEGER = Definition(name="integer", pr... |
from collections import defaultdict
N, K = (int(x) for x in input().split())
A = list(int(x) for x in input().split())
acc = [0]
for a in A:
acc.append(acc[-1]+a)
cnt = defaultdict(int)
ans = 0
for i in range(N, -1, -1):
ans += cnt[acc[i] + K]
cnt[acc[i]] += 1
print(ans) |
import matplotlib.pyplot as plt
import numpy as np
path = "../data/proto1/"
file = "means.csv"
means = np.loadtxt(path + file)
print(means)
plt.subplot()
plt.plot(means)
plt.show()
|
from datetime import timedelta, date
def daterange(start_date, end_date):
for n in range(int ((end_date - start_date).days)):
yield start_date + timedelta(n)
def daterange_day(start_date, days):
for n in range(int (days)):
yield start_date + timedelta(n)
#TODO: Either leave as is or add to ru... |
# implement an algorithm to determine if a string has all unique characters.
# brute force is you loop over all combos and see if there are any duplicates
#
# hash map is very useful here - you just add every element in and if you see a duplicate you return false: O(n)
#
# What if you cannot use additional data structu... |
# -*- coding: utf-8 -*-
import sqlite3
# Conexión y cursor a la base de datos
conn = sqlite3.connect(':memory:')
cursor = conn.cursor()
# Creo la tabla
cursor.execute("""CREATE TABLE currency
(ID integer primary key, name text, symbol text)""")
# Inserto datos de monedas
cursor.execute("INSERT INTO currency VALUES ... |
import os
import numpy as np
import pandas as pd
from PIL import Image
import matplotlib.pyplot as plt
import cv2
from keras.applications.resnet50 import ResNet50
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D, Flatten, Conv2D, Dropout
from keras.layers.core import Dense, Dropo... |
from datetime import datetime, timedelta
from scripto import db
from scripto import Script
if __name__ == '__main__':
pastTime=datetime.strptime(datetime.strftime(datetime.utcnow()-timedelta(hours=2), "%Y-%m-%d %H:%M:%S"),"%Y-%m-%d %H:%M:%S")
futurTime=datetime.strptime(datetime.strftime(datetime.utcnow()+time... |
# basic screen settings
screen_size = (1280, 650)
background_image = 'white.png'
background_size = None
piano_image = 'piano.png'
piano_size = None
message_color = (0, 0, 0, 255)
fonts_size = 23
label1_place = (300, 400)
label2_place = 300, 350
label3_place = 300, 450
label_anchor_x = 'left'
label_anchor_y = 'center'
... |
import sys
sys.path.insert(0, 'lib')
import numpy as np
import tensorflow as tf
from proposal_layer_tf import proposal_layer_tf
test_file = 'proposal_layer_test/test1'
npz_file = np.load(test_file + '_input.npz')
rpn_cls_prob, rpn_bbox_pred, im_info, cfg_key, anchors, num_anchors = \
npz_file['rpn_cls_prob'], ... |
import netCDF4 as nc
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.metrics import mean_squared_error
import xgboost
from sklearn.ensemble import RandomForestRegressor
import pickle as pk
def ... |
from django.urls import path
from .views import *
urlpatterns = [
path('', index, name='post_index'),
path('post/<int:post_id>/', detail, name='post_detail'),
path('post/new', new, name='post_new'),
path('post/<int:post_id>/edit/', edit, name='post_edit'),
path('post/<int:post_id>/delete/', delete,... |
#Embedded file name: evecamera\dungeonhack.py
"""
Why is this here?
A long time a go in a galaxy not all that far away someone decided that navigation, grid setup and things like accessing
the dungeon editor ui scene should reside in the inflight camera service.
Because you know... why not?
...
BECAUSE ITS A HORRIB... |
def add():
while True:
user=str(input("Enter the username:"))
flag = False
while True:
flag = True
if user in userpassword:
print("Please enter the user already exists and Change this user password\n")
oldpassword=str(input("Ple... |
# Generated by Django 2.1.7 on 2019-03-19 21:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('articles', '0003_auto_20190319_1805'),
]
operations = [
migrations.AddField(
model_name='article',
name='top',
... |
import wandb
from stable_baselines3.common.callbacks import BaseCallback
import plotly.graph_objects as go
from wandb.trigger import reset
class WandBCallback(BaseCallback):
def __init__(self, verbose: int=True, frequency=1000, ignore=["train/n_updates"], mode="online", name="", resume=False):
super().__i... |
from selenium.webdriver.common.by import By
from Pages.BasePage import BasePage
from Pages.WebTablePage import WebTablePage
class RegisterPage(BasePage):
def __init__(self, driver):
super().__init__(driver)
self.pageMethods.ValidateTitlePage("Register")
#declaram webelementele
__firstNa... |
"""
import time
def tiemr(func): #装饰功能的函数
def dome(*args,**kwargs):
start_time = time.time()
func(*args,**kwargs)
stop_time = time.time()
ks = stop_time-start_time
print('time:',ks) #print('time%s'%(stop-start))
return dome
@tiemr
def bar():
time.sleep(3)
prin... |
from pyspark.sql import SparkSession
from pyspark.sql import functions as func
spark = SparkSession.builder.appName("SparkSQL").getOrCreate()
people = spark.read \
.option("header", "true") \
.option("inferSchema", "true") \
.csv("files/fakefriends-header.csv")
result = people \
.groupBy('age') \
... |
# Python3 模拟,字典统计每个字符个数,使用栈进行保存结果
from collections import Counter
class Solution:
def removeDuplicateLetters(self, s: str) -> str:
dic = Counter(s)
stack = [s[0]]
dic[s[0]] -= 1
for i in range(1, len(s)):
while stack and stack[-1] > s[i] and dic[stack[-1]] > 0 and s[i] ... |
from timeit import Timer
time1 = Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
time2 = Timer('a,b = b,a', 'a=1; b=2').timeit()
print(time1)
# 0.020502762
print(time2)
# 0.018866841999999995 |
import psycopg2
import os
import sys
import subprocess
import time
operation_type = sys.argv[1].lower()
test_query = ""
csv_rows = sys.argv[2]
table_name = "key_" + csv_rows
if operation_type == "sort":
test_query = "SELECT * FROM " + table_name + " ORDER BY c1"
elif operation_type == "hash":
test_query = "SE... |
# Author: Denys Makogon
#
# 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 t... |
"""
"""
import os
from analyzer.utilities.check_env import check_env
#FIXME: add prepare_pkg()
def install_module(module_name):
"""
"""
check_env()
archive_dir = module_name + "_module_source"
cd_cache_dir = os.getenv('ROOT_PKG_CACHE') + "/" + module_name
os.chdir(cd_cache_dir)
if cd_cache... |
# --coding:utf-8--
from django.urls import path
from . import views
app_name = 'stockapp'
urlpatterns = [
path('stocks/<stock_id>/', views.StockView.as_view(), name='stocks'),
path('goods/<wd>/', views.GoodsView.as_view(), name='goods'),
path('query/<wd>/',views.QueryView.as_view(),name='query')
] |
#!/usr/bin/env python3
'''
Print the serial output of the CC430 MCU.
last update: 2018-09-24
author: rdaforno
'''
import serial
import sys
import time
import os.path
import serial
import serial.tools.list_ports
from serial.serialutil import SerialException
baudRate = 115200
def getFirstPort(printPorts):
... |
class Actions:
'''Have to figure out a way where everytime a method
in this class is called, it goes out and gets the
current df and portfolo
'''
def _test(self):
print(self.todays_df())
def _check_valid_buy(self, symbol, quantity):
pass
def _check_valid_sell(self, symbol,... |
from django.db import models
from django.contrib.auth.models import User
from cadastro.models import Anuncio
class NumeroDaSorte(models.Model):
numero_escolhido = models.IntegerField()
anuncio_escolhido = models.ForeignKey(Anuncio, on_delete=models.CASCADE)
comprador = models.ForeignKey(
User, on_... |
from django.db import models
from django.contrib.auth.models import AbstractUser, PermissionsMixin
from django.conf import settings
from django.core.validators import MaxValueValidator, MinValueValidator
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
from django.contrib.auth import get... |
jsonRequest = {
'name' : 'MyProject',
'description': 'Something'
}
request = HttpRequest(jsonRequest)
sendRequest("http://127.0.0.1:8000/api/project/", request)
|
# -*- coding: utf-8 -*-
# Computadora elige número aleatorio entre 0 y 100
# Pregunta al usuario por un número
# Si el número es igual, el juego termina
# El usuario tiene 5 intentos
import random
elegido = random.randint(0, 10)
intentos = 15
numero_usuario = ''
# undefined
# print(elegido)
while intentos > 0 and n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.