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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
d6e7b0cf941632dee22d801ee41360d7d50d3859 | Python | nishiyamayo/atcoder-practice | /src/main/scala/past004/F.py | UTF-8 | 478 | 3.1875 | 3 | [] | no_license |
N, K = map(int, input().split())
K -= 1
d = dict()
for i in range(N):
S = input()
d[S] = d.get(S, 0) + 1
l = d.items()
l = sorted(l, key=lambda x:x[1], reverse=True)
if len(l) == 1 and K == 0:
print(l[K][0])
elif K == 0:
print(l[K][0] if l[K + 1][1] != l[K][1] else "AMBIGUOUS")
elif K == len(l) - 1:... | true |
ac59234e19a555b6fa62a6056ccb1f281abf89c5 | Python | joeyqzhou/recommendation-system | /cf_to_predict_rating.py | UTF-8 | 3,638 | 2.96875 | 3 | [] | no_license | '''
Created on Nov 1, 2015
@author: joey
'''
import random
import numpy as np
import math
import data_preparation as dp
def userSimilarityRating(data):
#Build the inverse table:
#item_users(key:item,value:{user,rating_user_have give the item})
item_users = dict()
for useri , items_rating in data.it... | true |
cef179ae95ea3db91c8de4110f00dc19f402892c | Python | markok20/twitter-toolbox | /twitter_nlp_toolkit/tweet_sentiment_classifier/models/lstm_models.py | UTF-8 | 49,344 | 2.53125 | 3 | [
"MIT"
] | permissive | from zipfile import ZipFile
from twitter_nlp_toolkit.file_fetcher import file_fetcher
from ..tweet_sentiment_classifier import Classifier, tokenizer_filter
import os
import json
import pickle as pkl
import numpy as np
import tensorflow as tf
from tensorflow.keras.preprocessing.sequence import pad_sequences
from ten... | true |
85c9b6a16f4355018f66651b8df4c52276be3379 | Python | dlondonmedina/Everyday-Coding | /week2/homework/Player.py | UTF-8 | 344 | 3.109375 | 3 | [] | no_license | class Player:
def __init__(self, id, token):
self.id = id
self.token = token
self.wins = 0
self.rows = [0, 0, 0]
self.cols = [0, 0, 0]
self.diags = [0, 0]
def get_token(self):
return self.token
def add_win(self):
self.wins += 1
def get_wins(self):... | true |
dbc422532dc17527363cd20c1b25235c27694ddf | Python | Aasthaengg/IBMdataset | /Python_codes/p02257/s884997944.py | UTF-8 | 390 | 3.078125 | 3 | [] | no_license | N = int(input())
a = [int(input()) for x in range(N)]
import math
cnt = 0
for i in range(N) :
cnt += 1
if a[i] == 2 :
continue
else :
for j in range(2, int(math.sqrt(a[i])) + 1) :
if a[i] % 2 == 0 :
cnt -= 1
break
if a[i] % j == 0 :
... | true |
39b49022b06282570c724ac6e8e18af401cfd524 | Python | codermoji-contrib/python | /start/Intro to Dicts/printdict/printval4.py | UTF-8 | 123 | 2.765625 | 3 | [
"MIT"
] | permissive | age = dict(tom=23, jane=32, mike=27, linda=25)
print(age['mike'])
print(age['linda'])
print(age['jane'])
print(age['tom'])
| true |
89bec2dac4eca41d758985b85e3a155b52439b3e | Python | OaklandPeters/abf | /abf/test_abf.py | UTF-8 | 5,851 | 3.015625 | 3 | [
"MIT"
] | permissive | from __future__ import absolute_import
import unittest
import types
import abc
if __name__ == "__main__":
import sys
sys.path.append('..')
from abf.meta import *
from abf.error import *
else:
from .meta import *
from .error import *
class TestMyProcessing(unittest.TestCase):
class MyProces... | true |
ecc139d202672de8a994b48e7258344bb46b4a07 | Python | A-Schmid/python-audio-tutorial | /mido/midi_device.py | UTF-8 | 575 | 3.15625 | 3 | [] | no_license | import mido
# list of all available MIDI input devices
inputs = mido.get_input_names()
# let user select a device
counter = 0
for device in inputs:
print(f'[{counter}] {device}')
counter += 1
selection = input('select device: ')
try:
# listen to input from selected device and print MIDI messages
wit... | true |
f3c5350ae8ad234f3ef3fdcb9722ee858fe71015 | Python | fulder/python-httpsig | /httpsig/tests/test_verify.py | UTF-8 | 12,473 | 2.671875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
import sys
import os
import unittest
from httpsig.sign import HeaderSigner, Signer
from httpsig.sign_algorithms import PSS
from httpsig.verify import HeaderVerifier, Verifier
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
class BaseTestCase(unittest.TestCase):
def _pars... | true |
84ce930d03cf753f40aa0028b7f88c188d893a7c | Python | r4mi4/Algorithm | /two_sum.py | UTF-8 | 358 | 3.953125 | 4 | [] | no_license | """
two sum:
[2,7,11,15], 18 => [1,2]
"""
def two_sum(numbers,target):
p1 = 0
p2 = len(numbers) - 1
while p1 < p2:
print(p1,p2)
s = numbers[p1] + numbers[p2]
if s == target:
return [p1,p2]
elif s > target:
p2 -=1
else:
... | true |
a78e11a2bfe378a3b25c139696cef545dedc63ad | Python | Junghwan-brian/web-programming | /Web-Scrapper/main.py | UTF-8 | 487 | 2.59375 | 3 | [] | no_license | #%%
import requests
from bs4 import BeautifulSoup
import pandas as pd
import sys
sys.path
#%%
# stackoveflow와 indeed를 'C:\\Users\\brian\\Anaconda3\\envs\\WebProgramming\\lib\\site-packages'
# 폴더안에 넣어주고 사용했다.
import stackoverflow
import indeed
# %%
stackoverflow_job = stackoverflow.get_so_jobs()
indeed_job = indeed.ge... | true |
5392b17de6e8767ba5506cf21447618c7b243445 | Python | walkccc/LeetCode | /solutions/0249. Group Shifted Strings/0249.py | UTF-8 | 471 | 3.234375 | 3 | [
"MIT"
] | permissive | class Solution:
def groupStrings(self, strings: List[str]) -> List[List[str]]:
keyToStrings = collections.defaultdict(list)
# 'abc' . '11' because diff(a, b) = 1 and diff(b, c) = 1
def getKey(s: str) -> str:
key = ''
for i in range(1, len(s)):
diff = (ord(s[i]) - ord(s[i - 1]) + 26) ... | true |
db062c7f0a3964f838bac52eab65bc23a2ff53d3 | Python | EwersLabUWyo/TREES_Py_R | /Python3_Version/scripts/TREES_GUI.py | UTF-8 | 2,380 | 2.59375 | 3 | [] | no_license | # Written by Matt Cook
# Created July 8, 2016
# mattheworion.cook@gmail.com
import os.path
import pickle
import tkinter
import TREES_utils as utils
class MainMenu(object):
def __init__(self):
root = self.root = tkinter.Tk()
root.title('Welcome to the TREES Graphical User Interface')
... | true |
65649364f555ee7c03489b072721dfe2bf823181 | Python | zhaolijian/suanfa | /leetcode/1011.py | UTF-8 | 1,319 | 3.671875 | 4 | [] | no_license | # 传送带上的包裹必须在 D 天内从一个港口运送到另一个港口。
# 传送带上的第 i 个包裹的重量为 weights[i]。每一天,我们都会按给出重量的顺序往传送带上装载包裹。我们装载的重量不会超过船的最大运载重量。
# 返回能在 D 天内将传送带上的所有包裹送达的船的最低运载能力。
class Solution:
def shipWithinDays(self, weights, D: int) -> int:
max_weight = max(weights)
length = len(weights)
# 平均每艘船运的货物数量
temp = leng... | true |
a80280d6377ac1b5bce4091736203558ad2ea879 | Python | mykhaly/ucu | /computer_vision/HW4/helper.py | UTF-8 | 1,430 | 2.96875 | 3 | [] | no_license | import itertools as it
import numpy as np
def get_homography(source, destination):
h = np.zeros((source.size, 9))
for idx, ((x_src, y_src), (x_dest, y_dest)) in enumerate(zip(source, destination)):
row_idx = idx * 2
h[row_idx][0:3] = np.array([-x_src, -y_src, -1])
h[row_idx][6:9] = n... | true |
00f2cc8a2cc9bcf125175d33bfce8765e09cb9fe | Python | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_1/Witzy/A.py | UTF-8 | 855 | 2.921875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
created by huash at 2016/4/9 08:32
"""
__author__ = 'huash'
import sys
import os
import datetime
import functools
import itertools
import collections
def getDigits(num):
result = set()
while num > 0:
result.add(num % 10)
num /= 10
return ... | true |
541a36fb793ac61107e9e8361317487167142204 | Python | ksielemann/QUOD | /variance_in_repl_test.py | UTF-8 | 5,567 | 2.609375 | 3 | [
"BSD-3-Clause"
] | permissive | ### Katharina Sielemann ###
### kfrey@cebitec.uni-bielefeld.de ###
### v1 ###
#prior to this analysis: run QUOD.py for the (I) whole dataset including all accessions and (II) the replicate dataset of the same accession
#imports
import os, glob, sys
from argparse import ArgumentParser
import scipy.stats
import numpy ... | true |
d4a4663f0ede98675e7384d12e6594e1256c7999 | Python | zymov/leetcode | /py/_53_Maximum_Subarray.py | UTF-8 | 683 | 3.671875 | 4 | [] | no_license | """
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solu... | true |
307e5a11874e6bbfbcc958349d0fbc79a80b6802 | Python | jkapila/theNatureofCodeProject | /genrics.py | UTF-8 | 402 | 3.265625 | 3 | [] | no_license |
"""
These are general methods definition
"""
from vector import PVector
def addition(vec1, vec2):
return PVector(vec1.x+vec2.x, vec1.y+vec2.y, vec1.z+vec2.z)
def subtract(vec1, vec2):
return PVector(vec1.x-vec2.x, vec1.y-vec2.y, vec1.z-vec2.z)
def multiply(vec1, d):
return PVector(vec1.x,vec1.y,vec1... | true |
dbea24b22fcedc3f9ea56d299ad39f5dfef2d435 | Python | OmarTahoun/competitive-programming | /Miscellaneous/UIA_Warm_Up/Python/phoneCode.py | UTF-8 | 285 | 3.0625 | 3 | [] | no_license | n = int(input())
substring = list(raw_input())
for i in range(n-1):
phone = list(raw_input())
for j in range(len(substring)):
if substring[j] == phone[j]:
continue
else:
substring = substring[:j]
break
print len(substring)
| true |
e3ad9dcf26d1da0d1f0654ba72c17e7ca0d4256c | Python | sloria/webtest-plus | /webtest_plus/response.py | UTF-8 | 3,192 | 2.953125 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
import re
from webtest import response
class TestResponse(response.TestResponse):
'''Same as WebTest's TestResponse but adds basic HTTP authentication to
``click`` and ``clickbutton``.
'''
def click(self, description=None, linkid=None, href=None,
index=None, ver... | true |
9c5bb4ec55693cb8ef72aba460d5bfe2fd6f614d | Python | DeepSwissVoice/Dobby | /dobby/errors.py | UTF-8 | 3,902 | 3.140625 | 3 | [
"MIT"
] | permissive | from typing import Any, Callable, Optional, TYPE_CHECKING
if TYPE_CHECKING:
from . import Context
DobbyBaseError = type("DobbyBaseError", (Exception,), {})
DobbyBaseError.__doc__ = """This exception is just a subclass of `Exception`.
It doesn't add any extra functionality but it's supposed to be the only error ... | true |
ed0ca502bf073ff2853b26d7e70e8fcf076dcfab | Python | yiv/py-lab | /datatype/dict.py | UTF-8 | 230 | 3.203125 | 3 | [] | no_license | book = {'padme': 35, 'edwin': 34}
print(book)
book['nick'] = 33
print('增', book)
book['edwin'] = 50
print('改', book)
print('查', book['padme'])
print('键列表', list(book))
print('键列表(排序)', sorted(book))
| true |
0699ee1d56bd5a355e0723e10bd8e61401aefffc | Python | trec-dd/trec-dd-jig | /old-scorer/scorer.py | UTF-8 | 1,632 | 2.53125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
# Run all the old-scorer in one trial
from subprocess import call
import click
def run_all():
cubetest()
stage_aware_cubetest()
nDCG()
snDCG()
def cubetest(truth, run):
print 'Calling cubetest'
# results print to screen
call(["perl", "cubeTest_dd.pl", truth, run, ... | true |
df5236ef929ea667965c723bd0f24674b0b631d9 | Python | Aasthaengg/IBMdataset | /Python_codes/p03807/s352343009.py | UTF-8 | 235 | 3.015625 | 3 | [] | no_license | import sys
input = sys.stdin.readline
def main():
N = int(input())
a_list = list(map(int, input().split()))
if sum(a_list) % 2 == 1:
print("NO")
else:
print("YES")
if __name__ == '__main__':
main() | true |
c259b02e9473222828a55e03ac514bbe0450c2da | Python | LKhushlani/leetcode | /duplicte0s.py | UTF-8 | 514 | 2.90625 | 3 | [] | no_license | class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
l = len(arr)
shifts = 0
for i in range(l):
if arr[i] == 0:
shifts += 1
for i in range((l-1), -1, -1):
... | true |
51a33b9fa028cf391ae4939791510888d3c5caea | Python | Aasthaengg/IBMdataset | /Python_codes/p02970/s119776449.py | UTF-8 | 102 | 3.015625 | 3 | [] | no_license | n,d = map(int,input().split())
c = d*2+1
if n%c ==0:
print(int(n//c))
else:
print(int(n//c)+1) | true |
b55c89444a2b4c620ff073f3bf1b9b4d5efb8722 | Python | rafarios/quicksort | /quicksort.py | UTF-8 | 1,177 | 3.65625 | 4 | [] | no_license |
#import subprocess
def printArray(arr):
n = len(arr)
f = open("README.md", "w")
for i in range(n):
print (arr[i])
f.write(arr[i] + "\n")
print(" ")
f.close()
#output = subprocess.run(['git', 'add README.md'])
#output = subprocess.run(['git', 'commit -F "README.md updated"'])
def partition(arr,low,high)... | true |
edb4712bf0c452f66d0da6f246451b9c93f3e3ea | Python | tools4origins/pysparkling | /pysparkling/tests/test_context.py | UTF-8 | 2,693 | 3.125 | 3 | [
"MIT",
"Apache-2.0"
] | permissive | import logging
import unittest
import pysparkling
class Context(unittest.TestCase):
def test_broadcast(self):
b = pysparkling.Context().broadcast([1, 2, 3])
self.assertEqual(b.value[0], 1)
def test_lock1(self):
"""Should not be able to create a new RDD inside a map operation."""
... | true |
2fb401ed5b35314d0bc072cb21178ae77afe8933 | Python | Benny93/dragonflow | /dragonflow/db/drivers/redis_calckey.py | UTF-8 | 990 | 2.53125 | 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 |
4ca5a35f79db9a0d38f55fa4a4ec6a6994f220ca | Python | WanzhengZhu/local-embedding | /code/find_general_terms.py | UTF-8 | 5,919 | 2.515625 | 3 | [] | no_license | import numpy as np
from sklearn.feature_extraction.text import *
from sklearn.linear_model import SGDClassifier
from sklearn.preprocessing import normalize
import time
def read_file(filename):
lines = []
with open(filename) as file:
for line in file:
# line = " ".join(line.split())
... | true |
9863a5914df334b8ea4c0c124c20125e2a8114af | Python | BQSKit/bqskit | /bqskit/passes/processing/exhaustive.py | UTF-8 | 6,358 | 2.796875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | permissive | """This module implements the ExhaustiveGateRemovalPass."""
from __future__ import annotations
import logging
from typing import Any
from typing import Callable
import numpy as np
from bqskit.compiler.basepass import BasePass
from bqskit.compiler.passdata import PassData
from bqskit.ir.circuit import Circuit
from bq... | true |
18d31fb5ec52da0d2eed3b6e716937b34f3315bb | Python | italosaniz/SisTelecomunicaciones | /modulogit.py | UTF-8 | 1,204 | 3.609375 | 4 | [] | no_license | #COSTANCIA DE MATRICULA
def nombre():
global nom
nom=input("Ingrese su nombre: ")
if (not verificar(nom)):
print("Intentelo de nuevo")
nombre()
def verificar(x):
for i in x:
if (ord(i)<65 or ord(i)>90) and (ord(i)<97 or ord(i)>122) and ord(i)!=32:
return Fal... | true |
70943469fe4721c8019c58ceaf47d7d9aede8b69 | Python | Tmk10/Reddit_dailyprogramming | /Kaprekar routine/kaprekar_routine.py | UTF-8 | 723 | 3.109375 | 3 | [] | no_license | #main challenge
def kaprekar_routine(number):
number = list(str(number))
if len(number) <4:
number.insert(0,"0")
return(max(number))
#bonus 1
def kaprekar_routine_1(number):
number = list(str(number))
if len(number) < 4:
number.insert(0, "0")
return "".join(sorted(number,rev... | true |
918aeaeaf69f1b365f23c6208b63883f71425df0 | Python | AbdulHannanKhan/Advance-Lane-Finding | /lane.py | UTF-8 | 15,579 | 2.921875 | 3 | [
"MIT"
] | permissive | import numpy as np
import cv2
def eval_poly(vec, poly):
"""
Evaluates value of a polynomial at a given point
:param vec: The given point :float
:param poly: The polynomial :ndarray[3,]
:return: value of polynomial at given point :float
"""
return vec ** 2 * poly[0] + vec * poly[1] + poly[2... | true |
64c644e5f0a55ef375c391ac186cefbb8f78d011 | Python | AwsManas/Practice | /SieveOfErathonenis.py | UTF-8 | 1,079 | 3.640625 | 4 | [] | no_license | def SieveOfEratosthenes(n):
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
# If prime[p] is not changed, then it is a prime
if (prime[p] == True):
# Update all multiples of p
for i in range(p * 2, n+1, p):
... | true |
655e869d768038629fa79d90614be3d85a4002d7 | Python | Randy777/100_PyExample | /.history/10-19/14_20200908163947.py | UTF-8 | 143 | 3.21875 | 3 | [] | no_license | # 将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。
def FunTest(n):
if __name__ == "__main__":
FunTest(90) | true |
5cca83c1368c920c2ec4e005495d18062c284408 | Python | james20141606/eMaize | /bin/random_projection.py | UTF-8 | 6,883 | 2.71875 | 3 | [] | no_license | #! /usr/bin/env python
import argparse, sys, os, errno
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)s [%(levelname)s] : %(message)s')
logger = logging.getLogger('random_projection')
def prepare_output_file(filename):
try:
os.makedirs(os.path.dirname(filename))
excep... | true |
9ea3dd153802cfe3793e6a6120a590cfc09446e5 | Python | poojagmahajan/Data_Analysis | /Data Analytics/Numpy/Transpose.py | UTF-8 | 784 | 4.5 | 4 | [] | no_license |
import numpy as np
# Creating 2-D array
arr = np.arange(0,50,1).reshape(10,5) # Declare a 2-D array
print("The original array")
print(arr)
print("\nThe transposed array")
print(arr.transpose()) # Print the transposed array
#print(arr.T) # This can also be used and same result will be produced
# Declare 2 array
arr1... | true |
4cda9bc26150dbefdf4f021d5711f9b661188d65 | Python | juicyfruityo/spheremailru | /homework(1_semestr)/data_analysis/hw2/C_2.py | UTF-8 | 1,698 | 3.46875 | 3 | [] | no_license | #!/bin/python3
import operator
from operator import add
from functools import reduce
def solution1(arr):
return [int(''.join(list(filter(str.isalnum, arr_i[::-1])))) for arr_i in arr]
def solution2(iterator):
return [x[0]*x[1] for x in iterator]
def solution3(iterator):
return [i for i in iterator
... | true |
bfd8a193fb8b6073ed76a04229d9585189c9bcdf | Python | TiMusBhardwaj/pythonExample | /python-and-mongo-master/python_dict.py | UTF-8 | 1,272 | 3.9375 | 4 | [] | no_license |
#Dictionary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
x = thisdict["model"]
y = thisdict.get("model")
if x==y:
print("Same Result")
#Dictionary constructor
thisdict = dict(brand="Ford", model="Mustang", year=1964)
thisdict["year"] = 2018
print(thisdict)... | true |
369abcc07bcfbd4fd487da9e6355153e6362a7e9 | Python | nPellejero/deepNet | /src/scripts/detect3.py | UTF-8 | 2,711 | 2.625 | 3 | [] | no_license | # para ejecutar en el directorio images-originals
# pasa imagenes a escala de grises, equaliza su histograma de intensidad y luego detecta la cara mas grande, recorta la imagen y la guarda en images-croped.
import numpy as np
import cv2
import os,sys
rootdir = os.getcwd()
face_cascade = cv2.CascadeClassifier('../script... | true |
90e7466093dd1e08334f146f401c2ebd4f456cd5 | Python | efaro2014/Dojo-Assignments | /python_stack/python/oop/chain_oop.py | UTF-8 | 761 | 3.328125 | 3 | [] | no_license | class User:
def __init__(self, name, email):
self.name = name
self.email = email
self.account_balance = 0
def make_deposit(self, amount):
self.account_balance += amount
return self
def make_withdrawal(self, amount):
self.account_balance -= amount
retu... | true |
26ba8ea3ca77c4e3cac2e7318a600611cfbc3afb | Python | ChoiHyeongGeun/ScriptProgramming | /Practice/#4/Problem6.16.py | UTF-8 | 737 | 4.59375 | 5 | [] | no_license | # 6.16
# 1년의 총 일수를 구하는 함
def numberOfDaysInYear(year) :
# 윤년이면
if (year % 4 == 0) and (year % 100 != 0) and (year % 400 == 0) :
return 366 # 총 366일
# 윤년이 아니면
else :
return 365 # 총 365일
# 결과를 출력하는 함수
def printResult() :
# 일수의 총 합을 0으로 초기화
sum = 0
... | true |
b9f6f319b4b5b99687a320d5e697ef32852a35ce | Python | davidaries/Job8 | /tools.py | UTF-8 | 918 | 2.53125 | 3 | [] | no_license | import working_data
import initial_load_data as ild
def summary():
"""Prints out a summary of information to the console"""
print('\n========= Summary data at this point =========================================================')
print('\npdata =', working_data.pdata)
for h in working_data.pdata:
... | true |
27e708816da9ef0bd3dd4c12d693c58973f3b463 | Python | Mashfiq137/Hough_transform_Image_processing | /main.py | UTF-8 | 1,447 | 2.9375 | 3 | [
"Apache-2.0"
] | permissive | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 08 16:11:33 2021
@author: rizvee
"""
from patterns import pattern_detect
from collections import defaultdict
from PIL import Image, ImageDraw
from math import sqrt, pi, cos, sin
# ----------------------------------------------Input Image-------------------------... | true |
b27fae3d70457e239a458c2b77959a0ce0902658 | Python | cerealkill/light_karma | /utils.py | UTF-8 | 1,722 | 3.09375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import re
from itertools import cycle
MANTRA = cycle(["om vajrasattva samaya", "manupalaya", "vajrasattva denopa titha", "dido me bhava",
"suto kayo me bhava", "supo kayo me bhava", "anurakto me bhava", "sarva siddhi me prayatsa",
"sarva karma su tsame", "tsitta... | true |
d8fed868b7675ca62266e52693b8e8c24eac9f6b | Python | rakibkuddus1109/pythonClass | /multithreading.py | UTF-8 | 478 | 3.71875 | 4 | [] | no_license | import time
import threading
a = [2,3,4,5]
def square(a):
for j in a:
time.sleep(0.5)
print(j**2)
def cube(a):
for j in a:
time.sleep(0.3)
print(j**3)
t = time.time()
# square(a)
# cube(a)
t1 = threading.Thread(target=square,args=(a,))
t2 = threading.Thread(target=cube,args=(... | true |
434c9b0d8b8475bdbfd374f18de855dc000b0942 | Python | genebarsukov/MadFuzzWebScraper | /src/models/Story.py | UTF-8 | 1,609 | 3.203125 | 3 | [] | no_license |
class Story(object):
"""
A simple object to hold the parsed story parameters
The variables that are initialized are done so to match the default database values
"""
story_id = None
url = ''
title = ''
author = ''
body = ''
snippet = ''
source_id = None
active = False
... | true |
664f8f38d7aeea06896476bfeb26faef467b80f0 | Python | wattaihei/ProgrammingContest | /AtCoder/キーエンス2020/probD.py | UTF-8 | 3,094 | 3.125 | 3 | [] | no_license | # instead of AVLTree
class BITbisect():
def __init__(self, max):
self.max = max
self.data = [0]*(self.max+1)
# 0からiまでの区間和
# 立っているビットを下から処理
def query_sum(self, i):
s = 0
while i > 0:
s += self.data[i]
i -= i & -i
return s
# i番目の要素に... | true |
a6b00cd4e644c018b8cbb2cc86b053d8a17ca7dc | Python | burakbayramli/books | /PHY_604_Computational_Methods_in_Physics_and_Astrophysics_II_Zingale/code1/ODEs/eigenvalues/finite-well.py | UTF-8 | 1,233 | 2.8125 | 3 | [] | no_license | from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
import schrodinger
def V(x):
""" the potential well -- a finite square well """
idx = np.abs(x) < 1.0
Vwell = np.zeros_like(x)
Vwell[idx] = -1000.0
return Vwell
# pick a starting point far from the action --... | true |
ab964e1838d1df76b32cfe80a28e076883981ce6 | Python | AaronBecker/project-euler | /euler081.py | UTF-8 | 795 | 3.234375 | 3 | [] | no_license |
with open('euler081_input.txt') as f:
pe81 = [map(int, line.strip().split(',')) for line in f.readlines()]
def euler81(matrix=pe81):
"""http://projecteuler.net/index.php?section=problems&id=81
Find the minimal path sum from the top left to the bottom right by moving
right and down."""
shortest_pa... | true |
5c96603cea1fe92470dd135c43b6d4dbab8e2793 | Python | felixhalim/python-bot | /update_reg_user.py | UTF-8 | 1,340 | 2.640625 | 3 | [] | no_license | import gspread
from oauth2client.service_account import ServiceAccountCredentials
import pprint
scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('spreadsheet-token.json', scope)
client = gspread.authorize(creds)
register... | true |
e342384f741b23537d88e26e4a92c2dedbd77777 | Python | cristinarivera/python | /untitled-11.py | UTF-8 | 220 | 3.109375 | 3 | [] | no_license | def udacify(string):
word = 'U'+string
return word
# Remove the hash, #, from infront of print to test your code.
print udacify('dacians')
#>>> Udacians
print udacify('turn')
#>>> Uturn
| true |
8aa905946ab08c7ac77609161bb31eba0d566db5 | Python | ironmann250/python-wikiquotes | /tests/test_random_titles.py | UTF-8 | 538 | 2.625 | 3 | [
"MIT"
] | permissive | import wikiquote
import unittest
class SearchTest(unittest.TestCase):
"""
Test wikiquote.random_titles()
"""
def test_random(self):
for lang in wikiquote.langs.SUPPORTED_LANGUAGES:
results = wikiquote.random_titles(lang=lang, max_titles=20)
self.assertTrue(len(results) ... | true |
cc602a0e49d72a055f8ee86c17d720836979e6c3 | Python | veera-sivarajan/Weather-Graphing | /graph.py | UTF-8 | 270 | 2.765625 | 3 | [] | no_license | import datetime
from matplotlib import pyplot as plt
from weather import get_weather
def graph(x, y):
plt.xlabel('Time')
plt.ylabel('Temperature')
plt.xlim(0, 24, 2)
plt.ylim(10, 60)
plt.plot(x, y)
plt.show()
#plt.savefig("weather graph.pdf") | true |
3868551324de22aac6c858a809eb7b4f7bf60e15 | Python | mmweber2/hackerrank | /test_convert_string.py | UTF-8 | 1,053 | 3.25 | 3 | [] | no_license | from nose.tools import assert_equals
from convert_string import convert_string
from string import ascii_lowercase as letters
def test_no_duplicates():
assert_equals("xyz", convert_string("xyz"))
def test_all_duplicate_no_wrap():
assert_equals("abc", convert_string("aaa"))
def test_all_duplicate_wrap():
a... | true |
f8d6403b16a48142d3ecac4ccf141209961d07ba | Python | fangwendong/machineLearning | /classify_tree.py | UTF-8 | 2,283 | 3.296875 | 3 | [] | no_license | # coding: utf-8
from sklearn.datasets import load_iris
from sklearn import tree
import numpy as np
'''
iris数据一共有150组,前100组作为训练样本,后50组作为测试样本
'''
def predict_train(x_train, y_train):
'''
使用信息熵作为划分标准,对决策树进行训练
参考链接: http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html#skle... | true |
79df0ac8f7455f6993fef763f6cfa3797c49dff4 | Python | pylinx64/mon_python_16 | /mon_python_16/pepsibot/teext.py | UTF-8 | 219 | 3.5625 | 4 | [] | no_license | print('HELLO')
print('HELLO' == 'hello')
print(10 > 9 )
print(10 / 1)
print('Hello' == 'hello')
print('HELLO'.lower())
print('как' in 'как дела ?')
print('как' in 'приветкакдела?')
| true |
181abba50e371627c90d6a1b676851217da702f2 | Python | diekhans/t2t-chm13-gene-analysis | /bin/bioTypeToCat | UTF-8 | 735 | 2.765625 | 3 | [] | no_license | #!/usr/bin/env python3
import argparse
from pycbio.sys import fileOps
from bioTypeCat import BioCategory
def parseArgs():
usage = """
Convert biotypes, including CAT-specified, to more general categories
"""
parser = argparse.ArgumentParser(description=usage)
parser.add_argument('inTypes', nargs='?', ... | true |
745f10e3784d7375279e5ee065eeaa87f9eb7945 | Python | JesseWright/cs373 | /notes/03-24.py | UTF-8 | 836 | 2.90625 | 3 | [] | no_license | # -----------
# Fri, 24 Mar
# -----------
def theta_join (
r: Iterable[Dict[str, int]],
s: Iterable[Dict[str, int]],
f: Callable[[Dict[str,int], Dict[str, int]], bool]
-> Iterator[Dict[str, int]] :
for v1 in r :
for v2 in s :
if f(v1, v2) :
yield dict(v1, **v2)
... | true |
194c58beac8c5f868ac514553662348f144152cc | Python | q2806060/python-note | /numpydemo/03/demo3-05.py | UTF-8 | 487 | 3.078125 | 3 | [] | no_license | import numpy as np
import matplotlib.pyplot as mp
# 生成网格点坐标矩阵
n = 1000
x, y = np.meshgrid(np.linspace(-3, 3,n), np.linspace(-3, 3, n))
# 根据x, y计算当前坐标下的z高度值
z = (1-x/2 + x**5 + y**3) * np.exp(-x**2 - y**2)
mp.figure("Imshow", facecolor="lightgray")
mp.title("Imshow", fontsize=18)
mp.xlabel("X", fontsize=14)
mp.ylab... | true |
8e8fddd224fbffb97a7f8da3930859db6ff3a1c4 | Python | SoniaAmezcua/qa_minds_proyecto_final | /tests/test_menu_categories.py | UTF-8 | 1,016 | 2.59375 | 3 | [] | no_license | from actions.shop_actions import ShopActions
from core.utils import datafile_handler as data_file
from facades import menu_facade as menu
from facades import menu_categories_facade as menu_categories
import pytest
import datetime
from time import sleep
#Prueba 2.- Verificar los elementos del menú de categorías
@pyte... | true |
4a21d14b98d02566e9d097f354b1083296a4d442 | Python | fantasysea/HelloPython | /getjikexuexi.py | UTF-8 | 1,683 | 2.65625 | 3 | [] | no_license | __author__ = 'wuheyou'
__author__ = 'CC'
# coding=utf-8
# -*- coding: utf8 -*-
import requests
import re
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
# r = requests.get("http://www.baidu.com/")
# r.encoding = 'utf-8'
# print r.content
class spider:
def getHtml(self,url):
return requests.get(url... | true |
426ce8416c1463b6c670783ce6efb9cceb50c450 | Python | ragnartrades/LimitOrderBooks | /Analytics/ExtractPrices.py | UTF-8 | 1,360 | 3.140625 | 3 | [] | no_license |
from Analytics.Features import Features
from Analytics.LimitOrderBookSeries import LimitOrderBookSeries
class ExtractPrices(Features):
def __init__(self):
pass
def extract_data(self, data):
"""
:param data: data frame
:return: time series
"""
# return a limi... | true |
8000a58f89b46c41be0023b9aef4066aa819b065 | Python | rexarabe/Python_projects2 | /020_operator/001_operator.py | UTF-8 | 209 | 4.125 | 4 | [] | no_license | #!/bin/python
"""Python Operators
Operators are used to perform operations on variables and values.
"""
x = 10
y = 15
print(x+y)
print(x-y)
print(x*y)
print(x/y)
print(y%x)
print(x**y)
print(y//x)
| true |
5e5242c4da067d8149d8374e4f5038f2065a1652 | Python | shoeferg13/fa18-hw-ref | /hw4.py | UTF-8 | 6,935 | 4.34375 | 4 | [] | no_license | """
CS 196 FA18 HW4
Prepared by Andrew, Emilio, and Prithvi
You might find certain default Python packages immensely helpful.
"""
# Good luck!
"""
most_common_char
Given an input string s, return the most common character in s.
"""
def most_common_char(s):
if len(s) == 0:
return None
s = s.lower()
max = 0;
fo... | true |
9e8ce4ad5f043443ae43d8445d21afabd0e73f1e | Python | amchugh/rocket | /python/rocketfollow.py | UTF-8 | 3,919 | 2.71875 | 3 | [] | no_license | import rocketenv
import pygame
import random
SIZE = (800,900)
FLOOR = 800
class Missile:
def __init__(self, world_size, pos, vel, dt):
self.world_size = world_size
self.pos = [pos[0], pos[1]]
self.vel = vel
self.dt = dt
def step(self):
self.pos[0] += self.vel[0] * self.... | true |
5a57ffa79b664adf3f82d0f5a5f09f6ec4b7855b | Python | Akankshipriya/Trade-App | /Trade App/s2Port.py | UTF-8 | 4,411 | 2.71875 | 3 | [] | no_license | from pandas_datareader import data as pdr
import yfinance as yf
import pandas as pd
import numpy as np
from datetime import datetime
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import pandas_datareader as pdr
import matplotlib.axis as ax
from pandas.util.testing import assert_frame_equal
d... | true |
59f24fe9070f697e695846fba7883bed22e66da5 | Python | yusheng88/RookieInstance | /Rookie054.py | UTF-8 | 1,114 | 3.859375 | 4 | [] | no_license | # -*- coding = utf-8 -*-
# @Time : 2020/7/8 22:18
# @Author : EmperorHons
# @File : Rookie054.py
# @Software : PyCharm
"""
https://www.runoob.com/python3/python3-examples.html
Python 使用正则表达式提取字符串中的 URL
给定一个字符串,里面包含 URL 地址,需要我们使用正则表达式来获取字符串的 URL
"""
import pysnooper
import re
@pysnooper.snoop()
def re_Find(string):
... | true |
a4082ceb7a01808681c50811afce5fe7b84055d1 | Python | shills112000/django_course | /PYTHON/STATEMENTS_WHILE_FOR_IF/while.py | UTF-8 | 1,385 | 3.953125 | 4 | [] | no_license | #!/usr/local/bin/python3.7
#https://docs.python.org/3/tutorial/introduction.html#first-steps-towards-programming
#while True:
# print ("Looping")
count = 1
while count <=4:
print (f"counting : {count}")
count += 1
count =0
while count < 10:
if count % 2 == 0:# miss even numbers
count +=1
... | true |
43c9ef192077a2f0050a6ebd70495f91ad73bf4a | Python | jdrubin91/BidirectionalTFAnalyzer | /src/Depletion_Simulator.py | UTF-8 | 844 | 2.609375 | 3 | [] | no_license | __author__ = 'Joseph Azofeifa'
import math
import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate
def simulate(N=10000, mu=0, si=300, a=-1500,b=1500):
f = lambda x: (1.0 / math.sqrt(2*math.pi*pow(si,2)) )*math.exp(-pow(x-mu,2)/(2*pow(si,2)))
u = lambda x: 1.0 / (b-a)
xs... | true |
4eff248cc023f334759b5ce93d11ee1e87263507 | Python | kimdanny/HeapSort-and-QuickSort-Comparison | /Automation/testing.py | UTF-8 | 336 | 3.125 | 3 | [] | no_license | from random import randint
import numpy
randomList = []
size = 100_000 + 1100_000 * 5
for x in range(size):
randomList.append(randint(0, 1_000_000))
# See how many repetitions of elements in a single list
a = numpy.array(randomList)
unique, counts =numpy.unique(a, return_counts=True)
this = dict(zip(unique, count... | true |
0df114cc93c9f7f7ada529ed52fe07c072be4c27 | Python | kbase/taxonomy_re_api | /src/exceptions.py | UTF-8 | 768 | 2.828125 | 3 | [
"MIT"
] | permissive | """Exception classes."""
class ParseError(Exception):
code = -32700
class InvalidRequest(Exception):
code = -32600
class MethodNotFound(Exception):
code = -32601
def __init__(self, method_name):
self.method_name = method_name
class InvalidParams(Exception):
code = -32602
class Int... | true |
41b14397da76619ae7c34efb12c94aff91ae6821 | Python | da-ferreira/uri-online-judge | /uri/3096.py | UTF-8 | 592 | 4.09375 | 4 | [] | no_license |
def kamenetsky(number):
"""
Formula de kamenetsky permite saber quantos
digitos tem o fatorial de um numero qualquer > 0
se calcular seu fatorial.
:param number: O numero do fatorial
:return: Quantidade de digitos do fatorial desse numero.
"""
import math
if numb... | true |
2dba2dcc2fd0c07c91985f8a2142653e172eae51 | Python | tkhunlertkit/Sketches | /python/Bit Coin Computation/test.py | UTF-8 | 320 | 2.796875 | 3 | [] | no_license | import requests
response = requests.get('https://chain.so/api/v2/get_price/BTC/USD',verify=True)
response = response.json()['data']['prices']
cumulative = 0
for i in response:
cumulative += float(i['price'])
for key in i:
print key, i[key]
print
print cumulative
print 'avg:', cumulative / len(i)
| true |
c7caf6b14a5bb703d03288ca138117f8b52c36bd | Python | ghomsy/makani | /analysis/aero/avl/avl_reader.py | UTF-8 | 21,745 | 2.890625 | 3 | [
"Apache-2.0"
] | permissive | #!/usr/bin/python
# Copyright 2020 Makani Technologies LLC
#
# 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 applicabl... | true |
ee25c8ed2eabeb12a3826f3556c152606e6f464e | Python | nclv/My-Gray-Hacker-Resources | /Cryptography/Hash_Functions/MD5/Hash-Length-extension-attacks/VimeoHashExploit/server.py | UTF-8 | 1,638 | 2.53125 | 3 | [
"CC-BY-SA-4.0",
"MIT"
] | permissive | """
adapted from Fillipo Valsorda's tutorial
august/2014
"""
import os
import binascii
import md5
import urlparse
from flask import Flask, request, abort, render_template
PORT = 4242
USER_ID = 42
USER_NAME = "Jack"
API_KEY = binascii.hexlify(os.urandom(16))
API_SECRET = binascii.hexlify(os.urandom(16))
app =... | true |
b54c8d732c668e9ed5536d8714db5e08a63e17e3 | Python | Andrii-Dykyi/2D-game-pygame | /bullet.py | UTF-8 | 992 | 3.34375 | 3 | [] | no_license | import os
import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
"""Class to manage bullets fired from rocket."""
def __init__(self, game_settings, screen, rocket):
"""Create a bullet object at the rocket's current position."""
super().__init__()
self.screen... | true |
70c5317cc3c2690738f19bfbe738a81fad822a13 | Python | NeugeCZ/czech-derivation | /upravy.py | UTF-8 | 138 | 2.703125 | 3 | [] | no_license | import re
def uprava_pravopisu(slovo):
if 'rě' in slovo:
return re.sub('rě', 'ře', slovo)
else:
return slovo
| true |
ee1a566c75bbd419f3939057260d9a4c228dfb93 | Python | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4160/codes/1723_2504.py | UTF-8 | 404 | 3.453125 | 3 | [] | no_license | v = int(input("Quantidade inicial de copias do virus no sangue de Micaleteia: "))
l = int(input("Quantidade inicial de leucocitos no sangue: "))
pv = int(input("Percentual de multiplicacao diaria do virus: "))
pl = int(input("Percentual de multiplicacao diaria dos leucocitos: "))
dias = 0
while(l < 2*v):
h = (pv ... | true |
53ead851be5ab9e0516e264130b7f26fb50250ba | Python | voidnologo/advent_of_code_2020 | /1_code.py | UTF-8 | 301 | 3.203125 | 3 | [] | no_license | from itertools import combinations
from math import prod
with open("1_data.txt", "r") as f:
data = f.read().splitlines()
print("Part 1:", next((c, prod(c)) for c in combinations(data, 2) if sum(c) == 2020))
print("Part 2:", next((c, prod(c)) for c in combinations(data, 3) if sum(c) == 2020))
| true |
0348b226ac3edc1e5551b2135d8aa04b4775e588 | Python | ZeweiSong/FAST | /filter_database.py | UTF-8 | 1,951 | 3.015625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 08 10:51:54 2015
This is a trial script for filtering the UNITE database.
All records with 'unidentified' in its name are discarded, resutling a clean reference database for taxonomic assignment.
Please feel free to contact me for any question.
--
Zewei Song
University o... | true |
f284c9f0bb2cd3aaeb73f47ac0b3f89ed670e09e | Python | RakeshSharma21/HerokuDeployment | /model.py | UTF-8 | 383 | 2.921875 | 3 | [] | no_license | import pandas as pd
import pickle as pkl
hiringDf=pd.read_csv('hiring.csv')
print(hiringDf.head())
y=hiringDf['salary']
X=hiringDf.drop(['salary'],axis=1)
from sklearn.linear_model import LinearRegression
regressor=LinearRegression()
regressor.fit(X,y)
pkl.dump(regressor, open('model.pkl','wb'))
model=pkl.lo... | true |
4da4c4b183c6945c5a711540f2ef596d7d21efd8 | Python | RobinVdBroeck/ucll_scripting | /exercises/basics/02-conditionals/student.py | UTF-8 | 330 | 3.84375 | 4 | [] | no_license | # Voorbeeld
def abs(x):
if x < 0:
return -x
else:
return x
# Merk op dat 'else if' in Python een speciale syntax heeft
# Zoek deze zelf op online
def sign(x):
if x < 0: return -1
if x is 0: return 0
return 1
def factorial(n):
if n in (0,1):
return 1
return n * facto... | true |
e56b1f292163ad6b5d88e01eb7a2e7759b8bd58f | Python | timcosta/prawtools | /prawtools/stats.py | UTF-8 | 14,667 | 2.53125 | 3 | [
"BSD-2-Clause"
] | permissive | """Utility to provide submission and comment statistics in a subreddit."""
from __future__ import print_function
from collections import defaultdict
from datetime import datetime
from tempfile import mkstemp
import codecs
import logging
import os
import re
import time
from praw import Reddit
from praw.models import S... | true |
d7e13ba422bac0211543ef74cb765ea7e3475219 | Python | Billerens/conventional-commits-vscode-helper | /commit-msg | UTF-8 | 3,046 | 3.109375 | 3 | [] | no_license | #!/usr/bin/env python3
import re, sys, os
def main():
buffered = ''
counter = -1
currentPosition = 0
patternHeaderType = r'^(build|ci|docs|feat|fix|perf|refactor|style|test|chore|revert)'
patternHeaderScope = r'(?:\(([^\)\s]+)\))?'
patternHeaderImportant = r'!?'
patternHeaderMessage = r': ... | true |
e21ea88ac1b078e33ff368e0819139b48438a9b8 | Python | Aletvia/point_of_sale | /src/modules/inventory/models.py | UTF-8 | 332 | 2.546875 | 3 | [
"MIT"
] | permissive | from django.db import models
"""
Model which represent a product (p. ej. Coca-Cola 500ml, 800.00, 500).
"""
class Products(models.Model):
description = models.TextField(max_length=100)
#unit_price = models.DecimalField(max_digits=7, decimal_places=2)
unit_price = models.IntegerField()
stock = models.In... | true |
0979196c44084f7438c405baa600add4938aacde | Python | Ofrogue/ENOT | /quad.py | UTF-8 | 2,422 | 3.5 | 4 | [] | no_license | # quad tree class
import random
class QuadNode:
def __init__(self, x, y, width, height, level):
# x, y are left upper corner
self.x = x
self.y = y
self.width = width
self.height = height
self.center = (x + width / 2, y + height / 2)
self.children = list()
... | true |
e461d4e3441c38562cfac83b2cfd026273b3fcb3 | Python | Juniorlimaivd/MachineLearningCIn | /lista-2/prototype.py | UTF-8 | 515 | 3.015625 | 3 | [] | no_license | import numpy as np
import math
import random
def generateRandomPrototypes(data, prototypesNumber):
n_instances = len(data.values)
n_attributes = len(data.values[0])
result_x = []
result_y = []
for _ in range(prototypesNumber):
prototype = [data.values[random.randrange(n_instances)][i] for i... | true |
a1d591556391ae558d7436ade8d7d1a0d6e76f90 | Python | walkingpanda/walkingpanda | /get start/main.py | UTF-8 | 680 | 2.8125 | 3 | [] | no_license | import torch
import numpy as np
import torch.nn as nn
N, D_in, H, D_out = 64, 1000, 100, 10
x = torch.randn(N, D_in)
y = torch.randn(N, D_out)
model = torch.nn.Sequential(
nn.Linear(D_in, H),
nn.ReLU(),
nn.Linear(H, D_out),
)
loss_fn = nn.MSELoss(reduction='sum')
lr = 1e-4
for t in ra... | true |
adbeb3d9148e1eb971ee7c6347bb05b935cd1c9e | Python | ryu577/algorithms | /algorith/sequencegen/permutations/all_permutations.py | UTF-8 | 634 | 3.640625 | 4 | [
"MIT"
] | permissive |
def perm(t,i,n):
"""
Based on procedure "perm" in ch6 of Giles and Bassard.
"""
if i==n:
print(t)
else:
for j in range(i,n+1):
swap(t,i,j)
perm(t,i+1,n)
swap(t,i,j)
def perm2(a,ix):
"""
My own version of perm.
"""
if ix==len(a):
... | true |
f71c782dc9099fced1acd39bdad33014a7de39df | Python | georgenewman10/stock | /history.py | UTF-8 | 647 | 2.96875 | 3 | [] | no_license | from datetime import datetime
from iexfinance.stocks import get_historical_data
import pandas as pd
### maybe replace hist() with hist(start, end, etc) so you can more easily change important variables
def hist(output=None):
#if output=='pandas'
histories = {}
stock_list = ['AAPL','GOOG','MSFT','AMZN','... | true |
600724228c3a068f87dc599158fef17bf64e9ef7 | Python | CRSantiago/Python-Projects | /Micro Projects/prime_factorization.py | UTF-8 | 551 | 4.625 | 5 | [] | no_license | # Prime Factorization - Have the user enter a number and find all Prime Factors (if there are any) and display them.
import math
def find_prime_factors(n):
while n%2==0:
yield 2
n/=2
for i in range(3,int(math.sqrt(n))+1,2):
while n%i==0:
yield i
... | true |
1b8c54d7f65037e8e2af4518c6b29b3c3fe00586 | Python | AlieksieienkoVitalii/Labs | /Lesson_6/Lesson_6_3_3.py | UTF-8 | 1,015 | 4.3125 | 4 | [] | no_license | # СПОСОБ 3_______________________________________________________________________________________________________________________________________________________
def my_function(n):
if n == 1 or n == 2:
return 1
else:
return my_function(n - 1) + my_function(n - 2)
steps = int(input('Введите ко... | true |
a13316066102cc3bd033fd937823cd811f4114ef | Python | frossie-shadow/astshim | /tests/test_xmlChan.py | UTF-8 | 2,060 | 2.609375 | 3 | [] | no_license | from __future__ import absolute_import, division, print_function
import os.path
import unittest
import astshim
from astshim.test import ObjectTestCase
DataDir = os.path.join(os.path.dirname(__file__), "data")
class TestObject(ObjectTestCase):
def test_XmlChanDefaultAttributes(self):
sstream = astshim.S... | true |
af9e6dda53b19142673ca7cb39d84d571a3ad4fa | Python | Jovamih/PythonProyectos | /Pandas/Data Sciensist/alto-rendimiento.py | UTF-8 | 918 | 3.390625 | 3 | [
"MIT"
] | permissive | #/usr/bin/env python
import pandas as pd
import numpy as np
import numexpr
def rendimiento():
#la libreria numexpr proporciona eval() funcion que evalua literales de cadena a expresiones python logicas
data=pd.DataFrame(np.random.randint(12,200,size=(8,4)),columns=list('ABCD'))
#la libreria Pandas tambien ... | true |
69ad3f4d4f52b3c9d14674659d5a6bbda834f54d | Python | varungambhir/Major_Project | /preprocess.py | UTF-8 | 297 | 2.96875 | 3 | [] | no_license |
li=""
with open('response.txt') as f:
while True:
c = f.read(1)
if not c:
print "End of file"
break
li=li+c
print li
fn=""
for i in range(0,len(li)-2):
fn+=li[i]
if li[i+1]=='{' and li[i]=='}':
fn+=','
f=open('response.txt','w')
f.write(str(fn))
| true |
4193f13355a64d6cc1ef850546db8a76f386f3a7 | Python | JamesBrowns/data-analysis | /D A/python/回归预测/简单线性linearregression.py | UTF-8 | 996 | 2.953125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
# 引入模块
import pandas as pd
from sklearn.linear_model import LinearRegression
# 读取数据
train = pd.read_csv("data/train1.csv")
test = pd.read_csv("data/test1.csv")
submit = pd.read_csv("data/sample_submit.csv")
# 删除id
train.drop('id', axis=1, inplace=True)
test.drop('id', axis=1,... | true |
893f9b77a05a9de3e38dd61a9d334e6eaf5efbe6 | Python | p2327/CS61a_Berkeley | /list_lab_recursion.py | UTF-8 | 1,308 | 4.03125 | 4 | [] | no_license | def reverse_recursive(lst):
if lst == []:
return []
else:
return reverse_recursive(lst[1:]) + [lst[0]]
test = reverse_recursive([1, 2, 3, 4])
def merge(lst1, lst2):
"""Merges two sorted lists recursively.
>>> merge([1, 3, 5], [2, 4, 6])
[1, 2, 3, 4, 5, 6]
>>>... | true |