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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
620ac7ac402725c02cd6f6013ef91fc7a44be896 | Python | DrexelSTARChess/server | /boardTranslator.py | UTF-8 | 4,472 | 3.6875 | 4 | [] | no_license | from board import Board
from rook import Rook
from knight import Knight
from bishop import Bishop
from queen import Queen
from king import King
from pawn import Pawn
def client_to_server(board):
"""
Translates client format of board to server format
board: A 2D array of strings representing the board
... | true |
6cbebd5cb1997ec696665cbc7fa19d5fcbe174d5 | Python | sleyzerzon/soar | /Deprecated/GGP/analogy/test_gen/multimap.py | UTF-8 | 222 | 3.28125 | 3 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | class MultiMap:
def __init__(self):
self.__m = {}
def __getitem__(self, k):
if k in self.__m:
return self.__m[k]
else:
return []
def __setitem__(self, k, item):
self.__m.setdefault(k, []).append(item)
| true |
d2c303d04f493eb7c3d37a3dd04e348dab145fe1 | Python | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/kindergarten-garden/bf458b3dcf93449ba18668151456aaff.py | UTF-8 | 561 | 3.09375 | 3 | [] | no_license | plants = { 'G': 'Grass', 'V': 'Violets', 'R': 'Radishes', 'C': 'Clover' }
childrens = [ 'Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Fred', 'Ginny',
'Harriet', 'Ileana', 'Joseph', 'Kincaid', 'Larry' ]
class Garden(object):
def __init__(self, windows, **kwargs):
self.childrens = sorted(kwargs.get('students', ... | true |
463ddd29c834a92a9b68751987c92eaf961e474b | Python | SKrishna93/EPAi3-Session12 | /customPolygon.py | UTF-8 | 2,478 | 3.609375 | 4 | [] | no_license | from polygon import Polygon
class Polygon_Sequence :
"""
Implementaion Of Custom Sequence of Polygons which takes
largest polygon num of edges and circumradius as input
"""
def __init__(self, num_edges : int , circumradius : float) -> None:
self._largest_num_edges = num_edges
self.... | true |
29aa4ec214f08343db84a63f057d53dfc7dc52e3 | Python | WayneRocha/Desafios_python-CeV | /6 - Condições (if,else e elif)/desafio32.py | UTF-8 | 322 | 4.28125 | 4 | [] | no_license | # ler um ano e mostrar se ele é BISEXTO
print("Ano Bisexto?")
print("-" * 20)
ano = int(input('Digite um ano: '))
if ano % 100 != 0 and ano % 4 == 0:
print('É um ano \033[35mBISEXTO!\033[m')
if ano % 100 == 0 and ano % 400 == 0:
print('É um ano \033[35mBISEXTO!\033[m')
else:
print('Apenas um ano normal')
| true |
c343a0d1a03cc2491690a4e34d1ca46d9b89cc43 | Python | daum913/python_project | /assignments/if-2/if-2_2.py | UTF-8 | 682 | 4.4375 | 4 | [] | no_license | # 문제 2.
# 나이를 입력받아 나이에 따라 지하철 교통요금 출력하는 프로그램을 만드시오.
# 8세 미만의 어린이의 지하철 교통요금은 450원이다.
# 8세 이상 19세 이하의 청소년 지하철 교통요금은 720원이다.
# 20세 이상의 성인 지하철 교통요금은 1250원이다
# 입력 예1: 2
# 출력 예1: "450원입니다."
# 입력 예2: 19
# 출력 예2: "720원입니다."
# 입력 예3: 82
# 출력 예3: "1250원입니다."
age = int(input("나이를 입력하세요 : "))
if age < 8 :
print("450원 입니다.")
e... | true |
d61ca233bac6ef973045db698d07dcefb6b4cc7d | Python | chouchouyu/my_words | /my_words/sign.py | UTF-8 | 680 | 2.671875 | 3 | [] | no_license | #來自拉丁語signum
#sign,符號
#signal,信號
signatory,簽署者,簽署方
#signature,簽名,簽字,署名
#significance,意義
#significant,重要的
#signify,表示
#as來,臨近sign標記
#assign,分配,指定,委派
#assigning,指定設備
#con,強調,sign,記號,標記,
consign--0,委託,交付給
#de加強意義sign標記
#design,設計
#designate,指明,指出
#designation,指示
#designer,設計者,構思者,時裝設計師
#en,進入,使,sign,記號,標誌,
ensign,艦旗
... | true |
fec7131ff0b1231052e7c968889947f03f014f14 | Python | edilsonlonC/Comp_grap | /limit.py | UTF-8 | 2,150 | 3.0625 | 3 | [] | no_license | import pygame
pygame.init()
import pygame
import random
from math import*
r=lambda: random.randint(0,255)
r2=lambda: random.randint(1,5)
pygame.init()
def transformation (cx,cy,x,y):
xp=cx+x
yp=cy-y
return xp,yp
def cartesianas(cx,cy,xp,yp):
x=xp-cx
y=cy-yp
return x,y
def Create... | true |
2077eba224b252bbcab1c92650de59069b1b45fc | Python | TolyaTalamanov/Radix-sort | /scripts/graphic_script.py | UTF-8 | 2,235 | 3 | 3 | [] | no_license | # -*- coding: UTF-8 -*-
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import mlab
# Значения по оси X
X = []
lower_bound = 1
upper_bound = 1000000
i = lower_bound
while(i <= upper_bound):
X.append(i)
i += 10000
# Набор значений по оси Y
Y_BRS = []
Y_CBRS = []
Y_LSRS = []
Y_LRS ... | true |
856a0a9dc6809edd91f7241aba171fd8feedfae9 | Python | momsspaghettti/coursera-programming-in-python | /Python_4/keras.py | UTF-8 | 799 | 2.671875 | 3 | [] | no_license | import tensorflow as tf
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train = x_train.reshape(60000, 784)
x_test = x_test.reshape(10000, 784)
x_train = x_train.astype('float')
x_test = x_test.astype('float')
x_train /= 255
x_test /= 255
y_train = tf.keras.utils.to_categorical(y_train... | true |
5f36949d1deca3243617731d6dacab4fee10f411 | Python | srihariprasad-r/workable-code | /unittest_debugging/debugging_sample.py | UTF-8 | 235 | 3.4375 | 3 | [] | no_license | def calc(i, n):
j = i * n
j = j - 1
if j % 2 == 0:
print('Even!')
else:
print('odd!')
return j
def f(n):
for i in range(n):
j = calc(i, n)
return
if __name__ == '__main__':
f(5) | true |
dd0fa5f684eef56759b91137a963102c609fea42 | Python | AengusDavies/Practicals | /prac_05/word_occurrences.py | UTF-8 | 536 | 4.0625 | 4 | [] | no_license | """
CP1404/CP5632 Practical
Program that prints counts of each word in dictionary
"""
words_to_count = {}
text = str(input("Text: "))
words = text.split()
for word in words:
try:
word_occurrences = words_to_count.get(word, 0)
words_to_count[word] = word_occurrences + 1
except KeyError:
... | true |
7945931866dc345c78c4f64ec493a6b9db1850d4 | Python | JPWS2013/PoE_F2013 | /Lab_1/lidar_classdef.py | UTF-8 | 943 | 3.703125 | 4 | [] | no_license | import math #Imports math to do trig calculations
class lidar: #Definition of a new class called lidar
def __init__(self, input_horz_ang=0, input_vert_ang=0, radius=0):
horz_ang=math.radians(input_horz_ang) #converts the horizontal angle from degrees to radians
vert_ang=math.radians(input_vert_ang) #converts the ... | true |
ce1ad28225adba194b8467b7aa2120f8c88e84d2 | Python | shali-mor/kmean | /client_consul/kmean-consul.py | UTF-8 | 4,504 | 2.65625 | 3 | [] | no_license | """
# Full Imports
This is a pure Python implementation of the K-Means Clustering algorithmn. The
original can be found here:
http://pandoricweb.tumblr.com/post/8646701677/python-implementation-of-the-k-means-clustering
"""
import sys, getopt, os, json
import requests
from cluster import *
from point import Point
... | true |
6f6d430fe2ff8cf6b5d663e4aa833d5f732db3f3 | Python | quangvinh86/Python-Exercises | /Level3-Advance/Ex3_22.py | UTF-8 | 1,385 | 4.28125 | 4 | [] | no_license | '''
Question:
Write a program to compute the frequency of the words from the input.
The output should output after sorting the key alphanumerically.
Suppose the following input is supplied to the program:
New to Python or choosing between Python 2 and Python 3? \
Read Python 2 or Python 3.
Then, the output should be:
... | true |
07e2d6b282271f504d51bde38a162fe0089dc969 | Python | dylan-meiners/lookout | /lookout.py | UTF-8 | 18,908 | 2.6875 | 3 | [
"MIT"
] | permissive | RED = "\033[;31m"
BLUE = "\033[34m"
GREEN = "\033[32m"
MAGENTA = "\033[35m"
RESET = "\033[;0m"
try:
import requests
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import smtplib
from email.mime.text import MIMEText
import time
import msvcrt
except Excep... | true |
3833bda31d1f14adc39d4257434ad18f69fc3c21 | Python | pgornstein/recommendation_system | /recommendations_system/controller/backend/saved.py | UTF-8 | 1,059 | 2.515625 | 3 | [] | no_license | import psycopg2
from .config import config_db
from .interact_db import get_session_user
import json
params = config_db()
connection = psycopg2.connect(**params)
cursor = connection.cursor()
def add_to_saved_movies(token, movie):
userid = get_session_user(token)
unformatted_title = movie['unformatte... | true |
d4e6124613b5fac04c14aba3af854ef81e51737e | Python | yangxiaoyong/gunstr | /py/oscillator.py | UTF-8 | 1,646 | 2.78125 | 3 | [] | no_license | #-*- encoding:utf-8 -*-
import time
import multiprocessing
from datetime import datetime
'''
oscillator 类接受一个代理对象,变量event
代理对象是multiprocessing.Manger类返回的一个实例
multiprocessing.Manager 可以让不同的进程共享状态和数据并且也支持其它数据
类型共享,比如: list, dict, NameSpace, Lock, RLock, Semaphore, Condition,
Event, Queue, Value, 和 Array,。除 list, dict, ... | true |
ced15313d5e592607cad972cd7d42d9ecaf6a358 | Python | JalexDooo/Project_2018_ | /database/dataset.py | UTF-8 | 897 | 2.796875 | 3 | [] | no_license | import os
import numpy as np
class get_file(object):
"""docstring for get_file"""
def __init__(self, file_dir):
super(get_file, self).__init__()
self.file_dir = file_dir
def func(self):
image_rule = ['png', 'jpg', 'jpeg']
labels = []
images = []
temp = []
for root, sub_folders, files in os.walk(self.... | true |
edead62969e93cc62c617286326f8f725957fccd | Python | lwher/CS420-Project | /deep_learning_methods/data_loader.py | UTF-8 | 1,137 | 2.765625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import csv
import os
import numpy as np
def LoadDataSubset(data_csv):
csv_file = data_csv
num = 1
data_list = []
label_list = []
with open(csv_file) as f:
csvr = csv.reader(f)
header = next(csvr)
for i, (label, pixel) in enumerate(csvr):
p... | true |
a8dc7cd8a6f9099df6ce0cc99287f286c2029a3c | Python | okayell/Scikit-learn_practice | /Iris_KNN_1.py | UTF-8 | 608 | 2.953125 | 3 | [] | no_license | import pandas as pd
from sklearn import datasets
from sklearn import neighbors
from sklearn.model_selection import train_test_split
iris = datasets.load_iris()
X = pd.DataFrame(iris.data, columns=iris.feature_names)
X.columns = ["sepal_length","sepal_width","petal_length","petal_width"]
target = pd.DataFrame(iris.tar... | true |
f40948e6bc058cbb119c82d4d66a219a4587567a | Python | Hellsender01/Naughty_Debian | /src/rebuild_deb.py | UTF-8 | 2,478 | 2.515625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/python3
import subprocess
import os
from colorama import Fore, Style
import shutil
def rebuild_deb(filename: str, payload: str):
rebuild_deb.filename = filename
printout('[+] Extracting Package....', 'blue')
extract()
printout('[+] Looking for Already Present Scripts....', 'blue')
scri... | true |
0db7ffd097e87f58c7fb74b5f54f1a61423d2bc8 | Python | adonis-lau/LeetCode-Python | /project/22.generate-parentheses.py | UTF-8 | 1,461 | 3.765625 | 4 | [] | no_license | #!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
22. Generate Parentheses
https://leetcode.com/problems/generate-parentheses/
参考:
https://blog.csdn.net/timemagician/article/details/79096914
符合规则的一定是左括号开头,所以先从左括号开始暴力破解
左括号添加数量够了之后,再从右括号开始
效率较低
"""
from typing import List
class Solution:
def generateParenthesis(sel... | true |
7e3dd13912a14be5679f06f9577090a8bea23f52 | Python | farshidjf/advent-of-code-2020 | /Day06/lol.py | UTF-8 | 198 | 2.5625 | 3 | [] | no_license | groups = open('./Day6/large_input').read().strip().split('\n\n')
print(sum(len(set(g.replace('\n', ''))) for g in groups))
print(sum(len(set.intersection(*map(set, g.split('\n')))) for g in groups)) | true |
ddda02473ba71bf752d22572e92a52bd9dff6f35 | Python | BlandineLemaire/StegaPy | /tools/charSearch.py | UTF-8 | 1,223 | 4.5625 | 5 | [] | no_license | '''
Fonction :
charSearcher(byteList)
byteList : liste de byte dans lesquels on va chercher tout les caracteres qui sont imprimable
Explication :
charSearcher est une fonction qui permet de trouver tout les caracteres imprimable qui sont dans
une liste de bytes et de les retourner dans une v... | true |
1dca57e5de4a7e9e4e8ddef730a385b8d73d3547 | Python | in-silico/statistical-modeling | /lab4/ShortCourse_lab4.py | UTF-8 | 3,491 | 2.5625 | 3 | [] | no_license | import numpy as np
import pylab as pb
import scipy as sp
import GPy
pb.ion()
##############################
# functions
def Q2(F,mX):
return(1-sum((F-mX)**2)/sum((F-np.mean(F))**2))
# This functions converts the original parameters into the new one:
# Wl,Ww,Tl,Al -> Wl, Wp (Wing area), Hl (Total helicopter lengt... | true |
0f4133e62d518ec7f6a3b63e693842ed3e52bcfa | Python | michaelaradova/kurz | /06/DP/ukol_10.py | UTF-8 | 904 | 3.921875 | 4 | [] | no_license | """Vypise tabulku vsech variant vzajemneho nasobeni cisel od 0 do uzivatelem
zadaneho cisla"""
print("Vypisu tabulku vsech variant vzajemneho nasobeni cisel od 0 do" +
" zadaneho cisla.")
maximum = int(input("Zadej cele kladne cislo: "))
while maximum <= 0:
maximum = int(input("Zadane cislo musi byt kladn... | true |
92c6360d6056460bb58e5245d373ddf19f6bd34c | Python | jstevenpappas/datastrs | /sorting/insertion_sort.py | UTF-8 | 625 | 3.875 | 4 | [] | no_license |
def insertion_sort(alist):
for index in range(1, len(alist)):
current_value = alist[index]
position = index
while position > 0 and alist[position - 1] > current_value:
alist[position] = alist[position - 1]
position = position - 1
alist[position] = curr... | true |
7af93807d4722957b735e3f7c1d4a8227a37aacb | Python | beadsland/fixTracks | /savvy/common/lazydict.py | UTF-8 | 1,395 | 3 | 3 | [] | no_license | # Copyright 2020 Beads Land-Trujillo
import collections
import itertools
class LazyDict(collections.MutableMapping):
def __init__(self, source, keyfunc, dict=None):
self._source = iter(source)
if not callable(keyfunc): raise TypeError("unhashable type")
self._keyfunc = keyfunc
self._dict = dict if d... | true |
53e2e77e5efc1dbfad4e595cfbfb86a95d94b4c8 | Python | alexandraback/datacollection | /solutions_5756407898963968_0/Python/vector9x/magictrick.py | UTF-8 | 442 | 3.09375 | 3 | [] | no_license | def read_mat():
return [raw_input().split() for i in xrange(4)]
for _t in xrange(int(raw_input())):
row1 = int(raw_input())
set1 = set(read_mat()[row1-1])
row1 = int(raw_input())
set2 = set(read_mat()[row1-1])
inter = set1 & set2
if len(inter)==1:
res = inter.pop()
elif len(in... | true |
25460b6a3f9a6c780ad59d3761f05566e616c2ea | Python | andrecianflone/seq2seq_drr | /pdtb_helper.py | UTF-8 | 13,329 | 2.890625 | 3 | [] | no_license | """
Author: Andre Cianflone
"""
import random
import codecs
import os
import re
import json
import copy
from random import shuffle
def scan_folder(directory, output_file):
""" Scan raw PDTB files and save as a single json """
print("Scanning dir for pipe files: ", directory)
for walk in _walklevel(directory, lev... | true |
e01a2c9f2b7790af28400e94a1e88bdbf249aeda | Python | themanoftalent/Python-3-Training | /08 Some Works/02_python.py | UTF-8 | 219 | 3.25 | 3 | [] | no_license | # Python three some new works easy
# !_author_: Manoftalent
print(3 + 4)
print(3 * 20)
print(12 / 4)
print(8 + 2 * 10)
print((8 + 2) * 10)
print(18 / 4)
a = 18 // 4
print(a)
b = 18 % 4
print(b)
print(5 * 5 * 5)
| true |
8738a84a2e2c72f41a673c2567a5720fdae983a2 | Python | chanpatrick/gym-forex | /agents/agent_DQN.py | UTF-8 | 5,035 | 2.734375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import random
import gym
from gym.envs.registration import register
import numpy as np
from collections import deque
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import Adam
from keras import backend as K
EPISODES = 2000
class DQNAgent:
def __in... | true |
db0ee7f18f03605e10a8dc532adb12bd920bc66c | Python | ARC-21-0408/400B_Cunningham | /Homeworks/Homework5/CenterOfMass.py | UTF-8 | 12,451 | 3.203125 | 3 | [] | no_license | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
# Homework 4
# Center of Mass Position and Velocity
# Seen Cunningham
# In[1]:
# import modules
import numpy as np
import astropy.units as u
import astropy.table as tbl
from ReadFile import Read
# In[2]:
class CenterOfMass:
# Class to define COM position and ve... | true |
bdbc878d5f8f96a5440119220b6035ce7c8dcb5a | Python | chengzizhen/Airmcl_Test | /MyTestProjects/Test_case/url_case/class_threading.py | UTF-8 | 513 | 3.1875 | 3 | [] | no_license | import threading
class ThreadingA(threading.Thread):
def __init__(self, threadName):
threading.Thread.__init__(self)
self.name = threadName
def run(self):
print('In run:', self.name)
def output(self):
print('In output:', self.name)
class ThreadingB(ThreadingA):
def ... | true |
98871764cba7afe415cd382a313e67a22645db19 | Python | msds-thakur/Artificial-Intelligence-and-Deep-Learning-Python | /Assignment4.py | UTF-8 | 8,491 | 2.890625 | 3 | [] | no_license |
# coding: utf-8
# In[2]:
#Prabhat Thakur Date 06/07/2019
#2019SP_MSDS_458-DL_SEC56 Week10- Assignment4
#Create deep neural networks CNN for Gender classcification.
#Data : Downloaded from Google
#Code Addopted from F. Challot (2018), Deep Learning with Python (Manning)
# and https://github.com/arunpo... | true |
c3c3af88a171def8a1488695408c2891712da368 | Python | leodue/Spark-Scale-adaptation-study | /单节点/spark_lr_en30.py | UTF-8 | 1,941 | 2.8125 | 3 | [
"Apache-2.0"
] | permissive | # -*- coding: UTF-8 -*-
from pyspark import SparkContext,SparkConf
from pyspark.mllib.feature import HashingTF, IDF
from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.classification import LogisticRegressionWithSGD
from pyspark.sql import SparkSession
from pyspark.sql import SQLContext
from pyspark.... | true |
85a7dc42c64fc9d37e69166c0f7f3f16090906d9 | Python | bsb808/crlb-abv | /crlb_usbl_alongaxis.py | UTF-8 | 6,042 | 2.53125 | 3 | [] | no_license |
import crlbutils as cu
reload(cu)
close('all')
# Position
L=300
L=10.0
LL = [300.0,10.0]
for L,ll in zip(LL,range(len(LL))):
XX = linspace(1,L,10)
y = 0
xb = 0
yb = 0
# Parameters
# USBL
dtUsbl = 5.0
varr = (0.04)**2 #0.3)**2 #(0.14)**2 # USBL range variance
vara = (0.9*pi/180.... | true |
f1e0f9ec4809266df2a6da8a212440bb6a902cd7 | Python | mnbotk/python_study | /sort1.py | UTF-8 | 160 | 3.578125 | 4 | [] | no_license |
# coding: utf-8
lst1 = ["fly", "good", "ABC", "Bad", "Woo", "Foo", "and"]
lst2 = sorted(lst1)
print(lst2)
lst2 = sorted(lst1, key = str.upper)
print(lst2)
| true |
76283bee63552ed29fec1cd9794b4b46e7f187fc | Python | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_96/437.py | UTF-8 | 927 | 3.09375 | 3 | [] | no_license | import pprint
def create_table(surprising=False):
d = 2 if surprising else 1
table = {}
for i in xrange(0, 11):
r = xrange(max(0, i - d), min(i + d, 11))
for j in r:
for k in r:
s = i + j + k
m = max([i, j, k, table.get(s, 0)])
table[s] = m
return table
def count(surprising, p, notes, m, ms):
... | true |
9a94dd44c89468bfa112b407649b3c1e38dc3a52 | Python | Anh1223/C4T6-All | /C4T6/test/test3.py | UTF-8 | 224 | 3.578125 | 4 | [] | no_license | color_list=[]
n=int(input("How many new color?"))
color_list.append(new_color)
for i in range(n):
new_color=input("New color?")
color_list=[]
color_list.append(new_color)
for color in color_list:
print(color) | true |
3faeee515ee6b98564beb838f23a14631c926db3 | Python | tawrahim/Taaye_Kahinde | /Taaye/chp5/progs/average_finding_machine.py | UTF-8 | 488 | 4.0625 | 4 | [] | no_license | #2
print "*************************************************************\n"
print "Let me find the average of any 3 number you like."
number1= float(raw_input("Type in your first number."))
number2= float(raw_input("Type in your second number."))
number3= float(raw_input("Type in your third number."))
sum= number1... | true |
7159ece38977a7ee555861fae3efca836cab5a7e | Python | sonal7930/numpy_advanced_project | /q03_get_toss_win_count/build.py | UTF-8 | 445 | 2.875 | 3 | [] | no_license | #Default Imports
import numpy as np
ipl_matches_array =np.genfromtxt("data/ipl_matches_small.csv", dtype="|S50", skip_header=1, delimiter=",")
team = 'Mumbai Indians'
def get_toss_win_count(team):
#To get the records where Mumbai Indians had won the toss
team_records = ipl_matches_array[ipl_matches_array[:, 5... | true |
cf13bde0e802503e7e1c26203f666e97338d5809 | Python | Zzz-Ray/Digital-Image-Preocessing | /DIP_homework_形态学处理/ErodeDilate.py | UTF-8 | 1,069 | 2.78125 | 3 | [] | no_license | import numpy as np
from scipy import signal#为了调用其二维卷积函数
def imdilate(I,SE):
IM=np.array(I,dtype='uint8') #转换输入图像数值类型
IM_SE=signal.convolve(IM,SE,'same')#结构元SE与图像IM卷积
m,n=IM.shape
for i in range(m):
for j in range(n):
if IM_SE[i,j]!=0:#卷积结果不为0,则结果赋值为1(True),否则为0
... | true |
1addab2be3d7a2dfee09b7b012233140cea86bf1 | Python | jhalverson/data_science | /misc/the_numbers/choropleth_counties_svg/county_svg.py | UTF-8 | 3,185 | 3.15625 | 3 | [] | no_license | # Jonathan Halverson
# Friday, March 3, 2017
# Usage: python county_svg.py > poverty.svg
# This script makes a choropleth map of us counties
# http://flowingdata.com/2009/11/12/how-to-make-a-us-county-thematic-map-using-free-tools/
import pandas as pd
from bs4 import BeautifulSoup
us_state_abbrev = {
'Alabama': '... | true |
c540ace9a1428a541edc5c0b0fb7f397728429a6 | Python | danibencze/multiplexssh | /connection_collector.py | UTF-8 | 773 | 3 | 3 | [
"MIT"
] | permissive | import server_conn
class Runner:
def __init__(self):
self.connections = []
def multi_execute(self, command):
results = {}
for connection in self.connections:
stdin = connection.execute(command)
results[str(connection.get_address())] = stdin
for i in range(0, len(stdin)):
print(stdin... | true |
660d1e233750a0cb552c86ab77d3ada9036714dc | Python | wookim789/baekjoon_algo_note | /타사이트_문제풀이/leetcode/median.py | UTF-8 | 351 | 2.890625 | 3 | [] | no_license | class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
nums1 = nums1 + nums2
l = len(nums1)
nums1.sort()
result = 0
if l % 2 == 0:
a = l // 2 - 1
result = (nums1[a] + nums1[a + 1]) / 2.0
else:
result = nums1[l // 2]... | true |
992db114e1fdf7386d570add28a0278df17c603e | Python | karthikeyan-17/Simple-Python-program | /Palindrome of words.py | UTF-8 | 1,353 | 4.96875 | 5 | [] | no_license | ''' A palindrome is a word that is spelled the same backward and
forward, like “noon”and “redivider”.Recursively, a word is a palindrome
if the first and last letters are thesame and the middle is a palindrome.
The following are functions that take a stringargument and return the
first, last, and middle letters:
... | true |
4bdd7ec6c3588de1a328fc02760fd9229cd87931 | Python | ybim/stanford-algs | /greedy-algorithms/assignment_2/clustering.py | UTF-8 | 3,650 | 3.375 | 3 | [] | no_license | import copy
import itertools
from collections import namedtuple
Edge = namedtuple('Edge', ('head', 'tail', 'cost'))
class UnionFind:
def __init__(self, nodes):
self.nodes = nodes
self.leaders = dict()
self.members = dict()
for node in nodes:
# Keeps mapping of leaders... | true |
1283e7cafd3ec6428d09a29f34210b994db20680 | Python | Kodmackan/python-playground | /findCommonElements.py | UTF-8 | 473 | 3.90625 | 4 | [] | no_license | # Skriv ett program för att hitta antal lika värden i 2 givna listor.
array1 = [1, 2, 3, 4]
array2 = [1, 2, 3, 5]
array3 = [11, 22, 33, 44]
"""
Funktionen checkSameElements tar in 2 listor (arrayer) vars värden
jämförs och sedan returneras antalet lika värden i de båda listorna.
"""
def checkSameElements(arr1, arr2)... | true |
88cd220eb0221da4a44a6a71b0bfdb7aeb6fd36d | Python | Joaofreitas99/AudioBeamTree | /ProcessamentoC/dsb/ProcessamentoSinalemC/client.py | UTF-8 | 1,593 | 2.859375 | 3 | [] | no_license | #!/usr/bin/env python3
""" client.py - Echo client for sending/receiving C-like structs via socket
References:
- Ctypes: https://docs.python.org/3/library/ctypes.html
- Sockets: https://docs.python.org/3/library/socket.html
"""
import socket
import sys
import random
from ctypes import *
import json
import firebase_a... | true |
3958183011668fea8dde19e7c66942ded7bfb7ff | Python | mnihatyavas/Python-uygulamalar | /Bernd Klein (520) ile Python/p_31513.py | IBM852 | 2,328 | 2.703125 | 3 | [] | no_license | # coding:iso-8859-9 Trke
# p_31513.py: Ayn yatay eksenli ve iki farkl dikey grafik rnei.
import numpy as np
import matplotlib.pyplot as mp
from p_315 import Renk
ekil, altekil1 = mp.subplots()
x = np.arange (1, 7, 0.5)
altekil1.set_ylabel (r"Dairenin evresi $(sm)$", fontsize=16, color="blue")
for entik in... | true |
5cca3321a3d10c9019f1e8206b88461a079a8dfa | Python | jhaprerna/CrackingTheCodingInterview_Solutions | /Ch01_Q01Is Unique.py | UTF-8 | 383 | 3.625 | 4 | [] | no_license | import sys
input_string = input("Enter the string:")
#input = sys.argv[1]
#print(input)
unique_chars = ''.join(set(input_string))
#print(unique_chars)
print("=================================")
if (len(input_string) == len(unique_chars)):
print("The input string is unique")
else:
print("The input stri... | true |
459c853dac74d4bbe3fad033e7e5397a641d3da0 | Python | lbakke/hadoop-database-aggregation | /sumReduce.py | UTF-8 | 402 | 3.390625 | 3 | [] | no_license | #!/usr/bin/env python3
import sys
from operator import itemgetter
table = {}
for line in sys.stdin:
d_col, sum_col = line.split("\0")
if d_col in table:
try:
table[d_col] += int(sum_col)
except:
pass
else:
try:
table[d_col] = int(sum_col)
... | true |
0b6b247de0bd41f831f298c4e19a452f476a7183 | Python | yuanguLeo/untitled1 | /CodeDemo/QFEDU/Day10/安装第三方模块/安装第三方模块.py | UTF-8 | 343 | 2.890625 | 3 | [] | no_license | #!/usr/bin/env python
#_*_coding:utf-8_*_
from PIL import Image
'''
Pillow 非常强大的处理图像的工具库
pip install Pillow
Windows安装如果报错,则输入:pip install --upgrade pip 升级pip
'''
#打开图片
im = Image.open("2014.jpg")
#查看图片的信息
print(im.format, im.size, im.mode)
| true |
a7fa6a825147f8ab4892e7b81a212c8be28243a2 | Python | xxao/miniml | /miniml/flatten.py | UTF-8 | 2,423 | 3.15625 | 3 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | # Created byMartin.cz
import numpy as np
from . layer import Layer
class Flatten(Layer):
"""Represents a flattening layer of neural network."""
def __init__(self):
"""Initializes a new instance of Flatten."""
self._shape = None
def initialize(self, shape):
... | true |
2a363c00680f64812fcf46e9d965fabde573a6ab | Python | guillaume-philippon/raspi-test | /examples/gpio_monitor/cli/config.py | UTF-8 | 1,283 | 3.53125 | 4 | [] | no_license | """
This module will manage Command Line Interface (CLI) for gpio-monitor.
It will parse argument and build a configuration reference for gpio-monitor.
For more information about argparse, see https://docs.python.org/3/library/argparse.html
"""
import argparse
class Config: # pylint: disable=too-few-public-methods
... | true |
81c4ec0fffcf64c5186413b6be9aae260cc15a06 | Python | taishan-143/BrewApp | /src/classes/app_classes.py | UTF-8 | 12,724 | 3.03125 | 3 | [] | no_license | #Classes for the main app
import csv
import datetime
import pymysql
from src.functions.table_function import table, table_width, recipts
class Round:
def __init__(self):
self.person_tag = ''
self.drink_tag = ''
not_chosen_owner = True
while not_chosen_owner:
self.owner... | true |
95b4876cecd977efb7ce4c4a20a7225950470702 | Python | aws/aws-sam-cli | /samcli/lib/generated_sample_events/events.py | UTF-8 | 5,791 | 3.015625 | 3 | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"BSD-2-Clause"
] | permissive | """
Methods to expose the event types and generate the event jsons for use in SAM CLI generate-event
"""
import base64
import json
import os
import warnings
from typing import Dict
from urllib.parse import quote as url_quote
with warnings.catch_warnings():
# https://github.com/aws/aws-sam-cli/issues/2381
# ch... | true |
0293a0b5cd0f1c107685ec6d241ea9c666654957 | Python | ukulsh/projecteulersolution | /q18.py | UTF-8 | 260 | 3.078125 | 3 | [] | no_license | arr = []
for arr_i in range(15):
arr_temp = map(int,input().strip().split(' '))
arr.append(list(arr_temp))
print(arr,'\n')
for i in range(13,-1,-1):
for j in range(len(arr[i])):
arr[i][j] += max(arr[i+1][j],arr[i+1][j+1])
print(arr[0][0])
| true |
c870894f83630fa237a6d686f74c66520baf78e3 | Python | jenkins957/google-tech-dev-solutions | /GoogleTechDev/python/foundations/interpret.py | UTF-8 | 1,349 | 4.1875 | 4 | [] | no_license | """
https://codingbat.com/prob/p294185
Write a simple interpreter which understands "+", "-", and "*" operations. Apply the operations in order using command/arg pairs starting with the initial value of `value`. If you encounter an unknown command, return -1.
interpret(1, ["+"], [1]) → 2
interpret(4, ["-"], [2]) → 2... | true |
85a9c81e30ccad83f60a7c82d24375b158495cfc | Python | lpakula/exa-client | /src/utils/exchange.py | UTF-8 | 10,878 | 2.515625 | 3 | [] | no_license | #!/usr/bin/python
# -*- coding: utf-8 -*-
import time
import math
from decimal import Decimal as D
from math import floor
import ccxt
from ccxt.base.errors import InsufficientFunds, BaseError, ExchangeError
from utils.server import ExAServerHelper
from exceptions import ExAClientException
from models import Exchange,... | true |
367dafb98292d93c4d46f4fd8083fa4df407e2cc | Python | vladtf/CodeWars-py | /Project/DeodorantEvaporator.py | UTF-8 | 219 | 3.140625 | 3 | [] | no_license | def evaporator(content, evap_per_day, threshold):
threshold = threshold * content / 100
days = 0
while content > threshold:
content -= content * evap_per_day / 100
days += 1
return days
| true |
eeb4959be577a1b7888c7b84955674ceb0240125 | Python | remix-yh/fish_classification | /fish/dl.py | UTF-8 | 5,053 | 2.65625 | 3 | [] | no_license | import os
import csv
import numpy as np
import pandas as pd
import PIL
import tensorflow
from keras.applications.vgg16 import VGG16
import keras
from keras.utils import np_utils
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, ... | true |
30e3b99d45749e381b9d15756b8b292815153b64 | Python | nguyenhoanglam1402/BI_Python | /ASM1.py | UTF-8 | 4,674 | 3.3125 | 3 | [] | no_license | import numpy
import pandas as pd
from pandas.core.frame import DataFrame
def openCSVFile(path):
file = pd.read_csv(path)
pd.set_option('display.max_columns', 4)
return file
def getCVSLines(path):
with open(path) as f:
for i, line in enumerate(f):
print("line {0} = {1}".format(i, ... | true |
ebaca43113602436fc97a789441c4e59ee5fdd00 | Python | ethanlmm/cs185C_machine_learning | /hmm/hmm.py | UTF-8 | 5,509 | 2.65625 | 3 | [] | no_license |
import math
import random
import numpy as np
import functools
import json
import os
class hmm():
def __init__(self,name,state,symbol):
self.name=name
self.state=state
self.symbol=symbol
sum_A=0
sum_B=0
sum_PI=0
self.PI={}
self.A={}
self.B={}
... | true |
859fa77a4be7daaeac63da60b6dd02c40a87aadd | Python | feMap/Python | /15PythonicCode/demo01-05.py | UTF-8 | 1,191 | 3.875 | 4 | [] | no_license | # -*- coding: utf-8 -*-
################################################
# 01 -- 变量交换
# Bad
tmp = a
a = b
b = tmp
# Pythonic
a, b = b, a
################################################
# 02 -- 列表解析式
# Bad
my_list = []
for i in range(10):
my_list.append(i*2)
# Pythonic
my_list = [i*2 for i i... | true |
101b767559664e874d9be4928f5c9f7d2ef622a5 | Python | Jason-Yuan/Interview-Code | /LeetCode/Jump_Game_II.py | UTF-8 | 958 | 3.25 | 3 | [] | no_license | # Greedy
class Solution(object):
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return -1
start = end = steps = 0
while end < len(nums) - 1:
steps += 1
farthest = end
f... | true |
b5f13cc02b3ffd0a9c1672caa41719eee4587009 | Python | jadugnap/python-data-structure | /problem6_Two_Linked_Lists/test_union_intersection.py | UTF-8 | 1,352 | 3.25 | 3 | [] | no_license | from union_intersection import *
def test_ui_list():
list1 = LinkedList()
list2 = LinkedList()
element1 = [3,2,4,35,6,65,6,4,3,21]
element2 = [6,32,4,9,6,1,11,21,1]
for i in element1:
list1.append_node(i)
for i in element2:
list2.append_node(i)
s1 = set(element1)
s2 = s... | true |
920c4cda0de8fd726d031b128512e7b36c5276de | Python | novenopatch/Youtube_formation | /Graven/Game/game.py | UTF-8 | 598 | 3.140625 | 3 | [] | no_license | import pygame
from player import Player
from monster import Monster
class Game:
def __init__(self):
# génère le jeu
self.all_players= pygame.sprite.Group()
self.player = Player(self)
self.all_players.add(self.player)
self.all_monsters = pygame.sprite.Group()
self.pres... | true |
15c7a8cac604af7c8e3d8b792eaaf60d4c81342c | Python | fovegage/learn-python | /Python内建模块/pathlib/path_stu.py | UTF-8 | 340 | 3.109375 | 3 | [] | no_license | from pathlib import Path
import pathlib
# 实例化Path,路径可以是不存在的
p = Path('E:\study')
# print([x for x in p.iterdir() if x.is_dir()])
# 输出实例化的绝对路径
print(p.absolute())
# 判断路径是否存在
print(p.exists())
#
print(p.expanduser())
# 返回所属分组,windows不支持
# print(p.group())
| true |
7b8445a2629f136ad61ffb0080426c3b2499d009 | Python | moratorium08/ctf_writeups | /2020/defcon/fountain-ooo-reliving/trans.py | UTF-8 | 1,282 | 2.515625 | 3 | [] | no_license | insts = open('nue').read().strip('\n').split('\n')
#insts = [int(s.replace('0', '1').replace('1', '0'), 2) for s in insts]
insts = [int(s.replace('1', '1').replace('0', '0'), 2) for s in insts]
opcodes = ['MNZ',
'MLZ',
'ADD',
'SUB',
'AND',
'OR' ,
'X... | true |
3908b34ce86dd597b67330ae44059bede6b9a395 | Python | alexandraback/datacollection | /solutions_5738606668808192_0/Python/BlueFish/coinjam2.py | UTF-8 | 865 | 2.796875 | 3 | [] | no_license | # Python 2.5.3
def disclog(n,b):
out=0
while n>=b: n/=b; out+=1
return out
def bin(n):
out=''
while n: out+=str(n%2); n/=2
return out[::-1]
def solve(N,J):
m=[]; i=3
while len(m)<J:
compl=2**(N-1-disclog(i,2))
if (compl*i)&i==0: m.append((i*(compl+1),i))
i+=2
out=''
for num,fac in ... | true |
517dff2e242b61cf6f992c6af904647abc77bd93 | Python | nina-mir/w3-python-excercises | /json_exercises.py | UTF-8 | 2,728 | 3.4375 | 3 | [] | no_license | import json, operator
# some json example
example_json = '''
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "o... | true |
a31afde3f518e41e03cb9981b4d0a1bb2a31194c | Python | GauriP/DataAnalytics | /EnronMLPRoject/ud120-projects/svm/svm_author_id.py | UTF-8 | 1,451 | 3.03125 | 3 | [] | no_license | #!/usr/bin/python
"""
This is the code to accompany the Lesson 2 (SVM) mini-project.
Use a SVM to identify emails from the Enron corpus by their authors:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../tools/")
from email_preprocess import preproce... | true |
c92ae5f0f7d1882e6c2ff141de198ea965a6e2d2 | Python | cantek41/detecting-iris-anomaly | /Code/ApiClient.py | UTF-8 | 567 | 2.609375 | 3 | [] | no_license | import requests
import json
url="http://192.168.0.34:5000/"
def sendRequest(api):
response=requests.get(url+api)
return response.content.decode("utf-8")
def sendFile(file):
files = {'file': open(file, 'rb')}
#files = {'file': open('image/gozcan.jpg', 'rb')}
response=requests.post(url+"takeImage",... | true |
4ae134b663f1838fad92635c0535754398b57d1a | Python | sangho61/UMSI | /SI507/proj1/proj1_w18.py | UTF-8 | 4,873 | 2.96875 | 3 | [] | no_license | import json
import requests
import webbrowser
class Media:
name = 'Media'
def __init__(self, title="No Title", author="No Author", release_year = "0000", json= None):
if json is None:
self.title = title
self.author = author
self.release_year = release_year
el... | true |
98d17e79f2bd4ccb9ef95b87a1bc224bd0ccd712 | Python | 404alex/CIS2750_F17 | /bin/iCalGUIPro/view/AboutWindow.py | UTF-8 | 1,115 | 2.953125 | 3 | [] | no_license | #some code from the book: programming python 4th edition
from tkinter import *
from ..business import HelpMethod
def dialog():
win = Toplevel()
HelpMethod.centerOfWindow(win, 280, 185)
win.resizable(width=False, height=False)
win.focus_set()
win.grab_set()
win.title('About iCalGUI')
Label(... | true |
d49814038de659db1fd04596fdf7c883910ffcc3 | Python | Speters1086/res_strava_reader | /test.py | UTF-8 | 1,008 | 2.671875 | 3 | [
"MIT"
] | permissive | import pandas as pd
from stravalib.client import Client
from config import Config
config = Config()
client = Client(config.access_token)
athlete = client.get_athlete()
print("For {id}, I now have an access token {token}".format(id=athlete.id, token=client.access_token))
# my_activities = client.get_activities(lim... | true |
5d521020f857281eeac477764dcb8e7d0ddf227d | Python | toku345/RayTracerChallenge_Python | /raytracerchallenge_python/material.py | UTF-8 | 1,893 | 2.75 | 3 | [
"MIT"
] | permissive | from raytracerchallenge_python.tuple import Color
from math import pow
class Material:
def __init__(self):
self.color = Color(1, 1, 1)
self.ambient = 0.1
self.diffuse = 0.9
self.specular = 0.9
self.shininess = 200.0
self.pattern = None
self.reflective = 0.0
... | true |
ad5fa27f91227feabceb4e0d431fe15a4c0e4ad1 | Python | taufderl/ProgITSec | /studienbrief1/beispiele/quelltext_1_21.py | UTF-8 | 331 | 3.609375 | 4 | [] | no_license | from operator import attrgetter
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return repr((self.name, self.age))
person_objects = [
Person('Otto', 22),
Person('Eva', 20),
Person('Tim', 23),]
print(sorted(person_objects, key=attrgett... | true |
cb9871c52bb74e63f473fb5967b29e0f059d09c3 | Python | http-www-testyantra-com/Surbhi_Sony | /training_day3/scenarios/scenario32.py | UTF-8 | 426 | 3.25 | 3 | [] | no_license | from selenium import webdriver
class Scenario32():
def store_locator(self):
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("http://www.bluestone.com")
driver.find_element_by_xpath("//span[text()='Locate']").click()
places = driver.find_elements_by_xpath("//u... | true |
f31fb84de9973af0967035d32ddb9623f4747c5c | Python | evsheino/wish-list-backend | /lists/models.py | UTF-8 | 1,178 | 2.546875 | 3 | [] | no_license | from django.db import models
from django.contrib.auth.models import User
from model_utils.models import TimeStampedModel
class Category(models.Model):
""" Represents the different types of gifts. """
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class Gift(TimeStam... | true |
f76ea140e66d4e6334c85c17b52af18730fbdf8e | Python | monics7/pythopraccode | /example/stringstrip.py | UTF-8 | 90 | 3.015625 | 3 | [] | no_license | language = ' Python '
print(language)
new_language = language.strip()
print(new_language)
| true |
87f23036b47b59b52dcb4fad1e63852778d0442f | Python | python-tutorial/unit-test-examples | /user.py | UTF-8 | 183 | 3.03125 | 3 | [] | no_license | import random
class User:
def add_two_numbers(self, first, second):
return first+second+self.return_random()
def return_random(self):
return random.random() | true |
3e55492ffbe3df17a940d3a91d1a91b86ef65173 | Python | ABCmoxun/AA | /AB/linux2/day15/day14_exercise/99_mul.py | UTF-8 | 260 | 3.796875 | 4 | [] | no_license | # 2. 打印九九乘法表:
# 1x1=1
# 1x2=2 2x2=4
# 1x3=3 2x3=6 3x3=9
# .....
# 1x9=9 2x9=18 ........ 9x9=81
for i in range(1, 10):
# 打印一行
for j in range(1, i + 1):
print("%dx%d=%d" % (j, i, j * i), end=' ')
print() | true |
918ccaad1bae88460c803c3912832caa2d7f6969 | Python | scarfaceablo/elastic-apm-logger | /test_apm.py | UTF-8 | 1,084 | 2.796875 | 3 | [] | no_license | import unittest
from loggerqos3 import ApmHelper
class TestCalc(unittest.TestCase):
def setUp(self):
self.apm_helper = ApmHelper("http://localhost:8200", "unittest1")
class X():
def __init__(self):
self.x = 1
self.y = 1
@self.apm_helper.timeit
def decoratored(self,z):
... | true |
c3f48b728121b68d5ff5a13bc7b98ed1e4680825 | Python | gaozejing/test2 | /字典.py | UTF-8 | 679 | 4.28125 | 4 | [] | no_license | #创建一个空字典
Dictionary = {}
#假设这个添加词典操作可以循环100次
for i in range(100):
Choose = input("Add or look up a word (a/l)? ")
if Choose == "a":
word = input("Type the word: ")
definition = input("Type the definition: ")
#将key和value放进字典
Dictionary[word] = definition
print("Word added"... | true |
ffc656ff1d646018ed13c61fb194c94bf63ac84c | Python | Aludeku/Python-course-backup | /lista exercícios/PythonTeste/desafio09.py | UTF-8 | 500 | 3.359375 | 3 | [
"MIT"
] | permissive | print('\nTabuada master de aludeku')
n1 = int(input('Diga um número: '))
print('{} x {} = {}'.format(n1,1,n1*1))
print('{} x {} = {}'.format(n1,2,n1*2))
print('{} x {} = {}'.format(n1,3,n1*3))
print('{} x {} = {}'.format(n1,4,n1*4))
print('{} x {} = {}'.format(n1,5,n1*5))
print('{} x {} = {}'.format(n1,6,n1*6))
print('... | true |
e45b6377e39a64304006c2a6b7c85c60fb4e4676 | Python | yskang/AlgorithmPractice | /baekjoon/python/police_car_2618.py | UTF-8 | 1,861 | 3.015625 | 3 | [
"MIT"
] | permissive | # Title: 경찰차
# Link: https://www.acmicpc.net/problem/2618
import sys
sys.setrecursionlimit(10 ** 6)
read_single_int = lambda: int(sys.stdin.readline().strip())
read_list_int = lambda: list(map(int, sys.stdin.readline().strip().split(' ')))
INF = 999999999999999
dp = []
events = []
event_size = 0
w... | true |
24a6309a0278a47692566de974015db5fa09e6c3 | Python | Fatmahmh/100daysofCodewithPython | /Day043.py | UTF-8 | 528 | 4.03125 | 4 | [] | no_license | #Python Inheritance
class person :
def __init__(self,fname,lname):
self.fname = fname
self.lname = lname
def printname(self):
print(self.fname, self.lname)
x = person("fatma", "maid")
x.printname()
#Create a Child Class
'''Use the pass keyword when you do not want to add a... | true |
447d0c706e8d8702bbd2c0432a5cb5d8707e1715 | Python | brainmentorspvtltd/RDE_Python | /CS2C/GUI/01-intro.py | UTF-8 | 283 | 3.203125 | 3 | [] | no_license | import tkinter
from tkinter import *
window = Tk()
window.geometry('400x400')
label = Label(window, text="Hello Python", foreground='red',
font=('Arial',28,'bold'))
# label.pack()
# label.grid(row=0,column=0)
label.place(x = 10, y = 10)
window.mainloop() | true |
f7fb31ebbdb8dfa1c1e815987010aaa434f14bb9 | Python | superxiaoying/ToolBox | /heatmap.py | UTF-8 | 657 | 3.1875 | 3 | [] | no_license | import numpy as np
import cv2
import matplotlib.pyplot as plt
def CenterLabelHeatMap(img_width, img_height, c_x, c_y, sigma):
X1 = np.linspace(1, img_width, img_width)
Y1 = np.linspace(1, img_height, img_height)
[X, Y] = np.meshgrid(X1, Y1)
X = X - c_x
Y = Y - c_y
D2 = X * X + Y * Y... | true |
269cfd9c91a24016ddec618fff2825b03355f86f | Python | tashakim/puzzles_python | /tail_nontail_rec.py | UTF-8 | 633 | 3.984375 | 4 | [] | no_license | arr = [1,2,3]
# non-tail recursion
def function(arr):
if len(arr) == 0:
return 0
return arr[0] + function(arr[1:])
# tail recursion
def tail_recurse(arr):
def helper(arr, res):
if len(arr) == 0:
return res
return helper(arr[1:], arr[0] + res)
return helper(arr, 0)
class Sol:
def version2(self, arr... | true |
1cefd31efbb693cbebdb59ab2cbc04a03d5649c5 | Python | WeberLiu94/Data-Structure-and-Algorithms-for-Python-1 | /动态规划问题/钢筋切割问题.py | UTF-8 | 862 | 3.71875 | 4 | [] | no_license | #一段长度为n的钢筋,切割成不同的长度,每种长度有不同的价格,求收益最大的切割方案与收益值
#采用动态规划的思想
def cut(n,price_list):
result_list = []#用来保存每一次迭代的结果,存储子问题的解
cut = [0]*(n+1)#存储最佳的切割方案
result_list.append(0)
for sublength in range(1, n+1):#从子问题开始迭代求解
total = 0
for i in range(1, sublength+1):#子问题的左边开始切
if total < pric... | true |
8bc16ea04b219b41aa10b3846500e3c4829ef29d | Python | liviu-gheorghe/math-quiz | /up.py | UTF-8 | 508 | 2.671875 | 3 | [] | no_license | #!/usr/bin/python3
import subprocess
import shlex
def parse_envfile(env_filename):
env_file = open(env_filename,'r')
vars_dict = {}
for line in env_file.readlines():
[arg,val] = line.strip().split('=')
vars_dict[arg] = val
return vars_dict
def spawn_webserver_process(vars_dict):
... | true |
74269999b59599d0c2fdb048dc8e7d92be5b5759 | Python | mehdisebbar/hashcode2017 | /write_output.py | UTF-8 | 432 | 3.03125 | 3 | [] | no_license |
# result_dict example
# result_dict = {0:[1,2],1:[2,3]}
def write_output(result_dict, file_name):
nb_cache_server = len(result_dict.keys())
with open(file_name, 'w+') as infile:
infile.write(str(nb_cache_server) + '\n')
for key, values in result_dict.iteritems():
values_to_string ... | true |
c1ddaa1a9dc4ee26d0dd9b65d879c9ddc453b904 | Python | clarisli/RL-Easy21 | /utils.py | UTF-8 | 2,740 | 2.796875 | 3 | [] | no_license | import pickle
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib
matplotlib.use('TkAgg')
from matplotlib import pyplot as plt
def dump(Q, file_path):
with open(file_path, 'wb') as file:
pickle.dump(Q, file)
def load_dump(file_path):
with open(file_path, 'rb') as file:
return pi... | true |
ceb4486969d2be3e180a3c6e238c060841572478 | Python | Rob-Conan/NetworkPythonClasses | /Lesson 7/exercise2.py | UTF-8 | 674 | 2.609375 | 3 | [] | no_license | # Use regular expressions to find all
# remote hostnames, remote IP addresses,
# and remote plaftforms
import re
remote_hosts = []
IPs = []
platform = []
with open("sw1_cdp.txt", 'r') as f:
for line in f:
hosts = re.search(r"Device ID: (.+)", line)
if hosts:
if not hosts.group(1) in remote_hosts:
remote_h... | true |
ca979bea6a13e50c22091338c774aff928d6ceae | Python | Navyhoang/Python-challenge | /PyBank/main.py | UTF-8 | 5,012 | 3.59375 | 4 | [] | no_license | #Open the budget_data file to read and calculate
#Open a text file to write to:
#Total number of months (how many rows), Skip the header
#Net profit/loss (sum of column B), skip the header
#Average of the profit/loss (average of column B), skip the header
# Find the greatest increase in profits (max of ... | true |