text stringlengths 8 6.05M |
|---|
# t9.py
from collections import deque
class DigitTree():
key_mapping = {
"a": 2,
"b": 2,
"c": 2,
"d": 3,
"e": 3,
"f": 3,
"g": 4,
"h": 4,
"i": 4,
"j": 5,
"k": 5,
"l": 5,
"m": 6,
"n": 6,
"o": 6,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-04-12 21:36:40
# @Author : Fallen (xdd043@qq.com)
# @Link : https://github.com/fallencrasher/python-learning
# @Version : $Id$
#内置函数
#print(self,*args,sep=' ',end='\n',file=None)
print(1,2,3,4,sep='|')
print(1,2,3,4,end='\t')
#list() 转换为列表
l1 = list(... |
df3 = df3[~df3.index.duplicated()] |
#!/usr/bin/env python
from setuptools import setup
setup(
name='mschap',
version='1.0.6',
author='bit0rez',
author_email='b1t0r3z@gmail.com',
description='Copy of mschap library for python. Library copied from IBS project (http://sourceforge.net/projects/ibs/).',
long_description=open('README.... |
import pandas as pd
import sqlalchemy as alc
#import petl as etl
__author__ = 'Meraz'
dw_config = {
"user": "root",
"password": "claire",
"host": "localhost",
"database": 'diploma'
}
#DataFrame.to_sql(name, con, flavor='sqlite', schema=None, if_exists='fail', index=True, index_label=None, chunksiz... |
from account.models import MyUser, MyUserProfile, RateReader
from rate.models import Rate
from countrycity.models import Location, Liner
from rest_framework import serializers, status
from django.contrib.auth.password_validation import validate_password
class ProfileSerializer(serializers.HyperlinkedModelSerializer):
... |
from . import analysis, config, io, pipeline, postprocess, segment |
import requests
import csv
import json
from bs4 import BeautifulSoup
from pprint import pprint
import yfinance as yf
import threading
def get_stock_list():
stocks = []
with open('stock_data.txt') as stock_string:
stocks = stock_string.read()
stocks = stocks.split(',')
clean_data = []
f... |
import numpy as np
n, q = [int(x) for x in input().split()]
ans = np.zeros(n, dtype = int)
for i in range(q):
l,r,t = [int(x) for x in input().split()]
ans[l-1:r] = t
for i in range(n):
print(ans[i]) |
from django.urls import path
from . import views
urlpatterns = [
path('', views.DeputiesList.as_view()),
path('parties/', views.PartiesList.as_view())
] |
"""Define automations for plants."""
# pylint: disable=attribute-defined-outside-init,unused-argument
from typing import Union
from automation import Automation, Feature # type: ignore
class PlantAutomation(Automation):
"""Define an automation for plants."""
class LowMoisture(Feature):
"""Define a featu... |
import vcf
import sys
import time
MOTHER_SAMPLE = 9
FATHER_SAMPLE = 10
def de_novo_one_parent(progeny, parent):
for n in progeny:
if n in parent:
return False
return True
def de_novo_both_parents(progeny, parents):
possible_progeny = [[parents[0][0], parents[1][0]],
... |
from django.http import HttpResponse
from rest_framework.views import APIView
from rest_framework import status
from rest_framework.response import Response
from .models import Article
from .serializerModel import ArticlesSerializer
from rest_framework import status
class ArticleApiView(APIView):
def get(self, req... |
import urllib3
from PIL import Image
import numpy as np
import boto3
import io
import os
def lambda_handler(event, context):
from_number = event['fromNumber']
pic_url = event['image']
num_media = event['numMedia']
if num_media != '0':
http = urllib3.PoolManager()
response = http.r... |
from utils import *
from tqdm import tqdm
import os
if __name__ == '__main__':
train_text_data_path = os.path.abspath('..') + '/gen_data/data/train_text_data.pkl'
train_text_data = load_pkl_data(train_text_data_path)
question_ids = {}
pos_ans_ids = {}
neg_ans_ids = {}
corpus = []
corpus_sent... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from NaoCreator.setting import Setting
Setting(nao_connected=False, debug=True, bypass_wait_for=False, nao_quest_v="2.1", load_cpt_data=False, ip="169.254.88.3", USE_MIC=False)
from NaoQuest.questor import Questor
from PlayerManager.player_manager import Player
from NaoSim... |
from django.contrib import admin
from.models import Product, Comment, Order
class CommentInLine(admin.TabularInline):
model = Comment
extra = 0
@admin.register(Order)
class Admin(admin.ModelAdmin):
fields = ('product_fk', 'user_fk', 'product_count', 'cost', 'order_code', 'date_order',)
list_display = ... |
from math import cos,pi,radians
import time
def dcos(a):
return cos(radians(a))
def motor1(value):
if value<0 and value >=-255:
motor1r = 0
motor1l = 1
motor1speed = abs(value)
print('Motor1 is rotating CCW')
elif value>0 and value<=255:
motor1r = 1
motor1l ... |
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class BarycentricLagrange:
# initialize the class with data points
def __init__(self, data_points):
# data_points is an array of Point objects
self.data_points = data_points
self.weights = []
#... |
import time
import webbrowser
from pywin.tools import browser
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium import webdriver
from selenium import *
from selenium.webdriver.common.keys import Keys
options = webdriver.FirefoxOptions()
options.add_argument("-headless")
driver = w... |
#!/usr/bin/python
"""
This is the code to accompany the Lesson 3 (decision tree) mini-project.
Use a Decision Tree to identify emails from the Enron corpus by author:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../tools/")
from email_preprocess import prep... |
import unittest
from katas.kyu_8.opposite_number import opposite
class OppositeNumberTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(opposite(1), -1)
def test_equals_2(self):
self.assertEqual(opposite(25.6), -25.6)
def test_equals_3(self):
self.assertEqual(o... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
# Copyright (c) 2012 dput authors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either v... |
class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
"""
https://leetcode.com/problems/number-of-closed-islands
well flags were not declared as it should be.
loops needed more strict range. my bad.
"""
m, n = len(grid), len(grid[0])
island = 0... |
__author__ = 'Sebastian Bernasek'
from copy import deepcopy
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import ttest_ind, ks_2samp
from .base import Base
from .settings import *
from .palettes import Palette
from flyeye.processing.alignment import Mul... |
a = int(input("enter"))
b = int(input("enter"))
c = int(input("enter"))
d = int(input("enter"))
e = int(input("enter"))
if(a>=b) and (a>=c) and (a>=d) and (a>=e):
print(a)
elif(b>=c) and (b>=d) and (b>=e):
print(b)
elif(c>=d) and (c>=e):
print(c)
elif(d>=e):
print(d)
else:
print(e) |
# -*- coding: utf-8 -*-
from django.db import models
from tipo_questao import TipoQuestao
from questao import Questao
#from libs.uniqifiers_benchmark import f11 as uniqifier
class FiltroQuestao(models.Model):
"""
Classe que ira gerar uma questao(QuestaoDeAvaliacao) com base em alguns criterios/filtros(TipoQue... |
#!/usr/bin/python
# Copyright 2015 Jason Edelman <jason@networktocode.com>
# Network to Code, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENS... |
count_days = int(input())
count_cooks = int(input())
count_cake = int(input())
count_waffles = int(input())
count_pancakes = int(input())
price_cake = 45
price_waffles = 5.8
price_pancakes = 3.20
daily_wage = (count_cake * price_cake + count_waffles * price_waffles + count_pancakes * price_pancakes) *count_cooks
tot... |
from math import trunc
def two_decimal_places(number):
factor = float(10 ** 2)
return trunc(number * factor) / factor
|
# Create Node
# Create Linkedlist
# Add nodes to Linkedlist
# Print Linkedlist
class Node:
def __init__(self,data=None):
self.data = data
self.next = None
class Linkedlist:
def __init__(self):
self.root = None
def InsertNode(self,newNode):
if self.root is None:
... |
from mlmicrophysics.models import DenseNeuralNetwork
from mlmicrophysics.data import subset_data_files_by_date, assemble_data_files
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler, MinMaxScaler, MaxAbsScaler, RobustScaler, OneHotEncoder
from sklearn.metrics import confusion_matri... |
import subprocess
import os
"""
There are many cases in which you want to call an external command
in python and you can do this with the built-in library called subprocess.
And if you need to, you can also capture the output of that command or even pipe the output
from one command into another.
"""
# running an e... |
'''
Created on Oct 12, 2010
Decision Tree Source Code for Machine Learning in Action Ch. 3
@author: Peter Harrington
Things to note:
Entropy is a measurement of "chaos in a set"
Example high entropy set:
high_entropy_set = set("dog", "cat", "bird", "fish", "lizard")
Example low entropy set:
... |
#!/usr/bin/python
# coding=utf-8
# 作者:李发富
# 邮箱:fafu_li@live.com & 348926676@qq.com
# 时间:2018.07.05
from kafka import KafkaConsumer
from kafka import TopicPartition
import time
import datetime
import sys
#reload(sys)
#sys.setdefaultencoding('utf-8')
class KafkaC:
"""
消费模块: 通过不同groupid消费topic里面的消息
"""
... |
import mysvg
def variations(filter_key):
filter_key = mysvg.get_filter_key(filter_key)
iterables = mysvg.get_iterables(filter_key)
print(f"iterables : {iterables }")
if __name__ == '__main__':
variations("Cross-smooth")
|
from django import forms
from .models import Post,UserProfile
import os
class PostForm(forms.ModelForm):
content=forms.CharField(widget=forms.Textarea(attrs={'class':'mdl-textfield__input','rows':4}))
# media=forms.FileField(widget=forms.FileInput(attrs={'class':"mdl-button mdl-js-button mdl-button--raised mdl... |
class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack = []
for ast in asteroids:
if not stack or stack[-1] < 0 or ast > 0:
stack.append(ast)
continue
while stack and stack[-1] > 0:
if abs(stack[... |
import numpy as np
import scipy.sparse as sp
import numba
from numba import njit
from ..base_transforms import SparseTransform
from ..transform import Transform
from ..sparse import add_selfloops, eliminate_selfloops
@Transform.register()
class NeighborSampler(SparseTransform):
def __init__(self, max_degree: in... |
#!bin/python
# For simplicity of the implementation this assumes square matrix with size being a power of 2
def matrixAdd(A, B, sub = False):
assert len(A) == len(B)
assert len(A[0]) == len(B[0])
C = []
for i in range(len(A)):
C.append([])
for j in range(len(A[i])):
if not ... |
p, n = map(int, input().split(' '))
l = list(map(int, input().split()))
s = ''
for i in range(n-1):
if l[i+1] - l[i] > p or l[i] - l[i+1] > p:
s = 'GAME OVER'
break
else:
s = 'YOU WIN'
print(s) |
# -*- coding: utf-8 -*-
# !/usr/bin/env python
"""
-------------------------------------------------
File Name: message.py
Description: 对外输出的log,显示及统计信息处理
Author: Dexter Chen
Date:2017-09-19
-------------------------------------------------
"""
import mongodb_handler as mh
import screen
import stats
impor... |
import datetime
import logging
from storm.monitoring.sensor.api import sensor
from storm.monitoring.sensor.api import metrics
from storm.monitoring.sensor.api import services
from storm.monitoring.sensor.api import measure
from storm.monitoring.sensor.host.mem import mem_check
from storm.monitoring.sensor.api import m... |
#-*-coding:utf-8-*-
# Author : Zhang Zhichaung
# Date : 2019/6/20 下午2:46
import numpy as np
path = '/mnt/share/users/zzc/kitti_second/training/velodyne/000000.bin'
points = np.fromfile(path, dtype=np.float32, count=-1).reshape([-1, 4])
# path:待打开的文件对象, dtype: 返回的数据类型, count: int,要读取的项目数.
# reshape([a, b]),原来a*b个一维数组,每... |
import urllib.request
import csv
# Function to retrieve data from Open Data Portal of the City of Rome
# url: the location of the dataset (in CSV format) in the Open Data Portal
# localfile: the filename that will be used to store the file on the local disk
# header: the initial rows that do not include any data and s... |
from _typeshed import Incomplete
def from_sparse6_bytes(string): ...
def to_sparse6_bytes(G, nodes: Incomplete | None = None, header: bool = True): ...
def read_sparse6(path): ...
def write_sparse6(
G, path, nodes: Incomplete | None = None, header: bool = True
) -> None: ...
|
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "copying from %s to %s" % (from_file, to_file)
in_file = open(from_file)
indata = in_file.read()
print " Does the input file %r exit? " % to_file
raw_input()
out_file = open(to_file, 'w')
out_file.write(indata) ... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:hua
with open("TEST2.txt","r",encoding="utf-8") as f:
s11 = f.read()
# s1=s.replace('医疗健康人工智能应用落地优秀案例投票医疗健康人工智能应用落地优秀案例投票秒题请至少选择一个案例进行投票谢谢多选题','')
s2 =s11.split("查看详情")
name = 0
for s in s2:
s1 = s.replace('案例名称', '案例名称:')
s2 = s1.replace('仿宋申报单位仿宋', '... |
from v2.client import Personnage
class Salvateur(Personnage):
def __init__(self, pseudo, Emeteur):
Personnage.__init__(self, pseudo, Emeteur, Jeu)
self.accesChat = 1
self.sauvePrecedent = ""
self.role = 'salvateur'
def protege(self, perso):
if self.sauvePrecedent != pe... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import logging
from dataclasses import dataclass
from typing import Iterable
from pants.backend.cc.lint.clangformat.subsystem import ClangFormat
from p... |
import numpy as np
# Construct the matrix
input = np.matrix([[2, 1, 0, 1], [1, 0, 0, 0], [1, 0, 0, 0]])
# Calculate DFT
output = np.fft.fft2(input)
print output
|
from bs4 import BeautifulSoup
import random
import requests
from fake_useragent import UserAgent
import datetime
import traceback
from scraper.functionScraper import *
from scraper.classListingObject import *
from scraper.classHelpClasses import *
# ####### SECOND PART SCRAPER ######
def scraper2():
uncheckedUrls... |
from datetime import datetime, timedelta
from typing import Any, Dict, Optional
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from passlib.context import CryptContext
from sqlalchemy.ext.asyncio import AsyncSession
from app.config i... |
#!/usr/bin/env /proj/sot/ska/bin/python
#########################################################################################################
# #
# extract_data_redo.py: extract data from archive ... |
"""
Create a set of turtles and set them on a starting line. Turtles
are created with a function. User sets number of turtles to be
created. Each turtle is a different random color. Turtles race
to finish line.
"""
import turtle
import random
num_t = int(input("Please input the number of turtles desired: "))
t_... |
import paho.mqtt.subscribe as subscribe
class Communication(object):
def __init__(self):
super(Communication, self).__init__()
subscribe.callback(lambda client, userdata, message: self.onMessageReceive(message.payload), "/dtc", hostname="localhost")
def onMessageReceive(self, dtc_msg):
... |
#!/usr/bin/python
"""
Using the tau amino acid sequence from 5o3l, this script threads a sliding
frame of 6 tau residues into the substrate of Htra1 protease 3nzi then runs a
FastRelax. The aim is to determine the most favorable docking points along the
tau chain based only on sequence.
"""
from os import make... |
'''
Created on 30. mar. 2017
@author: tsy
'''
class specialRules(object):
'''
classdocs
'''
def __init__(self, attacker,defender):
'''
Constructor
'''
self.attacker=None
self.defender=None
|
#!/usr/bin/env python3
# Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
import os
import sys
def main(args):
for file in os.listdir(args[0]):
... |
from flask_restful import Resource, reqparse, fields, marshal
from models import User, db
from common.crypto import encode, decode
import jwt
import os
import uuid
user_fields = {
'id': fields.String,
'username': fields.String
}
class Register(Resource):
def __init__(self):
self.post_parser = req... |
import micro_nw as nw
import numpy as np
from sklearn.linear_model import Lasso, LassoCV
import pandas as pd
import sys
from scipy import stats
folde = sys.argv[1]
fo1 = open(folde+'/disease_list','w')
fo1.write(sys.argv[2])
dis =[]
dis.append(sys.argv[2])
if len(sys.argv)>3:
dis.append(sys.argv[3])
fo1.write('\t'+s... |
from .catalog_ref import CatalogRef
from .exchange_ref import ExchangeRef
|
# Copyright 2017 The Forseti Security Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... |
from django.conf.urls import url
from message.views import HistoriqueView
urlpatterns = [
url('', HistoriqueView.as_view(), name='historique'),
]
|
import numpy as np
import cv2
def show_img(img):
cv2.imshow("canvas",img)
cv2.waitKey(0)
return
canvas = np.zeros((300,300,3), dtype= 'uint8')
green = (0,255,0)
cv2.line(canvas, (0,0), (300,300), green) # (0,0) starting coordinate and
# (300,30... |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... |
import down_util
import pandas as pd
import os
from glob import glob
from os import path
# os.environ['http_proxy']='127.0.0.1:1080'
# os.environ['https_proxy']='127.0.0.1:1080'
if __name__=='__main__':
df, _ = down_util.split_collection(r"Z:\yinry\Landsat.Data\GOOGLE\landsat_index.csv.gz")
# pr_list_file = ... |
import tensorflow as tf
from tensorflow import keras
from keras.models import load_model
import numpy as np
import random
import matplotlib.pyplot as plt
# Generate the Model using Keras
def generate_model(train_data, test_data, train_label, test_label, epochs):
# Create the Multilayer Network
model = keras.S... |
import numpy as np
class SLHMM:
h_cnt = None
sym_cnt = None
p1 = None
p21 = None
p31 = None
b1 = None
binf = None
bx = None
U = None
V = None
Sig = None
def initMatrices(self):
self.p1 = np.zeros(self.sym_cnt)
self.p21 = np.zeros((self.sym_cnt, s... |
import sqlite3
def loadTables(regionFile, salesFile):
regions = open(regionFile, "r")
sales = open(salesFile, "r")
conn = sqlite3.connect('Avocado.db')
c = conn.cursor()
# drop tables
c.execute('DROP TABLE IF EXISTS region')
c.execute('DROP TABLE IF EXISTS sales')
# create new tables
... |
# Exercício 6.12 - Livro
numeros = [2, 6, 8, 4, 1, 20, -26]
menor = numeros[0]
for num in numeros:
if num < menor:
menor = num
print('=-=' * 10)
print(f'Menor → {menor}')
|
# -*- coding: utf-8 -*-
"""
ytelapi
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
import jsonpickle
import dateutil.parser
from .controller_test_base import ControllerTestBase
from ..test_helper import TestHelper
from ytelapi.api_helper import APIHelper
... |
import time
from _base.base_actions import BaseActions
from _base.base_elements import BaseElements
from _test_suites._variables.variables import Variables
class BasePopup(BaseActions):
def _set_popup(self, name):
locator = "//span[text()='" + str(name) + "']" \
"[@dir... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 3 18:42:45 2016
Cache class to store a specified number of data elements in memory to reduce loading time from DB
@author: alex
"""
import time
import copy
"""
Basic Cache
FIFO - Max Length Cache
"""
class BasicCache(object):
"""
Initialization Function
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author = 'wyx'
@time = 16/5/25 14:07
@annotation = ''
"""
debug = True
encoding = 'utf8'
# MySQL配置
db_config = {
"db_reader": {"host": "192.168.1.20", "port": 13306, "db": "statics",
"user": "bulu", "passwd": "123456", "charset": encoding},
"... |
from setuptools import setup
import sys
APP = ['gierzwaluw/gui.py']
DATA_FILES = [('static', ['static/swallow.png', 'static/index.html'])]
MAC_OPTIONS = {
'argv_emulation': True,
'iconfile':'static/swallow.icns',
'plist': {
"LSUIElement": True,
},
}
WIN_OPTIONS = {}
options = {}
if sys.platf... |
import urllib
import urllib2
import re
import os
from BeautifulSoup import BeautifulSoup
base_url = 'http://comment.rsablogs.org.uk/videos/page/'
def open_page(url):
'''
Returns the contents of a page as a string
'''
# Fool the page into thinking it's a request from Firefox on Windows
user_agent='Mozilla/5.0 (Wi... |
import numpy as np
import datetime
from scipy.special import gamma
# References:
# [1] S. Sra, D. Karp, The multivariate Watson distribution:
# Maximum-likelihood estimation and other aspects,
# Journal of Multivariate Analysis 114 (2013) 256-269
def pdf(X, mu, kappa):
"""Evaluates the pdf defined from a Wat... |
import matplotlib.pyplot as plt
import numpy as np
import sys
import os
from io import StringIO
from io import BytesIO
import mnist_cnn
from PIL import Image
from recog.image3 import ImageParser
dir = '/home/mhkim/data/images'
if os.path.exists(dir) == False :
os.mkdir('/home/mhkim/data/images')
param = b'test... |
"""
Not yet implemented.
added FMC v6.5.0
Appears to only be valid for Firepower 1010 devices.
"""
|
# -*- coding: utf-8 -*-
import logging
import sys
from yyfeed.fetcher import *
logger = logging.getLogger(__name__)
def test_fetcher(fetcher):
count = 0
for i, item in enumerate(fetcher.fetch()):
logger.info(' -------- [%d] ------[[', i)
logger.info(item)
logger.info(']]------ [%d] -... |
from .funcs import MathFunctions # noqa: F401
from .groups import MultiplicativeGroup # noqa: F401
|
#TOIMII
def isInTriangle(x,y,x1,y1,x2,y2,x3,y3):
det = (y2-y3)*(x1-x3)+(x3-x2)*(y1-y3)
detPositive = det > 0
l1nodet = (y2-y3)*(x-x3)+(x3-x2)*(y-y3)
l2nodet = (y3-y1)*(x-x3)+(x1-x3)*(y-y3)
l3nodet = det - l1nodet - l2nodet
l1Pos = l1nodet >= 0
l2Pos = l2nodet >= 0
l3Pos = l3nodet >= 0
return (l... |
from artiq.experiment import *
import socket
import time
class TCPIP_LaserFrequency(EnvExperiment):
"""TCPIP_LaserFrequency"""
def build(self):
pass
def prepare(self):
pass
def run(self):
sk = socket.socket()
# 绑定一个ip和端口
# Bind an... |
import unittest
from katas.beta.lowest_product_of_4_consecutive_nums import lowest_product
class LowestProductTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(lowest_product('123456789'), 24)
def test_equals_2(self):
self.assertEqual(lowest_product('2345611117899'), 1)
... |
import gensim
from gensim import corpora
from pprint import pprint
import pandas as pd
import numpy as np
import gensim.downloader as api
import matplotlib.pyplot as plt
# Стандартное импортирование plotly
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.offline import iplot
from gensim.utils imp... |
#!/usr/bin/python
#
#import inspect_shell
#
from logging import getLogger, setLoggerClass, FileHandler, Formatter, StreamHandler, INFO
from random import seed
from sys import argv
from time import time
from traceback import format_exc
from PyQt4 import uic
from PyQt4.QtCore import Qt, QTimer
from PyQt4.QtGui import... |
# -*- coding: utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def __eq__(self, other):
return (
other is not None
and self.val == other.val
and self.left == other.left
and self.rig... |
import sqlite3
def loadTables(regionFile, salesFile):
regions = open(regionFile, "r")
sales = open(salesFile, "r")
#create or connect to database
conn = sqlite3.connect('Avocado.db')
c = conn.cursor()
#drop tables
c.execute('DROP TABLE IF EXISTS region')
c.execute('DROP TABLE IF ... |
a, b, c = sorted(map(int, input().split()))
print(max(0, c - a - b + 1))
|
## Logicly group a data and function for reuse
## attributes and methods assosiated with calss
# this is a class
class Employee:
## this is a constrctore or init method
def __init__(self,first,last,pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '... |
#I pledge my honor that I have abided by the Stevens Honor System
def month_review(month):
if month > 0 and month <= 12:
return True
else:
return False
def day_review(month, day):
month_list_31days = [1, 3, 5, 7, 8, 10, 12]
month_list_30days = [4, 6, 9, 11]
month_list_28days = 2
... |
import numpy as np
import matplotlib.pyplot as plt
from sympy import *
from sympy.parsing.sympy_parser import parse_expr
s="-y+sin(x)"
z=Symbol("x")
w=Symbol("y")
F=parse_expr(s)
# variables to be read S-> striing of equation
# x0,y0 initial condition
# xf -> x to stop at it , n-> number of interval slices
# ou... |
import csv , sys
import utils
import random
def reproducefile(filename):
trainpath = 'data/twitter.txt'
train_object = open(trainpath, 'w')
text2id = {}
with open(filename) as f:
for line in f:
text = line.split('\t')
# print(text[0])
assert '.' in text[0] or... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
"""This is an empty Pants plugin for the help info extracter test."""
|
__copyright__ = '''
Copyright (c) 2016 Qualcomm Technologies, Inc.
All Rights Reserved.
Confidential and Proprietary - Qualcomm Technologies, Inc.
'''
import xml.etree.ElementTree
import sys
import time
from optparse import OptionParser
class ProcessScopePacketTypeFile:
def __init__(self):
use = 'usage:... |
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from app import db
from flask import Blueprint
snippet = Blueprint('snippet', __name__)
engine = create_engine('sqlite://... |
#!/usr/bin/python
# -*- coding: cp936 -*-
import os
import sqlite3
import re
import pandas as pd
def importHisClientLoginEventToSQLite():
with sqlite3.connect('C:\sqlite\db\hxdata.db') as db:
# ExcelDocument('..\input\营销人员和营业部列表.xlsx') as src:
insert_template1 = "INSERT INTO hisclientloginevent "... |
import numpy as np
import pandas as pd
#read main and meta data
appl = pd.read_csv('application_train.csv')
bur = pd.read_csv('bureau.csv')
ccb = pd.read_csv('credit_card_balance.csv')
pos = pd.read_csv('pos_cash_balance.csv')
pre = pd.read_csv('previous_application.csv')
#create new columns in main data
a... |
import random
import math
import game_framework
from BehaviorTree import BehaviorTree, SelectorNode, SequenceNode, LeafNode
from pico2d import *
import world_build_state
# zombie Run Speed
PIXEL_PER_METER = (10.0 / 0.3) # 10 pixel 30 cm
RUN_SPEED_KMPH = 10.0 # Km / Hour
RUN_SPEED_MPM = (RUN_SPEED_KMPH * 1000.0 / 60.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.