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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
7348850e81970fbc9e344b098e965f36b5e8eaf7 | Python | c-d0wd/SSH-Command-Bot | /ssh-command-bot.py | UTF-8 | 3,815 | 2.671875 | 3 | [] | no_license | #!/usr/bin/python
import os
import sys, getopt
import pexpect
import getpass
#-- VARIABLE DECLARATION --#
USERNAME=getpass.getuser()
PASSWORD="admin"
CIPHER="aes128-cbc"
KEXALGORITHMS="diffie-hellman-group1-sha1"
CIPHER_ERR="Unable to negotiate with .* no matching cipher found\.*"
#-- FUNCTTION DECLARATIONS --#
def w... | true |
804248df65bd4af03ab14d7725d45bf037c8903a | Python | yanhualei/about_python | /python_learning/python_base/爬虫/页面解析库/爬虫利器之beautifulsoup/beautifulsoup的学习与理解.py | UTF-8 | 4,321 | 3.546875 | 4 | [] | no_license | import requests
from bs4 import BeautifulSoup
import bs4
"""BeautifulSoup主要有四类对象,Tag(标签),NavigableString(可遍历的字符串),BeautifulSoup,Comment"""
# 获取网页内容并处理
# html = requests.get("http://www.baidu.com")
# soup = BeautifulSoup(html.text)
# 获取本地文件
soup = BeautifulSoup(open("index.html","rb"),"html.parser",from_encoding="utf-... | true |
bd37795cf070fdf26650b76693be53f019ba9e9d | Python | Camilo-neck/TareApp | /Codigo_Fuente/Data/GenerarPDFClases.py | UTF-8 | 8,059 | 2.625 | 3 | [] | no_license | from docx import Document
import sys
import os
import comtypes.client
import re
import docx
import pkg_resources
pkg_resources.require("xlrd==1.2.0")
import xlrd
from datetime import datetime as dt
import locale
class FormattedDocument:
#Defining constructor for class
def __init__(self, path, exc_doc=None):
... | true |
f22c567381e297811eaa3f844fa19916dada9f2a | Python | omkaradhali/python_playground | /prob607.py | UTF-8 | 1,600 | 4.40625 | 4 | [] | no_license | """
There are M people sitting in a row of N seats, where M < N. Your task is to redistribute people such that
there are no gaps between any of them, while keeping overall movement to a minimum.
For example, suppose you are faced with an input of
[0, 1, 1, 0, 1, 0, 0, 0, 1], where 0 represents an empty seat and 1 re... | true |
8f4deefdbcfb70c52d06968a3f2a997f30674960 | Python | linusg/adventofcode | /2020/8.py | UTF-8 | 2,126 | 3.421875 | 3 | [
"MIT"
] | permissive | import sys
from itertools import chain
from typing import Iterator, List, Sequence, Tuple
Instruction = Tuple[str, int] # name, value
ExecutionResult = Tuple[int, bool] # accumulator, did_terminate
def execute(instructions: Sequence[Instruction]) -> ExecutionResult:
accumulator = 0
instruction_pointer = 0
... | true |
36f967c5edef48c6ba7da3fffb82d544237c62ca | Python | FR98/dynamic-rendering | /obj.py | UTF-8 | 3,470 | 3.015625 | 3 | [
"MIT"
] | permissive | """
---------------------------------------------------------------------------------------------------
Author:
Francisco Rosal 18676
---------------------------------------------------------------------------------------------------
"""
import struct
from utils.color import Color
from numpy import arctan2, arccos, ... | true |
b351855ba442246739d4359810e2f1637f7f7aed | Python | LiJiaqi96/DeeCamp_Project | /Movieinfo_Crawler/douban_image.py | UTF-8 | 998 | 2.671875 | 3 | [] | no_license | from bs4 import BeautifulSoup
import requests
# import json
# import urllib2
# import time
path = "Movie.txt"
f = open(path)
files = f.readlines()
nums = []
for file in files[1:]:
nums.append(file.split('\t')[0])
print(len(nums))
count = 0
images_url = {}
for num in nums:
# url = "https://api.douban.com/v2/mov... | true |
ee2ab6076efa66bc2b6816c08e224fe907cc1844 | Python | mnot/thor | /thor/dns/__init__.py | UTF-8 | 1,933 | 2.828125 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
from concurrent.futures import Future, ThreadPoolExecutor
from itertools import cycle, islice
import socket
from typing import Callable, Union, Tuple, List, Iterable, Any
POOL_SIZE = 10
Address = Union[Tuple[str, int], Tuple[str, int, int, int]]
DnsResult = Tuple[
socket.AddressFamily, # p... | true |
2f187fca49c894e551e46fc04eb424261af4ce85 | Python | 4THEEND/python-all | /PasswordCreator.py | UTF-8 | 1,568 | 3.234375 | 3 | [] | no_license | from guizero import *
import random as r
class AppCreate(App):
def __init__(self):
super().__init__(title="Password Generator", width=350, height=350, layout="grid")
self.list_chars = {
"hex-lower": "abcdefghijklmnopqrstuvwxyz0123456789 ",
"hex-upper": "ABCDEFGHIJK... | true |
22c43e059c8b9529fdab070def3f603cc8aa1c06 | Python | dim4ik2008/pleased | /plot.py | UTF-8 | 1,607 | 2.6875 | 3 | [] | no_license | import matplotlib.pyplot as plt
from collections import Counter
import os
import os.path
import glob
import datapoint as datap
def plant_data(pd):
plt.plot(pd.readings)
for s in pd.stimuli:
plt.axvline(s.time)
def datapoints(X, y):
[datapoint(xx, yy) for xx, yy in zip(X, y)]
def datapoint(xx,... | true |
e990b92e4094cea0a1094835be7699d7a8e45a5c | Python | aliakseik1993/skillbox_python_basic | /Module15/09_word_analysis_2/main.py | UTF-8 | 421 | 4.03125 | 4 | [] | no_license | word = input("Введите слово: ")
letters_of_count = list(word)
count_of_word = len(letters_of_count) - 1
new_word = []
for index in range(count_of_word, -1, -1):
new_word.append(letters_of_count[index])
if new_word == letters_of_count:
print("Слово является палиндромом")
else:
print("Слово не является палинд... | true |
4e002cc6544552ff9544e98c622898f596a5fc3f | Python | avim2809/CameraSiteBlocker | /venv/Lib/site-packages/uiutil/unittests/switchbox_dictionary_switches_test_gui.py | UTF-8 | 1,483 | 2.953125 | 3 | [
"Apache-2.0"
] | permissive | from uiutil import BaseFrame, standalone, Label, Position
from uiutil import NewSwitchBox as SwitchBox
from uiutil.tk_names import CENTER
class MyFrame(BaseFrame):
def __init__(self,
**kwargs):
super(MyFrame, self).__init__(**kwargs)
self.switchbox = SwitchBox(title="Three",
... | true |
cc81e90ac22a39aaef36203bb95025852eeb525a | Python | abhishekjee2411/python_for_qa_synechron | /exception_4.py | UTF-8 | 251 | 3.59375 | 4 | [] | no_license | #raising an exception manually
import time
import random
e = ValueError("Too Hot","Engine temperature is very high")
def get_temp():
return random.randint(50,130)
while True:
temp = get_temp()
print(temp)
if temp>120:
raise e
time.sleep(1)
| true |
88d913a9624442bf5831027db5dabeef5c437d8e | Python | gustavopierre/Introduction_to_Programming_using_Python | /raise2.py | UTF-8 | 412 | 3.328125 | 3 | [] | no_license | def main():
try:
for line in readline('file1.doc'): print(line.strip())
except IOError as e:
print('cannot read file: ', e)
except ValueError as e:
print('wrong file extension: ', e)
def readline(filename):
if filename.endswith('.txt'):
fh = open(filename)
retur... | true |
f9eae5d861cfee56c069f9e73bed4bfdda663414 | Python | beckdaniel/flakes | /flakes/tests/test_string.py | UTF-8 | 17,725 | 2.625 | 3 | [] | no_license | import flakes
import unittest
import numpy as np
import GPy
import datetime
from copy import deepcopy
class StringKernelBasicTests(unittest.TestCase):
def setUp(self):
self.s1 = 'cata'
self.s2 = 'gatta'
self.s3 = 'cgtagctagcgacgcagccaatcgatcg'
self.s4 = 'cgagatgccaatagagagagcg... | true |
c0be0661657d9502f9ee80117f12f0d4c8fa6d25 | Python | zmaktouf/sma | /tests/test_stock.py | UTF-8 | 3,744 | 3 | 3 | [
"MIT"
] | permissive | import sys
import unittest
from dateutil.parser import parse
class StockTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
sys.path.insert(0, '..')
@classmethod
def tearDownClass(cls):
sys.path.pop(0)
def test_eq(self):
from atslib import Stock
self.assert... | true |
84a04dd4b3a921bc004f0fa3e83acdffcdad99f8 | Python | tcjansen/telescopy | /telescopy/vega.py | UTF-8 | 2,491 | 2.625 | 3 | [
"MIT",
"BSD-3-Clause"
] | permissive | import os
from astropy.io import fits
import matplotlib.pyplot as plt
import astropy.units as u
import numpy as np
from json import load
__all__ = ['vega']
vega_path = os.path.join(os.path.dirname(__file__), 'data',
'alpha_lyr_stis_008.fits')
# https://classic.sdss.org/dr7/algorithms/sdssUBV... | true |
7320af8f0df27f6ea3dde266a1f29577103c9ee5 | Python | foolkevin/CodeInterviews | /No199.py | UTF-8 | 1,022 | 3.375 | 3 | [] | no_license | from collections import deque
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def leftSideView(self, root: TreeNode):
if not root: return []
results, queue = [], deque()
queue.app... | true |
2e5393a933b78b42d299461b379af7f1ab082281 | Python | Tinm/extracting_relevant_images | /stopWord_removal.py | UTF-8 | 3,472 | 3.09375 | 3 | [] | no_license | """
Student: Adriana Carolina Camacho
Class: Data Mining
Spring 2016
Python program that uses a text file to make a list of stop words to remove from
a json formated file
"""
import string
import os.path
import json
import sys
import time
stopFile = "stop.txt"
jsonFile = "0_0_0.txt"
fromP = os.path... | true |
d81166b3ecf75ccbe4163fcf3106965bd19af9c5 | Python | hochan222/vs-code-test | /python/BJ_10809.py | UTF-8 | 82 | 3.4375 | 3 | [] | no_license | word = input()
for k in range(ord('a'), ord('z')+1):
print(word.find(chr(k)))
| true |
83b2e7ca06587dc038284a128bb085e1b014f2c5 | Python | polrib/AdvancedML_HW3 | /ex3_convnet_2.py | UTF-8 | 14,901 | 2.65625 | 3 | [] | no_license | import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import numpy as np
import matplotlib.pyplot as plt
def weights_init(m):
if type(m) == nn.Linear:
m.weight.data.normal_(0.0, 1e-3)
m.bias.data.fill_(0.)
def update_lr(optimizer, lr):
... | true |
56cc25f0947e20cacdf1e07c847461316c85d6b7 | Python | BogomilaKatsarska/Python-Advanced-SoftUni | /Functions Advanced - L1 Unpacking of Elements - Demos.py | UTF-8 | 1,018 | 4.875 | 5 | [] | no_license | #1. Unpacking Arguments [Unpack Lists, Tuples and Dictionaries]:
# We can use * to unpack the list so that all elements of it can be passed as different parameters
# And we can use ** to unpack a dictionary, so all of its elements are passed as keyworded arguments
# Note that the length of the list that you unpack m... | true |
12fc9abe6e871654f5267a5ae7bedb7e85b01edd | Python | daverb/Titanic_Analysis | /KaggleTitanicRandomForest.py | UTF-8 | 2,167 | 3.015625 | 3 | [] | no_license | """Submission to Kaggle - Titanic Competition
Author: David Burson
Date: 12/11/2014
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import sklearn
# Prepare the data for our model
df = pd.read_csv('data/train.csv', header=0)
df = df.drop(['Name','Cabin','Ticket'], axis=1)
# Interpolate pre... | true |
5d8f5aee43a6afc0b22b02cbef72129d3e33467a | Python | boustrophedon/algorithms_playground | /algo/linked_list.py | UTF-8 | 8,320 | 3.78125 | 4 | [] | no_license | from typing import List, TypeVar, Optional, Generic, Callable
E = TypeVar("E")
Ctx = TypeVar("Ctx")
class Empty(Exception):
""" Exception raised during an operation when the linked list is empty """
pass
class Node(Generic[E]):
""" A node in a linked list """
def __init__(self, value: E, next: Op... | true |
595b10fb690b49f0d2f7b8e157211d65305064b2 | Python | tabdansby/newRepo | /nightclass/functions.py | UTF-8 | 309 | 3.796875 | 4 | [] | no_license | def greet(n):
print('Hello {}'.format(name))
name = input('What is your name?: ')
greet(name) #<----don't forget about those ending parentheses!
#print = something for humans to see (great for debugging using the Boolean response you get);
#return = something you want the computer to do something with
| true |
cd52573c8521a78a5fd795fa6707370be3901b06 | Python | volodumurgaydayenko/sample | /Modul_2/files.py | UTF-8 | 510 | 2.515625 | 3 | [] | no_license | import json
xs = [1, 2, 3, 4, {'mode': True}]
dumped = json.dumps(xs)
print(type(dumped))
print(dumped)
f = open('test-data.json', 'w')
f.write(dumped)
f.close()
f = open('test-data.json', 'r+')
readData = f.read()
load = json.loads(readData)
load.append("1231")
print(type(f))
print(load)
# f = open('stats.jso... | true |
1385d84d7c52014eaacb92c07d46969432b665f5 | Python | fpelliccioni/RGSPL | /calc.py | UTF-8 | 7,999 | 4.09375 | 4 | [
"MIT"
] | permissive | """
Implement a basic calculator with APL-like syntax.
This simple calculator only implements the operators +-×÷ and ¯ on simple integer scalars.
This is the grammar accepted, where rules match from right to left.
STATEMENT := EOL (TERM OP)* TERM
TERM := NUM | "(" STATEMENT ")"
NUM := "¯"? INTEGER
OP := "+" | "-" | "×... | true |
92fd128062d3dd3d3faa7d9d57bc0083a9607222 | Python | cwiz/RoboND-Rover-Project | /code/perception.py | UTF-8 | 5,337 | 2.921875 | 3 | [
"MIT"
] | permissive | import numpy as np
import cv2
# Color Manipulation
def color_limit_hsl(image, hsl_lower=[20,120,80], hsl_upper=[45, 200, 255]):
# convert image to hls colour space
hls = cv2.cvtColor(image, cv2.COLOR_RGB2HLS).astype(np.float)
# hls thresholding for yellow
lower = np.array(hsl_lower,dtype = "uint8")
... | true |
be343778d60c5f03f9ac05b8855b41117fe7e608 | Python | nikhilgarg28/pysstable | /reader.py | UTF-8 | 2,048 | 3.171875 | 3 | [] | no_license | import struct
def _bytes_to_int(b):
return struct.unpack('I', b)[0]
class Reader(object):
def __init__(self, fname):
self.fname = fname
self._values = []
self._key_data = []
self._loaded = False
def _read_value(self, offset, size):
return self._values[offset:offs... | true |
ca67fd9257f378176728d10f5d36d678a8a7792d | Python | rymo90/hackerrank | /interquarityrange.py | UTF-8 | 1,219 | 3.28125 | 3 | [] | no_license | import math
def evenElement(lis):
half = len(lis)//2
return (lis[half-1]+lis[half])//2
def oddElement(lis):
half = len(lis)//2
return lis[half]
def qualities(x):
result = []
middle = 0
lowerHalf = 0
upperHalf = 0
element = len(x)//2
if len(x) % 2 == 0:
middle = (x[e... | true |
72611ecd008c7b08ed540eaecec1f4440feec497 | Python | Uranux1993/AlgorithmTemplates | /BinaryIndexTree/binary_index_tree.py | UTF-8 | 583 | 3.1875 | 3 | [] | no_license | class BinaryIndexTree:
def __init__(self, N):
self.N = N
self.C = [0 for _ in range(self.N + 1)]
def lowbit(self, x):
return x & -x
def query(self, i):
ans = 0
while i > 0:
ans += self.C[i]
i -= self.lowbit(i)
return ans
def upda... | true |
400a2a92083cdeb3ff95ce1329117ac506ba1d12 | Python | irk2adm/pythontutor | /05/02_NumberOfWords.py | UTF-8 | 315 | 3.59375 | 4 | [] | no_license | # Задача «Количество слов»
# Дана строка, состоящая из слов, разделенных пробелами. Определите, сколько в ней слов. Используйте для решения задачи метод count.
print(input().count(' ') + 1)
| true |
ffcd0b3d9b2b114a74bb692212278a73bd19af39 | Python | bryan11komputer/airline | /airline3/application.py | UTF-8 | 2,621 | 2.765625 | 3 | [] | no_license | import os
from config import Config
from flask import Flask, render_template, request
from models import *
thisConfig = Config()
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = thisConfig.DB_URL
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.init_app(app)
@app.route(... | true |
debabfe225ed2291902eb5e4967b3aaa25588b8a | Python | Gerhardark/python_intermedio | /intermedio/list_comprehension.py | UTF-8 | 152 | 3.25 | 3 | [] | no_license | def main():
square = [i for i in range(1,1000) if i % 4 ==0 and i % 6 == 0 and i % 9 == 0]
print(square)
if __name__ == '__main__':
main() | true |
fcbc215d07cfd19b97621bb1dfc1d88f4b4732fb | Python | ranstotz/simple-rss-scraper | /scripts/main.py | UTF-8 | 2,493 | 2.8125 | 3 | [] | no_license | import feedparser
import pprint
import re
pp = pprint.PrettyPrinter(indent=4)
feeds = [
{'name': 'cnn', 'url': 'http://rss.cnn.com/rss/cnn_topstories.rss'},
{'name': 'nytimes', 'url': 'https://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml'},
{'name': 'wapo', 'url': 'http://feeds.washingtonpost.com/rss... | true |
b5a61b36636f364c963e3a553152a3afb57616b6 | Python | C-Miranda/python-challenge | /PyBank/main.py | UTF-8 | 2,105 | 3.453125 | 3 | [] | no_license | import os
import csv
# Create file name
csvpath = os.path.join('.', 'Resources', 'budget_data.csv')
# Declare lists
dates = []
profit_losses = []
profit_changes = []
# Read/load file into lists
with open(csvpath) as csvfile:
# Drop header row
csvreader = csv.reader(csvfile, delimiter=',')
csv_header = ne... | true |
44cd2ac195ff1b3deed2f0cbca2990fef2377030 | Python | pedromorelli96/UNICAMP-pad-mc102-2s2020 | /lab04/lab04.py | UTF-8 | 1,204 | 3.578125 | 4 | [] | no_license | ######################################################################
# MC102 - Algoritmos e Programação de Computadores
# Laboratório 4 - Street Fighter
# Nome: Pedro Rodrigo Ramos Morelli
# RA: 204737
######################################################################
# Leitura do hp dos lutadores
ryu = int(inp... | true |
157e7e4e4d55d92d3104f4c97cb5d2321610e238 | Python | sabarnwa/panoptic_flask | /iff_dashboard/gsheets_utils.py | UTF-8 | 645 | 2.78125 | 3 | [
"MIT"
] | permissive | import gspread
from oauth2client.service_account import ServiceAccountCredentials
from config import credential_json_path, scope, source
from random import randint
def random_with_N_digits(n):
'''
Random number generator
'''
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_sta... | true |
21d7cee0c07ee7f1ba0deb2004f8e754b99d1496 | Python | miniamisha/DS-in-python | /DAY1/problem2.py | UTF-8 | 258 | 3.90625 | 4 | [] | no_license | '''Write a Python program to print the numbers in the list which are divisible by 3.'''
def divby3():
list1 = []
for i in range(1,30):
if i % 3 == 0:
list1.append(i)
return list1
result = divby3()
print(result)
| true |
a0b97208dde08ee1d9d51d81ac39c43d4c08b9b0 | Python | gxwangdi/Leetcode | /392-Is-Subsequence/IsSubsequence_3.py | UTF-8 | 330 | 3.34375 | 3 | [] | no_license | class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
if not s or not t or len(s) > len(t):
return False
ls = len(s)
lt = len(t)
i = 0
j = 0
while i<ls and j<lt:
if s[i]==t[j]:
i+=1
j+=1
return i =... | true |
ed1872ab243b4cda3dcd574db43c7c93ac00707c | Python | python-practice-b02-927/kuleshov | /lab2/ex8.py | UTF-8 | 376 | 3.3125 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 10 10:08:56 2019
@author: student
"""
from turtle import *
a = 10
n = 10
def squarespy(a, j):
for i in range(3):
forward(j*a)
left(90)
right(90)
forward(a)
left(90)
forward((j+1)*a)
left(90)
shape('turtle'... | true |
fa621eeb3db551b9ae6f97c1a93ec5234b1f0dc7 | Python | QueenDekimZ/Sample_Tkinter_Game_Platform | /Sample_Game_Platform/flappy_bird/ball_game_test/font_draw.py | UTF-8 | 1,556 | 3.109375 | 3 | [] | no_license | # @Time : 2019/4/10 18.41
# @Author : QueenDekimZ
# @Email : QueenDekimZ@163.com
import pygame, sys
import pygame.freetype
pygame.init()
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Pygame文字绘制")
GOLD = 255, 251, 0
f1 = pygame.freetype.Font("C://Windows//Fonts//msyh.ttc", 36)
f1surf... | true |
7cc8387cd6efa94adbef298c6923a9256e3177ba | Python | digggy/CS-Jacobs | /ADT/Homework 6/implement_word.py | UTF-8 | 2,057 | 4.375 | 4 | [
"MIT"
] | permissive |
# Function to rescale the values of the alphabets
'''
This is done inorder to consume less array size
'''
def scaledown(i, string):
return ord(string[i])-96
# Function to get the value of the letter in the word
'''
If the index i is greater than the length it returns 0 the
minimum value among all ... | true |
09b5dc1ef8b2741505bce333b20133522c74c3d7 | Python | saghul/python-asiri | /asiri/__init__.py | UTF-8 | 759 | 2.578125 | 3 | [
"LicenseRef-scancode-other-permissive",
"BSD-3-Clause"
] | permissive |
from .mcp230xx import MCP230XX
__version__ = '0.1.0'
__all__ = ['GPIO']
class GPIO(object):
"""
RPi.GPIO-like interface for MCP23017 and MCP23008
"""
OUT = MCP230XX.OUTPUT
IN = MCP230XX.INPUT
HIGH = 1
LOW = 0
def __init__(self, num_gpios=16, busnum=1, address=0x20):
sel... | true |
016241d2434dbed91882220bdad3f92e63bfc81f | Python | ken8203/leetcode | /algorithms/h-index.py | UTF-8 | 451 | 3.09375 | 3 | [] | no_license | class Solution(object):
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
candidates = []
for h in citations:
N = len([each for each in citations if each >= h])
if N >= h:
candidates.append(h)
... | true |
02ea582de6ffd4707c99c8155982b7932ecdda06 | Python | glcrazier/LeetCodePlay | /util.py | UTF-8 | 785 | 3.59375 | 4 | [
"MIT"
] | permissive | class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e
def __str__(self):
return '[%d, %d]' % (self.start, self.end)
def __repr__(self):
return self.... | true |
522eff1d4d951f3955c1f1b9db93327702d3bd41 | Python | glc12125/Algo | /lintcode/Find Mode in Binary Search Tree.py | UTF-8 | 1,673 | 3.75 | 4 | [] | no_license | """
Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than or equal to the node's key.
The right subtree of a node contains only nodes with ke... | true |
ad18004435a61e5d254162b75f501c4ac3b70bdd | Python | Accioy/sar-10-classification | /vi_gradient_acent.py | UTF-8 | 2,536 | 2.796875 | 3 | [] | no_license | from keras.models import load_model
from keras import backend as K
from keras import utils
import os
import numpy as np
import matplotlib.pyplot as plt
model=load_model('mstar10_1.h5')
root_path=os.path.abspath('./')
def normalize(x):
"""utility function to normalize a tensor.
# Arguments
x: An inp... | true |
fa868060203540fb4a73bb64e09b33c622873479 | Python | devsnice/data-structures-algorithms | /algorithmic-toolbox/week-5/moneyChange.py | UTF-8 | 703 | 3.296875 | 3 | [] | no_license | # Uses python3
import math
import sys
def moneyChange(coins, money):
minNumberOfChangesForCoins = [0]
index = 1
while index <= money:
minNumberOfChanges = math.inf
for coin in coins:
if index >= coin:
numberOfChanges = minNumberOfChangesForCoins[index - coin] ... | true |
01f4f0dc996e28d97d0bc7624ca8da87170bf2c4 | Python | YaminiNarayanan-359/guvi | /codekata/divbybothnum.py | UTF-8 | 154 | 3.125 | 3 | [] | no_license | a=input()
a=a.split()
a=list(map(int,a))
b1=int(a[0])
c1=int(a[1])
for i in range(1,b1*c1+1):
if(i%b1==0)and(i%c1==0):
print(i)
break
| true |
e30991526d879ba87122dc8355d4ace9e410b033 | Python | dmsherazi/xbee-homeautomation | /plugins/webgraphs/combine.py | UTF-8 | 5,657 | 2.6875 | 3 | [] | no_license | import collections
import datetime
import json
import logging
import xh
log = logging.getLogger('webgraphs.combine')
TIMESTAMP_COLUMN_HEADER = 'Timestamp'
GAP_VALUE = 'datagap'
GAP_DT = datetime.timedelta(minutes=10)
EPOCH = datetime.datetime.utcfromtimestamp(0)
_UNUSEDS_TITLE = 'Unconfigured'
_UNUSEDS_VAR_NAME = 'u... | true |
328ed644e10597455ba5f450e5ba07145b5ca359 | Python | Aries5522/DL-Prep | /04_Algorithms/Leetcode/L48 Rotate Image.py | UTF-8 | 1,037 | 3.578125 | 4 | [] | no_license | class Solution:
def rotate(self, matrix):
"""
Do not return anything, modify matrix in-place instead.
"""
matLen = len(matrix)
padding = 0
def rotatePeri(matrix,padding,matLen):
removelist = []
for i in range(padding+1,matLen-padding):
remo... | true |
3a168c8c5cf8826bec8e7af126247c74ec0308c6 | Python | riberajo/cs-325 | /project1/helpers.py | UTF-8 | 3,507 | 3.46875 | 3 | [] | no_license | import random
import time
def getArrFromFile(src):
arrData = []
with open(src) as file:
for line in file:
#remove space and brackets
line = line.replace('[', '').replace(' ', '').replace(']', '')
#create list
arrData.append([int(num) for num in line.split... | true |
3e56ef049d1256a4c42a9bd950538bbce6ea4012 | Python | Peratham/caption-america | /spatial_recurrent.py | UTF-8 | 2,045 | 2.703125 | 3 | [] | no_license | import numpy as np
import tensorflow as tf
from keras import layers, models
from keras.layers import TimeDistributed as TD
BATCH_SIZE = 1
IMG_WIDTH = 11
IMG_HEIGHT = IMG_WIDTH
GRU_SIZE = 20
print("Keras won't let you change the batch size, so set it to 1")
img = layers.Input(batch_shape=(1, BATCH_SIZE, IMG_HEIGHT, IM... | true |
e112ee9d96d9f1515555d5e71fb2c2418a2b5938 | Python | Jeff-Hill/Python-Intro | /flower-shop/flowers/rose.py | UTF-8 | 227 | 2.78125 | 3 | [] | no_license | from .flower import Flower
from organic import Organic
class Rose(Flower, Organic):
def __init__(self, color):
self.color = color
Flower.__init__(self, "Rose", 7)
Organic.__init__(self)
pass
| true |
6a3921f51f94e0995646f419853eec4e661de200 | Python | omkar-javadwar/CodeWars | /katas/kyu_7/Thinking_&_Testing:_Something_capitalized.py | UTF-8 | 274 | 2.9375 | 3 | [
"MIT"
] | permissive | # https://www.codewars.com/kata/56d93f249c844788bc000002/train/python
'''
Instructions:
No Story
No Description
Only by Thinking and Testing
Look at result of testcase, guess the code!
'''
def testit(s):
return ' '.join([i[:-1]+i[-1].upper() for i in s.split()])
| true |
e6fd2e952f5916256448c68ad3280f408c8275da | Python | dorukhansergin/APL-Brochu | /apl/posterior_approximation.py | UTF-8 | 2,167 | 2.984375 | 3 | [
"MIT"
] | permissive | from typing import Tuple, Any
import numpy as np
from scipy.stats import multivariate_normal
import scipy as sp
ROOT_TWO = np.sqrt(2)
class LogLikelihood:
def __init__(self) -> None:
self.D = None
def __call__(self, f_x: np.ndarray) -> Any:
raise NotImplementedError
def register_data(se... | true |
943a248eb890628ed13de5ef38fbb0ebb85b9b21 | Python | pwentrys/etl_system_base | /helpers/sql/mssql/mssql.py | UTF-8 | 3,248 | 2.546875 | 3 | [
"MIT"
] | permissive | __author__ = 'Przemyslaw "Blasto" Wentrys'
import pymssql
from config.configuration import SQL
from helpers.simplifiers.functions import Simplify
class MSSQL_Connection():
def __init__(self):
pass
def fetch_all_return(self, server_name, query):
"""
Run fetchall query.
:param... | true |
ccc9297cb9ffaf523405e3269d1da6d7652425f5 | Python | highslater/Python_Socratica | /python_examples/11b_If_Then_Else.py | UTF-8 | 444 | 3.640625 | 4 | [] | no_license | #!/usr/bin/env python3.7
"""11b_If_Then_Else.py.
Eleventh Program of the Socratica Sexy Hologram Human/Computer Hybrid
Python Series.
"""
from platform import python_version
from sys import hexversion
print("The Python Version is:", python_version(), " #" + str((hexversion)))
N_input = input("Please enter an inte... | true |
18f7a9f41511a72d225713dc3661388241f2a981 | Python | HOtTEa-bug/Quiz-Project-17- | /data.py | UTF-8 | 2,697 | 2.5625 | 3 | [] | no_license | question_data = [
{
"category":"Science: Computers",
"type":"boolean","difficulty":"medium","question":"The HTML5 standard was published in 2014.",
"correct_answer":"True",
"incorrect_answers":["False"]
},
{
"category":"Science: Computers",
"type":"boolean","d... | true |
c6b88a4b3a40e30b2d9a0c7b1da3fa6b01bd6bf8 | Python | avinashmnit30/pyade | /pyade/mmts.py | UTF-8 | 10,451 | 2.640625 | 3 | [
"MIT"
] | permissive | import cec2014
import numpy as np
import pyade.commons
from typing import Callable, List, Union
def local_search_1(individual: np.ndarray, reset_sr: np.ndarray, search_range: Union[int, float], improve: np.ndarray,
k: int, func: Callable, fitness: float, best_solution, best_fitness):
grade = 0
... | true |
49ec604c3e11f5beebf460c5884462b94be720a2 | Python | 6oghyan/data_science_for_everyone | /bokeh_project/bokeh_network_graphs.py | UTF-8 | 1,068 | 2.765625 | 3 | [] | no_license | import networkx as nx
from bokeh.plotting import figure, show, from_networkx
from bokeh.models import BoxZoomTool, Circle, HoverTool, MultiLine, Plot, Range1d, ResetTool
from bokeh.palettes import Spectral4
G = nx.karate_club_graph()
SAME_CLUB_COLOR, DIFFERENT_CLUB_COLOR = "navy", "red"
edge_attr = dict()
for start_... | true |
a421f0ed467e8959fb2c2666c3a86137ce0b6df4 | Python | thennal10/adventofcode | /2021/day17.py | UTF-8 | 599 | 3.140625 | 3 | [] | no_license | input = open('./input.txt').readlines()[0][13:]
tx, ty = [[int(i) for i in x[2:].split('..')] for x in input.split(', ')]
def xpos(v, n):
if n < v: return ypos(v, n)
else: return v*(v+1)//2
def ypos(v, n): return n*v - (n*(n-1)//2)
count = 0
for vx in range(0, tx[1] + 1):
for vy in range(ty[0], -ty[0]):
... | true |
abe83e74e54bbba47969cc23054b68232603f26e | Python | FREDY1969/tampa-bay-python-avr | /ucc/word/validators.py | UTF-8 | 2,548 | 3.09375 | 3 | [] | no_license | # validators.py
r'''These are the various kinds of input validators.
All validators are subclasses of the `validator` class.
'''
import re
from xml.etree import ElementTree
VALIDATOR_TAG = 'validator' #: XML tag for a validator
def g(): return globals()
def from_xml(root_element):
r'''Return a list of `v... | true |
4c27763fd85db8a4a62d1b73e77ce6c2904e5441 | Python | simondlevy/PythonSockets | /server.py | UTF-8 | 934 | 3.34375 | 3 | [] | no_license | #!/usr/bin/env python3
'''
server.py
Simple Python socket server example with threading
Copyright Simon D. Levy 2018
MIT License
'''
from sockets import SocketServer
from threading import Thread
from sys import stdout
from time import sleep
from hostport import hostport
def talk(server):
while True:
... | true |
3ee0bee8c55c7aba84b809bb3e031feb17bf6c1e | Python | Karanveer08/ga-learner-dsb-repo | /Loan-approval-analysis/code.py | UTF-8 | 1,723 | 3.125 | 3 | [
"MIT"
] | permissive | # --------------
# Import packages
import numpy as np
import pandas as pd
from scipy.stats import mode
# code starts here
bank = pd.read_csv(path)
categorical_var = bank.select_dtypes(include = 'object')
print(categorical_var)
numerical_var = bank.select_dtypes(include = 'number')
print(numerical_var)
# code end... | true |
6b4213710456d964be7cfef4e201b4718a5f8123 | Python | zulip/zulip | /puppet/zulip/files/nagios_plugins/zulip_postgresql/check_postgresql_replication_lag | UTF-8 | 4,866 | 2.515625 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | permissive | #!/usr/bin/env python3
"""Nagios plugin to check the difference between the primary and
replica PostgreSQL servers' xlog location. Requires that the user this
connects to PostgreSQL as has been granted the `pg_monitor` role.
This can only use stdlib modules from python.
"""
import configparser
import re
import subpr... | true |
5217d24382e333b0c97a5b7d3f646270fbaadabc | Python | smtamh/oop_python_ex | /study_ex/15_thread/1502_thread.py | UTF-8 | 346 | 3.3125 | 3 | [] | no_license | import time
while True:
print("clientA")
time.sleep(0.1)
print("clientB")
time.sleep(0.1)
print("clientC")
time.sleep(0.1)
print("clientD - 지연 2초")
time.sleep(2)
print("clientE")
time.sleep(0.1)
print("clientF - 지연 3초")
time.sleep(3)
print("clientG")
time.s... | true |
89fa785c698896065222f715936a49ef266dbc71 | Python | worldbank/GOST_PublicGoods | /GOSTNets/GOSTNets/Calculate_OD.py | UTF-8 | 5,278 | 2.671875 | 3 | [
"MIT"
] | permissive | import os, sys, logging, warnings, time
import osmnx
import networkx as nx
import pandas as pd
import geopandas as gpd
import numpy as np
from shapely.geometry import Point
import GOSTnet as gn
def calculateOD_gdf(G, origins, destinations, fail_value=-1, weight="time"):
''' Calculate Origin destination matrix f... | true |
de51acd6edfa5355c4fd2009e4b589678492a483 | Python | yanzj/bkt-toolbox | /installer/config.py | UTF-8 | 1,821 | 2.59375 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
import sys
import os
import argparse
import helper
parser = argparse.ArgumentParser()
parser.add_argument('-af', '--add_folder', action='append', help='Add feature folder to config file')
parser.add_argument('-mg', '--migrate', help='Migrate config.txt from the given version to the current on... | true |
1482cc8f392529779d94a3d3e92e58bd3d5f1462 | Python | fengxiaolong886/leetcode | /804. 唯一摩尔斯密码词.py | UTF-8 | 1,662 | 4.1875 | 4 | [] | no_license | """
国际摩尔斯密码定义一种标准编码方式,将每个字母对应于一个由一系列点和短线组成的字符串, 比如: "a" 对应 ".-", "b" 对应 "-...", "c" 对应 "-.-.", 等等。
为了方便,所有26个英文字母对应摩尔斯密码表如下:
[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
给定一个单词列表,每个单词可以写成每个字母对应摩尔斯密码的组合... | true |
1e2cbc8a5dd0bddd3bccec1b4c0f4e34ddbd501f | Python | dbmarch/python-complete | /test/exampleModules.py | UTF-8 | 159 | 2.609375 | 3 | [] | no_license | import shelve
# print (dir())
# print()
# print (dir(shelve))
# for obj in dir (shelve.Shelf):
# if obj[0] != '_':
# print (obj)
#
#
help(shelve) | true |
865adaf4f469260353f94c1db09046dd4c2a7ee6 | Python | srikarkasyap/Python-scripting | /Greatest_of_3_Numbers.py | UTF-8 | 265 | 4.28125 | 4 | [] | no_license | a=float(input("Enter a number:"))
b=float(input("Enter 2nd number:"))
c=float(input("Enter 3rd number:"))
if a>b and a>c:
print("The greatest number is ",a)
if b>a and b>c:
print("The greatest number is ",b)
if c>a and c>b:
print("The greatest number is ",c)
| true |
826503f77cce383e403515ec67fffd5637efa442 | Python | dpuentesserrano/airflow-dags | /archive/dags/train_models.py | UTF-8 | 2,249 | 3 | 3 | [
"MIT"
] | permissive | # Import modules
import datetime as dt
import os
from airflow.operators.python_operator import PythonOperator
from airflow.models import DAG
# The default arguments for our DaG
default_args = {
'owner': 'kavi sekhon',
'depends_on_past': False,
'start_date': dt.datetime(2018, 10, 11),
'email': ['kavi.sk... | true |
37c6f3a8cf2b49a52fb52f6a0ca7de38c0e37cc2 | Python | hunhoon21/TOBIGS_HW | /5_NN/Model.py | UTF-8 | 3,403 | 3.234375 | 3 | [] | no_license | import numpy as np
class TwoLayerNet():
"""
2 Layer Network를 만드려고 합니다.
해당 네트워크는 다음과 같은 구조를 따릅니다.
input - Linear - ReLU - Linear - Softmax
Softmax 결과는 입력 N개의 데이터에 대해 각 클래스에 대한 확률입니다.
"""
def __init__(self, input_size, hidden_size, output_size, std=1e-4):
"""
네트워크에 필요한 가... | true |
199176c6ef406841b32e0c06250d5a6fb3b07154 | Python | lets-code-together/lets-code-together | /AlgorithmsBasic/1-InputOutput/10992_3.py | UTF-8 | 321 | 3.859375 | 4 | [] | no_license | # 별찍기17
# 예제를 보고 규칙을 유추한 뒤에 별을 찍어 보세요.
N = int(input())
# 첫째 줄
print(' ' * (N-1) + '*')
# 첫째 줄과 마지막 줄을 제외한 줄
for i in range(1, N-1) :
print(' ' * (N-i-1) + '*' + ' ' * (2*i-1) + '*')
# 마지막 줄
if N > 1 :
print('*' * (2*N-1))
| true |
5f15bbe5c11a881b4ef581acd86937fef189950b | Python | NetworkRanger/tensorflow-ml-exercise | /chapter02/demo_2.3.py | UTF-8 | 939 | 3.21875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/python2.7
# -*- coding:utf-8 -*-
# Author: NetworkRanger
# Date: 2018/11/1 下午10:06
# 2.3 TensorFlow 的嵌入Layer
import numpy as np
import tensorflow as tf
# 1.首先,创建数据和占位符
my_array = np.array([[1., 3., 5., 7., 9.],
[-2., 0., 2., 4., 6.],
[-6., -3., 0., 3., 6.]])
x_vals = np.a... | true |
2acac152abf60d6cd9e9be28f43e88fd9d0b9d9c | Python | dhengkt/CourseProjects | /Python/330/cateAnalysis_problem3.py | UTF-8 | 1,668 | 3.859375 | 4 | [] | no_license | #---------------------------------------------------------------------------
# cateAnalysis_problem3.py
# This function calculates the p-value given an input contingency table
# using the chi-squared test of independence for an r row, c column
# contingency table without using for or while loops.
#
# Designed by Hsin... | true |
793adc099273d8d5afbb1d2df4728fa1a9ac31fe | Python | AshOil/APS | /SWEA/D1/2027_대각선 출력하기.py | UTF-8 | 218 | 3.125 | 3 | [] | no_license | import sys
sys.stdin = open("input_data/2027.txt","r")
for i in range(5):
my_list = ['+','+','+','+']
my_list.insert(i,'#')
''.join(my_list)
for ii in my_list:
print(ii, end='')
print()
| true |
13cd90a4a9a991219a334b151fc9961c94510f94 | Python | snowdj/cs_course | /QSTK/HW4/backtest.py | UTF-8 | 6,859 | 3.078125 | 3 | [] | no_license |
'''
@author: Tony (Ning) Liu
@contact: tonyningliu@gmail.com
@summary: Simple backtest. Combining event finder and market simulator.
'''
#--- import library ---#
# standard library
import numpy
import datetime
import copy
# 3rd party library
import pandas
# local library (QSTK)
from qstkutil import qsdateutil, Dat... | true |
cb0d0ceb832b92f6b167675d619cb0c937a46563 | Python | gllewellyn19/blue-devil-rideshare | /Flask/accountPageHelpers/previous_rides.py | UTF-8 | 661 | 2.53125 | 3 | [
"MIT"
] | permissive | import datetime
from datetime import date
from database import db
from flask import session, render_template
def get_prev_rides():
"""
Use prepared statements to find all of the users rides in the past
"""
db.session.execute('''PREPARE PastRides (varchar, date) AS SELECT * FROM Ride WHERE driver_netid... | true |
383cd638180b595ac1f308c2b919dce0a78b6f2b | Python | MeatballNissan/py | /untitled/day04/fib.py | UTF-8 | 412 | 3.9375 | 4 | [] | no_license |
#迭代器原理
def fib(max):
n,a,b = 0,0,1
while n < max:
# print(b)
yield b #保存了函数的中断状态
a, b = b, a + b # t = (b, a+b) ; a = t[0] ; b = t[1]
n += 1
return
f = fib(10)
print(f.__next__())
print(f.__next__())
print(f.__next__())
for i in f:
print(i)
try:
print(f.__next_... | true |
bf675def66f2f1ff586a3bfea57935363f15c2f5 | Python | lukszyn/Python | /Zadanie28.py | UTF-8 | 2,039 | 4.40625 | 4 | [] | no_license | # ZADANIE 28
def menu():
while True:
print('***** MENU *****')
print('1 - Wprowadz dane o nowym pojezdzie')
print('2 - Wyswietl dane o pojezdzie')
print('3 - Usun dane o pojezdzie')
print('x - Wyjdz z programu')
wybor = input('Wybierz opcje programu: ')
... | true |
ef0fdca8cd6fb8f369eb23ef99b8ab09b42ee85c | Python | mskuroedov/trello_spreadsheet | /core/spreadsheets_helpers.py | UTF-8 | 2,513 | 2.546875 | 3 | [] | no_license | from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client.service_account import ServiceAccountCredentials
from trello_spreadsheets_django.consts import google_config
scope = [
'https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive'
]
creds = ServiceAccou... | true |
4e8174335f6382806db991eb5e05d6979e789ed6 | Python | Rinimabi/WebLab | /formerFile/正则表达式.py | UTF-8 | 167 | 3.09375 | 3 | [] | no_license | import re
string = """
<a href='www.runoob.com'>first</a>,
<a href='www.baidu.com'>second</a>
"""
r = re.findall(r'<a href=\'([www].*)\'>(.*)</a>', string)
print(r)
| true |
9a601358b6b2b57b3a0dc7c6479097c562869ddc | Python | magicericat/lamastate | /model.py | UTF-8 | 3,123 | 2.859375 | 3 | [] | no_license | """Models and database functions for EEG tracking project."""
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import func
db = SQLAlchemy()
##############################################################################
# Model definitions
class User(db.Model):
"""User of lama log website."""
__... | true |
6139256bf2faecf2d4342824460327d3e6df8a76 | Python | charliekaks/Restful-service-for-questions-and-answers | /app/v1/models/models.py | UTF-8 | 902 | 3.046875 | 3 | [] | no_license |
from flask_sqlalchemy import SQLAlchemy
import json
db = SQLAlchemy()
class Answers(db.Model):
__tablename__ = 'answers'
id = db.Column(db.Integer, primary_key=True)
answer = db.Column(db.String, nullable= False)
def __init__(self, answer):
self.answer = answer
def json_maker(self):
... | true |
8eb971fe55e6a9e3cf05f52dd07ab463b33c09a3 | Python | subenakhatun/python-problems | /online1.py | UTF-8 | 687 | 3.921875 | 4 | [] | no_license | # t = int(input("Enter a integer number: "))
# if t < 15:
# a = input('Enter a value: ')
# b = input('Enter a value: ')
#
# if a < b:
# print('<')
# a = input('Enter a value: ')
# b = input('Enter a value: ')
# if a > b:
# print('<')
#
# a = input('Enter a value: ... | true |
b7dffd7d72a90fc370cfd9ce4060dc0f488e106c | Python | isoscl/betterlifepsi | /psi/app/utils/format_util.py | UTF-8 | 3,006 | 3.296875 | 3 | [
"MIT"
] | permissive | # coding=utf-8
from decimal import Decimal, ROUND_HALF_UP
from pypinyin import pinyin, lazy_pinyin
import pypinyin
def format_decimal(value):
"""
Format a decimal with two decimal point with rounding mode ROUND_HALF_UP
:param value the decimal to format
"""
return Decimal(
Decimal(value).qu... | true |
eef8a8612b5adf5a0472bd768dece45115baf57f | Python | yanjindulam1223/Python-lesson-2 | /d1.py | UTF-8 | 183 | 3.515625 | 4 | [] | no_license | #өгөгдсөн 2 тооны нийлыэр олоорой.
too1 = input("too1: ")
too2 = input("too2: ")
niilber = int(too1) + int(too2)
print("Нийлбэр:" + str(niilber)) | true |
53a63a93e2812ceb73ce8ce1d8b3199caf3d3736 | Python | ja1600/RFID_D302 | /d302_scanner/keyboard.py | UTF-8 | 652 | 2.96875 | 3 | [] | no_license | import applescript
class KeyboardWriter:
def __init__(self):
print "Keyboard Init"
def writeKey(self, key):
if key is "return":
scpt = applescript.AppleScript('''
tell application "System Events"
key code 36
end tell
''')... | true |
a2929945c4226e6085b556bbd9ec3bd70fc73699 | Python | blessingayo/parsel_tongue_mastered | /blessing/PerfectSquare.py | UTF-8 | 258 | 3.640625 | 4 | [] | no_license | import math
while(True):
perfectSquare = int(input("Enter any number: "))
if (int(math.sqrt(perfectSquare))) **2 == perfectSquare:
print("it is a perfect number")
else:
print("Borrow Sense naw: it is not a perfect number")
| true |
a1ae5ae9fa6d93ff7c653307ed5ed813c646821f | Python | krnets/codewars-practice | /8kyu/Count Odd Numbers below n/index.py | UTF-8 | 415 | 4 | 4 | [] | no_license | # 8kyu - Count Odd Numbers below n
""" Given a number n, return the number of positive odd numbers below n, EASY!
oddCount(7) //=> 3, i.e [1, 3, 5]
oddCount(15) //=> 7, i.e [1, 3, 5, 7, 9, 11, 13]
Expect large Inputs! """
# def odd_count(n):
# return n // 2
def odd_count(n):
return len(range(1, n, 2))
# ... | true |
de4c3f45513b4f78c655a494d79cc3fda49544ed | Python | GoranTopic/Web-Scrapping-with-Python | /mapping_wikipedia/wikipedia_node_scapper.py | UTF-8 | 4,237 | 3.015625 | 3 | [] | no_license | #!/usr/bin/python
# a program to scrap an store the whole wikipedia vertex and edges,
# so that an ofline program can find the shortes path on this data
# istahd of having to do online html requests, which take time
# by Goran Topic
from urllib.request import urlopen
from bs4 import BeautifulSoup
from multip... | true |
4aef49bec42e5bb175a96f0050218a28a6c14058 | Python | YoInterneto/Algoritmia-Y-Complejidad | /aaAlberto/T3/Ejercicio4.py | UTF-8 | 2,003 | 3.484375 | 3 | [] | no_license |
def comparar(pivote, lista, estaLista, menores, mayores, index):
#si esta vacía retornamos el resultado
if(len(lista) <= index):
return (estaLista,menores,mayores)
else:
elemento = lista[index]
if (elemento == pivote):
estaLista = True
elif (elemento > pivote):... | true |
22e9ae483ccfd2b4048f5a300adfd647971a8329 | Python | jonemo/gum | /gum/tools/upc2color.py | UTF-8 | 618 | 2.921875 | 3 | [
"MIT"
] | permissive | from argparse import ArgumentParser
from sys import exit
from gum import upc_to_color
parser = ArgumentParser(
description='Get gum package color as hex rgb value given a UPC code')
parser.add_argument(
'UPC', type=str, help='UPC code from barcode')
def main():
args = parser.parse_args()
print(args... | true |
6e0a173a2988e6b09c379f9a2f5eb9109ef7fb8f | Python | qwe764840446/py-L | /spider/Trip.py | UTF-8 | 818 | 2.546875 | 3 | [] | no_license | #!/user/bin/env python
# -*- coding:utf-8 -*-
from bs4 import BeautifulSoup
import requests
url = "https://www.tripadvisor.cn/Attractions-g60763-Activities-New_York_City_New_York.html"
wb_data = requests.get(url)
soup = BeautifulSoup(wb_data.text, 'lxml')
"""
print(soup)
titles=soup.select('#taplc_attraction_coverpa... | true |
d209bd85501e8fb871135a83a2e1f739947480c7 | Python | dodo5575/CLRD | /regression.py | UTF-8 | 6,806 | 2.984375 | 3 | [] | no_license | import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn.apionly as sns
from pandas.plotting import scatter_matrix
from sklearn.model_selection import train_test_split, KFold
from sklearn import preprocessing
from sklearn.linear_model import LinearRegression, SGDRegressor
# Fir... | true |
1d665de875234f3c482d5c753f2148e7d9a5415f | Python | lijiansong/lang | /python/foo/decorators/class_decorator.py | UTF-8 | 411 | 3.71875 | 4 | [
"WTFPL"
] | permissive | #!/usr/bin/env python
'''
Using a Class as a Decorator
'''
'''
def decorator(f):
def helper():
print("Decorating", f.__name__)
f()
return helper
'''
class decorator:
def __init__(self, f):
self.f = f
def __call__(self):
print("Decorating", self.f.__name__)
self.... | true |
ae893a72994395e98d7001de2c62f25a38a688a2 | Python | underflow101/MLDL | /SW_Maestro/EMG_DTC.py | UTF-8 | 2,054 | 2.796875 | 3 | [] | no_license | import numpy as np
import pandas as pd
from pandas import read_csv
from sklearn.svm import SVC
from sklearn.metrics.classification import accuracy_score
from sklearn.metrics import confusion_matrix
from matplotlib import projections
from math import gamma
from numpy import float64
from sklearn.neural_network import MLP... | true |