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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
8f9ee93f9bde30042c9daf590a02098fcbbdff92 | Python | bloolizard/Intro2Python | /mini_project3.py | UTF-8 | 1,872 | 3.546875 | 4 | [] | no_license | # template for "Stopwatch: The Game"
# by Edwin Villanueva
# last updated 10/31/2013
import simplegui
import random
import math
import time
# define global variables
gtime = 0
# define helper function format that converts time
# in tenths of seconds into formatted string A:BC.D
def new_game():
f... | true |
9bae631602240e5c3528c49183bf882109f82e16 | Python | mindnhand/Learning-Python-5th | /Chapter27.ClassCodingBasics/third_class_example.py | UTF-8 | 1,489 | 3.78125 | 4 | [
"MIT"
] | permissive | #!/usr/bin/env python3
#encoding=utf-8
#---------------------------------------------------
# Usage: python3 third_class_example.py
# Description: Operator overload
#---------------------------------------------------
from second_class_example import SecondClass
class ThirdClass(SecondClass): ... | true |
db98d744c0fd60a0194ea82493aa60a20c3817dc | Python | profidev/worm | /src/renderer/wormrenderer.py | UTF-8 | 1,084 | 2.796875 | 3 | [
"MIT"
] | permissive | import time
import pygame
from src.colors import *
from src.constants import *
from src.worm import Direction
class WormRenderer:
DEATH_COLORS = [RED, LIGHT_GREY, WHITE, BLUE, BLACK, RED, LIGHT_GREY]
def __init__(self, screen):
self.__screen = screen
self.__color = SANDY_BROWN
def rend... | true |
3a246432010d4f4da2ca251b82d6fbf1bd52ec75 | Python | Flinnj77/ECEN361-Final-Project | /baby_drone(0.2)/position.py | UTF-8 | 264 | 3.75 | 4 | [] | no_license | import math
class Position:
def __init__(self):
self.x = 0
self.y = 0
def movePosition(self, angle, magnitude):
self.x = self.x + (magnitude * math.cos(angle))
self.y = self.y + (magnitude * math.sin(angle))
| true |
2a4c0e76a2edda86b4ed4560668d7da9e5c8a26a | Python | balakumardevil/set-4 | /62.py | UTF-8 | 124 | 3.21875 | 3 | [] | no_license | n=input()
y=0
for i in n:
if ((i=='0') or (i=='1')):
y+=1
if(y==len(n)):
print("yes")
else:
print("no")
| true |
8dcebba0cdf27fdae58fcd534edeb1527e6e7d5b | Python | dashvinsingh/Daily-Sale-Tracker | /MainFiles/Daily_Class.py | UTF-8 | 3,739 | 3.09375 | 3 | [] | no_license | #DailySale Class
from datetime import datetime as dt
from MainFiles.Sale_Class import Sale
from file_operations import *
from NewSale.objects_file_ops import add_to_file_obj
import os
class DailySales:
def __init__(self):
self.sales = []
self.sale_num_dict = {}
self.total_sale_today = len(s... | true |
213bcf26c845a9ebce90efb89543e58b935db7a4 | Python | mbillingr/miniKANREN | /Python/core.py | UTF-8 | 4,812 | 3.109375 | 3 | [
"MIT"
] | permissive | import sympy as sy
from functional_data_structures import Map, Singleton
from stream import take, take_inf
variables = sy.symbols
Variable = sy.Symbol
Variable.__unify__ = lambda self, other, s: s.extend(self, other)
def is_var(x):
return isinstance(x, Variable)
def is_atom(x):
return type(x) in {bool, in... | true |
7952e9649d0ce6317f6b871c78a72fbb69f3a2bd | Python | sphinx-doc/sphinx | /tests/test_config.py | UTF-8 | 17,904 | 2.546875 | 3 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | """Test the sphinx.config.Config class."""
import time
from pathlib import Path
from unittest import mock
import pytest
import sphinx
from sphinx.config import ENUM, Config, check_confval_types
from sphinx.errors import ConfigError, ExtensionError, VersionRequirementError
@pytest.mark.sphinx(testroot='config', con... | true |
831ffe1f9b75171e90f01f335f772c393b17fe2c | Python | matheusrf96/sometests | /models/purchase.py | UTF-8 | 857 | 2.890625 | 3 | [] | no_license |
from models.holder import Holder
from models.product import Product
class Purchase:
PM_CREDITCARD = 0
PM_TRANSFER = 1
def __init__(self, price, payment_method):
self.price = price
self.payment_method = payment_method
def __eq__(self, other):
return self.__dict__ == other.__d... | true |
0c929f1d129a3d2a1a31b84a7a854ed72a011727 | Python | patidarjp87/python_core_basic_in_one_Repository | /79.sortaccordingvalue.py | UTF-8 | 452 | 3.71875 | 4 | [] | no_license |
print(" script to sort dict according to value")
n=int(input('Enter ....how many pairs of key:value do you want to in your dict...?'))
d={eval(input('key')):eval(input('value')) for x in range(n)}
l=[]
d1={}
for x in d.values():
l.append(x)
l.sort()
i=0
while i!=n:
for x in d.keys():
if d[x]==l[i]:
d1... | true |
fc547f77c067f0ee05e695ed37bf9a2bab2393ff | Python | panzergame/info_406 | /Source/client/view/event.py | UTF-8 | 4,711 | 2.71875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from .common import *
from .observer import *
from datetime import *
from .add_event import *
class EventBox(Gtk.ListBox, ViewObserver):
#Boîte d'affichage détaillé d'un évènement
def __init__(self, common):
Gtk.ListB... | true |
6e47547e7eca730fc686282f85f219e4efc82686 | Python | Shaomik/DatabaseApp | /import_Games.py | UTF-8 | 1,079 | 2.640625 | 3 | [] | no_license | import pymysql
import csv
from db_connect import *
#finished in 0.3s
def import_Games():
is_success = True
insert_prefix = "insert into Games (game_id, title, release_date, platform, genre) values (%s,%s,%s,%s,%s)"
try:
connection = create_connection()
cursor = connection.cursor()
csvfile = open("Game.c... | true |
d3dcd36f19521c423c62dcc338448cccca15dcc1 | Python | Agolds/CodeSamples | /ChallengeExam/Controller/df_formatter.py | UTF-8 | 2,912 | 3.046875 | 3 | [] | no_license | from pyspark.sql import DataFrame
from pyspark.sql.functions import lit, to_timestamp, to_date
from datetime import datetime
class FormatDataFrame:
@staticmethod
def parse_nyse2012(df: DataFrame, types: str) -> DataFrame:
"""
:param types: Column types
:param df: Dataframe ... | true |
172cf347fb85aef8c03bd3bdcbbe4dc001eb8c1b | Python | chester-leung/BaySportsTweets | /Skill.py | UTF-8 | 8,421 | 2.828125 | 3 | [] | no_license | import tweepy
import emoji
import re
# Consumer keys and access tokens, used for OAuth
# OAuth process, using the keys and tokens
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
# Creation of the actual interface, using authentication
api = tweepy.... | true |
81d104e82987eb98424a5b6ba43d40b47290b979 | Python | zkailinzhang/dl_distributed_training_predict | /SVM/svm_mnist.py | UTF-8 | 2,367 | 2.890625 | 3 | [] | no_license | #导入必备的包
import numpy as np
import struct
import matplotlib.pyplot as plt
import os
##加载svm模型
from sklearn import svm
###用于做数据预处理
from sklearn import preprocessing
import time
#加载数据的路径
path='./dataset/mnist/raw'
def load_mnist_train(path, kind='train'):
labels_path = os.path.join(path,'%s-labels-idx1-ubyte'% ki... | true |
ccc5dd04bbdd58f8a0ecb8411cc04788ab14d90f | Python | yoav-shaham/School | /Final Project/understanding.py | UTF-8 | 251 | 3.1875 | 3 | [] | no_license | def createGenerator():
yield 1
yield 2
yield 3
yield 4
mygenerator = createGenerator() # create a generator
x=0
for i in mygenerator:
print i
if i==2:
break
print "hey"
for i in mygenerator:
print i
print "hello"
| true |
8d05234b288bcc4f26cce8532ab82318a9817543 | Python | PeterHKC/Pattern-Recognition | /hw1/hw1.py | UTF-8 | 2,837 | 2.875 | 3 | [] | no_license | import requests
import re
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
class HW1():
def __init__(self, filename):
self.row = []
self.clz = dict()
with open(filename) as file:
for line in file:
r = self.parseLine(line)
self.row.append(r)
if int(r[0]) in ... | true |
2114e61c4d548da82ae710302231a9ef995ed9dc | Python | krishnamalli/seleniumnew | /pages/loginpage.py | UTF-8 | 651 | 3.046875 | 3 | [] | no_license | class Loginpage():
def __init__(self,driver):
self.driver = driver
self.username_id = 'txtUsername'
self.password_id = 'txtPassword'
self.login_id = 'btnLogin'
def enter_username(self,username):
self.driver.find_element_by_name(self.username_id).clear()
self.drive... | true |
9920580ce0475a6035ac6281a086d413968f3bd4 | Python | br-th-slnc/study_projects | /task5.py | UTF-8 | 2,235 | 3.5625 | 4 | [] | no_license | import random
class Box:
def __init__(self, h, w, l, mass):
self._h = h
self._w = w
self._l = l
self._mass = mass
self._v = h * l * w
@property
def h(self):
return self._h
@property
def l(self):
return self._l
@prope... | true |
54e54361b86230b71d71495e4e212c04f96f8755 | Python | Nastasiya132/homeworkPY | /lesson2/1.py | UTF-8 | 223 | 3 | 3 | [] | no_license | my_dict = { 'planet': 'Earth', 'population': 7530000000000, 'rationality': 'controversial'}
my_tuple = ('home', 'war', 12)
my_list = ['history', 1045, 1.5, my_dict, my_tuple]
for i in my_list:
print(f'{i} is {type(i)}') | true |
40d01ca0202a921418028d750557dc9d09fbbfb7 | Python | dicamposlima/FIT | /DAD/AC5/enunciado/sistema_atividades.py | UTF-8 | 2,463 | 2.59375 | 3 | [] | no_license | from typing import List
from acesso import leciona, aluno
from flask import Flask, jsonify
from flask import request
app = Flask(__name__)
atividades = [
{
'id_atividade': 1,
'id_disciplina': 1,
'enunciado': 'crie um app de todo em flask',
'respostas': [
{'id_aluno': 1,... | true |
a1e7f6e09737ffa6fdcf597eb9fbb9ad951d5651 | Python | KosukeMizufune/gunosy_task | /articles/management/commands/get_data.py | UTF-8 | 979 | 2.625 | 3 | [] | no_license | import argparse
from django.core.management.base import BaseCommand
from get_train import get_data
class Command(BaseCommand):
help = 'Train naivebayes model'
parser = argparse.ArgumentParser(description='Process some integers.')
def add_arguments(self, parser):
"""
スクレイプする予定の、各タグの記事一覧ペ... | true |
e211c3c69a55500decbe7fa22d863d03897a37e9 | Python | Sharmaanuj10/Phase1-basics-code | /python book/book projects 1/4-7/dictonaries/dicto in dicto.py | UTF-8 | 488 | 3.515625 | 4 | [] | no_license | cities = {
'NYC' : {
'country' : 'america',
'population' : '333'
},
'tokyo' : {
'country' : 'japan',
'population' : '98379'
}
}
for city, data in cities.items():
# her i get the key and value form the dictonary and print key first
... | true |
a85a04aa7eb0abcc162380f696b7634ab9bf60ff | Python | qhduan/ocr-web | /handler.py | UTF-8 | 790 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive |
import sys
import json
from recog import recog_json
def handle(req):
return 'xxx'
obj = None
try:
obj = json.loads(req)
except:
return json.dumps({'ok': False, 'error': 'Invalid JSON Req'})
if 'name' not in obj:
return json.dumps({'ok': False, 'error': 'No Name'})
retu... | true |
71908a2848367e362fc7eeccddee844068d597f2 | Python | lrmneves/mltextmining | /hw5/src/preprocess.py | UTF-8 | 7,276 | 2.6875 | 3 | [] | no_license | import json,string
from scipy.sparse import csr_matrix,vstack
import cPickle as pickle
import os
import sys
from math import log
import re
from nltk.stem.porter import PorterStemmer
class Review:
'''Class to store review values'''
def __init__(self,id,user,business,text_count,rating = None):
self.id = id
self.use... | true |
0090607043a3e5f209231d5f3a55f1f2b7ad3196 | Python | andreavs02/EjemplosC_Cpp | /EjerciciosVariables.py | UTF-8 | 838 | 2.921875 | 3 | [] | no_license | # -*- coding: iso-8859-15 -*-
# Este codigo ha sido generado por el modulo psexport 20180802-w32 de PSeInt.
# Es posible que el codigo generado no sea completamente correcto. Si encuentra
# errores por favor reportelos en el foro (http://pseint.sourceforge.net).
if __name__ == '__main__':
dato1 = int()
dato2 = str(... | true |
7042c7a7b59d0099879b54f1b9597d9f8e23a9e4 | Python | thehappydinoa/echo-fauxmo | /fauxmo_minimal.py | UTF-8 | 1,184 | 2.640625 | 3 | [
"MIT"
] | permissive | import fauxmo, logging, time
from debounce_handler import debounce_handler
logging.basicConfig(level=logging.DEBUG)
# Device callback functions
class device_handler(debounce_handler):
"""Publishes the on/off state requested,
and the IP address of the Echo making the request.
"""
TRIGGERS = {"device... | true |
0e1fa861754eb6f691596f5a2924fb2c59e2513b | Python | qobiljon-archives/KELOS | /Test.py | UTF-8 | 508 | 2.765625 | 3 | [] | no_license | from KELOS import Cluster
from Tools import PriorityQueue
q = PriorityQueue()
q.add(key=1, value=Cluster(d=(1, 1)))
q.add(key=0, value=Cluster(d=(0, 0)))
q.add(key=-1, value=Cluster(d=(-1, -1)))
q.add(key=-2, value=Cluster(d=(-2, -2)))
q.add(key=2, value=Cluster(d=(2, 2)))
q.add(key=1, value=Cluster(d=(1, 1)))
for k... | true |
4731ab984776f9f31c8ea2dd48b063981cebdf55 | Python | handofkwll/fisica | /fts.py | UTF-8 | 3,544 | 3.03125 | 3 | [] | no_license | """This module contains the FTS class.
"""
from __future__ import absolute_import
import collections
import numpy as np
class FTS(object):
"""Class describing the Fourier Transform Spectrometer used to combine
the interferometer beams.
Contains the methods:
__init__
run
__repr__
"""
... | true |
e1ab51a2ab59eb7ae94e654780f436b77c27fb7a | Python | ravichoudhary123/LeetCode | /Python/KSmallSortMat.py | UTF-8 | 311 | 3.109375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import heapq
matrix = [[ 1, 5, 9], [8, 11, 13], [10, 13, 15]]
k = 5
h = [(row[0], row, 1) for row in matrix]
heapq.heapify(h)
for _ in xrange(k - 1):
v, r, i = h[0]
if i < len(r):
heapq.heapreplace(h, (r[i], r, i + 1))
else:
heapq.heappop(h)
print h[0][0] | true |
b6db81b932f4e65ea1d8389ab301ff279689aeb5 | Python | bharathi-srini/Bayesian_Inference_Recommender_Systems | /BNN_Rec_Sys/Data/feature_engineering.py | UTF-8 | 2,936 | 3.21875 | 3 | [] | no_license | import pandas as pd
import gc
def prod_features(df):
"""
Product Features
"""
sub1 = df.sort_values(['product_id'],ascending=True)
# 'product_id_orders' indicates the popularity of a product
sub2 = sub1.join(sub1.groupby('product_id')['product_id'].size(), on='product_id', rsuffix='_orders')
# 'reordered_tot... | true |
7b22fb432439088a486d26a1af7929da5062780f | Python | gundammaster/mtec2002_assignments | /class10/labs/exceptions.py | UTF-8 | 1,288 | 4.25 | 4 | [] | no_license | """
exceptions.py
=====
To handle errors, use a try/catch block:
-----
try:
# do your stuff
except SomeError:
# deal with some error
-----
optionally... you can continue catching more than one exception:
-----
.
.
except AnotherError:
# deal with another error
-----
Substitute SomeError with the kind of error yo... | true |
8dd80e2afb5823ca0e5f719f56344e44094fde6c | Python | Kieran-Bacon/InfoGain | /infogain/cognition/evalrelation.py | UTF-8 | 1,182 | 2.703125 | 3 | [
"Apache-2.0"
] | permissive | import weakref
from ..knowledge import Ontology, Relation, Rule
from ..knowledge.relation import RuleManager
from .evalrule import EvalRule
class EvalRuleManager(RuleManager):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._ruleMapper = {}
def add(self, rule: R... | true |
5db73c7a1b29ee6d958dd3577d5cfb80242e0284 | Python | bgoonz/UsefulResourceRepo2.0 | /_PYTHON/python-scripts/scripts/05_load_json_without_dupes.py | UTF-8 | 293 | 3.546875 | 4 | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | permissive | def dict_raise_on_duplicates(ordered_pairs):
"""reject duplicate keys"""
my_dict = dict()
for key, values in ordered_pairs:
if key in my_dict:
raise ValueError("Duplicate key: {}".format(key,))
else:
my_dict[key] = values
return my_dict
| true |
7079cefe560bb0b26fbfc6b6b348b3404362c53f | Python | alex15964/Python-others | /insert_space.py | UTF-8 | 288 | 3.1875 | 3 | [] | no_license | s = "aoxjyomdymtbsdkfmitbsddtxjyozgep gsxjkf zkoklfymgoigsdokzk sdhzdtzg mgokzgzgtbmdok zgkflflfokzgzglkkfmimigoep estbzg yoxjsd sdxjxj zkdtlklkdtlfkfmisd okdtsdhzokymmz qdtbzg dtsdhd esokmimimz mdxjxjzk ruxjceep twyosdokym sdhzdtzg nzokgoqdxjymzk tbzg zgxjmikfsddtxjyomf xjigmiigzgcezglfmdmgzkmiep"
t = ""
i = 0
whil... | true |
a9e0cad2c292c99524641c5dcccb7129c59eb2e1 | Python | dumpmemory/WorryFreeGroceryStore | /tools/loader.py | UTF-8 | 1,853 | 3.109375 | 3 | [] | no_license | #encoding utf8
# author : yang
# date : 20191124
from .common_tools import timer
import pickle
# 功能:存储 pkl 数据
@timer
def saveDict(obj,outputPath,name):
if "." not in name:
fileName = f"{outputPath}{name}.pkl"
else:
fileName = f"{outputPath}{name}"
with open(fileName, 'wb') as f:
pick... | true |
431405b455df1b044d39dc96092396b5c1a2ad70 | Python | shin96/practice_rough | /slidingWindow/longestSubStringWithSameLetter.py | UTF-8 | 1,328 | 3.984375 | 4 | [] | no_license | # Given a string with lowercase letters only, if you are allowed to replace no more than ‘k’ letters with any letter, find the length of the longest substring having the same letters after replacement.
# Example 1:
# Input: String="aabccbb", k=2
# Output: 5
# Explanation: Replace the two 'c' with 'b' to have a longes... | true |
236c05e440726b3f57f2e1c7c09d7857a257d99d | Python | Aikann/DT-Project---Pattern-CG | /Instance.py | UTF-8 | 13,407 | 2.609375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 18 09:58:55 2018
@author: Guillaume
"""
import regtrees2 as tr
from learn_tree_funcs import transform_data, read_file, write_file, scale_data, get_num_features, get_feature_value, get_data_size, get_target, get_leaf_parents, get_sorted_feature_values
from learn_tree_fun... | true |
04ecba43c39151374341a977da215993107f53b3 | Python | prof79/realpython-python-csv | /pandaswritecsv.py | UTF-8 | 676 | 3.1875 | 3 | [
"Unlicense"
] | permissive | #!/usr/bin/env python3
# pandaswritecsv.py
# https://realpython.com/python-csv
import pandas
FILENAME = 'hrdata2.csv'
OUTPUT_FILENAME = 'hrdata_modified.csv'
def main() -> None:
print('Re-writing CSV ...')
print()
# Load a CSV file without header information
fieldnames = ['Employee', 'Hired', 'Sal... | true |
1a71c2b457cd8f1e2199c665280c3ac99695064c | Python | walshdavid/eleventyone | /AudioCaseStudies.py | UTF-8 | 959 | 2.734375 | 3 | [] | no_license | #-*- coding: utf-8 -*-
"""
Created on Thu Jul 13 14:42:48 2017
@author: datkin10
"""
from AccuracyChecker import AccuracyChecker
from AudioFeatureAnalyzer import AudioFeatureAnalyzer
file = 'fox2017.wav'
ac = AccuracyChecker()
ac.record('Audio-Case-Study-Files/Converted-Wav/' + file)
afa = AudioFeatureAnalyze... | true |
d3536759e3549785c108c9d5b1bee9fa275af4a9 | Python | shailesh-singh/monte_carlo-pi | /mc_pi.py | UTF-8 | 1,221 | 3.3125 | 3 | [] | no_license | from __future__ import division
import random
from matplotlib import pyplot as plt
def calc_pi(sample=0,passes=1,plot=False):
"""Calculates Pi using Monte Carlo Method
Returns: average of pi values of all passes
Parameters:
-----------
sample: sample size in integer value
passes: numbe... | true |
f49274dff4e7f225fd549d9ccec0a0fb4d729e84 | Python | borrabeam/Games | /roulette.py | UTF-8 | 3,723 | 3.53125 | 4 | [] | no_license | import random
class Roulette:
def __init__(self):
# self.odd = [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35]
# self.even = [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36]
# self.low = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
# self.high = [19,20,21,22,23,24,25,... | true |
57622e984988018650fb6ee6a5cabde439840834 | Python | antonio36alv/python-click-cli-programs | /todos/todos/utils.py | UTF-8 | 4,276 | 3.390625 | 3 | [] | no_license | from PyInquirer import prompt, print_json
from datetime import datetime
def fuckthis():
print("fuck this")
def createDateTime():
# HH:MMa/p
# prompt for time input
time = input("Enter a time pls: ")
# find index that contains the semicolor
semi = time.find(":")
# digits until t... | true |
e135e48fddbde5ff530c770c3db1b08e3af1eb5d | Python | tarhashi/pynlp100 | /chapter3/jawiki.py | UTF-8 | 427 | 2.71875 | 3 | [] | no_license | # -*- coding:utf-8 -*-
import json
import gzip
import re
def search_by_title(title):
with gzip.open('jawiki-country.json.gz', 'r') as f:
for line in f.readlines():
doc = json.loads(line)
if doc['title'] == title:
return doc['text']
return None
def basic_info(te... | true |
1f7e66e741d613e3ddf2d569b411070c1b28fe64 | Python | rrwielema/ezgoogleapi | /ezgoogleapi/common/validation.py | UTF-8 | 3,823 | 2.8125 | 3 | [
"MIT"
] | permissive | import json
import re
import pandas as pd
import validators
from googleapiclient.errors import HttpError
from ezgoogleapi.common.exceptions import InvalidKeyFileError, InvalidRangeError, NotAuthorizedError
import os
def check_keyfile(keyfile):
if '.json' not in keyfile:
raise IOError('Keyfile needs to be... | true |
f4c9a2c6d31d4b0fe0f15b831095e2e6a552ac77 | Python | thispassing/learningPython | /more_loops2.py | UTF-8 | 958 | 3.984375 | 4 | [] | no_license | # while True:
# print("How many times do I have to tell you?")
# x = input()
# print("CLEAN UP YOUR ROOM!\n"*int(x))
# while True:
# times = input("How many times do I have to tell you? ")
# times = int(times)
# for time in range(times):
# print("CLEAN UP YOUR ROOM!")
# while True:
# ... | true |
33aaf8ad7cba5934e9e2f2655e6edb4ee8275ac5 | Python | GriTRini/study | /python/2일차/리스트.py | UTF-8 | 1,208 | 4.5 | 4 | [] | no_license | # 1) 학생이 2명['로제', ' 아이유']인 동아리에 '브레이브걸스'가 가입을 했다고 가정하
# 고, ' 브레이브걸스 ' 를 리스트 맨 뒤에 추가하고 리스트 모든 요소를 출력하세요
student = ['로제', '아이유']
student.append('브레이브걸스')
student
# 2) 위 리스트에 동명이인인 “로제”가 새로 가입을 했다고 가정하고 요소 “아이유” 뒤에 “로제”
# 를 추가하고 리스트 모든 요소를 출력하세요
student.insert(2, '로제')
# 3) “로제”는 몇 명인지 출력하세요.
student.count('로제')
# 4... | true |
773f99201eeb0d165e7868355f10c2d819c8f5e7 | Python | luque/better-ways-of-thinking-about-software | /Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/course_api/blocks/transformers/block_completion.py | UTF-8 | 6,031 | 2.8125 | 3 | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | permissive | """
Block Completion Transformer
"""
from completion.models import BlockCompletion
from xblock.completable import XBlockCompletionMode as CompletionMode
from openedx.core.djangoapps.content.block_structure.transformer import BlockStructureTransformer
class BlockCompletionTransformer(BlockStructureTransformer):
... | true |
495ccf2e01405d1838e3b06305820dd3b46c533d | Python | xXPinguLordXx/py4e | /exer10.py | UTF-8 | 208 | 4.3125 | 4 | [] | no_license | str = input("Enter word: ")
# using while loop:
# length = len(str)
#
# while length > 0:
# print(str[length-1])
# length -= 1
# using for loop
for i in range(len(str), 0, -1):
print(str[i-1])
| true |
f31a9fb1ba734d75931137526d90aa8cf8e7409f | Python | gmlwjd9405/djangoProgrammers-tutorial | /mysite/elections/views.py | UTF-8 | 3,674 | 2.5625 | 3 | [] | no_license | from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseNotFound, Http404
from django.db.models import Sum
from .models import Candidate, Poll, Choice
import datetime
# Create your views here.
def index(request):
# Candidate로 저장된 모든 DB의 내용을 불러... | true |
f456f5ee4a7fe2e3c3450c93e65993de98bcfd25 | Python | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/leap/9d58e6f060594ff689f8b5b584e1b710.py | UTF-8 | 473 | 3.796875 | 4 | [] | no_license |
# on every year that is evenly divisible by 4
# except every year that is evenly divisible by 100
# unless the year is also evenly divisible by 400
def is_leap_year(year):
# Let's mod 400 first since if its divisible by 400,
# its also gotta be divisible by 4 and no nested if/else is needed now
if year... | true |
3127b6b2e459d0270a22bdf866876cb83081a5b3 | Python | Lemigt/webSpider | /day02/Handler$open.py | UTF-8 | 367 | 2.703125 | 3 | [] | no_license | import urllib.request
http = urllib.request.HTTPHandler()
# 创建打开器对象
opener = urllib.request.build_opener(http)
# 打开url
# response = opener.open("http://www.baidu.com/")
# print(response)
# 创建全局打开器
urllib.request.install_opener(opener)
response = urllib.request.urlopen("http://www.ifeng.com/")
print(response.read()... | true |
bbe9929b2b89bfff8655518d0c5c0edb8c8437a4 | Python | isds/pessoas-crud | /backend/models.py | UTF-8 | 764 | 2.625 | 3 | [] | no_license | from database import db
def dump_date(value):
"""Deserialize datetime object into string form for JSON processing."""
if value is None:
return None
return value.strftime("%Y-%m-%d")
class Telefone(db.Model):
__tablename__ = 'telefones'
id = db.Column(db.Integer, primary_key=True)
dd... | true |
78012cd6b94b26698de14c8e60dbe0e35538deb6 | Python | gabriellehebert/python_projects | /batting_file.py | UTF-8 | 7,437 | 3.296875 | 3 | [
"MIT"
] | permissive | #GABRIELLE HEBERT
#
#CS 1411
#05/07/2017
#
#BATTING FILE STATISTIC ORGANIZER
#
#MAJOR PROGRAM SEQUENCE:
#OPENS A FILE OF BASEBALL BATTING STATISTICS
#ASKS USER WHAT INFORMATION THEY ARE LOOKING FOR
#CALLS A FUNCTION
#FUNCTION ORGANIZES THAT INFORMATION INTO A DICTIONARY WITH THE PLAYER+YR AS A KEY
#ASKS USE... | true |
361a7645ed099eab50c69ab9c8d44f9278df2d34 | Python | IbrahimFadel/Y9Design-IbrahimFadel | /GuiInput.py | UTF-8 | 370 | 3.453125 | 3 | [] | no_license |
#Import all contents of tkinter for the gui
from tkinter import *
# Tk() makes a window
window = Tk()
def return_entry(en):
content = entry.get()
if(content != ""):
print(content)
entry.delete(0, END)
Label(window, text="Input: ").grid(row=0)
entry = Entry(window)
entry.grid(row=0, column=1)
entry.bind('<Ret... | true |
0548993a9f341b210b49882d80dcb3f8107a96a3 | Python | rafaelperazzo/programacao-web | /moodledata/vpl_data/65/usersdata/126/34821/submittedfiles/investimento.py | UTF-8 | 220 | 3.3125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
from __future__ import division
#COMECE SEU CODIGO AQUI
i= float(int('digite o valor do investimento:'))
t= float(int('digite a taxa de crecimento anual em numero decimal:'))
a1=i+t*i
print(a1) | true |
c2efd5b6667db42257b880cd0da50f75149d13b2 | Python | Aasthaengg/IBMdataset | /Python_codes/p03193/s680738437.py | UTF-8 | 118 | 2.6875 | 3 | [] | no_license | n,h,w=map(int,input().split())
print(n-sum(a<h or b<w for a,b in [list(map(int,input().split())) for i in range(n)]))
| true |
cedc10447a05a972d41c98a3d412a59b13be030e | Python | rsenwar/depot | /depot/lib/smart_decorators.py | UTF-8 | 405 | 2.53125 | 3 | [] | no_license | import time
from functools import wraps
from lib import smartlogging
logger = smartlogging.getLogger("depot")
def timed_decorator(f):
@wraps(f)
def wrapper(*args, **kwds):
start = time.time()
result = f(*args, **kwds)
elapsed = (time.time() - start)*1000
logger.debug("f::{0} t... | true |
e8cb4b267129d05918c06bbfdc5bde38cfa43b29 | Python | geyyer/multiclass | /training.py | UTF-8 | 2,875 | 2.6875 | 3 | [
"MIT"
] | permissive | # imports
import numpy as np
import os
import pandas as pd
from keras import models
from keras.preprocessing.image import ImageDataGenerator
from keras.utils import to_categorical
from model import ModelCustom
from sklearn.model_selection import train_test_split
# consts
SIZE = 28
TEST_FRAC = 0.2
RANDOM_SEED = 42
# p... | true |
538a7a8b61b7fb3065b2ec31d01d2e84af1c2c04 | Python | daniel-reich/ubiquitous-fiesta | /6vSZmN66xhMRDX8YT_5.py | UTF-8 | 156 | 3.25 | 3 | [] | no_license |
def advanced_sort(lst):
out, seen = [], []
for x in lst:
if x not in seen:
out.append([x] * lst.count(x))
seen.append(x)
return out
| true |
b28b1fcfccf005b6e017823e3610f83b7becbe3c | Python | cseharshit/Python_Practice_Beginner | /09.determine_the_quadrant.py | UTF-8 | 322 | 3.984375 | 4 | [
"MIT"
] | permissive | x,y= map(float,input("Enter X and Y: ").split())
if x > 0 and y > 0:
print("The First Quadrant.")
elif x < 0 and y > 0:
print("The Second Quadrant.")
elif x < 0 and y < 0:
print("The Third Quadrant.")
elif x > 0 and y < 0:
print("The Fourth Quadrant.")
elif x==0 and y==0:
print("Point of origin... | true |
0ae112631e3bd66ac174b3c002e5edb659850b75 | Python | Sreeram341/leetCodeChallenges | /leetChallenges/sum_double.py | UTF-8 | 1,934 | 3.515625 | 4 | [] | no_license | def sum_double(a, b):
if int(a) == int(b):
return 2*(a+2)
else:
return a+b
def diff21(n):
if n <= 21:
return 21-n
else:
return 2*(n-21)
def parrot_trouble(talking, hour):
if talking == True:
if hour < 7 or hour > 20 :
return True
else:... | true |
149908059dccf802066df219f66c60959db3a4d9 | Python | zaochnik555/Python_1_lessons-1 | /lesson_05/home_work/hw05_normal.py | UTF-8 | 2,370 | 4.3125 | 4 | [] | no_license | # Задача-1:
# Напишите небольшую консольную утилиту,
# позволяющую работать с папками текущей директории.
# Утилита должна иметь меню выбора действия, в котором будут пункты:
# 1. Перейти в папку
# 2. Просмотреть содержимое текущей папки
# 3. Удалить папку
# 4. Создать папку
# При выборе пунктов 1, 3, 4 программа запр... | true |
e9ec5e63afa29e68a2ed1291833be5c75f678115 | Python | jairollongo/Trabajo_Inves | /Basico.py | UTF-8 | 4,228 | 3.953125 | 4 | [] | no_license | class Basico:
def numerosN(n): # PRESENTAR LOS NUMEROS DEL 1 AL N
cont = 0
while n != cont :
cont += 1
print(cont)
def Multiplo(numero, multiplo): # MULTIPLO DE CUALQUIER NUMERO
res = numero % multiplo
return res
... | true |
8112dc1c158eb5bfdfd13bb2e0ee3c6864eae695 | Python | DerekHeidorn/flask_base_oauth2 | /app/models/common.py | UTF-8 | 634 | 2.546875 | 3 | [] | no_license |
from sqlalchemy import Column, String, Integer
from app.models.baseModel import BaseModel
class Config(BaseModel):
__tablename__ = 'tb_config'
# "CFGPRM_KEY" character varying(100) NOT NULL, -- ID name for a configurable parameter value
key = Column("cfgprm_key", String(100), primary_key=True)
# "C... | true |
9d3f1cc0d9a1355a37abee9afa0b7ecd4576173f | Python | betty29/code-1 | /recipes/Python/252180_Combining_simple_specific_property/recipe-252180.py | UTF-8 | 1,730 | 3.640625 | 4 | [
"Python-2.0",
"MIT"
] | permissive | import sys
def attribute(attrname, permit='rwd', fget=None, fset=None, fdel=None, doc=''):
"""returns a property associated with 'attrname'.
By default, a simple property with get, set, and delete methods
will be created. Optionally, specific get/set/del methods may be
supplied. You can a... | true |
eda161cf05a03f7887f29abe685a3b02c22a5eda | Python | juhani-hietikko/kotimonitori | /tools/schedule_config.py | UTF-8 | 3,093 | 2.921875 | 3 | [] | no_license | #!/usr/bin/env python
import boto3
import argparse
from argparse import RawTextHelpFormatter
actions = ['put', 'get', 'list', 'list_target']
description = """
tool for maintaining ruuvibridge tag configuration in AWS DynamoDB
"""
def read_args():
parser = argparse.ArgumentParser(description='', formatter_cl... | true |
a7e743d1388b77ebf6db48eb0fc6f36db7a11254 | Python | SamNgigi/News-Highlight | /tests/news_testSource.py | UTF-8 | 923 | 2.9375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python3.6
import unittest
from app.models import Source
# Source = news_source.Source
class NewsSource(unittest.TestCase):
"""
Test Class to test the behaviours we expect in our applications
"""
def setUp(self):
"""
This will function runs before every Test. Its a
... | true |
d50e61333764f605b2b9b2089a4b7532777d27d4 | Python | dknupp/practice | /string_compression/string_compression.py | UTF-8 | 1,012 | 4.09375 | 4 | [] | no_license | from itertools import groupby
def groupby_compress(input_str):
'''
Given an input string, return a list of tuples with per character counts.
e.g.: 'aaabbccccd' --> [(3, 'a'), (2, 'b'), (4, 'c'), (1, 'd')]
Use itertools.groupby() to find groups
:param input_str: a string to compress
'''
c... | true |
bf8a9d807a536330f68fa44f78589909b04f3e83 | Python | Yannyezixin/python-study-trip | /stack-qa/string/check_contains.py | UTF-8 | 258 | 3.71875 | 4 | [] | no_license | str = 'This is my name!'
if 'is' not in str:
print 'is not found in the str'
else:
print 'is found in the str'
if str.find('is') == -1:
print 'is not found in the str by the method find'
else:
print 'is found in the str by the mothod find'
| true |
caf9610742fd8ab04742298f5f1beac67b8cae97 | Python | aredev/quic-scapy | /crypto/CertificateDecoder.py | UTF-8 | 1,420 | 2.75 | 3 | [] | no_license | from enum import Enum
# Implementation is not finished, as I don't think it is necessary
class EntryTypes(Enum):
COMPRESSED = 1
CACHED = 2
COMMON = 3
def determine_entry_type(entry_type_byte):
if entry_type_byte == 1:
return EntryTypes.COMPRESSED
elif entry_type_byte == 2:
return... | true |
540741244d015dc24c792e219aea30f19fc4b1c4 | Python | dplastico/CTF_l4t1n_abrl2020 | /format/xpl.py | UTF-8 | 527 | 2.53125 | 3 | [] | no_license | from pwn import *
r = remote("208.68.39.19", 4423)
#loopeando 100 intentos
for i in range(1,100):
try:
r = remote("208.68.39.19", 4423)
payload ="%"+str(i)+"$s" #format string, debe haber una forma mas inteligente de hacer esto que con este loop
r.sendlineafter("> ",payload)
result... | true |
6653e240880183d5a3127603c5a9f5c3eff37d2c | Python | MediaUncovered/NewsAnalysis | /unittests/testModel.py | UTF-8 | 1,317 | 2.828125 | 3 | [] | no_license | from newsAnalysis.Model import Model
from newsAnalysis.Collection import Collection
import unittest
class testModel(unittest.TestCase):
def setUp(self):
model_path='./sampleModels/MoscowTimes_1000'
self.model = Model().load(model_path= model_path)
self.data_path = './sampleModels/MoscowTim... | true |
321bee6a1c8f56c8c9acaea93d66391166bb8c63 | Python | lilyshao/sudoku | /gen.py | UTF-8 | 1,047 | 3.59375 | 4 | [] | no_license | '''
- fill diagonal boxes first:
box 1,5,9 are independent, just need to check boxValid
- recursively fill out the rest: using solve()
- remove k cells from the complete board
'''
import random
import solver
# calls fill_box() for box 1,5,9
def fill_diagonal(grid):
for i in range(0, 9, 3):
fill_box(grid, i, i)
def... | true |
3954af842e687f3514a5734d4ca2eab4598c67fe | Python | JackLiar/DeepPacket | /src/ml/models.py | UTF-8 | 3,308 | 2.609375 | 3 | [] | no_license | import torch
from torch import nn
class DeepPacketCNN(nn.Module):
def __init__(self, n_classes):
super(DeepPacketCNN, self).__init__()
self.conv1 = nn.Conv1d(1, 200, 5, 2, 0)
self.bn1 = nn.BatchNorm1d(200)
self.relu = nn.ReLU(inplace=True)
self.conv2 = nn.Conv1d(1, 100, 4, 1, 0)
self.bn2 =... | true |
f6ce9c4fe2aede9cf5a2c0aae33d84490ab1a150 | Python | MiguelChichorro/PythonExercises | /World 2/For/ex054 - Majority Group.py | UTF-8 | 694 | 3.53125 | 4 | [
"MIT"
] | permissive | from datetime import date
colors = {"clean": "\033[m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"purple": "\033[35m",
"cian": "\033[36m"}
today = date.today().year
old = 0
new = 0
for c in range(1, 8):
major = int(i... | true |
fd049f585d4ecfad6b940ad2361bcd08067bf015 | Python | maggielehr/tust_political_leadership | /multi_trustE_instructionsNI/pages.py | UTF-8 | 2,510 | 2.515625 | 3 | [] | no_license | from otree.api import Currency as c, currency_range
from ._builtin import Page, WaitPage
from .models import Constants
class Instruction(Page):
pass
class Instruction2(Page):
pass
class Instruction3(Page):
pass
class Quiz1(Page):
pass
form_model = 'player'
form_fields = ['submitted_answer... | true |
84305343cea56358d52060f2d46ee681f9f11449 | Python | slopesneves/take-a-break | /break_time.py | UTF-8 | 334 | 3.1875 | 3 | [] | no_license | import time
import webbrowser
break_count = 0
total_break = 3
second_to_wait_before_next_break = 10
print("This program started at ", time.ctime())
while (break_count < total_break):
time.sleep(second_to_wait_before_next_break)
webbrowser.open("https://www.youtube.com/watch?v=DgwzRB2ijHY")
break_count = br... | true |
dbbbbd4591556dd35aeb172be8ec6a2e418d3bf1 | Python | DedSecInside/Awesome-Scripts | /Web Scraping/bing_search.py | UTF-8 | 2,736 | 2.984375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/python
# -*- coding: utf-8 -*-
# python bing_search.py inurl:index.php?id=
import sys
import requests
from bs4 import BeautifulSoup
results = []
def main(query):
"""
Main function.
Args:
query: (str): write your description
"""
global page
session = requests.Session()
... | true |
008abe3737add9a85ca1a20b64625442d35e6525 | Python | ConnerLambdaAccount/Data-Structures | /queue/singly_linked_list.py | UTF-8 | 2,859 | 3.703125 | 4 | [] | no_license | class ListNode:
def __init__(self, value, next=None):
self.value = value
self.next = next
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def __str__(self):
out = ""
# Add head to string
if self.head:
out += f"{sel... | true |
f2d2547b405248e3ac2f0868bee1fa778e9acec5 | Python | lawrel/unilabs | /cs1/hw3/lecture9_p3.py | UTF-8 | 334 | 3.953125 | 4 | [] | no_license | values = []
stop = False
while stop == False:
x = int(input("Enter a value (0 to end): "))
print(x)
if x == 0:
stop = True
else:
values.append(x)
minval = min(values)
maxval = max(values)
avg = round(sum(values)/len(values),1)
print("Min: {0}\nMax: {1}\nAvg: {2}".format(minva... | true |
ecc49a08b08475269923b0d8cf41d8fec6ce65d3 | Python | mindnhand/Learning-Python-5th | /Chapter17.Scopes/factory_function.py | UTF-8 | 794 | 3.796875 | 4 | [
"MIT"
] | permissive | #!/usr/bin/env python3
#encoding=utf-8
#-----------------------------------------
# Usage: python3 factory_function.py
# Description: state retention with enclosing function
#-----------------------------------------
def maker(n):
def action(x): # make and return action
return x ** n # a... | true |
a5a25a9e80541f56a372f5ce7a1450e19f162dac | Python | Vedarth/Twitter-bots | /remove-friends.py | UTF-8 | 853 | 2.625 | 3 | [] | no_license | import os
import tweepy
from time import sleep
import random
import json
try:
from credentials import *
except ModuleNotFoundError:
consumer_secret = os.environ['consumer_secret']
consumer_key = os.environ['consumer_key']
access_token = os.environ['access_token']
access_token_secret = os.... | true |
41687e6115248330b3ecee718651e4e732adcec5 | Python | roddehugo/alfredpnr | /flaskpnr.py | UTF-8 | 4,979 | 2.546875 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
import lxml.html
import re
import requests
from flask import Flask, jsonify
from werkzeug.exceptions import default_exceptions
from werkzeug.exceptions import HTTPException
################################
# Alfred PNR Flask Application #
################################
app = Flask(__name__)
... | true |
59ab2122b8dc92d8f821f032cb04d1aa2601e010 | Python | NCAR/geocat-comp | /geocat/comp/stats.py | UTF-8 | 20,503 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | from eofs.xarray import Eof
import numpy as np
from typing import Iterable
import xskillscore as xs
import xskillscore.core.np_deterministic as xs_internal
import xarray as xr
import warnings
def pearson_r(a,
b,
dim=None,
weights=None,
skipna=False,
... | true |
2a62d4e45c2d77da2a139ca0ef08dcca209ef48b | Python | GregPhillips2001/unit2 | /gradeCalculator.py | UTF-8 | 470 | 4.15625 | 4 | [] | no_license | #Greg Phillips
#9/13/17
#gradeCalculator.py - calculates the letter grade to their percentage grade
gradePercent = float(input("Enter your percent grade here: "))
if(gradePercent<60):
print("You earned an incomplete")
elif(gradePercent>=60 and gradePercent<70):
print("You earned a D")
elif(gradePercent>=70 and... | true |
caeb2f2020bf2ea2a927c67c19583441fe124888 | Python | D-J-Harris/AdventOfCode2020 | /days/day20.py | UTF-8 | 5,294 | 3.171875 | 3 | [] | no_license | """Jurassic Jigsaw"""
from collections import defaultdict
import numpy as np
import regex as re
def get_side(tile, side):
if side == 'top':
return ''.join(str(x) for x in tile[0])
if side == 'bottom':
return ''.join(str(x) for x in tile[-1])
if side == 'left':
return ''.join(str(x[... | true |
7f1453bcc3300abe4b0fa7fa0a76f0072fc38e66 | Python | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4123/codes/1575_1327.py | UTF-8 | 72 | 2.78125 | 3 | [] | no_license | total = 90
heraclito = 55
diferenca = total - heraclito
print(diferenca) | true |
7f45d9079208b6e20cc24447fec7c3ba445c6bca | Python | obs145628/py-utils | /src/dataset_norm4.py | UTF-8 | 1,449 | 2.9375 | 3 | [
"MIT"
] | permissive | import numpy as np
import pickle
TRAIN_TEST_FILE = './norm_100k_10k.bin'
MINI_TRAIN_TEST_FILE = './norm_1k_100.bin'
def vec_to_num(x):
return np.argmax(x)
def num_to_vec(x):
if x >= 1:
return np.array([0, 1])
else:
return np.array([1, 0])
def gen_train_test(train_len, test... | true |
b47131a389548e7404be0b5e8f68eed0d63bd666 | Python | SamFaraz/Uebungen | /antworten/1_b.py | UTF-8 | 1,376 | 2.921875 | 3 | [] | no_license | from pyspark.sql import Window, SQLContext
import pyspark.sql.functions
from pyspark import SparkContext, SparkConf
import pyspark
conf = SparkConf().setAppName("1_b").setMaster("local[1]")
sc = SparkContext(conf = conf)
def Func(lines):
lines = lines.lower()
lines = lines.replace('.','').replace(':', '... | true |
8b720cf3c8224acbf2af7dd501e941914ad9183e | Python | mihainegrisan/small_python_projects | /password_locker.py | UTF-8 | 1,706 | 3.015625 | 3 | [] | no_license | #! python3
# pw.py - An insecure password locker program.
import shelve, pyperclip, sys, os
os.chdir('D:\\Python_code\\Automate_stuff')
# TODO: Password strength detector
with shelve.open('pass') as my_shelf:
if len(sys.argv) < 2 or len(sys.argv) > 3:
print("""
"Not enough or too... | true |
d814079d402de1c237ca342cc493df9532ffca21 | Python | petrovp/networkx-related | /framework/class_builder.py | UTF-8 | 2,063 | 2.96875 | 3 | [
"BSD-3-Clause"
] | permissive | # -*- coding: utf-8 -*-
# Copyright (C) 2018 by
# Marta Grobelna <marta.grobelna@rwth-aachen.de>
# Petre Petrov <petrepp4@gmail.com>
# Rudi Floren <rudi.floren@gmail.com>
# Tobias Winkler <tobias.winkler1@rwth-aachen.de>
# All rights reserved.
# BSD license.
#
# Authors: Marta Grobelna <marta.grob... | true |
eea4202f81495456b20d3766c2ba4a7c21692df2 | Python | appbanana/MachineLearningAction | /机器学习实战/chapter04/02-使用朴素贝叶斯过滤垃圾邮件.py | UTF-8 | 2,385 | 3.1875 | 3 | [] | no_license | import bayes
import numpy as np
def spam_test():
"""
data/email/spam 路径下邮件的测试
:return: 返回正确率
"""
doc_list = []
class_list = []
full_text = []
for i in range(1, 26):
# 读取email路径下spam中邮件内容
email_content = open('./data/email/spam/%d.txt' % i, encoding='gbk').read()
... | true |
c53157a1fe8e09b6748f64eda1b8704ea1c2b72f | Python | mohitsshah/documents-caf | /Information-Extraction/read_xml.py | UTF-8 | 2,492 | 3.078125 | 3 | [] | no_license | import xml.etree.ElementTree
import os
import json
import argparse
import re
def get_attribs(items):
obj = {}
for item in items:
obj[item[0]] = item[1]
return obj
def get_page_text(tree):
text_boxes = tree.findall("textbox")
text = []
for box in text_boxes:
for line in box:
... | true |
764ec39ee6691b745e97f01fbebe171ce274e6ea | Python | Daniel-1275/estructuraDatos | /Pilas.py | UTF-8 | 635 | 3.984375 | 4 | [] | no_license | from Listas import ListaEnlazada
class Pila:
def __init__(self):
self.lista = ListaEnlazada()
def push(self, dato):
self.lista.insertarPrincipio(dato)
def pop(self):
return self.lista.removerPrincipio()
def __len__(self):
return self.lista.len
def __str__(self):
... | true |
896617bcdbf2f82a094632dbca9c96e12df74c00 | Python | dailybruin/starter.django-react | /django_project/utils/views.py | UTF-8 | 5,026 | 2.796875 | 3 | [] | no_license | from bs4 import BeautifulSoup, Tag
from django.shortcuts import render
from django.http import HttpResponse
from django.core.cache import cache
import logging
# Create your views here.
"""
DO NOT MODIFY THESE FUNCTIONS!!
"""
#Use this function to set og meta tags in soup
def insert_meta_prop(soup, property, content)... | true |
ba6103a0b2dbd8d9d69f2386129d4239c018d551 | Python | spel-uchile/SeismicScripts | /ss_folder_fft.py | UTF-8 | 4,152 | 2.5625 | 3 | [] | no_license | #!/usr/bin/env python
__author__ = 'toopazo'
import argparse
import os
from obspy.core import read
from os import listdir
from os.path import isfile, join
import numpy as np
import matplotlib.pyplot as plt
import copy
parser = argparse.ArgumentParser(description='Obspy wrapper: Apply \"FFT\" operation for infolder')... | true |
777955f12c7b612e8ad1608dbdbc2a18dcb4c352 | Python | zahidzqj/learn_python | /class_demo/class_汽车4s店/test2.py | UTF-8 | 598 | 3.765625 | 4 | [] | no_license | class CarStore(object):
def __init__(self):
self.factor = Factor()
def order(self,name):
return self.factor.Choosecar(name)
class Factor(object):
def Choosecar(self,name):
if name == "BMW":#为什么不写成self.name
return Bmw()
elif name =='AUDI':
... | true |
f0a6aad26427a8b9c244004f021d7cafe30f4357 | Python | abhaykatheria/cp | /DivisibleSubarray.py | UTF-8 | 283 | 2.90625 | 3 | [] | no_license | from collections import defaultdict
n = int(input())
arr = list(map(int,input().split()))
rem = defaultdict(int)
rem[0],som=1,0
for i in range(n):
som+=arr[i]
rem[som%n]+=1
ans = 0
for key,values in rem.items():
if values>1:
ans+=(values*(values-1))//2
print(ans) | true |
99fecc2d1befc7c42c0a00962b92a3923fedb823 | Python | jazperez/data-structures-and-algorithms | /Python/chapter02/2.4 - Partition/Nick.py | UTF-8 | 2,202 | 4.0625 | 4 | [] | no_license | #!/usr/bin/python3
import unittest
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
def __str__(self):
return str(self.data)
class SinglyLinkedList:
def __init__(self):
self.head = None
def addNode(self, data):
node = Node(... | true |