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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
20131502451 | #!/usr/bin/env python3
"""Module containing the AverageStiffness class and the command line interface."""
import shutil
import argparse
from pathlib import Path
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from biobb_dna.utils import constants
from biobb_dna.utils.loader import read_series
f... | bioexcel/biobb_dna | biobb_dna/stiffness/average_stiffness.py | average_stiffness.py | py | 10,178 | python | en | code | 0 | github-code | 90 |
9412524873 |
import torch
from torch import autograd
from torch.autograd import Variable
import torch.nn.functional as F
import torch.nn as nn
import bouncing_balls as b
from conv_lstm import CLSTM, weights_init
import numpy as np
import cv2
import time
num_features=10
filter_size=3
batch_size=4
shape=(32,32) #H,W
inp_chans=3
n... | rAm1n/bouncing-ball-pytorch | train.py | train.py | py | 2,709 | python | en | code | 2 | github-code | 90 |
18581971069 | N = int(input())
T = 0
t = 0
ans = []
for i in range(N-1):
C, S, F = map(int, input().split())
for j in range(len(ans)):
if ans[j] <= S:
ans[j] = S+C
elif ans[j]%F != 0:
ans[j] = ans[j]+F-(ans[j] % F)+C
else:
ans[j] += C
ans.append(S+C)
for a in an... | Aasthaengg/IBMdataset | Python_codes/p03475/s582032066.py | s582032066.py | py | 345 | python | en | code | 0 | github-code | 90 |
23079683349 | """
This is the first part of the Python project, related to webscrapping data from
Boursorama website.
"""
import requests
import pandas as pd
from tqdm import tqdm
from bs4 import BeautifulSoup
def data_collection(nb_pages):
""" This is the webscrapping function that will allow us to retrieve fund
data from... | ELAARADI/Projects | Webscrapping&API project/Webscrapping.py | Webscrapping.py | py | 3,820 | python | en | code | 0 | github-code | 90 |
43492347457 | import urllib.request
import re
stock_url = 'http://quote.eastmoney.com/stocklist.html'
def urlToList(url):
allCodeList = []
html = urllib.request.urlopen(url).read()
html = html.decode('gbk')
s = r'<li><a target="_blank" href="http://quote.eastmoney.com/\S\S(.*?).html">'
pat = re.compile(s)
... | vencewill/myscripts | Python/tutorials/getStockID.py | getStockID.py | py | 595 | python | en | code | 0 | github-code | 90 |
3516741582 | import pandas as pd
import rdflib
import os
import pickle
import time
import constants
def _get_sources_from_mapping(mapping_graph: rdflib.Graph):
"""Retrieves a list of sources from the mappings.
Args:
mapping_graph:
A rdflib.Graph that contains the mapping triples.
Returns:
... | ershimen/incremental-kgc | src/incremental_kgc.py | incremental_kgc.py | py | 20,366 | python | en | code | 1 | github-code | 90 |
37715193250 |
import numpy as np
def gen_gabor(imgsize, sigma = 5.0, theta = np.pi / 4, Lambda = np.pi, psi = 0.0, gamma = 1.0):
sigma_x = sigma
sigma_y = float(sigma) / gamma
# Bounding box
nstds = 5 # Number of standard deviation
xmax = max(abs(nstds * sigma_x * np.cos(theta)), abs(nstds * sigma_y * np.sin... | msrepo/opencv-practice | python-image-operators/gabor.py | gabor.py | py | 1,309 | python | en | code | 1 | github-code | 90 |
36205425284 | import numpy as np
import time
import sys
class regression:
def __init__(self, X, y, theta, learning_rate, iterations):
self.X = X
self.y = y
self.theta = theta
self.learning_rate = learning_rate
self.iterations = iterations
def sigmoid(self, z):
return (1 / (1 + np.exp(-z)))
def cost(self):
m = le... | ayguillo/dslr | src/reg_fit.py | reg_fit.py | py | 1,150 | python | en | code | 1 | github-code | 90 |
22555224658 | import pygame
import os
_image_library = {}
def get_image(path):
global _image_library
image = _image_library.get(path)
if image == None:
canonicalized_path = path.replace('/', os.sep).replace('\\', os.sep)
image = pygame.image.load(canonicalized_path)
... | Beisenbek/PP2_2023 | week10/3.py | 3.py | py | 1,509 | python | en | code | 0 | github-code | 90 |
18012304389 | from math import factorial
n, a, b = map(int, input().split())
V = sorted(map(int, input().split()), reverse=True)
av = sum(V[:a]) / a
print(av)
def comb(m, k):
ans = 1
if k == 0:
return 1
else:
for i in range(k):
ans *= m - i
ans //= i + 1
return ans
num =... | Aasthaengg/IBMdataset | Python_codes/p03776/s787448757.py | s787448757.py | py | 554 | python | en | code | 0 | github-code | 90 |
43442052607 | """
8. Scrieti un program de tip joc "ghiceste numarul".
Cerinte:
1. Programul genereaza un numar aleator in intervalul [1, 99].
2. Intr-o bucla conditionata de gasirea numarului cautat:
- se citeste de la tastatura un numar
- se compara cu numarul cautat
- daca numarul introdus est... | tohhhi/it_school_2022 | Sesiunea 4/temaEx8.py | temaEx8.py | py | 888 | python | ro | code | 0 | github-code | 90 |
44455752204 | import pandas as pd
from pathlib import Path
import shutil
from constants import ap_obj
class Copier:
def __init__(self, df_copy_groups, df_addresses, subfldr):
self.__df_groups = df_copy_groups
self.__df_addresses = df_addresses
self.__subfldr = subfldr
adr = ap_obj.getDa... | YuriGribauskasDenis/PYTHON_BigProjMLDataFilter | core_help/copier.py | copier.py | py | 1,621 | python | en | code | 0 | github-code | 90 |
39546709181 | import aiohttp
import sqlite3
from retry import retry
from typing import Optional
@retry(aiohttp.ContentTypeError, tries=5, delay=1, backoff=2)
async def extract(
url: str, session: aiohttp.ClientSession, params: Optional[dict[str, str]] = None
) -> dict:
"""
Perform an API get requests and return the res... | tanjt107/football-prediction | footballprediction/pipeline.py | pipeline.py | py | 1,349 | python | en | code | 12 | github-code | 90 |
21617340168 | class Solution:
def findMinArrowShots(self, intervals: List[List[int]]) -> int:
if len(intervals) == 1:
return 1
#sort it based one the first value
intervals = sorted(intervals, key=lambda x:x[0])
count = 1
start = intervals[0][0]
end = i... | sgowdaks/CP_Problems | LeetCode/minimum_numbers_of_arrows_to_burst_ballon.py | minimum_numbers_of_arrows_to_burst_ballon.py | py | 1,038 | python | en | code | 0 | github-code | 90 |
6552344872 | import sys
from os import system
import getopt
from player import Player
from game import BlackJack
from question import Question
# Starts a game of Blackjack
def main():
game_options = {
"bet_min": 2,
"bet_max": 10,
"shoe_count": 3
}
try:
matched_args, _ = getopt.getopt(sys.argv[1:], "hn:x:s:"... | tomfuller71/BlackJack | blackjack.py | blackjack.py | py | 1,986 | python | en | code | 0 | github-code | 90 |
15402442101 | """
value % 3 foo
value % 5 bar
value % 3 and value % 5 foobar
value
"""
def foobar(upto):
for num in range(1, upto):
if num % 3 == 0 and num % 5 == 0:
print("FooBar")
elif num % 3 == 0:
print("Foo")
elif num % 5 == 0:
print(... | np-n/Python-Basics-GCA | Session 4/foobar.py | foobar.py | py | 518 | python | en | code | 0 | github-code | 90 |
31774694091 | # READING AND WRITING FILES
''' FILE COMMANDS
• close – Closes the file. Like File->Save.. in your editor.
• read – Reads the contents of the file. You can assign the result to a variable.
• readline – Reads just one line of a text file.
• truncate – Empties the file. Watch out if you care about the fil... | madhur3u/Python3 | Basic File Handling/ex16.py | ex16.py | py | 1,590 | python | en | code | 0 | github-code | 90 |
38502548174 | from tkinter import *
from tkinter import messagebox
from ResumeGenerator import *
def e1_del():
e1.delete(first=0,last=99)
def e2_del():
e2.delete(first=0,last=99)
def e3_del():
e3.delete(first=0,last=99)
def check(val):
if val == '':
messagebox.showinfo("ERROR", "PUT BASE FORMAT TEXT FILE ... | animehart/CoverLetterGenerator | GUI.py | GUI.py | py | 1,435 | python | en | code | 0 | github-code | 90 |
22626967030 | #! /usr/bin/env python3
import argparse
import datetime
import json
import requests
def parseLinkHeader(headers):
"""
adapted from: https://github.com/PyGithub/PyGithub/blob/master/github/PaginatedList.py#L227
"""
links = {}
if "link" in headers:
linkHeaders = headers["link"].split(", ")... | teliov/tech_debt_analysis | commit_analysis.py | commit_analysis.py | py | 3,353 | python | en | code | 0 | github-code | 90 |
70910146537 | # class Solution:
# def numTrees(self, n: int) -> int:
# # dp[n] = dp[0] * dp[n-1] + dp[1] * dp[n-2] + ... + dp[n-1] * dp[0]
# dp = [0] * (n + 1)
# dp[0] = 1
# dp[1] = 1
# for i in range(2, n + 1):
#
# for j in range(i):
#
# dp[i] += dp[j] * dp[i -... | Ericshunjie/algorithm | 动态规划/不同的二叉搜索树.py | 不同的二叉搜索树.py | py | 1,291 | python | en | code | 0 | github-code | 90 |
18029410099 | n=int(input())
ans=1
rec=[True]*(n+1)
for i in range(2,n+1):
if rec[i]:
x=1
for j in range(1,n+1):
y=j
if y%i==0:
rec[y]=False
while y%i==0:
x+=1
y=y//i
ans=(ans*x)%1000000007
print(ans) | Aasthaengg/IBMdataset | Python_codes/p03828/s974345018.py | s974345018.py | py | 298 | python | en | code | 0 | github-code | 90 |
10586395142 | # -*- coding: utf-8 -*-
import os,shutil
def copy(sorcePath,targetPath):
if(os.path.exists(sorcePath)):
shutil.copyfile(sorcePath,targetPath)
print("copy %s => %s"%(sorcePath,targetPath))
source = r"TD\table\unit.ini"
dest = r"物遍生成\unit.ini"
copy(dest,source)
source = r"TD\table\ability.ini"
dest = r"物遍生成\abili... | j8383888/War3MapTD | copy-package.py | copy-package.py | py | 527 | python | en | code | 1 | github-code | 90 |
6557431577 | #
# replay_memory.py
# Here we go once again...
#
import random
import numpy as np
class ArbitraryReplayMemory:
"""
A replay memory for storing any type of elements
"""
def __init__(self, max_size):
self.replay_size = max_size
self.replay_memory = [None for i in range(max_size)]
... | Miffyli/minecraft-bc | utils/replay_memory.py | replay_memory.py | py | 1,209 | python | en | code | 12 | github-code | 90 |
15835744688 | from fastapi import HTTPException
from SharedInterfaces.RegistryModels import *
from SharedInterfaces.AsyncJobModels import *
from SharedInterfaces.RegistryAPI import VersionRequest
from helpers.util import py_to_dict
from helpers.job_api_helpers import *
from config import Config
from helpers.dynamo_helpers import wri... | provena/provena | registry-api/helpers/workflow_helpers.py | workflow_helpers.py | py | 4,514 | python | en | code | 3 | github-code | 90 |
20907925222 | import numpy as np
from scipy.special import comb
from pymoab import rng
from preprocessor.meshHandle.finescaleMesh import FineScaleMesh
from .utils import rotation_to_align
class DFNMeshGenerator(object):
"""
Base class for the mesh generator.
"""
def __init__(self):
pass
def run(self):... | padmec-reservoir/dfn-vugs-generator | src/dfn_mesh_generator.py | dfn_mesh_generator.py | py | 31,330 | python | en | code | 1 | github-code | 90 |
12705574611 | class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
stack = []
for i in s:
if stack and stack[-1][0] == i:
stack[-1][1] += 1
else:
stack.append([i, 1])
if stack[-1][1] == k:
stack.pop()
resul... | FevenBelay23/competitive-programming | 1209-remove-all-adjacent-duplicates-in-string-ii/1209-remove-all-adjacent-duplicates-in-string-ii.py | 1209-remove-all-adjacent-duplicates-in-string-ii.py | py | 411 | python | en | code | 0 | github-code | 90 |
18487253479 | N = int(input())
xyh = []
for i in range(N):
xyh.append(list(map(int,input().split())))
xyh_sorted = sorted(xyh, key=lambda x: x[2], reverse=True)
answer = [0, 0, 0]
for cy in range(0, 101):
for cx in range(0, 101):
H = xyh_sorted[0][2] + abs(xyh_sorted[0][0] - cx) + abs(xyh_sorted[0][1] - cy)
... | Aasthaengg/IBMdataset | Python_codes/p03240/s179454517.py | s179454517.py | py | 729 | python | en | code | 0 | github-code | 90 |
28411658694 | import tensorflow as tf
from tensorflow.contrib import layers
def flatten_layer(layer):
layer_shape = layer.get_shape()
num_features = layer_shape[1:4].num_elements()
layer_flat = tf.reshape(layer, [-1, num_features])
return layer_flat, num_features
def graph_attention_layer(A, M, v, laye... | xdweixia/SGCMC | 2021-TMM-SGCMC/Network/Graph_Attention_Encoder.py | Graph_Attention_Encoder.py | py | 6,941 | python | en | code | 31 | github-code | 90 |
4549378940 | '''
Напишите программу-калькулятор, которая поддерживает следующие операции: сложение, вычитание, умножение, деление и
возведение в степень. Программа должна выдавать сообщения об ошибке и продолжать работу при вводе некорректных данных,
делении на ноль и возведении нуля в отрицательную степень.
'''
def calc():
c... | kds3000/Python_Essential_Homeworks | calculator_with_exceptions.py | calculator_with_exceptions.py | py | 3,481 | python | ru | code | 0 | github-code | 90 |
5143513774 | import random
f = open("small_input.txt", "r")
interval = f.readline().split(" ")
start = int(interval[0])
end = int(interval[1])
def gcd(a,b):
if (a < b):
return gcd(b, a)
if (a % b == 0):
return b
return gcd(b, a % b)
def is_prime(n):
if n <= 2:
return n == 2
if n % 2 =... | nikitasadok/myparcs | serial.py | serial.py | py | 924 | python | en | code | 0 | github-code | 90 |
12885021818 | import requests
def test():
url = "http://localhost:5000/predict"
body = {
'address': '504 W 35 St',
'dogs_allowed': 1,
'cats_allowed': 1,
'trash_valet': 0,
'ev_charging': 0,
'washer_dryer': 1,
'stainless_steel_appliances': 1,
'bedrooms': 3,
... | chrischen88/apartment-worth-app | backend/test.py | test.py | py | 481 | python | en | code | 0 | github-code | 90 |
33890839078 | #! /usr/bin/env morseexec
""" Basic MORSE simulation scene for <test> environment
Feel free to edit this template as you like!
"""
from morse.builder import *
from morse.sensors import *
from fourwd.builder.robots import Hummerscaled
import math
robot = Hummerscaled()
robot.add_default_interface('ros')
scale = 0.2
... | eugeniu1994/Small-scale-self-driving-car | software_integration-master/morse/fourwd/default.py | default.py | py | 3,798 | python | en | code | 0 | github-code | 90 |
38744734103 | from __future__ import annotations
from collections import defaultdict
from typing import List, Tuple
import tree_path as tp
from tree_path import Search, Match, Tree, ParsedSentence, ParsedDoc
from valences import check_valences
class FullLemma:
def __init__(self, lemma : str, others : List[Search|str], others... | serban-hartular/UD_Search | valences/verb_lemma.py | verb_lemma.py | py | 4,661 | python | en | code | 0 | github-code | 90 |
18509983979 | s = input()
if s[0] == 'A':
t = ''
c_cnt = 0
for i in range(1, len(s)):
if s[i] != 'C':
t += s[i]
else:
c_cnt += 1
if t.islower() and 'C' in s[2:-1] and c_cnt == 1:
print('AC')
else:
print('WA')
else:
print('WA')
| Aasthaengg/IBMdataset | Python_codes/p03289/s376928585.py | s376928585.py | py | 253 | python | en | code | 0 | github-code | 90 |
30786998634 | """
FILE IO
"""
from translate import Translator
translator = Translator(to_lang='fr')
try:
with open('translate.txt', mode='r') as my_file:
# mode='r+' to read and write
# mode='w' to write and create a new folder if it doens't exist with specific name
# mode='a' to read and append
... | AntonioIonica/Automation_testing | exercices_todo/text_test.py | text_test.py | py | 898 | python | en | code | 0 | github-code | 90 |
6859034302 | #https://www.acmicpc.net/problem/1931
times=[]
for i in range(0,int(input(""))):
times.append([int(i) for i in input('').split()])
s=len(times)
for i in range(0,s):
for j in range(i+1,s):
if times[i][1]>times[j][1]:
t=times[i]
times[i]=times[j]
times[j]=t
b... | dltbwoddl/Algorithmuslearning | 그리디 알고리즘/회의실배정.py | 회의실배정.py | py | 431 | python | en | code | 0 | github-code | 90 |
13090400547 | import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
# Generar datos de ejemplo
X = np.random.randn(100, 1) # 100 ejemplos con 1 variable independiente
y = 2 * X[:, 0] + ... | JJSirius/MLLab | Lab02/regresion.py | regresion.py | py | 1,332 | python | es | code | 1 | github-code | 90 |
36886514536 | import requests
import pandas
import scipy
import numpy
import sys
import pandas as pd
TRAIN_DATA_URL = "https://storage.googleapis.com/kubric-hiring/linreg_train.csv"
TEST_DATA_URL = "https://storage.googleapis.com/kubric-hiring/linreg_test.csv"
def transform(dat):
dat = dat.T.reset_index()
dat.c... | Piperidine/Anvay_Varerkar_Kubric | regression.py | regression.py | py | 1,816 | python | en | code | 0 | github-code | 90 |
74744099817 | import gc
from collections import defaultdict
from functools import partial
from time import time
from typing import Dict, NamedTuple, Generator, Optional, Iterator, Tuple, Union
import bpy
from sverchok.data_structure import post_load_call
from sverchok.core.events import TreeEvent, GroupEvent
from sverchok.utils.log... | thatboyjake/.config | blender/3.0/scripts/addons/sverchok-master/core/main_tree_handler.py | main_tree_handler.py | py | 19,812 | python | en | code | 0 | github-code | 90 |
70202253097 | import numpy as np
from config import GlobalConfig
from UTIL.colorful import *
from UTIL.tensor_ops import my_view, __hash__, repeat_at, gather_righthand
from MISSION.uhmap.actset_lookup import encode_action_as_digits
from .foundation import AlgorithmConfig
from .cython_func import roll_hisory
from .hete_assignment imp... | binary-husky/unreal-map | PythonExample/hmp_minimal_modules/ALGORITHM/hete_league_onenet_fix/shell_env.py | shell_env.py | py | 10,724 | python | en | code | 145 | github-code | 90 |
18459888109 | import sys
sys.setrecursionlimit(10 ** 6)
def dfs(x, y, matrix, visited, isWhite):
global black, white
dxy = [[1, 0], [-1, 0], [0, -1], [0, 1]]
visited[y][x] = True
w = len(matrix[0])
h = len(matrix)
for dx, dy in dxy:
nx = x + dx
ny = y + dy
if nx < 0 or w <= nx or ... | Aasthaengg/IBMdataset | Python_codes/p03157/s241642158.py | s241642158.py | py | 1,164 | python | en | code | 0 | github-code | 90 |
35349566743 | from unittest import TestCase, main
from project.hardware.hardware import Hardware
from project.software.express_software import ExpressSoftware
class TestHardware(TestCase):
def setUp(self) -> None:
self.test_hardware = Hardware("test", "Power", 100, 200)
def test_initialization(self):
sel... | yetoshimo/python-oop | JC_20200816_Exam/tests/test_hardware.py | test_hardware.py | py | 2,028 | python | en | code | 0 | github-code | 90 |
35645770866 | class Solution(object):
def subsetsWithDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
res = []
self.dfs(0,nums,[],res)
return res
def dfs(self,level,nums,tmp,res):
res.append(tm... | cloi1994/session1 | Facebook/90.py | 90.py | py | 571 | python | en | code | 0 | github-code | 90 |
29542752585 | from django.urls import path
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
path('',views.IndexView.as_view(),name="shop"),
path('products/', views.ProductListView.as_view(),name="productList"),
path('caregories/<int:idc>/products/', views.ProductsByCategoryV... | leriaetnasta/E-commerce-web-app | backend/shop/urls.py | urls.py | py | 1,063 | python | en | code | 0 | github-code | 90 |
5830171249 | OPERAND_SIGIL = '*'
PSEUDO_OPERAND_FLAG = ':'
UNARY_OP_SIGIL = '='
BINARY_OP_SIGIL = '\\'
SIMULTANEOUS_OP_FLAG = '+'
MODIFIER_SIGIL = ','
ANNOTATION_SIGIL = ';'
ALPHA_CHARS = "A-... | linclelinkpart5/cheffu-old | cheffu/constants.py | constants.py | py | 958 | python | en | code | 1 | github-code | 90 |
74809259177 |
def inMap(str):
l = ['i', 'like', 'sam', 'sung', 'samsung' , 'mobile' , 'ice' ,
'cream' , 'icecream' , 'man' , 'go' , 'mango' ]
for i in l:
if i==str:
return True
return False
def printList(ans):
for i in ans:
print(i,end=" ")
def isSegmented(input,startIndex,an... | anmolaithinker/Algorithms-Practise | Recursion/word-break.py | word-break.py | py | 821 | python | en | code | 1 | github-code | 90 |
3246767962 | def split_excel_equally(filepath, split_number):
try:
import pandas as pd
from time import strftime
file_location = '\\'.join(filepath.split('\\')[:-1])
log_list = [strftime("%d/%m/%Y %H:%M:%S") + '- Inside split_excel_equally']
df = pd.read_excel(filepath)
log_lis... | sumitmx/Uipath_Python | Uipath_python.py | Uipath_python.py | py | 7,547 | python | en | code | 0 | github-code | 90 |
28593346607 | from __future__ import print_function
import tensorflow as tf
a = tf.get_variable("a", dtype=tf.float32, initializer=tf.constant(0.0))
b = tf.get_variable("b", dtype=tf.float32, initializer=tf.constant(0.0))
x = tf.placeholder(tf.float32)
linear_model = a*x + b
y = tf.placeholder(tf.float32)
loss = tf.reduce_sum(tf.... | jasonzhang2022/tfprac | get_started1.py | get_started1.py | py | 787 | python | en | code | 0 | github-code | 90 |
20767864911 | import torch
import torch.nn.init as init
import math
class Conv2dZ2P4(torch.nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, g_type="p4",
dilation=1, groups=1, bias=False, device="cuda", dtype=None, *args, **kwargs):
super().__init__()
assert g_type == "p4"... | maple5717/PyTorch-Implementation-of-Group-Equivariant-CNN | gcnn/layers.py | layers.py | py | 5,075 | python | en | code | 0 | github-code | 90 |
37326953535 | ROCK = 'X'
OPPONENT_ROCK = 'A'
PAPER = 'Y'
OPPONENT_PAPER = 'B'
SCISSORS = 'Z'
OPPONENT_SCISSORS = 'C'
play_mappings_and_scores = {
ROCK: {
'match': OPPONENT_ROCK,
'defeats': OPPONENT_SCISSORS,
'score': 1
},
PAPER: {
'match': OPPONENT_PAPER,
'defeats': OPPONENT_ROC... | andrewdieken/advent-of-code | 2022/day_2/pt_1.py | pt_1.py | py | 1,181 | python | en | code | 0 | github-code | 90 |
44036529161 | #!/usr/bin/env python
import numpy as np
from util import softmax, sample_probs
class Tree:
''' Data structure used during simulated games '''
def __init__(self, prior, c_puct):
self.c_puct = c_puct
self.T = 0 # Total visits
self.N = np.zeros(len(prior), dtype=int) # Visit count
... | machinaut/azero | azero.py | azero.py | py | 5,785 | python | en | code | 2 | github-code | 90 |
73332713258 | # goorm / 기타 / 채점하기
# https://level.goorm.io/exam/43280/%EC%B1%84%EC%A0%90%ED%95%98%EA%B8%B0/quiz/1
target = list(input())
score = 0
answer = 0
for a in target:
if a == 'o':
score += 1
answer += score
else:
score = 0
print(answer) | devwithpug/Algorithm_Study | python/goorm/기타/goorm_43280.py | goorm_43280.py | py | 277 | python | en | code | 0 | github-code | 90 |
24543433240 | for slovo in 'Viktorija':
print(slovo)
# set
for item in {1,2,3,4,5}:
for x in ['a','b','c']:
print(item, x)
# iterator - objekat/kolekcija kroz koji mozemo da iterisemo
# da idemo 1 po 1, da proverimo svaki item u kolekciji
# iterables - list, dict, tuple, set, string
# Objekat - dictionary
user =... | ViktorijaSiktorija/Python-Concepts | forLoops.py | forLoops.py | py | 2,567 | python | sr | code | 0 | github-code | 90 |
43954274261 | import argparse
from src.constants import CHOICES, CHOICES_PLURAL, JOB_POSTINGS
from src.constants import DESCRIPTION, EPILOG, ADD_HELP, SHOW_HELP, UPDATE_HELP, DELETE_HELP
from src.cli_helper import print_to_screen, show, class_factory, get_all_objects_in_db, selection_screen, update_class
from src.cli_helper import ... | crazcalm/job-search | jobs.py | jobs.py | py | 2,108 | python | en | code | 3 | github-code | 90 |
18484555409 | def main():
n=int(input())
for k in range(1,450):
if k*(k+1)==2*n:
print("Yes")
print(k+1)
break
else:
print("No")
return 0
ans=[]
cnt=1
for i in range(k+1):
ans.append([])
for j in range(i):
ans[i].append(an... | Aasthaengg/IBMdataset | Python_codes/p03230/s832994486.py | s832994486.py | py | 459 | python | en | code | 0 | github-code | 90 |
17981280619 | from collections import deque
n = int(input())
A = deque(map(str, input().split()))
D = deque()
while A:
x = A.popleft()
D.append(x)
if A:
y = A.popleft()
D.appendleft(y)
if n % 2 != 0:
D.reverse()
print(" ".join(D)) | Aasthaengg/IBMdataset | Python_codes/p03673/s385090778.py | s385090778.py | py | 232 | python | en | code | 0 | github-code | 90 |
15541407495 | from pathlib import Path
import win32com.client
def excelVBARun():
xlapp = win32com.client.Dispatch("Excel.Application")
# 開く
abspath = str(Path(r"C:\Users\dede2\OneDrive\デスクトップ\開発\Excelツール\個人的なテスト.xlsm").resolve())
workbook = xlapp.Workbooks.Open(abspath, UpdateLinks=0, ReadOnly=True)
# シート一覧
... | dede-20191130/CreateToolAndTest | Test_Miscellaneous_Python/Test_ExcelLink/ExcelLink.py | ExcelLink.py | py | 1,295 | python | ja | code | 0 | github-code | 90 |
27480307993 | __author__ = 'Cue'
countries = ['China', 'India', 'United States', 'Indonesia', 'Pakistan']
populations = [1439323776, 1380004385, 331002651, 273523615, 220892340]
no_of_countries = len(countries)
# for i in range(0, no_of_countries):
# print('Population of',countries[i],'is',populations[i])
print('COUNTRIES')
pri... | kevin-aus/cp1404_TR1_2022 | lec04/activity2_first_way.py | activity2_first_way.py | py | 706 | python | en | code | 0 | github-code | 90 |
36527224605 | """
This setup.py handles compiling .po (portable object) files into their
appropriate .mo (machine object) results.
Reference: https://setuptools.pypa.io/en/latest/userguide/extension.html#setuptools.command.build.SubCommand
"""
# pyright: strict
import shutil
import subprocess
from pathlib import Path
from typing im... | thegamecracks/discord.py-i18n-demo | setup.py | setup.py | py | 4,866 | python | en | code | 1 | github-code | 90 |
25606101755 | import logging
from flask import request
from airflow.api_connexion import security
from airflow.security import permissions
from airflow.www.app import csrf
from airflow_xtended_api.api.app import blueprint
import airflow_xtended_api.core.s3_sync as s3
import airflow_xtended_api.utils as utils
import airfl... | anr007/airflow-xtended-api | airflow_xtended_api/api/endpoints/sync_dags_from_s3.py | sync_dags_from_s3.py | py | 3,793 | python | en | code | 11 | github-code | 90 |
73426286697 | #!/usr/bin/env python3
import re
import json
import re
import os
_HERE = os.path.dirname(os.path.abspath(__file__))
import pandas as pd
def makeWordLists(file):
# helper function for assembling regexes from dictionary files
# takes in a file that has one word/phrase per line
# produces (word1|word2|word w... | iangow/ling_features | non_answer/non_answers.py | non_answers.py | py | 2,919 | python | en | code | 10 | github-code | 90 |
36674028744 | from django.urls import path
from services.views import (CategoryList, CategoryCreate, CategoryDetail, ServiceCreate,
SalonServices, ServiceUpdate, CategoryUpdate, CategoryDelete,
ServiceDelete)
from staffer.views import StafferAddService
app_name = "services"
... | Abdubek/salon | src/services/urls.py | urls.py | py | 1,055 | python | en | code | 0 | github-code | 90 |
8583857075 | ## @package app.stats_app
from app.app import App
from ui.stats_app.view_configs_window import ViewConfigsWindow
## Handles startup for the statistics app.
class StatsApp(App):
## Constructor
# @param self
def __init__(self):
super(StatsApp, self).__init__(
'stats_app',
App... | babylanguagelab/bll_app | wayne/app/stats_app.py | stats_app.py | py | 516 | python | en | code | 0 | github-code | 90 |
70117278698 | import os
import click
import datasheets
import numpy as np
import pandas as pd
from pulp import LpVariable, LpProblem, LpMaximize, lpSum, PULP_CBC_CMD
import yaml
class Optimizer:
def __init__(self, input_data, num_screens, budget):
self.input_data = input_data
self.num_screens = num_screens
... | EthanRosenthal/fml | fml/optimizer.py | optimizer.py | py | 5,342 | python | en | code | 2 | github-code | 90 |
9503807486 | import pipes
import re
import os
import sys
import shutil
import argparse
import subprocess
from pathlib import Path
from datetime import datetime
FOURTEEN_DAYS = 14
def how_old(date: datetime) -> int:
"""Return a integer that represents how many days has passed given a date"""
return (datetime.now() - date... | quick-lint/quick-lint-js | infrastructure/quick-lint-js-web-2/roles/builds/files/prune-old-builds.py | prune-old-builds.py | py | 3,814 | python | en | code | 956 | github-code | 90 |
14775720595 | """Script to run different optimization methods on rosenbrock funciton."""
from function import *
from algorithm import steepest_descent
import numpy as np
def main():
frosenbrock = RosenbrockFunction()
f, grad = frosenbrock.value, frosenbrock.grad_value
optimizer = steepest_descent.SteepestDescent(f,
... | zhuyifengzju/optimization | rosenbrock_minima.py | rosenbrock_minima.py | py | 701 | python | en | code | 2 | github-code | 90 |
71441041256 | import json
from django.contrib.auth.decorators import login_required
from django.contrib.auth import get_user_model
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse
from .models import Favorite
from rec... | dronsovest/foodgram-project | favorites/views.py | views.py | py | 1,632 | python | en | code | 0 | github-code | 90 |
21211540065 | import sys
sys.path.append('/home/data/hq/DA')
#from yacs.config import CfgNode as CN
import time
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.optim.lr_scheduler import StepLR, LambdaLR
from torch.utils import data
from build_dataset import build_dataset_preDA,build_d... | huqian999/UDA-MIMA | train/ADA.py | ADA.py | py | 12,835 | python | en | code | 1 | github-code | 90 |
19134106863 | class Date(object):
def __init__(self,z0=1900,x0=1,y0=1):
self.x = x0
self.z = z0
self.y = y0
def __str__(self):
return "{}/ {}/ {}".format(self.z,str(self.x).rjust(2,'0'),str(self.y).rjust(2,'0'))
def same_day_in_year(self,other):
if self.y == other.y and self.x == o... | Anooj-Pai/Python-Projects | Labs/Lab9/check2.py | check2.py | py | 1,895 | python | en | code | 0 | github-code | 90 |
28170422187 | import re
from pyndn.util.regex.ndn_regex_matcher_base import NdnRegexMatcherBase
class NdnRegexComponentMatcher(NdnRegexMatcherBase):
"""
Create a RegexComponent matcher from expr.
:param str expr: The standard regular expression to match a component.
:param NdnRegexBackrefManager backrefManager: The... | named-data/PyNDN2 | python/pyndn/util/regex/ndn_regex_component_matcher.py | ndn_regex_component_matcher.py | py | 2,280 | python | en | code | 23 | github-code | 90 |
36048229679 | import turtle
import pandas
screen = turtle.Screen()
screen.title("U.S. States Game")
image = "blank_states_img.gif"
screen.addshape(image)
turtle.shape(image)
data = pandas.read_csv("50_states.csv")
states_list = data["state"].to_list()
correct_guesses = []
while len(correct_guesses) < 50:
answer_state = screen... | rachanahegde/python-pro-bootcamp-intermediate-projects | day-25-us-states-game/main.py | main.py | py | 1,388 | python | en | code | 1 | github-code | 90 |
865942954 | # 8C3 , 7C5 프로그램 만들기
# nPr/r!
from tkinter import N
numn = int(input('numn 입력: '))
numr = int(input('numr 입력: '))
resultp = 1
resultr = 1
resultc = 1
for n in range(numn, (numn-numr), -1):
print('n : {}'.format(n))
resultp = resultp * n
print('resultp: {}'.format(resultp))
for n in range(numr, 0, -1):
... | jungwonguk/Education | 강의/27~28강 조합/조합1.py | 조합1.py | py | 503 | python | en | code | 1 | github-code | 90 |
17991351979 | n,a,b = map(int,input().split())
s = 0
H = []
for _ in range(n):
h = int(input())
H.append(h)
from copy import deepcopy
from math import ceil
def count(x):
Hc = deepcopy(H)
cnt = 0
for i in range(n):
Hc[i] -= b*x
if Hc[i]>0:
cnt += ceil(Hc[i]/(a-b))
return cnt <= x
... | Aasthaengg/IBMdataset | Python_codes/p03700/s799165017.py | s799165017.py | py | 446 | python | en | code | 0 | github-code | 90 |
18356882629 | n = int(input())
s_cnt = {}
for _ in range(n):
s = input()
s = ''.join(sorted(s))
s_cnt.setdefault(s,0)
s_cnt[s] += 1
ans = 0
for s,cnt in s_cnt.items():
ans += cnt*(cnt-1)//2
print(ans) | Aasthaengg/IBMdataset | Python_codes/p02947/s672918472.py | s672918472.py | py | 209 | python | en | code | 0 | github-code | 90 |
22572465015 | """ A weather object. Pure flavor. """
class EwWeather:
# The identifier for this weather pattern.
name = ""
str_sunrise = ""
str_day = ""
str_sunset = ""
str_night = ""
def __init__(
self,
name = "",
sunrise = "",
day = "",
sun... | mudkipslaps/endless-war | ew/model/weather.py | weather.py | py | 511 | python | en | code | null | github-code | 90 |
17986453485 | # -*- coding: utf-8 -*-
from collections import defaultdict
from intervaltree import Interval, IntervalTree
from utils import tsv, overlap_length
from gtfclasses import GTFLine, GTFCluster
__author__ = 'Matthew L. Bendall'
__copyright__ = "Copyright (C) 2017 Matthew L. Bendall"
def subtract_gtflines(gA, gB):
... | mlbendall/telebuilder | telebuilder/utils/gtfutils.py | gtfutils.py | py | 6,519 | python | en | code | 2 | github-code | 90 |
29596181293 | import pandas as pd
import numpy as np
import numpy.random as r
import scipy.io as sio
import scipy.stats
import matplotlib.pyplot as plt
import random
from collections import Counter
pi = np.pi
def LDA(mu0, mu1, cov,X):
return ((mu1-mu0).T).dot(np.linalg.inv(cov)).dot(X) - 1/2*((mu1.T).dot(np.linalg.inv(cov)).dot... | Loielaine/Machine_learning | hw4/p6_LDA_QDA.py | p6_LDA_QDA.py | py | 2,264 | python | en | code | 1 | github-code | 90 |
18608212016 | import os
import cv2
import numpy as np
class betterFrameCacher:
def __init__(self, threshold):
self.bestFrame = None
self.prev = -1
self.isBoring = True
self.threshold = threshold
def getScore(self, newFrame):
grayFrame = cv2.cvtColor(newFrame, cv2.COLOR_BGR2GRAY)
... | acenturyandabit/lec2note | lec2note_main/video_pipeline.py | video_pipeline.py | py | 5,179 | python | en | code | 0 | github-code | 90 |
13491899267 | """
数据包的创建和导入
"""
import tensorflow as tf
import cv2
import numpy as np
import os
import random
import sys
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from tflearn.layers.conv import global_avg_pool
from tensorflow.contrib.layers import batch_norm,flatten
from tensorflow.contrib... | LLAYGDD/FaceRecognition_project | FaceRecognition_project/Model_Code/Densenet_train.py | Densenet_train.py | py | 11,600 | python | en | code | 1 | github-code | 90 |
12684452726 | import pandas as pd
import numpy as np
from .utilities import can_be_float
import csv
def csvToMatrix(csv_name):
"""Takes the name of the csv file and returns the 2D matrix version of the file.
Args:
csv_name (str) : the name of the csv file
Returns:
result_mat (2d array) : Matrix... | Shubhanshi-Gaudani/338-dirtydata | src/csv_to_matrix.py | csv_to_matrix.py | py | 1,062 | python | en | code | 0 | github-code | 90 |
69984263978 | __all__ = ["PowerState", "Pulse", "Mini", "DiyPlug"]
from pyiot.watchers.sonoff import EwelinkWatcher
from pyiot.connections.http import HttpConnection
from pyiot.traits import OnOff
from pyiot.watchers import Watcher
from pyiot.discover.sonoff import DiscoverSonoff
from pyiot import BaseDevice, Attribute
from enum im... | angrysoft/pyiot | pyiot/sonoff/diy.py | diy.py | py | 4,768 | python | en | code | 0 | github-code | 90 |
23977269095 | import random
import unittest
import numpy
import torch
import torch.nn.functional as F
import nni
from nni.compression.pytorch.pruning import (
LinearPruner,
AGPPruner,
LotteryTicketPruner,
SimulatedAnnealingPruner,
AutoCompressPruner,
AMCPruner
)
from nni.algorithms.compression.v2.pytorch.ut... | linbinskn/nni_movement | test/ut/compression/v2/test_iterative_pruner_torch.py | test_iterative_pruner_torch.py | py | 5,828 | python | en | code | 0 | github-code | 90 |
18818290181 | import os
import glob
import matplotlib.pyplot as plt
import torch
import torchvision
from tqdm import tqdm
from PIL import Image
from utils import make_gif, make_gif_from_tensor, save_images
from modules import UNet_conditional
from ddpm_conditional import Diffusion
# import japanize_matplotlib
if __name__ == '__main... | tf63/diffusion-trans | regenerate_mask.py | regenerate_mask.py | py | 7,178 | python | en | code | 0 | github-code | 90 |
35166286439 |
import numpy as np
import matplotlib.pyplot as plt
if __name__ == "__main__":
b = np.load('./state_trajectory_mpc.npy')
data_des = np.load('./state_trajectory_mpc_desired.npy')
b = b.squeeze()
b = b.T
data_des = data_des.squeeze()
data_des = data_des.T
line_c = ['b', 'g', 'r', 'c', 'k', 'm', 'y']
x_ = np.a... | lasithagt/admm | data/plot_state_trajectory_ddp_mpc.py | plot_state_trajectory_ddp_mpc.py | py | 815 | python | en | code | 9 | github-code | 90 |
12122027447 | import os
from unittest.mock import patch, Mock, MagicMock
from datetime import datetime, timedelta
from teuthology import worker
from teuthology.contextutil import MaxWhileTries
class TestWorker(object):
def setup_method(self):
self.ctx = Mock()
self.ctx.verbose = True
self.ctx.archive... | ceph/teuthology | teuthology/test/test_worker.py | test_worker.py | py | 11,616 | python | en | code | 153 | github-code | 90 |
1529350824 | import random
import numpy as np
import pandas as pd
import sys
import SimpleNetwork
parameter = sys.argv[1]
if len(sys.argv) == 2:
network_extract = 100
else:
network_extract = int(sys.argv[2])
random.seed(12)
for time in range(100):
if (time + 1) % 10 == 0:
print('Iteration ' + str(time + 1))
... | zwhbio2017/Network_duplication | Run_SimpleNetwork.py | Run_SimpleNetwork.py | py | 3,864 | python | en | code | 0 | github-code | 90 |
18372218319 | #!/usr/bin/env python3
import sys
import math
import decimal
import itertools
from itertools import product
from functools import reduce
def input():
return sys.stdin.readline()[:-1]
def sort_zip(a:list, b:list):
z = zip(a, b)
z = sorted(z)
a, b = zip(*z)
a = list(a)
b = list(b)
return a, b
... | Aasthaengg/IBMdataset | Python_codes/p02983/s617814160.py | s617814160.py | py | 673 | python | en | code | 0 | github-code | 90 |
18430529297 | #!/usr/bin/env python
"""
Solution to Project Euler Problem 44
http://projecteuler.net/
by Apalala <apalala@gmail.com>
(cc) Attribution-ShareAlike
http://creativecommons.org/licenses/by-sa/3.0/
Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first
ten pentagonal numbers are:
1, 5, 12, 22, 35, 51, ... | Web-Dev-Collaborative/PYTHON_PRAC | projecteuler/euler044_pentagon_numbers.py | euler044_pentagon_numbers.py | py | 1,150 | python | en | code | 6 | github-code | 90 |
18408073329 | import math
def main():
N, K = map(int, input().split())
count = 0
flag = True
while flag:
if N - K < 0:
flag = False
else:
N -= 1
count += 1
print(count)
main()
| Aasthaengg/IBMdataset | Python_codes/p03047/s067827402.py | s067827402.py | py | 234 | python | en | code | 0 | github-code | 90 |
41783048829 | import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--inputFile", type=str, help="the log file to parse")
parser.add_argument("-o", "--outputFile", type=str, help="the output log file")
args = parser.parse_args()
if(args.inputFile == None):
inputFile =... | ArifSohaib/player_tracking | parse_log.py | parse_log.py | py | 1,128 | python | en | code | 0 | github-code | 90 |
11438745928 | """
Render a set of NetCDF files to images.
Stretched renderers may have one of the following colormap values:
1.0 (absolute)
max (calculate max across datasets)
0.5*max (calculate max across datasets, and multiply by value)
TODO:
* connect palettes to create matching class breaks
* combine palette and scal... | consbio/trefoil | trefoil/cli/render_netcdf.py | render_netcdf.py | py | 18,125 | python | en | code | 13 | github-code | 90 |
19378751676 | # Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
#
# A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
#
#
#
# Example:
#
# Input: "23"
# Output: ["ad", "ae", "af", "b... | joneyyx/LeetCodes | Others/17LetterCombinationsOfPhoneNumber.py | 17LetterCombinationsOfPhoneNumber.py | py | 1,847 | python | en | code | 0 | github-code | 90 |
35753663921 | #!/usr/bin/env python
from string import ascii_lowercase
alpha,copy={},{}
for _ in range(int(input())):
flag=True
for i in ascii_lowercase:
alpha[i]=0
copy[i]=0
word, cpy = map(str,input().split())
if len(word)!=len(cpy):
flag = False
break
else:
for i in r... | hansojin/python | string/bj11328.py | bj11328.py | py | 601 | python | en | code | 0 | github-code | 90 |
7058390358 | from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from typing import Optional
from pydantic import BaseModel
import db_manager
app = FastAPI()
origins = [
"http://127.0.0.1:8080",
"http://localhost:8080",
"http://192.168.1.41:8080",
"https://buzo.... | gsidhu/buzo.dog | api/main.py | main.py | py | 1,575 | python | en | code | 0 | github-code | 90 |
5074343196 | gender = "man"
h = 173 * 0.01
w = 65
bmi = round(w / (h*h), 2)
print(bmi)
if bmi > 30 :
print("fat")
elif 25<= bmi <30:
print("little fat")
elif 20<= bmi < 25:
print("good")
else:
print("skinny") | hsbummy/multicampus_lecture | 1. Python-django/day02/ws100.py | ws100.py | py | 214 | python | en | code | 0 | github-code | 90 |
38152767481 | import cv2
import numpy as np
import matplotlib.pyplot as plt
image = cv2.imread('images/frame1296.jpg')
hls = cv2.cvtColor(image, cv2.COLOR_BGR2HLS)
lower = np.array([0, 150, 0], dtype = "uint8")
upper = np.array([255, 255, 255], dtype = "uint8")
mask = cv2.inRange(hls, lower, upper)
res = cv2.bitwise_and(image, imag... | ridouaneg/DeepFootballAnalysis | hsl_test.py | hsl_test.py | py | 1,862 | python | en | code | 10 | github-code | 90 |
40172572810 | import datetime
import ccxt
import pytz
from unittest import mock
from django.test import TestCase
from django.core.management import call_command
from .utils import parse_datetime
from . import factories as factory
from .factories import ExchangeFactory, MarketFactory, MarketOHLCVFactory, AccountFactory
from .models... | henrypalacios/crypstation | src/exchanges/tests.py | tests.py | py | 5,463 | python | en | code | 0 | github-code | 90 |
37118828163 | def merge_sort(seq):
if len(seq) <= 1:
return seq
mid = int(len(seq)/2)
left = merge_sort(seq[:mid])
right = merge_sort(seq[mid:])
return merge_sorted_list(left, right)
def merge_sorted_list(sorted_a, sorted_b):
len_a, len_b = len(sorted_a), len(sorted_b)
a = b = 0
new_sorte... | nanw01/python-algrothm | Python Algrothm Advanced/practice/040207mergesorted copy 4.py | 040207mergesorted copy 4.py | py | 767 | python | en | code | 1 | github-code | 90 |
73805668776 | total = 0
mais = 1000
contp = 0
pbarato = 9999999999999999999999999
nomepb = 'a'
while True:
pdt = str(input('Informe o nome do produto: '))
preço = float(input('Informe o preço do produto: '))
total += preço
if preço > 1000:
contp += 1
if preço < pbarato:
pbarato = preço
nom... | lucasptcastro/projetos-curso-em-video-python | ex070.py | ex070.py | py | 739 | python | pt | code | 1 | github-code | 90 |
44872392858 | import sys
import collections
import copy
def bfs(virus_activated):
chart = copy.deepcopy(table)
queue = collections.deque()
dx = [0, 0, 1, -1]; dy = [1, -1, 0, 0]
check = [[0 for _ in range(size)] for _ in range(size)]
while virus_activated:
temp = virus_activated.pop()
check[temp[... | Quinsie/BOJ | Python/BOJ_17142_연구소 3.py | BOJ_17142_연구소 3.py | py | 2,121 | python | en | code | 0 | github-code | 90 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.