text stringlengths 8 6.05M |
|---|
# Generated by Django 2.2 on 2020-12-16 02:50
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('coffee_app', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='... |
#!usr/bin/env python
# -*- coding: utf-8 -*-
# *******************************************************
# @File: upload
# @Auth: winver9@gmail.com
# @Create: 2019-2-26 14:47
# @License: © Copyright 2019, LBlog Programs.
# *******************************************************
from django.core.exceptions impo... |
# Generated by Django 2.2.6 on 2019-10-23 18:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('contest', '0009_auto_20191012_2255'),
]
operations = [
migrations.AddField(
model_name='score',
name='minutes',
... |
#Array reversa in Place O(n)
def array_reversal(a):
N=len(a)
if(N%2==0):
mid=N/2
for i in range(0,mid):
temp=a[i]
a[i]=a[N-1-i]
a[N-1-i]=temp
elif(N%2==1):
mid=(N+1)/2
for i in range(0, mid):
temp = a[i]
... |
# Exercício 8.11 - Livro
def valida_string(string, minimo, maximo):
string_length = len(string)
if string_length < minimo or string_length > maximo:
return False
else:
return True
res = valida_string('Eu', 1, 5)
print(res)
|
n = int(input("Input integer"))
d = dict()
for x in range(1,n+1):
d[x] = x*x
print(d)
|
import numpy as np
import math
from matplotlib import pyplot as plt
# Parametros de la senal de interes
fo = 1000. # es una frecuencia fundamental
k = 4
f = k*fo # es la frecuencia de la senoidal
N = 32
# Las senales discretas
n = np.linspace(0,N-1,N)
signal = np.cos(2.*math.pi*k*n/N)
signal2 = np.exp(1.j*2.*math.pi*k... |
#!/usr/bin/env python
# coding: utf-8
# script to test the read speed of two competing methods for reading candidates:
# 1) pre-saved images (resampled)
# 2) resample on-the-fly
# imports
import SimpleITK as sitk
import numpy as np
import csv
import os
from PIL import Image
import matplotlib.pyplot as plt
import scip... |
import subprocess
import Info_to_web_site
test = Info_to_web_site.Site()
subprocess.run(Info_to_web_site.Site.__init__(test))
print(123123123)
|
import z
import math
import csv
from collections import defaultdict
import table_print
import statistics
import os
from sortedcontainers import SortedSet
from rows import *
from scipy import stats
import args
import buy
#table_print.accurate = 2
# mc 30.00B to 1.54T
# mc 7.5B to 30.00B
# mc 2.7B to 7.5B
# mc 0 to 2.... |
'''
Процедура - именованный блок кода, который работает, но НЕ возвращает результат
Функция - именованный блок кода, который работает, но возвращает результат
def имя_функции(параметр1, параметр2):
--->сделать_что_то
--->вернуть результат
'''
# определить функцию с именем add
def add(a, b): # добавить параметры а и... |
from tkinter import *
from tkinter import messagebox
calculator = Tk()
calculator.title("CALCULATOR")
calculator.resizable(0, 1)#remove or change this in order to get different screen sizes
class Application(Frame):
def __init__(self, master, *args, **kwargs):
Frame.__init__(self, master, *args, **kwargs)
self.c... |
from sklearn.datasets import load_iris
iris = load_iris()
from sklearn.linear_model import LogisticRegression
from sklearn import metrics
from sklearn.neighbors import KNeighborsClassifier
from sklearn.cross_validation import train_test_split
import matplotlib.pyplot as plt
# source - http://www.ritchieng.com/machine-... |
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import classification_report, confusion_matrix, precision_recall_fscore_support, accuracy_score
class Classification_svm:
"""docstring for Classification_svm."""
def __... |
# -*- coding: utf-8 -*-
"""
ytelapi
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class Numbertype1Enum(object):
"""Implementation of the 'Numbertype1' enum.
Number type either SMS,Voice or all
Attributes:
ALL: TODO: type description... |
from sqlalchemy import nullsfirst, nullslast, desc
class NullOrderMixinView(object):
"""
A mixin view that will allow setting NULLS FIRST or NULLS LAST
"""
def _order_by(self, query, joins, sort_joins, sort_field, sort_desc):
"""
Apply order_by to the query
:param qu... |
"""
REF:[giampaolo/psutil](https://github.com/giampaolo/psutil)
[ArgumentParserの使い方を簡単にまとめた - Qiita](https://qiita.com/kzkadc/items/e4fc7bc9c003de1eb6d0)
[Pythonの文字列フォーマット(formatメソッドの使い方) | ガンマソフト株式会社](https://gammasoft.jp/blog/python-string-format/)
cpu[%] mem[%] (= [GB] / [GB])
------ ------------------... |
import sys
sys.path.append('../doubly_linked_list')
from doubly_linked_list import DoublyLinkedList, ListNode
class Stack:
def __init__(self):
self.size = 0
# Why is our DLL a good choice to store our elements?
# self.storage = ?
self.storage = DoublyLinkedList()
def push(self,... |
from django.contrib import admin
from .models import ShortUrl
# Register your models here.
class ShortUrlAdmin(admin.ModelAdmin):
list_display = ['id', 'url', 'short_url']
class Meta:
model = ShortUrl
admin.site.register(ShortUrl,ShortUrlAdmin) |
from django.core.management.base import BaseCommand
from django.contrib.auth.models import Group,Permission,ContentType
from apps.news.models import News,NewsCategory,Banner,Comment
from apps.course.models import Course,CourseCategory,Teacher,CourseOrder
from apps.payinfo.models import Payinfo,PayinfoOrder
class Comma... |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 5 20:01:41 2018
@author: Octavio Ordaz
"""
#Libreria para leer desde archivos csv
import pandas as pd
#Libreria para trabajar con documentos JSON
import json
#Libreria que ocupamos para graficar los resultados de las consultas
import matplotlib.pyplot as plt
#En la c... |
easy_test = 'aabcdefgaa'
hard_test = 'ieodomkazucvgmuy'
found = False
positions = []
for i, c in enumerate(list(hard_test)):
if i < len(hard_test)-1:
if len(positions) > 0:
for p in positions:
if [c, hard_test[i + 1]] == p[0] and i != p[1][1]:
found = True
... |
import discord
from discord.ext import commands
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as', self.user)
async def on_message(self, message):
# don't respond to ourselves
if message.author == self.user:
return
if message.content == ... |
import collections, math
class StupidBackoffLanguageModel:
def __init__(self, corpus):
"""Initialize your data structures in the constructor."""
self.unigramCounts = collections.defaultdict(lambda: 1)
self.bigramCounts = collections.defaultdict(lambda: 0)
self.unigramTotal = 0
self.bigramTotal =... |
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return x**2
x = np.arange(0,10,0.01)
y = f(x)
print(y)
plt.plot(x,y)
plt.show()
|
# Generated by Django 2.2.11 on 2020-03-16 03:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('orgchart', '0015_detail_subordinates_url'),
]
operations = [
migrations.RemoveField(
model_name='detail',
name='sub... |
my_list = [1, 3, 2, 5, 14, 6, 2, 3, 5, 6, 14, 9, 1]
new_list = list(set(my_list))
print(new_list)
|
import numpy as np
import matplotlib.pyplot as plt
import os
import shutil
# Generate the figures in the same folder
os.chdir(os.path.dirname(__file__))
rng = np.random.RandomState(42)
# 2D parameter space:
n_steps = 200
w1 = np.linspace(-2.5, 2.5, n_steps)
w2 = np.linspace(-2.5, 2.5, n_steps)
w1, w2 = np.meshgrid(w... |
import cv2
import tensorflow.keras
import numpy as np
from kakao import beepsound, send_music_link, send_question_text
## 이미지 전처리
def preprocessing(frame):
# 사이즈 조정
size = (224, 224)
frame_resized = cv2.resize(frame, size, interpolation=cv2.INTER_AREA)
# 이미지 정규화
frame_normalized = (frame_resized.... |
"""Treadmill module launcher.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import importlib
if __name__ == '__main__':
init_hook = os.environ.get('TREADMILL_INIT_HOOK')
if init_hook:
... |
import sys
import clean_taffy
import make_pool_v2
import preprocess_data
import train_recommend_v2
import glob
directory = "/var/www/html/users/"+str(sys.argv[1])
province = sys.argv[2]
root_dir = "/var/www/html/"
clean_taffy.clean_taffy_liste(root_dir, directory, province)
make_pool_v2.make_pool_data(root_dir, ... |
# Tuples #
# Tuples are immutable sequences.
tpl = (1,2,3)
print(tpl[1])
tpl = ('a', True, 123)
print(tpl)
# tpl[0] ='New'#It gives error because of tuples not changable
# Sets #
# Sets are unordered collections of unique elements.
x = set()
x.add(1)
x.add(2)
x.add(4)
x.add(0.1)
x.add(... |
import numpy as np
import cv2 as cv
import copy
from cameraParameter import CameraParameter
from algo import get_padding_transform
class FrameInterface:
def __init__(self):
self.m_img = None
self.m_kp = None
self.m_desc = None
self.m_R = None
self.m_T = None
self.m_... |
# don't need -u everytime we push changes, only the first time it happens in a repo
# friendlistCleanser -- removes everyone from a League of Legends account's friendlist
import pyautogui, time
pyautogui.FAILSAFE = True
# click coordinates
FRIEND = (1517, 269)
UNFRIEND = (1560, 500)
CONFIRM = (900, 600 )
print(... |
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import itertools
import os.path
from dataclasses import dataclass
from typing import Iterable
from pants.backend.javascript import package_json
from pan... |
#JSON(javascript object notation) realtime server_to_browser communication
#Loading json in python
import json
with open('E:\csvdhf5xlsxurlallfiles/snakes.json', 'r') as json_file:
json_data = json.load(json_file)
print(type(json_data))
for key, value in json_data.items():
print(str(key)+':'+str(value))
#c... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 28 22:53:35 2015
@author: lenovo
"""
"""
题目内容:
如果列出10以内自然数中3或5的倍数,则包括3,5,6,9。
那么这些数字的和为23。
要求计算得出任意正整数n以内中3或5的倍数的自然数之和。
"""
#a = int(raw_input())
#sum = 0
#for i in range(0,a):
# if i % 3 == 0:
# sum += i
# elif i % 3 == 0 and i % 5 ==0:
# sum += i
# ... |
#Test
import pyaudio
import numpy as np
from numpy import zeros,linspace,short,fromstring,hstack,transpose,log, ndarray
from scipy import fft
from time import sleep
import time
import piplates.DAQC2plate as DAQC2
#import openpyxl
#from openpyxl import Workbook
import struct
import scipy.fftpack
#import ma... |
"""
Models for User Information (students, staff, etc)
Migration Notes
If you make changes to this model, be sure to create an appropriate migration
file and check it in at the same time as your model changes. To do that,
1. Go to the edx-platform dir
2. ./manage.py lms schemamigration student --auto description_of_... |
from django.urls import path
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
path("", views.index, name="ShopHome"),
path("about/", views.about, name="AboutUs"),
path("contact/", views.contact, name="ContactUs"),
path("profile/", views.profile, name="profile"),
... |
""" Core Messaging Pages """
import os
from typing import Optional
from datetime import datetime, timedelta
from fastapi import APIRouter, Request, status, Cookie, Depends
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
from ..u... |
Lat1= -33.4503685
Lon1= -70.6897731
Alt = 10
AltMax = 20
perimetroLat= [-33.4506, -33.4506, -33.4500, -33.4500];
perimetroLon= [-70.6897, -70.6894, -70.6894, -70.6897];
largo=0
ancho=0
dron = [0, 0, 4, Alt]
area=0
completitud= 0
trayectoria= []
import numpy as np
def SetearParametros():
Lat1 = input("Latitud de D... |
version = "1.7.5-$Format:%h$"
|
# -*- coding: utf-8 -*-
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
result = []
self.inorderTraversal(root1, re... |
from __future__ import division
import numpy as np
import numpy.random as npr
from scipy.stats import norm
from svae.forward_models import _diagonal_gaussian_loglike
def check_diag_gauss_loglike(x, mu, log_sigmasq):
loglike = _diagonal_gaussian_loglike(x, mu, log_sigmasq)
scipy_loglike = np.mean(norm.logpdf(... |
import os.path
# Set up a level object
class Level:
width = 25
height = 15
filename = 'DEFAULT'
level = []
# Initialize
def __init__(self, filename):
self.filename = filename
self.loadLevel()
# Just fill our level with lots of zeroes
def zeroLevel(self... |
from setuptools import setup
setup(
name='delivery',
version='1.0',
py_modules=[''],
install_requires=['Click', 'numpy', 'pandas', 'colorama'],
entry_points='''
[console_scripts]
delivery=delivery:cli
''',
) |
# -*- coding: utf-8 -*-
import os.path
PROJECT_PATH = os.path.dirname(os.path.abspath(__file__))
# flask core settings
DEBUG = True
TESTING = False
SECRET_KEY = 'qh\x98\xc4o\xc4]\x8f\x8d\x93\xa4\xec\xc5\xfd]\xf8\xb1c\x84\x86\xa7A\xcb\xc0'
PERMANENT_SESSION_LIFETIME = 60 * 60 * 24 * 30
# flask wtf settings
WTF_CSRF... |
#!/usr/bin/python
from __future__ import print_function
from vizdoom import *
from agent import Runner
import time
game = DoomGame()
game.load_config("config/my_custom_config.cfg")
# Name your agent and select color
# colors: 0 - green, 1 - gray, 2 - brown, 3 - red, 4 - light gray, 5 - light brown, 6 - light red, 7 ... |
val = 0.0
def change():
global val
val = 1.0
print("val is " + str(val)) |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2019-11-12 00:07
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('index', '0001_initial'),
]
operations = [
... |
import os
import shutil
import unittest
DATA_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), 'data'))
_STORAGE_DIR = os.path.join(DATA_DIR, 'storage')
os.environ.setdefault('GRAPHITE_STORAGE_DIR', _STORAGE_DIR)
class TestCase(unittest.TestCase):
def _cleanup(self):
shutil.rmtree(DATA_DIR, i... |
#!/usr/bin/env python
import http.server
import os
import pathlib
import socketserver
build_root = pathlib.Path(
os.path.abspath(os.path.dirname(__file__)), "..", "build", "local"
).resolve()
os.chdir(str(build_root))
port = 8020
class MagicHTMLHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self)... |
import datetime
import logging
import sqlalchemy
from flask import json
from sqlalchemy import (create_engine, Column, String,
DateTime, func, Integer)
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from... |
import qutip as qt
import random
from typing import Tuple, Callable
import numpy as np
from simulator import Simulator
Strategy = Tuple[Callable[[int], int], Callable[[int], int]]
def random_bit() -> int:
return random.randint(0, 1)
def referee(strategy: Callable[[], Strategy]) -> bool:
you, eve = strat... |
"""
Faça um Programa que peça dois números e imprima o maior deles.
"""
def pede_numero_ao_usuario(msg):
return float(input(msg))
def obter_o_maior_numero(num_1, num_2):
# este é o chamado if ternário, faz o if em apenas uma linha
maior_numero = num_1 if num_1 >= num_2 else num_2
return maior_numero... |
from __future__ import print_function
import urllib2
from bs4 import BeautifulSoup
# File to dump the article link list
f = open('lists/listAddPortalArticles.txt','w')
#URLs for the Vital 100
#urls = ['http://en.wikipedia.org/wiki/Wikipedia:Vital_articles/Level/2'] # Single page where the 100 vital articles are link... |
#!/usr/bin/python
from copy import copy
import sys
def find_words(letter_string, preferred_letters=''):
#Convert letters to lowercase and split it into a list
letters = list(letter_string.lower())
preferred = list(preferred_letters.lower())
#list to hold our words loaded from our text file
words=[... |
import numpy as np
from tqdm import tqdm
from notebooks.notebook_utils import vod_coefficient, dice_coefficient, accuracy_score, get_contour_mask
### Functions that determine slices order of fixing
# Can return the full order (like baseline_func, baseline_seq_func) or return the next slice to fix (like best_func2)
# ... |
from collections import OrderedDict
import torch
import torch.nn as nn
from torchvision.models import densenet121, densenet169, densenet201, densenet161, squeezenet1_1
from torchvision.models.video import r2plus1d_18
def densenet_121(num_classes, expansion=False):
"""
Args:
num_classes (int):
Re... |
from random import randint
from typing import List
from MainSettings import MainSettings
from shardcalc.models.Awaken import Awaken
from common.utils.DateUtils import DateUtils
from shardcalc.utils.ShardEventUtils import CommonEventUtils, ShardEventUtils
class ShardUtils:
__QUEST_COOLDOWN: int = 21
__QUEST_... |
# -*- coding: utf-8 -*-
from openerp import http
# class Demo(http.Controller):
# @http.route('/demo/demo/', auth='public')
# def index(self, **kw):
# return "Hello, world"
# @http.route('/demo/demo/objects/', auth='public')
# def list(self, **kw):
# return http.request.render('demo.li... |
from __future__ import print_function
import functools
import tensorflow as tf
def lazy_property(function):
attribute = '_' + function.__name__
@property
@functools.wraps(function)
def wrapper(self):
if not hasattr(self, attribute):
setattr(self, attribute, function(self))
... |
#!/usr/bin/env python
# coding: utf-8
# <b> Load data from the File-input.csv file into a pandas dataframe and print it to the Jupyter console. <b>
# In[12]:
import os
# In[4]:
import pandas as pd
# In[5]:
dataframe = pd.read_csv("File-input.csv")
dataframe
# <b> Convert the dataframe into a list of Dicti... |
import sys
from PyQt5.QtWidgets import (QApplication, QCheckBox, QColorDialog, QDialog,
QErrorMessage, QFileDialog, QFontDialog, QFrame, QGridLayout,
QInputDialog, QLabel, QLineEdit, QMessageBox, QPushButton)
def defin_right(d_x):
d_x_s = str(d_x)
pos = d_x_s.find('.')
right = d_x_s[pos + ... |
#!/usr/bin/python3
"""
PYTHON OBJECT RELATIONAL MAPPING MODULE
Model_State_Fetch_All module provides function to get all states from states
table in the DB.
"""
import sys
from model_state import Base, State
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
def model_state_fetch_all():
... |
from django.db import models
from django.contrib.auth import get_user_model
from django.core.validators import MinLengthValidator
class Category(models.Model):
"""カテゴリー"""
title = models.CharField(max_length=20)
def __str__(self):
return self.title
class ReadBook(models.Model):
"""読んだ本"""
... |
import pytest
from unittest import mock
import builtins
import re
regex_pattern = r"M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$" # Do not delete 'r'.
def validating():
return str(bool(re.match(regex_pattern, input(''))))
def test_substraction():
with mock.patch.object(builtins, 'input', lamb... |
"""
Author: John Beckingham
Student ID: <redacted>
Author: Hai Yang Xu
Student ID: <redacted>
Maze Generator maze solver
"""
import server.libbfs as libbfs
def solve(graph, start=(0, 0), end=(34, 24)):
"""
Given a graph representing a maze with unique solution, find that solution
The default player pos... |
#!/usr/bin/python2.7 -E
#
# Code generator main program
#
# Copyright (C) Sierra Wireless, Inc. 2013. All rights reserved. Use of this work is subject to license.
#
import os
import sys
import argparse
import collections
import codeTypes
import interfaceParser
import codeGen
def GetArguments():
# Define the com... |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 14 10:32:09 2017
@author: Xithrius
"""
import random
rString = random.randint(0, 3)
r = int(rString)
d = {0: 'screw you',
1: 'frick you',
2: 'flip you',
3: 'razzel dazzel you'
}
x = d[r]
print(x)
|
from lib.Song import Song
import requests as http
import redis as rd
from base64 import b64encode
import statistics
cache = rd.StrictRedis(host='localhost', port=6379, db=0)
client_id = 'f3b0c51df1124cc985fd4012b6d55d95'
client_secret = 'e54ca2e0bf394944a1247830443dba3c'
token_uri = 'https://accounts.spotify.com/api... |
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> range(20)
range(0, 20)
>>> range(10,20)
range(10, 20)
>>> list(range(10,20))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> list(range(10,21))... |
#Author Gayatri Deo
import nltk;
import sys;
from nltk.corpus import wordnet as wn;
def printExamples(category):
for f in wn.synsets(category):
for hypo in f.hyponyms():
for hypo1 in hypo.hyponyms():
for e in hypo1.examples:
e = '__'.join(e.split(hypo1.... |
from utils import s_box, r_con, combine_byte, mix_matrix, get_rounds, sub_byte
def subWord(a):
"""
>>> hex(subWord(0x00102030))
'0x63cab704'
>>> hex(subWord(0x40506070))
'0x953d051'
>>> hex(subWord(0x8090a0b0))
'0xcd60e0e7'
>>> hex(subWord(0xc0d0e0f0))
'0xba70e18c'
"""
res =... |
from nltk.tag import StanfordNERTagger
from nltk.tokenize import word_tokenize, sent_tokenize
import fileinput
def ner_tagger(filename):
st = StanfordNERTagger('/Users/avnish/stanford-ner-2017-06-09/classifiers/english.muc.7class.distsim.crf.ser.gz','/Users/avnish/stanford-ner-2017-06-09/stanford-ner.jar',encoding =... |
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence,pad_packed_sequence
MAX_QUESTION_LEN = 20
UNKNOWN_TOKEN = "<unk>"
PAD_TOKEN = "<pad>"
SPECIAL_TOKENS = [PAD_TOKEN, UNKNOWN_TOKEN]
class LSTM_question(nn.Module):
def __init__(self, word_vocab_size, word_embedding_dim, hidden_dim, out_dim: in... |
#!/usr/bin/python3
import pandas as pd
import quandl
quandl.ApiConfig.api_key = 'UqFxQsZQUXnBRfLxAnsp'
df = quandl.get_table('WIKI/PRICES')
df = df[["adj_open","adj_high","adj_low","adj_close","adj_volume"]]
df['HL-PCT']=(df['adj_high']-df['adj_close'])/df["adj_close"] *100.0
df['HL-change']=(df['adj_close']-df['a... |
import openpyxl
from openpyxl.chart import RadarChart, Reference
wb = openpyxl.load_workbook(r"..\data\radar_chart.xlsx")
sh = wb.active
data = Reference(sh, min_col=2, max_col=4, min_row=1, max_row=sh.max_row)
labels = Reference(sh, min_col=1, min_row=2, max_row=sh.max_row)
chart = RadarChart()
#預設為standa... |
from collections import deque
from typing import Optional, List
class TreeNode:
def __init__(self, val: int):
self.val: int = val
self.left: Optional[TreeNode] = None
self.right: Optional[TreeNode] = None
def __eq__(self, other: object) -> bool:
return (
isinstance... |
import io, os, sys, csv, random, logging
from jacks.infer import LOG, inferJACKS
from jacks.jacks_io import createPseudoNonessGenes, readControlGeneset, createGeneSpec, createSampleSpec, getJacksParser, collateTestControlSamples, writeJacksWResults
from jacks.preprocess import loadDataAndPreprocess
py_cmd = 'python'
... |
# import sys
# import os
# sys.path.append(os.path.normpath(os.path.join(
# os.path.dirname(os.path.abspath(__file__)), '..')))
|
import datetime
from django import forms
from django.conf import settings
from django.core.validators import ValidationError
from django.template.defaultfilters import filesizeformat
from django.utils.translation import ugettext_lazy as _
from crispy_forms.bootstrap import StrictButton
from crispy_forms.layout import... |
"""Entry point script; implements CLI."""
import argparse
import msvcrt
import sys
from src import classify, train
def training_prompt():
"""
Prompts the user with a warning message about overwriting the saved model.
"""
print('WARNING: Training will overwrite the saved model (if it exists). EXECUTE... |
import time
from selenium import webdriver
browser='ie'
if browser=='chrome':
driver=webdriver.Chrome(executable_path="C:/Users/Dell/PycharmProjects/5_Class/drivers/chromedriver.exe")
elif browser=='firefox':
driver = webdriver.Firefox(executable_path="C:/Users/Dell/PycharmProjects/5_Class/drivers/geckodriver.... |
from urllib.request import urlopen #used to open remote object and read it
from urllib.error import HTTPError #it is used to through an exception if any library error is there
from urllib.error import URLError #to check any url exception is there
from bs4 import BeautifulSoup
try:
html = urlopen('https:/... |
def color(code):
def inner(text, bold=False):
c = code
if bold:
c = '1;{}'.format(c)
return '\033[{new}m{text}\033[{old}m'.format(new=c, text=text, old=39)
return inner
grey = color('0')
black = color('30')
red = color('31')
green = color('32')
yellow = color('33')
blue =... |
import numpy as np
import pandas as pd
import cv2
import matplotlib.pyplot as plt
import yaml
default_colors=[(255,96,208),(1,0,255),(255,0,0),(255,255,0),(0,255,0),(160,128,96),(255,128,0),(153,0,153),(153,153,0),(102,0,0)] #default colors for plotting phases
default_colors_2=[(255,128,0),(153,0,153),(153,153,0),(102... |
import time
from Pages.base_page import BasePage
from Utils.locators import *
class Alerts(BasePage):
def __init__(self, driver):
self.locator = AlertsLocators
super().__init__(driver)
def click_autoclosable_buttons(self):
self.driver.find_element(*self.locator.autoclosable_btn_succ... |
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from musee.frontend.app import create_app
from musee.frontend.model import db, KeyWords
from musee.collect_text_data.textFromUrl import TextFromUrl
from musee.keyword_extract.extractKeywords import ExtractKeywords
app = create_app()
mi... |
"""empty message
Revision ID: 83e3c2ddae30
Revises: 16949f631586
Create Date: 2017-05-25 00:36:45.441822
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '83e3c2ddae30'
down_revision = '16949f631586'
branch_labels = None
depends_on = None
def upgrade():
# ... |
# coding=utf-8
import unittest
from katas.kyu_4.strip_comments import solution
class StripCommentsTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(solution(
'apples, pears # and bananas\ngrapes\nbananas !apples',
['#', '!']), 'apples, pears\ngrapes\nbananas')
... |
# Create a function called calc_dollars. In the function body, define a dictionary and store it in a variable named piggyBank. The dictionary should have the following keys defined.
# quarters
# nickels
# dimes
# pennies
# For each coin type, give yourself as many as you like.
# piggyBank = {
# "pennies": 342,
# ... |
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.testutil.pants_integration_test import run_pants, setup_tmpdir
def test_build_ignore_list() -> None:
with setup_tmpdir({"dir/BUILD": "target()"}) as tmpdir:
ignore... |
{'city':'北京', 'num':18297}
{'city':'南京', 'num':18223497}
{'city':'上海', 'num':197}
{'city':'扬州', 'num':1823397}
{'city':'泰州', 'num':182297}
{'city':'徐州', 'num':18291247} |
#!/usr/bin/python2.6
###################
# Michael Molho #
# 2014 #
###################
import sys
import struct
if len(sys.argv) != 4:
sys.stderr.write('Usage ' + sys.argv[0] + ' <template file> <ip> <port> \n')
sys.exit(1)
template = sys.argv[1]
ip = sys.argv[2]
port = sys.argv[3]
raw = open... |
import pygame
import os
##############################
#Robot
enemywalk=[pygame.image.load(os.path.join("sprites/Robot/Robot_walk",image)) for image in os.listdir(os.path.join("sprites/Robot","Robot_Walk"))]
enemyattackleft=[pygame.image.load(os.path.join("sprites/Robot/Robotattackleft",image)) for image in os.l... |
from urllib.parse import urlparse
from threading import Thread
import http.client, sys
from queue import Queue
import requests
from bs4 import BeautifulSoup
concurrent = 10
def doWork():
while True:
url = q.get()
print(url)
html_content = requests.get(url).text
soup = BeautifulSoup... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import pytest
from pants.backend.python import target_types_rules
from pants.backend.python.lint.pyupgrade.rules import PyUpgradeFieldSet, PyUpgradeReq... |
import requests # for making standard html requests
from bs4 import BeautifulSoup # magical tool for parsing html data
import json # for parsing data
from pandas import DataFrame as df # premier library for data organization
#requesting data
page = requests.get("https://locations.familydollar.com/id/")
soup = Beautif... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.