seq_id stringlengths 7 11 | text stringlengths 156 1.7M | repo_name stringlengths 7 125 | sub_path stringlengths 4 132 | file_name stringlengths 4 77 | file_ext stringclasses 6
values | file_size_in_byte int64 156 1.7M | program_lang stringclasses 1
value | lang stringclasses 38
values | doc_type stringclasses 1
value | stars int64 0 24.2k ⌀ | dataset stringclasses 1
value | pt stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
32043962015 | # -*- coding: utf-8 -*-
"""
Created on Sat Jan 12 02:46:22 2019
@author: Michael
"""
#importing the necessary libraries
import os
import shutil
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from kera... | Monarene/CV-Deep-learning-Pracittioner | minivggnet_flower17_data_aug.py | minivggnet_flower17_data_aug.py | py | 3,346 | python | en | code | 0 | github-code | 6 |
35525386991 | """
Module containing ports and adapters for forward curve suppliers.
Contains both the abstract interface and concrete implementation.
"""
import abc
import datetime as dt
from typing import Collection
from volfitter.adapters.option_metrics_helpers import create_expiry
from volfitter.adapters.sample_data_loader imp... | docadam78/vf_project | src/volfitter/adapters/forward_curve_supplier.py | forward_curve_supplier.py | py | 2,503 | python | en | code | 2 | github-code | 6 |
71643512507 | import pygame
from pygame.sprite import Sprite
class Button(Sprite):
def __init__(self, ai_settings, screen, msg, position, function_num):
super(Button, self).__init__()
self.screen = screen
self.screen_rect = screen.get_rect()
self.ai_settings = ai_settings
sel... | Karllzy/Architect | button.py | button.py | py | 3,292 | python | en | code | 2 | github-code | 6 |
25814086176 | from selenium.webdriver import Firefox
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
import pytest
import time
@pytest.mark.needs_server
class TestMaxlifeFeature:
"""
Checks if the maxlife feature is working
"""
def setup_class(self):
... | bepasty/bepasty-server | src/bepasty/tests/test_website.py | test_website.py | py | 4,149 | python | en | code | 162 | github-code | 6 |
25399032626 | import re
from csv import reader
from colorama import init, Fore
# Insert the actual exploits in searchsploit in the database
def update_database(exploit_database, mycursor):
print(Fore.BLUE + "Updating database...")
# Read the CSV to get the basic information
with open('/usr/share/exploitdb/files_exp... | alvaroreinaa/Can-You-EXPLOIT-It | update_database.py | update_database.py | py | 7,870 | python | en | code | 1 | github-code | 6 |
27127443756 | """
基于Memoization的递归可以大大提升性能,此时可以自定义一个memorize修饰器
author:Andy
"""
import functools
def memorize(fn):
# 缓存字典
know = dict()
# 为创建修饰器提供便利,保留被修饰函数的__name__和__doc__属性
@functools.wraps(fn)
def memoizer(*args):
# 如果缓存字典中已经存在
if args in know:
return know[args]
# 如果缓存字典中不存在
else:
know[args] = fn(*args)
... | LiUzHiAn/pythonDesignPatterns | decorate_pattern/my_math.py | my_math.py | py | 1,213 | python | en | code | 0 | github-code | 6 |
24993603901 | from osv import fields
from osv import osv
class dm_matchcode(osv.osv):
_name = 'dm.matchcode'
_description = 'Matchcodes for DM'
_columns = {
'name': fields.char('Name', size=64, required=True),
'matchexp': fields.char('Match Expression', size=128, help="""This string defines ... | factorlibre/openerp-extra-6.1 | dm_partner_address/dm_partner_address.py | dm_partner_address.py | py | 1,845 | python | en | code | 9 | github-code | 6 |
2615744068 | # topics = ["Таѕ"]
from typing import List
class Solution:
def simplifyPath(self, path: str) -> str:
st: List[str] = []
for s in path.split('/'):
if not s or s == '.':
continue
if s == '..':
if st:
st.pop()
e... | show-me-code/signInHelper-using-face- | algorithms/[71]简化路径/solution.py | solution.py | py | 389 | python | en | code | 0 | github-code | 6 |
20299042800 | """crud URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based vi... | JairoObregon/django | crud/urls.py | urls.py | py | 1,405 | python | en | code | 0 | github-code | 6 |
19167047686 | """
A part is a component of the overall derp system that communicates with other parts
"""
from derp.util import TOPICS, MSG_STEM, init_logger, subscriber, publisher, get_timestamp
class Part:
""" The root class for every part, includes a bunch of useful functions and cleanup """
def __init__(self, config, n... | notkarol/derplearning | derp/part.py | part.py | py | 2,517 | python | en | code | 40 | github-code | 6 |
26632895276 | import pygame
from setting import *
from bullet import Bullet
class Player(pygame.sprite.Sprite):
#初期化(元グループ、初期位置x、初期位置y)
def __init__(self, groups, x, y, enemy_group):
super().__init__(groups)
#敵グループ
self.enemy_group = enemy_group
#画面取得
self.screen = py... | shu0411/training | python/trainingEnv/shooting/player.py | player.py | py | 5,639 | python | ja | code | 0 | github-code | 6 |
29579733720 | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 7 15:39:51 2018
@author: Akitaka
"""
import numpy as np
from sklearn.model_selection import cross_val_score
from lwpls import LWPLS
def psi(xlist,M):
""" make a design matrix """
ret = []
for x in xlist:
ret.append([x**i for i in rang... | nakanishi-akitaka/python2018_backup | 1207/cross_validation_lwpls.py | cross_validation_lwpls.py | py | 740 | python | en | code | 5 | github-code | 6 |
8829027988 | ########################################################
# Rodrigo Leite - drigols #
# Last update: 21/09/2021 #
########################################################
def OLS(dic):
from matplotlib import pyplot as plt
import pandas as pd
df =... | drigols/studies | modules/ai-codes/modules/linear-regression/src/students_ols_bestLineFit.py | students_ols_bestLineFit.py | py | 1,511 | python | en | code | 0 | github-code | 6 |
70633246909 | #c1 dung for
print("cach 1 dung for")
try:
a,b=map(int, input().split())
except:
print("dau vao ko hop le")
tong=0
for i in range(a,b+1):
tong+=i
print("tong:{}".format(tong))
#c2 dung while
print("cach 2 dung while")
try:
a,b=map(int, input().split())
except:
print("dau vao ko hop le")
tong=0
i=a
... | Clapboiz/Python-basics | tongcacsotrongdoanab.py | tongcacsotrongdoanab.py | py | 383 | python | en | code | 0 | github-code | 6 |
25844066272 | """Test Role"""
import unittest
import json
from flask import url_for
from app.test import BaseTest
class RolePermissionTests(BaseTest):
""" Role Permission Test api class """
def test_insert_update_delete(self):
""" insert, update, delete roles permission"""
role_url = url_for('auth.role_r... | ekramulmostafa/ms-auth | app/test/test_role_permission.py | test_role_permission.py | py | 2,795 | python | en | code | 0 | github-code | 6 |
40341366552 | import os
import re
import selenium
from selenium import webdriver
from time import sleep
from openpyxl import load_workbook
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait # Required for explicit wait
from selenium.webdriver.support import expected_conditions as... | Himu1234/web-automation-chandpur | prepaid_token_generation_xlsx.py | prepaid_token_generation_xlsx.py | py | 3,524 | python | en | code | 0 | github-code | 6 |
130536507 | import numpy as np
import matplotlib.pyplot as plt
import pyRaven as rav
import emcee
import corner
from scipy.stats import norm
import scipy
from statistics import mode
def fitdata(param,DataPacket,guess):
'''
This function fits a set of LSD profiles using scipy's curve fit function.
Inputs:
param - input... | veropetit/pyRaven | fitparams.py | fitparams.py | py | 10,372 | python | en | code | 0 | github-code | 6 |
23947460253 | from game_object.base_object import BaseObject, Wall, Life
import random
class FactoryMethod:
def __init__(self, health=1000, position=None, velocity=None, acceleration=None, size=None, control=None) -> None:
self.health = health
self.position = position or [0, 0]
self.velocity = velocity o... | NoOneZero/wall_game | game_object/factory.py | factory.py | py | 2,244 | python | en | code | 1 | github-code | 6 |
41957074771 | import json
import os
j = None
searchables = {}
path = os.path.dirname(os.path.abspath(__file__))
with open (os.path.join(path, 'fhir_parser/downloads/search-parameters.json'), 'r') as f:
j = json.loads(f.read())
for entry in j['entry']:
resource = entry['resource']
for base in resource['base']:
searchabl... | zensoup/fhirbug | tools/get_searchables.py | get_searchables.py | py | 420 | python | en | code | 14 | github-code | 6 |
42060446091 | import pygame as pg
from settings import *
class Bullet(pg.sprite.Sprite):
def __init__(self, groups):
self.groups = groups
pg.sprite.Sprite.__init__(self, self.groups)
class PlayerBullet(Bullet):
def __init__(self, game, x, y):
self.game = game
self.groups = self.game.sprite... | soupss/space-invaders | sprites/bullet.py | bullet.py | py | 2,099 | python | en | code | 0 | github-code | 6 |
27125372338 | import logging
from datetime import datetime
import smtplib
from notifications import *
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from db.client import db_create_close, r
logging.config.fileConfig('/opt/TopPatch/conf/logging.config')
logger = logging.getLogger('rvapi')
@d... | SteelHouseLabs/vFense | tp/src/emailer/mailer.py | mailer.py | py | 10,469 | python | en | code | 5 | github-code | 6 |
23229945677 | from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
admin.site.site_header = "Адмнистрирование TBO Dashboard"
admin.site.site_title = "Адмнистрирование TBO Dashboard"
admin.site.index_title = "TBO Dashboard"
urlpatterns = ... | alldevic/tbo_dash_old | tbo_dash/urls.py | urls.py | py | 875 | python | en | code | 0 | github-code | 6 |
30162237145 | from tkinter import *
import plateau as plateau
import gestionnaire_evenements as g_evenements
import pions as pions
import debug as de
import gestionnaire_images as g_images
def recommencer_jeu(fenetre,can,*debug):
"""
Relance le jeu avec certains paramètres
:param can: Canva Tkinter
:type can: Objet T... | PierreMonrocq/L1-Latroncules-game | relance.py | relance.py | py | 1,433 | python | fr | code | 0 | github-code | 6 |
10423383033 | from __future__ import annotations
import copy
import dataclasses
import json
from typing import TYPE_CHECKING
import pytest
from randovania.game_description.db.node_identifier import NodeIdentifier
from randovania.games.prime2.layout.echoes_configuration import EchoesConfiguration
from randovania.games.prime2.layou... | randovania/randovania | test/gui/test_tracker_window.py | test_tracker_window.py | py | 17,755 | python | en | code | 165 | github-code | 6 |
21077625640 | import json
import os
import requests
from get_token import GetToken
from log_setup import Logging
from program_data import PDApi
"""
NetApp / SolidFire
CPE
mnode support utility
"""
"""
Package service api calls
https://[mnodeip]/package-repository/1
"""
# set up logging
logmsg = Logging.logmsg()
# disabl... | solidfire/mnode-support-util | api_package_service.py | api_package_service.py | py | 2,719 | python | en | code | 0 | github-code | 6 |
39434540766 | # from sklearn.naive_bayes import MultinomialNB
# from sklearn.naive_bayes import GaussianNB
# from sklearn.cluster import KMeans
import pandas as pd
# from random import shuffle
import numpy as np
import os
# from sklearn.feature_extraction.text import CountVectorizer
# from sklearn.feature_extraction.text import Tfi... | svroo/PNL-Escom | Joder es cine/Modulo/text_proc.py | text_proc.py | py | 3,744 | python | es | code | 0 | github-code | 6 |
72283436667 | import requests
import json
match = {
"Date": "21-01-2023",
"Form": "decent",
"Opposition": "tough",
"season": "middle",
"venue": "home",
"Previous match": "0",
"uEFa": "active"
}
#url = 'http://localhost:9696/predict'
url = 'https://klopp-s-liverp-prod-klopp-s-liverpool-hql7qt.mo4.mogeniu... | Blaqadonis/klopps_liverpool | predict_test.py | predict_test.py | py | 416 | python | en | code | 0 | github-code | 6 |
44354332755 | from datetime import datetime
## Method to remove empty values from a dictionary
def remove_empty_values_from_dict(dictionary):
return {k: v for k, v in dictionary.items() if v is not None and v != '' and v != [] and v != {} }
def pretty_time(seconds):
seconds = abs(int(seconds))
days, seconds = divmod(secon... | eengoron/close-crm-ringcentral-connector | app/format_rc_to_close.py | format_rc_to_close.py | py | 2,444 | python | en | code | 1 | github-code | 6 |
15370026614 | import random
numbers=[1,2,3,4,5,6,7,8,9]
guess=input("your guess : ")
randomNumber=random.choice(numbers)
if randomNumber==guess:
print("you win")
else:
print("you lose")
print("the number is : ")
print(randomNumber) | pavanajmadhu/guessing-python | guessing.py | guessing.py | py | 235 | python | en | code | 0 | github-code | 6 |
4737933535 | #Defines what a 'student' is (Something in your program that has 'name, major, gpa, and is_on_probation' parameters)
class student:
def __init__(self, name, major, gpa, is_on_probation): #Constructor: when creating a new student object, this function is called and uses the given parameters
self.name = name
... | danlhennessy/Learn | Python/fundamentals/OOP/class.py | class.py | py | 1,097 | python | en | code | 0 | github-code | 6 |
24347584300 | # # Categorize all issues
#
# To use: open with jupyter notebook/lab using jupytext and run all cells
# +
from getpass import getpass
from textwrap import dedent
from ipywidgets import Button, ToggleButtons, Output, VBox
from IPython.display import display, Markdown
import gitlab
# -
gl = gitlab.Gitlab(url="https:/... | zesje/zesje | label_issues.py | label_issues.py | py | 2,370 | python | en | code | 9 | github-code | 6 |
72787079228 | import time
import psutil
import scapy.interfaces
from scapy.all import *
from PyQt6.QtCore import QObject, pyqtSignal
class GetInterfaceServer(QObject):
"""捕获网卡信息"""
isActive = True
bytes_flow = pyqtSignal(dict)
interfaces_scapy = scapy.interfaces.get_working_ifaces()
interfaces_psutil = psutil.... | VanCoghChan/CCSniffer | models/GetInterfaceModel.py | GetInterfaceModel.py | py | 1,002 | python | en | code | 0 | github-code | 6 |
26401762339 | # %%
import plotly.express as px
import plotly.graph_objects as go
import os
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pdb
def visualize_map():
# %%
map_prefix = "50_10_5_10_5_2"
ndf = pd.read_csv("" + map_prefix + "_Nodes.csv")... | pwang649/3D_MAPF | hello_world/core/visualization.py | visualization.py | py | 4,687 | python | en | code | 0 | github-code | 6 |
43392192504 | import cv2
import numpy as np
from matplotlib import pyplot as plt
# 模版匹配
img = cv2.imread("fb.png", 0)
img2 = img.copy()
template = cv2.imread("zdbz.png", 0)
w,h = template.shape[::-1]
method = eval("cv2.TM_CCOEFF")
res = cv2.matchTemplate(img2, template ,method)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(r... | frebudd/python | 阴阳师副本自动化/副本自动化2.py | 副本自动化2.py | py | 450 | python | en | code | 2 | github-code | 6 |
35426911515 | #!/usr/bin/python3
import numpy as np
import scipy.integrate
import matplotlib.pyplot as plt
def vdp(t,y):
"""calculate Van Der Pol Derivatives"""
# y is a tuple (y0,y1)
y0dot = y[1]
y1dot = (1-y[0]**2)*y[1]-y[0]
dydt = ( y0dot, y1dot )
return dydt
solution = scipy.integrate.solve_ivp(vdp, t_... | martinaoliver/GTA | ssb/m1a/numeric/Practical_full_solutions_jupyter/python_script_solutions/vanderpol_20191001.py | vanderpol_20191001.py | py | 695 | python | en | code | 0 | github-code | 6 |
28493662472 | ###### Librerias ######
import tkinter as tk
import Widgets as Wd
import Ecuaciones as Ec
import time as tm
import threading as hilos
import numpy as np
###### Modulos De Librerias ######
import tkinter.ttk as ttk
import tkinter.messagebox as MsB
import serial
import serial.tools.list_ports
import matplotlib.pyplot as ... | daridel99/UMNG-robotica | Interfaz.py | Interfaz.py | py | 39,199 | python | es | code | 0 | github-code | 6 |
2418871084 | import torch
import numpy as np
from copy import deepcopy
from typing import List, Optional, Tuple
from torch.utils.data import DataLoader
from supervised.utils import ids, keys, typeddicts
from supervised import saving, data, networks
VERBOSE = False # Default: whether the code output should be verbose
NR_EPOCHS = ... | doggydigit/Biasadaptation-jureca | supervised/simulate/train.py | train.py | py | 17,379 | python | en | code | 0 | github-code | 6 |
43623562044 | #Micah lee 03/12/18
media_type = input("what is the media type? ")
title = input("what is the title ")
des = input("give me a brief description ")
yr = str(input("what year was it created "))
rating = float(input(" what rating would you give this media type (1/10) " ))
new_list = [ title, des, yr, rating ]
if media_ty... | MicLee52/Micah-Lee | micah_lee-assign01.py | micah_lee-assign01.py | py | 414 | python | en | code | 1 | github-code | 6 |
73549603388 | '''
Slakeys Surf Alert
Add Users with the argument "add" "user name * email * surf spot name * surf spot url"
Run with the argument "run"
'''
import sys
from SurfAlertUtils import *
if __name__ == "__main__":
args = sys.argv
args.pop(0)
if len(args) == 0:
print("Welcome to Slakey\'s Surf Alert. If you have no... | aslakey/SlakeysSurfAlert | surfalert.py | surfalert.py | py | 514 | python | en | code | 0 | github-code | 6 |
508734253 | from itertools import permutations
import cProfile
#
#make permutation of array
#
list = [1,2,3,4]
listPermutations = permutations(list)
for permutation in listPermutations:
print(permutation)
#
#count number of permutations
#
listPermutations = permutations(list)
count = 0
for permutation in listPermu... | sleevs/JSNSecurity | Permutations.py | Permutations.py | py | 695 | python | en | code | 0 | github-code | 6 |
71811420988 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""code_info
@Time : 2020 2020/7/9 13:15
@Author : Blanc
@File : double_color_ball.py
"""
# 程序运行之后,从1‐64中挑选5个数作为彩票的抽奖结果
import random
a = list()
for i in range(0, 5):
b = random.randint(1, 64)
a.append(b)
print('双色球号开奖:', a) | Flynn-Lu/PythonCode | 2020python实训/Day7/double_color_ball.py | double_color_ball.py | py | 361 | python | en | code | 0 | github-code | 6 |
24794059633 | #!/usr/bin/env python3
#
import sys, argparse
import ROOT
ROOT.PyConfig.IgnoreCommandLineOptions = True
def h2pgf(h):
""" Convert TH1 into pgfplot data with error bars
input: xmin xmax y ey
output: x ex y ey
ex = (xmax+xmin)/2
"""
nbins = h.GetNbinsX()
# print("# \\begin{axis}")
# print... | kbat/mc-tools | mctools/common/root2pgf.py | root2pgf.py | py | 1,629 | python | en | code | 38 | github-code | 6 |
22117461324 | import rospy
from MyStatics.RealTimePlotter import RealTimePlotter
from MyStatics.GaussianPlotter import GaussPlot
from FaultDetection import ChangeDetection
from geometry_msgs.msg import AccelStamped
from dynamic_reconfigure.server import Server
from accelerometer_ros.cfg import accelerometerGaussConfig
import numpy a... | jcmayoral/collision_detector_observers | collision_observers/accelerometer/accelerometer_ros/src/fault_detection/AccGaussCUSUM.py | AccGaussCUSUM.py | py | 2,101 | python | en | code | 0 | github-code | 6 |
70879484348 | import collections
import functools
from operator import mul
def tokenize(s: str):
tokens = []
words = s.strip().split()
for word in words:
if word.startswith("("):
tokens.append(word[0])
tokens.extend(tokenize(word[1:]))
elif word.endswith(")"):
tokens.... | cj81499/advent-of-code | src/aoc_cj/aoc2020/day18.py | day18.py | py | 2,065 | python | en | code | 2 | github-code | 6 |
74472010426 | import unittest
from car_simulation import Car, Field, main
from unittest.mock import patch
from io import StringIO
class TestCar(unittest.TestCase):
def test_change_direction(self):
car = Car("TestCar", 0, 0, "N", "F")
car.change_direction("R")
self.assertEqual(car.direction, "E")
def... | LiSheng-Chris/car-simulation | car_simulation_test.py | car_simulation_test.py | py | 3,835 | python | en | code | 0 | github-code | 6 |
12258821097 | import math
import random
import time
import carla
import cv2
import numpy as np
actor_list = []
def pure_pursuit(tar_location, v_transform):
L = 2.875
yaw = v_transform.rotation.yaw * (math.pi / 180)
x = v_transform.location.x - L / 2 * math.cos(yaw)
y = v_transform.location.y - L / 2 * math.sin(yaw... | DYSfu/Carla_demo | demo3.py | demo3.py | py | 3,290 | python | en | code | 4 | github-code | 6 |
75235905147 | from v_model import *
aho=visual.box()
par=visual.box()
par.color=visual.color.red
baka=V_PartsObject(FRAME())
baka.set_shape(aho)
pa=FRAME(xyzabc=[0,0,0,pi/4,0,0])
pb=FRAME(xyzabc=[0,0,0,0,pi/4,0])
pc=FRAME(xyzabc=[0,0,0,0,0,pi/4])
pe=FRAME(xyzabc=[1,0,0,0,pi/4,0,0])
pf=FRAME(xyzabc=[0,1,0,0,0,0])
| hsnuhayato/iv-plan-hironx | rmrc_geo_model/src/model/test.py | test.py | py | 300 | python | en | code | 0 | github-code | 6 |
19399824149 | from typing import List
# 438. 找到字符串中所有字母异位词
# https://leetcode-cn.com/problems/find-all-anagrams-in-a-string/
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
p_vec = self.to_vector(p)
s_vec = self.to_vector(s[0: len(p) - 1])
# print(s_vec, p_vec)
i = 0
... | Yigang0622/LeetCode | findAnagrams.py | findAnagrams.py | py | 1,375 | python | en | code | 1 | github-code | 6 |
4552159327 | import random
import sys
sys.path.insert(1, '../')
from utils import read_instance, objetive_function, corrent_solution_size
import config
# Heurística Construtiva 02
# Constructive Heuristic 02
# Random para selecionar o teste e calculado a melhor mesa para aplicá-lo
def constructive_heuristic_02(corrent_size):
d... | guilhermelange/Test-Assignment-Problem | stage_01/constructive_heuristic_02.py | constructive_heuristic_02.py | py | 1,701 | python | en | code | 0 | github-code | 6 |
9401341695 | # coding: utf-8
import re
import requests
response = requests.get('http://ads.fraiburgo.ifc.edu.br')
if response.status_code == 200:
texto = response.content.decode('utf-8')
links = re.findall(r'<a href="(.*?)".*>(.*)</a>', texto)
for url in links:
print(url) | fabricioifc/python_regex_tarefa | exemplos_professor/regex_02.py | regex_02.py | py | 266 | python | en | code | 1 | github-code | 6 |
74548599546 | import boto3
from botocore.exceptions import NoCredentialsError
def upload_to_aws(local_file, bucket, s3_file):
s3 = boto3.client('s3')
try:
s3.upload_file(local_file, bucket, s3_file)
print("Upload Successful")
return True
except FileNotFoundError:
print("The file was not f... | HULKMARXEL/Group_6_AWS_project | localhost/S3.py | S3.py | py | 562 | python | en | code | 0 | github-code | 6 |
32693295741 | class man(object):
# name of the man
name = ""
def __init__(self, P_name):
""" Class constructor """
self.name = P_name
print("Here comes " + self.name)
def talk(self, P_message):
print(self.name + " says: '" + P_message + "'")
def walk(self):
""" This... | code4ghana/randomPrograms | PythonPrograms/testme.py | testme.py | py | 2,360 | python | en | code | 1 | github-code | 6 |
7649624460 | # convolution 계산 함수
import numpy as np
import pycuda.autoinit
from pycuda.compiler import SourceModule
from pycuda import gpuarray, tools
import pycuda.driver as cuda
class padding():
# CUDA Limit size
cu_lim = 32
def __init__(self,D,K,mode='vaild'):
# D : Data, K = kernel,
kw = int(K.shap... | JUHYUKo3o/CUDAKernelStudy | padding.py | padding.py | py | 1,964 | python | en | code | 1 | github-code | 6 |
18385134746 | class MetaSingleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(MetaSingleton, cls).__call__(
*args, **kwargs
)
return cls._instances[cls]
class Logger(metaclass=MetaSingleton):
... | kelvins/design-patterns-python | criacao/singleton/main.py | main.py | py | 1,460 | python | en | code | 468 | github-code | 6 |
18028370803 | import json
from logging import info
import boto3
from botocore.exceptions import ClientError
from lgw.lambda_util import get_lambda_info, grant_permission_to_api_resource
def create_rest_api(
api_name,
api_description,
binary_types,
lambda_name,
resource_path,
deploy_stage,
integration_ro... | ebridges/lgw | lgw/api_gateway.py | api_gateway.py | py | 5,773 | python | en | code | 0 | github-code | 6 |
29778083632 | import stagger
import os
import sys
from stagger.id3 import *
def metaHound(argvPath):
#ef það er sendur parametri inní fallið þá er það slóðin a möppuna
#sem á að fara i gegnum.
#ef ekki er sendur parameter er reiknað með að mappan sem á að fara
#í gegnum sé í cwd.
if argvPath != '':
os.c... | asav13/PRLA-Verk5 | part1/metaDataReader.py | metaDataReader.py | py | 3,804 | python | is | code | 0 | github-code | 6 |
24362863500 | from odoo import models, fields, api
from ..tools.nawh_error import NAWHError
class NetaddictionWhLocationsLine(models.Model):
_name = 'netaddiction.wh.locations.line'
_description = "Netaddiction WH Locations Line"
_order = 'qty'
product_id = fields.Many2one(
'product.product',
requi... | suningwz/netaddiction_addons | netaddiction_warehouse/models/netaddiction_wh_locations_line.py | netaddiction_wh_locations_line.py | py | 4,531 | python | it | code | 0 | github-code | 6 |
73675812026 | import django
from django.conf import settings
import pandas as pd
import os, sys
proj_path = "/home/webuser/webapps/tigaserver/"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tigaserver_project.settings")
sys.path.append(proj_path)
django.setup()
from tigaserver_app.models import Fix
FILE = os.path.join(setti... | Mosquito-Alert/mosquito_alert | util_scripts/update_geo_userfixes_static.py | update_geo_userfixes_static.py | py | 1,682 | python | en | code | 6 | github-code | 6 |
12704422220 | #!/usr/bin/env python3
import asyncio
import discord
import os
client= discord.Client()
TOKEN = os.getenv('USER_TOKEN')
CHANNEL_ID = int(os.getenv('CHANNEL_ID'))
MESSAGE = os.getenv('MESSAGE')
def lambda_handler(event, context):
print("lambda start")
client.run(TOKEN, bot=False)
@client.event
async def on_re... | mgla/lambda-discord-messager | lambda_function.py | lambda_function.py | py | 580 | python | en | code | 0 | github-code | 6 |
38905374725 | from torch import Tensor, LongTensor, max
from typing import Dict
from sklearn.metrics import accuracy_score
def compute_metrics(
outputs: Tensor,
labels: LongTensor,
) -> Dict[str, float]:\
metrics = {}
outputs = outputs.cpu()
labels = labels.cpu()
_, pred = max(outputs.data, 1)
y_true ... | Agiratex/histological-image-classification | utils/compute_metrics.py | compute_metrics.py | py | 570 | python | en | code | 0 | github-code | 6 |
12228572050 | import pygame
import socket
import numpy as np
import math
import random
import time
import sys
class launch_missiles:
def __init__(self, screen, pygame, socket, board, is_client, is_server):
self.screen = screen
self.pygame = pygame
self.socket = socket
self.board = board
... | AtulPhadke/Battleship | missile.py | missile.py | py | 8,591 | python | en | code | 0 | github-code | 6 |
32150136387 | from collections import deque
def solution(queue1, queue2):
answer = -1
queue1Sum = sum(queue1)
queue2Sum = sum(queue2)
sameSum = (queue1Sum + queue2Sum) // 2
queue1Copy = deque(queue1)
queue2Copy = deque(queue2)
cnt = 0
while cnt < len(queue1) * 3:
if sameSum < queue1Sum:... | HS980924/Algorithm | src/8.Queue,Deque/두큐합.py | 두큐합.py | py | 810 | python | en | code | 2 | github-code | 6 |
32731940278 | from collections import deque
n, m = map(int, input().split())
number = list(map(int, input().split()))
deq = deque(i for i in range(1, n+1))
count = 0
for i in range(m):
while True:
if (deq[0] == number[i]):
deq.popleft()
break
else:
if(len(deq) / 2 > deq.ind... | woo222/baekjoon | python/큐,스택/s3_1021_회전하는큐.py | s3_1021_회전하는큐.py | py | 505 | python | en | code | 0 | github-code | 6 |
34390260723 | from pathlib import Path
from datetime import timedelta
import environ
import os
import pymysql
pymysql.install_as_MySQLdb()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
REST_AUTH = {
'SESSION_LOGIN': False
}
###### 환경변수 쪽 설정 ###############... | YCWG/YCWG-BackEnd | ycwg/settings.py | settings.py | py | 6,231 | python | en | code | 0 | github-code | 6 |
30003290472 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Description:
# @File: test.py
# @Project: ip_nlp
# @Author: Yiheng
# @Email: GuoYiheng89@gmail.com
# @Time: 7/15/2019 10:30
import time
from pymongo import ASCENDING
from common import logger_factory
from mongo.connect import get_collection
from mongo.utils.query_fil... | zhenxun815/ip_nlp | src/mongo/doc_service.py | doc_service.py | py | 3,720 | python | en | code | 0 | github-code | 6 |
29098845226 | #!/bin/env python
# This script undoes the "WellFolders.py" script, aka it empties all of the well folders out into the parent folder.
import os
import re
import argparse
parser = argparse.ArgumentParser(description='Takes a folder formatted by WellFolders and undoes it ',
usage='%(p... | jc6213/CRANIUM | UndoWellFolders.py | UndoWellFolders.py | py | 1,123 | python | en | code | 0 | github-code | 6 |
40546898692 | import json
from django.http import JsonResponse
from django.shortcuts import render
from admin_manage.models import Company
from admin_manage.views import method_verify, verify_token
from face_machine_client.models import ClientInfo
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
... | hamster1963/face-all-in-one-machine-backend | face_machine_client/views.py | views.py | py | 6,512 | python | en | code | 0 | github-code | 6 |
19400727989 |
class Car:
def __init__(self, id, brand, model, product_year, convertible):
self.id = id
self.brand = brand
self.model = model
self.production_year = product_year
self.convertible = convertible
def jsonEncoder(car):
if isinstance(car, Car):
return ... | Yifei-G/vintage-car-database | car.py | car.py | py | 426 | python | en | code | 0 | github-code | 6 |
3477127800 | import logging
from dvc.cli.command import CmdBase
logger = logging.getLogger(__name__)
class CmdQueueWorker(CmdBase):
"""Run the exp queue worker."""
def run(self):
self.repo.experiments.celery_queue.worker.start(self.args.name)
return 0
def add_parser(experiments_subparsers, parent_pars... | gshanko125298/Prompt-Engineering-In-context-learning-with-GPT-3-and-LLMs | myenve/Lib/site-packages/dvc/commands/experiments/queue_worker.py | queue_worker.py | py | 656 | python | en | code | 3 | github-code | 6 |
8105081811 | # coding=utf-8
import os
import re
import glob
import MeCab
import torch
from torch import nn
import pickle
import linecache
import pandas as pd
from sklearn.model_selection import train_test_split
import torch.optim as optim
import sys
sys.path.append(os.path.join('./', '..', '..'))
from classification.script.models i... | ys201810/lstm_pytorch | classification/script/train.py | train.py | py | 5,357 | python | en | code | 0 | github-code | 6 |
41255517387 | while True:
try:
a = int(input("Enter a: "))
b = int(input("Enter b: "))
op = input("Operation: ")
break
except:
print('Ви повинні використовувати числа!')
if __name__ == '__main__':
print('Ви запустили цей файл, як головний!\n')
elif __name__ == 'operations':
print('Дякуємо за використання модуля отрима... | timkaaa23/TP-KB-221-Tymofii-Savosta | topic_6/operations.py | operations.py | py | 434 | python | uk | code | 0 | github-code | 6 |
40688712803 | import logging
from feg.protos import s6a_proxy_pb2, s6a_proxy_pb2_grpc
from google.protobuf.json_format import MessageToJson
from magma.common.rpc_utils import print_grpc
from magma.subscriberdb import metrics
from magma.subscriberdb.crypto.utils import CryptoError
from magma.subscriberdb.store.base import Subscriber... | magma/magma | lte/gateway/python/magma/subscriberdb/protocols/s6a_proxy_servicer.py | s6a_proxy_servicer.py | py | 6,492 | python | en | code | 1,605 | github-code | 6 |
39275803820 | ## For random paymentid
import re
import secrets
import sha3
import sys
from binascii import hexlify, unhexlify
import pyed25519
# byte-oriented StringIO was moved to io.BytesIO in py3k
try:
from io import BytesIO
except ImportError:
from StringIO import StringIO as BytesIO
b = pyed25519.b
q = pyed25519.q
l ... | wrkzcoin/TipBot | wrkzcoin_tipbot/cn_addressvalidation.py | cn_addressvalidation.py | py | 11,230 | python | en | code | 137 | github-code | 6 |
72960119867 | """def is_triangle(a, b, c):
if a > (b + c) or b > (a + c) or c > (a + b):
print("You cannot form a triangle with these numbers")
else:
print("You can form a triangle with these numbers")
is_triangle(4, 8, 12)"""
"""def compare(a, b):
if a > b:
#print(1)
return 1
elif a == b:
#print(0)
r... | derinsola01/Projects | sticks.py | sticks.py | py | 578 | python | en | code | 0 | github-code | 6 |
3897488762 | from pointcloud import PointCloud
from evaluation import Evaluation_3d
pc = PointCloud(channel_num=4, filename='../data/TCC12.pcd')
pc.create_vis()
pred_boxes = pc.draw_3dboxes_from_txt('../data/PC_0729_3_pred.txt')
gt_boxes = pc.draw_3dboxes_from_txt('../data/PC_0729_3.txt', color=[1, 0, 1])
eval = Evaluation_3d(pred... | zhangtingyu11/pointcloud_utils | pointcloud_utils/demo.py | demo.py | py | 390 | python | en | code | 0 | github-code | 6 |
24519510155 | from __future__ import print_function
import sys
import re
import argparse
import json
from constants import *
class Graph(object):
"""
contains all data and information about a single graph inside a
:py:class:diagram.Diagram.
"""
def __init__(self,name, signal_accumulators, ylabel, formatting):... | DFE/night-owl | graph.py | graph.py | py | 2,380 | python | en | code | 3 | github-code | 6 |
30299002056 | import datetime
from elasticsearch import Elasticsearch
def insertData():
es = Elasticsearch('[localhost]:9200')
# index : product_list, type : _doc
index = "product_list"
doc = {
"category": "t-shirt",
"price": 16700,
"@timestamp": datetime.datetime.now()
}
es.index(i... | yeahyung/python-flask | study/elastic.py | elastic.py | py | 730 | python | en | code | 0 | github-code | 6 |
15963688161 | # Profundizando tipo float
a = 3.0
# Constructor float puede recibir int y str
a = float(10)
a = float('10')
# print(f'a: {a:.2f}')
# Notación exponencial (valores positivos o negativos)
a = 3e5
a = 3e-5
# print(f'a: {a:.5f}')
# Cualquier cálculo que involucre un float, se promueve a float
a = 4 + 5.0
print(a)
print(t... | Drako01/Python-Curso | 0029/01-03-00-ProfundizandoTipoFlotante-UP.py | 01-03-00-ProfundizandoTipoFlotante-UP.py | py | 329 | python | es | code | 2 | github-code | 6 |
34862439177 | import datetime
import decimal
import urllib.parse
from typing import Dict, Any
from django import template
from django.conf import settings
from django.template.defaultfilters import date
from django.urls import NoReverseMatch, reverse
from django.utils import timezone
from django.utils.safestring import mark_safe
fr... | Status-Page/Status-Page | statuspage/utilities/templatetags/helpers.py | helpers.py | py | 10,704 | python | en | code | 45 | github-code | 6 |
12950748282 | #!/usr/bin/env python
# coding: utf-8
# ## 3. Sphere of influence
# In[1]:
import matplotlib.pyplot as plt
import numpy as np
import scipy.integrate as spy
G = 6.674e-11 #N*m^2/kg^2
# In[2]:
class Body:
def __init__(self, mass, radius,r0,v0):
self.m = mass
self.R = radius
self.r0 = ... | veronicasaz/AstrodynamicsScripts | SimpleExercises/SphereOfInfluence.py | SphereOfInfluence.py | py | 1,078 | python | en | code | 1 | github-code | 6 |
25569721131 | import numpy as np
batch_size_dis = 64 # batch size for discriminator
batch_size_gen = 63 # batch size for generator
lambda_dis = 1e-5 # l2 loss regulation factor for discriminator
lambda_gen = 1e-5 # l2 loss regulation factor for generator
n_sample_dis = 20 # sample num for generator
n_sample_gen = 20 # sample n... | PonderLY/NetworkEmbedding | GraphGAN/config.py | config.py | py | 1,814 | python | en | code | 4 | github-code | 6 |
6829602172 |
# ====================================================
# Quantum Information and Computing exam project
#
# UNIPD Project | AY 2022/23 | QIC
# group : Barone, Coppi, Zinesi
# ----------------------------------------------------
# > description |
#
# dQA utilities: percep... | baronefr/perceptron-dqa | lib/dQA_utils.py | dQA_utils.py | py | 4,128 | python | en | code | 2 | github-code | 6 |
37018522643 | import numpy as np
import statsmodels.api as sm
np.random.seed(2021)
mu = 0
sigma = 1
# number of observations
n = 100
alpha = np.repeat(0.5, n)
beta = 1.5
def MC_estimation_slope(M):
MC_betas = []
MC_samples = {}
for i in range(M):
# to make sure the variance in X is bigger than the variance i... | TatevKaren/mathematics-statistics-for-data-science | Statistical Sampling/Monte Carlo Simulation OLS estimate.py | Monte Carlo Simulation OLS estimate.py | py | 985 | python | en | code | 88 | github-code | 6 |
45484267256 | from setuptools import setup, find_packages
__version__ = '0.8.6'
with open('README.rst', 'r', encoding='utf-8') as fh:
long_description = fh.read()
setup(
name='LMRt', # required
version=__version__,
description='LMR turbo',
long_description=long_description,
long_description_content_type='t... | fzhu2e/LMRt | setup.py | setup.py | py | 1,031 | python | en | code | 9 | github-code | 6 |
17371125676 | from django.contrib import admin
from django.contrib.auth import get_user_model
User = get_user_model()
class UserAdmin(admin.ModelAdmin):
list_display = (
'id',
'first_name',
'last_name',
'username',
'email',
'balance',
'freeze_balance',
'role',
... | vavsar/freelance_t | users/admin.py | admin.py | py | 363 | python | en | code | 1 | github-code | 6 |
7938194140 | import pytesseract
from PIL import Image
import cv2
# Path to the Tesseract executable (you might not need this on Ubuntu)
# pytesseract.pytesseract.tesseract_cmd = r'/usr/bin/tesseract' # You may need to set the correct path to Tesseract on your system
# Open an image file
image_path = 'image.jpeg'
img = Image.open... | KolKemboi/AiMazing | OCR.py | OCR.py | py | 572 | python | en | code | 0 | github-code | 6 |
4728965077 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 11 10:19:22 2018
@author: psanch
"""
import tensorflow as tf
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
import numpy as np
import utils.utils as utils
class BaseVisualize:
def __init__(self, model_name, result_dir, fig_... | psanch21/VAE-GMVAE | base/base_visualize.py | base_visualize.py | py | 1,607 | python | en | code | 197 | github-code | 6 |
8564353511 | import tkinter as tk
import random
from sql import SqlInject
LARGE_FONT = ("Verdana", 12)
data = SqlInject()
class GuiFood(tk.Tk):
def __init__(self, data=data, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side="top", fill="both", ex... | Bainard/activite5 | newgui.py | newgui.py | py | 6,917 | python | en | code | 0 | github-code | 6 |
12580230297 | from django.shortcuts import render
from django.http import JsonResponse
import openai
# Create your views here.
openai_api_key='MI-API-KEY'
openai.api_key=openai_api_key
def ask_openai(message):
response = openai.Completion.create(
model = "text-davinci-003",
prompt= message,
max_tokens=1... | elgualas/MichiAI | chatbot/views.py | views.py | py | 880 | python | en | code | 0 | github-code | 6 |
2734136284 | # -*- coding: utf-8 -*-
"""
@project ensepro
@since 25/02/2018
@author Alencar Rodrigo Hentges <alencarhentges@gmail.com>
"""
import json
import logging
from ensepro.constantes import ConfiguracoesConstantes, StringConstantes, LoggerConstantes
def __init_logger():
global logger
logging.basicConfig(
... | Ensepro/ensepro-core | ensepro/configuracoes/configuracoes.py | configuracoes.py | py | 2,135 | python | pt | code | 1 | github-code | 6 |
40176969885 | from setuptools import setup, find_packages
VERSION = "0.0.6"
DESCRIPTION = "Investopedia simulator trading API"
LONG_DESCRIPTION = (
"An API that allows trading with stock simulator for from Investopedia"
)
install_requires = ["selenium", "schedule"]
setup(
name="simulatorTradingApi",
version=VERSION,
... | mchigit/investopedia-simulator-api | setup.py | setup.py | py | 752 | python | en | code | 0 | github-code | 6 |
5892500320 | import tkinter
import requests
import ujson
import datetime
from PIL import ImageTk,Image
from tkinter import ttk
from concurrent import futures
# pip install: requests, pillow, ujson
#region Static Requests
key = 0000000000 #<-- Riot developer key needed.
# ----------- Request Session -----------
... | WandersonKnight/League-Quick-Data | MainFile.py | MainFile.py | py | 54,615 | python | en | code | 0 | github-code | 6 |
21816512190 | from flask import Flask, request
import json
app = Flask(__name__)
@app.route("/")
def api():
x = request.headers.get("Xxx")
if x == None:
return "missing header"
headers = [header for header in request.headers]
return json.dumps(headers)
if __name__ == "__main__":
app.run(host="0.0.0.0",... | mrtc0/abusing-hop-by-hop-header | app/app.py | app.py | py | 344 | python | en | code | 1 | github-code | 6 |
1175959273 | #!/usr/bin/env python3
"""
Watersheds problem
for Google Code Jam 2009
Qualification Round
Link to problem description:
http://code.google.com/codejam/contest/dashboard?c=90101#s=p1
author:
Chris Nitsas
(nitsas)
language:
Python 3.2.1
date:
April, 2012
usage:
$ python3 runme.py sample.in
or
$ runme.py sample.in
(... | nitsas/codejamsolutions | Watersheds/runme.py | runme.py | py | 3,572 | python | en | code | 1 | github-code | 6 |
70078444988 | import logging
import math
import threading
import time
import torch
#import support.kernels as kernel_factory
from ...support.kernels import factory
from ...core import default
from ...core.model_tools.deformations.exponential import Exponential
from ...core.models.abstract_statistical_model import AbstractStatistic... | lepennec/Deformetrica_coarse_to_fine | core/models/deterministic_atlas_withmodule.py | deterministic_atlas_withmodule.py | py | 45,901 | python | en | code | 0 | github-code | 6 |
35754362412 | import pandas as pandas
import matplotlib.pyplot as pyplot
import numpy as numpy
import streamlit as st
import geopandas as gpd
import pydeck as pdk
from helpers.data import load_data, data_preprocessing, load_geo_data, geo_data_preprocessing
from helpers.viz import yearly_pollution, monthly_pollution, ranking_polluti... | natalie-cheng/pollution-project | main.py | main.py | py | 3,405 | python | en | code | 0 | github-code | 6 |
26609155963 | import pyautogui
import time
def click_on_bluestacks(x, y):
# Attendez 5 secondes pour vous donner le temps de changer de fenêtre
time.sleep(5)
# Trouvez la fenêtre Bluestacks
bluestacks_windows = pyautogui.getWindowsWithTitle('Bluestacks')
# Vérifiez si la fenêtre Bluestacks a été trouvée
if... | Edgarflc/Summoners-War-Bot | test.py | test.py | py | 941 | python | fr | code | 0 | github-code | 6 |
42123413608 | import datetime
from collections import namedtuple
import isodate
from .. import build_data_path as build_data_path_global
from ..input_definitions.examples import LAGTRAJ_EXAMPLES_PATH_PREFIX
TrajectoryOrigin = namedtuple("TrajectoryOrigin", ["lat", "lon", "datetime"])
TrajectoryDuration = namedtuple("TrajectoryDu... | EUREC4A-UK/lagtraj | lagtraj/trajectory/__init__.py | __init__.py | py | 2,892 | python | en | code | 8 | github-code | 6 |
27532635720 | # Question 19
class Py:
def get_String(self, str):
self.str = str
def print_String(self):
print(self.str.upper())
str = input("Enter a String: ")
p1 = Py()
p1.get_String(str)
print("String in uppercase: ", end="")
p1.print_String()
| rudravashishtha/Python_ETE_Solution | 19ques.py | 19ques.py | py | 261 | python | en | code | 0 | github-code | 6 |
32636741250 | import six
from c7n_azure.actions.tagging import Tag, AutoTagUser, RemoveTag, TagTrim, TagDelayedAction
from c7n_azure.actions.delete import DeleteAction
from c7n_azure.filters import (MetricFilter, TagActionFilter,
DiagnosticSettingsFilter, PolicyCompliantFilter)
from c7n_azure.provider ... | LRuttenCN/cloud-custodian | tools/c7n_azure/c7n_azure/resources/arm.py | arm.py | py | 3,163 | python | en | code | 1 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.