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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
73820290537 | class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
result = []
size = len(nums)
idx = 0
while idx < size:
num = nums[idx]
left, right = idx + 1, size - 1
while left < right:
_sum = num + num... | HarrrrryLi/LeetCode | 15. 3Sum/Python 3/solution.py | solution.py | py | 1,091 | python | en | code | 0 | github-code | 90 |
42474650520 | #A Project by Ben Ber 2022
#!/usr/bin/env python3
print("--- Stundenplan Abfrage HHS ---") #just to cover up the loading time (psst)
print("")
from bs4 import BeautifulSoup #just used to get the date very inefficient
import requests
import pandas as pd
#defaults
days = 3
dropindex = "n"
loop = "y"
while loop == "... | Poliano/Vertretungsplan_HeinrichHertzSchule | Plan.py | Plan.py | py | 3,061 | python | de | code | 0 | github-code | 90 |
22653401584 | import xlrd
from TestRequest import *
from testdata.getpath import GetTestDataPath
Testdata = xlrd.open_workbook(GetTestDataPath())
testUrl="http://127.0.0.1:8000"
def post_vote():
try:
table = Testdata.sheets()[1]
for i in range(3,5):
choice=table.cell(i,0).value
status=ta... | qiumomoqiu/learnPython | py接口自动化测试/TestRequest_TestCase/testVote.py | testVote.py | py | 2,376 | python | en | code | 0 | github-code | 90 |
2836932924 | #### Libraries
# Standard library
import pickle
import gzip
# Third-party libraries
import numpy as np
#### Load the MNIST data
def get_part(data, seed, size):
X, y = data
n = X.shape[0]
if n <= size:return data
if seed:
np.random.seed(seed)
shuffle_indexes = np.random.permutation(n)
p... | windmissing/DeepLearningPractise | Chapter8/mnist_loader.py | mnist_loader.py | py | 1,193 | python | en | code | 13 | github-code | 90 |
18064148759 | '''
Created on 2020/08/19
@author: harurun
'''
def main():
import sys
pin=sys.stdin.readline
pout=sys.stdout.write
perr=sys.stderr.write
S=pin()[:-1]
T=list(set(S))
if len(T)==4:
print("Yes")
elif len(T)==3 or len(T)==1:
print("No")
else:
if (("N" in S )and ("S" in S)) or (("W" in S) a... | Aasthaengg/IBMdataset | Python_codes/p04019/s035664854.py | s035664854.py | py | 400 | python | en | code | 0 | github-code | 90 |
36391511495 | from gluon.storage import Storage
settings = Storage()
settings.migrate = True
settings.title = 'PyRest'
settings.subtitle = 'Aplicacion para manejo de expendios de alimentos y afines'
settings.author = 'Wuelfhis Asuaje'
settings.author_email = 'wasuaje@hotmail.com'
settings.keywords = ''
settings.description = ''
set... | wasuaje/web2py5 | applications/PyRest/models/0.py | 0.py | py | 735 | python | en | code | 0 | github-code | 90 |
18763618700 | from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth import login
from .forms import RegisterForm
from api.views import home
from account.models import Favorite
def register(request):
if request.method == 'GET':
... | ardakoc/djweather | account/views.py | views.py | py | 1,309 | python | en | code | 0 | github-code | 90 |
4585758422 | import math
def Nhap():
a=int(input('Nhap tu so:'))
b=int(input('Nhap mau so:'))
return a,b
def rutgonphanso(a,b):
d=math.gcd(a,b)
e=a//d
f=b//d
return e,f
a,b=Nhap()
e,f=rutgonphanso(a,b)
print('Phansorutgon:',e,f)
| tkieuvt/CoSoLapTrinh123 | BaiC4Nhom5/Bai101.py | Bai101.py | py | 248 | python | en | code | 0 | github-code | 90 |
24647633160 | import numpy as np
import os
import random
import argparse
import scipy
from scipy.stats import chi2_contingency
from Args import args
class Graph:
def __init__(self, g_args):
self._build_param(g_args)
"""
{
r_name: r_id,
r_name: r_id,
...
}
... | nju-websoft/RGRec | src/Graph.py | Graph.py | py | 24,032 | python | en | code | 15 | github-code | 90 |
18204165949 | import math
N = int(input())
def bunkai(n):
factor={}
tmp = int(math.sqrt(n)) + 1
for num in range(2, tmp):
while n%num == 0:
n /= num
try:
factor[num] += 1
except:
factor[num] = 1
if int(n) != 1:
factor[int(n)] =... | Aasthaengg/IBMdataset | Python_codes/p02660/s383951281.py | s383951281.py | py | 518 | python | en | code | 0 | github-code | 90 |
41169892845 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 4 05:11:04 2020
@author: donbo
"""
# %% imports
import scipy
import scipy.optimize as spo
import gc
import numpy as np
import jax
import jax.numpy as jnp
# this next line is CRUCIAL or we will lose precision
from jax.config import config; config.update("jax_enable_x64"... | donboyd5/weighting | src/geoweight_poisson_lsq.py | geoweight_poisson_lsq.py | py | 3,981 | python | en | code | 0 | github-code | 90 |
34037115896 | import csv
import logging
import unittest
def load_from_csv(filepath, header = True, delim = ','):
"""
Parse a CSV file to extract paramaters
Args:
filepath (str) to local csv file containing
SeriesType, Denomination, SerialNumber, IssueDate
Data is expected in the followi... | DougForrest/treasurydirect-bulk-valuation-app | helpers/csv_parser.py | csv_parser.py | py | 1,016 | python | en | code | 1 | github-code | 90 |
16947860471 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def make_list(A):
head = ListNode(A[0])
ptr = head
for i in A[1:]:
ptr.next = ListNode(i)
ptr = ptr.next
return head
def display(head):... | iamsuman/algorithms | iv/Leetcode/easy/203_remove_linked_list_element.py | 203_remove_linked_list_element.py | py | 1,026 | python | en | code | 2 | github-code | 90 |
18326932090 | from django.db import models
from django.utils.timezone import now
from django.contrib.auth.models import User
choices = (
("bn", "Bengali"),
("gu", "Gujarati"),
("hi", "Hindi"),
("kn", "Kannada"),
("ml", "Malayalam"),
("mr", "Marathi"),
("ne", "Nepali"),
("or", "Oriya"),
("pa", "Pa... | anuran-roy/translator-django | worker/models.py | models.py | py | 1,659 | python | en | code | 1 | github-code | 90 |
8383403500 | from __future__ import annotations
import json
import requests
import threading
import time
from workflow.api import (
TrainMainWorkflow,
TestMainWorkflow
)
from network.api import Network
from pi.api import PI
from authentication.api import Authentication
from typeguard import typechecked
#@typechecked
cl... | Collaborative-AI/colda | package/colda/short_polling/polling.py | polling.py | py | 8,048 | python | en | code | 17 | github-code | 90 |
43044569981 | import eulerlib, itertools
# Model the problem as a Markov process, and solve using dynamic programming
def compute():
# Memoize the successors of each valid state
successors = {}
for st in State.list_all_states():
successors[st.id] = [s.id for s in st.get_successors()]
# Run the simulation
ans = 0.0
probs ... | nayuki/Project-Euler-solutions | python/p280.py | p280.py | py | 3,046 | python | en | code | 1,809 | github-code | 90 |
6968025190 |
version = "v0.1"
import string
import random
"""
NOTE
"Encryption is poggers" -Alan Turing, probably
This is a very simple method I came up with, but I'm sure its already been discovered and has a proper name
Very bad explanaion considering the message is part of the key lol
Generate and assign a random character ... | besser435/Cipher | Cipher_old.py | Cipher_old.py | py | 2,066 | python | en | code | 0 | github-code | 90 |
38856382625 | # линейный поиск
#
name = ['бука','beka','erf','нурислам','adahan']
search_for = 'нурислам' # что мы ищем
def linear_search(where,what):
for v in enumerate(where):
if v[1] == what :
return v[0] # возвращаем индекс
return None
print('искомый элемент',search_for,'найден под индексом'... | Ansordeveloper/Lessons-2 | lesson_7.py | lesson_7.py | py | 2,351 | python | ru | code | 0 | github-code | 90 |
23685196968 | import cv2
import time
import paho.mqtt.client as mqtt
import socket
import numpy as np
filename = "receive.jpg"
Con_Flag=0
host = '192.168.1.111' # sever's IP
port = 5555 # sever's host
address = (host, port)
####################
def on_connect(client, userdata, flags, rc):
print("Connected with code :"+ str(... | digiplusdaniel/embedded | 6.Source Code/Rasp1_MQTTPUB_ImageArray_TCPRecive.py | Rasp1_MQTTPUB_ImageArray_TCPRecive.py | py | 1,868 | python | en | code | 0 | github-code | 90 |
24623232251 | import json
from typing import Tuple, Dict, Any, Iterable, TYPE_CHECKING
import fastjsonschema
from werkzeug import exceptions as werkzeug_exceptions
from dragonchain import logger
from dragonchain import exceptions
from dragonchain.lib import error_reporter
from dragonchain.lib.dto import schema
if TYPE_CHECKING:
... | dragonchain/dragonchain | dragonchain/webserver/helpers.py | helpers.py | py | 9,802 | python | en | code | 701 | github-code | 90 |
33458157804 | from typing import List
from unittest import TestCase
class Solution:
def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
n = len(nums)
nums.sort()
res = []
for query in queries:
count = 0
currentSum = 0
while count < n:
... | Samuel-Black/leetcode | longest-subsequence-with-limited-sum.py | longest-subsequence-with-limited-sum.py | py | 686 | python | en | code | 0 | github-code | 90 |
14643189520 | from datetime import datetime, timedelta
from collections import namedtuple
from sqlalchemy import select, desc
from sqlalchemy import func
from flask import current_app, json
from flask_script import Manager
Statistics = Manager(usage='Manage quiz statistics.')
Row = namedtuple('Row', ['quiz_type', 'school_id', 'fi... | Vickyogesh/quiz-platform | wsgi/quiz/stat.py | stat.py | py | 3,342 | python | en | code | 0 | github-code | 90 |
38280948515 | import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import urllib.request
import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, iplot, plot
import squarify
plt.style.use('seaborn')
def plot_success_failure(df, col, ax=None):
plt.style.use('seaborn'... | EdanZwick/Kickstarter | kickstarter/visio.py | visio.py | py | 7,143 | python | en | code | 0 | github-code | 90 |
21457642854 | import numpy as np
import pygame
import torch
import uuid
from food import Food
from creature import Creature
from geneutils import Genome
from brain import Brain
from config import CONFIG
class World(object):
def __init__(self, borderDims=list([int, int]), foodList=[], creatureList=[], foodPerTimestep: int = 0.5)... | Shr1ftyy/alife | world.py | world.py | py | 3,306 | python | en | code | 0 | github-code | 90 |
38902387090 | import os
from scipy.stats import chisquare
from scipy.stats import ks_2samp
from scipy.stats import combine_pvalues
import plotly.graph_objects as go
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from fbprophet import Prophet
def init_df(df, colname, target, target_value):
value_arr = df... | ygeszvain/GusPI | GusPI/statsPy.py | statsPy.py | py | 5,649 | python | en | code | 0 | github-code | 90 |
71972991338 | from django.urls import path
from .views import Signup, Login, Test
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
urlpatterns = [
path('signup/', Signup.as_view(), name='signup'),
path('login/', Login.as_view(), name='login'),
path('api/token/', TokenObtainPa... | VadimSadriev/OnlineStore | OnlineStore.WebServer/onlinestore/account/urls.py | urls.py | py | 496 | python | en | code | 1 | github-code | 90 |
12821669472 | from model.Models import *
from controller.Actions import *
from view.View import *
from time import sleep
class App:
def __init__(self):
self.state = initial_state()
self.actions = Actions()
pass
def start(self):
print('Inicia el Juego')
view = View(self)
... | baiest/Snake | src/app.py | app.py | py | 709 | python | en | code | 0 | github-code | 90 |
71954606698 | import numpy as np
from bioptim import (
Node,
OptimalControlProgram,
ConstraintFcn,
ObjectiveFcn,
DynamicsFcn,
QAndQDotBounds,
PhaseTransitionFcn,
ConstraintList,
ObjectiveList,
DynamicsList,
BoundsList,
InitialGuessList,
PhaseTransitionList,
BiMappingList,
C... | s2mLab/BioptimPaperExamples | jumper/JumperOcp/__init__.py | __init__.py | py | 13,085 | python | en | code | 3 | github-code | 90 |
13733805590 | # -*- coding: ISO-8859-1 # Encoding declaration -*-
# file: create_reference_dir.py
#
# description
"""\n\n
for given start directory of a compare run, create a reference dir out of the result files
"""
import sys
import os
import shutil
import datetime
from glob import glob
from argparse import Argum... | bbbkl/python | regression/create_reference_dir.py | create_reference_dir.py | py | 6,121 | python | en | code | 0 | github-code | 90 |
18021703249 | def main():
n, ma, mb, *L = map(int, open(0).read().split())
M = 1 << 30
dp = [[M] * 420 for _ in range(420)]
dp[0][0] = 0
ua = ub = 15
for a, b, c in zip(*[iter(L)] * 3):
for i in range(ua, -1, -1):
for j in range(ub, -1, -1):
t = dp[i][j] + c
if dp[i + a][j + b] > t:
dp[i + a][j + b] = t
... | Aasthaengg/IBMdataset | Python_codes/p03806/s468498336.py | s468498336.py | py | 564 | python | en | code | 0 | github-code | 90 |
22773483256 | # 3장 피마 인디언 당뇨병 예측
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, precision_score, recall_score, roc_auc_score
from sklearn.metrics import f1_score, confusion_matrix, precision_recall_curve, roc_cu... | parkdoyun/machine_learning_study | ch3.py | ch3.py | py | 6,531 | python | ko | code | 0 | github-code | 90 |
18212096069 | MOD = 10 ** 9 + 7
from math import gcd
from collections import defaultdict
n = int(input())
plus = defaultdict(int)
minus = defaultdict(int)
zero = [0, 0, 0]
for _ in range(n):
a, b = map(int, input().split())
if a * b == 0:
if a == b == 0:
zero[0] += 1
elif a == 0:
zero... | Aasthaengg/IBMdataset | Python_codes/p02679/s243550971.py | s243550971.py | py | 940 | python | en | code | 0 | github-code | 90 |
25746371732 | from model.level.LevelRepository import LevelRepository
from model.game.GameRepository import GameRepository
from view.LevelCommands import LevelCommands
from view.LevelEndCommands import LevelEndCommands
from view.QuitCommands import QuitCommands
class GameController:
def __init__(self, user):
self._game... | Charlie-robin/text-adventure-python | src/controller/GameController.py | GameController.py | py | 1,387 | python | en | code | 0 | github-code | 90 |
35383576414 | # -*- coding:utf-8 -*-
import time
from application import redis_link as redis
from application import app
if not app.config['DEBUG']:
from application.util import logger as LOGGER
else:
from application.util import LocalLogger as LOGGER
class RedisLock(object):
def __init__(self, key):
self.redis... | cnboysliber/AutoTest | application/util/redis_lock.py | redis_lock.py | py | 1,781 | python | en | code | 4 | github-code | 90 |
18369455603 | import re
import requests
from lxml import etree
headers={
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36"
}
url = 'http://dy.163.com/v2/article/detail/EOA7FNU60527AQ4N.html'
response = etree.HTML(requests.get(url, headers=headers... | lyt0527/scrapy | Wangyi/ceshi.py | ceshi.py | py | 454 | python | en | code | 0 | github-code | 90 |
13581140022 | from extdirect.django import remoting, ExtRemotingProvider, ExtPollingProvider
from django.conf import settings
from django.core.urlresolvers import clear_url_caches
from biogps.utils.helper import json
#add a new method to the original ExtRemotingProvider class
class ExtRemotingProvider2(ExtRemotingProvider):
de... | SuLab/biogps_core | src/biogps/biogps/extdirect/views.py | views.py | py | 1,396 | python | en | code | 0 | github-code | 90 |
71125374696 | from flask import Flask
from flask import Response
from flask import request
from flask import make_response
from IDEAS.api.structure_v1 import APIcache
from IDEAS.api.structure_v1 import APIquery
import IDEAS.lib.inflect
import IDEAS.base
import urllib
app = Flask(__name__)
#starting to explore FlashAuth
#from flaske... | laironald/IDEAS-Pub | IDEAS/api/server_v1.py | server_v1.py | py | 9,953 | python | en | code | 0 | github-code | 90 |
13197688434 | import os
import csv
# opening the csv file
# I programmed this with the files being located on my c-drive
# the following code will only work if the .py file is in the same directory
# as the resources subfolder
file_name = "budget_data.csv"
csvpath = os.path.join(os.getcwd(), "Resources", file_name)
#arrays f... | laurahp00/python-challenge | PyBank/main.py | main.py | py | 2,296 | python | en | code | 0 | github-code | 90 |
9591200205 | """
Command Plugin for handling Readings
"""
from com.Globals import *
import dev.Reading as Reading
import dev.Cmd as Cmd
#######
@Cmd.route('reading.full.list.#')
@Cmd.route('vfl.#')
def cmd_reading_full_list(cmd:dict) -> tuple:
""" gets a list of dics with all reading parameters """
index = cmd['IDX']
... | happytm/ezPiC | ezPiC/dev/plugins/cmds/cmdReading.py | cmdReading.py | py | 1,264 | python | en | code | 0 | github-code | 90 |
18430690849 | def main():
from collections import Counter
N = int(input())
S_count = Counter(input())
P = 10**9+7
ans = 1
for v in S_count.values():
ans *= v+1
ans %= P
print(ans-1)
main() | Aasthaengg/IBMdataset | Python_codes/p03095/s101596221.py | s101596221.py | py | 221 | python | en | code | 0 | github-code | 90 |
7697943087 | from logging import getLogger
from apiclient.errors import HttpError
from flask import current_app
from flask import request
from flask import json
from flask import render_template
from werkzeug.exceptions import (
BadRequest, InternalServerError, Unauthorized
)
from ggrc import settings
from ggrc.gdrive import... | saalimzafar/ggrc-core | src/ggrc/views/converters.py | converters.py | py | 5,810 | python | en | code | null | github-code | 90 |
5645521656 | # coding: utf-8
'''
Profile our registration functionality.
'''
# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------
from typing import TYPE_CHECKING, Optional, Iterable, Literal
from typ... | cole-brown/veredi-code | run/zprofile_registry.py | zprofile_registry.py | py | 5,696 | python | en | code | 1 | github-code | 90 |
38442735949 | from pathlib import Path
import pytest
from m23.utils import sorted_by_number
class TestSortedByNumber:
def test_ints(self):
test_in = [1, 2, 3]
with pytest.raises(ValueError, match="items of list must be either str or Path instance"):
sorted_by_number(test_in)
def test_num_only(s... | LutherAstrophysics/m23 | tests/test_utils.py | test_utils.py | py | 1,643 | python | en | code | 0 | github-code | 90 |
13997371638 | # -*- coding: utf-8 -*-
import urllib.request
import urllib.error
import time
import os
import json
from config import Config
http_url = r'https://api-cn.faceplusplus.com/facepp/v3/detect'
key = r"os2x76mV8-UjMTVZ5Y2vJsVSX2SGX4YX"
secret = r"jc5huvAfw9-CzgICpy2Hx7iIqNmHPKJH"
class Detect:
def __init__(self, img_d... | Jeret-Ljt/average_face | faceplusplus_sdk.py | faceplusplus_sdk.py | py | 3,051 | python | en | code | 1 | github-code | 90 |
37136401936 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import butter, iirnotch, filtfilt, freqz
from get_SNR import get_SNR
def NotchFilter(f0, signal, fs = 1000.0, Q = 30.0):
# Design notch filter
b_notch, a_notch = iirnotch(f0, Q, fs)
# Compute magnitude response of the... | lichangling3/EMG-decoding-Arduino | src/get_freq.py | get_freq.py | py | 4,499 | python | en | code | 0 | github-code | 90 |
39922437775 | from .meta_base import MetaBase
from .base import Base
from .caching_query import FromCache
from sqlalchemy import create_engine
from sqlalchemy.engine import reflection
from sqlalchemy.schema import (
MetaData,
Table,
DropTable,
ForeignKeyConstraint,
DropConstraint,
)
f... | konstantinov90/calc_factory | utils/ORM/__init__.py | __init__.py | py | 1,787 | python | en | code | 0 | github-code | 90 |
18063417079 | N,A=map(int,input().split())
x=list(map(int,input().split()))
ans=0
y=[0]*(len(x))
for k in range(len(x)):
y[k]=x[k]-A
minus=0
plus=0
for k in range(N):
if y[k]<0:
minus-=y[k]
if y[k]>0:
plus+=y[k]
total=minus+plus+1
ans=[[0 for i in range(N)]for j in range(total)]
ans[y[0]+minus][0]=1
ans[m... | Aasthaengg/IBMdataset | Python_codes/p04013/s128707746.py | s128707746.py | py | 548 | python | en | code | 0 | github-code | 90 |
19012871405 | class Solution:
def __method1 (self, i, j, nums):
if (i > j): return 0
if (self.dp[i][j] != None): return self.dp[i][j]
self.dp[i][j] = 0
left = 1 if ((i - 1) < 0) else nums[i - 1]
right = 1 if ((j + 1) >= len(nums)) else nums[j + 1]
k = i
while (k <= j):
... | Tejas07PSK/fraz-leetcode-hot-250 | Dynamic Programming/burst_balloons.py | burst_balloons.py | py | 1,393 | python | en | code | 1 | github-code | 90 |
12287059029 | import numpy as np
def getZ(X, Y):
return np.sin(np.sqrt(X ** 2 + Y ** 2))
X = np.linspace(-5, 5, 100)
Y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(X, Y)
Z = getZ(X,Y)
print(X, Y)
print(Z)
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
fig = plt.figure()
ax = plt.axes(projection="3d")
ax.... | humerbenjamin/PHY427_APL | Experiment2_GAUS/Code/temp.py | temp.py | py | 672 | python | en | code | 0 | github-code | 90 |
859895912 | '''
Overview:
Parses as run files in a directory and adds break durations together
as Timecode objects. Returns durations with date, time and duration in CSV.
e.g. 9/26/2022,04:19:18:15,00:01:00;02
Define an ID range for commercial spots,
search directory, output filename and ignore patterns.
'''
import os
from tim... | Nathan-Powell/asrun-break-duration-parser | asrun_break_duration_parser.py | asrun_break_duration_parser.py | py | 3,511 | python | en | code | 0 | github-code | 90 |
9186626898 | # Imports
import requests
from bs4 import BeautifulSoup
import urllib.parse as getDomain
# Function to run for getting the GdTot links
def magic():
url = input("Media Homepage from OlaMovies - ")
page = requests.get(url)
soup = BeautifulSoup(page.content, "html.parser")
links = soup.find_all(
... | MoviesCave/OlaMoviesScraper | Scraper.py | Scraper.py | py | 1,181 | python | en | code | 1 | github-code | 90 |
71214439658 | #!/usr/bin/env python3
import pychromecast
import threading
import cec
import time
import argparse
import sys
import os
import shutil
import subprocess
parser = argparse.ArgumentParser(description='Checks if a particular Chromecast is idle, and switches off specified TV/Hifi equipment after a timeout. Also allows con... | askvictor/ChromecastControls | chromecast_controls.py | chromecast_controls.py | py | 6,850 | python | en | code | 95 | github-code | 90 |
524495877 | #!/usr/bin/env python3
import os
import sys
from pathlib import Path
def listdir(dir):
print('listdir:')
print([e for e in os.listdir(dir) if os.path.isdir(os.path.join(dir, e))])
def scandir(dir):
print('scandir:')
with os.scandir(dir) as entries:
print([e.name for e in entries if e.is_dir()... | joez/letspy | lang/module/listdir.py | listdir.py | py | 745 | python | en | code | 0 | github-code | 90 |
25525372168 | #!/usr/bin/env python3
#pylint: disable=superfluous-parens
from flask import Flask
app = Flask(__name__)
try:
with open('secret.key', 'rb') as keyFile:
app.secret_key = keyFile.read()
except Exception as e:
print(e)
print(
"\nIn order to use sessions you have to set a secret key.\n" +
... | codingjerk/ztd.blunders-web | app/__init__.py | __init__.py | py | 528 | python | en | code | 0 | github-code | 90 |
3618205694 | import math
import pygame as pg
from collections import OrderedDict
from data.core import tools, constants
from data.components.labels import Button, ButtonGroup
from data.components.special_buttons import GameButton, NeonButton
from data.components.animation import Animation
from data.components.state_machine import... | reddit-pygame/Python_Arcade_Collab | data/states/lobby/lobby_screen.py | lobby_screen.py | py | 5,597 | python | en | code | 3 | github-code | 90 |
18130884810 | class Solution:
def distinctNames(self, ideas: List[str]) -> int:
wordMap=collections.defaultdict(set)
for word in ideas:
wordMap[word[0]].add(word[1:])
ans=0
for char1 in wordMap:
for char2 in wordMap:
if char1==char2:
... | narendrasingodia1998/LeetCode | 2306-naming-a-company/2306-naming-a-company.py | 2306-naming-a-company.py | py | 694 | python | en | code | 0 | github-code | 90 |
27713170532 | """
The update() method of the hash calculators can be called repeatedly. Each time, the digest
is updated based on the additional text fed in. Updating incrementally is more efficient than
reading an entire file into memory, and produces the same results.
"""
import hashlib
with open("../hash_data.txt", "rt") as fil... | rakkaalhazimi/Python_Std_Library | Ch9Cryptography/hashlib_module/No_6_Incremental_updates/hashlib_update.py | hashlib_update.py | py | 928 | python | en | code | 0 | github-code | 90 |
18141168839 | def how_many_ways(n, x):
ways = 0
for i in range(1, n-1):
for j in range(i+1, n):
for k in range(j+1, n+1):
if i+j+k == x:
ways += 1
return ways
def main():
while True:
n, x = [int(x) for x in input().split()]
if n == x == 0:
... | Aasthaengg/IBMdataset | Python_codes/p02412/s337393283.py | s337393283.py | py | 410 | python | en | code | 0 | github-code | 90 |
71079803817 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 20 00:16:33 2019
@author: Ryan
"""
import matplotlib.pyplot as plt
import pandas as pd
file_name_CX = './jbs/jbs_CX_result.csv'
file_name_GTX = './jbs/jbs_GTX_result.csv'
file_name_PMX = './jbs/jbs_PMX_result.csv'
df_CX = pd.read_csv(file_name_C... | HaoziHuang/IntelligentOptimizationAlgorithmEvaluation | result/show.py | show.py | py | 981 | python | en | code | 0 | github-code | 90 |
3035974097 | from ..HIR import Variable
from . import Tree
import string
import random
NL = '\n'
module_name = None
module_vars_used = 0
operators = {
'*': ('imul ' + NL),
'/': ('idiv ' + NL),
'<<': ('ishl ' + NL),
'>>': ('ishr ' + NL),
'>>>': ('iushr' + NL),
'&': ('iand ' + NL),
'|': (... | rendoir/feup-comp | compiler/LIR/Instruction.py | Instruction.py | py | 17,080 | python | en | code | 1 | github-code | 90 |
12111084531 | from simulation.rotor_contact import RotorContact
class Plugboard:
''' Class representing an Enigma plugboard / Steckerbrett (German). '''
__slots__ = ['_wiring']
def __init__(self):
self._wiring = {}
for letter in RotorContact:
self._wiring[letter] = letter
def set_plug(... | SwatKat1977/EnigmaSimulator | enigma_simulator/simulation/plugboard.py | plugboard.py | py | 2,076 | python | en | code | 1 | github-code | 90 |
117628069 | """ Solution to the 19th AOC of 2020. """
import re
from sys import argv
def parse_input(lines):
"""
Parse the lines into rules (first part) and messages (second part)
separated by a newline.
"""
newline = lines.index("")
messages = lines[newline + 1 :]
rules = {}
for rule in lines... | ollehu/aoc-2020 | 19/main.py | main.py | py | 3,150 | python | en | code | 0 | github-code | 90 |
8804818980 | from django import forms
from .models import Default_Templates
#Change path to parent directory for aneasier acces to files
import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
from employee.m... | constantinp2022/documentExporter | web_interface/default_tmpl/forms.py | forms.py | py | 1,080 | python | en | code | 0 | github-code | 90 |
41842538260 | import re
import csv
import sys
import json
import time
import logging
import requests
import traceback
import mysql.connector
from secrets import host, user, password, database
from urllib.parse import urlencode
logging.basicConfig(filename="GeoCodeLogEntries.log", format='%(asctime)s %(message)s', filemod... | akshitd11/Doctor-Extraction-Spell | geocoder.py | geocoder.py | py | 2,835 | python | en | code | 0 | github-code | 90 |
30832206776 | import can
import os
import time
import sys
from carData import rpmCode
def rpmOut(car):
# os.system("sudo ifconfig can0 down && sudo /sbin/ip link set can0 up type can bitrate 500000")
# time.sleep(0.1)
try:
bus = can.interface.Bus(channel='can0', bustype='socketcan_native')
except OSError:
... | Noahcdls/Project-Portunus | Project Portunus Diagnostics/rpmOut.py | rpmOut.py | py | 884 | python | en | code | 0 | github-code | 90 |
8966560608 | from bson.json_util import dumps
from app import app
from app import db
@app.route('/devices', methods=['GET'])
def get_all_devices():
collection = db['devices']
devices = collection.find()
response = []
for device in devices:
response.append(device)
return dumps(response)
@app.route('/... | knowlezi/serm | serm/simulator-api/app/device/device_controller.py | device_controller.py | py | 458 | python | en | code | 0 | github-code | 90 |
889071726 | current_users = ['mboucard', 'admin', 'john', 'zobi', 'luka' ]
new_users = ['Mboucard', 'hector', 'zobi', 'bibovski', 'leila']
for user in new_users:
if user.lower() in current_users:
print("username " + user + " already in use, pick another username")
else:
print("username " + user + " available")
| RayGutt/python | 5-10_checking_usernames.py | 5-10_checking_usernames.py | py | 309 | python | en | code | 0 | github-code | 90 |
4950608495 | import wx
import wx.xrc
import noname
import wx.richtext
import codecs
class funtion(noname.MyFrame1):
def newfile( self, event ):
self.text.Clear() #清除畫面
def openfile( self, event ):
file = wx.FileSelector( #將檔案路徑存成file
'請選擇檔案',
wildcard='全部|*.*',
... | EvanXwang/Python_training | wx_notebook/fun.py | fun.py | py | 1,186 | python | en | code | 1 | github-code | 90 |
35582816800 | import os
import random
import re
import time
from datetime import datetime
import pandas as pd
import requests
from .config import config
from .const import TreeHoleURLs
class TreeHoleClient(object):
def __init__(self):
self._session = requests.Session()
self._headers = {}
self._headers[... | yxwucq/Holemonitor | networks/utils.py | utils.py | py | 5,533 | python | en | code | 1 | github-code | 90 |
13147450069 | from tkinter import*
from tkinter import ttk
from PIL import Image,ImageTk
class Face_Recognization_System:
def __init__(self,root):#calling constructor(root(window name))
self.root=root#intialize root
self.root.geometry("1430x690+0+0")#width and height(starting point)
self.root.t... | KMVANDANA/LookIn | template.py | template.py | py | 3,864 | python | en | code | 0 | github-code | 90 |
42336502960 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import xarray as xr
import rasterio
from affine import Affine
import numpy as np
class GridType(object):
"""
Enumeration with grid types.
"""
UNKNOWN = 0
RGRID = 1 # equidistant regular grid
UGRID = 2 # unstructured grid
UCGRID = 3 # Unit-catc... | pauliscuss/xgeo | xgeo/utils.py | utils.py | py | 6,610 | python | en | code | 0 | github-code | 90 |
1115930192 | import os
from pathlib import Path
IMAGES_IN_FILE = "images.txt"
TRAIN_SPLIT_IN_FILE = "train_test_split.txt"
IMAGES_OUT_FILE = "images.txt"
TRAIN_SPLIT_OUT_FILE = "train_test_split.txt"
REMOVED_LIST_OUT_FILE = "removed.txt"
IMAGES_FOLDER = "images"
# Look for image files that might have been removed and remove them... | WouterJansen/BirbBro-ml | flickr_parser/remove_images_not_found.py | remove_images_not_found.py | py | 2,150 | python | en | code | 0 | github-code | 90 |
72821486057 | import json
import requests
# this function is used to send the request to teams using webhook url
def send_request_to_teams(webhook_url):
try:
message = {
"@type": "MessageCard",
"@context": "http://schema.org/extensions",
"summary": "Approval Request",
"t... | OnstakInc/ms-team_card | teams.py | teams.py | py | 2,886 | python | en | code | 0 | github-code | 90 |
15804475972 | '''
Artificial Neural Networks for Paris Endoscopic Classification of Superficial Neoplastic Lesions.
Proposal of a standardized implementation pipeline.
Code written by Stefano Magni.
If you have questions, please email me at: stefano.magni@outlook.com
Code to Preprocess data and prepare it for the data generato... | Stefano97/polyp-classification-poliambulanza | data_preparation.py | data_preparation.py | py | 50,947 | python | en | code | 0 | github-code | 90 |
5009331195 | import re
import pandas as pd
import measurement_stats as mstats
import cauldron as cd
couplings_data = cd.shared.couplings_data
rows = []
for entry in couplings_data:
id_parts = entry['id'].split('_')
gait_parts = id_parts[0].split('-', 2)
gait_id = gait_parts[0]
gait_number = re.sub(r'[^0-9]+', ''... | sernst/tracksim-analysis | regular-ideals/build_dataframe.py | build_dataframe.py | py | 1,904 | python | en | code | 0 | github-code | 90 |
13218471450 | import shutil
from pathlib import Path
from hello.x3m.transforms import *
img_formats = set([".bmp", ".jpg", ".jpeg", ".png"])
def regular_preprocess(img_path, out_path, transformers, dtype=np.uint8):
img_path, out_path = str(img_path), str(out_path)
img = cv.imread(img_path)
if img.ndim != 3:
... | flystarhe/hello | hello/x3m/preprocess.py | preprocess.py | py | 3,280 | python | en | code | 2 | github-code | 90 |
73090196775 | class Solution:
def isHappy(self, n: int) -> bool:
newnum = 0
res = []
while (1 not in res):
for i in str(n):
newnum += int(i)*int(i)
if newnum not in res:
res.append(newnum)
else:
return False
n ... | devWorldDivey/mypythonprogrammingtutorials | TutortAcademy/Assignmentpart3.py | Assignmentpart3.py | py | 2,982 | python | en | code | 0 | github-code | 90 |
18320683299 | import numpy as np
N = int(input())
xy = [list(map(int, input().split())) for _ in range(N)]
XY = np.array(xy).flatten()
X = XY[::2] ; Y = XY[1::2]
dx = X[:,None] - X[None, :]
dy = Y[:, None] - Y[None,:]
dist_mat = (dx*dx + dy*dy) ** .5
answer = dist_mat.sum() / N
print(answer)
| Aasthaengg/IBMdataset | Python_codes/p02861/s735112783.py | s735112783.py | py | 284 | python | en | code | 0 | github-code | 90 |
9533830494 | import numpy as np
import pandas as pd
from sklearn.utils import resample
def bootstrap_classes(num_iters, df_data, col_class, random_seq):
if not isinstance(df_data, pd.DataFrame):
raise TypeError
if col_class not in df_data.columns:
raise ValueError
s_classes = df_data[col_class]
... | fegarcia-bcam/FeatSel-COVID-19-PLOS-ONE | code/ai/bootstrap.py | bootstrap.py | py | 2,495 | python | en | code | 0 | github-code | 90 |
73179961575 | import os
import sys
import bpy
# #### Global variables
MODULE = os.path.dirname(__file__).split(os.sep)[-1]
exec("from " + MODULE + " import rm_error")
exec("from " + MODULE + " import rm_context")
exec("import " + MODULE + " as rm")
# #############################################################################
... | aqsis/RIBMosaic | render_ribmosaic/rm_link.py | rm_link.py | py | 14,425 | python | en | code | 8 | github-code | 90 |
28478658609 | import cv2
class Face_Detector:
def __init__(self, face_cascade_path, eyes_cascade_path):
self.face_detect = cv2.CascadeClassifier(face_cascade_path)
self.eyes_detect = cv2.CascadeClassifier(eyes_cascade_path)
def detect(self, frame, scaleFactor=1.1, minNeighbors=5, minSize=(30,30... | uzairqazi870/Computer_Vision | face detector/face_detector.py | face_detector.py | py | 1,501 | python | en | code | 0 | github-code | 90 |
14014794768 | tc = int(input())
for _ in range(tc):
n = input()
word = map(int, input().split())
mx = 0
count = 0
for i, c in enumerate(word):
if c == 1:
if mx < count:
mx = count
count = 0
elif c == 0:
count += 1
if mx < count:
mx =... | hozblok/codeforces | 1829/B_Blank_Space.py | B_Blank_Space.py | py | 359 | python | en | code | 0 | github-code | 90 |
6268918245 | """
Make sure we get the latest ocp image
"""
from html.parser import HTMLParser
import requests
class GetData(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.answer = ''
def handle_starttag(self, tag, attrs):
for apt in attrs:
if apt[0] == 'href':
... | wusui/aws-startup | get_oc.py | get_oc.py | py | 586 | python | en | code | 0 | github-code | 90 |
9208257187 | import tensorflow as tf
from tensorflow import keras
import numpy as np
import pandas as pd
import scipy.signal
from sklearn.metrics import classification_report
import time
# Customizable Values
WINDOW_SIZE = 360
EPOCHS = 30
VERBOSE = 0
CLASSIFICATION = {'N': 0, 'L': 1, 'R': 2, 'B': 3, 'A': 4, 'a': 5, 'J': 6, 'S': 7,... | TPetty714/LSTM_Real_Time_Arrhythmia_Classifier | tflite_run_collab.py | tflite_run_collab.py | py | 2,998 | python | en | code | 1 | github-code | 90 |
21929573769 | import numpy as np
import matplotlib.pyplot as plt
import scipy.misc
# Perform fourier reconstruction with numpy.
rad = scipy.misc.imread('../autoencoded_inpainting/img/original.png')
inp = scipy.misc.imread('../autoencoded_inpainting/img/inpainted.png')
# Perform FFT.
ffts = [np.fft.fft2(rad), np.fft.fft2(inp)]
for... | mhubii/inpainting | src/fourier_space_analysis.py | fourier_space_analysis.py | py | 1,233 | python | en | code | 0 | github-code | 90 |
7387920739 | import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from confusionmatrix import plot_confusion_matrix
from sklearn.metrics import confusion_matrix
CATEGORIES = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8'... | chenalan02/CameraCalculator | symbol_recognizer_model/math_symbols_model.py | math_symbols_model.py | py | 2,965 | python | en | code | 1 | github-code | 90 |
11002731902 | #두 수의 최대공약수(GCD)를 구하는 방법
#1. a, b가 주어졌을 때, b가 a보다 크면 b의 값을 a로, a의 값을 b로 지정한다.
#2. a를 b로 나눈 나머지를 n으로 지정한다.
#3. n이 0이면 b가 최대공약수이다. (종료)
#4. n이 0이 아니라면, a의 값을 b로, b의 값을 n로 지정하고, 2번으로 돌아간다.
def GCD(a,b):
while b>0:
a, b = b, a%b
return a
x, y = map(int, input().split())
print(GCD(x,y)) | joey0807/CodeStudy | 문제풀기/알고리즘/유클리드호제법.py | 유클리드호제법.py | py | 478 | python | ko | code | 0 | github-code | 90 |
36851434167 | # Lai Zhi Ming
# TP072714
from contextlib import suppress
import xlsxwriter
from datetime import date
d = {}
months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November",
"December"]
today_date = date.today()
def addEmployee():
si... | Kelvinvinvin/simple-payroll-system | payroll system.py | payroll system.py | py | 13,695 | python | en | code | 0 | github-code | 90 |
12341862240 | import torch
from .op import PerfOP
from .attention_base import PerfAttentionBase
class PerfNaiveAttention(PerfAttentionBase):
def __init__(self, b, a, s, h, bias, p, op_index, both_fw_bw):
super(PerfNaiveAttention, self).__init__(b, a, s, h, bias, p, op_index, both_fw_bw)
def prepare_data(self):
... | dingboopt/model_prediction | op/naive_attention.py | naive_attention.py | py | 1,646 | python | en | code | 0 | github-code | 90 |
18402615319 | # 1 つの組を固定したとき、その他の置き方は (N*M-2)C(K-2) 通り
# x 座標が h 離れる組み合わせは、(N-h)*M*M 通り (h!=0)
def combination(n, r, mod=10**9+7):
# nCr mod m
# rがn/2に近いと非常に重くなる
n1, r = n+1, min(r, n-r)
numer = denom = 1
for i in range(1, r+1):
numer = numer * (n1-i) % mod
denom = denom * i % mod
return nume... | Aasthaengg/IBMdataset | Python_codes/p03039/s317781015.py | s317781015.py | py | 795 | python | ja | code | 0 | github-code | 90 |
6230962344 | import time
import hikari
import lightbulb
import platform
import asyncio
import logging
import os
import sys
from functools import wraps
from pathlib import Path
from watchgod import Change, awatch
class Watcher :
def __init__(self,
bot: lightbulb.BotApp,
path: str = "plugi... | Rounak-Das-02/HikariWatcher | hikariWatcher/hikariWatch.py | hikariWatch.py | py | 9,523 | python | en | code | 0 | github-code | 90 |
18335811859 | # 2020/07/18
# AtCoder Beginner Contest 142 - C
# Input
n = int(input())
a = list(map(int,input().split()))
al = [0] * (n+1)
# Calc
for i in range(n):
al[a[i]] = i+1
al.remove(0)
# Output
print(' '.join([str(j) for j in al]))
| Aasthaengg/IBMdataset | Python_codes/p02899/s520945114.py | s520945114.py | py | 234 | python | en | code | 0 | github-code | 90 |
18036323399 | from collections import Counter
N = int(input())
A = [int(c) for c in input().split()]
ans = 1
MOD = 10**9+7
Cnt = Counter(A)
if N%2==1:
for k,v in Cnt.items():
if (k%2==0 and v==2) or (k==0 and v==1):
ans *= v
ans %= MOD
else:
print(0)
break
else:
print(ans)
else:
for k,v in C... | Aasthaengg/IBMdataset | Python_codes/p03846/s631644737.py | s631644737.py | py | 447 | python | en | code | 0 | github-code | 90 |
28292731184 | #insertLine.py
#gcsadovy
#Garik Sadovy
#insertLine.py
# Purpose: Find the centroids of two polygons in COVER63p, then
# crreate a line segment connecting these points
# and add it to parkLines with left_fid set to 50.
# Solution is similar to the insertPolygon.py example
import arcpy
fc... | gcsadovy/generalPY | insertLine.py | insertLine.py | py | 807 | python | en | code | 0 | github-code | 90 |
18339529439 | S = str(input())
Ans = True
for i in range(0, len(S)):
if (i + 1) % 2 == 0:
if S[i] != 'L' and S[i] != 'U' and S[i] != 'D':
Ans = False
break
if (i + 1) % 2 == 1:
if S[i] != 'R' and S[i] != 'U' and S[i] != 'D':
Ans = False
break
if Ans == False:
print('No')
else:
print('Yes'... | Aasthaengg/IBMdataset | Python_codes/p02910/s117977547.py | s117977547.py | py | 321 | python | en | code | 0 | github-code | 90 |
18487691949 | n = int(input())
z = [[0] * 101 for _ in range(101)]
xyh = [tuple(map(int, input().split())) for _ in range(n)]
xyh = sorted(xyh, key=lambda x: x[2], reverse=True)
for xi in range(101):
for yi in range(101):
hi = 0
allok = True
for i in range(n):
x,y,h = xyh[i]
if i ... | Aasthaengg/IBMdataset | Python_codes/p03240/s696338011.py | s696338011.py | py | 535 | python | en | code | 0 | github-code | 90 |
24718253654 | import cv2
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
import datetime
a = datetime.datetime.now()
image = cv2.imread('im.png')
print('Segmenting')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Reshaping the image into a 2D array of pixels and 3 color values (RGB)
pixel_vals ... | vishvesh-g/Parallel-Image-Segmentation | 1 image 1 processor.py | 1 image 1 processor.py | py | 1,348 | python | en | code | 0 | github-code | 90 |
8286499021 | # -*- coding: utf-8 -*-
"""
Created on Mon May 8 09:46:28 2017
@author: darren
"""
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
def weight_variable(shape):
initial = tf.truncated_normal(shape,stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initail... | darren1231/Tensorflow_tutorial | 7_CNN_mnist/cnn_mnist.py | cnn_mnist.py | py | 2,604 | python | en | code | 0 | github-code | 90 |
6005518981 | import math
from functools import partial
import torch
import torch.nn as nn
import torch.nn.functional as F
def _no_grad_trunc_normal_(tensor, mean, std, a, b):
# Cut & paste from PyTorch official master until it's in a few official releases - RW
# Method based on https://people.sc.fsu.edu/~jburkardt/present... | Frankluox/CloserLookAgainFewShot | architectures/backbone/ViT_eTT.py | ViT_eTT.py | py | 18,106 | python | en | code | 24 | github-code | 90 |
24982554223 | import contextlib
import numpy as np
global vec
vec = np.zeros(3)
@contextlib.contextmanager
def mymanager(slide: np.ndarray):
global vec
vec += slide
yield
vec -= slide
with mymanager(np.ones(3)):
print(vec)
print(vec)
| HiroIshida/snippets | python/std_examples/contextmanager.py | contextmanager.py | py | 246 | python | en | code | 6 | github-code | 90 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.