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
31621055131
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request, Header from fastapi.responses import JSONResponse from pydantic import BaseModel from google.cloud import datastore from typing import List from fastapi.middleware.cors import CORSMiddleware from functools import wraps import uuid import uvicorn imp...
kshithijareddy/jobsmaster
Backend/chat/main.py
main.py
py
3,344
python
en
code
0
github-code
13
30607414625
# Import required libraries # general imports import numpy as np from numpy import vstack from numpy import argmax # import for calculating the accuracy and confusion matrix from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix from sklearn.metrics import ConfusionMatrixDisplay # impor...
dmegkos/Noisy-handwritten-digits-classification-using-MLP-and-CNN
customCNN.py
customCNN.py
py
10,292
python
en
code
0
github-code
13
21909732615
""" Wizard to help user select parameters for various operations. WIP. """ import numpy as np import sys from PyQt5 import QtWidgets, QtCore, Qt, QtGui class HelpWindow(QtWidgets.QMainWindow): def __init__(self, app): super(HelpWindow, self).__init__() ####################### # ...
Jfeatherstone/pepe
pepe/auto/ParameterSelect.py
ParameterSelect.py
py
2,190
python
en
code
1
github-code
13
909330423
import json import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches data = open("polygon.json").read() data = json.loads(data) for plot_area in data: coords = data[plot_area]["Road"] plt.figure(figsize=(8, 8)) plt.axis('equal') for coord in coords: coords_x = ...
CarParty/CarParty
resources/json_examples/polygon.py
polygon.py
py
900
python
en
code
3
github-code
13
9336145567
from bs4 import BeautifulSoup from pprint import pprint from scraper.sas.sas_models import SASEvent, SASCategory, SASCategoryStage, SASEventStage from scraper.base_models.models import Event, Category, CategoryStage, EventStage, Participant, Result from scraper.sas.sas_config import DESTINATION_URL, MTB_EVENT_TYPE, YE...
coertzec/scraper
scraper/sas/scrape.py
scrape.py
py
11,067
python
en
code
0
github-code
13
3634652820
# Triangular Letter Pattern num = int(input("Enter Number: ")) Num = 65 for i in range(1,num+1): for j in range(i,i+1): print(i * chr(Num),end= '') Num +=1 print("") # Option-2 for i in range(0,num): print(chr(65 + i) * (i+1))
ashish-kumar-hit/python-qt
python/python-basics-100/Loops 2.6.py
Loops 2.6.py
py
255
python
en
code
0
github-code
13
35060658520
""" Brightness in an image can be changed simply by adding or subtracting a constant from each RGB value in the image. This is that implementation. """ from typing import List, Tuple import numpy as np from PIL import Image import click def brighten(img_arr: np.ndarray, brightness_factor: float) -> np.ndarray: "...
kathirmeyyappan/edge-detector-algorithms
src/other_algorithms/brightness.py
brightness.py
py
1,871
python
en
code
3
github-code
13
34040839162
import numpy as np import matplotlib from matplotlib import pyplot as plt import math def nearest_idx(array, value): array = np.asarray(array) idx = (np.abs(array - value)).argmin() return idx # D_opt_avg[i][2]+100*D_opt_avg[i][6] # (B, B_1, earnings, avg_l_price, avg_off_price, B+B_1-sum(cost[1:]), B-co...
ydidwania/Coffee-Conundrum
final/extend.py
extend.py
py
2,593
python
en
code
0
github-code
13
23028221159
import os import sys import traceback import types import gc import torch import torch.nn as nn import torch.optim as optim from diora.net.diora import DioraTreeLSTM from diora.net.diora import DioraMLP from diora.net.diora import DioraMLPShared from diora.logging.configuration import get_logger def override_inside...
anshuln/Diora_with_rules
pytorch/diora/net/trainer.py
trainer.py
py
20,666
python
en
code
4
github-code
13
1280044607
# https://leetcode.com/problems/reverse-string/ def reverseString(s): left,right = 0,len(s)-1 while(left < right): # swap s[left] and s[right] s[left],s[right] = s[right],s[left] left+=1 right-=1 return s print(reverseString(["h","e","l","l","o"])) print(reverseString(["...
Rajjada001/LeetCode-Topic_Wise-Problems
Strings/1.reverseString.py
1.reverseString.py
py
346
python
en
code
0
github-code
13
9407734339
import numpy as np from itertools import groupby from find_modes_mean_shift import findModesMeanShift def edgeOrientations(img_angle, img_weight): # init v1 and v2 v1 = [0, 0] v2 = [0, 0] # number of bins (histogram parameters) bin_num = 32 # convert images to vectors vec...
postBG/libcbdetect
code/edge_orientation.py
edge_orientation.py
py
2,000
python
en
code
1
github-code
13
42168561182
""" As the seeds get bigger we break new records in lenght or in height. Usage: import records Usage: from records import heightrecords Usage: from records import lengthtrecords >>> lengthrecords(20) [(1, 1), (2, 2), (3, 8), (6, 9), (7, 17), (9, 20), (18, 21)] >>> heightrecords(250) [(1, 1), (2, 2), (3, ...
lzhengem/python-projects
LAB04/hailstoneslab/records.py
records.py
py
1,625
python
en
code
0
github-code
13
43082964712
# # @lc app=leetcode.cn id=1154 lang=python3 # # [1154] 一年中的第几天 # # @lc code=start class Solution: def dayOfYear(self, date: str) -> int: # 拆出年月日 year, month, day = [int(x) for x in date.split("-")] # 模拟每一年的每月天数 amount = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # 闰年...
Guo-xuejian/leetcode-practice
1154.一年中的第几天.py
1154.一年中的第几天.py
py
592
python
en
code
1
github-code
13
30847785045
# use torch to build a rbfnet to fit 2-d points. import numpy as np import torch import torch.nn as nn import torch.optim as optim import matplotlib.pyplot as plt import copy class RBFNet(nn.Module): def __init__(self, n = 5): super(RBFNet, self).__init__() # the number of neurons in hidden layer. ...
wlsdzyzl/GAMES102
hw2/rbfnet.py
rbfnet.py
py
2,845
python
en
code
14
github-code
13
70713148498
import hid import time product_id = 0x2107 vendor_id = 0x413D usage_page = 0xFF00 # 初始化HID设备 def init_usb(vendor_id, usage_page): global h h = hid.device() hid_enumerate = hid.enumerate() device_path = 0 for i in range(len(hid_enumerate)): print(hid_enumerate[i]) # if (hid_enumera...
Jackadminx/KVM-Card-Mini
Client/module/hid_def.py
hid_def.py
py
1,667
python
en
code
53
github-code
13
29530333138
from __future__ import annotations import numpy as np from ConfigSpace import ( Categorical, Configuration, ConfigurationSpace, Float, Integer, ) import sklearn from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.compose import ColumnTransformer from skl...
josephgiovanelli/mo-importance
src/inner_loop/sklearn_model.py
sklearn_model.py
py
2,499
python
en
code
0
github-code
13
7953458575
import numpy as np import matplotlib.pyplot as plt if __name__ == '__main__': LENGTH = 2 ANGLE = np.pi/2 stack = [] dragonX = 'X+YF+' dragonY = '-FX-Y' hilbert_curveX = '-YF+XFX+FY-' hilbert_curveY = '+XF-YFY-FX+' def draw_fractal(actual_position, rule, angle, number_of_iterations, ...
maras49/NAVY
CV_6/__init__.py
__init__.py
py
2,120
python
en
code
0
github-code
13
31087824503
#!/usr/bin/python3 """ Flask implementation for the HTTP Server Overall this is more noisy and doesnt just die when you tell it too """ import logging from os import environ from threading import Thread from datetime import datetime from flask import Flask, request try: from .logger impor...
notxesh/sebknary
sebknary/http/flask-app.py
flask-app.py
py
1,982
python
en
code
3
github-code
13
18484684734
import numpy as np import json from dataclasses import dataclass import math import time import arcade import algorithms import isometric import constants as c import interaction from vision import VisionCalculator from map_tile import Tile # GATES and POI_LIGHTS are the highlights used to show the player points of ...
DragonMoffon/Temporum
mapdata.py
mapdata.py
py
20,017
python
en
code
2
github-code
13
25718805079
import requests from bs4 import BeautifulSoup import time def soupify(url): try: r = requests.get(url) soup = BeautifulSoup(r.content, 'html.parser', from_encoding='utf-8') soup.prettify() return r, soup except: time.sleep(3) def rev_address(r, soup): r_links = [...
iglee/outrunJulesVerne
src/parse_funcs.py
parse_funcs.py
py
1,376
python
en
code
7
github-code
13
4974027926
''' https://www.acmicpc.net/problem/18222 문제 0과 1로 이루어진 길이가 무한한 문자열 X가 있다. 이 문자열은 다음과 같은 과정으로 만들어진다. X는 맨 처음에 "0"으로 시작한다. X에서 0을 1로, 1을 0으로 뒤바꾼 문자열 X'을 만든다. X의 뒤에 X'를 붙인 문자열을 X로 다시 정의한다. 2~3의 과정을 무한히 반복한다. 즉, X는 처음에 "0"으로 시작하여 "01"이 되고, "0110"이 되고, "01101001"이 되고, ⋯ 의 과정을 거쳐 다음과 같이 나타내어진다. "0110100110010110100...
yeos60490/algorithm
백준/18222-투에모스문자열.py
18222-투에모스문자열.py
py
1,122
python
ko
code
0
github-code
13
31237114039
def homework_6(nodes): # 請同學記得把檔案名稱改成自己的學號(ex.1104813.py) n=len(nodes) initial = [[float("inf")]*n for i in range(n)] #列出各點之間之距離 for i in range(n): for j in range(n): if i==j: continue if i!=j: initial[i][j]=abs(nodes[i][0]-nodes[j][0])+abs(nod...
daniel880423/Member_System
file/hw6/1090338/hw6_s1090338_0.py
hw6_s1090338_0.py
py
1,346
python
en
code
0
github-code
13
21361088473
import spglib from ase.io import read from ase.neighborlist import neighbor_list import matplotlib.pyplot as plt import argparse parser = argparse.ArgumentParser(description='Calculate and plot bond lengths for given input file and cutoff distance.') parser.add_argument('input_file', type=str, help='path to input file...
mzkhalid039/Bond-lengths
bond_lengths.py
bond_lengths.py
py
2,239
python
en
code
3
github-code
13
25906669302
from .scraper import NewsScraper from .console import Console from .constants import constants if __name__ == "__main__": run_program = True console = Console() news_scrapper = NewsScraper() news_scrapper.default() console.start_program() while run_program: menu_execution = 0 ...
meobilivang/newsreader-cli
newsreadercli/__main__.py
__main__.py
py
667
python
en
code
6
github-code
13
42809800591
"""initial migration. Revision ID: a65f918ff3a0 Revises: Create Date: 2022-01-24 10:37:29.136316 """ from alembic import op from sqlalchemy.dialects import postgresql import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'a65f918ff3a0' down_revision = None branch_labels = None depends_on = Non...
BorodaUA/practice_api_server
db/migrations/versions/a65f918ff3a0_initial_migration.py
a65f918ff3a0_initial_migration.py
py
1,400
python
en
code
0
github-code
13
2957049975
# -*- coding: UTF-8 -*- # 开发团队: xx科技 # 开发人员: lee # 创建时间: 3/8/20 12:06 AM # 文件名称: 322-coinChange.py from typing import List class Solution: def coinChange2(self, coins: List[int], amount: int) -> int: coins_sort = list(reversed(coins)) nums, max = 0, len(coins_sort) - 1 results = [] ...
yanhuilee/hello_leetcode
src/main/python3.6/322-coinChange.py
322-coinChange.py
py
1,302
python
en
code
1
github-code
13
22165349969
data = [] count = 0 with open('reviews.txt', 'r') as f: for line in f: data.append(line) count += 1 if count % 10000 == 0: print(len(data)) print('讀取完成,共有', len(data), '筆資料') sum_length = 0 for d in data: sum_length = sum_length + len(d) print('每一筆的平均長度為', sum_length/len(data), '個字') wc = {} for d in dat...
iwels/read_count
read.py
read.py
py
771
python
en
code
0
github-code
13
7008590695
from DUBtils import * database_name="三国集团" sql="insert into information values (%s,%s,%s,%s,%s,%s,%s)" param=['曹操',56,'男',106,'IBM',500,50] updata(sql,param,database_name) sql1="insert into information values (%s,%s,%s,%s,%s,%s,%s)" param1=['大桥',19,'女',230,'微软',501,60] updata(sql1,param1,database_name) sql2="in...
zhongyusheng/store
练习3.py
练习3.py
py
2,560
python
en
code
0
github-code
13
39233588354
# -*- encoding:utf-8 -*- """ Author:wangqing Date: 20190707 Version:1.3 实现模型的建立,模型具体细节: 1. Encoder部分 由于各个段落的长度不一致,因此分别将各个段落送入BertModel中 经过BertModel得到embedding 在这个过程中,注意到有一个函数,model.train()或者model.eval() 这个两个参数仅对模型中有dropout时有影响。 Encoder出来后,得到的output为;encoder_layer,pooled_output, encoder_layer中的结果为我们所需的hidden_state 2. De...
CatherineWong1/hierarchy_model
hierarchy_model.py
hierarchy_model.py
py
2,390
python
zh
code
0
github-code
13
18578522800
## extra file to test loading txt file into a list. function was also added in project1.py def load_txt(filename): # opening the file in read mode my_file = open(filename, "r") # reading the file data = my_file.read() # replacing end of line('/n') with ' ' and # splitting the text it further ...
Brunozml/ml1_p1_linear_reg
loadtxt.py
loadtxt.py
py
504
python
en
code
0
github-code
13
16132559683
import collections import multiprocessing as mp Msg = collections.namedtuple("Msg", ["event", "args"]) class BaseProcess(mp.Process): """A process backed by an internal queue for simple one-way message passing.""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.qu...
udhayprakash/PythonMaterial
python3/19_Concurrency_and_Parallel_Programming/02_multiprocessing/example2.py
example2.py
py
1,073
python
en
code
7
github-code
13
39447991925
import torch import torch.nn as nn class TextEncoder(torch.nn.Module): def __init__(self, hidden_size, input_dim, n_layers=1, dropout=0): super(TextEncoder, self).__init__() self.n_layers = n_layers self.hidden_size = hidden_size self.embedding = nn.Embedding(input_dim, sel...
talk2car/Talk2Car
baseline/models/nlp_models.py
nlp_models.py
py
1,317
python
en
code
50
github-code
13
28105948739
#!/usr/bin/env python3 import sys class Day04: def __init__(self, file): self.data = [line.strip() for line in open(file).readlines()] @staticmethod def parse_line(line): def parse_section(section): first, second = section.split('-') return set(range(int(first), int(...
danschaffer/aoc
2022/day04.py
day04.py
py
1,260
python
en
code
0
github-code
13
8868623369
# -*- coding: utf-8 -*- """ Created on Sun Dec 6 01:36:40 2020 @author: apmle """ '''This is a program to convert Temperature in degrees Celsius to degrees Fahrenheit''' def convert(Celsius): F= (Celsius*9/5)+32 print(f"{Celsius} degrees in Celsius is equivalent to {F} degrees Fahrenheit") ...
FabioRochaPoeta/Python-v1-Ana
Celsius to Fahrenheit.py
Celsius to Fahrenheit.py
py
545
python
en
code
1
github-code
13
27389303153
import pickle import numpy as np from utils import get_sentence_vector, get_glove_matrix # 导入预处理后的问题列表 preprocessed_question_list = pickle.load(open('model/preprocessed_question_list.pkl', 'rb')) # # 建立GloVe矩阵 # glove_words, embeddings = get_glove_matrix() # # # 保存GloVe中的词头到文件 # with open('model/glove_words.pkl', 'wb...
huangjunxin/SimpleQuestionAnsweringSystem
vectorize_corpus_glove.py
vectorize_corpus_glove.py
py
1,234
python
en
code
4
github-code
13
39709992731
from manimlib.imports import * class Equations(Scene): def construct(self): #Making equations first_eq = TextMobject("$$S = \\int_{a}^{b} 2\\pi f(x) \\sqrt{1+[\\frac{dy}{dx}]^2} dx$$") second_eq = ["$S$", "=", "$\\int_{a}^{b}$", "$2\\pi f(x)$", "$\\sqrt{1+[f'(x)]^2} dx$",] second_...
advayk/Manim-CalcII-Project
trial_equations.py
trial_equations.py
py
1,267
python
en
code
0
github-code
13
21792333050
import functools import logbook import math import numpy as np import numpy.linalg as la from alephnull.finance import trading import pandas as pd import risk from . risk import ( alpha, check_entry, information_ratio, sharpe_ratio, sortino_ratio, ) log = logbook.Logger('Risk Period') choose_t...
CarterBain/AlephNull
alephnull/finance/risk/period.py
period.py
py
9,040
python
en
code
259
github-code
13
18859958667
import json from time import sleep import requests from requests.models import Response from serial import Serial ser = Serial('COM2', 9600) # baudrate print('Serial port is open: ' + str(ser.is_open)) while True: print('Waiting for data...') data = str(ser.readline())[2:-5] print('Data received: ' + da...
BrahR/Supervision
Arduino/serial_COM2.py
serial_COM2.py
py
605
python
en
code
0
github-code
13
71252112017
########################################################################################## # CityXen 16 Relay Board Serial Bridge Program # by Deadline # # NOTE: This is subject to heavy modification, especially the way it converts the signals # so don't presume that the state it is in now is the way it will stay # # R...
cityxen/HACKME
Click-A-Tron/Click-A-Tron.py
Click-A-Tron.py
py
7,527
python
en
code
0
github-code
13
14505760577
from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.action_chains import ActionChains from bs4 import BeautifulSoup from time import sleep import random from project_solo_app.models import Background_Task, Job, Li_Job, Li_Company, Li_Poster, Web_Scrape_Er...
catalystTGJ/01_project_solo
tasks/webscrape_li.py
webscrape_li.py
py
12,193
python
en
code
0
github-code
13
9730566725
# coding: UTF-8 from burp import ITab from burp import IBurpExtender from burp import IProxyListener from burp import IBurpExtenderCallbacks from burp import IContextMenuFactory from burp import IContextMenuInvocation from javax.swing import JPanel from javax.swing import JButton from javax.swing import JLabel from ja...
WhaleMountain/Match-and-Replace
match-and-replace.py
match-and-replace.py
py
10,837
python
en
code
0
github-code
13
22454449734
# -*- coding: utf-8 -*- from setuptools import setup, find_packages with open('README.rst') as f: README = f.read() with open('LICENSE') as f: LICENSE = f.read() setup( name='python-sample', version='0.1.0', description='Sample Python Project', long_description=README, author='Ben Schmitt...
foxdb/python-sample
setup.py
setup.py
py
493
python
en
code
0
github-code
13
17153516901
import argparse import numpy as np from torch import nn from erfnet_cp import customized_erfnet, erfnet from gpu_energy_eval import GPUEnergyEvaluator import time import torch import random class CustomizedAlexnet(nn.Module): def __init__(self, width=None): super(CustomizedAlexnet, self).__init__() ...
hyang1990/energy_constrained_compression
energy_tr_gen.py
energy_tr_gen.py
py
7,618
python
en
code
21
github-code
13
6985844056
import numpy as np import copy def retrieve_index_and_tfidf_from_txt(doc_index): ''' get term indexes and their unit tfidfs from specified documents ''' index = [] unit_tfidf = [] pos = './result/doc' + str(doc_index) + '.txt' with open(pos) as f: count = 0 for l...
shengyenlin/Introduction-to-information-retrieval-and-text-mining-Fall-2020
hw4/pa4.py
pa4.py
py
4,839
python
en
code
0
github-code
13
17058371604
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class PromoPageResult(object): def __init__(self): self._page_num = None self._page_size = None self._total_count = None self._total_pages = None @property def ...
alipay/alipay-sdk-python-all
alipay/aop/api/domain/PromoPageResult.py
PromoPageResult.py
py
2,369
python
en
code
241
github-code
13
1064691272
import re from py2neo import Graph, Node, Relationship test_graph = Graph("http://localhost:7474", username="neo4j", password="08166517416reny") input_message = input('input your message:') def kgquery_entity(target): find_entity = test_graph.find_one(re.search(r".*[老师/学生/项目]", target).group(0), property_ke...
Veronica1997/knowledge-graph
match_test.py
match_test.py
py
3,805
python
en
code
6
github-code
13
14624965323
from gtts import gTTS from base.models import RecipeInstruction from pydub import AudioSegment import os def getRecipeAudio(recipe_instructions, user_id = 0, language = 'en'): for i in recipe_instructions: myobj = gTTS(text=i.instruction, lang=language, slow=False) myobj.save('media/%d_%d_%d.m...
jincy-p-janardhanan/recipettsdjango
services/tts_service.py
tts_service.py
py
1,330
python
en
code
0
github-code
13
15289497457
import datetime import re from django import forms from django.forms.widgets import DateInput from django.core.exceptions import ValidationError from django.contrib.postgres.fields import ArrayField from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.utils import timez...
DiplomaTeamSDU/PartTimersApp
jobs/models.py
models.py
py
10,819
python
en
code
0
github-code
13
22648490107
#!/usr/bin/env python import boto3 import json import logging import pystac import requests import landsat from boto3 import Session from boto3utils import s3 from cirruslib import Catalog from cirruslib.errors import InvalidInput from dateutil.parser import parse from os import getenv, environ, path as op from shutil...
cirrus-geo/cirrus-earth-search
tasks/landsat-to-stac/task.py
task.py
py
5,303
python
en
code
21
github-code
13
12679648787
""" 给定一个链表,两两交换其中相邻的结点,并返回交换后的链表。 注:不能只是单纯的改变结点内部的值,而是需要实际的进行结点交换 """ class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def swapPairs(self, head: ListNode) -> ListNode: def helper(start): if not start.next: return ...
ayingxp/LeetCode
recursion/common/swap_pairs.py
swap_pairs.py
py
1,290
python
en
code
0
github-code
13
38275394215
from machine import Pin import time def toggle(p): p.value(not p.value()) def callback(p): print('pin change', p) led = Pin(2, Pin.OUT) led.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=callback) led.on() while True: toggle(led) time.sleep_ms(500)
Shinner/ESP32Demo
common/led.py
led.py
py
275
python
en
code
0
github-code
13
17814527825
import visitAllNodes input = open("input/9", "r").read().strip() lines = input.splitlines() distances = {} for journey in lines: route, distance = journey.split(" = ") distances[frozenset(route.split(" to "))] = int(distance) print(visitAllNodes.getWeight(distances))
QuarkNerd/adventOfCode
2015/9.py
9.py
py
279
python
en
code
1
github-code
13
10205779525
import selectors import socket import types # Where to connect to. HOST = 'localhost' PORT = 65432 # Selector for handling multiple connections. sel = selectors.DefaultSelector() # The byte messages that will be sent. m1 = b'' m2 = b'' for i in range(0, 250): m1 += b'a' m2 += b'b' MESSAGES = [m1, m2] def s...
jlangvand/Sat2RF1-TCP
tests/connection_tester.py
connection_tester.py
py
2,629
python
en
code
1
github-code
13
20694503697
from rss_fetch import CheckFeeds from load_config import load_section #LOAD INI CONFIG TO GET ALL THE RSS URLs THE_FEEDS = load_section() print("THE FEEDS: ", THE_FEEDS) test_feed_url = 'http://ourbigdumbmouth.libsyn.com/rss' def run_get_feed(the_feed_url): """ do stuff :return: """ print("TES...
maxnotmin/podcast_transfer
main.py
main.py
py
976
python
en
code
0
github-code
13
37320269273
from projects.qm_brain.utils.utils import * import scipy.stats as ss import numpy as np import pandas as pd cond10_taken_avg_tpm = load_matrix('/home/user/Desktop/QMBrain/tpm/8_regions/tpm_us_taken.csv') cond12_taken_avg_tpm = load_matrix('/home/user/Desktop/QMBrain/tpm/8_regions/tpm_s_taken.csv') cond10_byd_avg_tpm =...
jrudascas/brain_lab
projects/qm_brain/TPM/avg_tpm_stat.py
avg_tpm_stat.py
py
2,991
python
en
code
2
github-code
13
37086500206
from typing import Union import torch from e3nn import o3 from e3nn.util.jit import compile_mode from nequip.data import AtomicDataDict from nequip.nn import GraphModuleMixin @compile_mode("script") class EdgeSymmetricEmbedding(GraphModuleMixin, torch.nn.Module): """Construct edge attrs as a concatenation of a...
klarh/gala-nequip-plugin
gala_nequip_plugin/nn/embedding/EdgeSymmetricEmbedding.py
EdgeSymmetricEmbedding.py
py
1,293
python
en
code
1
github-code
13
40366557176
import tensorflow as tf from google.protobuf import text_format from object_detection.protos import pipeline_pb2 from absl import app from absl import flags import os flags.DEFINE_integer( 'step', 10000, """num_steps""") flags.DEFINE_integer( 'batch', 8, """batch size""") flags.DEFINE_integer( 'num_class', 3, """Re...
Dansato1203/TFLite_ObjectDetector
src/fix_pipeline.py
fix_pipeline.py
py
2,091
python
en
code
1
github-code
13
69837490579
import math import sys import numpy as np from hexgames.hexGrid import HexGrid from simWorld import SimWorld from actor_and_critic import * import random import time import matplotlib.pyplot as plt class Agent: def __init__(self, env, actor, critic, epsilon = 0.5): self.epsilon = epsilon self.simW...
Brakahaugen/Peg-solitaire-RL
agent.py
agent.py
py
1,262
python
en
code
0
github-code
13
70148065617
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F # from ..utils import * from daakg.sampling import typed_sampling class Decoder(nn.Module): def __init__(self, name, params): super(Decoder, self).__init__() self.print_name = name if name.startswith("[")...
nju-websoft/DAAKG
daakg/model/decoder.py
decoder.py
py
7,346
python
en
code
3
github-code
13
44407873101
# -*- coding: utf-8 -*- """Tricks for defining numeric types Routine Listings ---------------- The following return mixin classes for defining numeric operators / functions: convert_mixin Methods for conversion to `complex`, `float`, `int`. ordered_mixin Comparison operators mathops_mixin Arithmetic opera...
subhylahiri/sl_py_tools
number_like.py
number_like.py
py
36,268
python
en
code
1
github-code
13
23406900532
import torch import torch.nn as nn import torch.nn.functional as F from torch import optim from torch.autograd import Variable import numpy as np import torch_util from tqdm import tqdm from model.baseModel import model_eval import util.save_tool as save_tool import os from datetime import datetime import util.data_lo...
easonnie/multiNLI_encoder
model/tested_model/stack_3bilstm_last_encoder.py
stack_3bilstm_last_encoder.py
py
10,220
python
en
code
59
github-code
13
30643406912
import random def roll_dice(num_dice): print(f"\nRolling {num_dice} dice...") for _ in range(num_dice): dice_value = random.randint(1, 6) print(f"Dice: {dice_value}") def main(): while True: print("\nWelcome to the Dice Rolling App!") print("1. Roll the dice") ...
akash-inft1905/aidTec_Diceroller
diceroller.py
diceroller.py
py
677
python
en
code
0
github-code
13
7867303342
import datetime from .base import ConnectionType from copaco.utils import getFile from copaco.constants.mappings import PRICELISTITEM_MAPPINGS, STOCK_MAPPINGS from copaco.constants.constants import PRICELISTITEM_STATUS from copaco.models.pricelist import PriceListItem, PriceList class PriceListType(ConnectionType): ...
alexander-schillemans/python-copaco-connections
copaco/types/pricelist.py
pricelist.py
py
3,079
python
en
code
0
github-code
13
1139150469
# -*- coding: utf-8 -*- """ Created on 13.04.23 """ import numpy as np def cutout_image(annos, image, cutout_ratio, scale=1): """ Cut out the image according to the annotations, adding 20% margin to all sides :param annos: num_keypoints x 2 or 3 :param image: :param cutout_ratio: width to height ...
kaulquappe23/all-keypoints-jump-broadcast
utils/visualization.py
visualization.py
py
1,780
python
en
code
1
github-code
13
42746779375
import math import numpy as np from poptransformer import ops from poptransformer.utils import shard, repeat, shard_fused_qkv from poptransformer.layers import BaseLayer from poptransformer.layers import Linear class BaseAttention(BaseLayer): softmax_fn_map = { 'aionnx': ops.softmax, 'ce': ops.sof...
graphcore/PopTransformer
poptransformer/models/llama2/attention.py
attention.py
py
8,185
python
en
code
6
github-code
13
13418984523
# -*- coding:utf-8 -*- # 作者:IT小学生蔡坨坨 # 时间:2020/12/4 15:09 from django.conf.urls import url from web.views import account from web.views import home urlpatterns = [ url(r'^send/sms/$', account.send_sms, name='send_sms'), # 发送短信验证码 url(r'^register/$', account.register, name='register'), # 注册 url(r'^login...
y297374507/saas
web/urls.py
urls.py
py
725
python
en
code
0
github-code
13
73251601618
import matplotlib.pyplot as plt import numpy as np from utils import TFuncs import os def plot_gp(ax, X, m, C, no_last_data,training_points=None): """ Plotting utility to plot a GP fit with 95% confidence interval""" # Plot 95% confidence interval ax.fill_between(X[:, 0], m - 1.96*np.sq...
Dwaipayan-R-C/SimCFD_ML
utils/plots.py
plots.py
py
6,773
python
en
code
0
github-code
13
36940080710
# Extended Rauch-Tung-Striebel smoother or Extended Kalman Smoother (EKS) import jax import chex import jax.numpy as jnp from .base import NLDS from functools import partial from typing import Dict, List, Tuple, Callable from jsl.nlds import extended_kalman_filter as ekf def smooth_step(state: Tuple[chex.Array, chex....
gileshd/JSL
jsl/nlds/extended_kalman_smoother.py
extended_kalman_smoother.py
py
2,520
python
en
code
null
github-code
13
10191740225
n= int(input()) arr = list(map(int, input().split())) dy = [0] * n dy[0] = 1 for i in range(1, n): res = 0 for j in range(i): if arr[j] < arr[i]: if dy[j] > res: res = dy[j] dy[i] = res + 1 print(max(dy))
Jinnie-J/Algorithm-study
python/동적계획법/최대_선_연결하기.py
최대_선_연결하기.py
py
254
python
en
code
0
github-code
13
71347980818
from cryptozen.Euclid import GCD import random class Transpose: def __init__(self, key): self.key = key self.encoded = "" self.decoded = "" def encrypt(self, message=None): if message is None: message = input("Enter message to encrypt: ") if message == "": ...
Darknez07/CyberSec-Ciphers-hashes
cryptozen/cryptozen/Transposition.py
Transposition.py
py
1,470
python
en
code
0
github-code
13
18697945245
import clip import torch from PIL import Image class ObjectDetector: def __init__(self): # Load the model self.device = "cuda" if torch.cuda.is_available() else "cpu" self.model, self.preprocess = clip.load('ViT-B/32', self.device) def runDetect(self,filename,options = ["smoke dete...
ez314/Live-Safe-and-Save
backend/objectDetect.py
objectDetect.py
py
1,180
python
en
code
2
github-code
13
2871922038
from __future__ import absolute_import from __future__ import division from __future__ import print_function from contextlib import contextmanager import functools import inspect import threading import numpy as np from scipy import stats import six from . import log_probs as _log_probs def make_log_joint_fn(model)...
google-research/autoconj
autoconj/pplham.py
pplham.py
py
9,231
python
en
code
36
github-code
13
39580130106
# -*- coding: utf-8 -*- """ Global configuration file for TG2-specific settings in turbogag. This file complements development/deployment.ini. Please note that **all the argument values are strings**. If you want to convert them into boolean, for example, you should use the :func:`paste.deploy.converters.asbool` func...
mengu/turbogag
turbogag/config/app_cfg.py
app_cfg.py
py
3,285
python
en
code
8
github-code
13
23693546930
from googlesearch import search,get_random_user_agent import re,sys,time,os r = '\033[031m' g = '\033[032m' b = '\033[036m' y = '\033[033m' n = '\033[00m' class ghd(object): settings = { 'count':20, 'sleep':2, 'mode':"all", 'dork': '', 'target': '', 'output' : "{dork}_%H%M%d%m.txt" } ...
HanZawNyine/Special_Created
h4k3rTools/tool collect/ghd.py
ghd.py
py
6,267
python
en
code
1
github-code
13
17047278044
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayUserPeerpayprodAgreementModifyModel(object): def __init__(self): self._alipay_related_uid = None self._alipay_user_id = None self._quota = None self._request...
alipay/alipay-sdk-python-all
alipay/aop/api/domain/AlipayUserPeerpayprodAgreementModifyModel.py
AlipayUserPeerpayprodAgreementModifyModel.py
py
2,571
python
en
code
241
github-code
13
43110440559
#! /usr/bin/env python import os from math import pi import pandas from bokeh.io import curdoc from bokeh import plotting as plt from bokeh.layouts import column from bokeh.models.tools import PanTool, WheelZoomTool, BoxZoomTool, CrosshairTool, HoverTool, ResetTool, SaveTool column_names = [ 'timestamp', 'date',...
Elindorath/finance
test-bokeh.py
test-bokeh.py
py
2,968
python
en
code
0
github-code
13
36603704384
# 드래곤커브 N = int(input()) grid = [[0 for _ in range(101)] for _ in range(101)] # 격자 dx, dy = [1,0,-1,0], [0,-1,0,1] # 0: x좌표 증가 1: y좌표 감소 2: x좌표 감소 3: y좌표 증가 endPoint = [0,0] # 회전 기준점의 x, y 좌표 def turn(sPoint,bPoint): # sPoint 회전 기준점, bPoint 회전 시키려는 점 sx, sy = sPoint[0], sPoint[1] bx, by = bPoint[0], bPoint...
majung2/CTpractice
python/2020summer_study/boj_15685.py
boj_15685.py
py
1,828
python
en
code
0
github-code
13
41017219670
import sys, os sys.path.append(os.getcwd()) from tornado import gen, ioloop, web from lib.conf import KBConfig from lib.log import KBLogger from lib.store import Store from lib.stm import STM from lib.buffer import Buffer from ui_handlers.admin.routing import adminRouting from ui_handlers.front.routing import front...
alierkanimrek/rpui
src/server.py
server.py
py
2,648
python
en
code
0
github-code
13
24698089880
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import logging from logging.config import dictConfig from dynaconf import LazySettings # Configure Dynaconf settings = LazySettings( ENVVAR_PREFIX_FOR_DYNACONF="APP_{{ cookiecutter.app_name | upper }}", ENVVAR_FOR_DYNACONF="APP_SETTINGS", ) dictConf...
Lowess/cookiecutter-python-app
{{cookiecutter.app_name}}/app/__init__.py
__init__.py
py
632
python
en
code
0
github-code
13
18127409792
import numpy as np from facerec.distance import AbstractDistance from facerec.util import asColumnMatrix class OSS(AbstractDistance): """This metric calculates the One-Shot Similarity (OSS) using LDA as the underlying classifier OSS was originally described in the paper: Lior Wolf, Tal ...
naveenmm/facerec
py/facerec/oss.py
oss.py
py
1,594
python
en
code
0
github-code
13
2338298671
# Q program accepts n numbers from user add into list and return minimum and minimum number in list: def minimum (List): min = List[0] for i in range(0, len(List), 1): if min > List[i]: min = List[i] return min def maximum(List): max=List[0] for i in range(0,len(List),...
mayurgore2023/Python
list5.py
list5.py
py
839
python
en
code
0
github-code
13
4265040764
import os from invoke import task from app.product.model import Product as ProductModel from app.db import get_db, Base, engine from wsgi import app from app.config import source_path from app.utils.reader import Reader @task def init_db(ctx): print("Creating all resources.") Base.metadata.create_all() en...
linikerdev/sapo-products
tasks.py
tasks.py
py
1,228
python
en
code
0
github-code
13
22188309012
import pandas as pd def get_course_title(course_code): try: return courses.get(course_code).get('title') except: print(course_code + ' doesn\'t exist. Please verify the entry or contact the developer.') return 'TITLE NOT FOUND ERROR' def get_course_credit(course_code): ...
jeandecian/polymtl-gpa-calculator
main.py
main.py
py
4,038
python
en
code
0
github-code
13
23745230091
class ExtratorArgumentosUrl: url: str = None def __init__(self, url): if self.url_eh_valida(url): self.url = url.lower() else: raise LookupError("Url invalida!") def __len__(self): return len(self.url) def __str__(self): moeda_origem, moeda_dest...
DAT-Alura/Formation_Python
String_manipulation/content/extrator_argumentos_url.py
extrator_argumentos_url.py
py
2,253
python
pt
code
0
github-code
13
31078500963
#!/usr/bin/env python # -*- coding: utf-8 -*- """Advent of Code 2020 day 13 module.""" import math def _earliest_time(bus, arrival): return math.ceil(arrival / bus) * bus def earliest(buses, arrival): earliest_bus = None earliest_time = None for bus, _ in buses: if bus is None: ...
pmrowla/aoc2020
day13.py
day13.py
py
1,776
python
en
code
0
github-code
13
4593672785
class Solution: """ @param nums: A list of integers @param k: An integer denote to find k non-overlapping subarrays @return: An integer denote the sum of max k non-overlapping subarrays """ def maxSubArray(self, nums, k): o = -sys.maxint matrixLocal = [[o] * (k + 1) for i...
ultimate010/codes_and_notes
43_maximum-subarray-iii/maximum-subarray-iii.py
maximum-subarray-iii.py
py
1,606
python
en
code
0
github-code
13
32873653543
import torch import torchvision.transforms.functional as TF import kornia.geometry.transform as K import cv2 from torch.utils.data import Dataset from pathlib import Path import numpy as np from superpoint.settings import DATA_PATH import matplotlib.pyplot as plt from torch.utils.data import DataLoader class HPatches(...
AliYoussef97/SuperPoint-NeRF-Pytorch
superpoint/superpoint/data/HPatches.py
HPatches.py
py
5,995
python
en
code
5
github-code
13
26702363144
import argparse, boto3, json, logging, os, requests, time, yaml, zlib from datetime import datetime from multiprocessing.pool import ThreadPool from config import * def pull_subreddit(packed_item): subreddit = packed_item[0] item_type = packed_item[1] item_count = 0 retry_count = 0 additional_ba...
r-cybersecurity/pushshift-to-s3
main.py
main.py
py
6,414
python
en
code
1
github-code
13
21308681889
''' This module contains helper functions for plotting rampedpyrox data. ''' from __future__ import( division, print_function, ) __docformat__ = 'restructuredtext en' __all__ = ['_bd_plot_bge', '_plot_dicts', '_plot_dicts_iso', '_rem_dup_leg', ] import numpy as np #define function to plot carbon fl...
FluvialSeds/rampedpyrox
build/lib/rampedpyrox/plotting_helper.py
plotting_helper.py
py
7,021
python
en
code
4
github-code
13
3128938195
from independent_set import MIS from utilities import * from vertex_covers import MVC def experiment4(): num_nodes = 8 edge_ranges = range(1, 31, 4) num_graphs = 1000 x_vals = [] mvc_avg_size, mis_avg_size, sum_size = [], [], [] for num_edges in edge_ranges: mvc_total, mis_total = 0,...
MahboobMMonza/3XB3-Lab2
experiment4.py
experiment4.py
py
1,311
python
en
code
0
github-code
13
25523551348
# run in the medimg conda environment from pathlib import Path import pickle import SimpleITK as sitk import numpy as np import pandas as pd import h5py class GetPatches(): def __init__( self, bbox_file, path_file, side_file, output_file, spacing, min_si...
LangDaniel/MAEMI
utils/generate_patches/image_patches.py
image_patches.py
py
13,829
python
en
code
4
github-code
13
28133642295
# 주차 요금 계산 https://programmers.co.kr/learn/courses/30/lessons/92341 from math import ceil def solution(fees, records): dic = {} for rec in records: print(dic) time = int(rec[0:2])*60+int(rec[3:5]) carnum = int(rec[6:10]) # 처음 보는 차가 들어올 때 if carnum not in dic: dic[carnu...
yypark21/my_coding_test
level2_python/7.py
7.py
py
1,285
python
en
code
0
github-code
13
38362735628
class Solution(object): def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ if numRows==1: return s Mod_k = (numRows-1)*2 Rows = [[] for r in range(numRows)] for i,c in enumerate(s): for r in range(num...
rctzeng/AlgorithmDataStructuresPractice
Leetcode/ZigZagConversion_6.py
ZigZagConversion_6.py
py
446
python
en
code
0
github-code
13
13092848920
from typing import Optional, Any import attr from .initialize_from_attr import InitializeFromAttr from .transform_common import ( IsTransformed, IsPrototype, GetDecoratedClass, GetTransformedInstanceVars, GetMemberType) from .signal import ModelSignal, InterfaceSignal def Initialize( s...
JiveHelix/pex
python/pex/initializers.py
initializers.py
py
2,133
python
en
code
0
github-code
13
10438364906
# #START_LICENSE########################################################### # # # This file is part of the Environment for Tree Exploration program # (ETE). http://etetoolkit.org # # ETE is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the...
dongzhang0725/PhyloSuite
PhyloSuite/ete3/tools/ete_build_lib/task/prottest.py
prottest.py
py
6,215
python
en
code
118
github-code
13
12812260216
# This program performs sentimental analysis on movie reviews # Importing libraries import nltk import nltk.classify.util from nltk.classify.naivebayes import NaiveBayesClassifier from nltk.corpus import movie_reviews from nltk.corpus.reader import wordlist # download the data nltk.download("movie_reviews") # def...
blacdev/Machine-learning-Nltk-Library-
nlp_demo.py
nlp_demo.py
py
2,382
python
en
code
0
github-code
13
3022438493
#!/usr/bin/python3 """Defines a class Square""" from models.rectangle import Rectangle class Square(Rectangle): """ Represents a square""" def __init__(self, size, x=0, y=0, id=None): """Initializes a new Square Args: size (int): size of the new square x (int): x coord...
JozeSIMAO/alx-higher_level_programming
0x0C-python-almost_a_circle/models/square.py
square.py
py
1,740
python
en
code
0
github-code
13
18875461221
import torch import torch.nn as nn import torch.nn.init import torchvision.models as models from torch.autograd import Variable from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence import torch.backends.cudnn as cudnn from torch.nn.utils.clip_grad import clip_grad_norm import torch.nn.functional as ...
ramakanth-pasunuru/video_captioning_rl
models/seq2seq_atten.py
seq2seq_atten.py
py
20,298
python
en
code
43
github-code
13
278579122
from django.shortcuts import render from django.http import HttpResponse from .models import Line from django.template import loader, Context def add(request): if request.method == 'GET': context = {'状态': 'GET方法不允许提交'} return render(request,'line_add.html', context=context) else: name =...
ApostleMelody/Django
Test1/DB_manager/views.py
views.py
py
2,264
python
en
code
0
github-code
13
38622958265
#coding: utf-8 __autor__ = 'Cleber Augusto Dias Da Silva' #Números Primos print('Descubra se um número é primo!!') n = int(input('Digte o número que deseja saber:\n')) l = [2,3,5,7,9,11] b = 0 for idx,item in enumerate(l): x = n%l[idx] if x == 0: b += 1 if b == 0 : print('é primo') if b > 0: ...
CleberSilva93/Study-Exercicios-Python
Exercicio_PythonBrasil/EstruturadeRepetição/ex21.py
ex21.py
py
350
python
pt
code
0
github-code
13