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
14557064993
import sys import cv2 import numpy import copy import scipy.misc import itertools from PIL import Image, ImageOps, ImageDraw from scipy.ndimage import morphology, label from copy import deepcopy from operator import itemgetter from statistics import median, mean from math import sqrt from random import randint from sc...
stepmat/ScienceBirds_sketch_generation
generate_sketch.py
generate_sketch.py
py
114,707
python
en
code
4
github-code
36
8635132151
# TODO : # ElasticSearch : 검색기능 구현(DB) # DRF Swagger(ysag) : API 문서화 작업용 # Celery(+Redis, + Naver SENS) : 문자인증을 위한 Naver SENS API 비동기 작동 # POSTMAN 설치 후 사용(DRF API Check) import json import os import random import datetime import calendar from django.contrib.auth import get_user_model from django.core.exceptions imp...
hanoul1124/healthcare2
app/members/apis.py
apis.py
py
7,757
python
ko
code
0
github-code
36
14265869744
import os from PIL import Image from scipy.ndimage.filters import gaussian_filter import cv2 import shutil # To copy the file import sys import numpy as np import torch from torchvision import transforms from torch.utils.data import Dataset import torch.nn.functional as F import torchvision from tqdm import tqdm ...
LudovicoL/PaDiM
backbone/AITEX.py
AITEX.py
py
14,796
python
en
code
2
github-code
36
73579291943
from lscore.midi.midifile import MIDIFile from lscore.midi.midiinstruments import * from lscore.lsystem.lsystem import * from musicalinterpretation import MusicalInterpretation import scales """ Schenkerian Rendering - see Growing Music: musical interpretations of L-Systems by Peter Worth and Susan Stepney """ c...
bflourenco/lscore
src/lscore/interpretation/schenkerianrendering.py
schenkerianrendering.py
py
2,082
python
en
code
0
github-code
36
21620206001
from __future__ import absolute_import from concurrent.futures import ThreadPoolExecutor import grpc from apache_beam.portability.api import beam_runner_api_pb2_grpc from apache_beam.portability.api.beam_runner_api_pb2_grpc import TestStreamServiceServicer class TestStreamServiceController(TestStreamServiceService...
a0x8o/kafka
sdks/python/apache_beam/testing/test_stream_service.py
test_stream_service.py
py
1,048
python
en
code
59
github-code
36
21619670691
import unittest from mock import Mock from apache_beam.metrics.cells import DistributionData from apache_beam.runners.google_cloud_dataflow.dataflow_runner import DataflowRunner from apache_beam.runners.google_cloud_dataflow.internal import apiclient from apache_beam.runners.google_cloud_dataflow.internal.clients imp...
a0x8o/kafka
sdks/python/apache_beam/runners/google_cloud_dataflow/internal/apiclient_test.py
apiclient_test.py
py
2,815
python
en
code
59
github-code
36
24684070432
# -*- coding: utf-8 -*- """ Created on Sat Aug 3 12:48:55 2019 @author: sudesh.amarnath """ import boto3 import os import glob import findspark findspark.init('/home/ubuntu/spark-2.1.1-bin-hadoop2.7') import pyspark from pyspark.sql import SparkSession spark = SparkSession.builder.appName('test').getOrCreate() from ...
sudeshg46/Phoenix
json_csv_extractor.py
json_csv_extractor.py
py
2,733
python
en
code
0
github-code
36
37353981095
"""Re-export of some bazel rules with repository-wide defaults.""" load("@npm//@angular/bazel:index.bzl", _ng_module = "ng_module", _ng_package = "ng_package") load("@build_bazel_rules_nodejs//:index.bzl", _pkg_npm = "pkg_npm") load("@npm//@bazel/jasmine:index.bzl", _jasmine_node_test = "jasmine_node_test") load("@npm...
angular/universal
tools/defaults.bzl
defaults.bzl
bzl
5,099
python
en
code
4,017
github-code
36
5217081023
#!/usr/bin/env python3 import pandas as pd def best_record_company(): df = pd.read_csv('src/UK-top40-1964-1-2.tsv', sep='\t') pubs = df.groupby('Publisher') best = pubs['WoC'].sum().max() return pubs.filter(lambda df: df['WoC'].sum().max() == best) def main(): print(best_record_company()) i...
lawrencetheabhorrence/Data-Analysis-2020
hy-data-analysis-with-python-2020/part05-e05_best_record_company/src/best_record_company.py
best_record_company.py
py
357
python
en
code
0
github-code
36
9959080371
import numpy as np import itertools import math from math import comb import random import numpy as np import itertools plural_dictionary = { "fruit": "fruits", "apple": "apples", "orange": "oranges", "banana": "bananas", "strawberry": "strawberries", "grape": "grapes", "vegetable": "vege...
GVS-007/MLLM_Reasoning
common_utils.py
common_utils.py
py
1,585
python
en
code
0
github-code
36
70955306664
""" Tests for scramble generation background tasks. """ from unittest.mock import Mock, patch, call import pytest from huey.exceptions import TaskException from cubersio.tasks import huey from cubersio.tasks.scramble_generation import check_scramble_pool, ScramblePoolTopOffInfo, top_off_scramble_pool from cubersio.u...
euphwes/cubers.io
tst/tasks/test_scramble_generation.py
test_scramble_generation.py
py
5,529
python
en
code
27
github-code
36
74552228582
""" Test File """ from flask import Flask from redis import Redis app = Flask(__name__) redis_client = Redis( host='redis_db', port=6379 ) @app.route('/') def hello(): """ Main app route, simply returns a Hello """ count_key = redis_client.get('count') count = int(count_key) if count_key...
ZacharyATanenbaum/docker_dev_build_system
examples/docker_compose_services/python_docker/index.py
index.py
py
489
python
en
code
0
github-code
36
26947568079
import tidypolars as tp from tidypolars import col import polars as pl from tidypolars.utils import _repeat def test_arrange1(): """Can arrange ascending""" df = tp.Tibble(x = ['a', 'a', 'b'], y = [2, 1, 3]) actual = df.arrange('y') expected = tp.Tibble(x = ['a', 'a', 'b'], y = [1, 2, 3]) assert ac...
markfairbanks/tidypolars
tests/test_tibble.py
test_tibble.py
py
19,053
python
en
code
275
github-code
36
15131025008
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ dummy = cur = ListNod...
EnteLee/practice_algorithm
leetcode/021_merge_two_sorted_lists/merge_two_sorted_lists_khy.py
merge_two_sorted_lists_khy.py
py
910
python
en
code
0
github-code
36
16039010135
import csv import numpy as np from random import sample class Data(object): """ Abstraction for the training data for classification """ def __init__(self, classes, input_dimension): """ Initialize the Data object. Arguments: `classes` : a array of all ...
laserprec/Iris-Flower-Classifier
datapipe.py
datapipe.py
py
7,882
python
en
code
0
github-code
36
23708455692
#!/usr/bin/env python from __future__ import print_function import sys import math import re import string from operator import itemgetter from ConfigBundle import * from urlparse import * import simplejson ## @package Document # Provides operations on pieces of text/documents #import global variable defined i...
achalatsis/News-Spread-Analyzer
Document.py
Document.py
py
5,540
python
en
code
0
github-code
36
23988137844
from fastapi import APIRouter import traceback from .nl_to_sql_utils import get_similar_severities, get_most_relevant_severity, get_sql_query from .nl_to_sql_prompts import tables_info from pydantic import BaseModel router = APIRouter() class NLtoSQL(BaseModel): """Request body for streaming.""" query: st...
yadneshSalvi/cybersec_genai
src/nl_to_sql/nl_to_sql_routes.py
nl_to_sql_routes.py
py
1,288
python
en
code
0
github-code
36
14934819007
import pytest from dbt.tests.adapter.utils.data_types.test_type_bigint import BaseTypeBigInt from dbt.tests.adapter.utils.data_types.test_type_bigint import ( models__actual_sql as bigint_model, ) from dbt.tests.adapter.utils.data_types.test_type_bigint import ( models__expected_sql as bigint_expected, ) from d...
firebolt-db/dbt-firebolt
tests/functional/adapter/utils/test_data_types.py
test_data_types.py
py
3,823
python
en
code
26
github-code
36
31008233432
# Given a string of words, you need to find the highest scoring word. # Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc. # For example, the score of abad is 8 (1 + 2 + 1 + 4). # You need to return the highest scoring word as a string. # If two words score the s...
jschoellkopf/My-Deployed-Code
code_wars/highest_scoring_word.py
highest_scoring_word.py
py
1,769
python
en
code
0
github-code
36
15733574091
from __future__ import absolute_import from __future__ import division from __future__ import print_function import re import os import copy import yaml from enum import Enum from utils.util import mace_check from utils.util import MaceLogger from py_proto import mace_pb2 CPP_KEYWORDS = [ 'alignas', 'alignof', '...
SheepHuan/CoDL-Mace
codl-mobile/tools/python/utils/config_parser.py
config_parser.py
py
10,751
python
en
code
0
github-code
36
14838409343
import json import random import re import pubchempy as pcp from csv_to_json import formulate_code # -------- \begin constants ---------------------- atoms_list = [" Hydrogen ", " Helium ", " Lithium ", " Beryllium ", " Boron ", " Carbon ", ...
arrafmousa/generate_code
generate_questiontion_with_chempy.py
generate_questiontion_with_chempy.py
py
25,754
python
en
code
0
github-code
36
74831593702
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- """This module corresponds to the bspline directory in idlutils. This is Aaron C. Rizzuto's version, with corrected handling of the Cholesky band fails and maskpoints logic to more close match the idl versio...
tofflemire/saphires
saphires/extras/bspline_acr.py
bspline_acr.py
py
24,850
python
en
code
8
github-code
36
35689287977
from utils.database import db from utils.database import Product as ProductDB, ProductSize as ProductSizes, ProductColor as ProductColors, SubCategories as SubCategoriesDB, Categories as CategoriesDB def get_products(id:int=None, search_string:str=None, category_item:str=None, subcategory_item:str=None) -> list: ...
holajoyceciao/MCloset
mystoreapp/py_files/models/product.py
product.py
py
5,389
python
en
code
0
github-code
36
2193878792
class YelpCandidateGen: def __init__(self, elasticsearch, biz_acronyms_file, index_name='yelp', biz_doc_type='biz'): self.es = elasticsearch self.index_name = index_name self.biz_doc_type = biz_doc_type self.acronym_biz_dict = dict() if biz_acronyms_file: self.acr...
hldai/labelel
yelp/yelpcandidategen.py
yelpcandidategen.py
py
3,598
python
en
code
0
github-code
36
15509801064
import numpy as np import geopandas import shapely class SparseGrid: def __init__(self, x_lim, y_lim, n_cols=10, n_rows=10, tag_prefix = ''): ''' General class to define a spatial frame composed of regular polygons, based on a grid of size n_cols x n_rows :param x_lim: Minimum an...
disarm-platform/disarm-gears
disarm_gears/frames/sparse_grid.py
sparse_grid.py
py
5,682
python
en
code
0
github-code
36
7595447308
from .base.dynamic_symbol import DynamicSymbolLexeme from .identifier import IdentifierLexeme class KeywordSymbolLexeme(DynamicSymbolLexeme): lexeme_id = "keywords.keyword" @classmethod def precedence(cls): return 1 + IdentifierLexeme.PRECEDENCE KeywordSymbolLexeme.register([ # undecided,...
padresmurfa/yapl
v0/transpiler/lexemes/keywords.py
keywords.py
py
1,716
python
en
code
0
github-code
36
23255193442
ADDITION_SYMBOL = '+' SUBTRACTION_SYMBOL = '-' MULTIPLICATION_SYMBOL = '*' EXPONENTIATION_SYMBOL = '^' OPERATORS = (ADDITION_SYMBOL, SUBTRACTION_SYMBOL, MULTIPLICATION_SYMBOL, \ EXPONENTIATION_SYMBOL) class Polynomial: def __init__(self, terms, pronumeral): # Terms must be a dictionary, with the keys ...
thewrongjames/ncss-challenge-2017
expand_this.py
expand_this.py
py
4,262
python
en
code
0
github-code
36
25597505663
# Basic packages import pandas as pd import numpy as np import re import collections # import matplotlib.pyplot as plt from pathlib import Path # Packages for data preparation from sklearn.model_selection import train_test_split from nltk.corpus import stopwords from keras.preprocessing.text import Tokenizer from ker...
ntesh21/profanity-detection
train.py
train.py
py
7,843
python
en
code
0
github-code
36
70846346343
import models.data import models.email_notice from flask import Flask, request, render_template, redirect, flash, url_for, session, abort app = Flask(__name__, static_url_path='', root_path='/root/SPM') @app.route('/') def index(): return app.send_static_file('index.html') @app.route('/user_view') def user_vie...
Elfsong/SPM
demo.py
demo.py
py
5,888
python
en
code
1
github-code
36
3751805748
from __future__ import print_function, division from torch.utils.data import Dataset, DataLoader import scipy.io as scp from keras.utils import to_categorical import numpy as np import torch from matplotlib import pyplot as plt import warnings warnings.filterwarnings("ignore") from matplotlib import pyplot as plt from ...
affect2mm/emotion-timeseries
emotion-timeseries/MovieGraphs/utils_co_attn.py
utils_co_attn.py
py
9,455
python
en
code
12
github-code
36
70606654505
import multiprocessing import os import sys import time import warnings from datetime import date import akshare as ak import numpy as np import pandas as pd warnings.filterwarnings("ignore") # 输出显示设置 pd.set_option('max_rows', None) pd.set_option('max_columns', None) pd.set_option('expand_frame_repr', False) pd.set_o...
cgyPension/pythonstudy_space
05_quantitative_trading_mysql/ods/ods_financial_analysis_indicator_di.py
ods_financial_analysis_indicator_di.py
py
5,216
python
en
code
7
github-code
36
13346852826
from osgeo import gdalnumeric from osgeo import osr from osgeo import gdal from osgeo.gdal_array import * from osgeo.gdalconst import * from PIL import Image import pylab as P import os import numpy as np from IPython.core.debugger import set_trace def readData(filename, ndtype=np.float64): ''' z=readData(...
bosmanoglu/adore-doris
lib/python/gis.py
gis.py
py
21,211
python
en
code
13
github-code
36
71521743464
from konlpy.tag import Okt # 오픈 소스 한국어 분석기 # 속도는 느리지만, 정규화에 매우 좋음 from collections import Counter def NLP(text) : # Okt 형태소 분석기 객체 생성 okt = Okt() #text = "냉장고 앞에서 최면!" ''' # 형태소 추출 morphs = okt.morphs(text) print(morphs) # 형태소와 품사 태그 추출 pos = okt.pos(text) print(pos) ''' ...
Junst/KoNLPy-tTV
KoNLPy/KoNLPy_Okt.py
KoNLPy_Okt.py
py
1,218
python
ko
code
0
github-code
36
18269283758
N = int(input()) orders = list(map(str, input().split())) # N = 5 # orders = ["R", "R", "R", "U", "D", "D"] # 0123 -> R L D U dx = [1,-1,0,0] dy = [0,0,1,-1] idx = 0 def isIn(r, c): return r>=1 and r<=N and c>=1 and c<=N class Point: def __init__(self, r, c): self.r = r self.c = c def mo...
shinzan7/algostudy
src/이코테/Chapter4 - 구현/ex4-1.py
ex4-1.py
py
693
python
en
code
0
github-code
36
73274037545
from django.urls import re_path from . import views urlpatterns = [ # Marketing TL # My tasks # re_path(r'^$', views.index), re_path(r'^marketingTL_dashboard$', views.marketingTL_dash, name="marketingTL_dashboard"), re_path(r'^mytasks$', views.marketingTL_mytasks, name="marketingTL_mytasks"), ...
Emil-20/infoxmain
marketingapp/urls.py
urls.py
py
4,392
python
en
code
1
github-code
36
70955299304
"""add unique constraint to solve for scramble and event results Revision ID: 5de7c9b4e68c Revises: 66f166a908a4 Create Date: 2019-10-13 13:11:53.915868 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '5de7c9b4e68c' down_revision = '66f166a908a4' branch_labels ...
euphwes/cubers.io
migrations/versions/039_5de7c9b4e68c_add_unique_constraint_to_solve_for_.py
039_5de7c9b4e68c_add_unique_constraint_to_solve_for_.py
py
924
python
en
code
27
github-code
36
41911943994
from django.shortcuts import render from .forms import * from django.http import HttpResponse import requests def index(request): #Making try-except block for excluding KeyError #This is made because in post request may be field which API cannot work with try: #accepting POST request film_t...
adilluos/Movie-Searcher
WebProject/taskmanager/main/views.py
views.py
py
3,026
python
en
code
0
github-code
36
71234511143
#!/usr/bin/env python # # An example on how to read the YAML output from etisnoop # Pipe etisnoop to this script # # License: public domain import sys import yaml for frame in yaml.load_all(sys.stdin): print("FIGs in frame {}".format(frame['Frame'])) for fib in frame['LIDATA']['FIC']: if fib['FIGs']: ...
Opendigitalradio/etisnoop
yamlexample.py
yamlexample.py
py
401
python
en
code
8
github-code
36
23212831424
#Desenvolva uma calculadora de IMC, o programa deve pedir o peso e a altura ao usuario. calcular o IMC e retronar para o usuario o IMC # e a categoria em que se encontra def calculadora_IMC(peso,altura): calculo_altura = altura * altura calculo_IMC = peso / calculo_altura if calculo_IMC < 18.5: ...
EduardoFB321/CalculadoraIMC
CalculadoraIMC.py
CalculadoraIMC.py
py
696
python
pt
code
0
github-code
36
10507399118
import argparse import sys import json import pickle import os import time status_colors_hex = { '200': '#6FB665', '204': '#4FA29F', '400': '#D8C726', '404': '#F06A2A', '406': '#78CAEF', '414': '#86F6D2', '500': '#043E8A', '502': '#A81E03', } def fetch_input(stats_file): file_reso...
stefanooldeman/gecko_http_codes
update_graph_data.py
update_graph_data.py
py
6,440
python
en
code
1
github-code
36
73895270183
''' Author: airscker Date: 2022-09-21 18:43:31 LastEditors: airscker LastEditTime: 2023-08-31 12:23:45 Description: NULL Copyright (C) 2023 by Airscker(Yufeng), All Rights Reserved. ''' # Always prefer setuptools over distutils from setuptools import setup, find_packages import pathlib import os here =...
Airscker/DeepMuon
setup.py
setup.py
py
6,250
python
en
code
1
github-code
36
31456331042
from openerp import models from openerp.tools.safe_eval import safe_eval as eval import cStringIO import re try: from elaphe import barcode except ImportError: pass class Report(models.Model): _inherit = 'report' def generate_barcode(self, type, value, kw, width=0, height=0): width = int(wi...
blooparksystems/bp_reportbarcode_elaphe
models/report.py
report.py
py
1,293
python
en
code
0
github-code
36
38565788435
__author__ = '''Brent Lambert, David Ray, Jon Thomas, Shane Graber''' __version__ = '$ Revision 0.0 $'[11:-2] from plone.app.layout.viewlets.content import DocumentActionsViewlet from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile from Products.CMFCore.utils import getToolByName class Bookmark...
makinacorpus/collective.plonebookmarklets
collective/plonebookmarklets/browser/viewlets.py
viewlets.py
py
1,510
python
en
code
0
github-code
36
20391645340
""" An Armstrong number is an n-digit number that is equal to the sum of the n'th powers of its digits. Determine if the input numbers are Armstrong numbers. INPUT SAMPLE: Your program should accept as its first argument a path to a filename. Each line in this file has a positive integer. E.g. 6 153 351 OUTPUT SAMP...
joelstanner/codeeval
python_solutions/ARMSTRONG_NUMBERS/ARMSTRONG_NUMBERS.py
ARMSTRONG_NUMBERS.py
py
979
python
en
code
0
github-code
36
15596107022
import os import traceback from . import datasets from . import tasks from . import util from logging import getLogger logger = getLogger('mrs') class WorkerSetupRequest(object): """Request the worker to run the setup function.""" def __init__(self, opts, args, default_dir): self.id = 'worker_setup...
byu-aml-lab/mrs-mapreduce
mrs/worker.py
worker.py
py
7,442
python
en
code
3
github-code
36
71809107943
# Import files from ScrapingProducts.AmazonRateLimiterException import AmazonRateLimiterException from Utilities.Utils import get_page_source from Utilities.MetadataUtils import * # Import libraries from bs4 import BeautifulSoup import logging as logger import time AMAZON_ERROR = "Sorry! Something went wrong on our e...
Yogesh19921/Scrapper
CollectingProducts/Crawl.py
Crawl.py
py
1,798
python
en
code
0
github-code
36
1991798018
from .card import APDUError from .iso import IsoMixin PIV_AID = b"\xA0\x00\x00\x03\x08\x00\x00\x10\x00" GET_DATA = b"\x00\xCB\x3F\xFF" PIV_CHUID = b"\x5F\xC1\x02" # Card Holder Unique Identifier CERTIFICATE_9A = b"\x5F\xC1\x05" # X.509 Certificate for PIV Authentication CERTIFICATE_9C = b"\x5F\xC1\x0A" # X.509 Cer...
timhawes/timhawes_circuitpython_nfc
timhawes_nfc/piv.py
piv.py
py
3,073
python
en
code
0
github-code
36
36060739387
from lxml import html import requests # Define parsing function def parse(score): return float(score[2:score.index('-')]) def scrape(league_id): # Store scores in list league_scores = [] # Loop through each team for team_id in range(1, 13): # Make request page = requests.get('http://games.espn.go.com/ffl/s...
JonathanWarrick/data-viz-web-crawler
web_scraper.py
web_scraper.py
py
987
python
en
code
0
github-code
36
43251321825
import pandas as pd import numpy as np from tkinter.filedialog import askopenfilenames def npzToFormat(NPZfiles = ''): #Prompt for file names if none provided if not NPZfiles: NPZfiles = askopenfilenames(title = "Select NPZ Files",filetypes = (("NPZ Files","*.npz"),("all files","*.*"))) ...
farrarmj/FalCorr
fileFormatter.py
fileFormatter.py
py
1,941
python
en
code
1
github-code
36
74105530982
#!/usr/bin/env python3 """Gleitzsch core.""" import argparse import sys import os import random import string import subprocess from subprocess import DEVNULL # from subprocess import PIPE from array import array import numpy as np from skimage import io from skimage import img_as_float from skimage.util import img_as_...
kirilenkobm/gleitzsch_v4
gleitzsch.py
gleitzsch.py
py
24,870
python
en
code
0
github-code
36
30112355766
import os import wikipedia from nltk.tag.stanford import StanfordPOSTagger from nltk.tokenize import sent_tokenize from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer from nltk.corpus import wordnet import matplotlib.pyplot as plt os.environ["JAVAHOME"] = "C:\\Program Files (x86)\\Common F...
daneel95/Master_Homework
Restanta/NLP/Lab3/homework1.py
homework1.py
py
4,985
python
en
code
0
github-code
36
21620647161
from __future__ import absolute_import import sys import threading import weakref from concurrent.futures import _base try: # Python3 import queue except Exception: # Python2 import Queue as queue # type: ignore[no-redef] class _WorkItem(object): def __init__(self, future, fn, args, kwargs): self._futu...
a0x8o/kafka
sdks/python/apache_beam/utils/thread_pool_executor.py
thread_pool_executor.py
py
5,126
python
en
code
59
github-code
36
31414321307
import datetime import json from .base_test import BaseTestCase, LoggedActivity class EditLoggedActivityTestCase(BaseTestCase): """Edit activity test cases.""" def setUp(self): """Inherit parent tests setUp.""" super().setUp() # add tests logged activity and corresponding activity ...
andela/andela-societies-backend
src/tests/test_edit_logged_activity.py
test_edit_logged_activity.py
py
6,852
python
en
code
1
github-code
36
22477753948
import numpy as np from sklearn.neighbors import KNeighborsClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.naive_bayes import GaussianNB from sklearn.svm import SVC from sklearn import model_selection as sk_ms from sklearn.model_selection import train_test_split from sklearn.metrics import auc,...
mailaucq/book_classification
classifierv2.py
classifierv2.py
py
1,771
python
en
code
0
github-code
36
3353061598
import time import redis from django.core.management import BaseCommand from django.conf import settings class Command(BaseCommand): def handle(self, *args, **options): self.stdout.write('Waiting for Redis...') redis_instance = redis.StrictRedis(host=settings.REDIS_HOST, ...
MykKos/discord_automated_sender
discord_posts/management/commands/check_on_redis.py
check_on_redis.py
py
671
python
en
code
0
github-code
36
44037875301
from flask import Blueprint, request, jsonify from flask_cors import CORS from storeback.models import db from storeback.models.admins import Admin admin_api = Blueprint('admin_api', __name__) CORS(admin_api) @admin_api.route('/api/admin', methods=['GET']) def get_all_admins(): params = request.args admins = ...
rguan72/StoreBack
storeback/handlers/admin.py
admin.py
py
1,682
python
en
code
2
github-code
36
23216761350
#!/usr/bin/env python # coding: utf-8 """ module: utilities for bounding box processing, including: xyxy <-> xywh, IoU, crop, """ import numpy as np def xyxy_to_xywh_int(xyxy, dtype=int): """ convert [xmin, ymin, xmax, ymax] -> [x-center, y-center, w, h] xy in screen coord => x/y as matrix ...
LiyaoTang/Research-Lib
Utilities/Bounding_Box.py
Bounding_Box.py
py
6,277
python
en
code
1
github-code
36
34836391359
# _*_ coding: utf-8 _*_ import os import sys import warnings sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) warnings.filterwarnings("ignore") import pandas as pd from COMM import DB_Util from COMM import Figure_Util from COMM import TechnicalAnalysis_Util # Wrap운용팀 DB Connect d...
dxcv/InvestmentTestbed
CODE/LOGIC/Test_TechnicalAnalysis.py
Test_TechnicalAnalysis.py
py
1,913
python
en
code
0
github-code
36
18458121758
from __future__ import unicode_literals import datetime import cairo import pycha.line import StringIO import time import six from uds.models import getSqlDatetime import counters # Chart types CHART_TYPE_LINE, CHART_TYPE_AREA, CHART_TYPE_BAR = range(3) # @UndefinedVariable __typeTitles = None def make(obj, cou...
karthik-arjunan/testuds
server/src/uds/core/util/stats/charts.py
charts.py
py
2,497
python
en
code
1
github-code
36
369197996
#!/usr/bin/python # -*- coding:utf-8 -*- import math ''' 最优化每个节点的坐标位置,使得相交的线段最少,保证画出的网络图比较稀疏可看性强 ''' people = ['Charlie','Augustus','Veruca','Violet','Mike','Joe','Willy','Miranda'] links=[('Augustus', 'Willy'), ('Mike', 'Joe'), ('Miranda', 'Mike'), ('Violet', 'Augustus'), ('Miranda', ...
LixinZhang/bookreviews
Programming_Collective_Intelligence/chapter5/socialnetwork.py
socialnetwork.py
py
1,526
python
en
code
10
github-code
36
15828932059
def heap_sink(heap, heap_size, parent_index): """最大堆-下沉算法""" child_index = 2 * parent_index + 1 # temp保存需要下沉的父节点,用于最后赋值 temp = heap[parent_index] while child_index < heap_size: # 如果有右孩子,且右孩子比左孩子大,则定位到右孩子 if child_index + 1 < heap_size and heap[child_index + 1] > heap[child_index]: ...
wangwenju269/leetcode
八大排序/堆排序.py
堆排序.py
py
1,236
python
en
code
1
github-code
36
20453951121
class Options(): def __init__(self): self.iters = None self.trials = None def copy(self): opt = Options() attributes = [attr for attr in dir(self) if not callable(getattr(self, attr)) and not attr.startswith("__")] for attr in attributes: value = getattr(...
jon--lee/dfr
options.py
options.py
py
783
python
en
code
0
github-code
36
14069626332
class Solution: def minMaxGame(self, nums: List[int]) -> int: while 1 < len(nums): newnums = [] for i in range(len(nums)//2): if i % 2 == 1: newnums.append(max(nums[2*i],nums[2*i+1])) else: ...
ibrahimbayburtlu/LeetCode
2293-min-max-game/2293-min-max-game.py
2293-min-max-game.py
py
442
python
en
code
2
github-code
36
75173901865
"""Read a numpy file and output an image.""" import sys import numpy as np from PIL import Image def main(filename): depth_array = np.load(filename) print(depth_array.shape) if np.max(depth_array) > 255: print("Values over 255! There is going to be truncations") depth_array = np.clip(de...
squeakus/bitsandbytes
blenderscripts/npy2img.py
npy2img.py
py
677
python
en
code
2
github-code
36
37369375965
import os import pandas as pd import numpy as np import matplotlib.pyplot as plt import cv2 """ iterate csv boxes in /box_4096 and convert them to images """ # boxfiles_dir = 'data/box_4096' # des_dir='data/allsolar_png1500_boximage' boxfiles_dir = 'data/box_full_4096' des_dir='data/allsolar_full_png512_boximage' if ...
dyu62/solar_share
data/box2img.py
box2img.py
py
1,426
python
en
code
0
github-code
36
45097764726
# -*- coding: utf-8 -*- """ Created on Fri Jul 24 18:29:51 2020 @author: rosaz """ import argparse import sys import errno import os import json import numpy as np from matplotlib import pyplot as plt from numpy import array import torch import jsonschema from torch.nn import functional as F def writeJsonNorma(path,...
rroosa/machineL
ProjectCode/file_prove.py
file_prove.py
py
18,111
python
en
code
0
github-code
36
6171283144
import matplotlib.pyplot as plt import numpy as np from numpy import * from mpl_toolkits import mplot3d import random # Presets ax = plt.axes(projection='3d') def randomcolor(): colorArr = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'] color = "" for i in range(6): co...
RS-gty/GTY_Chemistry
Group.py
Group.py
py
1,802
python
en
code
0
github-code
36
14431724379
#from ast import If #from pprint import pp #from typing import final from doctest import master from multiprocessing.reduction import duplicate import re import string from struct import pack from unittest import result from tokens import tokens from tkinter import * from tkinter import ttk #from Interfaz import da...
AngelHernandez20/191180-191280
analizadorlexico.py
analizadorlexico.py
py
5,673
python
es
code
0
github-code
36
40393533142
#!/usr/bin/env python import argparse import random import numpy as np import pandas as pd from pathlib import Path import torch from torch import optim from torch import nn from torch import cuda import torchvision from uniform_augment import ImageTransform from model import load_model from train import train_model ...
yamaru12345/UniformAugment
main.py
main.py
py
2,045
python
en
code
0
github-code
36
70441922343
import sys input = sys.stdin.readline class Solution: def __init__(self) -> None: numSteps = int(input()) points = [0] * (numSteps + 1) for i in range(1, numSteps + 1): points[i] = int(input()) self.maxScore(numSteps, points) def maxScore(self, numSteps: int, point...
cjy13753/algo-solutions
baekjoon/solution_2579.py
solution_2579.py
py
1,075
python
en
code
0
github-code
36
71514879785
import sys import time import numpy as np import torch import torch.nn as nn class RewardTracker: def __init__(self, writer, stop_reward, group_rewards=1): self.writer = writer self.stop_reward = stop_reward self.reward_buf = [] self.steps_buf = [] self.group_rewards = gro...
a046829713/DQNStockSysteam
lib/common.py
common.py
py
5,518
python
en
code
0
github-code
36
74473073385
import urllib.request, urllib.parse import bs4 as BeautifulSoup # 建立与用户以及网络的会话 base = input("Enter the URL: ") try: page = urllib.request.urlopen(base) except: print("Cannot open %s" % base) quit() # 准备soup soup = BeautifulSoup.BeautifulSoup(page) # 提取链接,并用(名称,网址)的元组表示 links = [(link.string, link['href']...
zhanwen/PythonDataScience
chapter3/practice/Solution_Broken_link.py
Solution_Broken_link.py
py
1,067
python
en
code
20
github-code
36
5941584041
import turtle as t class Rectangle(t.RawTurtle): def __init__(self, screen=t.Screen(), width=0, height=0): super().__init__(screen) self.screen = screen self.width = width self.height = height def draw(self): for i in range(2): self.fd(self.height) ...
musaaj/bot
rectangle.py
rectangle.py
py
888
python
en
code
0
github-code
36
9929931369
from models.base import ( db, TableOperateMixin, GenColumn) class DemoModel(db.Model, TableOperateMixin): """ CREATE TABLE `tb_demo` ( `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id', `name` varchar(100) NOT NULL DEFAULT '' COMMENT '名称', `tag` varchar(100) NOT NULL DEFAULT '' COMMENT '...
spxinjie6/sql-crud
models/tb_demo.py
tb_demo.py
py
943
python
en
code
1
github-code
36
74267279783
import requests import time TIMEOUT: int = 1 ATTEMPTS: int = 3 def _get_base_headers() -> dict: """Get base header for request.""" return {"Content-Type": "application/json"} def _get(url: str, headers: dict, params: dict) -> requests.Response: """Send GET request to server.""" for _ in range(ATTE...
gordienko-dmitry/job_analyzer
api/server.py
server.py
py
961
python
en
code
1
github-code
36
20026451101
from hashlib import sha1 import time import json from pulsar import get_actor, Future from pulsar.apps.wsgi import WSGIServer, WsgiResponse, WsgiHandler import aio_etcd as etcd from jirachi.io.abstract import JirachiMonitor, JirachiMonitorNotFound from pulsar.apps.wsgi import Router __all__ = ['RemoteMonitorWSGI'] bl...
RyanKung/jirachi
jirachi/io/remote/monitor.py
monitor.py
py
2,379
python
en
code
3
github-code
36
70123922664
#! /usr/bin/env python from sortrobot.mech import Robot from sortrobot.webcam import Camera from sortrobot.neural import Classifier, OrientationClassifier from sortrobot.utils import random_filename import numpy as np from PIL import Image import sys, random, os from optparse import OptionParser parser = OptionParser...
AaronParsons/sortrobot
scripts/sr_neural_sort.py
sr_neural_sort.py
py
2,532
python
en
code
0
github-code
36
26335020274
x = 5 #While后面接是非题(True, Fasle) while True: print("我还在里面,现在是:", x ) x = x + 1 #当 x < 10的时候,印出两句话,并且回头审视问题,造成“循环” #要怎么停止?把条件增加到已经超出问题 #此版本是无限,因为问题永远正确,不管结果怎样都会接到True #怎么解决? break print('我逃出循环了!')
penguin87315/while_pratices
while_true.py
while_true.py
py
398
python
zh
code
0
github-code
36
33912887364
from Faturas.Pyside2 import GUITela_de_Login as tl, Tela_Principal as tp import sys def system_load(): logged = tl.execution() if logged: tp.execution() system_load() sys.exit(0)
LC-burigo/Camerge_Faturas
Faturas/Pyside2/Gerente.py
Gerente.py
py
199
python
en
code
1
github-code
36
72056734183
from warnings import filters from billing.billing.api.sales_invoice.create_sales_invoice import re_eveluate_sales_orders # from billing.billing.utils.payment_notifications import get_party_phone import frappe from datetime import date from frappe.utils.background_jobs import enqueue from frappe.utils.data import nowda...
mudux/lims
lims/doc_hooks/lab_test.py
lab_test.py
py
11,016
python
en
code
0
github-code
36
26224523041
import xml.etree.ElementTree as ET import time import requests class BaseAPIConnector(object): def __init__(self, user_agent='', verbose=False): self.user_agent = user_agent self.verbose = verbose def construct_url(self): return None def html_request(self): if self.user_...
TheOneWho/EveCommonLibrary
EveCommon/BaseAPIConnector.py
BaseAPIConnector.py
py
1,149
python
en
code
0
github-code
36
16726065794
from __future__ import print_function import sys data = {} for ln in sys.stdin: flds = ln.rstrip('\n').split('\t') if flds[0] not in ['320600', '360100']: continue key = (flds[0], flds[1], flds[2][:6]) if key not in data: data[key] = [0.0] * 5 for i, val in enumerate(flds[3:]): ...
kn45/rider-level
tranform.py
tranform.py
py
436
python
en
code
0
github-code
36
14114323371
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="mktable2matrix", version="0.1.2", author="Guilherme Lucas", author_email="guilherme.slucas@gmail.com", description="Converts markdown table to Matrix", long_description=long_descripti...
Guilhermeslucas/mktable2matrix
setup.py
setup.py
py
646
python
en
code
1
github-code
36
24593021836
"""Implement a text output of the time entered from the console (the user should input data in the format hh:mm). Show the responses to the user in Russian according to the rules listed below: min == 0: такое-то значение часа ровно (15:00 - три часа ровно) min < 30: столько-то минут следующего часа (19:12 - двенадцат...
MikitaTsiarentsyeu/Md-PT1-69-23
Tasks/Sherel/Task2/Task2.py
Task2.py
py
5,840
python
en
code
0
github-code
36
71091836904
from unittest import TestCase from gobeventproducer.naming import camel_case class TestNaming(TestCase): def test_camel_case(self): cases = [ ("test_case", "testCase"), ("test_case_2", "testCase2"), ("test", "test"), ] for _in, _out in cases: ...
Amsterdam/GOB-EventProducer
src/tests/test_naming.py
test_naming.py
py
364
python
en
code
0
github-code
36
35260765665
from binaryninja import * import xxhash ################################################################################################################ # MLIL Instruction # ####################################################...
CySHell/Binja4J
Core/extraction_helpers/Instruction.py
Instruction.py
py
2,116
python
en
code
15
github-code
36
30473232781
from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.keys import Keys from tkinter import messagebox import time import os from App.Login import username, password, security_question class Core: def __init__(self, file_path, driver): ...
abdlalisalmi/UpWork-Select-Checkbox-in-a-Web-Page-with-Python-Selenium
App/Core.py
Core.py
py
2,090
python
en
code
1
github-code
36
30990966321
# need to implement CSRF from rest_framework.authentication import CSRFCheck from rest_framework_simplejwt.authentication import JWTAuthentication from rest_framework import exceptions from channels.db import database_sync_to_async from server.settings import SIMPLE_JWT from django.core.exceptions import ObjectDoesNotE...
Kredam/MyRoom
back-end/server/api/authentication.py
authentication.py
py
2,167
python
en
code
2
github-code
36
15969653865
#!/usr/bin/env python ## Test an algorithm in real life import sys if sys.version_info[0] != 3 or sys.version_info[1] < 6: print("This script requires Python version >=3.6") sys.exit(1) import algorithms import datetime import exchange import pandas_market_calendars as mcal import portfolioLive ## Main function d...
WattsUp/PyStonks
stonks/live.py
live.py
py
810
python
en
code
2
github-code
36
14071366665
# -*- coding: utf-8 -*- from PyQt4 import QtCore, QtGui import sys total=0 try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.trans...
LucasMatBorges/ProjetoFinal_DesignSoftware
DesignCircuitLab.py
DesignCircuitLab.py
py
32,163
python
en
code
0
github-code
36
6070176870
# encoding=utf-8 ''' Author: Haitaifantuan Create Date: 2020-09-08 23:47:11 Author Email: 47970915@qq.com Description: Should you have any question, do not hesitate to contact me via E-mail. ''' import numpy as np import random import time class First_Visit_Monte_Carlo_Policy_Evaluation(object): def __init__(self...
haitaifantuan/reinforcement_leanring
强化学习中的蒙特卡罗应用(贝尔曼方程)(含代码)-《强化学习系列专栏第2篇》/首次访问型蒙特卡罗策略估计.py
首次访问型蒙特卡罗策略估计.py
py
8,217
python
zh
code
8
github-code
36
35479998073
import pandas as pd replay_data = pd.read_csv('ReplayCharacters 2015-12-30 - 2016-01-29.csv') hero_info = pd.read_csv('hero_info.csv') replay_info = pd.read_csv('Replays 2015-12-30 - 2016-01-29.csv') map_info = pd.read_csv('map_info.csv') all_games = replay_data.merge(replay_info, how='left', on='ReplayID') all_games...
veldrin23/heroes_of_the_storm
bayes.py
bayes.py
py
503
python
en
code
0
github-code
36
31746754037
from django.core.exceptions import ValidationError from rest_framework import serializers from reviews.models import Category, Comment, Genre, Review, Title, User class ConfirmationTokenSerializer(serializers.Serializer): """Serializing verification data to provide full user registration""" username = seria...
GenVas/yamdb_final
api/serializers.py
serializers.py
py
3,954
python
en
code
1
github-code
36
18664116649
from pathlib import Path import joblib IS_KAGGLE = True if IS_KAGGLE: DATA_DIR = Path("/kaggle/working/chap5-data") OUTPUT_DIR = Path("/kaggle/working/") else: DATA_DIR = Path("../data") # Path(os.getenv("QQP_DATA_DIR", "/data")) OUTPUT_DIR = Path("../outputs") INPUT_DIR = DATA_DIR / "input" TRAIN_...
room-208/Kaggle-Gokui-Book
chap5/common/constants.py
constants.py
py
708
python
en
code
0
github-code
36
29053052757
from db import session, UniqueVictims, Victims from sqlalchemy.sql import func def calc_totals(): """ Calculate the total time frame the IP appears in and the udp/tcp/icmp packet count as well as the packets/s rate :return: """ all_victims = session.query(UniqueVictims).all() for victim i...
Kbman99/DDoS-Detection
calculate.py
calculate.py
py
934
python
en
code
1
github-code
36
34002187294
import os from app import app from flask import Flask, flash, request, redirect, url_for, render_template from werkzeug.utils import secure_filename from pneumonia_prediction import predict import tensorflow as tf ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg']) os.environ["CUDA_VISIBLE_DEVICES"]="-1" physical_de...
Nathanael-Mariaule/Pneumonia_Detection
flask_app/main.py
main.py
py
1,710
python
en
code
0
github-code
36
40423351728
from django.urls import path, include from . import views from rest_framework import routers route = routers.DefaultRouter() route.register("user", views.UserViewSet, basename='user') route.register("tuyenxe", views.TuyenXeViewset, basename='tuyenxe') route.register("chuyenxe", views.ChuyenXeViewset, basename='chuyen...
TamHoang1512/backend-django
QuanLyXeKhach/quanly/urls.py
urls.py
py
595
python
en
code
0
github-code
36
27744894909
import numpy as np import pickle import string import sys import math class RNN: def __init__(self, input_dim, output_dim, sentence_length, initializer="normal", optimizer="gd", hidden_dim=64, learning_rate=0.001, momentum=0.9, beta=0.9): # Checking if the optimizer is a valid optimizer valid_opti...
hrishikeshshekhar/Vanilla-RNN
rnn.py
rnn.py
py
19,714
python
en
code
0
github-code
36
15149970678
import Image import PSDraw #-*- coding:utf-8 -*- def text2png(text): adtexts = [ ] textcolor = "#000000" adcolor = "#FF0000" import Image, ImageDraw, ImageFont, uuid ad = [] for adtext in adtexts: ad += [(adtext.encode('gbk'), adcolor)] wraptext = [""] l = 0 for i in tex...
Entel/yeqin.me
model/picToAscii/letter.py
letter.py
py
1,171
python
en
code
0
github-code
36
10923117030
"""This is my attempt to solve the random numbers challenge in python game""" import random # Display welcome message to player print("Welcome Code Breaker! Lets see if you can break my 3 digit number!") print("Code has been generated, please guess a 3 digit number ") guess = list(input("What is your guess?: ")) print...
BornRiot/Python_DjangoDev
python_LevelOne/P10_SimpleGame_MySolution.py
P10_SimpleGame_MySolution.py
py
1,674
python
en
code
1
github-code
36