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
7557841018
import sys from collections import deque def Run(fin, fout): readline = fin.readline N = int(readline()) to = [None] * (N + 1) from_ = [set() for _ in range(N + 1)] for i in range(1, N + 1): a, v = map(int, readline().split()) to[i] = (a, v) from_[a].add((i, v)) visited = set() ans = 0 f...
chenant2017/USACO
Silver/2022 Open/p1.py
p1.py
py
1,247
python
en
code
2
github-code
36
73118843944
import multiprocessing from threading import Thread import time def is_prime(n): if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def find_primes(end, start): primes = [] for num in range(start, end - 1): if i...
IlyaOrlov/PythonCourse2.0_September23
Practice/achernov/module_12/task_1.py
task_1.py
py
2,712
python
ru
code
2
github-code
36
10392633050
import json import os import cv2 from cfg import cfg import numpy as np from collections import defaultdict as dd from dsl.base_dsl import BaseDSL, one_hot_labels class NSFWDSL(BaseDSL): def __init__(self, batch_size, shuffle_each_epoch=False, seed=1337, normalize=True, mode='train', val_frac=0.0...
gongzhimin/ActiveThief-attack-MLaaS
dsl/nsfw_dsl.py
nsfw_dsl.py
py
3,309
python
en
code
2
github-code
36
36720200958
#!/usr/bin/env python """ Parser for condor job log files to get information out """ from datetime import datetime, timedelta from .logit import log from . import jobsub_fetcher from .poms_model import Submission # our own logging handle, goes to cherrypy def get_joblogs(dbhandle, jobsub_job_id, cert, key, experim...
fermitools/poms
webservice/condor_log_parser.py
condor_log_parser.py
py
6,245
python
en
code
0
github-code
36
38766389801
# # aberdeen/utils/prompt.py # """ Utility functions which prompt the user for input. """ from distutils.util import strtobool from .error_messages import warning def get_user_bool(prompt, default=None): """ Uses distutils 'strtobool' function to interpret a request from the user. @param default: if defau...
akubera/aberdeen
aberdeen/utils/prompt.py
prompt.py
py
1,516
python
en
code
1
github-code
36
14298574762
import tensorflow as tf from board_class import Board from memory_class import Memory from critic_class import Critic from actor_class import Actor import numpy as np gamma = 0.5#discount factor batch_size = 200 def fix_policy(state, policy): for i in range(9): if state[i] != 0: policy[i] = 0 ...
EpicDuckPotato/TicTacToe_PolicyGradient
trainer_nobad_a2c.py
trainer_nobad_a2c.py
py
4,586
python
en
code
0
github-code
36
8445183338
from numpy import prod import cupy from cupy.fft import config from cupy.fft._fft import (_convert_fft_type, _default_fft_func, _fft, _get_cufft_plan_nd, _get_fftn_out_size, _output_dtype) from cupy.fft._cache import get_plan_cache def get_fft_plan(a, shape=None,...
cupy/cupy
cupyx/scipy/fftpack/_fft.py
_fft.py
py
19,687
python
en
code
7,341
github-code
36
74105735145
from django.contrib import admin from django.urls import path from tareas import views urlpatterns = [ path("admin/", admin.site.urls), path ("", views.menu, name = "menu"), path ("registro/", views.registro, name = "registro"), path ("iniciar_sesion/", views.iniciar_sesion, name = "iniciar_sesion"),...
MallicTesla/Mis_primeros_pasos
Programacion/002 ejemplos/002 - 14 django/16 django proyrcto inicio de cesion/django_crud/urls.py
urls.py
py
732
python
en
code
1
github-code
36
4034979286
a = [1 ,2 ,3 ,4 ,5] print(a) print(a[3]) n = 10 a = [0] * n a[0] = 1 print(a) array = [i for i in range(10)] print(array) # 리스트 컴프리 핸션 # 이 방식을 사용하지 않고 단순히 나타내면 콜바이 레퍼런스로 변해서, 데이터 전체가 변하게 된다. array_2 = [[0] * 10 for _ in range(10) ] array_2[0][0] = 1 # 리스트 에서 특정 값 제거하기 a = [1, 2, 3, 4, 5, 5] remove_set = {3, 5} a...
kakaocloudschool/dangicodingtest
001_pythonBasic/002_list.py
002_list.py
py
499
python
ko
code
0
github-code
36
15282409982
import regTrees from numpy import * import matplotlib.pyplot as plt myDat = regTrees.loadDataSet('ex00.txt') myMat = mat(myDat) print(regTrees.createTree(myMat)) plt.plot(myMat[:,0],myMat[:,1], 'ro') plt.show() myDat1 = regTrees.loadDataSet('ex0.txt') myMat1 = mat(myDat1) print(regTrees.createTree(myMat1)...
mengwangme/MachineLearninginAction
Ch09/test.py
test.py
py
376
python
en
code
0
github-code
36
42243497350
import numpy as np import matplotlib.pyplot as plt from hs_digitizer import * import glob import scipy.signal as ss from scipy.optimize import curve_fit import re import matplotlib #Ns = 500000 #Fs = 200000. path = "/data/20181030/bead1/high_speed_digitizer/golden_data/amp_ramp_50k_good" files = glob.glob(path + "/*.h...
charlesblakemore/opt_lev_analysis
scripts/spinning/old_scripts/ampt_ramp_spectra_plot.py
ampt_ramp_spectra_plot.py
py
1,607
python
en
code
1
github-code
36
25872641550
__author__ = "Domenico Solazzo" __version__ = "0.1" RESPONSE_CODES = { 200: "OK: Success", 202: "Accepted: The request was accepted and the user was queued for processing", 401: "Not Authorized: either you need to provide authentication credentials, or the credentials provided aren't valid.", ...
domenicosolazzo/PythonKlout
pythonklout.py
pythonklout.py
py
8,616
python
en
code
1
github-code
36
10098349578
import numpy as np import pandas as pd class Node(): """ Class for defining each node of the Decision Tree. """ def __init__(self, attr = None, pred = None, class_label = None) -> None: self.attr = attr self.children = None self.isLeaf = False self.pred = pred ...
pri1311/ML_Algorithms
ML-Algorithms/Classification/DecisionTreeID3.py
DecisionTreeID3.py
py
6,215
python
en
code
1
github-code
36
16389167601
# -*- coding: utf-8 -*- import os import sys import xbmc import xbmcaddon import xbmcgui import xbmcplugin from xbmcvfs import translatePath from libs.session import Session from libs.utils import get_url, check_settings def list_settings(label): addon = xbmcaddon.Addon() _handle = int(sys.argv[1]) xbmcp...
waladir/plugin.video.rebittv
libs/settings.py
settings.py
py
3,931
python
en
code
0
github-code
36
8593741282
#! /usr/bin/env -S python3 -u import os, shutil, sys, glob, traceback from easyterm import * help_msg="""This program downloads one specific NCBI assembly, executes certains operations, then cleans up data ### Input/Output: -a genome NCBI accession -o folder to download to ### Actions: -c bash command ...
marco-mariotti/ncbi_single_use_genome
ncbi_single_use_genome.py
ncbi_single_use_genome.py
py
6,805
python
en
code
0
github-code
36
37313593372
''' 1. input the members in the team and take the score. 2. if x has a higher score than other two then 3. create a set arranged in order of the score. 4. create a function to compare the scores. 5. decide the order is valid or not using if else ladder. 6. if anyone has higher skill score then yes. 7. if such order is...
Aashutosh748/comprino_tests
2_ordering_teams.py
2_ordering_teams.py
py
1,401
python
en
code
0
github-code
36
72694784745
import heapq roads = [["ULSAN","BUSAN"],["DAEJEON","ULSAN"],["DAEJEON","GWANGJU"],["SEOUL","DAEJEON"],["SEOUL","ULSAN"],["DAEJEON","DAEGU"],["GWANGJU","BUSAN"],["DAEGU","GWANGJU"],["DAEGU","BUSAN"],["ULSAN","DAEGU"],["GWANGJU","YEOSU"],["BUSAN","YEOSU"]] node = [] for road in roads: x, y = road node.append(x) ...
baejinsoo/algorithm_study
algorithm_study/Stack_Queue/쿠팡경로.py
쿠팡경로.py
py
984
python
en
code
0
github-code
36
70091360103
from datetime import datetime from persistent.list import PersistentList from zope.annotation import IAnnotations import logging TWITTER_KEY = "noise.addon.twitter" FACEBOOK_KEY = "noise.addon.facebook" EMAIL_KEY = "noise.addon.email" HARDCOPY_KEY = "noise.addon.hardcopy" TWITTER_CSV_HEADERS = ["timestamp", "twitter-...
cleanclothes/vmd.noise
noise/addon/storage.py
storage.py
py
1,916
python
en
code
0
github-code
36
17230876576
# -*- coding: utf-8 -*- import numpy as np def get_linear_value(current_index, start_value, total_steps, end_value=0, **kwargs): values = np.linspace(start_value, end_value, total_steps, dtype=np.float32) values = values / start_value * start_value return values[current_index] def get_cosine_value(curre...
TheDenk/Attention-Interpolation
iattention/interpolation_schedulers.py
interpolation_schedulers.py
py
835
python
en
code
5
github-code
36
1947036421
from collections import defaultdict def solution(genres, plays): answer = [] stream = defaultdict(list) # 같은 장르내에서는 plays수가 같을 수 있지만 # 장르 합은 다른 장르의 합과 다르다 for g,p in zip(genres, plays): stream[g].append(p) answer = [] stream = sorted(stream.items(), key = lambda x:-sum(x[1])) # list ...
hellokena/2022
프로그래머스/LV2/LV3_베스트앨범(해시).py
LV3_베스트앨범(해시).py
py
862
python
ko
code
0
github-code
36
5812402236
import unittest import warnings from datetime import date, datetime from decimal import Decimal import pytz from babel import Locale from fluent.runtime.types import FluentDateType, FluentNumber, fluent_date, fluent_number class TestFluentNumber(unittest.TestCase): locale = Locale.parse('en_US') def setUp...
projectfluent/python-fluent
fluent.runtime/tests/test_types.py
test_types.py
py
12,837
python
en
code
185
github-code
36
27517754092
import torch import torch.nn as nn import torchvision.datasets as dsets import torchvision.transforms as transforms from torch.autograd import Variable import geojson import json import time def chip_image1(img, chip_size=(300, 300)): """ Segment an image into NxWxH chips Args: img : Array of imag...
catsbergers/Final-Project-Group-2
jiarong-che-final-project/Code/mywork.py
mywork.py
py
3,764
python
en
code
0
github-code
36
71249021545
import json from math import sqrt # Returns a distance-based similarity score for person1 and person2 def sim_distance(prefs, person1, person2): # Get the list of shared_items si = {} for item in prefs[person1]: if item in prefs[person2]: si[item] = 1 # if they have no ratings in common, retu...
brokencranium/recommender
ItemBasedFiltering.py
ItemBasedFiltering.py
py
4,740
python
en
code
0
github-code
36
28518113817
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.variables.variable import Variable from opus_core.misc import unique from numpy import zeros, logical_not class total_spaces(Variable): """return proposed spaces (units) ac...
psrc/urbansim
psrc_parcel/development_project_proposal_component/total_spaces.py
total_spaces.py
py
3,179
python
en
code
4
github-code
36
74833825064
import unittest import vics import os global test_db test_db = "testing_db.sqlite" class TestVicsServer(unittest.TestCase): def test_create_new_database(self): vics.create_new_database(test_db) self.assertTrue(os.path.exists(test_db) == 1) os.remove(test_db)
fine-fiddle/vics
test/test_vics_server.py
test_vics_server.py
py
296
python
en
code
0
github-code
36
33078013582
# pylint: disable=W0102 # pylint: disable=W0212 # pylint: disable=W0221 # pylint: disable=W0231 # pylint: disable=W0640 # pylint: disable=C0103 """Module for representing UDS corpora.""" import os import json import requests from pkg_resources import resource_filename from os.path import basename, splitext from loggi...
decompositional-semantics-initiative/decomp
decomp/semantics/uds/corpus.py
corpus.py
py
26,248
python
en
code
56
github-code
36
7964665793
# Программа принимает действительное положительное число x и целое отрицательное число y. # Необходимо выполнить возведение числа x в степень y. Задание необходимо реализовать в виде функции my_func(x, y). # При решении задания необходимо обойтись без встроенной функции возведения числа в степень. def my_func(x, y): ...
sekundra/Python_basic
3дз/3_4.py
3_4.py
py
1,316
python
ru
code
0
github-code
36
534600653
#Desafio python - Desenvolver um protótipo para sistema bancário, inicialmente com as opções: Depósito, saque e extrato saldo_conta = 0 limite = 500 extrato = "" saques_realizados = 0 limite_saques = 3 print("Bem vindo ao Banco *Selecione uma opção no menu:*") menu=""" [1] - Depositar [2] - Sacar [3...
LeandroJBrito/desafio_python_bank
desafio_sistema_bank.py
desafio_sistema_bank.py
py
2,087
python
pt
code
0
github-code
36
8779071357
# -*- coding: utf-8 -*- from math import sqrt from os.path import isfile from .datum import Datum,getDatum class Linear(object): def __init__(self): self.a = Datum() self.b = Datum() self.r = None def echo(self): print("Coeficiente de correlación: " + str(self.r)) pri...
jatolmed/arduino-meteo
statistics/statistics_old.py
statistics_old.py
py
4,150
python
en
code
0
github-code
36
38400918265
# This is a demo of running face recognition on a Raspberry Pi. # This program will print out the names of anyone it recognizes to the console. # To run this, you need a Raspberry Pi 2 (or greater) with face_recognition and # the picamera[array] module installed. # You can follow this installation instructions to get ...
minakhan01/LanguageLearning
PrototypingFiles/Python Vision Files/raspi_facerec.py
raspi_facerec.py
py
3,217
python
en
code
0
github-code
36
7862870875
#!/usr/bin/env python3 import sys import re import glob import prettytable import pandas as pd import argparse import os def readFile(filename): fileContents = list() with open(filename, "r") as f: for line in f: line = line.strip() fileContents.append(line) return fileContents def getStatusLine(fileConte...
vjbaskar/cscipipe
farm/farmhist.py
farmhist.py
py
4,130
python
en
code
0
github-code
36
43135278080
# Mnemonic: em.py # Abstract: Run em (Expectation Maximisation) # # Author: E. Scott Danies # Date: 06 March 2019 # # Acknowledgements: # This code is based in part on information gleaned from, or # code examples from the following URLs: # https://github.com/minmingzhao?...
ScottDaniels/gtcs7641
a3/em.py
em.py
py
4,623
python
en
code
0
github-code
36
3093110826
starting_number = int(input()) final_number = int(input()) magic_number = int(input()) combinations = 0 is_found = False for i in range(1, starting_number + 1): for j in range(1, final_number + 1): combinations += 1 if i + j == magic_number: is_found = True break e...
ivn-svn/SoftUniPythonPath
Programming Basics with Python/7_nested_loops/lab/4_magicn.py
4_magicn.py
py
545
python
en
code
1
github-code
36
15290025439
# -*- coding: utf-8 -*- from threading import Thread, Event from yasc.utils import CONFIG, state, ZoneAction, in_production, ControllerMode from datetime import datetime, timedelta from time import sleep import logging # RPi imports not working if in_production(): from yasc.pi_controller import get_active_zone, a...
asmyczek/YASC
yasc/zone_controller.py
zone_controller.py
py
6,739
python
en
code
1
github-code
36
21366953261
''' Link: https://www.lintcode.com/problem/shortest-path-in-undirected-graph/description ''' # Uses bidirectional BFS. I closesly followed the teachings on Jiuzhang.com. from collections import deque class Solution: """ @param graph: a list of Undirected graph node @param A: nodeA @param B: nodeB @...
simonfqy/SimonfqyGitHub
lintcode/medium/814_shortest_path_in_undirected_graph.py
814_shortest_path_in_undirected_graph.py
py
1,593
python
en
code
2
github-code
36
18287559618
from urllib.request import urlopen from bs4 import BeautifulSoup url = input('Enter URL:') count = int(input('Enter count:')) position = int(input('Enter position:'))-1 html = urlopen(url).read() soup = BeautifulSoup(html,"html.parser") href = soup('a') #print href for i in range(count): link = href[position].g...
Abhishek32971/python_my_code
college/ActivitySet01/problem16.py
problem16.py
py
473
python
en
code
1
github-code
36
73198190823
import json import re from typing import Any, Dict, List, Text from airflow.exceptions import AirflowException from airflow.providers.google.cloud.hooks.datacatalog import CloudDataCatalogHook import google.auth.transport.requests from google.auth.transport.urllib3 import AuthorizedHttp from grizzly.config import Conf...
google/grizzly
airflow/plugins/grizzly/data_catalog_tag.py
data_catalog_tag.py
py
15,091
python
en
code
51
github-code
36
25677729371
import cv2 import torch from PIL import Image from utils.segmenter import Segmenter from utils.type_conversion import * def resize(img, short_size): w, h = img.size if w < h: nw, nh = short_size, int(w * short_size / h) else: nw, nh = int(h * short_size / w), short_size return img.resi...
MondayYuan/HairSegmentation
scripts/test.py
test.py
py
2,875
python
en
code
5
github-code
36
18050976874
from django.urls import path from .views import RegistrationView, CustomLoginView, CustomLogoutView, ProfileView, UserProfileUpdateView, UserEducationalUpdateView urlpatterns = [ path('register/', RegistrationView.as_view(), name='register'), path('login/', CustomLoginView.as_view(), name='login'), path('l...
Kamal123-cyber/skillshare
skillshare/skillapp/urls.py
urls.py
py
618
python
en
code
0
github-code
36
33893578543
#nf=open('/m/triton/scratch/elec/puhe/p/jaina5/Psmit_lstm_50_nbest_lm_cost','w') #nf=open('/m/triton/scratch/elec/puhe/p/jaina5/ac_cost.50best.aff','w') #nf=open('yle_nbest_50_pre','w') #nf=open('rescore_72layer_100nbest_yle_20191119-133110.txt','w') nf=open('/m/triton/scratch/work/jaina5/kaldi/egs/yle_rescore/s5/lm_co...
aalto-speech/FinnishXL
FinnishXL/get_nbest_lists.py
get_nbest_lists.py
py
1,619
python
en
code
1
github-code
36
6239431595
from datetime import datetime import json from odd_utils import * VERSION = "1.0" def shallow_copy(data) -> dict: if type(data) is list: return traverse(data) elif(type(data) is str): with open(data, "r") as f: return shallow_copy(json.load(f)) else: return traverse(da...
SamuelMiddendorp/OpenDataDocumentor
odd_library.py
odd_library.py
py
1,332
python
en
code
0
github-code
36
69960188586
from django.contrib.auth.models import AbstractUser, Group from django.db import models class User(AbstractUser): CREATOR = 'CREATOR' SUBSCRIBER = 'SUBSCRIBER' ROLE_CHOICES = ( (CREATOR, 'Créateur'), (SUBSCRIBER, 'Abonné'), ) profile_photo = models.ImageField(verbose_name='Photo de ...
TonyQuedeville/fotoblog
authentication/models.py
models.py
py
1,089
python
fr
code
0
github-code
36
29391745282
class Solution: def diagonalSum(self, mat: List[List[int]]) -> int: size = len(mat) if size == 1: return mat[0][0] sum = 0 for i in range(size): sum += mat[i][i] + mat[i][size - i - 1] if size % 2 == 1: ...
AnotherPianist/LeetCode
1572-matrix-diagonal-sum/1572-matrix-diagonal-sum.py
1572-matrix-diagonal-sum.py
py
375
python
en
code
1
github-code
36
39844679092
""" Iguana (c) by Marc Ammon, Moritz Fickenscher, Lukas Fridolin, Michael Gunselmann, Katrin Raab, Christian Strate Iguana is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License. You should have received a copy of the license along with this work. If not, see <http://creativecommons.org...
midas66/iguana
src/common/templatetags/user_preference.py
user_preference.py
py
603
python
en
code
null
github-code
36
23597401890
from tkinter import * import mysql.connector import matplotlib.pyplot as plt import csv root = Tk() root.title('VINCI FarmDB') root.geometry("400x700") root.iconbitmap('Logo.ico') # Connec to the MySQL Server mydb = mysql.connector.connect( host="localhost", user = "", ...
murali22chan/Aatmanirbhar-Bharat-Hackathon
main.py
main.py
py
10,762
python
en
code
0
github-code
36
33039135016
from pyglet import gl class Polygon: def __init__(self, vertices, u0=None, v0=None, u1=None, v1=None): self.vertices = vertices if isinstance(u0, int): f = 0.0015625 f2 = 0.003125 vertices[0] = vertices[0].remap(u1 / 64.0 - f, v0 / 32.0 + f2) vertice...
pythonengineer/minecraft-python
mc/net/minecraft/model/Polygon.py
Polygon.py
py
770
python
en
code
2
github-code
36
7689661777
def method1(arr, n, x): first = -1 last = -1 for i in range(0, n): if x != arr[i]: continue if first == -1: first = i last = i if first != -1: print("Last Occurrence = ", last) if __name__ == "__main__": """ arr = [1, 2, 2, 2, 2, 3, 4, 7...
thisisshub/DSA
E_searching/problems/B_index_of_last_occurence_in_sorted_array.py
B_index_of_last_occurence_in_sorted_array.py
py
476
python
en
code
71
github-code
36
75104190825
# Given an array of lowercase letters sorted in ascending order, find the # smallest letter in the given array greater than a given ‘key’. # Assume the given array is a circular list, which means that the last letter # is assumed to be connected with the first letter. This also means that the # smallest letter in t...
itsmeichigo/Playgrounds
GrokkingTheCodingInterview/ModifiedBinarySearch/next-letter.py
next-letter.py
py
1,228
python
en
code
0
github-code
36
22179863
#!/usr/bin/python3 from time import sleep import mysql.connector import pprint import threading import tkinter as tk import sys class MainWindow: def __init__(self, main) -> None: self.main = main self.main['bg'] = '#909090' self.lightColor = '#909090' self.threadRunning = True ...
DrOeter/parkhaus
main.py
main.py
py
8,496
python
en
code
0
github-code
36
3829718910
from __future__ import print_function import io import logging import logging.handlers import sys import threading import time try: import argparse except ImportError: sys.stderr.write(""" ntploggps: can't find the Python argparse module If your Python version is < 2.7, then manual installation is ne...
ntpsec/ntpsec
ntpclients/ntploggps.py
ntploggps.py
py
7,198
python
en
code
225
github-code
36
7055499592
""" 面向对象的思考步骤: 现实事物 -抽象化-> 类 -具体化-> 对象 # int 类的对象 a = 10 # str 类的对象 b = "悟空" # list 类的对象 c = [1,2,3] 语法: class 类名:  def __init__(self, 参数): self.数据 = 参数  """ class Wife: # 数据:名词性的描述 def __init__(self, name, face_score, money=0.0): s...
haiou90/aid_python_core
day09/exercise_personal/05_exercise.py
05_exercise.py
py
1,045
python
en
code
0
github-code
36
25450887207
from django.urls import path, include from . import views app_name = "accounts" urlpatterns = [ # login path("login/", views.LoginView.as_view(), name="login"), # logout path("logout/", views.LogoutView.as_view(), name="logout"), # signup path("signup/", views.SignupView.as_view(), name="signu...
AmirhosseinRafiee/Blog
mysite/accounts/urls.py
urls.py
py
391
python
en
code
0
github-code
36
42911658215
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of Sick Beard. # # Sick Beard is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of t...
zeon/qpkg-sickbeard
src-shared/sickbeard/common.py
common.py
py
10,833
python
en
code
4
github-code
36
8660980424
import numpy as np from ctypes import * # c 类型库 import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from astropy.io import ascii from astropy.table import Table, vstack import os from scipy.stats import * import time z4figpre = '../z4/figs/' z4datapre = '../z4/data/' z5figpre = '../z5/figs/' z5data...
lovetomatoes/BHMF
PYmodule/__init__.py
__init__.py
py
8,267
python
en
code
0
github-code
36
33064377909
# Better implementation # -> separate class for printing from abc import ABC class Expression(ABC): pass class DoubleExpression(Expression): def __init__(self, value): self.value = value class AdditionExpression(Expression): def __init__(self, left, right): self.right = right se...
PratikRamdasi/Design-Patterns-in-Python
Behavioral-Patterns/Visitor/reflective_visitor.py
reflective_visitor.py
py
1,704
python
en
code
0
github-code
36
43110037810
i,j = input().split("-") if i == "joker JOKER" or j =="joker JOKER": print("joker JOKER") else: a = i.split(" ") b = j.split(" ") x = ['3','4','5','6','7','8','9','10','J','Q','K','A','2','joker','JOKER'] if len(a) == len(b): c=0 d=0 for m in a: c += x.index(m) ...
bbandft/Operating-Examination-of-Huawei-
2016校招笔试-扑克牌大小.py
2016校招笔试-扑克牌大小.py
py
596
python
en
code
0
github-code
36
2628647448
import os import cv2 import glob import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm import random from ipdb import set_trace as bp size_h, size_w = 600, 600 from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', one_hot=False, dtype='uint8') ob...
nguyenvantui/mnist-object-detection
mnist_gen.py
mnist_gen.py
py
8,145
python
en
code
1
github-code
36
7182292805
#!/usr/bin/env python3 """sarsa""" import numpy as np import gym # Q(St) = Q(St) + alpha * delta_t * Et(St) # delta_t = R(t + 1) + gamma * q(St + 1, At + 1) - q(St, At) # ET(S) = gamma + lambda * Et - 1(S) + q(St + 1, At + 1) - q(St, At) def epsilon_greedy(env, Q, state, epsilon): action = 0 if np.random.un...
JohnCook17/holbertonschool-machine_learning
reinforcement_learning/0x02-temporal_difference/2-sarsa_lambtha.py
2-sarsa_lambtha.py
py
1,708
python
en
code
3
github-code
36
18890544635
import re from dca.dca_cmd import DcaCmd from control_protocol.ssh_server_control import SSHServerControl dev1 = DcaCmd(SSHServerControl, '10.137.59.22', 'tianyi.dty', 'Mtfbwy626488') # initialize an instance to operate 10.137.59.22 dev2 = DcaCmd(SSHServerControl, '10.65.7.131', 'root', 'hello1234') # initialize an ...
obiwandu/DCA
src/script/script-linux.py
script-linux.py
py
958
python
en
code
0
github-code
36
2964071525
#!/bin/python3 import math import os import random import re import sys used = set() edge_dict = {} class Node(object): def __init__(self, index, value): self.index = index self.value = value self.children = [] self.total = 0 def add_children(self, nodes): used.add(sel...
jvalansi/interview_questions
cut_the_tree.py
cut_the_tree.py
py
2,206
python
en
code
0
github-code
36
5409351564
import sys from pathlib import Path from shutil import copy, copytree, ignore_patterns # This script initializes new pytorch project with the template files. # Run `python3 new_project.py ../MyNewProject` then new project named # MyNewProject will be made current_dir = Path() assert ( current_dir / "new_project.py...
Ttayu/pytorch-template
new_project.py
new_project.py
py
1,242
python
en
code
0
github-code
36
14963542759
import mysql.connector import socket import logging from logging.config import fileConfig fileConfig('log.ini', defaults={'logfilename': 'bee.log'}) logger = logging.getLogger('database') mydb = mysql.connector.connect( host="45.76.113.79", database="hivekeeper", user="pi_write", password=")b*I/j3s,umyp0-8"...
jenkinsbe/hivekeepers
database.py
database.py
py
1,702
python
en
code
0
github-code
36
11378811101
def mutate_string(string, position, character): temp = [] for char in string: temp.append(char) temp[position] = character edit_string = "" for char in temp: edit_string += char return edit_string if __name__ == "__main__": s = input() i, c = input().split() s_new =...
scouvreur/hackerrank
python/strings/mutations.py
mutations.py
py
366
python
en
code
1
github-code
36
23777096489
import re import sys from random import randrange, randint, choices, shuffle from typing import List, Dict, Tuple import numpy as np import pandas as pd from pepfrag import ModSite, IonType, pepfrag from pyteomics.mass import calculate_mass from src.fragment_matching import write_matched_fragments from src.model.frag...
Eugleo/dibby
src/generate_data.py
generate_data.py
py
18,105
python
en
code
1
github-code
36
875221895
#!/usr/bin/python from foo import bar import datetime import json import pathlib import shutil import sys import urllib.request date_13w39a = datetime.datetime(2013, 9, 26, 15, 11, 19, tzinfo = datetime.timezone.utc) date_17w15a = datetime.datetime(2017, 4, 12, 9, 30, 50, tzinfo = datetime.timezone.utc) date_1_17_pre...
JWaters02/Hacknotts-23
testclient/test_code.py
test_code.py
py
3,249
python
en
code
1
github-code
36
34091963292
from loader import dp, bot from aiogram.types import ContentType, Message from pathlib import Path # kelgan hujjatlar (rasm/video/audio...) downloads/categories papkasiga tushadi download_path = Path().joinpath("downloads","categories") download_path.mkdir(parents=True, exist_ok=True) @dp.message_handler() async def ...
BakhtiyarTayir/mukammal-bot
handlers/users/docs_handlers.py
docs_handlers.py
py
1,536
python
en
code
0
github-code
36
8635223611
import calendar from datetime import date from django.contrib.auth import get_user_model from django.core.cache import cache from rest_framework import generics, status from rest_framework.permissions import IsAuthenticated from rest_framework.renderers import TemplateHTMLRenderer from rest_framework.response import Re...
hanoul1124/healthcare2
app/tables/apis.py
apis.py
py
4,279
python
en
code
0
github-code
36
33078309482
from flask import request from flask.ext.babel import Babel from tweetmore import app import re babel = Babel(app) # *_LINK_LENGTH constants must be get from help/configuration/short_url_length daily # last update 14th November 2013 TWITTER_HTTPS_LINK_LENGTH = 23 TWITTER_HTTP_LINK_LENGTH = 22 TWITTER_MEDIA_LINK_LENG...
dedeler/tweet-more
tweetmore/views/utils.py
utils.py
py
5,555
python
en
code
0
github-code
36
34747812186
import random def play(): com_score = user_score = 0 while com_score != 5 and user_score != 5: user = input("What's your choice? 'r' for rock, 'p' for paper, 's' for scissors : ") computer = random.choice(['r', 'p', 's']) if user == computer: print("It's a tie") ...
AlpeshJasani/My-Python-Projects
rock-paper-scissors.py
rock-paper-scissors.py
py
861
python
en
code
0
github-code
36
41847098946
from telegram.ext import Updater from telegram.ext import CommandHandler, CallbackQueryHandler from telegram.ext import MessageHandler, Filters import os import square import telegram #initialize updater and dispatcher updater = Updater(token='TOKEN', use_context=True) dispatcher = updater.dispatcher def start(updat...
sethiojas/Square_It_Bot
bot.py
bot.py
py
2,367
python
en
code
0
github-code
36
19937726668
import random def drawField(field): print(field[0],"|",field[1],"|",field[2]) print("-","+","-","+","-") print(field[3],"|",field[4],"|",field[5]) print("-","+","-","+","-") print(field[6],"|",field[7],"|",field[8]) field=[" "," "," "," "," "," "," "," "," "] token = "X" for attempt in range(4): ...
shurikkuzmin/ProgrammingCourse2018
Lesson4/tictactoe.py
tictactoe.py
py
625
python
en
code
1
github-code
36
39914557124
from fastapi import APIRouter from utils import model from utils.socket import socket_connection from services.event_service import write_log, write_video_log from utils.plc_controller import * from services.camera_service import camera_service import time import threading router = APIRouter(prefix="/event") @router...
ngocthien2306/be-cctv
src/router/event_router.py
event_router.py
py
2,107
python
en
code
0
github-code
36
9634671657
import argparse # Parse arguments parser = argparse.ArgumentParser() parser.add_argument("text") parser.add_argument("repetitions") args = parser.parse_args() # Convert repetitions to integer try: text = args.text repetitions = int(args.repetitions) except: quit(1) # Create repeated repeated input text a...
jdwijnbergen/CWL_workshop
3_create-text-file.py
3_create-text-file.py
py
518
python
en
code
0
github-code
36
27119975624
#Crie um programa que declare uma matriz de dimensão 3x3 e preencha com valores lidos pelo teclado. No final, mostre a matriz na tela, com a formatação correta. m = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] for i in range(0, 3): #linha for j in range(0, 3): #coluna m[i][j] = int(input(f'Insira o elemento [{i+1}][{j...
JoaoFerreira123/Curso_Python-Curso_em_Video
Exercícios/#086.py
#086.py
py
501
python
pt
code
0
github-code
36
13191472979
# Question at: # https://www.reddit.com/r/dailyprogrammer/comments/7btzrw/20171108_challenge_339_intermediate_a_car_renting/ # determines the optimal solution to serve the most rental requests) # uses greedy solution, sorting by the rental finish date # input is n the number of requests and and array of pairs for the ...
gsmandur/Daily-Programmer
339/339_sol.py
339_sol.py
py
1,798
python
en
code
0
github-code
36
18345784828
""" Define a procedure histogram() that takes a list of integers and prints a histogram to the screen. For example, histogram([4, 9, 7]) should print the following: **** ********* ******* """ # args used to pass a non-keyworded, variable-length argument list, def histogram(myList = [], *args): """ This Definitio...
sonimonish00/Projects-College
Project 1 - College Miniprojects/Python/Prac1-c.py
Prac1-c.py
py
701
python
en
code
1
github-code
36
21126149841
"""The core of p2pg.""" import logging from threading import Lock from .conf import conf, dump_after __author__ = 'Michael Bradley <michael@sigm.io>' __copyright__ = 'GNU General Public License V3' __copy_link__ = 'https://www.gnu.org/licenses/gpl-3.0.txt' __website__ = 'https://p2pg.sigm.io/' __support__ = 'https:/...
TheDocTrier/p2pg
core/__init__.py
__init__.py
py
1,156
python
en
code
0
github-code
36
5765246532
import pyautogui import schedule import time import datetime import random pyautogui.FAILSAFE = False screenWidth, screenHeight = pyautogui.size() # Get the size of the primary monitor. currentMouseX, currentMouseY = pyautogui.position() # Get the XY position of the mouse. datetime.datetime.now() print(datetime.date...
jbernax/autoclicktimer
autoclick.py
autoclick.py
py
5,721
python
en
code
0
github-code
36
72655514343
import copy import json import os import datetime from json import dumps import logging import uuid import tweepy from flask import Flask, render_template, url_for, request, send_from_directory from flask_pymongo import PyMongo import folium from geopy.exc import GeocoderTimedOut from geopy.geocoders import Nominatim ...
rwth-acis/bot-detector
web_application/ms_signal_generator.py
ms_signal_generator.py
py
4,034
python
en
code
3
github-code
36
6786801031
import unittest from local import EXOLEVER_HOST import requests class ChatUserTest(unittest.TestCase): def do_login(self): url = '/api/accounts/login/' prefix = '' url = EXOLEVER_HOST + prefix + url data = { 'username': 'gorkaarrizabalaga@example.com', 'pa...
tomasgarzon/exo-services
service-exo-broker/tests/test_chat_user.py
test_chat_user.py
py
1,990
python
en
code
0
github-code
36
14114861210
import sys bead_N, edge = map(int, sys.stdin.readline().strip().split()) heavy_bead_list = [[] for _ in range(bead_N + 1)] light_bead_list = [[] for _ in range(bead_N + 1)] for _ in range(edge): heavy, light = map(int, sys.stdin.readline().strip().split()) heavy_bead_list[light].append(heavy) light_bead_l...
nashs789/JGAlgo
Week02/Q2617/Jisung.py
Jisung.py
py
814
python
en
code
2
github-code
36
29449039491
""" Script name: 03_count_language_editions_at_point_in_time.py Purpose of script: count language editions per month and year Dependencies: 02_get_language_edition_history_wikidata.py Author: Alexandra Rottenkolber """ import pandas as pd # read in data creation_date_df = pd.read_csv("./data_analysis/01_data/Wikiped...
AlexandraRoko/Discourse_openess_and_pol_elites
2_Wikipedia/03_pull_historical_Wiki_data/03_count_language_editions_at_point_in_time.py
03_count_language_editions_at_point_in_time.py
py
3,658
python
en
code
0
github-code
36
74274579943
import pytest import ruleset import util import os def get_testdata(rulesets): """ In order to do test-level parametrization (is this a word?), we have to bundle the test data from rulesets into tuples so py.test can understand how to run tests across the whole suite of rulesets """ testdata = ...
fastly/ftw
ftw/pytest_plugin.py
pytest_plugin.py
py
3,940
python
en
code
263
github-code
36
39076799665
from string import ascii_lowercase class Node: def __init__(self, val, parents = []): self.val = val self.parents = parents def __str__(self): return self.val from collections import deque from string import ascii_lowercase class Solution: def findLadders(self, beginWord: str, endWor...
YuxiLiuAsana/LeetCodeSolution
q0126.py
q0126.py
py
2,196
python
en
code
0
github-code
36
26606758529
import sys t= int(input()) for _ in range(t): data=[] count=1 n=int(input()) for i in range(n): a,b=map(int,sys.stdin.readline().split()) data.append((a,b)) data.sort(key=lambda x: x[0]) min_data=data[0][1] for i in data[1:]: if min_data>i[1]: count...
realme1st/Algorithm-study
Baekjoon/그리디/신입사원 (1946).py
신입사원 (1946).py
py
367
python
en
code
0
github-code
36
42867652572
from utils import read_input def age_and_spawn_the_fish(fishes): baby_age = 8 spawns = determine_num_spawns(fishes) for i, fish in enumerate(fishes): fishes[i] = calc_next_age(fish) for i in range(0, spawns): fishes.append(baby_age) return fishes def calc_next_age(fish): ...
tthompson691/AdventOfCode
src/2021/Day6/day6_solution.py
day6_solution.py
py
1,479
python
en
code
2
github-code
36
6750580086
# -*- coding: utf-8 -*- from PyQt5.QtWidgets import QDialog, QTreeWidgetItem, QMenu from PyQt5.QtCore import pyqtSlot, QPoint from labrecord.controllers.labrecordscontroller import LabrecordsController from labrecord.modules.editobservationmodule import EditObservationModule from labrecord.modules.checkreportmodule i...
zxcvbnmz0x/gmpsystem
labrecord/modules/editsamplerecorddetailmodule.py
editsamplerecorddetailmodule.py
py
10,508
python
en
code
0
github-code
36
18701687808
import numpy as np from numpy import linalg as LA from keras.applications.vgg16 import VGG16 from keras.preprocessing import image from keras.applications.vgg16 import preprocess_input from PIL import Image from cv2 import imread,resize,cvtColor,COLOR_BGR2RGB,INTER_AREA,imshow ''' VGG16模型,权重由ImageNet训练而来 使用vgg16模型提取特...
935048000/ImageSearch
core/feature_extraction.py
feature_extraction.py
py
1,808
python
en
code
1
github-code
36
1054566885
# -*- coding = utf-8 -*- # @Time : 2021/5/5 18:25 # @Author : 水神与月神 # @File : 灰度转彩色.py # @Software : PyCharm import cv2 as cv import numpy as np import os import mypackage.dip_function as df # demo # path = r"C:\Users\dell\Desktop\8.png" # # image = cv.imread(path, cv.IMREAD_UNCHANGED) # # image1 = image[:, :, 0] # ...
mdwalu/previous
数字图像处理/灰度转彩色.py
灰度转彩色.py
py
2,065
python
en
code
1
github-code
36
70167417064
from mongoengine import Q from django_pds.conf import settings from django_pds.core.managers import UserReadableDataManager, GenericReadManager, UserRoleMapsManager from django_pds.core.rest.response import error_response, success_response_with_total_records from django_pds.core.utils import get_fields, get_document, ...
knroy/django-pds
django_pds/core/pds/generic/read.py
read.py
py
6,463
python
en
code
3
github-code
36
34203743613
import numpy as np import torch import torch.nn as nn from pytorch_lightning.utilities.rank_zero import _get_rank import models from models.base import BaseModel from models.utils import scale_anything, get_activation, cleanup, chunk_batch from models.network_utils import get_encoding, get_mlp, get_encoding_with_net...
3dlg-hcvc/paris
models/geometry.py
geometry.py
py
13,820
python
en
code
31
github-code
36
3572388059
## # @file mathlib.py # @package mathlib # @brief Module with functions to convert and evaluate expression using expression tree import treeClass import logging # """Priorities of operators""" priority = { '!' : 3, '^' : 2, '*' : 1, '/' : 1, '%' : 1, '+' : 0, '-' : 0, } # """Associativit...
Hedgezi/jenna_calcutega
src/mathlib.py
mathlib.py
py
4,055
python
en
code
0
github-code
36
14784031149
# -*- coding: utf-8 -*- #coding=utf-8 from AppiumTest import webdriver import unittest from time import sleep desired_caps = {} desired_caps['platformName'] = 'Android' desired_caps['platformVersion'] = '4.4.4' desired_caps['deviceName'] = 'Android Emulator' desired_caps['appPackage'] = 'com.entstudy.enjoystudy' des...
flamecontrol/flamecontrol
Latent/script/testswipe.py
testswipe.py
py
995
python
en
code
1
github-code
36
74518602024
#import os from typing import Union import torch import numpy as np from . import torch_knn gpu_available = torch_knn.check_for_gpu() if not gpu_available: print("The library was not successfully compiled using CUDA. Only the CPU version will be available.") _transl_torch_device = {"cpu": "CPU", "cuda": "GPU"} c...
thomgrand/torch_kdtree
torch_kdtree/nn_distance.py
nn_distance.py
py
7,259
python
en
code
5
github-code
36
4197719073
"""Utilities for plotting the results of the experiments.""" import os import json import numpy as np import pandas as pd import matplotlib matplotlib.use("pdf") # Avoid trouble when generating pdf's on a distant server # matplotlib.use("TkAgg") # Be able to import matplotlib in ipython import matplotlib.pyplot as plt ...
RobinVogel/Weighted-Empirical-Risk-Minimization
plot_utils.py
plot_utils.py
py
10,788
python
en
code
1
github-code
36
27253300099
#!/usr/bin/python import sys #latepath="/home/akavka/minimax/" def compareGames(inFile1, inFile2): in1=open(inFile1, "r") in2=open(inFile2,"r") #result=True lines1=in1.readlines() lines2=in2.readlines() # if (len(lines1)!=len(lines2)): # return False #implicit else ...
akavka/minimax
takeAverages.py
takeAverages.py
py
5,604
python
en
code
0
github-code
36
11370165603
import numpy as np import torch import torch.nn as nn from ml.modules.backbones import Backbone from ml.modules.bottoms import Bottom from ml.modules.heads import Head from ml.modules.layers.bifpn import BiFpn from ml.modules.tops import Top class BaseModel(nn.Module): def __init__(self, config): super()...
gregiberri/DepthPrediction
ml/models/base_model.py
base_model.py
py
4,058
python
en
code
0
github-code
36
2463271534
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: node = head while node: runner = node.next while runner and runner.val == nod...
Iannikan/LeetCodeQuestions
removeDuplicatesFromSortedList/solution.py
solution.py
py
440
python
en
code
0
github-code
36
43069956711
import csv import io from Crypto.Signature import pkcs1_15 from Crypto.PublicKey import RSA from Crypto.Hash import SHA256, SHA gSigner = "signer@stem_app" def loadVoters(fname): try: voters = {s['studNr']: s for s in csv.DictReader( loadFile(fname), delimiter=';')} return voters ...
Tataturk/stem_app
audit.py
audit.py
py
2,468
python
en
code
0
github-code
36
44575910113
from dbmanager import DatabaseManager from tgbot import Bot from market import Market from plot_provider import PlotProvider import threading import sys import logging import logging.handlers import queue from apscheduler.schedulers.background import BackgroundScheduler class MarketManager: def __init__(self, pa...
hype-ecosystem/predictions_bot
market_manager.py
market_manager.py
py
3,531
python
en
code
2
github-code
36