blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 133 | path stringlengths 2 333 | src_encoding stringclasses 30
values | length_bytes int64 18 5.47M | score float64 2.52 5.81 | int_score int64 3 5 | detected_licenses listlengths 0 67 | license_type stringclasses 2
values | text stringlengths 12 5.47M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
9ca79f710b30c37ca731c98df2f859464b4e99dd | Python | craiglow68/Substitution_Cipher_Tools | /shiftTools.py | UTF-8 | 3,541 | 3.203125 | 3 | [] | no_license | #Author: Jacob Craiglow
#Description: Contains tools, charts, and a UI to help break a shift cipher
#Usage: python shiftTools.py cipherText
from displayPartial import displayPartialSolution
from shiftcipher import decodeCipher, encodeCipher
from tokenizer import *
import sys
if len(sys.argv) != 2:
print("Incorre... | true |
56d928836c4e89236d79195a1b527619981a2d99 | Python | JackGao1234/PythonToolkit | /monkey_patching/main.py | UTF-8 | 997 | 2.765625 | 3 | [] | no_license | from poc_code import Model_YOU_CANNOT_MODIFY
from utils.bcolor import *
print_header('==Normal Calling==')
a_model = Model_YOU_CANNOT_MODIFY()
a_model.analyze("jack")
def profiling(func):
def wrapped(*args, **kwargs):
print_warn("**start timing")
result = func(*args, **kwargs)
print_warn... | true |
3b6dd2d507c43c022ba4d6ba4db04e2e778c9d46 | Python | kauemenezes/Mestrado | /MachineLearning/python-gaussianmix/GaussianMixture.py | UTF-8 | 3,582 | 2.84375 | 3 | [] | no_license | import numpy as np
from sklearn.cluster import KMeans
import math
from Classifier import Classifier
class GMM(Classifier):
def gaussian(self, X, mu, cov):
n = X.shape[1]
diff = (X - mu).T
return np.diagonal(1 / ((2 * np.pi) ** (n / 2) * np.linalg.det(cov) ** 0.5) * np.exp(
-0.... | true |
efa52c28504ad57a656353ac8c190af77f340ed3 | Python | Existentialist-Robot/natHack_2021 | /raspberryPi/webApp/call_webhook.py | UTF-8 | 1,055 | 2.578125 | 3 | [
"MIT"
] | permissive | import requests
WEBHOOK_IP = 'localhost'
WEBHOOK_PORT = 14739
BROW_URL = f'http://{WEBHOOK_IP}:{WEBHOOK_PORT}/brow'
BLINK_URL= f'http://{WEBHOOK_IP}:{WEBHOOK_PORT}/blink'
EYE_URL = f'http://{WEBHOOK_IP}:{WEBHOOK_PORT}/eye'
WINK_LEFT_URL = f'http://{WEBHOOK_IP}:{WEBHOOK_PORT}/wink-left'
WINK_RIGHT_URL = f'http://{WEBHO... | true |
f5f2ec18d92059d1aae1e60d49a3ba3ff28a09e6 | Python | azharmunir43/insightish | /titanic/models.py | UTF-8 | 1,029 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | from django.db import models
# Create your models here.
class Passenger(models.Model):
age = models.IntegerField()
siblings_and_spouse_count = models.IntegerField()
parent_and_children_count = models.IntegerField()
gender = models.CharField(max_length=6)
ticket_number = models.CharField(max_leng... | true |
62bea151a19a8cf0d094298b87841327aff08423 | Python | ethanbond64/Project-Euler | /additional/Primes.py | UTF-8 | 254 | 3.6875 | 4 | [] | no_license | import math
checker = True
num = int(input("print a number: "))
for i in range(2,int(math.sqrt(num))+1):
if num%i == 0:
checker = False
break
print(checker)
# prints True if the value is prime, False if non-prime, does not work for 1
| true |
407721d74bbccd8193f437b0482db362af9b50f4 | Python | nicrodriguez/PythonSimpleAndRobustFitting | /SimpleFit.py | UTF-8 | 1,646 | 3.296875 | 3 | [] | no_license | from BackgroundFunctions import *
def simple_fit(x_points, y_points, z_points):
# Calculating the centroid of the points
cent = [sum(x_points) / len(x_points), sum(y_points) / len(y_points), sum(z_points) / len(z_points)]
# Calculating the covariance matrix
xx = yy = xy = xz = yz = zz = 0
for i ... | true |
8317116585e4a78a541fc13e4bf29a664e16d905 | Python | korea7030/pythonwork | /python-machine-learning/ch04/ch04-6/mushroom-train.py | UTF-8 | 964 | 3.21875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn import metrics
from sklearn.model_selection import train_test_split
# 데이터 읽어 들이기
mr = pd.read_csv("mushroom.csv", header=None)
# 데이터 내부의 기호를 숫자로 변환
label = []
data = []
attr_list = []
for row_index, row in mr... | true |
1f060909a6e25201596f7e6c1b3f564007279d26 | Python | yuede/Lintcode | /Python/Unique-Characters.py | UTF-8 | 300 | 3.296875 | 3 | [] | no_license | class Solution:
# @param s: a string
# @return: a boolean
def isUnique(self, str):
# write your code here
seq = [0] * 256
for i in str:
cur = ord(i)
seq[cur] += 1
if seq[cur] > 1:
return False
return True | true |
7a1b8310ed9903518f90a387bee8eea622665d69 | Python | 5ya7/3D-CLoST | /Notebook/CLOST/utils.py | UTF-8 | 2,961 | 2.75 | 3 | [
"MIT"
] | permissive | from .imports import *
def normalize(X, min_x, max_x):
X = 1. * (X - min_x) / (max_x - min_x)
return X
def denormalize(X, min_x, max_x):
X = 1. * X * (max_x - min_x) + min_x
return X
def root_mean_squared_error(y_true, y_pred):
# Keras RMSE
return K.sqrt(K.mean(K.square(y_pred - y_true)... | true |
7f24483a9eca02f47f49a5650ad460e8e83a5f6c | Python | vimleshtech/mynewrepository | /Python/corrEx.py | UTF-8 | 209 | 3 | 3 | [] | no_license | import pandas as pd
df = pd.DataFrame({'A': range(4), 'B': [2*i for i in range(4)]})
A B
0 0 0
1 1 2
2 2 4
3 3 6
df['A'].corr(df['B'])
df.loc[2, 'B'] = 4.5
df['A'].corr(df['B'])
df.corr()
| true |
bda8d9f349869e824d5b3f8fcdb9925f27c0d96b | Python | dsv61999/OcrApp | /input.py | UTF-8 | 2,828 | 3.546875 | 4 | [] | no_license | import display
# OCR言語の入力処理を行う関数
def inputLang():
langList = (1, 2) # 存在する言語のリスト(型はタプル)
langDict = {"1":"日本語", "2":"英語"}
display.showCaption_Em("OCRの言語を選んでください")
print("1・・・日本語")
print("2・・・英語")
print("*----------------------------------------*")
lang = input()
# 整数が入力されているかのチェック
... | true |
92a15e8945238f23ae122b22f317e27102039575 | Python | cweight/Maui | /process-usertimeline.py | UTF-8 | 3,218 | 2.890625 | 3 | [
"Apache-2.0"
] | permissive | import json, tweepy
filename = 'usertimeline.json'
READ = 'rb'
tweets = json.load(open(filename,READ))
#Which hashtags were used?
# Consumer keys and access tokens, used for OAuth
READ = 'rb'
WRITE = 'wb'
tokens = json.load(open('../tokens.json',READ))
# OAuth process, using the keys and tokens
auth = tweepy.OAu... | true |
b6e8e1f274db472428ee278985a7b0ab65bd6cfd | Python | SANIYA-05/AITPL2110-saniya | /saniya/states and capitals.py | UTF-8 | 159 | 3.09375 | 3 | [] | no_license | import csv
with open("states.csv") as csv_file:
readcsv=csv.reader(csv_file,delimiter=',')
for row in readcsv:
next(readcsv)
print(row) | true |
b9a2f0b0078ee5ea76e32f4e262aaea6a80c3dcd | Python | deejay077/Python-sabiprogrammers | /DAY3/While loops.py | UTF-8 | 790 | 4.375 | 4 | [] | no_license | # While loops
'''while condition:
do something'''
num = 1
while num < 10:
print(num)
num = num + 1
if num == 10:
print('you have reached the end')
# using break statement
while True:
name = input('Enter your name: ')
if name == 'Triumph':
break
# using continue statement
whil... | true |
71868a9a6f265fde35ef224e49e22fa539452e53 | Python | matsuyu/CSconference | /input_handling.py | UTF-8 | 1,112 | 3.71875 | 4 | [] | no_license | from microbit import *
while True:
reading = pin0.read_analog() / 204
if reading > 4.0:
pos = 4
elif reading > 3.0:
pos = 3
elif reading > 2.0:
pos = 2
elif reading > 1.0:
pos = 1
else:
pos = 0
# note that this can be written as
# pos = reading//... | true |
72b99ae6c6147857cf9a33a733bafd42bcae143d | Python | qingyuanhujnu/RayTracer | /test/test.py | UTF-8 | 4,031 | 2.796875 | 3 | [] | no_license | import os
import sys
import re
import time
import shutil
import filecmp
def DeleteFile (filePath):
if os.path.exists (filePath):
os.remove (filePath)
def DeleteFolder (folderPath):
if os.path.exists (folderPath):
shutil.rmtree (folderPath)
def CreateFolder (folderPath):
if not os.path.exists (folderPath):
... | true |
b156e4399158415b26fbc518663f63f8d9d270cd | Python | sravanpulipati/Durgamma | /1. Series.py | UTF-8 | 1,283 | 3.796875 | 4 | [] | no_license | import numpy as np
import pandas as pd
#Series is a one-dimensional labeled array capable of holding
#any data type (integers, strings, floating point numbers, Python objects, etc.)
#Series created using ndarray
s = pd.Series(np.random.randn(4), index=['d', 'a', 't', 'a'])
s
s.index
#constant number passed... | true |
1e8e2d40e66d9c3342c583e0b195561cda60914f | Python | FTCompany8884/FTSnake | /main.py | UTF-8 | 3,339 | 3.375 | 3 | [] | no_license | import turtle
import time
import random
d = 0.1
score = 0
hscore = 0
win = turtle.Screen()
win.title('FT snake')
win.bgcolor('chartreuse')
win.setup(width = 600, height = 600)
win.cv._rootwindow.resizable(False, False)
win.tracer(0)
head = turtle.Turtle()
head.speed(0)
head.shape('square')
head.color('blue')
head.penup... | true |
45d07da72d163a8095da716a80df9dcfd61a699b | Python | ericbgarnick/prints-backend | /prints/serializers.py | UTF-8 | 2,544 | 2.578125 | 3 | [] | no_license | from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from photos.models import Photo
from prints.models import PrintSizeInfo, PrintSize, Print
class PrintSizeInfoSerializer(serializers.ModelSerializer):
size = serializers.ChoiceField(
choices=[ps[1] for ps in Print... | true |
c9172ba8e0da3109c0c80679f357071f91dbf389 | Python | mtkarim/Discrete-Structures | /program12/ch12.py | UTF-8 | 833 | 2.984375 | 3 | [] | no_license | import sys
import re
from node import *
value = open(sys.argv[1]) #opening a file
disp=[]
for wall in value:
disp.append(re.split(",",re.sub(r"\n", "",wall )))
arr=[]
arg=disp[0]
loc = ""
for row in disp:
loc = ""
if row[-1] is'1':
iterator = 0
loc += ... | true |
fffc10f50460a7ccffaf2e3ed6e925faa95985c5 | Python | Juanrola97/diplomado_django | /centro_medico/objetos_medico/cita.py | UTF-8 | 1,085 | 2.984375 | 3 | [] | no_license | class Cita():
id = ''
descripcion = ''
paciente_id = ''
doctor_id = ''
notamedica_id = ''
def __init__(self, id, descripcion, paciente_id, doctor_id, notamedica_id):
self.id = id
self.descripcion = descripcion
self.paciente_id = paciente_id
self.doctor_i... | true |
8c8b17c7f7f90c345490e91090bf22b49cfb815e | Python | SapnaSap/sappy2212 | /dict.py | UTF-8 | 1,014 | 3.640625 | 4 | [] | no_license | def listfun():
veglist=['chilli','potato','radish']
print('I have',len(veglist),'veg to purchase.')
print('the veglist is', veglist)
print('\n1 also have to buy potato.')
veglist.append('potato')
print('My veg list is now',veglist)
print('I will sort my list now')
veglist.sort()
print('sorted veg list is',vegl... | true |
870e91fafd030aca5608dd2433dc07606232c932 | Python | davidszotten/sentry-stack-checker | /sentry_stack_checker.py | UTF-8 | 4,448 | 2.765625 | 3 | [
"MIT"
] | permissive | """Checker for calls to logger.exception with `stack: True`."""
import astroid
from astroid.node_classes import ExceptHandler
from pylint.checkers import BaseChecker, utils
from pylint.interfaces import IAstroidChecker
def register(linter):
"""Register checker."""
linter.register_checker(SentryStackChecker(... | true |
e15358386fe8f8e78a4d2dd933942c2395d7f084 | Python | sayan1995/DFS-3 | /Number Confused.py | UTF-8 | 1,234 | 3.609375 | 4 | [] | no_license | '''
Time Complexity: O(4^n)
Space Complexity: O(n)
Did this code successfully run on Leetcode : Yes
Explanation: Use Backtracking to create all number pairs from 0 to N but each number pair would only be of digits 0,3,6,8,9
as these are confusing numbers and at each state of creating a number check if its a valid numbe... | true |
9545f204dc2216b12cfb739bde09f0dfd2a6d293 | Python | dealvv/EGE | /Python/ЕГЭ2021/12/Решение заданий. Поляков/2810.py | UTF-8 | 1,516 | 4.21875 | 4 | [] | no_license | #(№ 2810) (А.М. Кабанов) Исполнитель Редактор получает на вход строку цифр и преобразовывает её.
#Редактор может выполнять две команды, в обеих командах v и w обозначают цепочки символов.
#1. заменить (v, w)
#2. нашлось (v)
#Первая команда заменяет в строке первое слева вхождение цепочки v на цепочку w.
#Если цепочки v... | true |
df866b4f1e84a1e8417daa7fab0411bea02707dc | Python | Captain-Eli/Cranberries | /Items.py | UTF-8 | 4,112 | 3.515625 | 4 | [] | no_license |
class Item(object):
def __init__(self, name, description, value):
self.name = name
self.description = description
self.value = value
def __str__(self):
return "{}\n=====\n{}\nValue: {}\n".format(self.name, self.description, self.value)
class Weapon(Item):
def __init__(self, name, description,... | true |
8cdd220d129c48c50f155c08030780f4149ecaa9 | Python | Aasthaengg/IBMdataset | /Python_codes/p02787/s963790441.py | UTF-8 | 367 | 2.609375 | 3 | [] | no_license | H, N = list(map(int, input().split()))
dp = [[float('inf')] * (H + 1)]
dp[0][0] = 0
magic = []
for i in range(N):
magic.append(list(map(int, input().split())))
for i in range(H+1):
next = dp[i]
if dp[i][i] != float('inf'):
for j in magic:
next[min(H, i + j[0])] = min(dp[i-1][i] + j[1], dp[i][min(H, i... | true |
950be3b8b38b31868f21a77e38406494f7432f44 | Python | catboost/catboost | /contrib/python/pythran/pythran/types/conversion.py | UTF-8 | 5,090 | 2.609375 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | """ Module to convert Python type to Pythonic type. """
from numpy import int8, int16, int32, int64, intp, intc
from numpy import uint8, uint16, uint32, uint64, uintp, uintc
from numpy import float64, float32, complex64, complex128
import numpy
from pythran.typing import List, Dict, Set, Tuple, NDArray, Pointer, Fun
... | true |
58f20f13b0487602ebb5b3a3716c6033b1c456f9 | Python | jeffsabarman/COVID-19 | /Chatbot COVID-19.py | UTF-8 | 3,645 | 3.46875 | 3 | [] | no_license | from bs4 import BeautifulSoup
import requests
print('Welcome to COVID-19 Chatbot')
while True :
print('1. The COVID-19 situation in the area')
print('2. What is COVID-19?')
print("3. What's the symptoms after affected by COVID-19? ")
print('4. How to protect my self from COVID-19?')
print(... | true |
c808997d785293ebce36a6c8f8607c7aa2215468 | Python | haldous2/IntroToPython | /Students/EricWestman/session02/distance.py | UTF-8 | 273 | 3.890625 | 4 | [] | no_license |
import math
def distance(x1,y1,x2,y2):
"""Calculate distance between two points x & y. Not sure what units this calculation is in, assuming miles"""
cDistance = math.sqrt( (x1-x2)**2 + (y1-y2)**2 )
return cDistance
print "distance %f" % distance(1,2,3,4)
| true |
df634e19b420d5953afe6f623a9b8ad2be9a5978 | Python | Gennadii8/Netology_Py_Prof_HW_4_Tests | /Task_22/test_creation_folder.py | UTF-8 | 769 | 3 | 3 | [] | no_license | import unittest
from main import make_a_folder
from ya_token import ya_token
class TestAnswers(unittest.TestCase):
def setUp(self):
print("method setUp")
def tearDown(self):
print("method tearDown")
def test_make_a_folder_201(self):
result = make_a_folder(ya_token)
if re... | true |
ec6d6108bda00f36684d997ffb5071837058c582 | Python | jardellx/arcade | /base/011/solver.py | UTF-8 | 256 | 3.046875 | 3 | [] | no_license | hora = int(input())
minuto = int(input())
dia = int(input())
mes = int(input())
ano = int(input())
# hora = hora if hora <= 12 else hora - 12
if hora > 12:
hora -= 12
ano = ano % 100
print("%02d:%02d %02d/%02d/%02d" % (hora, minuto, dia, mes, ano))
| true |
579391e258cd4e14087d259370001a585ce671a4 | Python | otsukaresama/molecular-graph-descriptors | /graphdescriptors/analysis_scripts/projected_graph.py | UTF-8 | 2,238 | 3.015625 | 3 | [] | no_license | import numpy as np
import pandas as pd
import networkx as nx
from collections import defaultdict
from collections import Counter
from analysis_scripts import compute_analytics, graph_loader, projected_graph
def graph_projection(graph):
"""
Project a new graph based on connectivity between a subset of nodes in ... | true |
93973af88f99c79fa5da50bd26cc106aab4401ca | Python | ArchyPeshenka/cp2019hackaton | /Server/mapcreator.py | UTF-8 | 1,191 | 2.640625 | 3 | [] | no_license | import folium
import numpy
import random
class MapGenerator():
def __init__(self):
self.warnicon = 'img/warn.png'
self.alerticon = 'img/alert.png'
self.icon_warn = folium.features.CustomIcon(self.warnicon, icon_size=(32, 32))
self.icon_alert = folium.features.CustomIcon(self.alerticon, icon_size=(32,... | true |
a1b4f335f69cd5d3f97eed1d14806ec7817cfd89 | Python | AI-ROS/pyrobots | /testing/base.py | UTF-8 | 2,231 | 2.65625 | 3 | [
"ISC"
] | permissive | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import logging
import unittest
import robots
from robots.decorators import action
from robots import __version__
from robots.signals import ActionCancelled
# a dummy goto action that waits for 1 sec
@action
def goto(robot, target):
print("Starting to move ... | true |
dc81bc8c41b0a4aa017635d29537116119eda644 | Python | hphp/demo | /demo_python/rand.py | UTF-8 | 108 | 2.609375 | 3 | [] | no_license | #!/usr/bin/python
import random
for i in range(10):
rand = random.randrange(1000000000)
print rand
| true |
7be602ea3e4feae11b7aa099256f0d5e522acc51 | Python | SamJ2018/LeetCode | /python/python语法/pyexercise/Exercise09_29.py | UTF-8 | 2,926 | 3.484375 | 3 | [] | no_license | from tkinter import * # Import tkinter
from random import randint
import math
width = 300
height = 200
radius = 2
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
# Is point (x, y) close to this point
def isNearBy(self, x, y):
return distance(self.x, self.y... | true |
e6d3b6f78694d08488494d283891820b15b745dd | Python | mingyyy/crash_course | /week1/variables.py | UTF-8 | 522 | 4.0625 | 4 | [] | no_license | '''
1. avoid using python keywords
2. use lower case (leave the capital for Classes, camel case) and underscore _
3. clear naming for others and yourself to understand
4. can't start with a number
'''
# use the list function to create a list
print(list("kldjflkadjflks"))
l = ['a','b','c']
t = ('a', 'b', 'c')
print(l... | true |
a90cc711fd16182a032cc4b5743f95e83e247807 | Python | uigiporc/icon-sr | /inference/inference.py | UTF-8 | 3,081 | 2.65625 | 3 | [] | no_license | import numpy as np
import threading
import tensorflow as tf
import librosa
import queue
import wave
import pyaudio
from tensorflow import keras
FORMAT = pyaudio.paInt16
CHANNELS = 2
p = pyaudio.PyAudio()
buffer = queue.Queue(10)
SAMPLE_RATE = 16000
# The set of characters accepted in the transcription.
characters = [... | true |
438d7d4e02b81ba27ed1db40db62f814b2055f9b | Python | ahenrici/Planet_Maker | /MapMaker.py | UTF-8 | 4,144 | 2.953125 | 3 | [] | no_license | #!/usr/bin/python3
import pygame
from math import sin, cos, pi#, acos
from opensimplex import OpenSimplex
from itertools import repeat
import random
import numpy as np
from multiprocessing.dummy import Pool as ThreadPool
from Cell import Cell
from Quadrant import Quadrant
import sys
class Map:
def __init__(self, dep... | true |
76dbd036e6998e566a4924ccd9abb10e43083828 | Python | MMhenna/holberton-system_engineering-devops | /0x16-api_advanced/1-top_ten.py | UTF-8 | 492 | 2.984375 | 3 | [] | no_license | #!/usr/bin/python3
"""queries the Reddit API"""
import requests
def top_ten(subreddit):
"""returns first 10 posts"""
url = "https://www.reddit.com/r/" + subreddit + "/hot.json"
header = {"User-Agent": "mehdi"}
params = {"limit": 10}
response = requests.get(url, headers=header, params=params)
... | true |
14709e58840564f5e88133603289a7a5d44260b4 | Python | axxiao/toby | /ax/wrapper/sqlalchemy.py | UTF-8 | 1,713 | 2.6875 | 3 | [
"MIT"
] | permissive | """
The wrapper for Postgres through SQLAchemy
__author__ = "Alex Xiao <http://www.alexxiao.me/>"
__date__ = "2018-11-03"
__version__ = "0.1"
Version:
0.1 (03/11/2018 AX) : init
"""
from urllib.parse import quote_plus
from sqlalchemy import create_engine, text
import pandas
from ax.log import ge... | true |
02fde70a8b9300a9e09c717072aeb4780387620a | Python | vjsyong/tf_data_experiment | /utilities/process_wiki_csv.py | UTF-8 | 699 | 3.140625 | 3 | [] | no_license | from datetime import timedelta, datetime
import pandas as pd
def convert_matlab(matlab_datenum):
python_datetime = datetime.fromordinal(int(matlab_datenum)) + timedelta(days=matlab_datenum%1) - timedelta(days = 366)
print(python_datetime)
if __name__ == '__main__':
df = pd.read_csv("wiki.csv")
paths... | true |
9255907bb550bcbe9b0470c39573620cea478a90 | Python | teedr/Loop-Analysis | /plotdist.py | UTF-8 | 4,295 | 2.75 | 3 | [] | no_license | #!/usr/bin/python
import sys
import re
import operator
import numpy as np
import json
import start_api as st
import numpy as np
import matplotlib.pyplot as plt
def sort_lengths(SequenceList):
sorted_sequence_dict = {}
for sequence in SequenceList:
length = len(sequence)
if length not in sorted_sequence_dict:
... | true |
df6f6d67ac1f99d7c10648f707c61383be362a68 | Python | dockerizeme/dockerizeme | /hard-gists/6754465/snippet.py | UTF-8 | 512 | 2.828125 | 3 | [
"Apache-2.0"
] | permissive | from PIL import Image
backgroundColor = (0,)*3
pixelSize = 9
image = Image.open('input.png')
image = image.resize((image.size[0]/pixelSize, image.size[1]/pixelSize), Image.NEAREST)
image = image.resize((image.size[0]*pixelSize, image.size[1]*pixelSize), Image.NEAREST)
pixel = image.load()
for i in range(0,image.size... | true |
2d34d2420f4f26227dd075d0ce5a9e59abbd68ce | Python | bcmoritz/Week7 | /Assessment.py | UTF-8 | 6,773 | 3.171875 | 3 | [] | no_license | import requests
from bs4 import BeautifulSoup
import json
from dataclasses import dataclass, field
import datetime
import sys
from datetime import date
url = "https://api.tomorrow.io/v4/timelines"
querystring = {
"location":"43, 87",
"fields":["temperature", "cloudCover"],
"units":"imperial",
"timesteps":"1d",
"apike... | true |
0d5d07f5e98c3400a4706846a5f53940367dc5f4 | Python | user-789/GoodImageEditor | /goodImageEditor.py | UTF-8 | 3,726 | 2.640625 | 3 | [
"MIT"
] | permissive | import sys
import re
import os
def getstr(line, cursor = -1):
str_ = ""
for i, (r, g, b) in enumerate(line):
char = "[]" if i == cursor else " "
xcolor = 255 if r+g+b <= 384 else 0
str_ += f"\033[48;2;{r};{g};{b}m\033[38;2;{xcolor};{xcolor};{xcolor}m\033[1m{char}\033[m"
return str_
def printimg(image):
for... | true |
8c1993f99c686032139cbdd7f2a910b6ebb9e32c | Python | Eloiza/Trabalho-IA2020 | /tsp.py | UTF-8 | 5,040 | 3.328125 | 3 | [] | no_license | import random
import itertools
class MSTGraph:
def __init__(self, vertices):
self.V = vertices
self.graph = []
def __str__(self):
return str(self.graph)
def add_edge(self, u, v, w):
self.graph.append([u, v, w])
def find(self, parent, i):
if parent[i] == i:
... | true |
5a843b30a68ab53926bef9b8c61d3ea8e5aefdbe | Python | nuriengincatak/Python_practice | /practice_python/Trying2-.py | UTF-8 | 339 | 3.671875 | 4 | [] | no_license |
try:
numb= int(input('Input a number:\n'))
check= int(input('Input a divisor:\n'))
if numb%4==0:
print('Even and multipe of 4')
if numb%check==0:
print('OK')
else:
print('Not OK')
except ValueError:
print('It is not a number!')
except ZeroDivisionError:
print('Diviso... | true |
f6fdd97fee0fc47493b11627b19290b62a0f34f6 | Python | maureengithu/bootcamp_7 | /day_3/oop.py | UTF-8 | 549 | 3.046875 | 3 | [] | no_license | from person import Person
from kenyan import Kenyan
p = Person('Joe', 23)
p2 = Person('Jane', 23)
p3 = Person('George', 40)
print p.say_hello()
a = [('jane', 23), ('joe', 50), ('jackie', 34), ('jacob', 23), ('jee', 18), ('josh', 60)]
b = []
for name,age in a:
person = Person(name, age)
b.append(person)
print b
... | true |
3892784ec42f213c24a3f13fb35f002a55e0a619 | Python | rrlins/python3-exercicios | /python_exercicios/ex019.py | UTF-8 | 504 | 4.21875 | 4 | [] | no_license | # Desafio 019 - Um professor quer sortear um dos seus quatro alunos para apagar
# o quadro. Faça um programa que ajude ele, lendo o nome dos alunos
# e escrevendo na tela o nome do escolhido.
from random import choice
a1 = input('Digite o nome do primeiro aluno: ')
a2 = input('Digite o nom... | true |
52be10eb437a3f3ba5c3547d2c2ce0521dfb3c58 | Python | Florian-Moreau/Development-Python | /SIO 1/DivisionQR.py | UTF-8 | 153 | 3.90625 | 4 | [] | no_license | d1=float(input ("Entrer le dividende : "))
d2=float(input ("Entrer le diviseur : "))
q = d1 // d2
r = d1 % d2
print('Quotient : ',q, ' Reste : ',r)
| true |
fab42d2bbb28bff895054c136584314f4091fb20 | Python | xis24/CC150 | /Python/FreqOfMostFrequentElement.py | UTF-8 | 965 | 3.734375 | 4 | [] | no_license | from typing import List
class FreqOfMostFrequentElement:
'''
The frequency of an element is the number of times it occurs in an array.
You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1.
Return the maxim... | true |
f2912ac7cfe9daa06d7d63b639299c2a7429f062 | Python | realAhmedRoach/MachineLearning | /ML_GettingStarted.py | UTF-8 | 2,967 | 3.828125 | 4 | [] | no_license |
# coding: utf-8
# In[ ]:
# import library of functions
from numpy import exp, array, random, dot
# In[ ]:
# the neural network class
class NeuralNetwork():
def __init__(self):
# seed the random number generator so the same
# numbers are generated every time
random.seed(1)
... | true |
f46157fec83b98389e4b14294c8cced34dc21694 | Python | lilymagliente/Udacity | /ML Pipeline Preparation.py | UTF-8 | 6,109 | 3.484375 | 3 | [] | no_license | #!/usr/bin/env python
# coding: utf-8
# # ML Pipeline Preparation
# Follow the instructions below to help you create your ML pipeline.
# ### 1. Import libraries and load data from database.
# - Import Python libraries
# - Load dataset from database with [`read_sql_table`](https://pandas.pydata.org/pandas-docs/stable/g... | true |
5f6aaefd0e37f0a2ddcfd3a7ea6c9481945ce26a | Python | Shakil-1501/Session12 | /Calculator/operations/ee.py | UTF-8 | 554 | 3.328125 | 3 | [
"MIT"
] | permissive | import math
#from sympy import *
from scipy.misc import derivative
__all__ = ['calc_expe']
def calc_expe(x):
#k=round(math.sin(x),2)
print('The value after calculation is {0}'.format(math.exp(x)))
return round(math.exp(x),2)
def derivative_exp(x):
#l=round(derivative(calc_sine,math.pi... | true |
740df2c500dcf578ad82d9a778a60f6b447e93bf | Python | hu-ng/timsort | /performance_compare.py | UTF-8 | 4,981 | 3.71875 | 4 | [] | no_license | from timsort import timsort
from normal_merge import mergesort
import matplotlib.pyplot as plt
import time
import math
# With random data
def graph_runtimes(length_lst, repeats):
merge_avg = []
timsort_avg = []
theory_time = [0]
# Providing data for theoretical run times
# Adjusted ... | true |
bf82271dc93082377a5ffd24bd7f6d605b4d733b | Python | csrgxtu/Sansa | /src/PlayWav.py | UTF-8 | 607 | 2.65625 | 3 | [] | no_license | #!/usr/local/env python
# encoding=utf-8
#
# Author: Archer
# File: PlayWav.py
# Desc: 通过声卡播放音频
import pyaudio
import wave
chunk = 1024
wf = wave.open('../data/odinary-signed-16bit-pcm.wav', 'rb')
p = pyaudio.PyAudio()
# 打开声音输出流
stream = p.open(format = p.get_format_from_width(wf.getsampwidth()),
ch... | true |
403b7228e9b0931418e3335fc7807c36c8d5d9c2 | Python | prasanthkp89/MTA-98-381-Introduction-to-Programming-Using-Python-1 | /04 Loops/example6.py | UTF-8 | 52 | 3.0625 | 3 | [] | no_license | # example 6
for i in range(1, 9, -1):
print (i)
| true |
7bb2bb9624b9149fc216f7252a8723f8a41ceb17 | Python | WSY-123/CourseDiscussion_1 | /search/tests.py | UTF-8 | 855 | 2.703125 | 3 | [] | no_license | from django.test import TestCase
from django.urls import reverse, resolve
from .views import index
class IndexTest(TestCase):
"""课程搜索主页测试"""
def setUp(self):
url = reverse('search:index')
self.response = self.client.get(url)
def test_index_views_status_code(self):
self.assertEqua... | true |
9f2d8b9633f9ca43639d5b7ba7ff2dcfcbdb4367 | Python | mohammedabbas15/Python-and-Data-Structures | /createDB.py | UTF-8 | 657 | 2.515625 | 3 | [] | no_license | # we will connect to a data base
import sqlite3 as sql
conn = sql.connect('TestDB.db')
c = conn.cursor()
# create table - Clients
c.execute('''CREATE TABLE CLIENTS
([generated_id] INTEGER PRIMARY KEY,
[Client_Name] text, [Country_ID] integer,
[Date] date)''')
# ... | true |
52670dae17dbbf11995946a7cb2c6dcf0429b3d6 | Python | PublicMakings/openCVexperiments | /alphabets/handwriting_reader/checkLetters.py | UTF-8 | 1,518 | 2.859375 | 3 | [] | no_license | try:
from PIL import Image
except ImportError:
import Image
import pytesseract
import os
def tesseract():
# If you don't have tesseract executable in your PATH, include the following:
#pytesseract.pytesseract.tesseract_cmd = r'<full_path_to_your_tesseract_exec$
# Example tesseract_cmd = r'C:\Progra... | true |
d2508dd594826289f3f44e92a64cbaf07f922c36 | Python | smilejakdu/django_book_project | /main/blog/models.py | UTF-8 | 3,327 | 2.5625 | 3 | [] | no_license | from django.db import models
class Post(models.Model):
title = models.CharField(max_length=100, blank=True, null=True)
author = models.CharField(max_length=10, blank=True, null=True)
date = models.DateField(blank=True, null=True)
content = models.TextField(blank=True, null=True)
w... | true |
d7ba4045959aaa529e0bbb3c32b30ddd830a9b9e | Python | P-ppc/microblog | /app/forms.py | UTF-8 | 2,704 | 2.546875 | 3 | [] | no_license | from flask.ext.wtf import Form
from wtforms import StringField, BooleanField, TextAreaField, FileField
from wtforms.validators import DataRequired, Length
from app.models import User
from app import db
class LoginForm(Form):
username = StringField('username', validators = [DataRequired()])
email = StringField(... | true |
72e5904dc33303bfe6e333bd7c71d17c60d6fdef | Python | thelouwdown/UdacityPostGresProject | /sql_queries.py | UTF-8 | 2,846 | 2.703125 | 3 | [] | no_license | # DROP TABLES
songplay_table_drop = "DROP TABLE IF EXISTS songplays"
user_table_drop = "DROP TABLE IF EXISTS users"
song_table_drop = "DROP TABLE IF EXISTS songs"
artist_table_drop = "DROP TABLE IF EXISTS artists"
time_table_drop = "DROP TABLE IF EXISTS time"
# CREATE TABLES
songplay_table_create = ("""
CREATE TABLE... | true |
d1faa69142d7d8e381f4fd49b61af0d8d79e219d | Python | grabadabar/Hello-world | /test.py | UTF-8 | 240 | 2.953125 | 3 | [] | no_license | #!/usr/bin/env python
import os
import string
cars = ["lada" , "volga" , "zaz" , "shkoda"]
for x in cars:
if x == "zaz":
print(x)
names = [ "joro", "ilieq", "rosen", "jivko" ]
for y in names:
continue
print(y)
| true |
d804ae6cf085f50f83dbf84a5bd410ef8d205124 | Python | tausiq2003/Hacktoberfest-Python | /modulus.py | UTF-8 | 29 | 2.96875 | 3 | [] | no_license | a=25
b=15
c=a%b
print(c)
| true |
e5cc2485f5a083bca6e659f79c82dd37d0979692 | Python | ashwintk/TwitterInformationBubble | /TweetSearch/ProcessLocalFSPythonFile.py | UTF-8 | 2,263 | 2.828125 | 3 | [] | no_license | import json, re
from Tkinter import Tk
from tkFileDialog import askopenfilename
import TweetsLib as tlib
Tk().withdraw()
inputFile = askopenfilename()
print "File to be processed "+inputFile
with open(inputFile, "r") as readHandle:
for line in readHandle.readlines():
try:
# Load Tweets
... | true |
fe5f4ba28e04166ba0a048615ea47a78a8d7d774 | Python | maZymaZe/pyHW2.1 | /InputData.py | UTF-8 | 292 | 2.84375 | 3 | [] | no_license | def input_data(): #数据的文件读入
data = []
for i in range(30):
data.append(0)
f = open("data.txt", "r")
for i in range(29):
line = f.readline().split()
data[int(line[0])] = int(line[1])
f.close()
return data
#input_data() | true |
4eb9e723a211848567c00221ba70ff992e0746d3 | Python | NiceToMeeetU/ToGetReady | /Demo/DataStructre/_TOOL.py | UTF-8 | 478 | 2.890625 | 3 | [] | no_license | # coding : utf-8
# @Time : 21/02/16 19:24
# @Author : Wang Yu
# @Project : ToGetReady
# @File : _TOOL.py
# @Software: PyCharm
import time
def cal_time(func):
"""
程序计时简单装饰器
"""
def wrapper(*args, **kwargs):
t1 = time.time()
res = func(*args, **kwargs)
... | true |
323e16dc401c4167ac0e1390e3e901d12e048f72 | Python | opbeat/opbeatcli | /opbeatcli/exceptions.py | UTF-8 | 838 | 2.53125 | 3 | [
"BSD-2-Clause"
] | permissive | #noinspection PyCompatibility
import argparse
class OpbeatError(Exception):
"""
Our base exception. It's not shown to the user, because it's assumed
an error message has been logged.
"""
class InvalidArgumentError(OpbeatError, argparse.ArgumentTypeError):
"""Invalid command line argument"""
c... | true |
7e17a2c3fc281d38550a5e57b08a5e7666000e75 | Python | Zovube/Tasks-solutions | /Timus/Vol.03/1228/sol.py | UTF-8 | 261 | 3.15625 | 3 | [
"MIT"
] | permissive |
n, s = (int(i) for i in input().split())
aa = []
for i in range(n) :
aa.append(int(input()))
ans = []
x = 1
for i in range(n - 2, -1, -1) :
ans.append(aa[i] // aa[i + 1])
ans.append(s // aa[0])
for x in ans[::-1] :
print(x - 1, end=' ')
| true |
9b7ef3619cfb35526b5521fef23ace12b743b1be | Python | kjh03160/fund_python | /data_processing1/prac7_1.py | UTF-8 | 482 | 4.0625 | 4 | [] | no_license | def triangle(height):
for i in range(0, height):
for j in range(i + 1):
print("*", end = "")
print()
height = int(input("삼각형의 높이 입력 : "))
triangle(height)
def triangle():
height = int(input("삼각형의 높이 입력 : ")) # height를 정의 안에 넣으면 파라미터 불필요
for i in range(0, heigh... | true |
ebc8a08c8108bca1d03f39ceb62840d9bf20625d | Python | ABGEO/vigenere.py | /main.py | UTF-8 | 1,095 | 3.53125 | 4 | [
"MIT"
] | permissive | from viginere import Viginere as vC
if __name__ == '__main__':
# Define keys.
key_string = 'somekey'
key_tuple = tuple(key_string)
key_list = list(key_string)
# Define text for encryption.
text_string = 'Hello, World!'
text_tuple = tuple(text_string)
text_list = list(text_string)
... | true |
b88eb370343e193da1e92b335ec9b708dc932f14 | Python | fhchstr/check_galera | /check_galera | UTF-8 | 12,851 | 2.546875 | 3 | [] | no_license | #!/usr/bin/env python
#
# Author: Fabien Hochstrasser <fabien.hochstrasser@swisscom.com>
# Date: 2018-03-20
# Purpose: Nagios check to monitor the health of a Galera cluster node.
#
# It implements all the recommendations documented on the Galera Cluster website
# as well as ideas discussed with the MariaDB support... | true |
474d780185b775c18cb3cb9979c29a08f5792a5c | Python | JeffreyMaurer/Code_Challenges | /findPrime/prime.py | UTF-8 | 255 | 3.21875 | 3 | [] | no_license | import sys
def is_prime(i):
j = i // 2
while j > 2:
if (i / j) * j == i:
return 0
j -= 1
return i
print '\n'.join( \
['\t'.join(['%i' % is_prime(x) for x in range(i, i + 10)] \
) for i in range(0, 1000, 10)])
| true |
588ecd7856531fb298d82080db7f7dabd2f4ab6d | Python | HoMLSHSID/HoMLSHSID.github.io | /src/pythonFun.py | UTF-8 | 3,773 | 3.609375 | 4 | [] | no_license | ##Python Turtle
##Draw "HAPPY BIRTHDAY"
##Produced by Kaku, Kitetsu
##Version 0.0.1 Beta (I have no idea about the meaning of these numbers)
##Published on Feb 3, 2019
from turtle import*
import math
print()
def square(length):
for i in range(4):
t.fd(length)
t.left(90)
def draw_square(x, y, leng... | true |
b2c7db8a2107541de5bb5fae0544576ed9d53f56 | Python | dellielo/Pharmap | /src/data_structuration/phylotree.py | UTF-8 | 4,246 | 2.890625 | 3 | [] | no_license | import tools
import config
import pandas as pd
from ete3 import Tree, TreeStyle, NCBITaxa, NodeStyle, faces, AttrFace, TreeFace
import itertools
from db import dbDriver
class PhyloTree(Tree):
'''
TODO :
Put the distribution and environmental pandaDataframe without useless columns (taxonomy) thus mak... | true |
466abc3fcd5487d06377b581b9d00d602e5362e5 | Python | snpdevop/Data_Science | /Python/f1.py | UTF-8 | 33 | 2.640625 | 3 | [] | no_license | a = 2
b = 12
c = a + b
print(c)
| true |
b64cb91b30ce6de25ca90a9080eab0676eda8db2 | Python | 1399959932/python | /day3+4.py | UTF-8 | 4,547 | 4.34375 | 4 | [] | no_license | # C:/Users/JK-chenxs/AppData/Local/Programs/Python
# python内置数据类型:
# 列表:list是一种有序的集合,可以随时添加删除其中的元素 优点:方便操作
# classmates = ['Micheal','Bob','JK-chenxs']
# classmates
# len(classmates)
# php的数组array 相似与 python的列表list
# len()返回容器中的项数 我理解为长度或者是个数
# classmates[0]
# -1可以取最后一个元素,以此类推
# list操作方法 ,以下 'var' = '变量'' ,p... | true |
bfb11600c0bdd514a1a4adf1bedb228f11eddee9 | Python | asladej1/Basketball_Stats_Tool | /app.py | UTF-8 | 5,284 | 3.28125 | 3 | [] | no_license | #looking to qualify for "exceeds expectations" grade.
import copy
from constants import PLAYERS
from constants import TEAMS
GREETING = 'BASKETBALL TEAM STATS TOOL\n'
players = copy.deepcopy(PLAYERS)
teams = copy.deepcopy(TEAMS)
max_players = len(players)/len(teams)
exp_players = []
nexp_players = []
panthers = []
... | true |
7900bf5fe962b83d65f07dd8dc066fdc8c78228f | Python | dongfangzhang/Project_P876_Tools | /CheckPPCLnBOM.py | UTF-8 | 2,346 | 2.71875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 4 16:45:42 2020
@author: zhang_d2
"""
import pdfplumber
import pandas as pd
import re
from pandas import DataFrame
#%%
PDFpath=r'C:\Users\zhang_d2\Desktop\P.876_IBCM10.pdf'
Excelpath=r'C:\Users\zhang_d2\Desktop\PPCL-P.876-M50-CA-ALT2_20200703.xlsx'
#%% check name consis... | true |
3ded6a28a7316ba8de24ed94c35f2d0bf99e51a8 | Python | olymk2/scaffold | /scaffold/libs/truncate.py | UTF-8 | 236 | 3.390625 | 3 | [] | no_license |
def paragraph(content, length=100, suffix='...'):
"""shorten text with out cuting of mid word"""
if len(content) <= length:
return content
else:
return ' '.join(content[:length+1].split(' ')[0:-1]) + suffix
| true |
75134047ac7ea971bd4c8e0df368eb13000a89ef | Python | fgdangiolo/Python | /UART_Python/Rx/Com_Rx.py | UTF-8 | 807 | 3.796875 | 4 | [] | no_license |
import serial
def get_data_port(usb_port):
#Flush of file like objects
usb_port.flushInput()
#Read data from port
data_read = usb_port.readline()
return(data_read)
def data_to_string(data):
#Convert data in bytes to string
data_string = data.decode()
return(data_string)
if... | true |
3e045c52dd74db35acc2105f9fb17d6f179d5b6f | Python | michaelmagdyshaker/Extract-and-translate-text-from-image- | /average_precision.py | UTF-8 | 6,656 | 2.859375 | 3 | [] | no_license | import numpy as np
from collections import defaultdict ,namedtuple
Size = namedtuple('Size', ['w', 'h'])
IMG_SIZE = Size(1000, 1000)
def prop2abs(center, size, imgsize):
width2 = size.w*imgsize.w/2
height2 = size.h*imgsize.h/2
cx = center.x*imgsize.w
cy = center.y*imgsize.h
r... | true |
3cfc79fb34cf43c97ef15d6ddc793ac1235ad26e | Python | apast/python-brasil-toolkit | /pybr/__main__.py | UTF-8 | 693 | 2.71875 | 3 | [] | no_license | import csv
import sys
import click
@click.group()
def cli():
pass
@cli.command()
@click.option("-c", "--columns", type=click.File("r"), help="File with columns to keep")
@click.option("csvout", "--out", default=sys.stdout, type=click.File("w"), help="Save output to file")
@click.argument("file", type=click.Fil... | true |
563642ccb58a4029bc948d87ea89e7b21cb0dcb0 | Python | smaass/colador | /tests/test_messages_group.py | UTF-8 | 1,179 | 3.15625 | 3 | [
"MIT"
] | permissive | from unittest import TestCase
from colador.messages_group import MessagesGroup
class MessagesGroupTestCase(TestCase):
def test_iteration(self):
some_messages = ['a', 'b', 'c', 'd']
group = MessagesGroup(None, some_messages)
for i, message in enumerate(group):
self.assertEqu... | true |
ed778f1eaa27228cfe3bf34d2caaa15e0fbe415b | Python | hyperledger-archives/indy-stp | /stp_core/common/logging/TimeAndSizeRotatingFileHandler.py | UTF-8 | 1,518 | 2.640625 | 3 | [] | no_license | import os
from logging.handlers import TimedRotatingFileHandler
from logging.handlers import RotatingFileHandler
class TimeAndSizeRotatingFileHandler(TimedRotatingFileHandler, RotatingFileHandler):
def __init__(self, filename, when = 'h', interval = 1, backupCount = 0,
encoding = None, delay = F... | true |
9448e9ca06fb5aa7241c4d00c0abbb3fc72bca97 | Python | arjun921/Python-TIL | /misc/hackerrank/general/Two Characters.py | UTF-8 | 178 | 3.078125 | 3 | [] | no_license | import re
n=int(input())
s = input()
r = re.compile("^[a-z]*$")
if len(s) in range(1,1001):
if len(s)<=n:
if r.match(s):
for x in s:
else:
print('Invalid Input')
| true |
0f0c8223a9ba9faaa8c7b72a9cee6837b9214736 | Python | luuklsl/ARPNLP | /NLG.py | UTF-8 | 8,184 | 2.765625 | 3 | [] | no_license | import sqlite3
import nltk
import json
from nltk.stem.snowball import EnglishStemmer
def transform_to_past(tag):
ps = EnglishStemmer()
tag_0, tag_1 = tag
tag_0 = ps.stem(tag[0])
print("tag_0", tag_0)
if tag_0 == 'be' or tag_0 == 'is':
tag_0 = 'was'
elif tag_0 == 'begin':
tag_0 ... | true |
4e0a088bedadb527e3adf2ae275a5a6f00c39261 | Python | Ale1120/Learn-Python | /Fase4-Temas-avanzados/tema12-Manejo-de-ficheros/ejerccio/gestor.py | UTF-8 | 1,976 | 3.703125 | 4 | [] | no_license | # ejerccios 3
from io import open
import pickle
class Personaje :
def __init__(self, nombre, vida, ataque, defensa, alcance):
self.nombre = nombre
self.vida = vida
self.ataque = ataque
self.defensa = defensa
self.alcance = alcance
def __str__(self):
return "{} ... | true |
ac58dc71bd88b8d6d88b3e5f9c9c34326e1ea5d4 | Python | bunshue/vcs | /_4.python/class/test04_class6c.py | UTF-8 | 726 | 4.125 | 4 | [] | no_license | # 定義Vehicle父類別
class Vehicle:
# 建構子
def __init__(self, name):
self.name = name
# 方法
def getName(self):
return self.name
# 方法
def displayVehicle(self):
print("廠牌: ", self.name)
# 定義Car子類別
class Car(Vehicle):
# 建構子
def __init__(self, name, model):
# 呼叫父類... | true |
ebd379f07ee461b36c4ad896f1ed9a9b19fe3965 | Python | Markiewi/AlgGeo | /labs/useless/SweepingAlgorythm/RedBlackTree.py | UTF-8 | 13,639 | 3.359375 | 3 | [] | no_license | from TreeNode import *
class RedBlackTree:
NIL_LEAF = TreeNode(segment=None, color=NIL, parent=None)
def __init__(self):
self.count = 0
self.root = None
self.ROTATIONS = {
'L': self._right_rotation,
'R': self._left_rotation
}
def insert(self, segme... | true |
9ece95172907b1fca5fe7906f03674fee7408736 | Python | twang1010/fluent | /deco/clock_demo.py | UTF-8 | 477 | 3.546875 | 4 | [] | no_license | import time
from clock_deco2 import clock
@clock
def snooze(seconds):
time.sleep(seconds)
@clock
def factorial(n):
return 1 if n < 2 else n * factorial(n-1)
if __name__=='__main__':
print('*' * 40, 'calling snooze(.123)')
snooze(.123)
print('*' * 40, 'calling factorial(6)')
print('6! =' , fa... | true |
9e6d9bf1dd48be7ee5f972adcc4b56578d8298c6 | Python | BarryZM/Python-AI | /MachineLearning/OVO&OVR/error-correcting.py | UTF-8 | 769 | 3.046875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
'''
Created by hushiwei on 2018/6/18
Desc : Error-Correcting案例代码
'''
from sklearn import datasets
from sklearn.multiclass import OutputCodeClassifier
from sklearn.svm import LinearSVC
from sklearn.metrics import accuracy_score
# 数据获取
iris = datasets.load_iris()
x, y = iris.data, iris.t... | true |
8af072099e7eea68aa99cb0e243e70b2658c76bc | Python | Sighter/remeta2 | /File.py | UTF-8 | 2,434 | 3.078125 | 3 | [] | no_license | #!/usr/bin/python3
# File.py
# @Author: The Sighter (sighter@resource-dnb.de)
# @License: GPL
# @Created: 2011-07-20.
# @Revision: 0.1
from os import path
from shutil import copy
from os import rename
from TagHeader import TagHeader
from stagger.errors import *
from Helpers import ePrint
## class f... | true |
869e8e2dbabd36973b8990f34c2066c3ff989582 | Python | Miloloaf/Self-Scripts | /amazon_search.py | UTF-8 | 1,435 | 2.734375 | 3 | [] | no_license | #! python3
import requests, bs4, webbrowser, sys
# Opens the first 5 links of the search term in Amazon in a webbrowser
# TODO Remove "Top Rated from Our Brands"
searchterm = "cables"
#req = requests.get("https://www.amazon.co.uk/s/ref=nb_sb_noss_2?url=search-alias%3Daps&field-keywords=" + " ".join(sys.argv[1:]))
r... | true |
09559879f1550d9591b21c6aade7cf5bc3b6032e | Python | catanzaromj/MPFigs | /Wrinkled_cylinder/wrinkled_cylinder_slices.py | UTF-8 | 4,584 | 2.921875 | 3 | [] | no_license | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
This code creates an html file, plotting the x = const slices of the wrinkled cylinder.
"""
import plotly
import plotly.graph_objs as go
import numpy as np
## Grid parameters
xdiv=100
tdiv=50
## Make the rectangular grid, the surface of the dented cylinder
theta = n... | true |
e794937cba2fdb45cec6926ac263df96c9fb730b | Python | lianhuaren/deeplearningin30days | /python剑指offer/codinginterview15.py | UTF-8 | 675 | 3.203125 | 3 | [] | no_license | #coding=utf-8
class Solution:
def NumberOf1(self, n):
if n < 0:
n = n&0xffffffff
n = bin (n)
print (n)
length = len(str(n))
# print (length)
count = 0
for i in range(length):
print (str(n)[i])
if "1" == str(n)[i]:
... | true |