text stringlengths 8 6.05M |
|---|
VOWELS = frozenset('aeiouAEIOU')
def count_vowels(s=''):
return sum(a in VOWELS for a in s) if isinstance(s, str) else None
|
import sys
import os
import curses
from dataclasses import dataclass
from typing import Optional
@dataclass
class WindowContent:
title: str
subtitle: str
content: str
def main_menu():
return WindowContent("What's new in Python 3.8",
f"Alexander Hagerman DerbyPy November 2019",... |
import torch.nn as nn
import torch
N, D_in, H, D_out = 64, 1000, 100, 10
# 随机创建一些训练数据
x = torch.randn(N, D_in)
y = torch.randn(N, D_out)
model = torch.nn.Sequential(
torch.nn.Linear(D_in, H, bias=False), # w_1 * x + b_1
torch.nn.ReLU(),
torch.nn.Linear(H, D_out, bias=False),
)
torch.nn.init.normal_(model... |
#!/usr/bin/env python
# -*- coding::utf-8 -*-
# Author :GG
# 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
#
# 示例:
#
# 输入: [-2,1,-3,4,-1,2,1,-5,4],
# 输出: 6
# 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
#
#
# 进阶:
#
# 如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。
# Related Topics 数组 分治算法 动态规划
# 👍 2176 👎 0
# leetcode submit re... |
from flask import Flask, request
from flask_cors import CORS
import jsonpickle
from storage import *
app = Flask(__name__)
CORS(app)
#player endpoints
#TODO: Bug fix - 500 error on baseball and softball
@app.route("/player", methods=["GET"])
def Player():
sport = request.args.get("sport")
id = request.args.ge... |
from math import pi
def circleArea(r):
return round(pi * r**2, 2) if isinstance(r, (int, float)) and r > 0 else False
'''
Complete the function circleArea so that it will return the area of a circle with
the given radius. Round the returned number to two decimal places (except for Haskell).
If the radius is not... |
from django.conf.urls import url
from . import views
from django.urls import path
from django.contrib.sitemaps.views import sitemap
from blog.sitemaps import PostSitemap
sitemaps = {
'posts' : PostSitemap
}
urlpatterns =[
path('', views.post_list_view, name='post_list_view'),
path('<int:year>)/<int:month>... |
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly
import pandas as pd
from plotly.graph_objs import *
from dash.dependencies import Input, Output
app = dash.Dash()
data_df = pd.read_csv('https://data.austintexas.gov/api/views/ecmv-9xxi/rows.csv?accessType=DOWNLOAD')
data... |
#일반적 사용
squares = list()
for x in range(10):
squares.append(x**2)
print(squares) #[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
#리스트 컴프리헨션을 사용했을 때
squares = [x**2 for x in range(10)] #x를 정의해줘야 한다
print(squares) #[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]squares
combs = []
for x in [1, 2, 3]:
for y in [2, 3, 4]:
if ... |
a = int(input("ENTER A NUMBER = "))
b = int (input("ENTER A NUMBER = "))
PI = 3.14
select = int(input("chose any one \n 1.square 2. rectangle \n 3. circle "))
if(select == 1 ):
print("Area Of Square = ",a**2)
if(select == 2):
print("AREA OF RECTANGLE = ",a*b)
if(select == 3):
print("AREA OF CIRCLE... |
from django.db import models
class Computer(models.Model):
name = models.CharField(max_length=128)
desc = models.TextField(blank=True)
videocard = models.CharField(max_length=128)
ram = models.CharField(max_length=128)
cpu = models.CharField(max_length=128)
mother_board = models.CharField(max_l... |
""" Contains facies-related functions. """
import os
from copy import copy
from textwrap import dedent
import numpy as np
import pandas as pd
from scipy.ndimage import find_objects
from skimage.measure import label
from ..plotters import plot_image
from ..utils import groupby_min, groupby_max
from ...batchflow impo... |
#!/usr/bin/env python3
import re
import requests
from bs4 import BeautifulSoup
from urllib.request import urlopen
from urllib.parse import urlparse, urljoin
import urllib.error
import numpy as np
import colorama
# init the colorama module
colorama.init()
GREEN = colorama.Fore.GREEN
YELLOW = colorama.Fore.YELLOW
GRAY ... |
import sys
sys.path.append('/usr/local/anaconda3/lib/python3.6/site-packages')
#print(vars())
from numpy import sin
#print(vars())
from numpy import cos, linspace
#print(vars())
#x = linspace(0, 7, 70) #solis = (7-0)/(70-1)
x = linspace(0, 4, 11) #solis = (4-0)/(11-1)
y = cos(x)
y1 = sin(x)
#print(vars())
from ... |
import markovgen
original = open("remezcla.txt", encoding='utf-8')
nuevo = open("mezclota.txt", "w", encoding="utf-8")
newtext = []
mk = markovgen.Markov(original)
counter = 0
while counter < 200:
line = mk.generate_markov_text() + '\n'
exclude = ['"', '(', ')', ';']
line = ''.join(ch for ch in line i... |
LOGIN_FORM_PREFIX = 'login-form'
REGISTER_FORM_PREFIX = 'register-form'
|
list1 = [1,2,3,4,5]
list2 = ['a','b','c']
list3 = [1,'a','abc',[1,2,3,4,5],['a','b','c']]
list1[0] = 6
print(list1) # [6,2,3,4,5]가 출력됨
def myfunc():
print('안녕하세요')
list4=[1,2,myfunc]
list4[2]() # '안녕하세요'가 출력됨
|
import numpy as np
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from Chapter2 import MyTransform_6, downloadData
if __name__ == '__main__':
downloadData.fetch_housing_data()
data = downloadData.load_hou... |
import pytest
a = 0
@pytest.mark.skip(reason='out-of-date api')
def test_connect():
pass
@pytest.mark.skipif(a > 1, reason='out-of-date api')
def test_connect2():
pass
|
#!/usr/bin/python
# coding: utf-8
# haacheuur 0.24
# port industriel de port la nouvelle - couleur - 60cm*30cm
# image source : pln.jpg
# image rendue : pln..20150910-11h59m53s.jpg
import sys
import Image
import random
import os
import ImageDraw
import ImageFont
import ImageFilter
from time import gmtime, strftime
#... |
### ADD BUTTON REGARDING COUNTER. 2 is the last line in counter!
from tkinter import *
import os
import json
from selenium import webdriver
from getpass import getpass
from functools import partial
creds = 'tempfile.temp'# This just sets the variable creds to 'tempfile.temp'
store = 'storefile.json'
global lines#mad... |
# integer
x = 100
print type(x)
if x >= 100:
print "That's a big number!"
else:
print "That's a small number"
# string
y = 'hello world'
print type(y)
if y >= 50:
print 'Long sentence'
else:
print 'Short setence'
z = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
print type(z)
if len(z) >= 10:
print 'Big L... |
import sys
# Modified from cpo example
# https://github.com/chrisvam/psana_cpo/blob/master/hexanode_save_lcls1.py
if len(sys.argv) == 1:
print("Usage: ")
print("source /reg/g/psdm/etc/psconda.sh")
print("python cspad_save_lcls1.py exp run detname n_events xtc_dir")
print("note: use n,m for run n to m... |
''' Like stack, queue is a linear data structure that stores items in First In First Out (FIFO) manner.
With a queue the least recently added item is removed first.
A good example of queue is any queue of consumers for a resource where the consumer that came first is served first.'''
class Queue(obje... |
# Given two integer arrays of equal length target and arr.
#
# In one step, you can select any non-empty sub-array of arr and reverse it.
# You are allowed to make any number of steps.
#
# Return True if you can make arr equal to target, or False otherwise.
class Solution:
def canBeEqual(self, target,... |
import requests, dicttoxml, xmltodict
from xml.dom.minidom import parse
import xml.dom.minidom
from xml.dom.minidom import parseString
import glob
import os, json
import time
# xml 自动化本地测试框架
filepath = 'xml/G2/'
base_url = 'http://124.70.178.153:8082/'
xml_list = glob.glob(os.path.join(filepath, '*.xml'))
for i in ra... |
Part I - What is a wrapper? (not rapper)
A wrapper function is making your code more efficient and DRY (keep it in one language) by wrapping it in a method we can invoke when we need it.
In terms of Python and APIs we want to wrap our api calls in a method so we don't have to fill our code repeating endpoints
when we ... |
#!/usr/bin/env python
"""
v0.1 Go through various "interesting" source resources and re-evaluate epochs, features. classes
Source resources include:
- ptf_09xxx associated sources in source_test_db.caltech_classif_summary
- list of high nobjs sources, which actually have < 2 epochs associated with the... |
import mariadb
def settingUpTables(user, password, host, port):
print("######### Creating tables #########")
try:
conn = mariadb.connect(
user=user,
password=password,
host=host,
port=port,
database="steamscrape")
# initiating Cursor
... |
import requests
from os import getcwd
import os
from git import Repo
import aws_encryption_sdk
# Importants necessary dependencies
ver = 1.3
# version number
keyvalue = []
# creates keyvalue variable
github_dir = "https://github.com/Dithilli/kongappend.git"
working_dir = "./testdir"
def getkey():
key = str(inp... |
# -*- coding: utf-8 *-*
import os
import tornado
from app.helpers import DB
from tornado.options import options as opts
import routes
from app import path
class Application(tornado.web.Application):
def __init__(self):
self.r_db = DB(opts.db_r_host,opts.db_r_port,opts.db_r_name,opts.db_r_user,opts.db_r_... |
import dash_bootstrap_components as dbc
from dash import html
badges = html.Div(
[
html.H1(["Example heading", dbc.Badge("New", className="ms-1")]),
html.H2(["Example heading", dbc.Badge("New", className="ms-1")]),
html.H3(["Example heading", dbc.Badge("New", className="ms-1")]),
ht... |
#!usr/bin/python
from Tkinter import *
import Tkinter
import tkMessageBox
top = Tkinter.Tk()
frame = Frame(top)
frame.pack()
bFrame = Frame(root)
bFrame.pack(side = BOTTOM)
rbut= Button(frame(text="Red", fg="red")
rbut.pack(side=LEFT)
gbut = Button(frame, text="Brown", fg="brown")
gbut.pack(side=LEFT)
bbut = Butt... |
def total_licks(env):
total = 252
max_env = max(env, key=env.get) if env else -1
tc =' The toughest challenge was {}.'.format(max_env) if env.get(max_env)>0 else ''
for x in env:
total-= -env[x]
return 'It took {} licks to get to the tootsie roll center of a tootsie pop.{}'.format(total,tc... |
from django.urls import include, path, re_path
from rest_framework import routers # add this
from .import views
router = routers.DefaultRouter() # add this
router.register(r'home', views.TodoView, 'todo')
urlpatterns = [
path('', include(router.urls))
] |
import uuid
from datetime import datetime
from src.common.database import Database
class Plantation(object):
def __init__(self, typeOfPlantation, typeOfCrop, block, totalPits, workName, totalSanctionedPlants, user_name, user_id,costOfCrops, plantationStatus= 'Open', plantationDate=None, hectre=None, plotNo=N... |
import vrep
import math
from collections import namedtuple
VrepProximitySensorResult = namedtuple('VrepProximitySensorResult', 'detectionState distance detectedPoint detectedObjectHandle detectedSurfaceNormalVector')
class VrepObject(object):
def __init__(self, connection, handle):
self.connection = conne... |
from linker import Linker
from selenium import webdriver
driver = webdriver.Chrome('./chromedriver')
class JSLinker(Linker):
def __init__(self):
pass
def setBoardState(self, board_info):
'''
设置棋盘状态,输入是一个迭代的线性数据结构,不返回任何数据
'''
self.place = board_info[0] * 7 + bo... |
#!/usr/bin/python2.7
#-*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.cm as cm
import matplotlib.image as mpimg
import numpy as np
from matplotlib import rc
from matplotlib import gridspec
plt.rcParams["legend.fontsize"]=35
plt.rcParams["font.size"]=15
rc... |
#!/usr/bin/python3
import unittest
from datetime import datetime, timedelta
import pandas as pd
from pandas.testing import assert_frame_equal
from model.time_series.time_series import TimeSeries
from model.time_series.time_series_row import TimeSeriesRow
class TestTimeSeries(unittest.TestCase):
def test_to_jso... |
from PIL import ImageGrab as IG
import pyautogui as pa
import sys
import os
import time
import re
pa.FAILSAFE = True
sec_between_keys = 0.25
sec_between_term = 3
sec_sleep = 0.5
#스크린샷
def screenGrab():
box = ()
im = IG.grab(box)
im.save(os.getcwd() + '\\img\\full_snap__' + str(int(time.time())) + '.png',... |
print('*****CELSIUS TO FAHRENHEIT CONVERTER*****')
celsius_temp = int(input('Enter the temperature in Celsius: '))
fahrenheit_temp = int(1.8 * celsius_temp + 32)
print(f'Temperature in Fahrenheit is {fahrenheit_temp}˚F')
|
# -*- coding: utf-8 -*-
class Solution:
def findOcurrences(self, text, first, second):
result = []
words = text.split()
for i in range(len(words) - 2):
if words[i] == first and words[i + 1] == second:
result.append(words[i + 2])
return result
if __na... |
#!/usr/bin/python3
# -*- Mode: Python; py-indent-offset: 4 -*-
#
# Copyright (C) 2005,2007 Ray Burr
#
# 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 l... |
import pytest
@pytest.fixture
def dummy_socket():
return DummySocket()
class DummySocket:
def __init__(self):
self.data = [b'hello', b'world', b'']
def recv(self, bufsize):
return self.data.pop(0)
@pytest.fixture
def transport():
return None
|
__author__ = 'SufferProgrammer'
import mysql.connector as mariaDBConnector
class DBase:
def __init__(self):
self.conn = mariaDBConnector.connect(host = '192.168.8.101', user = 'developer', database = 'crud_trial', password='')
self.cur = self.conn.cursor()
def execute(self, comman... |
# Generated by Django 2.0.7 on 2018-07-18 19:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0002_user_is_staff'),
]
operations = [
migrations.AlterField(
model_name='song',
name='artist',
f... |
from ..algorithms.tracker import Tracker
from ..algorithms.utils import Volume
def test_add_volume():
tracker = Tracker()
tracker.add_volume(Volume(0, (5,5,5), (10,10,10)))
assert len(tracker.i_dict.keys()) == 1
assert len(tracker.i_dict[(5,10)]) == 1
assert len(tracker.i_dict[(5,10)][(5,10)]... |
#!/usr/bin/python
# ---------------------------------
# 文件工具方法, 主要包含常见的文件处理方法
# 以及常见的文件存储的方法
# ---------------------------------
import glob
import math
import os
import random
import smtplib
import time
from collections import Counter
from email.header import Header
from email.mime.text import MIMEText
import cv2
im... |
class Solution:
def minimumRounds(self, tasks: List[int]) -> int:
cnt = Counter(tasks)
# print(cnt)
res = 0
for k, v in cnt.items():
if v == 1:
return -1
if v % 3 == 0:
res += v // 3
if v % 3 != 0:
... |
import unittest
from katas.kyu_6.stop_spinning_my_words import spin_words
class SpinWordsTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(spin_words('Welcome'), 'emocleW')
def test_equals_2(self):
self.assertEqual(spin_words('Hey fellow warriors'),
... |
from post_question import generateRandomId
from datetime import datetime
"""-----------------------------------------------------------------
create_answer - Creates an answer
Purpose: Based upon the body provided it creates an answer in the
posts collection
Input: questionId : The id of the question on which we are ... |
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) Qotto, 2019
from .commands import MakeCoffee
from .results import MakeCoffeeResult
from .events import CoffeeStarted
__all__ = [
'CoffeeStarted',
'MakeCoffeeResult',
'MakeCoffee',
]
|
#!/usr/bin/python
from os import environ
print "Content-Type: text/html"
print "Set-Cookie: foo=bar"
print
print """
<table>
<thead>
<tr>
<th>Name</th>
<th>Value</th>
</tr>
</thead>
<tbody>
"""
for x in environ.iteritems():
print "<tr><td>%s</td><td>%s</td></tr>" % x
print """
</tbod... |
"""
Api app views
"""
from django.http import Http404, JsonResponse
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.utils.crypto import get_random_string
from rest_framework import status, viewsets
from rest_framework.decorators import action, api_view, permission_classes
from... |
# -*- coding: UTF-8 -*-
#
# generated by wxGlade 0.8.0b3 on Fri Feb 23 22:28:04 2018
#
import wx
# begin wxGlade: dependencies
# end wxGlade
# begin wxGlade: extracode
# end wxGlade
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
# begin wxGlade: MyFrame.__init__
kwds["style"] = kwd... |
import json
from flask import Flask, make_response, request
import bot
from config import CONFIG
from storage import create_tables, get_or_create_event_log, create_user_message_reaction_log
from utils import hash_data
app = Flask(__name__)
pyBot = bot.Bot()
slack = pyBot.client
def _event_handler(event_type, slack... |
from common.run_method import RunMethod
import allure
@allure.step("极运营/系统设置/优惠设置/优惠券/查看单个学生优惠券操作记录")
def coupon_queryOperationRecordByCouponItemId_get(params=None, header=None, return_json=True, **kwargs):
'''
:param: url地址后面的参数
:body: 请求体
:return_json: 是否返回json格式的响应(默认是)
:header: 请求的header
... |
import numpy as np
import pandas as pd
# import datetime
def transform_cols (df, dict_col_types = None):
# Расширяйте для необходимых столбцов и их явной типизации
if dict_col_types is None:
dict_col_types = {
'amount_original':(float, 0.0),
'cdf_s_126':(str, u'null'),
'cdf_s_1... |
# encoding.py
# Copyright (C) 2011-2014 Andrew Svetlov
# andrew.svetlov@gmail.com
#
# This module is part of BloggerTool and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from bloggertool.exceptions import UnknownDocType
MARKDOWN = 'Markdown'
REST = 'ReST'
def find_type(f):... |
{
'target_defaults': {
'xcode_settings': {
'SYMROOT': '<(DEPTH)/$SRCROOT/',
},
},
}
|
from math import *
path = [[0,0],
[0,1],
[0,2],
[1,2],
[2,2],
[3,2],
[4,2],
[4,3],
[4,4]]
def smooth(path, weight_data=0.5, weight_smooth=0.1, tolerance=0.000001):
#deep copy into newpath
newpath = [[0 for row in range(len(path[0]))] for col in r... |
from flask_dance.consumer.storage.sqla import OAuthConsumerMixin
from flask_login import UserMixin
from flask_security import RoleMixin
from sqlalchemy import (
Boolean, Column,
ForeignKey, Integer, PickleType, String, Table
)
from sqlalchemy.orm import relationship, synonym
from bitcoin_acks.database.base imp... |
import sys
from tuntap import Packet,TunTap
import optparse
from _thread import start_new_thread
import traceback
def readtest(tap):
while not tap.quitting:
p = tap.read()
if not p:
continue
if tap.nic_type == "Tap":
packet = Packet(frame=p)
else:
... |
#libraries
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
R = np.arange(-4, 4, 0.1)
X, Y = np.meshgrid(R, R)
Z = np.sum(np.exp(-0.5 * (X**2 + Y**2)))
P = (1/Z) * np.exp(-0.5 * (X**2 + Y**2))
invalid_xy = (X**2 + Y**2) < 1
P[invalid_xy] = 0
fig = plt.figure(figsize=(10,6))... |
import json
import boto3
def boto3_client(resource):
"""Create Boto3 client."""
return boto3.client(resource)
def s3_add_tags(tags):
boto3_client('s3').put_bucket_tagging(
Bucket='dmansfield-dev',
Tagging=tags
)
def main():
dev_tags_file = open('test.json')
dev_tags = json.l... |
def loadPassphrases():
phrases = []
with open('../inputs/day4.txt', 'r') as phraseFile:
line = phraseFile.readline()
while line:
phrases.append(line[:-1].split(' '))
line = phraseFile.readline()
return phrases
def validPhraseCount(phrases):
filteredPhrases = ... |
from django.urls import path
from . import views
urlpatterns = [
path('',views.index, name='index'),
path('profile/<int:officer_id>/',views.profile, name='profile'),
path('add', views.add_review, name='add_review'),
path('search', views.search, name='search'),
]
|
import logging
import fmcapi
def test__geolocations(fmc):
logging.info("Testing Geolocation class. Requires a configured Geolocation")
obj1 = fmcapi.Geolocation(fmc=fmc)
logging.info("All Geolocation -- >")
result = obj1.get()
logging.info(result)
logging.info(f"Total items: {len(result['item... |
from django.conf.urls import patterns, include, url
# from django.contrib import admin
# admin.autodiscover()
from apps.jobs import views as jobviews
urlpatterns = patterns('',
url(r'^calendar/events/$', jobviews.events, name='jobCalendarEvents'),
url(r'^calendar/$', jobviews.calendar, name='jobCalendar'),
... |
import numpy as np
from utils.utils import Utils
class Score(object):
def scoreData(self, weights, indepData,layers, depData = None, isError = False):
self.utils = Utils()
thisInput = indepData
scores = {}
error = None
self.layers = layers
scores[0] = indepData
... |
"""
Generates polynomial from secret string with use of CRC encoding
"""
from bitstring import BitArray
import binascii
from Galois.Galois_Converter import GaloisConverter
from Galois.Galois_Field import GF
class PolynomialGenerator:
def __init__(self, secret_bytes, degree, crc_length, gf_exp):
"""
... |
# Bubble sort algorithm
# Very straightforward to implement in code.
# Merge, Quick and Heap are more complicated.
# Iterate multiple times, and initiate swaps to correct order.
# Check if the curr and curr + 1 are in correct order.
# If sorted, we move on, else we swap their position.
# Eg. [8, 5, 2, 9, 5, 6, 3]
# ... |
from .. import list_segments, list_segments_by_coordinates
def test_list_segments():
# As of April 2020 there were more than 900 active segments.
segments = list_segments()
assert len(segments) > 900
def test_list_segments_by_coordinates():
# As of April 2020 there are more than 30 active segments i... |
import requests
from pprint import pprint
url = f"https://api.github.com/users?"
data = requests.get(url).json()
for i in data:
f = open("User_List.txt", "a")
f.write(i['login'])
f.write("\n")
f.close()
|
# Standard Python libraries
from __future__ import (absolute_import, print_function,
division, unicode_literals)
from collections import OrderedDict
# https://github.com/usnistgov/DataModelDict
from DataModelDict import DataModelDict as DM
# http://www.numpy.org/
import numpy as np
# https://... |
"""apps"""
from django.apps import AppConfig
class YbAppConfig(AppConfig):
"""app config"""
name = 'yb_app'
|
import unittest
from katas.kyu_7.distance_from_the_average import distances_from_average
class DistancesFromTheAverageTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(distances_from_average([55, 95, 62, 36, 48]),
[4.2, -35.8, -2.8, 23.2, 11.2])
def test_e... |
"""
steam.py
purpose: steam API integration to look up steam game information
"""
import re
import asyncio
import aiohttp
import discord
import json
from discord.ext import commands
#to check how similiar two strings are
from difflib import SequenceMatcher
#functions to make accessor functions easier and faster f... |
# 6063
a, b = input().split()
a = int(a)
b = int(b)
c = (a if a >= b else b)
print(c)
# 6064
# 잘 안됨 ㅜ
# 6065
a, b, c = input().split()
a = int(a)
b = int(b)
c = int(c)
if a % 2 == 0:
print(a)
if b % 2 == 0:
print(b)
if c % 2 == 0:
print(c)
# 6066
a, b, c = input().split()
a = int(a)
b = int(b)
c = int(c)... |
# Endi "while" operatoriga to'xtatlsak while operatori bu takrorlash operatoridir
# shu while ko'prastilgan shartgacha ya'ni xolatgacha takrorla shunga yetganda to'xta degani
i=1
while i<=10:
print(i)
i=i+1 # bu degani i ga bittadan oshirib boraver degani 1,2,3,4,.......
else:
print("Done") |
# -*- coding:utf-8 -*-
"传入所有中继设备的信息和选择的中继设备编号"
def Fairness(UES):
#计算当前状态的设备的公平状态
U_total = 0
U_link_s = 0
for i in range(0,len(UES)):
U_total += UES[i].gains
U_link_s += (1-UES[i].link_e)
X=[]
for i in range(0,len(UES)):
Ui_overline = ((1-UES[i].link_e)/U_l... |
# Reverse Engineering
# Lab 5, script 2
# Jeremy Mlazovsky
print "Hello Lab5\n"
from idaapi import *
from idc import *
class MyDbgHook(DBG_Hooks):
""" Own debug hook class that implementd the callback functions """
def dbg_process_start(self, pid, tid, ea, name, base, size):
print "Process started, pid=%d tid=... |
import pandas as pd
from sklearn.utils import shuffle
DATA_PATH = "./DataSet/"
REPOSITORY = "/On_Time_On_Time_Performance_"
CSV_PATH = "/On_Time_On_Time_Performance_"
useless1 = ["Quarter","UniqueCarrier","Carrier","TailNum","FlightNum","OriginAirportSeqID","Origin","OriginCityMarketID","OriginCityName","OriginStateFi... |
from django.db import models
class Quote(models.Model):
text = models.TextField()
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
owner = models.ForeignKey('auth.User', related_name='quotes')
class Meta:
ordering = ('-created',)
|
#!/usr/bin/env python3
"""prelockd"""
import os
import mmap
from re import search
from sre_constants import error as invalid_re
from time import sleep, monotonic, process_time
from sys import stdout, stderr, exit, argv
from signal import signal, SIGTERM, SIGINT, SIGQUIT, SIGHUP
from ctypes import CDLL
def valid_re(r... |
from django import template
register = template.Library()
@register.filter
def to_stroke_dashoffset(value):
return int(402 * (1 - value)) |
def odczyt_pliku(jezyk, plik):
a = open('TrescMaila/'f'{jezyk}''/'f'{plik}', mode='r', encoding='utf8', newline='\r\n')
return a.read()
def odczyt_zalacznika(jezyk, plik):
return open(f"TrescMaila/{jezyk}/{plik}", 'rb')
|
import unittest
from types import FunctionType
from katas.beta.string_repetition_without_function import str_repeat
class StrRepeatTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(str_repeat('a', 4), 'aaaa')
def test_equal_2(self):
self.assertEqual(str_repeat('hello ', 3... |
# Generated by Django 2.2.4 on 2019-09-14 13:48
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('webapp', '0006_auto_20190914_1907'),
]
operations = [
migrations.DeleteModel(
name='Library',
),
]
|
import os
from dotenv import load_dotenv
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
load_dotenv()
SENDGRID_API_KEY = os.getenv("SENDGRID_API_KEY")
MY_ADDRESS = os.getenv("MY_ADDRESS")
#print(MY_ADDRESS, SENDGRID_API_KEY)
client = SendGridAPIClient(SENDGRID_API_KEY) #> <class 'send... |
from RPi import GPIO
import spidev
import time
class MCP3008:
def __init__(self,spi):
self.spi = spi
spi.open(0,0)
spi.max_speed_hz = 10**5
def read_channel(self, channel):
adc = self.spi.xfer2([1,(8+channel)<<4,0])
data = ((adc[1]&3) << 8) + adc[2]
return data |
from common.run_method import RunMethod
import allure
@allure.step("JkyAPP/查询学生")
def students_studentInfo_get(params=None, header=None, return_json=True, **kwargs):
'''
:param: url地址后面的参数
:body: 请求体
:return_json: 是否返回json格式的响应(默认是)
:header: 请求的header
:host: 请求的环境
:return: 默认json格式的响应, re... |
import numpy as np
import pandas as pd
from scipy.stats import norm
from r.ts.adf import adf_r
from r.ts.arima import arima_r
from r.ts.kpss import kpss_r
from r.ts.smuce import smuce_r
from r.ts.stl import stl_r
### multiscale change-point inference
### see reference Sieling14
# x : pd.Series
# alpha : float
# -> ... |
import telebot
from telebot import types
import config
class Bot:
""" Singleton class to create bot object """
__instance = None
def get_instance():
if Bot.__instance is None:
Bot()
return Bot.__instance
def __init__(self, proxy=False):
if Bot.__instance is n... |
# -*- coding: utf-8 -*-
"""Tests for output writers."""
import unittest
from dtformats import output_writers
from tests import test_lib
class StdoutWriterTest(test_lib.BaseTestCase):
"""Stdout output writer tests."""
def testClose(self):
"""Tests the Close function."""
test_writer = output_writers.Std... |
from django.urls import path, re_path
from . import views
urlpatterns = [
path("banner/", views.BannerListAPIView.as_view())
]
|
#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from urlparse import urlparse, parse_qs
from Controller import Controller
import logging
import json
PORT_NUMBER = 7777
#This class will handles any incoming request from
#the browser
class myHandler(BaseHTTPRequestHandler):
#Handler f... |
import shout
import time
import sys
class RadioConnectionException(Exception):
pass
class RadioPlayer():
def __init__(self, host="localhost", port=8501, user='source', password='hackme', mount='/mymout'):
self._s = shout.Shout()
self._s.host = host
self._s.port = port
self._s... |
from pprint import pprint
# from sudoku import pretty_repr
import sys
import numpy as np
# SAT dependencies
from pysat.formula import CNF
from pysat.solvers import MinisatGH
# CSP dependencies
from ortools.sat.python import cp_model
# ILP dependencies
import gurobipy as gp
from gurobipy import GRB
# ASP dependencie... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.