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
8695805257
from lxml import etree from sys import stdout, stderr def mk_comment(text): return '/*'+text.strip(' ')+'*/\n' header_gen = u"""var wl = require('./build/Release/wayland_client'); var interfaces = {}; exports.interfaces = interfaces; """ interface_template = u"""function %(name)s(proxy) { this.proxy = proxy; ...
cheery/node-wayland
tools/nodeland-scanner.py
nodeland-scanner.py
py
4,464
python
en
code
61
github-code
36
256680613
nbCharettes = int(input()) totalPoids = 0 charettes = [0] * nbCharettes for i in range(nbCharettes): poids = float(input()) charettes[i] = poids totalPoids += poids moyenne = totalPoids / nbCharettes for charette in charettes: print(moyenne - charette)
SlicedPotatoes/France_IOI
Niveau 2/2 – Découverte des tableaux/05 - Répartition du poids.py
05 - Répartition du poids.py
py
268
python
en
code
0
github-code
36
74082781542
# import numpy as np # from sympy import Symbol, Poly, simplify, re, im # from dispersion_relation import longitudinal_disp, transverse_disp # # Number of data points # # N = 10 # k = Symbol('k') # S0 = Symbol('S0') # w = Symbol('w') # S0 = 0.4 # w_array = np.linspace(100,1E7,5) # for w in w_array: # disp_rel =...
tigeryst/alcbl
Numerical Simulation/source/archive/test_solve.py
test_solve.py
py
3,330
python
en
code
0
github-code
36
74302981863
from googleapiclient.discovery import build import my_settings def commentList(video_id): # 테스트 api_key = my_settings.YOUTUBE_API_KEY comment_list = list() api_obj = build('youtube', 'v3', developerKey=api_key) response = api_obj.commentThreads().list(part='snippet,replies', videoId=video_id, maxResu...
dev-grace/youtube_comment_analysis
analysis/comment_list.py
comment_list.py
py
1,494
python
en
code
0
github-code
36
38221724083
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]: n = len(nums) mid = n//2 ...
vaibhavTekk/leetcoding
problems/convert_sorted_array_to_binary_search_tree/solution.py
solution.py
py
878
python
en
code
1
github-code
36
26661454366
import datetime import http import json import sys import time from http.client import HTTPSConnection import discord from discord.ext import commands, tasks import settings def current_time_string(): return datetime.datetime.utcfromtimestamp(time.time()).strftime('%H:%M:%S') class TwitchCog(commands.Cog, nam...
gr3ger/pyGaBot
twitch_cog.py
twitch_cog.py
py
7,835
python
en
code
0
github-code
36
34338900072
# https://leetcode.com/problems/length-of-last-word/ class Solution: def lengthOfLastWord(self, s: str) -> int: lens = 0 totalLen = len(s) curIdx = totalLen - 1 while curIdx >= 0 and s[curIdx] == " ": curIdx -= 1 if curIdx < 0: return 0 lens...
0x0400/LeetCode
p58.py
p58.py
py
440
python
en
code
0
github-code
36
20015190759
import math import datetime # Literal är en konstant värde i koden s = 'This is String' s2 = "This is also another String" # man kan placera text på flera olika rader redan här s3 = '''This is a triple String''' sEmpty = ' ' # problem = 'this won't work' solution = "This os how it´s done" orThatWay = ' "like that"...
yararajjoub/pythonModulo
Modul3/Strings.py
Strings.py
py
2,088
python
sv
code
0
github-code
36
38659585982
from django.forms.models import model_to_dict from django.http import JsonResponse import re class JsonBaseMixin: json_response_class = JsonResponse response_type = 'text/http' accepted_types = ['text/http', 'application/json'] def dispatch(self, response, *args, **kwargs): accept = response.META.get('HTTP_ACCEP...
niklasmh/it1901-band-booking-project
json_views/views.py
views.py
py
2,002
python
en
code
1
github-code
36
438511318
# -*- coding: utf_8 -*- #pytho3.5 import csv import urllib.request import lxml from bs4 import BeautifulSoup import re import codecs # -------------------- main -------------------- if __name__ == '__main__': #2014-2016年に東京と中山で行われた全大会・全日数・全ラウンドの勝敗データを取得 #Webページ(HTML)の取得 # for year in [2014]: # for place i...
Ryota819/Data
競馬/20180501/keiba_blood_to_csv.py
keiba_blood_to_csv.py
py
2,462
python
en
code
0
github-code
36
27379695129
import os import numpy as np import tensorflow as tf from flask import Flask, request, jsonify from tensorflow.keras.preprocessing import image import tensorflow_hub as hub from PIL import Image import io import cv2 import uuid import datetime import random import firebase_admin from firebase_admin import credentials,...
nzwhd/wearit_cloud
app.py
app.py
py
4,354
python
en
code
0
github-code
36
7575866797
# liczby = [2, 6, 12, 14, 16, 77, 52, 1, 4, 9] # min = 0 # for i in range(len(liczby)): # if liczby[i] < liczby [min]: # print("Znalazłem minimum") # print("Nowa wartość minimum to: ", liczby[i]) # print("Nowy indeks minimum to: ", i) # min = i # # liczby[1], liczby[min] = liczby[mi...
TworzeDoliny/bootcamp-08122018
kolekcje/zadanie_12.py
zadanie_12.py
py
881
python
pl
code
0
github-code
36
75273745385
from weather import Weather_object class Weather_CMD: def __init__(self, city_id=None, output_mode='console'): self.ANS_YES = ('1', 'true', 'y', 'yes', 'yo', 'yop') self.object = Weather_object(city_id) if city_id is not None: self.object.city_id = city_id else...
branislavblazek/notes
Python/projekty/weather/weather_cmd.py
weather_cmd.py
py
1,784
python
en
code
0
github-code
36
18316291673
import abc import devtools from typing import Any, AsyncIterator, Optional import kubernetes_asyncio.watch from servo.logging import logger class BaseKubernetesHelper(abc.ABC): @classmethod @abc.abstractmethod async def watch_args(cls, api_object: object) -> AsyncIterator[dict[str, Any]]: ... ...
opsani/servox
servo/connectors/kubernetes_helpers/base.py
base.py
py
1,920
python
en
code
6
github-code
36
36445667629
"""add latest updates Revision ID: 9d2bc5f28130 Revises: 98b564f17b54 Create Date: 2021-02-20 18:07:38.182527 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '9d2bc5f28130' down_revision = '98b564f17b54' branch_labels = None depends_on = None def upgrade(): ...
mhelmetag/mammoth
alembic/versions/9d2bc5f28130_add_latest_updates.py
9d2bc5f28130_add_latest_updates.py
py
898
python
en
code
1
github-code
36
11044632470
import numpy as np from scipy.special import expit as sig import matplotlib.pyplot as plt def sigmoid(arr): return sig(arr) def sigmoid_prime(arr): arr = sigmoid(arr) return arr*(1.0-arr) def train(epoches,X,Y,weightHidden,weightOutput,lR): for epoch in range(epoches): hiddenIn = np.dot(X,we...
mars-boy/deeplearning_handson
neuralnet.py
neuralnet.py
py
2,134
python
en
code
0
github-code
36
7375849160
#!/usr/bin/python3 import shamir import sqlite3 import rsa_encrypt import time import base64 import settings #Class to hold the database class db: name = "" key = "" def __init__(self): self.name = "" self.key = "" #add user secret to the secrets database def add_secret(username, name,...
sellenth/crow
shamir/code/shamir_gen.py
shamir_gen.py
py
3,462
python
en
code
2
github-code
36
14863334950
from argparse import ArgumentParser from screenshot_handler.screen_grabber import ScreenGrabber def read_arguments(): parser = ArgumentParser() parser.add_argument('-d', '--dest-folder', help='Destination folder for the images') parser.add_argument('-m', '--monitor', help='Dimensions for cropped screensho...
Luisetex/HexAI
grab_images.py
grab_images.py
py
799
python
en
code
5
github-code
36
4107413077
import sys input = sys.stdin.readline def update(ind): while ind <= n: BIT[ind] += 1 ind += ind & (-ind) def query(ind): tmp = 0 while ind > 0: tmp += BIT[ind] ind -= ind & (-ind) return tmp n = int(input()) key = {} original = [] values = [] BIT = [0] * (n + 1) for...
AAZZAZRON/DMOJ-Solutions
ccc05s5.py
ccc05s5.py
py
710
python
en
code
1
github-code
36
28248113208
from telebot.types import Message from loader import bot from database.orm import User from states.states import UserStates from keyboards.inline.inline import get_language_keyboard from utils.utils import get_user_state from telebot.callback_data import CallbackData ru_lang = CallbackData('ru_RU', prefix="search") ...
makushatnik/travelbot
handlers/custom_handlers/language.py
language.py
py
1,900
python
en
code
0
github-code
36
1765068678
import numpy as np import matplotlib.pyplot as plt from fact.io import read_h5py import pandas as pd import plotting import click import matplotlib if matplotlib.get_backend() == 'pgf': from matplotlib.backends.backend_pgf import PdfPages else: from matplotlib.backends.backend_pdf import PdfPages columns = [ ...
LukasBeiske/bachelor_thesis_cta
mrk421.py
mrk421.py
py
2,591
python
en
code
0
github-code
36
29282168130
# encoding=utf-8 import config import datetime import threading import time # 每日删除config中网址宣传的Ip列表 def clear_config_ip_days(interval): config.url_ip_list.clear() threading.Timer(interval, clear_config_ip_days).start() # 开启某个任务,固定每日每时执行 def task_start_day_hour(task, which_hour=0, max_error=10, interval=86400...
gaowenhao/AdProject
tools.py
tools.py
py
757
python
zh
code
0
github-code
36
3678024520
import copy import json import logging import os import pickle import warnings import numpy as np from typing import Any, List, Optional, Text, Dict, Tuple import rasa.utils.io from rasa.core.domain import Domain from rasa.core.featurizers import ( TrackerFeaturizer, FullDialogueTrackerFeaturizer, LabelTo...
msamogh/rasa-frames
rasa/core/policies/embedding_policy.py
embedding_policy.py
py
24,298
python
en
code
4
github-code
36
43511135639
import re def latent_representation_to_fasta(latent_representation, length): sequences = [latent_representation[i:i+length] for i in range(0, len(latent_representation), length)] fast_str = "" fast_str += "> oligo\n" fast_str += "\n> oligo\n".join(sequences) return fast_str def get_value_from_fast...
djleonardo1400/jpegdna-ecc
JPEG-DNA-BC-Transcoder-main/simulation/tofasta_webServer_simulation.py
tofasta_webServer_simulation.py
py
882
python
en
code
1
github-code
36
490667732
import math class Entity(): def __init__(self, x, y, char, color, name, blocks=False, block_sight=None, explored=False, fighter=None, ai=None): self.x = x self.y = y self.char = char self.color = color self.name = name self.blocks =...
Denrur/map_as_dict
entity.py
entity.py
py
1,255
python
en
code
0
github-code
36
73068609064
board = [' ' for x in range(10)] def insertLetter(letter,pos): board[pos] = letter def spaceIsFree(pos): return board[pos] == ' ' def printBoard(board): print(' | | ') print(' '+board[1]+'| '+board[2]+' | '+board[3]) print(' | | ') print('-----------') print(' | | ') print(' '+board[4]+'| '+b...
Dishant-L/TicTacToe_Project
TicTacToe.py
TicTacToe.py
py
2,648
python
en
code
0
github-code
36
26721591942
import scrapy from scrapy.http import Request, Response from xdvideo.items import XdvideoItem class CrawlSpider(scrapy.Spider): name = 'xdvideo' allowed_domains = ['sme.xidian.edu.cn'] VIDEOS_PER_PAGE = 15 # start_urls = [f'https://sme.xidian.edu.cn/html/bkjj/zxkt/bdtwl1/list_92_{i}.html' for i in ra...
ttimasdf/XIDIAN-SME-OCW-Crawler
xdvideo/xdvideo/spiders/crawl.py
crawl.py
py
1,554
python
en
code
1
github-code
36
70427092265
# import math def check_prime(n): if n==1: return False if n==2 or n==3: return True if n%2==0 or n%3==0: return False # for i in range(5, math.floor(math.sqrt(n))): # if n%i==0: # return False i = 5 while i*i <= n: if n%i==0: retu...
asu2sh/dev
DSA_SPy/1.Maths/7_check_for_prime.py
7_check_for_prime.py
py
398
python
en
code
3
github-code
36
15287690449
from __future__ import print_function import bisect ######################################################################## # official recepi from doc.python.org # # https://docs.python.org/2/library/bisect.html#searching-sorted-lists # ################################################...
MacHu-GWU/Angora
angora/DATA/binarysearch.py
binarysearch.py
py
6,977
python
en
code
0
github-code
36
34089857022
from source.utils.dataload import loadData from source.programming_languages.pl import PL def mainfunc(): # set coefs here modelSize = 250 learnSize = 158 pl = PL("./datasets/programming languages.csv", [modelSize, learnSize]) curlang = 'Rust' pl.analyzeLanguage(curlang) if __name__ == '__...
Arfabrika/time-series-predictions
main.py
main.py
py
343
python
en
code
0
github-code
36
19197360818
import cv2, os, random, colorsys, onnxruntime, string, time, argparse, uuid, logging import numpy as np from utils import Processing from glob import glob from PIL import Image, ImageDraw, ImageFont import matplotlib.pyplot as plt parser = argparse.ArgumentParser("license") parser.add_argument('-i',"--input", type = s...
Kurmangozhin/plates-recognition-yolo4
module.py
module.py
py
3,557
python
en
code
1
github-code
36
14551216933
from collections import defaultdict from pathlib import Path from typing import DefaultDict, List from jubeatools import song from jubeatools.formats.dump_tools import make_dumper_from_chart_file_dumper from jubeatools.formats.filetypes import ChartFile from jubeatools.utils import group_by from .. import commons as ...
Stepland/jubeatools
jubeatools/formats/konami/jbsq/dump.py
dump.py
py
3,650
python
en
code
4
github-code
36
29870177823
import sys import copy from collections import deque # Running script: given code can be run with the command: # python file.py, ./path/to/init_state.txt ./output/output.txt # Variable ordering heuristics: Most constrained variable + Most constraining variable # Value ordering heuristics: Least constraining value # I...
cs3243-ay1920s2-g30/sudoku
CS3243_P2_Sudoku_30_1.py
CS3243_P2_Sudoku_30_1.py
py
7,898
python
en
code
0
github-code
36
830008449
#!/usr/bin/env python import re import lib.analysis.analyse as a import lib.analysis.component as a_comp import lib.dynamic.component as comp import lib.independence.fs as fs import lib.settings as s import lib.ui.menu as menu # The greater purpose of (functions in) this file is to # ask user what results are to be ...
Sebastiaan-Alvarez-Rodriguez/Meizodon
lib/analysis/menu.py
menu.py
py
8,592
python
en
code
4
github-code
36
7438956466
# Pure Doubly Linked List # My intention is to get familiar with Doubly Linked List before implementing the LRU cache algorithm. class Node: def __init__(self, next = None, prev = None, data = None): self.next = next self.prev = prev self.data = data class DoublyLinkedList: # Adding...
walnut07/GoogleSTEP
Week_2/Doubly-Linked-List.py
Doubly-Linked-List.py
py
2,463
python
en
code
1
github-code
36
21421821259
from flask import Flask,render_template,request from pymongo import MongoClient import subprocess as sp import os mongo_server_url="mongodb://127.0.0.1:27017" client = MongoClient(mongo_server_url) app = Flask("chat app") #here i am going to defind database and collection name db ="lw" collection="flask" #We have to...
MDMOQADDAS/RegistrationApp
app.py
app.py
py
1,857
python
en
code
1
github-code
36
41786469041
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 22 20:10:01 2018 @author: Suveen """ from urllib.request import urlopen from bs4 import BeautifulSoup import ssl import re # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NON...
SuveenMekala/Web_scraping
scrapetest.py
scrapetest.py
py
1,118
python
en
code
0
github-code
36
3474101003
#Python - Partie 2 - Exercice 9 #Script qui affiche 8 carré à la suite. #Importation des module from turtle import * from dessins_tortue import * #Lecture de l'entrée taille=int(input("Entrez la taille des carrés.")) couleur=input("Entrez la couleur des carrés. (en anglais)") for i in range (8): down...
antoinech2/ISN-exercices-Python-Ann-e-1
partie 2/ex9/dessin.py
dessin.py
py
408
python
fr
code
0
github-code
36
34203818933
import torch import torch.nn.functional as F def R_from_axis_angle(k: torch.tensor, theta: torch.tensor): if torch.norm(k) == 0.: return torch.eye(3) k = F.normalize(k, p=2., dim=0) kx, ky, kz = k[0], k[1], k[2] cos, sin = torch.cos(theta), torch.sin(theta) R = torch.zeros((3, 3)).to(k) ...
3dlg-hcvc/paris
utils/rotation.py
rotation.py
py
6,716
python
en
code
31
github-code
36
70934643944
import cv2,os,shutil import numpy as np import argparse ap = argparse.ArgumentParser() ap.add_argument("-i", "--input", required=True,help="directory of the cropped odonates") ap.add_argument("-o", "--output", required=True,\ help="parent directory to which each one be stored") args = vars(ap.parse_args()) ...
robinjacobroy/Odonata_detection
sorting.py
sorting.py
py
2,940
python
en
code
0
github-code
36
3182784604
from datetime import datetime from pyquery import PyQuery as pquery import urllib3 urllib3.disable_warnings() import webbrowser def timestamp(): return datetime.now().strftime('%Y-%m-%d %H:%M:%S') def main(): active = 'https://webbtelescope.org/contents/media/images/2022/028/01G77Q8BTTSEB7ZSB2ZEY49HSQ' ...
bmikolaj/WebbScrap
main.py
main.py
py
1,853
python
en
code
0
github-code
36
36060935686
import requests url = "https://ngl.link/api/submit" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36", "X-Requested-With": "XMLHttpRequest", "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "Or...
zxrby/NGL.Link-Spammer
ok.py
ok.py
py
754
python
en
code
2
github-code
36
43758661213
import csv import shlex import subprocess from decimal import Decimal ZERO = Decimal("0") def execute(cmd): # TODO: check return code process = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE) return process.communicate() # must be used instead of wait def save_inter...
turicas/no-silence
nosilence.py
nosilence.py
py
3,550
python
en
code
10
github-code
36
28224928026
from django.urls import path from . import views urlpatterns = [ # API routes path('', views.index, name='index'), path('library', views.library, name='library'), path('library/<int:song_id>', views.song, name='song'), path('setlists', views.setlists, name='setlists'), path('setlists/<int:id>'...
alexboneham/lyric-library
backend/apis/urls.py
urls.py
py
847
python
en
code
0
github-code
36
16251544507
##### for mounting drive on colab # from google.colab import drive # drive.mount('/content/drive') ################################# import urllib.request import os import time import tensorflow as tf root_path = os.getcwd() def download_images(link_file_images,output_directory,image_type): print("\nDownoading", ...
ashujack/Street-locator
get-data.py
get-data.py
py
1,343
python
en
code
0
github-code
36
35671367197
from django.contrib import admin from import_export import resources from import_export.admin import ImportExportModelAdmin from .models import Product, Inventory, OrderLine from import_export import fields from import_export.widgets import ForeignKeyWidget class ProductResource(resources.ModelResource): class Me...
HirokiShimoi/investoru_app
myapp/admin.py
admin.py
py
1,384
python
en
code
0
github-code
36
495151957
from collections import namedtuple from enum import Enum from dagster import check from dagster.core.definitions import Materialization, SolidHandle from dagster.core.definitions.events import EventMetadataEntry from dagster.core.serdes import whitelist_for_serdes from dagster.core.types.runtime_type import RuntimeTyp...
helloworld/continuous-dagster
deploy/dagster_modules/dagster/dagster/core/execution/plan/objects.py
objects.py
py
8,359
python
en
code
2
github-code
36
10962724593
import base64 import json import requests from cassandra.cqlengine import connection from flask import make_response from flask_restful import Resource from conf.config import CASSANDRA_HOSTS, FRIEND_KEYSPACE from conf.service import USER_INFO_BULK_URL from model.friend import FriendRelation from service.common impor...
glimpseapp/glimpse-service-friend
service/get_friend_list.py
get_friend_list.py
py
1,574
python
en
code
0
github-code
36
22815747066
# This figure requires the grackle chemistry and cooling library. # Visit grackle.readthedocs.org for more information. from matplotlib import pyplot from utilities.testing import * from pygrackle.grackle_wrapper import * from pygrackle.fluid_container import FluidContainer from utilities.api import \ setup_fl...
enzo-project/enzo-method-paper-ApJ-2014
test_problems/IonizationBalance/enzo_paper_equilibrium_figure.py
enzo_paper_equilibrium_figure.py
py
7,156
python
en
code
0
github-code
36
3051216703
#!/usr/bin/python # tetrous.py import wx #All functions and objects from the basic modules will start with a wx. APP_EXIT = 1 class tetrous(wx.Frame): #tetrous was changed from Example def __init__(self, parent, title, *args, **kwargs): super(tetrous, self).__init__(parent, title=title, ...
Shapez/Tetris_Project
tetrous.py
tetrous.py
py
1,269
python
en
code
0
github-code
36
72664562664
import cv2 import numpy as np from matplotlib import pyplot as plt # loading image #img0 = cv2.imread('SanFrancisco.jpg',) img0 = cv2.imread('segmented_img.jpg') # converting to gray scale img = cv2.cvtColor(img0, cv2.COLOR_BGR2GRAY) # remove noise #img = cv2.GaussianBlur(gray,(3,3),0) # convolute with proper kerne...
kateriska/IBP
sobelExercise.py
sobelExercise.py
py
1,025
python
en
code
1
github-code
36
933336823
import copy import uuid import sqlalchemy as sa from sqlalchemy import orm from sqlalchemy.orm import exc as orm_exc from neutron.api.v2 import attributes from neutron.common import core as sql from neutron.common import constants as n_constants from neutron.common import utils from neutron import context as t_contex...
CingHu/neutron-ustack
neutron/db/vm/vm_db.py
vm_db.py
py
67,145
python
en
code
0
github-code
36
41289141746
import itertools from Atom import Atom class Struct: # computes the space when the instance is initialized def __init__(self, name, types): self.name = name self.types = types self.unpackaged = self._calculate_space_unpackaged() self.packaged = self._calculate_space_packaged() self.optimal = s...
mfaria724/ci3641-examen2
pregunta3/Struct.py
Struct.py
py
2,603
python
en
code
0
github-code
36
36011232562
#!/bin/python # -*- coding: utf-8 -*- # Created by 顾洋溢 from test_interfacecase.public.reg_bythird import Reg_bythird import unittest import HTMLTestRunner class Reg_bythirdTestCase(unittest.TestCase): def setUp(self): self.regbythird = Reg_bythird() def test_reg_bythird(self): u""""第三方登录,注...
xuxiuke/Android_test
SmartHomeV6Code_TestTeam-InterfaceTest/test_interfacecase/unite/test_reg_bythird.py
test_reg_bythird.py
py
676
python
en
code
1
github-code
36
17684485992
# -*- mode: python -*- import sys block_cipher = None a = Analysis(['ayab/ayab.py'], pathex=['./ayab'], hiddenimports=[], binaries=[], datas=[('patterns','patterns')], hookspath=[], runtime_hooks=[], excludes=[], w...
Adrienne200/ayab-desktop
ayab.spec
ayab.spec
spec
1,181
python
en
code
null
github-code
36
73934948902
# coding=utf-8 # 笑脸弹跳游戏 import pygame pygame.init() screen = pygame.display.set_mode([800,600]) keep_going = True # step1. 载入图像 # smilePic = pygame.image.load("smile.gif") smilePic = pygame.image.load("data/asprite.bmp") # 去除图像的白色背景和边框,貌似对gif无效 colorkey = smilePic.get_at((0,0)) smilePic.set_colorkey(colorkey) # step...
jellier/forPython2.7
SmileBounce.py
SmileBounce.py
py
1,375
python
en
code
0
github-code
36
2786391582
from typing import Any, NoReturn, List from numpy import ndarray import socket import select import xml.etree.ElementTree as ElementTree import logging import errno from base_classes import PostProcessorBase class SocketServerPostProcessor(PostProcessorBase): """ Outputs data to clients as a TCP server. ...
1777TheVikings/FRC1777-Vision
postprocessors/socketserver.py
socketserver.py
py
2,969
python
en
code
1
github-code
36
73015585385
from nose.tools import assert_raises from libsheep.protocol import Message, MessagePart, Context, Command from libsheep.features.base import BASE, SUP def test_disabled_base_feature_decodes_generic_instance(): m = Message.decode('HSUP ADBASE ADTIGR') assert type(m.command) is Command def test_enabled_base_fea...
exogen/80sheep
tests/test_base.py
test_base.py
py
641
python
en
code
4
github-code
36
31414302477
"""Test suite for Point Redemption Module.""" from .base_test import BaseTestCase, User class PointRedemptionBaseTestCase(BaseTestCase): """Test class for Society point redemption including endpoint.""" def setUp(self): """Set up all needed variables.""" BaseTestCase.setUp(self) self...
andela/andela-societies-backend
src/tests/points_redemption_base_test_case_setup.py
points_redemption_base_test_case_setup.py
py
1,095
python
en
code
1
github-code
36
24903490945
# Importing the Pillow library from PIL import Image, ImageDraw, ImageFont import os def text_wrapper(text, font, max_width): # Totally not stolen from eyong kevin https://gist.github.com/Eyongkevin/adbac2334f1355d8045111c264d80621 list_of_lines = [] if font.getlength(text) <= max_width: return te...
maticahacic/transcript_to_ebook
cover.py
cover.py
py
6,794
python
en
code
12
github-code
36
5951741639
from pymongo import MongoClient import tiktoken from configsecrets import mongoConnection def upload_to_mongo(data): # connect to mongodb with MongoClient(host=mongoConnection["host"], port=mongoConnection["port"], username=mongoConnection["login"], ...
wyler-m/docubot
load_documents.py
load_documents.py
py
1,704
python
en
code
0
github-code
36
41417358000
# Problem statement link # https://leetcode.com/problems/reverse-integer/ class Solution: def reverse(self, x: int) -> int: if x == 0: return 0 negative_flag = False op = "" num = "".join(reversed(str(x))) if num[-1] == "-": negative_flag = True ...
gproxx-coder/LeetCode
reverse-integer.py
reverse-integer.py
py
694
python
en
code
0
github-code
36
2265981494
import os import json import sqlite3 import argparse import logging import pickle from copy import deepcopy import difflib import traceback from semparser.common import registry from semparser.common.utils import print_dict from semparser.modules.semantic_parser.preprocessor.process_spider_sql import get_sql, get_sch...
BorealisAI/DT-Fixup
spider/semparser/modules/semantic_parser/evaluator/spider_evaluator.py
spider_evaluator.py
py
47,165
python
en
code
15
github-code
36
36633682423
# I think there can be something cool to come from this eventually, I'm bad at picking colors import json from json import JSONDecoder class ColorSchemaDeserializationError(Exception): """ Exception deserializing color schema from JSON """ pass class ColorSchema: def __init__(self, name: str = None, ser...
picoevent/picoevent
PicoEvent/ColorSchema.py
ColorSchema.py
py
2,536
python
en
code
0
github-code
36
72487623143
import scipy.io import numpy as np #frames the signal @x into frames of size @frame_size separated by @hop samples def get_frames( x, frame_size, hop ): start_idx = 0 end_idx = frame_size frames = [] limit = x.shape[1] while end_idx <= limit: frames.append( x[:, start_idx:end_idx] ) ...
bperezorozco/lstm_tea_talk
util.py
util.py
py
1,007
python
en
code
0
github-code
36
36343463761
from django.shortcuts import render,redirect from django.core.paginator import Paginator from siteSettings.models import SiteSettings from django.contrib import messages from users.models import User from carts.models import * from .models import * def courses_page(request): if request.user.is_authenticated: ...
benyaminsh/Logofon
courses/views.py
views.py
py
2,657
python
en
code
0
github-code
36
41158523349
#!/usr/bin/env python3 with open('numbers.txt', 'r') as f: text = f.read().split("\n")[:-1] enumerated_list = list(enumerate(text, 1)) dictionary = dict(enumerated_list) for i in dictionary.keys(): print(f"{hex(hash(dictionary[i]))}: '{dictionary[i]}'") lengths = [] for i in text: lengths.append(len(i)) max...
The-Debarghya/Sem4-Assignments
Python/q23.py
q23.py
py
424
python
en
code
1
github-code
36
31626287834
import os import bs4 from nltk.corpus.reader.api import CorpusReader from nltk.corpus.reader.api import CategorizedCorpusReader import nltk import time from sklearn.feature_extraction.text import TfidfVectorizer import pandas as pd from sklearn.cluster import DBSCAN import numpy as np from sklearn.metrics import silhou...
kyle1213/data-mining
_old/abstract_clustering_pca.py
abstract_clustering_pca.py
py
12,035
python
en
code
0
github-code
36
12781939308
""" This file contains a function to get the coordinates from the GPS """ import serial import time import string import pynmea2 #GPS gets coordinates #UART communication protocols def getCoordinates(): port="/dev/ttyAMA0" ser=serial.Serial(port, baudrate=9600, timeout=0.5) dataout = pynmea2.NMEAStreamReader() ne...
JanPat/i-dont-know-go
GPS.py
GPS.py
py
481
python
en
code
0
github-code
36
72705650343
numbers = (1,2,3) # topples are not like arrays, they are not changeable, they are good for making sure a list cannot be changed # example of unpacking coordinates = (1, 2, 3) x, y, z = coordinates # same as # x = coordinates[0] # y = coordinates[1] # z = coordinates[2] print(y)
jjmonte20/pythonPlayground
topple.py
topple.py
py
281
python
en
code
0
github-code
36
43104582394
import csv source = open("Nucleotide.txt", "r") matrix = [[], [], [], [], [], []] for x in range(6): line = source.readline() while True: c = source.read(1) if c == '>' or c=='': break if (c!='\n' and c!='\r') : matrix[x].append(c) distance = [[0 for x in range(6)] for x in range(6)] x=0 for x in ran...
Ras-al-Ghul/UPGMA-Phylogenetic-Tree
Q1a.py
Q1a.py
py
894
python
en
code
2
github-code
36
33639010391
''' main driver file. Responsible for handling user inputs and displaying current GameState ''' import pygame as p from PIL import Image import ChessEngine p.init() WIDTH = HEIGHT = 512 # or you can keep it as 512 DIMENSION = 8 # Chess boards are 8x8 SQ_SIZE = HEIGHT // DIMENSION IMAGES = dict.fromkeys(['wR', 'wN',...
aaliixii/Chess-Engine
ChessMain.py
ChessMain.py
py
3,651
python
en
code
0
github-code
36
17140780409
# Creates a basic BLE Advertiser # Check the Advertiser.py class for more info import sys import time from datetime import datetime, timedelta from Advertiser import Advertiser # Advertise def main(): dt = datetime.now() print("Started at: %s" % dt) # Create advertiser adv = Advertiser() #...
horace1024/ble
run_adv.py
run_adv.py
py
900
python
en
code
0
github-code
36
15708723931
import numpy as np import cv2 as cv import pandas as pd import random from math import ceil from sklearn.utils import shuffle dt = np.dtype(np.float32) def generator(batch_size=50): while True: for j in range(batch_size): Xs = [] Ys = [] count = 0 ...
JackDrinkwater/traffic_lights_detector
src/data_gen.py
data_gen.py
py
5,719
python
en
code
0
github-code
36
33571523766
import random def Rectangle(a,b): x1 = a*b return x1 def sur(a,b): x2 = 2*(a+b) return x2 a = input("長辺:") a = float(a) b = input("短辺:") b = float(b) y=Rectangle(a,b) z=sur(a,b) print("面積:",y) print("周囲:",z)
Yuki1015Mitsunari/YukiMitsunari1015
Py5-4.py
Py5-4.py
py
248
python
en
code
0
github-code
36
38665630567
import matplotlib.pyplot as plt import numpy as np from sympy import * x = Symbol('x') #! INPUT print(""" Bắt đầu chương trình Đây là phương pháp lặp đơn INPUT f(x) với f(x)=0 khoảng phân li nghiệm (a,b) Và thêm SaiSoE đã cho INPUT """) def Phi(x): # ** là mũ # return 1/(x-1.5) return -1/3*x**3 a = -2 b = ...
buihuyhau/HocLaiGTS
2LapDon/a.py
a.py
py
1,044
python
vi
code
0
github-code
36
2808355432
""" INSTANCE METHODS in CLASSES: In instance methods of a class, the first argument is a reference to the instance of the object itself. By convention, this argument is named self. It's automatically passed by Python when you call an instance method on an object. """ import sys class MyClass: def instance_meth...
sirin-koca/Python-Projects
methods-functions/intance_methods.py
intance_methods.py
py
596
python
en
code
0
github-code
36
3195242150
import re class Rule: def __init__(self, regex, fields, pattern): self.regex = re.compile(regex) self.fields = fields self.pattern = pattern def apply(self, cls_factory, text): return self._setattrs(cls_factory(), self._get_match(text)) def apply_many(self, cls_factory, t...
heijp06/regel
regel/rule.py
rule.py
py
968
python
en
code
0
github-code
36
73326093223
#!/usr/bin/python # Import needed to use the GPIO import RPi.GPIO as GPIO from time import sleep import ConfigParser # Tells the program which numbering scheme you're using for the GPIO pins, # BCM is the "Broadcom SOC channel", the name of the pins, as opposed # to the physical numbering of the pins (BOARD). GPIO...
Beamsy/PAIRR
PAIRR/GPIO_utils.py
GPIO_utils.py
py
1,552
python
en
code
2
github-code
36
41165592833
# Imported libraries import random as r import time as t import colorama as col # Functions # little helper function that converts an array of numbers into a string def arr_to_string(arr_nums): arr_str = "" for n in arr_nums: arr_str += str(n) + " " return arr_str # color(numb...
habit456/Python3_Projects_msc
bubble_sort.py
bubble_sort.py
py
4,224
python
en
code
1
github-code
36
6797316241
from django.utils.translation import ugettext_lazy as _ from utils.faker_factory import faker from ..mails import BaseMailView class ProjectsMemberRoleChangedMailView(BaseMailView): """ """ template_name = 'mails/projects/member_role_changed.html' mandatory_mail_args = [ 'name', 'us...
tomasgarzon/exo-services
service-exo-mail/mail/mailviews/projects_member_role_changed.py
projects_member_role_changed.py
py
818
python
en
code
0
github-code
36
40954037620
import nltk.classify.util from nltk.classify import NaiveBayesClassifier from nltk.corpus import movie_reviews def extract_features(word_list): return dict([(word, True) for word in word_list]) if __name__=='__main__': # Load positive and negative reviews positive_fileids = movie_reviews.fileids('pos') n...
pkankariya/CS5560_Knowledge_Discovery_Management
ICP_10/Sentiment_Analysis.py
Sentiment_Analysis.py
py
3,729
python
en
code
0
github-code
36
6301255873
from flask import current_app, g, Flask, flash, jsonify, redirect, render_template, request, session, Response import logging import sqlite3 import json import requests from db import DB, KeyNotFound, BadRequest import datetime # Configure application app = Flask(__name__) app.config['JSON_SORT_KEYS'] = False # Ensu...
sarikam1/DatabaseModelling
Database Modelling/server/app.py
app.py
py
20,869
python
en
code
0
github-code
36
20543918172
from copy import deepcopy from pandas import DataFrame as DF from scipy.spatial.transform import Slerp from scipy.spatial.transform import Rotation as R import pandas as pd import numpy as np import matplotlib.pyplot as plt import os id = 0 USE_SLERP = False class Sample: def __init__( self, source...
Oloqq/activity-recognition
recognizer/samples.py
samples.py
py
7,117
python
en
code
0
github-code
36
36450057709
def bubble_up_max(node, heap): heap.append(node) i = len(heap) - 1 while (heap[i // 2] < node) : new_i = i // 2 heap[new_i], heap[i] = heap[i], heap[new_i] i = new_i def bubble_up_min(node, heap): heap.append(node) i = len(heap) - 1 while (heap[i // 2] > n...
mehrshad-sdtn/Algorithm-Design
src/Heap.py
Heap.py
py
1,911
python
en
code
0
github-code
36
31977214474
load("@gapid//tools/build:cc_toolchain.bzl", "cc_configure") load("@gapid//tools/build/rules:android.bzl", "android_native_app_glue", "ndk_vk_validation_layer", "ndk_version_check") load("@gapid//tools/build/rules:repository.bzl", "github_repository", "maybe_repository") load("@gapid//tools/build/third_party:breakpad.b...
google/agi
tools/build/workspace.bzl
workspace.bzl
bzl
12,552
python
en
code
815
github-code
36
38967305907
def solution(people, tshirts): answer = 0 people.sort() tshirts.sort() for p in range(len(people)): if people[p] in tshirts: del tshirts[tshirts.index(people[p])] answer += 1 elif people[p] not in tshirts: tshirts = [i for i in tshirts if i > peop...
leehyeji319/PS-Python
프로그래머스/피어리뷰/1주차 중간고사_2.py
1주차 중간고사_2.py
py
474
python
en
code
0
github-code
36
26443050513
# -*- coding: utf-8 -*- """ Created on Thu May 28 11:29:23 2020 @author: jampi """ """BUG FIX NOTES: -needs functions change so intake array is not edited array """ import csv #Function to cut eva def cut_eva(EVA_width, cut_list_in, cut_pieces_in = [],EVA_consumption_length = 0, k = -1, main_cut...
Epic-Cyclops/Guillotine-Cut
Guillotine_Cut_Algorithm.py
Guillotine_Cut_Algorithm.py
py
13,129
python
en
code
3
github-code
36
40507960364
from django import template from apps.carts.models import * from apps.products.models import Category register = template.Library() @register.simple_tag(takes_context=True) def get_user_cart(context): request = context['request'] user = request.user try: cart = Cart.objects.get(client=user, is_or...
MansurSobirjonov/ogani
apps/products/templatetags/cart_tag.py
cart_tag.py
py
817
python
en
code
1
github-code
36
27769825762
import numpy as np import pandas as pd # 1:Male 0:Female flag=['1','0','1','1','0','0','1','1','1','0'] # 1 Yes 0 No datalist = [['1','0','0','0'], ['1','1','1','1'], ['0','0','0','0'], ['1','1','1','1'], ['1','0','1','0'], ['0','0','0','0'], ['1...
kshsky/PycharmProjects
machinelearning/bayes/test1.py
test1.py
py
2,394
python
en
code
0
github-code
36
11352936054
import pandas as pd from sklearn.ensemble import RandomForestClassifier def train_random_forest(): # ****** Fit a random forest and extract predictions # forest = RandomForestClassifier(n_estimators = 100) # Fitting the forest may take a few minutes print("Fitting a random forest to labeled trai...
electronick1/stairs_examples
bag_of_words/bag_of_words/model.py
model.py
py
644
python
en
code
5
github-code
36
37348679197
from math import pi from collections import defaultdict import numpy as np from my_gpaw.kpt_descriptor import KPointDescriptor from .kpts import RSKPoint, to_real_space def create_symmetry_map(kd: KPointDescriptor): # -> List[List[int]] sym = kd.symmetry U_scc = sym.op_scc nsym = len(U_scc) compcon...
f-fathurrahman/ffr-learns-gpaw
my_gpaw/hybrids/symmetry.py
symmetry.py
py
6,817
python
en
code
0
github-code
36
12427469941
import os, sys import logging import numpy as np import pandas as pd import matplotlib.pyplot as plt from collections import defaultdict import multiprocessing from functools import partial import gensim from gensim import models, matutils from gensim.corpora import MmCorpus, Dictionary from scipy.stats import entropy ...
karakayaonurr/Topic-Modelling-with-LDA-at-Twitter
lda_tuna.py
lda_tuna.py
py
8,596
python
en
code
0
github-code
36
9194485366
# coding: utf-8 """ Lightly API Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501 OpenAPI spec version: 1.0.0 Contact: support@lightly...
tibe97/thesis-self-supervised-learning
lightly/openapi_generated/swagger_client/models/tag_arithmetics_request.py
tag_arithmetics_request.py
py
6,991
python
en
code
2
github-code
36
4543553383
import numpy as np import cv2 import matplotlib.pyplot as plt pt_1 = './pt_2D_1.txt' pt_2 = './pt_2D_2.txt' f1 = open(pt_1, 'r') f2 = open(pt_2, 'r') pt_1 = [] pt_2 = [] for line in f1.readlines(): x = line.rstrip('\n').split(' ') pt_1.append(x) for line in f2.readlines(): x = line.rstrip('\n').split('...
yehsin/CV_class_hw2
1/hw2-1.py
hw2-1.py
py
5,803
python
en
code
0
github-code
36
23944279921
import pyaudio import numpy as np from core.tools.buffer import AudioBuffer class PyAudio(): def __init__(self,verbose=True): """ instantiate pyaudio client and buffer for input stream recording to plot """ self.input_stream = None # on start will beinput stream from mic via pyaudio...
AlexKingsland/GuitarGuru
core/tools/pythonaudio.py
pythonaudio.py
py
1,200
python
en
code
0
github-code
36
17981838498
#!/usr/bin/python3 import requests import subprocess # to execute bash commands import sys try: check_for_package = subprocess.Popen(("dpkg", "-s", "html2text"), stdout=subprocess.PIPE) output = subprocess.check_output(("grep", "Status"), stdin=check_for_package.stdout) check_for_package.wait() opstr ...
technodict/Parcel_Tracking_CLI
tracking.py
tracking.py
py
1,131
python
en
code
2
github-code
36
31561340570
#!/usr/bin/env python # coding=utf-8 # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None """ 给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。 k 是一个正整数,它的值小于或等于链表的长度。 如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。   示例: 给你这个链表:1->2->3->4->5 当 k = 2 时,...
lee3164/newcoder
leetcode/25. K 个一组翻转链表/main.py
main.py
py
2,005
python
zh
code
1
github-code
36
74325129065
import unittest import textwrap from test.parse_helper import TransformTestCase class TestSubscript(TransformTestCase): def test_list_indexing_valid(self): owl = textwrap.dedent(r""" bool[] b = [True, False] b[0] """) self.assertNoTransformError(owl) def test_list_indexing_var_valid(self): owl = text...
dashuaige92/owl
test/transform/test_subscript.py
test_subscript.py
py
600
python
en
code
1
github-code
36
69808754346
import numpy as np import matplotlib import matplotlib.pyplot as plt from PIL import Image from scipy import interpolate def floats_to_rgb(x, min=-1, max=1): """ Translates floats in [min, max) to valid RBG integers, in [0, 255]. Values are clamped to min and max. """ x = np.array(x) out = 25...
kr-colab/product-space-FEM
simulation/maps/map_utils.py
map_utils.py
py
9,643
python
en
code
2
github-code
36