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
13453142002
from .post_manager import PostManager from app.data import post_response, posts_response, new_post_request class NaiivePostManager(PostManager): def __init__(self): self.posts = [] def list_posts(self): return posts_response.dump(self.posts) def get_post_by_id(self, id): p = next...
jj-style/FlaskReactTemplateApp
flask/app/facades/post/naiive_post_manager.py
naiive_post_manager.py
py
1,074
python
en
code
0
github-code
1
279999487
cu=[] def fn(a,y): x=a+y cu.append(a) if x<100: return fn(y,x) print(fn(0,1)) print(cu) print() #第二种:循环的方法 a=0 b=1 i=1 cu2 = [] while i<10: c=a+b # print(c) cu2.append(c) a=b b=c i += 1 print(cu2) print() #第三种:递归函数 def fi(n): if n<=1: return n else: ...
zhouf1234/untitled3
函数编程函数练习10递归.py
函数编程函数练习10递归.py
py
417
python
en
code
0
github-code
1
14889123182
import re import os def readFile(): path = os.path.join(os.path.expanduser('~'), 'listaSadow', 'listaSadow.txt') with open(path,"r") as file: for line in file.readlines(): yield line def writeMongoCommand(listaCommand): path = os.path.join(os.path.expanduser('~'), 'listaSadow', 'dbPopu...
tomektarabasz/courtApi
app/excel_to_db/dbparser.py
dbparser.py
py
3,812
python
en
code
0
github-code
1
18021165672
import Pyro4 import Pyro4.naming from xbmcjson import XBMC import _thread as thread from subprocess import run, PIPE from evdev import UInput, InputEvent, ecodes as e from time import sleep import logging as log from pulse_mute import Pulse @Pyro4.expose class RemoteServer(object): def __init__(self): sel...
zteifel/raspberry_remote
htpc/server_pyro.py
server_pyro.py
py
3,311
python
en
code
0
github-code
1
74418312994
from __future__ import annotations from typing import TypedDict from movielog.reviews import serializer from movielog.utils import export_tools, list_tools from movielog.utils.logging import logger StatGroup = TypedDict("StatGroup", {"reviewYear": str, "reviewsCreated": int}) def export() -> None: # noqa: WPS210 ...
fshowalter/movielog
movielog/reviews/exports/review_stats.py
review_stats.py
py
1,081
python
en
code
1
github-code
1
5163632616
# Python3 program to illustrate deletion in a Binary Tree # class to create a node with data, left child and right child. class Node: def __init__(self,data): self.data = data self.left = None self.right = None # Inorder traversal of a binary tree def inorder(temp): if(not temp): return inorder(temp.left) ...
manu-prakash-choudhary/dsaWithPython
Python3 program to illustrate deletion.py
Python3 program to illustrate deletion.py
py
1,720
python
en
code
5
github-code
1
5856668077
import logging import sys import os LOG_CONFIG = { 'name': 'event-tracker', 'level': logging.DEBUG, 'stream_handler': logging.StreamHandler(sys.stdout), 'format': '%(asctime)s: %(module)s: %(levelname)s: %(message)s' } TWITTER_CONFIG = { 'api_key': os.environ["TWITTER_API_KEY"], 'api_secret':...
TheGBG/pic_sender
src/config/config.py
config.py
py
666
python
en
code
0
github-code
1
36126670493
from random import randint from time import sleep def maior(*arg): arg = list(arg) if len(arg) == 0: arg.append(0) print('-=' * 30) print(f'Analisando valores passados...') for c in arg: print(c, flush=True, end=' ') sleep(0.07) print(f'Foram informados {len(arg)} valores ao todo.') maior = arg[0] ...
VBAguiar/Python-Aprendizado
Desafios/desafio099.py
desafio099.py
py
512
python
pt
code
0
github-code
1
16026511667
import sys import rdkit from argparse import ArgumentParser from rdkit import Chem, DataStructs from rdkit.Chem import AllChem import pandas as pd pred_mols = pd.read_csv('', header=None).values.reshape(-1) ref_path = 'actives.txt' with open(ref_path) as f: next(f) true_mols = [line....
jkwang93/MCMG
eval/final_eval.py
final_eval.py
py
1,343
python
en
code
59
github-code
1
17287949508
# -*- coding: utf-8 -*- """ Created on Wed Sep 29 13:12:03 2021 @author: thuang Plots the sensitivity delta = master_branch - my_branch for 1e3 and 1e4. """ from matplotlib import pyplot as plt import numpy as np class delta_bars: def __init__(self, data_dict, tolerance): """ Parameters ...
thuang-work/txrx_sync_rssi
plot_ber_delta.py
plot_ber_delta.py
py
2,778
python
en
code
0
github-code
1
30045234159
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed unde...
openstack/senlin
senlin/api/common/serializers.py
serializers.py
py
2,897
python
en
code
44
github-code
1
42819608473
import time import pyupm_grove as grove import mraa def AirRead(): air = mraa.Aio(2) airValue = air.read() return airValue # Create the temperature sensor object using AIO pin 0 def TemperatureRead(): temp = grove.GroveTemp(0) celsius = temp.value() fahrenheit = celsius * 9.0/5.0 + 32.0; r...
Lee-Kevin/19.HomeControlCenterBBGW
Code/sensor.py
sensor.py
py
843
python
en
code
3
github-code
1
15956813860
import os import numpy as np import pickle import open3d as o3d from absl import app from absl import flags flags.DEFINE_string('task', 'stack-block-pyramid', '') flags.DEFINE_string('data_dir', './training_datasets/voxel_grids', '') flags.DEFINE_string('data_source', './training_datasets/rgbd', '') flags.DEFINE_integ...
tinwech/subgoal_success_detection
trans_rgbd_to_voxel.py
trans_rgbd_to_voxel.py
py
5,622
python
en
code
0
github-code
1
41226237989
from typing import List class AES: def __init__(self, plainText:str, key:str) -> None: self.plainText = plainText self.key = key self.keyBytes = b'' def __pad(self, input:bytes) -> bytes: length = 16 - (len(input) % 16) paddedInput = input paddedInput += bytes(...
Parth576/aes-des-python
aes/aes.py
aes.py
py
1,386
python
en
code
0
github-code
1
23870021739
""" This script is meant to be iterated many times to replicate the spawning of many error popups. """ from PySide2 import QtWidgets import random from PySide2.QtWidgets import QMainWindow, QApplication from PySide2.QtGui import QIcon from configparser import ConfigParser import sys app = QApplication(sys.argv) appcfg...
blitpxl/nk-popup-generator
src/iterable_popup.py
iterable_popup.py
py
1,783
python
en
code
0
github-code
1
14386612441
''' 72. 두 정수의 합 두 정수 a와 b의 합을 구하라. + 또는 - 연산자는 사용할 수 없다. ''' class Solution: def getSum(self, a: int, b: int) -> int: mask = 0xffffffff while (b & mask) > 0: carry = ( a & b ) << 1 a = (a ^ b) # XOR 연산 b = carry return (a & ...
hyo-eun-kim/algorithm-study
ch19/taeuk/ch19_3_taeuk.py
ch19_3_taeuk.py
py
453
python
ko
code
0
github-code
1
24843089063
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Run 1st, 2nd or 3rd level analyses using FSL FEAT. First, fsf files are created based on template fsf files (one per analysis). For each analysis from these templates one fsf file is created for each participant and run (1st level only). Analyses are defined in analy...
Cogitate-consortium/cogitate-msp1
coglib/fmri/glm/02_run_fsf_feat_analyses.py
02_run_fsf_feat_analyses.py
py
51,299
python
en
code
0
github-code
1
822464889
# Crie um programa que leia dois números e mostre a soma entre eles. valor1 = input("Digite o primeiro valor") valor2 = input("digite o segundo valor") s = int(valor1) + int(valor2) mensagem = "A soma entre {} e {} é {}" print(mensagem.format(valor1, valor2, s)) #print("A soma entre", valor1, "e", valor2, "...
EstevesMarcelo/ExerciciosPython3
ex001.py
ex001.py
py
361
python
pt
code
1
github-code
1
27406796251
from typing import Optional, List from fastapi import Body, Depends, HTTPException, status, Query from pydantic import EmailStr from .app_helper import ( create_student, get_student, update_student, delete_student, ) from .models import ( Student, StudentDelete, StudentUpdate, StudentRet...
Ajinkya7poppyi/DeepManager
app/modules/studentmanager/app.py
app.py
py
4,792
python
en
code
0
github-code
1
40666007920
import sys sys.stdin = open("달팽이사각형_input.txt") def iswall(x, y): if x >= 0 and x < 5 and y >= 0 and y < 5 and result_list[x][y] == 0: return True else: return False def my_min(a): mymin = 99 min_X = 0 min_Y = 0 for x in range(len(a)): for y in range(len(a[x])): ...
manuck/Algorithm
codexpert/달팽이사각형.py
달팽이사각형.py
py
1,105
python
en
code
0
github-code
1
27107627726
___author___='Huang' import numpy as np import pandas as pd def loadData(fileName): dataSet=pd.read_table(fileName,header=None).values dataArray=dataSet[:,:-1] labelArray=dataSet[:,-1] return dataArray,labelArray def selectJrand(i,m): j=i while(j==i): j=int(np.random.uniform(0,m)) ...
SwimSweet/My-DataMining-Learning
Algorithm/SVM/SVM.py
SVM.py
py
17,343
python
en
code
6
github-code
1
70861926755
# fmt: off import os import sys class OS: def __init__(self): self.rust_build = None self.copy_lib = None self.execute_python = None self.compile_python = None def lib_build(self): os.system(self.rust_build) os.system(self.copy_lib) def dev_build(self): ...
becelli/kayn
project.py
project.py
py
2,760
python
en
code
0
github-code
1
73948599075
import pickle as pkl import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches from matplotlib.ticker import FixedLocator, FixedFormatter def log_histogram(data, name): """ Create ridgeline plots, where each individual plot is a log-y scaled histogram. data: 2D Numpy arr...
brohrer/scs-gallery
log_y_histograms.py
log_y_histograms.py
py
3,565
python
en
code
9
github-code
1
32107199860
from zlib import adler32 from functools import wraps from flask_restful import Resource as DefaultResurce, ResponseBase, OrderedDict, request, unpack, marshal VALIDATION_ERROR_MESSAGE = 'Fields validation error' class marshal_with(object): """A decorator that apply marshalling to the return values of your metho...
annacorobco/flask-formula
v01/dockerfiles/backend/app/libs/controllers.py
controllers.py
py
4,630
python
en
code
null
github-code
1
11087451085
# Import the libraries import nltk from nltk.chat.util import Chat, reflections import tkinter as tk from tkinter import * # Define the responses pairs = [ ['hi', ['Hello!', 'Hi there!']], ['what is your name', ['My name is Chatbot', 'I am Chatbot']], ['how are you', ['I am doing well', 'I am fine, thanks'...
Beimnet27/Simple-Python-Chatbot
SimpleChat_Bot.py
SimpleChat_Bot.py
py
1,647
python
en
code
1
github-code
1
35663643651
import pandas as pd import matplotlib.pyplot as plt from datetime import datetime, timedelta import sys def moving_averages(stock_name, tdays, mdays): data = pd.read_csv('log_data.csv') data = data.set_index('Date') data.index = pd.to_datetime(data.index, format = '%Y-%m-%d %H:%M:%S') ldata = data['Lo...
Kiran9351/project
moving_averages.py
moving_averages.py
py
1,715
python
en
code
0
github-code
1
11806840571
import json import requests from config.const import SPOTIFY_HEADERS, SPOTIFY_URLS from config.tokens import SPOTIFY_OAUTH_TOKEN, SPOTIFY_USER_ID class SpotifyAPI: name = 'spotify' @staticmethod def __get_request_headers(): headers = SPOTIFY_HEADERS headers["Authorizatio...
simbi0nts/local-music-to-Spotify-transfer
api/spotify.py
spotify.py
py
2,218
python
en
code
1
github-code
1
37117203904
from flask import Flask, render_template, request #import requests import pickle #import numpy as np import sklearn from sklearn.preprocessing import StandardScaler app = Flask(__name__) model = pickle.load(open('model.pkl', 'rb')) @app.route('/',methods=['GET']) def index(): return render_template('ind...
Swathikrishnatu/ibm-attrition--Final-project
web.py
web.py
py
5,528
python
en
code
0
github-code
1
25650890509
from django.urls import path from repairshop import views urlpatterns = [ path("", views.home, name="home"), path("categories/<slug:sub_category>/", views.sub_category, name="sub_category"), path("about/", views.about, name="about"), path("categories/", views.categories, name="categories"), path("...
bmyronov/eremont
repairshop/urls.py
urls.py
py
441
python
en
code
0
github-code
1
45184258436
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Michael Liao (askxuefeng@gmail.com)' DEPRECATED = True from google.appengine.ext import db DEFAULT_GROUP = 'default' def get_instance_settings_as_dict(widget_instance): ''' get widget instance settings as dict which contains key-value...
Albertnnn/express-me
src/widget/store.py
store.py
py
1,446
python
en
code
0
github-code
1
37338983645
import server import os import config import time import threading class Chord: def __init__(self): self.qnt_key = None self.qnt_nodes = None self.cfg = config.Config() self.host = self.cfg.getHost().strip("\n") self.portaInicial = int(self.cfg.getMinPort().strip...
ruehara/SdPython
chord.py
chord.py
py
2,378
python
en
code
0
github-code
1
19076092035
from __future__ import print_function, division # requires Python >= 2.6 # numpy and scipy imports import numpy as np import math from scipy.sparse import kron, identity from scipy.sparse.linalg import eigsh # Lanczos routine from ARPACK from collections import namedtuple ####Initial parameter #physical parameter ...
liuzhsunshine/tensor-network-practice
3M-01-infinite-dmrg-1D-XXZ.py
3M-01-infinite-dmrg-1D-XXZ.py
py
4,911
python
en
code
0
github-code
1
22508709753
import math from enum import Enum from numbers import Number from typing import Tuple import torch import torch.nn.functional as F import torch.distributed as dist from torch.optim.lr_scheduler import CosineAnnealingLR, LinearLR from accelerate import init_empty_weights from transformers import ( AutoModelForCau...
microsoft/LMOps
minillm/minillm/utils.py
utils.py
py
6,065
python
en
code
2,623
github-code
1
18291176938
print('Calculadora Iniciada!!!\n') info = 1; soma = 0; sub = 0; mult = 0; div = 0; poten = 1; num1 = 0; num2 = 0 def calcular_soma(num1: float, num2: float, soma: float): num1 = float(input('\n\nDigite um Número: ')) num2 = float(input('Digite outro Número: ')) soma = num1 + num2 print('A soma do númer...
PlynioH/Calculadora
calcfunction.py
calcfunction.py
py
2,227
python
pt
code
0
github-code
1
32390876497
from django.test import TestCase, Client from shortener_url.models import Url from rest_framework import status import json class TestShortenerUrl(TestCase): def setUp(self): Url.objects.create(original_url="https://web.whatsapp.com/", custom_alias="whatsapp", shortened_url="http://shortener/u/whatsapp")...
karolGuimaraes/hire.me
tests.py
tests.py
py
2,457
python
en
code
null
github-code
1
16074380398
import tkinter as tk from PIL import ImageTk, Image class Caption: """ """ text = '' lastx = None lasty = None speech_bubble = 'imgs/spb-300x165.png' thought_bubble = 'imgs/thought.png' long_sample = ("I am the hope of the universe. I am the answer to all living things " ...
brianteachman/comic-dialog-builder
ui/caption.py
caption.py
py
2,077
python
en
code
1
github-code
1
37282786931
from typing import List, Dict from fastapi import WebSocket from fastapi import HTTPException, status from sqlalchemy import exc from sqlalchemy.ext.asyncio import AsyncSession from database.models.chat_models.chat_model import Chat from database.models.chat_models.members_model import ChatMember from database.model...
Whitev2/WebsocketChatExample
app/src/crud/chat_crud.py
chat_crud.py
py
4,420
python
en
code
0
github-code
1
20275789174
from config import TG_KEY, GPT_KEY from keybrds import kb from redis_client import redis_client import openai from aiogram import Bot, Dispatcher, executor, types openai.api_key = GPT_KEY bot = Bot(token=TG_KEY) dispatcher = Dispatcher(bot) @dispatcher.message_handler(commands=["start"]) async def start_func(mess...
EgorShabalin/chat_bot
main.py
main.py
py
2,315
python
en
code
0
github-code
1
34521429221
import matplotlib.pyplot as plt import seaborn as sns; sns.set() # for plot styling import numpy as np from sklearn.datasets.samples_generator import make_blobs from numpy import genfromtxt #humm, encontre este codigo en un servidor remoto #estaba junto con el "traffic.pcap" # que podria ser?, like some sample code ...
p4-team/ctf
2018-09-15-trendmicro/misc_constellation/proc.py
proc.py
py
1,156
python
en
code
1,716
github-code
1
73094670755
import random from Coverage import Coverage def fuzzer(max_length=100, char_start=32, char_range=32): length = random.randint(0, max_length + 1) out = "" for i in range(length): out += chr(random.randint(char_start, char_start+char_range)) return out def cgi_decode(s): """Decode the CGI-...
SlimPw/fuzzing-tuto
4_simple_coverage.py
4_simple_coverage.py
py
3,329
python
en
code
0
github-code
1
20581596447
""" 热力图 """ from pyecharts import options as opts from pyecharts.charts import Geo from pyecharts.globals import GeoType, ThemeType from pyecharts.faker import Faker import random, os map = ( Geo(init_opts=opts.InitOpts(width="1000px", height="800px", renderer="canvas", theme=Theme...
qugemingzizhemefeijin/python-study
ylspideraction/chapter15/_002charts_geo.py
_002charts_geo.py
py
1,471
python
en
code
1
github-code
1
2967834130
#!/usr/bin/env python3 # Laboratorio 12 - Tetris # Nome: Marcos Diaz # RA: 221525 ALTURA_TABULEIRO = 10 LARGURA_TABULEIRO = 10 # Funcao: atualiza_posicao # # Parametros: # l: largura do bloco que ira cair # a: altura do bloco que ira cair # x: posicao horizontal inicial do bloco que ira cair # desl:...
Marcos-Tonari-Diaz/MC102
LAB12/lab12.py
lab12.py
py
3,252
python
pt
code
1
github-code
1
20861603753
""" Store things and forget them. """ import time class Session: """ Session acts a dict, with a max size, and it forgets old items. Eviction is lazy, or explicit, with garbage collection. The code is compatible with asyncio. """ def __init__(self, max_size: int = 0, max_age: int = 0) -> ...
factorysh/aiohttp-stream
aiohttp_stream/session.py
session.py
py
2,247
python
en
code
0
github-code
1
28925820348
import requests from bs4 import BeautifulSoup def strip_string(string1): for i in string1: if i=='<': var1 = string1[string1.index(i):string1.index(">")+1] string1 = string1.replace(var1, "") return string1 def scrape_meaning(a): URL = f"https://www.dictionary.com/browse/{a}"...
priyanshusingh509/AashaEd
webscrape.py
webscrape.py
py
1,199
python
en
code
1
github-code
1
2714834337
from django.contrib.auth.decorators import login_required from django.contrib.auth.views import LoginView from django.shortcuts import get_object_or_404 from rest_framework.authentication import BasicAuthentication, SessionAuthentication from rest_framework.decorators import api_view, permission_classes, authentication...
artemovaka22pv191/back_movie
views.py
views.py
py
7,622
python
en
code
0
github-code
1
34280674306
from math import gcd n1=int(input('\n\t Enter first number = ')) n2=int(input('\n\t Enter second number = ')) print('\n\t Primitive Pythagorean Triples between ',n1,'and ',n2,'are as below :-') if n1>n2: n1,n2=n2,n1 if n1<3: n1=3 if n1==n2 or n2<5: print('\n\tWrong Input') else: b,i=1,0 ...
hack-parthsharma/Useless-Python-Codes
Pythagorean Triples.py
Pythagorean Triples.py
py
821
python
en
code
5
github-code
1
7678123747
# Let's learn about list comprehensions! You are given three integers x,y and z representing the dimensions of a cuboid along' \ # ' with an integer n. Print a list of all possible coordinates given by [i,j,k] on a 3D grid where the sum of it is not equal to n.' \ # ' Here, . Please use list comprehensions rat...
holcay92/HackerRankQuestions
list_comprehensions.py
list_comprehensions.py
py
599
python
en
code
0
github-code
1
13607688058
import pandas as pd import numpy as np from scipy.integrate import solve_ivp import matplotlib.pyplot as plt from numpy.random import rand from random import sample, shuffle plt.close() import torch from torch import nn from torch.utils.data import Dataset, DataLoader from itertools import permutations import matplotli...
erlebach/basic_UODE
circle_2pts.py
circle_2pts.py
py
8,461
python
en
code
0
github-code
1
9673124412
import jc from connectors.core.connector import get_logger, ConnectorError from .constants import LOGGER_NAME logger = get_logger(LOGGER_NAME) def convert(config, params): parser = params.get('parser') cmd_output = params.get('command_output') raw = params.get('raw', False) if not parser or not cmd_...
fortinet-fortisoar/connector-json-convert
json-convert/convert.py
convert.py
py
1,045
python
en
code
0
github-code
1
27401206260
from __future__ import annotations from typing import Literal, Optional from cognite.client import data_modeling as dm from pydantic import Field from ._core import DomainModel, DomainModelApply, TypeList, TypeApplyList __all__ = ["CogPool", "CogPoolApply", "CogPoolList", "CogPoolApplyList", "CogPoolFields", "CogPo...
cognitedata/pygen
examples-pydantic-v1/markets_pydantic_v1/client/data_classes/_cog_pool.py
_cog_pool.py
py
3,336
python
en
code
2
github-code
1
73767645472
import time from datetime import datetime from models.cancel_queue import CancelQueue from models.last_updated_tracker import LastUpdatedTracker from sqlalchemy import insert, update, select from .get_orders import get_orders from .get_orders_items import get_orders_items from ... import my_logger, SP_EXCEPTIONS, pacif...
aman-saleem-qbatch/dagster-cloud-dev
ops/apis/helpers/orders_processor.py
orders_processor.py
py
5,474
python
en
code
0
github-code
1
3259518810
import art import subprocess clear = lambda: subprocess.call('cls||clear', shell=True) print(art.logo) list = [] def add_list(name,bid): new_dic = { "name": name, "bid": bid } list.append(new_dic) def declare_winner(list): max_bid = 0 for dic in list: if max_bid < int(di...
idris-bahce/Blind-Auction
Auction.py
Auction.py
py
938
python
en
code
1
github-code
1
23466392621
#!/usr/bin/python3 from brownie import web3, Attack from scripts.deploy import deploy from scripts.helpful_scripts import get_account from colorama import Fore from time import time # * colours green = Fore.GREEN red = Fore.RED blue = Fore.BLUE magenta = Fore.MAGENTA reset = Fore.RESET def print_colour(solved): ...
Aviksaikat/Blockchain-CTF-Solutions
capturetheether/lotteries/GuessTheNewNumber_DONE/scripts/hack.py
hack.py
py
1,700
python
en
code
1
github-code
1
8702134035
import streamlit as st import altair as alt import inspect from vega_datasets import data @st.experimental_memo def get_chart_99637(use_container_width: bool): import altair as alt from vega_datasets import data airports = data.airports() states = alt.topo_feature(data.us_10m.url, feature='states'...
streamlit/release-demos
1.16.0/demo_app_altair/pages/115_Airports.py
115_Airports.py
py
1,260
python
en
code
78
github-code
1
35319358450
Students = {} with open("input.txt") as file: for line in file: info = line.strip().split(";") Students[info[0]] = info[1:] inputNumber = None print("To exit input 0") while inputNumber != "0": inputNumber = input("Student Number to Search:") if inputNumber != "0": if inputNumber i...
ZePedroFernandes/LEI_ASI
Parte 1/Aula3/Ex3/Ex3_B.py
Ex3_B.py
py
434
python
en
code
0
github-code
1
1585948759
from typing import Optional from decimal import Decimal from validator_collection import validators from highcharts_core import errors from highcharts_core.metaclasses import HighchartsMeta from highcharts_core.decorators import class_sensitive from highcharts_core.options.sonification.track_configurations import (In...
highcharts-for-python/highcharts-core
highcharts_core/options/sonification/__init__.py
__init__.py
py
13,339
python
en
code
40
github-code
1
34013188604
''' Array where each index contains the number of 1s in it's binary form. Brute Force: Is to obviouly convert each number to binary representation and count number of 1s. This has Time complexity O(n * len(binstring)) However, we can use these rules of binary numbers: - Count(n) = Count(n // 2) for even numbers,...
kjingers/Leetcode
Problems/CountingBits/CountingBits.py
CountingBits.py
py
776
python
en
code
0
github-code
1
2328641718
class Solution(object): def maxArea(self, height): """ :type height: List[int] :rtype: int The code is to find the area of the rectangle thats it! The code works perfectly for any input But time limit is exceeded all the time complexityy is 0(n^2) """ ...
yagamiram/Leetcode_problems_in_python
container_with_most_water.py
container_with_most_water.py
py
1,061
python
en
code
0
github-code
1
18259114828
import json import boto3 from datetime import datetime # get ec2 metrics def get_metric_ec2(namespace, metricname, client): response = client.get_metric_statistics( Namespace=namespace, MetricName=metricname, Dimensions=[ { 'Name': 'InstanceI...
BrunosBastos/ES_TDG
MetricsService/lambda_function.py
lambda_function.py
py
2,499
python
en
code
0
github-code
1
24129528828
import cv2 filepath = "vtest.avi" # cap = cv2.VideoCapture(filepath) # Webカメラを使うときはこちら class Capture: """ Captureクラスは動画の動体検出をサポートするメソッドを提供します。 """ def __init__(self,movie_path:str|None=None,device:int=0) -> None: """initialize capture mode. and configs.""" if not movie_path: ...
ik0326/aisolution
test/capture.py
capture.py
py
2,167
python
ja
code
0
github-code
1
11807410755
def not_empty(s): return s and s.strip() list(filter(not_empty, ['A', '地方', ' B阿斯顿发 ', None, 'C', ' '])) str = 'sakdj ' str.strip( ) str sorted([28,2345,723467,12541023,23,-1878,89*52],key=abs) list(map(lambda x:x*x,[1,2,4,5,6,10])) 50**3 7//2.1 thisset = set(("Google", "Runoob", "Taobao")) thisset.update({"...
Gmle7/myPythonCode
filter.py
filter.py
py
378
python
en
code
0
github-code
1
27821623666
from flask import Flask, request import json from datetime import datetime import requests from lights import light from constants import Tables, Params, PHUE from sqlite import sqlite app = Flask(__name__) Light1 = light.Light(1) Light2 = light.Light(3) @app.route("/listener") def generate_refresh_token(): c...
Shak-codes/Smart-Home-Routines
database/api/app.py
app.py
py
2,648
python
en
code
0
github-code
1
73791587875
#program to print stars(*) in nxn matrix form '''eg: 5 * * * * * * * * * * * * * * * * * * * * * * * * * ''' class Solution: def printSquare(self, N): for i in range (N): for j in range(N): print("*",end=" ") print( ) if __name__ == '__main__': t = int(input(...
NithyakumarA/100days-coding-challenge
cc day25.py
cc day25.py
py
450
python
en
code
0
github-code
1
16676517988
from django.shortcuts import render from django.http import HttpResponse from django.template import Template,Context # Create your views here. def suma(request,num1,num2): res = num1+num2 contenido = """ <html> <head> <body> <h2>El resultado es: %s </h2> </body></head> </html> """ %res return HttpRe...
Yahir5/examenunidad3
ESYG/prueba3/uno/views.py
views.py
py
660
python
es
code
0
github-code
1
73062305953
from mrjob.job import MRJob from mrjob.protocol import JSONProtocol, RawValueProtocol, JSONValueProtocol from mrjob.step import MRStep import json import numpy as np def multivar_gauss_pdf(x, mu, cov): ''' Caculates the multivariate normal density (pdf) Parameters: ----------- x - nu...
AmazaspShumik/MapReduce-Machine-Learning
Gaussian Mixture Model MapReduce/IterationGaussianMixtureMR.py
IterationGaussianMixtureMR.py
py
8,086
python
en
code
22
github-code
1
18480733171
from typing import List class UserCard(): gCardIds = [] def __init__(self, tPackage: tuple=()) -> None: """ Parameters ---------- tPackage : tuple (id, userId, cardCode, level, bond, userTags, moves, skills) + id : str + userId : str + code...
kaleidocli/gachaSim
model/user/UserCard.py
UserCard.py
py
1,776
python
en
code
1
github-code
1
38604647476
import torch from torch.utils.data import DataLoader import torchaudio import time import warnings warnings.filterwarnings('ignore') yesno_data = torchaudio.datasets.YESNO('.', download=False) def collate_fn(batch): tensors = [b[0].t() for b in batch if b] tensors = torch.nn.utils.rnn.pad_sequence(tensors, b...
sangje/sslsv
number_worker_test.py
number_worker_test.py
py
1,994
python
en
code
1
github-code
1
74540295072
import json import os from tornado import web from .base import BaseApiHandler, check_xsrf, check_notebook_dir from ...api import MissingEntry class StatusHandler(BaseApiHandler): @web.authenticated @check_xsrf def get(self): self.write({"status": True}) class GradeCollectionHandler(BaseApiHan...
jupyter/nbgrader
nbgrader/server_extensions/formgrader/apihandlers.py
apihandlers.py
py
11,194
python
en
code
1,232
github-code
1
6818157468
import identifier_phase, biomarker, clinical_trial_code, patient_number, lines_of_therapy, study_evaluation import utils.chunk_utils as cu import utils.json_utils as ju def get_overall_info(content): overall_dict = {} identifier_phase_dicts = identifier_phase.get_final_result(content) overall_dict['Identi...
ye8303019/ChatGPT_demo
clinical_result/overall.py
overall.py
py
1,832
python
en
code
27
github-code
1
72545619235
#!/usr/bin/env python3 import numpy as np import time import cv2 import matplotlib.pyplot as plt def corr(F, I): """ Input F: A (k, ell, c)-shaped ndarray containing the k x ell filter (with c channels). I: An (m, n, c)-shaped ndarray containing the m x n image (with c channels). Returns...
pol-francesch/aa274_group31
AA274A_HW3/Problem_3/linear_filter.py
linear_filter.py
py
2,582
python
en
code
1
github-code
1
71526482593
# Detection Cross Sections # All cross sections in cm^2 # All energies in MeV from .constants import * from .fmath import * from .photon_xs import PECrossSection from .matrix_element import * from matplotlib.pyplot import hist2d # Define ALP DETECTION cross-sections #### Photon Coupling #### def iprimakoff_dsigma_...
athompson-tamu/alplib
det_xs.py
det_xs.py
py
5,154
python
en
code
2
github-code
1
34469969520
n, m = map(int, input().split()) grid = [[0]*m for _ in range(n)] s = ord('A') dxs = [0, 1, 0, -1] dys = [1, 0, -1, 0] dir_num = 0 x, y = 0, 0 grid[x][y] = s def in_range(x, y): return 0 <= x < n and 0 <= y < m count = 1 for i in range(1, n*m): nx = x + dxs[dir_num] ny = y + dys[dir_num] if not (in_r...
yeafla530/algorithms
코드트리/NM/시뮬레이션/빙빙돌며사각형채우기.py
빙빙돌며사각형채우기.py
py
624
python
en
code
0
github-code
1
22314540095
# -*- coding: utf-8 -*- """ Created on Sun Jun 25 20:12:52 2017 @author: dell """ import collections def topKFrequent(nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ cnt=collections.Counter(nums) sort_fre=sorted(cnt.items(),key=lambda d:d[1...
ding1995/Leetcode
347.py
347.py
py
444
python
en
code
0
github-code
1
39286301539
import torch import torch.nn as nn import torch.nn.functional as F from pycls.models.resnet_style.shake_shake_function import get_alpha_beta, shake_function import pycls.utils.logging as lu logger = lu.get_logger(__name__) def initialize_weights(module): if isinstance(module, nn.Conv2d): nn.init.kaiming...
PrateekMunjal/TorchAL
pycls/models/resnet_style/resnet_shake_shake.py
resnet_shake_shake.py
py
7,326
python
en
code
56
github-code
1
11995643688
from rest_framework import generics from rest_framework.response import Response from .models import Ganado, Categoria, Raza, LitrosDeLeche from .serializers import GanadoSerializer,CategoriaSerializer, RazaSerializer, LitrosDeLecheSerializer from django.views.generic import View class GanadoListCreateAPIView(generi...
edwinjojoa/proyecto_grado
backend/ganado/views.py
views.py
py
2,860
python
en
code
0
github-code
1
2683877642
import random from turtle import Turtle, Screen import turtle colors = ["red", "orange", "yellow", "green", "blue", "purple"] is_race_on = False i = 0 all_turtles = [] red = Turtle(shape="turtle") red.color(colors[i]) i += 1 screen = Screen() screen.setup(width=500, height=400) user_bet = screen.textinput(title="Make...
Bootbastick/100_days_with_python
Day19/turtle_race.py
turtle_race.py
py
1,588
python
en
code
0
github-code
1
72117823394
from telnetServer import TelnetServer from player import Player from mud import Mud from worker import Worker from busevent import BusEvent from mysql import Mysql from callback import Callback import time def loadBroadcasts(mysql, callbacks, worker): for i in mysql.getEntry("select time_interval, message from bro...
L3nn0x/mud
main.py
main.py
py
961
python
en
code
0
github-code
1
70196467554
L=[] K=[] M=[] R=[] def Solution(): for i in range(100,1000): L.append(i) print(L) for a in range(1,10): for b in range(0,10): for c in range(0,10): K=[str(a),str(b),str(c),str(c),str(b),str(a)] new=''.join(K) print(new) M.append(int(new)) print(M) for j...
oen0thera/project
Solving_Math_Problems_With_Python_Coding/Problem 4.py
Problem 4.py
py
463
python
en
code
0
github-code
1
26553030524
from flask_app.config.mysqlconnection import connectToMySQL from flask import flash from flask_app.controllers.users import User class Sighting: def __init__(self, data): self.id = data['id'] self.location = data['location'] self.scenario = data['scenario'] self.date_of_sighting = d...
OhJackie21/Python-Practice
practice/sasquatch2/flask_app/models/sighting.py
sighting.py
py
4,436
python
en
code
0
github-code
1
28575068555
from . import bp from flask.views import MethodView from app import db from app.schemas import JobQueryArgsSchema, JobSchema from app.models import Job @bp.route('/jobs') class Jobs(MethodView): @bp.arguments(JobQueryArgsSchema, location="query") @bp.response(JobSchema(many=True)) @bp.paginate() def g...
rabizao/starter_flask
backend/app/api/routes.py
routes.py
py
800
python
en
code
0
github-code
1
41139310734
import json import time import os import datetime from scraper.halooglasi import get_latest_with_retry from scraper.db import check_if_exists, insert_property from scraper.discord import send_to_discord from scraper.logger import logger def get_local_time(): """ convert current time to CEST """ cest_...
avramdj/halo-oglasi-scraper
scraper/__main__.py
__main__.py
py
1,400
python
en
code
1
github-code
1
16921598410
import util from command import process_command import session as discord_session import filters from discord import Embed from logger import log # for the memes from random import choice @util.client.event async def on_message(message): if message.author.bot: # check to make sure it didn't send message ...
ComedicChimera/Null-Discord-Bot
bot.py
bot.py
py
3,439
python
en
code
0
github-code
1
7735751532
#!/usr/bin/env python # vim: set expandtab tabstop=4 shiftwidth=4: import sys from ftexplorer.data import Data data = Data('BL2') locker_count = 0 for (name, node) in data.get_level_package_nodes('GaiusSanctuary_P'): for point in node.get_children_with_name('willowpopulationopportunitypoint'): point_str...
apocalyptech/ft-explorer
sandbox/count_lockers.py
count_lockers.py
py
538
python
en
code
4
github-code
1
15114313938
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 2 11:44:08 2019 @author: ashish """ import pandas as pd import numpy as np import seaborn as sn import matplotlib.pyplot as plt import time dataset = pd.read_csv('new_appdata10.csv') # Data Preprocessing response = dataset["enrolled"] dataset ...
singhashish4000/MachineLearning-Supervised-Logistic-Regression-DCTSBAB
directing_customers_to_subscribstions_through_app_behavior_analysis_Model.py
directing_customers_to_subscribstions_through_app_behavior_analysis_Model.py
py
2,008
python
en
code
1
github-code
1
70243838433
#tire_volume.py from datetime import datetime import math print('This program calculte the tire volume') print() form_1 = 0 volume_1 = None w=float(input('Please Enter the width of the tire in mm: ')) a =float(input('Please Enter the aspect ratio of the tire: ')) d =float(input('Enter the diameter of the whe...
CFrancoChavez/CFrancoChavez
tire_volume.py
tire_volume.py
py
755
python
en
code
0
github-code
1
15501808433
import discord import asyncio from discord.ext.commands import Bot from discord.ext import commands import platform import logging import os import pymongo from urllib.parse import urlparse from datetime import datetime # constants MESSAGE_START_CONFIRMED = 'Okay. Asking feedback from **{}** to **{}**.' MESSAGE_WRONG_...
szilvesztererdos/feedbackbot
feedbackbot.py
feedbackbot.py
py
18,976
python
en
code
0
github-code
1
41976957988
import argparse import logging import os import shutil import subprocess import time logging.basicConfig(level=logging.DEBUG) parser = argparse.ArgumentParser(description="Famous Submitter") parser.add_argument("-t", "--tag", type=str, help="Dataset tag.") parser.add_argument("-i", "--input", type=str, help="Input fi...
SUEPPhysics/SUEPCoffea_dask
resubmit.py
resubmit.py
py
5,108
python
en
code
3
github-code
1
75149854432
'''Task You are given the shape of the array in the form of space-separated integers, each integer representing the size of different dimensions, your task is to print an array of the given shape and integer type using the tools numpy.zeros and numpy.ones.''' import numpy as np N,M,P = map(int,input().split()) arr...
karinabk/Python
NumPy/zeros_ones.py
zeros_ones.py
py
519
python
en
code
1
github-code
1
73454469792
import os import ctypes dir_path = os.path.dirname(os.path.realpath(__file__)) lib = ctypes.cdll.LoadLibrary(dir_path + "/" + "larcv2_to_larcv3.so") class larcv2_to_larcv3(object): def __init__(self): lib.larcv2_to_larcv3_new.argtypes = [] lib.larcv2_to_larcv3_new.restype = ctypes.c_void_p ...
DeepLearnPhysics/larcv2_to_larcv3
larcv2_to_larcv3.py
larcv2_to_larcv3.py
py
3,015
python
en
code
0
github-code
1
18854083745
import numpy as np from copy import deepcopy class Car: # x, y in meters # angle in radians # velocity in meters/sec # dt in seconds def __init__(self, x_init, y_init, L, theta_init, phi_init, velocity_init, dt, goal_loc, max_velocity=25.0, min_velocity=-25.0, max_angle=45, ...
sriharis123/DynamicObstacleAvoidance-RL
car.py
car.py
py
10,172
python
en
code
7
github-code
1
27970434469
# coding=utf-8 import os import logging from django.core.management.base import BaseCommand, CommandParser from django.conf import settings from django.apps import apps from django.utils.translation.trans_real import translation from prettytable import PrettyTable, ALL, FRAME, NONE logger = logging.getLogger(__name__)...
xiaolin0199/bbt
apps/ws/management/commands/gendoc.py
gendoc.py
py
14,000
python
en
code
0
github-code
1
31915854876
# -*- coding: utf-8 -*- """ TRABAJO 1. Estudiante: JJavier Alonso Ramos """ # Importamos módulo para trabajar con datos matemáticos import numpy as np # Importamos módulo para gráficos 2D import matplotlib.pyplot as plt # Importamos el módulo para formater tablas import pandas as pd # Importamos el módu...
JJavier98/AA
PRACTICAS/P1/Template/Práctica1.py
Práctica1.py
py
40,408
python
es
code
0
github-code
1
7467875956
import numpy as np from sklearn.linear_model import LinearRegression, Ridge from sklearn.preprocessing import PolynomialFeatures import matplotlib.pyplot as plt # read data def readData(path): data = [] with open(path, 'r') as f: line = f.readline() while line: d = list(map(float, line.str...
Dm697/EE559-Supervised-Machine-Learning-Midterm
q1.py
q1.py
py
5,538
python
en
code
0
github-code
1
8651064290
from django.shortcuts import render, redirect from .models import Csvdata import csv, io, os from django.http import HttpResponse, Http404 from myproject.settings import STATIC_ROOT # Home page def home(request): return render(request, 'myapp/home.html') # Read sqlite3.db, load datas def showdata(request): cs...
milescm/VisualPTP
myapp/views.py
views.py
py
4,249
python
en
code
1
github-code
1
14644906241
import subprocess def getPortMapArgs(container): return ['-p', container['portMap']] if 'portMap' in container else [] def getEnvArgs(container): return [arg for env in container['env'] for arg in ['-e', env]] if 'env'\ in container else [] containers = [ # { 'name': 'master' }, # { 'name': 'logging', 'p...
rosesonfire/docker-try-out
start.py
start.py
py
1,400
python
en
code
0
github-code
1
25272762590
#!/usr/bin/env python ''' This file works in python2 The code is largely modified from http://deeplearning.net/tutorial/mlp.html#mlp First use read_caffe_param.py to read fc7 and fc8 layer's parameter into pkl file. Then run this file to do a trojan trigger retraining on fc6 layer. This file also requires files from ht...
chenyanjiao-zju/Defense-Resistant-Backdoor
backdoor/mnist/retrain/load_data.py
load_data.py
py
5,876
python
en
code
0
github-code
1
26384838275
#!/usr/bin/env python3 """ module train_model """ import tensorflow.keras as K def train_model(network, data, labels, batch_size, epochs, validation_data=None, early_stopping=False, patience=0, verbose=True, shuffle=False): """ trains a model using mini-batch gradient descent ...
jhonaRiver/holbertonschool-machine_learning
supervised_learning/0x06-keras/6-train.py
6-train.py
py
1,876
python
en
code
0
github-code
1
20254723614
""" file: practica1 autor: davidpillco """ # Importa el codecs y json import codecs import json # Lee el archivo archivo = codecs.open("datos.txt","r") # Lee en lineas lineas_diccionario = archivo.readlines() # Pasa los diccionario a lista lineas_diccionario = [json.loads(l) for l in lineas_diccionario] # Func...
ProgFuncionalReactivaoct19-feb20/practica04-davidpillco
practica1.py
practica1.py
py
1,684
python
es
code
0
github-code
1
6033788614
import typing as t """ When inserting a string into a trie we first check if the root node has the first letter of the string we want to insert. --> When inserting a new word into the Trie: We start from the root of the tree. Then we iterate over all chars in the str to insert. For each char (iteration), I check the...
EvgeniiTitov/coding-practice
coding_practice/data_structures/tries/trie_implementation_1.py
trie_implementation_1.py
py
3,871
python
en
code
1
github-code
1
2396940716
import os from typing import Dict, List from nltk.corpus import wordnet as wn from tqdm import tqdm import models import parse import preprocess import utils from sequence import TextSequence def predict_babelnet(input_path: str, output_path: str, resources_path: str) -> None: """ DO NOT MODIFY THE SIGNATUR...
Riccorl/elmo-wsd
elmo-wsd/predict.py
predict.py
py
10,774
python
en
code
2
github-code
1