blob_id large_string | language large_string | repo_name large_string | path large_string | src_encoding large_string | length_bytes int64 | score float64 | int_score int64 | detected_licenses large list | license_type large_string | text string | download_success bool |
|---|---|---|---|---|---|---|---|---|---|---|---|
efe2d59103e68fa5fd7cfb9c98cf1455cadcb9b3 | Python | rcheng805/MLcomp_02_2017 | /plot_adaboost.py | UTF-8 | 913 | 2.65625 | 3 | [] | no_license | import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import csv
data = []
with open('results_adaboost_1_clean.csv', 'r') as ff:
f = csv.reader(ff)
for row in f:
data.append([float(item.split('=')[1]) for item in row])
data = np.array(data)
ind_1 = data[:, 0] == 7... | true |
629c424b94f22898a1cfbc7fb66437beb58a127d | Python | dothedung1982/ds-program-2 | /mathplotlib.py | UTF-8 | 564 | 3.84375 | 4 | [] | no_license | import numpy as np
import matplotlib.pyplot as plt
input_1 = (input('Nhập tọa độ x1, y1 = '))
x1, y1 = input_1.split(' ')
x1, y1 = (int(x1)), (int(y1))
#
input_2 = (input('Nhập tọa độ x2, y2 = '))
x2, y2 = input_2.split(' ')
x2, y2 = (int(x2)), (int(y2))
#
print('(x1, y1) = {}, {}'.format(x1, y1))
print('(x2, y2) = {... | true |
d0ffd3c8f2a7b766152f33db5a8b728a39f82e6e | Python | gxmls/Python_Leetcode | /1748.py | UTF-8 | 865 | 3.359375 | 3 | [] | no_license | '''
给你一个整数数组 nums 。数组中唯一元素是那些只出现 恰好一次 的元素。
请你返回 nums 中唯一元素的 和 。
示例 1:
输入:nums = [1,2,3,2]
输出:4
解释:唯一元素为 [1,3] ,和为 4 。
示例 2:
输入:nums = [1,1,1,1,1]
输出:0
解释:没有唯一元素,和为 0 。
示例 3 :
输入:nums = [1,2,3,4,5]
输出:15
解释:唯一元素为 [1,2,3,4,5] ,和为 15 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sum-of-unique-eleme... | true |
def2c3bc8025c34e808bf171fa598ea4f27c5135 | Python | Mansi149/Machine-Learning-Lab | /Exp 7.py | UTF-8 | 1,127 | 3.390625 | 3 | [] | no_license | # Implement Multiple Linear Regression Model
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('50_Startups.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values
print(X)
# Encoding categorical data
from sklearn.compose im... | true |
50f8df4e1bb39203bf14b32af61917099a501f12 | Python | Tianw22/Capstone-GWU-DataScience | /code/blackorwhitefilter.py | UTF-8 | 1,255 | 3.09375 | 3 | [] | no_license | #The pictures has white or black ones.
#This code is to build a filter to estimate whether the picture is almost all black or all white.
#I didn't delete the "black" or "white" ones. Because some films has a darker color tone or lighter color tone.
#Gave in. Delete all the pictures that match the conditions. That's i... | true |
381a9c9aabc1c47ffe1297a4cdb06b70293b0f96 | Python | avellar1975/python-pro | /procedural/teste.py | UTF-8 | 1,259 | 3.953125 | 4 | [] | no_license | """Conceito de testes unitários."""
from unittest import TestCase
def soma(*args):
"""Recebe argumentos e retorna a soma, dependendo do tipo de argumento."""
concatena = ''
if any(type(item) == str for item in args):
for item in args:
item = str(item)
concatena += item
... | true |
c5e42619dc36bb1f4285b1c216e8a409e5fcafce | Python | nzw0301/PFI_PFN_summer_intern_task_code | /2016/tasks/task1.py | UTF-8 | 304 | 3.3125 | 3 | [] | no_license | def outer(x, y):
return [[x_i*y_j for y_j in y] for x_i in x]
if __name__ == "__main__":
# init test data
x = [1, 2, 3]
y = [3, 2, 1, 0]
result = outer(x, y)
expected = [[3, 2, 1, 0],
[6, 4, 2, 0],
[9, 6, 3, 0]]
assert (result == expected)
| true |
0b8e4f3c2620a38c0a45734423855fa1200042c8 | Python | sarvex/code2flow | /code2flow/javascript.py | UTF-8 | 14,486 | 2.765625 | 3 | [
"LGPL-2.0-or-later",
"MIT"
] | permissive | import logging
import os
import json
import subprocess
from .model import (Group, Node, Call, Variable, BaseLanguage,
OWNER_CONST, GROUP_TYPE, is_installed, djoin, flatten)
def lineno(el):
"""
Get the first line number of ast element
:param ast el:
:rtype: int
"""
if isin... | true |
46ef3557be2e9b4a691779eda49ff65716177229 | Python | CyeCandy/WebScrapingCoursework | /ScrapingExample.py | UTF-8 | 3,343 | 3.421875 | 3 | [] | no_license | #Parse 2014 MN Capital budget - https://www.revisor.mn.gov/laws/?year=2014&type=0&doctype=Chapter&id=294
#Store the summary in a DataFrame for eventual manipulation
from __future__ import print_function
import os.path
from collections import defaultdict
import string
import requests
from bs4 import BeautifulSoup
import... | true |
1a3f140572b1fab6d768f021439f9f403182b325 | Python | fcant/dicer | /python/testing/mask.py | UTF-8 | 301 | 2.53125 | 3 | [] | no_license | import cv2
import numpy as np
cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
print(cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)))
kernel = [[0,0,1,0,0],
[0,1,1,1,0],
[1,1,1,1,1],
[0,1,1,1,0],
[0,0,1,0,0]]
# np.ones((6, 6), np.uint8)
print(kernel)
| true |
4568f3fe3e900992350679a28b6912de6acda1e4 | Python | raphael-njamo/SID_Terrorisme | /version_0/localisation_v0.py | UTF-8 | 7,860 | 2.765625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Ce code permet de nettoyer la liste de toutes les villes du
monde par pays pris sur la page wikipédia de "liste des villes du monde"
"""
# chargement de packages utiles
import json
import re
import codecs
# chargement de la liste de toutes les villes du monde par pays
f... | true |
aa3ef338a7b60dfb18399d95154b84ccb97d272b | Python | qtvspa/offer | /Matrix/path.py | UTF-8 | 1,573 | 3.5 | 4 | [] | no_license | # -*- coding:utf-8 -*-
"""
矩阵中的路径
https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/
思路:dfs递归+回溯
"""
from typing import List
def dfs(board, i, j, word):
# 深度优先搜索
if not word:
return True
# 检查角标边界条件 以及 word首字母是否与当前元素相等
if (i < 0 or j < 0
or i >= len(board) or j >= le... | true |
d6d862dc2884d773b98989e7c23f0f3755fbc304 | Python | maiksurco/tareas-de-alto-nivelG2 | /calcularahorrosanualesRMSA.py | UTF-8 | 582 | 3.1875 | 3 | [] | no_license | def calcularahorrosanualesRMSA():
#datos de entrada:
contador_demes=1
valorde_cadames=20
resultado=0
total=0
#proceso:
while contador_demes<=12:
valorde_cadames=int(input(f"ingrese la cantidad de dinero por cada mes {contador_demes}:"))
resultado=resultado+valorde_cada... | true |
e16bbb6f4d1f2dd5109753bf1d93b00c6614e27f | Python | zebrajack/Tangent-Images | /examples/visualize_icosphere_sampling.py | UTF-8 | 2,914 | 2.671875 | 3 | [
"BSD-3-Clause"
] | permissive | import torch
from tangent_images.util import *
kernel_size = 1 # Kernel size (so we know how much to pad)
base_order = 1 # Base sphere resolution
sample_order = 6 # Determines sample resolution
skip = 10 # How many tangent images to skip in sampling ones to visualize
show_tangent_with_padding = True # Include pad... | true |
8e5189b0142e38bf18014e2521580167e3207a81 | Python | avinashrulz/PythonDump | /CodeChefEasyMath.py | UTF-8 | 372 | 2.609375 | 3 | [] | no_license | T = int(input())
while T > 0:
multiply = 0
sum = 0
sumLi = []
N = int(input())
li = list(map(int, input().strip().split()))[:N+1]
(i, j, k) = (0, 0, 0)
for k in range(len(li)):
for j in range(len(li)):
if k!=j:
multiply = li[k]*li[j]
print(... | true |
85e22512d179e7e2b3f78dbd8d3e0a09c7ba0608 | Python | Elvirangel/Pytorch_Learning | /PyLearning.py | UTF-8 | 2,960 | 2.546875 | 3 | [] | no_license | import torch
import numpy as np
from torchvision import datasets,transforms
import torchvision
from torch.autograd import Variable
import matplotlib.pyplot as plt
# 数据转换Transform
transform=transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize(mean=[0.5],std=[0.5])])
# 下载数据集
train_data=datasets.MNI... | true |
34a6f5a5a4faa379b4f6172d6747d36c11823060 | Python | rileymiller/livelot-tracking | /livelot-tracker/utils/request_interface.py | UTF-8 | 785 | 2.796875 | 3 | [] | no_license | import requests
import logging
logger = logging.getLogger('livelot-tracker.car_tracker')
# moved this out of the actual request if we ever change where the api is hosted
requestURL = 'https://livelotapi.herokuapp.com'
def carIn(lotId):
try:
response = requests.put(requestURL + '/lot/{}/carIn'.format(lotId))
if r... | true |
e7bef06756f81617ff7bd59098dc37ecd3eb9689 | Python | famalhaut/ProjectEuler | /problems_00s/problem_5.py | UTF-8 | 1,672 | 4.125 | 4 | [] | no_license | """
Smallest multiple
Problem 5
2520 is the smallest number that can be divided by each of the numbers
from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""
def check(x, list_primes):
for prime in list_primes:
if x % prim... | true |
d2414fec04bb80df8c0a50abc43e9c190688aefb | Python | RohitPr/PythonProjects | /01. Tip Calculator/1.Tip_Calculator.py | UTF-8 | 487 | 4.65625 | 5 | [] | no_license | # Python program to split the bill among the friends.
print("Welcome to the tip calculator")
total_bill = float(input("What was the total bill? Rs "))
tip_percentage = float(
input("What percentage tip would you like to give? 10, 12 or 15? "))
total_people = int(input("How many people to split the bill? ")... | true |
3cb1d4e8da355dd5bcb6651de17bd9ce78ab6907 | Python | diegohabarbosa/Basics-Projects | /CursoemVideo/Curso_de_Python/Mundo1_40hs/Exercícios/ex020.py | UTF-8 | 272 | 3.796875 | 4 | [
"MIT"
] | permissive | # Sorteando uma ordem na lista
import random
n1 = input('Digite o nome: ')
n2 = input('Digite o nome: ')
n3 = input('Digite o nome: ')
n4 = input('Digite o nome: ')
alunos = [n1, n2, n3, n4]
random.shuffle(alunos)
print('A ordem da apresentação será {}'.format(alunos)) | true |
9c9dd0adae74357012aacbe67e7e6d4e4b5a8257 | Python | TanVD/itmo-graphics | /shadows/controls.py | UTF-8 | 759 | 2.578125 | 3 | [] | no_license | from camera import Camera
from display import *
class Controls:
_mouse_force = 1
_mouse_back_force = -1
_glut_scroll_up = 3
_glut_scroll_down = 4
@staticmethod
def mouse(btn, state, x, y):
if state != GLUT_DOWN:
Camera.disable_rotation()
return
if btn ... | true |
a24ed495f182181196988b75309678e200d7a20d | Python | daschaich/misc_scripts | /strip_duplicate.py | UTF-8 | 1,029 | 2.59375 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | #!/usr/bin/python
import os
import sys
import glob
from subprocess import call
# ------------------------------------------------------------------
# Strip duplicate output from files where HMC accidentally run twice
# Should have no effect on files that are already okay
# First make sure we're calling this from the r... | true |
344b86c45c3b9ac66de868f72e91eb6094d41e25 | Python | renat1sakenov/musicplayer | /src/mmp_album.py | UTF-8 | 578 | 3.421875 | 3 | [] | no_license | #! /usr/bin/env python2
class Album():
def __init__(self,name="default"):
self.name = name
self.songs = []
''' return the track following 'song'. if 'song' is the last None is returned '''
def get_next(self,song):
for i in range(len(self.songs)):
if self.songs[i][0]==... | true |
ae3d423ea9c8f5522ab7e94c85b1862ebf69e7f4 | Python | KeleiAzz/LeetCode | /Single Number II.py | UTF-8 | 439 | 3.125 | 3 | [] | no_license | __author__ = 'keleigong'
class Solution:
# @param {integer[]} nums
# @return {integer}
def singleNumber(self, nums):
nums = sorted(nums)
while True:
tmp = nums[0]
for j in range(3):
try:
if tmp != nums.pop(0):
... | true |
847511b10aab35ebaa791642076eb12f108ae4ff | Python | porchard/2021-03-sn-muscle | /bin/common-peaks.py | UTF-8 | 1,314 | 2.625 | 3 | [] | no_license | #!/usr/bin/env python
import os
import sys
import pybedtools as bt
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
BEDS = sys.argv[1:]
N_FILES = len(BEDS)
beds = pd.concat([pd.read_csv(f, usecols=[0, 1, 2], delimiter='\t', header=None, names=['chrom', 'start', 'end']) for... | true |
04604c02c2c6fc7c6c389e792e9fc3f232c87c54 | Python | dmarty1/Earley-Parser-Tree-Edit-Distance-algorithm-Tree-Grammar-Inference-algorithm | /asanas/Basics/generatorsPart2.py | UTF-8 | 1,459 | 3.046875 | 3 | [] | no_license | #!/usr/bin/env python
import multiprocessing.pool
import threading
import time
from queue import Queue
from threading import Thread
dictionary = {}
def flatten(x):
y = []
for xx in x:
y.extend(xx)
return y
def generator(ys):
x = threading.get_ident()
if x in dictionary:
threadnam... | true |
8aeb9ff9028b3f346b747ce997b6e1de29189495 | Python | rrwt/daily-coding-challenge | /gfg/graphs/depth_first_traversal.py | UTF-8 | 1,227 | 3.703125 | 4 | [
"MIT"
] | permissive | """
Depth first search traversal of an undirected graph
"""
import math
from gfg.graphs.ds import GraphM # type: ignore
def depth_first_traversal(graph: list, first_node: int) -> None:
"""
Time complexity: O(V+E)
Space complexity: O(V)
"""
if graph:
stack: list = []
visited: set ... | true |
12040defa33a73c66fcd8b57260f3b478931a5a2 | Python | akimovaen/management | /management/finance/util.py | UTF-8 | 1,399 | 3.515625 | 4 | [] | no_license | from datetime import datetime
def view_month(month_delta):
today = datetime.today()
year = today.year
month_to_view = today.month - month_delta or 12
date_to_view = {'year': year, 'month': month_to_view}
return date_to_view
def weekdays_in_month(first_weekday, days_in_month):
weekday_list =... | true |
23ac58b2105326c921486d9cfd3e25a2b11a6380 | Python | mukeshsehdev/CECS424Sp2017-Assignment-2 | /Part Two/prime.py | UTF-8 | 1,004 | 4.53125 | 5 | [] | no_license | #Finding sum of all the prime numbers
import sys
print("Assigntment 2 - Part 2: Find the sum of all the primes below what the user inputs.")
print("")
primes = []
def isPrime(num):
for i in range(2,int(num**0.5) + 1):
if num%i == 0:
return False
return True
#Second function needed: get_primes y... | true |
20a343180bcbe6f7eb2dd7c748efe578b5768282 | Python | Vitalie999/json-processing-event | /app.py | UTF-8 | 155 | 2.59375 | 3 | [] | no_license | import json
def load_event_data():
file = open("data/event.json")
data = json.load(file)
return data
data = load_event_data()
print(data) | true |
33fbf3f7e797e694b10257d4cd2531bdacffbf3c | Python | cjrzs/LoveYiNuo | /网络编程/socket_test.py | UTF-8 | 422 | 3.265625 | 3 | [
"Apache-2.0"
] | permissive | import socket
s = socket.socket() # 创建一个新的套接字
host = socket.gethostname() # 获取本地主机名
port = 12345 # 设置端口
s.bind((host, port)) # 绑定端口
s.listen(5) # 监听套接字
while True:
c, addr = s.accept() # 接受客户端连接
print(f'连接地址:{addr}')
c.send(b'hello world') # 有连接的客户端 给他发送消息
c.close()
| true |
b0bcf81e77c1a5d01490e0d1fb093b02ddc28abe | Python | jailukanna/Python-Projects-Dojo | /17.Python for Automation/02.Web Scraping with Beautiful Soup/scraping_quotes.py | UTF-8 | 592 | 3.140625 | 3 | [
"MIT"
] | permissive | import requests
import lxml
from bs4 import BeautifulSoup
url = "http://quotes.toscrape.com"
response = requests.get(url)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'lxml')
quotes = soup.find_all("span", class_="text")
authors = soup.find_all("small", class_="author")
tags =... | true |
26bad203afc9c6bec5c286eeb33ede0507b08065 | Python | goto40/self-dsl | /extensions/pi/namedref.py | UTF-8 | 2,417 | 2.703125 | 3 | [
"CC-BY-4.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #!/usr/bin/env python
import re
import markdown
import subprocess
class MyPreprocessor(markdown.preprocessors.Preprocessor):
BLOCK_RE = re.compile(r'''
::namedref::\s*\(\s*(\S+)\#(\w+)\s*\)
'''
, re.VERBOSE)
BLOCK_RE2 = re.compile(r'''
::namedref::\s*\{\s*(\w+):([^}]+)\}
... | true |
2d5386154d84e8905bd2c129e9b30f3c3d33b919 | Python | DanielMalheiros/geekuniversity_programacao_em_python_essencial | /Exercicios/secao06_estruturas_de_repeticao/exercicio61.py | UTF-8 | 514 | 4.0625 | 4 | [] | no_license | """61- Faça um programa que calcule o maior número palíndromo feito a partir do produto de dois números
de 3 dígitos. Ex. O maior palíndromo feito a partir do produto de dois números de dois dígitos é
9009 = 91 * 99"""
i = 0
j = 0
pol = 0
while i <= 999:
j = i
while j <= 999:
temp = str(i * j)
... | true |
aadc46a98bd30f39dd44cd65248fc16a0abb446b | Python | floris0807/AIBASIC2 | /WEEK1/day2h7.py | UTF-8 | 116 | 3.84375 | 4 | [] | no_license | num_str = input("enter a number:")
num_int = int(num_str)
if num_int >= 50:
print("up")
else:
print("down") | true |
b74e601c897a11f80ea03ccdeb03cef264c19e98 | Python | lurenxiao1998/CTFOJ | /[SUCTF 2019]Pythonginx/test.py | UTF-8 | 1,160 | 2.75 | 3 | [] | no_license | from urllib import parse
from urllib.parse import urlsplit, urlparse, urlunsplit
import urllib
def getUrl(url):
# host = parse.urlparse(url).hostname
# print("urlparse:")
# print(parse.urlparse(url))
# if host == 'suctf.cc':
# return "我扌 your problem? 111"
parts = list(urlsplit(... | true |
a5a771fe562e1579923e13420fbe698d2583985c | Python | JetBrains/intellij-community | /python/testData/inspections/PyNumpyType/Transpose.py | UTF-8 | 930 | 3.734375 | 4 | [
"Apache-2.0"
] | permissive |
def transpose(a, axes=None):
"""
Permute the dimensions of an array.
Parameters
----------
a : array_like
Input array.
axes : list of ints, optional
By default, reverse the dimensions, otherwise permute the axes
according to the values given.
Returns
-------
... | true |
6108dd47ab5ae458a04b8dfadef9fdd8c5a193e8 | Python | gustavnilsson14/cardrouge | /src/mapgen.py | UTF-8 | 4,448 | 2.65625 | 3 | [] | no_license | import time, math
from message import *
from unit import *
from block import *
from prop import *
from item import *
from world import *
import game
class MapGen(JoinableObject):
def __init__(self,queues):
JoinableObject.__init__(self,queues)
self.generate()
return
while 1:
... | true |
66f9539b23b343b0db79499ae1ea3b27d6ea3950 | Python | aacharya14/school_incentives | /simulations/current_sys_simulation.py | UTF-8 | 11,107 | 2.671875 | 3 | [] | no_license | import random
import copy
import pickle as pkl
from student import Student,School
students = pkl.load(open("students.p", "rb"))
schools = pkl.load(open("schools.p", "rb"))
students = random.sample(students, int(round(len(students) / 10.0) - 1))
tent_offers = {}
tent_offers_student = {}
assignments = {}
assigned_stud... | true |
759649a91ebcf8f66299c69778764343d8727fe5 | Python | Studies-Alison-Juliano/geek_university_curso_python | /secao4_variaveis_e_tipos_de_dados/tipo_none.py | UTF-8 | 588 | 4.21875 | 4 | [] | no_license | """
Tipo none
O tipo de dado none em Python representa o tipo sem tipo, ou poderia ser conhecido também como tipo vazio, porem, falar
que é um tipo sem tipo é mais apropriado
OBS: O tipo None é SEMPRE especificado com a primeira letra maiúscula.
Quando utilizamos ?
- Podemos utilizar None quanto queremos criar uma v... | true |
9a625361af1cb26ffda78ea32d2461e1944b36ef | Python | darka/projecteuler | /problem94.py | UTF-8 | 510 | 3.140625 | 3 | [] | no_license | from math import *
from fractions import gcd
def main():
result = 0
MAX = 100000
done = False
for u in xrange(1, MAX):
for v in xrange(1, u):
if gcd(u, v) == 1:
a = 2 * (u**2 - v**2)
b = u**2 + v**2
d = abs(b - a)
if a % d == 0 and b % d == 0:
P = a/d + 2*b/d... | true |
1c887028537537cd7d3a5c6c3339205bf2a8dffb | Python | JasonLeeSJTU/Jianzhi_Offer | /max_heap.py | UTF-8 | 1,136 | 3.671875 | 4 | [
"MIT"
] | permissive | #!/usr/bin/env python
# encoding: utf-8
'''
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: jiansenll@163.com
@file: max_heap.py
@time: 2019/4/29 19:58
@desc:
change a given array to max heap
'''
def max_heap(array):
if not array:
return None
length = len(array)
if length =... | true |
779c342299082a085061e065b3f41d854a5571fc | Python | QingzhiHu/IR2_Project | /experiments_doc/2021-10-21_0004_msmarco_doc_bert/matchmaker-src/losses/loss_smooth_mrr.py | UTF-8 | 1,840 | 2.703125 | 3 | [] | no_license | import torch.nn as nn
import torch
class SmoothRank(nn.Module):
def __init__(self):
super(SmoothRank, self).__init__()
self.sigmoid = torch.nn.Sigmoid()
def forward(self, scores):
x_0 = scores.unsqueeze(dim=-1) # [Q x D] --> [Q x D x 1]
... | true |
9cae102caf1ef61b44712044acd2cccd44ebc5a8 | Python | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_95/1143.py | UTF-8 | 720 | 2.8125 | 3 | [] | no_license | import string
f = open("A-small-attempt0.in")
fwrite = open('A-small-attempt0.out', 'w')
numCases = int(f.readline())
trans = string.maketrans("""a o z q ejp mysljylc kd kxveddknmc re jsicpdrysi rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd de kr kd eoya kw aej tysr re ujdr lkgc jv""",
"""y... | true |
67385221626098100273ce58dc31c39274b91302 | Python | yangyuxiang1996/leetcode | /34.在排序数组中查找元素的第一个和最后一个位置.py | UTF-8 | 1,414 | 3.546875 | 4 | [] | no_license | #
# @lc app=leetcode.cn id=34 lang=python
#
# [34] 在排序数组中查找元素的第一个和最后一个位置
#
# @lc code=start
class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if not nums:
return [-1, -1]
... | true |
b996f1258ea7694ef092ed139f97279cd1891c86 | Python | thomaslzb/dcg-edi | /decode_file.py | UTF-8 | 6,995 | 2.609375 | 3 | [] | no_license | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
解码文件
@File : decode_file.py
@Contact : thomaslzb@hotmail.com
@License : (C)Copyright 2020-2022, Zibin Li
@Modify Time @Author @Version @Desciption
------------ ------- -------- -----------
04/12/2020 13:19 lzb 1.0 None
"... | true |
9008ff35b9c2397cbf55afb4a48299c747854d72 | Python | NoelRuizLopez/rest_controller_python | /tests/utils_to_made_easy_testing/http_requests.py | UTF-8 | 1,687 | 2.609375 | 3 | [
"MIT",
"Apache-2.0"
] | permissive | import requests
class HTTPRequests(object):
HOST = '127.0.0.1'
PORT = '5000'
URL = "http://%s:%s" % (HOST, PORT)
@classmethod
def set_host(cls, host):
cls.HOST = host
cls.URL = "http://%s:%s" % (host, cls.PORT)
@classmethod
def set_port(cls, port):
cls.PORT = port... | true |
6c4046e4b768a388e1556a07e6dec387a3e4d35e | Python | leandroli/Smartphone-Price-Analysis | /scrap_taobao&Analysis/preprocess_j2.py | UTF-8 | 987 | 2.859375 | 3 | [] | no_license | import pandas as pd
import logging
logging.Logger(__name__)
info = pd.read_csv('phone_info_j_raw2.csv')
for i in range(info.shape[0]):
info.loc[i, 'title'] = "".join(info.loc[i, 'title'].split())
# 将每个详情页的总销量平均到每个型号上,获得每个手机的总销量并排序
temp = info[['shop', 'title', 'sales']].groupby(['shop', 'title']).mean(... | true |
d2368385a7d663975795eff0401252d4de34e7f8 | Python | kanhataak/opencv-python | /OpenCV_python/6_RGB_to_HSV.py | UTF-8 | 457 | 2.78125 | 3 | [] | no_license | import cv2
img = cv2.imread("bharti.jpeg")
imgHsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# how to show HSV Images what is the output actually
cv2.imshow("HSV image", imgHsv)
cv2.waitKey(0) # press enter
cv2.imshow("Hue CHANNEL :",imgHsv[:, :, 0])
cv2.waitKey(0) # press enter
cv2.imshow("Saturation CHANNEL :",imgHsv[:... | true |
d03c0b23d07564708aec44716757e250148e7d33 | Python | bernasteros/Turtle-Race-Simulator | /main.py | UTF-8 | 5,192 | 3.734375 | 4 | [] | no_license | from turtle import Screen, Turtle
from random import choice, randint
def random_hexer():
"""Returns a random color based on the hex-code"""
hexcolor = "#"
hexlist = list("0 1 2 3 4 5 6 7 8 9 a b c d e f".split(" "))
for char in range(6):
hexcolor += choice(hexlist)
return hexcolor
def... | true |
b87090166b4ec5e181b8936209d1a47ed67abded | Python | falaqm/basicm | /testfunc.py | UTF-8 | 1,013 | 3.234375 | 3 | [] | no_license | # # def expense(exp):
# # total=0
# # for item in exp:
# # total=total+item
# # return total
# #
# # tom_exp=[2100, 3000, 3500]
# # joe_exp=[200, 500, 700]
# #
# # tom_total=expense(tom_exp)
# # joe_total=expense(joe_exp)
# # print("tom total",tom_total)
# # print("joe total",joe_total)
#
# # de... | true |
ef497b7dd5f05b2450f8e953d36467ac4d3fe044 | Python | nobe0716/problem_solving | /leetcode/longest-mountain-in-array.py | UTF-8 | 734 | 3.5 | 4 | [] | no_license | from typing import List
class Solution:
def longestMountain(self, arr: List[int]) -> int:
if len(arr) < 3:
return 0
u = d = 0
r = 0
for i in range(1, len(arr)):
if d and arr[i] > arr[i - 1] or arr[i] == arr[i - 1]:
u = d = 0
if ... | true |
e34341c4e9e6024bae4ba60aa400cb5de4bce379 | Python | WisTiCeJEnT/lectureCompro | /week12/my.py | UTF-8 | 733 | 3.625 | 4 | [] | no_license | while True:
try:
num = int(input('Input the numerator: '))
den = int(input('Input the denomerator: '))
print('%d//%d = %d'%(num, den, num//den))
except Exception as e:
print(type(e))
print('Try next input..')
else:
print('Very good, next input..')
"""
Input... | true |
35dc45876311997d6811f8a95d866d23b13989f9 | Python | eth-sri/UniversalCertificationTheory | /PythonConstruction.py | UTF-8 | 6,463 | 3.03125 | 3 | [
"MIT"
] | permissive | from math import ceil
from numpy import hstack, array, linspace, sqrt, ndarray
import numbers
############################# Intervals ###############################
class Interval(object):
def __init__(self, l, u):
assert(l <= u)
self.l = l
self.u = u
def __add__(self, other):
... | true |
87726bf501c7824c4cccf89ce6bf1acc1b983fc1 | Python | SooryaVN/python-programming | /roman to integer.py | UTF-8 | 292 | 3.0625 | 3 | [] | no_license | f=(input())
if(f=="I"):
print("1")
elif(f=="II"):
print("2")
elif(f=="III"):
print("3")
elif(f=="IV"):
print("4")
elif(f=="V"):
print("5")
elif(f=="VI"):
print("6")
elif(f=="VII"):
print("7")
elif(f=="VIII"):
print("8")
elif(f=="IX"):
print("9")
elif(f=="X"):
print("10")
| true |
8833e562f7df5b4203f57cc13a6661a4a815b863 | Python | jwalto/Notes | /basicPrograms/BasicMath.py | UTF-8 | 149 | 4.03125 | 4 | [] | no_license | num1 = input("Enter one number: ")
num2 = input("Enter another number: ")
numTotal = int(num1) + int(num2)
print("Your total is: " + str(numTotal)) | true |
d1c6dd7b2d80edb1db31b1ae2ed6619e5a39e30a | Python | pnoga190401/projekt | /python_inf/tabliczka.py | UTF-8 | 345 | 3.15625 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# tabliczka.py
#
def tabliczka():
for k in range(1, 11):
for w in range(1, 11):
print("{:>3} ".format(k * w), end='')
print()
def main(args):
tabliczka()
return 0
if __name__ == '__main__':
import sys
... | true |
8a0398c71fdc2ffffda25d16a3ca4dc58df51eb7 | Python | ukysung/roguelikelike | /web.py | UTF-8 | 4,791 | 2.546875 | 3 | [] | no_license | import json
import os
import datetime
import threading
from flask import Flask, session, request, send_from_directory, jsonify
from flask.ext.mysql import MySQL
from game import KeyCode, Game
app = Flask(__name__)
# 게임 데이터 로드
with open('game_data.json', 'r', encoding='utf-8') as f:
server_data = json.load(f)
ga... | true |
2549ef584d10b48fbc467717179327ad0389d963 | Python | dominiksinsaarland/relation_extraction | /create_dep_parses.py | UTF-8 | 4,439 | 2.65625 | 3 | [] | no_license | import networkx as nx
import spacy
import numpy as np
import sys
"""
tokens_in = 0
tokens = 0
mean = []
mean_2 = []
with open("semeval_test.tsv") as infile:
for line in infile:
line = line.strip().split("\t")
spd = line[1].split()
#print (spd)
#print (len(spd))
#input("")
tokens_in += len(spd) - 2
es = l... | true |
ba036f7ed23d30d89e38dbbbd2c2e88d45cecb22 | Python | ryinyang/2048 | /tester.py | UTF-8 | 3,153 | 3.140625 | 3 | [] | no_license | from grid import Grid
import os
import unittest
class TestStringMethods(unittest.TestCase):
def testCreateGrid(self):
true = [0, 2, 4, 2], [0, 2, 8, 16], [0, 0, 0, 0], [2048, 0, 0, 1]
test = Grid(true)
for r in range(4):
for c in range(4):
self.assertEqual(test.... | true |
2519593f5e1a4f39bc15c877888a95330f792ad1 | Python | hwsonnn/python_crawling | /pythoncrawling-master/07/10_dict.py | UTF-8 | 428 | 4.375 | 4 | [] | no_license | #파이썬 data type
x1 = 10 #int(정수)
x2 = 10.1 #float(실수)
x3 = "안녕하세요\n반갑습니다." #str(문자열) , '', """.."""
x4 = """
안녕하세요
반갑습니다.
"""
print(x3)
print(x4)
#형변환
x1_1 = float(x1) #int->float
x2_1 = int(x2) #float->int
x2_2 = str(x2) #float ->str
print(x1_1, type(x1_1))
print(... | true |
ffe9fbdaa8aafa1e68155a936e9edfaa9e457244 | Python | min1378/-algorithm | /BOJ/2573. 빙산.py | UTF-8 | 1,417 | 2.9375 | 3 | [] | no_license | import sys
sys.stdin = open('2573.txt', 'r')
def isWall(x, y):
if x < 0 or x > N - 1 or y < 0 or y > M - 1:
return True
return False
dx = [-1, 0, 1, 0]
dy = [0, 1, 0, -1]
def DFS(i, j):
s = []
s.append([i, j])
visited[i][j] = True
while s:
x, y = s.pop()
count = 0
... | true |
3862136c1ee855f10ab4829cd87f254807934a9d | Python | Nicolas-Wursthorn/Exercicios-Python-Brasil | /EstruturaDeRepeticao/exercicio24.py | UTF-8 | 885 | 4.09375 | 4 | [
"MIT"
] | permissive | # Faça um programa que peça para n pessoas a sua idade, ao final o programa devera verificar se a média de idade da turma varia entre 0 e 25,26 e 60 e maior que 60; e então, dizer se a turma é jovem, adulta ou idosa, conforme a média calculada.
idades = []
while True:
idade = int(input('Digite sua idade (caso que... | true |
182aea6ff4cdf2f3b7e669492555019a17bbb906 | Python | kunhuang/LeetCode | /208_Implement Trie (Prefix Tree).py | UTF-8 | 2,265 | 4.25 | 4 | [] | no_license | class TrieNode(object):
def __init__(self, val):
"""
Initialize your data structure here.
"""
self.val = val
self.children = []
self.is_end = False
class Trie(object):
def __init__(self):
self.root = TrieNode(None)
def insert(self, word):
""... | true |
581af0396a4987e05dfa7facceecd496c31974dc | Python | chunjy2004/hello_python | /day18_file_read_write.py | UTF-8 | 1,391 | 2.5625 | 3 | [] | no_license | FILE_DIR = './_static/_pdb/'
FILE_NAME = 'test1_file_rw.pdb'
DATA = '안농\n하세\n요'
import _script_run_utf8
_script_run_utf8.main()
def test_write():
"""
#f = open(FILE_DIR+FILE_NAME, mode='w')
#f.write(DATA)
#f.close()
"""
with open(FILE_DIR+FILE_NAME, mode='w', encoding='utf8')as f:
f.w... | true |
cb9f6c3486c0292c93c69e9cfa506a326e12ad38 | Python | elginbeloy/trading | /ap22/get_trade_data.py | UTF-8 | 5,679 | 2.671875 | 3 | [] | no_license | import os
import pandas as pd
import json
from tqdm import tqdm
from datetime import datetime
from polygon import RESTClient
from util import log_to_file
from requests.exceptions import HTTPError
api_key = "ESnn_eXGO4gk57uOohD6H7yfqB5_huCq"
# Get list of acceptable trade exchange ids
def get_accepted_trade_exchange_i... | true |
c9c7e471e39efdb28c2302e468f99b600e175d39 | Python | Khemchand5487/VD-Notes | /SpeechToText.py | UTF-8 | 3,292 | 2.625 | 3 | [] | no_license | import json
from ibm_watson import SpeechToTextV1, ApiException
from ibm_watson.websocket import RecognizeCallback, AudioSource
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from pydub import AudioSegment # pip install pydub
from pydub.silence import split_on_silence
import os
# Insert API Key in pla... | true |
31780d2ec5986bf69e8a2be1af5d84db754cca50 | Python | nayyyyy/Learning-Python | /src/Function/function_lambdaexpression.py | UTF-8 | 196 | 2.84375 | 3 | [] | no_license | def increment_function(num):
return lambda x: x + num
def pairs():
data = [(2001, 'nayaka'), (2000, 'shabrina'), (2000, 'risky')]
data.sort(key=lambda pair: pair[1])
return pairs | true |
cd9314f8a36d192e39f5e03a2e20764628e41c72 | Python | levinyi/GZ_Tcell_work | /meta_genomics_pipeline/bin/prokka_multi_result.py | UTF-8 | 1,422 | 2.890625 | 3 | [] | no_license | import sys
import os
import pandas as pd
import argparse
def _argparse():
parser = argparse.ArgumentParser(description="This is description")
parser.add_argument('--input', action='store', dest='input_path', type=str, help = "the input folder with kraken2 log files.")
parser.add_argument('--output', actio... | true |
b2a912194c27a58b72031ee246a9bbb0ea48914b | Python | bravecollective/core | /tools/keystats/stats.py | UTF-8 | 1,636 | 2.5625 | 3 | [
"MIT"
] | permissive | from brave.core.character.model import EVECharacter
from brave.core.key.model import EVECredential
import operator
import datetime
today = datetime.date.today()
masks = {}
masks_user = {}
ages = {}
ages_user = {}
creds = set()
for c in EVECharacter.objects():
if not c.corporation:
continue
if c.corpo... | true |
68d278a4ae162af490b8de23d2402ee931df5210 | Python | ravisharmaa/python101 | /inheritances/lesson407.py | UTF-8 | 552 | 4.21875 | 4 | [] | no_license | # Abstract Classes Example
import abc
class GetterSetter:
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def set_value(self, input):
"""Set a value in instance"""
return
@abc.abstractmethod
def get_value(self):
"""Get and return a value from the instance..."""
re... | true |
5251d71c4ddbf94336cbc710d2ff39e0738c6d29 | Python | dnorkett/pythonLearning | /RSS_Project/ps5.py | UTF-8 | 9,505 | 2.890625 | 3 | [] | no_license | import feedparser
import string
import time
import threading
from project_util import translate_html
from mtTkinter import *
from datetime import datetime
import pytz
def process(url):
"""
Fetches news items from the rss url and parses them.
Returns a list of NewsStory-s.
"""
feed = feedparser.par... | true |
7e4c37da415960d14e0499afc60d39a4cbe9e37d | Python | CroatianMeteorNetwork/cmn_binviewer | /module_highlightMeteorPath.py | UTF-8 | 2,478 | 3.09375 | 3 | [
"BSD-3-Clause"
] | permissive | # import time
# import matplotlib.pyplot as plt
import numpy as np
def highlightMeteorPath(input_img, rho, phi, path_width=20):
""" Draws two guides parallel to the meteor so it highlights the detection.
input_img: numpy array containing a grayscale image
rho: HT parameter (distance from the cen... | true |
f43192c29d15b388983e8674305f180aacdcd0a3 | Python | rkrishan/Image_recognition | /image_detection_and_recognition/Image_recognition/search1.py | UTF-8 | 769 | 2.609375 | 3 | [] | no_license | from my_imagesearch.colordescriptor import ColorDescriptor
from my_imagesearch.searcher import Searcher
import cv2
path='/home/rams/Desktop/image_detection_and_recognition/Image_recognition/my_imagesearch/index.csv'
class Solution:
def perform(self,root_1):
cd = ColorDescriptor((8, 12, 3))
# load the query imag... | true |
4c953665c404a82c912908221397510095ec3636 | Python | ryh95/leetcode-2020 | /binary-tree-maximum-path-sum.py | UTF-8 | 1,953 | 3.375 | 3 | [] | no_license | # Definition for a binary tree node.
from utils import generate_tree
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
res_0 = self.helper(root,0)
... | true |
b8146257edce903e2b6e120dd449812386d3755e | Python | Nockiro/Duolingo | /duolingo.py | UTF-8 | 7,137 | 2.765625 | 3 | [
"MIT"
] | permissive | """Unofficial API for duolingo.com"""
import re
import json
import random
import datetime
import time
import requests
from requests import Session
__DEBUG__ = False
with open('sampleLearnSession.json', 'r') as f:
__sampleData__ = json.load(f)
class Struct:
def __init__(self, **entries):
self.__dict... | true |
754641b1f0b559ae0bf69e8b6986f7d956a25141 | Python | trung-hn/Project-Euler | /Solution/Problem_40.py | UTF-8 | 1,074 | 4.21875 | 4 | [] | no_license | # An irrational decimal fraction is created by concatenating the positive integers:
# 0.123456789101112131415161718192021...
# It can be seen that the 12th digit of the fractional part is 1.
# If dn represents the nth digit of the fractional part, find the value of the following expression.
# d1 × d10 × d100 × d1000 × ... | true |
8861de61b30581e7389a938521a1fbeac175937f | Python | MarynaHaiduk/pthn | /Leetcode/0520_detect_capital.py | UTF-8 | 602 | 3.265625 | 3 | [] | no_license | class Solution:
# Solution 1.
# def detectCapitalUse(self, word):
# if word.islower():
# return True
# elif word.istitle():
# return True
# elif word.isupper():
# return True
# else:
# return False
# Solution 2.
def detectC... | true |
e284523f9842f1000618416ac76896df309213dc | Python | noobmaster007/Python_Excel | /main().py | UTF-8 | 376 | 3.6875 | 4 | [] | no_license | import openpyxl
wrk=openpyxl.load_workbook("wrksht.xlsx") #this method will load your worksheet into a var
print(type(wrk)) #basically it will print a class that is assigned with wrk var
sheets=wrk.sheetnames
print(sheets) # this will return how many sheets in that file. (it will print lists)
#First we have to see w... | true |
c386130c7731ac4f4a088af9cc5e945511dde449 | Python | HazardDede/pnp | /pnp/utils.py | UTF-8 | 41,616 | 2.96875 | 3 | [
"MIT"
] | permissive | """Utility / helper functions, classes, decorators, ..."""
# pylint: disable=too-many-lines
import inspect
import logging
import os
import re
import sys
import time
from base64 import b64encode
from collections import OrderedDict
from datetime import datetime, timedelta
from functools import wraps
from threading impor... | true |
2cef974b682c774770678e480fa13c9cccfe69c5 | Python | AdityaNaresh/Competitive-Programming | /CodeChef/JULY19A/PRTAGN.py | UTF-8 | 567 | 2.5625 | 3 | [] | no_license | t=int(input())
for xxx in range(t):
a=[0]*1000000
l=[]
e=0
o=0
q=int(input())
for xx in range(q):
k=int(input())
if a[k]==0:
a[k]=1
lt=[]
lt.append(k)
for c in l:
z=k^c
lt.append(z)
a[... | true |
d0b5a8eeb704599cd1dab60d30c777c581837a05 | Python | Bartosz-Wegrzyn/Auto-weather-info-on-FB | /main.py | UTF-8 | 815 | 2.765625 | 3 | [] | no_license | import facebook
import pyowm
token = 'Y0uR T0K3N' # Your Facebook token here
fb = facebook.GraphAPI(access_token=token)
owm = pyowm.OWM("Your Token") # Your open weather token here
city = owm.weather_manager().weather_at_place("Wroclaw,pl")
def get_temp():
tem = city.weather.temperature(unit="celsius")
te... | true |
ce1ee1587c7617469d46ceecfffca23b3ba365ca | Python | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4160/codes/1674_1101.py | UTF-8 | 740 | 3.953125 | 4 | [] | no_license | # Teste seu código aos poucos.
# Não teste tudo no final, pois fica mais difícil de identificar erros.
# Use as mensagens de erro para corrigir seu código.
c = float(input("consumo: "))
t = input("Tipo de instalacao (R para residencias, I para industrias, C para comercios): ").upper()
h = "Valor total: R$ "
print("Entr... | true |
ce1693679249f224360af8927341d65127c204b6 | Python | sauravm8/book_to_audiobook | /text_to_speech.py | UTF-8 | 1,775 | 2.953125 | 3 | [] | no_license | import pyttsx3
import logging
import config
class TexttoSpeech:
def __init__(self):
self.engine = pyttsx3.init()
# Setting the
def set_rate(self):
rate = self.engine.getProperty('rate') # getting details of current speaking rate
logging.info(f"The current rate is {rate}") # loggi... | true |
8e4ef9e148791cffed80aaf9863fece7dc7f6f7d | Python | akshar/python-playground | /Python Practice Book/files/files.py | UTF-8 | 490 | 3.71875 | 4 | [] | no_license | f = open("foobar.txt")
# realine will return '' when there is no data
print f.readline()
print f.readline()
print f.readline()
print f.readline()
f.close()
# write is used to write to file in write or append mode
f = open("foobar.txt", 'a')
f.write("random foo")
f.close()
f = open("foobar.txt")
print f.read()
f.close... | true |
ecda5adea84b801aff13ad6cdd0a3080fa8e835a | Python | Bagaspamungkas88/lab01 | /lab 2 latihan 2.py | UTF-8 | 184 | 3.703125 | 4 | [] | no_license | data = []
for i in range (5):
x =int(input("masukan bilangan : "))
data.append(x)
print('data sebelum diurutkan: ',data)
list.sort(data)
print('data setelah diurutkan: ',data)
| true |
b1f018b40f39384e39a81d8ed6094c939d301ee9 | Python | jammerware/pandashape | /src/pandashape/describers/CategoricalDescriber.py | UTF-8 | 669 | 3.484375 | 3 | [
"MIT"
] | permissive | from .Describer import Describer
import pandas as pd
class CategoricalDescriber(Describer):
def get_section_header(self):
return "Categorical data"
def describe(self, df: pd.DataFrame):
df_strings_or_objects = df.select_dtypes(object)
if len(df_strings_or_objects.columns) == 0:
... | true |
3057d19d6a6924fa329753d755a1ac23b396d859 | Python | ncianeo/numpycl | /npcl/ops/convolve.py | UTF-8 | 3,860 | 2.546875 | 3 | [
"MIT"
] | permissive | from os.path import abspath
import pyopencl as cl
import npcl
import numpy as np
prg = None
def build(parameter):
if type(parameter) == cl.Context:
ctx = parameter
if type(parameter) == npcl.Array:
ctx = parameter.context
global prg, local_mem_size, TS
kernel_fp = abspath(__file__).r... | true |
1d5f71d762fcc258045cb59a8b0d117c19005821 | Python | Nemchinovrp/PythonTutorial | /src/loop_While.py | UTF-8 | 212 | 2.96875 | 3 | [] | no_license | def main():
print("program start")
i = 1
while (i < 100):
if (i % 4 == 0):
print("Count {}".format(i))
i += 1
print("progarm end")
if __name__ == '__main__': main()
| true |
d33c4c1c5615fc04e18bc5759947678abcffca30 | Python | saketrule/Scala_Interpreter | /base_parsers.py | UTF-8 | 5,130 | 3.046875 | 3 | [] | no_license | class Literal:
def __init__(self,val):
self.val = val
def eval(self,env):
return self.val
class IntLit(Literal):
def __repr__(self):
return 'IntLit(%d) ' % self.val
class BoolLit(Literal):
def __repr__(self):
return 'BoolLit(%d) ' % self.val... | true |
15ce7355a8fb52931e9aa5f89678c98107cbc97d | Python | nascimentorafael/visualcomputingclass | /Hello World/helloworld.py | UTF-8 | 339 | 3.28125 | 3 | [] | no_license | #Using scipy to handle image processing
from scipy import misc
# Using lena as a test
# Lena is the hello world from scipy
lena = misc.lena()
# Save lena
misc.imsave("../images/lena.png",lena)
# Read image lena form images folder
img = misc.imread("../images/lena.png")
print type(lena)
# Print image shape (512, 51... | true |
73de03602f8272502ee203abcf0a3e2be5676289 | Python | DarshitRathod/INS | /P-9/diffie2.py | UTF-8 | 770 | 3.8125 | 4 | [] | no_license |
import math
import random
global prime, root
def secretnumber ():
secret = int(random.randint(0,100))
return secret
prime = 17
print("The prime is ",prime, "\n")
root = 3
print("The root is",root, "\n")
alicesecret = secretnumber()
print("Alice chooses a secret number",alicesecret)
bobsecret = secretnumber... | true |
a9f012995d0ee4f15183382b0bf9041400dff5ba | Python | oliverhuangchao/algorithm | /epic/test.py | UTF-8 | 271 | 3.46875 | 3 | [] | no_license | #Telephone Number
#Print all valid phone numbers of length n subject to following constraints:
# If a number contains a 4, it should start with 4
# No two consecutive digits can be same
# Three digits (e.g. 7,2,9) will be entirely disallowed, take as input | true |
523ae2b10a4d31dae62a61b0ac940de739086d43 | Python | kode-konveyor/CategorizerAI | /test/TestHelper.py | UTF-8 | 1,446 | 3.1875 | 3 | [] | no_license | import unittest
asserter = unittest.TestCase()
def assertPrintedOn(mockedStdout, printedObject):
argsList = mockedStdout.write.call_args_list
asserter.assertEqual(str(printedObject), argsList[0][0][0])
asserter.assertEqual('\n', argsList[1][0][0])
asserter.assertEqual(2, len(argsList))
def callArgume... | true |
cfec8498e04543cf53aa8dfe146506130ec1b625 | Python | AdityaNarayan001/Learning_Python_Basics | /Python Basics/random_dice.py | UTF-8 | 213 | 3.890625 | 4 | [] | no_license | import random
class Dice():
def roll(self):
x = (1, 2, 3, 4, 5, 6)
y = (1, 2, 3, 4, 5, 6)
print(f'({random.choice(x)}, {random.choice(y)})')
dice1 = Dice()
dice1.roll()
| true |
6dcc4813cfb92c02b629185dadb4cdd6abd4af0b | Python | warrick00/comp705-warrick | /labs/week4/lab4.py | UTF-8 | 2,582 | 4.25 | 4 | [] | no_license | """
lab3.py
Ryan Warrick
2/6/2018
"""
def squared(num_list):
"""
squares numbers in num_list
num_list: list of numbers
Returns: list of these numbers squared
>>> squared([1,2,3])
[1, 4, 9]
>>> squared([])
[]
>>> squared ([-1, -2])
[1, 4]
"""
new_list = [] # initialize l... | true |
6bd19847bc05223ac3225c5c3dcb8a7d930b49ca | Python | baby5/HackerRank | /DataStructures/Stacks/ANDxorOR.py | UTF-8 | 274 | 2.8125 | 3 | [
"MIT"
] | permissive | #coding:utf-8
N = int(raw_input())
A = map(int, raw_input().split())
stack = []
Max = 0
for a in A:
while stack and a <= stack[-1]:
Max = max(Max, stack.pop() ^ a)
if stack != []:
Max = max(Max, stack[-1] ^ a)
stack.append(a)
print Max
| true |
5bef15e5a7f051eadf086cc33bb733ee73262658 | Python | huhuang03/sdl-x | /sdl_x/util/__init__.py | UTF-8 | 241 | 2.734375 | 3 | [] | no_license | import numpy as np
def same_with_small_deviation(n1: np.ndarray, n2: np.ndarray, allowed_deviation=1e-7):
"""
对比,并允许很小很小的误差
"""
return n1.shape == n2.shape and np.all((n1 - n2) < allowed_deviation) | true |
8f3a7562f7e426cca304425ad1caa7095e76f013 | Python | McFeod/lab_three_sec | /gost2001/keygen.py | UTF-8 | 2,996 | 2.953125 | 3 | [] | no_license | from functools import partial
from random import randint
from sympy import randprime, sqrt_mod_iter, isprime
from gost2001.ecc import mul, add
from utils.utils import positive_mod
MIN_RANDOM = 0x1000 # границы n
MAX_RANDOM = 0xffff
COEFFICIENT_RANGE = 0xff # граница для a, b
get_random_prime = partial(randprime,... | true |
e073b5e1e82a35fd61ff30ff085eca9dfcebd57d | Python | DanlanChen/HackerRank | /Easy/angryProfessor.py | UTF-8 | 449 | 2.859375 | 3 | [] | no_license | '''
Created on May 27, 2015
@author: da_chen
'''
T=int(input())
aptitude=[]
for i in range(T):
N,K=list(map(int,input().split()))
time_li=input().split()
time_li=list(map(int,time_li))
count=0
for j in range(N):
if time_li[j]<=0:
count+=1
if count>=K:
... | true |