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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
1c5547f781096e70d696d2c00148755e1d5d2595 | Python | mayankmusaddi/hgnn | /plot_osmfish.py | UTF-8 | 1,243 | 2.59375 | 3 | [] | no_license | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
import h5py
file1 = "osmfish/osmFISH_SScortex_mouse_all_cells.loom"
f = h5py.File(file1,mode = 'r')
meta = f['col_attrs']
cell_types = np.asarray(meta['ClusterID'])
cell_names = np.asarray(meta['ClusterName'])
X =... | true |
e8abd6c0b31f6f824c46b4f2c2128adf7d53b2a0 | Python | Yue2u/Coursera_Python | /Diving_in_Python/W5/Multithread_programming.py | UTF-8 | 4,034 | 3.234375 | 3 | [] | no_license | import time
# import os
# from multiprocessing import Process
from threading import Thread
# import threading
# from concurrent.futures import ThreadPoolExecutor, as_completed
# from queue import Queue
# pid = os.getpid()
#
# Make process to watch on oit in linux console
# while True:
# print(pid, time.time())
... | true |
9249f20e4a4c110c31f46aff975624fae5dd67a9 | Python | bishwa3141/Math450 | /FloatingPoint/Zeta1.py | UTF-8 | 157 | 3.0625 | 3 | [] | no_license | #!/usr/bin/python
import sys
N = 10**int(sys.argv[1]);
sum = 0
for i in xrange(N,0,-1):
print i
sum += 1/float(i)
print('sum(%d) = %f' % (N , sum))
| true |
582892f53a5d552caacee3c1261a5648787cf337 | Python | victorou22/donation-analytics | /src/donation_analytics_driver.py | UTF-8 | 1,177 | 2.578125 | 3 | [] | no_license | import argparse
import os
from donation_analytics_validations import *
from donation_analytics_process import *
def main():
# Parses command line arguments for the paths
parser = argparse.ArgumentParser(description='Parses the path for the percentile file and the contributions file.')
parser.add_argument('... | true |
efce3c5c7795b97d164c3b31ae3b37c7277b1143 | Python | payneio/babybot_junk | /Pin.py | UTF-8 | 727 | 3.296875 | 3 | [] | no_license | import math
class Pin:
def __init__(self, board, pin_no):
self.pin = board.get_pin("d:"+str(pin_no)+":p")
self.board = board
def transition(self, a, b, secs):
steps = math.fabs((b - a) * 100.0)
wait_time = secs/float(steps)
increment = (b-a) / 100.0
position = a
epsilon = .05
w... | true |
9dd62d31a8ef82d59fe8dcc0f951b81466c9bc1c | Python | andreyvit/yoursway-python-commons | /utils/sequtil.py | UTF-8 | 798 | 3.015625 | 3 | [] | no_license |
def index_by_key(entities):
return index(lambda e: e.key(), entities)
def group(func, iterable):
result = {}
for i in iterable:
result.setdefault(func(i), []).append(i)
return result
def slice(count, iterable):
result = []
for i in iterable:
if len(result) == 0 or len(result[... | true |
720703f2fc2bccd85ef24d25414788e7d2e89ebe | Python | GSIL-Monitor/Share | /python/qt/QtDemo02.py | UTF-8 | 1,262 | 2.546875 | 3 | [] | no_license | # coding=utf-8
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWidgets import QMessageBox
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.ui = uic.loadUi('mainwindow.ui')
self.ui.closeEvent = self.closeEvent
... | true |
355ecaec0fe31022694ae73e09b1478f5f2af715 | Python | RohanGautam/Algorithm-implementations | /sorting/quickSort.py | UTF-8 | 1,423 | 3.75 | 4 | [] | no_license | def partition(L):
start, end, mid = 0, len(L), len(L)//2
L[start], L[mid] = L[mid], L[start] # move pivot to the beginning
pivot = L[start] # make pivot the middle value (it was swapped with the first). We need it's value so we can make comparisions with it later on
last_small = start # last_small ke... | true |
188b1ad34cb0eae1f1238fced85f888c9f29b28d | Python | CodeSteak/write-your-python-program | /python/tests/testDefinedLater.py | UTF-8 | 469 | 3 | 3 | [
"BSD-3-Clause"
] | permissive | import unittest
from writeYourProgram import *
setDieOnCheckFailures(True)
class TestDefinedLater(unittest.TestCase):
def test_isSome(self):
ty = DefinedLater('Name')
Name = Record("Name", "firstName", str, "lastName", str)
myName = Name("Stefan", "Wehr")
self.assertTrue(ty.isSome... | true |
2fd3d351d02cd415c36134c863ab3fd1deade8fe | Python | Media1129/elastic_search | /create_index.py | UTF-8 | 1,759 | 2.65625 | 3 | [] | no_license | import json
from elasticsearch import Elasticsearch, helpers
from tqdm import tqdm
# RECIPE1M_FILE = "layer1.json"
RECIPE1M_FILE = "../recipes_with_nutritional_info.json"
def get_connection():
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
if not es.ping():
raise ConnectionError("Cannot c... | true |
2902857b999f16f50f99daf82e524564a681b9e5 | Python | danieldfc/trainling-python | /Atividades/Yuri/Aula/numeros_sequencia.py | UTF-8 | 86 | 3.828125 | 4 | [] | no_license | numero = int(input('Informe um número -> '))
for i in range(numero + 1):
print(i)
| true |
3822c8397d4cb34d1c99bc1d8cc4c9d83dd7e4c1 | Python | jlumpe/python-emacs | /emacs/elisp/ast.py | UTF-8 | 3,556 | 3.625 | 4 | [
"MIT"
] | permissive | """Base classes for Emacs Lisp abstract syntax trees."""
from typing import Union, Tuple, Iterable
from .util import escape_emacs_string
class Expr:
"""Base for classes which represent Elisp expressions."""
def __str__(self):
"""Render the expression as elisp code."""
raise NotImplementedError()
def quote(... | true |
d866c8f40ffd324a1e80524d8a5db444a456b59a | Python | MediaPreneur/Introduction-to-python | /while-else.py | UTF-8 | 82 | 3.234375 | 3 | [
"CC0-1.0"
] | permissive | i=0
while i<5:
print i
i=i+1
else:
print "the value execeeds 5" | true |
7105902139a3e65b990cb80ba7913fb06914b673 | Python | SmithGeorge/khiimel-oyuun | /khiimel-oyuun.py | UTF-8 | 1,177 | 3.3125 | 3 | [] | no_license | normal_answers = ["你们懂吗","人生的意义是什么","你们的开发经验是什么","我要屎了","男人要的是到底什么样的女人","加我飞书","我不行了","我要建立资产", "龙腾世纪","内裤","我为什么总是有很多的想法","你们用扫地机器人吗","你们思考吗","你们学数学吗","五感","为别人着想"]
special_answers = {"lqt":"lqt的家像宫殿一样","美女":"哪里有有才的美女,在电脑上查找美女","你们有Google voice吗":"没有","养孩子":"自己的事情都没搞好 养什么孩子"}
import random
import re
def answer(que... | true |
5089153c105a4280641fb186cfdae6d2ecfac978 | Python | chrisliu529/winminer | /bench.py | UTF-8 | 1,685 | 2.8125 | 3 | [] | no_license | #!/usr/bin/python3
import subprocess
import sys
import re
import time
from string import Template
from concurrent.futures import ProcessPoolExecutor
def get_output(cmd):
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
out, err = p.communicate()
if p.returncode != 0:
print(out)
... | true |
ee24b5e2ba197808d25e6b15c2cd1d22198b85d2 | Python | uhla/fler-downloader | /downloader/excel_item_reader.py | UTF-8 | 1,171 | 2.75 | 3 | [] | no_license | from os import path
import xlrd
from downloader.catalog_item_configuration import CustomizedCatalogItem
class ExcelItemReader:
def read_configuration(self, filename):
customized_catalog_items = {}
if path.exists(filename):
print("Loading customized configuration from file: " + filen... | true |
5048db1e210b65aa6d21c0c6c7a1e96166b407f4 | Python | yaopoppysong/Partial-Least-Square-Regression | /RealExample.py | UTF-8 | 945 | 3.453125 | 3 | [] | no_license | # Using Real Data Set
# load package
import pandas as pd
from sklearn.cross_decomposition import PLSRegression
from sklearn.preprocessing import scale
import matplotlib.pyplot as plt
# read in data set
wine = pd.read_excel('wine.xlsx')
wine.head()
wine_new = wine.copy()
# normalize the data set
n = len(wine.columns)... | true |
77dbf1a4ebf84f27a1711b223abd551b2deea6ec | Python | ashukumar27/DeepLearning | /Image_identification.py | UTF-8 | 1,170 | 2.828125 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 22 10:31:47 2018
@author: ashutosh
Image Classification with VGG19
"""
import os
import time
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(42)
os.chdir("/Users/ashutosh/Documents/analytics/DeepLearning/VGG19")
from keras.appli... | true |
bec7eca3ef985cd3c62f9bea525cef0abf02d0e2 | Python | Luc1103/CSForum | /CSForum/WelcomePage.py | UTF-8 | 5,746 | 3.171875 | 3 | [] | no_license | import tkinter as tk
import mysql.connector
import HomePage
#Connects to the database
mydb = mysql.connector.connect(
host = "localhost",
user = "root",
passwd = "sD6G7Bx@f8cve$i3",
database = "forum"
)
#Allows editing of the database
mycursor = mydb.cursor()
#Displays the welcome page UI
def... | true |
204b6da42a0022de9d0375b340b2d1918dd6cd73 | Python | Lenazhou/simple-faster-rcnn-interact | /data/ut_dataset.py | UTF-8 | 5,775 | 2.921875 | 3 | [
"MIT"
] | permissive | import os
import xml.etree.ElementTree as ET
import json
import numpy as np
from .util import read_image
class UTDataset:
"""Bounding box dataset for PASCAL `VOC`_.
.. _`VOC`: http://host.robots.ox.ac.uk/pascal/VOC/voc2012/
The index corresponds to each image.
When queried by an index, if :obj:`re... | true |
e65a9d84966614051af998ea0faea69994319ca4 | Python | stasvorosh/pythonintask | /PINp/2014/DASHA_ZABOLOTNOVA/task_2_44.py.py | UTF-8 | 621 | 3.328125 | 3 | [
"Apache-2.0"
] | permissive | #Задача 2. Вариант 44.
#Напишите программу, которая будет выводить на экран наиболее понравившееся вам высказывание, автором которого является Эразм Роттердамский. Не забудьте о том, что автор должен быть упомянут на отдельной строке
#Zabolotnova D.K.
#23.02.2016
print ("Нет ничего отважнее, чем победа над самим с... | true |
5f1981c50ae29eb94fca8ea505e32667cd4e0aee | Python | snowmanunderwater/hr | /hr.py | UTF-8 | 1,629 | 3.09375 | 3 | [] | no_license | #!/usr/bin/env python3
import argparse
import subprocess
import sys
# read terminal width
columns = int(subprocess.check_output(['stty', 'size']).decode().split()[1])
# argparse
parser = argparse.ArgumentParser(description='Horizontal rule')
parser.add_argument('-c',
dest='color', # argument n... | true |
fd62cd8d27b971fdc88286644bf49c4be1527cdb | Python | 06hong/Marvel | /marvel_stuff/authentication/routes.py | UTF-8 | 1,893 | 2.859375 | 3 | [] | no_license | from flask import Blueprint, render_template, request, redirect, url_for, flash
from marvel_stuff.forms import UserLoginForm
from marvel_stuff.models import db, User, check_password_hash
from flask_login import login_user, logout_user, login_required
auth = Blueprint('auth',__name__, template_folder='auth_templates')
... | true |
f8a25b6332add240d5ea0a90c518521dfbc214e9 | Python | Sachin-ninja/2D-Plot | /GUI-2D-Plot-master/Final_Project.py | UTF-8 | 5,464 | 3.453125 | 3 | [] | no_license | from tkinter import *
#import array
import numpy as np
#for exit option in file
import sys
#for getting the file from the computer we use the modul filename
from tkinter import filedialog
import os
import matplotlib.pyplot as plt
#function to select a file from the system upon clicking the button
def getfile(... | true |
d3ff54885df6c8e854306bbf6c7789cb9db8a00a | Python | saadmohmed/exif-gps-tracer | /getexif.py | UTF-8 | 1,716 | 2.546875 | 3 | [] | no_license | from PIL import Image
from PIL.ExifTags import TAGS
from PIL.ExifTags import GPSTAGS
def get_exif(filename):
image = Image.open(filename)
image.verify()
return image._getexif(),filename
def get_gpstags(exif,filename):
if not exif:
print("No EXIF metadata found for "+filename)
if exif:
... | true |
e2feb2e7737fc69b31e7bdac4f5f85ecac9c0677 | Python | JustinLokHinWu/OpenEyeTap | /OpenEyetap_Applications/Bluetooth/notificationservice.py | UTF-8 | 4,731 | 2.796875 | 3 | [
"MIT"
] | permissive | from tkinter import *
import PIL
from PIL import ImageTk, Image
import os
import threading
import time
from queue import Queue
import json
class NotificationService(threading.Thread):
def run(self):
# set up UI
self.root = Tk()
self.root.overrideredirect(True)
width = self... | true |
fccaf2359df5faf467918c4e19d36fc0e8142c5d | Python | sarudalf3/poo-python | /stores.py | UTF-8 | 857 | 3.109375 | 3 | [] | no_license | class Store:
def __init__(self, name): #, market):
self.name = name
self.productsList = []
def add_product(self, new_product):
self.productsList.append(new_product)
def sell_product(self, product):
for prod in self.productsList:
if prod.ID == product.ID:
... | true |
807ae744c8c634c73bbe7f1e78002fe503a63a5b | Python | bong1915016/Introduction-to-Programming-Using-Python | /evennumberedexercise/Exercise4_8.py | UTF-8 | 336 | 4 | 4 | [] | no_license | # Enter three numbers
number1, number2, number3 = eval(input("Enter three integers: "))
if number1 > number2:
number1, number2 = number2, number1
if number2 > number3:
number2, number3 = number3, number2
if number1 > number2:
number1, number2 = number2, number1
print("The sorted numbers are", number1, n... | true |
c8330fac27d5f375b02e34b08bea3a549c24658f | Python | arunmcherian94/library-rest-api | /core_apis/crud/models.py | UTF-8 | 5,126 | 2.578125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.validators import RegexValidator
from django.db import models
from core_apis import settings
import uuid
# Create your models here.
class Member(models.Model):
"""
Member table to store member parameters.
"""
phone_regex... | true |
9192d51447a7f9e87fa54bfd029c56719c0fa4d3 | Python | RanadheerDanda/Selenium-Python | /SeleniumPractice/Slider.py | UTF-8 | 1,027 | 2.890625 | 3 | [] | no_license | from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
class SliderExample:
def slider_test(self):
path='F:\\selenium-java-3.141.59\\geckodriver.exe'
baseUrl='https://jqueryui.com/slider/'
driver = w... | true |
f8416ed101fd036510d6e4a55882f6bf34337fe1 | Python | snakedragon/udacity-dlnd | /language-translation/doTrans.py | UTF-8 | 2,567 | 2.890625 | 3 | [
"MIT"
] | permissive | import tensorflow as tf
import numpy as np
import helper
import problem_unittests as tests
# Number of Epochs
epochs = 50
# Batch Size
batch_size = 64
# RNN Size
rnn_size = 108
# Number of Layers
num_layers = 2
# Embedding Size
encoding_embedding_size = 100
decoding_embedding_size = 100
# Learning Rate
learning_rate ... | true |
70a40cde8c7c2fb6a06e19d3642aa3632d2cbae5 | Python | Not2Day2Die/PySnow | /createTable.py | UTF-8 | 548 | 2.75 | 3 | [] | no_license | import pymssql
conn = pymssql.connect(host='60.251.238.43',
user='sa',
password='8179311!QAZ',
database='db8780',
charset='utf8',
port=8433)
#查看连接是否成功
cursor = conn.cursor()
'CREATE TABLE Cust... | true |
6f99dced5a4b2e17ecdd67695f60b0d33182c644 | Python | ehudb9/cyberBall | /venv/Experiment/control_modes/keyboard_control_mode.py | UTF-8 | 1,116 | 2.859375 | 3 | [] | no_license | from venv.Experiment.arm_movement_control import ArmMotorControl
from venv.Experiment.constants import *
from pynput import keyboard
class KeyboardControlMode:
def __init__(self):
self.arm = ArmMotorControl()
self.arm.set_moving_speed(MOTOR_NAME, 120)
self.arm.set_acceleration(MOTOR_NAME, ... | true |
5e2045a72218448c42c0388df9e8a06f6034e419 | Python | lmquan1609/robot | /01_sample_search_and_return/05_decision_to_go.py | UTF-8 | 1,226 | 3.109375 | 3 | [] | no_license | import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
import cv2
from decision_extra_functions import *
# Define a function to convert from cartesian to polar coordinates
def to_polar_coords(xpix, ypix):
# Calculate distance to each pixel
dist = np.sqrt(xpix ** 2 + ypix ** 2)
... | true |
a16e1fc7a4c94579bcbe24b00e522485afc3152c | Python | Alfonsxh/Python | /LoggerTest/Test_logger.py | UTF-8 | 1,565 | 3.015625 | 3 | [] | no_license | """
@Author : Alfons
@Contact: alfons_xh@163.com
@File : Test_logger.py
@Time : 2019/5/7 16:41
"""
import os
import logging
def Init(level, filename, console):
"""
日志初始化函数
:param level: 日志等级
:param filename: 日志输出文件名
:param console: 是否在控制台输出
:return:
"""
logger = logging.getL... | true |
84d9e2001b0c977317c5b8a4b76f7b61f12fac76 | Python | sadashiv30/pyPrograms | /rmotr/class2-Lists-Tuples-Comprehensions/factorial.py | UTF-8 | 671 | 4.40625 | 4 | [] | no_license | """
Write a function that produces all the members to compute
the factorial of a number. Example:
The factorial of the number 5 is defined as: 5! = 5 x 4 x 3 x 2 x 1
The terms o compute the factorial of the number 5 are: [5, 4, 3, 2, 1].
Once you have that function write other function that will compute the
factorial... | true |
3a8d5b4bb7668b44ca1b05ee9b3aaa2ba9e9334d | Python | olimpiadi-informatica/oii | /2013/nazionali/fermata/gen/generatore.py | UTF-8 | 2,156 | 3.234375 | 3 | [] | no_license | #!/usr/bin/env python2
from limiti import *
usage="""Generatore per "Fermata".
Parametri:
* K (tipo di generazione)
* S (seed)
* Se K == 0:
Generazione random:
* N (primo numero in input)
* ST (numero di stati)
* D (massimo valore assoluto dei salti)
* Se K == 1:
Generazione a catene e cicli:
* N ... | true |
79f40a90d1d9faea046ddfce546456555dd6f8e3 | Python | quasarbright/quasarbright.github.io | /python/oop.py | UTF-8 | 2,807 | 3.78125 | 4 | [
"MIT"
] | permissive | import unittest
'''
an object is what an object has
hashmap of fields and methods
goals:
inheritance
dynamic dispatch
field and method access
tools: functions, lambdas, dictionaries
'''
def dot(obj, attribute_name, args=None):
if attribute_name in obj['fields']:
return obj['fields'][attribute_name]
... | true |
28940b522a11c6b7022443a3136a0090e14a85ec | Python | blackadar/xray-qa | /measure.py | UTF-8 | 7,907 | 3.453125 | 3 | [] | no_license | """
Algorithmically measures the distance between bones in a hand joint.
"""
import pathlib
import numpy as np
import numpy.polynomial.polynomial as poly
from PIL import Image
read_from = pathlib.Path('data/out/')
def find_horizontal_range(image, show_plots=True):
"""
Algorithmically discovers the approxima... | true |
5539633a7a901d247c183eb87a466b2d6148dffe | Python | sadhudgp91/Smart-City | /Camera.py | UTF-8 | 566 | 2.75 | 3 | [] | no_license | # import the necessary packages
import time
import sys, os
import RPi.GPIO as GPIO
# Use BCM GPIO references
# instead of physical pin numbers
GPIO.setmode(GPIO.BCM)
# Define GPIO signals to use
# Physical pins 18
# GPIO18
pin_button = 18
GPIO.setup(pin_button, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# allow the camera t... | true |
f88625e0fb77d5fc2684bf9a6eccfc574a2c3ac6 | Python | Lich2013/leetcode | /Reorganize String.py | UTF-8 | 808 | 3.078125 | 3 | [] | no_license | class Solution:
def reorganizeString(self, S: str) -> str:
if len(S) == 0:
return ''
letterCount = [0]*26
for x in S:
letterCount[ord(x)-97] += 1
if max(letterCount)*2 > len(S)+1:
return ''
cur = letterCount.index(max(letterCount))
... | true |
6153f79f91c40164683321b62db00deb207d5bc2 | Python | nailanawshaba/Tyler | /homeControllerClient.py | UTF-8 | 748 | 2.890625 | 3 | [] | no_license | #!/usr/bin/python
import urllib
import urllib2
import json
class HomeControllerClient:
switchList = dict()
def __init__(self, serverIP):
self.serverAddress = "http://" + serverIP + ":5000/"
def getSwitches(self):
req = urllib2.Request(self.serverAddress + "wemo/list")
resp = urllib2.urlopen(req)
response... | true |
0a8c352cb2c225a77d8f52b4dabef02d4955b313 | Python | sarahappleby/cgm | /absorption/ml_project/train_spectra/tpot_forest_lines.py | UTF-8 | 3,199 | 2.578125 | 3 | [] | no_license | ### Routine to apply the sklearn randomm forest to the line by line absorption data
import h5py
import numpy as np
import pandas as pd
import pickle
import sys
from tpot import TPOTRegressor
from sklearn import preprocessing
from sklearn.metrics import r2_score, explained_variance_score, mean_squared_log_error, mean... | true |
a2ab3c1a60f6e9fd84769b5fb221921b49a78977 | Python | Shaheen-Ebrahimi/COMHAND | /control.py | UTF-8 | 822 | 2.890625 | 3 | [] | no_license | def openTab():
'''Opens tab when whole hand visible'''
import webbrowser
import speech
print('Open')
website = speech.listen().strip().split(' ')
url = ''
if(('Google' in website[0] or 'google' in website[0]) and len(website)>1):
url += 'https://www.google.com/search?q='
... | true |
06e7515013ef77e4f7fe383a63e3e2bbb1ac43ac | Python | jzhoucliqr/kube-auto-label | /quick-and-dirty/feature.py | UTF-8 | 332 | 2.75 | 3 | [] | no_license | #!/bin/env python
import json
with open('./data.json') as f:
content = f.readlines()
xf = open('./x.txt', 'w')
yf = open('./y.txt', 'w')
for c in content:
j = json.loads(c)
print j
print>>xf, (j['Title'] + j['Body']).encode('utf-8').replace("\r\n", " ").replace("\n", " ")
print>>yf, ",".join(j['L... | true |
39feada77ce902b3257baff30d3c29dae8467841 | Python | sassyfire/abe487 | /problems/grph/grph.py.save | UTF-8 | 1,186 | 2.78125 | 3 | [] | no_license | #!/usr/bin/env python3
import os
import sys
from Bio import SeqIO
from collections import defaultdict
args = sys.argv[1:]
if len(args) != 1:
print('Usage: {} FILE'.format(os.path.basename(sys.argv[0])))
sys.exit(1)
file = args[0]
if not os.path.isfile(file):
print('"{}" is not a file'.format(file))
... | true |
574ad8b0844bdecf95481a086d78d7988e9bf464 | Python | kaiwensun/leetcode | /0001-0500/0085.Maximal Rectangle.2.py | UTF-8 | 1,487 | 3.015625 | 3 | [] | no_license | class Solution:
def maximalRectangle(self, matrix: List[List[str]]) -> int:
if not matrix:
return 0
n = len(matrix[0])
data = [[0, float('inf'), float('inf')] for _ in range(n)] # [[heights, left_arms, right_arms], ...]
res = 0
for row in matrix:
row =... | true |
0ea32ef3c2cd7d89c6af8e16826f1e7bc62b3ff5 | Python | BowenNCSU/lecture-notes | /project/spring2018.py | UTF-8 | 3,070 | 3.8125 | 4 | [] | no_license | """
This assignement will walk you through gathering data for various
econmic indexes and calculating the correlation between them
using the daily returns.
The Federal Reserve Bank of St. Louis (FRED) makes various economic data
available for research: https://fred.stlouisfed.org/
Data from the site can be downloaded... | true |
81d6bfae9de4177de983df305415e0bd7af23b9f | Python | kut-info-ase-2019/raspberry-pi-g05 | /ultrasonic.py | UTF-8 | 3,111 | 3.640625 | 4 | [] | no_license | import RPi.GPIO as GPIO
import time
def pulse_in(pin, value=GPIO.HIGH, timeout=1.0):
"""
ピンに入力されるパルスを検出します。
valueをHIGHに指定した場合、pulse_in関数は入力がHIGHに変わると同時に時間の計測を始め、
またLOWに戻るまでの時間(つまりパルスの長さ)をマイクロ秒単位(*1)で返します。
タイムアウトを指定した場合は、その時間を超えた時点で0を返します。
*1 pythonの場合はtimeパッケージの仕様により実装依存ですが、概ねnanosecで返ると思います。
... | true |
e52107f26a037b6e88aaf45b72247702ef6d0cbd | Python | Kinddle-tick/ML_Bayesian_prediction | /Myfunc.py | UTF-8 | 26,080 | 2.8125 | 3 | [] | no_license | import pyqtgraph as pg
import pandas as pd
import numpy as np
from pyqtgraph.Qt import QtCore, QtGui
from collections import Counter
import time
from sklearn.cluster import Birch
from scipy import stats
from matplotlib import pyplot as plt
'''
在该目录下可以编写和注册自己的函数,根据GUI的特点,函数有以下约束:
1.函数的第一个参数必须是点的np.array类型数据
2.函数可以有三个可以在... | true |
7b09b67222673e345cc238d41b82ffb99d28d2fa | Python | LoboAnimae/FinalProyect_Graficas | /pygame_functions.py | UTF-8 | 343 | 2.859375 | 3 | [] | no_license | from pygame.display import set_mode
from pygame.time import Clock
import pygame
def initPygame(height: int = 800, width: int = 600)->object:
try:
pygame.init()
screen = set_mode((height, width), pygame.OPENGL | pygame.DOUBLEBUF)
clock = Clock()
except Exception as e:
print(e)
return None, None... | true |
f55f278ad24b34fd4d1adfad6f3e0ce15c47ad1b | Python | SalmaQueen/Flask-Rest-Api-Prototype | /app/models.py | UTF-8 | 3,038 | 2.75 | 3 | [
"MIT"
] | permissive | from werkzeug.security import check_password_hash, generate_password_hash
from app.extensions import db
class Book(db.Model):
__tablename__ = 'books'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
price = db.Column(db.Float, nullable=False)
isbn = db.C... | true |
c7fcb233e2802e7d06555778579304786394869d | Python | manon2012/python | /work/Do/testlist.py | UTF-8 | 236 | 3.4375 | 3 | [] | no_license | a=[1,9,0,2] # out [0,1,2,9]
# a.sort()
newa=[]
for i in range(len(a)):
newa.append(min(a))
# a.pop(a.index(min(a)))
a.remove(min(a))
print (newa)
# print (a)
#a.reverse()
# print (a)
#
# b=list(reversed(a))
# print (b)
| true |
0ed2867ab70461fb542167f3fce0197d3630fe51 | Python | NathanRuprecht/CS210_IntroToProgramming | /DailyLabs/Lsn35/SharedData.py | UTF-8 | 1,985 | 4.03125 | 4 | [] | no_license | # CS 210 - Introduction to Programming - Fall 2014
#
# Author: Maj. Caswell, Dr. Bower
#
# Documentation Statement: None.
#
from threading import Thread
""" This file contains a example of the difficult
of sharing data between threads.
"""
from threading import Thread
MAX = 1000000
def main():... | true |
54d569aec0383ac4bd76f5c5d7e933fea52b5feb | Python | AdamZhouSE/pythonHomework | /Code/CodeRecords/2795/60683/235052.py | UTF-8 | 283 | 3.15625 | 3 | [] | no_license | n = eval(input())
nums = [int(x) for x in input().split()]
sole = []
for i in range(n):
if nums[i] not in sole:
sole.append(nums[i])
if len(sole) == 1:
print(sole[0])
elif len(sole) == 2:
print(abs(sole[0] - sole[1]))
else:
print((max(sole) - min(sole)) // 2) | true |
82997202bfe503456e518dff541e2983088d3b87 | Python | kangfend/bahasa | /bahasa/stemmer/disambiguator/prefixes/rule_40.py | UTF-8 | 854 | 3.078125 | 3 | [
"MIT"
] | permissive | import re
class Rule40a(object):
"""Disambiguate Prefix Rule 40a (CC infix rules)
Rule 40a : CinV -> CinV
"""
def disambiguate(self, word):
"""Disambiguate Prefix Rule 40a (CC infix rules)
Rule 40a : CinV -> CinV
"""
matches = re.match(r'^([bcdfghjklmnpqrstvwxyz])(in[a... | true |
c16423c837e1041a93334ec04c4c938ab2cdec30 | Python | MatellioLiyaquet/hackathonML | /hackathon-backend/plot3.py | UTF-8 | 730 | 2.765625 | 3 | [] | no_license | import pandas
import numpy as np
import base64 as base64
import matplotlib.pyplot as plt
Tweet= pandas.read_csv("tmp/csv/Tweets.csv")
import matplotlib.pyplot as plt
Mood_count=Tweet['sentiments'].value_counts()
labels = 'negative','neutral','positive'
sizes = Mood_count
explode = (0, 0, 0.1)
fig1, ax1 = plt.subplots... | true |
58ee7aca55f93be663c240e6ab1bbc2b7eaa0df3 | Python | wnstlr/ligo | /IMR_PN_plot.py | UTF-8 | 5,995 | 2.875 | 3 | [] | no_license | #!/opt/local/bin/python2.6
'''Plots the Amplitude against frequency plot for Post-Newtonian Approach and
Inspiral Merger Ringdown Template.'''
import numpy
import scipy
from matplotlib import *
import pylab
def generatePSD(f):
'''This function calculates the Power Spectral Density using the fitted
curve eq... | true |
b1d2fc0461bcce656ba690203d19d3c687b18919 | Python | pacellyjcax/ProgrammingChallenge | /URI/1536 - Libertadores.py | UTF-8 | 584 | 3.28125 | 3 | [] | no_license | def saldoDeGols(l1,l2):
return (int(l1[0])+int(l2[2])) - (int(l1[2])+int(l2[0]))
def golsNoAdversario(l1,l2):
if l1[2] > l2[2]:
return "Time 2"
elif l1[2] < l2[2]:
return "Time 1"
return "Penaltis"
res = []
n = int(raw_input())
for i in range(n):
p1 = [x for x in raw_input().spli... | true |
cccea2f04929a0b39cbe261fb6d2db4ef3a96e86 | Python | natebrunelle/cs1110f18 | /markdown/files/cs1111_19fa/clicking_example.py | UTF-8 | 399 | 2.90625 | 3 | [] | no_license | import pygame
import gamebox
camera = gamebox.Camera(800,600)
logo = gamebox.from_image(-100, -100, "https://www.python.org/static/img/python-logo.png")
score = 0
def tick(keys):
if pygame.K_UP in keys:
print(" the up key is currently being pressed")
if camera.mouseclick:
logo.center = camera... | true |
c0954bf2e49b0bc90fa9b1928457ecb0d4f2e2d8 | Python | philipgreat/pla-article-classify | /parse-dict.py | UTF-8 | 477 | 2.9375 | 3 | [] | no_license | # encoding=utf-8
import jieba
import jieba.analyse
import math
'''
从文件中得到向量
'''
def dict_from_file(file_path):
dict = {}
number = 1
with open(file_path,'r') as inf:
for line in inf:
print str(number)+": "+line+" "
(key, val) = line.strip().split(' ')
#dict.appe... | true |
98f2245d845e3ccfce96c00053c698ce216597d2 | Python | abeltomvarghese/Data-Analysis | /Learning/basics.py | UTF-8 | 972 | 3.421875 | 3 | [] | no_license | import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import style
import numpy as np
style.use('ggplot')
web_stats = {'Day': [1,2,3,4,5,6],
'Visitors': [43,53,34,45,64,34],
'Bounce_Rate': [65,72,62,64,54,66]}
df = pd.DataFrame(web_stats)
##print(df) #printing the entire datafr... | true |
ed66db1627fdf79be3c0b61b5d0b3dd49ebd2ff3 | Python | oguncan/YMGK | /YMGK.py | UTF-8 | 14,241 | 2.53125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 7 16:15:30 2020
@author: Ogün Can KAYA
"""
import joblib
import numpy as np
import pandas as pd
import math
import matplotlib.pyplot as plt
import seaborn as sns
import datetime
# from sklearn.preprocessing import Imputer
import seaborn as seabornInstance
... | true |
d373581a481069828b5266d051b7afebe01a073c | Python | ace964/Azubot | /Control/azubot_gpio.py | UTF-8 | 4,300 | 3 | 3 | [
"MIT"
] | permissive | from IPin import IPin
from IServo import IServo
from IPwm import IPwm
from IAzubot import IAzubot
import time
from pygame import mixer # Load sound library
import pigpio
# Initialize connection to local pigpio server
pi=pigpio.pi(port=8888)
# Create Custom Error for hardware interaction
class AccessError(Exception):
... | true |
6755ae8afa96314d1472795f24dca0809804b830 | Python | bekhnam/Telco-Churn-app | /churn-app.py | UTF-8 | 3,462 | 2.59375 | 3 | [] | no_license | from numpy.lib.npyio import load
import streamlit as st
import pandas as pd
import numpy as np
import pickle
import base64
import seaborn as sns
import matplotlib.pyplot as plt
st.write("""
# Churn Prediction App
Customer churn is defined as the loss of customers after a certain period of time. Companies are
... | true |
53702c266817a8e3fd52bb9f69b8c19f881f5107 | Python | vrillusions/jeelink-receiver | /util/garage_door_status.py | UTF-8 | 5,133 | 2.796875 | 3 | [
"Unlicense"
] | permissive | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Python Template.
Environment Variables
LOGLEVEL: overrides the level specified here. Choices are debug, info,
warning, error, and critical. Default is warning.
"""
from __future__ import (division, absolute_import, print_function,
u... | true |
e3b6b6a5e7c87f176656a47ad39279a1e1e950fb | Python | boisgera/audio.frames | /audio/frames.py | UTF-8 | 6,686 | 3.375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
# coding: utf-8
"""
Audio Frames Toolkit
"""
# Python Standard Library
from __future__ import division
import doctest
# Third-Party Libraries
import numpy as np
#
# Metadata
# ------------------------------------------------------------------------------
#
__main__ = (__name__ == "__main__")
f... | true |
6baaa05b9681f1538f99bb1ae9fd200a1e576c60 | Python | whiteydoublee/Python | /Test1/1_8.py | UTF-8 | 309 | 3.40625 | 3 | [] | no_license | """
날짜: 2021/08/12
이름: 김예은
내용: 파이썬 최대값 최소값 연습문제
"""
scores=[62,82,76,88,54,92]
max = scores[0]
min = scores[0]
for score in scores:
if max< score:
max = score
if min > score:
min = score
print('최대값: ',max)
print('최소값: ',min) | true |
e773cb9261811accaa7af537bd883d4c2162f963 | Python | Jekwulum/Hackerrank | /nested_lists.py | UTF-8 | 543 | 3.390625 | 3 | [] | no_license | n = int(input())
def get_2nd_lowest(args):
val= sorted(set(args))[1]
return val
def nested_list(n):
if n not in range(2, 6):
return
my_list = []
for _ in range(n):
name = input()
score = float(input())
new_list = [name, score]
my_list.append(new_list)
... | true |
a0c3373a1fd9ae209bf5a0bdaf5dc5392e4b7906 | Python | fs-akjha/Hacker_Rank_Practises | /HackerRank_Solutions_Python/program37.py | UTF-8 | 186 | 2.75 | 3 | [] | no_license | import numpy
n = int(input())
a = numpy.array([input().split() for _ in range(n)], int)
b = numpy.array([input().split() for _ in range(n)], int)
result=numpy.dot(a, b)
print(result) | true |
695fb8e01353cf4be916471a1193232e195e8763 | Python | tmg1991/Python | /Batch_rename/test.py | UTF-8 | 1,364 | 3.21875 | 3 | [
"MIT"
] | permissive | print('$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$')
print('Üdvözöllek az egyszerû számológépben! Ver. 1.0')
print('$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$')
print(
'Help:... | true |
62dd690a9c5ad89c3b9bf0b2888a39e273fc421d | Python | rockym93/hotleaf | /hotleaf.py | UTF-8 | 4,992 | 2.953125 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python3
import os
import markdown
import sandwich
import datetime
import json
from operator import itemgetter
class Leaf(dict):
def __format__(self, formatstring):
return formatstring.format(**self)
def __missing__(self, key):
return ''
def navsetup(self, pot):
'''Adds navigational helper clas... | true |
d4d5874a893027c398cb9f06ee9e562b80e8653a | Python | hazrmard/Agents | /src/agents/agent/gpi/offpolicy.py | UTF-8 | 3,319 | 3.28125 | 3 | [] | no_license | """
Contains off-policy temporal difference agents:
* Q-Learning
* TD(lambda)
* N-step Tree Backup
"""
import numpy as np
from ...helpers.schedule import Schedule
from ...algorithm import q, nsteptd
from .agent import Agent, GREEDY
class QAgent(Agent):
"""
Implements Q-Learning: Off-policy temporal differ... | true |
e570af4aedec5812c8cc5b68b40f3c7f837531a0 | Python | chanjulee/Algorithm | /프로그래머스_해시/해시.py | UTF-8 | 2,478 | 4.46875 | 4 | [] | no_license | #딕셔너리 만들기,추가,삭제,사용
def dictionary():
#key 값이 중복되면 하나빼고 무시됨
#key 값은 리스트 못 씀
dic = dict() #빈 딕셔너리
dic = {'name':'Hong', 'phone':'12345678', 'birth':'1218'}
#딕셔너리 쌍 추가하기
dic['e-mail'] = ['123@gmail','456@naver']
#딕셔너리 요소 삭제하기
del dic['birth']
#딕셔너리에서 key 사용해 value 얻기
print(dic['n... | true |
3991a3f9dca1c327e745909d2e55cf836d40ca7a | Python | lightningmonkey/dino | /main.py | UTF-8 | 7,482 | 3.375 | 3 | [] | no_license | from import_all import *
from sets import Set
from player import Player
from background import Background
from scenery import GenericScenery, SceneryTests
from animals import AnimalsTests, GenericAnimal
from text import Eating, GenericText
# from map import Map, MapTests
class MainLoop(object):
""" The... | true |
45bebb130937111547bec7e0503cc12f5b1805a9 | Python | ibigio/deep-learning-final | /project/cheating_assignment.py | UTF-8 | 9,316 | 2.65625 | 3 | [] | no_license | import pyspiel
from pylab import *
import numpy as np
import tensorflow as tf
from cheating_model import ReinforceWithBaseline
from liars_dice_gym import LiarsDiceEnv
from safe_naive_agent import SafeNaiveAgent
from random_agent import RandomAgent
def visualize_data(total_rewards):
"""
Takes in array of rew... | true |
7ea26915922db448688853a399632baf1ad40c52 | Python | gyoforit/study-algorithm | /programmers/위클리_복서정렬하기.py | UTF-8 | 576 | 2.765625 | 3 | [] | no_license | def solution(weights, head2head):
answer = []
L = len(weights)
for i in range(L):
records = head2head[i]
weight = weights[i]
total_fights = records.count('W') + records.count('L')
winrate = 0 if not total_fights else records.count('W') / total_fights
wincnt = 0
... | true |
9a1e3e1d53a9ad3f74a6b1fa375396ed149ba7c7 | Python | HRG-Lab/UGR_2017-2018 | /jfreking/CV_for_NI/colorDetect.py | UTF-8 | 4,449 | 2.6875 | 3 | [] | no_license | import numpy as np
import cv2
from socket import *
import socket
import os
import sys
import pandas as pd
import netifaces as ni
# Get codewords from Excel file
codebook = pd.read_excel('/home/jfreking/Desktop/1920_codewords_azimuth_only.xlsx',header=0)
txCodes = codebook['TX Codewords']
#print txCodes
# Get IP addr... | true |
039685f0084173435e3dd6ef08848e5c3400d00b | Python | huaxr/Pyweby | /Pyweby/handle/template.py | UTF-8 | 9,649 | 2.59375 | 3 | [] | no_license | #coding: utf-8
import re
import types
import os
class BaseEngine(object):
WHATEVER = 0
_template_cache = {}
re_variable = re.compile(r'\{\{ .*? \}\}')
re_comment = re.compile(r'\{# .*? #\}')
re_tag = re.compile(r'\{% .*? %\}')
re_extends = re.compile(r'\{% extends (?P<name>.*?) %\}')
re_bl... | true |
3ee10985a43ca3ac4a7508188edb197db41c240f | Python | techadddict/Python-programmingRG | /Reading text files/reading textfiles4.py | UTF-8 | 547 | 3.78125 | 4 | [] | no_license | #Write a program that asks the user for a file name and prints the number of characters, words and lines in
#that file
filename = input('Please enter a filename to open')
#filename ='lyricso.txt' #use filename of your choice
file =open (filename ,'r')
lines=file.readlines()
lettersCount=0
wordsCount= 0
for line in li... | true |
e007bf7ea86170e80429d453313a65075d79bbb1 | Python | ebcarty/grapl | /src/aws-provision/swarm/configure_docker_daemon.py | UTF-8 | 1,067 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | import json
import os
import shlex
import subprocess
import sys
from typing import Dict
def _merge_daemon_config(config_update: Dict) -> Dict:
"""merge the given configuration update with the existing
configuration in /etc/docker/daemon.json
"""
config = {}
if os.path.exists("/etc/docker/daemon.j... | true |
0f6021b763ee190b8c74249c936baab0e811d42f | Python | OTRF/OSSEM | /resources/scripts/xlsx_to_yaml.py | UTF-8 | 3,856 | 2.9375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python3
# Project: OSSEM Data Dictionaries
# Author: Jose Rodriguez (@Cyb3rPandaH)
# License: GPLv3
# Importing libraries
import yaml
yaml.Dumper.ignore_aliases = lambda *args : True
import glob
import os
from os import path
import openpyxl
# Creating a list with ms excel files' names in your curren... | true |
56509f67d43ffa04911bd137ddc93252fce9595d | Python | pyaephyokyaw15/PythonFreeCourse | /chapter3/eq_comparison.py | UTF-8 | 331 | 3.59375 | 4 | [] | no_license | print("True ==1 ", True == 1)
print("False ==0 ", False == 0)
print("'False' ==0 ", 'True' == 1)
lst1 = [1,2,3]
lst2 = ["1",2,3]
tp1 = (1,2,3)
tp2 = (1,2,3)
print("lst1 == lst2 ",lst1 == lst2)
print("lst1 == tp1 ",lst1 == tp1)
print("tp1 == tp2 ",tp1 == tp2)
set1 = {1,2,3}
set2 = {1,2,3}
print("Set 1 == set2 ",s... | true |
cc0996556412b5cdd69185bc74797640802779bd | Python | ChandlerBang/Simple-SearchEngine | /spider.py | UTF-8 | 4,458 | 2.875 | 3 | [] | no_license | from lxml import html
import os
import requests
from bs4 import BeautifulSoup
seed_url = u"http://shakespeare.mit.edu/"
file_folder = 'The Complete Works of William Shakespeare/'
<<<<<<< HEAD
# this part of code is beyond the range of this course
=======
# this part of code is beyond the range of our class
>>>>>>> 3f... | true |
a4387882d0765e961c70ae2456c4f6b6e6463004 | Python | nikita-sunyata/codeforces | /466A/466A.py | UTF-8 | 618 | 3.375 | 3 | [] | no_license | while True :
try:
data=input()
n,m,a,b = [int(i) for i in data.split()]
#check if same
if b == m * a:
print( n * a )
else:
normal = n*a
special_part1 = (n//m)*b
if (n%m) * a <= b:
special_part2 = (n%m)*a
... | true |
5a56740f18af53da753a63b03e22c2efc943faa8 | Python | Andrey0563/Kolocvium | /№ 58.py | UTF-8 | 624 | 4.1875 | 4 | [] | no_license | '''
№58
Дан одновимірний масив цілих чисел. Знайдіть, скільки разів в ньому
повторюється найчастіше число.
Дужак Андрій 122-Г
'''
import random
a = []
for i in range(20):
a.append(random.randint(-30, 30))
b = 0
for i in range(len(a)): # Знаходження елементу який повторюється найчастіше
c = 0
for j in ra... | true |
3df952d7f2830d9939b308a9d5fb69891386a379 | Python | bumpo/bot-scripts | /fleck.py | UTF-8 | 240 | 3.21875 | 3 | [] | no_license | #!/usr/bin/env python
import sys
message = " ".join(sys.argv[1:])
message = message.replace("fuck", "fleck")
message = message.replace("FUCK", "FLECK")
new_message = "Excuse me, I think you meant: {0}".format(message)
print(new_message)
| true |
2beac2eb30c0f0997dd3b2af1eec4809bed1f4a3 | Python | shivendra036/python-programs | /ex38.py | UTF-8 | 562 | 3.515625 | 4 | [] | no_license | ten_things= "Apple Oranges Crows Telephone Light Sugar"
print "Wait there is not 10 things in that list,let's fix that."
stuff = ten_things.split(' ')
more_stuff = ["Days","Night","Songs","Frisbee","Corn","Banana","Girl","boy"]
while len(stuff) != 10:
next_one = more_stuff.pop()
print "adding:",next_one
... | true |
e90a667d2f87fe69ec6235058c77d92fc38d077e | Python | mike10004/subprocess-java | /src/main/site/render_readme.py | UTF-8 | 3,316 | 2.96875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python3
"""
Program that produces the README file for the repository.
This program reads a source file in the Jinja2 template syntax and
interpolates variables defined with `--define` as well as code snippets
demarcated by `README_SNIPPET theSnippetName` in source code files.
This ensures that content... | true |
477e3217d3c7289b2cc5250f2b9d1bc0342a159c | Python | regreg/regreg | /regreg/problems/tests/test_newton.py | UTF-8 | 1,595 | 2.75 | 3 | [
"BSD-2-Clause"
] | permissive | import numpy as np
from ...atoms.seminorms import l1norm
from ...smooth.glm import glm
from ..newton import quasi_newton
from ..simple import simple_problem
def test_lagrange():
n, p, s = 1000, 50, 5
X = np.random.standard_normal((n, p))
beta = np.zeros(p)
beta[:s] = 20 * np.random.standard_normal(s)... | true |
ea6ea84829b5b2a29f65dfe9c2bc030deb96a65f | Python | nguyepe2/class_courses | /CS160 Computer Science Orientation/lab8.py | UTF-8 | 1,304 | 3.796875 | 4 | [] | no_license | import random
def main():
num=random.randint(1,20)
attempts=[]
# for i in range(5):
i=0
while i < 5:
guess=input("Guess a number 1-20: ")
if guess==str(num):
# if guess==str(num):
print(str(guess)+" is the right number")
break
elif guess in attempts:
# elif list(attempts)==guess:
print("You've alre... | true |
d92533cb97ed5d94bcc8b94ab2bbf5fcd7a9c88c | Python | teaduwow/Tutorial | /CLASS/4.number.py | UTF-8 | 429 | 4.09375 | 4 | [] | no_license | #如何只用數字 數字的用法
print(8+5)
print(8*5)
#整數除法
print(8//5)
print((8+8)*5)
number = -8
#取於數
print(number%5)
#字串
print("會印出數字"+str(number))
#取絕對值
print(abs(number))
#次方
print(pow(2,5))
print(max(2,100,88,3))
print(min(1,10,-10,100))
#4捨5入
print(round(99/7))
from math import *
#無條件捨去
print(floor(5.1))
#無條件進位
print(ceil... | true |
d3cb021c52475deeba3e3dcd0aa2280f86514903 | Python | KannanVS/Password_Changer | /index.py | UTF-8 | 2,477 | 3.015625 | 3 | [] | no_license | from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import getpass
import json
import time
def main():
f = open("details.JSON", "r")
data = json.load(f)
# Fetch... | true |
4511000b869532d0e12492521c1ec6b718bd48dc | Python | bellettif/hawkes_processes | /RNG_test/main.py | UTF-8 | 817 | 3.046875 | 3 | [] | no_license | '''
Created on 3 nov. 2013
This script computes an histogram of the values simulated
by the mt19937 pseudo random generator.
@author: francois belletti
'''
from matplotlib import pyplot as plt
from datetime import datetime
import rng
import time
# Test of the Mersenne-Twister mt19937
n_sims = 1000000
start_time = ... | true |
0a67ee707f4a73d7a967828b2c12be288ecc93c3 | Python | mattvenn/atbristol-megadrawbz | /tests/reflecto-homing/encoder/test.py | UTF-8 | 505 | 2.859375 | 3 | [] | no_license | import serial
import struct
import time
port_name = '/dev/ttyACM1'
print("opening port " + port_name)
enc_port=serial.Serial()
enc_port.port=port_name
enc_port.timeout=1
enc_port.baudrate=115200
enc_port.open()
time.sleep(2)
def send(pos, port):
bin = struct.pack('<h',pos)
port.write(bin)
# will block wh... | true |
eb7254892a72122092bcad724b5e8c52b12b9363 | Python | seangao14/clairvoyance | /clairvoyance/champ_utils.py | UTF-8 | 1,566 | 2.65625 | 3 | [] | no_license | import pandas as pd
import json
# rid = riot id for the champion
# maps riot id to index
def idx_from_rid():
with open('clairvoyance/data/champions.json', encoding='utf-8') as f:
champs = json.load(f)
df = pd.DataFrame.from_dict(champs['data'], orient='index')
names = df['key']
names = pd.Se... | true |
fd168b64360143a7c8d7d797e04350c684010180 | Python | Thewessen/hello-world | /Exercism/python/armstrong-numbers/armstrong_numbers.py | UTF-8 | 173 | 3.578125 | 4 | [
"MIT"
] | permissive | def is_armstrong_number(number: int) -> bool:
"""Checks if a number is an Armstrong number."""
n = str(number)
return sum(int(d) ** len(n) for d in n) == number
| true |
6d02747d720c2acdf884552f1799aafb6b017642 | Python | TrendingTechnology/pyrustic | /pyrustic/widget/scrollbox.py | UTF-8 | 11,453 | 3.03125 | 3 | [
"MIT",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | import tkinter as tk
from pyrustic import widget
from pyrustic.tkmisc import get_cnf
from pyrustic.view import View
# Components
CANVAS = "canvas"
BOX = "box"
HSB = "hsb"
VSB = "vsb"
# Orient
BOTH = "both"
VERTICAL = "vertical"
HORIZONTAL = "horizontal"
class Scrollbox(widget.Frame):
"""
Scrollbox is a scr... | true |
cb79010677f1e01ec09051be63055bbf918016b0 | Python | svetakeda/project_oop_1 | /book.py | UTF-8 | 700 | 3.5625 | 4 | [] | no_license | class Book:
def __init__(self, name, year, author, cost):
self.__name = name
self.__year = year
self.__author = author
self.__cost = cost
@property
def name(self):
return self.__name
@property
def year(self):
return self.__year
@property
def... | true |
66dd140a57094f9f2d4fd11d671ee2f34b4c5657 | Python | iacsstudent/quizgame | /quizgame.py | UTF-8 | 536 | 3.265625 | 3 | [] | no_license | import math
import random
# This is my quiz game
# I'm going to put my test functions and stuff in here
def get_addition_question (level):
addend1 = random.randint(1,10*level)
addend2 = random.randint(1,10*level)
return '%i+%i'%(addend1,addend2),addend1+addend2
def test_get_addition_question ():
for... | true |