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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
24709845293 | from typing import List
DISTANCE_END = 5
def determine_place(n: int, distance_list: List[int]) -> int:
"""
Функция которая определяет, максимально высокое место участника.
:param n: длинна входного списка с расстояниями бросков участников
:type n: int
:param distance_list: список с расстояниями ... | OkhotnikovFN/Yandex-Algorithms | trainings_1.0/hw_2/task_e/e.py | e.py | py | 1,780 | python | ru | code | 1 | github-code | 1 |
11040136855 | from common.FrontendTexts import FrontendTexts
view_texts = FrontendTexts('materials')
labels = view_texts.getComponent()['selector']['choices']
ACTION_CHOICES = (
(1, labels['edit']),
(2, labels['weight'])
)
UNIT_CHOICES = (
(1, "M"),
(2, "M2"),
(3, "M3"),
(4, "EA")
)
| Conpancol/PyHeroku | CPFrontend/materials/choices.py | choices.py | py | 297 | python | en | code | 0 | github-code | 1 |
30022552251 | import numpy as np
from src.data import read_raw_data, prepare_data, split_data
from src.features import CustomTransformer
from src.entity import TrainingPipelineParams
def test_custom_transformer(params: TrainingPipelineParams):
df = read_raw_data(params.input_data_path)
df, target = prepare_data(df, params.... | made-ml-in-prod-2022/AnnaSmelova | ml_project/tests/test_custom_transformer.py | test_custom_transformer.py | py | 830 | python | en | code | 1 | github-code | 1 |
28874796424 | from inputforms.models import *
import django_tables2 as tables
class WithoutLPTable(tables.Table):
class Meta:
model = AllAccident
exclude = ('id', 'age', 'learning_point')
sequence = (
'unit_name', 'accd_type', 'emp_id', 'emp_type', 'emp_name', 'date', 'shift', 'cause',
... | subhashishkumar/R-D_SailProject | outputviews/tables.py | tables.py | py | 2,085 | python | hi | code | 0 | github-code | 1 |
10669863739 | import gspread
import copy
service_account = gspread.service_account('data/~service-account.json')
sheet = service_account.open("Mapout3.0")
scenario_sheet = sheet.worksheet("SCENARIO")
cover_sheet = sheet.worksheet("COVER")
sheet_rows = scenario_sheet.get_all_values()
times = snow_accu = sleet_accu = frzg_accu = tot... | weathermandgtl/display_grid | data/melt_slr.py | melt_slr.py | py | 5,403 | python | en | code | 0 | github-code | 1 |
13944629308 | import sys
input = sys.stdin.readline
n = int(input())
op = input().split()
c = [False]*10
mx = mn = ""
def possible(i, j, k):
if k == '<':
return i < j
if k == '>':
return i > j
return True
def solve(cnt, s):
global mx, mn
if cnt == n+1:
if not len(mn):
mn = s... | Taein2/PythonAlgorithmStudyWithBOJ | Taein/2021-02-07/2529.py | 2529.py | py | 615 | python | en | code | 1 | github-code | 1 |
73582152353 | import scrapy
from ..items import TutorialItem
class QuoteSpider(scrapy.Spider):
name = 'quote'
pageNumber = 2
# def start_requests(self):
start_urls = [
'http://quotes.toscrape.com/page/1/'
# 'http://quotes.toscrape.com/page/1/',
# 'http://quotes.toscrape.com/page/2/',
]
... | Ankitdeveloper15/python | Boring Stuff/Scrapy/tutorial/tutorial/spiders/quotes_spider.py | quotes_spider.py | py | 1,393 | python | en | code | 0 | github-code | 1 |
27708762121 | #!/usr/bin/env python3
VALID_2ND_POSITION_TOKENS = ('NAME', 'SEX', 'BIRT', 'DEAT', 'FAMC', 'FAMS',
'MARR', 'HUSB', 'WIFE', 'CHIL', 'DIV', 'DATE', 'HEAD', 'TRLR', 'NOTE')
VALID_3RD_POSITION_TOKENS = ('INDI', 'FAM')
def detect_tokens(line):
# determines tokens in a GEDCOM file line
... | fabriciof12345/CS555 | gedcom_parser.py | gedcom_parser.py | py | 1,559 | python | en | code | 0 | github-code | 1 |
30997752571 | from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask import request
from flask_migrate import Migrate
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://postgres:password@localhost:5432/FlaskDB"
db = SQLAlchemy(app)
mig... | Agasiland/FlaskService | app.py | app.py | py | 2,360 | python | en | code | 0 | github-code | 1 |
21104357591 | # -*- coding: utf-8 -*-
# This program ensures that the last lines in a set of OBS markdown files are italicized.
import re # regular expression module
import io
import os
import string
import sys
import shutil
# Globals
source_dir = r'C:\DCS\Russian\ru_obs.STR\content'
# Inserts underscores at beginning and e... | unfoldingWord-dev/tools | md/obs_italicize_last_line.py | obs_italicize_last_line.py | py | 2,684 | python | en | code | 8 | github-code | 1 |
26594790083 | class Environment:
def __init__(self, record={}, parent=None):
self.record = record
self.parent = parent
def define(self, name, value):
self.record[name] = value
return value
def assign(self, name, value):
if name not in self.record:
# identifier res... | calwoo/mlcompiler-notes | langs/eva/evalang/environment.py | environment.py | py | 818 | python | en | code | 0 | github-code | 1 |
32466005602 | import random
from colorama import init, Fore, Back, Style
from checker import check_wordle
def text_edit(guess, result, alphabet):
editted_text = []
def _letter_paint(letter, color):
letter_painted = ''
if color=='Green':
letter_painted = Back.GREEN + letter.upper()
elif color=='Yellow':
... | ivlmag/simple_wordle_clone | console_wordle.py | console_wordle.py | py | 2,396 | python | en | code | 0 | github-code | 1 |
32195531566 | import sys
import os.path
from cStringIO import StringIO
from mapnik import *
from django.conf import settings
import PIL.Image
from ebgeo.maps import bins
from ebgeo.maps.constants import TILE_SIZE
def xml_path(maptype):
path = os.path.join(sys.prefix, 'mapnik', '%s.xml' % maptype)
return path
def get_mapser... | brosner/everyblock_code | ebgeo/ebgeo/maps/mapserver.py | mapserver.py | py | 7,489 | python | en | code | 130 | github-code | 1 |
40047697878 | import numpy as np
import os
def load_uci_boston_housing(path, dtype=np.float32):
data = np.loadtxt(path)
data = data.astype(dtype)
permutation = np.random.choice(np.arange(data.shape[0]),
data.shape[0], replace=False)
size_train = int(np.round(data.shape[0] * 0.9))
... | vevake/Housing_BNN | utils.py | utils.py | py | 1,146 | python | en | code | 1 | github-code | 1 |
71006897315 | import xarray as xr
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import cartopy.crs as ccrs
import cartopy.io.shapereader as shpreader
from cartopy.feature import ShapelyFeature
import cartopy.feature as cfeature
from cartopy.mpl.ticker import LongitudeFormatter, Latit... | pkmn99/dryland_moisture | code/plot_china_dryland_source.py | plot_china_dryland_source.py | py | 2,696 | python | en | code | 0 | github-code | 1 |
6034178664 | from typing import List, MutableMapping
"""
Summary: The trick is - the problem is the duplicate of the original except for
if you steal from the first house, you can't steal from the last. So, 2 cases:
stole from the first or not. Then, the problem is identical to the original one
___________________________________... | EvgeniiTitov/coding-practice | coding_practice/sample_problems/leet_code/medium/greedy-dynamic-backtracking/213_house_robber_2.py | 213_house_robber_2.py | py | 3,911 | python | en | code | 1 | github-code | 1 |
27624425145 | import numpy as np
import tensorflow as tf
import tensorflow.keras.layers as layers
import tensorflow.keras.models as models
import tensorflow.lite as lite
# Downloading MNIST data set from keras
mnist = tf.keras.datasets.mnist
(image_data_training, label_data_training), (image_data_testing, label_data_testi... | Mohamed-512/Hand-Written-Number-Identifier | Main Keras.py | Main Keras.py | py | 3,694 | python | en | code | 0 | github-code | 1 |
14749681743 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 8 22:57:54 2019
@author: weichi
"""
import datetime as dt
from datetime import datetime
import pytz
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import linear_model, metrics, model_selection
from sklearn.model... | WeichiChen1210/PM2.5-Prediction | pm2.5_prediction.py | pm2.5_prediction.py | py | 3,991 | python | en | code | 0 | github-code | 1 |
42703895429 | # Import Required Libraries
from tkinter import *
from tkinter import messagebox
from tkinter import filedialog
import cv2
import numpy as np
import os
import sys
import tensorflow as tf
from matplotlib import pyplot as plt
from PIL import Image,ImageTk
num_classes = 3
pb_fname = '/home/ubuntu/content/models/resea... | 13020363/Deep-Learning | Assignments/A3/GUI_v2.py | GUI_v2.py | py | 8,872 | python | en | code | 0 | github-code | 1 |
26384518165 | #!/usr/bin/env python3
"""Module list_all."""
def list_all(mongo_collection):
"""
List all documents in a collection.
Args:
mongo_collection (obj): pymongo collection object
"""
all_docs = []
collection = mongo_collection.find()
for document in collection:
all_docs.append(... | jhonaRiver/holbertonschool-machine_learning | pipeline/0x02-databases/30-all.py | 30-all.py | py | 350 | python | en | code | 0 | github-code | 1 |
21415819246 | import statistics
import random
import pandas as pd
import plotly_express as px
import plotly.figure_factory as ff
import plotly.graph_objects as go
file1 = pd.read_csv('data.csv')
data = df['reading_time'].tolist()
dataset = []
def randomdata():
for i in range(0,100):
index = random.randint(0,(len(data... | SaanviSinha/Project-110 | program.py | program.py | py | 1,003 | python | en | code | 0 | github-code | 1 |
39633978744 | import pygame # 1. pygame 선언
import random
pygame.init() # 2. pygame 초기화
# 3. pygame에 사용되는 전역변수 선언
BLACK = (0, 0, 0)
size = [600, 800]
screen = pygame.display.set_mode(size)
done = False
clock = pygame.time.Clock()
# 4. pygame 무한루프
def runGame():
global done
while not done:
clock.tick(10)
s... | kyungkkk/week9 | game2.py | game2.py | py | 1,222 | python | en | code | 0 | github-code | 1 |
31972901700 | class Solution:
# @param matrix, a list of lists of 1 length string
# @return an integer
def largestRectangleArea(self, height):
height.append(0)
stk = []
i = sum = 0
while i<len(height):
if not stk or height[i]>height[stk[-1]]:
stk.append(i)
... | phc260/leetcode | Python/maximal-rectangle.py | maximal-rectangle.py | py | 916 | python | en | code | 0 | github-code | 1 |
1633661385 | from collections import deque
from fuzzywuzzy import fuzz
from datasets.fuman_base import load_fuman_rant
dataset = load_fuman_rant('data/20151023/bad-rants-4189.csv')
duplicates = set()
deduped = list()
n_elements = len(dataset.data)
rant_indexes = deque([i for i in range(n_elements)])
while rant_indexes:
i = r... | dumoulma/py-evalfilter | src/deduplicate_rants.py | deduplicate_rants.py | py | 1,055 | python | en | code | 0 | github-code | 1 |
41060910588 | import json
import os
import re
import sys
import gzip
import math
import hashlib
import logging
import portalocker
from collections import defaultdict
from typing import List, Optional, Sequence, Dict
from argparse import Namespace
from tabulate import tabulate
import colorama
# Where to store downloaded test sets.... | mjpost/sacrebleu | sacrebleu/utils.py | utils.py | py | 22,550 | python | en | code | 896 | github-code | 1 |
9338192510 | import dash
import dash_core_components as dcc
import dash_html_components as html
import json
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import plotly.express as px
import plotly.graph_objs as go
from urllib.request import urlopen
import plotly.io as pio
from sklearn.linear_model import Lin... | johnli25/uscoronavirusinfo | us_states_per_capita.py | us_states_per_capita.py | py | 3,428 | python | en | code | 0 | github-code | 1 |
26400940612 | jogadores = {} #aqui as keys vão ser o "index" da posição dos jogadores
posicoes = input()
alvo = int(input())
posicoes = posicoes.replace('[', '') #removendo o que não é número
posicoes = posicoes.replace(']', '')
posicoes = [int(numero) for numero in posicoes.split(',')]
for index in range(len(posicoes)): #pego os... | amandaarruda/introduction-to-programming | dictionaries-&-tuples;/target.py | target.py | py | 993 | python | pt | code | 0 | github-code | 1 |
70742407715 | class Solution:
def smallestDistancePair(self, nums: List[int], k: int) -> int:
n = len(nums)
nums.sort()
minDiff = inf
maxDiff = nums[-1] - nums[0]
for i in range(1, n):
minDiff = min(minDiff, nums[i] - nums[i - 1])
# binary search for t... | Euaell/CompProgramming | 0719-find-k-th-smallest-pair-distance/0719-find-k-th-smallest-pair-distance.py | 0719-find-k-th-smallest-pair-distance.py | py | 1,275 | python | en | code | 0 | github-code | 1 |
25058904996 | import pygame
class Player (object):
inititalJumpSpeed=30
jumpSpeed=30
jumping=False
gravity=2
initialFallSpeed=0
fallSpeed=0
falling=True
spriteName="./Run1.png"
spriteNum=0
sprite=pygame.image.load("./Run1.png");
sprite=pygame.transform.scale(sprite,(50,... | SlothDemon42/htne_game | v0.1/HTNE_Game.py | HTNE_Game.py | py | 8,075 | python | en | code | 1 | github-code | 1 |
33460571231 | import os
from io_scs_tools.utils import path as _path_utils
from io_scs_tools.utils.printout import lprint
from io_scs_tools.internals.containers.parsers import sii as _sii
def get_data_from_file(filepath):
"""Returns entire data in data container from specified SII definition file."""
container = None
... | paypink/BlenderTools | addon/io_scs_tools/internals/containers/sii.py | sii.py | py | 934 | python | en | code | null | github-code | 1 |
34166720448 | #!/usr/bin/python3
import yaml, sys
import numpy as np
import matplotlib.pyplot as plt
import glob
import os
import math
from matplotlib.colors import LogNorm
from scipy.interpolate import griddata
from io import StringIO
filename = sys.argv[1]
f = '%s.yaml' % (filename)
# Read YAML file
with open(f, 'r') as stre... | droundy/sad-monte-carlo | plotting/grand2d.py | grand2d.py | py | 4,441 | python | en | code | 4 | github-code | 1 |
18918269738 | '''
class inheritence
Inherit Employee to Developer & Manager
in-built function
isinstance(<inst name>, <class name>)
issubclasse(<child class>, <parent class>)
'''
#i.e HTTPException class
##simple Employee class
class Employee(object):
raise_amt = 1.04
def __init__(self, first, last, pay):
self... | srawla3010/py-training | _practice/MS_corey/oop-class4-2.py | oop-class4-2.py | py | 2,887 | python | en | code | 0 | github-code | 1 |
12712332139 | import os
try:
import busio
import armachat_lora
import aesio
except ImportError:
pass
from collections import namedtuple
import time
import struct
import binascii
import minipb
MeshtasticData = minipb.Wire([
("portnum", "t"),
("payload", "a"),
("want_response", "b"),
("dest", "I"),
... | rosmo/armassi | armassi/lib/comms.py | comms.py | py | 7,772 | python | en | code | 0 | github-code | 1 |
10300908544 | from tkinter import *
import tkinter as tk
def submit():
print("your idotic profile has been taken out of the toilet")
root = tk.Tk()
root.configure(background="black")
root.title("Final Form")
root.geometry("400x450")
fName = StringVar()
fName = a1.get()
lname = StringVar()
lnam... | Lusimba/Little_Inventors_Assignments_Folder | Solution_vidit/tkinter2/registration.py | registration.py | py | 4,866 | python | en | code | 0 | github-code | 1 |
42296024184 | import random
from itertools import starmap, cycle
class PacketState:
def __init__(self, seq_no, status, is_final, data):
self.seq_no = seq_no
self.status = status
self.data = data
self.packet = PacketState.make_pkt(data, seq_no, is_final)
@staticmethod
def make_pkt(data, ... | TarekAlQaddy/reliable-data-transfer-server | Helpers.py | Helpers.py | py | 2,829 | python | en | code | 0 | github-code | 1 |
16241233028 | from rest_framework.permissions import (
DjangoModelPermissions, BasePermission, IsAdminUser, SAFE_METHODS)
class IsProfileOwnerOrReadOnly(BasePermission):
def has_object_permission(self, request, view, obj):
print(obj)
if request.method in SAFE_METHODS:
return True
retur... | Axubyy/ATS | Backend/week_8/MiniBlog/blog/api/permissions.py | permissions.py | py | 833 | python | en | code | 0 | github-code | 1 |
36629116758 | """Возьмите любую из задач с прошлых семинаров (например сериализация данных),
которые вы уже решали. Превратите функции в методы класса, а параметры в свойства.
Задачи должны решаться через вызов методов экземпляра."""
import csv
import json
class SaveToCsv:
def __init__(self, input_file_name, output_file_name):... | Pisarev82/Immersion_in_Python | sem_10/hw_10_2.py | hw_10_2.py | py | 1,252 | python | ru | code | 0 | github-code | 1 |
31799853905 | import cv2
import mercantile
from shapely.geometry import Polygon, MultiPolygon, mapping
from toolz import curry, pipe
from toolz.curried import *
import numpy as np
from abfs.api.prediction.image import ImagePrediction
BASE_URL = 'https://api.mapbox.com/v4/mapbox.satellite'
class LatLongPrediction():
def __init... | rcdilorenzo/abfs | abfs/api/prediction/lat_long.py | lat_long.py | py | 2,544 | python | en | code | 8 | github-code | 1 |
38989140015 | import random
import torch
import os
import pandas as pd
from pathlib import Path
import torch.utils.data as data
from torch.utils.data import dataloader
class CamelData(data.Dataset):
def __init__(self, dataset_cfg=None, state=None):
# Set all input args as attributes
self.__dict__.update(locals... | ptoyip/6211H_Final | code/baseline_model/datasets/camel_data.py | camel_data.py | py | 3,369 | python | en | code | 0 | github-code | 1 |
14503858692 | from django.forms import Form, IntegerField, TextInput, CharField, ModelForm, Textarea
from .models import Feedback
class Calculator(Form):
width = IntegerField(min_value=1, widget=TextInput(
attrs={
'class': 'form-control',
'type': 'number',
'placeholder': 'Введите шир... | Skywalker-69/python_django_belhard | catalogue/forms.py | forms.py | py | 2,291 | python | en | code | 0 | github-code | 1 |
2255056672 | import unittest
from hash_table_chaining import *
class HashTableTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.empty = HashTable()
one = empty_hash_table()
one.ls[1] = [(1, "one")]
one.length = 1
cls.one = one
two = empty_hash_table()
tw... | BrianIshii/PracticeCode | breadth_first_search/hash_table_chaining/hash_table_chaining_tests.py | hash_table_chaining_tests.py | py | 3,902 | python | en | code | 0 | github-code | 1 |
3480526611 | x = [5, 6, 2, 1, 19, 5]
y = [200, 300, 180, 50, 1100, 580]
import matplotlib.pyplot as plt
from scipy import stats
s, inter, r, p, err = stats.linregress(x, y)
def fun(x):
return s * x + inter
model = list(map(fun, x))
plt.scatter(x, y)
plt.plot(x, model, color='r')
plt.show() | jj8000/kurs-cz.2 | zaj_6/regresja_prow.py | regresja_prow.py | py | 287 | python | en | code | 0 | github-code | 1 |
10180003978 | import os
import requests
import shutil
#################
# PREPARE FILES #
#################
source_dir = os.path.dirname(os.path.realpath(__file__))
md_file = os.path.join(source_dir, 'project.md')
##################
# PARSE MARKDOWN #
##################
with open(md_file, 'r') as f:
md = f.read()
##############... | Acrop146/Test | project-description/render-site.py | render-site.py | py | 1,393 | python | en | code | 0 | github-code | 1 |
11468083578 | from io import StringIO
from django.core.management import call_command
from django.core.management.base import CommandError
from django.test import TestCase
from geostore.models import Layer
from geostore.tests.factories import LayerFactory
from geostore.tests.utils import get_files_tests
class ImportGeojsonTest(T... | Terralego/django-geostore | geostore/tests/test_commands/test_import_geojson.py | test_import_geojson.py | py | 3,126 | python | en | code | 21 | github-code | 1 |
29672505067 | import random
dinero = 1000
siguente_ronda = False
coleccion_apuestas = []
while True:
if siguente_ronda:
print('######## Nueva ronda de apuestas ########')
print("Usted tiene " + str(dinero) + " para usar.")
else:
print("################## Bienvenido a la Ruleta ####################... | kizwolak/Ruleta | ruleta.py | ruleta.py | py | 8,196 | python | es | code | 0 | github-code | 1 |
23131275206 | """ Databricks - Terminate Cluster
User Inputs:
- Authentication
- Cluster ID
- terminates a single cluster.
"""
import argparse
import sys
import shipyard_utils as shipyard
try:
import errors
from helpers import DatabricksClient
except BaseException:
from . import errors
def get_args():
parser = ar... | shipyardapp/databricks-blueprints | databricks_blueprints/terminate_cluster.py | terminate_cluster.py | py | 3,593 | python | en | code | 0 | github-code | 1 |
12090767387 | import requests
from bs4 import BeautifulSoup as bs
import json
import os
import time
#This URL will be the URL that your login form points to with the "action" tag.
POSTLOGINURL = 'https://www.hackerrank.com/auth/login'
LOGINREST = "https://www.hackerrank.com/rest/auth/login"
#This URL is the page you actually want t... | moamen-ahmed-93/hackerrank_sol | hackerrank_scrapper/hackerrank.py | hackerrank.py | py | 3,629 | python | en | code | 6 | github-code | 1 |
11721583622 | # -*- coding: utf-8 -*-
"""
Preppin' Data 2021: Week 20 - Controlling Complaints
https://preppindata.blogspot.com/2021/05/2021-week-20-controlling-complaints.html
- Input the data file
- Create the mean and standard deviation for each Week
- Create the following calculations for each of 1, 2 and 3 standard deviations:... | kelly-gilbert/preppin-data-challenge | 2021/preppin-data-2021-20/preppin-data-2021-20.py | preppin-data-2021-20.py | py | 6,866 | python | en | code | 19 | github-code | 1 |
36038909243 | import collections
def calcEquation(equations, values, queries):
"""
:type equations: List[List[str]]
:type values: List[float]
:type queries: List[List[str]]
:rtype: List[float]
"""
record = collections.defaultdict(lambda: collections.defaultdict(int))
for (var1, var2), v in zip(equatio... | zhaoxy92/leetcode | 399_evaluate_division.py | 399_evaluate_division.py | py | 1,024 | python | en | code | 0 | github-code | 1 |
31416846331 | import zipfile
dest_dir = "Bonusfiles/Bonusfiles/files"
def extract_archive(archive_path, dest_dir):
with zipfile.ZipFile(archive_path, 'r') as archive:
archive.extractall(dest_dir)
if __name__ == "__main__":
extract_archive("Bonusfiles/compressed.zip", dest_dir)
| manzitlo/Zip_CreateAndExtract | zip_extractor.py | zip_extractor.py | py | 285 | python | en | code | 0 | github-code | 1 |
29250312355 |
def solution(enter, leave):
answer = []
meetList = [[] for i in range(len(enter))]
for entered in range(len(enter)):
# X 교차 경우
for left in range(len(leave)):
if entered < enter.index(leave[left]) and leave.index(enter[entered]) > left:
meetList[enter[entered] - ... | ho991217/Python | Programmers/Weekly_Challenge/Week_7.py | Week_7.py | py | 1,290 | python | en | code | 0 | github-code | 1 |
35238480999 | # Implement the Buffer class
# https://stepik.org/lesson/24461/step/9?auth=login&unit=6767
# my solution
class Buffer:
def __init__(self):
self.current_list = []
# конструктор без аргументов
def add(self, *a):
# добавить следующую часть последовательности
self.current_list.exte... | orlovsky-maya/Selenium_Python_Test_Automation | OOP_solutions/1.introduction_to_classes_ Buffer.py | 1.introduction_to_classes_ Buffer.py | py | 2,006 | python | ru | code | 1 | github-code | 1 |
30322070220 | import os
import numpy as np
base = "train"
label = 0
number = 400
train_0 = np.empty([number,50176,9])
for i in range(number):
file_path = os.path.join(base,str(label),str(i+1)+".txt")
np_array = np.loadtxt(file_path)
# 归一化(小数)
np_array_regular = (np_array - np.min(np_array))/(np.max(np_array)-np.min... | huilizhou/Deeplearning_Python_DEMO | operate_clouddata/generate_bin.py | generate_bin.py | py | 405 | python | en | code | 0 | github-code | 1 |
5409861942 | import torch
import torch.nn as nn
import statistics
import torchvision.models as models
import torch.nn.functional as F
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class encoder(nn.Module):
def __init__(self, embed_size, model, unfreeze=10):
super(encoder, self).__init__()
... | bhavyanarang/Image-Captioning | scripts/models.py | models.py | py | 14,504 | python | en | code | 0 | github-code | 1 |
73938024675 | '''
Created on 25 abr. 2020
@author: jesus.fernandez
'''
from common.SQLUtil import SQLUtil
class EmpleoINEProcessor(object):
'''
classdocs
'''
def __init__(self, spark, sc, sql):
'''
Constructor
'''
self.spark = spark
self.sc = s... | jfernandezrodriguez01234/TFM_jfernandezrodriguez01234 | src/processors/social/EmpleoINEProcessor.py | EmpleoINEProcessor.py | py | 1,261 | python | es | code | 0 | github-code | 1 |
34214470629 | import logging
import modules.net as model_arch
from torch.utils.data.dataloader import default_collate
from tqdm import tqdm
import torch
import torch.nn as nn
class Predictor():
def __init__(self, batch_size=64, max_epochs=100, valid=None, labelEncoder=None, device=None, metric=None,
learning_rate=1... | hsinlichu/Customer-Service-Data-Analysis-with-Machine-Learning-Technique | src/mypredictor.py | mypredictor.py | py | 6,299 | python | en | code | 1 | github-code | 1 |
71793823393 | import time
import threading
import sip_parser
import random
import string
import socket
import hashlib # import md5 - this is deprecated - dookie
import sys
from Queue import Queue
from random import Random
from sip_transaction_manager import SIPTransaction
from sip_transaction_manager import TData
from sip_transac... | pwnieexpress/raspberry_pwn | src/pentest/voiper/protocol_logic/sip_agent.py | sip_agent.py | py | 26,246 | python | en | code | 1,000 | github-code | 1 |
14085867754 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 17 15:15:36 2020
@author: Administrator
"""
import numpy as np
import torch
import torch.nn as nn
import time
#import skimage.measure as sm
import skimage.metrics as sm
import cv2
from osgeo import gdal
import matplotlib.pyplot as plt
###img read t... | endu111/remote-sensing-images-fusion | STARFM_torch.py | STARFM_torch.py | py | 11,637 | python | en | code | 38 | github-code | 1 |
32301689640 | #!/usr/bin/env python3
import os
import argparse
import copy
import time
import json
import signal
import types
from datetime import datetime
from contextlib import contextmanager
import wandb
import yaml
def main():
args = parse_args()
init_wandb(args)
log_parser = LogParser(args.experiment_dir, wait_f... | b0hd4n/multitarget_mt | scripts/wandb_runner.py | wandb_runner.py | py | 13,135 | python | en | code | 0 | github-code | 1 |
35968078948 | from population import *
from route import *
import config
import NSGAII
class GA:
mutationRate = 0.65
tournamentSize = 10
elitism = True
runningAvg = 0
@classmethod
def evolvePopulation(cls, pop):
newPopulation = Population(2*pop.populationSize, False)
#copy over... | Akshay-Kawlay/MTSP-throughput-max | approach1&2/galogic.py | galogic.py | py | 4,700 | python | en | code | 1 | github-code | 1 |
30689755641 | ####################################################################################
# Estimator Models
# Contains different estimators
# Each Estimator Contains:
# -A set of required conditional distributions (nuisance parameters) that must be trained
# -The set of parameters that are shared between nuisance param... | weberna/causalchains | causalchains/models/estimator_model.py | estimator_model.py | py | 10,710 | python | en | code | 6 | github-code | 1 |
75224693472 | from data import *
from models import *
import argparse
import os
import pickle
parser = argparse.ArgumentParser(description='NLI training')
parser.add_argument("--data_path", type=str, default='./data', help="path to data")
# model
parser.add_argument("--encoder_type", type=str, default='GRUEncoder', help="see lis... | tingchunyeh/Sentence-Sim | train.py | train.py | py | 7,510 | python | en | code | 0 | github-code | 1 |
12753959980 | import matplotlib.pyplot as plt
import autograd.numpy as np
import autograd.numpy.random as npr
import autograd.scipy.stats.multivariate_normal as mvn
import autograd.scipy.stats.norm as norm
import sys
sys.path.append('..')
from bbvi import BaseBBVIModel
"""
This implements the example in http://www.cs.toronto.edu/... | jamesvuc/BBVI | Examples/BBVI_test2.py | BBVI_test2.py | py | 2,606 | python | en | code | 8 | github-code | 1 |
38810424481 | a = str(input("Введите число, без пробела\n a = "))
s = 0
i = 0
for i in range(len(a)):
if a[i] == '.':
s = 0
break
if a[i] == '.':
s = 0
break
if int(a[i]) % 2 == 0:
s = s + 1
if s != 0:
print("Колличество четных чисел ", s)
else:
print(0) | LiveInside/Labs | Laba5.1.py | Laba5.1.py | py | 360 | python | ru | code | 0 | github-code | 1 |
3757279275 | # -*- coding: utf-8 -*-
from django.conf import settings
from urlparse import parse_qs, urlparse
from datetime import datetime
from celery import task
from twython import Twython
from dashboard.models import SocialSearch, Item
@task(ignore_result=True)
def collect_all_social_searchs():
social_search_list = Socia... | allisson/django-social-monitor-example | dashboard/tasks.py | tasks.py | py | 1,986 | python | en | code | 17 | github-code | 1 |
89310945 | # -*- coding: utf-8 -*-
from collections import namedtuple
GENERIC_DICT = 'GenericDict'
def __convert(obj):
if isinstance(obj, dict):
for key, value in obj.iteritems():
obj[key] = __convert(value)
return namedtuple(GENERIC_DICT, obj.keys())(**obj)
elif isinstance(obj, list):
... | tech-sketch/fiware-ros-turtlesim | src/fiware_ros_turtlesim/params.py | params.py | py | 777 | python | en | code | 1 | github-code | 1 |
11212571235 | import subprocess
from num2words import num2words
def say(number: int) -> str:
"""
Say the number in words
:param
number: int
:return:
sentence: str
"""
if 0 <= number < 1000000000000:
sentence = num2words(number).split()
for index, word in enumerate(sentence):
... | stimpie007/exercism | python/say/say.py | say.py | py | 831 | python | en | code | 0 | github-code | 1 |
74736955554 | import os
import sys
import warnings
from decouple import config
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if BASE_DIR not in sys.path:
sys.path.append(BASE_DIR)
STORAGE_DIR = os.path.join(BASE_DIR, 'storage')
RUN_DIR = os.path.join(STORAGE_DIR, 'run')
MSD_DIR = os.path.join(STORAGE_... | bpptkg/bulletin | wo/settings.py | settings.py | py | 3,089 | python | en | code | 1 | github-code | 1 |
27782909287 | """Tools for Graphs representing Markov processes using `networkx`.
"""
from . import plots
from ._tricks import (DiGraph,
MultiDiGraph,
GraphAttrs,
mat_to_graph,
param_to_graph,
make_graph,
... | subhylahiri/Markov_python_helpers | markov_helpers/graphs/__init__.py | __init__.py | py | 614 | python | en | code | 1 | github-code | 1 |
19105383629 | import os
import json
import pandas as pd
from aideme.explore import ExplorationManager, PartitionedDataset
from aideme.active_learning import KernelVersionSpace
from aideme.active_learning.dsm import FactorizedDualSpaceModel
from aideme.initial_sampling import random_sampler
import src.routes.points
from src.route... | AIDEmeProject/AIDEme | api/tests/routes/test_points.py | test_points.py | py | 4,014 | python | en | code | 0 | github-code | 1 |
15533905597 |
# A very simple Bottle Hello World app for you to get started with...
from bottle import route, run, template, default_app
import json
import get_stream
@route("/")
@route("/index")
def index():
data = get_stream.get_stream_data()
#print(data)
return template("""
<b>
An example weather ... | smahagos/WeatherData | mysite/bottle_app.py | bottle_app.py | py | 1,680 | python | en | code | 0 | github-code | 1 |
25008123076 | from Net import Net
import torch
import torch.nn as nn
import torch.optim as optim
from typing import List
from pathlib import Path
import os
class ModelTrainEval:
def __init__(self):
self.net = Net()
self.criterion = nn.MSELoss()
self.optimizer = optim.Adam(self.net.parameters(), lr=0.00... | paddywardle/Computational_Chemistry_Data_Engineering_Project | main/Models/ModelTrainEval.py | ModelTrainEval.py | py | 2,392 | python | en | code | 1 | github-code | 1 |
866384618 | class Viterbi:
# This is the constructor for this class, which takes as input a
# given HMM with respect to which most likely sequences will be
# computed.
hmm = None
def __init__(self, hmm):
self.hmm = hmm
self.states = hmm.states
self.start_p = hmm.start_p
self.tran... | jantus/semanticClassifier | viterbi.py | viterbi.py | py | 1,457 | python | en | code | 1 | github-code | 1 |
36343414639 | # -*- coding: utf-8 -*-
import pymysql
from learn_pymysql.test_api.mysql_api import MysqlClient
from learn_pymysql.test_api.redis import RedisClient
from learn_project.my_project.test_api.test_public import Job
class StuChooseCls(object):
@staticmethod
def create_course(token, course):
"""
创建... | Liabaer/Test | learn_flask/course/course_selection_project/course_selection_api/stu_choose_service.py | stu_choose_service.py | py | 5,442 | python | en | code | 0 | github-code | 1 |
20523314908 | from telegram import Update, Bot, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler
from tg_token import token
bot = Bot(token)
updater = Updater(token, use_context = True)
dispatcher = updater.dispatcher
def printt(update, conte... | letSmilesz/meet_python | seminar10/telegram_bot.py | telegram_bot.py | py | 2,548 | python | en | code | 1 | github-code | 1 |
8272807423 | # MAGIC CODEFORCES PYTHON FAST IO
import atexit
import io
import sys
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER
@atexit.register
def write():
sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
# END OF MAGIC CODEFORCES P... | elsantodel90/cses-problemset | food_division.py | food_division.py | py | 644 | python | en | code | 0 | github-code | 1 |
14202406531 | from typing import ClassVar, Dict, List, Type, Union, TYPE_CHECKING
from typing_extensions import Annotated
from inflection import underscore
from pydantic import BaseModel, Field, ConfigDict, BeforeValidator, PlainSerializer
from pydantic.functional_validators import AfterValidator
from pydantic._internal._model_con... | teej/titan | titan/resources/base.py | base.py | py | 15,887 | python | en | code | 91 | github-code | 1 |
38728874269 | import speech_recognition as sr
import os
from gtts import gTTS
import datetime
import pyttsx3
import playsound
import warnings
import pyaudio
import random
import datetime
import time
import calendar
import wikipedia
warnings.filterwarnings("ignore")
engine = pyttsx3.init()
voices = engine.getProperty('rate')
engine... | cs-darshan/AIR | main.py | main.py | py | 4,105 | python | en | code | 0 | github-code | 1 |
10924485509 | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
"""
在 main 方法中才会延迟输出
"""
def auto_search():
"""
自动搜索
:return:
"""
driver = webdriver.Chrome()
url = "http://www.dianping.com"
# url = "https://www.baidu.com/"
driver.get(url)
# 获取页面元素
print(driv... | logonmy/spider-mz | utils/selenium_utils_delay.py | selenium_utils_delay.py | py | 1,411 | python | en | code | 0 | github-code | 1 |
19323733535 | import random
import uuid
import copy
import json
import multihash
from intergov.domain.jurisdiction import Jurisdiction
from intergov.domain.wire_protocols import generic_discrete as gd
from intergov.domain import uri as u
from intergov.serializers import generic_discrete_message as ser
def _random_multihash():
... | bizcubed/intergov | tests/unit/domain/wire_protocols/test_generic_message.py | test_generic_message.py | py | 6,256 | python | en | code | 0 | github-code | 1 |
73116256035 | # Write a function that takes the binary representation of an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
class Solution:
def hammingWeight(self, n: int) -> int:
res: int = 0
while n != 0:
# print(n)
res += n & 1
... | eliteGoblin/sky_ladder | sessions/biancheng_nengli_beginner/191.py | 191.py | py | 401 | python | en | code | 0 | github-code | 1 |
10785644029 | # coding:utf-8
"""
@file: .py
@author: dannyXSC
@ide: PyCharm
@createTime: 2022年05月15日 19点47分
@Function: 把协作关系转化为csv文件
"""
import pandas as pd
from Reader.CoauthorReader import read_coauthor
from utils import get_coauthor_csv_path, timer
coauthor_path = get_coauthor_csv_path()
collaboration_list = []
@timer("读取协作关... | dannyXSC/BusinessIntelligence | ETL/Service/TransformCoauthorToCSV.py | TransformCoauthorToCSV.py | py | 956 | python | en | code | 0 | github-code | 1 |
71039993315 | import requests
import pandas as pd
def get_children_leis(targetLei):
"""
Gets a list of LEIs for all ultimate children of a given LEI.
Parameters
----------
targetLei : str
The LEI of the parent entity for which the ultimate children LEIs are to be retrieved.
Returns
-------
... | Donquicote/utils | utils.py | utils.py | py | 2,005 | python | en | code | 0 | github-code | 1 |
7602448585 | class Solution:
def equalPairs(self, grid: List[List[int]]) -> int:
n = len(grid)
count = 0
rows = {}
for r in range(n):
row = tuple(grid[r])
rows[row]= 1 + rows.get(row, 0)
for c in range(n):
col = tuple(grid[i][c] for i in range... | nelson123-lab/Leetcode_solved_problems_solutions | Leetcode 75/Heap map-set/2352. Equal Row and Column Pairs.py | 2352. Equal Row and Column Pairs.py | py | 3,027 | python | en | code | 0 | github-code | 1 |
6566002246 | # -*- coding: utf-8 -*-
# IEC
import os
os.environ['DJANGO_SETTINGS_MODULE']='settings'
#from iec import iec_input <---- HAS THIS BEEN DONE? (I JUST CHANGED THE NAME)
import webapp2 as webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
import cgi
imp... | hongtao510/u_tool | iec/iec_output.py | iec_output.py | py | 2,218 | python | en | code | 0 | github-code | 1 |
4157944015 | import os
import re
import jwt
from django.http import JsonResponse
from django.conf import settings
from apis.models import User
def login_decorator(func):
"""로그인 데코레이터"""
def wrapper(self, request, *args, **kwargs):
try:
token = request.headers.get("Authorization", None)
... | HyeonWooJo/tts-input-service | backend/core/utils.py | utils.py | py | 2,087 | python | ko | code | 0 | github-code | 1 |
70113408995 | from django.db import models
# Create your models here.
class BaseModelTable(models.Model):
id = models.AutoField("id", primary_key=True)
create_time = models.DateTimeField(null=True, verbose_name='创建时间', auto_now_add=True)
modify_time = models.DateTimeField(null=True, verbose_name='修改时间', auto_now=Tru... | jiqialin/AutoCaseManagemantPlatform | AutoCaseInfoManagement/index/models.py | models.py | py | 3,588 | python | en | code | 0 | github-code | 1 |
43456818359 | import requests
from MyParser import Parser
def main():
'''
the algorithm:
1. buka file small_links.txt
2. untuk setiap line, parse websitenya di beautiful soup
parse: judul, soal, pilihan, solusi
3. simpan hasil setiap line dalam sebuah folder tersendiri
'''
LINK_DIR = "small_lin... | tsdhrm/latScraper | scraper/all_small.py | all_small.py | py | 736 | python | en | code | 0 | github-code | 1 |
15362382953 | import copy
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from functools import partial
from sklearn.metrics import roc_auc_score, f1_score
from torch.utils.data import DataLoader
def collate(block, word_to_ix):
block_size = len(block)
max_words = np.max([len(i[0]) for i in... | bllguo/KSI | KSI_utils.py | KSI_utils.py | py | 12,920 | python | en | code | 0 | github-code | 1 |
22652081377 | import boto3
import unittest
import lakelayer
from datetime import datetime
from datetime import timedelta
import json
import pytz
#
# Author: Tim Burns
# License: Apache 2.0
#
# A Testing Class to Validate Scraping the KEXP Playlist for the blog
# https://www.owlmountain.net/
# If you like this, donate to KEXP: http... | timowlmtn/bigdataplatforms | src/kexp/pytest/test_kexp_get_historical_1000.py | test_kexp_get_historical_1000.py | py | 2,953 | python | en | code | 3 | github-code | 1 |
18929890543 | from tkinter import *
from tkinter import ttk
import os
def main():
window = Window()
window.mainloop()
class Window(Tk):
def __init__(self):
super().__init__()
# object attributes
self.size = "400x400"
self.title_text = "Canvas with Transparent Object"
# configure
self.geometry(self.size)
self.title... | rontarrant/tkoopython | 006_canvas/canvas_004_transparent_object.py | canvas_004_transparent_object.py | py | 1,887 | python | en | code | 2 | github-code | 1 |
71874630115 | """Endpoints of the strava_ingestion_service for metriker."""
from database_utils.activity_handler import StravaActivityHandler, parse_activity
from database_utils.user_handler import StravaUserHandler
from fastapi import APIRouter
from .config import settings
from .strava_handler import StravaHandler
# initiate dat... | christophschaller/metriker | strava_ingestion_service/strava_ingestion_service/endpoints.py | endpoints.py | py | 3,012 | python | en | code | 1 | github-code | 1 |
988098948 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 18 15:21:25 2018
@author: Sergio Balderrama
ULg-UMSS
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import enlopy as el
from matplotlib.dates import DateFormatter
#%%
###################... | Slbalderrama/Phd_Thesis_Repository | Demand_Modeling/Scenario_Creation_Demand.py | Scenario_Creation_Demand.py | py | 3,753 | python | en | code | 1 | github-code | 1 |
38928738675 | from django import forms
from ckeditor.widgets import CKEditorWidget
from .models import UserProfile
class UserProfileForm(forms.ModelForm):
# It is valid to explicitly instantiate a form field that has a
# corresponding model field, but such a field will not take any of the
# defaults from the model
... | Crossroadsman/treehouse-techdegree-python-project7 | accounts/forms.py | forms.py | py | 1,336 | python | en | code | 0 | github-code | 1 |
9563649653 | text="AGT"
text2="CTTCTCACGTACAACAAAATC"
def SymbolToNumber(symbol):
if symbol=="A":
return 0
if symbol=="C":
return 1
if symbol=="G":
return 2
if symbol=="T":
return 3
def NumberToSymbol(number):
if number == 0:
return "A"
if number == 1:
re... | rinnerthomas/bioinformatics-BC | assignment2/PatternToNumber.py | PatternToNumber.py | py | 656 | python | en | code | 0 | github-code | 1 |
17326080433 | import cv2
class Coordinates:
def __init__(self, video_path: str):
self.cap = cv2.VideoCapture(video_path)
cv2.namedWindow("Frame")
cv2.setMouseCallback("Frame", self.print_coordinates)
self.video()
def print_coordinates(self, event, x, y, flags, params):
if event == ... | FernandoLpz/YouTube | CountCars/coordinates.py | coordinates.py | py | 775 | python | en | code | 5 | github-code | 1 |
20581591067 | """
多进程多线程抓取案例
"""
from multiprocessing import Process, Queue, Pool, Manager, Lock
import os, time, random, requests, traceback, json, threading
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor
import pymongo
client = pymongo.MongoClient(host='127.0.0.1', port=27017, username="root", p... | qugemingzizhemefeijin/python-study | ylspideraction/chapter09/_020mulitprocessingthreadtxt8.py | _020mulitprocessingthreadtxt8.py | py | 3,463 | python | en | code | 1 | github-code | 1 |
4851242917 | # -*- coding: utf-8 -*-
from flask import abort, Blueprint, render_template, request
from .partial import send_file_partial
pileup_bp = Blueprint('pileup', __name__, template_folder='templates',
static_folder='static', static_url_path='/pileup/static')
@pileup_bp.route('/remote/static', method... | gitter-badger/scout | scout/server/blueprints/pileup/views.py | views.py | py | 1,343 | python | en | code | null | github-code | 1 |
39296585411 |
addTable = [
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'],
['1', '0', '3', '2', '5', '4', '7', '6', '9', '8', 'b', 'a', 'd', 'c', 'f', 'e'],
['2', '3', '0', '1', '6', '7', '4', '5', 'a', 'b', '8', '9', 'e', 'f', 'c', 'd'],
['3', '2', '1', '0', '7', '6', '5', '4', 'b', 'a', '... | Sly143/Criptografia | 2 Unidade/1 bloco.py | 1 bloco.py | py | 21,738 | python | pt | code | 1 | github-code | 1 |
4217403596 | from turtle import Turtle
ALIGNMENT = 'center'
FONT = ("Courier", 15, "bold")
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.penup()
self.hideturtle()
self.pencolor('white')
self.setposition(0, 280)
self.speed('fastest')
self.score ... | phalgunir/snake-game | scoreboard.py | scoreboard.py | py | 1,117 | python | en | code | 0 | github-code | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.