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 |
|---|---|---|---|---|---|---|---|---|---|---|
f9be686223b81d2136cf061abe74f780d62de32f | martinpbarber/python-workout | /tests/chapter_02/test_exercise_05.py | UTF-8 | 511 | 3.28125 | 3 | [] | no_license | """ Test exercise_05 """
import pytest
from src.chapter_02.exercise_05 import pig_latin
def test_empty_string():
""" Verify it works with empty string """
assert pig_latin("") == ""
@pytest.mark.parametrize(
"word, expected",
[
("eat", "eatway"),
("air", "airway"),
("python"... | true |
a9c48396ac8dbda82f263887e49b914ca731e43c | oriasegal/Python_Programs | /ex05/e5q1.py | UTF-8 | 613 | 3.890625 | 4 | [] | no_license | """
Exercise 5, question 1
This program is using generators to get all the even numbers between N1 and N2 and prints N3 in a row.
"""
def genEven(N1, N2):
if N1 % 2 == 0:
start = N1
else:
start = N1 + 1
return (i for i in range(start, N2, 2))
def evenprt(N1, N2, N3):
d... | true |
c54e948005c3d46be680cdaa1b288fd1dbdc4a61 | Louis-Gabriel-TM/wf3_poo_en_python | /ch10_tp_datatypes/2_tp_lists/exo_10.31alt.py | UTF-8 | 627 | 4.0625 | 4 | [] | no_license | nb = [5, 3, 1, 5, 4, 4, 2, 3]
"""On va transformer cette liste en un ensemble, un 'set'. Il s'agit d'un type de données "built-in" au même titre que les listes ou les tuples.
Un 'set' ne comporte pas de doublon et ses éléments ne sont pas repérés par des indices. Les éléments sont considérés comme n'étant pas ordonnés... | true |
c9aff7a5fb3c42160936cdb753b62bc8e8b84b1a | kliner/leetcode | /334.py | UTF-8 | 556 | 3.359375 | 3 | [] | no_license | class Solution(object):
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
n1 = 1e100
n2 = 1e100
for n in nums:
if n > n2: return True
elif n > n1: n2 = n
else: n1 = n
return False
test = ... | true |
6aebf616b74b5324feccc76a23c3b0fa21de7d96 | openstack/rally | /tests/unit/test_test_mock.py | UTF-8 | 14,784 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | true |
a4f280dea5b58fcc8da6c83d3a166e43e4919ebc | mickvav/biotools | /marine/ec2/check_dl_progress.py | UTF-8 | 981 | 2.734375 | 3 | [] | no_license | #!/usr/bin/env python3
import subprocess
import re
from os import stat, readlink
from time import sleep
from sys import argv
if len(argv) > 1:
interval=float(argv[1])
else:
interval=5
def wget_pid_progress(pid):
stat1 = stat(f"/proc/{pid}/fd/5")
return stat1[6]
lines = subprocess.check_output('ps -A |... | true |
216dda966210dd67a8d2fb164b0a5e0717c752cf | aphexer/sewer | /sewer/auth.py | UTF-8 | 1,110 | 2.546875 | 3 | [
"MIT"
] | permissive | import logging
from .lib import create_logger
class BaseAuthProvider(object):
def __init__(self, auth_type, LOG_LEVEL="INFO"):
self.LOG_LEVEL = LOG_LEVEL
self.dns_provider_name = self.__class__.__name__
self.logger = create_logger(__name__, self.LOG_LEVEL)
self.auth_type = auth_t... | true |
1eb26949de55a274a862feaa60da4c8277f927c1 | DongxuGuo1997/TransNet | /src/dataset/trans/data.py | UTF-8 | 17,473 | 2.71875 | 3 | [
"MIT"
] | permissive | import random
from .jaad_trans import *
from .pie_trans import *
from .titan_trans import *
class TransDataset:
"""
Unified class for using data from JAAD, PIE and TITAN dataset.
"""
def __init__(self, data_paths, image_set="all", subset='default', verbose=False):
dataset = {}
assert i... | true |
8fbacecdf05b81e837cbdf95dbafb4a64c2b0f3b | aurora314156/leetcode | /Array/leetcode1035. Uncrossed Lines.py | UTF-8 | 424 | 2.71875 | 3 | [
"MIT"
] | permissive | class Solution:
def maxUncrossedLines(self, A: List[int], B: List[int]) -> int:
m = len(A)+1
n = len(B)+1
dp = [[0] * n for _ in range(m)]
for i in range(1, m):
for j in range(1, n):
if A[i-1] == B[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
... | true |
160433784336ad711c46a63629422db4eaa2b76b | lovasoa/marshmallow_dataclass | /tests/test_postdump.py | UTF-8 | 1,842 | 2.609375 | 3 | [
"MIT"
] | permissive | import typing as T
from dataclasses import field
import marshmallow as mm
import marshmallow_dataclass as mmdc
import collections.abc
import unittest
# Test from https://github.com/lovasoa/marshmallow_dataclass/issues/125
class TestPostDump(unittest.TestCase):
def setUp(self) -> None:
class BaseSchema(mm... | true |
bc23616c52d21e344dcfd3c5d7221ad03f5a7995 | lizzybrooks/python-possible | /class-notes/examples/natural-language-processing/classify.py | UTF-8 | 1,053 | 3.75 | 4 | [] | no_license | from textblob import TextBlob
from textblob.classifiers import NaiveBayesClassifier
train = [
('i am happy today', 'pos'),
('this is a good burger', 'pos'),
('you\'re a good boy', 'pos'),
('you are doing well', 'pos'),
('i do not like you', 'neg'),
("don't go there", 'neg'),
('this is ... | true |
d27d481dcf8b35c20a9af5b0b39b59f64e75d349 | MoCuishle28/deep-learning-practice | /nn-learn/keras/NLP/simple-RNN-in-keras.py | UTF-8 | 1,913 | 2.703125 | 3 | [] | no_license | from tensorflow.keras.datasets import imdb
from tensorflow.keras.preprocessing import sequence
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding, SimpleRNN
from tensorflow.keras.layers import Dense
import matplotlib.pyplot as plt
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] =... | true |
595b8a8585179efb0f19bb62520ed715a5c0b86b | ideaspaper/PythonCodes | /opencvProjects/colorSpace/colorSpace.py | UTF-8 | 1,123 | 2.71875 | 3 | [] | no_license | import os, cv2
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
_projectDirectory = os.path.dirname(__file__)
_fileName = os.path.join(_projectDirectory, "images/input/Lenna512x512.jpg")
_img = cv2.imread(_fileName, cv2.IMREAD_UNCHANGED)
_fig = plt.figure("Color Spa... | true |
d55ecb133fc08c0ecba5b02f36b8093612bf2698 | lr17951play/my-projects | /my-py-demo/io_test.py | UTF-8 | 1,365 | 2.984375 | 3 | [] | no_license | import os
age = int(input("请输入你家狗狗的年龄: "))
if age < 0:
print("你是在逗我吧!")
elif age == 1:
print("相当于 14 岁的人。")
elif age == 2:
print("相当于 22 岁的人。")
elif age > 2:
human = 22 + (age - 2) * 5
print("对应人类年龄: ", human)
# 退出提示
input("点击 enter 键退出,测试File")
try:
with open("C:/Users/Z0040FRJ/Desktop/hist... | true |
333f1700e62f85d0ba19a379bbefea02bae8e054 | thing-zoo/osp-repo | /py_lab2/my_pkg/binConvert.py | UTF-8 | 526 | 3.390625 | 3 | [] | no_license | #!/usr/bin/python
def convert2(num):
num = int('0b'+ num, 2)
print('=> OCT> ', format(num, 'o'))
print('=> DEC> ', num)
print('=> HEX> ', format(num, 'X'))
def toDec(n):
#n is string (10101110)
n = list(reversed(n))
s = int(0)
for i in range(len(n)):
s += int(n[i])*(2**i)
... | true |
ed984b6e1fa33005c764553e2f841ffe5fe35d4f | oujin/my_leetcode | /405.数字转换为十六进制数.py | UTF-8 | 486 | 3.046875 | 3 | [
"MIT"
] | permissive | #
# @lc app=leetcode.cn id=405 lang=python3
#
# [405] 数字转换为十六进制数
#
# @lc code=start
class Solution:
def toHex(self, num: int) -> str:
if num == 0:
return '0'
n2str = [str(i) for i in range(10)] + ['a', 'b', 'c', 'd', 'e', 'f']
nh = ''
while num != 0:
num, r =... | true |
ef571585b345dc974a23bbf0e0a593109ad56f4f | ricardoMondardo/Snippets | /regex/playing.py | UTF-8 | 662 | 3.96875 | 4 | [] | no_license | import re
# Have the function CodelandUsernameValidation(str) take the str parameter being passed and determine if the string is a valid username according to the following rules:
# 1. The username is between 4 and 25 characters.
# 2. It must start with a letter.
# 3. It can only contain letters, numbers, and the... | true |
69586e44996a4dc0aa4d7949dcf05b4839336a82 | zweed4u/total_min_max | /min_max_sum.py | UTF-8 | 372 | 3.421875 | 3 | [] | no_license | #!/usr/bin/python3
import sys
from typing import List
def miniMaxSum(arr: List[int]) -> str:
total = 0
min_value = sys.maxsize
max_value = 0
for number in arr:
max_value = max(number, max_value)
min_value = min(number, min_value)
total += number
return f"{total-max_value} {... | true |
b24f827145db474eca35fc37ba0d7dc16da503cc | Duttp1998/IS218Project | /Tests/test_Random.py | UTF-8 | 1,043 | 3.328125 | 3 | [] | no_license | import unittest
from Random.Elements import Elements
from Random.Lists import Lists
from Random.Numbers import Numbers
class MyTestCase(unittest.TestCase):
def test_Random_Integer_Seed(self):
self.assertEqual(9, Numbers.prandINT(1, 10, 30))
def test_Random_Float_Seed(self):
self.assertEqual(5.... | true |
c1f236fa87b80cb8f0edce1d0fde6fb4ca2d7072 | Ahmad-Magdy-Osman/IntroComputerScience | /Lists/mOsmanWkst07.py | UTF-8 | 1,521 | 4.25 | 4 | [] | no_license | ################################################################
#
# CS 150 - Worksheet #07
# Purpose: Generating random rainfall values for the year's 12
# month and storing them in a list where a variety of
# calculations are proceeded on - Practicing Lists
#
# Author: Ahmad M. Osman
# Date: November 4, 2016... | true |
d47f94d876d5d2f54089740f23774e6a0ac4d77e | DegardinJonathan/Python | /Exercice de base/Exo 8.py | UTF-8 | 275 | 3.53125 | 4 | [] | no_license | S=int(input('Saisissez une somme : '))
piècejaune50=0
piècejaune20=0
piècejaune10=0
piècemarron05=0
piècemarron02=0
piècemarron01=0
while S>0.5:
piècemarron05=piècemarron05+1
S=S-0,5
print('il vous faudra',piècemarrion05,'pièce de 0.5€')
| true |
528ad1750bac588137e9d4c15d3aa3fa8d487c29 | goyoambrosio/RobotAtHome2 | /robotathome/transition/dataset.py | UTF-8 | 120,230 | 2.515625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | #!/usr/bin/env python
# -*- coding: utf-8; buffer-read-only: t -*-
""" Robot@Home Python API """
__author__ = "Gregorio Ambrosio Cestero"
__contact__ = "gambrosio[at]uma.es"
__copyright__ = "Copyright 2020, 2021, Gregorio Ambrosio Cestero"
__date__ = "2021/02/03"
__license__ = "MIT"
import version
import os
import h... | true |
f09e38ad1b0f9c6ff52b8e001f141eeb6aff3e93 | wncowan/python2_algorithms | /SLists/main.py | UTF-8 | 2,706 | 3.71875 | 4 | [] | no_license | class SLNode(object):
def __init__(self, value):
self.val = value
self.next = None
class SList(object):
def __init__(self):
self.head = None
self.tail = None
def PrintAllVals(self):
runner = self.head
while runner != None :
print(runner.val)
... | true |
e5a4c44d5d53704fe32b3e8fec1b2e92e07e98d4 | chelseali2001/CS160-Computer-Science-Orientation | /Labs/Lab 5/turtle.py | UTF-8 | 3,854 | 2.859375 | 3 | [] | no_license | import turtle
from random import randint
import random
def drawA():
myTurtle.lt(90)
myTurtle.fd(100)
myTurtle.rt(90)
myTurtle.fd(50)
myTurtle.rt(90)
myTurtle.fd(100)
myTurtle.rt(90)
myTurtle.pu()
myTurtle.fd(50)
myTurtle.pd()
myTurtle.rt(90)
myTurtle.fd(50)
myTurtle.rt(90)
myTurtle.fd(50)
... | true |
70baad9735366ea7a4011ea878abf0732a7417ea | AnaMariaBiliciuc/Tipul-de-date-STRING | /1 string.py | UTF-8 | 65 | 3.359375 | 3 | [] | no_license | n=str(input('Introdu numele tau: '))
print('SALUT {}'.format(n)) | true |
a94f57d2221028a6385c1a8b50b2ee16efe6daf7 | vincenthanna/vh1981_library | /python/tensorflow/temp_p1/face_model.py | UTF-8 | 2,748 | 2.8125 | 3 | [] | no_license | import numpy as np
import os
import tensorflow as tf
# from tensorflow.nn import conv2d, max_pool2d
from tensorflow.keras.layers import Conv2D, MaxPool2D, Flatten, Dense
from tensorflow.nn import relu
def all_diffs(a, b):
# Returns a tensor of all combinations of a - b
print("shapes:", a.shape, b.shape)
... | true |
00aa219ab9f3b06d690cd0576f379a74f555ac15 | liyunzhi2020/3d_geometry | /depthAPI_ipad_scan/test_RGBD.py | UTF-8 | 3,947 | 2.703125 | 3 | [] | no_license | import numpy as np
import json
import cv2
import png
def create_output(vertices, colors, filename):
colors = colors.reshape(-1, 3)
vertices = np.hstack([vertices.reshape(-1, 3), colors])
np.savetxt(filename, vertices, fmt='%f %f %f %d %d %d')
ply_header = '''ply
format ascii 1.0
element ve... | true |
d63c9ebccbe81042a225485399ffd9c98746505f | ManishaHingne/ML | /apr_1/python/page3.py | UTF-8 | 4,274 | 2.53125 | 3 | [] | no_license | import urllib3
class Source:
def __init__(self, url, fileName):
self.__url = url
self.__fileName = fileName
def downloadContents(self):
http = urllib3.PoolManager()
request = http.request('GET', self.__url)
data = request.data
self.processContents(data)
... | true |
f6d0e3cfbd007dfd05ab42ed5d29704ab4c91ec4 | WizErnest/vugc1_control | /src/xjoystick.py | UTF-8 | 2,820 | 2.578125 | 3 | [] | no_license | #!/usr/bin/env python
import rospy
from vugc1_control.msg import drive_param
from vugc1_control import gamecontroller
class Xjoystick(gamecontroller.Observer):
def __init__(self):
gamecontroller.Observer.__init__(self)
self.started = False
self.max_speed = 100
self.max_angle = 100... | true |
dd557d0d35524851386a6554855499bd67bc0fad | Kromey/piroute | /helpers/utils.py | UTF-8 | 236 | 3.390625 | 3 | [
"MIT"
] | permissive |
def ip2int(ip):
ip = ip.split('.')
# Convert each octet to an integer, shift it appropriately, and sum them
ip_int = (int(ip[0]) << 24) + (int(ip[1]) << 16)
ip_int += (int(ip[2]) << 8) + int(ip[3])
return ip_int
| true |
ae4081b4ebe7af25e43bf097ec0698f942621ab2 | rafaeldmelo98/Jogo-BBB-Python | /Jogador.py | UTF-8 | 5,849 | 3.4375 | 3 | [] | no_license | import random
class JogadorPrincipal:
def __init__(self, nome, peso, altura):
self.__nome = nome
self.__peso = peso
self.__altura = altura
self.__velocidade = 0
self.__resistencia = 0
self.__sorte = random.randrange(0,100)
self.carisma = 50
@property
... | true |
8de80054b57083ab6f3e1232fc5ef907f2b879ac | Aasthaengg/IBMdataset | /Python_codes/p03775/s561261577.py | UTF-8 | 176 | 2.96875 | 3 | [] | no_license | from math import sqrt
N = int(input())
ans = 100
sq_n = int(sqrt(N))
for i in range(1, sq_n+1):
if N % i == 0:
ans = min(ans, max(len(str(i)),len(str(N//i))))
print(ans) | true |
2ab51cfc6c18f591347f0d61427f5e3a95753cf1 | cwfay4/ardx | /code/CIRC05bp-code.txt | UTF-8 | 725 | 2.765625 | 3 | [
"CC-BY-4.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # CIRC05 Shift register
import board
import adafruit_74hc595
import busio
import digitalio
import time
print("SCK " + str(board.SCK))
print("MOSI " + str(board.MOSI))
spi = busio.SPI(board.SCK, MOSI=board.MOSI)
#spi = busio.SPI(board.D3, MOSI=board.D2)
latch_pin = digitalio.DigitalInOut(board.D5)
#latch_pin = dig... | true |
8846228e9c9393344d16ef8906404df9c294a3fa | fredylagui/BitacoraW-master | /Main.py | UTF-8 | 3,858 | 2.890625 | 3 | [] | no_license | # -*- coding: utf-8 *-*
#!/usr/bin/ python
'''
Created on 19/03/2014
@author: Admin
'''
# -----------
# Librerias
# -----------
#import logging
from datetime import datetime
import pygame
from pygame.locals import *
import sys
sys.path.append("..")
# -----------
# Constantes
# -----------
# ---------------------------... | true |
f9d80448ee9774ec2fe5ff5b7ba4655773909250 | ivanbearcat/BearCatOMS_v2 | /gather_agent/plugins/disk.py | UTF-8 | 483 | 2.515625 | 3 | [] | no_license | #!python
from libs.libs import run_shell
class gather_disk(object):
# 获取磁盘信息
def start(self):
print('get disk')
data_list = []
# 获取根磁盘UUID
code, name = run_shell('lsblk |grep disk')
data = name if code == 0 else ''
for i in data.split('\n'):
... | true |
6dd1848b9262fdf2e21a5a4bcf80b88389b98c86 | beeldengeluid/beng-lod-server | /src/tests/unit_tests/apis/pong/pong_test.py | UTF-8 | 226 | 2.53125 | 3 | [
"MIT"
] | permissive | import pytest
from apis.pong.pong_api import Pong
@pytest.fixture(scope="function")
def pong():
yield Pong()
def test_init(pong):
assert isinstance(pong, Pong)
def test_get(pong):
assert pong.get() == "pong"
| true |
c0a2ce06e1886612c246f09f00ea913d32f312a6 | estherbouquet/lectura-plus | /qrcodegenerator.py | UTF-8 | 1,357 | 3.109375 | 3 | [] | no_license | import pyqrcode
import os
def createQrCode(urlstr, filenameURL):
# nouveaux réglages / L a moins de correction que le M /
url = pyqrcode.create(urlstr, 'L', 12, None, None)
url.png('./input/'+filenameURL+'.png', scale=3)
# anciens réglages :
#url = pyqrcode.create(urlstr, 'M', 10, None, None) # On crée un qrc... | true |
ffd8959d9e6535f2fb7164a6da60947d3141104c | assaforon/pycir | /pycir/cir.py | UTF-8 | 3,120 | 3.03125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Centered isotonic regression, generic but more tailored to dose-response and dose-finding data
Assaf Oron, recoded from R 'cir' package
"""
import numpy as np
import pandas as pd
def cirPAVA(y, x=None, wt=None, outx=None, interiorStrict=True, strict=False, ybounds=None, full=False, dec=F... | true |
31dbd764b0d58201e6e6d9fb6e30dec3666ae20c | sergioperez1998/ProyectoClusteringIA | /codigo/punto.py | UTF-8 | 653 | 3.09375 | 3 | [
"MIT"
] | permissive | class Punto:
def __init__(self, x=0, y=0, grado_pertenencia=[]):
self.x = x
self.y = y
self.grado_pertenencia = grado_pertenencia
def get_x(self):
return self.x
def get_y(self):
return self.y
def get_grado_pertenencia(self):
return self.grado_pertenenc... | true |
6ffc4f99b27253835039fd5127a3a797a3c32dfd | carlb15/Python | /min_operations_for_2_strings.py | UTF-8 | 2,791 | 3.78125 | 4 | [
"MIT"
] | permissive | 583. Delete Operation for Two Strings
Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same, where in each step you can delete one character in either string.
Example 1:
Input: "sea", "eat"
Output: 2
Explanation: You need one step to make "sea" to "ea" and another... | true |
f72e3b3b608d3c25fc30073375527e870be5245a | ganlanshu/leetcode | /implement_stack.py | UTF-8 | 1,420 | 3.984375 | 4 | [] | no_license | #coding=utf-8
"""
Implement Stack using Queues
"""
from collections import deque
class MyStack(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.value = deque([])
def push(self, x):
"""
Push element x onto stack.
:type x: in... | true |
0d27818d95f5e3e49da9ff332662b8016251b24f | DVS-Lab/istart | /button_test/button_box_test.py | UTF-8 | 1,719 | 2.515625 | 3 | [] | permissive | from psychopy import visual, core, event
win = visual.Window([800,600], monitor="testMonitor", units="deg")
button_box = visual.ImageStim(win, image = './buttons.jpg',size=(10,20), pos=[0,0])
index = visual.ImageStim(win, image = './index.jpg',size=(10,20), pos=[0,0])
middle = visual.ImageStim(win, image = './mid... | true |
09eef4b2230e702a44ca3c23b022e7df6c37eff5 | utkuul/Some-Projects | /Voice Assistant.py | UTF-8 | 760 | 2.890625 | 3 | [] | no_license | import speech_recognition as sr
import os
import webbrowser
r = sr.Recognizer()
with sr.Microphone() as source:
print("Benimle Konuş!")
audio = r.listen(source)
data = ""
try:
data = r.recognize_google(audio, language='tr-tr')
data = data.lower()
print("Söylenilen:" + data)
finaldata... | true |
b44768008b083a52e37df357049910046e665537 | ENGSamShamsan/Web_Scrapping | /Web_Scrapping.py | UTF-8 | 827 | 3.34375 | 3 | [] | no_license | # Web_Scrapping
# Sam Shamsan, Saturday, Aug 11, 2018
# Platfrom imported : requests, lxml and BeautifulSoup + html5lib
import requests
import lxml
from bs4 import BeautifulSoup
''' intro'''
'''This is a quick WORKING snipit for Web Scraping
It featch the html page content and print it
'''
# Get the linke to t... | true |
d6395f817c91b1ecb4e08c7e241c17464940e0c4 | Ashwinduth/Basic-Python-Topic-programs- | /Python string functions/split.py | UTF-8 | 103 | 3.171875 | 3 | [] | no_license | #splits the given string into multiple strings o/p ["hi","how","you","do"]
a="hi how you do"
a.split()
| true |
82dfc908291d5d76f9be3636601a147a1cedd2e0 | jordan-melendez/Two-Nucleon-Bayesian-Analysis | /lowlevel/calc_phase_shifts.py | UTF-8 | 12,143 | 2.84375 | 3 | [] | no_license | # A function that calculates NN phaseshifts from potential files.
import numpy as np
from numpy import array, append, matrix, zeros, identity, matlib, linalg
from numpy import cos, tan, arctan, arctan2, pi, sin, sqrt, sign, exp
from math import fsum
from itertools import product
import scipy
from scipy.interpolate imp... | true |
3a45532aecc77f319c05d6d0ad40dfb8426594a6 | lmartinho/collaborative-credit-matcher | /src/matcher_optimization.py | UTF-8 | 20,327 | 2.953125 | 3 | [] | no_license | import constraint
import itertools
import logging
import numpy as np
import time
import matcher_constraint
import matcher_utils
MAX_RATE = 10000
class MatcherSolutionGenerator(object):
"""
Generates matcher solutions for the configured problem,
according to a standard parameter specificatio... | true |
f46c920c27cdd3ce0ef71bcd5e1bdd74799ef1c9 | kasheev/weather-bot | /weather.py | UTF-8 | 5,072 | 3.03125 | 3 | [] | no_license | import vk_api
from vk_api.longpoll import VkLongPoll
import pyowm
import math
import json
owm_api = open("owm.txt","r")
own = pyowm.OWM(owm_api.read(), language='ru')
class Weather:
def __init__(self, token):
"""конструктор"""
vk_session = vk_api.VkApi(token=token)
self.longpoll = VkLongP... | true |
bcb982946e0465a3ea73d2c35fc15a68b13f83ed | lkaihua/clay | /MinHeap.py | UTF-8 | 2,076 | 3.5625 | 4 | [] | no_license |
import sys
class MinHeap:
def __init__(self, maxSize):
# init arr to store elements
self.arr = [None for x in range(maxSize + 1)]
self.size = 0
self.arr[0] = -sys.maxint
def parent(self, pos):
return pos//2
def leftChild(self, pos):
return 2*pos
def r... | true |
eb5d5a9c2b2764decf330b9cd8ad92779c370fd3 | JSeam2/Schrodinger-Assignment | /Code/Week2.py | UTF-8 | 3,203 | 3.359375 | 3 | [
"MIT"
] | permissive | from __future__ import print_function
import numpy as np
import unittest
import scipy.constants as c
"""
Testing Framework with unittest
"""
class codeTester(unittest.TestCase):
def test_qn1(self):
self.assertEqual(energy_n(1), -13.60569)
self.assertEqual(energy_n(2), -3.40142)
self.assertE... | true |
fb750e6e1b6eed8d66db7d08f7e138c157ead801 | SimmonsRitchie/scraper-pa-hcsis-inspections | /hcsis/tests/test_data_integrity/test_data_integrity.py | UTF-8 | 11,868 | 2.984375 | 3 | [
"MIT"
] | permissive | import unittest
import pandas as pd
import numpy as np
from pathlib import Path
import logging
from logging import StreamHandler
import re
root_logger = logging.getLogger()
root_logger.setLevel(logging.DEBUG)
# stream handler
stream_log = StreamHandler()
root_logger.addHandler(stream_log)
def trim_and_upper(list_of_t... | true |
df817e7835d1bbbcc012363a2cb7555ec993b6dd | Thor77/AdventOfCode2015 | /day09.py | UTF-8 | 982 | 3.5 | 4 | [] | no_license | from itertools import permutations
def parse_line(line):
cities, distance = line.split(' = ')
city1, city2 = cities.split(' to ')
return ((city1, city2), distance)
def route_distance(graph, route):
distance = 0
for index, city in enumerate(route):
if len(permutation) > index + 1:
... | true |
cdd8e912c9778d7472041a2953fdff4011cc366d | bennydai/rvss_fork | /Triangulate.py | UTF-8 | 852 | 3.0625 | 3 | [] | no_license | import numpy as np
def eta(alpha):
return np.mat([
[-np.sin(alpha)],
[np.cos(alpha)]
])
def rpk(theta):
return np.mat([
[np.cos(theta), -np.sin(theta)],
[np.sin(theta), np.cos(theta)]
])
def triangulate(meas):
#Measurement is of the format list of [x,y,theta,alpha... | true |
d73ea879d18d03ea1cb74782a3e1203123787423 | Trapman/trading | /portfolio_optimization.py | UTF-8 | 4,603 | 3.21875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 21 11:10:40 2020
@author: das68451
"""
# import libraries
import pandas_datareader as web
import pandas as pd
import numpy as np
# test scrape stock data on Tesla
TSLA_quote = web.DataReader('TSLA', data_source = 'yahoo', start = '2010-01-01', end = '2020-08-20')
print... | true |
d2046ef58b4cb987fe08b47bb176cc0f9b175fbd | nikkisora/cses_problemset | /5 Range Queries/13 Subarray Sum Queries.py | UTF-8 | 899 | 3.9375 | 4 | [] | no_license | '''
CSES - Subarray Sum Queries
Time limit: 1.00 s
Memory limit: 512 MB
There is an array consisting of n integers. Some values of the array will be updated, and after each update, your task is to report the maximum subarray sum in the array.
Input
The first input line contains integers n and m: t... | true |
4e9fbd3c878775dca182c4e00cb018643104fcbb | HediaTnani/rosalind.info | /bioinformatics_stronghold/tree.py | UTF-8 | 406 | 2.953125 | 3 | [] | no_license | #!/usr/bin/env python
from igraph import *
n = False
g = Graph()
edges = []
with open('files/rosalind_tree.txt', 'r') as fi:
for line in fi:
if not n:
n = int(line.strip())
g.add_vertices(n+1)
else:
edges.append([int(x) for x in line.strip().split()])
g.add_edge... | true |
fa7037fdde3d75994ed8c684992842060982b5f9 | robcowan/panwdbl | /address.py | UTF-8 | 4,871 | 2.5625 | 3 | [
"ISC"
] | permissive | #
# Copyright (c) 2013-2015 Luigi Mori <l@isidora.org>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND TH... | true |
6d5f3131796b0d6a7ed86c1dbaadd9d436cf1c54 | renmarin/django_restaurants | /serializers.py | UTF-8 | 1,564 | 2.8125 | 3 | [
"MIT"
] | permissive | from rest_framework import serializers
from .models import Restaurant, MenuItem
class RestaurantsSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
name = serializers.CharField(max_length=200)
def create(self, validated_data):
return MenuItem.objects.create(**valida... | true |
2cb6498ca595ad1c4910df71ba6658bf0c55c1b8 | dsri19/trunk | /cmake/write_ref.py | UTF-8 | 1,012 | 2.5625 | 3 | [] | no_license | #!/usr/bin/python
import os
import sys
import fnmatch
def main():
oldref = sys.argv[1]
newref = sys.argv[2]
version_filename = sys.argv[3]
# if old and new ref are the same, the user was probably just messing
# around with something. I will not write a new tree Version file
# unless it doesn't exist yet.
i... | true |
ade1326dc6da8d2061c4f14a5dc3ac7994566309 | JinJiangHuang/house-price-monitor | /spider/lib/spider/rent_spider.py | UTF-8 | 9,127 | 2.859375 | 3 | [
"Apache-2.0"
] | permissive | #!/usr/bin/env python
# coding=utf-8
# 爬取租房数据的爬虫派生类
import re
from decimal import Decimal
import pymysql
import threadpool
from bs4 import BeautifulSoup
from lib.item.rent import *
from lib.spider.base_spider import *
from lib.utility.date import *
from lib.utility.log import logger
from lib.zone.area import *
from l... | true |
6d587e5ecdd167868dc94659e04a2f74da6a9131 | War-Keeper/ScheduleBot | /test/test_displayFreetime.py | UTF-8 | 3,084 | 2.65625 | 3 | [
"MIT"
] | permissive | import os
import sys
from datetime import datetime
import discord
import discord.ext.commands as commands
import discord.ext.test as test
import pytest
from Event import Event
from functionality.DisplayFreeTime import compute_free_time, get_free_time
from functionality.shared_functions import create_event_tree, add_ev... | true |
cb49f05f7110449dea988798959c13ed62c085a5 | ymattsun/Advanced-NLP | /5_047_set_program.py | UTF-8 | 2,117 | 2.640625 | 3 | [] | no_license | #!/usr/bin/env python
# coding: utf-8
import sys, re, optparse
parser = optparse.OptionParser()
parser.add_option('-a', '--verb', action = 'store_true', help = '5_042_verb', default = False)
parser.add_option('-b', '--vbase', action = 'store_true', help = '5_043_verb_base', default = False)
parser.add_opt... | true |
3b0303e1fa86dc7a6e18b3289d525413859fb184 | danielmichaels/word | /word/word_main.py | UTF-8 | 2,729 | 2.59375 | 3 | [
"MIT"
] | permissive | import configparser
import os
import click
import requests
from exceptions import UnauthorizedError, AuthenticationError, \
InternalServerError, BadGatewayError, ServiceUnavailableError
from output import thesaurus_printer, definition
class Word:
config = configparser.ConfigParser()
config.read(os.path.... | true |
5dc1553d894d91a94e07764046062d4799df0694 | linyu3294/elastic-search-indexing-script | /kl_sum.py | UTF-8 | 2,310 | 2.953125 | 3 | [
"MIT"
] | permissive | from sklearn.feature_extraction.text import TfidfVectorizer
import nltk
import math
class KLSum:
vectorizer = TfidfVectorizer(sublinear_tf=True, stop_words='english')
def __init__(self):
nltk.download('punkt')
def kl_summarize(self, doc_data, num_of_sentences):
summaries = []
for... | true |
31d35862cc25f228c3158ae8a00abe99235f9f73 | SIGSTACKFAULT/shipCostCalc | /scripts/eveConsts.py | UTF-8 | 1,505 | 2.765625 | 3 | [
"MIT"
] | permissive | pcIndex = 1 # This acts as an index for parts and a starting point for count
partIndex = 2 # This acts as an index for parts when it is referenced to with an index of 2
oreList = [
'Tritanium',
'Pyerite',
'Isogen',
'Megacyte',
'Mexallon',
'No... | true |
306b0d56a7070ae64bb4405c6101f6788a98834e | rbarkerappen/test_AudioServer | /utils/AudioServerRequest.py | UTF-8 | 2,264 | 2.734375 | 3 | [] | no_license | #!/usr/bin/env python
import copy
import os
import simplejson
import urllib2
from itsdangerous import URLSafeSerializer
from HeaderSpec import HeaderSpec
class AudioServerRequest(object):
"""
Builds a client request for the audio server.
"""
SECRET_KEY = os.environ.get("AUDIO_SERVER_SECRET_KEY")
def __init__(... | true |
faaa2aeb2a54d9b04a0aa57aa69328fb5945a445 | kubousky/abalone-data-analysis | /abalone.py | UTF-8 | 2,508 | 3.328125 | 3 | [] | no_license | import numpy as np
import pandas as pd
import datapackage
data_url = 'https://datahub.io/machine-learning/abalone/datapackage.json'
# to load Data Package into storage
package = datapackage.Package(data_url)
# to load only tabular data
resources = package.resources
for resource in resources:
if resource.tabular... | true |
198f6c9553185032af949535ebf271dd4f831390 | Tipwheal/PyYacc | /ProgramWriter.py | UTF-8 | 1,232 | 2.75 | 3 | [] | no_license | from ParsingTable import ParsingTable
from SyntaxSaver import SyntaxSaver
# writer will get the parsing table from previous part of the program,
# and attach some important data structures to "ParserTemplate.py"
# to generate the final SyntaxAnalyzer.
class Writer(object):
@staticmethod
# this method read th... | true |
7fe5963e4dc45af19a16ff5d9deb9fdc263fba73 | ShigeruIchinoki/pythonkadai | /py/sumsq.py | UTF-8 | 175 | 3.421875 | 3 | [] | no_license | #!/usr/bin/python
sum = 0
for i in [1,2,3,4,5,6,7,8,9,10]:
sum = sum + i**2
print i, sum
sum1 = 0
for i in range(1,11):
sum1 = sum1 + i**2
print i, sum1
| true |
d606629a824eed77f0f985ed01ea6e9fd6da99f9 | Do-code-ing/Python_Built-ins | /Functions/sorted.py | UTF-8 | 1,141 | 4.5625 | 5 | [] | no_license | # sorted(iterable, *, key=None, reverse=False)
# iterable의 항목들을 정렬하여 새 sorted list로 반환한다.
# key : str.lower과 같은 elements를 비교하는 함수를 제공하면 된다.
# (해당 함수의 비교법을 가져와서 쓴다.)
# reverse : True인 경우 반대로 정렬한다.
# 급여를 등급별로 나눠서 주기위해 부서별로, 직급별로, 등 여러번 정렬할 때 유용하다.
# 정렬해보자
lst = ["a", "b", "A", "B"]
sorted_a = sorted(lst)
print(sor... | true |
855c5971da68ab839f0c976ee7f59f600d578a12 | CrypticCalamari/Practice | /2016_11_06/mergesort/mergesort.py | UTF-8 | 651 | 3.140625 | 3 | [] | no_license | #!/usr/bin/python3
import random, sys, time
def merge(left, right):
i = 0
j = 0
m = []
while i < len(left) and j < len(right):
if left[i] <= right[j]:
m.append(left[i])
i += 1
else:
m.append(right[j])
j += 1
m += left[i:]
m += right[j:]
return m
def mergesort(a):
if len(a) <= 1:
return a
m... | true |
7e19e2d7305a33dc4bffeaa46fcfc6c7193b8815 | anderscui/spyders | /store_sqlite/exists.py | UTF-8 | 295 | 3.078125 | 3 | [] | no_license | import sqlite3 as sqlite
con = sqlite.connect('test.db')
with con:
cur = con.cursor()
car_id = 11
car_price = 21000
cur.execute('SELECT EXISTS(SELECT 1 FROM Cars WHERE Id = ?)', (car_id,))
if cur.fetchone()[0]:
print('Found')
else:
print('Not Found') | true |
846ce9eb9cda216147a6d097a12e758baa42d877 | sdblepas/exl_feed_ctl | /exl_feed_ctl.py | UTF-8 | 1,261 | 2.75 | 3 | [] | no_license | import json
import sys
from urllib.request import urlopen
url = "http://sd-99892.dedibox.fr:5555/exl_hands_on_lab/feeds.json"
def mapFeed(feed):
if str(feed['id']) == str(id):
feed[field_name] = field_value
return feed
else:
return feed
method = sys.argv[1]
if method == 'list':
... | true |
f83cd49afc3ac95579e8a066df367df31f2f4d39 | xin-wang-kr/Web-Scraping-Application-for-Yelp | /word_cloud.py | UTF-8 | 981 | 3.421875 | 3 | [] | no_license | #Word Cloud - show the words appear in different color and
#size according to the appeared frequency of each word.
from urllib.request import urlopen
from bs4 import BeautifulSoup
import requests
import operator
import os
import matplotlib.pyplot as plt
from wordcloud import WordCloud
import re
def start(url):
wo... | true |
6db1300eef2d9bec82675c4e919699b1362df2ce | ValeriaMaya/ComputacionII | /hkr-8/banco.py | UTF-8 | 3,922 | 3.03125 | 3 | [] | no_license | import datetime
x = datetime.datetime.now()
movimientos = [[(01, 01, 2004), 123, 500, 'Deposito'],[(01, 01, 2004), 800, 2, 'Extraccion'],[(01, 02, 2004), 124, 600, 'Deposito'],[(01, 02, 2004), 125, 5060, 'Deposito'],[(01, 02, 2004), 123, 8000, 'Extraccion'],[(01, 06, 2004), 123, 500, 'Deposito'],[(01, 01, 2014), 126,... | true |
eaffa31478e8c9d7a797baf65aa4b3429a6a0070 | delorenzo/advent2018 | /src/Day1/day1-b.py | UTF-8 | 523 | 3.1875 | 3 | [] | no_license | #!/usr/bin/env python
import re
import sys
input = open("input.txt", "rb")
output = 0
dict = {}
regex = r"^.*([+-])(\d+).*$"
first = True
while True:
for line in input:
match = re.search(regex, line)
print match.group(1) + match.group(2)
if match.group(1) == "+":
output = output + int(match.group(2))
else:... | true |
b25bfd45a4f94a2d3272f3c99355add1e2afd52b | Average-stu/Learrning-Python | /LikeBot/Instagram.py | UTF-8 | 3,827 | 3.015625 | 3 | [] | no_license | from selenium import webdriver
from time import sleep
from secrets import pw
from selenium.webdriver.common.keys import Keys
from random import randint
class Bot():
links = []
comments = [
'Great Post!', 'Awesome!'
]
accounts = [
'google', 'twitter', 'googledevs'
]
def __in... | true |
34fa8c6d9ab55904f3eef427965341da8aad6fb3 | chaconcarlos/udacity-data-structures-algorithms | /3-basic-algorithms/project/rearrange-array-digits.py | UTF-8 | 2,275 | 4.125 | 4 | [] | no_license | def sorted_merge(left, right):
merged = []
left_index = 0
right_index = 0
# Move through the lists until we have exhausted one
while left_index < len(left) and right_index < len(right):
# If left's item is larger, append right's item
# and increment the index
if left[l... | true |
6254f48d682a0ae44139994fc8d4b4e6823caea3 | kiyosumaeda/ReinforcementLearningTutorial | /FrozenLake/FrozenLakeEnvironment.py | UTF-8 | 1,537 | 2.703125 | 3 | [] | no_license | import gym
from FrozenLakeAgent import Agent
ENV = 'FrozenLake-v0'
MAX_STEPS = 100
NUM_EPISODES = 10000
class Environment:
def __init__(self):
self.env = gym.make(ENV)
# self.num_states = self.env.observation_space.shape[0]
self.num_states = 1
self.num_actions = self.env.action_space.n
self.agent = Agent(... | true |
a0ab663b12b07f52ce21c87acb9b7ecfa484747b | blackinv1/bom_climate_history | /src/elastic/elasticsearch_client.py | UTF-8 | 1,896 | 2.671875 | 3 | [] | no_license | from elasticsearch_dsl import connections, Search
from elasticsearch_dsl.response import Hit
from elasticsearch.helpers import bulk
import os
class ESConfig(object):
def __init__(self, cloud_id, username, password, timeout):
self.cloud_id = cloud_id
self.username = username
self.password ... | true |
b6180d6dda4f8f3771f069ae847dbeab6912ee7e | TIgorini/Python-studying | /lab3/lab3.py | UTF-8 | 1,993 | 2.875 | 3 | [] | no_license | import nltk
import re
import matplotlib
from pymongo import MongoClient
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.tokenize import word_tokenize
from nltk.corpus import wordnet as wn
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
from wordcloud import WordC... | true |
bcf817581b3594ff98921909809e6318f34d69aa | GMwang550146647/network | /1.networkProgramming/2.parallelProgramming/1.multiProcess/2.customizeMultiProcessing.py | UTF-8 | 685 | 2.734375 | 3 | [] | no_license | import os
import time
from multiprocessing import Process,Queue
"""
自定义 进程类
"""
class MyProcess(Process):
def __init__(self, argv):
super().__init__()
self.argv = argv
self.q=Queue()
def run(self):
time.sleep(1)
print("ppid:{}\tpid:{}\tparams:{}".format(os.getppid(), os... | true |
10d01135afac19635989d58e558d8596a105a257 | Dukemegaman/python_repo | /Algorithms/6. Работа с динамической памятью/task_1.py | UTF-8 | 5,511 | 3.328125 | 3 | [] | no_license | """
Задание 1.
Выполните профилирование памяти в скриптах
Проанализировать результат и определить программы с
наиболее эффективным использованием памяти.
Примечание: Для анализа возьмите любые 3-5 ваших РАЗНЫХ скриптов!
(хотя бы 3 разных для получения оценки отл).
На каждый скрипт вы должны сделать как минимум по две... | true |
a14d56b2f107565a13742e465c8bc3240df70a8e | Neocryan/optim | /test.py | UTF-8 | 7,067 | 3.1875 | 3 | [] | no_license | import numpy as np
import pandas as pd
import scipy.optimize as optim
import logging
import pickle
# Load price data
data = pickle.load(open('sample.pkl', 'rb')) # a list of ten years data, each year is a list of floats.
logging.basicConfig(level=logging.INFO)
#### functions:
def pfe(close, lookback):
"""
... | true |
8db891bf3b5fb51d011973f559bf761e060ab36d | snprpc/R_Interpreter | /snprpc/function/Rmath.py | UTF-8 | 4,974 | 3.15625 | 3 | [] | no_license |
import numpy as np
class Rmath:
##############
#函数列表
##############
Function = {
'sum':'Rsum',
'prod':'Rprod',
'max':'Rmax',
'min':'Rmin',
'mean':'Rmean',
'median':'Rmedian',
'std':'Rstd',
'var':'Rvar',
'sort':'Rsort... | true |
236b98e128a3aa29418aaf87a03f31414923541f | HishamKhalil1990/data-structures-and-algorithms | /python/code_challenges/graph/graph.py | UTF-8 | 4,798 | 3.671875 | 4 | [
"MIT"
] | permissive | from collections import deque
class Vertex:
def __init__(self,value):
self.value = value
def __str__(self):
return f"{self.value}"
class Edge:
def __init__(self,vertex,weight):
self.vertex = vertex
self.weight = weight
class Queue():
def __init__(self):
sel... | true |
08a37b06fcea0e9ee41af635f516e942f2f9064d | Masud2017/imagedownloader | /src/GoogleDownloader.py | UTF-8 | 3,055 | 2.65625 | 3 | [] | no_license | from pandas.core.base import DataError
from .CsvDataRecorderSingleton import CsvDataRecorderSingleton
from .Environment import Environmet
import requests
from bs4 import BeautifulSoup
import os
import logging
import requests
import re
import random
from multiprocessing import Process, Lock, cpu_count # This is the mir... | true |
91ae697c382c415db0a0c71463c5de59dfbe1f2f | blekinge/alpha-zero-general | /alpha_zero/NeuralNet.py | UTF-8 | 1,686 | 3.109375 | 3 | [
"MIT"
] | permissive | from typing import List, Tuple
import numpy as np
from alpha_zero.Board import Board
class NeuralNet():
"""
This class specifies the base NeuralNet class. To define your own neural
network, subclass this class and implement the functions below. The neural
network does not consider the current player... | true |
e8b72d4472798b153f3d36d6f4f22896db62e097 | rgkaufmann/PythonCodes | /PokemonGo/DataHandler.py | UTF-8 | 2,079 | 2.9375 | 3 | [] | no_license | import numpy as np
import math
class DataHandler:
def __init__(self):
self.dataset = np.array([])
self.file = ''
def checkdata(self, types):
if 'BaseStats' in self.file:
for pokemon in self.dataset:
print(str(pokemon["Name"])[2:-1])
if int(... | true |
da1e7a5c1ce88d0e0159fad128efa9e281108b7d | giahieu01/giahieu01 | /b10c7.py | UTF-8 | 235 | 3.3125 | 3 | [] | no_license | def longest_word(filename):
with open(filename,'r') as infile:
words=infile.read().split()
max_len=len(max(words,key=len))
return[word for word in words if len(word)==max_len]
print(longest_word('cau10.txt'))
| true |
99d9c93506fedd083c447e0cdb5512c8ff405507 | mrenoon/datafreezethaw | /RoBO/robo/models/base_model.py | UTF-8 | 2,131 | 3.3125 | 3 | [
"BSD-3-Clause"
] | permissive |
import numpy as np
class BaseModel(object):
"""
Abstract base class for all models
"""
def __init__(self, *args, **kwargs):
self.X = None
self.Y = None
def train(self, X, Y):
"""
Trains the model on the provided data.
Parameters
----... | true |
12d877206da8175bf1019a89a8162e91d038fe20 | shengqi158/bandit | /bandit/core/result_store.py | UTF-8 | 17,353 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | # -*- coding:utf-8 -*-
#
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unl... | true |
7752000e3d36ad80a8fdbd5184ee7fd879173a50 | nerooooooz/521project-Paraphrase-Identification | /main.py | UTF-8 | 6,997 | 3.09375 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 23 23:16:29 2019
@author: Cassie
"""
import argparse
import numpy as np
from nltk.translate import nist_score, bleu_score
from nltk.metrics.distance import edit_distance
from nltk import word_tokenize
from difflib import SequenceMatcher
from sklearn... | true |
41a99f68e3e7c4d9cf003fd8d63e0ef4bff5dad1 | moon0331/baekjoon_solution | /programmers/고득점 Kit/소수찾기.py | UTF-8 | 755 | 3.59375 | 4 | [] | no_license | from itertools import permutations
import math
def isPrime(x):
if x == 1 or x == 0: return False
sqrt_x = int(math.sqrt(x))
for i in range(2, sqrt_x+1):
if x % i == 0:
return False
return True
def calNumOfPrime(numbers, l, already_checked):
n_prime = 0
for num_tuple in perm... | true |
38efe01db38caa1f5682e8a41b37b57743bd16ad | liuhua4451/HelloWorld | /helloworld.py | UTF-8 | 1,734 | 3.4375 | 3 | [] | no_license | #!D:\Python27
def fib(n):
"""return a list of Fibonacci series
A list of Fibonacci series.
"""
a,b=0,1
rs=[];
while a<n:
rs.append(a)
a,b=b,a+b
return rs
print fib(100);
def readbooks(**books):
for bkName in sorted(books.keys()):
print bkName,books[bkName]
readbooks(h="hadoop",b="bigdata")
args=[4,... | true |
3c9edb366c53d8c31fa563d7de13901d08a52692 | roo-gar/blackjack-ia | /blackjack/testing/fishtest.py | UTF-8 | 479 | 3.53125 | 4 | [] | no_license | """ Script that tests the Fisher-Yates shuffling algorithm. """
import random
deck = range(1, 4)
combos = {(3, 1, 2): 0, (3, 2, 1): 0, (2, 3, 1): 0, (2, 1, 3): 0, (1, 2, 3): 0, (1, 3, 2): 0}
n = 2
loop = 1
while loop <= 600000:
while n >= 0:
k = random.randint(0, n)
deck[k], deck[... | true |
401271935403bc1b2024bbcbed8de8c5a08a1584 | domingomartinezstem/QC | /Qubit Transformations (Matrices using Python).py | UTF-8 | 3,841 | 3.734375 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 18 16:52:19 2019
@author: domin
"""
import numpy as np
from numpy.linalg import inv
#Assignment: Hermitian Matrices using Python
def twobytwo(a, b, c, d):
#MatrixInv= (1/(a*d - c*b))*np.array([[a, -b],[-c, d]])
Matrix = np.matrix([[a, b],[c, d]])
... | true |
0212c47045657a84900f7da14bb7725566a421dd | trinketapp/skulpt | /test/unit3/test_dict.py | UTF-8 | 6,478 | 3.109375 | 3 | [
"MIT",
"Python-2.0"
] | permissive | import unittest
'''
source: https://bitbucket.org/pypy/pypy/src/d7777f2ccd3f0c1a4720d5e6fc3c6b8da4547ea7/lib-python/2.7/test/test_dict.py?at=default
'''
class DictTest(unittest.TestCase):
def test_constructor(self):
# calling built-in types without argument must return empty
self.assertEqual(di... | true |
aea6f74d7b9f1b39243cb8cd5b3c4d9693207a8e | abhinavrungta/Yelp-Challenge | /visualization/business_avg_rating_vs_avg_checkins.py | UTF-8 | 1,150 | 2.578125 | 3 | [] | no_license | # run this code in zeppelin
%pyspark
checkin_file="/home/yogesh/datascience/project/yelp/yelp_dataset_challenge_academic_dataset/yelp_academic_dataset_checkin.json"
checkin_df = sqlContext.read.json(checkin_file)
checkin_df.registerTempTable("checkin")
%pyspark
from pyspark.sql.functions import UserDefinedFunction
f... | true |
ee8db8fb2bbecedc89a50e9b307d3204a1e7f12c | timonwong/sxsdiff | /examples/sxsdiff_example.py | UTF-8 | 1,127 | 2.515625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import codecs
import sys
import six
from sxsdiff import DiffCalculator
from sxsdiff.generators.github import GitHubStyledGenerator
_BOMDICT = {
codecs.BOM_UTF8: 'UTF-8',
codecs.BOM_UTF16_LE: 'UTF-16LE',
codecs.BOM_UTF16_BE: 'UTF-16BE',
}
def readfile_unicode(filename):
with ... | true |