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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
74975645307 | from model.plot_utils import *
from model.allocations import solve
def allocation_chart(x, solutions, ax=None, xlabel="", legend=True):
if not ax:
fig, ax = plt.subplots(1, 1, figsize=(5, 3))
x = np.array(list(x))
strategies = ["Eucalyptus 25", "Mahogany 100", "Mahogany 200", "Reserve"]
... | leo-ware/forest-model | model/make_plots.py | make_plots.py | py | 1,944 | python | en | code | 0 | github-code | 6 |
38047305072 | from flask import Flask, jsonify, render_template
import psutil
import subprocess
app = Flask(__name__)
def get_gpu_usage():
result = subprocess.check_output("nvidia-smi --query-gpu=utilization.gpu --format=csv,noheader,nounits", shell=True)
gpu_usage = float(result.strip())
return gpu_usage
@app.route('... | agbld/webserver_for_system_infos | app.py | app.py | py | 784 | python | en | code | 0 | github-code | 6 |
31788083835 | f = open("marks.txt", "rt")
for line in f.readlines():
parts = line.strip().split(",")
if len(parts) < 2:
continue
#print(parts)
name = parts[0]
marks = [int(v) for v in parts[1:] if v.isdigit()]
#print(marks)
total = sum(marks)
# total = sum(map(int, parts[1:]))
print(f"{n... | srikanthpragada/PYTHON_18_JULY_2022 | demo/libdemo/marks_list.py | marks_list.py | py | 377 | python | en | code | 0 | github-code | 6 |
30364393271 | import os.path
import shutil
import sys
import tempfile
import textwrap
import testfixtures
from okonomiyaki.file_formats import EggMetadata, PackageInfo
from okonomiyaki.utils.test_data import NOSE_1_3_4_RH5_X86_64
from okonomiyaki._cli import main
if sys.version_info < (2, 7):
import unittest2 as unittest
else... | enthought/okonomiyaki | okonomiyaki/_cli/tests/test_cli.py | test_cli.py | py | 2,580 | python | en | code | 2 | github-code | 6 |
36466168685 | #!/usr/bin/env python
import utils
import gzip
import argparse
from pysam import TabixFile
import numpy as np
import glob
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('-r',
dest='rate_dir',
required=True,
help='P... | ryanlayerlab/layer_lab_chco | bin/get_regions_zscores.py | get_regions_zscores.py | py | 2,039 | python | en | code | 1 | github-code | 6 |
8692787672 | from strong.models import Project, Images
from rest_framework import serializers
class ImagesSerializers(serializers.HyperlinkedModelSerializer):
project_id = serializers.PrimaryKeyRelatedField(queryset=Project.objects.all(),source='project.id')
class Meta:
model = Images
fields = ('project_id'... | urielcookies/RESTFUL_API | strong/serializers.py | serializers.py | py | 753 | python | en | code | 0 | github-code | 6 |
38861064997 | import sys
sys.setrecursionlimit(10000)
def check_array(N):
return [[False for _ in range(10)]for i in range(N)]
N, K = map(int, input().split())
board = [list(input()) for i in range(N)]
ck1 = check_array(N)
ck2 = check_array(N)
dx, dy = [0, 1, 0, -1], [1, 0, -1, 0]
def countDFS(x, y):
ck1[x][y] = True... | minhee0327/Algorithm | python/BOJ/12_탐색/16768_MooyoMooyo.py | 16768_MooyoMooyo.py | py | 2,117 | python | en | code | 0 | github-code | 6 |
34508758020 |
# https://www.geeksforgeeks.org/find-zeroes-to-be-flipped-so-that-number-of-consecutive-1s-is-maximized/
# https://leetcode.com/problems/max-consecutive-ones-iii/discuss/1304346/Simple-Solution-w-Explanation-or-Sliding-Window-Approach-with-Comments
# https://leetcode.com/problems/max-consecutive-ones-iii/discuss/278... | ved93/deliberate-practice-challenges | code-everyday-challenge/n189_maximize_number_of_ones.py | n189_maximize_number_of_ones.py | py | 997 | python | en | code | 0 | github-code | 6 |
73416501948 | """
Selection Sort, inefficient swapping sort. Practiced for understanding
algorithmic design, however, python sorting functions are the way to go here.
"""
def selectionSort(L):
"""Assumes that L is a list of elements that can be compared using >.
Sorts L in ascending order """
suffixStart = 0
while suffixStart !... | AndreiBratkovski/Training | MIT-Guttag/selectionSort.py | selectionSort.py | py | 598 | python | en | code | 1 | github-code | 6 |
21833792754 | #!/usr/bin/env python3
import os
import sys
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + '/..')
from test_framework.test_framework import BitcoinTestFramework
BLOCKS = 100
TXS = 100
class TXFlood(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self... | pinheadmz/warnet-scenarios | scenarios/tx-flood.py | tx-flood.py | py | 869 | python | en | code | 0 | github-code | 6 |
20755734857 | import pandas as pd
import logging as lg
import pickle
lg.basicConfig(filename='data_test_automation.log', level=lg.INFO, format='%(asctime)s %(name)-12s %(levelname)-8s %('
'message)s', datefmt='%m-%d %H:%M',
filemode='w')
def... | InduMouliMahamkali/flightfareprediction | pre-processing and modeling/automated_model_test.py | automated_model_test.py | py | 5,520 | python | en | code | 3 | github-code | 6 |
16601473639 | import socket
import serial
import sqlite3
import select
import time
import datetime
HEADERSIZE = 10
running_on_pie = False # pie or windows
if running_on_pie:
host = '192.168.1.10'
pos = '192.168.1.10'
win1 = '192.168.1.11'
win2 = '192.168.1.12'
conn = sqlite3.connect('/home/sysop/pos/order.db')... | RG11rant/donuts | server.py | server.py | py | 9,334 | python | en | code | 1 | github-code | 6 |
30282625342 | from dataclasses import dataclass, replace
from typing import Any
from uuid import UUID
from topics.domain.repositories.topic_repository import TopicRepository
from topics.domain.usecases.base import Usecase
@dataclass(kw_only=True)
class UpdateTopicRequest:
id: UUID
content: str | None = None
discussed:... | cbenavid/topics | src/topics/domain/usecases/topic/update_topic.py | update_topic.py | py | 893 | python | en | code | 0 | github-code | 6 |
5949670885 | import time
dic_function_time = {}
def store_time(function):
"""Décorateur qui stocke le nombre de secondes écoulées
entre le début et la fin de l'exécution de la fonction.
Un décorateur est une fonction qui prend une autre fonction (ou classe) en paramètre
pour modifier son comportement lors de ... | JeremyRozier/SawImageProject | version1/decorators.py | decorators.py | py | 3,861 | python | fr | code | 0 | github-code | 6 |
47533751 | from typing import List
class Solution:
def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int:
# dp table
dp = [[0] * (len(nums2)+1) for _ in range(len(nums1)+1)]
# initialize
# pass
# traverse dp table
for i in range(1, len(nums1)+1):
f... | code-cp/leetcode | solutions/1035/main.py | main.py | py | 689 | python | en | code | 0 | github-code | 6 |
29944774792 | import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], 'utils'))
import numpy as np
import pandas as pd
import argparse
import h5py
import librosa
from scipy import signal
import matplotlib.pyplot as plt
import time
import csv
import random
from concurrent.futures import ProcessPoolExecutor
from functools im... | iamjanvijay/Background-Sound-Classification-in-Speech-Audio-Segments | utils/features.py | features.py | py | 7,026 | python | en | code | 4 | github-code | 6 |
36766561062 | '''
점수중에 최대값을 M. 모든 점수를 점수/M*100으로 고쳤다.
최고점이 70이고, 수학점수가 50이었으면 수학점수는 50/70*100이 되어 71.43점이 된다.
세준이의 성적을 위의 방법대로 새로 계산했을 때, 새로운 평균을 구하는 프로그램을 작성하시오.
3
40 80 60
75.0
'''
from sys import stdin
n = int(input())
score_list = list(map(int, stdin.readline().split()))
max_score = max(score_list)
new_score_list = []
for sc... | jiyoung-dev/Algorithm | Baekjoon/단계별(Python)/5단계_1차원배열/b1546_평균.py | b1546_평균.py | py | 593 | python | ko | code | 0 | github-code | 6 |
70952127868 | import re
book1=open("Book1.txt",'r')
book2=open("Book2.txt",'r')
book3=open("Book3.txt",'r')
line=book1.read()
line=book2.read()
line=book3.read()
word=line.strip(" ")
nn=word.split()
longest_word = max(word, key=len)
print (longest_word)
| inwk6312fall2017/programming-task-final-bhagi162 | task1c.py | task1c.py | py | 243 | python | en | code | 0 | github-code | 6 |
35543810797 | from django.urls import path
from . import views
app_name='cv'
urlpatterns = [
path('curriculo', views.index, name='index'),
path('curriculo/dados-pessoais', views.cadastrar_ou_aletarar_foto_e_objetivo, name='editar_dados'),
path('curriculo/educacao', views.cadastrar_educacao, name='educacao'),
path('cu... | smctinf/casa_do_trabalhador | curriculo/urls.py | urls.py | py | 662 | python | pt | code | 0 | github-code | 6 |
13442824529 | import pygame, os
from modules.entitysets._puresensor import PureSensor
from imageload import loadImage
from button import Button
from menustate import MenuState
from staticimage import StaticImage
from gridrounding import gridRound
from selectionbox import SelectionBox
from label import Label
class RemoveSens... | Occuliner/ThisHackishMess | modules/menuentries/sensoredit.py | sensoredit.py | py | 6,709 | python | en | code | 2 | github-code | 6 |
31373127129 | # encoding=utf8
import datefinder
from datetime import datetime
import sys
import csv
import boto3
from data import Data
from PIL import Image
import pytesseract
import cv2
import os
import re
class TestData:
"""docstring for TestData"""
@staticmethod
def get():
data = Data()
data.set('Fi... | prasadbiradar/date-extraction-from-images | testdata.py | testdata.py | py | 2,928 | python | en | code | 0 | github-code | 6 |
25849126163 | import random
import time
from colorama import Back, Fore, init
from SudokuF import *
from SudokuT import *
from Menus import *
from Ahorcado import *
lop = 0
while lop == 0:
menuprincipal()
opcionprincipal = input(Fore.BLUE + "[4] Finalizar: " + Fore.RESET)
if opcionprincipal == "Fernando": #... | K23NO/Soduko | Sudoku.py | Sudoku.py | py | 7,562 | python | es | code | 0 | github-code | 6 |
40176574464 | import re
import urllib.parse
from bs4 import BeautifulSoup
from . import url
def name(soup):
title_bar = soup.find('div', {"class": "titleBar"})
name = title_bar.h1.text
#logger.debug("parse_brewery_name: name: {}".format(name))
return name
def beers(soup):
baContent = soup.find("div", {"id":"ba-content"})
... | JohnMcAninley/beer-goggles | scraper/src/parse/brewery.py | brewery.py | py | 1,516 | python | en | code | 0 | github-code | 6 |
21527705720 | from .models import Order, Customer
from django.http import HttpResponse
def cartData(request):
try:
customer = request.user.customer
except:
device = request.COOKIES['device']
customer, created = Customer.objects.get_or_create(device=device)
order, created = Order.objects.get_or_c... | SonnyTopG/Ecommerce-Website | website/shop/utils.py | utils.py | py | 618 | python | en | code | 0 | github-code | 6 |
4975361004 | def is_pent(n):
quad = (1 + (1+24 * n)**(1/2))/6
if quad == int(quad):
return True
return False
def is_hex(n):
quad = (1 + (1+ 8 * n)**(1/2))/4
if quad == int(quad):
return True
return False
stop = False
i = 286
while not stop:
tn = i * (i+1) / 2
if is_hex(tn):
... | colinmiller94/Project_Euler | e45.py | e45.py | py | 427 | python | en | code | 0 | github-code | 6 |
15974434638 | # Api Agenda Lionx
from src.infrastructures.mongo.mongo_infrastructure import MongoInfrastructure
# Third party
from decouple import config
from pymongo.cursor import Cursor
from pymongo.collection import InsertOneResult, UpdateResult
class MongoRepository:
def __init__(self):
self.mongo_client = MongoIn... | vinireeis/api_agenda_lionx | src/repositories/mongo/repository.py | repository.py | py | 2,050 | python | en | code | 1 | github-code | 6 |
7368403785 | #!/usr/bin/env python2.6
# -*- coding: utf-8 -*-
# mainframe.py
# Pomodoro
#
# Created by Roman Rader on 22.06.11.
# New BSD License 2011 Antigluk https://github.com/antigluk/Pomodoro
"""
Contains main frame of application.
"""
import wx
from state import PomodoroStateProxy as PomodoroState
from NotificationCente... | rrader/Pomodoro | pomodoro/mainframe.py | mainframe.py | py | 4,124 | python | en | code | 1 | github-code | 6 |
17600865196 | #encoding:UTF-8
import urllib
import urllib.request
import json
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
import matplotlib.lines as mlines
import numpy as np
import time
data = urllib.request.urlopen('https://stationdata.wunderground.com/cgi... | Louis-He/weather_map | wunderground_weather.py | wunderground_weather.py | py | 6,022 | python | en | code | 0 | github-code | 6 |
74903206266 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from collections import deque
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
i... | eungang3/Leetcode | binary-tree-level-order-traversal/binary-tree-level-order-traversal.py | binary-tree-level-order-traversal.py | py | 973 | python | en | code | 0 | github-code | 6 |
71836229628 | from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_insertar(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(570, 518)
self.verticalLayout = QtWidgets.QVBoxLayout(Form)
self.verticalLayout.setObjectName("verticalLayout")
self.groupBox = QtWidgets.QG... | JoseVale99/simulador_prediccion_desemepe-o | view/insertar.py | insertar.py | py | 9,728 | python | en | code | 0 | github-code | 6 |
170942993 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from rp_ui_harness import RequestPolicyTestCase
from marionette import expectedFailure
from marionette_driver import Wai... | RequestPolicyContinued/requestpolicy | tests/marionette/rp_puppeteer/tests-quick/test_error_detection.py | test_error_detection.py | py | 3,791 | python | en | code | 253 | github-code | 6 |
73652353149 | # 给你 二维 平面上两个 由直线构成且边与坐标轴平行/垂直 的矩形,请你计算并返回两个矩形覆盖的总面积。
# 每个矩形由其 左下 顶点和 右上 顶点坐标表示:
# 第一个矩形由其左下顶点 (ax1, ay1) 和右上顶点 (ax2, ay2) 定义。
# 第二个矩形由其左下顶点 (bx1, by1) 和右上顶点 (bx2, by2) 定义。
class Solution(object):
def computeArea(self, ax1, ay1, ax2, ay2, bx1, by1, bx2, by2):
"""
:type ax1: int
:type ay1... | xxxxlc/leetcode | array/computeArea.py | computeArea.py | py | 1,096 | python | zh | code | 0 | github-code | 6 |
16791541041 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 23 12:32:47 2022
@author: maksi
"""
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.datasets import load_digits
from keras.models import Sequential
from keras.layers import Dense
from tensorflow.keras.optimizers impor... | makspervov/Podstawy-SI-Python | lab5/lab5_zad2.py | lab5_zad2.py | py | 1,785 | python | en | code | 0 | github-code | 6 |
30459355654 | #!/usr/bin/python3
"""
This is a file to print squares with a given number
I am making up some words to get a better score I think
"""
def print_square(size):
"""Prints a square with a given size"""
if type(size) is not int:
TypeError("size must be an integer")
if size < 0:
ValueError("siz... | Ethan-23/holbertonschool-higher_level_programming | 0x07-python-test_driven_development/4-print_square.py | 4-print_square.py | py | 440 | python | en | code | 0 | github-code | 6 |
11278711462 | """
Here we test a basic strategy that includes an indicator and FX rate movements.
We'll start with an ($100K) AUD denominated portfolio and buy 100 shares of SPY
only if the VIX < 26.
Also, buying in SPY will make us short USD.
Generate funding trades, to be executed the day after we buy SPY, so that
we aren't shor... | simongarisch/pxtrade | tests/test_strategy2.py | test_strategy2.py | py | 4,212 | python | en | code | 2 | github-code | 6 |
17282581755 | from pynput.keyboard import Listener, Key
import time
from threading import Thread
from canvas import Canvas
from pedal import Pedal
from snake import Snake
from ball import Ball
import os
def on_press(key):
if hasattr(key, 'char'): # Write the character pressed if available
print(key.char)
elif key =... | devbit-algorithms/snakepong-snaka69 | gameLoop.py | gameLoop.py | py | 1,665 | python | en | code | 0 | github-code | 6 |
13918838862 | # License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
import time
from collections import defaultdict
from datetime import datetime
from odoo import api, models
class ManagementDashboard(models.Model):
_name = 'management.dashboard'
_description = "Project Management Dashboard"
@api.mo... | onesteinbv/ProjectManagement | management_dashboard/models/management_dashboard.py | management_dashboard.py | py | 5,708 | python | en | code | 1 | github-code | 6 |
30059046061 | from pyswarms.base.base_discrete import DiscreteSwarmBase
import numpy as np
from scipy.spatial import cKDTree
class PerezPSO(DiscreteSwarmBase):
def assertions(self):
"""Assertion method to check various inputs.
Raises
------
KeyError
When one of the required diction... | Ninalgad/PerezSwarm | base_discrete.py | base_discrete.py | py | 10,842 | python | en | code | 1 | github-code | 6 |
33584979695 | __author__ = 'Vivek'
def nextPermutation(A):
"""
:param: List of integer
:return : numerically next greater permutation of integers
"""
i = -1
last = False
for k in range(len(A)-1) :
if A[k] < A[k+1] :
i = k
if i == -1 :
last = True
j = -1
if not last ... | viveksyngh/InterviewBit | Arrays/NEXTPERM.py | NEXTPERM.py | py | 740 | python | en | code | 3 | github-code | 6 |
11859412516 | import logging
from copy import deepcopy
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any, Dict, List, Union
from pandas import DataFrame, to_datetime
from tabulate import tabulate
from freqtrade.constants import (DATETIME_PRINT_FORMAT, LAST_BT_RESULT_FN, UNLIMITED_ST... | robcaulk/freqai | freqtrade/optimize/optimize_reports.py | optimize_reports.py | py | 41,632 | python | en | code | 42 | github-code | 6 |
71601601789 |
def tabung ( b, c):
volume = 22/7 * b * c
luas = 2*22/7*b*(b + c)
return volume,luas
def balok ( a, b , c):
volume = a * b * c
return volume
def main():
ma = input("masukkan yang ingin di pake rumus (tabung, balok): ")
if ma == "tabung":
b = float(input("masukkan jari"))
... | MErlanggaa/Tugas | Python/tugas/menghitungtabungdanbalok.py | menghitungtabungdanbalok.py | py | 733 | python | id | code | 0 | github-code | 6 |
41457469135 | """
flaskr.utils.db
~~~~~~~~~~~~~~~
Utilities for database operations.
"""
import sqlite3
from typing import List, Optional
from datetime import datetime, timezone
from flask import g
from flask import current_app
from flaskr.utils.node import Node
def convert_timestamp(t):
return datetime.fromisoformat(t.decode... | MioYvo/unlimited-level-messages | backend/flaskr/utils/db.py | db.py | py | 3,870 | python | en | code | 0 | github-code | 6 |
12830935610 | class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
if len(s) > len(t):
return False
if len(s) == 0:
return True
index_s = 0
for char_t in t:
if char_t == s[index_s]:
index_s += 1
if index_s == len(s):
... | theRobertSan/LeetCode-Solutions-Python | 392.py | 392.py | py | 426 | python | en | code | 1 | github-code | 6 |
42012547996 | # python 3 has different package names
try: from urlparse import urlparse
except ImportError: from urllib.parse import urlparse
from collections import defaultdict
def _new_collection():
""" Collection data type is
{path: {method: (ResponseClass,) }}
So e.g. a POST request to http://venmo.com/... | venmo/tornado-stub-client | tornado_stub_client/collection.py | collection.py | py | 1,717 | python | en | code | 9 | github-code | 6 |
29542340141 | import re
from collections import defaultdict
from string import Template
from odoo import _
from odoo.exceptions import MissingError
DEFAULT_REFERENCE_SEPARATOR = ""
PLACE_HOLDER_4_MISSING_VALUE = "/"
class ReferenceMask(Template):
pattern = r"""\[(?:
(?P<escaped>\[) |
(... | odoonz/odoonz-addons | product_code_builder/models/helper_methods.py | helper_methods.py | py | 1,828 | python | en | code | 14 | github-code | 6 |
39993181023 | import os
import numpy as np
import matplotlib.pyplot as plt
import cv2
import open3d as o3d
def mkdirs(path):
try:
os.makedirs(path)
except:
pass
class Saver(object):
def __init__(self, save_dir):
self.idx = 0
self.save_dir = os.path.join(save_dir, "results")
... | zhijieshen-bjtu/PanoFormer | PanoFormer/saver.py | saver.py | py | 3,346 | python | en | code | 79 | github-code | 6 |
43229119277 | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("shop", "0005_auto_20150527_1127"),
]
operations = [
migrations.AlterField(
model_name="order",
name="key",
field=models.CharField(max_length=40, db_index... | stephenmcd/cartridge | cartridge/shop/migrations/0006_auto_20150916_0459.py | 0006_auto_20150916_0459.py | py | 345 | python | en | code | 696 | github-code | 6 |
22083785095 | def sieve_of_primes(n):
# n = 20
sev=[True for x in range(n+1)]
sev[1]=False
p=2
while (p*p<=n):
if sev[p] == True:
for i in range(p*p,n+1,p):
sev[i] = False
p += 1
return sev
hours,part=input().split()
hours = int(hours)
part = int(part)
div=hours//part
sev = sieve_of_primes(500)
# print(sev)
count=0
... | vamshipv/code-repo | TCS Codevita/primetime.py | primetime.py | py | 453 | python | en | code | 0 | github-code | 6 |
33359783594 | from unittest import TestCase
import unittest
# from unittest.mock import patch, Mock
# import csv
# from flask import request, jsonify
import requests
# import sys
#
# sys.path.insert(0, '../../src')
class TestLoadDailyReports(TestCase):
# def setUp(self):
# self.app = app.
def test_load_data_succ... | shin19991207/CSC301-A2 | tests/routes/test_daily_reports.py | test_daily_reports.py | py | 1,472 | python | en | code | 0 | github-code | 6 |
13504549380 | #For randomly choice; we need import keyword and random module.
import random
customers = ['Jimmy', 'kim', 'John', 'Stacie']
#Choose one customer randomly and put the value as winner.
winner = random.choice(customers)
#Set a variable named flavor to the text vanilla.
flavor = 'vanilla'
#Printing Congratulations,
#Na... | mainurrasel/Learn-To-Code | Assignments/ch1/pg-11/iceCream_writing_python_pg_11.py.py | iceCream_writing_python_pg_11.py.py | py | 1,151 | python | en | code | 0 | github-code | 6 |
40787879761 | from time import sleep
import time
import datetime
from datetime import timedelta
from time import sleep, strftime
motionTimeOutSeconds = 5
lastMotionTime = datetime.datetime.now()
def motionTimedOut():
myNow = datetime.datetime.now()
deltaTime = (myNow - lastMotionTime).total_seconds()
if deltaTime > mot... | mrncmoose/smart_controller | pi-code/thermalPreTest.py | thermalPreTest.py | py | 816 | python | en | code | 3 | github-code | 6 |
19601192171 | #-*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from blog.models import Mypost, MainPage
from blog.forms import CreateForms
# Create your views here.
def index(request):
all_posts = Mypost.objects.all()
maintext = MainPage.objects.all()
# print('all_posts_all')
# print(all_posts)... | drhtka/forms_urls_drf | blog/views.py | views.py | py | 3,836 | python | en | code | 0 | github-code | 6 |
5694314611 | import torch
import torch.nn as nn
class Decoder(nn.Module):
def __init__(self):
super(Decoder, self).__init__()
self.reduce_dim_5 = nn.Conv2d(2048, 256, kernel_size=(1, 1), stride=1, padding=0)
self.reduce_dim_4 = nn.Conv2d(1024, 256, kernel_size=(1, 1), stride=1, padding=0)
... | dmdm2002/FPN | Model/TopDown.py | TopDown.py | py | 1,762 | python | en | code | 2 | github-code | 6 |
31102190444 | from distutils.core import setup
import sys
sys.path.insert(1, "lib")
from maxicom.strings import *
files = ["glade/*"]
setup(name = PACKAGE,
version = VERSION,
description = DESCRIPTION,
author = AUTHOR,
author_email = AUTHOR_EMAIL,
url = URL,
license = LICENSE,
package_dir = {'': 'lib'},... | gsmcmullin/maxicom | setup.py | setup.py | py | 420 | python | en | code | 1 | github-code | 6 |
8352946523 | from setuptools import find_packages, setup
with open("./README.md") as fp:
description = fp.read()
setup(
name="pyC8",
version="1.1.1",
description="Python SDK for Macrometa Global Data Mesh",
long_description=description,
long_description_content_type="text/markdown",
author="Macrometa",... | Macrometacorp/pyC8 | setup.py | setup.py | py | 1,074 | python | en | code | 6 | github-code | 6 |
33349139375 | from data_test import DataGarbageCollector
from conftest import *
def test_function(setup_teardown):
node_name = "k3d-p3"
ip_address = get_ip(node_name)
setup_sessions_metadata(node_name)
setup_node_metadata(node_name)
con = Connection(node_name='k3d-p3', ip=ip_address)
session = 'marco'
... | leonardobarilani/edge-computing-thesis | FaaS/openfaas-offloading-session/tests/test_garbage_collector.py | test_garbage_collector.py | py | 785 | python | en | code | 4 | github-code | 6 |
34327083443 | import pickle
import re
from pathlib import Path
from typing import List
from IPython.display import display
import os.path as op
from datetime import datetime
import pandas as pd
from tqdm.notebook import tqdm
from matplotlib import pyplot as plt
from sklearn.metrics import (
accuracy_score,
balanced_accu... | ibrahimberb/Predicting-Mutation-Effects | src/dev/CancerValidation/A1/utils.py | utils.py | py | 11,283 | python | en | code | 0 | github-code | 6 |
4818420912 | import numpy as np
#this script contains all the necessary function required for training data using linear regression. Run gradient_Descent function and it will return the w vector, b and cost_history, which
#models your data. You can also apply the model to the new data for prediction.
def compute_pderivatives(l... | slama0077/ML-Packages | RLinearDescent.py | RLinearDescent.py | py | 1,664 | python | en | code | 0 | github-code | 6 |
48709281 | from typing import *
class Solution:
@staticmethod
def gcd(a, b):
while b:
a, b = b, a%b
return a
def dfs(self, nums, opt, mask):
# mask: 0 unused, 1 used
n = len(nums)
ans = 0
if mask == (1 << n - 1):
return ans
if ... | code-cp/leetcode | solutions/1799/main.py | main.py | py | 984 | python | en | code | 0 | github-code | 6 |
29528131446 | from flask import Flask, request
app = Flask(__name__)
@app.route('/')
def home():
return "TP Florian Marques"
@app.route('/means', methods=['GET'])
def meanOfList():
list = request.args.getlist('int', type=int)
if len(list) == 0:
return "Given list is null"
else:
return "Mean of the... | MarquesFlorian/python_server_testing_florian_marques | app.py | app.py | py | 362 | python | en | code | 0 | github-code | 6 |
12486639819 | import multiprocessing
import time
import hashlib
memory = list(range(30_000_000))
def function(name):
for i in range(10):
print("Current:", name, i)
time.sleep(1)
def slow_function(name):
for i in range(10):
print("Current:", name, i)
for j in range(300_000):
h... | tt-n-walters/21-tuesday-python | core/multiple_processes.py | multiple_processes.py | py | 524 | python | en | code | 0 | github-code | 6 |
43082395961 | n, nums = input().split(" ", 1)
n = int(n)
nums = list(map(int, nums.split(" ")))
# dynamic programming
def max_sum_increasing_subsequence(nums, n):
maximum = 0
dp = [0 for _ in range(n)]
for i in range(n):
dp[i] = nums[i]
for i in range(n):
for j in range(i):
if nums[i] ... | chaosdevil/leetcode-problem-solving | dynamic_programming/maximum_sum_increasing_subsequence.py | maximum_sum_increasing_subsequence.py | py | 547 | python | en | code | 0 | github-code | 6 |
16644551299 | import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
def ex_deal(df_Int, df_ex):
columns = ['顺序', '氮素', '频率', '刈割']
df_Int = pd.concat([df_Int, pd.DataFrame(columns=columns)])
for item in range(df_Int.shape[0]):
for jtem in range(df_ex.shape[0]):
if int(df_Int.iloc[it... | QingqingSun-Bao/GitResp2 | micro/Fig10_bar_distribution.py | Fig10_bar_distribution.py | py | 5,270 | python | en | code | 0 | github-code | 6 |
27933308570 | import time
from clusterbot import ClusterBot, activate_logger
# Print confirmation about sent Slack messages
activate_logger()
# Debug mode
# activate_logger('DEBUG')
# Send a message to the default user specified in you config files.
bot = ClusterBot()
message_id = bot.send("Starting example script.")
# Reply to th... | sprekelerlab/slack-clusterbot | example_script.py | example_script.py | py | 1,406 | python | en | code | 2 | github-code | 6 |
23907002609 | import numpy as np
import pandas as pd
import scipy.spatial.distance as spd
import scipy.stats as sps
import sklearn.model_selection as skm
import sklearn.metrics as skmetrics
import matplotlib.pyplot as plt
import seaborn as sb
from hw1_modules import *
# read data from CSV to array
data = np.array(pd.read_csv("train... | terry99999/M_hw1 | knn.py | knn.py | py | 1,791 | python | en | code | 0 | github-code | 6 |
32474300219 | from django.conf.urls import url, include
from rest_framework import routers
from api import views
router = routers.DefaultRouter()
router.register(r'signup', views.ProfileViewSet)
router.register(r'add_animal', views.AddAnimalViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login U... | stoic1979/pashu_palak_sahayak | api/urls.py | urls.py | py | 439 | python | en | code | 1 | github-code | 6 |
5070831792 | import pandas as pd
import matplotlib.pyplot as plt
# Load the CSV file and set the type of the date column
reviews = pd.read_csv("branch_reviews.csv", index_col=0, parse_dates=["date"])
# Display a histogram of the number of reviews by date
reviews["date"].hist()
#plt.show()
# Create a new dataframe from reviews wi... | carsten-hohnke/review_analysis | analyze_reviews.py | analyze_reviews.py | py | 638 | python | en | code | 0 | github-code | 6 |
70047131707 | import xml.etree.ElementTree as ET
import pandas as pd
import numpy as np
import cv2 as cv
def draw_label(path):
tree = ET.parse(path)
img_out = np.zeros(shape=(1024, 1280))
img_list_x = []
img_list_y = []
for elem in tree.iterfind('object'):
mylist_x = []
mylist_y = [... | Bagpip/-HSI- | label_test.py | label_test.py | py | 1,589 | python | en | code | 0 | github-code | 6 |
10164344104 | import sys
import os
def print_usage():
print("Usage:")
print("stringer.py 1 <file> <string_to_count>")
print(" 2 <file> <string_to_remove>")
if __name__ == "__main__":
if len(sys.argv) < 2 or sys.argv[1] == "-h":
print_usage()
exit(1)
if (sys.argv[1] == '1'):
p... | twono/PythonUtils | stringer.py | stringer.py | py | 646 | python | en | code | 0 | github-code | 6 |
14400222496 | #!/usr/bin/env python3.8
"""
Given two rectangles, determine if they overlap. The rectangles are defined as a Dictionary, for example:
r1 = {
# x and y coordinates of the bottom-left corner of the rectangle
'x': 2 , 'y': 4,
# Width and Height of rectangle
'w':5,'h':12}... | dnootana/Python | Interview/RectangleOverlap.py | RectangleOverlap.py | py | 1,356 | python | en | code | 0 | github-code | 6 |
854208264 | import core.modules
import core.modules.module_registry
from core.modules.vistrails_module import Module, ModuleError
import numpy
import scipy
import scipy.ndimage
from Array import *
from Matrix import *
class ArrayImaging(object):
my_namespace = 'numpy|imaging'
class ExtractRGBAChannel(ArrayImaging, Module):
... | VisTrails/VisTrails | contrib/NumSciPy/Imaging.py | Imaging.py | py | 7,502 | python | en | code | 100 | github-code | 6 |
29580890531 | # -*- coding: utf-8 -*-
##############################################################################
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the L... | odoomrp/odoomrp-utils | product_pricelist_partnerinfo/models/product.py | product.py | py | 1,677 | python | en | code | 36 | github-code | 6 |
23497624891 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import sys
BUFSIZE = 1024
def start_client(address):
tcpCliSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpCliSock.connect(address)
while True:
data = raw_input('> ')
if not data:
break
tcpCliSo... | Furzoom/learnpython | app/test/tsTclnt.py | tsTclnt.py | py | 675 | python | en | code | 0 | github-code | 6 |
31533830486 | x_house_height = float(input())
y_side_wall_lenght = float(input())
h_triangle_side_height = float(input())
window_side = 1.5
door_side_a = 1.2
door_side_b = 2
window_area = window_side * window_side
windows_total_area = window_area * 2
door_area = door_side_a * door_side_b
side_wall_area = x_house_height * y_side_wall... | iliyan-pigeon/Soft-uni-Courses | programming_basics_python/first_steps_more_exercises/house_painting.py | house_painting.py | py | 970 | python | en | code | 0 | github-code | 6 |
31366334882 | import torch
import torch.nn as nn
from GAWWN.tools.config import cfg
from GAWWN.tools.tools import replicate
class keyMulD(nn.Module):
def __init__(self):
super(keyMulD, self).__init__()
self.ndf = cfg.GAN.NDF
self.nt_d = cfg.TEXT.TXT_FEATURE_DIM
self.keypoint_dim = cfg.KEYPOINT.D... | LosSherl/GAWWN.Pytorch | GAWWN/model/discriminator.py | discriminator.py | py | 4,867 | python | en | code | 0 | github-code | 6 |
27535721148 | import json
from web3 import Web3
from decimal import Decimal
from router import*
import time
# add blockchain connection information
cronos_mainnet_rpc = "ws://rpc.vvs.finance/"
w3 = Web3(Web3.WebsocketProvider(cronos_mainnet_rpc, websocket_timeout= 6000))
ERC20ABI = json.load(open('./erc20_abi.abi'))
#getSelector("... | Galahad091/My-arb-on-fantom | test/encode_data.py | encode_data.py | py | 2,926 | python | en | code | 0 | github-code | 6 |
10426113272 | from measurements.models import Location, Station, SourceType, Network
from django.contrib.gis.geos import Point
import requests
from bs4 import BeautifulSoup
from datetime import datetime, timedelta
import pandas as pd
import re
IOC = "http://www.ioc-sealevelmonitoring.org/station.php?code={}"
stations = (
(... | CNR-ISMAR/ecoads | scripts/import_station_locations.py | import_station_locations.py | py | 1,738 | python | en | code | 0 | github-code | 6 |
2048923412 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
sort.Sort
Sort algorithm.
'''
class Sort(object):
__CUTOFF = 5
def _median3(arr, beg, end):
mid = (beg + end) // 2
if arr[beg] > arr[mid]:
arr[beg], arr[mid] = arr[mid], arr[beg]
if arr[mid] > arr[end]:
... | zhencliu/learning_python | sort/Sort.py | Sort.py | py | 5,879 | python | en | code | 0 | github-code | 6 |
23055488423 | """
Creation:
Author: Martin Grunnill
Date: 2022-11-01
Description: Getting prevelance data for world cup teams.
"""
import copy
import pandas as pd
import datetime
schedule_df = pd.read_csv('data_extraction/Fifa 2022 Group stages matches with venue capacity.csv')
covid_data = pd.read_csv('https://covid.o... | LIAM-COVID-19-Forecasting/Modelling-Disease-Mitigation-at-Mass-Gatherings-A-Case-Study-of-COVID-19-at-the-2022-FIFA-World-Cup | Running_and_analysing_simulations/parameters/data_extraction/getting_prevelance_data.py | getting_prevelance_data.py | py | 5,030 | python | en | code | 0 | github-code | 6 |
37009381909 | class Solution:
def minCostClimbingStairs(self, cost) -> int:
"""
dp[i]表示登上第i个阶梯所花费的体力值。
登上楼顶所花费的体力值为0,
所以我们要登上n层阶梯的阶梯顶部,则要求dp[n+1]
"""
n = len(cost)
if n < 1:
return 0
dp = [0] * (n+1)
cost.append(0)
dp[0] = cost[0]
... | wangluolin/Algorithm-Everyday | dp/746-爬楼梯.py | 746-爬楼梯.py | py | 591 | python | en | code | 0 | github-code | 6 |
1118355565 | '''02-05-2021 Baekjoon Algorithm
단계별 문제 풀이 - 12단계
언어 - Python'''
# 2751
# N개의 수가 주어졌을 때, 이를 오름차순으로 정렬하는 프로그램을 작성하시오.
'''
N = int(input())
num = []
for _ in range(0, N):
num.append(int(input()))
num.sort()
for i in range(0, N):
print(num[i])
############################################... | shiningnight93/Baekjoon_Algorithm | 02-05-2021.py | 02-05-2021.py | py | 1,068 | python | ko | code | 0 | github-code | 6 |
38315691636 | #khai báo hàm long_words với 2 tham số là n và str
def long_words(n, str):
#khai báo list rỗng
word_len=[]
#gán list mới bằng cách tách các từ trong str( mỗi chữ cách nhau bởi dấu cách sẽ biến thành một phần tử của list)
txt=str.split(" ")
for x in txt:
#nếu số ký tự của chuỗi x trong list t... | lananh104/chepcode_ham.split- | chepcode.py | chepcode.py | py | 743 | python | vi | code | 0 | github-code | 6 |
23125697422 | import os
import sys
sys.path.append("..")
import taobaoTry.taobaoTryUtils
from task.logUtils import logUtils
class taobaoTryTask:
def enum(**enums):
return type('Enum', (), enums)
taskType = enum(JingXuan=1, All=2)
mTaskTypeFor = taskType.All
taobaoTryTaskLockFile = ".." + os.path.sep + "loc... | tudousiji/pachong | taobaoTry/taobaoTryTask.py | taobaoTryTask.py | py | 2,503 | python | en | code | 3 | github-code | 6 |
19521127011 | from panda3d.core import CollisionNode, CollisionTube, CollisionBox, AmbientLight, Vec4, DirectionalLight
from FreedomCampaignGame.comm_with_server import ClientLogObject
client_logger = ClientLogObject().client_logger
class GameMap():
def __init__(self, render, load_model_fun):
self.render = render
... | optimjiang/my_3d_game | game_map.py | game_map.py | py | 4,327 | python | zh | code | 0 | github-code | 6 |
29432219565 | '''
투포인터로 접근했다가 실패함
'''
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
sum_num = 0
answer = -999999999999999
for i in range(len(nums)):
sum_num += nums[i]
answer = max(answer, sum_num)
if sum_num < 0:
... | mintaewon/coding_leetcode | 0921/P21_taewon.py | P21_taewon.py | py | 379 | python | en | code | 0 | github-code | 6 |
41708064158 | import glob
import math
import os
import sys
import random
import numpy as np
import pandas as pd
import tensorflow as tf
from tqdm import tqdm
from model.siamese.config import cfg
tqdm.pandas()
"""
Files have to be stored in a structure:
main_folder/
1/
0030.jpg
1080.jpg
...
2/
... | burnpiro/farm-animal-tracking | data/data_generator.py | data_generator.py | py | 6,118 | python | en | code | 24 | github-code | 6 |
29522073566 | import os
import random
import sys
import yaml
import numpy as np
with open("config.yml", 'r') as ymlfile:
cfg = yaml.load(ymlfile, Loader=yaml.FullLoader)
ymlfile.close()
if not cfg['use_gpu']:
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
seed = cfg['seed']
os.environ['PYTHONHASHSEED'] = str(seed)
random.... | emarche/Fashion-MNIST | main.py | main.py | py | 2,261 | python | en | code | 0 | github-code | 6 |
44717248733 | # Quick and dirty utility to get coordinates for transforming view into
# a bird's eye view. Useful in OCRs were the camera is in a fixed positioning
# viewing a straight plane.
import cv2
import numpy as np
def onTrackbarChange(trackbarValue):
pass
def order_points(pts):
# initialize a list of coordinates t... | hellkrusher/BirdsEyePerspectiveTransformationUtility | BirdsEyePerspectiveTransformationUtility.py | BirdsEyePerspectiveTransformationUtility.py | py | 6,413 | python | en | code | 5 | github-code | 6 |
74142812668 | import sys
from execute_query import *
if __name__ == "__main__":
q_values = [1]
if len(sys.argv) != 4:
print("3 arguments expected : input_file_rep input_file_model output_file")
else:
db_rep = '../generated_dbs/' + sys.argv[1]
db_model = sys.argv[2]
output_file = sys.... | YacineSahli/KRR | queries/run_queries.py | run_queries.py | py | 1,295 | python | en | code | 0 | github-code | 6 |
73832000827 | import numpy as np
import pandas as pd
import scipy.ndimage as nd
from skimage import io as skio
import sys
import getopt
def usage():
print("""
Usage : python3 gen_stacked_tif.py < -i mask.lst>
< -a anno.txt>
< -o output prefix>
... | BGI-Qingdao/4D-BioReconX | Preprocess/meshgen/gen_stacked_tif.py | gen_stacked_tif.py | py | 2,922 | python | en | code | 4 | github-code | 6 |
11119557677 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the timeInWords function below.
def timeInWords(h, m):
time = ''
words = ['','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve', 'thirteen','fourteen','fifteen','sixteen','seventeen','eightee... | lamanhasanli/challengers-club-adventure | MS-WarmUp/The_Time_in_Words.py | The_Time_in_Words.py | py | 1,213 | python | en | code | 0 | github-code | 6 |
14837094680 | import frappe
import json
#从前台传入items,客户料号→料号
@frappe.whitelist()
def so_refcode_to_itemcode():
#提取js传入参数
ao_items = json.loads(frappe.form_dict.get("items"))
customer_name = frappe.form_dict.get("customer")
#获取js传入的全部客户料号(非重复)
s_ref_code = {r.get("customer_item_code") for r in ao_items}
#从xx表获取所有客户料号对应的【料号】
it... | cwlong1987/yhen | yhen/api/sales_order.py | sales_order.py | py | 866 | python | en | code | 0 | github-code | 6 |
42909743578 | # Jin Yang 260724904
import dicts_utils as utilsd
import board_utils as utilsb
import random
# takes as input a dictionary representing the rack of a player; Displays one line containing
# the letter that're on the rack using upper case.
def display_rack(r):
""" (dict) -> NoneType
Displays one line cont... | jinyang10/Scrabble | scrabble_utils.py | scrabble_utils.py | py | 15,287 | python | en | code | 0 | github-code | 6 |
2108921101 | import sys
from requests import get
from io import BytesIO
import sqlite3
from PIL import Image
from data.PYTHON_files.main import Ui_MainWindow
from data.PYTHON_files.load_image import Ui_Form
from data.PYTHON_files.description import Ui_Form_Desk
from data.PYTHON_files.effects import *
from PyQt5.QtCore import Qt
... | Programmer-Anchous/Effects-program | run.py | run.py | py | 16,243 | python | en | code | 0 | github-code | 6 |
32124422720 | from pages.courses.register_courses_page import RegisterCoursesPage
from utilities.teststatus import TestStatus
import unittest
import pytest
import time
@pytest.mark.usefixtures("oneTimeSetUp", "setUp")
class RegisterCoursesTests(unittest.TestCase):
@pytest.fixture(autouse=True)
def classSetup(self, oneTime... | badekarganesh04/selenium-python-framework | tests/courses/register_courses_tests.py | register_courses_tests.py | py | 1,090 | python | en | code | 0 | github-code | 6 |
15387648798 | import matplotlib.pyplot as plt
from sklearn.datasets.samples_generator import make_blobs
import numpy as np
def sigmoid(x):
return 1.0 / (1 + np.exp(-x))
def dataset():
(X, y) = make_blobs(n_samples=250, n_features=2, centers=2,
cluster_std=1.05, random_state=20)
X = np.c_[np.ones((X.shape[0])), X]
... | nickruggeri/Machine_Learning | AdaGrad, ADAM and AMSGrad/Codes/my_sgd.py | my_sgd.py | py | 2,198 | python | en | code | 2 | github-code | 6 |
13485135608 | #!/usr/bin/python3
def search_replace(my_list, search, replace):
newList = my_list.copy()
count = 0
for i in my_list:
if i == search:
newList[my_list.index(i, count)] = replace
count = my_list.index(i) + 1
return newList
| phiweCode/alx-higher_level_programming | 0x04-python-more_data_structures/1-search_replace.py | 1-search_replace.py | py | 274 | python | en | code | 0 | github-code | 6 |
72465379387 | from django import forms
from .models import Meme
class MemeForm(forms.ModelForm):
class Meta():
model = Meme
fields = ('description','category','meme_img')
widgets = {
'description': forms.TextInput(attrs={
'class': 'field',
'placeholder': 'Enter... | omroczkowski/h8gag | meme/forms.py | forms.py | py | 701 | python | en | code | 0 | github-code | 6 |
12657002972 | # level: medium
# soluton: backtracking
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
# print candidates
res = []
self.backt... | PouringRain/leetcode | 39.py | 39.py | py | 764 | python | en | code | 1 | github-code | 6 |
71611302909 | import json
import open3d as o3d
import numpy as np
import os
import trimesh
import zipfile
from tqdm import tqdm
import matplotlib.pyplot as plt
plt.style.use('bmh')
default_color = [0,0.5,1]
cube = np.array([
[0,0,0], [1,0,0], [1,1,0], [0,1,0],
[0,0,1], [1,0,1], [1,1,1], [0,1,1],
])
'''plt fi... | GengxinLiu/SWMP | Extern/tools/mobility_tool.py | mobility_tool.py | py | 14,370 | python | en | code | 4 | github-code | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.