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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
03f336e88de9827c151834ff81d413dc0d85dc38 | Python | sindish/unitedwelearn | /object_detection/detectron2/experiments/examples/plot.py | UTF-8 | 896 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | import matplotlib.pyplot as plt
from PIL import Image
fig, axes = plt.subplots(2, 2)
axes[0,0].imshow(Image.open('concat1_part1.png'), aspect = 'equal')
axes[0,1].imshow(Image.open('concat1_part2.png'), aspect = 'equal')
# axes[0,2].imshow(Image.open('concat1_part3.png'), aspect='auto')
# axes[1,0].imshow(Image.open... | true |
245d70bb8d162aeec36013c4e1821c52b8241b40 | Python | syamilisn/Python-Files-Repo | /SmartWork/MinCostSpanTree.py | UTF-8 | 2,019 | 3.203125 | 3 | [] | no_license | #Minimum Cost Spanning Tree
"""
Created on Sun May 17 06:03:34 2020
@author: shyam
"""
#weighted graph:4x4
wtgraph=[[0,20,0,90],[2,0,100,10],[0,100,0,40],[90,10,40,0]]
#Display wtgraph
for row in range(4):
for col in range(4):
print(wtgraph[row][col],end=" ")
print(" ")
#start=input("Enter the startin... | true |
d6cc27750039b98130af8787c3b138df7b883ab1 | Python | tausifzmn/worm-game | /worm game.py | UTF-8 | 3,978 | 3.390625 | 3 | [] | no_license | # making the game window
import pygame
import time
import random
pygame.init() # Initializes all of the imported Pygame modules
# colors
grass = (147, 194, 198)
pink = (253, 177, 150)
yellow = (251, 231, 163)
red = (255, 0, 0)
milk = (255, 253, 246)
# Takes a tuple or a list as its parameter to cr... | true |
42deb932554bdc01a0ebdfa6244891dce48e87ea | Python | LucaKaufmann/Home-AssistantConfig | /scripts/build_maps.py | UTF-8 | 4,233 | 2.609375 | 3 | [
"MIT"
] | permissive | """
#!/usr/bin/env python3
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it wil... | true |
e49ce47a0b0a1fbfa366aa04b9c140c9bafc4554 | Python | Linus-MK/AtCoder | /AHC/ahc001_testcase.py | UTF-8 | 1,124 | 3.03125 | 3 | [] | no_license | import random
n = round(50 * 4 ** random.random())
print(f'n={n}')
# x, y
coords_list = []
xs = []
ys = []
for i in range(n):
x = random.randrange(10000)
y = random.randrange(10000)
assert (x, y) not in coords_list
coords_list.append((x, y))
xs.append(x)
ys.append(y)
# r
limit = 10**8
r = ran... | true |
a8df6d3d16477340e3a1f98aab9277ce14cac403 | Python | jcontrerasroberto/AES | /Python/aes.py | UTF-8 | 6,056 | 3.359375 | 3 | [] | no_license | from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad
from Crypto.Util.Padding import unpad
import base64
'''
FUNCTION DECLARATION
1) keyGenerator: Generate a valid DES3 24 bytes key using EDE
Output: A valid DES3 24 bytes key
2) saveKey: Sav... | true |
27f27e96abcc39147b014c24a79921b88985a18b | Python | hckhilliam/programming | /LeetCode/1395.py | UTF-8 | 852 | 3.375 | 3 | [] | no_license | import numpy as np
class Solution(object):
def numTeams(self, rating):
# d[i][j] = max possibilities if this is the jth number
# d[i][2] = sum(d[j][1] for j in 0..i-1 if rating[j] < rating[i])
# d[i][1] = sum[d[j][0] for j in 0..i-1 if rating[j] < rating[i])
# d[i][0] = 1
# ... | true |
e27588a492bedf383e4da59ce78a000458652a0a | Python | defcxz/2020_prog.algoritmos | /03-07_funciones/ArreglosFunciones.py | UTF-8 | 3,001 | 4.1875 | 4 | [] | no_license | import os #para limpiar pantalla
def llenar(arreglo, n):
sw=True
while(sw==True):
try:
n=int(input("Cuantos numeros desea ingresar? "))
if(n>0):
sw=False
else:
print("Debe ingresar una cantidad positiva")
except ValueError:
... | true |
f8c2387a2973a665aaf61f4585ce7c884f5486f6 | Python | wesrer/Algo_trading | /simple_btc_trader.py | UTF-8 | 2,065 | 2.953125 | 3 | [
"MIT"
] | permissive | import robin_stocks as r
import json
import time
import getpass as gp
from timeloop import Timeloop
from datetime import timedelta as td
username = input('Your Robinhood email: ')
passw = gp.getpass('Your pass: ')
login = r.login(username, passw)
# global flags to fulfill orders
sold = False
last_order_id = ""
tl ... | true |
4870b61a905d9ac6ce553dad416999407cea7964 | Python | Mamoth112/SML-Cogs-v3 | /dstats/utils.py | UTF-8 | 419 | 2.921875 | 3 | [
"MIT"
] | permissive | def get_emoji(bot, name, remove_dash=True):
"""Return emoji by name
name is used by this cog.
key is values returned by the api.
Use key only if name is not set
"""
if remove_dash:
name = name.replace('-', '')
for guild in bot.guilds:
for emoji in guild.emojis:
... | true |
27c1bf9c12ffca16b6d367559a0c18986a28114b | Python | mahathu/bachelorarbeit | /skripte/surface_3d.py | UTF-8 | 924 | 2.84375 | 3 | [] | no_license | from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.view_init(30,120)
e = np.e
r = 1
step = .025
stept = .5
X = np.arange(-r, r, step)
Y... | true |
27bcff7d24f14a8818cc5a504d6d9e4b88d7ca4b | Python | biolearning-stadius/rdkit | /rdkit/utils/chemutils.py | UTF-8 | 4,896 | 2.828125 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #
# Copyright (C) 2000 greg Landrum
#
""" utility functions with "chemical know-how"
"""
import os
import re
from rdkit import RDConfig
if not RDConfig.usePgSQL:
_atomDbName = os.path.join(RDConfig.RDDataDir, 'atomdb.gdb')
else:
_atomDbName = "::RDData"
def GetAtomicData(atomDict, descriptorsDesired, d... | true |
8b0296411c9df758b0350c21f9b7f5c403e7b004 | Python | shu-xiao/alicptfts | /alicptfts/sftpwrapper.py | UTF-8 | 2,371 | 2.859375 | 3 | [
"BSD-2-Clause"
] | permissive | # Adapted from Mathew Newville's code
# https://github.com/pyepics/newportxps/blob/master/newportxps/ftp_wrapper.py
import pysftp
from io import BytesIO
class SFTPWrapper():
def __init__(self):
self.host = None
self.username = None
self.password = None
self._conn = None
def co... | true |
d753f01c5e8739b0e9a6fb08cbf408dbecfbcda5 | Python | SirJan18/Youtube-Song-Downloader | /download.py | UTF-8 | 1,304 | 2.671875 | 3 | [] | no_license | # Include Libarires
# from pytube import YouTube
import pafy
import sys
import re
import os
import helpers
def downloadSong(link):
try:
yt = pafy.new(link)
print("Downloading: " + yt.title)
yt.getbestaudio().download(filepath='video', quiet=False)
ext = yt.getbestaudio().extension
... | true |
7e46335ff1efdfb88b071761b1f7372381bdf5fb | Python | HaGriD1993/Obiektowe-II | /Kowal.py | UTF-8 | 12,417 | 3.34375 | 3 | [] | no_license | import random
import time
import Bohater
import Przedmiot
class Kowal:
def __init__(self):
self.imie = "Ryszard"
self.wiek = 52
self.specjanosc = "Kowal"
def info(self):
print("\nWitaj nazywam się: " + self.imie, ",jestem", self.specjanosc+"em") #PRZEDSTAWIA SIE
def skl... | true |
25801d340a5adf33afea32801a176203e594f307 | Python | MathieuR/bioloid_typea_gazebo | /scripts/walker_demo.py | UTF-8 | 756 | 2.53125 | 3 | [
"BSD-2-Clause-Views",
"BSD-2-Clause"
] | permissive | #!/usr/bin/env python
import rospy
from typea_gazebo.typea import TypeA
if __name__=="__main__":
rospy.init_node("walker_demo")
rospy.loginfo("Instantiating TypeA Client")
typea=TypeA()
rospy.sleep(1)
rospy.loginfo("TypeA Walker Demo Starting")
typea.set_walk_velocity(0.2,0,0)
ros... | true |
3afca428e776c15e713b0ca02329d2fb75cff902 | Python | umutbozkurt/backend-challenges | /kvdb/tests.py | UTF-8 | 3,476 | 2.796875 | 3 | [] | no_license | import unittest
import time
from unittest.mock import patch
from dbserver import Server
class ServerTests(unittest.TestCase):
def setUp(self):
self.server = Server()
def test_ping(self):
payload = {
'command': 'PING'
}
response = self.server.handle_message(paylo... | true |
fc935b3dec9c1b7eb6bbc421efe4ca9f7b4a9bde | Python | lichkingwulaa/Codewars | /5 kyu/5_kyu_Return_substring_instance_count-2.py | UTF-8 | 1,247 | 3.140625 | 3 | [] | no_license | def search_substr(full_text, search_text, allow_overlap=True):
print(full_text, search_text, allow_overlap)
if allow_overlap:
count = 0
for i in range(len(full_text) - len(search_text) + 1):
if full_text[i:i + len(search_text)] == search_text != '':
count += 1
return count
else:
return full_text.count... | true |
6e9b4cc631e3282876add51d01def381594998dd | Python | Motamensalih/LISUM03_motamen_week5 | /model_deploy_using_html_form.py | UTF-8 | 782 | 2.71875 | 3 | [
"MIT"
] | permissive | from flask import Flask, render_template, request
import pickle
import numpy as np
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/predict' , methods = ['POST'])
def tumor_predict():
model = pickle.load(open('model.pkl' , 'rb'))
int... | true |
ebcf7316e577b5dad2e2284e1ab524db64d0d170 | Python | nicolopinci/6DOF | /Vision system/ballRecognition.py | UTF-8 | 4,900 | 3.125 | 3 | [] | no_license | """
Computer vision system for the detection of the ball position and velocity.
"""
import numpy as np
import cv2
from collections import deque
import imutils
from datetime import datetime
import math
from tkinter import *
def getCurrentRoll():
return 0
def getCurrentPitch():
return 0
def stabilizeCente... | true |
84aa8b043f5acd79ec051c0241b95dc7851afaa5 | Python | Yejin6911/Algorithm | /백준/BJ_1260.py | UTF-8 | 1,193 | 3.53125 | 4 | [] | no_license | import sys
from collections import deque
n, m, v = map(int, sys.stdin.readline().rstrip().split())
graph = [[] for _ in range(n+1)]
for i in range(m):
v1, v2 = map(int, sys.stdin.readline().rstrip().split())
# 양방향이기 때문에 양쪽에 다 넣어주어야 한다.
graph[v1].append(v2)
graph[v2].append(v1)
# 숫자가 작은 점부터 조회할 수 있도록 정... | true |
4e739a5642ccacb45895c05da2553be1fe75fe77 | Python | Ilgrim/cwmud | /cwmud/core/items.py | UTF-8 | 3,533 | 2.734375 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
"""Item management and containers."""
# Part of Clockwork MUD Server (https://github.com/whutch/cwmud)
# :copyright: (c) 2008 - 2017 Will Hutcheson
# :license: MIT (https://github.com/whutch/cwmud/blob/master/LICENSE.txt)
from collections import Counter
from .attributes import Attribute, ListA... | true |
d56f61c624424aa16dbda193d9b44aa754b4c235 | Python | BrianHerron-exe/CS103 | /lab-bmplib/lab-bmplib/compile | UTF-8 | 1,236 | 2.546875 | 3 | [] | no_license | #!/usr/bin/python
#-*- mode: python -*-
"""
Usage:
compile foo # runs clang++ <options> foo.cpp -o foo
compile foo.cpp # same as previous
compile foo.cpp bar.cpp baz.o -o bar # clang++ <options> <args>
For installation instructions, see
http://bits.usc.edu/cs103/compile/
Contact: dpritcha@usc.edu
"""
def... | true |
7972df936501804d6fd40b22450ae95fa5b7dd12 | Python | xfroggy/NOAA-Hurricane-RISK-predictor---local | /models.py | UTF-8 | 2,847 | 3.375 | 3 | [] | no_license | from datetime import timedelta
import math
def get_hits(data, my_location, radius):
#filter for only storms that became hurricanes
df_hu = data[data['status'] == 'HU']
#full list of storms
hurricane_dt = data
#sorted by unique storm identifier
id = df_hu['identifier'].unique()
# array ... | true |
024d6360e5b6cd06fca597eea47812776cc01e13 | Python | Ritvik09/My-Python-Codes | /Python Codes/Problems & Solutions/16..py | UTF-8 | 233 | 3.578125 | 4 | [] | no_license | v = input("Enter a verb: ")
a = input("Enter an adjective: ")
n = input("Enter a noun: ")
print("Jeeves " + v + " my " + a + " " + n + " out of the " + n + " as if he were a vegetarian fishing a " + n + " out of his salad.")
| true |
9980a770a6a1adb3b72a9936fd6f452ae6742f5a | Python | hackjoy/learn_cryptography | /cryptohack/encoding/decimalToAscii.py | UTF-8 | 245 | 2.578125 | 3 | [] | no_license | from Cryptodome.Util.number import long_to_bytes
number = 11515195063862318899931685488813747395775516287289682636499965282714637259206269
print(long_to_bytes(number)) # this somehow converted all the way to ascii rather than the raw bytes..
| true |
bfea29acbefb48c5033fa07a55e6457b91229a1c | Python | cjwcommuny/pybetter | /pybetter/global_function_replacer.py | UTF-8 | 484 | 2.921875 | 3 | [
"MIT"
] | permissive | from contextlib import contextmanager
class replace_attribute:
def __init__(self, obj, attr_name: str, new_attr):
self.obj = obj
self.attr_name = attr_name
self.new_attr = new_attr
self.__temp = None
def __enter__(self):
self.__temp = getattr(self.obj, self.attr_name)
... | true |
a123e0e656e312f76bee0b5873983a907d86fbb9 | Python | keyi/Leetcode_Solutions | /Algorithms/Python/Word-Break-II.py | UTF-8 | 1,025 | 3.0625 | 3 | [] | no_license | class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: Set[str]
:rtype: List[str]
"""
def check(word):
if not word:
return True
arr = [False for i in range(len(word))]
for i in r... | true |
f2e381e6801ec5698ccf79056d0e707fde583dee | Python | nax1016cs/ML | /iris.py | UTF-8 | 12,961 | 2.734375 | 3 | [] | no_license | import numpy as np
import pandas as pd
import math
import random
df =pd.read_csv("iris.data", header = None, names = ["sepal_length","sepal_width","petal_length", "petal_width", "name"])
df = df.sample(frac=1).reset_index(drop=True)
name = ["Iris-setosa","Iris-versicolor","Iris-virginica"]
feature = ["sepal_... | true |
e12336ab71fedd856d3dd3582e055ad805d97c3f | Python | PacktPublishing/Learning-Concurrency-in-Python | /Chapter 03/forking.py | UTF-8 | 330 | 3.25 | 3 | [
"MIT"
] | permissive | import os
def child():
print("We are in the child process with PID= %d"%os.getpid())
def parent():
print("We are in the parent process with PID= %d"%os.getpid())
newRef=os.fork()
if newRef==0:
child()
else:
print("We are in the parent process and our child process has PID= %d"%newRef)
... | true |
888ce47cfb264e98dddc737ae75c3f75df4acebc | Python | doan97/BSC | /Hille/exp/gamma/targets.py | UTF-8 | 3,470 | 2.953125 | 3 | [] | no_license | import numpy as np
# TODO write docstrings
class Target:
def __init__(self, position, stop_iteration):
self.position = position
self.stop_iteration = stop_iteration
def __iter__(self):
return self
def __next__(self):
raise NotImplementedError('create target subclass')
... | true |
533dd62b6fe0c915917e38ed0a321409b50e48cf | Python | vyahello/python-decorators-cheetsheet | /materials/decorate_class_method.py | UTF-8 | 742 | 3.890625 | 4 | [
"Apache-2.0"
] | permissive | def trace(method):
def wrapper(*args, **kwargs):
method_name = method.__name__
class_name = args[0].__class__.__name__
print(f'Entering "{method_name}" method in "{class_name}" class instance')
print(f'"{method_name}" class method takes [{args}, {kwargs}] args')
result = meth... | true |
e915717fcd42194c2f6828a4ea8e8ca51723bf0a | Python | 18haddadm/PythonProject1 | /menugenerator.py | UTF-8 | 104 | 3.125 | 3 | [] | no_license | import random
def food():
food = ["eggs", "milk", "candy"]
print (random.choice(food))
food ()
| true |
c0a9ea056083882be07ab435845b337a33dc6b32 | Python | nolanlum/kochira | /kochira/services/textproc/americanize.py | UTF-8 | 2,436 | 2.671875 | 3 | [
"MS-PL"
] | permissive | """
Passive-aggressive spelling corrector.
Ensures that users are using Freedom English. Could be configured for other
languages, I guess...
"""
import enchant
import re
from textblob import TextBlob
from nltk.corpus import wordnet
from kochira import config
from kochira.service import Service, background, Config
... | true |
76977b2b54ea8057fd26d9807bee881e63355a62 | Python | zzhaoiii/caculate | /caculate_acc.py | UTF-8 | 7,329 | 2.765625 | 3 | [] | no_license | import xml.etree.ElementTree as ET
import os
import shutil
import cv2
import json
CLASSES = []
def convert(xml_file):
tree = ET.parse(xml_file)
root = tree.getroot()
objects = root.findall('object')
gt = []
for element in objects:
org_name = element.find('name').text
... | true |
84e94cdb8aa1d7570e4350de0f452ce50d9d3a67 | Python | okekefrancis112/PythonEncyclopedia | /proandissuesc.py | UTF-8 | 947 | 2.609375 | 3 | [] | no_license | from requests.auth import HTTPBasicAuth
import json
import requests
def get_project(domain_name,auth,headers, project_key):
url = f"https://{domain_name}.atlassian.net/rest/api/latest/project/{project_key}"
response = requests.request("GET", url, headers=headers, auth=auth)
log = json.loads(response.text)... | true |
4e1b3b45983679b192e1118119d0050f115c4e43 | Python | AdamZhouSE/pythonHomework | /Code/CodeRecords/2846/60677/234652.py | UTF-8 | 116 | 2.953125 | 3 | [] | no_license | n=input()
x=list(set(input().split()))
y=x.__len__()
for i in x:
if i=="0":
y-=1
break
print(y)
| true |
2a2bbe882cd75858bbe13e628cab8a758ab1cf0e | Python | akhilsai0099/Python-Practice | /Sorting_algorithms/sorting_visualizer1.py | UTF-8 | 6,622 | 2.953125 | 3 | [] | no_license | import pygame
import random
pygame.font.init()
screen = pygame.display.set_mode((900,650))
pygame.display.set_caption("Sorting Visualisation")
run = True
width = 900
height = 600
array = [0]*151
arr_clr = [(0, 204, 102)]*151
clr_ind = 0
clr = [(0, 204, 102), (255, 0, 0),
(0, 0, 153), (255, 102, 0)]
TIME = 20
fnt = ... | true |
09c9c62a28f3a0222d2df65551bcb62fea8e69ab | Python | Xiaoctw/LeetCode1_python | /字符串/把数字翻译成字符串_面试题46.py | UTF-8 | 456 | 3.421875 | 3 | [] | no_license | class Solution:
def translateNum(self, num: int) -> int:
"""
不要首先考虑搜索,动态规划更好用
:param num:
:return:
"""
p, q = 1, 1
num_str = str(num)
for i in range(1, len(num_str)):
p, q = q, p + q if 10 <= int(num_str[i - 1:i + 1]) <= 25 else q
r... | true |
69af492b95693ff480f2c2e28242a816aac36419 | Python | PaulEcoffet/ipynbviewer | /src/ipynbviewer/ipynbview.py | UTF-8 | 747 | 3 | 3 | [
"MIT"
] | permissive | import json
import argparse
from .cell_readers import cell_readers
def read_ipynb(ipynb_dict: dict)-> str:
"""
Reads a whole notebook and output it in a human readable format
:param ipynb_dict:
:return: the human readable string
"""
outstr = []
try:
cells = ipynb_dict["cells"]
... | true |
48f67aff4b0cdc61e15749ff2f85a01430a384fa | Python | subutux/gusic | /lib/core/SearchCompletion.py | UTF-8 | 2,377 | 2.59375 | 3 | [] | no_license | # This file is part of gusic.
# gusic is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# gusic is distributed in the hope that it wil... | true |
afe769582b87e9c490c33dfb458bdb0e618bbe70 | Python | adalloul0928/Leetcode_Hell | /Archive/Amazon/minPathSum.py | UTF-8 | 698 | 3.28125 | 3 | [] | no_license | class Solution:
def minPathSum(self, grid) -> int:
rowLen = len(grid)
colLen = len(grid[0])
newGrid = [[0 for x in range(colLen)] for y in range(rowLen)]
newGrid[0][0] = grid[0][0]
for ind in range(1, colLen):
newGrid[0][ind] = newGrid[0][ind-1] + grid[0][ind]
... | true |
bb4b69505c115ef4b8b73fe435b1f1402611d0d1 | Python | Fxztam/sierra | /src/sierra/tTags.py | UTF-8 | 8,197 | 2.84375 | 3 | [
"Apache-2.0"
] | permissive | import traceback
class div():
def __init__(self, div_class=None, attr=None):
self.div_class = div_class
if div_class == None:
with open('index.html', 'a+') as f:
f.write("\n<div")
else:
with open('index.html', 'a+') as f:
f.write(f"\n... | true |
6a82ebe0257c5a01d110bc9deb3ee19ed19e49d3 | Python | Jackjet/pythonpachong | /代理ip/DL.py | UTF-8 | 2,354 | 2.703125 | 3 | [] | no_license | import requests
import re
import os
import time
class D(object):
def __init__(self):
self.url='https://www.kuaidaili.com/free/inha/'
def getIP(self,page):
'''
:param page: 页数
:return:
爬取ip代理
'''
head={
'User-Agent': 'Mozilla/5.0 (... | true |
74be3097c74eb9d29b28a63793231ef2b8418b74 | Python | cristianosoriopaz/Super-Mario | /proyecto mario/juego.py | UTF-8 | 84,370 | 2.625 | 3 | [] | no_license | import tkinter
import tkinter.ttk
import winsound
#creacion y titulacion de la ventana
v = tkinter.Tk()
v.title("Super Mario Game")
#inicializacion de variables de los enemigos y mario ademas de otras funcionalidades como sus limites en saltos, entre otras
posxm = 400
final=0
finall=0
both=0
nombres=[]
pare... | true |
bfbdedcb7c4212f38c38d17b88ee935fbf7a5b71 | Python | zengchenchen/OJ-Practice | /11.Cotainer with Most Water.py | UTF-8 | 379 | 3.125 | 3 | [] | no_license | class Solution(object):
def maxArea(self, height):
i, j, S = 0, len(height) - 1, 0
while j > i:
s = (j - i) * min(height[i], height[j])
S = max(S, s)
if height[i] < height[j]:
i = i + 1
else:
j = j - 1
return S
... | true |
417cca6f6e05aa711d929aed3442559badab4fca | Python | chittoorking/Top_questions_in_data_structures_in_python | /python_program_to_copy_odd_lines_of_one_file_to_other.py | UTF-8 | 397 | 2.578125 | 3 | [] | no_license | fhandle1=open('G:\Desktop\Dta structures and algorithms using python\Top_interview_questions_in_data_structures_in_python\\all_lines.txt')
fhandle2=open('G:\Desktop\Dta structures and algorithms using python\Top_interview_questions_in_data_structures_in_python\\vamsi.txt','w')
count=1
for line in fhandle1:
if ... | true |
47d1f81d362d7ee99e3d132e5a4e516aa50c3375 | Python | ZNNNNZ/pratice_code | /code21.py | UTF-8 | 1,046 | 3.65625 | 4 | [] | no_license | '''
大数乘法
大数指超过int64_t 可承载范围的数字
输入描述:
输入两行数n1, n2 (0 < n* < 2^100)
输出描述:
输出两数之积
输入例子1:
2
3
输出例子1:
6
输入例子2:
9223372024429430685
34223371424429430685
输出例子2:
315654886577740006976078312593219569225
'''
class Solution:
def mul_longnums(self,n1,n2):
len1=len(n1)
len2=len(n2)
new_list=[0]*(le... | true |
cfc72f6d70a0c8e6b6cb5ae57e752233549976cb | Python | Brimes7/recursive-sorting | /src/recursive_sorting/recursive_sorting.py | UTF-8 | 3,394 | 4.34375 | 4 | [] | no_license | # TO-DO: complete the helper function below to merge 2 sorted arrays
# arrA = [1, 3, 5, 7]
# arrB = [2, 4, 6, 8]
def merge(arrA, arrB):
elements = len(arrA) + len(arrB)
merged_arr = [0] * elements
# Left
x = 0
# right
y = 0
# new array
z = 0
# Your code here
# This will travers... | true |
ef61094adc98ca4e37e2dc917d27f53566224dfc | Python | liuguoyou/gtnet | /utils/os.py | UTF-8 | 212 | 2.765625 | 3 | [] | no_license | import os
import json
def makedir(dir_path):
if not os.path.exists(dir_path):
os.makedirs(dir_path)
def load_json(dict_path):
with open(dict_path) as f:
dict_data = json.load(f)
return dict_data
| true |
0f9e2590f1fe25a9ee27162f9d17bac8c9b9fbc2 | Python | blopblopy/excel_manipulations | /cluster/test_cluster.py | UTF-8 | 2,520 | 2.9375 | 3 | [] | no_license | import unittest
import cluster
from cluster import Vector, Cluster
class ClusterAlgoTest(unittest.TestCase):
def test_one(self):
center = cluster.Vector("1",[0,0,0])
points = set([center])
expected_clusters = cluster.Cluster(center=center, covers=set([center]))
result_clusters = ... | true |
17c7fd497eef364ec95fcc9210bf8e5627108097 | Python | jwodder/ghutil | /src/ghutil/regex.py | UTF-8 | 2,059 | 2.671875 | 3 | [
"MIT"
] | permissive | #: Regular expression for a valid GitHub username or organization name. As of
#: 2017-07-23, trying to sign up to GitHub with an invalid username or create
#: an organization with an invalid name gives the message "Username may only
#: contain alphanumeric characters or single hyphens, and cannot begin or end
#: with ... | true |
db2c8f46c22155ec0948fb61ae58d88c0ca696b8 | Python | Maplexc/UQ-IT | /CSSE7030/assign1/a1.py | UTF-8 | 7,824 | 3.890625 | 4 | [] | no_license | #!/usr/bin/env python3
## assignment 1 in 1 line
## enrypt = lambda string, offset: "".join([chr((ord(char) - ord('A') + offset) % ord('A')) for char in string])
"""
Assignment 1
CSSE1001/7030
Semester 2, 2018
"""
import a1_support
import string
from a1_support import is_word_english
__author__ = "Xin Chen 4518991... | true |
fc868a4ad73c0649342f962aaf820c62cd07a3a3 | Python | ahmedramzygi/Website-Blocker | /WebSite_Blocker.py | UTF-8 | 1,059 | 2.578125 | 3 | [] | no_license | import time
from datetime import datetime as dt
hosts_file= r"C:\Windows\System32\drivers\etc\hosts"
hosts_temp=r"C:\Users\aeram\Desktop\Projects\PythonBlocker\hosts"
redirect="127.0.0.1"
blocked_sites=["www.facebook.com","www.instagram.com"]
while(True):
if dt(dt.now().year,dt.now().month,dt.now().day,17) < dt.... | true |
1c9618aa0d9197c0509bd6a26715e339a70c9d3b | Python | ivankohut/spravodaj | /booklet-tool/classes.py | UTF-8 | 4,537 | 2.859375 | 3 | [] | no_license | from PyPDF2 import PdfFileReader, PdfFileWriter
from PyPDF2.pdf import PageObject
from collections.abc import Iterable
class OutputFiles:
def __init__(self, *files):
self.__files = files
def write(self):
for file in self.__files:
file.write()
class OutputPdfFileWithSuffix:
d... | true |
9ff66d5826297d51a9c84e600c4b5fa4a3620532 | Python | iamsuryakant/100-days-of-code | /PYTHON/text_wrap.py | UTF-8 | 388 | 3.75 | 4 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 29 19:42:16 2020
@author: Suryakant Thakur
HackerRank Text Wrap problem
https://www.hackerrank.com/challenges/text-wrap/problem
"""
import textwrap
def wrap(string, max_width):
return textwrap.fill(string,max_width)
if __name__ == '__main__':
string, max_width =... | true |
f305c2f3c569756d56c2ca02b633ce4352c98f9c | Python | patmanteau/sql2graph | /sql2graph/graph.py | UTF-8 | 5,029 | 2.75 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
#
# Copyright 2013 Paul Tremberth, Newlynn Labs
# See LICENSE for details.
import collections
import schema
# ----------------------------------------------------------------------
class DictLookup(object):
def __init__(self):
self.container = {}
def append(self, entity, enti... | true |
9bdb150e1d10ebbdb0479011517e3d25527c1a96 | Python | lrq3000/pyFileFixity | /pyFileFixity/lib/profilers/visual/runsnakerun/squaremap/squaremap.py | UTF-8 | 21,515 | 2.890625 | 3 | [
"MIT"
] | permissive | #! /usr/bin/env python
import wx, sys, os, logging, operator
import wx.lib.newevent
log = logging.getLogger( 'squaremap' )
#log.setLevel( logging.DEBUG )
SquareHighlightEvent, EVT_SQUARE_HIGHLIGHTED = wx.lib.newevent.NewEvent()
SquareSelectionEvent, EVT_SQUARE_SELECTED = wx.lib.newevent.NewEvent()
SquareActivationEven... | true |
8324fa28f571944426acc35ad5f1ee6b0cbd945d | Python | Krispy2009/work_play | /sb2.py | UTF-8 | 3,672 | 3.4375 | 3 | [] | no_license |
from string import ascii_lowercase
import sys
global finished
global queue
global my_words
queue = []
class Node:
def __init__(self, word, parent=None):
self.word = word
self.children = []
self.parent = parent
def get_children(self):
global my_words
#change the word ... | true |
0168715b4c52906c130662e8ecbb11b04cbe6551 | Python | sashkab/updaters | /pip_depend.py | UTF-8 | 471 | 2.671875 | 3 | [] | no_license | #!/usr/bin/env python
# Dependency finder for python packages
import pip
from pprint import pprint
d = {}
for dist in pip.get_installed_distributions():
p = dist.project_name
rev_dep = [
pkg.project_name for pkg in pip.get_installed_distributions() if p in
[requirement.project_name for requ... | true |
32bd1bfad6a6ce89562a12dc09a313f70ffc4114 | Python | Gu-Youngfeng/Config-Optimization | /experiments/min_flash.py | UTF-8 | 1,475 | 3.15625 | 3 | [
"Apache-2.0"
] | permissive | #!\usr\bin\python
# coding=utf-8
# Author: youngfeng
# Update: 07/17/2018
"""
This code is used to find the lowest rank in validation pool (top-10) by using flash method
"""
import sys
sys.path.append("../")
import os
from Flash import find_lowest_rank
from Flash import predict_by_flash
from Flash import split_data_b... | true |
a4dc1e68f1666f70c0ba0f73113fde616bf7b41b | Python | slauniainen/pyAPES-MXL | /wind_profile_inoue.py | UTF-8 | 630 | 2.65625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Thu May 16 12:45:13 2019
@author: slauniai
"""
import numpy as np
import matplotlib.pyplot as plt
#: machine epsilon
EPS = np.finfo(float).eps
Uo = 0.1
usto = 0.1
LAI = 5.0
a = LAI / 2.0
hc = 0.1
N = 20
dz = hc / N
z = np.arange(0, hc + dz, dz)
tau = usto**2 * np.exp(2*a*(z /... | true |
db293663fe920cbde83da9d297bd213f3474907c | Python | xiantang/AsianGames | /MedalRankRobot.py | UTF-8 | 779 | 2.546875 | 3 | [] | no_license | import json
import re
from lxml import etree
from WebRequest import WebRequest
class MedalRankRobot(WebRequest):
def __init__(self, start_url):
super().__init__()
self.start_url = start_url
def parse_start_html(self):
raw_json = self.get(self.start_url).text
raw_json = re.fi... | true |
8505a0a29430cb2630e68180078dc937df0a6c6d | Python | Mahad-Khan/Verification_API | /pipeline/utils/pdf417reader.py | UTF-8 | 1,464 | 2.703125 | 3 | [] | no_license | import zxing
import os
from PIL import Image
import sys
# get barcode directory full path
test_barcode_dir = os.path.join(os.path.dirname(__file__), "barcodes")
# get actual barcodereader
test_reader = zxing.BarCodeReader()
# filenames = ["vert_rev", "vert_norm", "horz_right", "horz_left"]
filenames = ["... | true |
adb7d3ce201a3df94010d0fe4c543b3044e4b191 | Python | bajram-a/Basic-Programing-Examples | /Inputs and Basic Math/Exercise1.2.py | UTF-8 | 245 | 3.65625 | 4 | [] | no_license | """Write a program that takes from the user a value 'r' that signifies a radius.
The program then calculates the surface area of the circle and its circumference"""
from math import pi
r = float(input())
sur_area = r**2 * pi
cir = 2 * pi * r
| true |
29c4939e576d583c7582bbc890dc704d92c8f6c8 | Python | rkuo2000/cv2 | /jpg_houghlinesP.py | UTF-8 | 453 | 2.6875 | 3 | [] | no_license | import numpy as np
import cv2
img = cv2.imread('testpic.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
edge = cv2.Canny(blur, 100, 200)
cv2.imshow("edge", edge)
lines = cv2.HoughLinesP(edge, 1, np.pi/180, 100)
print(lines)
for i in range(0, len(lines)):
for x1,y1,x2... | true |
bc828fbc7227dac4cdfee351ffc690ab299bf2ea | Python | awslabs/aws-emr-launch | /examples/spark_batch_orchestration/infrastructure/emr_orchestration/steps/data_preparation.py | UTF-8 | 2,572 | 2.671875 | 3 | [
"MIT-0",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | import argparse
import functools
import sys
import boto3
from pyspark.sql import SparkSession # noqa
from pyspark.sql import functions as F # noqa
def union_all(dfs):
return functools.reduce(lambda df1, df2: df1.union(df2.select(df1.columns)), dfs)
def parse_arguments(args):
parser = argparse.ArgumentPar... | true |
be85be354798334c2e42afe2440c847bde1f6876 | Python | lirun-sat/brahe | /brahe/astro.py | UTF-8 | 12,441 | 3.28125 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
"""This module provides functions to convert between different representations
of orbital coordinates. As well as functions to compute properties of the orbits
themselves.
"""
# Imports
import logging
import typing
import math as math
import copy as copy
import numpy as np
# Brahe Imports... | true |
5b12bc77e20454d73602c713a0ecf1aba71c0458 | Python | epistimos/opendata-client-samples-python | /sample_revocation_request.py | UTF-8 | 910 | 2.859375 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import opendata
# ADA of the decision to revoke
ada = u'ΑΔΑ...'
# Comment for the revocation request
comment = "reason..."
# Send request
client = opendata.OpendataClient()
client.set_credentials('10599_api', 'User@10599')
response = client.sub... | true |
04a1a95916762c652dfd106eb04d54d53585cd70 | Python | EightFawn/GruppoScommesseBot | /plugins/random_gioco.py | UTF-8 | 753 | 2.828125 | 3 | [] | no_license | import random
from pyrogram import Client, filters
from config.variabili import chatScommesse
@Client.on_message(filters.command("random") & filters.chat(chatScommesse) | filters.regex(r"^Random ❓$"))
def gioco_random(_, message):
giochi = ["Carte", "Tiro Con L'Arco", "Freccette", "Rune", "Dado"]
modalita = ... | true |
13a49964fa9e908068c82ea217b21ef99d32424e | Python | toreis/ML | /fapprox_q_replay_fixedtarget.py | UTF-8 | 10,846 | 2.90625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
@author: ligraf
basic code from: https://keon.io/deep-q-learning/
target net from: https://towardsdatascience.com/reinforcement-learning-w-keras-openai-dqns-1eed3a5338c
"""
import random
import gym
import numpy as np
import pandas as pd
from collections import deque
from... | true |
ef912acd1a87b58b4041a84f6d855692a1907bba | Python | calvetalex/codewars | /python/unique/index.py | UTF-8 | 192 | 3.3125 | 3 | [] | no_license | def unique_in_order(iterable):
if not iterable:
return []
res = [iterable[0]]
return res + [it for i, it in enumerate(iterable[1:], start=1) if it is not iterable[(i - 1)]] | true |
a333511402c73d363fd42d6f37a493ed6758a732 | Python | cambridgeltl/jp-pred-arg | /bp_pas/ling/pas.py | UTF-8 | 1,202 | 3.265625 | 3 | [
"MIT"
] | permissive | class PAS(object):
def __init__(self, pred, args):
self.pred = pred
self.args = args
def prd_index(self):
return self.pred.word_index
def __str__(self):
pstr = "{}({}) -> ".format(self.pred.word_form,
self.pred.word_index)
for arg... | true |
ba47c17d014ae19113e5a2861a7b63d763cb4084 | Python | hmchen47/Programming | /Python/MIT-CompThinking/MITx600.1x/Quiz/final-2015/p3-1.py | UTF-8 | 511 | 3.46875 | 3 | [] | no_license | #!/usr/bin/env python2
# _*_ coding: utf-8 _*_
def sort1(lst):
swapFlag = True
iteration = 0
while swapFlag:
swapFlag = False
for i in range(len(lst)-1):
if lst[i] > lst[i+1]:
temp = lst[i+1]
lst[i+1] = lst[i]
lst[i] = temp
... | true |
ce52390dc68472019b82adb3b4c08a2fffdbb473 | Python | zhora0412/py-crypt | /finalProject/venv/Lib/site-packages/tests/test_configuration.py | UTF-8 | 2,517 | 2.609375 | 3 | [] | no_license | import functools
import os
from pathlib import Path
import pytest
from smtpdfix.configuration import Config
values = [
("host", "mail.localhost", "mail.localhost", str),
("port", 5025, 5025, int),
("port", "5025", 5025, int),
("login_name", "name", "name", str),
("login_password", "word", "word",... | true |
50764a242d0eef672e750dcfde1d0196042178e9 | Python | 2heeesss/Problem_Solving | /reBOJ/1339.py | UTF-8 | 1,763 | 3.375 | 3 | [] | no_license | # import sys
# input = sys.stdin.readline
# n = int(input())
# arr = []
# for _ in range(n):
# arr.append(list(input().rstrip()))
# wordArr = [0]*10
# wordSize = 9
# result = 0
# while True:
# maxLength, maxIndex = 0, 0
# for i in range(len(arr)):
# if len(arr[i]) > maxLength:
# maxLe... | true |
dde9596739b296b43b51e1d7c84c2ddfded4c3d4 | Python | yeon4032/STUDY | /GIT_NOTE/03_python/chap08_MariaDB/exams/exam01.py | UTF-8 | 2,135 | 3.5 | 4 | [] | no_license | '''
문제1) goods 테이블을 이용하여 다음과 같은 형식으로 출력하시오.
<조건1> 전자레인지 수량, 단가 수정
<조건2> HDTV 수량 수정
[ goods 테이블 현황 ]
1 냉장고 2 850000
2 세탁기 3 550000
3 전자레인지 5 400000 <- 수량, 단가 수정
4 HDTV 2 1500000 <- 수량 수정
전체 레코드 수 : 4
[ 상품별 총금액 ]
냉장고 상품의 총금액은 1,700,000
세탁기 상품의 총금액은 1,650,000
전자레인지 상품의 총금액은 2,000,000
HDTV 상품의 총금액은 3,000... | true |
a036e35e4679a8f561435daed4a29b7eb97827e0 | Python | sarvenderdahiya/leetcode_solutions | /My solutions/1122_Relative_sort_array.py | UTF-8 | 1,806 | 3.421875 | 3 | [
"MIT"
] | permissive | from typing import List
class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
out = []
arr1.sort()
for i in range(len(arr2)):
pos1 = -1
pos2 = -1
lo = 0
hi = len(arr1) - 1
# To find first occ... | true |
200b72f7be22a879a36dbcdf19fafe1de97439f7 | Python | prihoda/bgc-pipeline | /bgc_detection/evaluation/prediction_plot.py | UTF-8 | 2,704 | 3.1875 | 3 | [
"MIT",
"BSD-3-Clause",
"Python-2.0",
"GPL-2.0-only",
"Apache-2.0",
"GPL-3.0-only",
"LicenseRef-scancode-biopython"
] | permissive | #!/usr/bin/env python
# David Prihoda
# Plot prediction probability output, producing a line plot with protein domains on x-axis and prediction value on y-axis
import argparse
import matplotlib.pyplot as plt
import pandas as pd
def count_y_clusters(y):
prev = 0
clusters = 0
for val in y:
if val ==... | true |
2102a631351e26e87277452516b0a90c96136ffc | Python | KarenWest/pythonClassProjects | /insertNewLinesTypeWriter.py | UTF-8 | 5,593 | 3.859375 | 4 | [] | no_license | '''
Imagine a typewriter: whenever it's in the middle of a word, and reaches its
desired line length, the internal bell rings. This signifies to the typist
that after finishing the current word, a newline must be manually inserted.
We ask you to emulate this process such that a newline is inserted as required
after eac... | true |
56b0201e448df1ba10fb88fe7bacebf23507a98f | Python | AlfredKai/KaiCodingNotes | /LeetCode/Hard/124. Binary Tree Maximum Path Sum.py | UTF-8 | 1,403 | 3.546875 | 4 | [] | no_license | 1044. Longest Duplicate Substring
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
import math
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
def helpe... | true |
11b21bbf9d24ac3867bd709091f7019f6e722602 | Python | fabriciocravo/Animals10 | /DataAnalysis/PercentageOfSucessfullAttacks.py | UTF-8 | 2,269 | 2.59375 | 3 | [
"MIT"
] | permissive | import os
import cv2
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import pickle as pkl
import cv2 as cv
# Needed for pickle loading!!!
from ResNet import ResNet
from VGG import VGG
from GoogLeNet import GoogLeNet
from AlexNet import AlexNet
# Parameters ######################... | true |
8cd5db8caaae6d93ab7bbcec9b982032c488ca2c | Python | RobertNeuzil/sandbox | /mulchoice.py | UTF-8 | 1,403 | 3.734375 | 4 | [] | no_license | class Multiple_Choice:
def __init__(self, question, correctanswer, answer2, answer3, answer4):
self.question = question
self.correctanswer = correctanswer
self.answer2 = answer2
self.answer3 = answer3
self.answer4 = answer4
one = Multiple_Choice("What color is the sky? ", "blue", "red", "green", "yellow")
t... | true |
3ddd65df5f592e6728f44ec6911ce0c4676ff340 | Python | Matmonsen/py-yr | /py_yr/weatherdata/links/links.py | UTF-8 | 907 | 2.796875 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
from .link import Link
class Links(object):
def __init__(self, links):
self.xmlSource = Link(links['link'][0])
self.xmlSourceHourByHour = Link(links['link'][1])
self.overview = Link(links['link'][2])
self.hourbyhour = Link(links['link'][3])
self.lon... | true |
295e5db1cd439fb334e1449fde5b1e60b10bac24 | Python | HBinhCT/Q-project | /hackerearth/Math/Number Theory/Basic Number Theory-1/Connected Components/solution.py | UTF-8 | 838 | 2.78125 | 3 | [
"MIT"
] | permissive | from sys import stdin
mod = 1000000007
def combine(comb, inv_comb, x, y):
return comb[x] * (inv_comb[x - y] * inv_comb[y] % mod) % mod
t = int(stdin.readline())
cases = []
size = 0
for _ in range(t):
n, m, c = map(int, stdin.readline().strip().split())
cases.append((n, m, c))
size = max(size, n, m,... | true |
61ec729aaf9e88913870aad76cd12d9f2db8d2d2 | Python | digital101ninja/pythonAutomateTasks | /pythonAutomate/ch7Regex.py | UTF-8 | 2,262 | 3.265625 | 3 | [] | no_license | #!/usr/bin/python
import re
phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
mo = phoneNumRegex.search('My number is 415-555-4242')
print "Phone number found:" + mo.group()
print "Area code is:" + mo.group(1)
batRegex = re.compile(r'Bat(man|mobile|copter|bat)')
mo = batRegex.search('Batcopter does not exist... | true |
8ee20553e61883dc17835e8a6d69f5ccdea8d3dd | Python | dythebs/happygoat | /backend/src/main/java/csu/edu/happygoat/spider/hunyanjiudiansousuo.py | UTF-8 | 1,910 | 2.578125 | 3 | [] | no_license | import requests
from bs4 import BeautifulSoup
import json
import re
import sys
url = sys.argv[1]
base_url = re.findall('(https://.*?/HunYan)', url)[0]
html = requests.get(url).text
soup = BeautifulSoup(html, "html.parser")
def trim(str):
return str.replace(' ', '').replace('\n', '').replace('\r', '')
lis = soup... | true |
3561d2eed8f7386fe2ed227fd25183577773a9e8 | Python | YanzheL/CatchU | /multiproc_model/consumer.py | UTF-8 | 1,956 | 2.609375 | 3 | [] | no_license | import six
import abc
from utils.logger_router import LoggerRouter
from utils.counter import Counter
@six.add_metaclass(abc.ABCMeta)
class Consumer:
global_running = True
all_stopped = Counter('Consumer')
@classmethod
def from_name(cls, name, **kwargs):
for sub_cls in cls.__subclasses__():
... | true |
3ce996947dd302c55552ff068ef78c670955e0f5 | Python | Penguin2600/mtp_breaker | /mtp.py | UTF-8 | 5,849 | 2.953125 | 3 | [] | no_license | import sys
import os
def rawxor(a, b):
"""xor two strings of different length"""
if len(a) > len(b):
return [x ^ y for (x, y) in zip(a[:len(b)], b)]
else:
return [x ^ y for (x, y) in zip(a, b[:len(a)])]
def decify(hexstring):
intarray = [int(hexstring[i:i+2], 16)
for ... | true |
aa0cba014a34b5c9bff9415c353e5b23c060b444 | Python | 02stevenyang850527/ML2017 | /hw3/grad_ascent.py | UTF-8 | 2,240 | 2.625 | 3 | [] | no_license | import matplotlib.pyplot as plt
from keras.models import load_model
from keras import backend as K
import numpy as np
NUM_STEPS = 20
RECORD_FREQ = 5
def normalize(x):
# utility function to normalize a tensor by its L2 norm
return x / (K.sqrt(K.mean(K.square(x))) + 1e-7)
def grad_ascent(num_step,input_image_da... | true |
a32561a522b6324eb471f93b2a7f7855d6b810cc | Python | jayrshah98/ASE-HW1 | /src/hw3/LIB.py | UTF-8 | 3,149 | 2.8125 | 3 | [
"MIT"
] | permissive | import math
import random
import re
import sys
from pathlib import Path
import config
lo = float('inf')
hi = float('-inf')
seed = 937162211
class LIB:
def __init__(self):
pass
def rint(self, lo, hi):
return math.floor(0.5 + self.rand(lo,hi))
def rand(self,lo, hi):
global seed
... | true |
cd5f23b7b7d336be09837689e487a2fe181bf5c3 | Python | Andrewlearning/Leetcoding | /leetcode/Math/264. 丑数II(第n个丑数,DP).py | UTF-8 | 1,317 | 4.09375 | 4 | [] | no_license | """
Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
一个数仅由 2,3,5的乘积构成
"""
class Solution(object):
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
if n < 1:
return n
res... | true |
766f1cdae4ca8ca4dea7374423d6d5bff6f58b8c | Python | JannaKim/PS | /DFS&BFS/음료수얼려먹기.py | UTF-8 | 499 | 2.8125 | 3 | [] | no_license | N, M = map(int, input().split())
mp=[]
mp.append([1]*(M+2))
for _ in range(N):
mp.append([1]+[int(i) for i in input()]+[1])
mp.append([1]*(M+2))
# [print(i) for i in mp]
dx=[0,0,1,-1]
dy=[1,-1,0,0]
def dfs(i,j):
mp[i][j]=1
for x, y in zip(dx,dy):
if mp[i+x][j+y]==0:
dfs(i+x,j+y)
cnt=0... | true |
30ae304892ff4510e6169c2d708b932ece5cd5cf | Python | yuanhuiru/xnr2 | /xnr_0429/xnr/cron/fb_xnr_operate/social_sensing/get_keywords.py | UTF-8 | 1,476 | 3.5 | 4 | [] | no_license | # -*-coding:utf-8-*-
from textrank4zh import TextRank4Keyword,TextRank4Sentence
def extract_keyword(text):
word = TextRank4Keyword()
word.analyze(text,window = 2,lower = True)
w_list = word.get_keywords(num = 20,word_min_len = 1)
print w_list
for w in w_list:
print w.word,w.weight
... | true |
200714b49d9cb4ffffdb165620a534658da2dd64 | Python | ahuangya/Practice | /lib_practice/pra_json.py | UTF-8 | 918 | 2.609375 | 3 | [] | no_license | # !/usr/bin/env python
# -*-coding:utf-8-*-
# **************************************
# Filename:pra_json.py
# Author:huangya
# Description:
# time:2017-01-21
# ***************************************
import json
global type_list
type_list = []
def dict2json(dict):
"""
dict convert json
"""
json_str... | true |
08f5f5546a474cf1279eeca36f698001277dbefe | Python | nyucusp/gx5003-fall2013 | /yz1897/Assigment2/problem1.py | UTF-8 | 1,077 | 2.578125 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 23 17:32:28 2013
@author: yilong
"""
import time
import sys
def find_late_student():
try:
deadline=sys.argv()[1]
#get the deadline as parameter
except:
deadline='09/19/2013 09:12:15'#
find=0
for line in file("c:... | true |
8bd75065b335df58581f3e158453ce0b483aeba2 | Python | ksh1ng/ML | /hw1/ML_hw1.py | UTF-8 | 3,843 | 3.09375 | 3 | [] | no_license | #ML HW1
import csv
import numpy as np
data = []
# 每一個維度儲存一種污染物的資訊
for i in range(18):
data.append([])
n_row = 0
train_f = open('train.csv', 'r', encoding='big5')
row = csv.reader(train_f, delimiter = ',')
for r in row:
if n_row != 0:
for i in range(3, 27):
if r[i] != 'NR':
... | true |
e250d9f9632f3cafe9a1870500fcb5036cf61b79 | Python | jovaandres/daspro | /riwayatpinjam.py | UTF-8 | 4,650 | 3.296875 | 3 | [] | no_license | #riwayatpinjam.py
#F11 - Melihat Riwayat Peminjaman Gadget
#tanggal pembuatan: 17 April 2021
import time as datetime
from load import gadgetBorrowHistoryDatas, gadgetDatas, userDatas
#FUNGSI/PROSEDURAL
def tampil_lagi(sorted_datas,idx):
p = True #kondisi untuk loop while
while p:
#Menampilkan riwayat... | true |
1981ef90455be8faede3ad565ce148a611eaeffc | Python | huangzhuo492008824/websocket | /redisDB.py | UTF-8 | 574 | 2.875 | 3 | [] | no_license | import redis
class RedisDB(object):
"""Simple Queue with Redis Backend"""
def __init__(self, namespace='websocket', **redis_kwargs):
"""The default connection parameters are: host='localhost', port=6379, db=0"""
self.__db = redis.StrictRedis.from_url(url='redis://localhost:6379/0')
sel... | true |
a521bb57155107c558280e2a09b6917cb86456ee | Python | nkmk/python-snippets | /notebook/dict_value_max_min_series.py | UTF-8 | 1,007 | 3.6875 | 4 | [
"MIT"
] | permissive | import pandas as pd
d = {'a': 100, 'b': 20, 'c': 50, 'd': 100, 'e': 80}
s = pd.Series(d)
print(s)
# a 100
# b 20
# c 50
# d 100
# e 80
# dtype: int64
print(s.index)
# Index(['a', 'b', 'c', 'd', 'e'], dtype='object')
print(s.values)
# [100 20 50 100 80]
print(s.max())
# 100
print(s.min())
# 2... | true |