blob_id 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 |
|---|---|---|---|---|---|---|---|---|---|---|
763f3e51a2e3b9a94ad9d0c6c061c56fe4925ac6 | fprotopapa/iota.py | /iota/multisig/crypto/addresses.py | UTF-8 | 2,548 | 2.953125 | 3 | [
"MIT"
] | permissive | from typing import List, Optional
from iota.crypto import HASH_LENGTH
from iota.crypto.kerl import Kerl
from iota.crypto.types import Digest
from iota.multisig.types import MultisigAddress
__all__ = [
'MultisigAddressBuilder',
]
class MultisigAddressBuilder(object):
"""
Creates multisig addresses.
... | true |
6d53b7e43787d02410bc4f39c8b2bf4d8be0c5ea | leonardoedgar/ma4825_robotics_inspection | /inspection/src/calibration/image_collector.py | UTF-8 | 1,009 | 2.8125 | 3 | [] | no_license | #!/usr/bin/python3
import cv2
import datetime
import os
from hardware.uvc_driver import UVCDriver
class ImageCollector(object):
"""
A class to represent the image saver.
"""
def __init__(self, uvc_driver, dir_to_save):
# type: (UVCDriver, str) -> None
"""Initialise the class.
A... | true |
0eea013b54e5ba106b38124ef7ef8550e23c744b | RobSpurrett/MQTT_integration | /sketchpad.py | UTF-8 | 383 | 2.828125 | 3 | [] | no_license | import json
text_file_name = 'MQTT_robs_mqtt_test.txt'
json_file_name = 'MQTT_robs_mqtt_test.json'
print("\n Debug of text file: \n")
text_file = open(text_file_name,"r")
print(text_file.read())
print("\n Debug of json file: \n")
with open(json_file_name) as json_file:
data = json.load(json_file)
pretty = js... | true |
d5106ceea9b49bafffb2d13be029efd127a56bd4 | ekernf01/spacewarps_sp2016 | /deprecated/cnn first attempts junk/tensorflow_cnn.py | UTF-8 | 2,991 | 2.796875 | 3 | [] | no_license | from AstroImageMunger import *
import tensorflow as tf
swmunge = AstroImageMunger() #switch this out of test mode eventually
# recover features image by image in a pd dataframe
feature = swmunge.nextExample(datum_type="image")
# set up logistic regression
sess = tf.InteractiveSession()
x = tf.placeholder(tf.float32,... | true |
d64ab5f5af02528f8f22936244af483b398eb944 | hack4sec/ws-cli | /classes/threads/HttpThread.py | UTF-8 | 2,181 | 2.5625 | 3 | [
"MIT"
] | permissive | import threading
from libs.common import is_binary_content_type
from classes.Registry import Registry
class HttpThread(threading.Thread):
def is_response_content_binary(self, resp):
return resp is not None \
and 'content-type' in resp.headers \
and is_binary_content_type(resp.head... | true |
b9908d76c05d2ba0677076ebd1eeea196cc91d42 | imansz/ADM | /Iman.py | UTF-8 | 5,325 | 3.90625 | 4 | [] | no_license | ***Say "Hello, World!" With Python
print("Hello, World!")
***Python If-Else
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
if n%2!=0:
print("Weird")
elif n in range(2,6):
print("Not Weird")
elif n i... | true |
56d88378ca39b65777980e985a9a7061e87a42db | Tarkiyah/googleResearch | /summae/sample.py | UTF-8 | 2,020 | 2.90625 | 3 | [
"Apache-2.0"
] | permissive | # coding=utf-8
# Copyright 2019 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | true |
c73106ea25ca5cadbb07fa62bc100c81ced644fa | Vagacoder/PythonStudy | /w3schools/019-numpyCopyView.py | UTF-8 | 387 | 3.859375 | 4 | [] | no_license | #
# * Numpy Array Copy and View
#%%
import numpy as np
a1 = np.array([1, 2, 3, 4, 5])
x = a1.copy()
y = a1.view()
z = a1
print('Original arrays')
print(a1)
print(x)
print(y)
print('\nUpdate copy')
x[0] = 42
print(a1)
print(x)
print(y)
print('\nUpdate view')
y[1] = 99
print(a1)
print(x)
print(y)
print('\nCheck bas... | true |
f8619f93d9cf69a842ba85f03d5aec484a3d62bd | kevinqiyefa/Python | /database analysis/bestSandalin2016to2017.py | UTF-8 | 2,129 | 3.015625 | 3 | [] | no_license | from operator import itemgetter
import xlsxwriter
# Create an new Excel file and add a worksheet.
workbook = xlsxwriter.Workbook('bestSandal-late2016-early2017.xlsx')
worksheet = workbook.add_worksheet()
# Widen the first column to make the text clearer.
worksheet.set_column('A:A', 20)
worksheet.set_column('B:B', 40... | true |
d58962ebb22f50c625a85fb9684bf87347048b3f | alex3kv/PythonAlgorithms | /Lesson7/Task2.py | UTF-8 | 3,479 | 4.03125 | 4 | [] | no_license | '''
Отсортируйте по возрастанию методом слияния одномерный вещественный массив, заданный случайными числами на промежутке [0; 50).
Выведите на экран исходный и отсортированный массивы.
'''
import random
# генерируем массив для отладки
#arr = [float(_) for _ in range(10)]
#random.shuffle(arr)
# генерируем массив случ... | true |
6842896fc4721768336a3c9549a24c99dfd8574d | AImacroFX/Desktop-Systematic-Trading | /numpy_basics1.py | UTF-8 | 214 | 2.9375 | 3 | [] | no_license | # Create 2 new lists height and weight
height = [1.87, 1.87, 1.82, 1.91, 1.90, 1.85]
weight = [81.65, 97.52, 95.25, 92.98, 86.18, 88.45]
import numpy as np
np_height=np.array(height)
np_weight=np.array(weight)
| true |
bc7382dfbdfcc8d5ca47a1ea5129780d583f6ed8 | Enas-Habashieh/Enas-Test | /anooseh/venv/Lib/site-packages/objects/__init__.py | UTF-8 | 1,877 | 2.6875 | 3 | [] | no_license | """A corpus of object images."""
from base64 import b64encode
import hashlib
import os
import shutil
import urllib
import zipfile
object_dir = os.path.dirname(os.path.realpath(__file__))
def objects(idx):
all = [Object(p) for p in sorted(os.listdir(object_dir)) if p.endswith(".jpg")]
return all[idx]
def dow... | true |
83af0a17abaa7cda17957e35ec4be851e34c7ec2 | donghan-lee/SCC-7 | /etc/python/genie.py | UTF-8 | 1,014 | 3.25 | 3 | [] | no_license | import requests
from bs4 import BeautifulSoup
# 타겟 URL을 읽어서 HTML를 받아오고,
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
data = requests.get('https://www.genie.co.kr/chart/top200?ditc=D&rtm=N',headers=headers)
# HTML을 Beauti... | true |
b4e249927a03880e37026d912c5b7baee989cefe | zmanso2/It412_cshock | /file_ex.py | UTF-8 | 1,166 | 2.84375 | 3 | [] | no_license |
with open("file/SacramentocrimeJanuary2006.csv") as csv_file:
for line in csv_file:
temp_line = line.split(",")
place_counter = 0
while place_counter < len(temp_line):
temp_line[place_counter] = temp_line[place_counter][1:-1]
if place_counter == 0:
... | true |
41bcc3a0cbb36c0e23225a2b2a701e3c281a2e51 | chrisr01/prueba | /hola/modu_prob.py | UTF-8 | 487 | 3.578125 | 4 | [] | no_license | import os
import sys
import time
def datos():
print("ingrese un numero: ")
global x
x=input()
x=int(x)
print("ingrese otro numero: ")
global y
y=input()
y=int(y)
def suma():
os.system("clear")
sum=x+y
print("la suma es",sum)
time.sleep(2)
def resta():
os.system("clear... | true |
2defbcd2a86db7ddc5d8c0a5b2f074e73f43a669 | kbs907/programmers_final_competition | /src/xycar_slam/draw_path.py | UTF-8 | 285 | 2.78125 | 3 | [] | no_license | import pickle
import numpy as np
import matplotlib.pyplot as plt
if __name__ == '__main__':
with open("path.pkl", "rb") as f:
path = pickle.load(f)
# draw path
plt.plot(path['x'],path['y'])
plt.show()
# draw heading angle
plt.plot(path['yaw'])
#plt.show()
| true |
7686d50d3b1ee8ab3cc348ea75412e0dc0ce0c86 | UltraShieldRog/LeetCode | /contests/weekly_128/1012_complement_of_base_10_integer.py | UTF-8 | 216 | 2.953125 | 3 | [] | no_license | class Solution:
def bitwiseComplement(self, N: int) -> int:
b = "{:b}".format(N)
res = ""
for i in range(len(b)):
res += '0' if b[i] == '1' else '1'
return int(res, 2)
| true |
82c53c35004b3771aca2a0de07ef5a79952f83bf | luliyucoordinate/Leetcode | /src/0972-Equal-Rational-Numbers/0972.py | UTF-8 | 344 | 2.9375 | 3 | [] | no_license | class Solution:
def isRationalEqual(self, S, T):
"""
:type S: str
:type T: str
:rtype: bool
"""
def toNumber(s):
i = s.find('(')
if i >= 0:
s = s[:i] + s[i + 1:-1] * 20
return float(s[:20])
return to... | true |
22223a7d3e721a788662aa81d661df594b45e251 | turner11/VQA-MED | /VQA-MED/VQA.Python/pre_processing/data_cleaning.py | UTF-8 | 847 | 2.9375 | 3 | [] | no_license | import re
import pandas as pd
import numpy as np
def clean_data(df: pd.DataFrame) -> pd.DataFrame:
from pre_processing.known_find_and_replace_items import find_and_replace_collection
find_and_replace_data = find_and_replace_collection
def replace_func(val: str) -> str:
if isinstance(val, str):
... | true |
1b1d05f514e67537a999cdca0c9f548321a35a10 | kaminski-tomasz/balloon-shooter | /game.py | UTF-8 | 1,227 | 3.265625 | 3 | [] | no_license | import pygame
import sys
size = screenWidth, screenHeight = 320, 240
class SpaceShip:
velocity = 0.1
def __init__(self):
self.width = 30
self.height = 40
self.x = screenWidth / 2 - self.width / 2
self.y = screenHeight - self.height
def draw(self):
pygame.draw.re... | true |
6b1341f0b4e8bbb897f46e7768fdd69374d4bfb0 | flav1s/pythonchallenges | /lonelyInteger.py | UTF-8 | 1,017 | 3.578125 | 4 | [] | no_license | #!/bin/python3
# -*- coding: utf-8 -*-
import math
import os
import random
import re
import sys
# Complete the lonelyinteger function below.
def lonelyinteger(a):
newList = []
lonelyNumber = a[0]
for i in range(len(a)):
newList.append(a[i])
for j in range(len(a)):
if a... | true |
4c70857fcd893b8be4bdd983acdcdb9a59b28965 | dbsiegel/lab-samples | /sampleSelect.py | UTF-8 | 3,628 | 3.40625 | 3 | [] | no_license | """
Python script to select one replacement sample for each of the patients
who have been "reset" for sequencing
"""
from argparse import ArgumentParser
import sys, getopt
from collections import defaultdict
def parse_cli_args ():
parser = ArgumentParser(prog="Sample Select", add_help=True,
de... | true |
4abd6c9b456bc3a9ead151ec8ed5a96165a3c3c5 | kusime/tool | /new-post.py | UTF-8 | 1,444 | 2.84375 | 3 | [] | no_license | #!/usr/bin/python
import os
zhpath='/home/kusime/Desktop/blog/content/zh/posts/'
enpath='/home/kusime/Desktop/blog/content/en/posts/'
path='/home/kusime/Desktop/blog/content/'
print("THIS SCRPIT FILE RUN AT " + path +" FLODER")
signal='.md'
muten='.en.md'
mutzh='.zh.md'
print("zh or en")
x=input("please input the l... | true |
3b428224aae1edef3bffb6c4c3dab846556e3745 | tOgg1/UtilitySolve | /UtilitySolver.py | UTF-8 | 4,698 | 2.875 | 3 | [] | no_license | from BayesianNetwork import BayesianNetwork
from BayesianNode import BayesianNode
from UtilityNode import UtilityNode
from DecisionNode import DecisionNode
from NetworkLoader import NetworkLoader
from MapManager import MapManager
from Misc import debugPrint as db
from Misc import normalPrint as pr
from Misc import err... | true |
6aa8f39ed6e2244c4f1c132179d9eb93cd06ed25 | saulquispe/My-Solutions-to-The-Python-Workbook-By-Ben-Stephenson-122-of-174- | /If Statement Exercises/ex55.py | UTF-8 | 1,452 | 4.4375 | 4 | [] | no_license | '''
Exercise 55: Frequency to Name
Electromagnetic radiation can be classified into one of 7 categories according to its
frequency, as shown in the table below:
Name Frequency range (Hz)
Radio waves Less than 3 × 109
Microwaves 3 × 109 to less than 3 × 1012
... | true |
31dbf2c790df49944981f2ffe07c59f5737f60a4 | poojithayadavalli/codekata | /sum of all adjacent pairs.py | UTF-8 | 112 | 3.015625 | 3 | [] | no_license | x=int(input())
y=list(map(int,input().split()))
sum1=0
for i in range(x-1):
sum1+=(y[i]+y[i+1])
print(sum1)
| true |
02d96055ad3f493024548f02bce765f54d0ccb11 | richajoy/Python | /python_youtube_downloader.py | UTF-8 | 1,703 | 2.953125 | 3 | [] | no_license | import json
import re
import urllib.request
import requests
from pytube import YouTube
api_key = "AIzaSyB5KUB_bvYN2KZ-Ph7HKd5FfGFyMZodqz4"
link_file = "test_links.csv"
class Helper:
def __init__(self):
pass
def id_from_url(self, url: str):
return url.rsplit("/", 1)[1]
def title_to_u... | true |
bdb95e9079d5152c7d1fd276b76cc034f0abef73 | 0001lizhubo/6556566- | /Untitled-1.py | UTF-8 | 12,551 | 2.75 | 3 | [] | no_license | # 图书管理系统UI界面
import wx
import datetime
class wxGUI(wx.App):
# 登陆界面
def Login(self):
self.frame_Login = wx.Frame(None, title="Login", size=(500, 300))
self.panel_Login = wx.Panel(self.frame_Login, -1)
self.label1 = wx.StaticText(self.panel_Login, -1, \
'欢迎来... | true |
4bafb98994f35188651692303877a68a75de3849 | shivanichauhan18/Ng_exceptions | /format_module_defination.py | UTF-8 | 1,586 | 3.328125 | 3 | [
"MIT"
] | permissive | import ast
The ast module helps Python applications to process trees of the Python abstract syntax grammar. The abstract syntax itself might change with each Python release; this module helps to find out programmatically what the current grammar looks like.
An abstract syntax tree can be generated by passing ast.PyCF... | true |
f5ac53c8da2dc7d2bbc607e655f710d7feffca70 | dhruvtyagi2015/web-scrapping | /web-scrapping.py | UTF-8 | 875 | 3.03125 | 3 | [] | no_license | import requests
from bs4 import BeautifulSoup
import pandas as pd
page=requests.get("http://forecast.weather.gov/MapClick.php?lat=37.7772&lon=-122.4168")
soup=BeautifulSoup(page.content,'html.parser')
seven_day=soup.find(id="seven-day-forecast")
forecast_items=seven_day.find_all(class_="tombstone-container")
t... | true |
ea768f09c68036ab0b585a84b225715b9aef2833 | axreldable/data-engineer-test-task-python-sql | /tweet_loader/tweet_loader/loader.py | UTF-8 | 1,705 | 2.984375 | 3 | [] | no_license | import logging
from tweet_loader.file import read_lines_from_file
from tweet_loader.sentiment import SentimentCounterFactory, _SentimentCounter
from tweet_loader.sql import SqLiteInserter
from tweet_loader.tweet import TweetCreator
logger = logging.getLogger(__name__)
class TweetLoader:
def __init__(self, tweet... | true |
bbabc8d0018548fda7859e42b2946baf19291268 | KudasaiCode/discord-python-bot | /NutPack.py | UTF-8 | 3,167 | 2.640625 | 3 | [] | no_license | import discord
from discord.ext import commands
import random
import typing
import os
import nacl
import json
# server specific prefix fetch
def get_prefix(client, message):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
return prefixes[str(message.guild.id)]
# Apply prefix to serve... | true |
b9422417f34e45f194e020337f9e05d3ffb4264e | NuM314/tf-keras-vis | /tests/tf-keras-vis/test_saliency.py | UTF-8 | 2,662 | 2.65625 | 3 | [
"MIT"
] | permissive | import numpy as np
import pytest
from tensorflow.keras import Model
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Conv2D, Dense, Flatten, Input
from tensorflow.keras.models import Sequential
from tf_keras_vis.saliency import Saliency
from tf_keras_vis.utils.losses import SmoothedLoss
... | true |
c203863e7f4a164568ca54a128d50d22d4f37a23 | nimish24/Python | /QueueUsing2Stack.py | UTF-8 | 558 | 3.421875 | 3 | [] | no_license | class queue2stacks():
def __init__(self):
self.instack = []
self.outstack = []
def enqueue(self,element):
self.instack.append(element)
def dequeue(self):
if not self.outstack:
while self.instack:
return self.outstack.append(self.instack.pop())
... | true |
3ced2ab0d9a75db5eb5f77f778368a0b5d984793 | pooking/pyqt5_tutorial | /signalAndSlot/lambda_or_partial.py | UTF-8 | 1,465 | 3.53125 | 4 | [] | no_license | """使用lambda、partial传递参数"""
import sys
from functools import partial
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QWidget, QApplication, QPushButton, QHBoxLayout
class LambdaOrPartial(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
# 定义两个按钮
btn1 = QPus... | true |
80e42fbf81b3783c5f1a1aad0c68660778e93017 | LakunCindy/django-angular | /TME_webAPI_DJVAWS/mySearchEngine/myRevendeurApp/views.py | UTF-8 | 6,203 | 2.671875 | 3 | [] | no_license | import requests
from rest_framework.views import APIView
from rest_framework.response import Response
from myRevendeurApp.config import baseUrl
from myRevendeurApp.models import QuantityInStock
from myManageSale.models import ProductSale
from myManageSale.serializers import ProductSaleSerializer
from myRevendeurApp.ser... | true |
5ec2567cb9afdf42c19fb7f7560d3933a6a4612c | DebugConnoisseur/practice-programs | /itzmahw.py | UTF-8 | 39 | 3.40625 | 3 | [] | no_license | for i in range(1,39,2):
print(i)
| true |
fef06489b04d1bff93f70f06ef3018a45a8976de | ProjetPC2/SIMM2.0-DEV | /BackUp.py | UTF-8 | 2,065 | 2.609375 | 3 | [] | no_license | import os
import sqlite3
import csv
import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QFileDialog
from Interface.FenetresEnPython.Fichiers import pathFichierConf, pathEquipementDatabase
def backUp():
""" Methode permettant de copier les fichiers de la base de données
Cette méthode va copier ... | true |
8054bbc25226bfa070f22c506aa3b01dae9ddb2d | unisushi226/algorithm | /binary_search.py | UTF-8 | 1,848 | 3.796875 | 4 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 19 17:25:22 2020
@author: osushi
二分探索
参考URL< https://codezine.jp/article/detail/9900?p=2 >
1.1 128個の名前が含まれたソート済みのリストがあり、
二分探索を使って名前を探しているとしよう。ステップ数は最大でいくつになるか。
1.2 このリストのサイズを2倍にした場合、ステップ数は最大でいくつになるか。
-------------------------------------------... | true |
ca6e3a863005a4d69bc7e06adeaa78519f081373 | AM0511-kee/workspace | /controlflow.py | UTF-8 | 1,377 | 3.921875 | 4 | [] | no_license | #iterate using while loop and for loop
c=0
while c<5:
print(c)
c+=1
#while loop need a counter and an iterator for working
# loop can be used with indexes for that we need to find len() of lst
lst=['greek','for','greek','what','ever','it','takes']
for index in range (len(lst)):
print(lst[index])
#ennum... | true |
2cf508e2b45e21a7f26d41d60e768f21817823b7 | ochiaierika/100knock | /chapter02/knock10.py | UTF-8 | 458 | 3.3125 | 3 | [] | no_license | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'erika.ochiai'
import sys
def count_lines(filename):
count = 0
with open(filename) as f:
for line in f:
count += 1
return count
if __name__ == '__main__':
if len(sys.argv) is not 2:
print('Please input file name w... | true |
a449080d4c732800456ef241a56ad283699acac8 | pitanshu/python_programs | /number_table.py | UTF-8 | 288 | 3.734375 | 4 | [] | no_license | num=int(input("rnter the number for which you want to display the table : "))
counter=int(1)
while(counter<=10):
print("{num}*{counter}={result}".format(num=num,counter=counter,result=int(num*counter)))
counter=counter+1
else:
print("end of table")
#print("table as above") | true |
9ebd9ca902bba40ada03432fd4bb1a76880b2f31 | borisachen/leetcode | /220. Contains Duplicate III.py | UTF-8 | 1,123 | 3.296875 | 3 | [] | no_license | 220. Contains Duplicate III
<<<<<<< HEAD
Given an array of integers, find out whether there are two distinct indices i and j in the array
such that the absolute difference between nums[i] and nums[j] is at most t
and the absolute difference between i and j is at most k.
=======
Given an array of integers, find out ... | true |
dc98f87fd7e736c26e3b8d3c634e61a0003fe0df | Bakx13/tbot_report | /tbot_venv/lib/python3.9/site-packages/telegram_bot_sdk/telegram_objects/inputVenueMessageContent.py | UTF-8 | 949 | 2.828125 | 3 | [
"MIT"
] | permissive | class InputVenueMessageContent:
"""This class represents the content of a venue message to be sent as the result of an inline query
:param latitude: Latitude of the venue in degrees
:type latitude: float
:param longitude: Longitude of the venue in degrees
:type longitude: float
:param title: Na... | true |
9ce4e308357ada34c0079547d942ec7c6e60db41 | anjali0508/SmartParking | /Development/Database/ResidentVehicles.py | UTF-8 | 1,388 | 2.859375 | 3 | [] | no_license | from firebase import firebase
import IDGenerator
firebase = firebase.FirebaseApplication(
'https://smartparkingsystem-bca72.firebaseio.com/', None)
id = IDGenerator.ID()
class ResidentVehicle:
def __init__(self, flatNo, vehicleNo, allottedSlot):
self.flatNo = flatNo
self.vehicleNo = vehicleNo... | true |
765348c6c7a895d83724e498a1d89e8f9f2dbdab | Pranav-Coding/Password-MANAGER | /main.py | UTF-8 | 3,194 | 2.921875 | 3 | [] | no_license | import random
import sys
import json
import pyperclip
from encriptit import encrypt_message, decrypt_message
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
charecter = ["!","@","#","$","%","&","*"]
numbers = [0,1,2,3,4,5,6,7... | true |
d96a068c18802c292996a955d451b02fe265424b | atrivedi8988/DSA-Must-Do-Questions | /02_Check for prime/Ideal Solutions/checkPrime.py | UTF-8 | 313 | 3.6875 | 4 | [] | no_license | import math
# Cheking Whether the number is prime or not
def checkPrime(Number):
for i in range(2, int(math.sqrt(Number)) + 1):
if Number % i == 0:
return "No"
return "Yes"
if __name__ == "__main__":
array = []
# Static Input
Number = 7
print(checkPrime(Number))
| true |
eb394a1a745198cd391f99a029c1736cb051d8b6 | emersonpisoni/face_mask_detection | /face_detection.py | UTF-8 | 1,188 | 2.515625 | 3 | [] | no_license | from tensorflow.keras.models import load_model
import cv2
import numpy as np
from mtcnn.mtcnn import MTCNN
path = "C://Users//Emerson//Desktop//"
detector = MTCNN()
model = load_model(path + "detector.h5")
size = (160, 160)
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
faces = detector.detect... | true |
c7d80ef76962ce9526e94893a6aa4066ab567305 | SuSandiWin/PythonLearning | /if_else.py | UTF-8 | 323 | 3.625 | 4 | [] | no_license | # age=int(input('age:'))
# if age<18:
# print('you are young');
# elif age >18 and age<30:
# print('You are normal age');
# else:
# print('you are old');
tried=input('Are you tired? "y/n"')
if tried=='y':
print('rest well')
elif tried=='n':
print('Go back to work')
else:
print('pls enter y or ... | true |
5e2cfb46324d9ea357e8c37504e803b46fa5597f | hansolJu/PythonTutorial | /021_030/021.py | UTF-8 | 361 | 4.09375 | 4 | [] | no_license | # 021 문자열 합치기
#
# 리스트에 회사 이름이 저장되어 있다. 각 회사 이름이 구분자 ";"로 연결된 문자열을 생성하라.
#
# >>> companies = ['NAVER', 'KAKAO', 'SK', 'SAMSUNG']
#
# 실행 예:
# >>> nstring
# 'NAVER;KAKAO;SK;SAMSUNG'
companies = ['NAVER', 'KAKAO', 'SK', 'SAMSUNG']
nstring = ';'.join(companies)
print(nstring) | true |
f55be000697ff2f2e082d8ab16fa7613f843e455 | Chacon-Miguel/CodeForces-Solutions | /balancedArray.py | UTF-8 | 498 | 3.609375 | 4 | [] | no_license | total = int(input())
numbers = [0] * total
for i in range(total):
numbers[i] = int(input())
for number in numbers:
if number%4 == 0:
print("YES")
arr = []
for evens in range(2, (number)+1, 2):
arr.append(evens)
for odds in range(1, (number), 2):
... | true |
591da174a4d712357443dc0222a573c80423c55b | milosdju/machine-learning-algorithms | /nn_model_funcs.py | UTF-8 | 5,937 | 2.84375 | 3 | [] | no_license | import csv
import numpy as np
import matplotlib.pyplot as pyplot
def initialize_weigths(layer_sizes, optimizer = 0.01):
weights = dict()
for idx, layer_size in enumerate(layer_sizes):
if idx == 0: continue
prev_layer_size = layer_sizes[idx - 1]
# Initializing random weights
weig... | true |
59aa64daa3ae71430afba33b95c7a81ef8fe35cf | javierperezferrada/tarea_final_taller | /controller.py | UTF-8 | 3,755 | 3 | 3 | [] | no_license | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Ahora que tenemos un modelo el controlador cumple el rol de ser una capa
intermedia entre la Vista y el modelo.
Su finalidad es validar los datos de entrada que envía la vista y decidir
que información enviar a ésta.
"""
from PySide import QtGui
from model import Producto, ... | true |
c258c1084536256490e729ad336a5b48106d7d2c | keiffster/program-y | /test/programytest/dynamic/sets/test_roman.py | UTF-8 | 714 | 2.546875 | 3 | [
"MIT"
] | permissive | import unittest
from programy.context import ClientContext
from programy.dynamic.sets.roman import IsRomanNumeral
from programytest.client import TestClient
class IsRomanNumeralDynamicSetTests(unittest.TestCase):
def setUp(self):
self._client_context = ClientContext(TestClient(), "testid")
def test... | true |
551c2080e29cd37e85f38981adfaf74823632217 | jonhillmtl/pipe_to | /pipe_to/__init__.py | UTF-8 | 6,077 | 2.765625 | 3 | [] | no_license | from functools import wraps
from enum import Enum, unique
import sys
import datetime
import os
from typing import Any, Callable, Dict, Tuple, IO
assert IO
@unique
class PipeType(Enum):
DEFAULT = 0
BATCH_NUMBER = 10
DATETIME = 20
DATE_BATCH_NUMBER = 30
DATE_HIERARCHY_BATCH_NUMBER = 40
DATE_HI... | true |
6a301bf039c6f383300c51bf771729a142ff8c0e | yinzhe1989/py | /test_unittest/mysort.py | UTF-8 | 252 | 3.21875 | 3 | [
"MIT"
] | permissive |
# 将要被测试的排序函数
def sort(arr):
l = len(arr)
for i in range(0, l):
for j in range(i + 1, l):
if arr[i] >= arr[j]:
tmp = arr[i]
arr[i] = arr[j]
arr[j] = tmp
| true |
f52a519adfff061103c846a2efec89a5c34eb9e1 | anguye2/hypeit | /database.py | UTF-8 | 5,270 | 2.828125 | 3 | [] | no_license | #!/usr/bin/python
import psycopg2
import io
import os, json, glob
from config import config
import sys
reload(sys)
sys.setdefaultencoding('utf8')
def create_table():
""" create tables in the PostgreSQL database"""
commands = (
"""
CREATE TABLE restaurant (
id SERIAL PRIMARY KEY,
... | true |
9ae68e9c6b58398504b5c8163bd9d8b4cdb352bf | anilvec09/python-practise | /List-Dictionary/Remove Duplicates from Sorted Array.py | UTF-8 | 238 | 3.359375 | 3 | [] | no_license |
def removeDuplicates( nums) :
for num in nums:
while(nums.count(num) > 1):
nums.remove(num)
return len(nums)
assert removeDuplicates([1,1,2]) == 2
assert removeDuplicates([0,0,1,1,1,2,2,3,3,4]) == 5 | true |
bbc3cd3778f329eb7a7366c411050bba16f8deec | MichelleZ/leetcode | /algorithms/python/subarraySumEqualsK/subarraySumEqualsK.py | UTF-8 | 475 | 3.109375 | 3 | [] | no_license | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Source: https://leetcode.com/problems/subarray-sum-equals-k/
# Author: Miao Zhang
# Date: 2021-02-22
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
if not nums: return 0
cnt = defaultdict(int)
cnt[0] = 1
cu... | true |
df34cea407f7de6d62b3031692c42bfac7620a5d | samlaudev/LeetCode | /Python/Longest Substring Without Repeating Characters/Solution.py | UTF-8 | 1,203 | 3.96875 | 4 | [
"MIT"
] | permissive | # Problem: Longest Substring Without Repeating Characters
#
# Given a string, find the length of the longest substring without repeating characters.
#
# Examples:
#
# Given "abcabcbb", the answer is "abc", which the length is 3.
#
# Given "bbbbb", the answer is "b", with the length of 1.
#
# Given "pwwkew", the answer ... | true |
0d6d46796102051c3e9623ef67af41f7b1c22687 | lime9903/DL | /MNIST/Neural Network_Numerical.py | UTF-8 | 9,032 | 3.390625 | 3 | [] | no_license | import numpy as np
from datetime import datetime
# 활성화 함수(activative function): sigmoid 함수
# 0 ~ 1 사이의 값을 가지도록 한다.
def sigmoid(x):
return np.exp(np.fmin(x, 0)) / (1 + np.exp(-np.abs(x)))
# 수치 미분
def numerical_derivative(f, x):
"""
수학적인 lim(x->0)을 프로그램으로 구현하기 위해서 아주 작은 값으로 설정.
컴퓨터는 32bit나 64bit 등 한정된 크... | true |
ad900dd0ff063e0d70b98b5318deac9efeef534b | AK-1121/code_extraction | /python/python_14009.py | UTF-8 | 93 | 2.734375 | 3 | [] | no_license | # How do I create a list from a single string without splitting the string in python
b = [a]
| true |
28a2c7e9e40f4f297c1f075c18a62d5dbb5e2516 | sqoor/python-exercises | /project3.py | UTF-8 | 7,203 | 3.546875 | 4 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 6 19:15:03 2019
@author: abdala
Title:
Project 3 Database
Description:
desktop interface to add employees information to the database (sqlite)
and view them on desktop window,
"""
import sqlite3
from tkinter import *
from tkinter import scrolled... | true |
457a9aaa8dd6851b7b827dfd94048a81a2f3bccd | Roninho514/Treinamento-Python | /ex016.py | UTF-8 | 123 | 3.734375 | 4 | [
"MIT"
] | permissive | from math import trunc
num = float(input('Digite um numero quebrado:'))
print('Ele inteiro ficaria {}'.format(trunc(num)))
| true |
d73fe2999c8f72c3df3b8d9ca6b6ba42cc7e8882 | malhotravasu/t2i_gan | /data_loader.py | UTF-8 | 2,590 | 2.765625 | 3 | [] | no_license | import pandas as pd
import os
import torch
import numpy as np
from PIL import Image
from skimage.transform import rescale, resize, downscale_local_mean
from skimage.io import imread
from torch.autograd import Variable
from torch.utils.data import Dataset
from torchvision import transforms
# Each batch will have 3 thin... | true |
be8ca702874b8c81bd7ca5f2c7a99e230ae0feaa | Hengle/SnapdragonData2Word | /FrameDataOutput.py | UTF-8 | 11,329 | 2.515625 | 3 | [] | no_license | import csv
import operator
import os
from typing import List
from docx import Document
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml
from enum import Enum
from PIL import Image
from docx.shared import Cm, Inches, Pt
class TableTool:
def make_table... | true |
971eff66400a1eddc6cfc6b0e8f7608adc9e0c77 | wfnuser/cs902 | /lab3/excel/template.py | UTF-8 | 2,892 | 3.15625 | 3 | [] | no_license | #!/usr/bin/env python
# encoding: utf-8
import sys
import xlwt
import xlrd
Weight = [0.1, 0.1, 0.1, 0.7]
def save(workbook, filename):
if (not isinstance(workbook, xlwt.Workbook)) and (not isinstance(filename, str)):
print "type error in save"
sys.exit(0)
"""
FIXME
"""
def add_sheet(... | true |
10273ee62b04a568b1026e9124646482d0fc44b5 | Maomaonihao/FedAvg_by_myself | /FedAvg_by_myself2/utils/loadDatasets.py | UTF-8 | 885 | 2.609375 | 3 | [] | no_license | import numpy as np
from torchvision import transforms, datasets
from torch.utils.data import Dataset, DataLoader
# customize transforms
transforms_mnist = transforms.Compose(
[
transforms.ToTensor(), # image -> Tensor(C, H, W) , grey level 0~255 -> 0~1
transforms.Normalize((0.1307,),(0.3081,)) ... | true |
fa702351e17afe9e183f5cd423d6c7b316dc6ce9 | maorros/edavid_filler | /single_strokes.py | UTF-8 | 3,094 | 2.53125 | 3 | [] | no_license | from Strokes import *
from RobotPainter import *
from Curves import *
import matplotlib.pyplot as plt
import numpy as np
from scipy import interpolate
# c = Curves()
# c.set_point_list([20, 40, 30, 30], [10, 40, 40, 50])
# c.points_to_pre(0.5,3)
# s_x, s_y = c.points_to_smooth(0.001)
# c.display()
canvas_ratio = 20
x... | true |
c938a97505f920fd53194cfda6db003e9098695c | voodoopeople42/Vproject | /Janus/python-base-unit_12/sql/04_cursor.py | UTF-8 | 313 | 2.796875 | 3 | [
"MIT"
] | permissive | # 04_cursor.py
import sqlite3
# Получаем объект указателя на соединения.
connection = sqlite3.connect('testdb.db')
# Создается курсор из соединения с БД:
cursor = connection.cursor()
# Закрьmаем базу данных
connection.close()
| true |
c0b12cf47ce7150d6c236a0f01ecd1d5730a1de6 | cc-CATs-LiVE-0000-GYNT-0Ent-ROPy/exercises | /practicepython.org/e28.py | UTF-8 | 509 | 3.84375 | 4 | [] | no_license |
def maxx():
print(sorted(li)[-1])
if __name__ == "__main__":
inp = input("Give three integers space separated: ")
li = [int(i) for i in inp.split()]
maxx()
''' https://www.practicepython.org/
Implement a function that takes as input three variables, and returns
the largest of the three. Do this without usin... | true |
c6bd33d027cf9c597e06bad2a01e22803c68f351 | saiswaroop5225/library-management-system | /Library Management System/My Library/addmember.py | UTF-8 | 2,442 | 3.1875 | 3 | [] | no_license | from tkinter import *
from tkinter import messagebox
import sqlite3
con =sqlite3.connect('library.db')
cur=con.cursor()
class AddMember(Toplevel):
def __init__(self):
Toplevel.__init__(self)
self.geometry("650x750+550+200")
self.title("Add Member")
self.resizable(False,False)
... | true |
8215023c9bf3ee9f7bef72444ed5d027d2768678 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2732/60731/314003.py | UTF-8 | 364 | 2.875 | 3 | [] | no_license | n=int(input())
a=[]
for i in range(n):
d=input()
a.append(d)
if a==['3 2 4', '10 9 3', '450 768 517']:
print(1)
print(1)
print(34)
elif a==['3 2 4', '10 9 7', '450 768 517']:
print(1)
print(6)
print(34)
elif a==['3 2 5', '10 9 7', '450 768 517']:
print(4)
print(6)
print(34)
e... | true |
56853f7fa7c21f3b200edad5992a4b23deb12219 | jailsonpj/pythonico | /cap3/exemplo1.py | UTF-8 | 392 | 3.71875 | 4 | [] | no_license | def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print("I sleep all night and I work all day.")
def repeat_lyrics():
print_lyrics()
print_lyrics()
#repeat_lyrics()
def print_twice(bruce):
print(bruce)
print(bruce)
def cat_twice(part1,part2):
cat = part1 + part2
print_twice(cat)
#print_twice(42)... | true |
8b16c2453ad29bc4dc64f4f13b80c30d26cd641e | azs06/PythonLearning | /function1.py | UTF-8 | 123 | 2.640625 | 3 | [] | no_license | def hello_world():
print('Hello World')
hello_world()
hello_world()
def convert(minutes):
return minutes * 60
| true |
927e79efc173d6cbb704ec8a7c5cc4d0285e3b79 | Ariel-De-Sarro/statistics_practices | /cars.py | UTF-8 | 8,204 | 3.5625 | 4 | [] | no_license | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
raw_data = pd.read_csv('1.04. Real-life example.csv')
raw_data.head()
raw_data.describe(include = 'all') # por defecto, solo pone las variables numericas
data = raw_data.drop(['Model'], axis = 1) #queremos sacar la... | true |
0b1e0fa5c3d9bb982d1ce4e88d8e14d6f4ce0296 | challeger/leetCode | /中级算法/leetCode_68_前K个高频元素.py | UTF-8 | 4,573 | 4.15625 | 4 | [] | no_license | """
day: 2020-08-20
url: https://leetcode-cn.com/leetbook/read/top-interview-questions-medium/xvzpxi/
题目名: 前K个高频元素
题目描述: 给定一个非空的整数数组,返回其中出现频率前K高的元素
示例:
输入: nums=[1, 1, 1, 2, 2, 3], k=2
输出: [1, 2]
思路:
1.桶排序
先将各个数字出现的次数记录到字典中,然后根据nums的长度建立一个List[List[int]],
第一个list的索引代表出现的次数,第二个list存放出现次数为该索引的数字,然后从末尾开始
... | true |
f9966182ebd3b9ca06fc219cdc3190a3b376297d | wzdnzd/leetcode | /python3/0300.最长递增子序列.py | UTF-8 | 1,450 | 3.5 | 4 | [
"Apache-2.0"
] | permissive | #
# @lc app=leetcode.cn id=300 lang=python3
#
# [300] 最长递增子序列
#
# https://leetcode.cn/problems/longest-increasing-subsequence/description/
#
# algorithms
# Medium (54.30%)
# Likes: 3263
# Dislikes: 0
# Total Accepted: 752.9K
# Total Submissions: 1.4M
# Testcase Example: '[10,9,2,5,3,7,101,18]'
#
# 给你一个整数数组 nums ... | true |
2634d4c25bd46c0142619910da94ce750a468edd | jwitheford/fs.smbfs | /tests/test_file.py | UTF-8 | 579 | 2.546875 | 3 | [
"Zlib",
"BSD-3-Clause",
"MIT"
] | permissive | # coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
import unittest
from fs.smbfs.file import _Cursor
class TestCursor(unittest.TestCase):
def test_write(self):
buffer = bytearray(8)
cursor = _Cursor(buffer)
self.assertEqual(cursor.write(b"abcd... | true |
266550a4a77ed063b3189ffdb321060f05956545 | stefreak/one-second | /benchmarks/branch.py | UTF-8 | 316 | 3.046875 | 3 | [] | no_license | #!/usr/bin/env python
# Number to guess: How many times per second can we
# sort an already sorted array with 500 elements?
# (small amount of branch mispredictions)
def f(NUMBER):
l = range(500)
for _ in xrange(NUMBER):
sorted(l)
if __name__ == '__main__':
import sys
f(int(sys.argv[1]))
| true |
20b77854da4542c744c57805364182a3985a5b33 | yjh8806/python-2019-July | /4일/07.포매팅/04.문제.py | UTF-8 | 922 | 3.5 | 4 | [] | no_license | kg = "KG ITBANK"
address = "부산광역시 수영구 민락동"
start = 15
name = "송진우"
end = 18
height = 170.2145
age = 30
Phone = "010-5567-1430"
#위의 변수를 이용하여 아래와 같이 출력
print("{}{}{}".format("☆"*10,kg,"☆"*10))
print("파이썬 강의 : {0}시 ~ {1}시".format(start,end))
print("본인 이름 : {}".format(name))
print("본인 나이 : {}".format(age))
... | true |
71c43317e0bb57c1c30d57b79a490020567d1fe8 | akaProgramer/python_tkinter | /tk_check_box.py | UTF-8 | 2,142 | 2.9375 | 3 | [] | no_license | from tkinter import *
def print_values():
print(mobile_brand_value.get())
print(processor_value.get())
print(ram_value.get())
print(storage_value.get())
print(os_value1.get())
with open("phone.txt","a") as f:
f.write(f"{mobile_brand_value.get(),processor_value.get(),ram_value.get(),sto... | true |
754230d53823b2daeaf627cb655b98f2717e79a3 | realight0316/rasp_IoT | /choumpa2.py | UTF-8 | 1,570 | 3.21875 | 3 | [] | no_license | import RPi.GPIO as GPIO # RPi.GPIO에 정의된 기능을 GPIO라는 명칭으로 사용
import time # time 모듈
GPIO.setmode(GPIO.BCM) # GPIO 이름은 BCM 명칭 사용
GPIO.setup(17, GPIO.OUT) # Trig=17 초음파 신호 전송핀 번호 지정 및 출력지정
GPIO.setup(18, GPIO.IN) # Ec... | true |
8da60893d556900d32677cdebb4693acfde466c9 | jbasko/typingpong | /tests/test_parser.py | UTF-8 | 1,611 | 3.078125 | 3 | [] | no_license | import typing
import pytest
from typingpong.parser import TypeStrGrammar
@pytest.mark.parametrize('input_str,expected', [
['str', {'name': 'str', 'args': None}],
['typing.List[str]', {'name': 'typing.List', 'args': [{'name': 'str', 'args': None}]}]
])
def test_primitives(input_str, expected):
assert exp... | true |
8c490383f67d14264cc708b1085535daef298124 | brayanesteves/Courses | /source/views/UDEMY/views/Redait Media/Machine Learning. Curso básico de Machine Learning/Sección 5. Módulo Pandas para análisis de datos/58. Leer páginas web HTML/index.py | UTF-8 | 347 | 3.640625 | 4 | [] | no_license | # Pandas - Ficheros HTML
print("Pandas - Ficheros HTML\n")
import pandas as pd
pagina_web = 'https://es.wikipedia.org/wiki/Anexo:Pa%C3%ADses_y_territorios_dependientes_por_poblaci%C3%B3n'
datos = pd.read_html(pagina_web)
print(datos)
print()
print(type(datos))
print()
print(datos[0])
print()
dataframe = datos[0... | true |
932c8f94b0a79b4e8f29085fc9b0af0519f52b6e | siyile/leetcode | /src/UpTo500/Problem462.py | UTF-8 | 688 | 2.828125 | 3 | [] | no_license | def partition(lo, hi, nums):
i, j, pivot = lo, lo, nums[hi]
while j < len(nums) - 1:
if nums[j] < pivot:
nums[i], nums[j] = nums[j], nums[i]
i += 1
j += 1
nums[i], nums[hi] = nums[hi], nums[i]
return i
class Solution:
def minMoves2(self, nums: List[int]) -> i... | true |
c4cb439d094a55a590c7480e6567756cdcfde87f | Teemperor/bash-utils | /exists | UTF-8 | 129 | 2.640625 | 3 | [] | no_license | #!/usr/bin/python
import sys
import os
for line in sys.stdin:
if os.path.isfile(line.strip()):
print(line.strip())
| true |
1f19bf1f07b7723f7980df0ba5c2d4e84f04d7c0 | liu1073811240/Cat-and-Dog-Recognition | /rand_sample.py | UTF-8 | 1,343 | 3.21875 | 3 | [] | no_license | import os, random, shutil
import numpy as np
def moveFile(fileDir):
pathDir = os.listdir(fileDir) # 取图片的原始路径
print(pathDir)
# exit()
filenumber = len(pathDir)
# print(filenumber)
rate = 0.8 # 自定义抽取图片的比例,比方说100张抽10张,那就是0.1
picknumber = int(filenumber * rate) # 按照rate比例从文件夹中取一定数量图片
s... | true |
9b88fd73e9f23d28140414acf97924104af5805b | aneeshgarg18/CS-251-project | /Demonstrative_Checker.py | UTF-8 | 3,690 | 2.84375 | 3 | [] | no_license | from nltk.tokenize import word_tokenize
from nltk import pos_tag
import urllib
import requests
from .helper import *
sentence = "It seems that that is a bad situation."
def Demonstrative_Checker(sentence):
lst = pos_tag(word_tokenize(sentence))
print(lst)
errors = []
pronouns = ['this', 'that', 'these', 'those']... | true |
2787e05dceaff543d8c4e8b9dfd7d63401424874 | adityakverma/Interview_Prepration | /Leetcode/Dynamic_Programming/01_Fibonacci_Numbers.py | UTF-8 | 1,372 | 3.9375 | 4 | [] | no_license |
# https://www.geeksforgeeks.org/program-for-nth-fibonacci-number/
# https://www.csdojo.io/dpcode
# A naive recursive solution
def fib(n):
if n == 1 or n == 2:
result = 1
else:
result = fib(n-1) + fib(n-2)
return result
############### TOP DOWN APPROACH ##################
# ... | true |
a46d84935c4ca73ee47e5feac5ff1b0441a9fcb8 | kandrey999/PingPong | /rect.py | UTF-8 | 835 | 3.515625 | 4 | [
"MIT"
] | permissive | # class Rect:
# def __init__(self, width, height):
# self.__width = width
# self.__height = height
#
# @property
# def width(self):
# return self.__width
#
# @property
# def height(self):
# return self.__height
#
# @property
# def left_top(self):
# ret... | true |
3e9b815ec4ab1f162fc7f659f2920044eaa70a9d | NemoHoHaloAi/cucumber-book | /监督式学习-马同学-手写算法/梯度下降法.py | UTF-8 | 961 | 3.546875 | 4 | [
"Apache-2.0"
] | permissive | import numpy as np
import matplotlib.pyplot as plt
'''
使用梯度下降法求解函数最小值,此处函数为抛物线函数y=x^2,可知最小值在x=0处,也可以通过求导得到该值;
简单说就是直接求导获取最值的方式因为公式复杂变得困难时,可以考虑以梯度的反方向为参考更新参数,以逼近最值,当然这局限于凸函数求解;
'''
xk = [10] # 初始x0
lr = .1 # 学习率η,学习率过大会导致无法收敛到最优,最小会导致逼近速度过慢
epochs = 100 # 迭代次数
e = 0.0000001 # 上限ε
def f(x):
return x**2
def grad(... | true |
ece87ed20910afaa4fb1dd3da7c1508273ceb551 | hrvach/CheckiO | /Numbers Factory.py | UTF-8 | 304 | 2.6875 | 3 | [] | no_license | def factorize(n, t=[]):
for i in range(9,1,-1):
if n % i == 0:
n, t = n/i, t+[str(i)]
return factorize(n, t)
return (n, t)
def checkio(number):
residue, factors = factorize(number, [])
return int(''.join(sorted(factors))) if residue==1 else 0 | true |
298b64597aa372779a8e185e1d85eae39f9f70a6 | princeyyadav/games_with_pygame | /snake_game/snake.py | UTF-8 | 767 | 3.5 | 4 | [] | no_license | import pygame
class Snake:
def __init__(self, start_pos, radius, color, step):
self.radius = radius
self.body = [[start_pos[0]+(2*self.radius*(i)), start_pos[1]] for i in range(4)]
self.color = color
self.step = step
self.vel = [-self.step, 0] # has two components x, y
... | true |
fde7c4c9e703c7edde294fc55721a3dff31138d7 | vd9hosigi6/gcamp-ros2-seminar | /basic_topic_pkg/basic_topic_pkg/topic_example_2_subscriber.py | UTF-8 | 2,248 | 2.890625 | 3 | [] | no_license | # Copyright 2021 @RoadBalance
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | true |
0185cee082f52fe3b28dca2074a91644bbfe000f | Paul3181/TP_IAA | /tp5/DONNEES_TP5/lecture_affichage_images.py | UTF-8 | 2,518 | 2.90625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on 08/02/19
@author: Thomas Pellegrini
"""
im='./images/joconde.jpg'
from scipy.misc import imread
import matplotlib.image as img
import numpy as np
import csv
from utils import load_dataset
from kmeans import KMeans
from PIL import Image, ImageFilter
def im_to_csv(data):
wi... | true |
97facc0443467b5f80d9f705f6003a89050f4cbb | ShikaZzz/disease-outbreak | /src/convert2type3.py | UTF-8 | 3,307 | 2.9375 | 3 | [] | no_license | '''
'''
import os
import json
import pandas as pd
from src.get_datatype import GetDatatype
class Convert2Type3:
def __init__(self):
'''
'''
self.cur_dir = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(self.cur_dir,"PARAMS.json")) as f:
self.params = json.load(f)
self.TYPE1 = self... | true |
e4e823fe555dfbdb261b0ecdd32f4facf6ef2665 | danilakazel/automationStepikCourse | /module2/Hw2.2.2.py | UTF-8 | 785 | 2.6875 | 3 | [] | no_license | import time
import math
from selenium import webdriver
url ="http://suninjuly.github.io/execute_script.html"
try:
browser = webdriver.Chrome()
browser.get(url)
x = browser.find_element_by_id("input_value").text
def calc(x):
return str(math.log(abs(12 * math.sin(int(x)))))
y = calc(x)
button = brows... | true |
63a7682a58960368f7a028cdd5048f63de8c2956 | gsudarshan1990/Training_Projects | /AdvancedLoops/comprehesions.py | UTF-8 | 1,437 | 4.25 | 4 | [] | no_license | """
This is an example of the comprehension
"""
num = range(10)
print([x*x for x in num])
letters = [letter for letter in 'anxiety']
print(letters)
list_of_words = ['this','is','a','list','of','words']
first_words = [word[0] for word in list_of_words]
print(first_words)
upper_fist_words = [word[0].upper() for wor... | true |
71a7098847f97d50ead0c85d5ca2547bb9e89052 | Nellyth/Lsv-Tech | /Practica/14-03-2019/Actividad #10.py | UTF-8 | 2,720 | 3.46875 | 3 | [] | no_license | #Servicios: Operadores Regiones
#Internet Banda Ancha Claro Caribe
#Telefonia Movil Etb Eje Cafetero
# Movistar Andina
# Tigo Une Llano Oriente
#1) Calcular las multas d... | true |