text
stringlengths
8
6.05M
#!/usr/bin/python # -*- coding: utf-8 -*- import httplib2 as http import httplib import re from urlparse import urlparse import pprint import urllib2 class streamscrobbler: def parse_headers(self, response): headers = {} int = 0 while True: line = response.readline() ...
import click from flask.cli import with_appcontext from .models import User, db, SocialMedia from grant.task.models import Task from grant.settings import STAGING_PASSWORD # @click.command() # @click.argument('identity') # @with_appcontext # def delete_user(identity): # print(identity) # if str.isdigit(ident...
from PyQt5.QtWidgets import * from PyQt5.QtGui import * import sqlite3 from Functions import GuiSignal from Gui import GuiTab #Gui основного окна class MainWindow(QMainWindow): def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.conn = sqlite3.connect...
import numpy as np import matplotlib.pyplot as plt import seaborn as sns import csv import matplotlib font = {'family' : 'normal', 'weight' : 'normal', 'size' : 18} matplotlib.rc('font', **font) cmap="RdBu_r" ######### Functions Defined Below ######### #############################################...
from rest_framework import viewsets from rest_framework.permissions import AllowAny from resume.apps.resumes.models import Resume from .serializers import ResumeSerializer class ResumeViewSet(viewsets.ReadOnlyModelViewSet): queryset = Resume.objects.all() serializer_class = ResumeSerializer permission_cl...
#!/usr/bin/env python #coding:utf8 import sys,os,re import subprocess import optparse import pexpect reload(sys) sys.setdefaultencoding('utf-8') class check_mysql_mongo_process: def __init__(self,node_name): self.node_name = node_name self.server_dir = "/data/%s/server"% self.node_name self.server_process_coun...
#!/usr/bin/env python import cv2 import serial #导入模块 import threading STRGLO="" #读取的数据 BOOL=True #读取标志位 #读数代码本体实现 def ReadData(ser): global STRGLO,BOOL # 循环接收数据,此为死循环,可用线程实现 if ser.in_waiting: STRGLO = ser.read(ser.in_waiting).decode("ascii") print(STRGLO) #打开串口 # 端口,GNU / Li...
# Posts Module from django.db import models from django.contrib.auth.models import User from django.conf import settings # Create your models here. class Post(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=50) excerpt = models.TextField() content = models.TextField() p...
POWER_SLOT_MED = 13 POWER_SLOT_HIGH = 12 POWER_SLOT_LOW = 11 POWER_SLOT_RIG = 2663 POWER_SLOT_SUBSYSTEM = 3772
#-*-coding:utf-8-*- class Solution: # @return a tuple, (index1, index2) def twoSum(self, num, target): d = {} index = 1 for i in num: d.update({i:index}) index+= 1 index = 0 for i in num: index += 1 if (target - i) in d and ...
# -*- coding: utf-8 -*- from numpy import * from matplotlib import pyplot from ospa import ospa_distance import tkFileDialog import tables from RangeBearingMeasurementModel import * import cProfile import pstats import os import cPickle import fnmatch from plot_results import plot_errors def compute_error_k(logfilen...
import os import nltk import math import pandas as pd import numpy as np import string import re from nltk.corpus import stopwords from nltk.stem import PorterStemmer from collections import Counter from sklearn.metrics import accuracy_score data = 'D:/vsm+knn/data/20news-18828' data_train = 'D:/vsm+knn/d...
import os from TimeLogger import time_logger SCORES_FILE_NAME = "Scores.txt" BAD_RETURN_CODE = -1 DEFAULT_WEB_PAGE = "http://127.0.0.1:5000/" DEFAULT_CHROME_PATH = "c:/Selenium/chromedriver.exe" @time_logger def screen_cleaner(): """ trying to clear the screen. Relevant function changes based on ...
import sqlite3 connection = sqlite3.connect("Estoque.db") cursor = connection.cursor() create_table = "CREATE TABLE IF NOT EXISTS Estoque (codigo INTEGER PRIMARY KEY AUTOINCREMENT, produto varchar(30), valor decimal (5,2) not null, qtd int not null)" cursor.execute(create_table) tables = cursor.fetchall(...
# Generated by Django 1.9.5 on 2016-11-04 18:00 from django.db import migrations, models import django.utils.timezone def move_dates(apps, schema_editor): """Move dates to models.""" Domain = apps.get_model("admin", "Domain") DomainAlias = apps.get_model("admin", "DomainAlias") Mailbox = apps.get_mode...
SIMULATE_ON_BOAT = False #use serial port from the controller SERIAL_PORT = "COM6" SERIAL_BAUD = 115200 SERIAL_TIMEOUT = 5 SIM_MOVE_INTERVAL = 1 SIM_PRINT_INTERVAL = 10 SIM_MAX_SPEED = 2000000.0 #SIM_RUDDER_RESPONSE = 0.00005 SIM_RUDDER_RESPONSE = 0.0001 TACKMODE_DIRECTLY = 0 TACKMODE_ADJ_POS = 1 TACKM...
# Generated by Django 3.2.4 on 2021-07-02 07:30 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('database', '0007_company_exchange'), ] operations = [ migrations.AlterField( model_name='compan...
from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.naive_bayes import MultinomialNB from nltk.corpus import stopwords from nltk.stem import RSLPStemmer import speech_recognition as sr from gtts import gTTS import random import string import numpy import nltk import sys import os class File: ...
"""Construct word map graphs for each sheet in page_data_dictionary.""" from operator import itemgetter import xmlColumnOperator import xmlWordOperators import numpy as np class xmlPageOperator(object): def __init__(self, i, year, page_data, file_path, xml_column_chart_center, xml_column_chart_thirds): ...
from flask import Flask from flask_sslify import SSLify from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager # Initiate Flask app = Flask(__name__) sslify = SSLify(app) app.config.from_object('config.HerokuConfig') # initialize the database connection db = SQLAlchemy(app) login = LoginManager(...
import numpy import scipy import matplotlib.pyplot as plt import numpy as np Fs = 1e4 sample = 1e4 f1 = 1000 f2 = 2000 f3 = 3000 x = np.arange(sample) a = np.cos(2 * np.pi * f1 * x / Fs) + 10 b = np.cos(2 * np.pi * f1 * x / Fs) + np.cos(2 * np.pi * f2 * x / Fs) + np.sin(2 * np.pi * f3 * x / Fs) c = x**2 + np.sin(2 *...
# magazine/models.py # -*- coding: UTF-8 -*- from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ from .app_settings import STATUS_CHOICES class NewsArticle(models.Model): status = models.CharField(_("Status"), max_length=20, choices=STATUS_CHO...
import re def get_game_date(game): _table = game.parent game_date_raw = _table.find('td', class_='gameTime').text p = re.compile(r'\d{4}-\d{02}-\d{2}') date = p.findall(game_date_raw) if not len(date): return None date = date[0] return date.replace('-', '') def get_endorsement(game): endorse = game.find(...
def print_soduko(puzzle, print_lists = False): l = ['-------------------\n'] for row in range(len(puzzle)): l.append('|') for col in range(len(puzzle)): entry = puzzle[row][col] if isinstance(entry, list): if print_lists: l.append(str(e...
#----------------URL and imports----------------------------- import requests import json URL = 'http://localhost:8088/services/' #---------------REQUESTS-------------------------------------- def post_user(email,phone,password): user = {} user['email'] = email user['phone'] = phone user['address'] = pa...
""" Errors like the error cases from Rackspace Monitoring. """ from __future__ import division, unicode_literals import attr from six import text_type @attr.s class ParentDoesNotExist(Exception): """ Error that occurs when a parent object does not exist. For instance, trying to access or modify a Check...
# Tuple(元组) # 元组(tuple)与列表类似,不同之处在于元组的元素不能修改。元组写在小括号(())里,元素之间用逗号隔开。 # 元组中的元素类型也可以不相同 tuple = ('abcd', 786, 2.23, 'runoob', 70.2) tinytuple = (123, 'runoob') print(tuple) # 输出完整元组 print(tuple[0]) # 输出元组的第一个元素 print(tuple[1:3]) # 输出从第二个元素开始到第三个元素 print(tuple[2:]) # 输出从第三个元素开始的所有元素 print(tinytuple * 2) # 输出两次元组 p...
#========================================================================= # This is a simple function to define land and ocean masks for LMR output. # author: Michael P. Erb # date : October 19, 2016 #========================================================================= import numpy as np import xarray as xr...
x, y = map(int, input().split()) # def F (x, y, cache): # print (f"Call for ({x}, {y})") # if ( (x, y) not in cache): # if (x == 0): # cache[(x, y)] = y+1; # elif (x > 0 and y == 0): # cache[(x, y)] = F(x-1, 1, cache); # else: # cache [(x, y)] = F(x-1...
""" Testing utilities. Do not modify this file! """ num_pass = 0 num_fail = 0 def assert_equals(msg, expected, actual): """ Check whether code being tested produces the correct result for a specific test case. Prints a message indicating whether it does. :param: msg is a message to print at t...
from typing import Any, Dict import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output from dash.exceptions import PreventUpdate from phi.field import SampledField from phiml.math._shape import parse_dim_order from phi.vis._dash.dash_app import DashApp from phi...
# This file is part of beets. # Copyright 2016, Adrian Sampson. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, ...
from script.conftest import get_host, ji_yun_ying_login
from quick_sort import partition def quick_select.py(givenList, left, right, k): split = partition(givenList, left, right) if split == k: return givenList[split] elif split < k: return quick_select(givenList, split + 1, right, k) else: return quick_select(givenList, left, split - 1, k)
''' Creating a Linked List in Python. Linked Lists are almost useless in Python, since lists are so valuable. This is mostly just an exercise in coding. However, it is good to know that Python Lists suffer from 2 small setbacks: 1) Lists in Python are equivalent to arrays. They are contiguous, so as to have O(1) access...
from django.apps import AppConfig class ProgressAnalyzerConfig(AppConfig): name = 'progress_analyzer'
import _time def sleep(s: float): for i in range(int(s)): _time.sleep_s(1) _time.sleep_ms(int((s - int(s)) * 1000)) def sleep_s(s: int): return _time.sleep_s(s) def sleep_ms(ms: int): return _time.sleep_ms(ms) def time() -> float: return _time.time() def time_ns() -> int: retur...
from . import product_product from . import product_pricelist from . import sale
import csv import os ifile = open('input.csv', "rb") ofile = open('output.csv', "wb") complete = 0 incomplete = 0 first = 1 username = '' prior_user = '' writer = csv.writer(ofile) reader = csv.reader(ifile) writer.writerow(["Username", "First Name", "Last Name", "Completed Mapped Items", "Incomplete Mapped Items",...
# 之前做过了, 分状态写的 # 双指针 # dl的解法是记录该点到左边R的距离和到右边L的距离,哪个近就往同侧倒,一样就不倒 class Solution: def pushDominoes(self, dominoes: str) -> str: n = len(dominoes) # [L_dist, R_dist] records = [[inf, inf] for _ in range(n)] cur = -inf for i, c in enumerate(dominoes): if c == 'R': ...
# -*- coding: utf-8 -*- """helpers.py: Various Helper Functions Handles all neccessary parts of the irc protocol for client connections. """ import os import sys import time import re import urllib import traceback try: import urllib2 except: urllib2 = None # Legacy support # Try to convert to string with...
# Hash Tables: Ransom Note # Cracking the Coding Interview Challenge # https://www.hackerrank.com/challenges/ctci-ransom-note class Word: def __init__(self, word, used): self.word = word self.used = used def ransom_note(magazine, ransom): # Initialize hashMap hashMap = [] for ...
#!/usr/bin/python # python stuff import time import sys import numpy as np import os.path # index coding stuff from Symbol import Symbol from alignment import alignment, nullvec from bs_index_coding import compute_interferers, transmit_messages, bs_decode_messages from multirandperm import pairingperm # tos stuff, ...
#! /usr/bin/python # Find data file in switchboard files using basename. import sys import subprocess sys.path.append('/home/nxs113020/cch_plda/tools/') import make_cochannel if __name__=='__main__': """ Reads list of switchboard sphfiles formatted as: filename, spkrid, channel Generates c...
import requests from bs4 import BeautifulSoup from election_snooper.helpers import post_to_slack class BaseSnooper: def get_page(self, url): return requests.get(url) def get_soup(self, url): req = self.get_page(url) return BeautifulSoup(req.content, "html.parser") def post_to_sla...
import math import random from copy import deepcopy from itertools import chain from typing import List, Tuple import numpy as np import torch from torch.utils.data import Dataset from parseridge.corpus.sentence import Sentence from parseridge.corpus.vocabulary import Vocabulary from parseridge.utils.logger import Lo...
#!/usr/bin/env python3 import argparse import biotools parser = argparse.ArgumentParser( description='Prokaryotic gene finder.') parser.add_argument('--file', required=True, type=str, metavar='<str>', help='FASTA file') parser.add_argument('--minorf', required=False, type=int, default=300, metavar='<int>', help='m...
from django.urls import path from . import views from django.conf.urls import handler404 urlpatterns = [ path('', views.home, name='home'), path('register', views.register, name='register_pizza_app'), path('login', views.login, name='login_pizza_app'), path('logout', views.logout, name='logout_pizza_ap...
# -*- coding: utf-8 -*- from extensions import db # Alias common SQLAlchemy names Column = db.Column Model = db.Model relationship = db.relationship backref = db.backref metadata = db.metadata
# print("Pengaplikasian List") # print("Contoh 1 (Menambahkan anggota pada list kosong)") # List1 = [] # Membuat list kosong # List1.append('Ahmad') # List1.append(2212) # print("Output : ", List1) # print("=================") # print("Contoh 2 (Menghapus anggota pada list)") # List2 = [1, 4, 'U'] # List2.remove('U') ...
#!/bin/python from flask import Flask import threading import time from datetime import datetime, timedelta import sys import RPi.GPIO as GPIO PIN = 25 app = Flask(__name__) GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(PIN, GPIO.OUT) led_status = False time_thread = None @app.route('/time/off') def ti...
""" Heber Cooke 10/3/2019 Chapter 2 Exercise 8 This program calculates and displays the value of a light year the program takes the light speed of 3 * 10^8 meters per second the program takes that value and multiply by seconds in a year program displays the meters traveled per year """ SPEED = 3 * (10 **8)# meters p...
def check(moves): # 1,2 - win, 404 - draw draw = [] for i in range(0, 3): draw.append(moves[0][i]) draw.append(moves[i][0]) if moves[i][0] != 0 and moves[i][0] == moves[i][1] and moves[i][1] == moves[i][2]: # horizontal return True, moves[i][0] elif moves[i][0] != ...
import pandas as pd import numpy as np import ipaddress from sklearn.preprocessing import LabelEncoder,OneHotEncoder import sklearn.metrics as sm import sys import matplotlib as mp import seaborn as sb from sklearn.preprocessing import Normalizer from sklearn.naive_bayes import GaussianNB from sklearn import ...
import utils import configuration , callbacks import combos import db import gtk try : import hildon except : hildon = None def cell_data_func (column, renderer, model, iter, user_data) : value = model.get( iter, user_data[0] )[0] if user_data[0] == configuration.column_dict["CONSUM"] or user_data[...
from .basic import (IdDict, intervals, LazyProperty, logger, keydefaultdict, natsorted, set_log_level) from . import kit from .system import caffeine
from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase from shoutout.models import organization, user, shoutout from rest_framework.test import APIRequestFactory class OrganizationTests(APITestCase): def test_create_account(self): """ Ensure ...
# streamlit_app.py import streamlit as st import s3fs import os # Create connection object. # `anon=False` means not anonymous, i.e. it uses access keys to pull data. fs = s3fs.S3FileSystem(anon=False) # Retrieve file contents. # Uses st.cache to only rerun when the query changes or after 10 min. @st.cache(ttl=600) ...
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). """The `BuildFileDefaultsParserState.set_defaults` is used by the pants.engine.internals.Parser, exposed as the `__defaults__` BUILD file symbol. When parsing a BUILD (from the rule `pants...
class bioconductor: def __init__(self): # initialize logger import logging self.logger = logging.getLogger('metapath') # check if python module 'rpy2' is available try: import rpy2.robjects as robjects except: self.logger.critical("could not...
import torch from torch import nn from .metric import Metric class Accuracy(Metric): def __init__(self, name="accuracy", dtype=None, reduction="sum", **kwargs): super().__init__(name, dtype, **kwargs) assert reduction in {"sum", "mean", "max", "min"} # TODO: mo...
# coding=utf-8 import sys from ualfred import Workflow3, notify log = None def main(wf): import pickle from data import Data from ualfred import web city = wf.stored_data('cy-city') api_key = wf.get_password('apiKey') if city is None: wf.add_item('请通过cy-opt 设置所在城市') wf.send_feedback() return if api_ke...
# -*- coding: utf-8 -*- # @File : paint_tree.py # @Author : jianhuChen # @Date : 2018-12-29 14:19:07 # @License : Copyright(C), USTC # @Last Modified by : jianhuChen # @Last Modified time: 2018-12-29 14:44:07 import numpy as np from sklearn import neighbors from sklearn import datasets from skle...
names = ['Lucy', 'Frank', 'Ann', 'Garry', 'Frank', 'Alex', 'Penny', 'Garry', 'Tom', 'Frank'] Emails = ['josh', 'alex', 'lord', 'marry', 'penny', 'dog'] Magazine = ['alex', 'frank', 'harry', 'yourCrash', 'lord'] setNames = set(names) print(setNames) witoutDuplicates = [] for name in names: if (not name in witoutDu...
# -*- coding: utf-8 -*- import wx from wx.html2 import WebView class MyTestFrame(wx.Frame): def __init__(self, parent, title): super().__init__(parent, wx.ID_ANY, title, size=(1200, 700)) bSizer9 = wx.BoxSizer(wx.VERTICAL) self._browser = WebView.New(self) bSizer9.Add(self._brow...
from flask import Blueprint, request, redirect, url_for from flask.templating import render_template from sqlalchemy.sql.operators import nullsfirst_op from database.models import Alimenti, Log from database.db import db from datetime import datetime main = Blueprint('main', __name__) @main.route("/") def home(): ...
"""Entry point for treadmill manage ecosystem. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging import os import click import pkg_resources from treadmill import cli, plugin_manager, utils _LOGGER...
n = int(input("enter a n value :")) #n means number of blood banks blood_bank_name = {} for i in range(n): keys1 = int(input()) #keys1 means index of blood bank name values1 = input() #values1 means name of blood bank blood_bank_name[keys1] = values1 print(blood_bank_name) areas1 = {} for i in r...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 9 08:43:41 2019 @author: meiying """ import pandas as pd import matplotlib.pyplot as plt from sklearn.preprocessing import StandardScaler from sklearn.cluster import KMeans from sklearn.metrics import silhouette_score import seaborn as sns from sk...
from elk.libs.db.mysql import db class Users(object): _table = 'users' def __init__( self, id_, name, passwd, email, role, alert, deleted, created, updated): self.id_ = str(id_) self.name = name self.passwd = passwd self.email = email self.role ...
import translator from .. import utils class ASCIITranslator(translator.Translator): """Simple ASCII translation using unichr""" def parseInput(self, cipher): return map(int, utils.split(str(cipher))) def translate(self, cipher): return "".join([unichr(i) for i in self.parseInput(cipher)]) def encode(self, c...
from django.shortcuts import render, get_object_or_404 from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin from django.urls import reverse from django.views import generic from communities.models import Community, CommunityMember from django.contrib import messages from . import models #...
import os import json import sys from troposphere import Ref, Template, Parameter, GetAtt, serverless, awslambda, stepfunctions, Sub, events, Output MONGODB_CONNECTION_STRING_PARAMETER = 'MongoDbConnectionString' REDIS_HOST = 'RedisHost' REDIS_PORT = 'RedisPort' REDIS_PASSWORD = 'RedisPassword' def add_parameters(t...
import unittest import homport homport.start() class NodeWrapTestCase(unittest.TestCase): def setUp(self): self.assertTrue('hou' in globals()) def testWrapped(self): self.assertTrue(isinstance(hou.node('/obj'), homport.NodeWrap)) def testInvalidNode(self): self.assertRaises(hompor...
# Author: Christian Brodbeck <christianbrodbeck@nyu.edu> """ Data Representation =================== Data is stored in three main vessels: :class:`Factor`: stores categorical data :class:`Var`: stores numeric data :class:`NDVar`: stores numerical data where each cell contains an array if data (e.g., EEG ...
import sys import os import numpy as np path_dir = '../data/' # CHANGE HERE! file_list = os.listdir(path_dir) file_list.sort() for files in file_list: tmp = np.fromfile(files, dtype=np.float32) prev = tmp[0:3] for i in range(1, int(len(tmp))/4): prev = np.vstack([prev,tmp[4*i:4*i+3]]) ''' ######...
# -*- python -*- import re def get_matching_words( regex ): words = [ "aimlessness", "assassin", "baby", "beekeeper", "belladonna", "cannonball", "crybaby", "denver", "embraceable", "facetious", "flashbulb", "gaslight",...
def debug(s): return s.replace('bugs','=').replace('bug','').replace('=','bugs') ''' Take debugging to a whole new level: Given a string, remove every single bug. This means you must remove all instances of the word 'bug' from within a given string, unless the word is plural ('bugs'). For example, given 'obugob...
# -*- coding: utf-8 -*- """ This is an implementation of Amazon Product Advertising API in Python. Thanks to following. - PyAWS http://pyaws.sourceforge.net/ - python-amazon-product-api http://pypi.python.org/pypi/python-amazon-product-api - ryo_abe http://d.hatena.ne.jp/ryo_abe/20100416/1271384372 "...
from distutils.core import setup from Cython.Build import cythonize setup( name='fast_bcf_parser', ext_modules=cythonize("lib/parsers/unbcf_fast.pyx", #gdb_debug=True ), )
import numpy as np from scipy.integrate import odeint from matplotlib import pyplot as plt import matplotlib as mpl class ModeloAsintomaticos(): def __init__(self, N_0, S_0, I_0, A_0, R_0, lambd, mu, mu_star, gamma, gamma_star, beta_1, beta_2, beta_3, beta_4): assert(N_0 == S_0 + I_0 + A...
""" Construa a função separaPal(string) que recebe como entrada um texto contendo um documento qualquer. A função deve retornar uma lista contendo palavras presentes no texto. Uma palavra é uma sequência de caracteres entre caracteres chamados de separadores. São considerados separadores os seguintes caracteres: Ponto...
""" MIT License Copyright (c) 2018 Rafael Felix Alves Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, pub...
from django.urls import path, re_path, include from . import views urlpatterns = [ path('', views.NewsView.as_view({'get': 'list'})), re_path('detail/(?P<pk>\d+)',views.NewsDetailView.as_view({'get': 'retrieve'})), # path('comment', views.CommentView.as_view({'get':'list','post':'create'})) path('com...
import json from django.contrib.auth.mixins import LoginRequiredMixin from django.http import JsonResponse from django.shortcuts import get_object_or_404 from django.views import View from recipes.models import ( Favorite, Follow, Ingredient, Recipe, ShoppingList, User) class Favorites(LoginRequiredMixin, View)...
import matplotlib.pyplot as plt import math s = math.e seg_length = 1. Nmax = 15000 eps = [0.] phi = [0.] X = [0.] Y = [0.] for step in range(Nmax): epsn = eps[-1] phin = phi[-1] epsnp1 = (epsn+2.*math.pi*s) % (2.*math.pi) phinp1 = epsn + (phin%(2.*math.pi)) eps.append(epsnp1) phi.append(phinp1) X.append(X[-1]...
import calendar import time import hdbfs.db TYPE_NILL = 0 TYPE_FILE = 1000 TYPE_FILE_DUP = 1001 TYPE_FILE_VAR = 1002 TYPE_GROUP = 2000 TYPE_ALBUM = 2001 TYPE_CLASSIFIER = 2002 ORDER_VARIENT = -1 ORDER_DUPLICATE = -2 LEGACY_REL_CHILD = 0 LEGACY_REL_DUPLICATE = 1000 LEGACY_REL_VARI...
sportsList = open('sports.txt') for index in range(1,11): sp = sportsList.readline() if len(sp) >= 8 : print (sp .rstrip())
# # -*- Mode: Python; indent-tabs-mode: nil; tab-width: 4 -*- # ################################################################################ # HEADING ################################################################################ # # Author # The author of the script. # Feature (Optional) # The 'Fea...
""" Tests for captions resources. """ import io import pytest import responses import pyyoutube.models as mds from .base import BaseTestCase from pyyoutube.error import PyYouTubeException from pyyoutube.media import Media class TestCaptionsResource(BaseTestCase): RESOURCE = "captions" def test_list(sel...
# Different occurences of a substring # can overlap one another ex. ATA in CGATATATC # This algorithm is a full proof way to find all substrings # INPUT - full genome string and substring we are looking for # ALGO - reads from input, splices every possible continuous # four letter string, if any of them equal our subs...
from setuptools import setup, find_packages with open("README.md", "r") as readme_file: long_description = readme_file.read() setup( name='SpoofDogg', version='1.0', description='A tool that does ARP poisoning and DNS spoofing.', long_description=long_description, long_description_content_type...
from django.conf.urls import url,include from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.job_list), path('<int:id>',views.job_details), ]
import logging import fmcapi def test__application(fmc): logging.info("Testing Application class.") obj1 = fmcapi.Applications(fmc=fmc) logging.info("All Application -- >") result = obj1.get(limit=1000) logging.info(result) logging.info(f"Total items: {len(result['items'])}") del obj1 ...
# 양수로 이루어진 m x n 그리드를 인자로 드립니다. 상단 왼쪽에서 시작하여, 하단 오른쪽까지 가는 길의 요소를 다 더했을 때,가장 작은 합을 찾아서 return 해주세요. # 한 지점에서 우측이나 아래로만 이동할 수 있습니다. # Input: [ [1,3,1], [1,5,1], [4,2,1] ] # Output: 7 # 설명: 1→3→1→1→1 의 합이 제일 작음 def min_path_sum(grid): x = len(grid) y = len(grid[0]) for i in range(1,x): ...
# create your solar system animation here! import turtle import math class SolarSystem: def __init__(self, height, width): self.sun = None self.planets = [] self.window = turtle.Screen() self.window.tracer(0) self.window.setup(900, 900) self.window.bgcolor("black")...
# -*- coding: utf-8 -*- """ Created on Wed Jan 24 13:41:52 2018 @author: Rafael Rocha """ import sys import time import os import numpy as np import keras import matplotlib.pyplot as plt #import my_utils as ut from sklearn.metrics import classification_report, confusion_matrix from keras.optimize...
import os from os.path import join # Messy counting files in directory # def messy_file_count(directory): # for dirpath, dirs, files in os.walk(directory): # filelist = [] # for f in files: # filelist.append(f) # if len(filelist) == 0: # continue # else: # ...
#!/usr/bin/python import sys import httplib # loope over sites and if anython but 200 or 301 shows sound alarm for site_name in ["prolinuxhub.com", "prolinuxhub.com", "site2.com", # REPLACE WITH YOUR WEBSITES ]: try: conn = httplib.HTTPConnection(site_name) conn.request("HEAD", "/") ...
s=input() a=[int(i) for i in s] sum=0 for i in a: sum+=(i**3) if(sum==int(s)): print("yes") else: print("no")