repo_name stringclasses 400
values | branch_name stringclasses 4
values | file_content stringlengths 16 72.5k | language stringclasses 1
value | num_lines int64 1 1.66k | avg_line_length float64 6 85 | max_line_length int64 9 949 | path stringlengths 5 103 | alphanum_fraction float64 0.29 0.89 | alpha_fraction float64 0.27 0.89 |
|---|---|---|---|---|---|---|---|---|---|
marina-kantar/Python-for-Everybody | refs/heads/master | d = {'a' : 2 , 'c' : 1 , 'd' : 4, 'b' : 3}
t =d.items()
print(t)
s = sorted(d.items())
print(s)
for i, v in sorted(d.items()) :
print(i, v)
o = list()
for i,v in d.items():
o.append((v, i))
print(o)
o= sorted(o, reverse=True)
| Python | 12 | 18.5 | 42 | /sorttuples.py | 0.508547 | 0.491453 |
marina-kantar/Python-for-Everybody | refs/heads/master | import urllib.request, urllib.parse, urllib.error
import json
import ssl
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
url = input('Enter url: ')
if len(url) < 1: url = 'http://py4e-data.dr-chuck.net/comments_468304.json'
fhand = urllib.... | Python | 27 | 20.074074 | 75 | /json_assignment.py | 0.684859 | 0.665493 |
marina-kantar/Python-for-Everybody | refs/heads/master | import urllib.request, urllib.parse, urllib.error
import xml.etree.ElementTree as ET
import ssl
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
url = input('Enter url: ')
if len(url) < 1: url = 'http://py4e-data.dr-chuck.net/comments_468303... | Python | 27 | 20.74074 | 74 | /assignment_parsing_xml.py | 0.693356 | 0.674617 |
marina-kantar/Python-for-Everybody | refs/heads/master | import sqlite3
conn = sqlite3.connect('emaildb.sqlite')
cur = conn.cursor()
cur.execute('DROP TABLE IF EXISTS Counts')
cur.execute('CREATE TABLE Counts (email TEXT, counts INTEGER)')
fname = input('Enter file name: ')
if len(fname)< 1 : fname = 'mbox-short.txt'
handle = open(fname)
for line in handle :
if not l... | Python | 30 | 28.566668 | 86 | /sqlite_py.py | 0.655756 | 0.642212 |
ShaneRich5/lab3-ex1 | refs/heads/master | import smtplib
fromaddr = 'shane.richards212@gmail'
toaddr = 'david@alteroo.com'
message = """From: {} <{}>
To: {} <{}>
Subject: {}
{}
"""
messagetosend = message.format(
fromname,
fromaddr,
toname,
toaddr,
subject,
msg)
# Credentials
username = 'shane.richards212@gmail.com'
password = 'curryishot'
# The a... | Python | 30 | 13.866667 | 48 | /sendmail.py | 0.676404 | 0.669663 |
Basetcan/Rock_Paper_Scissors-AI-Game | refs/heads/main | # importing the libraries that we use
import random
import numpy as np
import math
import itertools
import time
choice = 0
rock_data = []
paper_data = []
scissors_data = []
next_move_rock = []
next_move_paper = []
next_move_scissors = []
## We keep the times of the moves in these lists.
player0_... | Python | 222 | 31.171171 | 126 | /rps_ai_game.py | 0.604427 | 0.582564 |
beichao1314/TREC2016 | refs/heads/master | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 7 16:17:49 2016
@author: xiaobei
"""
import nltk
from nltk.corpus import stopwords
import re
def removeStopWords_1(originSegs):
stops = set(stopwords.words('english'))
resultStr = [seg.lower() for seg in originSegs if seg.lower() not in stops and seg.isalpha()... | Python | 36 | 21.75 | 97 | /run1_crawlerA/process_profile.py | 0.678877 | 0.659341 |
beichao1314/TREC2016 | refs/heads/master | import pymysql
from process import preprocess
import time as T
import nltk
import math
import operator
class PushSummary():
def __init__(self, lemda, interest_files, time, rest, fa, topicid):
self.topicid = topicid
self.L = len(self.topicid)
self.SumOfLenthOfStream = 0
self.wordInS... | Python | 296 | 56.270271 | 134 | /run2_crawlerA/rewritesummary.py | 0.382138 | 0.371579 |
beichao1314/TREC2016 | refs/heads/master | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 8 19:37:33 2016
@author: xiaobei
"""
import pycurl
import requests
import json
import logging
logging.basicConfig(level=logging.INFO)
class REST(object):
def __init__(self,clientid):
self.clientid=clientid
self.c = pycurl.Curl()
self.c.setopt... | Python | 32 | 30.1875 | 93 | /run2_crawlerA/Rest.py | 0.625626 | 0.590591 |
beichao1314/TREC2016 | refs/heads/master | from py_bing_search import PyBingWebSearch
# s1= 9uCkTYlAG9x4iPdxAeDuQipYvc2vEn6oUbPKZJnFlVY
# s2=3L8LwEROeBFVSA1FwUVKLfIO+Ue979rarr+Y4mBZwaE
s3 = 'E+ok1GP7qpi6xgtE0yfsbrQFZSElgMBK2ZD1kwf/WXA'
s4 = 'AKvk0/D9XzJuCQA9n/a+TFbqwOFder9xd9Yj/22ivA8'
s5='r8OUqrE+DW/W4qs8ShfN2ljAU8214AkuksvYy7iMPGk'
def search(search_term):... | Python | 12 | 26.333334 | 65 | /run2_crawlerA/extension.py | 0.698171 | 0.652439 |
beichao1314/TREC2016 | refs/heads/master | # from datetime import datetime
import datetime
import time as T
from email.utils import parsedate
class Time(object):
def __init__(self, firsttime):
self.firsttime = parsedate(firsttime)
self.firsttime = datetime.datetime.fromtimestamp(T.mktime(self.firsttime))
def calculatetime(self, time):... | Python | 19 | 28.894737 | 82 | /run2_crawlerA/estimate_time.py | 0.683099 | 0.679577 |
beichao1314/TREC2016 | refs/heads/master | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 7 17:10:58 2016
@author: xiaobei
"""
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import logging.handlers
from rewritesummary import PushSummary
from Rest import REST
import json
from estimate_time import Time
fro... | Python | 160 | 30.518749 | 119 | /run2_crawlerA/crawler.py | 0.537775 | 0.524291 |
frontier96/Covid-data-analysis-and-prediction | refs/heads/main | # mortality_rate = data_states1['Mortality_Rate']
# #operate_data_counties1['mortality_rate'] = operate_data_counties1[operate_data_counties1['State'].isin(mortality_rate.index)]
# plt.figure(figsize = (5,5))
# sns.distplot(data_states1['Mortality_Rate'])
# plt.figure(figsize = (5,5))
# sns.scatterplot(x=data_states1[... | Python | 292 | 29.910959 | 198 | /old/temp.py | 0.674352 | 0.652151 |
nurtai00/WebDevProjectBack | refs/heads/main | from rest_framework import serializers
from api.models import Category, Product, Cart, User
class CategoryModelSerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('id', 'name', 'description')
class ProductSerializer(serializers.Serializer):
class Meta:
... | Python | 26 | 24.846153 | 61 | /projectback/api/serializers.py | 0.641834 | 0.641834 |
nurtai00/WebDevProjectBack | refs/heads/main | from django.urls import path
from api import views
from api.views import product_list, product_detail, category_list, product2_list, category2_list
urlpatterns = [
path('api/product', product_list),
path('api/product/<int:product_id>/', product_detail),
path('api/category', category_list),
... | Python | 15 | 37.066666 | 96 | /projectback/api/urls.py | 0.691126 | 0.680887 |
nurtai00/WebDevProjectBack | refs/heads/main | from api.models import Product, Category
from django.http.response import JsonResponse
from api.serializers import CategoryModelSerializer, ProductSerializer, CartSerializer, UserModelSerializer
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from res... | Python | 139 | 32.27338 | 107 | /projectback/api/views.py | 0.650294 | 0.641058 |
nurtai00/WebDevProjectBack | refs/heads/main | from django.contrib import admin
from api.models import Product, Category, Cart, User
# Register your models here.
admin.site.register(Product),
admin.site.register(Category),
admin.site.register(Cart),
admin.site.register(User)
| Python | 8 | 27.75 | 52 | /projectback/api/admin.py | 0.768908 | 0.768908 |
nurtai00/WebDevProjectBack | refs/heads/main | from django.db import models
class Category(models.Model):
name = models.CharField(max_length=200)
description = models.TextField(max_length=500, default='')
def to_json(self):
return {
'id': self.id,
'name': self.name,
'description': self.descriptio... | Python | 39 | 27.179487 | 91 | /projectback/api/models.py | 0.614236 | 0.595782 |
nurtai00/WebDevProjectBack | refs/heads/main | # Generated by Django 3.2.2 on 2021-05-07 19:40
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Category',
... | Python | 56 | 33.55357 | 130 | /projectback/api/migrations/0002_auto_20210508_0140.py | 0.524862 | 0.509794 |
DonJayamanne/vscode-python-samples | refs/heads/master | import ptvsd
import time
import os
print(os.curdir)
print("Waiting to attach")
address = ('0.0.0.0', 3000)
ptvsd.enable_attach('my_secret', address)
ptvsd.wait_for_attach()
time.sleep(2)
print("attached")
print("end")
| Python | 15 | 13.8 | 41 | /remote-debugging-locally/sample.py | 0.711712 | 0.671171 |
DonJayamanne/vscode-python-samples | refs/heads/master | from django.shortcuts import render
from django.template import loader
def index(request):
context = {
'value_from_server':'one',
'another_value_from_server':'two'
}
return render(request, 'index.html', context)
# from django.shortcuts import render
# from django.shortcuts import render_... | Python | 20 | 29.549999 | 117 | /sample-django/home/views.py | 0.698854 | 0.698854 |
AEJ-FORMATION-DATA-IA/exercicepython-kmk | refs/heads/main | #!/usr/bin/env python
# coding: utf-8
# In[92]:
A = 15
B = 4
C = A + B
print("le résultat de ", A, "+", B," est ",C)
# In[93]:
#la multiplication des deux variables
D = A * B
print("le résultat de la multiplication de ", A,"*",B ," est ",D)
#la puissance
E = A**B
print("le resultat de la puissance de ", A,"**", ... | Python | 162 | 12.339506 | 151 | /exercice IGS.py | 0.625809 | 0.593432 |
AEJ-FORMATION-DATA-IA/exercicepython-kmk | refs/heads/main | A = input("entrez un nombre entier: ")
try:
A = int(A)
except:
A=input("\n Erreur !!! Veuillez entrer un nombre entier: ")
A=int(A)
B=input("entrez un deuxieme nombre entier: ")
try:
B = int(B)
except:
B = input("\n Erreur !!!, Votre nombre doit etre un nombre entier: ")
B = int(B)
C = A + B
pri... | Python | 14 | 24.714285 | 73 | /temp.py | 0.579387 | 0.579387 |
torchioalexis/python_basico | refs/heads/main | def run():
square_root = int(input("Ingrese un número para calcular su raíz cuadrada: "))
square = 0
while square**2 < square_root:
square += 1
if square**2 == square_root:
print ("La raíz cuadrada de", square_root, "es", square)
else:
print (square_root, "no tiene raíz cua... | Python | 14 | 25.642857 | 82 | /exha_enum.py | 0.580645 | 0.569892 |
Sohan-Pramanik/boilermake | refs/heads/main | # Developed by matthew-notaro, nalinahuja22, and ClarkChan1
| Python | 1 | 59 | 59 | /bin/timeline.py | 0.816667 | 0.766667 |
Sohan-Pramanik/boilermake | refs/heads/main | # Developed by matthew-notaro, nalinahuja22, and ClarkChan1
import os
import sys
class Audio:
def __init__(self, afile):
# Audio File Path
self.afile = afile
# Audio Analysis
self.track = []
def analyze(self):
# Audio File Duration
duration = librosa.get_durat... | Python | 30 | 22.766666 | 73 | /bin/audio.py | 0.596073 | 0.58906 |
jj240396/Medium | refs/heads/master |
#df - table containing the historical stock prices for the past 10 years.
#df_weights - dict containing the weightage of each stock in the portfolio
#converting the df_weights dict to dataframe
weightage = pd.DataFrame.from_dict(df_weights)
weightage = weightage.transpose()
weightage.columns = ['weightage']
np.sum(w... | Python | 54 | 32.129631 | 95 | /stock_portfolio_risk.py | 0.697934 | 0.695142 |
vanya2143/ITEA-tasks | refs/heads/master | """
2. Написать декоратор log, который будет выводить на экран все аргументы,
которые передаются вызываемой функции.
@log
def my_sum(*args):
return sum(*args)
my_sum(1,2,3,1) - выведет "Функция была вызвана с - 1, 2, 3, 1"
my_sum(22, 1) - выведет "Функция была вызвана с - 22, 1"
"""
def log(func):
def wrappe... | Python | 28 | 19.035715 | 73 | /hw-2/task_2.py | 0.597148 | 0.561497 |
vanya2143/ITEA-tasks | refs/heads/master | """
Реализовать алгоритм бинарного поиска на python.
На вход подается упорядоченный список целых чисел, а так же элемент,
который необходимо найти и указать его индекс,
в противном случае – указать что такого элемента нет в заданном списке.
"""
def search_item(some_list, find_item):
some_list.sort()
list_leng... | Python | 40 | 24.025 | 71 | /hw-1/task_3.py | 0.567433 | 0.535465 |
vanya2143/ITEA-tasks | refs/heads/master | # 2. Используя модуль unittests написать тесты: сложения двух матриц, умножения матрицы и метод transpose
import unittest
from .task_1 import Matrix, MatrixSizeError
class TestMatrix(unittest.TestCase):
def setUp(self) -> None:
self.matrix_1 = Matrix([[1, 2, 9], [3, 4, 0], [5, 6, 4]])
self.matrix... | Python | 37 | 36.540539 | 105 | /hw-6/task_2.py | 0.565155 | 0.478042 |
vanya2143/ITEA-tasks | refs/heads/master | """
1. Определить количество четных и нечетных чисел в заданном списке.
Оформить в виде функции, где на вход будет подаваться список с целыми числами.
Результат функции должен быть 2 числа, количество четных и нечетных соответственно.
"""
def list_check(some_list):
even_numb = 0
not_even_numb = 0
for e... | Python | 23 | 24.608696 | 83 | /hw-1/task_1.py | 0.62309 | 0.604414 |
vanya2143/ITEA-tasks | refs/heads/master | """
Реализовать некий класс Matrix, у которого:
1. Есть собственный конструктор, который принимает в качестве аргумента - список списков,
копирует его (то есть при изменении списков, значения в экземпляре класса не должны меняться).
Элементы списков гарантированно числа, и не пустые.
2. Метод size без аргументов, кото... | Python | 50 | 29.719999 | 109 | /hw-3/task_1.py | 0.664714 | 0.639323 |
vanya2143/ITEA-tasks | refs/heads/master | """
1. Реализовать подсчёт елементов в классе Matrix с помощью collections.Counter.
Можно реализовать протоколом итератора и тогда будет такой вызов - Counter(maxtrix).
Либо сделать какой-то метод get_counter(), который будет возвращать объект Counter и подсчитывать все элементы
внутри матрицы. Какой метод - ваш выбор.... | Python | 67 | 27.985075 | 110 | /hw-6/task_1.py | 0.591658 | 0.57724 |
vanya2143/ITEA-tasks | refs/heads/master | """
К реализованному классу Matrix в Домашнем задании 3 добавить следующее:
1. __add__ принимающий второй экземпляр класса Matrix и возвращающий сумму матриц,
если передалась на вход матрица другого размера - поднимать исключение MatrixSizeError
(по желанию реализовать так, чтобы текст ошибки содержал размерность 1 и 2... | Python | 90 | 28.288889 | 103 | /hw-4/task_1.py | 0.58915 | 0.563354 |
vanya2143/ITEA-tasks | refs/heads/master | """
Сделать скрипт, который будет делать GET запросы на следующие ресурсы:
"http://docs.python-requests.org/",
"https://httpbin.org/get",
"https://httpbin.org/",
"https://api.github.com/",
"https://example.com/",
"https://www.python.org/",
"https://www.google.com.ua/",
"https://regex101.... | Python | 67 | 32.701492 | 107 | /hw-7/task_1.py | 0.627989 | 0.61116 |
vanya2143/ITEA-tasks | refs/heads/master | """
Написать функцию, которая принимает 2 числа.
Функция должна вернуть сумму всех элементов числового ряда между этими двумя числами.
(если подать 1 и 5 на вход, то результат должен считаться как 1+2+3+4+5=15)
"""
def all_numbers_sum(num1, num2):
return sum([num for num in range(num1, num2 + 1)])
if __name__ =... | Python | 13 | 27.23077 | 85 | /hw-1/task_2.py | 0.689373 | 0.643052 |
vanya2143/ITEA-tasks | refs/heads/master | # Реализовать пример использования паттерна Singleton
from random import choice
# Генератор событий
def gen_events(instance, data, count=2):
for i in range(count):
event = choice(data)
instance.add_event(f'Event-{event}-{i}', event)
# Singleton на примере списка событий
class EventsMeta(type):
... | Python | 104 | 27.586538 | 88 | /hw-5/task_1.py | 0.57854 | 0.572822 |
vanya2143/ITEA-tasks | refs/heads/master | """
1. Написать функцию, которая будет принимать на вход натуральное число n,
и возращать сумму его цифр. Реализовать используя рекурсию
(без циклов, без строк, без контейнерных типов данных).
Пример: get_sum_of_components(123) -> 6 (1+2+3)
"""
def get_sum_of_components_two(n):
return 0 if not n else n % 10 + get... | Python | 14 | 29.214285 | 73 | /hw-2/task_1.py | 0.690307 | 0.652482 |
glorizen/hi10enc | refs/heads/master | import os
from flask import Flask
from flask import request
from flask import jsonify
from flask import render_template
from flask import send_from_directory
from parsers import MediaParser
from parsers import AvsParser
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'd:/temp'
@app.route('/static/metronic_v5.0.2... | Python | 111 | 21.432432 | 86 | /app.py | 0.715375 | 0.702529 |
glorizen/hi10enc | refs/heads/master | from pymediainfo import MediaInfo
class MediaParser(object):
def __init__(self, xml_string):
self.mediainfo = MediaInfo(xml_string)
self.metadata = self.mediainfo.to_data()
#>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
def get_gen... | Python | 186 | 34.446236 | 96 | /parsers.py | 0.505233 | 0.504171 |
adbedada/aia | refs/heads/master | #!/usr/bin/env python
# test yolo
#based on
"""
https://github.com/awslabs/amazon-sagemaker-examples/blob/
master/advanced_functionality/tensorflow_bring_your_own/container/cifar10/train
"""
import os
import sys
import subprocess
import traceback
import tqdm
def _run(cmd):
process = subprocess.Popen(cmd, stdout=s... | Python | 42 | 27.166666 | 99 | /sagemaker/yolo/train | 0.593063 | 0.582064 |
HeyamBasem/Digit-Recognition- | refs/heads/main | # sort data because using fetch_openml() return unsorted data
from scipy import ndimage
def sort_by_target(mnist):
reorder_train = np.array(sorted([(target, i) for i, target in enumerate(mnist.target[:60000])]))[:, 1]
reorder_test = np.array(sorted([(target, i) for i, target in enumerate(mnist.target[60... | Python | 421 | 28.783848 | 106 | /BookProject.py | 0.677006 | 0.640509 |
issyl0/alexa-house-cleaning-rota | refs/heads/master | def alexa_handler(event, context):
request = event['request']
# called when invoked with no values - early exit
if request['type'] == 'LaunchRequest':
return get_welcome_response()
if request['type'] == 'IntentRequest':
intent = request['intent']
if intent['name'] == 'HouseCle... | Python | 106 | 26.688679 | 92 | /handler.py | 0.539353 | 0.53799 |
joseruiz1989/teste_python_vsc_github | refs/heads/master | print("teste print file from github")
print("hola desde vs")
print("testesito más 1")
print("testesito más 12") | Python | 6 | 18 | 37 | /teste_code.py | 0.725664 | 0.699115 |
AriniInf/PROGJAR_05111740007003 | refs/heads/master | from client import *
if __name__=='__main__':
os.chdir('./client')
upload('progjar.txt', 'progjar.txt') | Python | 5 | 21.6 | 40 | /tugas4/client_upload.py | 0.580357 | 0.580357 |
AriniInf/PROGJAR_05111740007003 | refs/heads/master | import sys
import socket
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('127.0.0.1', 10000)
print(f"starting up on {server_address}")
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
while True:
# Wait for a... | Python | 28 | 29.178572 | 56 | /tugas1/tugas1b/server/server.py | 0.668639 | 0.64497 |
AriniInf/PROGJAR_05111740007003 | refs/heads/master | import threading
import logging
import requests
import datetime
import os
def download_gambar(url=None):
if (url is None):
return False
ff = requests.get(url)
tipe = dict()
tipe['image/png']='png'
tipe['image/jpg']='jpg'
tipe['image/jpeg']='jpg'
content_type = ff.headers['Content-... | Python | 42 | 25.952381 | 101 | /tugas3/client_3.py | 0.616946 | 0.603707 |
AriniInf/PROGJAR_05111740007003 | refs/heads/master | from client import *
if __name__=='__main__':
os.chdir('./client')
download('opo.txt', 'abc.txt') | Python | 6 | 17 | 34 | /tugas4/client_download.py | 0.551402 | 0.551402 |
xmlabs-io/xmlabs-python | refs/heads/master | from .aws_lambda import xmlabs_lambda_handler
| Python | 1 | 45 | 45 | /xmlabs/__init__.py | 0.826087 | 0.826087 |
xmlabs-io/xmlabs-python | refs/heads/master | from .config import xmlabs_settings
from .env import get_environment
from functools import wraps
def xmlabs_lambda_handler(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
env, config = None , None
try:
env = get_environment(*args, **kwargs)
if not env:
rai... | Python | 37 | 29.972973 | 74 | /xmlabs/aws_lambda/handler.py | 0.582024 | 0.582024 |
xmlabs-io/xmlabs-python | refs/heads/master | import pytest
from xmlabs.aws_lambda.config import settings
def test_xmlabs_aws_lambda_config():
"""Assert Settings"""
assert settings
| Python | 7 | 19.857143 | 45 | /tests/test_aws_lambda_settings.py | 0.732877 | 0.732877 |
xmlabs-io/xmlabs-python | refs/heads/master | from .handler import xmlabs_lambda_handler
| Python | 1 | 42 | 42 | /xmlabs/aws_lambda/__init__.py | 0.818182 | 0.818182 |
xmlabs-io/xmlabs-python | refs/heads/master | import os
import logging
logger = logging.getLogger()
def get_environment(event, context=None):
valid_envs = ["stage", "prod", "dev"]
env = None
# default_env = os.getenv("DEFAULT_ENV", "dev")
default_env = os.getenv("APP_ENV", os.getenv("DEFAULT_ENV", "dev"))
override_env = os.getenv("ENV")
... | Python | 77 | 31.207792 | 108 | /xmlabs/aws_lambda/env.py | 0.478226 | 0.47621 |
xmlabs-io/xmlabs-python | refs/heads/master | import boto3
import logging
import requests
from functools import lru_cache
from dynaconf.utils.parse_conf import parse_conf_data
logger = logging.getLogger()
IDENTIFIER = 'aws_ssm'
def load(obj, env=None, silent=True, key=None, filename=None):
"""
Reads and loads in to "obj" a single key or all keys from ... | Python | 90 | 29.722221 | 76 | /xmlabs/dynaconf/aws_ssm_loader.py | 0.558047 | 0.557324 |
xmlabs-io/xmlabs-python | refs/heads/master | from .base import ConfigSource
import logging
import requests
logger = logging.getLogger()
class ConfigSourceAwsEc2UserData(ConfigSource):
def load(self):
if self._running_in_ec2():
#TODO: fetch EC2 USERDATA
raise Exception("ConfigSourceEC2UserData Load Unimplemented")
... | Python | 19 | 33.842106 | 82 | /xmlabs/dynaconf/aws_ec2_userdata_loader.py | 0.645015 | 0.602719 |
xmlabs-io/xmlabs-python | refs/heads/master | from xmlabs.aws_lambda import lambda_handler
@lambda_handler
def main(event, context, config):
print(config.STRIPE_API_SECRET_KEY)
pass
if __name__ == "__main__":
main({"headers":{"X-Environment": "dev"}}, {})
main({"headers":{"X-Environment": "prod"}}, {})
main({"headers":{"X-Environment": "dev"}... | Python | 13 | 32.076923 | 51 | /example/aws_lambda/app.py | 0.581019 | 0.581019 |
xmlabs-io/xmlabs-python | refs/heads/master |
import pytest
from xmlabs import xmlabs_lambda_handler
@xmlabs_lambda_handler
def lambda_handler(event, context, config):
assert(config)
def test_lambda_handler():
lambda_handler({},{})
| Python | 11 | 17 | 43 | /tests/test_aws_lambda_integration.py | 0.728643 | 0.728643 |
xmlabs-io/xmlabs-python | refs/heads/master | from dynaconf import Dynaconf
from dynaconf.constants import DEFAULT_SETTINGS_FILES
LOADERS_FOR_DYNACONF = [
'dynaconf.loaders.env_loader', #Inorder to configure AWS_SSM_PREFIX we need to load it from environment
'xmlabs.dynaconf.aws_ssm_loader',
'dynaconf.loaders.env_loader', #Good to load environment las... | Python | 26 | 30.923077 | 110 | /xmlabs/aws_lambda/config.py | 0.715663 | 0.715663 |
xmlabs-io/xmlabs-python | refs/heads/master | from dynaconf import Dynaconf
def test_dynaconf_settingsenv():
settingsenv = Dynaconf(environments=True)
assert settingsenv
def test_dynaconf_settings():
settings = Dynaconf()
assert settings
| Python | 10 | 20.1 | 45 | /tests/test_dynaconf.py | 0.744076 | 0.744076 |
b3b0/allyourbase | refs/heads/master | import os
def wazuh():
os.system('echo "ALLYOURBASE" >> /var/log/auth.log')
print("IT HAS BEEN DONE")
wazuh()
| Python | 7 | 16.142857 | 56 | /allyourbase.py | 0.625 | 0.625 |
rexapex/tealight-files | refs/heads/master | from tealight.art import (color, line, spot, circle, box, image, text, background, rectangle)
from tealight.art import screen_width, screen_height
from math import sin, cos, pi, sqrt
class explosion:
def __init__(self):
self.time = 50
self.x = 0
self.y = 0
def set_pos(self, x, y):
self.x =... | Python | 39 | 21.205128 | 93 | /art/explosion.py | 0.546286 | 0.521143 |
rexapex/tealight-files | refs/heads/master | from tealight.art import (color, line, spot, circle, box, image, text, background, rectangle)
from tealight.art import screen_width, screen_height
from math import sin, cos, pi, sqrt
from github.Krimzar.art.racecar import car
from github.rexapex.art.explosion import explosion
car1 = None #The player using this... | Python | 225 | 25.559999 | 140 | /art/prj_racetrack.py | 0.67113 | 0.63749 |
rexapex/tealight-files | refs/heads/master | from tealight.art import (color, line, spot, circle, box, image, text, background)
from tealight.art import screen_width, screen_height
from math import sin, cos, pi
running = False
car1 = None
def handle_keydown(key):
global ax, ay
if key == "left" or key == "right":
car1.ax = 1
elif key == "up" or key ... | Python | 70 | 12.371428 | 82 | /art/racetrack.py | 0.534759 | 0.508021 |
rexapex/tealight-files | refs/heads/master | from tealight.art import (color, line, spot, circle, box, image, text, background)
from tealight.art import screen_width, screen_height
from math import sin, cos, pi
class car:
x = 0
y = 0
orientation = 0
acceleration = 0
power = 0.3
def update(self):
self.x += self.acceleration
def draw... | Python | 25 | 20.200001 | 82 | /art/prj_car.py | 0.657944 | 0.642991 |
rexapex/tealight-files | refs/heads/master | from tealight.robot import (move,
turn,
look,
touch,
smell,
left_side,
right_side)
# Add your code here
def moveBy(spaces):
for i in range(0, s... | Python | 25 | 17.280001 | 39 | /robot/mine.py | 0.366228 | 0.359649 |
rexapex/tealight-files | refs/heads/master | from tealight.logo import move, turn
def square(side):
for i in range(0,4):
move(side)
turn(90)
def chessboard():
sqSize = 8
for i in range(0, 8):
for j in range(0, 8):
square(sqSize)
move(sqSize)
turn(180)
move(8 * sqSize)
turn(-90)
move(8)
turn(-90)
turn(-90)
c... | Python | 21 | 14.809524 | 36 | /logo/chess.py | 0.570997 | 0.510574 |
rexapex/tealight-files | refs/heads/master | from tealight.art import (color, line, spot, circle, box, image, text, background)
from tealight.art import screen_width, screen_height
from math import sin, cos, pi
x = screen_width / 2
y = screen_height / 2
vx = 0
vy = 0
ax = 0
ay = 0
gravity = 0.2
drag = 0
power = 0.3
explosionX = 0
explosionY = 0
explosionTi... | Python | 90 | 16.411112 | 82 | /art/orbits.py | 0.583598 | 0.556898 |
kapilkalra04/face-off-demo-python-flask | refs/heads/master | import cv2
import numpy as np
import matplotlib.pyplot as plt
from keras.models import load_model
import keras
import pandas as pd
def rotate(face,left_eye_center_x,left_eye_center_y,right_eye_center_x,right_eye_center_y):
lx = left_eye_center_x
ly = left_eye_center_y
rx = right_eye_center_x
ry = right_eye_center... | Python | 148 | 32.020271 | 113 | /src/alignment.py | 0.697565 | 0.672601 |
kapilkalra04/face-off-demo-python-flask | refs/heads/master | from flask import Flask
from flask import request
import base64
import siameseTrain as ST1
import siameseTest as ST2
import siameseRecognizer as SR
import json
app = Flask(__name__)
@app.route("/")
def hello():
return "Connection Successful"
@app.route("/upload", methods=['POST'])
def upload():
base64Data = req... | Python | 42 | 23.857143 | 72 | /src/app.py | 0.706616 | 0.67977 |
kapilkalra04/face-off-demo-python-flask | refs/heads/master | import numpy as np
import matplotlib.pyplot as plt
import cv2
def convertToRGB(img):
return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
def convertToGRAY(img):
return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
def detect(model,weights,image,isPath):
# specify locations of the model and its weights
args = {}
args[... | Python | 117 | 29.632479 | 111 | /src/detection.py | 0.660061 | 0.631873 |
kapilkalra04/face-off-demo-python-flask | refs/heads/master | import detection
import matplotlib.pyplot as plt
import cv2
import alignment
def detectMainFace(imageName,isPath):
model = "src/deploy.prototxt.txt" # model-definition
weights = "src/res10_300x300_ssd_iter_140000.caffemodel" # pre-trained weights
image = imageName # image name reqd. images are load... | Python | 98 | 37.2449 | 128 | /src/pre_processing2.py | 0.755336 | 0.732391 |
kapilkalra04/face-off-demo-python-flask | refs/heads/master | # The pre-trained model was provided by https://github.com/iwantooxxoox/Keras-OpenFace #
import tensorflow as tf
import numpy as np
import cv2
import glob
import pre_processing2 as pre
import matplotlib.pyplot as plt
def load_graph(frozen_graph_filename):
with tf.gfile.GFile(frozen_graph_filename, "rb") as f:
... | Python | 73 | 35.931507 | 98 | /src/siameseTest.py | 0.657895 | 0.617865 |
kapilkalra04/face-off-demo-python-flask | refs/heads/master | import numpy as np
import glob
import cv2
import pre_processing2 as pre
import matplotlib.pyplot as plt
def calculateNorm():
empEmbeddings = np.load('src/empEmbeddings.npy')
cstmrEmbeddings = np.load('src/cstmrEmbeddings.npy')
faceListTrain = []
faceListTest = []
answer = {}
norm = []
for i in range(0,len... | Python | 60 | 22.933332 | 81 | /src/siameseRecognizer.py | 0.703136 | 0.677352 |
kapilkalra04/face-off-demo-python-flask | refs/heads/master | import glob
import numpy as np
import pre_processing2 as pre
import cv2
import matplotlib.pyplot as plt
images = []
for imagePath in glob.glob('data/library/train2/*'):
images.append(imagePath)
faceList = []
# labelList = [0,0,0,0,0,0,0,0,0,0]
labelList = [0]
index = 0
for path in images:
temp = pre.getFaceGray(p... | Python | 60 | 24.333334 | 65 | /src/recognition.py | 0.698026 | 0.651974 |
acheng6845/PuzzleSolver | refs/heads/master | __author__ = 'Aaron'
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5 import QtWidgets, QtCore, QtGui
class PADCompleter(QCompleter):
def __init__(self):
super().__init__()
self.prefix = ''
self.model = None
def _set_model_(self, model):
... | Python | 37 | 31.378378 | 88 | /PADCompleter.py | 0.606516 | 0.602339 |
acheng6845/PuzzleSolver | refs/heads/master | __author__ = 'Aaron'
# Class Description:
# Create framework for the split screens used in PAD_GUI
# import necessary files
import os
import json
from functools import partial
from PyQt5.QtWidgets import (QLabel, QWidget, QHBoxLayout,
QFrame, QSplitter, QStyleFactory,
... | Python | 536 | 47.794777 | 117 | /Calculator_Screen.py | 0.60052 | 0.589738 |
acheng6845/PuzzleSolver | refs/heads/master | __author__ = 'Aaron'
# import necessary files
from PyQt5 import PyQt5
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QHBoxLayout,
QFrame, QSplitter, QStyleFactory,
QMainWindow, QStackedWidget)
from PyQt5.QtCore import Qt
from PADScreen import P... | Python | 54 | 22.75926 | 64 | /PAD_GUI.py | 0.662246 | 0.640406 |
acheng6845/PuzzleSolver | refs/heads/master | __author__ = 'Aaron'
# Class Description:
# Our Monster Class where we hold all of the Monster's stats and calculate the values needed with those stats
import os
import json
class PADMonster:
def __init__(self):
# initialize the Class's stats
# _max, _min, and _scale are used for when the mon... | Python | 272 | 41.952206 | 120 | /PAD_Monster.py | 0.558076 | 0.538903 |
acheng6845/PuzzleSolver | refs/heads/master | __author__ = 'Aaron'
from Calculator_Screen import CalculatorScreen
from Board_Screen import BoardScreen
from PAD_Monster import PADMonster
from PAD_Team import PADTeam
from PyQt5.QtWidgets import (QVBoxLayout, QHBoxLayout, QWidget, QPushButton, QSplitter, QAction,
QFileDialog, QMainWindow... | Python | 214 | 47.626167 | 104 | /PADScreen.py | 0.620471 | 0.618837 |
acheng6845/PuzzleSolver | refs/heads/master | __author__ = 'Aaron'
import os
from PAD_Monster import PADMonster
class PADTeam:
def __init__(self, team):
"""
Initializes the PADTeam Class.
:param team: an array containing 6 PADMonster Classes
"""
# self.team = [PADMonster() for monster in range(6)] -> how the team shoul... | Python | 149 | 49.10067 | 113 | /PAD_Team.py | 0.564903 | 0.548292 |
acheng6845/PuzzleSolver | refs/heads/master | __author__ = 'Aaron'
from PyQt5.QtWidgets import (QVBoxLayout, QWidget, QLabel, QGridLayout, QSplitter,
QPushButton, QHBoxLayout)
from PyQt5.QtCore import Qt, QMimeData
from PyQt5.QtGui import QPixmap, QDrag
import os
from PAD_Monster import PADMonster
from PAD_Team import PADTeam
from func... | Python | 288 | 43.246529 | 118 | /Board_Screen.py | 0.561372 | 0.550306 |
acheng6845/PuzzleSolver | refs/heads/master | __author__ = 'Aaron'
# Class Description:
# Update our monsters.txt file and our images folder
from urllib3 import urllib3
import shutil
import os
import json
class image_updater():
def __init__(self):
# update monsters.txt here:
self.json_file = open(os.path.realpath('./monsters.txt'), 'r')... | Python | 59 | 30.016949 | 90 | /image_updater.py | 0.522143 | 0.517769 |
lonce/dcn_soundclass | refs/heads/master | """
eg
python testPickledModel.py logs.2017.04.28/mtl_2.or_channels.epsilon_1.0/state.pickle
"""
import tensorflow as tf
import numpy as np
import pickledModel
from PIL import TiffImagePlugin
from PIL import Image
# get args from command line
import argparse
FLAGS = None
VERBOSE=False
# -----------------------... | Python | 102 | 31.382353 | 105 | /testPickledModel.py | 0.679177 | 0.602603 |
lonce/dcn_soundclass | refs/heads/master | import os
import numpy as np
import matplotlib.pyplot as plt
# https://github.com/librosa/librosa
import librosa
import librosa.display
import scipy
from PIL import TiffImagePlugin
from PIL import Image
import tiffspect
# Set some project parameters
K_SR = 22050
K_FFTSIZE = 512 # also used for window length where th... | Python | 214 | 44.752335 | 158 | /utils/ESC50_Convert.py | 0.579598 | 0.57102 |
lonce/dcn_soundclass | refs/heads/master | #
#
#Morgans great example code:
#https://blog.metaflow.fr/tensorflow-how-to-freeze-a-model-and-serve-it-with-a-python-api-d4f3596b3adc
#
# GitHub utility for freezing graphs:
#https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/freeze_graph.py
#
#https://www.tensorflow.org/api_docs/python/tf/g... | Python | 62 | 30.709677 | 102 | /trainedModel.py | 0.712544 | 0.695277 |
lonce/dcn_soundclass | refs/heads/master | """
eg
python testModel.py logs.2017.04.28/mtl_2.or_channels.epsilon_1.0/my-model.meta logs.2017.04.28/mtl_2.or_channels.epsilon_1.0/checkpoints/
"""
import tensorflow as tf
import numpy as np
import trainedModel
from PIL import TiffImagePlugin
from PIL import Image
# get args from command line
import argparse
FL... | Python | 150 | 33.553333 | 170 | /testTrainedModel.py | 0.689236 | 0.634838 |
lonce/dcn_soundclass | refs/heads/master |
""" An implementation of the paper "A Neural Algorithm of Artistic Style"
by Gatys et al. in TensorFlow.
Author: Chip Huyen (huyenn@stanford.edu)
Prepared for the class CS 20SI: "TensorFlow for Deep Learning Research"
For more details, please read the assignment handout:
http://web.stanford.edu/class/cs20si/assignmen... | Python | 299 | 37.183945 | 144 | /style_transfer.py | 0.612804 | 0.604922 |
lonce/dcn_soundclass | refs/heads/master | #
#
#Morgans great example code:
#https://blog.metaflow.fr/tensorflow-how-to-freeze-a-model-and-serve-it-with-a-python-api-d4f3596b3adc
#
# GitHub utility for freezing graphs:
#https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/tools/freeze_graph.py
#
#https://www.tensorflow.org/api_docs/python/tf/g... | Python | 190 | 36.763157 | 197 | /pickledModel.py | 0.654961 | 0.625279 |
lonce/dcn_soundclass | refs/heads/master | """
"""
import tensorflow as tf
import numpy as np
import spectreader
import os
import time
import math
import pickledModel
# get args from command line
import argparse
FLAGS = None
# ------------------------------------------------------
# get any args provided on the command line
parser = argparse.ArgumentParser(f... | Python | 685 | 42.769344 | 239 | /DCNSoundClass.py | 0.688113 | 0.674438 |
lonce/dcn_soundclass | refs/heads/master | import os
import re
import numpy as np
import math
import tiffspect
import librosa
import librosa.display
import matplotlib.pyplot as plt
K_SPECTDIR = '/home/lonce/tflow/DATA-SETS/ESC-50-spect'
k_soundsPerClass=125 # must divide the total number of sounds evenly!
#============================================
def... | Python | 100 | 38.009998 | 135 | /utils/Centroid2ndaryClassMaker.py | 0.633778 | 0.625064 |
scissorhands/pynal | refs/heads/master | from __future__ import print_function
import json
from etl import Etl
def lambda_connect(event, context):
etl = Etl()
etl.retrieve_all_stats()
return 'pickle rick'
if __name__ == '__main__':
lambda_connect(None, None) | Python | 11 | 19.363636 | 37 | /index.py | 0.695067 | 0.695067 |
scissorhands/pynal | refs/heads/master | import analytics as service
class Requester:
def __init__(self):
self.analytics = service.initialize_analyticsreporting()
self.general_stats_metrics = [
{'expression': 'ga:sessions'},
{'expression': 'ga:pageViews'},
{'expression': 'ga:avgTimeOnPage'},
{'expression': 'ga:exits'},
{'expression': 'ga:... | Python | 56 | 28.071428 | 78 | /requester.py | 0.552551 | 0.550092 |
scissorhands/pynal | refs/heads/master | import dbconfig
import mysql.connector as _connector
from mysql.connector import errorcode as dberror
class Connector:
def __init__(self):
self.cnx = self.cur = None
try:
self.cnx = _connector.connect(**dbconfig.config)
except _connector.Error as e:
if(e.errno == dberror.ER_ACCESS_DENIED_ERROR):
prin... | Python | 69 | 24.202898 | 88 | /dbconnector.py | 0.620829 | 0.601266 |
scissorhands/pynal | refs/heads/master | from requester import Requester
from dbconnector import Connector
import json
import datetime as dt
class Etl:
def __init__(self):
self.req = Requester()
self.connector = Connector()
def get_report_dictionary(self, report):
columnHeader = report.get('columnHeader', {})
return {
'columnHeader': columnHea... | Python | 90 | 31.299999 | 89 | /etl.py | 0.692361 | 0.681349 |
scissorhands/pynal | refs/heads/master | from requester import Requester
import json
req = Requester()
localTest = False
print('Loading function')
def respond(err, res=None):
return {
'statusCode': '400' if err else '200',
'body': err.message if err else json.dumps(res),
'headers': {
'Content-Type': 'application/json... | Python | 51 | 24.254902 | 84 | /index_microservice.py | 0.547786 | 0.543124 |
jesbarlow/CP1404_practicals | refs/heads/master |
COLOUR_CODES = {"CadetBlue2": "#8ee5ee", "CornflowerBlue": "#6495ed", "Chartreuse4": "#458600",
"DarkOliveGreen3": "#a2cd5a", "DarkTurquoise": "#00ced1", "Gold1": "#ffd700",
"IndianRed2": "#eeb363", "PaleVioletRed2": "#ee799f", "RosyBrown4": "#8b6969",
"Snow2": "#eee9e9"... | Python | 16 | 40 | 95 | /prac_5/colour_codes.py | 0.602134 | 0.535061 |
jesbarlow/CP1404_practicals | refs/heads/master | name_file = open('name.txt', 'w')
name = input("What is your name?: ")
name_file.write(name)
name_file.close()
open_file = open('name.txt', 'r')
open_file.read().strip()
print ("Your name is",name)
open_file.close()
out_file = open('numbers.txt', 'r')
num_one = int(out_file.readline())
num_two = int(out_file.readline... | Python | 16 | 21.9375 | 36 | /prac_2/files.py | 0.65847 | 0.65847 |
jesbarlow/CP1404_practicals | refs/heads/master | sentence = input("Enter a sentence:")
words = sentence.split()
counting = {}
for word in words:
if word in counting:
counting[word] += 1
else:
counting[word] = 1
print("Text: {}".format(sentence))
for key, value in counting.items():
print("{} : {}".format(key,value)) | Python | 14 | 20.357143 | 38 | /prac_5/word_count.py | 0.607383 | 0.600671 |
jesbarlow/CP1404_practicals | refs/heads/master | import random
def main():
quick_picks = int(input("How many quick picks? "))
print_quickpicks(quick_picks)
def print_quickpicks(quick_picks):
for num in range(quick_picks):
NUMBERS = [random.randrange(1, 46) for i in range(0, 6)]
NUMBERS.sort()
number_line = ['%.2d' % number for ... | Python | 16 | 22.4375 | 64 | /prac_4/quickpick_lottery_generator.py | 0.619048 | 0.603175 |
jesbarlow/CP1404_practicals | refs/heads/master | """
CP1404/CP5632 - Practical
Answer the following questions:
1. When will a ValueError occur?
- value errors occur when the input os anything other than a number(including negative numbers),for example - the
letter a
2. When will a ZeroDivisionError occur?
- this will occur whenever the user input... | Python | 23 | 37.913044 | 120 | /prac_2/exceptions.py | 0.724832 | 0.710291 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.