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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
361e474450dd7f5683030543f0eaa91f87d64c47 | Python | athuls99/Ciphers | /Ciphers/Day 3/Keyword Sub Cipher/KeyWordSub.py | UTF-8 | 1,453 | 3.46875 | 3 | [] | no_license | def encrypt(message,key,alpha):
string=""
for char in message:
if char in alpha:
string+=char
index_values=[alpha.index(char) for char in string]
return "".join([key[ind] for ind in index_values]).upper()
def decrypt(message,key,alpha):
string=""
for char in message:
... | true |
bf0f4e8ca028466c9776b360b2322d3721e13b1a | Python | rodrigo740/ProjetosECT | /projeto_IIA/Sokoban.py | UTF-8 | 7,944 | 2.921875 | 3 | [
"MIT"
] | permissive | from random import randint
from tree_search import *
from mapa import Map
from consts import Tiles
# Classe que representa o dominio de pesquisa do Sokoban:
# Posição do keeper - self.keeper
# Posição das caixas - self.boxes
# Mapa de jogo - self.mapa
# Coordenadas em volta de um estado - self.dict
# Conjunto das dead... | true |
6b5ba8867281e2fd965ae1c2f16c77f361a2ede2 | Python | bywires/chara | /tests/fixtures.py | UTF-8 | 887 | 3.296875 | 3 | [
"MIT"
] | permissive | def dummy_function(a, b=0, *args, **kwargs):
return a + b + sum(args) + sum(kwargs.values())
class Dummy(object):
dummy_attribute = 123
def dummy_instance_method(self, a, b=0, *args, **kwargs):
assert isinstance(self, Dummy)
return dummy_function(a, b=b, *args, **kwargs)
@classmethod... | true |
d63494926aea6ad545da580ffc1de99ef7737961 | Python | haominhe/Undergraduate | /CIS210 Computer Science I/Projects/p6/test_harness.py | UTF-8 | 1,055 | 3.734375 | 4 | [
"GPL-1.0-or-later",
"MIT"
] | permissive | """
Test harness:
Utility functions for writing test cases in Python programs.
Python has a standard module, unittest, that provides a more
powerful but but more complex testing framework. This module
is designed to be very simple.
Currently test_harness provides just one function, testEQ,
for compa... | true |
4c8937512ef51ccfc775930e7166935dc6bdca4c | Python | smileshy777/practice | /array/medium/Container_With_Most_Water.py | UTF-8 | 849 | 3.328125 | 3 | [] | no_license | '''
Given n non-negative integers a1, a2, ..., an ,
where each represents a point at coordinate (i, ai).
n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0).
Find two lines, which together with x-axis forms a container,
such that the container contains the most water.
'''
cla... | true |
9592b9f39b64c927ff4384f85182835042c301c2 | Python | keerkeerhi/CodeHome | /identify_back/idh/ShellScript/sync_statistical.py | UTF-8 | 1,455 | 2.703125 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# 同步统计信息,包括:当前全部用户数量、当前总积分数
import os
import sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
from django.core.wsgi import get_wsgi_application
os.environ['DJANGO_SETTINGS_MODULE'] = "IDH.settings"
application = get_wsgi_ap... | true |
f9e613faefa88bf54be84bae0fa10841b1759537 | Python | CodingDojoOnline-Nov2016/MattBurnett | /Python/django/LoginAndReg/apps/LoginRegister/models.py | UTF-8 | 2,896 | 2.671875 | 3 | [] | no_license | from __future__ import unicode_literals
from datetime import datetime
from django.db import models
import re, bcrypt
NAME_REGEX = re.compile(r'^[a-zA-Z\-]+$')
EMAIL_REGEX = r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$'
# Create your models here.
class UserManager(models.Manager):
def validate_new_user(self, d... | true |
615f939f729a409211736b55b3ffd54ac0a8e645 | Python | leandroESS/aulas-de-Python | /aula11.py | UTF-8 | 764 | 3.3125 | 3 | [] | no_license | lista = [1, 10]
arquivo = open('teste.txt', 'r')
try:
divisao = 10/1
numero = lista[1]
x = a
print('fechando arquivo')
# arquivo.close() #arquivo não fechar, pois deu antes o problema da variável
except ZeroDivisionError:
print("Não é possível realizar uma divisão por zero") # corresponde a divisão p... | true |
f610a178130b8a33ecb9bde2ca25446063e55937 | Python | willnx/vlab_cli | /vlab_cli/subcommands/show/cee.py | UTF-8 | 1,841 | 2.75 | 3 | [] | no_license | # -*- coding: UTF-8 -*-
"""Defines the CLI for displaying information about EMC Common Event Enabler instances"""
import click
from vlab_cli.lib.api import consume_task
from vlab_cli.lib.ascii_output import vm_table_view, columned_table
from vlab_cli.lib.versions import Version
@click.command()
@click.option('-i', '... | true |
67de3f7c0e5ccb16ea0494dd6c85c3e28906aed3 | Python | RizwanAmjad/AI-Labs-Comsats | /Very First Code.py | UTF-8 | 819 | 3.71875 | 4 | [] | no_license | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def main():
my_list = [[1, 8, 10], [20, 30], [40, 50]]
my_list.append([1, 2, 3, 5])
print(my_list)
... | true |
1ffa174b296b305415a601d8f7dee8659bc19d48 | Python | robinklaassen/aoc2020 | /day03/test.py | UTF-8 | 254 | 2.609375 | 3 | [] | no_license | from unittest import TestCase
from day03.solution import _read_input, _count_trees
class Day03TestSuite(TestCase):
def test_count_trees(self):
lines = _read_input('./test_input.txt')
self.assertEqual(7, _count_trees(lines, 3, 1))
| true |
f1c99a2fd485ba2a999e987a93568e5faf7ae9a0 | Python | SkeyLearing/Python3 | /Socket/socket_server.py | UTF-8 | 945 | 3.078125 | 3 | [] | no_license |
import socket
import threading
# 类型与类型所用的协议
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 绑定
server.bind(('0.0.0.0', 8000))
# 监听
server.listen()
def handle_sock(sock, addr):
while True:
data = sock.recv(1024)
print(data.decode("utf8"))
if data.decode("utf8") == "exit":
... | true |
b96ab66ea1b728af4f973b818165e63c5b0d4a5c | Python | chrinide/Clique-Finding-With-Patterns | /core_alg.py | UTF-8 | 21,381 | 3.140625 | 3 | [
"MIT"
] | permissive | import graph_manip
import logging
from collections import *
import sys
## Levels: DEBUG, INFO, WARNING (default), ERROR, CRITICAL
logging.basicConfig(level=logging.WARNING) # set logging level & to console
#logging.basicConfig(filename='outputD.log', level=logging.DEBUG)
#logging.basicConfig(level=logging.DEBUG)
#l... | true |
e375816bb1450694885ff54a10a24acddf7a4e3c | Python | YoonDongHyeon/midterm_study | /shortestwayproblem.py | UTF-8 | 962 | 2.609375 | 3 | [] | no_license | load = {
'O': {'A': 2, 'B': 5, 'C': 4},
'A': {'O': 2, 'B': 2, 'D': 7},
'B': {'O': 5, 'A': 2, 'C':1, 'D': 4, 'E':3},
'C': {'O': 4, 'B': 1, 'E': 4},
'D': {'A': 7, 'B': 4, 'E':1, 'T':5},
'E': {'B': 3, 'D': 1, 'T': 7, 'C' : 4},
'T': {'D': 5, 'E': 7}
}
candidate =[]
x= {
'O': 0,
'A': 0,... | true |
8ae70c19930cab0069e4f2ebf6c0e01cba2823ac | Python | owen-herbert/cp1404practicals | /prac_07/taxi_simulator.py | UTF-8 | 2,160 | 3.859375 | 4 | [] | no_license | """Taxi simulator"""
from prac_06.car import Car
from prac_07.taxi import Taxi
from prac_07.silver_service_taxi import SilverServiceTaxi
MENU = "q)uit, c)hoose taxi, d)rive"
def main():
bill = 0
taxis = [Taxi("Prius", 100), SilverServiceTaxi("Limo", 100, 2),
SilverServiceTaxi("Hummer", 200, 4)]... | true |
a3383362040ab2e2df19ec158e03dd9d98dd4fb8 | Python | MAXPIL0T/WageCaluclator | /main.py | UTF-8 | 2,163 | 3.46875 | 3 | [] | no_license | import tkinter as tk
root = tk.Tk()
root.title("Wage Calculator")
def calculateWage():
hourlyWage = hourlyWageEntry.get()
sundayWage = sundayWageEntry.get()
regHours = regHoursEntry.get()
sunHours = sunHoursEntry.get()
regDollarsPreTax = float(regHours) * float(hourlyWage)
sunDoll... | true |
c72d694ba214881468d73186c6477c3d02280a07 | Python | trevisanj/pokerodds | /pokeroddsapi.py | UTF-8 | 4,216 | 2.6875 | 3 | [] | no_license | import re
from collections import Counter
import itertools
import math
import tabulate
import copy
import time
__all__ = ["CC", "get_cards", "trans", "valhand", "InvalidCardError", "analyze", "binomial_coefficient", "nice_hand"]
SU = "♥♠♣♦"
SUITES = "HSCD" # Hearts, Spades, Clubs, Diamonds
SUD = dict(zip(SUITES, SU)... | true |
024af2c79d02cb575eef3afb1b2c48242813d75f | Python | hictooth/forumvine-pm-grabber | /grabber.py | UTF-8 | 4,871 | 2.5625 | 3 | [] | no_license | import MySQLdb
import forumvine
import traceback
import time
import os
import json
import sys
import subprocess
SAVE_FILE = None
def getMessages(username, password):
if os.path.exists(SAVE_FILE):
with open(SAVE_FILE, "r") as f:
saveData = json.load(f)
currentMessages = saveData['messag... | true |
e4a6530872c05939d2fc4afff1c2e1d7c11502de | Python | pygauthier/junk | /gipo_test.py | UTF-8 | 584 | 2.5625 | 3 | [] | no_license | import RPi.GPIO as GPIO
from time import sleep
relay_pins = [26, 19, 13, 6]
led_pins = [21, 20, 16, 12]
GPIO.setmode(GPIO.BCM)
GPIO.setup(relay_pins, GPIO.OUT)
GPIO.setup(led_pins, GPIO.OUT)
GPIO.output(relay_pins, 1)
GPIO.output(led_pins, 1)
try:
while True:
for pin in led_pins:
... | true |
b5d87b8800c3576e7c8255d1c5ea35940b955ae9 | Python | PrajwalKrishna/Purple-Purse-A-group-expense-manager | /signature_dbms.py | UTF-8 | 3,250 | 2.78125 | 3 | [] | no_license | import sqlite3 as sql
import hashlib
def create_connection(database):
try:
conn = sql.connect(database)
return conn;
except:
print ("Cannot access database")
def hasher(password):
password_en = password.encode()
hashed = hashlib.sha384(password_en)
hash_paso = hashed.hexdig... | true |
8ea5d04d0983d3b6868e8d477bdcad5948a3b393 | Python | ahmed-gharib89/DataCamp_Data_Scientist_with_Python_2020 | /Cluster Analysis in Python/01_Introduction to Clustering/01_Unsupervised learning in real world.py | UTF-8 | 753 | 2.78125 | 3 | [] | no_license | """==================MCQ========================"""
# Unsupervised learning in real world
# Which of the following examples can be solved with unsupervised learning?
# Answer the question
# 50 XP
# Possible Answers
# A list of tweets to be classified based on their sentiment, the data has tweets associated with a posi... | true |
10e8362c3beb50d0dbdead7c4815ca119530e41b | Python | carreirabruno/Tese_BrunoCarreira_Squary-Shappy | /oneDBoxes2Scenario/MDP_Peer_Communication_Decentralized_policy_maker_oneDBoxes2.py | UTF-8 | 22,856 | 2.65625 | 3 | [] | no_license | import numpy as np
from numpy import savetxt
import random
import copy
import math
import pickle
from itertools import *
class State:
def __init__(self, state):
self.state = state
def __eq__(self, other):
return isinstance(other, State)
def __hash__(self):
return hash(str(self.st... | true |
fbd7c1dc1af88b5579b6f9407a09a4062d349857 | Python | htgdokania/opencv | /3.load image using imshow.py | UTF-8 | 337 | 2.6875 | 3 | [] | no_license | import numpy
import cv2
import matplotlib.pyplot as plt
img =cv2.imread('image.jpg',cv2.IMREAD_GRAYSCALE)
#IMREAD_COLOR=1
#IMREAD_UNCHANGED=-1
##cv2.imshow('image',img)
##cv2.waitKey(0)
##cv2.destroyAllWindows()
plt.imshow(img,cmap='gray',interpolation='bicubic')
plt.plot([50,100],[80,100],'c',linewidth... | true |
398f50ba12325754c88d67918a5cfdd8abb18a4b | Python | Elpida99/Credit-Card-Fraud-Neural-Network | /assignment1.py | UTF-8 | 3,082 | 3.0625 | 3 | [] | no_license | """
Elpida Makri - it21735
"""
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import precision_score, recall_score, f1_score, accuracy_score
from sklearn.preprocessing import StandardScaler
from tensorflow import keras
from tensorflow.keras import layers... | true |
6bb341496a7e695ac14da3f87d48fb4b00c16994 | Python | Sebkd/Algorythm | /eleven_task2.py | UTF-8 | 3,437 | 3.96875 | 4 | [] | no_license | """
Урок 8
Задание 2
Закодируйте любую строку из трех слов по алгоритму Хаффмана
"""
import heapq
from collections import Counter
from collections import namedtuple
class Node (namedtuple ("Node", ["left", "right"])):
"""Класс узлов"""
def step(self, code_n, acc):
"""
Функция формирования стр... | true |
82588ec8bcc36735cf8e14aa858636bd8e702af2 | Python | dvishwajith/shortnoteCPP | /languages/python/testing/leetcode/dynamicprogramming/53_maximum_subarray/q53.py | UTF-8 | 2,158 | 3.046875 | 3 | [] | no_license | #!/usr/bin/env python3
from typing import List
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
if len(nums) > 0:
#return self.checksumMemoized(0, len(nums)-1, nums)[0]
return self.checksumOptimum(nums)
else:
return 0
def checksum(sel... | true |
427db077d6ff7509cd433669ecc1b10f1a49ca48 | Python | bariis/leetcode-python | /Top_100_Liked_Questions/234.py | UTF-8 | 964 | 4.0625 | 4 | [
"MIT"
] | permissive | """
234. Palindrome Linked List
@Level: Easy
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
Example 2:
Input: 1->2->2->1
Output: true
Follow up:
Could you do it in O(n) time and O(1) space?
"""
# Definition for singly-linked list.
class ListNode:
def __init__... | true |
c91d269313dc89aa5c24d31dbed00c370a9e4f04 | Python | YoungcsGitHub/PythonHouse | /pyqt5/chapter4/multithread/AutoCloseWindow.py | UTF-8 | 747 | 2.71875 | 3 | [] | no_license | # -*- coding: utf-8 -*-#
#-------------------------------------------------------------------------------
# Name: AutoCloseWindow
# Description:
# Author: Dell
# Date: 2019/10/21
#-------------------------------------------------------------------------------
'''
让程序定时关闭
QTimer.singleShot
'... | true |
41f2b4537ab6beea02393f8050d98e37526dd69c | Python | handleart/projecteuler | /solutions/projecteuler-p36.py | UTF-8 | 1,037 | 3.21875 | 3 | [] | no_license | #Project Euler, Problem 36
#Ardeshir Mostofi
#9/18/2014
gNums = {}
import time
def base10to2base(n):
j = ''
i = 0
if n == 0:
return '0'
while n > 0:
if n % 2 == 0:
j = '0' + j
elif n % 2 == 1:
j = '1' + j
n = n / 2
return j
def calcBase2nums(maxNum):
F = {}
F[0] = '0'
F[1] = '1'
for i in r... | true |
8e89f9e3338ff46fbed4ecffd0ff91c61a2f8f53 | Python | yin1026/SpiderProject | /baidutiebaSpider/baidutiebaSpider.py | UTF-8 | 2,683 | 3.015625 | 3 | [] | no_license | # 贴吧爬虫
# '生活大爆炸'
import requests
from bs4 import BeautifulSoup
import time
import sys
def getHTMLText(url) :
try :
r = requests.get(url,timeout = 30)
r.raise_for_status()
# r.encoding = r.apparent_encoding
r.encoding = 'utf-8'
return r.text
except:
return ''
def parserHTML(html, ulist, autor, recordTim... | true |
3bf5e2640f950fe74f01571d8aa47e610e4c8d30 | Python | hoangvh1/Social-Analytics-hw | /SocialAnalytics_Script.py | UTF-8 | 3,845 | 3.203125 | 3 | [] | no_license | # Dependencies
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import json
import tweepy
import time
import seaborn as sns
# Initialize Sentiment Analyzer
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
analyzer = SentimentIntensityAnalyzer()
# Twitter API Keys... | true |
50d2b88b0fc71be8a54eab94c5d40a962f5376d1 | Python | hunterwilkins2/pyLox | /Lox/Interpreter.py | UTF-8 | 10,226 | 2.96875 | 3 | [] | no_license | from Lox.Stmt import StmtVisitor
from Lox.SyntaxTree import ExprVisitor
from Lox.TokenType import TokenType
from Lox.LoxFunction import LoxFunction
from Lox.LoxInstance import LoxInstance
from Lox.LoxCallable import LoxCallable, Clock, Read, Float
from Lox.LoxClass import LoxClass
from Lox.Enviorment import Envi... | true |
20f934c71b96e870477916893874d644ed39306e | Python | bvsbrk/Algos | /src/Codeforces/educational_round_47/B.py | UTF-8 | 293 | 3.1875 | 3 | [] | no_license | if __name__ == '__main__':
s = input().strip()
while True:
co = 0
if '21' in s:
s = s.replace('21', '12')
co += 1
if '10' in s:
s = s.replace('10', '01')
co += 1
if co == 0:
break
print(s)
| true |
58ba2c5ff3a7bae77a8bc23f9fe42ec688fa63d4 | Python | korea3611/practice | /baekjun/num_17298(오큰수).py | UTF-8 | 258 | 3.15625 | 3 | [] | no_license | n = int(input())
data = list(map(int,input().split()))
stack = []
res = [-1] * n
for i in range(n):
while stack and data[stack[-1]] < data[i]:
res[stack[-1]] = data[i]
stack.pop()
stack.append(i)
for i in res:
print(i, end=' ')
| true |
e62f5a0bef27ecce3bafe7b34502f0e8dfb47e04 | Python | sriram-rao/rush | /rush-worker/domain/pipeline.py | UTF-8 | 650 | 2.71875 | 3 | [] | no_license | class Pipeline:
def __init__(self, row: tuple):
self.name = row[0]
self.jobs = [JobDefinition(job_def, self.name) for job_def in row[1]["jobs"]] # list of job definitions
# we will start with pipelines having a single job so that we can handle child jobs later
class JobDefinition:
def... | true |
e24aad16badf6fb867168d655f3a3c7e94f43c45 | Python | recuraki/PythonJunkTest | /atcoder/lib/field2D/cumSum2D.py | UTF-8 | 2,497 | 4.1875 | 4 | [] | no_license | # 2次元累積和 Two-dimensional cumulative sum
"""
maze[h][w]2次元累積和を作成し、
[x0, [y0, (x1), y1)の区間のクエリ
★x0,y0は閉区間, x1,y1は開区間です
load: O(h*w)
query: O(1)
update: 未サポート
"""
class cumSum2D():
mazeSum = []
h, w = 0, 0
def __init__(self):
self.mazeSum = []
def load(self, maze):
self.h, self.w = len(ma... | true |
f0209af43bb78268cad7fbde2f963a9d17929ac4 | Python | percivalchen/bridge | /bridge.py | UTF-8 | 1,769 | 3.53125 | 4 | [] | no_license | """Bridge Simulator"""
###########################################
# Phase 1: Card Deck and Creation of Hands#
###########################################
import collections
from random import choice # Used to randomly deal out cards (akin to shuffling the deck)
Card = collections.namedtuple('Card', ['rank', 'sui... | true |
4c161f9faeba1fe2e298aca7684b572568da8bf8 | Python | sirkelen/python_ppl_test | /br.py | UTF-8 | 1,762 | 3.1875 | 3 | [] | no_license | import pandas as pd
import numpy as np
from bs4 import BeautifulSoup
import re
import sklearn
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
# Loading data
print('Loading and cleaning data... ')
mbti = pd.read_csv('data/mbti_1.csv.gz')
# Cleaning text
def cl... | true |
9bb73f74474c59aba87fbb38f815b6e5c085d5de | Python | guyao/leetcode | /compare-version-numbers.py | UTF-8 | 667 | 3.046875 | 3 | [] | no_license | class Solution(object):
def compareVersion(self, version1, version2):
"""
:type version1: str
:type version2: str
:rtype: int
"""
v1 = version1.split(".")
v2 = version2.split(".")
if len(v1) > len(v2):
v2 += ['0' for _ in range(len(v1) - l... | true |
46fba387a7519f50670c7ae6a010cf50e6af6ef8 | Python | hankhank10/dispatcher | /project/pathfinding_handling.py | UTF-8 | 3,215 | 2.53125 | 3 | [] | no_license | from flask import Blueprint, render_template, redirect, url_for, request, flash, jsonify
from . import db
from . import mapfunctions
from .models import Callout
from .models import Path
from .models import Waypoint
import datetime
pathfinding_handling = Blueprint('pathfinding_handling', __name__)
def create_new_pa... | true |
e20f9b9f286718c10a0f31878ea19267c71cb43a | Python | pavel-perina/sqrt-experiments | /run-all.py | UTF-8 | 299 | 2.53125 | 3 | [] | no_license | #!/usr/bin/python3
import subprocess
table=[("gcc9", "g++-9"),
("gcc10", "g++-10"),
("clang10", "clang++-10"),
("clang12", "clang++-12")]
for row in table:
# print("\033[96mRunning speed test for " + row[0] + ".\033[0m");
subprocess.run(["./sqrt-" + row[0]])
| true |
484f8368fb619d3eef49c8166ef2cb86efca3f4e | Python | vemanand/pythonprograms | /2_takeinput.py | UTF-8 | 170 | 3.96875 | 4 | [] | no_license | ''' input() method is used in python to take input values from the user'''
str = input("Enter your name: ")
print("Hi..."+str.upper()+"!Welcome to the world of Python")
| true |
d6aedb50052525a9dbc07434555ad7c6a6c1d0d6 | Python | Silver-Bullet-1/P_Manga | /manga.py | UTF-8 | 805 | 2.515625 | 3 | [
"Unlicense"
] | permissive | import os
os.system('clear')
import urllib.request
ColorYellow="\033[0;33m"
ColorRed="\033[0;31m"
ColorGreen="\033[0;32m"
ColorPurple="\033[0;35m"
print (ColorYellow+"Silver Bullet")
#os.mkdir('/storage/emulated/0/manga/')
link = "https://3asq.org/wp-content/uploads/WP-manga/data/manga_5ea11671db1b9/5cbed2808e5f2e71... | true |
8ea9d12ae9315a13b736e94131600e7f16678881 | Python | easywaldo/python_basic | /calculator.py | UTF-8 | 579 | 3.96875 | 4 | [] | no_license | class Calculator:
population = 0
def __init__(self, a, b):
self.a = a
self.b = b
Calculator.population += 1
def add(self):
return self.a + self.b
def sub(self):
return self.a - self.b
def mul(self):
return self.a * self.b
def div(self):
... | true |
0d9f820769b8c65e645982d77d6c00755927b75d | Python | ryogoOkura/atcoder | /entrant/abc113/abc113-b.py | UTF-8 | 979 | 3.03125 | 3 | [] | no_license | '''
問題文
ある国で、宮殿を作ることになりました。
この国では、標高がxメートルの地点での平均気温はT−x×0.006度です。
宮殿を建設する地点の候補はN個あり、地点iの標高はHiメートルです。
joisinoお姫様は、これらの中から平均気温がA度に最も近い地点を選んで宮殿を建設するようにあなたに命じました。
度に最も近い地点を選んで宮殿を建設するようにあなたに命じました。
宮殿を建設すべき地点の番号を出力してください。
ただし、解は一意に定まることが保証されます。
制約
1≤N≤1000
0≤T≤50
−60≤A≤T
0≤Hi≤105
入力は全て整数
解は一意に定まる
'''
n=int(input())
t,a=map(... | true |
bcb96a22ad1870446c4f05bc42db0be8392fe945 | Python | RicSegundo/HackerRank | /Solved/CircularArrayRotation.py | UTF-8 | 227 | 3.046875 | 3 | [] | no_license |
n, k, q = 3, 4, 3
arr = [1, 2, 3]
queries = [0, 1, 2]
def circularArrayRotation(arr, k, queries):
return [arr[(i-k) % n] for i in queries]
if __name__ == '__main__':
print(circularArrayRotation(arr, k, queries))
| true |
2e8df5d33a79d95c904e5fd9744c89473130f45a | Python | NaruKim/turtlepainting | /main.py | UTF-8 | 1,125 | 3.109375 | 3 | [] | no_license | # import heroes as h
# print(h.gen())
import turtle as t
import random
def dashed_line(m):
for i in range(m):
tim.forward(10)
tim.penup()
tim.forward(10)
tim.pendown()
def draw_figures(n):
for i in range(n):
tim.fd(50)
tim.left(360/n)
def r... | true |
471e805e1de757323b47b491c723ced2932103cf | Python | mako101/training_dragon_python_basics | /Day4/GuessGameApp/configmanager.py | UTF-8 | 1,766 | 3.484375 | 3 | [] | no_license |
# this class has methods to read and write values to the config file
class FileOps(object):
__FILE = 'settings.txt'
# find relevant config line and return its index
@staticmethod
def find_line_index(item):
lines = open(FileOps.__FILE, 'r+').readlines()
for line in lines:
... | true |
f13f5e7386d850e2b1caa729db4a98e543b086f6 | Python | adrian/udacity-cs387-applied-cryptography | /final/crypto.py | UTF-8 | 1,951 | 3.171875 | 3 | [] | no_license | from Crypto.Cipher import AES
from Crypto.Util import Counter
import binascii
class AESCounterMode:
def decrypt(self, key, nonce, ctr_iv, ciphertext):
"""
key: (byte string) - The secret key to use in the symmetric cipher
nonce: (hex string) - MUST be 4 bytes
ctr_iv: (hex string)... | true |
81b39b07994ea91a600b70a74e3140bfaecfa75b | Python | homholueng/playground | /python/asyncio/official_docs/synchronization/lock.py | UTF-8 | 513 | 3.3125 | 3 | [] | no_license | import asyncio
async def lock_competitor(n, lock):
print(f"competitor{n} try to get lock")
async with lock:
print(f"competitor{n} get the lock")
print(f"competitor sleep for {n} seconds...")
await asyncio.sleep(n)
print(f"competitor{n} wake up!")
print(f"competitor{n} ... | true |
c52acde9c62655ffc15da181eb40c1d999a05288 | Python | lellisls/queen | /relatorio/lucaslellis_69618_common.py | UTF-8 | 695 | 3.09375 | 3 | [] | no_license |
import random
import math
def board(vec):
n = len(vec)
print ("\n".join( 'O ' * (i) + 'X ' + 'O ' * (n-i-1) for i in vec) + "\n")
def collisions(vec):
tuples = []
for i in range(0,len(vec)):
for j in range(1,len(vec)):
if i != j :
if vec[i] == vec[j] or abs(j-i) == abs(vec[j] - vec[i]):
if i < j :
... | true |
d43bd1c2d0bc7fbc298c4013f1f1a045812f7e7e | Python | lzhw1991/XIBEM | /BEM2D/LagrangianElements.py | UTF-8 | 8,195 | 3.359375 | 3 | [] | no_license | # Michael Peake
# Durham University
import numpy as np
from scipy.integrate import quad
class QuadraticElement(object):
def __init__(self,nodal_points):
"""Constructs a 2D, continuous, Lagrangian quadratic element
with local coordinate xi in [-1,1]"""
P = np.asarray(nodal_points,np... | true |
b3c36c94d3f3e692c3245659df15a705c752addb | Python | gpolo/QAP | /random_stuff/a1.py | UTF-8 | 1,086 | 3.265625 | 3 | [] | no_license | import sys
import random
import time
seed = hash(time.time()) # Or your favourite one
random.seed(seed)
stdin = sys.stdin.next
def get_matrix(n):
l = []
while n:
line = stdin().split()
if not line:
# Empty line, discard
continue
n -= 1
l.append(map(int... | true |
ae7b62f2ecbd4edc58902a5c743dca047d2c8419 | Python | haosulab/ManiSkill2 | /mani_skill2/utils/wrappers/common.py | UTF-8 | 1,204 | 2.6875 | 3 | [
"Apache-2.0",
"CC-BY-NC-4.0"
] | permissive | import gymnasium as gym
from gymnasium import spaces
from ..common import (
clip_and_scale_action,
inv_clip_and_scale_action,
normalize_action_space,
)
class NormalizeBoxActionWrapper(gym.ActionWrapper):
"""Normalize box action space to [-1, 1]."""
def __init__(self, env):
super().__init... | true |
e25d40bfe07907fd6571b368a7019f9f39474850 | Python | abhaira/chassis_manager | /lock_tests.py | UTF-8 | 4,831 | 2.65625 | 3 | [] | no_license | import unittest
import lock
import os
class LockCreation(unittest.TestCase):
def test_fresh_lock(self):
lck = lock.Lock()
self.assertEqual(lck.type(), lock.LockType.FREE)
self.assertEqual(lck.owners(), [])
self.assertEqual(lck.waiters(), [])
self.assertEqual(lck.history(),... | true |
263c18e4fbc6b820f1caa7fd5f33914ab4f6378c | Python | alefnula/dg | /dg/commands/train_eval.py | UTF-8 | 3,427 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | __author__ = 'Viktor Kerkez <alefnula@gmail.com>'
__date__ = ' 16 December 2017'
__copyright__ = 'Copyright (c) 2017 Viktor Kerkez'
import dg
from dg import train_eval
from dg.utils import print_and_save_df
@dg.command
@dg.argument('-m', '--model', action='append', dest='models',
help='Models to train.... | true |
96a46544b14e3495f9dfd92095d1102908b031a5 | Python | nimish/xsdata | /tests/models/elements/test_restriction.py | UTF-8 | 3,174 | 2.703125 | 3 | [
"MIT"
] | permissive | from unittest import TestCase
from xsdata.models.elements import Enumeration
from xsdata.models.elements import FractionDigits
from xsdata.models.elements import Length
from xsdata.models.elements import MaxExclusive
from xsdata.models.elements import MaxInclusive
from xsdata.models.elements import MaxLength
from xsda... | true |
40c2a1f1a80fb4121505dce5c3f1b63020e17150 | Python | Ale3e/DIA_Project | /Part1/draw_demand_curve.py | UTF-8 | 4,299 | 3.28125 | 3 | [] | no_license | import numpy as np
import seaborn as sns
import scipy.stats as ss
import matplotlib.pyplot as plt
import tqdm
from errors import *
def draw_demand_curve (n_simulazioni, probabilities, color, label):
'''
:param n_simulazioni:
:param probabilities: needs to be an array of len(probs)= 8
:param color:
... | true |
e3abfa361cfbc0efb4ab2be50fbbbc3df293cfd5 | Python | Alonsovau/sketches | /test9.py | UTF-8 | 1,909 | 2.75 | 3 | [] | no_license | import re, time
class ss:
pass
def write(result):
with open('result.txt', 'w') as f:
for key, value in result.items():
f.write(key+'\n')
value = sorted(zip(value.values(), value.keys()),reverse=True)
for t in value:
f.write('\t' + str(t[0]).ljust(1... | true |
8e3f1c861d8ea65175517b04694dc9e74151a41d | Python | MilesAlmond/Competitions | /Showcode - Unicode/Final/Challenge_1/genesis.py | UTF-8 | 598 | 2.734375 | 3 | [] | no_license | class Solution:
def final_function(self, input):
if (input < 1):
result = 0
else:
flag = 0
for i in range(2,input):
if (input % i) == 0:
flag = 1
break
if (flag == 0):
result = 0
... | true |
88572fe1f5954385e0aab10d19a3c3d1d99d86aa | Python | formazione/tkinter_tutorial | /enrty_test_class.py | UTF-8 | 898 | 4 | 4 | [] | no_license | # entry_test_class.py
# template with entry and text, the text in the entry is passed in the text area
import tkinter as tk
# Create the main window
class Window:
def __init__(self):
self.window = tk.Tk()
self.window.title("Tkinter Window")
# Entry widget
self.entry = tk.Entry(s... | true |
ccb4dbc5e5dd45b0ba2618ad5bfa0d84d45ff4cc | Python | marcelomata/contextemb-wsd | /backoff_mfs.py | UTF-8 | 1,119 | 2.671875 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: backoff_mfs.py
# @author: chrhad
# Given neural-tagged WSD output and MFS output, back-off to MFS output if the former is unknown
import argparse
import io
import sys
import os
from instances_reader import open_file
if __name__ == '__main__':
argparser = argpa... | true |
0ea7f2e8a471e510015feb3862859086228a5468 | Python | sungc1/fake-news-framework_Py3 | /preprocessing_tools/data_preprocessor.py | UTF-8 | 5,530 | 2.59375 | 3 | [] | no_license | # Created by jorgeaug at 10/04/2016
import os
import re
from nltk.stem.snowball import GermanStemmer, EnglishStemmer
from commons.consts import Language
from bs4 import BeautifulSoup
from preprocessing_tools.abstract_controller import AbstractController
import time
import logging
import warnings
warnings.filterwarnings... | true |
d311e63938eb76e1ea591a90a3302f083a63345d | Python | nayohan/tf_for_all | /01_Linear_Regression/07_넘파이_파이플롯_데이터.py | UTF-8 | 2,657 | 3.09375 | 3 | [] | no_license | import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
import tensorflow as tf
import numpy as np #넘파이 배열,행렬계산에 편리함
import matplotlib.pyplot as plt #그래프 그려주는 라이브러리
"""Slicing"""
nums = [0, 1, 2, 3, 4] #"[0,1,2,3,4]"
print(nums[2:4]) #index 2 to 4 "[2,3]" (exclusive)
print(nums[2:]) #index 2 to end... | true |
931cc8a1a025a54f8bcbb40baeed710a6380334c | Python | phantomas1234/fbaproject | /ifba/GlpkWrap/glpk_Test.py | UTF-8 | 10,889 | 2.625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python
# encoding: utf-8
"""
glpk_Test.py
Created by Nikolaus Sonnenschein on 2008-02-12.
Copyright (c) 2008 Jacobs University of Bremen. All rights reserved.
"""
from ifba.glpki import glpki
import unittest
import util
import glpk
import sys
import copy
import random
import pickle
class test_glpk(uni... | true |
3e3cdaf91b2913d524a0f59ac9061c713de47c1d | Python | bilibalaPlus/Crawler | /爬虫代码_II/L_02/mp_queue.py | UTF-8 | 489 | 2.953125 | 3 | [] | no_license | import os
from multiprocessing import Process
from multiprocessing import Queue
def run_proc(w):
while not w.empty():
v = w.get(True)
print('Run child process %s (%s)...' % (v, os.getpid()))
if __name__ == '__main__':
q = Queue()
for i in range(100):
q.put(i)
p_1 = Process(targ... | true |
014b08a3cdf3a380b1e4b8422ad116732341cea9 | Python | Silverlined/HyDrone-Control-System | /src/ControlGoPro.py | UTF-8 | 1,337 | 2.765625 | 3 | [] | no_license | #!/usr/bin/env python3
from goprocam import GoProCamera
import serial
import time
PORT = "/dev/ttyACM0"
BAUDRATE = 115200
arduino_serial = None
isRecording = False
# GoPro
goproCamera = GoProCamera.GoPro()
def openSerial():
global arduino_serial
if arduino_serial == None:
try:
arduino_s... | true |
da01adb62d22d170e04457358e374d6c7fbfdd46 | Python | marshyn/nc-2020fall-python-final | /Final Project/final_01.py | UTF-8 | 2,509 | 3.65625 | 4 | [] | no_license | # Dance Dance RESOLUTION
# for copyright reasons. ALSO there's no music
# at least that way you can play whatever song you want
"""
how to run in terminal:
drag file
python3 coding.py (or name of file)
how to close window with keyboard commands:
control ^ + c (with the terminal window selected and active)... | true |
aff697bdfe59a91aa6235c40fab5df387b18dd98 | Python | DhunterAO/py-authChain-v2 | /BLOCKCHAINclass/attribute.py | UTF-8 | 1,596 | 3.15625 | 3 | [] | no_license | import copy
import logging
from BLOCKCHAINclass.duration import Duration
class Attribute:
def __init__(self, name='', duration=None):
self.name = name
if duration is not None:
self.duration = copy.deepcopy(duration)
else:
self.duration = Duration()
def get_nam... | true |
a06e44de38cb0e3f4693d6f4ccd88f3ea8576f29 | Python | PonchonB/Mathematical_Morphologies_And_Deep_Learning | /SourceCode/_old/ShallowAE/custom_regularizers.py | UTF-8 | 1,757 | 2.96875 | 3 | [] | no_license | from keras.regularizers import Regularizer
from keras import backend as K
class KL_divergence(Regularizer):
"""KL divergence for Sparsity regularization.
# Arguments
beta: Float; Weight of the kl_regularizer.
rho: Float; Sparsity Parameter.
"""
def __init__(self, beta=1, rho=0.1):
... | true |
0c897893737453dd08658730d2acda99fdc17a41 | Python | andyp13/Compilers | /Project 1/assembler.py | UTF-8 | 16,664 | 2.8125 | 3 | [] | no_license | import sys
print("Starting the Assembler")
# Simple Ways to figure out what I am looking at
def representsInt(myInt : int):
try:
int(myInt)
return True
except:
return False
def representsHex(myInt: str):
if(myInt.lower().startswith('0x')):
myInt = myInt[2:]
try:
... | true |
42566ad039404d57aa3263fdb153a71d2f59af10 | Python | jslepicka/aoc2020 | /16.py | UTF-8 | 3,556 | 3.234375 | 3 | [] | no_license | import re
fields = {}
tickets = [] #tickets[0] is my ticket
valid_tickets = []
section = None
with open("16.txt") as f:
for l in [x.strip() for x in f.readlines()]:
if l == "":
continue
elif l == "your ticket:":
section = "my_ticket"
continue
elif l == "... | true |
9bd4f53fb7003a8ea3cb925e7d050e46631978f0 | Python | Aasthaengg/IBMdataset | /Python_codes/p03962/s749563958.py | UTF-8 | 68 | 2.796875 | 3 | [] | no_license | arr = list(map(int, input().split()))
arr = set(arr)
print(len(arr)) | true |
5375d24a63f07a7a90783fdca2cc61af674e44dd | Python | yayen-lin/Madison-Metro-Sim | /msnmetrosim/controllers/route.py | UTF-8 | 2,367 | 3.140625 | 3 | [] | no_license | """
Controller of the MMT GTFS route data.
The complete MMT GTFS dataset can be downloaded here:
http://transitdata.cityofmadison.com/GTFS/mmt_gtfs.zip
"""
import csv
from typing import List, Dict
from msnmetrosim.models import MMTRoute
__all__ = ("MMTRouteDataController", "RouteIdNotFoundError")
class RouteIdNotF... | true |
64c1d1227b64a25a84918c2d36e552f85a1ef089 | Python | ajaykhanna123/Sorting-Searching-Algorithms | /Algorithms in Python/linear-search.py | UTF-8 | 694 | 5 | 5 | [] | no_license | # Searching an element in a list/array in python
# can be simply done using \'in\' operator
# Example:
# if x in arr:
# print arr.index(x)
# If you want to implement Linear Search in python
# Linearly search x in arr[]
# If x is present then return its location
# else return -1
def search(arr, x):
for i ... | true |
3db8edef9284ee21fd47eefff14ab5f2e0e0cb04 | Python | olhaterefenko/Rv-86.Python-Core | /Zhytkova/HW3/Home3_1.py | UTF-8 | 90 | 3.46875 | 3 | [] | no_license | a=int(input('Enter a number a: '))
b=int(input("Enter a number b: "))
a,b=b,a
print(a,b)
| true |
4278f230295675904e8490b033c81f7f96c4a5c6 | Python | ariel-tann/Siamese-Network | /SiameseNetwork.py | UTF-8 | 37,556 | 2.875 | 3 | [] | no_license | '''
------------------------------------------------------------------------------
IFN680 Assignment2 Siamese Network
Tan En Hui Ariel, n10497285
Patrick Choi, n10240501
Ian ChoiI, n10421106
-----------------------------------------------------------------------------... | true |
3b65950acb8e653540d7ee70fa60e8d65498ad29 | Python | Ch-Muhammad-Tahir/Hirst-Painting | /main.py | UTF-8 | 1,376 | 3.078125 | 3 | [] | no_license | # How to get Extract Color from any pic
# import colorgram
#
# colors = colorgram.extract('image.jpg', 30)
# rgb_colors =[]
# for color in colors:
# #rgb_colors.append(color.rgb)
# r = color.rgb.r
# g = color.rgb.g
# b = color.rgb.b
# new_color = (r, g, b)
# rgb_colors.append(new_color)
# print(... | true |
408ff0a855ac23d1c0db1c96e2d1a8b21b79563e | Python | bwiswell/py-virpu | /panels/valuepanel.py | UTF-8 | 1,505 | 3.265625 | 3 | [] | no_license | from typing import Callable
from pygame import Surface
from .panel import Panel
from ..ui.theme import Theme
class ValuePanel(Panel):
'''
A class to extend Panel for showing current variable values.
Attributes:
value_getter (Callable[[], object]): Method to update current value
'''
def ... | true |
667ebdd0a6498179fdb353eff1e83e95f2a112b1 | Python | arnabs542/Data-Structures-And-Algorithms | /Array/Minimum swaps required to bring all elements less than or equal to k together.py | UTF-8 | 1,963 | 4.0625 | 4 | [] | no_license | """
Minimum swaps required to bring all elements less than or equal to k together
Problem Description
Given an array of integers A and an integer B, find and return the minimum number of swaps required to bring all the numbers less than or equal to B together. Note: It is possible to swap any two elements, not necessa... | true |
e4568acd53007e6aee88d9cad6e2bf766e108fba | Python | BurnFaithful/KW | /Programming_Practice/Python/Python_Scraping/Scraping_004/csv_3.py | UTF-8 | 958 | 3.015625 | 3 | [] | no_license | import openpyxl
filename = "test_02.xlsx"
book = openpyxl.load_workbook(filename)
# 2018년 인구 최소 5개 자치 행정구역
# sheet = book.worksheets[0]
#
# data = list()
#
# for row in sheet.rows:
# data.append([row[0].value, row[10].value])
#
# del (data[0], data[1], data[2])
#
# data = sorted(data, key=lambda x:x[1])
#
# for i... | true |
58b973478b2906d006247101b67f7b22783d1a90 | Python | edrakopo/MLAlgorithms | /Classification/classification_e_mu_RemovingParameters.py | UTF-8 | 9,641 | 2.796875 | 3 | [] | no_license | import numpy as np
import pandas as pd
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn import preprocessing
#------- Merge .csv files -------
data_e = pd.read_csv("data/pdf_electron_Parametric_single.csv", header = None)
data_e[11] = "electron"
data_m... | true |
89e57b1f118e66787d0713b8f859372371cb6aae | Python | FTCr/beeline-lk | /beeline-lk.py | UTF-8 | 3,001 | 2.859375 | 3 | [] | no_license | #!/usr/bin/env python3
import pycurl
from optparse import OptionParser
from io import BytesIO
from urllib.parse import urlencode
from html.parser import HTMLParser
class Parser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.__table = False
self.__row = False
self.__col = False
self.__value... | true |
029fb4bcee8d7608cbf2f493df4cb0a19149205c | Python | DataBranner/Thin_Dict | /test/test_thin_dict.py | UTF-8 | 10,647 | 2.671875 | 3 | [] | no_license | # test_thin_dict.py
# David Prager Branner
# 20141219
"""Test various JSON objects with `thin_dict` program."""
import pytest
import json
import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, myPath + '/../')
# sys.path.append('..')
import thin_dict as T
# From http://adobe.github.io/... | true |
b166eb075af26054d48a4a31d54e6be8b07f9d32 | Python | AugustusMarvin/AugustusMarvin.github.io | /python语言进阶/ex_3.py | UTF-8 | 519 | 4.21875 | 4 | [] | no_license | #查找方法
def seq_search(items, key):
for index in range(len(items)):
if items[index] == key:
return index
return -1
def bin_search(items, key):
start, end = 0, len(items) - 1
while start <= end:
mid = (start + end) // 2
if key > items[mid]:
start = mid + 1
... | true |
c8bb94d62cb3cc822bd635e05c282c39d30e7715 | Python | nathan-create/simulation | /analysis/wolf_deer_model.py | UTF-8 | 483 | 3.046875 | 3 | [] | no_license | import matplotlib.pyplot as plt
plt.style.use('bmh')
deer = 100
wolves = 10
d_vals = []
w_vals = []
t = []
count = 0
while count <= 100:
t.append(count)
count += 0.001
for num in range(len(t)):
d_vals.append(deer)
w_vals.append(wolves)
d = deer
w = wolves
deer += (0.0006 * d) - (0.00005 * ... | true |
073568ff048ba7eb11c99458d22beb40dcfab486 | Python | tgkei/Algorithm_study | /by_python/kakao/2020-1/4.py | UTF-8 | 1,868 | 3.390625 | 3 | [] | no_license | from pprint import pprint
class Trie:
def __init__(self, tree=None):
self.head = dict()
self.head['?'] = dict({"length": dict()})
def add(self, word):
cur = self.head
n = len(word)
if n not in cur['?']["length"]:
cur['?']["length"][n] = 1
else:
... | true |
9f0e3a9982cc40f939f19dc5f190229294d9bd40 | Python | vani-public/pipes | /examples/configuration/example.py | UTF-8 | 3,661 | 2.84375 | 3 | [] | no_license | from __future__ import print_function
import os
from pprint import pprint
from pypipes import (
from_file, Config, from_environ, merge, from_url, InheritedConfig, ClientConfig)
# read config dict from yaml file
print('\nYAML config')
config = Config(from_file('config.yaml'))
# config is a dictionary
pprint(dict(... | true |
4d4da1888231b6e377719f1746af5771b1040eb8 | Python | Seungyoonkim66/Python-programming | /sort/selection_sort_acc_list_status.py | UTF-8 | 1,458 | 4.34375 | 4 | [] | no_license |
def selection_sort(q,n):
comparison_count = 0
for i in range(0, n-1):
# 리스트의 모든 원소 n-1개에 대해 (마지막 원소 제외)
min = i
for j in range(i+1, n):
# 해당 원소 다음 원소부터 리스트 끝까지 해당 원소와 비교
if q[j] < q[min]:
# min이 해당 원소를 임시로 저장해둔 변수인데 해당 원소가 리스트 순회하면서 자기보다 작은 원소를 ... | true |
06c4196f0b881d95ed8a38aa3d64c549f9f39ddd | Python | rednikon/Python | /Regular-Expressions/pattern_matching.py | UTF-8 | 1,026 | 3.984375 | 4 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 12 18:23:03 2019
@author: veemac
"""
# Pattern matching using the Standard-Library module named "re"
import re
# Functions from the re module
#re.match(pattern, string)
#returns a "match object" if the pattern matches the string
# otherw... | true |
a33b93e82a79f4d8b74ea1b6d64ee9179daa557d | Python | Hindbena/VnCFD_2D_v2 | /lib/functions.py | UTF-8 | 3,366 | 2.8125 | 3 | [
"MIT"
] | permissive | # coding: utf-8
# Copyright (C) 2019 Nguyen Ngoc Sang, <https://github.com/SangVn>
from numpy import array, zeros, loadtxt, sin, cos, deg2rad
from re import findall
from .constants import gamma, gamma_m1, R_gas
def P2U(P):
U = zeros(4)
U[0] = P[0]
U[1] = P[0] * P[1]
U[2] = P[0] * P[2]
U[3] = P[3]... | true |
7b981f438ad7c3b0811310175b3cf0aa2aefa2d1 | Python | alexavila150/CS2302 | /TreesHomework/BinaryTree.py | UTF-8 | 1,668 | 3.640625 | 4 | [] | no_license | class Node(object):
def __init__(self, item, left = None, right = None):
self.item = item
self.left = left
self.right = right
class Tree(object):
def __init__(self, root):
self.root = root
def contains(self, item) -> bool:
cur = self.root
while cur is not N... | true |
04898a675829a8462366caef9ee75227e0860ae8 | Python | shen-huang/selfteaching-python-camp | /exercises/1901090013/d13/main.py | UTF-8 | 2,538 | 2.609375 | 3 | [] | no_license | from mymodule import stats_word
import logging
import yagmail
import requests
import getpass
import pyquery
from pyquery import PyQuery
from wxpy import *
import matplotlib.pyplot as plt
import numpy as np
from pylab import mpl
import matplotlib
bot = Bot()
@bot.register(msg_types = SHARING)# 自动接受新的好友请求
def repl... | true |
acfc56dfffa2dcdf2f3194bfad2e80f85af94786 | Python | sylhare/charpy | /charpy/chartjs/__init__.py | UTF-8 | 2,088 | 2.59375 | 3 | [
"MIT"
] | permissive | __chartjs_version__ = "2.7.2"
SCRIPT = "<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/{}/Chart.min.js'>" \
"</script>".format(__chartjs_version__)
CANVAS = "<div id='chartContainer' style='width:50%; float: left; clear:none;'>" \
" <canvas id='{}'></canvas>" \
"</div>"
HT... | true |
3197af6e1a5f5688dbaf66ada07aecbfe298566d | Python | LONG990122/PYTHON | /第一阶段/2. Python01/day04/exercise/01_str_method.py | UTF-8 | 643 | 5 | 5 | [] | no_license | # 输入一个字符串
# 1. 判断您输入的字符串有几个空格
# 2. 将原字符串的左右空白字符去掉,打印出有效字符的长度
# 3. 判断您输入是否是数字
s = input("请输入一个字符串: ")
# 1. 判断您输入的字符串有几个空格
print("您输入的字符串有", s.count(' '), '个空格')
# 2. 将原字符串的左右空白字符去掉,打印出有效字符的长度
s2 = s.strip() # 去掉空白字符
print("有效字符的个数是: ", len(s2))
# 3. 判断您输入是否是数字
if s2.isdigit():
print("您输入的是数字")
else:
p... | true |
65bc7997aaa9cf8b6a7efceadd3cd036348fea5e | Python | OsirisLambert/CPSC386-Proj3-SpaceInvader | /alien.py | UTF-8 | 3,233 | 3 | 3 | [] | no_license | import pygame
import sys
from pygame.sprite import Sprite
from timer import Timer
from random import choice
class Alien(Sprite):
def __init__(self, ai_settings, screen, image_path1, image_path2):
super(Alien, self).__init__()
self.screen = screen
self.ai_settings = ai_settings
... | true |
fd0ec72c330d32d31fea737df14bfa8c293552c4 | Python | chaitanya41nexus/Saracasm-Detection | /Processing.py | UTF-8 | 3,724 | 3.34375 | 3 | [] | no_license | import nltk
from nltk.collocations import *
import re
import random
# This function parses tweets in a file. This function expects that tweets have been
# preprocessed so that there is only one tweet per line.
# This function also filters some data out of tweets:
# - Mentions (@Username)
# - Hashtags (#Hasht... | true |
4d955bd9c4ef7f6d4fc3e1e1e16c587d9d1eb4c9 | Python | suganthicj/hhh | /hhh.py | UTF-8 | 53 | 2.609375 | 3 | [] | no_license | b,n=map(str,input().split())
p=int(n)
print(b[-p::])
| true |
c2623122ee6b5348bf3d845d01fa908b5345e044 | Python | Sroubek/H2O-Technical_test | /src/sgm_parser.py | UTF-8 | 1,015 | 2.9375 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Parse data to the list and return them
"""
from bs4 import BeautifulSoup
from schemas import attributes, metas, fulltexts
def parse(file):
articles = []
for tag in BeautifulSoup(file, 'html.parser').find_all('reuters'):
articles.append(tag_parser(tag))
return articles
... | true |
00087ef9156862cbfe9ecacf2110b1f2298796c0 | Python | hemanthkumar17/Image-Processing-Lab | /Practice questions/scripts/q7.py | UTF-8 | 180 | 2.59375 | 3 | [
"MIT"
] | permissive | import numpy as np
import cv2
fft_basis = np.zeros((4, 4), dtype=complex)
for n in range(4):
for k in range(4):
fft_basis[n][k] = np.exp(-1j*2*np.pi*k*n/4)
print(fft_basis) | true |