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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
0142178864d8be3271db244220fde853c57dd295 | Python | Wason1797/Nn-Learn-Lib | /nn_lib/samples/perceptron_samples/refined_perceptron_sample.py | UTF-8 | 2,987 | 2.65625 | 3 | [] | no_license | from nn_lib.Perceptron import RefinedPerceptron as ps
from nn_lib.samples.perceptron_samples import perceptron_sample_ts as ts
from nn_lib.common import functions as fn
import pygame
from pygame.locals import *
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
WHITE = (255, 255, 255)
def ru... | true |
d25bdfef925d6942432a18a74981b17417cdfd78 | Python | zach96guan/Stupid_LeetCoder | /SlidingWindow/862.Shortest_Subarray_with_Sum_at_Least_K/Shortest_Subarray_with_Sum_at_Least_K.py | UTF-8 | 701 | 2.9375 | 3 | [] | no_license | class Solution:
def shortestSubarray(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: int
"""
# sliding window, O(N)
dq = []
n = len(A)
ret = float('inf')
# presum
for i in range(1, n):
A[i] += A[i -... | true |
b80a7f0cce694fb94da79048b5f3c30f4fdc1a71 | Python | andybloke/python4everyone | /Chp_3/Chp_3_ex_2_pay.py | UTF-8 | 320 | 3.84375 | 4 | [] | no_license | hours = input("Enter hours: ")
rate = input("Enter rate: ")
try:
hours = float(hours)
rate = float(rate)
if hours > 40.0:
extra = hours - 40
pay = (hours - extra) * rate + extra * 1.5 * rate
print("Pay:", pay)
else:
pay = hours * rate
print("Pay:", pay)
except:
print("Error, please enter numeric input") | true |
7be974e9f05e9326cdf31b04a99509e5a342a20b | Python | pavanmaganti9/pyfiles | /tree_struct.py | UTF-8 | 278 | 2.671875 | 3 | [] | no_license | import nltk
sentence = [("The", "DT"), ("small", "JJ"), ("red", "JJ"),("flower", "NN"),
("flew", "VBD"), ("through", "IN"), ("the", "DT"), ("window", "NN")]
grammar = "NP: {?*}"
cp = nltk.RegexpParser(grammar)
result = cp.parse(sentence)
print(result)
result.draw() | true |
82b8ff5a513abd232a439a7ea2450c802383d7aa | Python | marinkala/OSMnetworks | /NetworkAnalytics.py | UTF-8 | 5,203 | 2.734375 | 3 | [] | no_license | import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import collections as c
def getGraph(bucket):
folder='/Users/Ish/Dropbox/OSM/results/TwoWeeks/intersecting_roads/'
G=nx.read_yaml(folder+str(bucket)+'hourBigNetworkNodeEdgePers.yaml')
return G
def plotDegDist(G):
deg=G.degree()
... | true |
21b43253cb200a384db9aa512cdf5e6b34c8e497 | Python | zhihao0819/collect_log | /src/master.py | UTF-8 | 1,859 | 2.65625 | 3 | [] | no_license | #!/usr/bin/env python
#-*- coding: utf-8 -*-
# @Time : 2018/7/2 下午7:44
# @Author : Evan Liu
# @Email : liuzhihao@growingio.com
# @File : master.py
from color import ShowOutPut
class MasterServer(object):
def __init__(self, host, logslevels, obj):
# self.remote = RemoteOper(host, port, user, ... | true |
909195cda317c1d0227eb45525a8f16de4fa6b6d | Python | ExpHP/lonely-python | /lonely/scriptlib/gnuplot.py | UTF-8 | 5,396 | 2.671875 | 3 | [] | no_license | import argparse, sys, json
class Spec:
def __init__(self, comment='#', gnu_order='dblw', json_order='dblw'):
(self._comment, self._gnu_order, self._arr_order) = (comment, gnu_order, json_order)
self._arr_to_gnu = Spec._solve_permutation(json_order, gnu_order)
self._gnu_to_arr = Spec._solve_permutation(gnu_order... | true |
a3a17e38c085668c2feeb46fceb2d0dac99fbca0 | Python | Mamonter/GB_les_Petryaeva | /bas/less3/ex1.py | UTF-8 | 721 | 4.40625 | 4 | [] | no_license | #Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
#Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.
def func():
try:
a = int(input("Введите первое число >> "))
b = int(input("Введите второе число >>"))
result = a... | true |
6f9e174204effb168d8d914554a0a0979fc61c9b | Python | gigatexal/utils | /findFilesAndCopyThem.py | UTF-8 | 1,325 | 2.71875 | 3 | [] | no_license | import os
import shutil
# globals
output_dir_toplevel = '<dest>'
extension_folder_mapping = {'.mp4':output_dir_toplevel + '/' + 'movies',
'.mkv':output_dir_toplevel + '/' + 'movies',
'.flv':output_dir_toplevel + '/' + 'movies',
'.m4v'... | true |
5bfdfd81492839339641ff2c29facb6d9aaa1a26 | Python | KennanWong/The_Slakrs | /src/message.py | UTF-8 | 11,107 | 2.640625 | 3 | [] | no_license | '''
This file contains all 'message_' functions
'''
from datetime import datetime, timezone #pylint: disable=W0611
import threading
import hangman
from data_stores import get_messages_store, save_messages_store
from data_stores import save_channel_store
from error import InputError, AccessError
... | true |
ddff3d35a225578f4e3d95ed9a9604a01231b43a | Python | ByeonJaeJeong/python | /Everyone'sAlgorithm/sequentialsearch.py | UTF-8 | 1,113 | 3.921875 | 4 | [] | no_license | def search_list(a, x):
n = len(a)
for i in range(0, n):
if x == a[i]:
return i
return -1
v = [17, 92, 18, 33, 58, 7, 33, 42]
print(search_list(v, 18))
print(search_list(v, 33))
print(search_list(v, 500))
# search_list에서 검색 위치 결과를 목록으로 보여주는 알고리즘
def search_list_menus(a, x):
value... | true |
267e30cd24753b9ed9fef4c11e231eb596be3eaf | Python | microhhh/Artificial-Intelligence | /translator/Markov/normalize.py | UTF-8 | 2,275 | 2.859375 | 3 | [
"MIT"
] | permissive | # coding: utf-8
from translator.utils import *
INIT_START_FILE = 'init_start.json'
INIT_EMISSION_FILE = 'init_emission.json'
INIT_TRANSITION_FILE = 'init_transition.json'
PINYIN_TABLE = '../data/pinyin_table.txt'
PY_TO_HZ_FILE = 'hmm_pinyin_to_hanzi.json'
START_FILE = 'hmm_start.json'
EMISSION_FILE = 'hmm_emission.js... | true |
6ca2c522215594b94a262c6c2a5164807835c386 | Python | banga19/TKinter-Tutorials | /binding_layouts_to_func's.py | UTF-8 | 282 | 3.421875 | 3 | [] | no_license | from tkinter import *
root = Tk()
# method 1 and the best option and it prints on the terminal not on the window
def PrintName():
print("Hello My name is BANGA")
button_1= Button(root,text="Print it", command=PrintName )
button_1.pack()
root.mainloop()
| true |
f7ebfe4455cf3b57d9c2171f8215a404636f92ff | Python | justinjhjung/st_algorithm | /math/number2negbinary.py | UTF-8 | 393 | 3.25 | 3 | [] | no_license | input_ = int(input())
def number2negbinary(num):
if num == 0:
return 0
convert_list = []
while num!= 0:
mod = abs(num)%2
convert_list.append(mod)
if mod != 0:
num //= -2
num += 1
else:
num //= -2
return ''.join([s... | true |
991d69b640e1714bc84cfba22f17d5d73ce1335e | Python | octagonprogramming/ASSWU-Web-coding-challenge-2019 | /bracket_input_class.py | UTF-8 | 4,760 | 3.609375 | 4 | [] | no_license | from bracket_test_class import *
class Input():
#open and read from file
#NOTE TO SELF WHEN ADDING TO THIS FUNCTION: strip white space off line or the size will be off
def read_input_file():
#define class variable
test = Tests
#define variables to assign values to
... | true |
2e0d8dcd218594316ac6291368ffbba79d188e08 | Python | larellano1/nltk | /names.py | UTF-8 | 3,807 | 3.3125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Wed May 15 18:31:55 2019
@author: d805664
"""
import nltk
from nameparser.parser import HumanName
def get_human_names(text):
tokens = nltk.tokenize.word_tokenize(text)
pos = nltk.pos_tag(tokens)
sentt = nltk.ne_chunk(pos, binary = False)
person_list = []
per... | true |
9bece62692aecd6e0a539a944c4ef253584c60e4 | Python | UnsuccessfullHTTP/discordCraft | /DiscordBot/lib/console.py | UTF-8 | 772 | 2.859375 | 3 | [] | no_license | #
# PYTHON CONSOLE DESINGED FOR DISCORDCRAFT BOT BY UNSUCCESFULHTTP
#
# Execute python code while its running!
#
async def console_begin():
print("--------")
print("Python console by UnsuccesfulHttp")
print("Execute console_help() without for help!")
print("WARNING: This could break the bot if misused,... | true |
f09573c69de82ccb405bff3a9ba213ef602899d9 | Python | Vieiraork/Python-Learn | /Matriz 3x3 determinante.py | UTF-8 | 1,115 | 3.578125 | 4 | [] | no_license | lista = []
matriz = []
primeira = []
segunda = []
res = []
for li in range(3):
for co in range(3):
n = int(input(f'Digite o valor da matriz[{li}][{co}]: '))
lista.append(n)
if co == 0:
primeira.append(n)
if co == 1:
segunda.append(n)
matriz.append(lista[:... | true |
e31bba336b6372823c3a6be662394a2aebe421b0 | Python | afcarl/rwet-examples | /modularity/restaurants_forever.py | UTF-8 | 636 | 3.4375 | 3 | [] | no_license |
import sys
import random
def ucfirst(s):
return s[0].upper() + s[1:]
def restaurant(building="House", foodstuff="Pancakes"):
return "International " + building + " of " + foodstuff
def human_join(parts, conjunction):
if len(parts) == 1:
return parts[0]
first_join = ', '.join(parts[:-1])
return first_j... | true |
be04f0fe68609ae1c485c9c2e1c334394828b00f | Python | Folzi99/ItP_Trinket_Exercises-main | /ItP_Trinket_Exercises-main/wk4_Ex_03_Iterations/ex_09.py | UTF-8 | 202 | 3.296875 | 3 | [] | no_license | #!/bin/python3
value = 0
plier = 0
while value < 10:
value += 1
print('line', value, '->', end='\n')
while plier < value*9:
plier += value
print(plier, end= '')
print("")
| true |
f1fd8969a9eaa6d2b8fd63e2b95d2f484537873a | Python | hociss/CCC-Senior-Problems-Python | /2018_S1.py | UTF-8 | 420 | 3.34375 | 3 | [] | no_license | # CCC 2018 Senior Problem 1: Voronoi Villages
# https://cemc.uwaterloo.ca/contests/computing/2018/stage%201/seniorEF.pdf
n = int(input())
v = []
for i in range (n):
v.append(int(input()))
v.sort()
smallest = 2000000001
for i in range (1, n - 1):
if ((v[i + 1] + v[i]) / 2) - ((v[i] + v[i - 1]) / 2) ... | true |
3e0a29ee4e31ffe8b9a3d6b7b0ad7c40cd4d957b | Python | fengkai29/tensorflow_classesification | /test.py | UTF-8 | 674 | 2.703125 | 3 | [] | no_license | import tensorflow as tf
# import numpy as np
# batch_size = 2
# a = [[1,2],[3,4],[4,5],[6,7]]
# indices = np.arange(len(a))
# np.random.shuffle(indices)
# print(indices)
# def a(a,batch_size):
# for start_idx in range(0, len(a) - batch_size + 1, batch_size):
# excerpt = indices[start_idx:start_idx + batch_... | true |
5339e45ed415cb489c33497ff4bb679f3e7a68bc | Python | Aasthaengg/IBMdataset | /Python_codes/p02270/s254811134.py | UTF-8 | 1,007 | 2.953125 | 3 | [] | no_license | from collections import deque
def isPa(w,k,p):
tr = 0
c = 0
d = deque(w)
while(d):
tmp = d.popleft()
if(tmp > p):
return False
if( tr + tmp > p):
tr = tmp
c += 1
else:
tr += tmp
if c+1>k:
return... | true |
0c9cf84da66e1677aabf5845b7a2503517695ae4 | Python | milger/DEVFUNDA | /movie_rental_store/src/modules/entity/customer.py | UTF-8 | 4,760 | 3.296875 | 3 | [] | no_license | __author__ = 'JimenaSanabria'
from membership_type import MembershipType
from status import Status
class Customer(object):
"""Class to get an instance of customer with following attributes:"""
def __init__(self, code, first_name = "", last_name = "", date_of_birth = "", addresses = [], phones = [], emai... | true |
7bb6212d94aac76dcfb8318cb334cf8668a01d18 | Python | yuekangwei123/jianzhi_offer | /剑指offer_34-67题解法python版.py | UTF-8 | 46,061 | 4.09375 | 4 | [] | no_license | 剑指offer_34-67题解法
34.数组中的逆序对:在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。
并将P对1000000007取模的结果输出。 即输出P%1000000007
输入描述:
题目保证输入的数组中没有的相同的数字
数据范围:
对于%50的数据,size<=10^4
对于%75的数据,size<=10^5
对于%100的数据,size<=2*10^5
解法:此题有难度
35.两个链表的公共结点:输入两个链表,找出它们的第一个公共结点。
解法一:先找出两个链表的差,对于长的链表先遍历差个单位,然后同时遍历,这种不... | true |
8b0a95dd901e3ea7511f78add6904b2030b3f330 | Python | AzeemGhumman/asset-compute | /scripts/helper/common.py | UTF-8 | 2,135 | 2.609375 | 3 | [] | no_license | #!/usr/bin/python
import pdb
from enum import Enum
import os
import yaml
class SensorPin:
def __init__(self, name):
self.name = name
class ComputePin:
def __init__(self, name, pin_number, tags, gpio_pin = None):
self.name = name
self.pin_number = pin_number
self.tags = tags
... | true |
9568babdcf2c4bd62a291cc453b39968844bb410 | Python | connectheshelf/connectheshelf | /reader/extrafunctions.py | UTF-8 | 301 | 3.359375 | 3 | [] | no_license | def encrypt(message):
message=message.upper()
newmess=""
for i in message:
if(i>='A' and i<='Z'):
newmess+=chr(ord('A')+ord('z')-ord(i))
elif(i>='0' and i<='9'):
newmess+=str(9-int(i))
else:
newmess+=i
return newmess.upper()
| true |
29e8d5a4ec7dc67095bcbdc3e0ddae40bf6c58f4 | Python | zmbush/Yelp-CFG | /sentimental.py | UTF-8 | 822 | 2.9375 | 3 | [] | no_license | #!/usr/bin/env python
import json
reviews = 'review.json'
data = open(reviews)
words = {}
for review in data:
obj = json.loads(review)
contents = obj['text']
stars = float(obj['stars'])
for word in contents.split():
sanitized = ''.join(e for e in word if e.isalnum()).lower()
if len(sanitized) > 3 ... | true |
9d6f0c832fc8ba3960760fccc20d929ebf9ca924 | Python | kali666-6/holbertonschool-higher_level_programming | /0x0B-python-input_output/1-number_of_lines.py | UTF-8 | 261 | 3.25 | 3 | [] | no_license | #!/usr/bin/python3
""" Modules """
def number_of_lines(filename=""):
""" count lines of file """
line_num = 0
with open(filename, encoding="utf-8") as f:
line = f.readlines()
line_num = len(line)
f.close()
return line_num
| true |
1453db65f47987daa2b94f29d0ae96713086cc87 | Python | kbbingbai/jianshu02 | /jianshu02/spiders/jianshu03.py | UTF-8 | 2,263 | 2.609375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from jianshu02.items import Jianshu02Item
class Jianshu03Spider(CrawlSpider):
name = 'jianshu03'
allowed_domains = ['jianshu.com']
start_urls = ['https://www.jianshu.com/']
rules = (
... | true |
ec0ddc7dd9ae6be29c781b65c2c0762ad559603e | Python | urduhack/urduhack | /urduhack/tokenization/eos.py | UTF-8 | 3,478 | 3.140625 | 3 | [
"MIT"
] | permissive | # coding: utf8
"""Rule based Sentence tokenization module"""
# Global Variables
_URDU_CONJUNCTIONS = ['جنہیں', 'جس', 'جن', 'جو', 'اور', 'اگر', 'اگرچہ', 'لیکن', 'مگر', 'پر', 'یا', 'تاہم', 'کہ', 'کر',
'تو', 'گے', 'گی']
_URDU_NEWLINE_WORDS = ['کیجیے', 'کیجئے', 'گئیں', 'تھیں', 'ہوں', 'خریدا', 'گے', '... | true |
4e41dca5cdfc0fa89477d97dce1ff49ca7462d58 | Python | cscim918/PS | /10610.py | UTF-8 | 159 | 3.296875 | 3 | [] | no_license | a = list(input())
a.sort(reverse=True)
sum = 0
for i in a:
sum += int(i)
if sum % 3 != 0 or "0" not in a:
print(-1)
else:
print(''.join(a)) | true |
bdaf132cf2a9d3279cdadb40f21ccefc12cb02cf | Python | uralspotter/stepik-homework | /wait_test.py | UTF-8 | 858 | 3.109375 | 3 | [] | no_license | from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
import math
def calc(x):
return str(math.log(abs(12 * math.sin(x))))
def math_task(wd):
x = int(wd.f... | true |
4be348569ec90c481456a7547508ccd8de33f006 | Python | Elaine-Henrique/challenge | /backend/src/dispatcher.py | UTF-8 | 1,316 | 2.515625 | 3 | [] | no_license | from abc import ABC, abstractmethod
class Dispatcher(ABC):
def__init__(self, product)
self.product = product
@abstractmethod
def end_dispatcher(self, customer):
pass
class Digital_dispatcher(Dispatcher):
def end_dispatcher(self, customer):
self.add_voucher(customer)
... | true |
cb7e18fd05f7cb9b2bedb14e80ceef0c9d5591ea | Python | molusca/Python | /learning_python/speed_radar.py | UTF-8 | 955 | 4.5 | 4 | [] | no_license | '''
A radar checks whether vehicles pass on the road within the 80km/h speed limit.
If it is above the limit, the driver must pay a fine of 7 times the difference between the speed that he was
trafficking and the speed limit.
'''
def calculate_speed_difference(vehicle_speed, speed_limit):
return (vehicle_speed - s... | true |
1f4faf548f4d0418dd61fa0b996ced358ce4a76b | Python | AdamZhouSE/pythonHomework | /Code/CodeRecords/2676/60690/297233.py | UTF-8 | 401 | 2.59375 | 3 | [] | no_license | res=[]
t=int(input())
for i in range(t):
str=input().split(" ")
n=int(str[0])
k=int(str[1])
nums=input().split(" ")
for j in range(len(nums)):
nums[j]=int(nums[j])
this=0
for j in range(len(nums)-k+1):
temp=0
for m in range(j,j+k):
temp+=nums[m]
if... | true |
12293b3d8fda1bad7679ea1322eb9041f5a7578f | Python | aolbrech/codility-lesson-solutions | /Tasks/Painless_Lesson04_PermCheck/Solution_PermCheck.py | UTF-8 | 739 | 3.703125 | 4 | [] | no_license | # you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A):
# write your code in Python 3.6
if len(A) != max(A):
return 0
sumArray = 0
for index in range(len(A)):
value = A[index]
if abs(value) <= len(A):
if A[... | true |
6a2d692889e711b294bbfd475479b8a38fcd0ccf | Python | fernandochimi/Intro_Python | /Exercícios/102_Pesquisa_String_3.py | UTF-8 | 156 | 3.21875 | 3 | [] | no_license | string1 = "AAACTBF"
string2 = "CBT"
string3 = ""
for letra in string1:
if letra in string2 and letra not in string3:
string3+=letra
print("%s" % string3) | true |
07266612cadfa7ea58485e6820c1e369c71560aa | Python | jeffysam6/Leetcode | /2020/September Leetcode/day-5-image-overlap.py | UTF-8 | 566 | 3.078125 | 3 | [] | no_license | class Solution:
def largestOverlap(self, A: List[List[int]], B: List[List[int]]) -> int:
from collections import defaultdict
arr1,arr2 = [],[]
d = defaultdict(int)
for i in range(len(A)):
for j in range(len(B)):
if(A[i][j]):
arr1.ap... | true |
01909f10290c7fd5a079180bc2e6b4d78ca1f1b4 | Python | msalama/Radio-Lab-1-Code | /Lab3_code/moon.py | UTF-8 | 1,388 | 2.90625 | 3 | [] | no_license | import numpy as np
from math import *
import ephem, time
moon = ephem.Moon()
obs = ephem.Observer()
#UCB coordinates: (longitude = -122.2573 & latitude = 37.8732)
obs.lat = 37.8732*np.pi/180.
obs.long = -122.2573*np.pi/180.
obs.date = ephem.date('2014/04/06 03:34:44') #set time of observation
i = 0
dec = []
ra = []... | true |
09e05bf129522620f86ab3069835079c12063ed5 | Python | Hani1-2/All-codes | /oop practices sem2/abstract classes.py | UTF-8 | 5,379 | 3.84375 | 4 | [] | no_license | ###Slide 7
##
# from abc import ABC, abstractmethod
#
# class Polygon(ABC):
# @abstractmethod
# def noOfSides(self):
# pass
#
# class Square(Polygon):
# def noOfSides(self):
# print('I have 4 sides')
#
# class Triangle(Polygon):
# def noOfSides(self):
# print('I have 3 sides')
#
# #a=Po... | true |
496a410b0811af0aa1e496059f5d1a5efe2a2c77 | Python | avanov/Plim | /plim/console.py | UTF-8 | 3,056 | 2.5625 | 3 | [
"MIT"
] | permissive | """
This module contains entry points for command-line utilities provided by Plim package.
"""
import sys
import os
import argparse
import codecs
from pkg_resources import get_distribution
from pkg_resources import EntryPoint
from mako.template import Template
from mako.lookup import TemplateLookup
def plimc(args=No... | true |
d06196026d29a7d0c57310b0f960840b07d8e424 | Python | jackganesh/ganesan | /s2p15.py | UTF-8 | 88 | 3.4375 | 3 | [] | no_license | g,t=map(int,input().split())
for i in range(g+1,t):
if (i%2)==0:
print(i,end=' ')
| true |
c230bfdc0e93db8032d1e0e41cb8b531918c72fd | Python | maet3608/fast-pfp | /tests/test_match.py | UTF-8 | 1,979 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | """
.. module:: test_fastpfp
:synopsis: Unit tests for fastpfp module
"""
import numpy as np
from fastpfp.util import graph2matrices
from fastpfp.match import num_nodes, match_graphs, pfp, discretize
def test_num_nodes():
L1, A1 = graph2matrices(4, [(0, 1), (0, 2), (2, 3)])
L2, A2 = graph2matrices(4, [(0... | true |
182050805e152cf8276ec7e4a3784c72f8e275dd | Python | johncornflake/dailyinterview | /imported-from-gmail/2020-03-22-primes.py | UTF-8 | 280 | 3.71875 | 4 | [] | no_license | Hi, here's your problem today. This problem was recently asked by Amazon:
Given a positive integer
n
, find all primes less than
n
.
Here's an example and some starter code:
def
find_primes
(
n
):
# Fill this in.
print
(
find_primes
(
14
))
# [2, 3, 5, 7, 11, 13]
| true |
3cadb7ed984f670efb6f86f3997eaae08b5bc04e | Python | eafigbo/csv_web_view | /csv_processor.py | UTF-8 | 2,526 | 2.84375 | 3 | [] | no_license | #!/usr/bin/env python
import csv
import argparse
import pprint
import codecs
#import cStringIO
from unicode_csv import UnicodeReader,UnicodeWriter,UTF8Recoder
from bson.json_util import dumps
import json
import project_settings as settings
import load_class
db_class = load_class.load_class(settings.DB_DRIVER_CLASS... | true |
34113ef3d14cfa2ee8d13a6c0b8016f45829fd10 | Python | Shushmitha-N/Python | /sentiment analysis.py | UTF-8 | 29,413 | 4.03125 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
# The objective is to detect hate speech in tweets.
# For the sake of simplicity, we say a tweet contains hate speech if it has a racist or sexist sentiment associated with it.
# So, the task is to classify racist or sexist tweets ... | true |
707f9ad9751797d8e351713c6fd27875eb1f9fe8 | Python | Devalekhaa/deva | /play37.py | UTF-8 | 94 | 3 | 3 | [] | no_license | d=int(input())
e=0
for i in range(d):
v,a=map(int,input().split())
if v<a:
e=e+1
print(e)
| true |
d4a262f8233adca97798e583245586fdee88607e | Python | yu68/STEPIC | /Week-7/BWMatching-100-8.py | UTF-8 | 638 | 2.890625 | 3 | [] | no_license | import sys
Input=open(sys.argv[1],'r').read().split("\n")
text=Input[0].strip()
patterns=Input[1].strip().split(" ")
out=open("output.txt",'w')
def BWT_match(s,perm,p):
'''
s: bwt(text);
p: pattern
'''
indexs=filter(lambda x: s[x]==p[0], range(len(s)))
i=1
while i<len(p):
indexs=filter(lambd... | true |
07309b9f68ea09b7352a694b1698a7af973cc4a3 | Python | IvanRodriguez17/recursividad | /LongitudNumero.py | UTF-8 | 128 | 2.953125 | 3 | [] | no_license | def longNum(n):
if(n == 0):
return 0;
if(n < 10):
return 1;
else:
return 1 + longNum(n//10)
| true |
aa3f9dc90bf6562a101a348b60b4d36ea0ddc449 | Python | DaniSanchezSantolaya/RNN-customer-behavior | /src/statistical_significance_randomization_tukey.py | UTF-8 | 1,835 | 2.546875 | 3 | [] | no_license | import pickle
import numpy as np
import sys
measure = 'precision_r'
B = 2100000 # Num trials
folder_measures = 'pickles/movielens/measures/final_measures/'
methods = ['Frequency_Baseline', 'RQ1_1', 'RQ1_2', 'RQ1_3a', 'RQ1_3b', 'RQ1_4', 'RQ1_5', 'RQ2_1a', 'RQ2_1b', 'RQ2_2a', 'RQ2_2b']
values_method = []
num_users = ... | true |
d7e2c3c0a112c97c3c851e385d5da498869b4227 | Python | Brenda134/hola | /caja.py | UTF-8 | 376 | 3.046875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 11 19:57:58 2020
@author: User
"""
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111, projection='3d')
xpos = [1]
ypos = [2]
num_elements = len(xpos)
zpos = [0]
dx = 27
dy = 10
dz = [10]
... | true |
fef67b51d6988503740ec3d8023cd965d3203606 | Python | hiddenwaffle/Ax-equals-b | /singh/ch1_4_arithmetic_of_matrices/ex1_17_matrix_addition.py | UTF-8 | 707 | 3.578125 | 4 | [] | no_license | import numpy as np
# a
m1 = np.array([
[1, 2],
[3, 4]
])
m2 = np.array([
[5, 6],
[7, 8]
])
print('a')
print(m1 + m2)
# b
m1 = np.array([
[1, 2, 5, 6, 1],
[7, 9, 11, 6, 3]
])
m2 = np.array([
[9, 8, 5, 7, 6],
[2, 13, 7, 2, 3]
])
print('b')
print(m1 - m2)
# c
m1 = np.array([
[1, 2, 3... | true |
3c742d3146b19f62eed011ff4bf51a395ab2f8a1 | Python | genba/packer | /packer/platforms/linux.py | UTF-8 | 411 | 2.546875 | 3 | [
"MIT"
] | permissive | import os
import subprocess
from .base import CorePlatform
class LinuxPlatform(CorePlatform):
def create_shortcut(self, path, target):
os.symlink(target, path)
def add_to_path(self, path):
if path not in os.environ['PATH']:
line = 'export PATH=$PATH:{}'.format(path)
... | true |
359ac71dfe68539ff623c152bc9d3bae1214b6d8 | Python | jamesGadoury/slack-alert | /main.py | UTF-8 | 3,640 | 2.75 | 3 | [
"MIT"
] | permissive | import cv2
import argparse
from video import VideoCaptureWindow
from frameprocessing import ConditionalFrameEvaluator, NotYourFaceChecker, MultipleFaceChecker, FrameDebugger
from slackbot import SlackBot
import os
from datetime import datetime
import time
def get_user_id_and_token_from_env():
try:
slack_us... | true |
50247917738e3eb82fe3d7f217f60563d590d776 | Python | LaTonyaJ/Blogly | /test_app.py | UTF-8 | 1,815 | 2.640625 | 3 | [] | no_license | from unittest import TestCase
from app import app
from models import db, User
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///blogly_test'
app.config['TESTING'] = True
db.drop_all()
db.create_all()
class TestFlask(TestCase):
def setUp(self):
"""Add sample user."""
User.query.delete()
... | true |
2589535d83c3082c0fca964f5194e42d124c5f2f | Python | 1846169568/168206 | /168206229/2.py | UTF-8 | 270 | 3.359375 | 3 | [] | no_license | #斐波那切数列 尾递归
def fibo(first, second, n):
if n == 1:
return 1
if n == 2:
return 1
if n == 3:
return first+second
else:
return fibo(second, first+second, n-1)
for i in range(1,20):
print(fibo(1, 1, i))
| true |
cb5316ef00b4697babb83b5ecf869fd397b931bb | Python | NitinJRepo/Reinforcement-Learning | /Exploration-Vs-Exploitation/04_MAB-Thompson-sampling-example.py | UTF-8 | 1,381 | 3.140625 | 3 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 24 20:13:27 2019
@author: nitin
"""
import gym
import gym_bandits
import numpy as np
# number of rounds (iterations)
num_rounds = 20000
# Count of number of times an arm was pulled
count = np.zeros(10)
# Sum of rewards of each arm
sum_rewards = ... | true |
dc8c4f2a936473ca00563e62ec48fe16a4d1296e | Python | alexmacastro/VSC_Master_Estructuras | /VSC_Membrana_Rectangular.py | UTF-8 | 2,417 | 3.3125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 26 10:03:16 2016
@author: Alejandro
============================================
Vibraciones de Sistemas Continuos
Master Universitario de Estructuras
Universidad de Granada
Curso Académico 2015-2016
=============================================
... | true |
0e1e58ecf631c06b4c92179b9565b13f70f7dcd4 | Python | anlutro/fjell.py | /tests/config_test.py | UTF-8 | 551 | 2.71875 | 3 | [
"MIT"
] | permissive | from fjell.config import Config
def test_initial_access():
c = Config({"foo": "bar"})
assert c["foo"] == "bar"
assert c.foo == "bar"
def test_update():
c = Config({"foo": "old"})
c["foo"] = "new"
assert c["foo"] == "new"
c = Config({"foo": "old"})
c.foo = "new"
assert c.foo == "... | true |
092d6ec6fcc4c10ed2da294807543159ef02412c | Python | filipmihal/ml-coursera-python-coursework | /Exercise1/linear_regression.py | UTF-8 | 3,760 | 3.90625 | 4 | [] | no_license | # used for manipulating directory paths
import os
# Scientific and vector computation for python
import numpy as np
# Plotting library
from matplotlib import pyplot
# Read comma separated data
data = np.loadtxt(os.path.join('Data', 'ex1data1.txt'), delimiter=',')
X, Y = data[:, 0], data[:, 1]
M = Y.size # number o... | true |
3b7a5057ddf31255ffc9862745529409b50acb92 | Python | kissann/labor2 | /fourth.py | UTF-8 | 1,119 | 4.5625 | 5 | [] | no_license | #Задача 4.
#Скласти розклад на тиждень. Користувач вводить порядковий номер дня тижня і у нього на екрані відображається, те, що заплановано на цей день.
print("Введите номер дня недели:")
a = int(input("День = "))
if a==1:
print("Сегодня идем на работу первый день недели")
elif a==2:
print("Сегодня второй день... | true |
49fd3fbb26012bc7a372cfb640b33a246a724242 | Python | awsdocs/aws-doc-sdk-examples | /python/example_code/ses/ses_templates.py | UTF-8 | 7,482 | 2.96875 | 3 | [
"Apache-2.0",
"MIT"
] | permissive | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) with Amazon Simple Email Service
(Amazon SES) to manage email templates that contain replaceable tags.
"""
import logging
from pprint import pprint
im... | true |
368aa5113b4bbee2336b89b36137ed0e2e87020b | Python | karimadel88/linked-in-programming-foundations-course | /4- Programming Foundations Algorithms/Ch6-OtherAlgorithms/Filtter.py | UTF-8 | 199 | 2.953125 | 3 | [] | no_license | items = ["apple", "pear", "orange", "banana",
"apple", "orange", "apple", "pear", "banana"]
filter = dict()
for key in items:
filter[key] = 0
result = set(filter.keys())
print(result)
| true |
de8289ccc0fe52bede6227c143e08c619dac5341 | Python | vokindev/python-project-lvl1 | /brain_games/games/progression_game.py | UTF-8 | 868 | 3.71875 | 4 | [] | no_license | import random
from brain_games.control import greetings, is_correct_answer
def brain_progression():
name = greetings()
print('What number is missing in the progression?')
counter = 0
while counter <= 3:
if counter == 3:
print(f'Congratulations, {name}!')
break
... | true |
3c8318c048e5b178d6eb0beb311ea0e987909a4d | Python | sousben/portfolio | /00_Snippets/Python/CurrentDev.txt | UTF-8 | 4,201 | 2.765625 | 3 | [] | no_license | #!/bin/python3
import math
import os
import random
import re
import sys
from collections import deque
AdjList = []
minHealth = sys.maxsize
maxHealth = 0
opcount = 0
def init_trie(genes):
""" creates a trie of keywords, then sets fail transitions """
AdjList.append({'value':'', 'next_states':{},'fail_state':0,... | true |
3deceb380e2a28c834ff206340c2fcd4ef0277c1 | Python | tomkimpson/Orbital-Dynamics | /tools/plot_beam_width.py | UTF-8 | 1,458 | 2.515625 | 3 | [] | no_license | from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import sys
import glob
import matplotlib.gridspec as gridspec
from mpl_toolkits.mplot3d import Axes3D
#Setup plotting environment
plt.style.use('science')
fig, ax1 =plt.subplots(1, 1, sharex=True, figsize=(10,10))
path = '/Users/tom... | true |
624f3cb728c426a7d8da0244825a7ea5f687c5d9 | Python | shezanmirzan/DataVis-Mental-Health | /Sun-Burst_View/sunburst.py | UTF-8 | 1,651 | 3.359375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 16 16:58:44 2020
@author: Nidhi
"""
import numpy as np
import pandas as pd
import os
#Replace while maintaining ratio
def assign():
if np.random.randint(1,100)<=58: # Use 58 for 2016; Use 60 for 2019
return "Yes"
else:
return "No"
#Set pa... | true |
225c44c3adf09012ebafa8a2a26b253dfdd56bdc | Python | Jayozone1/Python-Practise | /card_dealer deal_cards fumction.py | UTF-8 | 629 | 4.53125 | 5 | [] | no_license | # The deal_cards function deals a specified numberr of cards from the deck
def deal_cards(deck, number):
# Initialize an accumulator for the hand value.
hand_value = 0
# Make sure the number of cards to deal is not geater tham the number of cards in the deck.
if number > len(deck):
num... | true |
1babdfc1a0d86f4bc0715e6200c6164046e15a55 | Python | Aeternix1/Python-Crash-Course | /Chapter_6/6.10_favourite_numbers.py | UTF-8 | 481 | 3.875 | 4 | [] | no_license | #Add extra numbers to everyones favourite numbers
numbers = {
'Ajay':[13, 29],
'Steve':[22],
'Timothy': [24, 29, 28],
'Suzie': [26, 33],
'Andrew': [32, 38],
}
for name, favourites in numbers.items():
if len(favourites) == 1:
print(name + "'s favourite number is:")
for number i... | true |
bb2b64bee863bb417f10ca42afa42a2959d45a2f | Python | juniorh0landa/planetario | /user interface.py | UTF-8 | 351 | 2.515625 | 3 | [] | no_license | from i_dados import leitor as ler #interpreta os dados
from a_dados import analisador as analisar #analisa os dados interpretados
from v_dados import visualizador as visualizar #visualiza os dados analisados
dados = ler("dados.txt")
analise = analisar(dados.planetas,dados.modelos,dados.contato,dados.integrador,da... | true |
09c4ab62345e15d8321fd4e5e9dde45bd07059d0 | Python | ericlagergren/ascon-hardware | /docs/runtime_ascon128v12.py | UTF-8 | 3,270 | 2.75 | 3 | [
"CC0-1.0"
] | permissive | '''
Notation:
Na, Nm, Nc, Nh : the number of complete blocks of associated data, plaintext, ciphertext, and hash message, respectively
Ina, Inm, Inc, Inh : binary variables equal to 1 if the last block of the respective data type is incomplete, and 0 otherwise
Bla, Blm, Blc, Blh : the number of bytes in the incomple... | true |
ca0bc2296f976b300eb615a340a0fe82b202f72c | Python | dreucifer/chargenstart | /import_products.py | UTF-8 | 1,522 | 2.78125 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
# encoding: utf-8
import functools
import csv
import database as db
from product.models import Product
def get_or_create(session, obclass, **kwargs):
result = obclass.query.filter_by(**kwargs).first()
if not result:
result = obclass(**kwargs)
session.add(result)
retur... | true |
7881ff54fd5bf15a438720f4bb567f26cd4e1039 | Python | Proch92/SIR-exam | /project/rl/DDQN/graphs.py | UTF-8 | 927 | 3.03125 | 3 | [] | no_license | import csv
import matplotlib.pyplot as plt
with open('rewards.csv', 'r') as f:
rewards = list(csv.reader(f, delimiter=','))[0][:-1]
with open('epsilon.csv', 'r') as f:
epsilon = list(csv.reader(f, delimiter=','))[0][:-1]
with open('loss.csv', 'r') as f:
loss = list(csv.reader(f, delimiter=','))[0][:-1]
... | true |
ff5216d4d48f0c35c8b04d8269d60d529500c141 | Python | soham0511/data_science | /pi_chart.py | UTF-8 | 299 | 3 | 3 | [] | no_license | import matplotlib.pyplot as plt
import numpy as np
hours=[2,3,1,3,4,1,3,2,3,2]
activity=["college","play","ready","sleep","study","video game","travel","youtube","web series","waiting"]
explodes=[0.2,0,0,0,0,0,0,0.2,0,0]
plt.pie(hours,labels=activity,shadow=True,explode=explodes)
plt.show()
| true |
b6004c266399da1ffad7c0a182177652c6afa058 | Python | hshrimp/letecode_for_me | /letecode/1-120/1-24/9.py | UTF-8 | 1,497 | 3.84375 | 4 | [] | no_license | #!/usr/bin/env python
# encoding: utf-8
"""
@author: wushaohong
@time: 2019-12-16 10:06
"""
"""判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例 1:
输入: 121
输出: true
示例 2:
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:
输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。
进阶:
你能不将整数转为字符串来解决这个问题吗?
来源... | true |
9bfc6f4f18d7b184f2274c202a9d0063a5a92e08 | Python | CEshiSafeiDaDaShi/ProEGAN | /ECGdata_Pretreatment.py | UTF-8 | 10,399 | 2.96875 | 3 | [] | no_license | #!/usr/bin/env python
# coding: utf-8
'''
N中原始数据信息 (74546,)
N中数据筛选后信息 (74517, 256)
L中原始数据信息 (8075,)
L中数据筛选后信息 (8072, 256)
R中原始数据信息 (7259,)
R中数据筛选后信息 (7255, 256)
V中原始数据信息 (6903,)
V中数据筛选后信息 (6902, 256)
A中原始数据信息 (2546, 256)
A中数据筛选后信息 (2546, 256)
'''
# 预处理:安心拍顺序排序
#预声明,这里的Hz不代表真正的赫兹,324Hz代表每个心拍324个像素点
import numpy as ... | true |
ffb1d69a706306d74b484b07b13680497fcb5327 | Python | drunk-bird/SVE-GA | /model/input_coords.py | UTF-8 | 6,614 | 2.828125 | 3 | [] | no_license | # coding=utf-8
import gzip
import pickle
import numpy as np
import scipy as sp
from scipy.ndimage.filters import gaussian_filter
from os.path import dirname
from scipy import signal
def wrap_coords(path, params):
"""
Parameters:
-----------
path: str
path to simulation directory
params: di... | true |
9e32f70382639e758442000100ed02e670bab301 | Python | BibekMagar99/Hacker-Rank-Python-challenges-solutions- | /Floor, Ceil and Rint.py | UTF-8 | 298 | 2.8125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 30 14:48:40 2021
@author: bibek
"""
import numpy
numpy.set_printoptions(legacy='1.13')
for i in range(3):
A = numpy.array(list(map(float, input().split())))
print(numpy.floor(A))
print(numpy.ceil(A))
print(numpy.rint(A)) | true |
59d97bbe87a111f1bb93dadd97fed5d97090e105 | Python | ryanSoftwareEngineer/algorithms | /graphs and trees/105_construct_binary_tree_from_preorder_and_inorder.py | UTF-8 | 1,163 | 3.953125 | 4 | [] | no_license | '''Given preorder and inorder traversal of a tree, construct the binary tree.
For example, given
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
'''
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val ... | true |
8498b6451ecf42b92c42ff395f9b711dfab219ba | Python | handsinoil/Learning_probable-octo-garbanzo | /cs61a/numerator_denominator.py | UTF-8 | 1,750 | 4.40625 | 4 | [
"MIT"
] | permissive | # Constructor and selectors
#
# def rational(n, d):
# """A representation of the rational number N/D."""
# return [n, d]
#
#
# def numer(x):
# """Return the numerator of rational number X."""
# return x[0]
#
#
# def denom(x):
# """Return the denominator of rational number X."""
# return x[1]
#... | true |
e07c11e00822c8ed6276d1bfcbe4ebbac6191416 | Python | kratos1398/Advent_of_Code | /Advent_of_Code/2020/day2/lvl1.py | UTF-8 | 1,072 | 3.609375 | 4 | [] | no_license | # a password looks like this 1-11 s: sbssswsqsssssrlss
# the password must have at least 1 s and at most 11 s. If it doesnt follow this range
# then the password doesnt follow the policy
password_file = open("password.txt","r")
total_valid_password_count = 0
password_list = password_file.readlines()
my_list = []
for p... | true |
fff78ae3c0ee01b1c12c85baaa95550bd6127ee5 | Python | gucorpling/compdisc | /centering/cb_finder.py | UTF-8 | 4,341 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | from xrenner.modules.xrenner_xrenner import Xrenner
from spacy.en import English
from depedit.depedit import DepEdit
import re
def cb_finder(xrenner):
'''
:param xrenner: an analyzed xrenner object
:return: a list of lists where each inner list corresponds to a sentence,
and contains either:
-one ... | true |
d6dd8b6db2addae15684608707dc90191f3f884e | Python | linversion/spam-filter | /trainmodule.py | UTF-8 | 5,568 | 3.1875 | 3 | [] | no_license | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import re
import collections
from splitwords import SplitWords
import sys
class TrainModule:
"""
use given mails to train the module
"""
def __init__(self):
self.wordlist = {'normal': [], 'spam': []} # 创建两个字典
self.mail_count = {'normal': 0, 'spam': ... | true |
cde6eabe936c12fad646592705a87decddfbf0f7 | Python | xusongbin/python-test | /Application/ScrapyDoubanMovie/ScrapyProxy/proxy_spiders.py | UTF-8 | 7,798 | 2.640625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
# @Time : 2019/3/30 9:42
# @Author : 陈强
# @FileName: proxy_spiders.py
# @Software: PyCharm
"""
爬取代理ip网站,获取代理ip,并验证ip有效性
"""
import logging
import re
import threadpool
from ScrapyProxy.proxy_model import Proxy
from ScrapyProxy.config import available_proxy, VALIDATED_URL, headers
import re... | true |
80e9f4172df51cc188470bb1145f9098fb28f3b3 | Python | dubemc/DubeCapstone2019 | /dataFrame_1.py | UTF-8 | 643 | 3 | 3 | [] | no_license |
import pandas as pd
#reads csv of January 2018 data
pd.set_option('display.max_rows', 1000)
pd.set_option('display.max_columns', 10)
pd.set_option('display.max_colwidth', 1000)
pd.set_option('display.width', None)
data = pd.read_csv("DubeCapstone2019/JanuaryData.csv")
#default n=5, so it will only print 5 rows of d... | true |
19edce73fee538927ee401199cae26654af3f9cc | Python | kemi-kun/KEMI | /scripts/multiplicative_prefix.py | UTF-8 | 826 | 3.453125 | 3 | [] | no_license | def load_data() -> dict:
data = {}
# TODO: Use module argparse to add + parse cmd options
with open('../assets/multiplicative-prefixes.csv') as f:
lines = f.read().splitlines()
for line in lines:
number, prefix, ligand_prefix = line.split(',')
data[number] = [pref... | true |
38125febe5133a3c0a53c3d91f7ca48aefc6f38d | Python | wyager/ManyBSTs | /bst.py | UTF-8 | 782 | 3.859375 | 4 | [
"MIT"
] | permissive | # Generic: yes
# Type checked: no
class Node():
def __init__(self, value):
self.value = value
self.l = None
self.r = None
def contains(self, value):
if self.value == value:
return True
if value < self.value:
if self.l == None:
return False
return self.l.contains(value)
if value > self.value:... | true |
8cccbd2bfc3143f3b0719b96d242efb2fb4cf280 | Python | 314H/competitive-programming | /marathon-codes/RP/Maratona 4 2019-04-13/B.py | UTF-8 | 90 | 3.40625 | 3 | [] | no_license | s = input()
pos = s.find('X')
if (pos == -1):
print(len(s))
else:
print(pos) | true |
a7e7eb9445fd67d3d6ea849206b197c5bf29bbb1 | Python | ajain0395/Auto-Filtering-of-Malicious-Comments | /wiki/Wikipedia Comment Classification_Evaluation Metrics.py | UTF-8 | 8,401 | 2.53125 | 3 | [] | no_license | #!/usr/bin/env python
# coding: utf-8
# In[2]:
#!/usr/bin/env python3
import pandas as pd
import numpy as np
import copy
import seaborn as seab
from sklearn import metrics
import matplotlib.pyplot as plt
import pickle
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text i... | true |
a0d9da6467dc0361eebf30166ad2e0aa0b2ef5dc | Python | mikcel/reuters-search-engine | /engine_interface/views.py | UTF-8 | 4,613 | 2.8125 | 3 | [] | no_license | """
Views.py
Contains methods to handle HTTP requests for the app
"""
import json
import os
from search_engine.settings import BASE_DIR
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from reuters_index.index_searcher import IndexSearcher
fro... | true |
746a03ec0955fe59b5c26e4fef03c63cb98504bb | Python | workroomprds/TDD-ish_TicTacToe | /TableMaker.py | UTF-8 | 3,617 | 3.609375 | 4 | [] | no_license | #!/usr/bin/env python3
class TableMaker():
defaultTableHeaders = ["1", "2", "3", "4", "5", "6", "7", "8", "9"] #single chars onle
defaultRowLabels = ["A", "B", "C", "D", "E", "F", "G", "H", "I"] #single chars only
def __init__(self, size= 3, headerLabels=defaultTableHeaders, rowLabels=defaultRowLabels):
self.si... | true |
2d1b567ed07056d95549d2605cdc353f1b1af8f9 | Python | sudseh/bhp3_class | /bhp3_class/packets/__init__.py | UTF-8 | 1,227 | 2.6875 | 3 | [
"MIT"
] | permissive | from ctypes import *
import ipaddress
import struct
class IP:
def __init__(self, buff=None):
header = struct.unpack('<BBHHHBBH4s4s', buff)
self.ver = header[0] >> 4
self.ihl = header[0] & 0xF
self.tos = header[1]
self.len = header[2]
self.id = header[3]
... | true |
bc4c8e1c028729175d4ec85f9884d8726ac72a69 | Python | sschatz1997/Sams_website | /py_MySQL/iptest.py | UTF-8 | 558 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | import re
from time import sleep as s
def getIPs():
log = list(open("/var/log/syslog.1",'r').read().split('\n'))
newip = []
for entry in log:
ips = re.findall(r'[0-9]+(?:\.[0-9]+){3}',entry)
for ip in ips:
newip.append(ip)
t = list(set(newip))
x = 0
size = len(t)
#print(len(t))
#while(x != size):
# p... | true |
13ae365e2ce44d916b059b5029fce15e6ff8a135 | Python | emli/leetcode-python | /1_Two_Sum.py | UTF-8 | 345 | 2.96875 | 3 | [] | no_license | # time : O(N) on average
# space: O(N)
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
pos = {}
size = len(nums)
for i in range(0, size):
complement = target - nums[i]
if complement in pos:
return [i, pos[complement]]
... | true |
b61774fd1865f01f2a48129560462a4fcc8b0a16 | Python | ian-whitestone/unearthed-toronto | /load_mine_news.py | UTF-8 | 1,263 | 2.8125 | 3 | [] | no_license | import src.database_operations as dbo
import src.miningfeeds_scraper as feed
class MinerNewsLoader():
def __init__(self):
self.conn = dbo.db_connect()
def insert_miner(self, miner):
data = [(miner["name"], miner["url"], miner["ticker"], miner["market_cap"])]
query = "INSERT INTO comp... | true |
5ab4dc8068fa63040a946b755af2c21e4c5dc0b9 | Python | sojiadeshina/sojvalasseha | /final-output.py | UTF-8 | 425 | 2.953125 | 3 | [] | no_license | # Takes in a bunch of .out files containing solutions for corresponding .in files
# and outputs a single solutions.out file
out = open('solutions.out', 'w')
for i in range(1,493):
try:
s = 'final/' + str(i) + '.out'
f = open(s, 'r')
if not f:
continue
curr = ''
for line in f:
curr += line[:-1] + '; ... | true |
b1e0db034b3e6a964b25d5f117f19fd2cd237f8d | Python | adostic/python-autopsy | /ControlStructures/calculator.py | UTF-8 | 1,168 | 4.65625 | 5 | [] | no_license | while True:
print("Options.")
print("Enter 'add' to add two numbers")
print("Enter 'sub' to subtract two numbers")
print("Enter 'mul' to multiply two numbers")
print("Enter 'div' to divide two numbers")
print("Enter 'quit' to end the program")
user_input = raw_input(':')
if user_input ... | true |
62568cfefc18732b90a4952aaf5f46bd495fe08b | Python | p2slugs/recipebox | /templates/sampleprojects2.py | UTF-8 | 619 | 3.234375 | 3 | [] | no_license |
def sample1():
name = "Animal Encyclopedia"
description = "This python project shows the knowledge of classes, variables, and for loops."
link = "https://repl.it/@evagravin/Animal-Encylopedia#main.py"
info = {"name": name, "description": description, "link": link}
return info
def sample2():
na... | true |
eb9e4da4efec9101f8aa74c64f36ea0999c4371d | Python | xiyuansun/bootcamp009_project | /Project2-WebScraping/Fu-Yuan Cheng/IMDB/spiders/IMDB_spider.py | UTF-8 | 4,771 | 2.515625 | 3 | [] | no_license | from IMDB.items import ImdbItem
import scrapy
url = "http://www.imdb.com/list/ls057823854?start=%d&view=detail&sort=listorian:asc"
class IMDB_spider(scrapy.Spider):
name = 'IMDB_spider'
allowed_urls = ['http://www.imdb.com/']
start_urls = [url % i for i in range(1,9901,100)]
def verify(self, content)... | true |