seq_id stringlengths 4 11 | text stringlengths 113 2.92M | repo_name stringlengths 4 125 ⌀ | sub_path stringlengths 3 214 | file_name stringlengths 3 160 | file_ext stringclasses 18
values | file_size_in_byte int64 113 2.92M | program_lang stringclasses 1
value | lang stringclasses 93
values | doc_type stringclasses 1
value | stars int64 0 179k ⌀ | dataset stringclasses 3
values | pt stringclasses 78
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
24845865028 | """
GraphEdge class
"""
import math
from typing import List, Set, Tuple, Optional
from ordered_set import OrderedSet
import numpy as np
from commonroad_geometric.external.map_conversion.osm2cr import config
from commonroad_geometric.external.map_conversion.osm2cr.converter_modules.utility import geometry
from commonr... | CommonRoad/crgeo | commonroad_geometric/external/map_conversion/osm2cr/converter_modules/graph_operations/road_graph/_graph_edge.py | _graph_edge.py | py | 18,504 | python | en | code | 25 | github-code | 13 |
41593821062 | #url: https://www.hackerrank.com/challenges/py-check-strict-superset/problem
# Enter your code here. Read input from STDIN. Print output to STDOUT
N = set(input().split(" "))
n = int(input())
j = 0
for i in range(n):
x = set(input().split(" "))
a = N.issuperset(x)
if a == True:
j += 1
print (j ... | Huido1/Hackerrank | Python/04 - Sets/13 - Check Strict Superset.py | 13 - Check Strict Superset.py | py | 326 | python | en | code | 0 | github-code | 13 |
8565605824 | def maxSequence(arr):
n = len(arr)
max_sum=[]
if n==0:
return 0
else:
for k in range(0,n+1):
for i in range(n - k + 1):
current_sum = 0
for j in range(k):
current_sum = current_sum + arr[i + j]
max_sum.append... | agharsh21/codewars_solutions | 5kyu/Maximum subarray sum/maximum-subarray-sum.py | maximum-subarray-sum.py | py | 384 | python | en | code | 0 | github-code | 13 |
1452557180 | import re
import mariadb
import dbcreds
from flask import request, Response
import json
from app import app
import datetime
@app.route("/api/dishes", methods = ["GET", "POST", "PATCH", "DELETE"])
def dishes():
try:
cursor = None
conn = None
conn = mariadb.connect(
... | aldwin101/posbackend | endpoints/dishes.py | dishes.py | py | 9,174 | python | en | code | 0 | github-code | 13 |
5594621790 | import fastcli
import sys
import time
def lancer_test_connexion():
print("Le test de connexion va être lancé...")
server = fastcli.get_best_server()
print("Serveur le plus proche : {}".format(server['sponsor']))
download_speed, upload_speed, ping = fastcli.test_speed(
server['url'], callback=pr... | BreakingTechFr/IpTools-BreakingTech | Scripts/8-vitesseconnexion.py | 8-vitesseconnexion.py | py | 1,433 | python | en | code | 0 | github-code | 13 |
14833289496 | import re
import paho.mqtt.client as mqtt
# Configure the MQTT broker and topic
mqtt_broker = "13.54.15.49"
mqtt_port = 1883
mqtt_topic = "sensor_data/all"
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
client.subscribe(mqtt_topic)
def on_message(client, userdata,... | pkeyur9978/IFN649_Tutorials | Soil_project/subscribe.py | subscribe.py | py | 1,650 | python | en | code | 0 | github-code | 13 |
20421032919 | # -*- coding: utf-8 -*-
"""
Created on Thu May 11 21:09:33 2023
@author: alexa
"""
import pygame
from settings import *
class Player(pygame.sprite.Sprite):
def __init__(self,pos,groups, obstacle_sprites):
super().__init__(groups)
self.image = pygame.image.load('C:/Users/alexa/OneDriv... | alehic173/Python-RPG-Game | player.py | player.py | py | 2,799 | python | en | code | 0 | github-code | 13 |
9620750165 | # ================================== Imports =====================================
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
# =============================== Window Setting ==================================
Window = Tk()
Window.title("Temp Converter")
Window.geometry("5... | Es-Kiani/Temperature-Converter | My Temp Converter Dev.py | My Temp Converter Dev.py | py | 3,984 | python | en | code | 0 | github-code | 13 |
45022384874 | import urllib.request
import os
from bs4 import BeautifulSoup
from selenium import webdriver
import time
from multiprocessing import Pool
import csv
urls = {}
with open('boards.csv', newline='', encoding="ISO-8859-1") as f:
reader = csv.reader(f)
for row in reader:
url = []
url.append(row[1] + ... | Sachin-Ramesh10/Image-Recommendation-System | Crawling/SaveImagesCrawl.py | SaveImagesCrawl.py | py | 2,953 | python | en | code | 0 | github-code | 13 |
3086277385 | from keras.models import Sequential
from keras.layers import Activation
from keras.optimizers import SGD
from keras.layers import Dense
from keras.layers import Dropout
from keras.constraints import maxnorm
from sklearn.metrics import make_scorer
from scipy.stats import spearmanr
from sklearn.preprocessing import Labe... | uhh-lt/poincare | Supervised Evaluation/learners_NN.py | learners_NN.py | py | 4,202 | python | en | code | 0 | github-code | 13 |
14734327185 | '''
217. Contains Duplicate
Solution
'''
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
hm = {}
for i in nums:
if hm.get(i) == None:
hm[i] = 1
else:
hm[i] += 1
if hm.get(i) > 1:
... | messiel12pr/LeetCode | Python/Easy/Contains_Duplicate.py | Contains_Duplicate.py | py | 353 | python | en | code | 1 | github-code | 13 |
29320825183 | import logging
import random
from signal import SIGHUP, SIGINT, SIGTERM, signal
from threading import Event, Thread
from typing import List
from rich.logging import RichHandler
from techflurry.controller.mqtt_client import MQTTClient
log = logging.getLogger(__name__)
FORMAT = "%(message)s"
logging.basicConfig(
... | atraides/techflurry-controller | examples/mqtt_threaded.py | mqtt_threaded.py | py | 2,422 | python | en | code | 0 | github-code | 13 |
43103613152 | '''
Created on Jul 12, 2017
@author: xgo
'''
import sys
import random
def sample_protein_database(filename_str: str, sample_rate_float: float, output_file_str: str) -> None:
keep_sequence_bool = False
with open(output_file_str, 'w') as fw:
with open(filename_str, 'r') as fr:
for line_str ... | guo-xuan/SiprosBenchmark | src/sample_proteins.py | sample_proteins.py | py | 1,159 | python | en | code | 0 | github-code | 13 |
41130624683 | import pygame
class ScoreStage:
def __init__(self, screen : pygame.Surface, x : int, y: int ,score: int)-> None:
"""
Clase que representa el puntaje en un escenario del juego.
Recibe:
Args:
screen (pygame.Surface): Superficie de la pantalla del juego.
x (... | HoracioxBarrios/mi_juego_final_limpio | class_score.py | class_score.py | py | 1,469 | python | es | code | 2 | github-code | 13 |
2255836727 | from hyggepowermeter.services.mqtt.mqtt_base_client import MQTTClient
from hyggepowermeter.services.mqtt.topics.topics_factory import TopicFactory
from hyggepowermeter.utils.logger import logger
class EnergySubscriberClient(MQTTClient):
def on_message(self, _, __, msg):
try:
topic = TopicFacto... | julianhygge/hygge-power-meter-back | hyggepowermeter/services/mqtt/subscriber_client.py | subscriber_client.py | py | 727 | python | en | code | 0 | github-code | 13 |
2074565697 | import datetime
import asyncio
import functools
from .log import *
from .cli import *
from .token import *
def aslist(x):
return x if isinstance(x, (list, tuple)) else [x] if x is not None else []
# data parsing
def pack_entries(data: list, sid=None, ts=None) -> tuple:
'''Pack multiple byte objects into a... | VIDA-NYU/ptgctl | ptgctl/util/__init__.py | __init__.py | py | 3,709 | python | en | code | 0 | github-code | 13 |
13667860633 | from __future__ import absolute_import
from __future__ import print_function
import numpy as np
from keras.models import Model, Sequential
from keras.layers import Input, Flatten, Dense, Dropout, Lambda, Conv2D, MaxPooling2D, TimeDistributed, LSTM, Conv1D
from keras.optimizers import RMSprop
from keras import backend a... | Pykeeper/practice | path_learning_v2/path_learning/model_set.py | model_set.py | py | 5,858 | python | en | code | 0 | github-code | 13 |
72248889939 | #---------------------------------Hi Reader 👋------------------------------------------
# This project contains two projects , means ( Project-112 & Project-113)
#-------------------------------PROJECT - 112-----------------------------------------
import pandas as pd
import plotly.express as pe
impor... | GargiJadhav/Project---112-113 | code.py | code.py | py | 4,490 | python | en | code | 0 | github-code | 13 |
37248575394 | from hashlib import new
from re import L
from this import d
import numpy as np
from collections import defaultdict, namedtuple
from network import Network
import scipy.stats as stats
from scipy import signal
import matplotlib.pyplot as plt
class Admissible_Path(object):
def __init__(self):
super(Admissibl... | Minyu-Shen/SD_shortest_path | main.py | main.py | py | 6,902 | python | en | code | 0 | github-code | 13 |
15470330019 |
from classes import th, pi, os, time #Modules
from classes import low, high, dev_pins, music_path, water_v, play_v, device, operation
from classes import er_pin, u_e, o_e, o_f #Variables
class switch():
def __init__(self, name):
global dev_pins
self.name = name
print(self.name)
self.pin = dev_pin... | rushendranadh/Jarvis | jun_30/new_file.py | new_file.py | py | 4,238 | python | en | code | 1 | github-code | 13 |
31145422596 | import os
import numpy
import module3d
import exportutils
import log
class CProxyRefVert:
def __init__(self, parent, scale):
self._parent = parent
self._scale = scale
def fromSingle(self, words, vnum, proxy):
self._exact = True
v0 = int(words[0])
... | KoenBuys/makehuman_datagen | apps/mh2proxy.py | mh2proxy.py | py | 25,934 | python | en | code | 5 | github-code | 13 |
29030601269 | from sympy import *
import numpy as np
rows,cols=map(int,input().split())
A,p,k,tvf,fgh=[],[],[],[],[]
blank_list=[]
for i in range(cols):
blank_list.append(0)
with open('matrix.txt') as f:
pfg = f.read().strip().split('\n')
A = []
for pf in pfg[0:rows]:
e = pf.split()
elements=e[0:cols]
int_elements... | Namitjain07/homogenous-system-solver | Solver.py | Solver.py | py | 843 | python | en | code | 0 | github-code | 13 |
12775791879 | import psycopg2
import sys
import time
#import pprint
import datetime
# pip install geotext
from geotext import GeoText
debug = False;
def log(msg, obj="", res='y'):
if debug:
if res == "y":
pprint.pprint("[+] " + str(msg) + str(obj))
if res == "e":
pprint.pprint("[-] " + ... | Smart-Harvesting/sh2-dblp-aggregation | src/main/resources/script/geolocationfinder.pyt | geolocationfinder.pyt | pyt | 2,772 | python | en | code | 0 | github-code | 13 |
2534337803 | """
clone a linkedlist with a next pointer and also an arbitrary node pointer
"""
def clone(node):
Tclone = {}
curr = node
head_clone = None
# creat a copy of each element mapped to his clone
while curr.next:
Tclone[curr] = curr
curr = curr.next
# iterate through the clone and ... | fizzywonda/CodingInterview | linkedlist/CloneLinkedList.py | CloneLinkedList.py | py | 549 | python | en | code | 0 | github-code | 13 |
11322532936 | from rdopkg.action import Action, Arg
ACTIONS = [
Action('review_patch',
help="send patch(es) for review",
optional_args=[
Arg('local_patches_branch', metavar='PATCHES_BRANCH',
positional=True, nargs='?',
help="local patches branch with ch... | softwarefactory-project/rdopkg | rdopkg/actions/review/__init__.py | __init__.py | py | 792 | python | en | code | 28 | github-code | 13 |
10269796052 | #writing function name as decimaltobinary and it convert the decimal number into binery number..
def decimaltobinary( decNumber):
bit=[]
actualBinary=[]
actualBinaryNum1=""
counter=0
while counter!=8 :
remainder=decNumber%2
bit.append(remainder)
decNumber=d... | BarshaDstudent/Mypython-project | DecimalNumintoBinary.py | DecimalNumintoBinary.py | py | 551 | python | en | code | 0 | github-code | 13 |
17531130949 |
from __future__ import print_function
import logging
import sys
import gc
import inspect
import unittest
import time
import os
import tempfile
import fnmatch
import weakref
from functools import wraps
from .. import listRefs
from .._p4p import _forceLazy
_log = logging.getLogger(__name__)
_forceLazy()
if not has... | mdavidsaver/p4p | src/p4p/test/utils.py | utils.py | py | 5,717 | python | en | code | 20 | github-code | 13 |
8090387645 | #!/usr/bin/env python3
import os
from parseResults import ParseResults_SubSubfolder, Update_Global_Variables
from readParams import Read_Required_Params
def find_files(root_dir, target_file, target_folder,test_parameter, only_digit_folders=False):
# print(root_dir)
for dirpath, dirnames, filenames in os.walk(r... | Johnemad96/masters | orbslam3_docker/orbslam_modifiedFork/Datasets/parseResults_Generic.py | parseResults_Generic.py | py | 3,879 | python | en | code | 1 | github-code | 13 |
11417331311 | import copy # Import copy for deepcopy
X = "X"
O = "O"
EMPTY = None
def initial_state():
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def player(board):
num_x = 0
num_o = 0
for i in range(0,len(board)):
for j in range(0,len(board[0]))... | yuzgulfatih/minimax_tic_tac_toe | tictactoe.py | tictactoe.py | py | 3,134 | python | en | code | 0 | github-code | 13 |
43083814752 | #
# @lc app=leetcode.cn id=1996 lang=python3
#
# [1996] 游戏中弱角色的数量
#
# @lc code=start
class Solution:
def numberOfWeakCharacters(self, properties: List[List[int]]) -> int:
# 攻击力从大到小排序,防御力从小到大,右边攻击力天然小于等于左边,只需要判定防御力情况即可
properties.sort(key=lambda x: (-x[0], x[1]))
ans = 0
max_defense ... | Guo-xuejian/leetcode-practice | 1996.游戏中弱角色的数量.py | 1996.游戏中弱角色的数量.py | py | 720 | python | zh | code | 1 | github-code | 13 |
21747288994 | from bookmarks.models import Bookmark
from django.contrib.auth.models import User
from bookmarks.serializers import BookmarkSerializer, UserSerializer
from rest_framework import generics
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthent... | msvalina/ksolutions | bookmarks/views.py | views.py | py | 2,117 | python | en | code | 1 | github-code | 13 |
34525423735 |
import time
import json
from pymemcache.client.base import Client
'''
memcached是一款开源、高性能、分布式内存对象缓存系统,
可应用各种需要缓存的场景,
其主要目的是通过降低对Database的访问来加速web应用程序。
'''
data = {'iphone': ['iphone6', 'iphone7', 'iphone8'], 'Android': ['oppo', 'vivo']}
client = Client(('127.0.0.1', 1121))
key = 'Phone_menu'
# client.set(key, json.du... | sczaixian/learn_pratice | learn_pratice/learn_pratice/apps/learn_python/python_memcached.py | python_memcached.py | py | 1,631 | python | zh | code | 0 | github-code | 13 |
25542620752 |
from silverback import *;
import glass;
from ringbuffer import RingBuffer;
class ChatBox( glass.GlassContainer ):
def __init__(self, scopeList):
self.scopeList = scopeList;
glass.GlassContainer.__init__(self);
self.setOpaque(False);
self.buffer = MessageBuffer( self.scopeList );
for i in range(10):
se... | biggeruniverse/srdata | client/game/gui/main/chatbox.py | chatbox.py | py | 9,092 | python | en | code | 1 | github-code | 13 |
33198554329 | from contextlib import contextmanager
from collections import namedtuple
from .compat import is_type, type_name
from .config import Section, Compose
Context = namedtuple('Context', 'section key')
Error = namedtuple('Error', 'context message')
def type_repr(t):
if is_type(t):
return repr(t)
else:
... | vmagamedov/strictconf | strictconf/checker.py | checker.py | py | 5,480 | python | en | code | 1 | github-code | 13 |
33361974713 | #!/home/zsiegel/anaconda3/bin/python
import zauxpy
def main():
# print(...)
if False:
# print(zauxpy.__dict__)
for key, value in zauxpy.__dict__.items():
if key not in ['__builtins__']:
print(key)
print(value, '\n')
print(zauxpy)
pr... | kerazarek/zauxpy | zauxpy_testing_20200306.py | zauxpy_testing_20200306.py | py | 726 | python | en | code | 0 | github-code | 13 |
2355703163 | #!/usr/bin/env python
import pandas as pd
import numpy as np
import fmriprep_singularity as fs
# Define your path names
project_dir = '/sc/arion/projects/k23'
bids_root = f'{project_dir}/BIDS_new/'
output_dir = f'{project_dir}/derivatives/'
fs_license = f'{project_dir}/software/license.txt'
# Define your list of sub... | matty-gee/fmri_tools | preprocessing/fmriprep/run_fmriprep.py | run_fmriprep.py | py | 1,331 | python | en | code | 0 | github-code | 13 |
72999631698 | #Front end for solar forecasting
import backend_solar as backend_solar
from tkinter import *
import tkinter.messagebox
import datetime
from datetime import date
import csv
from tkinter import Menu
import os
from tkinter import filedialog, messagebox, ttk
import tkinter.font as font
import random
def main():
root... | TylerTobin-CS/Solar-Energy-Forecast | frontend_solar.py | frontend_solar.py | py | 17,213 | python | en | code | 0 | github-code | 13 |
74861058257 | import logging
import os
import sys
DEBUG = True # this guy is a flag for extra messaging while debugging tests
#NOTE: Logger and Platform are initialized in TestRunner's main() or Configuration.GetLogger/Platform
Logger = None
LoggerFile = None
Platform = None
PLATFORM_PRO = "PRO"
PLATFORM_DESKTOP = "DESKTOP"
'''... | Esri/solutions-geoprocessing-toolbox | utils/test/Configuration.py | Configuration.py | py | 7,568 | python | en | code | 129 | github-code | 13 |
31151668773 | import math
from itertools import chain
from itertools import accumulate
from functools import reduce
from collections import Counter
from collections import defaultdict
from copy import deepcopy
import numpy as np
import heapq
import sys
sys.setrecursionlimit(10000)
f = open(0).read().strip().split('\n')
field = {}... | obiwac/advent-of-code | 2022/18/main.py | main.py | py | 1,729 | python | en | code | 2 | github-code | 13 |
16886380988 | import os
import jwt
import functools
from datetime import datetime, timedelta
from dateutil import parser
from database import Database
db = Database()
db.init_users_table()
db.init_urns_table()
def remove_key(d, key):
r = dict(d)
del r[key]
return r
def check_dn(dn):
db = Database()
row = db.ex... | kylecribbs/Flask-URN | dockerfiles/urn-flask/security.py | security.py | py | 2,607 | python | en | code | 0 | github-code | 13 |
17059832274 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.Signer import Signer
class SignField(object):
def __init__(self):
self._auto_execute = None
self._signer = None
self._struct_key = None
@property... | alipay/alipay-sdk-python-all | alipay/aop/api/domain/SignField.py | SignField.py | py | 2,005 | python | en | code | 241 | github-code | 13 |
11261647475 | from functools import lru_cache
import sys
from typing import List
class Voxel:
def __init__(self, x, y, z) -> None:
self.x: int = x
self.y: int = y
self.z: int = z
# @lru_cache(None)
def sides(self):
for c in [-1, 1]:
yield Voxel(self.x + c, self.y, self.z)
... | Tethik/advent-of-code | 18/b.py | b.py | py | 2,700 | python | en | code | 0 | github-code | 13 |
74905184017 | import itertools
print('Advent of Code 2015 - Day 09')
with open('day09.txt') as f:
paths = {}
# format of paths:
# {
# start1: {
# dest1: length of start1 to dest1,
# dest2: length of start1 to dest2,
# ...
# },
# start2: {
# dest1: length of s... | kdmontero/aoc | 2015/day09.py | day09.py | py | 1,383 | python | en | code | 0 | github-code | 13 |
6163680529 | import socket
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
import time, pickle, os, sys
import json
from encrypt_decrypt import encrypt, decrypt
from cryptography.hazmat.primitives import serialization... | rajKarra69420/cs355project | bob.py | bob.py | py | 2,226 | python | en | code | 0 | github-code | 13 |
37474234200 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 6 11:48:49 2019
@author: Joop
"""
import numpy as np
from scipy.optimize import linprog
# var names in all CAPS are supposed to be constants
# coordinates counting from up to down, left to right in the grid:
GOAL = (0, 3)
SHIPWRECK = (2, 2)
CRACKS = [(1, ... | EdoardoGuerriero/Reinforcement-Learning-VU-2019- | Linear_programming_policy_iteration.py | Linear_programming_policy_iteration.py | py | 4,937 | python | en | code | 1 | github-code | 13 |
73492596816 | # Binary Tree to Doubly Linked List using Morris Traversal
from queue import Queue
class Node:
def __init__(self,val):
self.val=val
self.left=None
self.right=None
def BuildTree(nodes):
n=len(nodes)
if n==0 or nodes[0]=='N':
return None
q=Queue()
root=Node(int(nodes... | Ayush-Tiwari1/DSA | Days.31/Python/1.Binary-Tree-to-DLL-using-Morris-Traversal.py | 1.Binary-Tree-to-DLL-using-Morris-Traversal.py | py | 1,950 | python | en | code | 0 | github-code | 13 |
27885129242 | import dgl
import torch
import numpy as np
import itertools
import os
import time
import warnings
import argparse
import random
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from utils.criterions import NCESoftmaxLoss, NCESoftmaxLossNS
from models.pretrain.memory_moco import Mem... | KDEGroup/PC-Attack | train.py | train.py | py | 16,692 | python | en | code | 2 | github-code | 13 |
72214435217 | #!/usr/bin/python3
#fileName = "sample.txt"
fileName = "input.txt"
f = open(fileName).readlines()
countLines = 0
line1 = ""
line2 = ""
line3 = ""
commonChar = []
commonChar2 = []
commonChar3 = []
lowercase = "abcdefghijklmnopqrstuvwxyz"
uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
totalCharValue = 0
for line in f:
inf... | thepcn3rd/AdventofCode2022 | d3part2.py | d3part2.py | py | 1,821 | python | en | code | 0 | github-code | 13 |
20215277503 | from selenium import webdriver
from selenium.webdriver.common.by import By
from Pages.BasePage import BasePage
class Checkboxes(BasePage):
def __init__(self,driver):
super().__init__(driver)
# locators for the page
# locator_checkbox_div=(By.XPATH,"//div[@class='example']")
locator_c... | kakamband/HerokuPracticeSelenium | Pages/Checkboxes.py | Checkboxes.py | py | 1,086 | python | en | code | 1 | github-code | 13 |
22497462831 | import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
import py
from jinja2 import Environment
from jinja2.loaders import BaseLoader
from jinja2.exceptions import TemplateNotFound
try:
# This code adds support for coverage.py (see
# http://nedbatchelder.com/code/modules/cover... | minixalpha/SourceLearning | jinja2/jinja2-2.0/tests/conftest.py | conftest.py | py | 4,141 | python | en | code | 107 | github-code | 13 |
18361326709 | import pygame
import pygame_gui
import math
from pygame import Vector2
import pygameoflife.renderer
from pygameoflife.renderer import MenuBar, Renderer, Camera
from pygameoflife.game import Game
MIN_SIZE = (800, 600)
FRAMERATE = 60
class App:
def __init__(self):
pygame.init()
print("Init pygame")
pygame.fon... | Aniruddha-Deb/PyGameOfLife | pygameoflife/app.py | app.py | py | 6,606 | python | en | code | 0 | github-code | 13 |
28014034129 | # coding: utf-8
import numpy as np
def softmax(x):
"""use softmax(x) = softmax(x - max(x)) for x too large
"""
x_T = np.transpose(x)
x_T -= np.max(x_T, axis=0)
y = (np.exp(x_T) / np.sum(np.exp(x_T), axis=0)).T
return y
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
import scipy as sp
d... | ShangruZhong/Toy-Machine-Learning | formulas.py | formulas.py | py | 1,616 | python | en | code | 0 | github-code | 13 |
29206911756 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
import albumentations
import torch
from torch.utils.tensorboard import SummaryWriter
from .cloud_dataset import CloudDataset
from .constants import DATA_DIR, MODEL_DIR, VALIDATION_SPLIT, IMAGE_SIZE_SMALL, IDX2LABELS
from .helpers import ... | myidispg/kaggle-cloud | utils/train_utils.py | train_utils.py | py | 16,304 | python | en | code | 0 | github-code | 13 |
33990148704 | from flask import Flask, render_template, request
from meal_plan import mp
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/project/')
def project_history():
return render_template('project_history.html')
@app.route('/register/')
def form():
return ... | kajankowska/final_project | app.py | app.py | py | 2,084 | python | en | code | 0 | github-code | 13 |
4210181010 | def aWayTooLongString(string):
last = string[len(string)-1]
size = len(string) - 2
if len(string) > 10:
s = string[0] + str(size) + last
return s
else:
return string
print(aWayTooLongString("pneumonoultramicroscopicsilicovolcanoconiosis")) | mhasan09/leetCode_M | aWayTooLongString.py | aWayTooLongString.py | py | 280 | python | en | code | 0 | github-code | 13 |
20507691167 | # -*- coding:UTF-8 -*-
from django.shortcuts import *
from django.template import RequestContext
from django.http import HttpResponse
import urllib
import urllib2
import cookielib
from Server.models import Profile
import BeautifulSoup
from env.env import *
from env.urlmap import *
from django.contrib import ... | pkuapp/pkuapp_server | views.py | views.py | py | 21,034 | python | en | code | 3 | github-code | 13 |
21898052823 | #PAGE 1 - Overview of US Market
import yfinance as yf
import datetime
import pandas as pd
import requests
from bs4 import BeautifulSoup
end = datetime.datetime(2020,3,12)
days = datetime.timedelta(365*3)
start = end - days
metals = ['GLD','SLV','COPX', 'PALL', 'SLX', 'REMX']
major_indexes = ['SPY','INDA','MCHI', 'EWZ... | mcadhoc/Markets-Data-Scraping | data_scripts/scrape_data.py | scrape_data.py | py | 2,321 | python | en | code | 0 | github-code | 13 |
10191452581 | import ssl
from typing import Optional
from requests.adapters import HTTPAdapter
class SSLCiphers(HTTPAdapter):
"""
Custom HTTP Adapter to change the TLS Cipher set and security requirements.
Security Level may optionally be provided. A level above 0 must be used at all times.
A list of Security Lev... | devine-dl/devine | devine/core/utils/sslciphers.py | sslciphers.py | py | 3,699 | python | en | code | 198 | github-code | 13 |
19435710129 | import pandas as pd
# save filepath to variable for easier access
melbourne_file_path = '~/Downloads/melb_data.csv'
# read the data and store data in DataFrame titled melbourne_data
melbourne_data = pd.read_csv(melbourne_file_path)
# print a summary of the data in Melbourne data
melbourne_data.describe()
avg_lot_siz... | hazalkntr/data-works | introML.py | introML.py | py | 1,472 | python | en | code | 0 | github-code | 13 |
30883112726 | def solution(scores):
n = len(scores)
wx,wy=scores[0]
w = wx+wy
scores.sort(key=lambda x:(-x[0],x[1]))
px = scores[0][0]
py = scores[0][1]
answer=1
for i in range(n):
x,y = scores[i]
if x>wx and y>wy:
return -1
if x+y<=w:
continue
... | weeeeey/programmers | 인사고과.py | 인사고과.py | py | 1,404 | python | ko | code | 0 | github-code | 13 |
69897780819 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
def fbnq():
i = 0
sum_f = 0
while i < 10:
i += 1
sum_f = sum_f + i
print(i)
return sum_f
t = fbnq()
print(t) | felixPEK/q1 | day6_ex8.py | day6_ex8.py | py | 195 | python | en | code | 0 | github-code | 13 |
15458690383 | from node import Node
import xml.etree.ElementTree as ET
import random
class BayesNet:
def __init__(self, source):
self.nodes = []
root = source.getroot()
for node in root:
newNode = Node()
for field in node:
if field.tag == 'id':
newNode.set_id(field.text)
elif field.tag == 'name':
... | khanhfumaster/comp3308_assignment2 | part4/classes/bayes_net.py | bayes_net.py | py | 2,147 | python | en | code | 0 | github-code | 13 |
26512131620 | '''
Faça um programa que leia um ângulo qualquer, e mostre na tela o seu seno, cosseno e tangente
'''
from math import sin, tan, cos,radians
ang = float(input("Digite o ângulo que você deseja saber: "))
ang=radians(ang) #para encontrar o radiano do angulo
sen = sin(ang) #sen, cos e tan devem ser calculados em radiano
... | MLucasf/PythonExercises | ex018.py | ex018.py | py | 490 | python | pt | code | 0 | github-code | 13 |
11509894019 |
# coding: utf-8
# In[1]:
import pandas as pd
# In[32]:
class ndist:
# d(p,q) = sqrt(((p1-q1)**2) + ((p2-q2)**2) + ... + ((pn-qn)**2))
def standardize_col(col, mean, sd):
return((col - mean) / sd)
def dataframe(p,q):
data = {'p':p,'q':q}
data_frame = pd.DataFrame(data... | adamrossnelson/distances | archive/ndist_Jan_28_2019.py | ndist_Jan_28_2019.py | py | 1,382 | python | en | code | 1 | github-code | 13 |
37970547080 | from collections import Counter
input_str = "..."
adapters = [0] + sorted(int(line) for line in input_str.split("\n"))
adapters.append(max(adapters) + 3) # Add phone adapter
# Part 1
jolt_differences = Counter(
[adapters[i] - adapters[i - 1] for i in range(1, len(adapters))]
)
print(
f"1-jolt differences: ... | glumia/advent_of_code_2020 | day10.py | day10.py | py | 964 | python | en | code | 0 | github-code | 13 |
14600502464 | # -*- coding: utf-8 -*-
"""
Creates the name_database which provides access to a database of character names.
Classes:
name_database
"""
import sys
import dice
import trace_log as trace
sys.path.append('../../')
class NameDatabase:
"""
The database of character names, sorted by race and gender.
Met... | AidanCopeland/merp | console/name_database/name_database.py | name_database.py | py | 42,682 | python | hr | code | 1 | github-code | 13 |
36617807952 | class LedMatrix(object):
def __init__(self):
self.array = []
self.jump = 16
self.altnum = (1,3,5,7,9,11,13,15)
self.start = 248
for y in range(0,8):
row = []
for x in range(self.start+y, -1, -1*(self.jump) ):
row.append(x)
... | johnjreiser/pisign | matrix.py | matrix.py | py | 440 | python | en | code | 0 | github-code | 13 |
73796061458 | import os
from pathlib import Path
from dotenv import load_dotenv
CONFIG = {}
CONFIG['MAIN'] = str(Path.cwd())
CONFIG['DOCUMENTS'] = str(Path.cwd() / 'docs')
CONFIG.update({
'DB_CONFIG' : str(Path(CONFIG['DOCUMENTS']) / 'db_connect.json'),
'PROMTS' : str(Path(CONFIG['DOCUMENTS']) / 'promts.json'),
'APP'... | Nick2201/chat_gpt_assisstant | app/config.py | config.py | py | 815 | python | en | code | 0 | github-code | 13 |
14400998615 | __author__ = 'Faaiz'
from PySide.QtUiTools import *
from PySide.QtGui import *
from WallObserver import *
from Project import *
class ProjectPageHeader(QWidget, WallObserver):
def __init__(self,system):
QWidget.__init__(self, None)
self.system = system
self.system.addObserver(self)
... | sathachao/Wall | ProjectPageHeader.py | ProjectPageHeader.py | py | 840 | python | en | code | 0 | github-code | 13 |
15977486371 | import matplotlib.pyplot as plt
import scipy.special as ss
import numpy as np
from time import perf_counter
def path_difference(**kwargs):
# Returns a function which computes the optical path difference multiplied
# by the wave number k. The returned function f is a function of the depth
# z and horizonta... | samuelhklumpers/mfi-photosynthetics | psf_generator.py | psf_generator.py | py | 7,129 | python | en | code | 1 | github-code | 13 |
70761869779 | valor = int(input("Informe a quantidade de valores inteiros que deseja somar\n"))
i = 0
soma = 0
while i <= valor:
soma += i
i += 1
print("A soma dos", valor, "primeiros números inteiros é", soma)
| LiajuX/Python-Exercises-2020 | Arquivo12-Ex.4.py | Arquivo12-Ex.4.py | py | 220 | python | pt | code | 0 | github-code | 13 |
30139217522 | from zou.app.services import (
base_service,
projects_service,
notifications_service,
)
from zou.app.utils import cache, events, fields, query as query_utils
from zou.app.models.entity import Entity, EntityLink
from zou.app.models.entity_type import EntityType
from zou.app.models.preview_file import Previe... | cgwire/zou | zou/app/services/entities_service.py | entities_service.py | py | 10,409 | python | en | code | 152 | github-code | 13 |
29723093265 |
# 3. Создайте программу для игры в "Крестики-нолики".
lst = [1, 2, 3,
4, 5, 6,
7, 8, 9]
def print_lst():
print('-------------')
for i in range(3):
print('|', lst[0 + i * 3], '|', lst[1 + i * 3], '|', lst[2 + i * 3], '|')
print('-------------')
return lst
win_combo = [[0, ... | KsuKudrina/SeminarsPython | HomeWork/HomeWork_5/Task_3.py | Task_3.py | py | 2,438 | python | ru | code | 0 | github-code | 13 |
5459884964 | # -*- coding: utf-8 -*-
"""
@contact: lishulong.never@gmail.com
@time: 2019/4/8 下午3:50
"""
import random
def test_c_profile():
for i in range(100):
print(random.random())
if __name__ == '__main__':
test_c_profile()
| lishulongVI/Ilhabela | analysis/c_profile.py | c_profile.py | py | 240 | python | en | code | 0 | github-code | 13 |
40766829169 | import csv
import requests
import json
import pandas as pd
import openpyxl
class Video:
def __init__(self, title, channel):
self.title = title
self.channel = channel
def GetVideoInfo(videoId):
response = requests.get("https://youtube.googleapis.com/youtube/v3/videos?part=snippet&id... | david-ruffner/Youtube-Video-ID-Converter | watch_later_convert.py | watch_later_convert.py | py | 1,658 | python | en | code | 0 | github-code | 13 |
4299518495 |
from tkinter import messagebox
from tkinter import *
from tkinter import simpledialog
import tkinter
from tkinter import filedialog
from imutils import paths
import matplotlib.pyplot as plt
import numpy as np
from tkinter.filedialog import askopenfilename
import numpy as np
import pandas as pd
from sklea... | vinay-kumar-uppala/Major-Project-D9 | WaterLevelPrediction.py | WaterLevelPrediction.py | py | 11,635 | python | en | code | 0 | github-code | 13 |
7733715166 | import npyscreen
import curses
from phonebook.extra import notifications
class RecordsList(npyscreen.GridColTitles):
def __init__(self, *args, **keywords):
super(RecordsList, self).__init__(*args, **keywords)
self.add_handlers({
curses.KEY_RIGHT: self.h_exit_right,
"d": sel... | fiskirton/Phone-book | phonebook/gui/widgets/records_list_widget.py | records_list_widget.py | py | 2,117 | python | en | code | 0 | github-code | 13 |
13054933290 | import numpy as np
# Replace this with your actual dataset
observations = [2.5, 3.0, 2.7, 3.2, 2.8, 3.5, 3.1, 2.9]
# Calculate the sample mean (μ_hat)
sample_mean = np.mean(observations)
# Calculate the sample standard deviation (σ_hat)
sample_stddev = np.std(observations)
print(f"Estimated Mean (μ_hat): {sample_me... | Shivkisku/data_science_problems | GaussianDistributionEstimation.py | GaussianDistributionEstimation.py | py | 402 | python | en | code | 0 | github-code | 13 |
21635325904 | import speech_recognition as sr
from chatterbot import ChatBot
from chatterbot.training.trainers import ListTrainer
# Create a new instance of a ChatBot
bot = ChatBot("Terminal",
storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapter",
logic_adapters=[
"chatterbot.adapters.logic.Mathematical... | RoboticsClubIITK/2016_HuRo | Speech_Engine/Speak_n_chat.py | Speak_n_chat.py | py | 1,887 | python | en | code | 2 | github-code | 13 |
42786879104 | import tkinter as tk
from tkinter import ttk
import main
def button_clicked():
main.swarmSize = swarm_size.get()
main.velocityMultiplier = velocity_multiplier.get()
main.maxNumberOfIterations = iterations.get()
main.c1 = c1.get()
main.c2 = c2.get()
main.w = w.get()
main.pickedFunction = fu... | FilGor/Python-ParticleSwarmOptimization | GUI.py | GUI.py | py | 2,378 | python | pl | code | 0 | github-code | 13 |
32952389742 | from glados import Module
from PIL import ImageFont, Image, ImageDraw
from os.path import join, dirname, realpath, exists
from os import makedirs
class Trumpify(Module):
left_margin = 56
right_margin = 68
font_size = 26
font_pad = 2
def __init__(self, server_instance, full_name):
super(T... | TheComet/GLaDOS2 | modules/general/trumpify.py | trumpify.py | py | 3,079 | python | en | code | 4 | github-code | 13 |
27731721322 | import sys
def solution(n,arr):
arr=sorted(arr,key=lambda x:(x[1],x[0]))
end=arr[0][1]
count=1
for i in range(1,n):
if end<=arr[i][0]:
count=count+1
end=arr[i][1]
print(count)
return count
if __name__=="__main__":
n=int(sys.st... | Wolfsil/CodingTestComplete | python/난이도 어려움/회의실 배정.py | 회의실 배정.py | py | 454 | python | en | code | 0 | github-code | 13 |
10734445138 | class Solution:
def majorityElement(self, nums):
limit=len(nums)/3
counters=[0,0]
cands=[None,None]
# First pass to find the two possible candidates.
for elem in nums:
if elem==cands[0]:
counters[0]+=1
elif elem==cands[1]:
... | Therealchainman/LeetCode | problems/majority_element_ii/solution.py | solution.py | py | 896 | python | en | code | 0 | github-code | 13 |
15356158431 | import numpy as np
import torch.nn as nn
from config import *
class REINFORCE(nn.Module):
def __init__(self, no_states, no_actions):
super(REINFORCE, self).__init__()
self.no_states = no_states
self.no_actions = no_actions
self.net = nn.Sequential(
nn.Linear(no_states... | Syzygianinfern0/Stable-Baselines | Policy Gradients/1. REINFORCE/model.py | model.py | py | 1,744 | python | en | code | 0 | github-code | 13 |
22787858901 | class Solution(object):
def massage(self, nums):
length=len(nums)
if length==0:
return 0
if length<=2:
return max(nums)
result=[nums[0],max(nums[:2])]
for i in range(2,length):
temp=max(result[i-2]+nums[i],result[i-1])
... | lmb633/leetcode | 17.16massage.py | 17.16massage.py | py | 369 | python | en | code | 0 | github-code | 13 |
73485228497 | # A noob programmer was given two simple tasks: sum and sort the elements of the given array
# a = [a1, a2, ..., an]. He started with summing and did it easily, but decided to store the sum he found in some random position of the original array which
# was a bad idea. Now he needs to cope with the second task, sorting... | aslamovamir/codeSignalPractice | shuffled_array.py | shuffled_array.py | py | 1,358 | python | en | code | 0 | github-code | 13 |
21836796146 | import os.path
import openpyxl
def ticket_saver(theme, sender, send_time,path):
my_path = f"/Users/sevak/PycharmProjects/VK_bot/{path}.xlsx"
if os.path.isfile(my_path):
wb = openpyxl.load_workbook(my_path)
wb.active = 0
sheet = wb.active
else:
wb = openpyxl.Workbook()
... | PEBU3OP1/VK_bot | VK_bot/excel.py | excel.py | py | 788 | python | en | code | 0 | github-code | 13 |
25698509032 | #KNN Surprise from kaggle
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from sklearn.model_selection import train_test_split as train_test_split_sklearn
import surprise
from surprise.model_selection.split import train_test_split
from surprise.prediction_alg... | mindis/thesis | retail-rocket /knnbasic.py | knnbasic.py | py | 3,575 | python | en | code | 0 | github-code | 13 |
6148864096 | import settings
import uasyncio as asyncio
from primitives.pushbutton import Pushbutton
from homie.constants import FALSE, TRUE, BOOLEAN
from homie.device import HomieDevice
from homie.node import HomieNode
from homie.property import HomieProperty
from machine import Pin
def reset(led):
import machine
wdt =... | microhomie/microhomie | examples/obi-socket/main.py | main.py | py | 1,871 | python | en | code | 78 | github-code | 13 |
21000711676 | import numpy as np
import random
values = [3.0, 4.0, 1.0, 2.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
def get_percentile(values, N):
k =[0.0]
for i in range(1, N):
s = np.percentile(values, round(i*100/N))
k.append(s)
return k
def get_percentile_number(N):
percentiles = get_percentile(val... | somasan/projectone | six/six35.py | six35.py | py | 1,179 | python | en | code | 0 | github-code | 13 |
22943010034 | import env_examples # Modifies path, DO NOT REMOVE
from sympy import Symbol
import numpy as np
from src import Circuit, CoordinateSystem, VoltageSource, Wire, World
if __name__ == "__main__":
WORLD_SHAPE = (101, 101)
BATTERY_VOLTAGE = 1.0
HIGH_WIRE_RESISTANCE = 1.0
LOW_WIRE_RESISTANCE = 0.01
c... | AlexandreBeliveau/Devoir-electromag | examples/CircuitDCartTest.py | CircuitDCartTest.py | py | 4,989 | python | fr | code | 0 | github-code | 13 |
33255582329 | from django.core.management.base import BaseCommand
from dynamic_initial_data.base import InitialDataUpdater
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
'--verbose', action='store_true', dest='verbose', default=False,
help='Determines if we sh... | ambitioninc/django-dynamic-initial-data | dynamic_initial_data/management/commands/update_initial_data.py | update_initial_data.py | py | 811 | python | en | code | 12 | github-code | 13 |
32125707115 | # -*- coding: utf-8 -*-
"""Module ga4gh.drs.util.method_types.https.py
Contains the HTTPS class, a child of MethodType. HTTPS contains submethods to
download DRS object bytes according to the https url scheme.
"""
from ga4gh.drs.exceptions.drs_exceptions import DownloadSubmethodException
from ga4gh.drs.util.method_ty... | ga4gh/ga4gh-drs-client | ga4gh/drs/util/method_types/https.py | https.py | py | 1,358 | python | en | code | 6 | github-code | 13 |
8082172388 | import cv2
import numpy as np
from numpy import ndarray
import torch
import torch.nn.functional as F
WINDOW_NAME: str = '16 x 9 test'
def getWebcamCapture() -> cv2.VideoCapture:
capture = cv2.VideoCapture(0)
capture.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)
retu... | Alethon/GpuInference | rect_processing/utils.py | utils.py | py | 1,104 | python | en | code | 0 | github-code | 13 |
71276692818 | from __future__ import print_function
'''Procedure'''
#1-4 N/A
#5. The integer, long, and float data types can represent six million
#6. The second one: type('tr' + 5), because you cannot concatenate a string and
#integer. Both data types have to be the same if you are concatenating or
#adding them.
#... | Anshul2004/pythonPer2_2018-2019 | 1.3.5/Kashyap_1.3.5.py | Kashyap_1.3.5.py | py | 1,796 | python | en | code | 0 | github-code | 13 |
43581349086 | from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.utils import platform
if platform == "android":
from jnius import autoclass
BuildVersion = autoclass('android.os.Build$VERSION')
PythonActivity = autoclass('org.r... | brousch/playground | playground/andverinfo/main.py | main.py | py | 1,763 | python | en | code | 2 | github-code | 13 |
12797406030 | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
# automatically opens chrome and performs google search
def search_google(query):
browser = webdriver.Chrome()
browser.get("https://www.google.com")
search = browser.find_element_by_name("q")
search.send_keys(query)
search.send_keys(Ke... | PhelimonSarpaning/AI-Voice-Assistant | google.py | google.py | py | 330 | python | en | code | 0 | github-code | 13 |
7141726869 | import os
from logging import getLogger
from typing import Any, Dict, List, Optional
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.files.storage import default_storage
from django.db import models
from django.db.models import JSONField, Q
from django.utils.transla... | harmony-one/multisig-transaction-service | safe_transaction_service/contracts/models.py | models.py | py | 7,009 | python | en | code | 4 | github-code | 13 |
36214609232 | '''
Adaptation from https://github.com/ternaus/TernausNetV2
'''
import torch.nn as nn
class ConvRelu(nn.Module):
def __init__(self, in_: int, out: int):
super().__init__()
self.conv = nn.Conv2d(in_, out, 3, padding=1)
self.activation = nn.ReLU(inplace=True)
def forward(self, x):
... | artyompal/kaggle_salt | code_gazay/salt/src/components/TernausNetV2/conv_relu.py | conv_relu.py | py | 389 | python | en | code | 0 | github-code | 13 |
8840846428 | # populate_product_review.py
import time
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from django.db import transaction
from faker import Faker
from product.enum.review import RateEnum
from product.enum.review import ReviewStatusEn... | vasilistotskas/grooveshop-django-api | core/management/commands/populate_product_review.py | populate_product_review.py | py | 3,600 | python | en | code | 4 | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.