blob_id large_string | repo_name large_string | path large_string | src_encoding large_string | length_bytes int64 | score float64 | int_score int64 | detected_licenses large list | license_type large_string | text string | download_success bool |
|---|---|---|---|---|---|---|---|---|---|---|
fee05745a887b2d86b53c487b81b9a05cbe32f0b | alexmjn/Intro-Python-II | /src/player.py | UTF-8 | 955 | 4.125 | 4 | [] | no_license | # Write a class to hold player information, e.g. what room they are in
# currently.
from room import Room
class Player():
# pass an object of class Room to the class constructor
def __init__(self, name, room, inventory=[]):
self.name = name
self.room = room
self.inventory = inventory
d... | true |
069fd810b106f707b134c2c666596d76bc16efba | x038xx38/contur_bot | /function.py | UTF-8 | 870 | 3.171875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import csv
import logging
import codecs
def write_csv(fn, data, encode='utf-8'):
path = 'db/' + fn
with codecs.open(path, 'w', encoding=encode) as csvFile:
writef = csv.writer(csvFile, delimiter=';')
for row in data:
writef.writerow(row)
logging.info('Фа... | true |
65f1f21df4046b918ed03fc4de6db409b48a173b | TR1GUN/SeleniumBot | /InstagramBot_new_account_registration.py | UTF-8 | 14,560 | 3.078125 | 3 | [] | no_license | # Давайте попытаемся сделать новый аккаунт инстаграмма
from selenium import webdriver
import time
import random
from selenium.webdriver.common.keys import Keys
import sqlite3
import datetime
import string
import secrets
# Функция нашего драйвера - запуск самого драйвера
def SMS_bomber_WebDriver():
dr... | true |
a6da056373abbe3be412ea845c0286f8b82a9415 | mariomech/mosaic-aca_aflux_data_processing | /radar/scripts/utils/artifacts/mirac_snr_filter.py | UTF-8 | 1,284 | 2.53125 | 3 | [] | no_license | #!/usr/bin/python
"""Remove signal weaker than a certain threshold. Sub-module to mirac.py.
Authors
-------
[see parent module]
History
-------
2018-11-21 (AA)
Exported from parent module
[earlier] [see parent module]
"""
# standard modules
from copy import deepcopy as ... | true |
f80ec5e4e1da689ede8b0bd7760943a31eff282e | shtalinberg/django-el-pagination | /el_pagination/paginators.py | UTF-8 | 4,896 | 3.234375 | 3 | [
"MIT"
] | permissive | """Customized Django paginators."""
from math import ceil
from django.core.paginator import EmptyPage, Page, PageNotAnInteger, Paginator
class CustomPage(Page):
"""Handle different number of items on the first page."""
def start_index(self):
"""Return the 1-based index of the first item on this pag... | true |
ea7da25535f2f938ffab762198d9ba8fc37a747e | GaganNamburi/CMPS130-Scientific-Programming-in-Python | /Midterm/Program1.py | UTF-8 | 532 | 4.0625 | 4 | [] | no_license | def LCM(num1, num2):
#Same number means LCM already found
if num1 == num2:
return num1
#Bigger number
if num1 > num2:
multi = num1
else:
multi = num2
#Bigger number iterates until there is a number that has no remainder for both
while(True):
if multi % num1 == 0 and multi % num2 == 0:
return multi
... | true |
cf385a4ae327915e548bce3851fc499f1ed79b62 | AgentOxygen/csc3323_coe332 | /homework01/generate_animals.py | UTF-8 | 1,460 | 3.5625 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
COE 322 Homework 01
@author: Cameron Cummins
"""
import json
import petname as pn
import random as rand
def genAnimal() -> dict:
"""
Generates and returns a dictionary to describe a mutant animal.
"""
animal = {}
heads = ["snake", "bull", "lion", "r... | true |
c2ca910a1f030d35e87fc71c01913893211d67ab | coder562/python | /15-exercise 2.py | UTF-8 | 325 | 4.3125 | 4 | [] | no_license | #ask user name and print back user name in reverse order
# note-try to make your program in 2 lines using string formatting
# name = input("enter your name:")
# reverse = name[-1::-1]
# print(f"rverse of your name is {reverse}")
#short method
name = input("enter your name:")
print(f"reverse of your name is {name[-1::-... | true |
5625b0d8652c18d95a45ecfa289576f1c375dfcb | Learning-Python-Team/Data-Analysis-Project | /mock_api_gen.py | UTF-8 | 2,069 | 3.109375 | 3 | [
"MIT"
] | permissive | import json
import requests
"""Python script to make a mockaroo api-call using schema from either .json or list of dicts. Writes mock data to a .json file and/or returns a list of dicts.
The function is modular, so you can remove specific if/elif/else statements to reduce code lines depending on your needs.
Limited ... | true |
ba6bae8cb39ef3a4bc9ab4208c68050f061ad82f | loganyu/leetcode | /problems/645_set_mismatch.py | UTF-8 | 1,063 | 3.46875 | 3 | [] | no_license | '''
You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number.
You are given an integer array nums representing the data... | true |
22cbedb5b13df5153c3cb5dd7331feddb70d3416 | clutonik/pylearn | /algorithms/recursion/flattened_array.py | UTF-8 | 323 | 3.78125 | 4 | [] | no_license | #!python3
# Accept array of arrays and return a flattend array
def flatten(arr):
resultArr = []
for i in arr:
if type(i) is list:
resultArr.extend(flatten(i))
else:
resultArr.append(i)
return resultArr
if __name__ == '__main__':
print(flatten([1, 2, 3, [4, 5]]... | true |
70d9cea4c9b8ea73260f031fd6d7969cc43cf307 | zhang-jx-nan/Python | /rpsls_template.py | GB18030 | 2,918 | 3.734375 | 4 | [] | no_license | #coding:gbk
"""
RPSLSϷ
ߣŽ
2019 11 14
"""
import random#randomģ
answer=random.randint(0,4)#randint0-4֮
print("ѡ")
name=input()
def name_to_num(name):#ַתΪ
if name=="ʯͷ":
return 0
elif name=="ʷ":
return 1
elif name=="":
return 2
elif name=="":
return 3
elif name=="":
return 4
else:
... | true |
19005ee2bc3add8308a6ee72407ee8070e38db1f | justinhsg/AoC2020 | /src/day14/solution.py | UTF-8 | 1,942 | 2.78125 | 3 | [
"MIT"
] | permissive | import sys
import os
import re
day_number = sys.path[0].split('\\')[-1]
if len(sys.argv)==1:
path_to_source = os.path.join("\\".join(sys.path[0].split("\\")[:-2]), f"input\\{day_number}")
else:
path_to_source = os.path.join("\\".join(sys.path[0].split("\\")[:-2]), f"sample\\{day_number}")
with open(path_to_sour... | true |
a570d33db04402e79da160225ecd50022fe1eb8c | nivransh2008/python-programme1 | /intro.py | UTF-8 | 276 | 3.96875 | 4 | [] | no_license | intro = input("Tell me about your self ")
charcount = 0
wordcount = 1
for i in intro:
charcount+=1
if(i==" "):
wordcount+=1
print("number of words in the string"+ str(wordcount))
print("number of characters in the string"+ str(charcount))
| true |
d27172233f8f44eb9b59504537ea32101c81348e | bsb00004/Python-Project-13-Investigating-Fandango-Movie-Ratings | /Movie_Ratings.py | UTF-8 | 8,354 | 3.671875 | 4 | [] | no_license | #!/usr/bin/env python
# coding: utf-8
#### Python Project 13 - Investigating Fandango Movie Ratings
# Reading in and explore briefly the two data sets:
# - fandango_score_comparison.csv :data he analyzed publicly available- (https://github.com/fivethirtyeight/data/tree/master/fandango).
# - movie_ratings_16_17.csv: d... | true |
a361e49b76d2789782fd413b7a095d41a03c29f7 | guigui64/advent-of-code | /2015/03b.py | UTF-8 | 706 | 3.515625 | 4 | [] | no_license | #!/usr/bin/python
f = open("03.txt", "r")
robotsturn = False
x = 0
y = 0
robotx = 0
roboty = 0
positions = [[0,0]]
for c in f.read():
if robotsturn:
if c == '>': robotx = robotx + 1
elif c == '<': robotx = robotx - 1
elif c == 'v': roboty = roboty - 1
elif c == '^': roboty = rob... | true |
e831d707f230ea8f9899bbb555f7e38e658ae8c9 | 5l1v3r1/otokuna | /svc/tests/test_scrape_property_data.py | UTF-8 | 1,347 | 2.5625 | 3 | [
"BSD-3-Clause"
] | permissive | import io
import os
from pathlib import Path
import boto3
import pandas as pd
from moto import mock_s3
import scrape_property_data
DATA_DIR = Path(__file__).parent / "data"
@mock_s3
def test_main(set_environ):
output_bucket = os.environ["OUTPUT_BUCKET"]
timestamp = 1611586765.0
raw_data_key = "dumped_d... | true |
d2432073bd89a715afcded8244e1c984d11a91db | smoulinos/Homework | /Chapter9.py | UTF-8 | 151 | 3.28125 | 3 | [] | no_license | def tuple((a,b), (c,d)):
if (a*c) + (b*d) > 20:
return "greater than 20"
else:
return "less than 20"
print(tuple[(1,4),(3,5)]) | true |
a3becd16042b82b45a016d02d8a7cea6bf75df48 | toni-li/spotify-recos | /app/process_data.py | UTF-8 | 3,034 | 2.59375 | 3 | [] | no_license | # resources
# https://developer.spotify.com/console/get-playlists/
# https://developer.spotify.com/console/get-playlist-tracks/
# https://developer.spotify.com/console/get-track/
def process(user_id, song, token):
import requests
import sys
import spotipy
import spotipy.util as util
# scope = 'pla... | true |
8345c184a491f0f1be891eacb85eaade1bd0d9cb | uscmakers/mqtt-tutorial | /simple_sub.py | UTF-8 | 925 | 2.828125 | 3 | [] | no_license | # import the necessary libraries
import paho.mqtt.client as mqtt
import time
# when we connect to the mqtt broker, subscribe to my topic
def connect_fn(client, userdata, flags, rc):
client.subscribe("MQTT_Simple/topic")
# specify what to do when messages are received on this topic
client.message_ca... | true |
ec7f2c925362d8424ff9f5a0d3c69e34df81bff9 | LukasPowalla/Space_Physics_Project_Sigve_Lukas | /sigve/ace/ace.py | UTF-8 | 1,198 | 2.78125 | 3 | [] | no_license | from numpy import *
import matplotlib.pyplot as p
import datetime
#filename = eval(raw_input('star('star#.txt'): ))
filename = 'acedata.txt'
def read_data(): # Function, gathering data from the
file = open(filename,'r') # files and returning them as arrays, for computing
Bz= [];
for line in file: # ... | true |
d498c570f77f0c4b5df28f7c2d672c8e32dc1ddd | katlakristin/Algorithms-and-git | /sequence.py | UTF-8 | 525 | 4.3125 | 4 | [] | no_license | # Creating a sequence, each number is the sum of the last three numbers
n = int(input("Enter the length of the sequence: "))
# We need to define the first three digits in the sequence
a = 1
b = 2
c = 3
print(a,b,c,end=" ")
# The first three are defined so we need to adjust the range
for _ in range(1,n-2):
# Next d... | true |
3db8ba806ba9b9851a9dd04a0a2c7a977be2a196 | scitao/advanced_lane | /frame_process.py | UTF-8 | 11,805 | 2.59375 | 3 | [] | no_license | #!usr/bin/python
'''
author: Shanglin Yang (kudoysl@gmail.com)
This script implements whole pipeline on one image
'''
import glob
import utils
import sys
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.lines as lines
import pickle
from scipy.misc impo... | true |
2c4d800101e357e69d9cef16a2515d68be95262d | fadhiladiahap/fadhiladiahap-Fadhila-Diah-Ayu-Pratiwi_I0320038_Andhika_Tugas9 | /I0320038_Exercise 9.10.py | UTF-8 | 182 | 3.09375 | 3 | [] | no_license | import array
# nilai awal (sebelum dibalik)
A = array.array('i', [100,-700,300,400,800])
print(A)
# membalik urutan elemen array
A.reverse()
#nilai akhir (setelah dibalik)
print(A)
| true |
29df3e90def1a723bccce9cbe674c2593fba99a7 | hulaba/Rice-Yield-Prediction-API | /validation.py | UTF-8 | 906 | 2.6875 | 3 | [] | no_license | import json
import pandas as pd
import urllib.request as urllib
import os
def get_df(link):
fp = urllib.urlopen(link)
return pd.read_csv(fp)
def get_previous_data(dst, tp):
link = os.environ['final_key']
print(link)
df = get_df(link)
df = df[(df['st'] == dst) & (df['rtype'] == tp)]
df = df[df['yr'] < 20... | true |
bc9e3ef54117ace1de74a8964e73e513606196df | Devanrio/myschoolproject | /URI/1043.py | UTF-8 | 429 | 3.625 | 4 | [] | no_license | A, B, C = input().split()
A = float(A)
B = float(B)
C = float(C)
if A > B and A > C and (B + C) > A:
S = A + B + C
print("Perimetro = %.1f"% S)
elif C > A and C > B and (A + B) > C:
S = A + B + C
print("Perimetro = %.1f"% S)
elif B > A and B > C and (A + C) > B:
S = A + B + C
print("Perimetro = %.1f"% S)
elif A ... | true |
e3edf200c92dfe0f0edc5d55666b4cd776a65454 | mzhao98/POMDPy-Declutter | /examples/object_declutter/rock_observation.py | UTF-8 | 1,486 | 2.875 | 3 | [
"MIT"
] | permissive | from __future__ import print_function
from builtins import str
from pomdpy.discrete_pomdp import DiscreteObservation
BLUE = 1
RED = 2
color_to_text = {BLUE: "blue", RED: "red"}
class HumanActionObservation(DiscreteObservation):
"""
Default behavior is for the rock observation to say that the rock is empty
... | true |
83f85f666185e141f746f11979c9238c5f257e6a | ariqrafikusumah/Tugas | /Chapter 2/D4 TI C/Yusuf Jordan(1184026)/src/if.py | UTF-8 | 200 | 2.921875 | 3 | [
"MIT"
] | permissive | npm = input ("Masukan NPM Anda: ")
if npm != "":
print("NPM Terisi")
if npm == "1184026":
print("Kamu Jojo")
else:
print("Apakah Kamu Hacker?")
else:
print("Masak Lupa Sama NPM sendiri")
| true |
2ab1c982472c64ce27d6c9a6ad7c7d4bfbd176aa | reporter-law/book_code | /keras深度学习/第五章视觉学习/小数据_预训练提取特征.py | UTF-8 | 6,982 | 2.515625 | 3 | [] | no_license | """程序说明"""
# -*- coding: utf-8 -*-
# Author: cao wang
# Datetime : 2020
# software: PyCharm
# 收获:
import os, shutil
os.environ["KERAS_BACKEND"] = "plaidml.keras.backend"
"""预训练进行特征提取"""
"""数据预处理"""
def data_preprocessing():
# 原始数据集路径
original_dataset_dir = r'J:\PyCharm项目\学习进行中\keras深度学习\data\train\train'
... | true |
c712875273f988a3aa6dab61f79e99a077823060 | danomatika/ofxLua | /scripts/lua_syntax.py | UTF-8 | 4,065 | 2.765625 | 3 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | #! /usr/bin/python
#
# convert the swig -debug-lsymbols output text file format into
# a simple list of lua module names and classes
#
# Dan Wilcox <danomatika@gmail.com> 2017
#
import sys
import re
if len(sys.argv) < 2:
print("USAGE: lua_syntax.py MODULENAME INFILE")
exit(0)
module = sys.argv[1]
infile = sys... | true |
fe2c4ecfeb0b0ca59dead1b12df92ce7d48b0f5c | ArgyZz/AI-Reversi-Ver2-With-Graphics- | /Reversi/main.py | UTF-8 | 20,379 | 3.09375 | 3 | [] | no_license | # Koutsompinas Giorgos 3150251
# Velaoras Apostolos 3180249
# Kaldis Argyrios 3160045
import sys
import time
import math
import random
import pip._internal as pip
def install(package):
pip.main(['install', package])
if __name__ == '__main__':
m = ''
while(m!='Y' and m!='N'):
pri... | true |
6b361cd617945698b028dd6726464ca0cd221033 | MamadTvl/Bank-Multi-Threading | /src/customer.py | UTF-8 | 704 | 2.953125 | 3 | [] | no_license | from datetime import datetime
from account import Account
class Customer:
def __init__(self, unique_id, cash, name, accounts, services):
self.id = unique_id
self.cash = cash
self.name = name
self.accounts = accounts
self.services = services
def add_service(self, servi... | true |
f9ddc8e878f5d1b6003d5f9d2287dd3b5b64e407 | ozerelkerem/Project-Eular-Solutions | /python/problem22.py | UTF-8 | 942 | 4.21875 | 4 | [] | no_license | print("""
Names scores
Problem 22
https://projecteuler.net/project/resources/p022_names.txt
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply ... | true |
c1d3828911736f83d467e105f0f8c804f9a60bbd | or1426/Clifford-T-estimator | /qk.py | UTF-8 | 3,352 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | import qiskit
from qiskit import QuantumCircuit
from qiskit.providers.aer import QasmSimulator
from qiskit import Aer
from gates import cliffords
import time
import numpy as np
class QiskitSimulator(object):
"""
Use Qiskit's stabilizer simulator to run one of our circuits
"""
def __init__(self):
... | true |
5a322abf4e63da21d7ccea32a01a3509af17ca77 | dcrawford027/semi_RESTful_tv_shows | /main_app/models.py | UTF-8 | 1,382 | 2.515625 | 3 | [] | no_license | from django.db import models
from datetime import *
# Create your models here.
class ShowManager(models.Manager):
def showValidator(self, postData):
error = {}
if len(postData['title']) < 2:
error['title'] = "You must include a title at least 2 characters long."
show = Show.obje... | true |
55e7482519286573ad7c4cecc70a58fbde52d4ab | jakkrits/Misc | /Stats/Python/linear_regression.py | UTF-8 | 949 | 3.078125 | 3 | [] | no_license | """ Linear Regression Analysis - HW#1 - JakkritS """
#%%
import statsmodels.api as StatModel
## import datasets from sckit-learn
from sklearn import datasets, linear_model
import numpy
import pandas
## loads Boston dataset from datasets library
data = datasets.load_boston()
# print(data.feature_names)
# print(data.... | true |
d7bb10159afd8491d7ac645320d573c8dec72ae6 | DesmondSL/Algorithms | /Leetcode/1.py | UTF-8 | 364 | 2.8125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dictnum = {}
for i in range(len(nums)):
if target-nums[i] in dictnum:
return [dictnum[target-n... | true |
0103141c7bc6ead30a749913b2e225880999cbf6 | gkrry2723/AI_with_python | /해커톤/mask_shopping.py | UTF-8 | 977 | 2.625 | 3 | [] | no_license | import os
import sys
import requests
import pprint
client_id = "zJKSgg5Whn0Iz1NJZXLb"
client_secret = "kZK1w3EsN6"
encText = "마스크"
url = "https://openapi.naver.com/v1/search/shop.json?query=" + encText + "&display=50&sort=asc"
header_params = {"X-Naver-Client-Id":client_id,'X-Naver-Client-Secret': clie... | true |
f0fc4a263879e54e13eaea2cbe8402369cce4a9d | JasonWei512/Tacotron-2-Chinese | /tacotron/utils/plot.py | UTF-8 | 2,204 | 2.921875 | 3 | [
"MIT"
] | permissive | import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
def split_title_line(title_text, max_words=5):
"""
A function that splits any string based on specific character
(returning it with the string), with maximum number of words on it
"""
seq = title_text.split()
return '\n'... | true |
d6bf33b4506e99517e976087c08366dd54039e6b | answer3xz2016/music_cnn | /MuseUtil/museUtility.py | UTF-8 | 2,796 | 2.875 | 3 | [] | no_license |
import ConfigParser
import numpy as np
def getDatabaseKey(dbcred_file):
conf = ConfigParser.ConfigParser()
conf.read(dbcred_file)
host = conf.get('database_creds','host')
port = conf.get('database_creds','port')
user = conf.get('database_creds','user')
database = conf.get('database_creds','da... | true |
1fcc3d7c2ac12731805a7502c98b8b4fd4f56f48 | fox016/projectEuler | /euler76.py | UTF-8 | 169 | 3.203125 | 3 | [] | no_license | values = xrange(1, 100)
target = 100
table = [1] + [0] * target
for value in values:
for i in xrange(value, target+1):
table[i] += table[i-value]
print table[target]
| true |
ac2469705aefc1d8a7fbcd6a931af57e984ec57a | abhishek0647/Anaconda-Backup | /pdfParser.py | UTF-8 | 526 | 2.703125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 17 00:03:19 2016
@author: abhishek
"""
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
# Open a PDF document.
fp = open('/Users/abhishek/Downloads/Table of Schedule for sales 11.03.2016.pdf', 'rb')
parser = PDFParser(fp)
document = ... | true |
a612538492b3a76332a7f89d2a0780c3869cb5b4 | YcheCourseProject/OJCodes | /qlcoder/data_mining/timeline/timeline_gen.py | UTF-8 | 611 | 2.71875 | 3 | [
"MIT"
] | permissive | import random
import string
import sys
if __name__ == '__main__':
if sys.version_info[0] == 3:
print ("Welcome to qlcoder!")
print ("We find your Python version is python3.X")
print ("But this script needs to be executed with Python2.X\n")
exit()
random.seed(10)
limit = 100... | true |
441a6ee84fc2cf52940faacfd0d66dc5fcc2182d | jsoni2/document-manipulation | /chapter13/docs/write.py | UTF-8 | 274 | 2.75 | 3 | [] | no_license | import docx
doc = docx.Document()
doc.add_paragraph('Hello world!', 'Title')
paraObj1 = doc.add_paragraph('second para')
paraObj2 = doc.add_paragraph('another para')
paraObj1.add_run(' This text is being added to the second paragraph.')
doc.save('multipleParagraphs.docx') | true |
073a47058c93dfa594a16bea9b840b3fcc4d9ec8 | CirXe0N/WebCrawler-Code-Challenge | /crawler/parsers.py | UTF-8 | 446 | 3.203125 | 3 | [
"MIT"
] | permissive | from html.parser import HTMLParser
from typing import NamedTuple
class HTMLLinkParser(HTMLParser):
def __init__(self):
super().__init__()
self.hrefs = []
def handle_starttag(self, tag: str, attrs: NamedTuple) -> None:
"""
Filter out the <a> tags and add the href value to the h... | true |
c0b57db38c4b0e49699147e6180f1491afa53fcb | boada/wmh | /fix_ccJSON.py | UTF-8 | 1,250 | 2.5625 | 3 | [
"MIT"
] | permissive | import pandas as pd
import sys
def fix(lists):
df = pd.read_json(lists)
df2 = pd.DataFrame([p for p1 in df.players for p in p1])
df2['theme1'] = ''
df2['theme2'] = ''
for i, l in df2.list2.iteritems():
try:
df2.theme2.iloc[i] = l['theme']
except KeyError:
c... | true |
2440d11b0efd7bac04d0af69fad62967f0df0ee5 | LakshBhambhani/Swiffee-Minikame-Simulator | /Server/quad.py | UTF-8 | 5,633 | 2.953125 | 3 | [
"MIT"
] | permissive | import RPi.GPIO as GPIO
import serial
from flask import Flask, render_template, request
app = Flask(__name__)
ser = serial.Serial("/dev/ttyUSB0", 9600)
GPIO.setmode(GPIO.BCM)
ser.flushInput()
# Create a dictionary called pins to store the pin number, name, and pin state:
pins = {
1 : {'name' : 'Port', 'state' : G... | true |
94d8c0ae680d08ccda2030295ac9ec9fa6e4b8b1 | dr-dos-ok/kaggle-higgs-boson | /DelaunayDensityEstimator.py | UTF-8 | 6,910 | 2.921875 | 3 | [] | no_license | import numpy as np
from scipy.spatial import Delaunay
import cPickle as pickle
import math, os
SAVE_DIR = "ddes/"
IMG_SAVE_DIR = "dde_imgs/"
def default_name(columns, num_rows):
return "%s|%s" % (
"|".join(columns),
num_rows
)
def default_save_name(columns, num_rows):
return SAVE_DIR + default_name(columns, n... | true |
b0a62f3471f7008db6e7e902be7fc1fd50f92508 | ClaudeHuang/GitLearn | /python/while_loop.py | UTF-8 | 350 | 4.03125 | 4 | [] | no_license | number = 23
running = True
while running:
guess = int(input('enter an integer : '))
if guess == number:
print('congratulations you guess it!')
running = False
elif guess < number:
print('no it is a little higher than you input')
else:
print('no it is a little lower than you input')
else:
print('the while... | true |
fa21e07fcc7d64368e51fd3697aefb3bedee7947 | MrGraves1986/Link-Locker | /solo_app/models.py | UTF-8 | 1,615 | 2.640625 | 3 | [] | no_license | from django.db import models
import re
class UserManager(models.Manager):
def validator(self, postdata):
email_check=re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
errors = {}
if len(postdata['first_name']) < 2:
errors['first_name']="First name must be at least 2 ... | true |
1b103ae4ed8ba575a22c6131343ba6c82ceb2773 | pcunhasilva/PythonCourse2017 | /Homeworks/HW1/hw1_answers.py | UTF-8 | 8,782 | 3.84375 | 4 | [] | no_license | from abc import ABCMeta, abstractmethod
from random import uniform, seed
class Portfolio():
"""A client's portfolio of a financial institution.
Attributes:
cash: A float representing the total of cash available.
stock: A dictionary representing each type of stocks.
The first ele... | true |
270677a1e2d3a9cc173f1ae2576e3d42eed7bc55 | min24/PythonCourseraHSE_duy171 | /week1_all/1.22_failed.py | UTF-8 | 164 | 3.234375 | 3 | [] | no_license | # Симметричное число *
n = 2015
x = str(n) == str(n)[::-1]
import random
y = random.randrange(0, 9999)
print(1*x + y*(1-x))
# Not working
| true |
39cc04ebc542569010d8e9f42e67235739d1eeb5 | plaidman/advent | /2022-py/03/part1.py | UTF-8 | 598 | 3.625 | 4 | [] | no_license | def value(char):
if char.isupper():
return ord(char) - 38
else:
return ord(char) - 96
input = []
with open("input.txt", "r") as file:
line = file.readline()
while line:
input.append(line.strip())
line = file.readline()
sum = 0
letter = ''
for line in input:
length =... | true |
2afe715d55b1d8bc3f9e4501f8c7bf408f48bce3 | iamjagan/Reflection-Refraction-less-Ronpa-Raytracing-Renderer | /anim_script/GLSLJinja.py | UTF-8 | 4,358 | 2.53125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | from jinja2 import Environment, FunctionLoader, ChoiceLoader, FileSystemLoader
from itertools import chain
from collections import OrderedDict
class TemplateError(Exception):
def __init__(self, message):
self.message = message
class _TemplateFunc:
def __init__(self, *params):
self.id... | true |
ca073c28b27bd65e1d30457efa5ce89ea71fa726 | gilgameshzzz/learn | /day4-循环和分支/03-for循环.py | UTF-8 | 1,685 | 4.65625 | 5 | [] | no_license | # 需要重复执行某个过程,就可以使用循环。
# Python中的循环有For循环和while循环
#1、for循环:
"""
for 变量名 in 序列:
循环体
for: 关键字
变量名:和声明变量时的变量名要求是一样的,功能是存储值
in :关键字 ,在。。。里的意思
序列:容器类型的数据。字符串、列表、字典、元组、集合等
循环体:需要重复执行的代码块
执行过程:使用变量去序列中取数据,一个一个的取,取完为止,每取一个值,执行一次体。
"""
for char in 'abc123':
print(char)
# 2、range函数
"""
xrange是Python2.x中的函数,在Python3.x使用ra... | true |
cdf457925268ed459125bf4b96731160fe55df63 | w40141/atcoder | /abc_227/a.py | UTF-8 | 101 | 2.90625 | 3 | [] | no_license | n, k, a = map(int, input().split())
k += a - 1
m = k % n
if m == 0:
print(n)
else:
print(m)
| true |
22d9788c6fee1428f48f388e2711495383bcbeac | M-110/learning-python-complexity | /complexity/game_of_life/cell_2d.py | UTF-8 | 2,833 | 3.6875 | 4 | [] | no_license | """Cell2D is meant as a base class which can be subclassed and allow
subclasses the functionality of things like saving the plot as an animated gif."""
from abc import abstractmethod
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
class Cell2D:
"""Implementation of a 2D CA.
... | true |
23252bae9a47f56c03a880b2f384055db9111d80 | avasquez-80/Opencv_Python | /custom_detection.py | UTF-8 | 2,071 | 2.859375 | 3 | [] | no_license | import cv2
######################################################
path = '/home/alejandro/Proyectos/ProyectosNuevos/Python/practicas/opencv/practicas/haar_cascade/data/haarcascade_smile.xml' #path of the cascade
camera_no = 0 #Camera number
object_name = 'face' #Object name to display
frame_width = 640 ... | true |
b2e935e639e4d49d0c9f29f2c3d55bf9ce90df72 | Cbkhare/Codes | /Pattern_match.py | UTF-8 | 579 | 2.84375 | 3 | [] | no_license | from Abstract_Data_Types import kmp_failure
def pattern_index(p, t):
n, m = len(t), len(p)
Kmp = kmp_failure.Kmp_failure(p)
pattern = Kmp.compute_kmp()
j, k = 0, 0
while j < n:
if p[k] == t[j]:
if k == m-1: #match is complte
return j - m+1
j += 1
... | true |
242a9dee6e37d615e04c94c50f9bb084e3e346d9 | ClaireShi28/MachineLearning | /Assignment1/Code/DecisionTree.py | UTF-8 | 3,186 | 2.765625 | 3 | [] | no_license | import numpy as np
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.tree import DecisionTreeClassifier
import LoadData
import Experiments
import time
from sklearn.metrics import plot_confusion_mat... | true |
d989e237a5c6ecc0e212d1cd0c526f875f76a20b | pollution-game-theory/PollutionModel | /taxman.py | UTF-8 | 1,020 | 2.84375 | 3 | [] | no_license | class Taxman:
def __init__(self, interventionThreshold = 10000, interventionIntensity=2, interventionFrequency=2, interventionLength= 8, thresholdIncreaseRate = 10000, reset = False):
self.interventionThreshold = interventionThreshold #pollution level that initiates intervention
self.interventionInt... | true |
9084778ca22fde2976c226ac09a1be8f8aabaa33 | sagarchaugule44/image_process | /source/image_process/background_remove.py | UTF-8 | 3,970 | 2.71875 | 3 | [] | no_license | import os
import subprocess
import cv2
import numpy as np
from matplotlib import pyplot as plt
temp_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'temp')
BLUR = 21
CANNY_THRESH_1 = 10
CANNY_THRESH_2 = 200
MASK_DILATE_ITER = 10
MASK_ERODE_ITER = 10
MASK_COLOR = (0.0,0.0,1.0) # In BGR format
class Ba... | true |
46d9dd48a564be91abe3f1a714cd6fb8b72797b5 | SabiulSabit/Pattern-Lab-CSI-416-A | /Nur Mahabub Morshedur Rahman/Assignment 3/RF Kmer 2.py | UTF-8 | 5,266 | 2.765625 | 3 | [] | no_license | import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import KFold
from sklearn.model_selection import train_test_split
pos_5289 = "C:/Users/Nur Rafi/Documents/Data Sets/Pattern Laboratory/Assignment 2/positive 5289/Kmer 2.npy"
ne... | true |
b25f32250a053b8c01fd02b61ec2aa4833e092ea | techkang/dip | /histogram.py | UTF-8 | 1,287 | 2.953125 | 3 | [] | no_license | # -*- encoding:utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
for index in range(4):
img = Image.open('Figure/'+str(index+1)+'.tif') # 500*500
arr = np.array(img)
new_arr = arr.copy()
counts = np.zeros(256)
s = np.zeros(256, dtype=np.uint8)
for i in range(le... | true |
7c363ba08ebea3e4db70ff975562b8329abcd32a | ritwik95/Project-Euler | /tre.py | UTF-8 | 688 | 3.265625 | 3 | [] | no_license | import itertools
abc=list(map("".join, itertools.permutations('0123456789')))
print len(abc)
import itertools
abc=list(map("".join, itertools.permutations('0123456789')))
lst=[]
a=0
while a<len(abc):
b=list(abc[a])
c=int(''.join(b[1:4]))
if (c%2==0):
continue
d=int(''.join(b[2:5]))
if (d%3==0):
c... | true |
fade51e05b25019b66d86369a48c5faf5fdb423e | meganzg/Competition-Answers | /CodeWars2018 - Competition/prob17.py3 | UTF-8 | 650 | 2.75 | 3 | [] | no_license | from collections import deque
vactrains = dict(A=[], B=[], C=[])
pending = deque()
nsent = 0
while True:
cmd = input()
if cmd == "DONE":
break
cmd, *values = cmd.split()
if cmd == "RECV":
print("RECVED", values)
pending.append(values)
elif cmd == "LOAD":
val = pend... | true |
a4f4ac5726b93d1de8da2fa9e6cf8e378bfd8b9f | pjyi2147/ccc | /2013_jr/j3_copy.py | UTF-8 | 360 | 2.9375 | 3 | [] | no_license | #ccc 2013 j3 copy answer
def Solution():
def distinct(year):
s = str(year)
for digit in s:
if s.count(digit) > 1:
return False
return True
y = int(input())
y += 1
while not distinct(y):
y += 1
print(y)
... | true |
2697504e3bfabbe61a0eb647ff10dfdc4e37653c | QFinUWA/2021-Momentum-Trading-Nicks-Team | /breakout_lib.py | UTF-8 | 1,342 | 3.140625 | 3 | [] | no_license | def return_support(asset_history, ticks):
"""
Input:
asset_history historical price movement of asset
ticks integer number of ticks
Output:
support_level price at which a SELL recommendation is issued
i.e. lowest price of as... | true |
81f25d17e4f0cd11872469ec55eb67f98de85667 | klq/whiteboarding2016 | /largest_prime_factor_Euler3.py | UTF-8 | 581 | 3.828125 | 4 | [] | no_license | # 1-24-2016
# Euler #3 https://projecteuler.net/problem=3
'''
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
See if you can optimize your solution. What is the complexity of your program?
'''
import time
def euler3():
n = 600851475143
i = 2
w... | true |
9e09f117b4cc271f21537569e4f65a13dc146bf6 | sachinlohith/leetcode | /Arrays/gameOfLife.py | UTF-8 | 2,448 | 3.984375 | 4 | [] | no_license | """
https://leetcode.com/problems/game-of-life/discuss/
According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."
Given a board with m by n cells, each cell has an initial state live (1) or dead (0). E... | true |
30a23fe7bed6213c482d21fdf6b74393b5d9d960 | zhangweichen2006/MICA | /instrument/generat_train.py | UTF-8 | 742 | 2.71875 | 3 | [] | no_license | from utils import Generator
''' Absolute path to the raw audios '''
PIANO_PATH_MP3 = '../raw_data/mp3/piano/'
PIANO_PATH_WAV = '../raw_data/wav/piano/'
DHOL_PATH_MP3 = '../raw_data/mp3/dhol/'
DHOL_PATH_WAV = '../raw_data/wav/dhol/'
VIOLIN_PATH_MP3 = '../raw_data/mp3/violin/'
VIOLIN_PATH_WAV = '../raw_data/wav/violi... | true |
d698af32438820b8ceeef44284d4c7b6de8a1dee | zhang-sgin/python_code | /day02-数据类型/test.py | UTF-8 | 4,739 | 3.96875 | 4 | [] | no_license | '''
1. 用户先给自己的账户充钱:比如先充3000元。
2. 页面显示 序号 + 商品名称 + 商品价格,如:
1 电脑 1999
2 鼠标 10
…
n 购物车结算
3. 用户输入选择的商品序号,然后打印商品名称及商品价格,并将此商品,添加到购物车,用户还可继续添加商品。
4. 如果用户输入的商品序号有误,则提示输入有误,并重新输入。
5. 用户输入n为购物车结算,依次显示用户购物车里面的商品,数量及单价,若充值的钱数不足,则让用户删除某商品,直至可以购买,若充值的钱数充足,则可以直接购买。
6. 用户输入Q或者q退出程序。
7. 退出程序之后,依次显示用户购买的商品,数量,单价,以及此次共消费多少钱,账户余额多少。
... | true |
7c1f40a790e42cc8def7b87e0cfeff33883fb87c | ahill2013/pythonamqp | /src/control/rc.py | UTF-8 | 2,915 | 2.8125 | 3 | [] | no_license | # try:
# import RPi.GPIO as GPIO
# except RuntimeError:
# print("Error importing RPi.GPIO! Are you superuser (root)?")
from threading import Thread
from amqp.amqplib import Protected
from time import sleep
from time import time
import pigpio
import read_PWM
class RemoteControl(Thread):
"""
Class wher... | true |
feaa3898f857d9fcd3316105ff1b7c719c21f129 | Wapiti08/DeepLog | /Deeplog_demo/loglizer/demo/PCA_demo_without_labels.py | UTF-8 | 6,488 | 2.859375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
# -*- coding: utf-8 -*-
''' This is a demo file for the PCA model.
API usage:
dataloader.load_HDFS(): load HDFS dataset
feature_extractor.fit_transform(): fit and transform features
feature_extractor.transform(): feature transform after fitting
model.fit(... | true |
e1a92810b363153d459f581ea58e25f1be5bf669 | clearfield-robotics-ros/jetson | /md/src/md_serial.py | UTF-8 | 3,296 | 2.59375 | 3 | [] | no_license | #!/usr/bin/env python
import serial
import sys
import datetime
import time
import rospy
from std_msgs.msg import Int16
start = time.time()
def hex_to_signed(source):
"""Convert a string hex value to a signed hexidecimal value.
This assumes that source is the proper length, and the sign bit
is the first... | true |
485190b73fa9c44f81e072314c8c29a21bbd875b | negromartin/Practica-Python | /practica python/practicaClases/ClaseLapiz.py | UTF-8 | 817 | 3.640625 | 4 | [] | no_license | class Lapiz: #Plantilla
#Metodos
def __init__(self,color,contieneBorrador,usaGrafito): # es el SET de toda clase.
self.color = color #Estos 3 son los atributos
self.contieneBorrador = contieneBorrador
self.usaGrafito = usaGrafito
def dibujar(self):#Variable self es la q va a tratar y devolver
pri... | true |
4ab079457f72e71d8efd2f03dfc6ddb4d7be43fa | marcelinorc/semantic-recovery | /tests/test_ARMControlFlowGraph.py | UTF-8 | 2,608 | 2.59375 | 3 | [] | no_license | import os
import unittest
from unittest import TestCase
from semantic_codec.architecture.disassembler_readers import TextDisassembleReader
from semantic_codec.static_analysis.cfg import ARMControlFlowGraph, CFGBlock
from libs.dot.dotio import write
class TestARMControlFlowGraph(TestCase):
ASM_PATH = os.path... | true |
978be482bcd5fa4f1226eababaa7b60b272e890f | Manoj431/Python | /Arrays/Solution_4.4.py | UTF-8 | 304 | 3.609375 | 4 | [] | no_license | import array
arr = array.array( 'i' , [45,62,23,80,12])
specific_number = 80
flag = False
for i in range(len(arr)):
if arr[i] == specific_number:
flag = True
print("Item is available in the array.")
if flag == False:
print("Item is NOT available in the array.")
| true |
672260d1a6dd1741d2383ed0a56635a45ce02335 | michaelbecker/log_stdin | /log_stdin.py | UTF-8 | 6,812 | 2.8125 | 3 | [
"MIT"
] | permissive | #!/usr/bin/python
#############################################################################
#
# This script allows you to capture stdin from a program and log it
# in an intelligent, configurable manner.
#
# MIT License
#
# Copyright (c) 2016, Michael Becker (michael.f.becker@gmail.com)
#
# Permission is hereby... | true |
b6fc237f6996114eda218578d778a114aaeaa1c9 | Luolingwei/LeetCode | /Heap/Q703_Kth Largest Element in a Stream.py | UTF-8 | 556 | 3.71875 | 4 | [] | no_license | from heapq import *
class KthLargest:
def __init__(self, k: int, nums):
heapify(nums)
self.large,self.small=nums,[]
self.k=k
def add(self, val: int):
heappush(self.small,-heappushpop(self.large,val))
while len(self.large)>self.k-1:
heappush(self.small,-heapp... | true |
34229200ffdf27be9b10ffd861a8d92a27daa89d | yashmakwana0702/lab | /heap.py | UTF-8 | 8,233 | 3.5 | 4 | [] | no_license | import time
import random
def heapify(arr, n, i):
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
if largest != i:
arr[i],arr[largest] = arr[largest],arr[i] # swap
heapi... | true |
ae25333fb680fafb936f33a91cf0b998e23c6602 | alqamahjsr/InterviewBit-1 | /02_Arrays/maximum_gap.py | UTF-8 | 1,916 | 3.859375 | 4 | [
"MIT"
] | permissive | # Maximum Consecutive Gap
# https://www.interviewbit.com/problems/maximum-consecutive-gap/
#
# Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
#
# Try to solve it in linear time/space.
#
# Example :
# Input : [1, 10, 5]
# Output : 5
#
# Return 0 if the array con... | true |
a1f9864821021629610ae1f3172abe2dbe530990 | rafacasa/OnlineJudgePythonCodes | /Iniciante/p1864.py | UTF-8 | 90 | 3.109375 | 3 | [] | no_license | cita = 'Life is not a problem to be solved'.upper()
qtd = int(input())
print(cita[:qtd])
| true |
9665814f8d1c6495bf8d81b805199fd119d765b9 | cmput401-fall2018/web-app-ci-cd-with-travis-ci-MichaelParadis | /test_service.py | UTF-8 | 949 | 3.15625 | 3 | [
"MIT"
] | permissive | from service import Service
from unittest import TestCase, mock
import pytest
class test_service(TestCase):
def test_divide(self):
service = Service()
service.bad_random = mock.Mock(return_value=42)
y = 3
assert service.divide(y) == 42 / y
y2 = -10
asser... | true |
ac9655d33a805832e1b03a7b47894f8c987457f3 | aarkwright/ableton_devices | /MIDI Remote Scripts/ableton/v2/control_surface/components/background.py | UTF-8 | 2,335 | 2.53125 | 3 | [
"MIT"
] | permissive | # uncompyle6 version 3.3.5
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)]
# Embedded file name: c:\Jenkins\live\output\win_64_static\Release\python-bundle\MIDI Remote Scripts\ableton\v2\control_surface\components\background.py
# Compiled at: 20... | true |
5adcb22b460230843ecaa9fbb0f72033807c9799 | scottidler/leatherman | /leatherman/friendly.py | UTF-8 | 933 | 2.890625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
human friendly functions
"""
import re
import datetime
WEEKS = "(?P<weeks>[0-9]+w)?"
DAYS = "(?P<days>[0-9]+d)?"
HOURS = "(?P<hours>[0-9]+h)?"
MINUTES = "(?P<minutes>[0-9]+m)?"
SECONDS = "(?P<seconds>[0-9]+s)?"
PARSE = re.compile(WEEKS + DAYS + HOURS + MINUTES + SEC... | true |
afd63d1cd0ee637911c4eba79e1ee6444decc06e | Air-df/office_worker_system | /sys_client/lib/snake.py | UTF-8 | 7,518 | 3.015625 | 3 | [] | no_license | #! /usr/bin/python3
# 线程
import threading,time,random,tkinter,traceback
class snake_game(tkinter.Toplevel):
def __init__(self, rows=20, columns=20,speed=0.2):
super().__init__()
# 行数
self.rows = rows
# 列数
self.columns = columns
# 游戏速度
self.speed = speed
... | true |
79c56150445cafc2eeea7f23cdadf7711a4de6e5 | ksh04023/algorithm-for-coding-test | /6-2.py | UTF-8 | 267 | 3.734375 | 4 | [] | no_license | #성적이 낮은 순서로 학생 출력하기
N = int(input())
data = []
for _ in range(N):
str = input().split()
data.append((str[0], int(str[1])))
data = sorted(data, key=lambda student: student[1])
for student in data:
print(student[0], end=' ')
| true |
0d57d06d5a4cd66865b469bf820f2fc7b8eb0f72 | tomasquinones/rwgps-battery-graph | /battery_graph.py | UTF-8 | 916 | 2.921875 | 3 | [] | no_license | #! Python3
#Graph battery usage over time for iPHone and Android logs.
import re, pyperclip
import plotly.express as px
dateRegex = re.compile(r'''(
(\d{4}-\d\d-\d\d)\s # date
(\d\d:\d\d:\d\d) # time
(.{2,100}) # log info
(Battery\slevel:|Battery:)\s? ... | true |
42979096e137012863dda22609329bffecc3361a | wancongji/python-learning | /lesson/11/作业3.py | UTF-8 | 348 | 3.28125 | 3 | [] | no_license | import random
s = 'abcdefghijklmnopqrstuvwxyz'
d = {}
lst = []
length = len(s)
for _ in range(100):
# randstr = ''.join(random.sample(s, 2))
lst.append(''.join(random.choice(s) for _ in range(2)))
for i in lst:
if i not in d.keys():
d[i] = 1
else:
d[i] += 1
d1 = sorted(d.items(),revers... | true |
a6b79b38de2800711cfee7b8ac3c039cb18080c6 | Vengalrao-eppa/rest_endpoint | /main_program.py | UTF-8 | 1,296 | 3.640625 | 4 | [] | no_license | from flask import Flask
from flask import jsonify
#Hardcoded list
numbers_to_add = list(range(10000001))
#Max size setting - could be omitted, but safer to have it
max_size = 10000001
# Static strings to be returned instead of a result, if a list length is bigger
# than max_size or if it contains anything other tha... | true |
676e408d5350d09dc797d10cefca4ca3e89f75f3 | matsu7874/contest_20190423 | /oyatsu/asano_AC_2/main.py | UTF-8 | 465 | 3.5 | 4 | [] | no_license | #!/usr/bin/env python3
# 枝刈りのない全探索
N,M = map(int, input().split())
a = []
for i in range(M):
a.append(int(input()))
a = sorted(a)
a.reverse()
def canPayExactly(n, i):
if n == 0:
return True
if i >= M:
return False
price = a[i]
for x in range(n // price + 1):
if canPayExac... | true |
70838454136d3d3ed29646b3b4efaad6106dd8ce | Bobby-Han/text-classification | /evaluator.py | UTF-8 | 6,545 | 2.640625 | 3 | [] | no_license | # -*- coding:utf-8 -*-
from __future__ import division
import numpy as np
import codecs
def sigmoid(X):
sig = [1.0 / float(1.0 + np.exp(-x)) for x in X]
return sig
def to_categorical_one_sample(cl, n_class):
y = np.zeros(n_class, dtype=np.int32)
for i in range(len(cl)):
y[cl[i]] = 1
retu... | true |
cd2707065b3114776f9c2210c8a40ac308212c3a | dimaqq/naive-asyncio-rwlock | /rwlock.py | UTF-8 | 2,306 | 3 | 3 | [
"MIT"
] | permissive | import asyncio
class RWLock:
def __init__(self):
self.cond = asyncio.Condition()
self.readers = 0
self.writer = False
async def lock(self, write=False):
async with self.cond:
while self.readers and write or self.writer:
await self.cond.wait()
... | true |
1d638ed883f658568cda613442b5d8c7707fc1d1 | zoomie/RNN_on_Dow_Jones_Index | /RNN.py | UTF-8 | 2,599 | 3.546875 | 4 | [] | no_license |
# Simple RNN
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_csv('dow_jones_index.csv')
# Removing the $
df['open'] = df['open'].map(lambda x: x.lstrip('$'))
# This model is only going to use opening price
training_set = df.iloc[:,3:4... | true |
45adcf641e0d34a9561d47e9dd57831709934ae7 | walkingpendulum/loan | /parsers.py | UTF-8 | 802 | 2.6875 | 3 | [] | no_license | import argparse
import yaml
import models
def arg_parser():
parser = argparse.ArgumentParser()
parser.add_argument('-c', dest='config_path', help='path to configuration file', required=True)
return parser
def parse_config(config_path):
with open(config_path) as f:
config = yaml.load(f, Lo... | true |
95a19024736341c559eb8da506fb457bd9575db8 | fung1018139/pythonExperiment | /重力加速度の解析/untitled2.py | UTF-8 | 486 | 3.078125 | 3 | [] | no_license | import pandas as pd
#import numpy as np
import matplotlib.pyplot as plt
df = pd.read_csv('/Users/fun1018139/Desktop/実験 2/10° おもり3.csv')
x=df['time']
y=df['radians']
z=df['acc']
fig, (axL, axR) = plt.subplots(ncols=2, figsize=(10,4))
axL.set_xlabel("time")
axL.set_ylabel("radians")
axL.scatter(x,y)
axR.set_xlabel("... | true |
59acdedc157f1f75f8b88346efd3fd9ac9e8ddc5 | ofisser86/test_python | /scraping_datawhatnow.py | UTF-8 | 496 | 3.6875 | 4 | [] | no_license | import requests
from lxml import html
url = 'https://www.datawhatnow.com'
def get_parsed_page(url):
"""Return the content of the website on the given url in
a parsed lxml format that is easy to query."""
response = requests.get(url)
parsed_page = html.fromstring(response.content)
ret... | true |
f8a921898a912dc108c4b1eee3fea4a6643b6bef | sebastianceloch/wd_io | /lab5/zadanie12.py | UTF-8 | 269 | 2.953125 | 3 | [] | no_license | def miesiace():
miesiac = ['Styczen','Luty','Marzec','Kwiecien','Maj','Czerwiec','Lipiec','Sierpien','Wrzesien','Pazdziernik','Listopad','Grudzien']
for x in range(0,12,1):
yield miesiac[x]
mies = miesiace()
for i in range(0,12,1):
print(next(mies)) | true |
a8e8e499c23bc270afdab594c5a8c46d701a73f0 | dataholic0/Algorithm_Test | /LeetCode/subarraySum.py | UTF-8 | 352 | 3.453125 | 3 | [] | no_license | from collections import deque
from itertools import combinations
def subarraySum(nums,k)->int:
"""
return the total number of continuous subarrays whose sum equals to k
"""
sum_list = [0]
answer = 0
for i in range(len(nums)):
sum_list.append(sum_list[-1]+nums[i])
print(sum_list)
nums = [1,... | true |