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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
31264b9c4bd36cdd160ecbfcd14dcd405f363147 | Python | synsrv/src_net-anaylsis | /methods/process_turnover.py | UTF-8 | 8,396 | 3 | 3 | [] | no_license |
from brian2.units import second
import numpy as np
def extract_lifetimes(turnover_data, N_neuron, initial,
t_cut = 0.*second):
'''
turnover data is assumed to be a numpy.array with
lines consisting of the four entries
gen/prune, t, i, j
where
-- gen/prun... | true |
46718f98bd45b9543c0687158e53ff08a77a117d | Python | HackBMU/hackbmu_beat | /dataSet_generator.py | UTF-8 | 2,443 | 3.046875 | 3 | [] | no_license | import cv2
#just a shortcut
import numpy as np
import sqlite3
#using defualt haarcascade from opencv library (opencv->sources->data->haarcascades)
#calling cascade classifier with file name with file extension
faceDetect = cv2.CascadeClassifier('haarcascade_frontalface_default.xml');
#video capture object to captu... | true |
b005e47ed932e37e1daf504bdde89ba286559b4e | Python | Hammerschmidt/Agenda_CRUD_DB | /DBClasses.py | UTF-8 | 1,265 | 2.59375 | 3 | [
"MIT"
] | permissive | import os
import sys
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
Base = declarative_base()
class Pessoa(Base):
__tablename__ = 'pessoa'
id = Column(Integer, prim... | true |
4beb0fc30858ba4a1b9597ce5ac711dc2cfb4e69 | Python | helunxing/algs | /leetcode/242.有效的字母异位词.py | UTF-8 | 1,283 | 3.5 | 4 | [] | no_license | #
# @lc app=leetcode.cn id=242 lang=python3
#
# [242] 有效的字母异位词
#
# https://leetcode-cn.com/problems/valid-anagram/description/
#
# algorithms
# Easy (51.54%)
# Total Accepted: 25.9K
# Total Submissions: 50.2K
# Testcase Example: '"anagram"\n"nagaram"'
#
# 给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的一个字母异位词。
#
# 示例 1:
#
# 输入:... | true |
969ceff8a4ad048d85ef65dc669e60b2d49557ed | Python | WILLYWZ/C200 | /LabAssignments/Lab2/myFunctions.py | UTF-8 | 1,587 | 3.8125 | 4 | [] | no_license | import math
#
def maxThree(x, y, z):
if x > y and x > z :
return x
elif y > x and y > z:
return y
else:
return z
print(maxThree(1,2,3))
#
def minThree(p1, p2, p3):
if p1 < p2 and p1 < p3:
return p1
elif p2 < p1 and p2 < p3:
return p2
else:
retu... | true |
e5535924f1194d82083ce0a4e662e311f295e8fd | Python | oksmina/hyperskill | /Problems/Creating a pattern for words/main.py | UTF-8 | 124 | 2.890625 | 3 | [] | no_license | from nltk.tokenize import regexp_tokenize
text = input()
pos = int(input())
print(regexp_tokenize((text), r"[A-z]+")[pos])
| true |
e8fbf3403e481953a219fdf77220c1cdb7a2c1d1 | Python | kp54/FtoA | /src/convert.py | UTF-8 | 2,747 | 2.734375 | 3 | [] | no_license | # flacをalacに変換するやつ
import argparse
import copy
from pathlib import Path
from typing import List
import ffmpeg
import taglib
import dirtree
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("src", type=Path, help="source directory")
parser.add_argument("dest"... | true |
d1c14f47d62acf43519f2112c2dc40f303d6541a | Python | elvis2workspace/CustomLibrary | /utils/Selenium/ideone_SimpleHTTPServer.py | UTF-8 | 11,298 | 2.75 | 3 | [] | no_license | """Simple HTTP Server.
This module builds on BaseHTTPServer by implementing the standard GET
and HEAD requests in a fairly straightforward manner.
"""
__version__ = "0.6"
__all__ = ["SimpleHTTPRequestHandler"]
import os
import posixpath
import BaseHTTPServer
import urllib
import cgi
import sys
import shutil
impor... | true |
d927fd08a9f03ce14c52d44f5d1fbdea0d603dd8 | Python | simonlingoogle/KiBRA | /kibra/ktask.py | UTF-8 | 4,962 | 2.546875 | 3 | [
"MIT"
] | permissive | import abc
import asyncio
import logging
import kibra.database as db
class status:
STARTING = 'starting'
RUNNING = 'running'
STOPPED = 'stopped'
STOPPING = 'stopping'
ERRORED = 'errored'
class action:
NONE = 'none'
START = 'start'
STOP = 'stop'
KILL = 'kill'
class Ktask:
_... | true |
40e15fb2f14c79cab3a7abd2173d8cb5421a23c0 | Python | slacknate/libhip | /libhip/__main__.py | UTF-8 | 1,172 | 2.953125 | 3 | [] | no_license | import os
import argparse
from .hip import HIPImage
def hip_to_png(hip_path):
image = HIPImage()
image.load_hip(hip_path)
image.save_png(hip_path.replace(".hip", ".png"))
def png_to_hip(png_path):
image = HIPImage()
image.load_png(png_path)
image.save_hip(png_path.replace(".png", ".hip"))
... | true |
5f3d6ddff01fa4b91977cc7435514d885da6d4cd | Python | frankdsouza55/YouTube-Stream-Links | /app.py | UTF-8 | 1,135 | 2.625 | 3 | [] | no_license | from flask import Flask, render_template, request
import pafy
app = Flask(__name__)
@app.route("/")
@app.route("/home")
def hello():
return render_template('index.html')
@app.route("/results", methods=['POST'])
def showResults():
domains = ['youtube.com', 'youtu.be']
data = {}
validURL = False
... | true |
93a043a4206e0b1872c71917cfc54be3c21b1706 | Python | shirtsgroup/cg_openmm | /examples/evaluating_energies_with_varying_parameters/reevaluating_heat_capacities.py | UTF-8 | 2,172 | 2.609375 | 3 | [
"LicenseRef-scancode-other-permissive",
"MIT"
] | permissive | #!~/anaconda3/bin/python
import os
import pickle
from cg_openmm.parameters.evaluate_energy import *
from cg_openmm.parameters.reweight import get_temperature_list
from cg_openmm.thermo.calc import *
from openmm import unit
# This example demonstrates how to use configurational sampling in combination with ... | true |
8a7414d329ab65946e6e9202687949e61b8de637 | Python | fomightez/gel_image_annotation | /gel_image_annotation.py | UTF-8 | 15,854 | 2.671875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 21 10:22:27 2019
@author: steven
"""
# Import the libraries
# Will probably need to pip install peakutils, pillow, OpenCV and plotly as these don't come as standard
import numpy as np
from scipy import signal
import peakutils
import matplotlib.py... | true |
aaf77e94b6627c4c4aa8808d4ddc98fb01d6a02d | Python | chengchang/algo | /leetcode/lc0001_find_two_sum_idx.py | UTF-8 | 1,007 | 3.421875 | 3 | [] | no_license | # coding: utf-8
# from: https://leetcode-cn.com/problems/two-sum/
# keys: n_sum, idx_cache
from typing import List
# Time: O(n^2), Space: O(1)
def two_sum(nums: List[int],
target: int) -> List[int]:
if not nums:
return []
n = len(nums)
for i in range(n):
for ... | true |
9b357d2ed101c262d5d79495a1f831aaffae6a01 | Python | attamatti/ABSL_OTF_GUI | /tomo-rename.py | UTF-8 | 2,714 | 3.203125 | 3 | [] | no_license | #!/usr/bin/env python
# give tomography files from serialEM reasonable names
import os # for running UNIX commands
import sys # for lots if utilities
import glob # for finding files
vers = '0.2.3' #version number
try:
files = glob.glob... | true |
201daf1b5307297d9b2d8521beb6ab87cd0ad72e | Python | vgrichina/time-uploader | /upload_time.py | UTF-8 | 4,228 | 2.671875 | 3 | [] | no_license | #!/usr/bin/env python
import sys
import csv
import re
import json
import urllib2
import requests
from datetime import datetime
from itertools import *
DATE_FORMAT = "%Y-%m-%d %H:%M:%S +0000"
def parse_time(csvFile):
reader = csv.reader(open(csvFile, "r"), skipinitialspace = True)
i = 0
for row in reader:
... | true |
5239eae5789baed1faef235010a3772acf45ec1d | Python | grayhong/bias-contrastive-learning | /debias/losses/gce.py | UTF-8 | 733 | 2.578125 | 3 | [] | no_license | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class GeneralizedCELoss(nn.Module):
def __init__(self, q=0.7):
super(GeneralizedCELoss, self).__init__()
self.q = q
def forward(self, logits, targets):
p = F.softmax(logits, dim=1)
if np.isn... | true |
9d657bb7ea4eb747cc6cac2c9b38111897e5b0d7 | Python | theseana/ajil | /Term 2/15/0-problem.py | UTF-8 | 268 | 3.765625 | 4 | [] | no_license | name = input("Name: ")
last_name = input("LastName: ")
file = open('name_and_last_name.txt', 'a')
while name != 'end':
txt = f"name: {name}, last_name: {last_name}\n"
file.write(txt)
name = input("Name: ")
last_name = input("LastName: ")
file.close() | true |
e7782749b467723a844ccc8b843cb007a3098322 | Python | TGLuis/LINGI2990-MalwareSandbox | /scripts/get_description.py | UTF-8 | 1,206 | 2.53125 | 3 | [
"MIT"
] | permissive | #!/usr/bin/python3
import pymongo
import types
import json
import sys
PORT=27017
client = pymongo.MongoClient("localhost", PORT)
db = client.cuckoo_db
collection = db.malware_results
if __name__ == "__main__":
if len(sys.argv) < 2:
print("give a name of signature to get description and severity, if '-'... | true |
3957918bb2b4fad429e7d57d330b3516ba02e4ba | Python | asifneyaz/pysparkproject | /flightdata/flight.py | UTF-8 | 593 | 2.59375 | 3 | [] | no_license | from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("flight").master("local[*]").getOrCreate()
flightdata = spark.read.option("inferSchema", True).option("header", True).csv("2015-summary.csv")
flightdata.createOrReplaceTempView("flight_data_view")
sqlway = spark.sql("""SELECT DEST_COUNTRY_NAME, C... | true |
f43dcafbf492f368f660e4727d36968367619506 | Python | kapitsa2811/TranskribusDU | /TranskribusDU/util/CollectionSplitter.py | UTF-8 | 2,785 | 3 | 3 | [
"BSD-3-Clause"
] | permissive | # -*- coding: utf-8 -*-
"""
Utility: split a list of things in n distinct parts, at random
Similar in spirit to sklearn's ShuffleSplit, but empty intersection between parts.
Copyright NAVER(C) 2019 Jean-Luc Meunier
This program is free software: you can redistribute it and/or modify
... | true |
fc4ac8a3a16d408710b91cbc3d4c18ed83223baf | Python | yy0827/Algorithm | /insert_sort.py | UTF-8 | 1,060 | 4.53125 | 5 | [] | no_license | # codinf:utf-8
# 插入即表示将一个新的数据插入到一个有序数组中,并继续保持有序。例如有一个长度为N的无序数组,
# 进行N-1次的插入即能完成排序;第一次,数组第1个数认为是有序的数组,将数组第二个元素插入仅有1个有序的数组中;
# 第二次,数组前两个元素组成有序的数组,将数组第三个元素插入由两个元素构成的有序数组中......
# 第N-1次,数组前N-1个元素组成有序的数组,将数组的第N个元素插入由N-1个元素构成的有序数组中,则完成了整个插入排序。
def insert_sort(nums):
count = len(nums)
for i in range(1, count):
... | true |
5d0354e5f185c8f01354f2ddbc421df6d06bc53b | Python | menghanii/LeetCode | /210706_체육복.py | UTF-8 | 445 | 2.75 | 3 | [] | no_license | def solution(n, lost, reserve):
answer = n - len(lost)
residual = []
while len(reserve):
r = reserve.pop()
if r in lost:
answer += 1
lost.remove(r)
else:
residual.append(r)
for r in residual:
if (r-1) in lost:
answer += 1
... | true |
cad24c919b7810cd1a2b0fa77f2649e057f242f2 | Python | neerajgupta37/cprograms | /Problem_Class_Example.py | UTF-8 | 870 | 3.75 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 22 17:11:57 2020
@author: dell
"""
class User():
def signin(self):
print('logged in')
class Wizard(User):
def __init__(self,name,power):
self.name=name
self.power=power
#
def attack(self):
print(f'Attacking wit... | true |
76152606cacbc0d24f67fbdfc9cab889d64ca2cb | Python | nickfrasco/C200 | /Assignment11/listco.py | UTF-8 | 553 | 3.125 | 3 | [] | no_license | import numpy as np
np.seterr(divide='ignore',invalid='ignore')
#Above statement was used to ignore an error message
#that read "invalid value encountered in true_divide"
Data = [(2,1),(5,2),(7,3),(8,3)]
X = np.zeros((4,2),dtype = int)
Y = np.zeros((4,1),dtype = int)
for r in range(0,len(Data)):
X[r][0] = 1
X... | true |
81672b612003d3368c0e3225ce6357cb059e6873 | Python | mrwtx1618/py_all | /endwith.py | UTF-8 | 4,462 | 2.921875 | 3 | [] | no_license | # -*- coding:UTF-8 -*-
import csv
import os
import xlrd
s = 38.0376719457
l = 15.7912997439
path = os.getcwd() #打印该py文件当前的路径
filenames = os.listdir(path) #该路径下所有的文件名
filenames_list = []
sum1 = 0
positive_sum = 0
negative_sum = 0
for filename in filenames:
if filename.endswith('.xlsx'):
fi... | true |
c5dcec3cc94db4c5eeb7dff80495ed7b38366b86 | Python | GabrielEstevam/icpc_contest_training | /uri/uri_python/ad_hoc/p1836.py | UTF-8 | 532 | 3.3125 | 3 | [] | no_license | import math
for t in range(int(input())):
entry = input().split(' ')
nome = entry[0]
L = int(entry[1])
at = ["HP", "AT", "DF", "SP"]
print("Caso #"+str(t+1)+":", nome, "nivel", L)
for i in range(4):
entry = input().split(' ')
B = int(entry[0])
IV = int(entry[1])
E... | true |
f0d5337040dbc6633cf4cc77dd7edfdc1693665e | Python | sebastianrosenzweig/mirdata | /tests/test_annotations.py | UTF-8 | 7,705 | 2.578125 | 3 | [
"BSD-3-Clause"
] | permissive | import sys
import pytest
import numpy as np
import mirdata
from mirdata import annotations
def test_repr():
class TestAnnotation(annotations.Annotation):
def __init__(self):
self.a = ["a", "b", "c"]
self.b = np.array([[1, 2], [1, 4]])
self._c = "hidden"
test_track... | true |
de5d1a7c8d6d82e93b9a2aff5757b827430ea04a | Python | RKHashmani/QHack2021 | /Open_Hackathon/CIFAR10/tools/eval_stats_plot.py | UTF-8 | 1,044 | 2.890625 | 3 | [] | no_license | import matplotlib.pyplot as plt
import csv
import numpy as np
with open('log_validation.csv', 'r') as f:
reader = csv.reader(f, delimiter=',')
quantum = np.array(list(reader)).astype(float)
with open('log_validation_classic.csv', 'r') as f:
reader = csv.reader(f, delimiter=',')
classical = np.arra... | true |
6bea6baeba093a5bacf531116d87329782569629 | Python | gusfrehse/square-chaos-game | /main.py | UTF-8 | 1,523 | 3.625 | 4 | [] | no_license | #!/usr/bin/env python3
import sys, pygame, random
pygame.init()
size = width, height = 600, 600
white = 255,255,255
black = 0, 0, 0
screen = pygame.display.set_mode(size)
check = 0
# Check for input
if len(sys.argv) == 2: check = int(sys.argv[1])
# Easier to understand
def drawPoint(xandy):
pygame.draw.rect(scre... | true |
017ec7a4a00eccd634fcd1fed64d0d582b90d668 | Python | RenegaDe1288/pythonProject | /lesson_002/00_distance.py | UTF-8 | 1,145 | 3.515625 | 4 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from pprint import pprint
# Есть словарь координат городов
sites = {
'Moscow': (550, 370),
'London': (510, 510),
'Paris': (480, 480),
}
# Составим словарь словарей рас+стояний между ними
# расстояние на координатной сетке - корень из (x1 - x2) ** 2 + (y1 - y2... | true |
fb4780a733260a5d0764c15dfb61c4be8741f3c2 | Python | sherrysun16/ninja_gold | /game_app/views.py | UTF-8 | 2,686 | 2.921875 | 3 | [] | no_license | from django.shortcuts import render, HttpResponse, redirect
from time import strftime, gmtime
import random
# Create your views here.
def setting(request):
request.session['count'] = request.POST['count1']
request.session['gold_win'] = request.POST['gold']
return redirect('/index')
def index(r... | true |
1fc1bd9235c823bff156a610db34f3d2b02788db | Python | syed0019/Unscramble_Computer_Science_Problems | /Task2.py | UTF-8 | 1,197 | 3.953125 | 4 | [] | no_license | """
Read file into texts and calls.
It's ok if you don't understand how to read files
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 2: Which telephone number spent the ... | true |
c66044f64b7cfd6813ec2318bc41c3efd3d26ad6 | Python | huikinglam02/Guided_Project_Working_with_a_SQLite_database | /query.py | UTF-8 | 217 | 2.890625 | 3 | [] | no_license | # Reading the 10 countries with the least population
import sqlite3
conn = sqlite3.connect('factbook.db')
c = conn.cursor()
c.execute('SELECT * FROM facts order by population asc limit 10;')
print(c.fetchall());
| true |
2431009edf2537b66a9d6ada78c4322ad62538a4 | Python | daniel-reich/turbo-robot | /XYvyirQMkmPHGLaZi_6.py | UTF-8 | 1,414 | 4.40625 | 4 | [] | no_license | """
Given a number, return a string of the word `"Boom"`, which varies in the
following ways:
* The string should include `n` number of "o"s, unless `n` is below 2 (in that case, return `"boom"`).
* If `n` is _evenly divisible by 2_ , add an exclamation mark to the end.
* If `n` is _evenly divisible by 5_ , r... | true |
bafdfe818de63f3af4b8d605bab6f63f6eb0825a | Python | pzhao28/physics_based_RL_for_CR | /Enviorenment5/Enviorenment5.py | UTF-8 | 7,787 | 2.890625 | 3 | [] | no_license | import pygame
import numpy as np
import random as rd
from math import sqrt, acos, asin, atan2, sin, cos
import torch
pygame.init()
max_x = 80
max_y = 80
own_x = max_x/2
#own_y = max_y/2
own_y = max_y/2
#scale = max_x / 160
scale = 1
time_step = 1
win = pygame.display.set_mode((max_x, max_y),depth=8)
pygame.display.se... | true |
5ae1fa02526edab3fdeb50ec8150d69e034d9df0 | Python | dany2501/escommerce | /dto/Payment.py | UTF-8 | 779 | 2.625 | 3 | [] | no_license | from flask import Flask
class Payment(dict):
def __init__(self,id,name,number,digits,year,month,cvv):
self.__id = id
self.__name = name
self.__number = number
self.__digits = digits
self.__year = year
self.__month = month
self.__cvv = cvv
dict.__init... | true |
c7226433b6a3bb5a8cc7f9f2064d14483bffdb8a | Python | f0rk/project-euler | /python/problem7.py | UTF-8 | 829 | 3.4375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/python
#solution: 104743
import math
def is_prime(n):
if n < 2:
return False
if n == 2:
return True
if n < 10:
values = { \
2: True, \
3: True, \
4: False, \
5: True, \
6: False, \
7: True, \
... | true |
80cdc337061fe2eb20ca0093ef15596aa71d9f51 | Python | jamco88/myflix | /app/models.py | UTF-8 | 1,223 | 2.515625 | 3 | [] | no_license | from datetime import datetime
from app import db, login# mdb
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True, unique=True)
... | true |
68aa7927a1f93b77766fed82bfa3353f9405688e | Python | AdamZhouSE/pythonHomework | /Code/CodeRecords/2389/60737/262431.py | UTF-8 | 348 | 3.359375 | 3 | [] | no_license | t = int(input())
while t:
N = int(input())
nums = [int(n) for n in input().split( )]
m = N // 2
for i in range(m):
temp = nums[2*i]
nums[2*i] = nums[2*i+1]
nums[2*i+1] = temp
for j in range(N):
print(nums[j], end="")
if j != N-1:
print(' ', end="")... | true |
8f414888c44ba3964d416dec8e6d17b27425b92a | Python | bluegenes/fasta_tools | /fasta_to_bed.py | UTF-8 | 799 | 2.640625 | 3 | [] | no_license | #Tessa Pierce
# 2.8.13
#Input - fasta file
#Output - basic BED file ( chr_name + '\t' + start_pos + '\t' + end_pos )
import sys, re
in_fasta = open(sys.argv[1], 'r')
out_BED = open(sys.argv[2], 'w')
fasta_lines = in_fasta.readlines()
#info = re.compile('^>(\S*)') #cegma
info = re.compile('^>(\S*) len=(\d*)') #t... | true |
0dd55f23aa474f9481b361f9080d0c3188f43036 | Python | yzl232/code_training | /mianJing111111/Google/Write a class DominoChecker that has a method called addBox(int[]) that takes a box of five dominoes, described as a list of 10 integers (explained after), adds it to a collection,.py | UTF-8 | 1,343 | 3.890625 | 4 | [] | no_license | # encoding=utf-8
'''
Write a class DominoChecker that has a method called addBox(int[]) that takes a box of five dominoes, described as a list of 10 integers (explained after), adds it to a collection, and returns true if a box with the same dominoes was already in the collection and false otherwise. A box of dominoes ... | true |
2be9dc16b3ee67a3887516cdd4f663d403a875b2 | Python | simarchhabra/NBA-Teammate-Chain | /nbateammatechain/players/build_teammates.py | UTF-8 | 9,900 | 2.78125 | 3 | [] | no_license | import player, build_players
import time
from ..utils import serialize, soup_opt, convert_date
# years we care about
B_YEAR = 1984
E_YEAR = 2018
#player_dict = serialize.load_pickle('../raw_files/player_dict.pickle')
# create player dictionary (w/o teammates)
player_dict = build_players.create_player_dict()
# base ur... | true |
2cea15bda37b4374589addab3c9ef2c4f1b994ec | Python | joshisameer343/3-Digit-Number-Guessing-Game | /Number guess.py | UTF-8 | 1,092 | 3.734375 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 30 17:23:33 2020
@author: Shanu
"""
from random import randint
num=str(randint(100, 999))
print("Welcome to the 3 digit number guessing game \nType \"quit\" to forfeit the game ")
def guess():
usr=str(input("Input your guess\n"))
if(len(usr)<3):
... | true |
67822fba3b5c72ff6eb2113763821d5d08dfed98 | Python | aquarioos/dvik-logging | /dvik_logging/dvik_logging.py | UTF-8 | 8,271 | 3.0625 | 3 | [
"MIT"
] | permissive | import logging
_LINE_FORMATS = {
'classic': '%(asctime)s %(levelname)-8s [%(name)s] %(message)s',
'short': '%(asctime)s %(levelname) [%(name)s] %(message)s',
'no_time': '%(levelname)-8s [%(name)s] %(message)s',
}
_DT_FORMATS = {
'classic': '%Y-%m-%d %H:%M:%S',
'time_first': '%H:%M:%S %Y-%m-%d',
... | true |
48b9df273d75b90c9f492b678c27dbad6a8bf10c | Python | devopstasks/PythonScripting | /12-datetime module to work with dates and times/55-Introduction-to-datetime-module.py | UTF-8 | 1,279 | 3.515625 | 4 | [] | no_license | '''
===============================
datetime module
=> It is a built-in module and used to work with dates and times
date
time
datetime
=> import datetime
dir(datetime)
dir(datetime.datetime)
===============================
'''
'''
import datetime
import pytz
req_timez=pytz.timezone('Asia/Kolkata')
print... | true |
7026e39b3f64a0439ad353e53dcc4217107e05ce | Python | flying-tiger/aero_util | /test/test_attitude.py | UTF-8 | 3,271 | 2.96875 | 3 | [
"MIT"
] | permissive | import numpy as np
import unittest
from aero_util.attitude import *
rad = np.radians
deg = np.degrees
def all_close(test_case, array1, array2):
test_case.assertTrue(np.all(np.isclose(array1, array2)))
def all_true(test_case, logical_array):
test_case.assertTrue(np.all(logical_array))
class AttitudeTestCase(... | true |
62e0388e9fed773f8dce07ff4cdace761b37a58f | Python | margo-corsetti/Intro-to-Programming---Adventure-Game | /adventure_game_refractured_Corsetti.py | UTF-8 | 4,547 | 4.125 | 4 | [] | no_license | # Udacity Adventure Game Project
# Margo Corsetti
# 23 May 2021
import time
import random
items = []
creature_list = ["wicked fairie", "troll", "dragon"]
def print_pause(string):
print(string)
time.sleep(2)
def intro(items):
items.clear()
creature = random.choice(creature_list)
... | true |
e5f9b83111a55ab589aec60f6adfccd3c035f5d4 | Python | catzoo/image-bot | /cog/mod_config.py | UTF-8 | 2,878 | 2.578125 | 3 | [
"MIT"
] | permissive | import discord
from discord.ext import commands
import asqlite
import env_config
from checks import Checks
class Moderation(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.checks = None
self.ready = False
@commands.Cog.listener()
async def on_ready(self):
if no... | true |
1dcf8636c486851b49b1ecb78157633ae74b555f | Python | feiwl/Coding | /code/test-39.py | UTF-8 | 3,154 | 2.59375 | 3 | [] | no_license | #!/usr/bin/env python3
import argparse
import os
import pandas as pd
import pymysql
import warnings
warnings.filterwarnings("ignore", category=pymysql.Warning)
class _DbConnector(object):
def __init__(self, host, user, password, database):
self._conn = pymysql.connect(host, user, password, database)
... | true |
56ec62e324916ff038294128d3516a397de66df4 | Python | sraaphorst/daily-coding-problem | /dcp_py/day175/day175.py | UTF-8 | 3,938 | 4.21875 | 4 | [
"MIT"
] | permissive | #!/usr/bin/env python3
# day175.py
# By Sebastian Raaphorst, 2019.
from typing import Callable, Dict, List, Tuple
from random import random
# Type aliases.
State = str
Probability = float
Transition = Tuple[State, State, Probability]
StateProbability = Tuple[State, Probability]
Markov = List[Transition]
MarkovChain =... | true |
1753493cf4a1e7c11d8373e48a90597617e6f596 | Python | JLBicho/VisionPorComputador | /identExpresiones/cargarModeloYUsar.py | UTF-8 | 1,422 | 3.375 | 3 | [] | no_license | """
Este script sirve para cargar un modelo previamente entrenado
y comprobar sus resultados con otras imagenes
"""
from sklearn.model_selection import train_test_split
from sklearn import linear_model
from sklearn import ensemble
from sklearn import neighbors
import numpy as np
import pandas as pd
import pickle
im... | true |
66f9c12775e7d575df554c8cca984f61f9acac4c | Python | ClarkResearchGroup/qosy | /qosy/transformation.py | UTF-8 | 23,241 | 3.53125 | 4 | [
"MIT"
] | permissive | #!/usr/bin/env python
"""
This module includes a Transformation object that represents
a discrete transformation, such as charge-conjugation or a
space group symmetry, and a method for computing the effect
of a Transformation on a Basis of OperatorStrings.
"""
import warnings
import numpy as np
import numpy.linalg as ... | true |
5091db6c0f896d894173bf78f9eda84223693419 | Python | joshlaplante/project-euler-problems | /9 special pythagorean triplet.py | UTF-8 | 2,067 | 4.65625 | 5 | [] | no_license | #A Pythagorean triplet is a set of three natural numbers,
#a < b < c, for which,
#a^2 + b^2 = c^2
#For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
#There exists exactly one Pythagorean triplet for which a + b + c = 1000.
#Find the product abc.
def main():
limit = 1000
for i in range(1,limit):
for j i... | true |
8c9fc74497994e712c0dc4b69c3b376615e1153a | Python | feldmatias/TeoriaDeAlgoritmos-AlgoritmoDeJohnson | /main.py | UTF-8 | 410 | 2.75 | 3 | [] | no_license | import sys
from initialization import create_graph
from johnson_algorithm import johnson_algorithm
from result import calculate_result
if __name__ == '__main__':
if len(sys.argv) <= 1:
print("Please enter file name.")
print("Usage: `python main.py <filename>`")
else:
vertices = create_... | true |
5d264102d6d69caac5649d4d664e55eef3906caa | Python | Khuf2/python-tutoring-modules | /Homework7/hw7_submission.py | UTF-8 | 1,408 | 4.21875 | 4 | [] | no_license | # Homework 7 - 6/25/20
# Lists, String Building, String Slicing, For Loop Review
'''
# blitz(): basic string-building from a list
Given a list of names, return a greeting message to each name in the form of a string.
If addressing more than one person, add an and to your final welcome, and adjust capitalization accord... | true |
905d9279dd7c3b12cf31370704716d685618faf5 | Python | OnestoneW/UZH | /week6/exercise_4.py | UTF-8 | 1,599 | 3.40625 | 3 | [] | no_license | import numpy as np
import pylab as plb
def lcg(numbers, a, m, x_0):
numbers_out = [x_0]
i = 0
for x in range(numbers):
numbers_out.append(((a*numbers_out[i])%m)/m)
i += 1
return np.array(numbers_out)
if __name__ == "__main__":
first = lcg(10000, 2, 3, 1)
second = lcg(10000, 2**... | true |
6a12baab9ca39be883d66f3560cf06afaee00fad | Python | root2pk/Game-Of-Life | /game_of_life.py | UTF-8 | 3,970 | 3.359375 | 3 | [] | no_license | """
Program to simulate game of life for an lx*ly lattice
Takes in N, which is the side length of the square lattice
4 initial conditions are possible
1) Random
2) Beehive
3) Glider
4) Blinker
Plots Average active sites as a function of time
Plots centre of mass position for glider and calculates glider s... | true |
1271aaa754b6082758dd5a08eeba02ce256f0595 | Python | Pr1yanshu/apitest | /test_api.py | UTF-8 | 1,219 | 2.84375 | 3 | [] | no_license | import unittest
import requests
class ApiTest(unittest.TestCase):
pass
def testGen(endpoint, params, mode):
if mode == "post":
def check(self):
req = requests.post(base_url + endpoint, params)
self.assertEqual(req.status_code, 200)
return check
else:
def check(self):
target_url = base_url + endpoi... | true |
4e4cb86fc0fa534e086c514df75eff1eb43caaf1 | Python | timothy-e/data-analysis | /graph_data.py | UTF-8 | 3,757 | 2.90625 | 3 | [] | no_license | from read_data import SpotifyReader, Fitbit
import matplotlib.pyplot as plt
import matplotlib
import numpy
from datetime import datetime
def smooth(values, distance):
return smooth2(values, distance, distance)
def smooth2(values, before, after):
return [
sum(values[i-before : i+after+1]) / (before + a... | true |
ecf01c45d1173fef89dd6a8e0ed6cea9d8af7dda | Python | dorisluvizute/BotEmail | /DecryptService.py | UTF-8 | 138 | 2.75 | 3 | [] | no_license | import base64
def decrypt(password):
password = str(base64.b64decode(password))
return password.replace('b', "").replace("'", "") | true |
36a81736db0f60caaf3915bfbe58e5d0f11212e2 | Python | patelkevin/kaggle-competitions | /CancerNet/preprocess.py | UTF-8 | 1,125 | 2.71875 | 3 | [
"MIT"
] | permissive | import os
import dicom
import pandas as pd
import numpy as np
data_dir = '../input/sample_images/'
patients = os.listdir(data_dir)
labels_df = pd.read_csv('../input/stage1_labels.csv', index_col=0)
labels_df.head()
for patient in patients[:1]:
label = labels_df.get_value(patient, 'cancer')
path = data_dir + ... | true |
a1a625c34bd276c1647b3b8116a24735cdf12c23 | Python | SunnyJimmy/algorithms | /graph.py | UTF-8 | 838 | 3.296875 | 3 | [
"MIT"
] | permissive | from collections import deque
graph = {}
graph["you"] = ["alice", "bob", "claire"]
graph["bob"] = ["anuj", "peggy"]
graph["alice"] = ["peggy"]
graph["claire"] = ["thom", "jonny"]
graph["anuj"] = []
graph["peggy"] = []
graph["thom"] = []
graph["jonny"] = []
def person_is_seller(person):
if person[-1] == 'm... | true |
ec5abbe8115b30e96f5d0345d8151e2b39f9a4d9 | Python | OstruszkaAdam/tvorba-vyrezu-z-obrazku | /kopirovat-a-prejmenovat/copy-and-rename-2.py | UTF-8 | 1,865 | 2.796875 | 3 | [] | no_license | import os
import shutil
import uuid
INPUT_DIR = r"H:\MIMIC"
OUTPUT_DIR = r"H:\SLOUCENY-DATASET"
INPUT_DATASET_NAME = "NIHH"
COUNT_OF_COPIED_FILES = 0
# Walk through all files in the directory that contains the files to copy
for root, dirs, files in os.walk(INPUT_DIR):
for filename in files:
# if the fi... | true |
253ae3aa5d22d86e605770390140299644e4c480 | Python | ArunRamachandran/ThinkPython-Solutions | /Chapter6/6-2.py | UTF-8 | 199 | 2.984375 | 3 | [] | no_license |
def len_hyp(x,y):
#return 0.0 # to chcek whether the fn is properly wrkng or not
sq = x ** 2 + y ** 2
#return sq
import math
result = math.sqrt(sq)
return result
len = len_hyp(3,4)
print len
| true |
bccb2e5f526a44d0c7d4a1ae3d552160e682261d | Python | Rain0193/WebInterfaceTest | /utils/interface.py | UTF-8 | 8,681 | 2.65625 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import json
import time
from libs import send_mail
# 设置接口请求最大时长
TIMEOUT = 5
# 设置不同用例间隔
TIME_INTERVAL = 3
class InterfaceTest:
def __init__(self, case_list, cookie=None):
self.__case_list = case_list
self.__cookie = cookie
@staticm... | true |
876605ae17fc39c2892a9957d7c4ef6cbdfc8202 | Python | bcgov/RSBC-DataHub-API | /python/writer/tests/test_database.py | UTF-8 | 1,657 | 2.90625 | 3 | [
"Apache-2.0"
] | permissive | import pytest
import python.writer.database as database
single_row = [
[
{
"table": "gis.geolocations",
"columns": [
"business_program",
"business_type",
"business_id",
],
"values": [
"ETK",
... | true |
9901134f78efb58bbf545d8db3cbafd9024c8917 | Python | bward/aoc-2020 | /day10.py | UTF-8 | 626 | 3.015625 | 3 | [] | no_license | from functools import lru_cache
with open("input/day10.txt") as puzzle_input:
joltages = sorted([int(line) for line in puzzle_input.readlines()])
end = max(joltages) + 3
def part_1():
ones = 0
threes = 0
cur = 0
for j in joltages:
if j - cur == 1:
ones += 1
elif j... | true |
481997907a02a3d7a77956a15f8ebdc649084acc | Python | danbi2990/python_practice | /tutorial_bodenseo/ch38_oop_multiple_inheritance/act7_super3.py | UTF-8 | 317 | 3.03125 | 3 | [] | no_license | class A:
def m(self):
print("m of A called")
class B(A):
def m(self):
print("m of B called")
A.m(self)
class C(A):
def m(self):
print("m of C called")
A.m(self)
class D(B, C):
def m(self):
print("m of D called")
B.m(self)
C.m(self) | true |
a98a86bcd0ef7e7045f2efe18ffc2b9b42764eed | Python | Livcrst/PE | /Source/Q4.py | UTF-8 | 1,092 | 3.8125 | 4 | [] | no_license | import matplotlib.pyplot as plt #para plotar
import pandas as pd #Manipular os dados
arquivo = open('male_female_counts.txt')
def tratarDados(dados):
#Percorrendo para salvar os dados do arquivo para salvar em listas e limpar o formato txt
TratarDados = []
for i in dados:
dado = i.rstrip()
... | true |
8cd59ec2525b24c293eb80c706ddace21b0e8c37 | Python | SleepNM/django_books_api | /src/api/models.py | UTF-8 | 584 | 2.546875 | 3 | [
"MIT"
] | permissive | from django.db import models
import os
import uuid
def book_image_file_path(instance, filename):
"""
Generate a file path and unique name for new book image
"""
ext = filename.split(".")[-1]
filename = f"{uuid.uuid4()}.{ext}"
return os.path.join("uploads/book/", filename)
class Book(models.... | true |
87b877ad9bbb8f5aa154985f486a58312f6c2ea4 | Python | hoiqz/Next_Gen_pipeline_python | /scripts/find_control.py | UTF-8 | 2,045 | 2.640625 | 3 | [] | no_license | import re
import sys
infile=sys.argv[1]
infile2=sys.argv[2]
case=open(infile,"r")
case_control=open("case_control_pair.tsv","w")
alreadychose=[]
def ethnicity_code(eth):
if eth =='1':
return 'Chinese'
elif eth =='2':
return 'Malay'
elif eth =='3':
return 'Indian'
else:
r... | true |
6c28c66e299904bd9679977551e407068d618df5 | Python | oxullo/projecteuler | /p022.py | UTF-8 | 542 | 3.1875 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def avalue(ch):
assert isinstance(ch, str) and len(ch) == 1
return ord(ch) - 64
def name_score(name):
return sum([avalue(ch) for ch in name])
if __name__ == '__main__':
f = open('p022_names.txt')
snames = f.read()
f.close()
snames = '[%s]' % s... | true |
c591cda7ea8eb8d2a8dad89221e4280e8de768c9 | Python | sampreethamithkumar/game-of-guess-the-number | /jd_task1.py | UTF-8 | 677 | 4.0625 | 4 | [] | no_license | import random
game = " "
while game == " ":
game = int(input("Enter the number of games you wanna play "))
for g in range (0, game):
number = random.randint(0,25)
attempt = 0
while True:
guess = int(input("guess the number "))
if guess > number:
... | true |
6ae1263ebeb103418cc6dcfd1c75270eb7ff4a85 | Python | SHCHwei/Python | /thinterTest.py | UTF-8 | 638 | 3.25 | 3 | [] | no_license | import tkinter as tk
#from tkinter import ttk
#from tkinter.messagebox import showinfo
rootWindow = tk.Tk()
rootWindow.geometry('860x860')
top_frame = tk.Frame(rootWindow)
# 將元件分為 top/bottom 兩群並加入主視窗
topTxt = tk.Label(top_frame,text='請依照下方指示輸入數值',font=('Arial',24))
topTxt.pack()
top_frame.pack()
bottom_frame = tk.... | true |
92499c84d52bbdd5df524383fb3ba23661eff141 | Python | hybridNeo/Compiler-design | /hello/pap_pgms/2_fn_return.py | UTF-8 | 727 | 3.21875 | 3 | [] | no_license | # return mechanism
# no default return mechanism
def f1() :
1729
res = f1()
print(res, type(res)) # None of NoneType
def f2() :
return 1729
res = f2()
print(res, type(res)) # 1729 int
# what can the fn return ? anything in python
def f3() :
return [1, 2, 3, 4]
res = f3()
print(res, type(res)) #
# single paramete... | true |
e4eb3a2a7e4c03abab142bde59213c1b952591d4 | Python | oleksa-oleksa/Python | /Machine_Learning/Python_for_MachineLearning_TU_Berlin_WS1920/exam_preparation_plotting.py | UTF-8 | 1,019 | 3.15625 | 3 | [] | no_license | import numpy as np
from matplotlib import pyplot as plt
mu_G, sigma_G = -1, 1 # mean and standard deviation
G = np.random.normal(mu_G, sigma_G, 1000)
mu_G = np.mean(G) # compute mean with numpy (make no sense, but it is a task)
mu_K, sigma_K = 1, 1
np.random.seed(42)
K = np.random.normal(mu_K, sigma_K, 1000)
# Creat... | true |
28dc1f1c988013d05bc496c003b23ed3519a9805 | Python | DavidGau/digit_recognition_gui | /Neural Network GUI/Graphique.py | UTF-8 | 3,425 | 2.828125 | 3 | [] | no_license | import pylab as plt
import numpy as np
class Graphique:
def __init__(self,fig,img):
self.ax1 = fig.add_subplot(211)
self.ax1.axis("off")
fig.set_figheight(10)
fig.set_figwidth(10)
self.pixels = np.array([img], dtype='float')
self.pixels = self.pixels.reshape((28, 28)... | true |
2b3e96c16d1bd08217782f5329ee4f30ddd53d6c | Python | SINHOLEE/PJT | /PJT_02/movie_image.py | UTF-8 | 787 | 3.25 | 3 | [] | no_license | import requests
import csv
with open('movie_naver.csv', 'r', newline='', encoding='utf-8') as f:
reader = csv.DictReader(f)
movive_url = {row['movieCd'] : row['imgurl'] for row in reader}
for key, value in movive_url.items():
print(key, value)
try:
img_url = value
response = requests... | true |
aabe12e50808755db18db60a609b8d514e9be1b0 | Python | kapilbindal/Movie-Review-Analysis | /clearData.py | UTF-8 | 537 | 2.8125 | 3 | [] | no_license | from nltk.tokenize import RegexpTokenizer
from nltk.stem.porter import PorterStemmer
from nltk.corpus import stopwords
tokenizer = RegexpTokenizer(r'\w+');
stpWrd = set(stopwords.words('english'))
ps = PorterStemmer()
def getCleanReview(review):
review = review.lower();
review = review.replace("<br/><br/>"," ")
to... | true |
3e322e7cfd1f6c6e0f183744140e8b078ce1d4df | Python | jizefeng0810/leetcode | /数据结构/数组/1011-在 D 天内送达包裹的能力.py | UTF-8 | 1,334 | 3.6875 | 4 | [] | no_license | class Solution:
"""
传送带上的包裹必须在 D 天内从一个港口运送到另一个港口。
传送带上的第 i 个包裹的重量为 weights[i]。每一天,我们都会按给出重量的顺序往传送带上装载包裹。我们装载的重量不会超过船的最大运载重量。
返回能在 D 天内将传送带上的所有包裹送达的船的最低运载能力。
"""
def shipWithinDays(self, weights, D):
left, right = max(weights), sum(weights)+1
while left < right:
mid = ... | true |
63ed6787242109d54ae7fbb719e74096d602dbf5 | Python | willkg/douglas | /douglas/plugins/rst_parser.py | UTF-8 | 3,965 | 2.765625 | 3 | [
"MIT"
] | permissive | """
Summary
=======
A reStructuredText entry formatter for douglas. reStructuredText is
part of the docutils project (http://docutils.sourceforge.net/). To
use, you need a *recent* version of docutils. A development snapshot
(http://docutils.sourceforge.net/#development-snapshots) will work
fine.
Install
=======
... | true |
849a337ba4145a3565e44f18c6a6d4663b504e82 | Python | brad2205229/python20210713_brad | /day02/Conversion.py | UTF-8 | 483 | 3.796875 | 4 | [] | no_license | import math as m
# 資料轉換
chinese = "90"
math = "80"
english = "100"
sum = chinese + math + english
print("sum=", sum) # 「+」號對字串而言是連接符號
print(type(chinese), type(math), type(english))
sum2 = int(chinese) + int(math) + int(english)
print("sum2=", sum2)
# 資料的轉換(Lab)
# 球 bmi 取道小數點2位
h, w = "180.5", "85"
print(type(h), type... | true |
b582afb2db971558684949e27035ec1129a2c647 | Python | meozz2109/codewars | /Python/5 Kyu/The Hashtag Generator.py | UTF-8 | 120 | 2.90625 | 3 | [] | no_license | def generate_hashtag(s):
re = "#"+s.title().replace(" ", "")
if s=="" or len(re)>140: return False
return re | true |
af0ddd0993a5f93f4b8f7971de8740fa6d92c4d2 | Python | antontomusiak/TopCoder | /srm178/simple_calculator.py | UTF-8 | 326 | 3.09375 | 3 | [] | no_license | class SimpleCalculator:
def calculate(self, input):
ops = ['-', '+', '/', '*']
op = ''
nums = []
num = ''
for i in range(len(input)):
if input[i] in ops:
op = input[i]
nums.append(int(num))
num = ''
else: num += input[i]
nums.append(int(num))
return eval(str(nums[0]) + op + str(num... | true |
a0ca39ad7c0fe4bfdd4b70b3bd5ecefabac33da5 | Python | morristech/PytPro | /Encryption-Decryption-ManInTheMiddle/Files/Encryption.py | UTF-8 | 5,011 | 3.296875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 26 21:02:29 2018
@author: Aayush
Python Project on
Encryption, Decryption and Man-In-The-Middle attack implementation
submitted by Aayush Garg aayushgarg.bu@gmail.com
"""
# Main.py is the starting point for the entire project
from KeyGeneration import KeyGenerati... | true |
ca05205a355c941b4cc2799e7e8ca90e053a5574 | Python | daniel-reich/ubiquitous-fiesta | /pzXrBSiQdMqvRWazp_20.py | UTF-8 | 133 | 2.75 | 3 | [] | no_license |
def score_calculator(easy, med, hard):
return "invalid" if len([1 for i in [easy,med,hard] if i<0])>0 else easy*5+med*10+hard*20
| true |
30895056376a4c830456f86ed9b2cde353949ba7 | Python | Transcendence-ML-Python/airbnb-ml-regression-python | /airbnb.py | UTF-8 | 1,637 | 2.84375 | 3 | [] | no_license | import pandas as pd
import streamlit as st
import seaborn as sns
import models
from sklearn.model_selection import train_test_split
def airbnb_regression_prep():
airbnb_data = pd.read_csv('AB_NYC_2019.csv')
raw_data = airbnb_data
# sns.catplot(x="room_type", y="price", data=raw_data)
# st.pyplot()
... | true |
8c8f126044a6b100f26958a875ae2cc1b222dc2e | Python | Shashi-Chaurasia/Python_Code_Tutorials | /Calculator/Inheritance/11_pr_04_complex.py | UTF-8 | 593 | 3.78125 | 4 | [] | no_license | class Complex:
def __init__(self , r , i) -> None:
self.real = r
self.imaginary = i
def __add__(self , c):
return Complex(self.real + c.real , self.imaginary + c.imaginary)
def __mul__(self ,c):
mul_real = (self.real*c.real ) - (self.imaginary * c.imaginary)
... | true |
988c812bb01545bd114394f00929d5b296e25fa3 | Python | PetrovNikA/Python_4 | /lesson_4_task_4.py | UTF-8 | 769 | 3.890625 | 4 | [] | no_license | # Задание 4.
# Представлен список чисел. Определите элементы списка, не имеющие повторений.
# Сформируйте итоговый массив чисел, соответствующих требованию. Элементы выведите в порядке их следования
# в исходном списке. Для выполнения задания обязательно используйте генератор.
# Пример исходного списка: [2, 2, 2, 7... | true |
edfa4fcb12bf893fcf1472d01c8e3885b26922dc | Python | superjodash/advent2019 | /Day06/Part01/main.py | UTF-8 | 1,486 | 3.140625 | 3 | [] | no_license | import sys
from anytree import Node, RenderTree, AsciiStyle, PostOrderIter
def main():
runFile("Day06/map.txt")
# runFile("Day06/Part01/sample_42.txt")
def runFile(filename):
program = load_file(filename)
tree = create_tree(program)
#renderTreeToFile(filename, tree)
nodes = countNodes(tree)
... | true |
c50c33f1b05d31e47a0e6c1605a29f0450ea52b5 | Python | Immortalv5/Attendance-Using-Face-Recognition | /Video_Capture.py | UTF-8 | 5,612 | 2.65625 | 3 | [] | no_license | import face_recognition
import os
import cv2
import matplotlib.image as mpimg
import math
import pickle
from sklearn import neighbors
from face_recognition.face_recognition_cli import image_files_in_folder
from Modules.Capture import FPS
from Modules.Capture import WebcamVideoStream
def Train(train_dir, model_save_pat... | true |
378ec45184421c51d1d2c8c91f4f5b27413197da | Python | knesto/Synthetic-Datasets-Spatio-Textual-Objects--with-Zipf-distribution | /generate_ synthetic_datasets_zipf.py | UTF-8 | 5,226 | 2.578125 | 3 | [] | no_license | #from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import numpy as np
import random
import math
alpha=1
x = -1
m_bFirst = True #// Static first time flag
c=0 #Normalization constant
def uniform_dataset(words):
size = 12000000 # size of records
x=np.random.uniform(30.027... | true |
b66cb06ceebcd3bd7f8ab9b4ca4c277e2b37097e | Python | zz112107117/NER-Chinese | /utils.py | UTF-8 | 3,693 | 3 | 3 | [] | no_license | # 预测时用于结果输出
def format_result(positions, text, tag):
entities = []
for position in positions:
begin, end = position # 实体的起点和终点
# 记录相关信息
entities.append({"begin": begin,
"end": end,
"content": text[begin: end + 1],
... | true |
658658e53dd2fa4683c38c9cdc22312242d3b15d | Python | mtaziz/Compadre | /digitalocean/app/mod_crawler/indexer.py | UTF-8 | 6,302 | 2.859375 | 3 | [] | no_license | """Each kind of item uses a kind of base spider to get its necessary data.
For example, smartphones and laptops use the AmazonSpider. But Cars might use a different spider,
because there might be a website that catalogs cars better than Amazon. smartphones and laptops also
have reviews on Amazon, so it might be a go... | true |
1cc0f689109bd6eac667cd8aee43cd53406ac097 | Python | ismaproco/image2hashtag | /evaluation.py | UTF-8 | 2,647 | 2.6875 | 3 | [] | no_license | ### Import packages
import torch
import numpy as np
from torch import nn, optim
import torch.nn.functional as F
from torchvision import datasets, transforms, models
from PIL import Image
def process_image(image):
''' Scales, crops, and normalizes a PIL image for a PyTorch model,
returns an Numpy array
... | true |
3e85ac260b9796038c4f755292b6889390cf484a | Python | JordanHaigh/Machine-Intelligence-Assignment1 | /Question1PartB-SebSpirals.py | UTF-8 | 5,308 | 2.921875 | 3 | [] | no_license |
# Import libraries
import tensorflow as tf
from numpy import round
import matplotlib.pyplot as plt
import csv
import math
def read_dataset(filename="spirals/OurSpirals.csv"):
x = []
y = []
spiralNo = -1
spiral1 = True
with open(filename) as file:
reader = csv.reader(file)
for row ... | true |
b0e37b37a10c975e92fb2cac31bfbaa965600b9d | Python | Aekanunpr/tokenize | /main.py | UTF-8 | 569 | 2.65625 | 3 | [] | no_license | import nltk
nltk.download('punkt')
nltk.download('stopwords')
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from fastapi import FastAPI
import uvicorn
app = FastAPI()
@app.get("/cut/{text}")
def read_root(text:str):
... | true |
38e5184a35182a4b73065f6f3b5a1371d5f1e9b9 | Python | apollowesley/Python2019_XXMU | /实例源代码/第03章/3.3.TextProgressBar.py | UTF-8 | 1,327 | 3.765625 | 4 | [] | no_license | #3.3.TextProgressBar.py
import time
scale = 10
#方式1:百分比多行非刷新显示
print("方式1:百分比多行非刷新显示")
print("------执行开始------")
for i in range(scale+1):
c = (i / scale) * 100
print("%{:3.0f}".format(c))
time.sleep(0.1)
print("------执行结束------")
#方式2:百分比单行动态刷新显示
print("方式2:百分比单行动态刷新显示")
print("------执行开始----... | true |
4a7b3b9091ae8dafdc4b0dc32cd4106c3966e1de | Python | umohpyro/Microsoft-AI-challenge | /Starting Kit/Baseline2_DL/text2ctf.py | UTF-8 | 4,534 | 2.8125 | 3 | [
"MIT"
] | permissive | import re
#Initialize Global variables
GloveEmbeddings = {}
max_query_words = 12
max_passage_words = 50
emb_dim = 50
#The following method takes Glove Embedding file and stores all words and their embeddings in a dictionary
def loadEmbeddings(embeddingfile):
global GloveEmbeddings,emb_dim
fe = open(embedding... | true |