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
30046164899
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed unde...
openstack/senlin
senlin/tests/unit/engine/test_cluster_policy.py
test_cluster_policy.py
py
5,169
python
en
code
44
github-code
1
14247111818
from typing import Text import requests import json import pprint as pp from datetime import datetime import re def get_suggestions(search_string: str): base_url = 'https://utility.arcgis.com/usrsvcs/servers/b89ba3a68c664268b9bdea76948b4f11/rest/services/World/GeocodeServer/suggest' query_data = { ...
jmmeneguel/SaneparWaterRestrictionCalendar
src/Sanepar/main.py
main.py
py
3,227
python
en
code
5
github-code
1
74965848034
class Solution(object): def getMinimumDifference(self, root): """ :type root: TreeNode :rtype: int """ arr = [] def helper(root): if not root: return arr.append(root.val) helper(root.left) helper(root.rig...
GreatTwang/lccc_solution
Python/Tree/Minimum Absolute Difference in BST.py
Minimum Absolute Difference in BST.py
py
561
python
en
code
2
github-code
1
1952095518
import torch import torch.nn as nn import torch.nn.functional as F import logging import collections from util import compute_aggreeings, AverageMeter, get_mask, mask_tokens def eval(model, val_loader, a2v, args, test=False): model.eval() count = 0 metrics, counts = collections.defaultdict(int)...
antoyang/just-ask
train/train_videoqa.py
train_videoqa.py
py
6,219
python
en
code
103
github-code
1
6759682425
import json class Kasir: stokBarang = {} barangPembeli = {} def __init__(self): pass def simpanBeliJson(self): with open("beli.json", "w") as beliFileJson: json.dump(Kasir.barangPembeli, beliFileJson) def isiStok(self): with open("stok.json", "r") as stokRea...
TakayumAja/ipplUasSem5
Kasir.py
Kasir.py
py
5,060
python
en
code
0
github-code
1
41244035127
import glob import argparse import re import os.path import shutil import sys import tempfile import itertools import json VALID_PROTOCOLS = ['git', 'ssh', 'http', 'https', 'ssh-colon', 'file', 'relative'] VERSION = '0.2.0' parser = argparse.ArgumentParser( description = 'Recursively search directory for .git...
misje/git-rename-uri
git-rename-uri.py
git-rename-uri.py
py
13,138
python
en
code
0
github-code
1
33198791197
from datetime import datetime from django.core.paginator import Paginator from django.db.models import Q from django.http import JsonResponse from django.core.serializers import serialize from django.shortcuts import render from django.urls import reverse_lazy from django.views.generic import CreateView, DeleteView, D...
Sampleeeees/MyHouse24
Master_application/views.py
views.py
py
5,264
python
en
code
0
github-code
1
35153355955
import sys import os #Caesar class: # variables: charToInt and intToChar # functions: getCharListFromFile(), writeToFile(), getIntListFromCharList(), getCharListFromIntList(), getWordListFromCharList(), encrypt(), decrypt(), bruteforce() # description: The Caesar class can encrypt and decrypt text from a file u...
worth-winchester/caesar
caesar.py
caesar.py
py
13,055
python
en
code
0
github-code
1
20185994114
''' Task 3 Написати функцiю season, яка приймає один аргумент — номер мiсяця (вiд 1 до 12), яка буде повертати пору року, якiй цей мiсяць належить (зима, весна, лiто або осiнь)''' def season(num_month): dict_season = {(1,2,12):'Winter', (3,4,5):'Spring', (6,7,8):'Summer', (9,10,11):'Autumn'} for key in dict_se...
Elena-from-UA/GeekHub_PYTHON_2021
HT_3/3.py
3.py
py
549
python
uk
code
0
github-code
1
17335067722
# -*- coding: utf-8 -*- __doc__ == """ Simple view that exposes a REST API over HTTP to retrieve the least of last read books from a bookshelf. To run it: .. code-block:: python $ python last_read.py --topic mytopic --broker <BROKER_ADDR>:9092 --port 8080 --name lastread --id lastread1 --tags book last This will...
antifragilesoftware/sandbox
kafka/microservices/last_read.py
last_read.py
py
2,901
python
en
code
1
github-code
1
38907288611
import math import random import pygame import sys from pygame.locals import * from copy import deepcopy pygame.init() pygame.mixer.init() width, height = 640, 480 screen = pygame.display.set_mode((width, height)) player1keys = [False, False, False, False] player2keys = [False, False, False, False] player1pos = [0] #M...
prfy9b/Ponkle
Ponkle/main.py
main.py
py
7,606
python
en
code
0
github-code
1
20165127873
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.dashboard, name='dashboard'), url(r'^add_mentor$', views.add_mentor, name='add_mentor'), url(r'^add_investor$', views.add_investor, name='add_investor'), url(r'^show_startups$', views.show_startups, name='show_start...
ramgopal18998/incubator-management-system
Startup_incubator/administrator/urls.py
urls.py
py
1,817
python
en
code
1
github-code
1
26062016837
# In class naming convension we use camel casing in which first word of the name # is capital # Class is blueprint of object. just like an architecture which first draws the blueprint # of any construction. He can use that same blueprint for another constructions also. like that # we define class as blueprint of ob...
dharmraj2061998/Python-Practice
Classes.py
Classes.py
py
1,172
python
en
code
0
github-code
1
7757712695
#coding=utf-8 import sys import pygame from Bullet import Bullet from Alien import Alien from time import sleep def check_keydown_events(event,ai_settings,screen,ship,bullets,stats,play_Button,aliens,sb): """按键响应""" #按下的是方向键右 if event.key == pygame.K_RIGHT: ship.moving_right = True #按下的是方向键左 ...
zXin1112/Python-Practice
alien_invasion/alien_invasion/game_function.py
game_function.py
py
9,113
python
en
code
0
github-code
1
41321025697
import streamlit as st import pandas as pd import matplotlib.pyplot as plt import pickle from joblib import dump, load from sklearn import ensemble from sklearn import metrics import numpy as np def main(): GrBosstClass = load_GRB() Bagging = load_Bagging() data = loadSet() defaulData = loadDefaultSet() cur...
sanloid/WheaterPrediction
App.py
App.py
py
5,315
python
ru
code
0
github-code
1
20828379656
from users.models import MossaicUser from risk_models.models import * from projects.models import * from communities.models import * from django import forms from django.forms.models import * from django.forms import ModelForm, Textarea from django.forms.widgets import HiddenInput from django.forms.models import inli...
parauchf/mossaic
communities/forms.py
forms.py
py
1,961
python
en
code
1
github-code
1
33519675992
import wx from wx.lib.agw import customtreectrl from wx.lib.agw.aui import GetManager from ..controller.project import Project from ..pluginapi import Plugin from ..pluginapi.plugin import ActionInfo class FileExplorerPlugin(Plugin): """Provides a tree view for Files and Folders. Opens selected item with mouse r...
robotframework/RIDE
src/robotide/ui/fileexplorerplugin.py
fileexplorerplugin.py
py
5,378
python
en
code
910
github-code
1
13035732107
from pyramid.httpexceptions import HTTPError from pyramid.httpexceptions import HTTPNotFound from oekocms.views import error_view from oekocms.views import exception_decorator from fanstatic import Library from fanstatic import Resource import kotti.static as ks lib_oekocms = Library('oekocms', 'static') view_css = ...
chrneumann/oekocms
oekocms/__init__.py
__init__.py
py
1,328
python
en
code
0
github-code
1
41858320835
import json notas = list() medias = list() auxiliar = list() def cadastro_aluno(ficha): cont = 0 resp = 'S' print('\nCADASTRAR ALUNO\n') while cont < 1 and resp in 'Ss' : aluno = input('Digite o nome do aluno: ') cad = 0 for alunos in ficha: for nome in alunos: ...
niverton-felipe/unifacisa
cadastro.py
cadastro.py
py
16,107
python
pt
code
0
github-code
1
18709135690
# program to find smallest number in a list print("========= Naive Method ========") l = [ i for i in input("List: ").split(" ")] min1 = l[0] for i in range(len(l)): if l[i] < min1: min1 = l[i] print("Smallest Element: ",min1) print("\n======= Ask for user input =========") list1 = [] n = int(input(...
dilipksahu/Python-Programming-Example
LIst Programs/smallestElement.py
smallestElement.py
py
536
python
en
code
0
github-code
1
27990442786
import requests import threading import sys import os from bs4 import BeautifulSoup from pandas import DataFrame from functools import reduce if len(sys.argv) == 1: CSV_FNAME = 'volunteermatch_data.csv' else: CSV_FNAME = sys.argv[1] URL_PART1 = 'https://www.volunteermatch.org/search/' locations = ['New+York%...
UChicago-Tech-Team-In2It/scraping
scrape.py
scrape.py
py
2,580
python
en
code
0
github-code
1
35733666865
# -*- coding: utf-8 -*- # @Time : 2020/11/22 8:50 # @Author : Zhongyi Hua # @FileName: ssr_utils.py # @Usage: # @Note: # @E-mail: njbxhzy@hotmail.com from Bio import SeqIO from os import remove as del_file import multiprocessing as multi from tqdm import tqdm def build_rep_set(repeat_file, unit_cutoff=None, motif_l...
Hua-CM/IdenSSR
ssr_utils.py
ssr_utils.py
py
5,154
python
en
code
2
github-code
1
16929617299
name = input('Enter file: ') handle = open(name) counts =dict() for line in handle: words = line.split() for word in words: counts[word] = counts.get(word, 0) + 1 print('Number of words fox: ', counts.get('fox', 0)) print('Number of every word as dictionary: ', counts) '''bigcount = None bigword = None ...
vyya/scicom_w_python
count_word_get.py
count_word_get.py
py
714
python
en
code
0
github-code
1
24486343784
import time start = time.time() ''' MAXN=1000 dp = [0]*(MAXN) # base case dp[0] = 1 for i in range(1,MAXN): dp[i] = dp[i-1] * i print(dp[-1]) ''' ''' list1 = [0]*10 list2=list1 list1.append(2) list2.extend([3,4]) print(list1) print(list2) ''' def area(length: int, width: int): print(length * width) area_func...
mw197hub/codingame
hilfen/dynamicP.py
dynamicP.py
py
409
python
en
code
0
github-code
1
11510469822
# Released under the MIT License. See LICENSE for details. # """Playlist related functionality.""" from __future__ import annotations import copy import logging from typing import Any, TYPE_CHECKING import babase if TYPE_CHECKING: from typing import Sequence from bascenev1._session import Session Playlist...
efroemling/ballistica
src/assets/ba_data/python/bascenev1/_playlist.py
_playlist.py
py
20,107
python
en
code
468
github-code
1
39497286221
#유클리드 호제법 def gcd(a,b): while b != 0: a,b = b, a%b return a #오일러의 phi def phi(n): #1과는 어차피 서로소이므로 최솟값은 1 result = 1 for i in range(2,n): if gcd(i,n) == 1: #2부터 n-1까지 n과의 최대공약수가 1이면 result += 1 return result
yundaehyuck/Python_Algorithm_Note
theory_source_code/number_theory/euler_phi_basic.py
euler_phi_basic.py
py
396
python
ko
code
0
github-code
1
22052343006
from .base import * SECRET_KEY = '3@(2#f78$ima@91y04uhqy*r6c98syn+79xff2=6^6f-b9_5=a' DEBUG = True ALLOWED_HOSTS = ['*'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } INSTALLED_APPS += [ 'debug_toolbar', 'django_e...
capuche777/school-demo
school/settings/dev.py
dev.py
py
669
python
en
code
0
github-code
1
33460982801
import bpy import os from io_scs_tools.utils.printout import lprint from io_scs_tools.utils import get_scs_globals as _get_scs_globals def strip_sep(path): """Strips double path separators (slashes and backslashes) on the start and the end of the given path :param path: path to strip separators from :type...
paypink/BlenderTools
addon/io_scs_tools/utils/path.py
path.py
py
24,096
python
en
code
null
github-code
1
43536840385
n = int(input("")) m = int(input("")) def get_align(matriz, coluna): column = [] for i in range(len(matriz)): column.append(matriz[i][coluna]) column.sort(reverse=True) return len(str(column[0])) matrizes = [[[int(i)**2 for i in input().split()] for i in range(m)] for i in range(n)] ...
lopes-gustavodossantos/College_Activities
1º Semester/Programming Fundamentals/Lesson 12/ex1.py
ex1.py
py
593
python
en
code
0
github-code
1
18204561723
"""URL patterns for Directory Services""" from django.urls import path # Must be full path import to allow including url patterns in project urls from os2datascanner.projects.admin.import_services import views urlpatterns = [ path('ldap/add/<uuid:org_id>', views.LDAPAddView.as_view(), name='...
os2datascanner/os2datascanner
src/os2datascanner/projects/admin/import_services/urls.py
urls.py
py
1,526
python
en
code
8
github-code
1
10273949450
""" wordcloud.py: A reusable library for word cloud visualizations """ """ from PIL import Image from wordcloud import WordCloud, STOPWORDS import matplotlib.pyplot as plt import pandas as pd def make_wordcloud(results, vid_dict): cloud = WordCloud(background_color="white",width=1000,height=1000, max_words=10,re...
johnmccarthy23/textbeast
wc.py
wc.py
py
871
python
en
code
0
github-code
1
73631206115
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="outlierpack-NG", version="0.1.0", author="Nikhil Gupta", author_email="ngupta_be17@thapar.edu", description="Removing outliers from a pandas dataframe", url='https://github.com/CachingNik...
CachingNik/OutlierPack
setup.py
setup.py
py
629
python
en
code
1
github-code
1
73152578915
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import AbstractUser from django.db.models.signals import m2m_changed from django.core.mail import send_mail import uuid from time import sleep import geocoder import urllib3 urllib3.disable_war...
donlafranchi/gfcmap
general/models.py
models.py
py
3,400
python
en
code
0
github-code
1
41055718886
import json from test_tools.example_stubber import ExampleStubber class OrganizationsStubber(ExampleStubber): """ A class that implements a variety of stub functions that are used by the AWS Organizations unit tests. The stubbed functions all expect certain parameters to be passed to them as par...
awsdocs/aws-doc-sdk-examples
python/test_tools/organizations_stubber.py
organizations_stubber.py
py
3,333
python
en
code
8,378
github-code
1
19509604543
import json import pytest from api.processing import units from unyt import unyt_quantity def test_unyt_encoder(): test_unyt_dict = { "test_quantity": unyt_quantity(5, "Mpc"), } expected = '{"test_quantity": "5 Mpc"}' assert expected == json.dumps(test_unyt_dict, cls=units.UnytEncoder) def...
UCL-ARC/dirac-swift-api
tests/test_units.py
test_units.py
py
3,144
python
en
code
1
github-code
1
33357721855
import pygame from pygame.surface import Surface import sys from Screens.Content import Content, State from Options.Options import KEY_REPEAT_DELAY, KEY_REPEAT_INTERVAL, TITLE_H_START, TITLE_W_START, TITLE_H_SIZE, BUTTON_H, BUTTON_W, FONT, BRICK_SIZE, ICON_H, ICON_W from Options.Colors import Colors, Color_mod class...
HTsuyoshi/py-tetris
src/Screens/Settings.py
Settings.py
py
4,030
python
en
code
1
github-code
1
10085711322
#!/usr/bin/python3 import os import argparse BASE_CMD = 'gtimeout 60 stack exec -- hplus \"{query}\" --stop-refine\ --stop-threshold=10 --cnt=5' def main(): parser = argparse.ArgumentParser(description='Run a single hoogle+ query') parser.add_argument('query', help='the signature to be searched'...
TyGuS/hoogle_plus
scripts/run_query.py
run_query.py
py
442
python
en
code
56
github-code
1
28773429057
atual = 1 anterior = 0 soma = 0 soma_par = 0 soma_impar = 0 soma_quad = 0 indice = 0 print(" %i" %anterior) while(soma <= 4000): c = atual print(" %i" %atual) atual = atual + anterior anterior = c soma += atual indice += 1 if(indice % 2 == 0): soma_par += atual else: soma...
camilobmoreira/Fatec
1_Sem/Algoritmos/fibonacci_com_soma_de_indices.py
fibonacci_com_soma_de_indices.py
py
518
python
pt
code
0
github-code
1
44291414984
import os, math, re, gc import decimal import numpy as np import scipy as sp import calendar from attrdict import AttrDict from eccodes import * GRID_SIZE = 0.75 RADIUS = 3 GRIB_FOLDER = '/media/isa/VIS1/' def drange(x, y, jump): x_ = decimal.Decimal(x) while x_ < y: yield float(x_) x_ += decimal.Decima...
Ironbell/nn-weather
save_location.py
save_location.py
py
6,763
python
en
code
0
github-code
1
4325563120
from Project.src.NeuralNetworks.neural_networks import NN import numpy as np classFeatures = [("mon_intensity", np.float), ("mon_duration", np.float), ("mon_hr", np.float), ("tue_intensity", np.float), ("tue_duration", np.float), ("tu...
gasperthegracner/psis2017
Project/src/NeuralNetworks/Sample/OptimizationSample.py
OptimizationSample.py
py
2,198
python
en
code
0
github-code
1
3588852824
import logging from typing import Any, Dict from sqlalchemy import NUMERIC, DateTime, bindparam, case, func, select from sqlalchemy.dialects.postgresql import INTERVAL from sqlalchemy.sql import Select from sqlalchemy.sql.functions import concat from execution_engine.constants import CohortCategory from execution_eng...
CODEX-CELIDA/execution-engine
execution_engine/omop/criterion/drug_exposure.py
drug_exposure.py
py
10,683
python
en
code
2
github-code
1
31518563478
import flask from flask import Flask, render_template, request, redirect from web3 import Web3 app = Flask(__name__) candidates = {1: "badi mohammad", 2: "hamza saht", 3: "omar hussein"} # Connect to the Sepolia network web3 = Web3( Web3.HTTPProvider( "https://eth-sepolia.g.alchemy.com/v2/ji4q...
NaturalT314/Dapp-Voting-System
app.py
app.py
py
3,156
python
en
code
0
github-code
1
20564522844
from re import search import hashlib from Crypto.Cipher import AES from Crypto import Random import os from configparser import ConfigParser from locale import getdefaultlocale import gettext from subprocess import check_output, CalledProcessError import logging from logging.handlers import TimedRotatingFileHandler imp...
j4321/CheckMails
checkmailslib/constants.py
constants.py
py
8,761
python
en
code
3
github-code
1
39893956481
import ipaddress import math class FirstSpyEstimator: def __init__(self, tx_maps, true_sources: {ipaddress.ip_address: [int]}): self.p = 0.0 self.r = 0.0 self.r_old = 0.0 benign_nodes = len(true_sources) self.observer_map = {} # BLOCK_ID: observer txs = sorted([it...
jansp/kadcast-privacy
kadcast/estimators.py
estimators.py
py
1,833
python
en
code
2
github-code
1
8604062010
import kivy from kivy.app import App from kivy.uix.widget import Widget from kivy.clock import Clock from kivy.uix.tabbedpanel import TabbedPanelItem, TabbedPanel from kivy.uix.gridlayout import GridLayout from kivy.uix.label import Label from kivy.uix.textinput import TextInput from kivy.uix.checkbox import CheckBox f...
jurrutiag/Robotic-Manipulator
InfoDisplay/InformationWindow.py
InformationWindow.py
py
14,142
python
en
code
0
github-code
1
27982625722
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, TIMESTAMP, Float, Table from sqlalchemy.orm import relationship from sqlalchemy.sql.sqltypes import Text from database import Base class User(Base): __tablename__ = "users" # user_id, roll_no, name, email, phone_number, password, c...
Gautam-Nanda/FEAST
models.py
models.py
py
4,781
python
en
code
0
github-code
1
2350374306
''' Lex Strings Name: <your name> ''' from collections import Counter, defaultdict # # Complete the 'rearrangedString' function below. # # The function is expected to return a STRING. # The function accepts following parameters: # 1. STRING s # # 1. This function will filter the alphanumeric characters from the str...
tkong9/ACSL-Sr
Assignments/lex.py
lex.py
py
2,876
python
en
code
1
github-code
1
27969864189
# coding=utf-8 from django import forms from django.db.models import Q from django.forms.models import formset_factory from BanBanTong.db import models class RolePrivilegesForm(forms.ModelForm): class Meta: model = models.RolePrivilege exclude = ['uuid', 'role'] class RoleForm(forms.ModelForm)...
xiaolin0199/bbt
apps/BanBanTong/forms/role.py
role.py
py
1,348
python
en
code
0
github-code
1
6585776436
import threading import time import serial.tools.list_ports from os import environ from re import search from PyQt6.QtCore import QObject, pyqtSignal from UM.Platform import Platform from UM.Signal import Signal, signalemitter from UM.OutputDevice.OutputDevicePlugin import OutputDevicePlugin from UM.i18n import i18nC...
Ultimaker/Cura
plugins/USBPrinting/USBPrinterOutputDeviceManager.py
USBPrinterOutputDeviceManager.py
py
6,487
python
en
code
5,387
github-code
1
32952521600
import binascii import base58 import hashlib from hashlib import sha256 from ecdsa import SECP256k1,VerifyingKey,util,BadSignatureError from six import b #字符串按字节反转。大小端数据的字符串转换。eg:"123456" to "563412" def str_reverse_on_byte(data): return binascii.hexlify(binascii.unhexlify(data)[::-1]).decode() #16进制字符串转整型。eg:"11...
whichouno/Python
BlockChain/Utils.py
Utils.py
py
8,269
python
de
code
0
github-code
1
22083646633
import win32com.client def WMIDateStringToDate(dtmDate): strDateTime = "" if (dtmDate[4] == 0): strDateTime = dtmDate[5] + '/' else: strDateTime = dtmDate[4] + dtmDate[5] + '/' if (dtmDate[6] == 0): strDateTime = strDateTime + dtmDate[7] + '/' else: strDateTime = strD...
chriskowk/PycharmProjects
PyQtTest/win32services.py
win32services.py
py
3,076
python
en
code
0
github-code
1
30800137028
import constants import base_class character_default_move_speed = 5 # pixels/tick character_default_wall_cooldown = constants.framerate*15 character_boosted_move_speed = 8 # pixels/tick default_effect_durations = { 'speed' : 10*constants.framerate, 'tripleshot' : 10*constants.framerate, 'bulletspeed' : 10...
KiRtAp2/shooter2
character.py
character.py
py
3,553
python
en
code
0
github-code
1
13638926947
#!/usr/bin/env python3 def insert_char(input, rules): new_input = dict(input) for seq in input: if input[seq] > 0: first = seq[0]+rules[seq] second = rules[seq]+seq[1] num = input[seq] new_input[seq] -= num new_input[first] += num ...
maketakunai/aoc2021
python/14b.py
14b.py
py
1,401
python
en
code
0
github-code
1
41745155125
ready = True while(1): while(ready): x = input('waiting for command : ') if x == 'start': print('send start to Pc2') ready = False if x == 'top': print('000000000000000 [x,y]') while(not ready): y = input('side of picture and degree: ').split()...
sirget/Data-Communication
Assignment Datacom/test.py
test.py
py
359
python
en
code
0
github-code
1
71710416995
import json import requests import pandas as pd import sweetviz as sv import pandas_profiling def extract_data(url = "http://api.tvmaze.com/schedule/web?date=2020-12-"): data = [] for i in range(1,32): url_api = url + str(i).zfill(2) result = requests.get(url_api) dato = json.loads(r...
Harolencio/lulo_bank_data_test
src/automatic_process.py
automatic_process.py
py
7,651
python
en
code
0
github-code
1
33458298086
def encode_range(r): i, j = r if i == j: return str(i) else: return f"{i}-{j}" def encode(g): result = [[int(i), int(i)] for i in g] changed = True while changed: changed = False prev = [None, None] for i, r in enumerate(result): if prev[1] i...
soundmud/soundrts
soundrts/lib/group.py
group.py
py
1,334
python
en
code
37
github-code
1
70852848035
import torch import torchvision from torch import nn class MyBetaModel(nn.Module): def __init__(self): super(MyBetaModel, self).__init__() self.convModel = nn.Sequential( nn.Conv2d(3, 32, kernel_size=5, stride=1, padding=2), nn.MaxPool2d(2), nn.Conv2d(32, 32, 5,...
JevonLiuZz/PyTorchBaseStone
Models/BetaModel.py
BetaModel.py
py
1,062
python
en
code
0
github-code
1
28833725406
import sqlite3 import typing from timetable_loader import BaseTimetableLoader def add_new_user(cursor: sqlite3.Cursor, user_id, group_id: int): cursor.execute(""" INSERT INTO users VALUES (?, ?) """, (user_id, group_id)) def delete_timetable_for_group(cursor: sqlite3.Cursor, group_id: int): cur...
just3mhz/timetable_bot
sql_queries.py
sql_queries.py
py
874
python
en
code
1
github-code
1
44303046716
import gym import numpy as np from keras_ppo_icm import Agent if __name__ == '__main__': #env_name = 'MountainCar-v0' env_name = 'CartPole-v1' env = gym.make(env_name) agent = Agent( input_shape=env.observation_space.shape, action_num=env.action_space.n, alpha=1e-3, bet...
Techno263/rl-exploration
keras_ppo_icm/keras_ppo_learn.py
keras_ppo_learn.py
py
2,196
python
en
code
0
github-code
1
70752880033
with open('day22.txt') as file: lines = [line.strip() for line in file.readlines()] def parse_commands(lines, min, max): commands = [] for line in lines: command, coords_string = line.split() coords_separate_string = [coord[2:] for coord in coords_string.split(',')] cube = tuple((int(min), int(max) + 1) for m...
blat-blatnik/Advent-of-Code
2021/day22.py
day22.py
py
1,664
python
en
code
0
github-code
1
840103315
def solution(rows, columns, queries): li_matrix = [[x+(y*columns)+1 for x in range(columns)] for y in range(rows)] dir = [(1,0),(0,1),(-1,0),(0,-1)] answer = [] for query in queries: sy,sx,ey,ex = query sx,sy,ex,ey = sx-1,sy-1,ex-1,ey-1 size = 2*(ex-sx+1)+2*(ey-sy+1)-4 cn...
smileostrich/algorithm-practice
problemSolving/others/pr/others/1.py
1.py
py
1,040
python
en
code
0
github-code
1
32081852087
# tests.py from unittest import TestCase, main as unittest_main from app import app from unittest import TestCase, main as unittest_main, mock from bson.objectid import ObjectId sample_id = ObjectId('5d55cffc4a3d4031f42827a3') sample_deck = { 'img': "static/red.jpeg", 'description': 'Red playing cards' } sample_data...
Gaoyagi/Contractor
test.py
test.py
py
1,596
python
en
code
0
github-code
1
3259335985
def count(w): cnt = [0 for _ in range(26)] for c in w: if (c >= 'A' and c <= 'Z'): cnt[ord(c) - 65] += 1 else: cnt[ord(c) - 97] += 1 if (cnt.count(max(cnt)) > 1): print("?") else: print(chr(65 + cnt.index(max(cnt)))) word = input() count(word)
zinnnn37/BaekJoon
백준/Bronze/1157. 단어 공부/단어 공부.py
단어 공부.py
py
317
python
en
code
0
github-code
1
21061957738
import numpy as np import glob import sys import cv2 import os import json import operator from matplotlib import pyplot as plt def get_data(directory): MIN_MATCH_COUNT = 10 img1 = cv2.imread('data/original.jpg',0) #queryImage # Initiate SIFT detector sift = cv2.xfeatures2d.SIFT_cr...
aishwaryaanaidu/sketch-recognition
sift/looping.py
looping.py
py
1,926
python
en
code
1
github-code
1
72603804514
def cycle_length(num): while num % 2 == 0: num //= 2 while num % 5 == 0: num //= 5 if num == 1: return 0 remainder = 1 length = 0 while True: remainder = (remainder * 10) % num length += 1 if remainder == 1: return length ...
ZazenCloud/Project-Euler
Solutions/026 - Reciprocal Cycles.py
026 - Reciprocal Cycles.py
py
599
python
en
code
0
github-code
1
9295811562
import numpy as np from gym.utils import seeding import math import matplotlib.pyplot as plt from maze import MazeWorldSmall def randargmax(b, np_random=None): if np_random is None: np_random = np.random return np_random.choice(np.flatnonzero(b == b.max())) class Agent(object): def __init__(self...
windweller/AutoGrade
autograde/toy/q_learning.py
q_learning.py
py
8,613
python
en
code
0
github-code
1
25662207429
import pandas as pd import os def extractDataFromMETA(): data = pd.read_excel(r'COVID-CT-MetaInfo.xlsx') df = pd.DataFrame(data, columns=[ 'File name', 'Age', 'Gender', 'Location', 'Medical history', 'Severity']) return df def extractTrainedFileName(): trainedPath = [] for filename in os....
DucNgn/COVID19-Detector
dataInfo.py
dataInfo.py
py
876
python
en
code
1
github-code
1
425665856
from typing import Union import numpy as np from matplotlib import pyplot as plt from matplotlib import patches from matplotlib import lines # Custom imports: from Synthetic_Sequencer import synthtools as syn # matrix_imager(tp_matrix, classes, facies_dict, layout, filepath, title=None): # ============================...
Ruben0-0/bep
Visualization_Tools/matrix_visualizers.py
matrix_visualizers.py
py
5,698
python
en
code
0
github-code
1
42926702835
import requests import re url = "http://46.101.60.26:31068/question3/" session = requests.Session() with open("top-usernames-shortlist.txt", "r") as f: wordlist = f.readlines() time_taken = {} print("Testing the time taken") print("======================") for word in wordlist: word = word.rstrip() data = { ...
singha-brother/Web_Security_Notes
HTB_Academy/BROKEN_AUTHENTICATION/questions/username_bf03.py
username_bf03.py
py
619
python
en
code
1
github-code
1
89305565
# -*- coding: utf-8 -*- import os import re import ssl import threading from math import pi import rospy from geometry_msgs.msg import Twist import paho.mqtt.client as mqtt from fiware_ros_turtlesim.params import getParams, findItem from fiware_ros_turtlesim.logging import getLogger logger = getLogger(__name__) cl...
tech-sketch/fiware-ros-turtlesim
src/fiware_ros_turtlesim/command_sender.py
command_sender.py
py
7,227
python
en
code
1
github-code
1
73732029792
from django.urls import path from tasks.views import complete, create, create_task_to_card, delete, list_all, update, find_by_id app_name = 'tasks' urlpatterns = [ path('create-task/', create, name='create'), path('tasks/', list_all, name='list_all'), path('tasks/<int:pk>/', find_by_id, name='find_by_id'...
l-eduardo/potential-pancake
tasks/urls.py
urls.py
py
590
python
en
code
3
github-code
1
5562710262
"""Gateway Class Module""" from typing import Dict import internal_schema import stores.chirpstack.base import stores.chirpstack.gateway_profile import stores.chirpstack.network_server import stores.chirpstack.organization import stores.chirpstack.service_profile import exception class Gateway(stores.chirpstack.base...
williamlun/fastapi_playground
keycloak_import/src/stores/chirpstack/gateway.py
gateway.py
py
2,806
python
en
code
0
github-code
1
27706601958
from datetime import datetime, date, timedelta from datetime import timedelta import tweepy from tweepy import OAuthHandler import json from lab9_config import CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET # Authorization setup to access the Twitter API auth = OAuthHandler(CONSUMER_KEY, CONSUMER...
wudixiaoyu008/twitter-api-and-database
test.py
test.py
py
821
python
en
code
0
github-code
1
19259342911
import os import sys if (len(sys.argv) < 3 or len(sys.argv) > 3): print("""Provide commandline arguments: program name, extension, directory to search Example usage: python find.py, .txt, $HOME""") exit() extension = str(sys.argv[1]) path = str(sys.argv[2]) for root, dirs, files in os.walk(path): for file i...
kristtuv/UiO
INF4331/Assignment3/find.py
find.py
py
411
python
en
code
0
github-code
1
5189201070
# Used with Python 3.7 import os lib_includes = [] output = [] def get_include_from_line(line): try: first = line.split(" ")[0].strip() if first == "#include": include = line.split(" ")[1] return include.strip() else: return None except: retu...
ollierik/puro
single_header_creation/single_header_creation.py
single_header_creation.py
py
2,387
python
en
code
4
github-code
1
19780094728
# bot.py import discord # IMPORT DISCORD.PY. ALLOWS ACCESS TO DISCORD'S API. import os # IMPORT THE OS MODULE. import sqlite3 import time from datetime import datetime, date from dotenv import load_dotenv # IMPORT LOAD_DOTENV FUNCTION FROM DOTENV MODULE. from discord.ext import commands, tasks # IMPORT COMMAND...
JoelW2003/Bin-Reminder-Bot
cindyBot/bot.py
bot.py
py
7,980
python
en
code
0
github-code
1
74416928034
def calc_score(his_move, my_move): points = 0 MYMOVES_SCORE = { "X": 1, # ROCK "Y": 2, # PAPER "Z": 3, # SCISSORS } points += MYMOVES_SCORE[my_move] if (his_move == "A" and my_move == "X") or (his_move == "B" and my_move == "Y") or (his_move == "C" and my_move == "...
fshsweden/AdventOfCode2022
2b.py
2b.py
py
2,134
python
en
code
0
github-code
1
13518570965
import requests from concurrent.futures import ThreadPoolExecutor, as_completed import threading import time import pprint from bs4 import BeautifulSoup import csv import os class WebSpider(threading.Thread): def __init__(self, cookies, headers): self.cookies = cookies self.headers = headers ...
huchiwen/LearnSpider
qa_crawl.py
qa_crawl.py
py
5,023
python
en
code
1
github-code
1
27405001850
import numpy as np import torch import torch.nn as nn import random from collections import deque from vicero.policy import Policy from copy import deepcopy from vicero.algorithms.common.neuralnetwork import NeuralNetwork, NetworkSpecification # DQN (Deep Q Networks) # DQN is an approximated variant of Q-learning # Si...
CogitoNTNU/vicero
vicero/algorithms/deepqlearning.py
deepqlearning.py
py
7,626
python
en
code
6
github-code
1
72772102433
import numpy as np import pandas as pd import matplotlib.pyplot as plt import math from sklearn.datasets import fetch_20newsgroups from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import KFold #数据加载 & 处理 def create_data(): corpus_path = './naiveBayes' sample_cate = ['a...
kildallithro/HW_ML-2020-2021_1
naiveBayes_20newsgroups/naiveBayes.py
naiveBayes.py
py
3,569
python
en
code
0
github-code
1
45470229472
import queue import sys import threading import time import os import cv2 from PyQt5 import QtCore from PyQt5.QtCore import Qt from PyQt5.QtCore import QTimer from PyQt5.QtGui import QImage, QPixmap from PyQt5.QtWidgets import QDialog, QApplication, QMessageBox from PyQt5.uic import loadUi import serial import csv fro...
jaehyunShinRmit/OpencvTest
main2.py
main2.py
py
11,014
python
en
code
0
github-code
1
40882243652
import click import dotenv from rich import print from rich.console import Console console = Console() from dotenv import load_dotenv load_dotenv() import os import pynetbox import requests import re import yaml import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) NETBOX_TOKEN = os.geten...
jeremypng/netbox-to-pyats
netbox_to_testbed.py
netbox_to_testbed.py
py
5,377
python
en
code
2
github-code
1
31588169742
from selenium import webdriver from bs4 import BeautifulSoup as bs import pandas as pd import requests, re import os import time import pandas as pd page = 15 name = '北京朝阳大悦城' info_table = pd.DataFrame(columns=['昵称', '口味', '环境', '服务', '时间', '评论']) css_headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10...
moyuweiqing/dazhongdianping
by-selenium.py
by-selenium.py
py
9,781
python
en
code
35
github-code
1
11562021062
# 20150307 Runtime: 60 ms class Solution: # @param n, an integer # @return an integer def reverseBits(self, n): ret = 0 for i in xrange(32): if n & 1 == 1: ret += 1 << (31 - i) n >>= 1 return ret
chaor/LeetCode_Python_Accepted
190_Reverse_Bits.py
190_Reverse_Bits.py
py
273
python
en
code
49
github-code
1
1959000648
# -*- coding: utf-8 -*- from googleapiclient.http import MediaFileUpload import pandas as pd import os from googleapiclient.discovery import build from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from oauth2clien...
StevePrat/google_service_python
google_service.py
google_service.py
py
15,535
python
en
code
0
github-code
1
10317462795
import uproot4 import matplotlib.pyplot as plt import matplotlib.patches as patches from matplotlib.collections import PatchCollection from matplotlib import cm from matplotlib.colors import LogNorm, Normalize import awkward1 as ak from lxml import etree as ET def get_module_positions(base_name, tree): # <posit...
eic/hybrid_calorimeter_tools
event_display.py
event_display.py
py
3,470
python
en
code
1
github-code
1
30946473107
""" 23. セクション構造 記事中に含まれるセクション名とそのレベル(例えば"== セクション名 =="なら1)を表示せよ. """ import re f = open('jawiki-england.txt', 'r') o = open('jawiki-england-section.txt', 'w') section = re.compile(r"=(=+) (.+) =\1") for line in f: m = re.match(section, line) if m: o.write("sec {}: ".format(len(m.group(1)))) o.write(m.group(2)...
hassyGo/NLP100knock2015
yada/chapter03/chp03_23.py
chp03_23.py
py
440
python
ja
code
1
github-code
1
70957373473
"""create relation between users and papers Revision ID: 4e860e37bb37 Revises: 1bd8afe10204 Create Date: 2013-10-03 20:59:42.374353 """ # revision identifiers, used by Alembic. revision = '4e860e37bb37' down_revision = '1bd8afe10204' from alembic import op import sqlalchemy as sa def upgrade(): ### commands a...
dedalusj/PaperChase
backend/alembic/versions/4e860e37bb37_create_relation_betw.py
4e860e37bb37_create_relation_betw.py
py
1,028
python
en
code
4
github-code
1
31966512950
from typing import List from synt.terminals import * from lex.tokens import * TERMINAL_COLOR = "\033[36m" NONTERMINAL_COLOR = "\033[37m" RESET_COLOR = "\033[0m" class Rule: def __init__(self, result, parts): self.result = result self.parts = parts def loadGrammar() -> list: file = open("sy...
PaulCh4/compiler-labs
compiler/synt/syntax.py
syntax.py
py
2,323
python
en
code
0
github-code
1
24981871542
# encoding='utf-8' import contextlib import functools import inspect from multiprocessing import Lock as m_lock class TestDecorator: ''' test decorate ''' def __init__(self, name): self.name = name self.mark = "test" def __call__(self, *args, **kwargs): i...
hautof/haf
haf/mark.py
mark.py
py
3,472
python
en
code
2
github-code
1
9526298834
""" @author: Aashis Khanal @email: sraashis@gmail.com """ from collections import OrderedDict as _ODict import os as _os import torch as _torch import coinstac_sparse_dinunet.config as _conf import coinstac_sparse_dinunet.metrics as _base_metrics import coinstac_sparse_dinunet.utils as _utils import coinstac_sparse_d...
bishalth01/coinstac_sparse_dinunet
coinstac_sparse_dinunet/nn/basetrainer.py
basetrainer.py
py
20,152
python
en
code
1
github-code
1
22575362577
import sys import itertools def solution(mylist): number= [x for x in range(1,mylist+1)] answer= list(map(list, itertools.permutations(number))) answer.sort() return answer n = int(input()) results = solution(n) for i in results: for j in i: print(j,end=" ") print("")
dydwkd486/coding_test
baekjoon/python/baekjoon10974.py
baekjoon10974.py
py
303
python
en
code
0
github-code
1
37338999785
from concurrent import futures import grpc import servicos_pb2 import servicos_pb2_grpc import threading import fila import banco import time import os import config import random _ONE_DAY_IN_SECONDS = 60 * 60 * 24 f1 = fila.Fila() f2 = fila.Fila() f3 = fila.Fila() f4 = fila.Fila() bd = banco.Banco()...
ruehara/SdPython
protos/server_grpc.py
server_grpc.py
py
4,072
python
en
code
0
github-code
1
71112236194
from AIPUBuilder.Optimizer.framework import * from AIPUBuilder.Optimizer.logger import OPT_ERROR from AIPUBuilder.Optimizer.utils.dtype_utils import * from AIPUBuilder.Optimizer.utils.quant_tool_utils import * @op_register(OpType.Clip) def clip(self, *args): inp_t = self.inputs[0].betensor out_max, out_min =...
Arm-China/Compass_Optimizer
AIPUBuilder/Optimizer/ops/clip.py
clip.py
py
3,820
python
en
code
18
github-code
1
36046629711
import requests from bs4 import BeautifulSoup as bs page = requests.get('https://umggaming.com/leaderboards') soup = bs(page.text, 'html.parser') # Get table with the id of leaderboards leaderboards = soup.find('table', {'id': 'leaderboard-table'}) # Get tbody from table tbody = leaderboards.find('tbody') # Get all...
edwardspresume/Sandbox
python/Data-scraper/leaderboard.py
leaderboard.py
py
599
python
en
code
0
github-code
1
42999149739
''' Problem 5 | Longest Palindromic Substring https://leetcode.com/problems/longest-palindromic-substring/ ''' class Solution: def longestPalindrome(self, s: str) -> str: l = len(s) dp = [[0 for i in range(l)] for j in range(l)] for i in range(l): dp[i][i] = True ...
davijit868/Programming-Solutions
Algorithms/Dynamic Programming/Longest Palindromic Substring.py
Longest Palindromic Substring.py
py
803
python
en
code
2
github-code
1
24753337216
import numpy as np import pandas as pd data_in_dict = { "year" : [ 1950, 1951, 1952, 1953, 1954, 1955, 1956, 1957, 1958, 1959 ], "champ" : [ "Farina", "Fangio", "Ascari", "Ascari", "Fangio", "Fangio", "Fangio", "Fangio", "Hawthorne", "Brabham" ], "wi...
teletobbie/dapom
week_3/A/f1.py
f1.py
py
1,354
python
en
code
0
github-code
1
7765613225
''' INPUT: WRF-Chem mechanism file: *.eqn Required species OUTPUT: Varnames in IRR*.nc file UPDATE: Xin Zhang: 05/25/2020: Basic ''' import re import pandas as pd def read_eqn(dir, eqn_file, species): ''' Read the equations from the mechanism file ''' # create the e...
zxdawn/pyXZ
XZ_model/irr_names.py
irr_names.py
py
2,646
python
en
code
23
github-code
1
74540182432
from tornado import ioloop, options, web options.define("port", default=8080, help="port to listen on") options.define( "host", default="127.0.0.1", help="host interface to connect on (0.0.0.0 is all)" ) options.define("path", help="the files to serve") SETTINGS = dict( # enabling compression can have securit...
jupyter/accessibility
pa11y-jupyter/serve.py
serve.py
py
1,663
python
en
code
63
github-code
1
3560320164
# In this Bite you calculate the total amount of points earned with Ninja Belts # by accessing the given ninja_belts dict. # # You learn how to access score and ninjas (= amount of belt owners) from # no less than a namedtuple (if you're new to them, check out the basic Point example in the docs). # # Why a namedtuple,...
panpusto/codewars_exercises
exercises/intro_bites_08_by_PyBites.py
intro_bites_08_by_PyBites.py
py
1,186
python
en
code
0
github-code
1