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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
02546d020a463a42a9cdc09e5b10ad1ffe826dba | Python | MingxingSu/MingxingLearnPython | /ClosureDemo.py | UTF-8 | 2,261 | 5.09375 | 5 | [] | no_license | """
Closure
A closure is a function where every free variable, everything except parameters,
used in that function is bound to a specific value defined in the enclosing scope of that function.
In effect, closures define the environment in which they run, and so can be called from anywhere.
The concepts of lambdas and... | true |
ab5870686141c41b5ba221aa2b6775475df7b187 | Python | ae-lexs/ABitly-Services | /abitly/services/link/controller.py | UTF-8 | 2,892 | 3.25 | 3 | [
"Apache-2.0"
] | permissive | """Define process functions to use in the Link Service"""
from werkzeug.exceptions import BadRequest, InternalServerError, NotFound
from shortuuid import ShortUUID
# DataBase
from abitly.db import db_session
# Models
from abitly.models import Link
def validate_request_body(body):
"""Validates the json format o... | true |
8fb81053366da370b9323e619fef43805661974c | Python | ZhangHarry/codeExercise | /src/Algorithm/leetcode/finished/MissingNumber.py | UTF-8 | 834 | 3.90625 | 4 | [] | no_license | # Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
#
# Example 1
# Input: [3,0,1]
# Output: 2
class Solution(object):
# beat 55%
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
... | true |
af0a6387517954aa230fbb9f9c2122043ab3ef2e | Python | zhoufosho/road-networks-project | /calInterest.py | UTF-8 | 763 | 2.953125 | 3 | [] | no_license | from snap import *
from scipy.spatial import distance
def printArray(args, f, toPrint):
f.write("\t".join(args))
if toPrint:
print "\t".join(args)
def writeMatrixToFile(f, toPrint=False):
for i in xrange(numNodes):
printArray([str(distanceMatrix[i][j]) for j in xrange(numNodes)], f, toPr... | true |
484e6bcf87beea9efbfc5ad1dba7504d9c5e4b0a | Python | Sonia133/Tehnici-Avansate-de-Programare | /Greedy/Varianta 3/Ex3.py | UTF-8 | 1,178 | 3.125 | 3 | [] | no_license | def readInput() :
n = int(input())
intervals = [None] * n
for i in range(n):
intervals[i] = [int(x) for x in input().split()]
return n, intervals
def getSol(n, intervals, sol):
count = 0
index = -1
maxF = -1
for x in intervals:
if sol[0][0] == -1:
... | true |
b5a1ef2ec87982fbe10dd7b636d47e1aa76bedb6 | Python | SoussouDhn/Matrix-Factorization-Recommandation-System-SVD | /data_preparation.py | UTF-8 | 2,293 | 3.03125 | 3 | [] | no_license | import numpy as np
import pandas as pd
# loading first table
bookmarks=pd.read_csv("/content/drive/My Drive/Colab Notebooks/bookmarks.csv")
bookmarks.time = 1 # we set this column to one, because we are gonna use it later in calculating interest
# loading second table
favorites=pd.read_csv("/content/drive/My ... | true |
a50600e5ebfd77bcf07b1f007da4d534bd73150f | Python | sahilpwr/Document-Information-Retrieval-System | /text classification.py | UTF-8 | 1,906 | 2.796875 | 3 | [] | no_license | from math import log
from math import sqrt
from collections import Counter
from operator import itemgetter
def idf(term, allDocuments):
numDocumentsWithThisTerm = 0
for cnt in allDocuments:
if term in cnt:
numDocumentsWithThisTerm = numDocumentsWithThisTerm + 1
if numDocumentsWithThisTe... | true |
da87cbd5a56af922f1e8cb4c03d626c23a597287 | Python | scikit-optimize/scikit-optimize.github.io | /dev/_downloads/d20503d0380fb778ad8116a8530b7f12/store-and-load-results.py | UTF-8 | 5,411 | 3.484375 | 3 | [] | permissive | """
===========================================
Store and load `skopt` optimization results
===========================================
Mikhail Pak, October 2016.
Reformatted by Holger Nahrstaedt 2020
.. currentmodule:: skopt
Problem statement
=================
We often want to store optimization results in a file.... | true |
3fde35c66932cfbebe69c1e29528e52fd5fb6060 | Python | Unleashedmen/Wiper | /wiper.py | UTF-8 | 3,553 | 3.53125 | 4 | [] | no_license | """
Wiper : Wipe your current directory's files in one go!
Author: @GaganGulyani
"""
from os import listdir, getcwd, remove
from os.path import isfile, join, realpath
from pickle import load, dump
from typing import Final
# CONFIG (CONSTANT VALUES)
CURRENT_DIR: Final = getcwd()
SELF_DESTRUCT: Final = False
CURRENT_SC... | true |
925e5fe0c5475bb0f2d1f0ac6020ca5774642c09 | Python | Aegarain/advent-of-code | /Python/2020/day_05.py | UTF-8 | 1,669 | 3.3125 | 3 | [] | no_license | input_file = open("day_05_example.txt")
input_text = input_file.read()
boarding_passes = input_text.split("\n")
boarding_passes.pop()
highest_ID = 0
def read(pass_text):
row = range(0,128)
column = range(0,8)
for x in range(8):
row_len = int(len(row))
mid = int(row_len/2)
char = pas... | true |
7d98c6ee971faeea0a760b149690cfc254a470f5 | Python | gaborpapp/AIam | /movement_ai/connectivity/avatar_osc_sender.py | UTF-8 | 2,299 | 2.609375 | 3 | [] | no_license | from connectivity.simple_osc_sender import OscSender
class AvatarOscSender:
def __init__(self, host, port):
self._host = host
self._port = port
self.reset()
def reset(self):
self._osc_sender = OscSender(self._host, self._port)
self._frame_index = 0
def get_status(s... | true |
56cc31e5311ee8bd23c0c48e0bec535d3b801613 | Python | PikachuPikachuHAHA/public_course_materials | /assignments/pypl/automarking/2/and.py | UTF-8 | 162 | 3.140625 | 3 | [] | no_license | #!/usr/bin/python3
x = 7
if x < 8 and x > 5: print("one")
if x < 8 and x > 7: print("two")
if x > 5 and x < 8: print("three")
if x > 9 and x < 8: print("four")
| true |
588fb9dcf214aa05ae1ca188998a7eb7ed79c17a | Python | sergio9977/SUMMER_BOOTCAMP_2018_Python | /lesson4/task6/dict_key_value.py | UTF-8 | 248 | 3.90625 | 4 | [] | no_license | """
Hay muchos métodos útiles en diccionarios como keys() y values()
"""
phone_book = {"John": 123, "Jane": 234, "Jerard": 345}
print(phone_book)
phone_book["Jill"] = 456
print(phone_book)
print(phone_book.keys())
print(phone_book.values())
| true |
8ebcc8e9faaf12987f4e0616b69a52ecd8331145 | Python | mlagtapon/number_game | /game_app/views.py | UTF-8 | 527 | 3.015625 | 3 | [] | no_license | from django.shortcuts import render, random
def index(request):
return render(request,'index.html')
def guessedNum(request):
num_from_form = request.POST[int('num')]
num = num_from_form
randomNum = random.randint(1, 100)
if randomNum == num:
print(num, " was the number!")
if randomNu... | true |
d18c2d2646f9e7dddd9c042e15ee5de4f1496bda | Python | Puquan/yolo_flask_vue | /train/core/utils/common.py | UTF-8 | 2,002 | 2.84375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
def decode_name(name_path):
with open(name_path, 'r') as f:
lines = f.readlines()
name = []
for line in lines:
line = line.strip()
if line:
name.append(line)
return name
def decode_annotation(anno_path, type='y_true'):
with open(anno_path... | true |
d598c83687a4367f3bf8845f06b0fb07345ee697 | Python | epolozyukov/PCore_Study | /11/11_Class+Home.py | UTF-8 | 924 | 4.46875 | 4 | [] | no_license | #1. Напишіть програму, яка пропонує користувачу ввести ціле число і визначає чи це число парне чи непарне, чи введені дані коректні.
num = int(input("PLease put the number: "))
def digit(num):
try:
if num%2 == 0 :
return "This is the even number"
return "this is the odd number"... | true |
c170c60b4aec86181550d4418021c2d03bb89e5b | Python | LiuFang816/SALSTM_py_data | /python/treigerm_WaterNet/WaterNet-master/waterNet/model.py | UTF-8 | 4,848 | 2.796875 | 3 | [] | no_license | """Implementation of the convolutional neural net."""
from keras.models import Sequential
from keras.layers import Dense, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.optimizers import SGD
from keras.callbacks import ModelCheckpoint, TensorBoard
import os
import numpy as np
from ... | true |
f5e049eb5f02a36745a3491b6815f86cf69635ff | Python | ericgreveson/projecteuler | /problem72.py | UTF-8 | 596 | 3.515625 | 4 | [
"Apache-2.0"
] | permissive | from factor_tools import get_primes, totient
def main():
"""
Entry point
"""
# We have n/d where n<d. For reduced proper fractions, n and d must be coprime.
# So for denominator d, there are phi(d) numerators, and we want sum(phi(d)), 1 < d <= 10^6
print("Getting primes up to 1000000...")
p... | true |
f6829d5e1a739e3e6751aebc094b760f8a55f274 | Python | pktippa/python-docs | /basics/collections/list.py | UTF-8 | 3,451 | 4.65625 | 5 | [
"MIT"
] | permissive | # List
sample_list = ["Raj",5,"Uday","Navya",9] #List can store both homogeneous and heterogeneous elements
# Creating a list with known size and unknown elements
sample_list2=[None]*5 # None denotes an unknown value in Python
# len(list) gives the length of list
print("2nd element in list ", sample_list[1], "last elem... | true |
9340f0a7e34cd8f8a43264381955321ea32518f1 | Python | Hallyson34/uPython2 | /criptografia.py | UTF-8 | 906 | 3.265625 | 3 | [] | no_license | def deslocaTres(msg):
for i in range(0,len(msg)):
if 64<ord(msg[i])<90 or 96<ord(msg[i])<123:
msg[i] = ord(msg[i]) + 3
msg[i] = chr(msg[i])
return msg
#------------------------------------------------------------
def inverter(d):
j = len(d)-1
inv = [0] * len(d)
for ... | true |
1081db7ebf1bf8c852cab624e80fc64822a67c14 | Python | trecuu/getsub | /getsub.py | UTF-8 | 973 | 2.671875 | 3 | [] | no_license | import sys
import time
import os
import hashlib
import requests
user_agent = {'User-Agent': "SubDB/1.0 (getsub/0.1; http://github.com/trecuu/getsub)"}
language = 'pt,en'#selected languages
videoFile = str(sys.argv[1]) #file location ex.: C:\Downloads\Video.mkv
def get_hash(name):
readsize = 64 * 1024
with open(nam... | true |
7878473c8d1d09c49a35a05e48fc096223eaa93a | Python | akozyreva/python-learning | /9.1-modules/two.py | UTF-8 | 205 | 2.9375 | 3 | [] | no_license | # two.py
import one
print("Top level in two.py")
one.func()
if __name__ == "__main__":
print("Two.py is running directly")
else:
print("Two.py hase been imported")
print("The end of execution")
| true |
9db2ad3061dc6bf6aba19bbaa6ad31ce7e3f9049 | Python | yaoyuanyy/python_demo | /src/if.py | UTF-8 | 150 | 3.40625 | 3 | [] | no_license | x = int(input("the value is"))
if(x < 0):
x = 0
print("x = 0")
elif x == 0:
print("0")
elif x > 0:
print("x>0")
else: print("x=100")
| true |
ebcb595ca41be0f8337e9b0ae81a5f56b6ec8808 | Python | bw2/bin-utils | /columnate | UTF-8 | 904 | 2.765625 | 3 | [] | no_license | #!/usr/bin/env python
import sys
if len(sys.argv) > 1:
f = open(sys.argv[1])
else:
f = sys.stdin
num_fields = None
data = []
max_widths = None
for line in f:
if not line.strip():
data.append(line.strip())
continue
fields = line.split('\t')
#print(fields)
if not num_fields:
num_fields = len(fields)
max_... | true |
b5662550495dae1a9a63561a63cd6dcedf4f68a5 | Python | krnets/codewars-practice | /7kyu/Distance from the average/index.py | UTF-8 | 1,931 | 3.984375 | 4 | [] | no_license | # 7kyu - Distance from the average
""" Given a starting list/array of data, it could make some statistical sense to know
how much each value differs from the average.
If for example during a week of work you have collected 55,95,62,36,48 contacts for your business,
it might be interesting to know the total (296), t... | true |
6d1f1ef8ac3c00e6af3bbcdaf3cc30034914d201 | Python | lhalstro/compressionTest | /plotCompression.py | UTF-8 | 11,006 | 3.1875 | 3 | [] | no_license | """COMPRESSION TEST VISUALIZATION TOOL
Logan Halstrom
CREATED: 08 JAN 2017
MODIFIY: 22 MAR 2017
DESCRIPTION: Visualize data for compression tests of internal combustion
engines. Compare pressure history of each cylinder as well as differences
between dry and wet (oil added to cylinder) tests.
NOTE:
Data files are m... | true |
109ab2cb2dee4c9fae693a5fec720bf992ac73c3 | Python | LucasSantos27/PythonBasico | /aula5-estruturas-de-laco.py | UTF-8 | 1,336 | 4.125 | 4 | [] | no_license | #Criando lista para percorrer com o laço
'''
lista_nomes = ['Futebol', 'Formula 1', 'Futebol Americano', 'Basquete']
for nome in lista_nomes:
print(nome)
'''
#Criação de uma lista numeros
'''
lista_de_numeros = range(4) #Até o número 4, sem contar ele
lista_de_numeros2 = range(5,10) #Intervalo de numeros até o 10... | true |
afcbb21ca3b2c082fb0d999ed2442501bcb90d65 | Python | rahulkmr/python3_musings | /total_grid_paths.py | UTF-8 | 1,311 | 3.59375 | 4 | [] | no_license | #!/usr/bin/env python
def gen_neighour(start, end):
directions = [[-1, 0], [1, 0], [0, 1], [0, -1], [-1, 1], [-1, -1], [1, 1], [1, -1]]
def neighours(current):
return ((current[0] + d[0], current[1] + d[1]) for d in directions
if (start[0] <= (current[0] + d[0]) <= end[0]) and (start[... | true |
37893ff387929ebd394f89e4c33214b19fb79a5c | Python | felipeCaetano/TkinterGalery | /Scale.py | UTF-8 | 254 | 3.265625 | 3 | [] | no_license | """
Cria um Slider sobre o objeto TK.
"""
from tkinter import *
root = Tk()
slider = Scale(root, from_=0, to=100).pack()
# na posição horizontal:
# horizontal_slider = Scale(root, from_=0, to=100, orient=HORIZONTAL).pack()
root.mainloop()
| true |
0b55096f5fac952ed9af7053da037a3186c739b2 | Python | Sankalp679/Competitive-Programming | /Leet Code/30 Days of Code/week_01/counting_numbers.py | UTF-8 | 280 | 3.34375 | 3 | [] | no_license | class Solution:
def countElements(self, arr: List[int]) -> int:
numbers = [0]*1002
for i in arr:
numbers[i] += 1
count = 0
for i in arr:
if numbers[i+1] > 0:
count += 1
return count | true |
ec44c2f995412cfef68bbfc4623afec4a71c83a1 | Python | ansrivas/imageprocessing | /ImageProcessingProject2/gaussian/SeparableConvolution.py | UTF-8 | 2,539 | 3.296875 | 3 | [] | no_license | import math
import numpy as np
import scipy.misc
import time
class SeparableConvolution:
def __init__(self, inputImageFileName, kernelSize):
#Get the Images as array
self.inputImage = scipy.misc.imread(inputImageFileName)
self.outputImage = np.zeros(self.inputImage.shape)
... | true |
ad881d7bab56e2cd445f5a5da65a3f98a58b981e | Python | fisadev/zombsole | /players/troll.py | UTF-8 | 392 | 2.890625 | 3 | [] | no_license | # coding: utf-8
from things import Player
class Troll(Player):
"""A player that always heals itself.
(trolls have regenerative capabilities, hence the name).
"""
def next_step(self, things, t):
self.status = u'healing myself'
return 'heal', self
def create(rules, objectives=None)... | true |
b9c2dda6ec5aaac2783bbcc816a219c9270c6f98 | Python | rafhaeldeandrade/learning-python | /4 - Estruturas de Repetição em Python/aula_10_loop_for.py | UTF-8 | 1,972 | 4.53125 | 5 | [] | no_license | """
Loop é uma estrutura de repetição
For é uma dessas estruturas.
C ou JAVA:
for(int i=0; i < 10; i++){
//commands
}
Python
for item in iteravel:
//commands
Utilizamos loops para iterar sobre sequências ou sobre valores iteráveis.
Valores iteráveis:
* String
nome = 'Python'
* Lista
nome = ['Linguagem', 'Py... | true |
6f22b887e28e725c030230cb7ca0cb1afa30314b | Python | falconandy/composer | /composer/efile/xmlio.py | UTF-8 | 3,750 | 2.671875 | 3 | [] | no_license | from collections.abc import Callable
from io import StringIO
import re
import lxml.etree
from lxml.etree import XMLParser, parse
from xmljson import XMLData
from collections import Counter, OrderedDict
# noinspection PyProtectedMember
# from .convert import convert
import sys
# Python 3: define unicode() as str()
... | true |
e61a82f96bbf6459d1a4272081dbaba87177a0dd | Python | Zikoat/musweeper | /musweeper/musweeper/muzero/tree/monte_carlo_test.py | UTF-8 | 4,725 | 2.640625 | 3 | [
"MIT"
] | permissive | import unittest
from .monte_carlo import *
from .node import *
from ..utils.basic_env import *
from ..model.mock import *
from ..model.muzero import *
class TestMonteCarlo(unittest.TestCase):
def setUp(self):
env = BasicEnv()
max_search_depth = 3
# even if rollout is False, it will do rollout since none of the ... | true |
ad408f07d7049ab717cc27e1ca97cb7e5d8e7d03 | Python | POPVOX/site | /site/writeyourrep/district_metadata.py | UTF-8 | 1,929 | 2.578125 | 3 | [] | no_license | import urllib, urllib2, json
from math import log, sqrt
from django.db import connection
state_bounds = { }
def http_rest_json(url, args=None, method="GET"):
if method == "GET" and args != None:
url += "?" + urllib.urlencode(args).encode("utf8")
req = urllib2.Request(url)
r = urllib2.urlopen(req)
return json.l... | true |
dd0b4d53371cf56cf3108353f7025559f4518c98 | Python | germanas/wrangling-OSM | /Case_study_excercises/auditing.py | UTF-8 | 1,410 | 2.734375 | 3 | [] | no_license | import xml.etree.cElementTree as ET
from collections import defaultdict
import re
import pprint
OSMFILE = "vilniussample.osm"
street_type_re = re.compile(r'\b\S+\.?$', re.IGNORECASE)
expected = ["gatve", "aikste", "aleja"]
# UPDATE THIS VARIABLE
mapping = { "g.": "gatve",
"a.": "aikste",
"al... | true |
b63cc1c883925d03e516e319c58b4769765d24bd | Python | BenWhitlock/Uni-Physics | /gameoflife.py | UTF-8 | 3,563 | 3.28125 | 3 | [] | no_license |
import numpy as np
import matplotlib.pyplot as plt
import scipy.misc
def upscale(img,scale):
shape = np.shape(img)
scaledShape = [shape[0]*scale,shape[1]*scale]
newImg = np.zeros((scaledShape[0],scaledShape[1]))
a = int(scaledShape[0])
b = int(scaledShape[1])
for i in ra... | true |
1e5f322d49e8d030048c663b6e9781e7660aad07 | Python | Helios74/Real-Time-Sound-Localization | /Raspberry Pi Implementation/Raspberry Pi.py | UTF-8 | 968 | 3.171875 | 3 | [] | no_license | import os
import spidev
import time
# Function to convert digital data to Volts
def Volts(data, places, Vref):
return round((data * Vref) / float(4096), places)
# Function to read Digital Data from a MCP3208 channel
# Channel 0-7
def ReadADCChannel(channel):
adc = spi.xfer2([6 + ((channel&4) >> 2),(channel&3) << ... | true |
03fd917c395b8caa9cdd7f9832bea97d5919a109 | Python | caribbean-boba/recommender-system-for-news | /helpers/newsapi_client.py | UTF-8 | 915 | 2.71875 | 3 | [] | no_license | import requests
from json import loads
ENDPOINT = 'https://newsapi.org/v2/'
KEY = 'd650981e4c624bc6868d82a810f850af'
SROURCE_LIST = ['cnn']
def getNews(sources = SROURCE_LIST, sortBy = 'top'):
print sources
sources = sources.split(',')
results = []
for source in sources:
payload = {'apiKey': KE... | true |
80e903481e628d0e89f45cc2d4de39cfbb76060e | Python | dsm-kbl/python-snippets | /ch13_while_for/tuple_assignment.py | UTF-8 | 134 | 3.53125 | 4 | [] | no_license | D = {'a': 1, 'b': 2, 'c': 3 }
for key in D:
print(key, '=>', D[key])
for (key, value) in D.items():
print(key, '=>', value)
| true |
440085a6c7c1ff5e91df946e292be46883f177de | Python | DGomez9803/proyectoLenguajes | /ProyectoLenguajes/entidad/Lr0.py | UTF-8 | 423 | 2.515625 | 3 | [] | no_license | from entidad import Gramatica;
#clase que hereda de Gramatica
class Lr0(Gramatica):
def __init__(self,tablaSintactica):
self.tablaSintactica=tablaSintactica
def getTablaSintactica(self):
return self.tablaSintactica
#metodo que llena la tabla sintactica lr0 y sro
#es diccionrario que s... | true |
6d77813f1ad9abee5dece0481d6c8371fdc4eac2 | Python | korbinianbauer/SyntheticPallet | /Inference/singleRetinaDetection.py | UTF-8 | 3,140 | 2.53125 | 3 | [] | no_license | import keras
import tensorflow as tf
from keras_retinanet import models
from keras_retinanet.utils.image import read_image_bgr, preprocess_image, resize_image
import numpy as np
from datetime import datetime
import cv2
import directories
# set tf backend to allow memory to grow, instead of claiming everything
def g... | true |
29341cf413bcefbf3c587a958715cc9e7850919c | Python | RBVinsWoller/bot_prascovya | /graphics.py | WINDOWS-1251 | 199 | 3.109375 | 3 | [] | no_license | import matplotlib.pyplot as plt
plt.ylabel(' Y')
plt.xlabel(' X')
plt.title(' ')
plt.plot([0,10],[10,0])
plt.plot([1,-2],[-8,0], 'r--')
plt.scatter([1,2],[8,0], color = 'g')
plt.show | true |
b0c11eb312f6d3b0a5cedf926572a1355104f0b7 | Python | hong8yung/algorithm | /BOJ/1826.py | UTF-8 | 1,084 | 3.03125 | 3 | [] | no_license | import sys
inp = sys.stdin.readline
def greedy():
arr = []
queGS = []
result = 0
idx = 0
for i in range(int(inp())):
dstGS, volFuel = map(int, inp().split())
arr.append((dstGS, volFuel))
dstVlg, orgnlFuel = map(int, inp().split())
arr = sorted(arr)
while dstVlg > org... | true |
742feab32a5ca83206b22101e04f1cfe11716a5c | Python | rbonhamcarter/network-diffusion-model | /network_diffusion_model.py | UTF-8 | 3,328 | 2.921875 | 3 | [] | no_license | import numpy as np
import matplotlib.pyplot as plt
from os.path import expanduser, join
import diffusionBBC
def main():
# Specifying the directories containing the empirical structural and functional connectivity data
home = expanduser('~')
struct_directory_name = join(home, 'Documents', 'data_conn')
... | true |
398dd3f2c471658d34b8add1da95f3cfa3b0eb46 | Python | oknowles/euler | /problem_5.py | UTF-8 | 892 | 4.15625 | 4 | [] | no_license | def divisible_by_set(n, nums):
for i in nums:
if ((n % i) != 0):
return False
return True
# find the unique factors in a given range, e.g. for upper_limit = 10
# the unique factors would be 6,7,8,9,10
# that is, if a number is divisible by 10 then it is also divisible by 5 so no need to che... | true |
d440269b72b2bb7fbad25edd8cb7d5318bf1f2e9 | Python | tarantot/homework-1 | /calculator.py | UTF-8 | 1,707 | 2.96875 | 3 | [] | no_license | from tkinter import *
from tkinter import messagebox
from tkinter import ttk
import math
window = Tk()
window.title("Калькулятор")
window.geometry("525x125")
window["bg"] = "#ffff00"
def calc(key):
global memory
if key == "=":
strl = "-+01234567890,*/"
if calc_entryspace.get()[0] not in strl:
... | true |
78e18daef22a27b722557406ad64af3d32a7b6b0 | Python | ashokbezawada/Python-Scripts | /Winter break/graphfrom_textfile.py | UTF-8 | 1,660 | 3.96875 | 4 | [] | no_license | # The main goal of this function is it will return all cities present in a text file
# The function takes argument as file path
def graphfrom_textfile_f1(file):
cities = []
new_cities_graph = []
for line in file:
new_line = line.split()
for i in new_line:
if i not in cities:
... | true |
3a25245efc52ebd620b9fb241ce130357034b303 | Python | alejandroanachuri/ia_basico | /perceptron.py | UTF-8 | 1,926 | 3.328125 | 3 | [] | no_license | import matplotlib.pyplot as plt
import numpy as np
def clases(x, y):
class_1 = []
class_2 = []
for i in range(len(y)):
if y[i] < 0:
class_2.append(x[i])
else:
class_1.append(x[i])
return class_1, class_2
def perceptron(x_set, y_set ):
print ("Procesando perce... | true |
2064d374ce7b6812255e8a396bb09f3221862d26 | Python | petramanuel/ibb | /src/ibbtest.py | UTF-8 | 7,615 | 2.53125 | 3 | [
"MIT"
] | permissive | import os
import shutil
import string
import tempfile
import unittest
import queue
import threading
import ibb
class TestCase(unittest.TestCase):
pass
class FlattenTests(TestCase):
def test_flatten(self):
self.assertEqual([], ibb.flatten([]))
self.assertEqual([], ibb.flatten([[]]))
se... | true |
567044c2882ba7ec1506cb41dab0040739d89ec5 | Python | NeniscaMaria/Grades-and-Assignments-Manager-Application | /model_Student.py | UTF-8 | 2,973 | 3.46875 | 3 | [] | no_license | import unittest
import json
class Student:
'''
THIS CLASS IS USED FOR MODELLING A STUDENT
A STUDENT HAS :
AN ID=A NATURAL NUMBER
A NAME=A STRING. A STUDENT CAN HAVE 2 OR 3 NAMES. THE PRENOMS ARE SEPPARTED BY '-'
A GROUP=A NATURAL NUMBER. EACH STUDENT BELONGS TO A GROUP
'... | true |
d445729d3f9e0d2e10076e65ea26634d2120571c | Python | giomalt/SLM_hologram_generation | /lib/opencavity/beams.py | UTF-8 | 6,578 | 2.96875 | 3 | [
"MIT"
] | permissive | '''
Created on 9 mars 2014
@author: Mohamed seghilani
'''
import numpy as np
import math
from opencavity import utilsfunc
class HgBasis(object):
'''
Generation of Hermite Gauss beams
'''
def __init__(self,wavelength,w0x,w0y=0):
'''
Constructor
'''
self.k=2*np.pi/... | true |
172b144631df0ccd01a936297476991ef1a966d4 | Python | AntonMikhaylovO/VerilogToFunction | /main.py | UTF-8 | 3,797 | 2.5625 | 3 | [] | no_license | from pyeda.inter import *
from graphviz import Source
class Parse():
def __init__(self):
buf=''
self.var=''
self.variable=[]
self.flag=True
self.sdnf=[]
self.len=[]
self.f = open('truth_table.txt', 'r')
for line in self.f:
for i in range(len... | true |
e36c69cefd2495faf7024f54910e2ef37f1a763a | Python | tatsunakano/AnswerExample | /data.py | UTF-8 | 1,166 | 2.875 | 3 | [] | no_license | import csv
from email.message import EmailMessage
from email.generator import Generator
#メール本文用テキスト
def read_txt(path):
with open(path,'r',encoding='utf-8') as f:
return f.read()
def create_mail(subject, to_addr, cc_addr, from_addr, body_txt):
mail_data = EmailMessage()
mail_data["subje... | true |
d964b7591e22f8e12b428711e2fd96b1f60463ee | Python | Reiuiji/UmassdPortfolio | /ECE369/python project/Chat_test/examples/chat/settings.py | UTF-8 | 579 | 2.609375 | 3 | [
"MIT"
] | permissive | file = open("connection.txt","r")
for line in file.readlines():
line = line.strip()
if line.startswith("#"): continue
if line == "": continue
try:
line = line.split(" = ")
if line[0] == "client_ip":
client_ip = line[1][1:-1]
elif line[0] == "server_ip":
... | true |
be3d434c2ae54af67da7a686eb938021ecae704f | Python | NNTin/twitter-backend | /app.py | UTF-8 | 1,909 | 2.625 | 3 | [] | no_license | from flask import Flask, render_template
from flask import jsonify
from config import config
import tweepy
app = Flask(__name__)
extracted_information = ["created_at", "description", "followers_count", "id", "screen_name", "name",
"profile_image_url", "statuses_count", "id_str"]
auth = tweepy... | true |
86815710dc9f34e4de9aff0ffb36ed89fe57b238 | Python | mbtomlinson/exercism | /allergies/allergies.py | UTF-8 | 691 | 3.390625 | 3 | [] | no_license | allergens = ['cats','pollen','chocolate','tomatoes','strawberries','shellfish','peanuts','eggs']
class Allergies(object):
def __init__(self,score):
binary = [0,0,0,0,0,0,0,0]
list_of_allergies = []
score = score % 256
for i in range(7,-1,-1):
if score >= 2**i:
... | true |
a08c11ee97cd4c6e96f5cc59bb949b3558ba1da5 | Python | zeuko/nao | /CommandExecution/NaoBasicCommandExecutor.py | UTF-8 | 1,274 | 2.6875 | 3 | [] | no_license | from math import pi
from naoqi import ALProxy
from CommandExecution.CommandExecutor import CommandExecutor
from TextToCommand.Errors import CommandNotFoundError
class NaoBasicCommandExecutor(CommandExecutor):
def __init__(self):
self.move = ALProxy("ALMotion")
self.posture = ALProxy("ALRobotPostur... | true |
6fe6f0c7ab0fe302ee4bf3f2244df992da04d702 | Python | liugingko/LeetCode-Python | /Leetcode/LeetCode1/410. Split Array Largest Sum.py | UTF-8 | 1,958 | 3.859375 | 4 | [] | no_license | # Bytedance AI Camp 2018 -编程题2-(北京时间)05月26日 09时30分-05月26日 12时00分
# 解题思路 二分查找(Binary Search)
# 将数组nums拆分成m个子数组,每个子数组的和的范围在 [sum(nums) / m,sum(nums)]内
# 又因为数组nums中只包含非负整数,因此可以通过二分法在上下界内搜索最优解。
# 时间复杂度O(n * log m),其中n是数组nums的长度,m为数组nums的和(准确的说应该是sum(nums)-sum(nums)/m)
# @Time :2018/5/27
# @Author :LiuYinxing
class Sol... | true |
2fde0ef33afe6bef64ffe7b15a8f59850cfdfa30 | Python | szchengmi/AI-news | /data/sanitize/__init__.py | UTF-8 | 865 | 3.171875 | 3 | [] | no_license | #!/usr/bin/env python3
import pandas as pd
import re
import sqlite3
def preprocess(articleString):
try:
articleString = articleString.lower()
articleString = re.sub(r"([.,!?])", r" \1 ", articleString)
articleString = re.sub(r"[^a-zA-A.,!?]+", r" ", articleString)
return articleStri... | true |
c0bcd8f16ffbf09c712ad876ccdca6bd12a43e4c | Python | nik-panekin/pyramid_puzzle | /rounded_rect.py | UTF-8 | 2,166 | 3.953125 | 4 | [
"MIT"
] | permissive | """Module for implementation the RoundedRect class.
"""
import pygame
# Brightness lowering for border color
# Must be in range (0..1) - not inclusively
BRIGHTNESS_LOW = 0.5
BORDER_WIDTH = 4 # Inner border width in pixels
class RoundedRect():
"""The RoundedRect class simplifies drawing filled rectangles with roun... | true |
979d633491e3765ae2c6271d304b607040420ca4 | Python | sflis/MLSandbox | /python/utils.py | UTF-8 | 776 | 2.546875 | 3 | [] | no_license |
def pval(uplim, uplim_dist):
from scipy import stats
import numpy as np
i = 0
uplim_dist = np.sort(uplim_dist)
while(((i+1)<len(uplim_dist)) and uplim_dist[i]< uplim):
i +=1
#Computing the p-value
p_value = 1-float(i)/len(uplim_dist)
p_value_sigma = stats.norm.ppf(1.0 - p_valu... | true |
e524c6b61eaa2c39ccd882d57147d6e3513e05b1 | Python | aqurilla/data-structures-and-algorithms | /python/binary_search.py | UTF-8 | 571 | 3.609375 | 4 | [] | no_license | # https://leetcode.com/problems/binary-search/
from math import floor
class Solution:
def BinarySearch(self, nums, low, high, target):
if high<low:
return -1
mid = floor(low + (high-low)/2)
if nums[mid]==target:
return mid
elif nums[mid]<target:
r... | true |
e5b2fbbef1575e011b6647d8edbad053f9c7dc24 | Python | wang520yan/study | /python/u_r_p_manage/u_r_p_manage/common.py | UTF-8 | 9,225 | 2.625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import hashlib
import json
import os
import re
import time
import datetime
from functools import wraps
import logging
from rest_framework.response import Response
from rest_framework import status
# 响应头的通用字段
RESPONSE_HEADER = {
"Server": "IIE CAS",
# "Date": datetime.datetime.now().strf... | true |
99ed64d79d590beed6abfccc4d256c64e216494c | Python | hile/soundforest | /soundforest/playlist.py | UTF-8 | 6,087 | 2.78125 | 3 | [] | no_license | #!/usr/bin/env python
import os
from soundforest import normalized, path_string
class PlaylistError(Exception):
pass
class Playlist(list):
def __init__(self, name, unique=True):
self.name = os.path.splitext(os.path.basename(name))[0]
self.unique = unique
self.modified = False
... | true |
5360311cb7f8fa541c1e1d49dbca0e699de5c3ea | Python | JasYoung315/UnderstandingTheEffectOfSelfishBehaviourInASeriesOfTwoQueues | /Code/sim.py | UTF-8 | 19,345 | 2.609375 | 3 | [] | no_license | """Simulation of Hierarchical queues
Usage:
sim.py sim <lambda> <mu> <c> [-w]
sim.py file <file> [-w]
sim.py -h | --help
sim.py --version
Options:
-w Write data to csv file [default: True].
-h --help Show this screen.
--version Show version.
Examples:
If using... | true |
dd8329551fb6b77ea8bccf6bcb3c080875d95526 | Python | GitPistachio/Competitive-programming | /SPOJ/BINARYIO - Binary Input and Output/Binary Input and Output_v3.py | UTF-8 | 397 | 2.625 | 3 | [] | no_license | # Project name : SPOJ: BINARYIO - Binary Input and Output
# Author : Wojciech Raszka
# Date created : 2019-03-10
# Description :
# Status : Accepted (23380016)
# Comment :
import sys
import struct
from math import log
inp = sys.stdin.buffer.read()
no_of_ret = len(inp)//8
sys.stdout.buffer.write(b''.... | true |
682f9b9ddda5426d4cbbab68d5af1cadbfb5eae9 | Python | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_76/948.py | UTF-8 | 531 | 3.046875 | 3 | [] | no_license | #! /usr/bin/env python
import operator
fin = open('in.txt','r')
numtests = int(fin.readline().rstrip('\n'))
casenum = 0
for casenum in range(numtests):
numcandies = int(fin.readline().rstrip('\n'))
candies = fin.readline().rstrip('\n').split(' ')
int_candies = map(lambda x: int(x), candies)
xor_total = reduce(l... | true |
d7e76af894493d028e0a51422e2932829f3ef90c | Python | Renderhaf/StockAnalyzer | /StockDataLearner.py | UTF-8 | 1,403 | 2.953125 | 3 | [] | no_license | import keras
import numpy as np
class StockDataLearner:
def __init__(self, inputSize = 7, outputSize = 1, activationFunction="linear", hiddenLayersFunction="relu"):
self.activationFunction = activationFunction
self.hiddenLayersFunction = hiddenLayersFunction
self.model = keras.Sequential()
... | true |
d6223c481fb02706dd5fa1e6029743d1e4ddac35 | Python | lesguillemets/notes | /Scripts/9Nov2013.perlinnoise.py | UTF-8 | 2,694 | 3.296875 | 3 | [
"CC-BY-4.0",
"CC-BY-3.0",
"MIT"
] | permissive | #!/usr/bin/python
import random
import operator
import numpy as np
import Image
import math
class PerlinGrid(object):
"""
PerlinGrid:
(x0,y1) (x1,y1)
--------------------------
| Grad:g3 | Grad:g2
| |
| u ... | true |
09559670a96fd976937f3d46d30539c4100fa69b | Python | aguscoppe/ejercicios-python | /TP_4_Estructura_iterativa/TP4_EJ17C.py | UTF-8 | 248 | 3.890625 | 4 | [] | no_license | # Ejercicio 17-C
tope = int(input("Ingrese un tope: "))
cont = 1
serieC = 1
numMayor = 0
while serieC < tope:
if serieC > numMayor and serieC <= tope:
numMayor = serieC
serieC = cont + serieC
cont = cont + 1
print(numMayor) | true |
bf0db247d9cc1be57fbb3f3e9598483deceb0439 | Python | benquick123/code-profiling | /code/batch-2/dn14 - zoge/M-17029-2474.py | UTF-8 | 3,190 | 2.75 | 3 | [] | no_license | from random import randint
import risar, datetime
from math import sqrt
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtWidgets import QMessageBox
def naredi_krogi(n):
krogi = []
i = x = y = 0
while i < n:
x = randint(-5, 6)
x1 = sqrt(x**2)
y = (5 - x1)**2
... | true |
05d781d475f870b317747f7c999b8f8001cb0efc | Python | glasperfan/thesis | /bach_code/chorale_range.py | UTF-8 | 2,227 | 2.953125 | 3 | [
"Apache-2.0"
] | permissive | #########
#
## File: chorale_range.py
## Author: Hugh Zabriskie (c) 2015
## Description: Code to determine the range of voices .
#
#########
from music21 import *
## Helper function: find the global minimum and maximum pitch for each voice over the entire set of chorales
# <scores>: a list of score objects
# <partID>... | true |
6d2f9e1e47632ea8c8cb1a4c8183298efcc81cb2 | Python | aaronjangel/aoc2018 | /python/aoc2018d14.py | UTF-8 | 1,336 | 3.328125 | 3 | [
"BSD-2-Clause"
] | permissive | #!/usr/bin/pypy
import sys
class scores(object):
def __init__(self):
self.elves = [0, 1]
self.scoreboard = list([3,7])
def tally(self):
score = self.scoreboard[self.elves[0]]
score += self.scoreboard[self.elves[1]]
self.scoreboard.extend(divmod(score, 10) if score > 9 ... | true |
12a1d668278afb1fb7a4838fde818ce1b82417bb | Python | DarleneAntonino/QuoteChecker | /quotechecker.py | UTF-8 | 9,076 | 3.03125 | 3 | [] | no_license | #!/usr/bin/env python3
## test.py
#imports for E-Mail
from smtplib import SMTP
from email.message import EmailMessage
#imports for regex
import re
#import for db
import mysql.connector
#import for os recognicion
import platform
# ----- FUNCTIONS -----
#get the pw for sending the email
def getSenderPW():
cursor = c... | true |
947e5d1349364c173c73fcbfdf6a6d2a4ebb0eb0 | Python | dytfy666/get-url | /huya.py | UTF-8 | 1,453 | 2.84375 | 3 | [] | no_license | # 获取虎牙直播的真实流媒体地址。
from typing import List, Any, Union
import requests
import re
def get_real_url(rid):
room_url = 'https://m.huya.com/' + str(rid)
header = {
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit... | true |
bd4fdfd4e7762deadeb7258d2d1109b9a1be64a9 | Python | giantZorg/lol_item_diversity | /src/ressources/mongodb.py | UTF-8 | 5,576 | 2.8125 | 3 | [] | no_license | '''
MongoDB functions
'''
###
# Imports
import copy
import logging
from typing import Dict, Set, Tuple
from pymongo import MongoClient, database, cursor
###
# Load ressources
try:
import src.ressources.constants as const
except Exception:
import ressources.constants as const
###... | true |
3ae8df1e07edff09b570e7ab7d3bb36bd09824ae | Python | kiddten/yax | /spoilog.py | UTF-8 | 2,050 | 3 | 3 | [] | no_license | from collections import OrderedDict
SPOIDOC = """
<!DOCTYPE html>
<meta charset='utf-8'>
<html>
<head>
<title></title>
<script type="text/javascript">
function spoiler(el, t) {{
var inner = el.parentNode.parentNode.getElementsByTagName('div')[1].getElementsByTagName('div')[0]
i... | true |
bb13af4c7e43865fad2e637be588f139a82156e4 | Python | aks97cs/Python-Practice | /opencv/read_image_from_disc.py | UTF-8 | 373 | 2.921875 | 3 | [] | no_license | import cv2
def main():
imgpath = 'G:\\Python-Practice\\opencv\\images\\4.2.03.tiff'
# READ IMAGE FROM DISC
img = cv2.imread(imgpath)
# TO VIEW IMAGE CV2.IMSHOW("NAME OF WINDOW", IMG)
cv2.imshow('imageViewer', img)
#TO BIND KEYBOARD EVENT WITH CV2.IMSHOW METHOD
cv2.waitKey(0)
cv2.destr... | true |
8bcafcfef80d1d58dd192f072b86d8159cb78fd3 | Python | pohily/checkio | /unlucky-days.py | UTF-8 | 528 | 3.5625 | 4 | [] | no_license | def checkio(year):
from datetime import date
result = 0
for month in range(1, 13):
day = date(year, month, 13)
if day.isoweekday() == 5:
result += 1
return result
print(checkio(2019))
"""
def checkio(year):
"""
calendar.weekday(year, month, day)
... | true |
87d6d0e515efd2644cc105a7ccf89594dab708b2 | Python | coquelin77/PyProject | /leetcode/28实现str.py | UTF-8 | 1,304 | 4.0625 | 4 | [] | no_license | '''实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
示例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1'''
if __name__ == '__main__':
haystack = "hello"
needle = "ll"
#h,e,l,l,o
#l,l
i=0
... | true |
1dfa2ab04a73180d3547162bee0c32405990db53 | Python | Guilherme-Galli77/Curso-Python-Mundo-3 | /Exercicios/Ex112/utilidades/moeda/__init__.py | UTF-8 | 1,003 | 3.609375 | 4 | [] | no_license | def metade(p):
return print(f"A metade de R$ {p:.2f} é R$ {p/2:.2f}")
def dobro(p):
return print(f"O dobro de R$ {p:.2f} é R$ {p*2:.2f}")
def aumentando(p,v):
return print(f"Aumentando {v}%, temos R$ {p*(1+(v/100)):.2f}")
def diminuindo(p,d):
return print(f"Diminuindo {d}%, temos R$ {p*(1-(d/100))... | true |
a075832b33e7d6ab918bc477076112626c08143a | Python | SGJJSR/Python_challenges | /python_plus_gis.py | UTF-8 | 6,333 | 3.640625 | 4 | [] | no_license | from shapely.geometry import Point, LineString, Polygon
import numpy as np
# 1)
# Create a function called createPointGeom() that has two parameters (x_coord, y_coord).
# Function should create a shapely Point geometry object and return that.
# Demonstrate the usage of the function by creating Point -objects with th... | true |
1a9c8f71a0c333f573e98f1b9cd5773959846b1d | Python | akffhaos95/pythonCode | /basic/03/classTest.py | UTF-8 | 816 | 4 | 4 | [] | no_license | import sys
class Calculator():
def __init__(self, x, y):
self.x = x
self.y = y
def add(self):
print(self.x + self.y)
def min(self):
print(self.x - self.y)
def mul(self):
print(self.x * self.y)
def div(self):
print(self.x / self.y)
class FourCalculato... | true |
ef92fd3499b6401cc01ed3ffec3d6ad25adf4945 | Python | Aakashbansal837/python | /the best player hackerearth.py | UTF-8 | 1,049 | 3.453125 | 3 | [] | no_license | total_fans, allowed_fans = (int(inp) for inp in input().split(' ')) #Taking th input as mentioned in the problem
hash_of_quotient_to_name = dict()
quotient_list=[]
#Storing the details in a dictionary by mapping the fan quotient to a list of names of fans with same fan quotient
i=1
while i<=total_fans:
name_an... | true |
81bf6f4da161fd0dbe09aff8d2faa08eaa2fbcce | Python | pmiller3/minecraft-pi | /python/Lesson1/HelloMinecraft.py | UTF-8 | 479 | 3.15625 | 3 | [] | no_license | # Import the library so we can talk to the game
from mcpi.minecraft import Minecraft
# Create and store a connection to our game in a variable
# By leaving the argument empty, it connects locally, but
# we could provide an IP address if we wanted to a remote pi
minecraft = Minecraft.create()
# Make sure we get someth... | true |
3891a1e68ac135962a2551a5c2afe4f15deda6cf | Python | AhmedMorsy95/Lexical-Analysis | /tokenizer/minimization.py | UTF-8 | 2,364 | 3.046875 | 3 | [] | no_license | from .dfaState import state
from .min_state import min_state
from .DFA import DFA
from .NodeGenerator import NodeGenerator
import queue
from string import ascii_letters
symbols_list = []
for char in ascii_letters:
symbols_list.append(char)
for i in range(0,9):
symbols_list.append(str(i))
no=0
dic ={} # for ... | true |
5cf1d49a04dd7928bef3882266e522aa23a0d5de | Python | tonyferrell/aoc2020 | /day3/day3sol.py | UTF-8 | 1,572 | 3.765625 | 4 | [] | no_license | from functools import reduce
class InfinteWidthMap:
def __init__(self, filename):
self.tree_char = '#'
self.open_char = '.'
self._base_map = []
self.height = 0
with open(filename) as map:
for row_raw in map:
if not row_raw:
pr... | true |
1c0085491101514c46c727c3512c5e725a690fce | Python | Brindledl1nc/python-tutorials | /lab-01/list-operations.py | UTF-8 | 228 | 3.078125 | 3 | [] | no_license |
mylist = []
mylist = [-15.3068189663,-0.883700335702,3.30128033411]
new_list = []
for l in mylist:
#print l * 100
new_list.append(l + 100)
print new_list
print max(new_list)
print min(new_list)
print sum(new_list)
| true |
aded0075b1f3902f7986ef1326e0a554efe273e7 | Python | DanilloMLS/lista_de_exercicios | /2014-1-bcc-ip-L2.2-DanilloMoraesLimaDosSantos/Q2.py | ISO-8859-1 | 79 | 3.34375 | 3 | [
"MIT"
] | permissive | num =input("Digite um nmero: ")
print ("O nmero informado foi: "), num
| true |
27de08e7d3af3a61b47861b12a7491a3c0c27b0a | Python | fang98525/MyLearning | /nlp_经典网络/激活函数.py | UTF-8 | 802 | 2.578125 | 3 | [] | no_license | import torch
import matplotlib.pyplot as plt
import torch.optim as optim
import torch.nn as nn
#
# #激活函数
# x=torch.range(-5,5,0.1)
# print(x)
# y=torch.sigmoid(x)
# y1=torch.tanh(x)
# y2=torch.relu(x)
# # y3=torch.softmax(x)
# # y1=torch.nn.Sigmoid(x)
# plt.plot(x.numpy(),y.numpy())
# # plt.plot(x.numpy(),y1.numpy()... | true |
c7670bc15cc66efd8ea05fba09e2235889621794 | Python | i-spark/pytype | /pytype_extensions/__init__.py | UTF-8 | 2,454 | 3.140625 | 3 | [
"Apache-2.0",
"MIT"
] | permissive | # Lint as: python2, python3
"""Type system extensions for use with pytype."""
import typing
from typing import Text, Dict, Any, TypeVar, Callable
if typing.TYPE_CHECKING:
_GenericCallable = TypeVar('_GenericCallable', bound=Callable[..., Any])
class Decorator(object):
"""A type annotation for decorators tha... | true |
48660b049628169c998bc454f129bc7576e0ed73 | Python | sylar-ws/poker | /pokerCarlo.py | UTF-8 | 7,124 | 3.859375 | 4 | [] | no_license | """
Approximates heads-up probability of winning your poker hand using Monte Carlo.
Enter cards into main function with
"""
import itertools
import random
NUMSAMPLES = 5000
suits = {"s": "Spades", "h": "Hearts", "d": "Diamonds", "c": "Clubs"}
numbers = {"A": 14, "K": 13, "Q": 12, "J": 11, "10": 10, "9": 9, "8": 8,... | true |
7f00cde09d557d422eb517af32837a731d118899 | Python | elijabesu/ossu-cs | /1--py4e/exercises/11.a.py | UTF-8 | 496 | 3.84375 | 4 | [] | no_license | # In this assignment you will read through and parse a file with text and numbers.
# You will extract all the numbers in the file and compute the sum of the numbers.
import re
# sample data:
# fhandle = open("sources/regex_sum_42.txt")
# actual data:
fhandle = open("sources/regex_sum_925874.txt")
matches = list()
f... | true |
47e6161c23729262065bab388e25cdc44112d6e4 | Python | MHiggs13/pBlob | /Server/src/Server/State.py | UTF-8 | 270 | 2.578125 | 3 | [] | no_license |
class State():
# All the available game states
MAIN_SCREEN = "MAIN_SCREEN"
TEAM_SCREEN = "TEAM_SCREEN"
GAME_SCREEN = "GAME_SCREEN"
states = [MAIN_SCREEN,TEAM_SCREEN, GAME_SCREEN]
def __init__(self):
self.currState = self.MAIN_SCREEN | true |
63684cab7b7e32e4e90be6fca1483608ee27a558 | Python | powellb/seapy | /seapy/oa.py | UTF-8 | 4,434 | 3.03125 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
"""
oa
Objective analysis. This function will interpolate data using the
fortran routines written by Emanuelle Di Lorenzo and Bruce Cornuelle
Written by Brian Powell on 10/08/13
Copyright (c)2010--2022 University of Hawaii under the MIT-License.
"""
import numpy as np
from seapy.exte... | true |
07792c6d448ad0b252131843e4802524f8cd1468 | Python | arpitttiwari/EECS337_Project1 | /winner.py | UTF-8 | 2,479 | 2.609375 | 3 | [] | no_license | import json
import nltk
from pprint import pprint
import re
import spacy
import config
from imdb import IMDb
ia = IMDb()
import string
import helpers
def findWinner(a, t, wdict, count, winnertweets):
if a.awardtype == "movie":
y = re.findall("(\".*\") wins best",t, re.IGNORECASE)
if y and "best" not in y[0].lowe... | true |
b2bdfac9d6e1eee4d125ee6331f99807f5a3b422 | Python | cratejoy/flask-experiment | /flask_experiment/cache.py | UTF-8 | 1,659 | 2.875 | 3 | [
"MIT"
] | permissive | from flask import request
from jinja2.utils import LRUCache
class ExperimentTemplateCache(LRUCache):
def experiment_key(self, key):
# newer versions of jinja pass this key as a tuple,
# but we want the name of the jinja file, which
# is the last item in the tuple
if key and isinsta... | true |
18af2e105e9af45cbaeaf71440001c3b98de0d2d | Python | CUCEI20B/zodiaco-SaulCabello | /main.py | UTF-8 | 2,077 | 3.390625 | 3 | [] | no_license | print("los dias y meses se ingresan en numeros")
dia = int(input("Ingresa dia "))
mes = int(input("Ingresa mes "))
if dia >= 1 and dia <= 31 and mes >= 1 and mes <= 12:
print ("El signo zodiacal es: ")
#ACUARIO
if mes == 1:
if dia >= 21 and dia <=31:
print ("acuario")
elif mes == 2:
if dia >= 1 and d... | true |