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 |
|---|---|---|---|---|---|---|---|---|---|---|
beeb112ab46645fbec46085ffd42ac9f61c25d56 | erikbostrom/Monte-Carlo-integration | /Monte-Carlo.py | UTF-8 | 1,370 | 3.59375 | 4 | [] | no_license | """
=============================================================================
1d Monte-Carlo integration example
=============================================================================
Area of square [0,1]x[0,1] is 1
Area of circle quadrant with radius 1 is equal to the probability a random
point (x_1,x_2) ... | true |
be9781aa60da197a6fc62ad3687ed5359443a054 | dontlivetwice/westock | /core/models/user.py | UTF-8 | 4,458 | 2.53125 | 3 | [] | no_license | import core
from core.models import fields
from core.utils import password_utils
import core.models.base as base
from core.models.user_stock import UserStock
from core.models.user_interest_model import UserInterest
from core.managers.user_stock_manager import UserStockManager
from core.managers.user_interest_manager i... | true |
ddfc9b7f558ccb1bb35ad619b33a3f0a831cb6f7 | kennethreitz-experiments/xyzzy | /xyzzy/game.py | UTF-8 | 661 | 2.671875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
xyzzy.game
~~~~~~~~~~
This module defines the actual game.
"""
from . import defaults
from .state import GameState
class Game(object):
"""The instance of the actual game."""
def __init__(self, state=None):
self.state = state or GameState()
self.commands = set()
... | true |
9e89e73d5bcdc7abe467ec066adb4a8f3d6c1cc7 | zhanghuihb/python | /python/action_ten/division_apple.py | UTF-8 | 753 | 4.21875 | 4 | [] | no_license | def division():
'''功能,分苹果'''
print("\n========分苹果了=======\n")
apple = int(input("请输入苹果的个数:"))
children = int(input("请输入来了几个小朋友:"))
assert apple > children, "苹果不够分"
# 计算每人分几个苹果
result = apple // children
# 计算余下几个苹果
remain = apple - result * children
if remain > 0:
print(ap... | true |
ade0218e6d65330e44c3a36043c6e1f60543543b | robertompfm/morais-parking-python | /MoraisParkingPython/view/funcoes_veiculo.py | UTF-8 | 1,032 | 2.984375 | 3 | [] | no_license | from control.controller_veiculos import ControllerVeiculos
from control.controller_proprietario import ControllerProprietario
from model.constants import *
controller_veiculo = ControllerVeiculos()
controller_proprietario = ControllerProprietario()
def cadastrar_veiculo():
print("\n====== CADASTRO VEICULO ======... | true |
6a6ab013d3b24a7e036482dbe54672173ffe88c5 | philippwindischhofer/Bayes4Leptons | /AnalysisStep/test/Python/ModelCollectionEvaluator.py | UTF-8 | 4,261 | 2.703125 | 3 | [] | no_license | from trainlib.ModelCollectionConfigFileHandler import ModelCollectionConfigFileHandler
from trainlib.ConfigFileHandler import ConfigFileHandler
from trainlib.generator import Generator
from trainlib.config import Config
from keras import optimizers
import sys
def main():
def _compute_class_weights_lengths(gen... | true |
543313aa2affa6e6db8ab4b49d1ab3d5bf19459a | venkateshraizaday/ArtificialIntelligence | /a1/route.py | UTF-8 | 8,600 | 3.84375 | 4 | [] | no_license | '''
- Program Description:-
Data is read from the file and is stored in the following dictionaries:-
dict_city_data : Contains distance, time and highway between a pair of cities. key - name of both cities
dict_city : Contains list of cities which have a route from a particular city. Key - name of city
dict_city_lat_l... | true |
6c564a5d39291823b0368ab964da952797c48651 | albrom5/utilidades | /numeracao_sequencial/protocolo_automatico_teste.py | UTF-8 | 1,209 | 2.734375 | 3 | [] | no_license | from freezegun import freeze_time
from auto_sequence_by_year import Contrato
contador = 0
for i in range(1, 3):
contador += 1
Contrato(objeto=f'Contrato {contador}')
freezer = freeze_time("2022-01-14 12:00:01")
freezer.start()
for i in range(1, 3):
contador += 1
Contrato(objeto=f'Contrato {contador}')... | true |
2c255ec5528804b4d65dc9d29c8e2b76dd97566d | andrewzlee/NeuralBlock | /preprocess.py | UTF-8 | 4,263 | 2.546875 | 3 | [] | no_license | import sqlite3
import random
from youtube_transcript_api import YouTubeTranscriptApi
import preprocess_helper as preprocess
import traceback
def main():
# Modes:
# 1 Read from database.db and pull all videos
# 2 Read from labeled.db and pull only unprocessed
# 3 Subtract labeled.db from da... | true |
47ecaad67dd4e274aad3b9a31b66d200397843af | lacie-life/IoT-Project | /DHT21_MQTT/DHT21.py | UTF-8 | 1,323 | 2.859375 | 3 | [] | no_license | import sys
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import Adafruit_DHT
# Our "on message" event
def messageFunction (client, userdata, message):
topic = str(message.topic)
message = str(message.payload.decode("utf-8"))
print(topic + message)
# Parse command line parameters.
sensor_a... | true |
28df47c76d778707f4b6adafc213ebb0ccbc744e | mkwiatkowski/mandelbrot | /mandelbrot.py | UTF-8 | 5,061 | 3.421875 | 3 | [
"MIT"
] | permissive | import hotshot
import hotshot.stats
import pygame
import sys
import time
PROFILER_FILE = "hotshot_mandel_stats"
SCREEN_RESOLUTION = (640, 480)
class Screen(object):
def __init__(self, surface, width, height, left_cord=-2.0, top_cord=1.0, scale=0.5):
self.surface = surface
self.width = wi... | true |
3f79d6acfbbca0364b38ea2c794cc50bd4abb488 | v123582/181222-itri-python-crawler-tutorial | /sample-code/02-資料來源與取得/05.py | UTF-8 | 221 | 2.625 | 3 | [] | no_license | import requests, json
ACCESS_TOKEN = ''
url = 'https://graph.facebook.com/v3.0/me?fields=likes&access_token={}'.format(ACCESS_TOKEN)
data = json.loads(requests.get(url).text)
for d in data['likes']['data']:
print(d) | true |
df688563e977baa33f1761584789b98cb299775e | tsinflam2/MachineLearning | /bokeh_candlestick_example.py | UTF-8 | 998 | 2.96875 | 3 | [] | no_license | from math import pi
import pandas as pd
from bokeh.plotting import figure, show, output_file
import quandl
# df = pd.DataFrame(MSFT)[:50]
df = quandl.get("WIKI/GOOGL", returns="pandas", start_date="2017-06-01", end_date="2017-07-01")
# print(df.Close)
df["Date"] = pd.to_datetime(df.index)
df.index = range(len(df))
#... | true |
d894b567a972913bc1cdd3a4cb9180b834507bf0 | jamesx0517/python | /ex11.py | UTF-8 | 263 | 3.609375 | 4 | [] | no_license | #--coding: utf-8--
print "How old are you ?",
age=raw_input()
#raw_input輸入框
print "How tall are you?",
height=raw_input()
print "How much do you weight?",
weight=raw_input()
print """So you're %r old , %r tall and %r heavy.""" %(
age , height ,weight
) | true |
e1ad0adbcfb23b588e438f01b00448731ab1a572 | shreyassk18/MyPyCharmProject | /Exception_Handling/Try_except.py | UTF-8 | 1,120 | 4.28125 | 4 | [] | no_license | #Exception is an abnormal condition
#it is an event that disrupts the normal flow of the program
#In python every exception is treated as an error
#There is a difference between error and exception
# a. An error can be syntax error or logical error
# b. An exception is occured by user input or we can say at run... | true |
e0b8a80262372d5ded50ee2dc02a49f83253960a | StevenLOL/kaggleScape | /data/script813.py | UTF-8 | 7,683 | 3.5 | 4 | [] | no_license |
# coding: utf-8
# # YouTube Trending Statistics Exploration in Python
#
# This notebook will walk you through some preliminary data exploration process of the *YouTube Trending* dataset, specifically the US dataset. Original data and more information could be found on two Kaggle sites:
# - [Link 1](https://www.kaggl... | true |
6b0006215fa7dd9345759d7a7360f703b0029d8f | stacygo/2021-01_UCD-SCinDAE-EXS | /12_Introduction-to-Deep-Learning-in-Python/12_ex_3-03.py | UTF-8 | 662 | 3.15625 | 3 | [] | no_license | # Exercise 3-03: Specifying a model
import pandas as pd
df = pd.read_csv('input/hourly_wages.csv')
target = df['wage_per_hour'].values
predictors = df.drop(['wage_per_hour'], axis=1).values
# Import necessary modules
from tensorflow import keras
from tensorflow.keras.layers import Dense
from tensorflow.keras.models... | true |
d04dc5d43257255bfdeebac1893aa044d2ecac90 | naazimjalal/M.A.T-Military-Activity-Tracker | /tracker/mat/automate.py | UTF-8 | 2,138 | 2.625 | 3 | [] | no_license | import os.path
from functions import data1, scrapeImgs, newCrater, output, newCrate
d = newCrate()
d = str(d)
d = 'a = ', d
d = str(d)
d = d.replace('(', '', 10000000)
d = d.replace("'", "", 2)
d = d.replace(",", "", 1)
d = d.replace('"', "", 10000000)
d = d.replace("])", "]", 10000000)
b = data1("https://... | true |
af11a938c7cffd9976afae0f87f6f97f876b583a | 123zimu123/my_spiders | /vedio_crawl/my_test/crawl_vedio.py | UTF-8 | 1,772 | 2.59375 | 3 | [] | no_license | import requests
import os
import json
from lxml import etree
import re
import random
import time
s = requests.session()
s.keep_alive = False
class bilibili_crawl:
def __init__(self):
self.url = "https://cdn-yong.bejingyongjiu.com/20200420/9950_24170b87/1000k/hls/index.m3u8"
self.headers = {"user-a... | true |
4cde6a64b1bac89efeda5b58b7bb1ce6b028ad5c | dlin94/leetcode | /sort_and_search/88_merge_sorted_array.py | UTF-8 | 598 | 3.421875 | 3 | [] | no_license | def merge(nums1, m, nums2, n):
if n == 0:
return
elif m == 0:
for i in range(0, n):
nums1[i] = nums2[i]
i = 0
j = 0
k = 0 # keep track of index of modified nums1
while i < m and j < n:
if nums2[j] < nums1[k]:
nums1.insert(k, nums2[j])
... | true |
167afb0b90ca9d85c36c6ef9d93a0b497977d43f | bguedj/pyrotor | /pyrotor/datasets.py | UTF-8 | 895 | 3.21875 | 3 | [
"MIT"
] | permissive | # !/usr/bin/env python
# -*- coding:utf-8 -*-
"""
File to load a toy dataset.
"""
from os.path import dirname, join
from glob import glob
import pandas as pd
def load_toy_dataset(dataset_name):
"""
Return a dataset with generic trajectories.
Input:
- dataset_name: str
Name of the da... | true |
127cc1b5c4907324093a300a226e85ebbf557896 | Nikhil-Kasukurthi/Image-Vision-Cascade | /signs.py | UTF-8 | 573 | 2.703125 | 3 | [] | no_license | import cv2
carCascade = cv2.CascadeClassifier('trafficSignsCascade.xml')
video = cv2.VideoCapture('./Dense/jan28.avi')
while True:
ret, image = video.read()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cars = carCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=1
)
# Draw a rectangle ... | true |
b1a1dc8d95d5b656708df34204265ca06fa85b39 | jonathanmann/leetcode | /python2/bit_range.py | UTF-8 | 260 | 3.28125 | 3 | [] | no_license | class Solution:
def rangeBitwiseAnd(self,m,n):
if m == 0: return m
if m == n: return m
while n > m:
n = n & (n-1)
return m & n
s = Solution()
print s.rangeBitwiseAnd(20000,2147483647)
"""
x = m
for i in range(m,n):
x = i & (i+1) & x
return x
"""
| true |
99cf8d8a0b977248327c4a88622d4cff7e00ca23 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/224/users/4381/codes/1596_1015.py | UTF-8 | 296 | 3.40625 | 3 | [] | no_license | # Teste seu codigo aos poucos.
# Nao teste tudo no final, pois fica mais dificil de identificar erros.
# Nao se intimide com as mensagens de erro. Elas ajudam a corrigir seu codigo
a=int(input())
b=int(input())
c=int(input())
print(min(a,b,c))
print(a+b+c-min(a,b,c)-max(a,b,c))
print(max(a,b,c)) | true |
49aa7d646b01370b098e11a4374e3245c95c1ab2 | dahyunhong/CCSF_Classes | /CS110A/extracredit.py | UTF-8 | 208 | 3.625 | 4 | [] | no_license | import turtle
screen = turtle.Screen()
turtle.speed(10)
turtle.color('blue')
sideLength = 10
turtle.right(90)
for i in range(25):
turtle.forward(sideLength*i)
turtle.left(90)
screen.exitonclick()
| true |
06d1735ee4b0ea9f66ff58586467b4c48593a413 | YukiNGSM/PythonStudy | /共通問題/6_9.py | UTF-8 | 130 | 3.609375 | 4 | [] | no_license | for i in reversed(range(1,10,2)):
print(i,'の段',sep='')
for j in reversed(range(1,10)):
print(i,'×',j,'=',i*j) | true |
8318d428bd5f7d1cad480f82752ff3e734cc5cda | YangStark/32ics | /Project2/internet/local_version.py | UTF-8 | 2,547 | 3.375 | 3 | [] | no_license | import connectfour
'''
ICS 32 Project 2
UCI_ID:16452673 Name: Zian Yang
UCI_ID:88474044 Name: Yu Zhang
'''
def manual():
print("Hi Welcome to the connect four game!")
print("The input should follow the format 'D 2' or 'p 1'.")
print("'D' for drop and 'P' for move and second number is the ... | true |
99bcb505c772155829264f8e8163ac673c807ac3 | mindcurry/InterviewBit | /Level 2/Arrays/Maximum Unsorted Subarray.py | UTF-8 | 1,053 | 3.8125 | 4 | [] | no_license | '''
You are given an array (zero indexed) of N non-negative integers, A0, A1 ,…, AN-1.
Find the minimum sub array Al, Al+1 ,…, Ar so if we sort(in ascending order) that sub array, then the whole array should get sorted.
If A is already sorted, output -1.
Example :
Input 1:
A = [1, 3, 2, 4, 5]
Return: [1, 2]
Input... | true |
314aaab0aff92828f2d2c0fdee382ea703901a09 | jpratty/intermediate-python-course | /dice_roller.py | UTF-8 | 266 | 3.921875 | 4 | [] | no_license | import random
def main():
dice_rolls=2
roll_sum = 0
for i in range(0,dice_rolls):
roll= random.randint(1,6)
print(f'You rolled a {roll}')
roll_sum += roll
print(f'Your total is {roll_sum}')
if __name__== "__main__":
main()
| true |
0e7c71494809736e747dd44d940a167573e7849d | msahu2595/PYTHON_3 | /210_17_exception_handling.py | UTF-8 | 416 | 3.375 | 3 | [] | no_license | # Exception handeling
# try except else finally
while True:
try:
age = int(input('enter your age: '))
break
except ValueError:
print("maybe you entered string instead of number, try again")
except:
print('invalid input')
# age = int(input('enter your age: '))
if age < 1... | true |
f52773989c8698b1f84a4f094107d23c020f96ed | chris3torek/scripts | /sizewatch | UTF-8 | 3,382 | 2.8125 | 3 | [
"BSD-3-Clause"
] | permissive | #! /usr/bin/env python
"watch file(s) grow in size"
import os
import stat
import subprocess
import sys
import time
import argparse
def timeout_arg(string):
"handle argument for -t: float >= 0.0"
value = float(string)
if value < 0:
raise argparse.ArgumentTypeError('timeout must be at least 0.0')
... | true |
fbea28495b1e1cc0de3dbd1f178008cecc39b311 | banje/acmicpc | /10817.py | UTF-8 | 67 | 3 | 3 | [] | no_license | a,b,c=input().split()
d=[int(a),int(b),int(c)]
d.sort()
print(d[1]) | true |
2899f83bf45af1e65a6f676e344e316ad8c989ea | HouariZegai/github-do-not-ban-us | /together/edbedbe/together.py | UTF-8 | 211 | 2.921875 | 3 | [] | no_license | #!/usr/bin/env python3
for access in ['GitHub', 'Open Source']:
for all_people in ['Everyone', 'Iranians', 'Syrians', 'Crimeans', 'Cubans', 'North Koreans']:
print(f'{access} is for {all_people}!')
| true |
c5975d24f3d3a02cc3462829f196c48359ec921b | christianvadillo/ML | /00_utils/scratch_codes/scratch_full_batch_stochastic_gd.py | UTF-8 | 7,001 | 2.734375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 11 11:03:14 2020
@author: 1052668570
"""
import numpy as np
import matplotlib.pyplot as plt
import scratch_mnist_betchmark_utils as utils
from sklearn.utils import shuffle
from datetime import datetime
def bechmark_full_gd(lr=0.0001, epochs=200):
X_train, X_test, ... | true |
422d3d2fea7be69bc892272899acaa4a7af404c7 | wangbaliang/thrift_service | /etutorservice/utils/datetime_helper.py | UTF-8 | 1,260 | 2.96875 | 3 | [
"ISC"
] | permissive | # -*- coding: utf-8 -*-
import arrow
from datetime import time, datetime
def format_date(date_info, date_format='YYYY-MM-DD', tz=None):
result = arrow.get(date_info)
if tz:
result = result.to(tz)
return result.format(date_format)
def to_timestamp(date_info, tz=None):
if tz:
return ... | true |
907cc58eebfdf61fda8cb101cff1976e34fcbeae | VladYashin/google_trends_analysis | /geo_data.py | UTF-8 | 1,833 | 2.640625 | 3 | [] | no_license | import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt
shapefile = 'gpd_shapefiles/vg2500_bld.shp'
excl = pd.read_excel('google_trends_kw.xlsx', sheet_name='Datenbasis (By region)')
df_ibr = pd.DataFrame(excl)
map_df = gpd.read_file(shapefile)
merged_dfs = map_df.set_index('GEN').join(df_ibr.set... | true |
371696526d924728f8d264a945219b0abd237e6c | keir/gastronomicus | /scripts/venison_gifters.py | UTF-8 | 1,500 | 2.84375 | 3 | [] | no_license | from collections import defaultdict
from gastronomicus.models import Serving
from gastronomicus.models import Meeting
# Top givers:
#
# Earl of Marchmont Hugh Hume - 88 id: 270
# Esq. Edward Hooper - 19 id: 403
# Earl of Morton James Douglas - 14 id: 100
# Mr. Joseph Banks - 10 id: 530
# Esq. Charles Stanhop... | true |
964bd7478c76850c065b23fee716ca71a6917d03 | Long0Amateur/Self-learnPython | /Chapter 7 Lists/problem/8. A program creates a list of factors of an input integer..py | UTF-8 | 255 | 4.28125 | 4 | [] | no_license | # A program asks user for an integer and creates a list that consists
# of the factors of that integer
x = eval(input('Enter an integer:'))
M = []
for i in range(1,x+1):
if x%i == 0:
M.append(i)
print('The factors of',x,':',M)
| true |
9cb605c0a86f41c25ec992b56fabb78711b7bd3a | sih4sing5hong5/liah8_bang2-loo7_tsu1-liau7 | /掠網路資料/看掠著的網站.py | UTF-8 | 1,938 | 2.921875 | 3 | [] | no_license | from urllib.request import urlopen
import html2text
import os
import subprocess
class 看掠著的網站:
def 對網頁看(self, 網址):
with urlopen(網址) as 資料:
return self.提網頁文字出來(資料.read().decode('utf-8'))
def 對檔案看(self, 檔名):
print(檔名)
try:
with open(檔名) as 資料:
return self.提網頁文字出來(資料.read())
except:
轉碼過 = subprocess... | true |
55d6d736b4682b05b85e21214e9881daf8f802de | almogboaron/IntroToCsCourseExtended | /generetor.py | UTF-8 | 1,681 | 3.953125 | 4 | [] | no_license | def naturals():
""" a generator for all natural numbers """
# print("start naturals")
n = 0
while True:
yield n
n += 1
# nat = naturals()
# for i in range(10):
# print(next(nat))
# for i in range(10):
# print(next(naturals()))
def fib():
""" a generator f... | true |
780586d4ca8e722b55a14181d0c1d823788dd469 | mtiid/putil | /docs/support/exh_example.py | UTF-8 | 540 | 2.8125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # exh_example.py
# Copyright (c) 2013-2016 Pablo Acosta-Serafini
# See LICENSE for details
# pylint: disable=C0111,C0302,W0212,W0640
from __future__ import print_function
import putil.exh
EXHOBJ = putil.exh.ExHandle()
def my_func(name):
""" Sample function """
EXHOBJ.add_exception(
exname='illegal_na... | true |
96713f8e5322bf4277acf3ef4de3f77b859a5980 | cotect/covid-local-api | /app/covid_local_api/endpoints.py | UTF-8 | 9,107 | 2.5625 | 3 | [
"MIT"
] | permissive | import geocoder
import uvicorn
from starlette.responses import RedirectResponse
from fastapi import FastAPI, Query, HTTPException
from typing import List
from enum import Enum
from timeloop import Timeloop
from datetime import timedelta
from covid_local_api.__version__ import __version__
from covid_local_api.db_handle... | true |
171578fa0427972b4ce04412acbdee400b3aff9a | JerryChen97/KitaevLadder | /rotation.py | UTF-8 | 1,184 | 3.421875 | 3 | [] | no_license | # in this file we will implement the rotation for (Jx, Jy) -> (a, b)
import numpy as np
special_shift = 0.001
def avoid_special_points(Jx, Jy, Jz):
if Jx == 0:
Jx += special_shift
if Jy == 0:
Jy += special_shift
if Jz == 0:
Jz += special_shift
return (Jx, Jy, Jz)
def clean_min... | true |
f9ff3bc1d659906f7d364bc7006036c54c15ed5e | VainF/Torch-Pruning | /benchmarks/engine/models/cifar/mobilenetv2.py | UTF-8 | 2,818 | 2.9375 | 3 | [
"MIT"
] | permissive | """mobilenetv2 in pytorch
[1] Mark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, Liang-Chieh Chen
MobileNetV2: Inverted Residuals and Linear Bottlenecks
https://arxiv.org/abs/1801.04381
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
class LinearBottleNeck(nn.Module):
de... | true |
b24010cd4d532abdca6a76bfbde4115e5b313a3c | Gowtham-cit/Python | /Guvi/partial_sorting_of_an_array.py | UTF-8 | 737 | 4.15625 | 4 | [] | no_license | '''You are given an array of N elements. Your task is to sort a subarray denoted by the index values i1 and i2 in descending order. Note: Index values start at 0. The sorting must be completed in O(i2-i1+1)log(i2-i1+1)
Input Description:
Size of array followed by elements of the array. The third line contains th... | true |
8347d2429ce341a55fe3f2b84f723d1f4c4184c5 | 1769258532/python | /py_core/day7/exception.py | UTF-8 | 394 | 2.96875 | 3 | [] | no_license | # -*-coding:utf-8 -*-
# !/usr/bin/python3
# @Author:liulang
'''
1001 : 被0除
1002: 参数类型错误
1003: 消息内容过少
'''
class My_Exception(Exception):
def __init__(self, error_code) -> None:
self.error_code = error_code
def __str__(self):
return str(self.error_code)
if __name__ == '__main__':
e = M... | true |
4797157fce651b1037cfb06b63cdbd872bd56780 | gaurakshay/PredictingParkinsons | /regularized_linear_regression.py | UTF-8 | 5,060 | 3.3125 | 3 | [
"MIT"
] | permissive | """ CS 5033 Homework 2
Code for Problem 1
"""
import os
import numpy as np
from numpy import genfromtxt
from sklearn.linear_model import ElasticNet
import math
from matplotlib import pyplot as plt
# Specify the filepath.
pwd = os.path.dirname(__file__)
filepath = os.path.join(pwd, 'ParkinsonsData/par... | true |
304a19c9fd6db47a930999f586197fc7db8c44ba | ZandTree/nep-shop | /bookstore/utils.py | UTF-8 | 1,533 | 3.203125 | 3 | [] | no_license | import random
import string
from django.utils.text import slugify
def make_random_string(chars=(string.ascii_lowercase + string.hexdigits),size=6):
"""
return string made of random (ascii-chars,digits)of length = size
"""
output = [random.choice(chars) for _ in range(size)]
return "".join(output)
... | true |
716917952665303c2cce8406e7b1cb7409bd5e8b | DeepanChakravarthiPadmanabhan/Soccer_Robot_Perception | /soccer_robot_perception/datasets/segmentation_dataset.py | UTF-8 | 2,857 | 2.65625 | 3 | [
"MIT"
] | permissive | import os
import typing
import logging
import re
import cv2
import gin
import torch
import numpy as np
from torch.utils.data import Dataset
import PIL.Image
LOGGER = logging.getLogger(__name__)
@gin.configurable
class SegmentationDataset(Dataset):
""""""
def __init__(
self,
root_dir: str,
... | true |
00787f2f9919b312a6a36fa37de9e3d695917dbf | JonnatasCabral/algorithms | /caesar_cipher.py | UTF-8 | 345 | 3.71875 | 4 | [] | no_license | # Caesar Cipher
def shift_position(shift, letter):
if shift > 90 and letter.isupper():
shift -= 26
elif shift > 122 and letter.islower():
shift -= 26
return shift
def encrypt(v, k):
v = map(
lambda x: chr(
shift_position(ord(x) + k % 26, x)) if x.isalpha() else x, ... | true |
afbb14b48273067d7b90a8f77fe396ff1d7ecccc | scott2000jones/ai-philosopher | /src/twitterbot.py | UTF-8 | 573 | 2.65625 | 3 | [] | no_license | from textgenrnn import textgenrnn
import tweepy
auth = tweepy.OAuthHandler(@, @)
auth.set_access_token(@, @)
api = tweepy.API(auth)
def generate_tweet():
textgen = textgenrnn('../weights/tao.hdf5')
tweet = ""
generation = ""
# avoid chance of empty tweet
while len(generation) < 20:
gene... | true |
63fb58a4637660503d2630363c1117fda5aef0d6 | kapilmathe/algorithms | /pp01/pp01/Microsoft/KeyPair.py | UTF-8 | 468 | 3.625 | 4 | [] | no_license | # https://practice.geeksforgeeks.org/problems/key-pair/0
def key_pair(a, n, x):
a.sort()
i = 0
j = n-1
while i < j:
if a[i]+a[j] > x:
j -= 1
elif a[i]+a[j] < x:
i += 1
else:
return 'Yes'
return 'No'
t = int(input().strip())
for i in range... | true |
35bcb02c098f20de4af4f13c70f58f640222554f | delaven007/4-redis-spider | /spider/spider-6-多线程写入同一文件-cookie模拟登陆-三个池子-解析模块-selenium/04_tencent_process.py | UTF-8 | 2,496 | 2.890625 | 3 | [] | no_license | from multiprocessing import Process
from useragents import ua_list
import requests
import json
import time
import random
from queue import Queue
class TencentSpider():
def __init__(self):
self.one_url='https://careers.tencent.com/tencentcareer/api/post/Query?timestamp=1563912271089&countryId=&cityId=&bgIds=... | true |
aebac9a5686b3f30d914f10f9a2f124af60c5177 | pdshah77/flask_rest_project | /myprojectapi/common/accessing_hellofresco_app.py | UTF-8 | 259 | 2.84375 | 3 | [] | no_license | from urllib import request
# Single Request to Fetch Home Message
request1 = request.Request('http://127.0.0.1:5000/')
try:
response1 = request.urlopen(request1)
print(response1.read())
except urllib.error.HTTPError as e:
print(e.code, e.read()) | true |
415728096ac3587342f894a20d497fd71a9d7a0d | NickDienemann/Bewerbung_NLP | /eda_toolkit.py | UTF-8 | 11,464 | 3.796875 | 4 | [] | no_license | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
class Cat_vs_cat_explorer():
"""
class that holds functions to explore relations between Categorical Features and Categorical Target
"""
def __init__(self,df):
"""
... | true |
6e0e788f6b0e2b23db0fcdcd9900056d461fc2c9 | DanaJoffe/Computational-Biology | /ex1/graphics/animation.py | UTF-8 | 3,241 | 3.234375 | 3 | [] | no_license | import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import colors
from configuration import CELL_STATES, CELL_COLORS, SPEED, SHOW_LABELS
def create_cmap():
# map colors
cols = [color for _, color in sorted(zip(CELL_STATES, [CELL_COLORS[n] for n in CELL_STATES]))]
nums ... | true |
1d36e2511d980333e060ea6c13a089d1b4730008 | screwed99/random_forest | /trees/tests/BinaryDecisionTreeTests.py | UTF-8 | 9,679 | 2.9375 | 3 | [] | no_license | import unittest
from unittest.mock import patch
import pandas as pd
from copy import deepcopy
from trees.BinaryDecisionTree import BinaryDecisionTree
class CopyingMock(unittest.mock.MagicMock):
def __call__(self, *args, **kwargs):
args = deepcopy(args)
kwargs = deepcopy(kwargs)
return sup... | true |
22c5c8e83880946d049b82fd03a99bc82fff04de | WesleyAlford/Misc | /Hacker Rank Challenges/Finding the Percentage/findPercent.py | UTF-8 | 501 | 3.21875 | 3 | [] | no_license | # Enter your code here. Read input from STDIN. Print output to STDOUT
num_students = int(raw_input())
for i in range(0,num_students):
record = raw_input()
split_record = record.split()
key = split_record[0]
if i == 0:
records = {key:split_record[1:]}
else:
records[key] = split_record... | true |
1ddc2c8c8eb415eb1456743c48808d44fb464e36 | austinhappy/Day3_test | /list.py | UTF-8 | 355 | 4.03125 | 4 | [] | no_license | # list 清單介紹
student = []
num = 1
print('輸入班級同學名字')
while True:
name = input('第 %d 位同學:' % num)
if name == "end":
break
else:
student.append(name)
num += 1
print("班級共 %d 位同學" % len(student))
print("名字分別是", student)
print('austin' in student) #檢查東西是否在清單裡,算是是非題
| true |
2cd6c27c977cf5fa842c7dc5f18a8bb539b563c5 | egyeasy/TIL_public | /baekjoon/2588_곱셈.py | UTF-8 | 200 | 3.078125 | 3 | [] | no_license | first = int(input())
second = input()
summ = 0
idx = 1
for digit in second[::-1]:
part_result = first * int(digit)
print(part_result)
summ += part_result * idx
idx *= 10
print(summ) | true |
5f7e67fd6ced4b73e10e7aa57c900e902b763cce | Ankit8989/Sample_Data | /Cass_Shape.py | UTF-8 | 805 | 4.25 | 4 | [] | no_license | #To create class Shape and derive class as Rectangle and Circle
class Shape:
def __int__(self):
self.colour='Black'
class Rectangle(Shape):
def __int__(self):
super().__init__() #to call base class
self.length=0
self.breath=0
self.colour='Blue'
def... | true |
ea6f50ff9e234f149544738910f9cbece68fc711 | tankeryang/flasto-service | /query_service/apis/crm/cic_static/utils/mapper.py | UTF-8 | 317 | 2.75 | 3 | [] | no_license | def mapper(sql, payload):
"""
payload 参数校验
query_sql 参数填充
:param sql: sql字符串
:param payload: restplus.Api.payload 传入参数
:return: 填充参数后的sql
"""
brands = str(payload['brands']).strip('[').strip(']')
return sql.format(brands=brands)
| true |
ad82ee885b9a004ecc4b81b954a7f07d8bcf6a7b | Erick-Faster/webscrap | /scrapfile.py | UTF-8 | 1,607 | 2.953125 | 3 | [] | no_license | import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import pandas as pd
def scrape_site(SAMPLE_URL):
SAMPLE_URL = 'https://webscraper.io/test-sites/tables/'
print(f"Begin extraction of {SAMPLE_URL}")
options = webdriver.ChromeOptions... | true |
c2a41b3152c4a0803f5fe62373cfdd17ad3bc310 | anton1k/python_crash_course | /part_2/games/game_12_5/game_functions.py | UTF-8 | 2,530 | 3.265625 | 3 | [] | no_license | import sys
import pygame
from bullet import Bullet
def check_keydown_events(event, ai_settings, screen, ship, bullets):
'''Реагирует на нажатие клавиш'''
if event.key == pygame.K_DOWN:
ship.moving_down = True
elif event.key == pygame.K_UP:
ship.moving_up = True
elif event.key == pygam... | true |
9f0e621f0af0bccafc1cde0f341e473be4f6e777 | znwang25/SmartStorage | /envs/dynamic_prob_env.py | UTF-8 | 10,925 | 2.703125 | 3 | [] | no_license | import numpy as np
from collections.abc import Iterable
import scipy.sparse as sparse
import itertools
from utils.utils import random_choice_noreplace, random_permutation
import logger
class DynamicProbEnv(object):
"""
Description:
This wrapper constructs state and provide various utilities for reinforcem... | true |
b058a44f8d23ceba4753a7e0f914a7703d9761a7 | Scarecrow1024/Python | /标志位.py | UTF-8 | 1,100 | 3.46875 | 3 | [] | no_license | # coding=utf-8
import threading, time
"""
简单信号量栗子,模拟黄绿灯
"""
event = threading.Event()
def lighter():
count = 0
event.set() #设置信号量为绿灯,车可以通过
while True:
if count > 10 and count < 20:
event.clear() #清空信号量为红灯车不能通过
print("\033[41;1mred light is on...\033[0m")
elif cou... | true |
4acde738c3b14c5627e68f1982a1ef638cbe33e5 | xkrakovskym/CoffeeMachine | /definitions.py | UTF-8 | 1,259 | 4 | 4 | [] | no_license | from enum import Enum
class MachineState(Enum):
mainMenu = 'Write action (buy, fill, take, remaining, exit):'
buyMenu = 'What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino:'
coffeeDone = 'I have enough resources, making you a coffee!\n'
coffeeNotDone = 'Sorry, not enough {}!\n'
fillW... | true |
59fbf537a8d8b9e8cdf33cf8696bed8c3daba6ea | MCavigli/AirBnB_clone_v2 | /web_flask/8-cities_by_states.py | UTF-8 | 626 | 2.65625 | 3 | [] | no_license | #!/usr/bin/python3
# displays states and associated cities
from flask import Flask, render_template
from models import storage
from models.state import State
app = Flask(__name__)
app.url_map.strict_slashes = False
ip = '0.0.0.0'
port = 5000
@app.route('/cities_by_states')
def states_list():
# lists the states an... | true |
9e211d19935bf574e45159f499676305ad27f0d5 | rheineke/log_merge | /main.py | UTF-8 | 2,419 | 3.265625 | 3 | [
"MIT"
] | permissive | """Read any number of files and write a single merged and ordered file"""
import time
import fastparquet
import numpy as np
import pandas as pd
def generate_input_files(input_filenames, n, max_interval=0):
for i_fn in input_filenames:
df = _input_data_frame(n,
max_interval=... | true |
a7c0718b111f6605d0a318eea85b042af7e096c7 | ja1goncalves/traceroute | /Traceroute.py | UTF-8 | 3,940 | 2.96875 | 3 | [] | no_license | #!/urs/bin/python
# coding=UTF-8
import random
import time
import socket
import struct
import sys
import signal
def signal_handler(sig, frame):
print('\nSee you, bye! \U0001f600 \U0001F618 \U0001F44B')
sys.exit(0)
def main():
print('-' * 60)
print("Init the footprint to target | Press Ctrl+C to exi... | true |
c4a551b071b0b3c14105c4847203fff45f81ebba | MarcosMaciel-MMRS/Desenvolvimento-python | /Python-desenvolvimento/ex035.py | UTF-8 | 602 | 3.921875 | 4 | [
"MIT"
] | permissive | #Analisando condiçôes para formação de triângulos.
#condição de existência: a medida de um lado for menor q a soma dos seus outros 2 segmentos.
print('-=-'*15)
print(' ANALISADOR DE SEGMENTOS')
print('-=-'*15)
r1 = float(input('Informe o primeiro segmento de reta: '))
r2 = float(input('Informe o segundo s... | true |
3fa0ffe1078d141d686d03b10c682c370bec492e | HiperbolickiParaboloid/Homework-3 | /zad1.py | UTF-8 | 3,100 | 3.109375 | 3 | [] | no_license | class Article:
def __init__(self, title, author, description, category, views = 0, comments = []):
self.__title = title
self.__author = author
self.__description = description
self.__category = category
self.__views = views
self.__comments = comments
#self.__n... | true |
329ab73a08d3dcdaf7f9533dce0cbe7f12439ae8 | njrahman/FUT-Random-Team | /import_data.py | UTF-8 | 930 | 3.125 | 3 | [] | no_license | import pandas as pd
import pprint as pprint
import random as random
import networkx as nx
player_data = pd.read_csv("fifa_19_player_data.csv", encoding="latin-1")
players = player_data["Player Name"]
clubs = player_data["Club"]
leagues = player_data["League"]
nationalities = player_data["Nationality"]
positions = pla... | true |
20c794cd98acfc52f17018b6fc603f7a2f90fcad | OluyemiJ/Local-energy-system-optimisation | /code/save_param.py | UTF-8 | 928 | 2.65625 | 3 | [] | no_license | #-----------------------------------------------------------------------------#
# Save Parameters
#-----------------------------------------------------------------------------#
from pyomo.core import *
def model_saveParam(model, param_file):
print("Saving model parameter values to text file...")
wi... | true |
f3d18cb17fc35a2adb60a1dd1e572ea0c9d742cc | danikoskas97/PythonTask04 | /main.py | UTF-8 | 1,305 | 3.5 | 4 | [] | no_license | from datetime import date
from student import Student
from lecturer import Lecturer
student1 = Student('Dani', 'koskas', '1997,6,04', 'Raanana', '0584190758'
, 'koskas.dani@gmail.com', ['python', 'js'], 2)
student2 = Student('Blaise', 'Matudi', '1979,4,12', 'Paris', '008-3402202'
... | true |
6f2bba2a58f218077ef4a682aad898b325e4081e | hubewa/KaggleGroceryForecasting | /src/xgboostTraining.py | UTF-8 | 1,038 | 2.84375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 16 23:24:34 2017
@author: Hubert
"""
import xgboost as xgb
import sklearn
import numpy as np
import pandas as pd
import datetime
import math
def trainXGModel(train):
target = train['unit_sales']
train['unit_sales'] = train['unit_sales'].astype('category')
... | true |
d3536dd3827c7bed3067a4461c1d66db021b802f | william1530/PlayRandomMovie | /movie.py | UTF-8 | 1,449 | 2.75 | 3 | [] | no_license | import os, random,subprocess, sys, platform
#get the file name
file_name = __file__
#get path from file_name
dir_path = os.path.dirname(os.path.realpath(file_name))
#change current working directory to where the file lies
os.chdir(dir_path)
#get current working directory
cwd = os.getcwd()
#set message text for the... | true |
ab0e672b3816d4fa47ed3632e7dd412d118dc050 | tails1434/Atcoder | /ABC/152/D.py | UTF-8 | 504 | 3.25 | 3 | [] | no_license | def main():
N = int(input())
cnt = 0
'''
i => Aの末尾の桁が Bの先頭の桁
j => Bの末尾の桁が Aの先頭の桁
'''
cnt = [[0] * 10 for _ in range(10)]
for i in range(N+1):
tmp = str(i)
first = int(tmp[0])
last = int(tmp[-1])
cnt[first][last] += 1
ans = 0
for i in range(1,10):
... | true |
82a76e8bfbd1358d47b8b86c4a3be925d2b6999d | ZS-Lib/slime_mould | /plot.py | UTF-8 | 2,814 | 3.09375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
# Creates plot of Region and Planned Path
#
# To test code, just run "plot()"
# x1,x2 are set to default values
# function set to Ackley by default
#
# To run real values run:
# plot(x1,x2,f)
# f = local min function, values below
# LocMinFuncs.ackley
# .bukin6
# ... | true |
2fa3ef7aef2596fd6ea4ba9f18ae56add1392572 | CSAIL-LivingLab/wifi-scraper | /wifi-scraper.py | UTF-8 | 3,733 | 2.640625 | 3 | [] | no_license | import time
import os
import requests
import json
from datetime import datetime
from datahub import DataHub
from secret import client_id, client_secret, username, password, ISTUSER, \
ISTPASS
def scrape_data():
tstamp = datetime.now()
json_data = []
try:
r = requests.get('https://nist-data.mi... | true |
6cf271f3348e29d6d89ba9c33fc8399472ac0cb2 | alinasansevich/hello-world | /black_friday_must_do.py | UTF-8 | 785 | 4.1875 | 4 | [] | no_license | # Inspired by the book "Automate the boring stuff with Python"
def print_list(items_dict, left_width, right_width):
print('SHOPPING LIST'.center(left_width + right_width, '-'))
for k, v in items_dict.items():
print(k.title().ljust(left_width, '.') + str(v).rjust(right_width, ' '))
black_friday_wish_li... | true |
07e1678d0ef84122a596e1b00b556b53e725de3f | haasosaurus/kaa | /kaa/exts/memes/_meme_generator.py | UTF-8 | 6,192 | 2.90625 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
# standard library modules
import io
import pathlib
# third-party packages
from PIL import Image, ImageDraw, ImageFont
class MemeGenerator:
def __init__(self) -> None:
"""initializer"""
# fonts
font_directory = 'resources/fonts'
font_name = 'impact.ttf'
... | true |
473508d3c39a6f857641ab65d498d7907e844cb8 | boschresearch/pcg_gazebo | /pcg_gazebo/parsers/types/string.py | UTF-8 | 1,773 | 2.609375 | 3 | [
"CC0-1.0",
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # Copyright (c) 2019 - The Procedural Generation for Gazebo authors
# For information on the respective copyright owner see the NOTICE file
#
# 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
#
#... | true |
32248a8f97320ee6800493ee5f01ee7c0f7e021c | southernsky/CorePythonProgramming | /eg11.3-numconv.py | UTF-8 | 244 | 3.5625 | 4 | [] | no_license | #!/usr/bin/env python3
# -*-coding:utf=8 -*-
def convert(fun,seq):
'convert sequence of numbers to same type'
return [fun(eachnum) for eachnum in seq]
seq = [123,45.67,-6.2e8,99999]
print(convert(int,seq))
print(convert(float,seq))
| true |
9223672313ce82db072621f4cfe4e2ff734ff426 | lanjianghua/mysiteday71 | /ORM_01.py | UTF-8 | 999 | 2.515625 | 3 | [] | no_license | import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysiteday71.settings')
import django
django.setup()
from app01 import models
# ret = models.Employee.objects.all().values('name', 'department')
# print(ret)
# from django.db.models im... | true |
e5133f30844d8f0a699089ef712e748dc51343e8 | IFennelly/Introrepo | /A Friday 28th Code.py | UTF-8 | 2,653 | 2.734375 | 3 | [] | no_license |
import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
pd.read_csv(r'C:\Users\Inez\Documents\IntroRepo\Hotel Booking Data\hotel_bookings.csv')
hotel_bookings = pd.read_csv(r'C:\Users\Inez\Documents\IntroRepo\Hotel Booking Data\hotel_bookings.csv')
# Importing CSV file into ... | true |
f32a66e7c125a729597fb2936845f7c3c0f94a97 | whikwon/recommender-system | /utils/helpers.py | UTF-8 | 6,300 | 3.359375 | 3 | [] | no_license | import scipy.sparse as sp
import numpy as np
def threshold_interactions_df(df, row_name, col_name, row_min, col_min):
"""Limit interactions df to minimum row and column interactions.
Parameters
----------
df : DataFrame
DataFrame which contains a single row for each interaction between
... | true |
0931cebaa7ba0d0a82995811512a2141f1749678 | maltejur/10-minute-mail | /minutemail.py | UTF-8 | 1,285 | 2.734375 | 3 | [] | no_license | #!/usr/local/bin/python3
# -*- coding: utf-8 -*-
# depends on websocket-client and pyperclip
import websocket
import pyperclip
import sys
import os
import requests
import re
from json import loads
from datetime import datetime
class mailbox(object):
"""10 minute mailbox"""
def __init__(self):
super(mailbox, self)... | true |
eef603033d77a5079d588a031934c7c8d2cfffad | Harris-Chara/Python-Spammer | /spammer.py | UTF-8 | 1,078 | 2.9375 | 3 | [] | no_license | import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# log in to the email you're sending from (not recommended to use your personal email)
sender = ''
password = ''
# email address of your enemy
target = ''
session = smtplib.SMTP('smtp.gmail.com', 587)
session.starttls... | true |
8078e55d7e56f8e8b7307d52a8b59ddcb1ba03e2 | edfine/intro_py101 | /lab_reverse.py | UTF-8 | 164 | 2.703125 | 3 | [] | no_license | with open('hamlet.txt', 'r') as fham:
lham = fham.readlines()
lham.sort(reverse=True)
with open('telmah.txt', 'w') as fhamr:
print(lham, file=fhamr, end='') | true |
d30dee8a06204b195b0b954117847c2071beda94 | parulsharma-121/CodingQuestions | /day_149_GenerateaStringWithCharactersThatHaveOddCounts.py | UTF-8 | 647 | 4.21875 | 4 | [] | no_license | '''
Given an integer n, return a string with n characters such that each character in such string occurs an odd number of times.
The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them.
Example 1:
Input: n = 4
Output: "pppz"
Explanation: "pppz" i... | true |
dbc1368dc0c565881f71b298fac251fd77821e8f | mahmoud-youssef/python-test | /test.py | UTF-8 | 3,094 | 2.765625 | 3 | [] | no_license |
ContactsList = {"1" : "Alice Brown / None / 1231112223","2" : "Bob Crown / bob@crowns.com / None","3" : "Carlos Drew / carl@drewess.com / 3453334445","4" : "Doug Emerty / None / 4564445556","5" : "Egan Fair / eg@fairness.com / 5675556667"}
LeadsList = {'1' : 'None / kevin@keith.com / None','2' : 'Lucy / lucy@liu.com... | true |
c92585472b2d227907ed2c0075272d8f4e50a911 | nicovalle/isw2 | /tp1/src2/posiciones/alero.py | UTF-8 | 186 | 2.625 | 3 | [] | no_license | from posicion import Posicion
class Alero(Posicion):
def __init__(self):
self._nombre = "alero"
def jugadorConPosicion(self, unEquipo):
return unEquipo.alero()
| true |
6558ecae455139ce28c5780f35961244f4b5adfe | backtothefuture3030/paikjoon | /백준 1541.py | UTF-8 | 614 | 2.9375 | 3 | [] | no_license |
num = input()
numbers = []
n = []
for i,j in enumerate(num):
if j=="-":
n.append(i)
n.append(len(num))
A = int(num[:n[0]])
for i in range(0,len(n)-1):
numbers.append(num[n[i]+1:n[i+1]])
t= []
q = []
for i in numbers:
w = list(map(int,i.split("+")))
t.append(w)
for i in t:
q.append(sum(i)... | true |
bbef8bcd58f4f7bb7c0249eb258df16bb7d5fcc8 | colinmiller94/Project_Euler | /e25.py | UTF-8 | 338 | 3.609375 | 4 | [] | no_license |
fib_dict ={}
def fibonacci(n):
if n in fib_dict:
return fib_dict[n]
if n == 1:
res =1
elif n == 2:
res = 1
else:
res = fibonacci(n-1) + fibonacci(n-2)
fib_dict[n] = res
return res
i = 1
while fibonacci(i) < 10**999:
#print fibonacci(i)
i +=1
print(fibo... | true |
49cbb944e803e5fab7c062c4c46c3f4d47f5d94c | agoragames/pluto | /test/functional/node_test.py | UTF-8 | 1,029 | 2.6875 | 3 | [
"MIT"
] | permissive |
from chai import Chai
from pluto.node import Node
class ScheduleTest(Node):
def run(self):
print 'run schedule test'
class NodeTest(Chai):
def setUp(self):
super(NodeTest,self).setUp()
Node.backend = {}
Node.backend.drop()
def test_node_can_save(self):
n = Node()
n.save()
def test_... | true |
07cfbc5dad0e7068563edfb0ae36d7e2c3326a05 | superpipal-yi/PlayGround | /LeetCode/ShortestWordDistance.py | UTF-8 | 999 | 3.078125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 17 20:42:38 2017
@author: zhang_000
"""
#shortest word distance
def getShortestWordDistance(S, w1, w2):
distance = len(S)
idx1 = -1
idx2 = -1
for i in range(len(S)):
if S[i] == w1:
idx1 = i
if idx2 >= 0:
di... | true |
3ad2bb557a460a0201830083d1a80091ebb44e4a | rcbops-qe/monster | /monster/features/base.py | UTF-8 | 523 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | """Base feature."""
class Feature(object):
def __repr__(self):
return 'class: ' + self.__class__.__name__
def __str__(self):
"""Prints out class name in lower case.
:rtype: str
"""
return self.__class__.__name__.lower()
def update_environment(self):
pass
... | true |
309841394cf76e35d7af635866b443b077045aa4 | AdityaChirravuri/CompetitiveProgramming | /HackerRank/Python/Introduction/Python_If-else.py | UTF-8 | 315 | 2.671875 | 3 | [
"MIT"
] | permissive | import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(raw_input().strip())
if n%2==1 :
print("Weird")
else :
if n>=2 :
if n<=5 :
print("Not Weird")
if n>=6 :
if n<=20 :
print("Weird")
else : print("Not Weird")
| true |
8bf42b16a16200e604ede4648abdc094c7362da8 | mjmiranda-dhi/w210-dataquality-project | /hierarchy.py | UTF-8 | 1,121 | 3.125 | 3 | [] | no_license | dim_df = #input file into pandas df
# creates a dateframe of fields sorted by count of unique values
sum_df = pd.DataFrame.from_dict({column: len(dim_df[column].unique()) for column in dim_df.columns}, orient='index')
sum_df.reset_index(inplace=True)
sum_df.columns = ['FIELDS','UNQ_VALUES']
sum_df.sort_values('U... | true |