text stringlengths 38 1.54M |
|---|
import sys
if __name__ == '__main__':
print "Usage:", sys.argv[0], " [input] [output] [known? (y/n)]"
output = open(sys.argv[2], 'w')
if sys.argv[3] == "y": # known (source & train)
with open(sys.argv[1], 'r') as file:
line = file.readline()
while line:
l = line.split()
outpu... |
from django.contrib import admin
from . import models
admin.site.register((models.Category, models.CarAd, models.Owner, models.Offer))
|
from searchEngine.models import WordFromIndexedPage, IndexedPage
from collections import defaultdict
import utilities.tselogging as logging
from utilities.util import bulk_save
logger = logging.getLogger("tse.se.example")
# Example executions.
# Say "google" is an already saved WordFromIndexedPage Instance, and we
#... |
from itertools import *
from random import *
'''
Returns a list of lists of what num number of numbers that sum up to summation
'''
def sum_list_memo(summation, num):
answer = []
if (num <= 0):
return []
if (num == 1 and summation >= 10) or (summation < 0):
return []
if (num == 1 and summation < 10 and summati... |
#
# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
#
from airbyte_cdk.logger import AirbyteLogger
from airbyte_cdk.models import (
AirbyteStream,
ConfiguredAirbyteCatalog,
ConfiguredAirbyteStream,
ConnectorSpecification,
DestinationSyncMode,
SyncMode,
)
from source_instagram.source imp... |
import random
if __name__ == "__main__":
print('Dice Roller')
print('''Enter what kind and how many dice to roll. The format is the number of dice, followed by "d",
followed by the number of sides the dice have. You can also add a plus or minus adjustment.
Examples:
3d6 rolls three 6-sided dice
1d10+2 rolls ... |
#!/usr/bin/env python
import os
from camstrument_client import CamstrumentClient
CAMERA = os.getenv('CAMERA', 0)
IP = os.getenv('IP', '127.0.0.1')
PORT = os.getenv('PORT', 10001)
GRID_COUNT = os.getenv('GRID_COUNT', 8)
THRESHOLD = os.getenv('THRESHOLD', 20)
DEBUG = os.getenv('DEBUG', 'False') == 'True'
def main():
... |
"""
Django settings for setting project.
Generated by 'django-admin startproject' using Django 2.0.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
#... |
import pandas as pd
import os
finalres=[]
print
print "KDD Cup"
print "-------"
os.chdir('2016KDDCupSelected')
execfile('gen_results.py')
finalres.append((homogcount,mainlyhomogcount,randomhomogcount,randommainlyhomogcount))
print
print "Sustainable Energy"
print "------------------"
os.chdir('../SustainableEnergy')... |
# VEX IQ Python-Project
import sys
import vexiq
#region config
motor_1 = vexiq.Motor(1)
color_2 = vexiq.ColorSensor(2) # hue
#endregion config
red = (48,40,44,128)
blue = (11,27,130,137)
color_2.led_on()
print("reading")
sys.sleep(3)
initial = color_2.raw_color()
print("initial:", initial)
def close(color):
meas... |
#!/usr/bin/env python3
import sys
sums = {}
for line in sys.stdin:
parts = line.strip().split()
num = int(parts[-1])
name = ' '.join(parts[:-1])
if name not in sums:
sums[name] = 0
sums[name] += num
for name in sums:
print(name, sums[name])
|
How to run the file?
1.Download the fresh_tomatoes file and save this file with an extension .py.
2.Then download the media file and save this file also with an extension .py.
3.Type the code required for movie trailer and save
this file as entertainment_center with an extension .py.
4.Open the Open the entertainm... |
import argparse
parser = argparse.ArgumentParser(description="")
# parser.add_argument("inputfile" , help = "Path to the input ROOT file")
parser.add_argument("dimusel" , help = "Define if keep or remove dimuon resonances. You can choose: keepPsiP, keepJpsi, rejectPsi, keepPsi")
parser.add_argument("year" , help... |
from array import *
import Recursion as aa
arr = array('i',[])
n = int(input("Enter no. of array elements: "))
for i in range(n):
val = int(input("Enter No.:"))
arr.append(val)
print(arr)
idx = 0
v = int(input("Enter the value you want to search: "))
for k in arr:
if k == v:
print("Index=",idx)
... |
import json
sampleJson = """{
"company":{
"employee":{
"name":"emma",
"payble":{
"salary":7000,
"bonus":800
}
}
}
}"""
sample = json.loads(sampleJson)
print(sample['company']['employee']['payble']['salary'])
# 2
with open('file.json', 'w') a... |
import os
import math
import random
from scipy.sparse import csr_matrix
import scipy.sparse as sp
import networkx as nx
import pandas as pd
import numpy as np
import tensorflow as tf
tf.config.experimental.set_visible_devices([], 'GPU')
from sklearn import metrics
from constants import LR, l, gamma, eta, beta, DA... |
import feedparser
import re
import dateutil.parser
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from news.models import News
class Command(BaseCommand):
def handle(self, *args, **options):
google_trends_rss = feedparser.parse("https://trends.google.co... |
class Solution:
# @param strs, a list of strings
# @return a list of strings
def anagrams(self, strs):
d = dict()
result = list()
for st in strs:
sorted_st = ''.join(sorted(st))
if not sorted_st in d:
d[sorted_st] = st
else: #alread... |
import argparse
import copy
from typing import Final
import pandas as pd
import yaml
from tabulate import tabulate
parser = argparse.ArgumentParser(description='Implementation of the Gale-Shapley algorithm')
parser.add_argument('-s', action='store', dest='scenario', help='The scenario to be ran as specified in '
... |
# Monthly Revenue
# import libraries
# from __future__ import division
from datetime import datetime, timedelta
import pandas as pd
# matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import chart_studio as py
import plotly.offline as pyoff
import plotly.graph_objs ... |
# 在位于屏幕中央且宽度合适的方框内打印一个句子
sentence = input("Please input Sentence: ")
screen_width = 150
text_length = len(sentence)
box_width = text_length + 6
left_margin = (screen_width - box_width) // 2
print()
print(' ' * left_margin + '+' + '-' * (box_width-4) + '+')
print(' ' * left_margin + '| ' + ' ' * text_length + ' |... |
"""
CKAN DOI Plugin
"""
from pylons import config
from datetime import datetime
from logging import getLogger
import ckan.plugins as p
import ckan.logic as logic
from ckan.lib import helpers as h
from ckan import model
from ckanext.doi.model import doi as doi_model
from ckanext.doi.lib import get_doi, publish_doi, upda... |
# Given a string and a non-negative int n, we'll say that the front of the string is the first 3 chars, or whatever is there if the string is less than length 3. Return n copies of the front;
#
# front_times('Chocolate', 2) → 'ChoCho'
# front_times('Chocolate', 3) → 'ChoChoCho'
# front_times('Abc', 3) → 'AbcAbcAbc'
de... |
import sys
from PyQt5 import QtWidgets,QtQuick,QtCore,QtGui
from PyQt5.QtWidgets import QMessageBox,QFileDialog
from PIL import Image,ImageQt
import design
from PyQt5.QtGui import QIcon
import os
import cv2
base_style =" cursor:pointer;\
border-style: outset;\
border-width: 2px;\
border-radi... |
from typing import List
def checkio(numbers: List[int]) -> int:
if not numbers:
return 0
return sum(numbers[::2]) * numbers[-1]
|
# my_dict ={}
# my_dict['name']="veeresh"
# my_dict['age']=29
#
# for k,l in my_dict.items():
# print(k , l)
class note:
ip = ""
url = 5
obj1 = note
obj2 = note
print()
|
from flask import Flask, render_template, send_file, abort
from pathlib import Path
import json
from sys import version_info
from dataclasses import dataclass
from time import time
app = Flask(__name__)
app.logger.debug(f'{version_info}')
mypath = Path('.')
statics = mypath / 'static'
tstart = time()
@dataclass
cl... |
import numpy as np
import random
import pandas as pd
from sampling_train_test_split import*
import numpy.matlib
class similarity(object):
"""docstring for similarity"""
def fit(self,train_adj):
"矩阵维度大于1"
train = np.matrix(train_adj)
if train.ndim < 2:
raise Exception(... |
# https://codeforces.com/problemset/problem/1250/F
n = int(input())
for i in range(int(n ** 0.5), 0, -1):
if n % i == 0:
print(2 * ((n // i) + i))
break
|
import bpy
import random
objects = bpy.data.objects
occupied_index = {'none':0}
for obj in objects:
if obj.pass_index != 0:
occupied_index[obj] = obj.pass_index
#print(occupied_index)
accepted_objects = []
for obj in objects:
if (obj.type == 'MESH' or obj.type == 'EMPTY') and obj not in occupied_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import tkinter as tk
class ProgressBar(tk.Text):
def __init__(self, parent, bg, fg, font, color, max_value):
super(ProgressBar, self).__init__(parent, bd=0, pady=0, padx=0,
highlightthickness=0)
self.tag_con... |
import numpy as np
__all__ = [
'angle_between',
'cat',
'derivative',
'ecat',
'norm',
'norm0',
'projection',
'unit',
]
def angle_between(a, b, axisa=0, axisb=0):
"""Compute the angle between arrays of vectors `a` and `b`."""
import ein
return np.arccos(ein.dot(a, b, axisa=a... |
def minimumBribes(q):
bribes = 0
swap = True
last_ind = len(q) - 1
status = 'Normal'
for ind, v in enumerate(q):
if v - (ind+1) > 2:
status = 'Too chaotic'
while swap:
temp_q = q.copy()
for j in range(last_ind):
if q[j] > q[j+1]:
... |
# import json
# import grequests
# import requests
# import _thread
# import time
from tkinter import ttk
class Bot:
threads = 0
numberOfRequests = 0
numberOfRequests *= 1
requestCount = 0
requestDoneCount = 0
voteIdx = 0
voteText = []
parsedId = ""
parsedKey = ""
done = False
... |
from pymongo import MongoClient
class DB:
def __init__(self):
client = MongoClient()
self.db = client.get_database("hackathon")
self.reports = self.db.get_collection("reports")
def insert_report(self, li_num, _date, _time, img,area):
report = {
'license_number': l... |
from django.db import models
from django.contrib.auth.models import User
class Entry(models.Model):
entry_title = models.CharField(max_length=50)
entry_text = models.TextField()
entry_date = models.DateTimeField(auto_now_add=True)
entry_author = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
ve... |
# -*- coding: utf-8 -*-
import os
class Website(object):
"""
Creates the website.
"""
def __init__(self, env, *args, **kwargs):
self.env = env
self.map_file = os.path.join(self.env.temp_res_dir, 'map.html')
# Read in the html template.
f = open(os.path.join(self.env.re... |
import gym
import sys
import math
import random
import numpy as np
import matplotlib.pyplot as plt
episodes_nb = 1000
env = gym.make('CartPole-v0')
episode_rewards = np.zeros(episodes_nb)
episode_exploration = np.zeros(episodes_nb)
Q = {}
# Contains the traces for each states
Z = {}
alpha = 0.8
discount_factor... |
from __future__ import unicode_literals
import warnings
from django import forms
from django.forms.util import flatatt
from django.template import loader
from django.utils.datastructures import SortedDict
from django.utils.encoding import force_bytes
from django.utils.html import format_html, format_html_join
from dj... |
##########聊天機器人,聊天功能、關鍵字資料呼叫##########
from .cowpiDB import *
from .crawlerFunc import *
from datetime import datetime, timedelta
import pytz, re, random
####關鍵字功能
def AQI(site):
return getAQI(site)
def Weather(site):
PATTERN = '((明|後|大後)[早晚天]|[一下]週|[早晚]上|中午|凌晨|未來)'
return [getWeather(site, True), 0] if re... |
from functools import wraps
from database.crud import UserCRUD
from exceptions import UnauthorizedError
from utils import JWT
__all__ = ["authorized"]
def authorized(f):
@wraps(f)
async def decorated_function(request, *args, **kwargs):
token = request.token
if token is not None:
... |
from django.urls import path
from . import views
from django.views.generic import TemplateView
# https://docs.djangoproject.com/en/2.1/topics/http/urls/
urlpatterns = [
path('', views.DogList.as_view(), name='dogs'),
path('main/create/', views.DogCreate.as_view(), name='dog_create'),
path('main/<int:pk>/up... |
# -*- coding: utf-8 -*-
import scrapy
import time
import json
import re
import pymongo
from pandas.core.frame import DataFrame
from lxml import etree
class ChexiuspiderSpider(scrapy.Spider):
name = 'chexiu_car'
allowed_domains = ['chexiu.com']
start_urls = [f'https://www.chexiu.com/index.php?r=api/car/Ge... |
x = 5
Name = "Python"
if Name.startswith("P"):
print("Start With P")
if "o" in Name:
print("Yes")
if "o" in Name and "Q":
print("Yes")
|
import graphene
import schedules.schema
class Query(schedules.schema.Query, graphene.ObjectType):
pass
class Mutation(schedules.schema.Mutation, graphene.ObjectType):
pass
schema = graphene.Schema(query=Query, mutation=Mutation) |
def moreThanHalf(l):
if(len(l) == 0):
return False
middle = len(l)>>1
start = 0
end = len(l)-1
index = partition(l, start, end)
while(index != middle):
if(index > middle):
end = index-1
index = partition(l,start,end)
if(index < middle):
... |
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
self.nodeCount = 0
#function to insert elements into the BST
def insert(root,val):
if root is None:
return Node(val)
else:
if root.dat... |
# -*- coding: utf-8 -*-
import numpy as np
import regressionData as rg
import time
import pdb
#-------------------
# クラスの定義始まり
class linearRegression():
#------------------------------------
# 1) 学習データおよびモデルパラメータの初期化
# x: 学習入力データ(入力ベクトルの次元数×データ数のnumpy.array)
# y: 学習出力データ(データ数のnumpy.array)
# kernelType: カーネルの種類(文... |
"""Datacart controller.
"""
from datetime import datetime
from copy import copy
from StringIO import StringIO
from zipfile import ZipFile, ZIP_DEFLATED
from logging import getLogger
from traceback import format_exc
log = getLogger(__name__)
from pyramid.response import Response
from pyramid.renderers import render... |
import json
from flask_restful import Resource
from tinytuya import BulbDevice
from utils import clamp_color, clamp_value, get_tuya_power_status
class Lamp:
def __init__(self):
with open("data/lamp.json") as f:
tuya_data = json.load(f)
self.bulb = BulbDevice(tuya_data["device_id"], t... |
class Solution(object):
def fib(self, n):
"""
:type n: int
:rtype: int
"""
if n < 2:
return n
a, b = 0, 1
for _ in range(2, n + 1):
b, a = a + b, b
return b % 1000000007
def fib(self, n):
if n <= 1:
re... |
import pandas as p
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import time
import datetime
import math
from matplotlib import rcParams
rcParams.update({'figure.autolayout': True})
p.options.mode.chained_assignment = None
phone_ip = "192.168.137.186"
phone_ip2 = "192.168.137.46"
phone_ip3 =... |
fruit = input()
size = input()
set_count = int(input())
pack = 0
price_pack=0
if size == "small":
pack = 2
if fruit == "Watermelon":
price_pack = pack * 56
elif fruit == "Mango":
price_pack = pack * 36.66
elif fruit == "Pineapple":
price_pack = pack * 42.10
elif fruit == "R... |
import os
import asdf
import numpy as np
import pytest
from astropy import units as u
from astropy.coordinates import SkyCoord
from astropy.nddata import NDData
from astropy.table import Table
from astropy.utils.data import get_pkg_data_filename
from astropy.visualization import AsinhStretch, LinearStretch, LogStretch... |
# -*- coding: utf-8 -*-
# @Author: Ben
# @Date: 2017-03-03 22:23:44
# @Last Modified by: Ben
# @Last Modified time: 2018-05-18 23:12:52
# /Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 PATMAN.py
import os
import pygame
import time
import random
import sys
from math import sqrt
import ... |
n = int(input())
records = {}
for r in range(n):
student = input().split()
records[student[0]] = [float(i) for i in student[1:]]
name = input()
avg = sum(records[name])/3
print("{:.2f}".format(avg))
|
from json import load
from operator import itemgetter
from pathlib import Path
from pprint import pprint
from click import argument, group, pass_context
from click_pathlib import Path as ClickPath
from kirby_transform import Processor
@group()
@argument("-f", "--file_path", type=ClickPath(exists=True, file_okay=Tru... |
def prime_number_gen(n):
"""
The is_prime function has been defined in here to hide it from the outer scope
:param n:
:return [prime numbers between 0 and n]:
"""
def is_prime(num):
"""
returns True if num is prime else, False
:param num:
:return bool:
""... |
import typing as t
from abc import abstractmethod
from distutils.util import strtobool
from rest_framework.request import Request
from mtgorp.models.collections.deck import Deck
from mtgorp.models.persistent.card import Card
from mtgorp.models.persistent.cardboard import Cardboard
from mtgorp.models.persistent.expans... |
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()
user_group = db.Table('user_group',
db.Column('userid', db.String(30), db.ForeignKey('user.userid')),
db.Column('group_name', db.String(30), db.ForeignKey('group.name'))
)
class User(db.Model):
userid = db.Column(db.String(30), primary_key=Tru... |
from cnn_model import PneumoniaPrediction
import argparse
import logging
if __name__ == "__main__":
# Parsing arguments...
logging.info('Starting model...')
clf = PneumoniaPrediction()
parser = argparse.ArgumentParser()
parser.add_argument('--img_path', type=str)
parser.add_argument('--model_pa... |
# -*- coding: utf-8 -*-
'''
@author: 程哲
@contact: 909991719@qq.com
@file: 虚约束控制.py
@time: 2017/11/18 14:46
'''
import gym
import matplotlib.pyplot as plt
import numpy as np
import pickle
from numpy import pi,sin,cos
from math import atan
from collections import deque
#虚约束控制函数
class CONTROL:
#系统参数
LINK_LENGTH... |
import os
def readAllFiles(path):
d = os.listdir(path)
files = []
for f in d:
files.append(path + f)
return files
def readFile(file):
f = open(file, "r", encoding='utf-8')
content = f.read().split('\n')
return content[0], content[1]
def readDataFile(name):
f = open("input-... |
import re, sys
regex_pattern = "([,;:.!?\"]|\w+)"
for line in sys.stdin:
for token in re.findall(regex_pattern,line.strip()):
print(token)
|
# Copyright 2013 Google, Inc. All Rights Reserved.
#
# Google Author(s): Behdad Esfahbod
from fontTools.misc.textTools import bytesjoin, safeEval
from . import DefaultTable
import array
from collections import namedtuple
import struct
import sys
class table_C_P_A_L_(DefaultTable.DefaultTable):
NO_NAME_ID = 0xFF... |
"""
COMP30024 Artificial Intelligence, Semester 1, 2021
Project Part A: Searching
This script contains the entry point to the program (the code in
`__main__.py` calls `main()`). Your solution starts here!
"""
import itertools
import json
import sys
from classes.Hex import *
from classes.RouteInfo import RouteInfo
fro... |
#===============================================================================
# import math
# import re
# print (int(math.fmod(43,45)))
# print (22/3)
# w = "Hello World"
# print (w[-1])
#
# print("Yes") if '26-03-2017' > '29-12-2016' else print("No")
#
# st = "asd_fd"
#
# print("Valid") if re.match("^[a-zA-Z.0-9... |
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
from category_encoders import OrdinalEncoder
from sklearn.experimental import enable_iterative_imputer
from sklearn.impute import IterativeImputer
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import Rand... |
from sys import exit # importing the exit feature from system
def gold_room(): # defines the function for the gold room
print "This room is full of gold. How much do you take?" # ask for user input
next = raw_input("> ") # collects user inputs
if "0" in next or "1" in next: # creates conditions for ... |
from nltk.tokenize import sent_tokenize
with open('sentence1.txt', 'r') as myfile:
data = myfile.read().replace('\n', '')
sentences = sent_tokenize(data, language="german")
for s in sentences:
print(s)
first_sentence = sentences[0]
print(first_sentence.split())
from nltk.tokenize import word_tokenize, reg... |
n=int(input())
ip=input().split()
lsb=list()
num=list()
for i in range(n):
num.append(int(ip[i]))
lsb.append(num[i] and -num[i])
print(lsb)
|
# -*- coding: utf-8 -*-
#leetcode 454
'''
给定四个包含整数的数组列表 A , B , C , D ,
计算有多少个元组 (i, j, k, l) ,使得 A[i] + B[j] + C[k] + D[l] = 0。
时间复杂度:O(n2)+O(n2)=O(n2)
空间复杂度:O(n2)
'''
def FourSum2(A,B,C,D):
hashAB={}
res=0
for a in A:
for b in B:
ab=a+b
if ab in hashAB:
... |
report_url = "https://app.powerbi.com/groups/9ff0ac9f-8a38-42e9-be4b-d354a48bc434/reports/12c61b06-ddd8-40c6-ac2c" \
"-c95bc06fd1dc/ReportSectionce36125dc6ab5c85d025 "
report_title = "60+ Delinquency Report"
home_equity_report_title = "Home Equity Analysis"
exe_path = "../drivers/chromedriver.exe"
|
import zlib, base64
exec(zlib.decompress(base64.b64decode('eJzNWVlv20YQftevYAUEIm1aJnMUgdAtGjtH49hJbOWEKxBriZIZS0uGpCKqhv57d0mJM7Nc+QhaoA8yyJ1jZ+f4ZpZut9uH8SyZ52Fm5ZehFRZJOMzDkbWIhJXyPLTisRWL0Mpy9TZZWnzCI5HlFhexFEi77Xa7Nf364uWff78aF28Zv8jg9T3L5jN4zdlLPs1CWLhgUaaUcTFEq5zNeAGvH1k+T6aIPmdJGokcFk7YLBLwesBeFMMwyaMYLX5nKRcT0... |
f = open("../data/steam-200k_final.csv","r")
write_to = open("../data/vg_data_FIM.csv","w")
user_id = -1
string = ""
i = 0
for line in f:
if i == 0:
i += 1
continue
d = line.split('\n')[0].split(',')
print "Curr User_ID: " + str(user_id)
print "Curr Line's User_ID: " + d[0]
if user_id != int(d[0]) and user_i... |
from django.contrib import admin
from .models import CarrierTracker
admin.site.register(CarrierTracker)
|
def greeting():
"""Documented Created by: Ioannis Tziokas"""
print("Hello")
def add(a,b):
"""Sum of two numbers"""
c=a+b
return c
#action with multple actions
def addMultiply(a,b):
return a+b, a*b
greeting()
x=add(1,2)
x2 = addMultiply(2,3)
print(x)
x3=add([1,3],[4,3])
pri... |
KEYWORD = 'keyword'
KEYWORDS = 'keywords'
ITEM_TYPE = "item_type"
CONTAINED_BY = "contained_by"
FED_BY = 'fed_by'
CONTAINS = 'contains'
FEEDS = "feeds" |
words = ['gallery', 'recasts', 'casters', 'marine', 'bird', 'largely', 'actress', 'remain', 'allergy']
def find_anagrams(list):
new = {}
#key should store strings from input list with letters sorted alphabetically
for word in list:
key = ''.join(sorted(word))
if key not in new:
... |
import pyaudio
import struct
import math
import time
import soundfile
import copy
import wave
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
TONE = 700
TIMEPERIOD = 0.30
PARIS = 40
MIN = 60
p = pyaudio.PyAudio()
morse = {
"a": "*-",
"b": "-***",
"c": "-*-*",
"d": "-**",
"e": "*",
"f": "**... |
from .evdev import get_devices as evdev_get_devices
from .evdev import get_joysticks
from .evdev import get_controllers
from .evdev import EvdevControllerManager as ControllerManager
from .x11_xinput_tablet import get_tablets
from .x11_xinput import get_devices as x11xinput_get_devices
def get_devices(display=None):
... |
from numpy import std
class BreakException(Exception):
pass
class EarlyStop(object):
def __init__(self):
self.list_loss = []
self.best_model = None
def get_best_model(self):
return self.best_model[0]
def check(self, loss, model, patience=10):
self.list_loss.append(l... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class TorextException(Exception):
def __init__(self, message=''):
if isinstance(message, str):
message = message.decode('utf8')
self.message = message
def __str__(self):
return unicode(self).encode('utf-8')
def __unicode__... |
# 13. Roman to Integer
class Solution:
def romanToInt(self, s: str) -> int:
sym = {"I":1, "V":5, "X":10,"L":50,"C":100,"D":500,"M":1000, "S":10000}
pre="S" #start
stack=[]
for digit in s:
if sym[digit]<=sym[pre]:
stack.append(int(sym[digit]))
e... |
#!/usr/bin/env python3
from lib import digits
max_sum = 0
for a in range(100):
for b in range(100):
s = sum(map(int,digits(a**b)))
if s > max_sum:
max_sum = s
print(a,b,s) |
from django.apps import AppConfig
class JustwriteConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'JustWrite'
|
# !/usr/bin/env python3
"""
This is a script designed to find the longest word in the text file, transpose the letters and show
the result.
"""
import argparse
import concurrent.futures
import logging
import logging.handlers
import os
import re
import sys
from glob import glob
logger = logging.getLogger(os.path.splite... |
from graph import Graph, Node
import unittest
__author__ = 'nikita'
class TestNode(unittest.TestCase):
def setUp(self):
self.node = Node()
def test_is_last_false(self):
next_node = Node()
self.node.connects.update({50: next_node})
result = self.node.is_last()
self.ass... |
from smart_pointer_typedef import *
f = Foo()
b = Bar(f)
b.x = 3
if b.getx() != 3:
raise RuntimeError
fp = b.__deref__()
fp.x = 4
if fp.getx() != 4:
raise RuntimeError
|
#coding=utf-8
#print('''
# +----------+
# +-----+ | |RIPEMD160(SHA256(.))结果记为 HASH
# |公钥P| | V
# +-----+ | +----+------+
# | ^ |0x00| HASH | --> SHA256
# V | +----+------+ |
# SHA256 | \ \ V
# | | \ \ SHA256
... |
'''
94. Binary Tree Inorder Traversal
Given a binary tree, return the inorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?
'''
# Solution -1 Iterative
# Definition for a binary tree... |
'''
#Obtenemos el historial de datos de una unidad
response = dashboard.sm.getNetworkSmDeviceCellularUsageHistory(
network_id,
device_id
)
'''
'''
#Obtenemos el historial de conectividad del telefono
response = dashboard.sm.getNetworkSmDeviceConnectivity(
network_id,
device_id,
total_pages='all',
... |
from sklearn import tree
#features =[[140, "smooth"], [130,"smooth"], [150, "bumpy"], [170, "bumpy"]]
#lables = ["apple", "apple", "orange", "orange"]
# 1 :- smooth & 0 :- bumpy
# 0 :- apple & 1 :- orange
features =[[140, 1], [130, 1], [150, 0], [170, 0]]
lables = [0 , 0, 1, 1]
clf = tree.DecisionTreeClassifier()
cl... |
# make a table of ASCII values of upper and lower-case alphabet
# fileU.txt = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# fileL.txt = 'abcdefghijklmnopqrstuvwxyz'
file = open("fileL.txt")
while 1:
char = file.read(1)
if not char:
break
for i in char:
print(i,":\t",ord(char))
|
import os
import re
import time
import pickle
import pyprind
import joblib
import numpy as np
import emoji
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier
from nltk.corpus import stopwords
stop = stopwords.words('english')
def tokenizer(text):
text= re.... |
# Programmer - python_scripts (Abhijith Warrier)
# PYTHON GUI GAME WHERE THE PLAYER HAS TO ENTER THE COLOR IN WHICH TEXT IS WRITTEN
# Importing necessary packages
import random
import tkinter as tk
from tkinter import *
from tkinter import messagebox
# Declaring global variables
timeleft = 60 # Setting ti... |
from django.db import models
from django.utils import timezone
from django.urls import reverse
from django.utils.html import strip_tags
import markdown
from users.models import MyUser
# Create your models here.
class Category(models.Model):
name = models.CharField('类别名称', max_length=100)
class Meta:
... |
from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse
app = Flask(__name__)
user_info = dict()
@app.route("/handle_sms", methods=['GET', 'POST'])
def incoming_sms():
"""Send a dynamic reply to an incoming text message"""
# Get the message the user sent our ... |
import ROOT
import numpy as np
import itertools as it
import data_management as dm
import run_log_metadata as md
ROOT.gROOT.SetBatch(True)
# The function imports pulse files and creates timing resolution files with
# time differences used for timingPlots and trackingAnalysis.
def createTimingFiles(batchNumber):
... |
from pathlib import Path
import json
import csv
import time
def detect_properties(path):
"""Detects image properties in the file."""
from google.cloud import vision
import io
client = vision.ImageAnnotatorClient()
with io.open(path, 'rb') as image_file:
content = image_file.read()
ima... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.